blob: 2a50e879fc24cfc034da5acc7b6d451c20d68b1b [file] [log] [blame]
Paul Stewart58a577b2012-01-10 11:18:52 -08001// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
Paul Stewartf65320c2011-10-13 14:34:52 -07002// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "shill/http_proxy.h"
6
7#include <errno.h>
8#include <netinet/in.h>
9#include <linux/if.h> // Needs definitions from netinet/in.h
10#include <stdio.h>
11#include <time.h>
12
13#include <string>
14#include <vector>
15
Eric Shienbrood3e20a232012-02-16 11:35:56 -050016#include <base/bind.h>
Paul Stewartf65320c2011-10-13 14:34:52 -070017#include <base/logging.h>
18#include <base/string_number_conversions.h>
19#include <base/string_split.h>
20#include <base/string_util.h>
21#include <base/stringprintf.h>
22
23#include "shill/async_connection.h"
Paul Stewartc8f4bef2011-12-13 09:45:51 -080024#include "shill/connection.h"
Paul Stewartf65320c2011-10-13 14:34:52 -070025#include "shill/dns_client.h"
26#include "shill/event_dispatcher.h"
27#include "shill/ip_address.h"
Ben Chanfad4a0b2012-04-18 15:49:59 -070028#include "shill/scope_logger.h"
Paul Stewartf65320c2011-10-13 14:34:52 -070029#include "shill/sockets.h"
30
Eric Shienbrood3e20a232012-02-16 11:35:56 -050031using base::Bind;
Paul Stewartf65320c2011-10-13 14:34:52 -070032using base::StringPrintf;
33using std::string;
34using std::vector;
35
36namespace shill {
37
38const int HTTPProxy::kClientHeaderTimeoutSeconds = 1;
39const int HTTPProxy::kConnectTimeoutSeconds = 10;
40const int HTTPProxy::kDNSTimeoutSeconds = 5;
41const int HTTPProxy::kDefaultServerPort = 80;
42const int HTTPProxy::kInputTimeoutSeconds = 30;
43const size_t HTTPProxy::kMaxClientQueue = 10;
44const size_t HTTPProxy::kMaxHeaderCount = 128;
45const size_t HTTPProxy::kMaxHeaderSize = 2048;
46const int HTTPProxy::kTransactionTimeoutSeconds = 600;
47
Paul Stewart58a577b2012-01-10 11:18:52 -080048const char HTTPProxy::kHTTPMethodConnect[] = "connect";
49const char HTTPProxy::kHTTPMethodTerminator[] = " ";
Paul Stewartf65320c2011-10-13 14:34:52 -070050const char HTTPProxy::kHTTPURLDelimiters[] = " /#?";
51const char HTTPProxy::kHTTPURLPrefix[] = "http://";
52const char HTTPProxy::kHTTPVersionPrefix[] = " HTTP/1";
53const char HTTPProxy::kInternalErrorMsg[] = "Proxy Failed: Internal Error";
54
Paul Stewartc8f4bef2011-12-13 09:45:51 -080055HTTPProxy::HTTPProxy(ConnectionRefPtr connection)
Paul Stewartf65320c2011-10-13 14:34:52 -070056 : state_(kStateIdle),
Paul Stewartc8f4bef2011-12-13 09:45:51 -080057 connection_(connection),
Eric Shienbrood3e20a232012-02-16 11:35:56 -050058 weak_ptr_factory_(this),
Eric Shienbrood9a245532012-03-07 14:20:39 -050059 accept_callback_(Bind(&HTTPProxy::AcceptClient,
60 weak_ptr_factory_.GetWeakPtr())),
Eric Shienbrood3e20a232012-02-16 11:35:56 -050061 connect_completion_callback_(Bind(&HTTPProxy::OnConnectCompletion,
Eric Shienbrood9a245532012-03-07 14:20:39 -050062 weak_ptr_factory_.GetWeakPtr())),
63 dns_client_callback_(Bind(&HTTPProxy::GetDNSResult,
64 weak_ptr_factory_.GetWeakPtr())),
65 read_client_callback_(Bind(&HTTPProxy::ReadFromClient,
66 weak_ptr_factory_.GetWeakPtr())),
67 read_server_callback_(Bind(&HTTPProxy::ReadFromServer,
68 weak_ptr_factory_.GetWeakPtr())),
69 write_client_callback_(Bind(&HTTPProxy::WriteToClient,
70 weak_ptr_factory_.GetWeakPtr())),
71 write_server_callback_(Bind(&HTTPProxy::WriteToServer,
72 weak_ptr_factory_.GetWeakPtr())),
Paul Stewartf65320c2011-10-13 14:34:52 -070073 dispatcher_(NULL),
74 dns_client_(NULL),
75 proxy_port_(-1),
76 proxy_socket_(-1),
77 server_async_connection_(NULL),
78 sockets_(NULL),
79 client_socket_(-1),
80 server_port_(kDefaultServerPort),
81 server_socket_(-1),
Eric Shienbrood3e20a232012-02-16 11:35:56 -050082 is_route_requested_(false) { }
Paul Stewartf65320c2011-10-13 14:34:52 -070083
84HTTPProxy::~HTTPProxy() {
85 Stop();
86}
87
88bool HTTPProxy::Start(EventDispatcher *dispatcher,
89 Sockets *sockets) {
Ben Chanfad4a0b2012-04-18 15:49:59 -070090 SLOG(HTTPProxy, 3) << "In " << __func__;
Paul Stewartf65320c2011-10-13 14:34:52 -070091
92 if (sockets_) {
93 // We are already running.
94 return true;
95 }
96
97 proxy_socket_ = sockets->Socket(PF_INET, SOCK_STREAM, 0);
98 if (proxy_socket_ < 0) {
99 PLOG(ERROR) << "Failed to open proxy socket";
100 return false;
101 }
102
103 struct sockaddr_in addr;
104 socklen_t addrlen = sizeof(addr);
105 memset(&addr, 0, sizeof(addr));
106 addr.sin_family = AF_INET;
107 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
108 if (sockets->Bind(proxy_socket_,
109 reinterpret_cast<struct sockaddr *>(&addr),
110 sizeof(addr)) < 0 ||
111 sockets->GetSockName(proxy_socket_,
112 reinterpret_cast<struct sockaddr *>(&addr),
113 &addrlen) < 0 ||
114 sockets->SetNonBlocking(proxy_socket_) < 0 ||
115 sockets->Listen(proxy_socket_, kMaxClientQueue) < 0) {
116 sockets->Close(proxy_socket_);
117 proxy_socket_ = -1;
118 PLOG(ERROR) << "HTTPProxy socket setup failed";
119 return false;
120 }
121
122 accept_handler_.reset(
123 dispatcher->CreateReadyHandler(proxy_socket_, IOHandler::kModeInput,
Eric Shienbrood3e20a232012-02-16 11:35:56 -0500124 accept_callback_));
Paul Stewartf65320c2011-10-13 14:34:52 -0700125 dispatcher_ = dispatcher;
126 dns_client_.reset(new DNSClient(IPAddress::kFamilyIPv4,
Paul Stewartc8f4bef2011-12-13 09:45:51 -0800127 connection_->interface_name(),
128 connection_->dns_servers(),
Paul Stewartf65320c2011-10-13 14:34:52 -0700129 kDNSTimeoutSeconds * 1000,
130 dispatcher,
Eric Shienbrood3e20a232012-02-16 11:35:56 -0500131 dns_client_callback_));
Paul Stewartf65320c2011-10-13 14:34:52 -0700132 proxy_port_ = ntohs(addr.sin_port);
133 server_async_connection_.reset(
Paul Stewartc8f4bef2011-12-13 09:45:51 -0800134 new AsyncConnection(connection_->interface_name(), dispatcher, sockets,
Eric Shienbrood3e20a232012-02-16 11:35:56 -0500135 connect_completion_callback_));
Paul Stewartf65320c2011-10-13 14:34:52 -0700136 sockets_ = sockets;
137 state_ = kStateWaitConnection;
138 return true;
139}
140
141void HTTPProxy::Stop() {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700142 SLOG(HTTPProxy, 3) << "In " << __func__;
Paul Stewartf65320c2011-10-13 14:34:52 -0700143
144 if (!sockets_ ) {
145 return;
146 }
147
148 StopClient();
149
150 accept_handler_.reset();
151 dispatcher_ = NULL;
152 dns_client_.reset();
153 proxy_port_ = -1;
154 server_async_connection_.reset();
155 sockets_->Close(proxy_socket_);
156 proxy_socket_ = -1;
157 sockets_ = NULL;
158 state_ = kStateIdle;
159}
160
161// IOReadyHandler callback routine fired when a client connects to the
162// proxy's socket. We Accept() the client and start reading a request
163// from it.
164void HTTPProxy::AcceptClient(int fd) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700165 SLOG(HTTPProxy, 3) << "In " << __func__;
Paul Stewartf65320c2011-10-13 14:34:52 -0700166
167 int client_fd = sockets_->Accept(fd, NULL, NULL);
168 if (client_fd < 0) {
169 PLOG(ERROR) << "Client accept failed";
170 return;
171 }
172
173 accept_handler_->Stop();
174
175 client_socket_ = client_fd;
176
177 sockets_->SetNonBlocking(client_socket_);
178 read_client_handler_.reset(
179 dispatcher_->CreateInputHandler(client_socket_,
Eric Shienbrood3e20a232012-02-16 11:35:56 -0500180 read_client_callback_));
Paul Stewartf65320c2011-10-13 14:34:52 -0700181 // Overall transaction timeout.
Paul Stewartf582b502012-04-04 21:39:22 -0700182 transaction_timeout_.Reset(Bind(&HTTPProxy::StopClient,
183 weak_ptr_factory_.GetWeakPtr()));
184 dispatcher_->PostDelayedTask(transaction_timeout_.callback(),
Eric Shienbrood3e20a232012-02-16 11:35:56 -0500185 kTransactionTimeoutSeconds * 1000);
Paul Stewartf65320c2011-10-13 14:34:52 -0700186
187 state_ = kStateReadClientHeader;
188 StartIdleTimeout();
189}
190
191bool HTTPProxy::ConnectServer(const IPAddress &address, int port) {
192 state_ = kStateConnectServer;
193 if (!server_async_connection_->Start(address, port)) {
194 SendClientError(500, "Could not create socket to connect to server");
195 return false;
196 }
197 StartIdleTimeout();
198 return true;
199}
200
201// DNSClient callback that fires when the DNS request completes.
Paul Stewartbdb02e62012-02-22 16:24:33 -0800202void HTTPProxy::GetDNSResult(const Error &error, const IPAddress &address) {
203 if (!error.IsSuccess()) {
Paul Stewartf65320c2011-10-13 14:34:52 -0700204 SendClientError(502, string("Could not resolve hostname: ") +
Paul Stewartbdb02e62012-02-22 16:24:33 -0800205 error.message());
Paul Stewartf65320c2011-10-13 14:34:52 -0700206 return;
207 }
Paul Stewartbdb02e62012-02-22 16:24:33 -0800208 ConnectServer(address, server_port_);
Paul Stewartf65320c2011-10-13 14:34:52 -0700209}
210
211// IOReadyHandler callback routine which fires when the asynchronous Connect()
212// to the remote server completes (or fails).
213void HTTPProxy::OnConnectCompletion(bool success, int fd) {
214 if (!success) {
215 SendClientError(500, string("Socket connection delayed failure: ") +
216 server_async_connection_->error());
217 return;
218 }
219 server_socket_ = fd;
220 state_ = kStateTunnelData;
Paul Stewart58a577b2012-01-10 11:18:52 -0800221
222 // If this was a "CONNECT" request, notify the client that the connection
223 // has been established by sending an "OK" response.
224 if (LowerCaseEqualsASCII(client_method_, kHTTPMethodConnect)) {
225 SetClientResponse(200, "OK", "", "");
226 StartReceive();
227 }
228
Paul Stewartf65320c2011-10-13 14:34:52 -0700229 StartTransmit();
230}
231
232// Read through the header lines from the client, modifying or adding
233// lines as necessary. Perform final determination of the hostname/port
234// we should connect to and either start a DNS request or connect to a
235// numeric address.
236bool HTTPProxy::ParseClientRequest() {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700237 SLOG(HTTPProxy, 3) << "In " << __func__;
Paul Stewartf65320c2011-10-13 14:34:52 -0700238
239 string host;
240 bool found_via = false;
241 bool found_connection = false;
242 for (vector<string>::iterator it = client_headers_.begin();
243 it != client_headers_.end(); ++it) {
244 if (StartsWithASCII(*it, "Host:", false)) {
245 host = it->substr(5);
246 } else if (StartsWithASCII(*it, "Via:", false)) {
247 found_via = true;
248 (*it).append(StringPrintf(", %s shill-proxy", client_version_.c_str()));
249 } else if (StartsWithASCII(*it, "Connection:", false)) {
250 found_connection = true;
251 (*it).assign("Connection: close");
252 } else if (StartsWithASCII(*it, "Proxy-Connection:", false)) {
253 (*it).assign("Proxy-Connection: close");
254 }
255 }
256
257 if (!found_connection) {
258 client_headers_.push_back("Connection: close");
259 }
260 if (!found_via) {
261 client_headers_.push_back(
262 StringPrintf("Via: %s shill-proxy", client_version_.c_str()));
263 }
264
265 // Assemble the request as it will be sent to the server.
266 client_data_.Clear();
Paul Stewart58a577b2012-01-10 11:18:52 -0800267 if (!LowerCaseEqualsASCII(client_method_, kHTTPMethodConnect)) {
268 for (vector<string>::iterator it = client_headers_.begin();
269 it != client_headers_.end(); ++it) {
270 client_data_.Append(ByteString(*it + "\r\n", false));
271 }
272 client_data_.Append(ByteString(string("\r\n"), false));
Paul Stewartf65320c2011-10-13 14:34:52 -0700273 }
Paul Stewartf65320c2011-10-13 14:34:52 -0700274
275 TrimWhitespaceASCII(host, TRIM_ALL, &host);
276 if (host.empty()) {
277 // Revert to using the hostname in the URL if no "Host:" header exists.
278 host = server_hostname_;
279 }
280
281 if (host.empty()) {
282 SendClientError(400, "I don't know what host you want me to connect to");
283 return false;
284 }
285
286 server_port_ = 80;
287 vector<string> host_parts;
288 base::SplitString(host, ':', &host_parts);
289
290 if (host_parts.size() > 2) {
291 SendClientError(400, "Too many colons in hostname");
292 return false;
293 } else if (host_parts.size() == 2) {
294 server_hostname_ = host_parts[0];
295 if (!base::StringToInt(host_parts[1], &server_port_)) {
296 SendClientError(400, "Could not parse port number");
297 return false;
298 }
299 } else {
300 server_hostname_ = host;
301 }
302
Paul Stewartc8f4bef2011-12-13 09:45:51 -0800303 connection_->RequestRouting();
304 is_route_requested_ = true;
305
Paul Stewartf65320c2011-10-13 14:34:52 -0700306 IPAddress addr(IPAddress::kFamilyIPv4);
307 if (addr.SetAddressFromString(server_hostname_)) {
308 if (!ConnectServer(addr, server_port_)) {
309 return false;
310 }
311 } else {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700312 SLOG(HTTPProxy, 3) << "Looking up host: " << server_hostname_;
Paul Stewartbdb02e62012-02-22 16:24:33 -0800313 Error error;
314 if (!dns_client_->Start(server_hostname_, &error)) {
315 SendClientError(502, "Could not resolve hostname: " + error.message());
Paul Stewartf65320c2011-10-13 14:34:52 -0700316 return false;
317 }
318 state_ = kStateLookupServer;
319 }
320 return true;
321}
322
323// Accept a new line into the client headers. Returns false if a parse
324// error occurs.
325bool HTTPProxy::ProcessLastHeaderLine() {
326 string *header = &client_headers_.back();
327 TrimString(*header, "\r", header);
328
329 if (header->empty()) {
330 // Empty line terminates client headers.
331 client_headers_.pop_back();
332 if (!ParseClientRequest()) {
333 return false;
334 }
335 }
336
337 // Is this is the first header line?
338 if (client_headers_.size() == 1) {
Paul Stewart58a577b2012-01-10 11:18:52 -0800339 if (!ReadClientHTTPMethod(header) ||
340 !ReadClientHTTPVersion(header) ||
341 !ReadClientHostname(header)) {
Paul Stewartf65320c2011-10-13 14:34:52 -0700342 return false;
343 }
344 }
345
346 if (client_headers_.size() >= kMaxHeaderCount) {
347 SendClientError(500, kInternalErrorMsg);
348 return false;
349 }
350
351 return true;
352}
353
354// Split input from client into header lines, and consume parsed lines
355// from InputData. The passed in |data| is modified to indicate the
356// characters consumed.
357bool HTTPProxy::ReadClientHeaders(InputData *data) {
358 unsigned char *ptr = data->buf;
359 unsigned char *end = ptr + data->len;
360
361 if (client_headers_.empty()) {
362 client_headers_.push_back(string());
363 }
364
365 for (; ptr < end && state_ == kStateReadClientHeader; ++ptr) {
366 if (*ptr == '\n') {
367 if (!ProcessLastHeaderLine()) {
368 return false;
369 }
370
371 // Start a new line. New chararacters we receive will be appended there.
372 client_headers_.push_back(string());
373 continue;
374 }
375
376 string *header = &client_headers_.back();
377 // Is the first character of the header line a space or tab character?
378 if (header->empty() && (*ptr == ' ' || *ptr == '\t') &&
379 client_headers_.size() > 1) {
380 // Line Continuation: Add this character to the previous header line.
381 // This way, all of the data (including newlines and line continuation
382 // characters) related to a specific header will be contained within
383 // a single element of |client_headers_|, and manipulation of headers
384 // such as appending will be simpler. This is accomplished by removing
385 // the empty line we started, and instead appending the whitespace
386 // and following characters to the previous line.
387 client_headers_.pop_back();
388 header = &client_headers_.back();
389 header->append("\r\n");
390 }
391
392 if (header->length() >= kMaxHeaderSize) {
393 SendClientError(500, kInternalErrorMsg);
394 return false;
395 }
396 header->push_back(*ptr);
397 }
398
399 // Return the remaining data to the caller -- this could be POST data
400 // or other non-header data sent with the client request.
401 data->buf = ptr;
402 data->len = end - ptr;
403
404 return true;
405}
406
407// Finds the URL in the first line of an HTTP client header, and extracts
408// and removes the hostname (and port) from the URL. Returns false if a
409// parse error occurs, and true otherwise (whether or not the hostname was
410// found).
411bool HTTPProxy::ReadClientHostname(string *header) {
412 const string http_url_prefix(kHTTPURLPrefix);
413 size_t url_idx = header->find(http_url_prefix);
414 if (url_idx != string::npos) {
415 size_t host_start = url_idx + http_url_prefix.length();
416 size_t host_end =
417 header->find_first_of(kHTTPURLDelimiters, host_start);
418 if (host_end != string::npos) {
419 server_hostname_ = header->substr(host_start,
420 host_end - host_start);
421 // Modify the URL passed upstream to remove "http://<hostname>".
422 header->erase(url_idx, host_end - url_idx);
423 if ((*header)[url_idx] != '/') {
424 header->insert(url_idx, "/");
425 }
426 } else {
427 LOG(ERROR) << "Could not find end of hostname in request. Line was: "
428 << *header;
429 SendClientError(500, kInternalErrorMsg);
430 return false;
431 }
432 }
433 return true;
434}
435
Paul Stewart58a577b2012-01-10 11:18:52 -0800436bool HTTPProxy::ReadClientHTTPMethod(string *header) {
437 size_t method_end = header->find(kHTTPMethodTerminator);
438 if (method_end == string::npos || method_end == 0) {
439 LOG(ERROR) << "Could not parse HTTP method. Line was: " << *header;
440 SendClientError(501, "Server could not parse HTTP method");
441 return false;
442 }
443 client_method_ = header->substr(0, method_end);
444 return true;
445}
446
Paul Stewartf65320c2011-10-13 14:34:52 -0700447// Extract the HTTP version number from the first line of the client headers.
448// Returns true if found.
449bool HTTPProxy::ReadClientHTTPVersion(string *header) {
450 const string http_version_prefix(kHTTPVersionPrefix);
451 size_t http_ver_pos = header->find(http_version_prefix);
452 if (http_ver_pos != string::npos) {
453 client_version_ =
454 header->substr(http_ver_pos + http_version_prefix.length() - 1);
455 } else {
456 SendClientError(501, "Server only accepts HTTP/1.x requests");
457 return false;
458 }
459 return true;
460}
461
462// IOInputHandler callback that fires when data is read from the client.
463// This could be header data, or perhaps POST data that follows the headers.
464void HTTPProxy::ReadFromClient(InputData *data) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700465 SLOG(HTTPProxy, 3) << "In " << __func__ << " length " << data->len;
Paul Stewartf65320c2011-10-13 14:34:52 -0700466
467 if (data->len == 0) {
468 // EOF from client.
469 StopClient();
470 return;
471 }
472
473 if (state_ == kStateReadClientHeader) {
474 if (!ReadClientHeaders(data)) {
475 return;
476 }
477 if (state_ == kStateReadClientHeader) {
478 // Still consuming client headers; restart the input timer.
479 StartIdleTimeout();
480 return;
481 }
482 }
483
484 // Check data->len again since ReadClientHeaders() may have consumed some
485 // part of it.
486 if (data->len != 0) {
487 // The client sent some information after its headers. Buffer the client
488 // input and temporarily disable input events from the client.
489 client_data_.Append(ByteString(data->buf, data->len));
490 read_client_handler_->Stop();
491 StartTransmit();
492 }
493}
494
495// IOInputHandler callback which fires when data has been read from the
496// server.
497void HTTPProxy::ReadFromServer(InputData *data) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700498 SLOG(HTTPProxy, 3) << "In " << __func__ << " length " << data->len;
Paul Stewartf65320c2011-10-13 14:34:52 -0700499 if (data->len == 0) {
500 // Server closed connection.
501 if (server_data_.IsEmpty()) {
502 StopClient();
503 return;
504 }
505 state_ = kStateFlushResponse;
506 } else {
507 read_server_handler_->Stop();
508 }
509
510 server_data_.Append(ByteString(data->buf, data->len));
511
512 StartTransmit();
513}
514
515// Return an HTTP error message back to the client.
516void HTTPProxy::SendClientError(int code, const string &error) {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700517 SLOG(HTTPProxy, 3) << "In " << __func__;
Paul Stewartf65320c2011-10-13 14:34:52 -0700518 LOG(ERROR) << "Sending error " << error;
Paul Stewart58a577b2012-01-10 11:18:52 -0800519 SetClientResponse(code, "ERROR", "text/plain", error);
Paul Stewartf65320c2011-10-13 14:34:52 -0700520 state_ = kStateFlushResponse;
521 StartTransmit();
522}
523
Paul Stewart58a577b2012-01-10 11:18:52 -0800524// Create an HTTP response message to be sent to the client.
525void HTTPProxy::SetClientResponse(int code, const string &type,
526 const string &content_type,
527 const string &message) {
528 string content_line;
529 if (!message.empty() && !content_type.empty()) {
530 content_line = StringPrintf("Content-Type: %s\r\n", content_type.c_str());
531 }
532 string response = StringPrintf("HTTP/1.1 %d %s\r\n"
533 "%s\r\n"
534 "%s", code, type.c_str(),
535 content_line.c_str(),
536 message.c_str());
537 server_data_ = ByteString(response, false);
538}
539
Paul Stewartf65320c2011-10-13 14:34:52 -0700540// Start a timeout for "the next event". This timeout augments the overall
541// transaction timeout to make sure there is some activity occurring at
542// reasonable intervals.
543void HTTPProxy::StartIdleTimeout() {
544 int timeout_seconds = 0;
545 switch (state_) {
546 case kStateReadClientHeader:
547 timeout_seconds = kClientHeaderTimeoutSeconds;
548 break;
549 case kStateConnectServer:
550 timeout_seconds = kConnectTimeoutSeconds;
551 break;
552 case kStateLookupServer:
553 // DNSClient has its own internal timeout, so we need not set one here.
554 timeout_seconds = 0;
555 break;
556 default:
557 timeout_seconds = kInputTimeoutSeconds;
558 break;
559 }
Eric Shienbrood3e20a232012-02-16 11:35:56 -0500560 idle_timeout_.Cancel();
Paul Stewartf65320c2011-10-13 14:34:52 -0700561 if (timeout_seconds != 0) {
Eric Shienbrood3e20a232012-02-16 11:35:56 -0500562 idle_timeout_.Reset(Bind(&HTTPProxy::StopClient,
563 weak_ptr_factory_.GetWeakPtr()));
564 dispatcher_->PostDelayedTask(idle_timeout_.callback(),
565 timeout_seconds * 1000);
Paul Stewartf65320c2011-10-13 14:34:52 -0700566 }
567}
568
569// Start the various input handlers. Listen for new data only if we have
570// completely written the last data we've received to the other end.
571void HTTPProxy::StartReceive() {
572 if (state_ == kStateTunnelData && client_data_.IsEmpty()) {
573 read_client_handler_->Start();
574 }
575 if (server_data_.IsEmpty()) {
576 if (state_ == kStateTunnelData) {
577 if (read_server_handler_.get()) {
578 read_server_handler_->Start();
579 } else {
580 read_server_handler_.reset(
581 dispatcher_->CreateInputHandler(server_socket_,
Eric Shienbrood3e20a232012-02-16 11:35:56 -0500582 read_server_callback_));
Paul Stewartf65320c2011-10-13 14:34:52 -0700583 }
584 } else if (state_ == kStateFlushResponse) {
585 StopClient();
586 return;
587 }
588 }
589 StartIdleTimeout();
590}
591
592// Start the various output-ready handlers for the endpoints we have
593// data waiting for.
594void HTTPProxy::StartTransmit() {
595 if (state_ == kStateTunnelData && !client_data_.IsEmpty()) {
596 if (write_server_handler_.get()) {
597 write_server_handler_->Start();
598 } else {
599 write_server_handler_.reset(
600 dispatcher_->CreateReadyHandler(server_socket_,
601 IOHandler::kModeOutput,
Eric Shienbrood3e20a232012-02-16 11:35:56 -0500602 write_server_callback_));
Paul Stewartf65320c2011-10-13 14:34:52 -0700603 }
604 }
605 if ((state_ == kStateFlushResponse || state_ == kStateTunnelData) &&
606 !server_data_.IsEmpty()) {
607 if (write_client_handler_.get()) {
608 write_client_handler_->Start();
609 } else {
610 write_client_handler_.reset(
611 dispatcher_->CreateReadyHandler(client_socket_,
612 IOHandler::kModeOutput,
Eric Shienbrood3e20a232012-02-16 11:35:56 -0500613 write_client_callback_));
Paul Stewartf65320c2011-10-13 14:34:52 -0700614 }
615 }
616 StartIdleTimeout();
617}
618
619// End the transaction with the current client, restart the IOHandler
620// which alerts us to new clients connecting. This function is called
621// during various error conditions and is a callback for all timeouts.
622void HTTPProxy::StopClient() {
Ben Chanfad4a0b2012-04-18 15:49:59 -0700623 SLOG(HTTPProxy, 3) << "In " << __func__;
Paul Stewartf65320c2011-10-13 14:34:52 -0700624
Paul Stewartc8f4bef2011-12-13 09:45:51 -0800625 if (is_route_requested_) {
626 connection_->ReleaseRouting();
627 is_route_requested_ = false;
628 }
Paul Stewartf65320c2011-10-13 14:34:52 -0700629 write_client_handler_.reset();
630 read_client_handler_.reset();
631 if (client_socket_ != -1) {
632 sockets_->Close(client_socket_);
633 client_socket_ = -1;
634 }
635 client_headers_.clear();
Paul Stewart58a577b2012-01-10 11:18:52 -0800636 client_method_.clear();
Paul Stewartf65320c2011-10-13 14:34:52 -0700637 client_version_.clear();
638 server_port_ = kDefaultServerPort;
639 write_server_handler_.reset();
640 read_server_handler_.reset();
641 if (server_socket_ != -1) {
642 sockets_->Close(server_socket_);
643 server_socket_ = -1;
644 }
645 server_hostname_.clear();
646 client_data_.Clear();
647 server_data_.Clear();
648 dns_client_->Stop();
649 server_async_connection_->Stop();
Eric Shienbrood3e20a232012-02-16 11:35:56 -0500650 idle_timeout_.Cancel();
Paul Stewartf582b502012-04-04 21:39:22 -0700651 transaction_timeout_.Cancel();
Paul Stewartf65320c2011-10-13 14:34:52 -0700652 accept_handler_->Start();
653 state_ = kStateWaitConnection;
654}
655
656// Output ReadyHandler callback which fires when the client socket is
657// ready for data to be sent to it.
658void HTTPProxy::WriteToClient(int fd) {
659 CHECK_EQ(client_socket_, fd);
660 int ret = sockets_->Send(fd, server_data_.GetConstData(),
661 server_data_.GetLength(), 0);
Ben Chanfad4a0b2012-04-18 15:49:59 -0700662 SLOG(HTTPProxy, 3) << "In " << __func__ << " wrote " << ret << " of "
663 << server_data_.GetLength();
Paul Stewartf65320c2011-10-13 14:34:52 -0700664 if (ret < 0) {
665 LOG(ERROR) << "Server write failed";
666 StopClient();
667 return;
668 }
669
670 server_data_ = ByteString(server_data_.GetConstData() + ret,
671 server_data_.GetLength() - ret);
672
673 if (server_data_.IsEmpty()) {
674 write_client_handler_->Stop();
675 }
676
677 StartReceive();
678}
679
680// Output ReadyHandler callback which fires when the server socket is
681// ready for data to be sent to it.
682void HTTPProxy::WriteToServer(int fd) {
683 CHECK_EQ(server_socket_, fd);
684 int ret = sockets_->Send(fd, client_data_.GetConstData(),
685 client_data_.GetLength(), 0);
Ben Chanfad4a0b2012-04-18 15:49:59 -0700686 SLOG(HTTPProxy, 3) << "In " << __func__ << " wrote " << ret << " of "
687 << client_data_.GetLength();
Paul Stewartf65320c2011-10-13 14:34:52 -0700688
689 if (ret < 0) {
690 LOG(ERROR) << "Client write failed";
691 StopClient();
692 return;
693 }
694
695 client_data_ = ByteString(client_data_.GetConstData() + ret,
696 client_data_.GetLength() - ret);
697
698 if (client_data_.IsEmpty()) {
699 write_server_handler_->Stop();
700 }
701
702 StartReceive();
703}
704
705} // namespace shill