Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(114)

Side by Side Diff: webrtc/base/httpclient.cc

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

Powered by Google App Engine
This is Rietveld 408576698