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

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

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

Powered by Google App Engine
This is Rietveld 408576698