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