1/*
2 * libjingle
3 * Copyright 2004--2005, Google Inc.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
8 *  1. Redistributions of source code must retain the above copyright notice,
9 *     this list of conditions and the following disclaimer.
10 *  2. Redistributions in binary form must reproduce the above copyright notice,
11 *     this list of conditions and the following disclaimer in the documentation
12 *     and/or other materials provided with the distribution.
13 *  3. The name of the author may not be used to endorse or promote products
14 *     derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28#include <time.h>
29
30#include "talk/base/httpcommon-inl.h"
31
32#include "talk/base/asyncsocket.h"
33#include "talk/base/common.h"
34#include "talk/base/diskcache.h"
35#include "talk/base/httpclient.h"
36#include "talk/base/logging.h"
37#include "talk/base/pathutils.h"
38#include "talk/base/socketstream.h"
39#include "talk/base/stringencode.h"
40#include "talk/base/stringutils.h"
41#include "talk/base/thread.h"
42
43namespace talk_base {
44
45//////////////////////////////////////////////////////////////////////
46// Helpers
47//////////////////////////////////////////////////////////////////////
48
49namespace {
50
51const size_t kCacheHeader = 0;
52const size_t kCacheBody = 1;
53
54// Convert decimal string to integer
55bool HttpStringToUInt(const std::string& str, size_t* val) {
56  ASSERT(NULL != val);
57  char* eos = NULL;
58  *val = strtoul(str.c_str(), &eos, 10);
59  return (*eos == '\0');
60}
61
62bool HttpShouldCache(const HttpTransaction& t) {
63  bool verb_allows_cache = (t.request.verb == HV_GET)
64                           || (t.request.verb == HV_HEAD);
65  bool is_range_response = t.response.hasHeader(HH_CONTENT_RANGE, NULL);
66  bool has_expires = t.response.hasHeader(HH_EXPIRES, NULL);
67  bool request_allows_cache =
68    has_expires || (std::string::npos != t.request.path.find('?'));
69  bool response_allows_cache =
70    has_expires || HttpCodeIsCacheable(t.response.scode);
71
72  bool may_cache = verb_allows_cache
73                   && request_allows_cache
74                   && response_allows_cache
75                   && !is_range_response;
76
77  std::string value;
78  if (t.response.hasHeader(HH_CACHE_CONTROL, &value)) {
79    HttpAttributeList directives;
80    HttpParseAttributes(value.data(), value.size(), directives);
81    // Response Directives Summary:
82    // public - always cacheable
83    // private - do not cache in a shared cache
84    // no-cache - may cache, but must revalidate whether fresh or stale
85    // no-store - sensitive information, do not cache or store in any way
86    // max-age - supplants Expires for staleness
87    // s-maxage - use as max-age for shared caches, ignore otherwise
88    // must-revalidate - may cache, but must revalidate after stale
89    // proxy-revalidate - shared cache must revalidate
90    if (HttpHasAttribute(directives, "no-store", NULL)) {
91      may_cache = false;
92    } else if (HttpHasAttribute(directives, "public", NULL)) {
93      may_cache = true;
94    }
95  }
96  return may_cache;
97}
98
99enum HttpCacheState {
100  HCS_FRESH,  // In cache, may use
101  HCS_STALE,  // In cache, must revalidate
102  HCS_NONE    // Not in cache
103};
104
105HttpCacheState HttpGetCacheState(const HttpTransaction& t) {
106  // Temporaries
107  std::string s_temp;
108  time_t u_temp;
109
110  // Current time
111  size_t now = time(0);
112
113  HttpAttributeList cache_control;
114  if (t.response.hasHeader(HH_CACHE_CONTROL, &s_temp)) {
115    HttpParseAttributes(s_temp.data(), s_temp.size(), cache_control);
116  }
117
118  // Compute age of cache document
119  time_t date;
120  if (!t.response.hasHeader(HH_DATE, &s_temp)
121      || !HttpDateToSeconds(s_temp, &date))
122    return HCS_NONE;
123
124  // TODO: Timestamp when cache request sent and response received?
125  time_t request_time = date;
126  time_t response_time = date;
127
128  time_t apparent_age = 0;
129  if (response_time > date) {
130    apparent_age = response_time - date;
131  }
132
133  size_t corrected_received_age = apparent_age;
134  size_t i_temp;
135  if (t.response.hasHeader(HH_AGE, &s_temp)
136      && HttpStringToUInt(s_temp, (&i_temp))) {
137    u_temp = static_cast<time_t>(i_temp);
138    corrected_received_age = stdmax(apparent_age, u_temp);
139  }
140
141  size_t response_delay = response_time - request_time;
142  size_t corrected_initial_age = corrected_received_age + response_delay;
143  size_t resident_time = now - response_time;
144  size_t current_age = corrected_initial_age + resident_time;
145
146  // Compute lifetime of document
147  size_t lifetime;
148  if (HttpHasAttribute(cache_control, "max-age", &s_temp)) {
149    lifetime = atoi(s_temp.c_str());
150  } else if (t.response.hasHeader(HH_EXPIRES, &s_temp)
151             && HttpDateToSeconds(s_temp, &u_temp)) {
152    lifetime = u_temp - date;
153  } else if (t.response.hasHeader(HH_LAST_MODIFIED, &s_temp)
154             && HttpDateToSeconds(s_temp, &u_temp)) {
155    // TODO: Issue warning 113 if age > 24 hours
156    lifetime = static_cast<size_t>(now - u_temp) / 10;
157  } else {
158    return HCS_STALE;
159  }
160
161  return (lifetime > current_age) ? HCS_FRESH : HCS_STALE;
162}
163
164enum HttpValidatorStrength {
165  HVS_NONE,
166  HVS_WEAK,
167  HVS_STRONG
168};
169
170HttpValidatorStrength
171HttpRequestValidatorLevel(const HttpRequestData& request) {
172  if (HV_GET != request.verb)
173    return HVS_STRONG;
174  return request.hasHeader(HH_RANGE, NULL) ? HVS_STRONG : HVS_WEAK;
175}
176
177HttpValidatorStrength
178HttpResponseValidatorLevel(const HttpResponseData& response) {
179  std::string value;
180  if (response.hasHeader(HH_ETAG, &value)) {
181    bool is_weak = (strnicmp(value.c_str(), "W/", 2) == 0);
182    return is_weak ? HVS_WEAK : HVS_STRONG;
183  }
184  if (response.hasHeader(HH_LAST_MODIFIED, &value)) {
185    time_t last_modified, date;
186    if (HttpDateToSeconds(value, &last_modified)
187        && response.hasHeader(HH_DATE, &value)
188        && HttpDateToSeconds(value, &date)
189        && (last_modified + 60 < date)) {
190      return HVS_STRONG;
191    }
192    return HVS_WEAK;
193  }
194  return HVS_NONE;
195}
196
197std::string GetCacheID(const HttpRequestData& request) {
198  std::string id, url;
199  id.append(ToString(request.verb));
200  id.append("_");
201  request.getAbsoluteUri(&url);
202  id.append(url);
203  return id;
204}
205
206}  // anonymous namespace
207
208//////////////////////////////////////////////////////////////////////
209// Public Helpers
210//////////////////////////////////////////////////////////////////////
211
212bool HttpWriteCacheHeaders(const HttpResponseData* response,
213                           StreamInterface* output, size_t* size) {
214  size_t length = 0;
215  // Write all unknown and end-to-end headers to a cache file
216  for (HttpData::const_iterator it = response->begin();
217       it != response->end(); ++it) {
218    HttpHeader header;
219    if (FromString(header, it->first) && !HttpHeaderIsEndToEnd(header))
220      continue;
221    length += it->first.length() + 2 + it->second.length() + 2;
222    if (!output)
223      continue;
224    std::string formatted_header(it->first);
225    formatted_header.append(": ");
226    formatted_header.append(it->second);
227    formatted_header.append("\r\n");
228    StreamResult result = output->WriteAll(formatted_header.data(),
229                                           formatted_header.length(),
230                                           NULL, NULL);
231    if (SR_SUCCESS != result) {
232      return false;
233    }
234  }
235  if (output && (SR_SUCCESS != output->WriteAll("\r\n", 2, NULL, NULL))) {
236    return false;
237  }
238  length += 2;
239  if (size)
240    *size = length;
241  return true;
242}
243
244bool HttpReadCacheHeaders(StreamInterface* input, HttpResponseData* response,
245                          HttpData::HeaderCombine combine) {
246  while (true) {
247    std::string formatted_header;
248    StreamResult result = input->ReadLine(&formatted_header);
249    if ((SR_EOS == result) || (1 == formatted_header.size())) {
250      break;
251    }
252    if (SR_SUCCESS != result) {
253      return false;
254    }
255    size_t end_of_name = formatted_header.find(':');
256    if (std::string::npos == end_of_name) {
257      LOG_F(LS_WARNING) << "Malformed cache header";
258      continue;
259    }
260    size_t start_of_value = end_of_name + 1;
261    size_t end_of_value = formatted_header.length();
262    while ((start_of_value < end_of_value)
263           && isspace(formatted_header[start_of_value]))
264      ++start_of_value;
265    while ((start_of_value < end_of_value)
266           && isspace(formatted_header[end_of_value-1]))
267     --end_of_value;
268    size_t value_length = end_of_value - start_of_value;
269
270    std::string name(formatted_header.substr(0, end_of_name));
271    std::string value(formatted_header.substr(start_of_value, value_length));
272    response->changeHeader(name, value, combine);
273  }
274  return true;
275}
276
277//////////////////////////////////////////////////////////////////////
278// HttpClient
279//////////////////////////////////////////////////////////////////////
280
281const size_t kDefaultRetries = 1;
282const size_t kMaxRedirects = 5;
283
284HttpClient::HttpClient(const std::string& agent, StreamPool* pool,
285                       HttpTransaction* transaction)
286    : agent_(agent), pool_(pool),
287      transaction_(transaction), free_transaction_(false),
288      retries_(kDefaultRetries), attempt_(0), redirects_(0),
289      redirect_action_(REDIRECT_DEFAULT),
290      uri_form_(URI_DEFAULT), cache_(NULL), cache_state_(CS_READY),
291      resolver_(NULL) {
292  base_.notify(this);
293  if (NULL == transaction_) {
294    free_transaction_ = true;
295    transaction_ = new HttpTransaction;
296  }
297}
298
299HttpClient::~HttpClient() {
300  base_.notify(NULL);
301  base_.abort(HE_SHUTDOWN);
302  if (resolver_) {
303    resolver_->Destroy(false);
304  }
305  release();
306  if (free_transaction_)
307    delete transaction_;
308}
309
310void HttpClient::reset() {
311  server_.Clear();
312  request().clear(true);
313  response().clear(true);
314  context_.reset();
315  redirects_ = 0;
316  base_.abort(HE_OPERATION_CANCELLED);
317}
318
319void HttpClient::OnResolveResult(AsyncResolverInterface* resolver) {
320  if (resolver != resolver_) {
321    return;
322  }
323  int error = resolver_->GetError();
324  server_ = resolver_->address();
325  resolver_->Destroy(false);
326  resolver_ = NULL;
327  if (error != 0) {
328    LOG(LS_ERROR) << "Error " << error << " resolving name: "
329                  << server_;
330    onHttpComplete(HM_CONNECT, HE_CONNECT_FAILED);
331  } else {
332    connect();
333  }
334}
335
336void HttpClient::StartDNSLookup() {
337  resolver_ = new AsyncResolver();
338  resolver_->SignalDone.connect(this, &HttpClient::OnResolveResult);
339  resolver_->Start(server_);
340}
341
342void HttpClient::set_server(const SocketAddress& address) {
343  server_ = address;
344  // Setting 'Host' here allows it to be overridden before starting the request,
345  // if necessary.
346  request().setHeader(HH_HOST, HttpAddress(server_, false), true);
347}
348
349StreamInterface* HttpClient::GetDocumentStream() {
350  return base_.GetDocumentStream();
351}
352
353void HttpClient::start() {
354  if (base_.mode() != HM_NONE) {
355    // call reset() to abort an in-progress request
356    ASSERT(false);
357    return;
358  }
359
360  ASSERT(!IsCacheActive());
361
362  if (request().hasHeader(HH_TRANSFER_ENCODING, NULL)) {
363    // Exact size must be known on the client.  Instead of using chunked
364    // encoding, wrap data with auto-caching file or memory stream.
365    ASSERT(false);
366    return;
367  }
368
369  attempt_ = 0;
370
371  // If no content has been specified, using length of 0.
372  request().setHeader(HH_CONTENT_LENGTH, "0", false);
373
374  if (!agent_.empty()) {
375    request().setHeader(HH_USER_AGENT, agent_, false);
376  }
377
378  UriForm uri_form = uri_form_;
379  if (PROXY_HTTPS == proxy_.type) {
380    // Proxies require absolute form
381    uri_form = URI_ABSOLUTE;
382    request().version = HVER_1_0;
383    request().setHeader(HH_PROXY_CONNECTION, "Keep-Alive", false);
384  } else {
385    request().setHeader(HH_CONNECTION, "Keep-Alive", false);
386  }
387
388  if (URI_ABSOLUTE == uri_form) {
389    // Convert to absolute uri form
390    std::string url;
391    if (request().getAbsoluteUri(&url)) {
392      request().path = url;
393    } else {
394      LOG(LS_WARNING) << "Couldn't obtain absolute uri";
395    }
396  } else if (URI_RELATIVE == uri_form) {
397    // Convert to relative uri form
398    std::string host, path;
399    if (request().getRelativeUri(&host, &path)) {
400      request().setHeader(HH_HOST, host);
401      request().path = path;
402    } else {
403      LOG(LS_WARNING) << "Couldn't obtain relative uri";
404    }
405  }
406
407  if ((NULL != cache_) && CheckCache()) {
408    return;
409  }
410
411  connect();
412}
413
414void HttpClient::connect() {
415  int stream_err;
416  if (server_.IsUnresolvedIP()) {
417    StartDNSLookup();
418    return;
419  }
420  StreamInterface* stream = pool_->RequestConnectedStream(server_, &stream_err);
421  if (stream == NULL) {
422    ASSERT(0 != stream_err);
423    LOG(LS_ERROR) << "RequestConnectedStream error: " << stream_err;
424    onHttpComplete(HM_CONNECT, HE_CONNECT_FAILED);
425  } else {
426    base_.attach(stream);
427    if (stream->GetState() == SS_OPEN) {
428      base_.send(&transaction_->request);
429    }
430  }
431}
432
433void HttpClient::prepare_get(const std::string& url) {
434  reset();
435  Url<char> purl(url);
436  set_server(SocketAddress(purl.host(), purl.port()));
437  request().verb = HV_GET;
438  request().path = purl.full_path();
439}
440
441void HttpClient::prepare_post(const std::string& url,
442                              const std::string& content_type,
443                              StreamInterface* request_doc) {
444  reset();
445  Url<char> purl(url);
446  set_server(SocketAddress(purl.host(), purl.port()));
447  request().verb = HV_POST;
448  request().path = purl.full_path();
449  request().setContent(content_type, request_doc);
450}
451
452void HttpClient::release() {
453  if (StreamInterface* stream = base_.detach()) {
454    pool_->ReturnConnectedStream(stream);
455  }
456}
457
458bool HttpClient::ShouldRedirect(std::string* location) const {
459  // TODO: Unittest redirection.
460  if ((REDIRECT_NEVER == redirect_action_)
461      || !HttpCodeIsRedirection(response().scode)
462      || !response().hasHeader(HH_LOCATION, location)
463      || (redirects_ >= kMaxRedirects))
464    return false;
465  return (REDIRECT_ALWAYS == redirect_action_)
466         || (HC_SEE_OTHER == response().scode)
467         || (HV_HEAD == request().verb)
468         || (HV_GET == request().verb);
469}
470
471bool HttpClient::BeginCacheFile() {
472  ASSERT(NULL != cache_);
473  ASSERT(CS_READY == cache_state_);
474
475  std::string id = GetCacheID(request());
476  CacheLock lock(cache_, id, true);
477  if (!lock.IsLocked()) {
478    LOG_F(LS_WARNING) << "Couldn't lock cache";
479    return false;
480  }
481
482  if (HE_NONE != WriteCacheHeaders(id)) {
483    return false;
484  }
485
486  scoped_ptr<StreamInterface> stream(cache_->WriteResource(id, kCacheBody));
487  if (!stream) {
488    LOG_F(LS_ERROR) << "Couldn't open body cache";
489    return false;
490  }
491  lock.Commit();
492
493  // Let's secretly replace the response document with Folgers Crystals,
494  // er, StreamTap, so that we can mirror the data to our cache.
495  StreamInterface* output = response().document.release();
496  if (!output) {
497    output = new NullStream;
498  }
499  StreamTap* tap = new StreamTap(output, stream.release());
500  response().document.reset(tap);
501  return true;
502}
503
504HttpError HttpClient::WriteCacheHeaders(const std::string& id) {
505  scoped_ptr<StreamInterface> stream(cache_->WriteResource(id, kCacheHeader));
506  if (!stream) {
507    LOG_F(LS_ERROR) << "Couldn't open header cache";
508    return HE_CACHE;
509  }
510
511  if (!HttpWriteCacheHeaders(&transaction_->response, stream.get(), NULL)) {
512    LOG_F(LS_ERROR) << "Couldn't write header cache";
513    return HE_CACHE;
514  }
515
516  return HE_NONE;
517}
518
519void HttpClient::CompleteCacheFile() {
520  // Restore previous response document
521  StreamTap* tap = static_cast<StreamTap*>(response().document.release());
522  response().document.reset(tap->Detach());
523
524  int error;
525  StreamResult result = tap->GetTapResult(&error);
526
527  // Delete the tap and cache stream (which completes cache unlock)
528  delete tap;
529
530  if (SR_SUCCESS != result) {
531    LOG(LS_ERROR) << "Cache file error: " << error;
532    cache_->DeleteResource(GetCacheID(request()));
533  }
534}
535
536bool HttpClient::CheckCache() {
537  ASSERT(NULL != cache_);
538  ASSERT(CS_READY == cache_state_);
539
540  std::string id = GetCacheID(request());
541  if (!cache_->HasResource(id)) {
542    // No cache file available
543    return false;
544  }
545
546  HttpError error = ReadCacheHeaders(id, true);
547
548  if (HE_NONE == error) {
549    switch (HttpGetCacheState(*transaction_)) {
550    case HCS_FRESH:
551      // Cache content is good, read from cache
552      break;
553    case HCS_STALE:
554      // Cache content may be acceptable.  Issue a validation request.
555      if (PrepareValidate()) {
556        return false;
557      }
558      // Couldn't validate, fall through.
559    case HCS_NONE:
560      // Cache content is not useable.  Issue a regular request.
561      response().clear(false);
562      return false;
563    }
564  }
565
566  if (HE_NONE == error) {
567    error = ReadCacheBody(id);
568    cache_state_ = CS_READY;
569  }
570
571  if (HE_CACHE == error) {
572    LOG_F(LS_WARNING) << "Cache failure, continuing with normal request";
573    response().clear(false);
574    return false;
575  }
576
577  SignalHttpClientComplete(this, error);
578  return true;
579}
580
581HttpError HttpClient::ReadCacheHeaders(const std::string& id, bool override) {
582  scoped_ptr<StreamInterface> stream(cache_->ReadResource(id, kCacheHeader));
583  if (!stream) {
584    return HE_CACHE;
585  }
586
587  HttpData::HeaderCombine combine =
588    override ? HttpData::HC_REPLACE : HttpData::HC_AUTO;
589
590  if (!HttpReadCacheHeaders(stream.get(), &transaction_->response, combine)) {
591    LOG_F(LS_ERROR) << "Error reading cache headers";
592    return HE_CACHE;
593  }
594
595  response().scode = HC_OK;
596  return HE_NONE;
597}
598
599HttpError HttpClient::ReadCacheBody(const std::string& id) {
600  cache_state_ = CS_READING;
601
602  HttpError error = HE_NONE;
603
604  size_t data_size;
605  scoped_ptr<StreamInterface> stream(cache_->ReadResource(id, kCacheBody));
606  if (!stream || !stream->GetAvailable(&data_size)) {
607    LOG_F(LS_ERROR) << "Unavailable cache body";
608    error = HE_CACHE;
609  } else {
610    error = OnHeaderAvailable(false, false, data_size);
611  }
612
613  if ((HE_NONE == error)
614      && (HV_HEAD != request().verb)
615      && response().document) {
616    char buffer[1024 * 64];
617    StreamResult result = Flow(stream.get(), buffer, ARRAY_SIZE(buffer),
618                               response().document.get());
619    if (SR_SUCCESS != result) {
620      error = HE_STREAM;
621    }
622  }
623
624  return error;
625}
626
627bool HttpClient::PrepareValidate() {
628  ASSERT(CS_READY == cache_state_);
629  // At this point, request() contains the pending request, and response()
630  // contains the cached response headers.  Reformat the request to validate
631  // the cached content.
632  HttpValidatorStrength vs_required = HttpRequestValidatorLevel(request());
633  HttpValidatorStrength vs_available = HttpResponseValidatorLevel(response());
634  if (vs_available < vs_required) {
635    return false;
636  }
637  std::string value;
638  if (response().hasHeader(HH_ETAG, &value)) {
639    request().addHeader(HH_IF_NONE_MATCH, value);
640  }
641  if (response().hasHeader(HH_LAST_MODIFIED, &value)) {
642    request().addHeader(HH_IF_MODIFIED_SINCE, value);
643  }
644  response().clear(false);
645  cache_state_ = CS_VALIDATING;
646  return true;
647}
648
649HttpError HttpClient::CompleteValidate() {
650  ASSERT(CS_VALIDATING == cache_state_);
651
652  std::string id = GetCacheID(request());
653
654  // Merge cached headers with new headers
655  HttpError error = ReadCacheHeaders(id, false);
656  if (HE_NONE != error) {
657    // Rewrite merged headers to cache
658    CacheLock lock(cache_, id);
659    error = WriteCacheHeaders(id);
660  }
661  if (HE_NONE != error) {
662    error = ReadCacheBody(id);
663  }
664  return error;
665}
666
667HttpError HttpClient::OnHeaderAvailable(bool ignore_data, bool chunked,
668                                        size_t data_size) {
669  // If we are ignoring the data, this is an intermediate header.
670  // TODO: don't signal intermediate headers.  Instead, do all header-dependent
671  // processing now, and either set up the next request, or fail outright.
672  // TODO: by default, only write response documents with a success code.
673  SignalHeaderAvailable(this, !ignore_data, ignore_data ? 0 : data_size);
674  if (!ignore_data && !chunked && (data_size != SIZE_UNKNOWN)
675      && response().document) {
676    // Attempt to pre-allocate space for the downloaded data.
677    if (!response().document->ReserveSize(data_size)) {
678      return HE_OVERFLOW;
679    }
680  }
681  return HE_NONE;
682}
683
684//
685// HttpBase Implementation
686//
687
688HttpError HttpClient::onHttpHeaderComplete(bool chunked, size_t& data_size) {
689  if (CS_VALIDATING == cache_state_) {
690    if (HC_NOT_MODIFIED == response().scode) {
691      return CompleteValidate();
692    }
693    // Should we remove conditional headers from request?
694    cache_state_ = CS_READY;
695    cache_->DeleteResource(GetCacheID(request()));
696    // Continue processing response as normal
697  }
698
699  ASSERT(!IsCacheActive());
700  if ((request().verb == HV_HEAD) || !HttpCodeHasBody(response().scode)) {
701    // HEAD requests and certain response codes contain no body
702    data_size = 0;
703  }
704  if (ShouldRedirect(NULL)
705      || ((HC_PROXY_AUTHENTICATION_REQUIRED == response().scode)
706          && (PROXY_HTTPS == proxy_.type))) {
707    // We're going to issue another request, so ignore the incoming data.
708    base_.set_ignore_data(true);
709  }
710
711  HttpError error = OnHeaderAvailable(base_.ignore_data(), chunked, data_size);
712  if (HE_NONE != error) {
713    return error;
714  }
715
716  if ((NULL != cache_)
717      && !base_.ignore_data()
718      && HttpShouldCache(*transaction_)) {
719    if (BeginCacheFile()) {
720      cache_state_ = CS_WRITING;
721    }
722  }
723  return HE_NONE;
724}
725
726void HttpClient::onHttpComplete(HttpMode mode, HttpError err) {
727  if (((HE_DISCONNECTED == err) || (HE_CONNECT_FAILED == err)
728       || (HE_SOCKET_ERROR == err))
729      && (HC_INTERNAL_SERVER_ERROR == response().scode)
730      && (attempt_ < retries_)) {
731    // If the response code has not changed from the default, then we haven't
732    // received anything meaningful from the server, so we are eligible for a
733    // retry.
734    ++attempt_;
735    if (request().document && !request().document->Rewind()) {
736      // Unable to replay the request document.
737      err = HE_STREAM;
738    } else {
739      release();
740      connect();
741      return;
742    }
743  } else if (err != HE_NONE) {
744    // fall through
745  } else if (mode == HM_CONNECT) {
746    base_.send(&transaction_->request);
747    return;
748  } else if ((mode == HM_SEND) || HttpCodeIsInformational(response().scode)) {
749    // If you're interested in informational headers, catch
750    // SignalHeaderAvailable.
751    base_.recv(&transaction_->response);
752    return;
753  } else {
754    if (!HttpShouldKeepAlive(response())) {
755      LOG(LS_VERBOSE) << "HttpClient: closing socket";
756      base_.stream()->Close();
757    }
758    std::string location;
759    if (ShouldRedirect(&location)) {
760      Url<char> purl(location);
761      set_server(SocketAddress(purl.host(), purl.port()));
762      request().path = purl.full_path();
763      if (response().scode == HC_SEE_OTHER) {
764        request().verb = HV_GET;
765        request().clearHeader(HH_CONTENT_TYPE);
766        request().clearHeader(HH_CONTENT_LENGTH);
767        request().document.reset();
768      } else if (request().document && !request().document->Rewind()) {
769        // Unable to replay the request document.
770        ASSERT(REDIRECT_ALWAYS == redirect_action_);
771        err = HE_STREAM;
772      }
773      if (err == HE_NONE) {
774        ++redirects_;
775        context_.reset();
776        response().clear(false);
777        release();
778        start();
779        return;
780      }
781    } else if ((HC_PROXY_AUTHENTICATION_REQUIRED == response().scode)
782               && (PROXY_HTTPS == proxy_.type)) {
783      std::string authorization, auth_method;
784      HttpData::const_iterator begin = response().begin(HH_PROXY_AUTHENTICATE);
785      HttpData::const_iterator end = response().end(HH_PROXY_AUTHENTICATE);
786      for (HttpData::const_iterator it = begin; it != end; ++it) {
787        HttpAuthContext *context = context_.get();
788        HttpAuthResult res = HttpAuthenticate(
789          it->second.data(), it->second.size(),
790          proxy_.address,
791          ToString(request().verb), request().path,
792          proxy_.username, proxy_.password,
793          context, authorization, auth_method);
794        context_.reset(context);
795        if (res == HAR_RESPONSE) {
796          request().setHeader(HH_PROXY_AUTHORIZATION, authorization);
797          if (request().document && !request().document->Rewind()) {
798            err = HE_STREAM;
799          } else {
800            // Explicitly do not reset the HttpAuthContext
801            response().clear(false);
802            // TODO: Reuse socket when authenticating?
803            release();
804            start();
805            return;
806          }
807        } else if (res == HAR_IGNORE) {
808          LOG(INFO) << "Ignoring Proxy-Authenticate: " << auth_method;
809          continue;
810        } else {
811          break;
812        }
813      }
814    }
815  }
816  if (CS_WRITING == cache_state_) {
817    CompleteCacheFile();
818    cache_state_ = CS_READY;
819  } else if (CS_READING == cache_state_) {
820    cache_state_ = CS_READY;
821  }
822  release();
823  SignalHttpClientComplete(this, err);
824}
825
826void HttpClient::onHttpClosed(HttpError err) {
827  // This shouldn't occur, since we return the stream to the pool upon command
828  // completion.
829  ASSERT(false);
830}
831
832//////////////////////////////////////////////////////////////////////
833// HttpClientDefault
834//////////////////////////////////////////////////////////////////////
835
836HttpClientDefault::HttpClientDefault(SocketFactory* factory,
837                                     const std::string& agent,
838                                     HttpTransaction* transaction)
839    : ReuseSocketPool(factory ? factory : Thread::Current()->socketserver()),
840      HttpClient(agent, NULL, transaction) {
841  set_pool(this);
842}
843
844//////////////////////////////////////////////////////////////////////
845
846}  // namespace talk_base
847