blob: 3d2fd0c4a33a1d8081fedb99811b05b5ce42a029 [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"
28#include "shill/sockets.h"
29
Eric Shienbrood3e20a232012-02-16 11:35:56 -050030using base::Bind;
Paul Stewartf65320c2011-10-13 14:34:52 -070031using base::StringPrintf;
32using std::string;
33using std::vector;
34
35namespace shill {
36
37const int HTTPProxy::kClientHeaderTimeoutSeconds = 1;
38const int HTTPProxy::kConnectTimeoutSeconds = 10;
39const int HTTPProxy::kDNSTimeoutSeconds = 5;
40const int HTTPProxy::kDefaultServerPort = 80;
41const int HTTPProxy::kInputTimeoutSeconds = 30;
42const size_t HTTPProxy::kMaxClientQueue = 10;
43const size_t HTTPProxy::kMaxHeaderCount = 128;
44const size_t HTTPProxy::kMaxHeaderSize = 2048;
45const int HTTPProxy::kTransactionTimeoutSeconds = 600;
46
Paul Stewart58a577b2012-01-10 11:18:52 -080047const char HTTPProxy::kHTTPMethodConnect[] = "connect";
48const char HTTPProxy::kHTTPMethodTerminator[] = " ";
Paul Stewartf65320c2011-10-13 14:34:52 -070049const char HTTPProxy::kHTTPURLDelimiters[] = " /#?";
50const char HTTPProxy::kHTTPURLPrefix[] = "http://";
51const char HTTPProxy::kHTTPVersionPrefix[] = " HTTP/1";
52const char HTTPProxy::kInternalErrorMsg[] = "Proxy Failed: Internal Error";
53
Paul Stewartc8f4bef2011-12-13 09:45:51 -080054HTTPProxy::HTTPProxy(ConnectionRefPtr connection)
Paul Stewartf65320c2011-10-13 14:34:52 -070055 : state_(kStateIdle),
Paul Stewartc8f4bef2011-12-13 09:45:51 -080056 connection_(connection),
Eric Shienbrood3e20a232012-02-16 11:35:56 -050057 weak_ptr_factory_(this),
Eric Shienbrood9a245532012-03-07 14:20:39 -050058 accept_callback_(Bind(&HTTPProxy::AcceptClient,
59 weak_ptr_factory_.GetWeakPtr())),
Eric Shienbrood3e20a232012-02-16 11:35:56 -050060 connect_completion_callback_(Bind(&HTTPProxy::OnConnectCompletion,
Eric Shienbrood9a245532012-03-07 14:20:39 -050061 weak_ptr_factory_.GetWeakPtr())),
62 dns_client_callback_(Bind(&HTTPProxy::GetDNSResult,
63 weak_ptr_factory_.GetWeakPtr())),
64 read_client_callback_(Bind(&HTTPProxy::ReadFromClient,
65 weak_ptr_factory_.GetWeakPtr())),
66 read_server_callback_(Bind(&HTTPProxy::ReadFromServer,
67 weak_ptr_factory_.GetWeakPtr())),
68 write_client_callback_(Bind(&HTTPProxy::WriteToClient,
69 weak_ptr_factory_.GetWeakPtr())),
70 write_server_callback_(Bind(&HTTPProxy::WriteToServer,
71 weak_ptr_factory_.GetWeakPtr())),
Paul Stewartf65320c2011-10-13 14:34:52 -070072 dispatcher_(NULL),
73 dns_client_(NULL),
74 proxy_port_(-1),
75 proxy_socket_(-1),
76 server_async_connection_(NULL),
77 sockets_(NULL),
78 client_socket_(-1),
79 server_port_(kDefaultServerPort),
80 server_socket_(-1),
Eric Shienbrood3e20a232012-02-16 11:35:56 -050081 is_route_requested_(false) { }
Paul Stewartf65320c2011-10-13 14:34:52 -070082
83HTTPProxy::~HTTPProxy() {
84 Stop();
85}
86
87bool HTTPProxy::Start(EventDispatcher *dispatcher,
88 Sockets *sockets) {
89 VLOG(3) << "In " << __func__;
90
91 if (sockets_) {
92 // We are already running.
93 return true;
94 }
95
96 proxy_socket_ = sockets->Socket(PF_INET, SOCK_STREAM, 0);
97 if (proxy_socket_ < 0) {
98 PLOG(ERROR) << "Failed to open proxy socket";
99 return false;
100 }
101
102 struct sockaddr_in addr;
103 socklen_t addrlen = sizeof(addr);
104 memset(&addr, 0, sizeof(addr));
105 addr.sin_family = AF_INET;
106 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
107 if (sockets->Bind(proxy_socket_,
108 reinterpret_cast<struct sockaddr *>(&addr),
109 sizeof(addr)) < 0 ||
110 sockets->GetSockName(proxy_socket_,
111 reinterpret_cast<struct sockaddr *>(&addr),
112 &addrlen) < 0 ||
113 sockets->SetNonBlocking(proxy_socket_) < 0 ||
114 sockets->Listen(proxy_socket_, kMaxClientQueue) < 0) {
115 sockets->Close(proxy_socket_);
116 proxy_socket_ = -1;
117 PLOG(ERROR) << "HTTPProxy socket setup failed";
118 return false;
119 }
120
121 accept_handler_.reset(
122 dispatcher->CreateReadyHandler(proxy_socket_, IOHandler::kModeInput,
Eric Shienbrood3e20a232012-02-16 11:35:56 -0500123 accept_callback_));
Paul Stewartf65320c2011-10-13 14:34:52 -0700124 dispatcher_ = dispatcher;
125 dns_client_.reset(new DNSClient(IPAddress::kFamilyIPv4,
Paul Stewartc8f4bef2011-12-13 09:45:51 -0800126 connection_->interface_name(),
127 connection_->dns_servers(),
Paul Stewartf65320c2011-10-13 14:34:52 -0700128 kDNSTimeoutSeconds * 1000,
129 dispatcher,
Eric Shienbrood3e20a232012-02-16 11:35:56 -0500130 dns_client_callback_));
Paul Stewartf65320c2011-10-13 14:34:52 -0700131 proxy_port_ = ntohs(addr.sin_port);
132 server_async_connection_.reset(
Paul Stewartc8f4bef2011-12-13 09:45:51 -0800133 new AsyncConnection(connection_->interface_name(), dispatcher, sockets,
Eric Shienbrood3e20a232012-02-16 11:35:56 -0500134 connect_completion_callback_));
Paul Stewartf65320c2011-10-13 14:34:52 -0700135 sockets_ = sockets;
136 state_ = kStateWaitConnection;
137 return true;
138}
139
140void HTTPProxy::Stop() {
141 VLOG(3) << "In " << __func__;
142
143 if (!sockets_ ) {
144 return;
145 }
146
147 StopClient();
148
149 accept_handler_.reset();
150 dispatcher_ = NULL;
151 dns_client_.reset();
152 proxy_port_ = -1;
153 server_async_connection_.reset();
154 sockets_->Close(proxy_socket_);
155 proxy_socket_ = -1;
156 sockets_ = NULL;
157 state_ = kStateIdle;
158}
159
160// IOReadyHandler callback routine fired when a client connects to the
161// proxy's socket. We Accept() the client and start reading a request
162// from it.
163void HTTPProxy::AcceptClient(int fd) {
164 VLOG(3) << "In " << __func__;
165
166 int client_fd = sockets_->Accept(fd, NULL, NULL);
167 if (client_fd < 0) {
168 PLOG(ERROR) << "Client accept failed";
169 return;
170 }
171
172 accept_handler_->Stop();
173
174 client_socket_ = client_fd;
175
176 sockets_->SetNonBlocking(client_socket_);
177 read_client_handler_.reset(
178 dispatcher_->CreateInputHandler(client_socket_,
Eric Shienbrood3e20a232012-02-16 11:35:56 -0500179 read_client_callback_));
Paul Stewartf65320c2011-10-13 14:34:52 -0700180 // Overall transaction timeout.
Eric Shienbrood3e20a232012-02-16 11:35:56 -0500181 dispatcher_->PostDelayedTask(Bind(&HTTPProxy::StopClient,
182 weak_ptr_factory_.GetWeakPtr()),
183 kTransactionTimeoutSeconds * 1000);
Paul Stewartf65320c2011-10-13 14:34:52 -0700184
185 state_ = kStateReadClientHeader;
186 StartIdleTimeout();
187}
188
189bool HTTPProxy::ConnectServer(const IPAddress &address, int port) {
190 state_ = kStateConnectServer;
191 if (!server_async_connection_->Start(address, port)) {
192 SendClientError(500, "Could not create socket to connect to server");
193 return false;
194 }
195 StartIdleTimeout();
196 return true;
197}
198
199// DNSClient callback that fires when the DNS request completes.
Paul Stewartbdb02e62012-02-22 16:24:33 -0800200void HTTPProxy::GetDNSResult(const Error &error, const IPAddress &address) {
201 if (!error.IsSuccess()) {
Paul Stewartf65320c2011-10-13 14:34:52 -0700202 SendClientError(502, string("Could not resolve hostname: ") +
Paul Stewartbdb02e62012-02-22 16:24:33 -0800203 error.message());
Paul Stewartf65320c2011-10-13 14:34:52 -0700204 return;
205 }
Paul Stewartbdb02e62012-02-22 16:24:33 -0800206 ConnectServer(address, server_port_);
Paul Stewartf65320c2011-10-13 14:34:52 -0700207}
208
209// IOReadyHandler callback routine which fires when the asynchronous Connect()
210// to the remote server completes (or fails).
211void HTTPProxy::OnConnectCompletion(bool success, int fd) {
212 if (!success) {
213 SendClientError(500, string("Socket connection delayed failure: ") +
214 server_async_connection_->error());
215 return;
216 }
217 server_socket_ = fd;
218 state_ = kStateTunnelData;
Paul Stewart58a577b2012-01-10 11:18:52 -0800219
220 // If this was a "CONNECT" request, notify the client that the connection
221 // has been established by sending an "OK" response.
222 if (LowerCaseEqualsASCII(client_method_, kHTTPMethodConnect)) {
223 SetClientResponse(200, "OK", "", "");
224 StartReceive();
225 }
226
Paul Stewartf65320c2011-10-13 14:34:52 -0700227 StartTransmit();
228}
229
230// Read through the header lines from the client, modifying or adding
231// lines as necessary. Perform final determination of the hostname/port
232// we should connect to and either start a DNS request or connect to a
233// numeric address.
234bool HTTPProxy::ParseClientRequest() {
235 VLOG(3) << "In " << __func__;
236
237 string host;
238 bool found_via = false;
239 bool found_connection = false;
240 for (vector<string>::iterator it = client_headers_.begin();
241 it != client_headers_.end(); ++it) {
242 if (StartsWithASCII(*it, "Host:", false)) {
243 host = it->substr(5);
244 } else if (StartsWithASCII(*it, "Via:", false)) {
245 found_via = true;
246 (*it).append(StringPrintf(", %s shill-proxy", client_version_.c_str()));
247 } else if (StartsWithASCII(*it, "Connection:", false)) {
248 found_connection = true;
249 (*it).assign("Connection: close");
250 } else if (StartsWithASCII(*it, "Proxy-Connection:", false)) {
251 (*it).assign("Proxy-Connection: close");
252 }
253 }
254
255 if (!found_connection) {
256 client_headers_.push_back("Connection: close");
257 }
258 if (!found_via) {
259 client_headers_.push_back(
260 StringPrintf("Via: %s shill-proxy", client_version_.c_str()));
261 }
262
263 // Assemble the request as it will be sent to the server.
264 client_data_.Clear();
Paul Stewart58a577b2012-01-10 11:18:52 -0800265 if (!LowerCaseEqualsASCII(client_method_, kHTTPMethodConnect)) {
266 for (vector<string>::iterator it = client_headers_.begin();
267 it != client_headers_.end(); ++it) {
268 client_data_.Append(ByteString(*it + "\r\n", false));
269 }
270 client_data_.Append(ByteString(string("\r\n"), false));
Paul Stewartf65320c2011-10-13 14:34:52 -0700271 }
Paul Stewartf65320c2011-10-13 14:34:52 -0700272
273 TrimWhitespaceASCII(host, TRIM_ALL, &host);
274 if (host.empty()) {
275 // Revert to using the hostname in the URL if no "Host:" header exists.
276 host = server_hostname_;
277 }
278
279 if (host.empty()) {
280 SendClientError(400, "I don't know what host you want me to connect to");
281 return false;
282 }
283
284 server_port_ = 80;
285 vector<string> host_parts;
286 base::SplitString(host, ':', &host_parts);
287
288 if (host_parts.size() > 2) {
289 SendClientError(400, "Too many colons in hostname");
290 return false;
291 } else if (host_parts.size() == 2) {
292 server_hostname_ = host_parts[0];
293 if (!base::StringToInt(host_parts[1], &server_port_)) {
294 SendClientError(400, "Could not parse port number");
295 return false;
296 }
297 } else {
298 server_hostname_ = host;
299 }
300
Paul Stewartc8f4bef2011-12-13 09:45:51 -0800301 connection_->RequestRouting();
302 is_route_requested_ = true;
303
Paul Stewartf65320c2011-10-13 14:34:52 -0700304 IPAddress addr(IPAddress::kFamilyIPv4);
305 if (addr.SetAddressFromString(server_hostname_)) {
306 if (!ConnectServer(addr, server_port_)) {
307 return false;
308 }
309 } else {
310 VLOG(3) << "Looking up host: " << server_hostname_;
Paul Stewartbdb02e62012-02-22 16:24:33 -0800311 Error error;
312 if (!dns_client_->Start(server_hostname_, &error)) {
313 SendClientError(502, "Could not resolve hostname: " + error.message());
Paul Stewartf65320c2011-10-13 14:34:52 -0700314 return false;
315 }
316 state_ = kStateLookupServer;
317 }
318 return true;
319}
320
321// Accept a new line into the client headers. Returns false if a parse
322// error occurs.
323bool HTTPProxy::ProcessLastHeaderLine() {
324 string *header = &client_headers_.back();
325 TrimString(*header, "\r", header);
326
327 if (header->empty()) {
328 // Empty line terminates client headers.
329 client_headers_.pop_back();
330 if (!ParseClientRequest()) {
331 return false;
332 }
333 }
334
335 // Is this is the first header line?
336 if (client_headers_.size() == 1) {
Paul Stewart58a577b2012-01-10 11:18:52 -0800337 if (!ReadClientHTTPMethod(header) ||
338 !ReadClientHTTPVersion(header) ||
339 !ReadClientHostname(header)) {
Paul Stewartf65320c2011-10-13 14:34:52 -0700340 return false;
341 }
342 }
343
344 if (client_headers_.size() >= kMaxHeaderCount) {
345 SendClientError(500, kInternalErrorMsg);
346 return false;
347 }
348
349 return true;
350}
351
352// Split input from client into header lines, and consume parsed lines
353// from InputData. The passed in |data| is modified to indicate the
354// characters consumed.
355bool HTTPProxy::ReadClientHeaders(InputData *data) {
356 unsigned char *ptr = data->buf;
357 unsigned char *end = ptr + data->len;
358
359 if (client_headers_.empty()) {
360 client_headers_.push_back(string());
361 }
362
363 for (; ptr < end && state_ == kStateReadClientHeader; ++ptr) {
364 if (*ptr == '\n') {
365 if (!ProcessLastHeaderLine()) {
366 return false;
367 }
368
369 // Start a new line. New chararacters we receive will be appended there.
370 client_headers_.push_back(string());
371 continue;
372 }
373
374 string *header = &client_headers_.back();
375 // Is the first character of the header line a space or tab character?
376 if (header->empty() && (*ptr == ' ' || *ptr == '\t') &&
377 client_headers_.size() > 1) {
378 // Line Continuation: Add this character to the previous header line.
379 // This way, all of the data (including newlines and line continuation
380 // characters) related to a specific header will be contained within
381 // a single element of |client_headers_|, and manipulation of headers
382 // such as appending will be simpler. This is accomplished by removing
383 // the empty line we started, and instead appending the whitespace
384 // and following characters to the previous line.
385 client_headers_.pop_back();
386 header = &client_headers_.back();
387 header->append("\r\n");
388 }
389
390 if (header->length() >= kMaxHeaderSize) {
391 SendClientError(500, kInternalErrorMsg);
392 return false;
393 }
394 header->push_back(*ptr);
395 }
396
397 // Return the remaining data to the caller -- this could be POST data
398 // or other non-header data sent with the client request.
399 data->buf = ptr;
400 data->len = end - ptr;
401
402 return true;
403}
404
405// Finds the URL in the first line of an HTTP client header, and extracts
406// and removes the hostname (and port) from the URL. Returns false if a
407// parse error occurs, and true otherwise (whether or not the hostname was
408// found).
409bool HTTPProxy::ReadClientHostname(string *header) {
410 const string http_url_prefix(kHTTPURLPrefix);
411 size_t url_idx = header->find(http_url_prefix);
412 if (url_idx != string::npos) {
413 size_t host_start = url_idx + http_url_prefix.length();
414 size_t host_end =
415 header->find_first_of(kHTTPURLDelimiters, host_start);
416 if (host_end != string::npos) {
417 server_hostname_ = header->substr(host_start,
418 host_end - host_start);
419 // Modify the URL passed upstream to remove "http://<hostname>".
420 header->erase(url_idx, host_end - url_idx);
421 if ((*header)[url_idx] != '/') {
422 header->insert(url_idx, "/");
423 }
424 } else {
425 LOG(ERROR) << "Could not find end of hostname in request. Line was: "
426 << *header;
427 SendClientError(500, kInternalErrorMsg);
428 return false;
429 }
430 }
431 return true;
432}
433
Paul Stewart58a577b2012-01-10 11:18:52 -0800434bool HTTPProxy::ReadClientHTTPMethod(string *header) {
435 size_t method_end = header->find(kHTTPMethodTerminator);
436 if (method_end == string::npos || method_end == 0) {
437 LOG(ERROR) << "Could not parse HTTP method. Line was: " << *header;
438 SendClientError(501, "Server could not parse HTTP method");
439 return false;
440 }
441 client_method_ = header->substr(0, method_end);
442 return true;
443}
444
Paul Stewartf65320c2011-10-13 14:34:52 -0700445// Extract the HTTP version number from the first line of the client headers.
446// Returns true if found.
447bool HTTPProxy::ReadClientHTTPVersion(string *header) {
448 const string http_version_prefix(kHTTPVersionPrefix);
449 size_t http_ver_pos = header->find(http_version_prefix);
450 if (http_ver_pos != string::npos) {
451 client_version_ =
452 header->substr(http_ver_pos + http_version_prefix.length() - 1);
453 } else {
454 SendClientError(501, "Server only accepts HTTP/1.x requests");
455 return false;
456 }
457 return true;
458}
459
460// IOInputHandler callback that fires when data is read from the client.
461// This could be header data, or perhaps POST data that follows the headers.
462void HTTPProxy::ReadFromClient(InputData *data) {
463 VLOG(3) << "In " << __func__ << " length " << data->len;
464
465 if (data->len == 0) {
466 // EOF from client.
467 StopClient();
468 return;
469 }
470
471 if (state_ == kStateReadClientHeader) {
472 if (!ReadClientHeaders(data)) {
473 return;
474 }
475 if (state_ == kStateReadClientHeader) {
476 // Still consuming client headers; restart the input timer.
477 StartIdleTimeout();
478 return;
479 }
480 }
481
482 // Check data->len again since ReadClientHeaders() may have consumed some
483 // part of it.
484 if (data->len != 0) {
485 // The client sent some information after its headers. Buffer the client
486 // input and temporarily disable input events from the client.
487 client_data_.Append(ByteString(data->buf, data->len));
488 read_client_handler_->Stop();
489 StartTransmit();
490 }
491}
492
493// IOInputHandler callback which fires when data has been read from the
494// server.
495void HTTPProxy::ReadFromServer(InputData *data) {
496 VLOG(3) << "In " << __func__ << " length " << data->len;
497 if (data->len == 0) {
498 // Server closed connection.
499 if (server_data_.IsEmpty()) {
500 StopClient();
501 return;
502 }
503 state_ = kStateFlushResponse;
504 } else {
505 read_server_handler_->Stop();
506 }
507
508 server_data_.Append(ByteString(data->buf, data->len));
509
510 StartTransmit();
511}
512
513// Return an HTTP error message back to the client.
514void HTTPProxy::SendClientError(int code, const string &error) {
515 VLOG(3) << "In " << __func__;
516 LOG(ERROR) << "Sending error " << error;
Paul Stewart58a577b2012-01-10 11:18:52 -0800517 SetClientResponse(code, "ERROR", "text/plain", error);
Paul Stewartf65320c2011-10-13 14:34:52 -0700518 state_ = kStateFlushResponse;
519 StartTransmit();
520}
521
Paul Stewart58a577b2012-01-10 11:18:52 -0800522// Create an HTTP response message to be sent to the client.
523void HTTPProxy::SetClientResponse(int code, const string &type,
524 const string &content_type,
525 const string &message) {
526 string content_line;
527 if (!message.empty() && !content_type.empty()) {
528 content_line = StringPrintf("Content-Type: %s\r\n", content_type.c_str());
529 }
530 string response = StringPrintf("HTTP/1.1 %d %s\r\n"
531 "%s\r\n"
532 "%s", code, type.c_str(),
533 content_line.c_str(),
534 message.c_str());
535 server_data_ = ByteString(response, false);
536}
537
Paul Stewartf65320c2011-10-13 14:34:52 -0700538// Start a timeout for "the next event". This timeout augments the overall
539// transaction timeout to make sure there is some activity occurring at
540// reasonable intervals.
541void HTTPProxy::StartIdleTimeout() {
542 int timeout_seconds = 0;
543 switch (state_) {
544 case kStateReadClientHeader:
545 timeout_seconds = kClientHeaderTimeoutSeconds;
546 break;
547 case kStateConnectServer:
548 timeout_seconds = kConnectTimeoutSeconds;
549 break;
550 case kStateLookupServer:
551 // DNSClient has its own internal timeout, so we need not set one here.
552 timeout_seconds = 0;
553 break;
554 default:
555 timeout_seconds = kInputTimeoutSeconds;
556 break;
557 }
Eric Shienbrood3e20a232012-02-16 11:35:56 -0500558 idle_timeout_.Cancel();
Paul Stewartf65320c2011-10-13 14:34:52 -0700559 if (timeout_seconds != 0) {
Eric Shienbrood3e20a232012-02-16 11:35:56 -0500560 idle_timeout_.Reset(Bind(&HTTPProxy::StopClient,
561 weak_ptr_factory_.GetWeakPtr()));
562 dispatcher_->PostDelayedTask(idle_timeout_.callback(),
563 timeout_seconds * 1000);
Paul Stewartf65320c2011-10-13 14:34:52 -0700564 }
565}
566
567// Start the various input handlers. Listen for new data only if we have
568// completely written the last data we've received to the other end.
569void HTTPProxy::StartReceive() {
570 if (state_ == kStateTunnelData && client_data_.IsEmpty()) {
571 read_client_handler_->Start();
572 }
573 if (server_data_.IsEmpty()) {
574 if (state_ == kStateTunnelData) {
575 if (read_server_handler_.get()) {
576 read_server_handler_->Start();
577 } else {
578 read_server_handler_.reset(
579 dispatcher_->CreateInputHandler(server_socket_,
Eric Shienbrood3e20a232012-02-16 11:35:56 -0500580 read_server_callback_));
Paul Stewartf65320c2011-10-13 14:34:52 -0700581 }
582 } else if (state_ == kStateFlushResponse) {
583 StopClient();
584 return;
585 }
586 }
587 StartIdleTimeout();
588}
589
590// Start the various output-ready handlers for the endpoints we have
591// data waiting for.
592void HTTPProxy::StartTransmit() {
593 if (state_ == kStateTunnelData && !client_data_.IsEmpty()) {
594 if (write_server_handler_.get()) {
595 write_server_handler_->Start();
596 } else {
597 write_server_handler_.reset(
598 dispatcher_->CreateReadyHandler(server_socket_,
599 IOHandler::kModeOutput,
Eric Shienbrood3e20a232012-02-16 11:35:56 -0500600 write_server_callback_));
Paul Stewartf65320c2011-10-13 14:34:52 -0700601 }
602 }
603 if ((state_ == kStateFlushResponse || state_ == kStateTunnelData) &&
604 !server_data_.IsEmpty()) {
605 if (write_client_handler_.get()) {
606 write_client_handler_->Start();
607 } else {
608 write_client_handler_.reset(
609 dispatcher_->CreateReadyHandler(client_socket_,
610 IOHandler::kModeOutput,
Eric Shienbrood3e20a232012-02-16 11:35:56 -0500611 write_client_callback_));
Paul Stewartf65320c2011-10-13 14:34:52 -0700612 }
613 }
614 StartIdleTimeout();
615}
616
617// End the transaction with the current client, restart the IOHandler
618// which alerts us to new clients connecting. This function is called
619// during various error conditions and is a callback for all timeouts.
620void HTTPProxy::StopClient() {
621 VLOG(3) << "In " << __func__;
622
Paul Stewartc8f4bef2011-12-13 09:45:51 -0800623 if (is_route_requested_) {
624 connection_->ReleaseRouting();
625 is_route_requested_ = false;
626 }
Paul Stewartf65320c2011-10-13 14:34:52 -0700627 write_client_handler_.reset();
628 read_client_handler_.reset();
629 if (client_socket_ != -1) {
630 sockets_->Close(client_socket_);
631 client_socket_ = -1;
632 }
633 client_headers_.clear();
Paul Stewart58a577b2012-01-10 11:18:52 -0800634 client_method_.clear();
Paul Stewartf65320c2011-10-13 14:34:52 -0700635 client_version_.clear();
636 server_port_ = kDefaultServerPort;
637 write_server_handler_.reset();
638 read_server_handler_.reset();
639 if (server_socket_ != -1) {
640 sockets_->Close(server_socket_);
641 server_socket_ = -1;
642 }
643 server_hostname_.clear();
644 client_data_.Clear();
645 server_data_.Clear();
646 dns_client_->Stop();
647 server_async_connection_->Stop();
Eric Shienbrood3e20a232012-02-16 11:35:56 -0500648 idle_timeout_.Cancel();
649 weak_ptr_factory_.InvalidateWeakPtrs();
Paul Stewartf65320c2011-10-13 14:34:52 -0700650 accept_handler_->Start();
651 state_ = kStateWaitConnection;
652}
653
654// Output ReadyHandler callback which fires when the client socket is
655// ready for data to be sent to it.
656void HTTPProxy::WriteToClient(int fd) {
657 CHECK_EQ(client_socket_, fd);
658 int ret = sockets_->Send(fd, server_data_.GetConstData(),
659 server_data_.GetLength(), 0);
660 VLOG(3) << "In " << __func__ << " wrote " << ret << " of " <<
661 server_data_.GetLength();
662 if (ret < 0) {
663 LOG(ERROR) << "Server write failed";
664 StopClient();
665 return;
666 }
667
668 server_data_ = ByteString(server_data_.GetConstData() + ret,
669 server_data_.GetLength() - ret);
670
671 if (server_data_.IsEmpty()) {
672 write_client_handler_->Stop();
673 }
674
675 StartReceive();
676}
677
678// Output ReadyHandler callback which fires when the server socket is
679// ready for data to be sent to it.
680void HTTPProxy::WriteToServer(int fd) {
681 CHECK_EQ(server_socket_, fd);
682 int ret = sockets_->Send(fd, client_data_.GetConstData(),
683 client_data_.GetLength(), 0);
684 VLOG(3) << "In " << __func__ << " wrote " << ret << " of " <<
685 client_data_.GetLength();
686
687 if (ret < 0) {
688 LOG(ERROR) << "Client write failed";
689 StopClient();
690 return;
691 }
692
693 client_data_ = ByteString(client_data_.GetConstData() + ret,
694 client_data_.GetLength() - ret);
695
696 if (client_data_.IsEmpty()) {
697 write_server_handler_->Stop();
698 }
699
700 StartReceive();
701}
702
703} // namespace shill