You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

847 lines
26 KiB

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