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.

896 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. // Copyright 2005 Google Inc. All Rights Reserved.
  28. //
  29. #ifdef WIN32
  30. #include "talk/base/win32.h"
  31. #else // !WIN32
  32. #define SEC_E_CERT_EXPIRED (-2146893016)
  33. #endif // !WIN32
  34. #include "talk/base/common.h"
  35. #include "talk/base/httpbase.h"
  36. #include "talk/base/logging.h"
  37. #include "talk/base/socket.h"
  38. #include "talk/base/stringutils.h"
  39. #include "talk/base/thread.h"
  40. namespace talk_base {
  41. //////////////////////////////////////////////////////////////////////
  42. // Helpers
  43. //////////////////////////////////////////////////////////////////////
  44. bool MatchHeader(const char* str, size_t len, HttpHeader header) {
  45. const char* const header_str = ToString(header);
  46. const size_t header_len = strlen(header_str);
  47. return (len == header_len) && (_strnicmp(str, header_str, header_len) == 0);
  48. }
  49. enum {
  50. MSG_READ
  51. };
  52. //////////////////////////////////////////////////////////////////////
  53. // HttpParser
  54. //////////////////////////////////////////////////////////////////////
  55. HttpParser::HttpParser() {
  56. reset();
  57. }
  58. HttpParser::~HttpParser() {
  59. }
  60. void
  61. HttpParser::reset() {
  62. state_ = ST_LEADER;
  63. chunked_ = false;
  64. data_size_ = SIZE_UNKNOWN;
  65. }
  66. HttpParser::ProcessResult
  67. HttpParser::Process(const char* buffer, size_t len, size_t* processed,
  68. HttpError* error) {
  69. *processed = 0;
  70. *error = HE_NONE;
  71. if (state_ >= ST_COMPLETE) {
  72. ASSERT(false);
  73. return PR_COMPLETE;
  74. }
  75. while (true) {
  76. if (state_ < ST_DATA) {
  77. size_t pos = *processed;
  78. while ((pos < len) && (buffer[pos] != '\n')) {
  79. pos += 1;
  80. }
  81. if (pos >= len) {
  82. break; // don't have a full header
  83. }
  84. const char* line = buffer + *processed;
  85. size_t len = (pos - *processed);
  86. *processed = pos + 1;
  87. while ((len > 0) && isspace(static_cast<unsigned char>(line[len-1]))) {
  88. len -= 1;
  89. }
  90. ProcessResult result = ProcessLine(line, len, error);
  91. LOG(LS_VERBOSE) << "Processed line, result=" << result;
  92. if (PR_CONTINUE != result) {
  93. return result;
  94. }
  95. } else if (data_size_ == 0) {
  96. if (chunked_) {
  97. state_ = ST_CHUNKTERM;
  98. } else {
  99. return PR_COMPLETE;
  100. }
  101. } else {
  102. size_t available = len - *processed;
  103. if (available <= 0) {
  104. break; // no more data
  105. }
  106. if ((data_size_ != SIZE_UNKNOWN) && (available > data_size_)) {
  107. available = data_size_;
  108. }
  109. size_t read = 0;
  110. ProcessResult result = ProcessData(buffer + *processed, available, read,
  111. error);
  112. LOG(LS_VERBOSE) << "Processed data, result: " << result << " read: "
  113. << read << " err: " << error;
  114. if (PR_CONTINUE != result) {
  115. return result;
  116. }
  117. *processed += read;
  118. if (data_size_ != SIZE_UNKNOWN) {
  119. data_size_ -= read;
  120. }
  121. }
  122. }
  123. return PR_CONTINUE;
  124. }
  125. HttpParser::ProcessResult
  126. HttpParser::ProcessLine(const char* line, size_t len, HttpError* error) {
  127. LOG_F(LS_VERBOSE) << " state: " << state_ << " line: "
  128. << std::string(line, len) << " len: " << len << " err: "
  129. << error;
  130. switch (state_) {
  131. case ST_LEADER:
  132. state_ = ST_HEADERS;
  133. return ProcessLeader(line, len, error);
  134. case ST_HEADERS:
  135. if (len > 0) {
  136. const char* value = strchrn(line, len, ':');
  137. if (!value) {
  138. *error = HE_PROTOCOL;
  139. return PR_COMPLETE;
  140. }
  141. size_t nlen = (value - line);
  142. const char* eol = line + len;
  143. do {
  144. value += 1;
  145. } while ((value < eol) && isspace(static_cast<unsigned char>(*value)));
  146. size_t vlen = eol - value;
  147. if (MatchHeader(line, nlen, HH_CONTENT_LENGTH)) {
  148. unsigned int temp_size;
  149. if (sscanf(value, "%u", &temp_size) != 1) {
  150. *error = HE_PROTOCOL;
  151. return PR_COMPLETE;
  152. }
  153. data_size_ = static_cast<size_t>(temp_size);
  154. } else if (MatchHeader(line, nlen, HH_TRANSFER_ENCODING)) {
  155. if ((vlen == 7) && (_strnicmp(value, "chunked", 7) == 0)) {
  156. chunked_ = true;
  157. } else if ((vlen == 8) && (_strnicmp(value, "identity", 8) == 0)) {
  158. chunked_ = false;
  159. } else {
  160. *error = HE_PROTOCOL;
  161. return PR_COMPLETE;
  162. }
  163. }
  164. return ProcessHeader(line, nlen, value, vlen, error);
  165. } else {
  166. state_ = chunked_ ? ST_CHUNKSIZE : ST_DATA;
  167. return ProcessHeaderComplete(chunked_, data_size_, error);
  168. }
  169. break;
  170. case ST_CHUNKSIZE:
  171. if (len > 0) {
  172. char* ptr = NULL;
  173. data_size_ = strtoul(line, &ptr, 16);
  174. if (ptr != line + len) {
  175. *error = HE_PROTOCOL;
  176. return PR_COMPLETE;
  177. }
  178. state_ = (data_size_ == 0) ? ST_TRAILERS : ST_DATA;
  179. } else {
  180. *error = HE_PROTOCOL;
  181. return PR_COMPLETE;
  182. }
  183. break;
  184. case ST_CHUNKTERM:
  185. if (len > 0) {
  186. *error = HE_PROTOCOL;
  187. return PR_COMPLETE;
  188. } else {
  189. state_ = chunked_ ? ST_CHUNKSIZE : ST_DATA;
  190. }
  191. break;
  192. case ST_TRAILERS:
  193. if (len == 0) {
  194. return PR_COMPLETE;
  195. }
  196. // *error = onHttpRecvTrailer();
  197. break;
  198. default:
  199. ASSERT(false);
  200. break;
  201. }
  202. return PR_CONTINUE;
  203. }
  204. bool
  205. HttpParser::is_valid_end_of_input() const {
  206. return (state_ == ST_DATA) && (data_size_ == SIZE_UNKNOWN);
  207. }
  208. void
  209. HttpParser::complete(HttpError error) {
  210. if (state_ < ST_COMPLETE) {
  211. state_ = ST_COMPLETE;
  212. OnComplete(error);
  213. }
  214. }
  215. //////////////////////////////////////////////////////////////////////
  216. // HttpBase::DocumentStream
  217. //////////////////////////////////////////////////////////////////////
  218. class BlockingMemoryStream : public ExternalMemoryStream {
  219. public:
  220. BlockingMemoryStream(char* buffer, size_t size)
  221. : ExternalMemoryStream(buffer, size) { }
  222. virtual StreamResult DoReserve(size_t size, int* error) {
  223. return (buffer_length_ >= size) ? SR_SUCCESS : SR_BLOCK;
  224. }
  225. };
  226. class HttpBase::DocumentStream : public StreamInterface {
  227. public:
  228. DocumentStream(HttpBase* base) : base_(base), error_(HE_DEFAULT) { }
  229. virtual StreamState GetState() const {
  230. if (NULL == base_)
  231. return SS_CLOSED;
  232. if (HM_RECV == base_->mode_)
  233. return SS_OPEN;
  234. return SS_OPENING;
  235. }
  236. virtual StreamResult Read(void* buffer, size_t buffer_len,
  237. size_t* read, int* error) {
  238. if (!base_) {
  239. if (error) *error = error_;
  240. return (HE_NONE == error_) ? SR_EOS : SR_ERROR;
  241. }
  242. if (HM_RECV != base_->mode_) {
  243. return SR_BLOCK;
  244. }
  245. // DoReceiveLoop writes http document data to the StreamInterface* document
  246. // member of HttpData. In this case, we want this data to be written
  247. // directly to our buffer. To accomplish this, we wrap our buffer with a
  248. // StreamInterface, and replace the existing document with our wrapper.
  249. // When the method returns, we restore the old document. Ideally, we would
  250. // pass our StreamInterface* to DoReceiveLoop, but due to the callbacks
  251. // of HttpParser, we would still need to store the pointer temporarily.
  252. scoped_ptr<StreamInterface>
  253. stream(new BlockingMemoryStream(reinterpret_cast<char*>(buffer),
  254. buffer_len));
  255. // Replace the existing document with our wrapped buffer.
  256. base_->data_->document.swap(stream);
  257. // Pump the I/O loop. DoReceiveLoop is guaranteed not to attempt to
  258. // complete the I/O process, which means that our wrapper is not in danger
  259. // of being deleted. To ensure this, DoReceiveLoop returns true when it
  260. // wants complete to be called. We make sure to uninstall our wrapper
  261. // before calling complete().
  262. HttpError http_error;
  263. bool complete = base_->DoReceiveLoop(&http_error);
  264. // Reinstall the original output document.
  265. base_->data_->document.swap(stream);
  266. // If we reach the end of the receive stream, we disconnect our stream
  267. // adapter from the HttpBase, and further calls to read will either return
  268. // EOS or ERROR, appropriately. Finally, we call complete().
  269. StreamResult result = SR_BLOCK;
  270. if (complete) {
  271. HttpBase* base = Disconnect(http_error);
  272. if (error) *error = error_;
  273. result = (HE_NONE == error_) ? SR_EOS : SR_ERROR;
  274. base->complete(http_error);
  275. }
  276. // Even if we are complete, if some data was read we must return SUCCESS.
  277. // Future Reads will return EOS or ERROR based on the error_ variable.
  278. size_t position;
  279. stream->GetPosition(&position);
  280. if (position > 0) {
  281. if (read) *read = position;
  282. result = SR_SUCCESS;
  283. }
  284. return result;
  285. }
  286. virtual StreamResult Write(const void* data, size_t data_len,
  287. size_t* written, int* error) {
  288. if (error) *error = -1;
  289. return SR_ERROR;
  290. }
  291. virtual void Close() {
  292. if (base_) {
  293. HttpBase* base = Disconnect(HE_NONE);
  294. if (HM_RECV == base->mode_ && base->http_stream_) {
  295. // Read I/O could have been stalled on the user of this DocumentStream,
  296. // so restart the I/O process now that we've removed ourselves.
  297. base->http_stream_->PostEvent(SE_READ, 0);
  298. }
  299. }
  300. }
  301. virtual bool GetAvailable(size_t* size) const {
  302. if (!base_ || HM_RECV != base_->mode_)
  303. return false;
  304. size_t data_size = base_->GetDataRemaining();
  305. if (SIZE_UNKNOWN == data_size)
  306. return false;
  307. if (size)
  308. *size = data_size;
  309. return true;
  310. }
  311. HttpBase* Disconnect(HttpError error) {
  312. ASSERT(NULL != base_);
  313. ASSERT(NULL != base_->doc_stream_);
  314. HttpBase* base = base_;
  315. base_->doc_stream_ = NULL;
  316. base_ = NULL;
  317. error_ = error;
  318. return base;
  319. }
  320. private:
  321. HttpBase* base_;
  322. HttpError error_;
  323. };
  324. //////////////////////////////////////////////////////////////////////
  325. // HttpBase
  326. //////////////////////////////////////////////////////////////////////
  327. HttpBase::HttpBase() : mode_(HM_NONE), data_(NULL), notify_(NULL),
  328. http_stream_(NULL), doc_stream_(NULL) {
  329. }
  330. HttpBase::~HttpBase() {
  331. ASSERT(HM_NONE == mode_);
  332. }
  333. bool
  334. HttpBase::isConnected() const {
  335. return (http_stream_ != NULL) && (http_stream_->GetState() == SS_OPEN);
  336. }
  337. bool
  338. HttpBase::attach(StreamInterface* stream) {
  339. if ((mode_ != HM_NONE) || (http_stream_ != NULL) || (stream == NULL)) {
  340. ASSERT(false);
  341. return false;
  342. }
  343. http_stream_ = stream;
  344. http_stream_->SignalEvent.connect(this, &HttpBase::OnHttpStreamEvent);
  345. mode_ = (http_stream_->GetState() == SS_OPENING) ? HM_CONNECT : HM_NONE;
  346. return true;
  347. }
  348. StreamInterface*
  349. HttpBase::detach() {
  350. ASSERT(HM_NONE == mode_);
  351. if (mode_ != HM_NONE) {
  352. return NULL;
  353. }
  354. StreamInterface* stream = http_stream_;
  355. http_stream_ = NULL;
  356. if (stream) {
  357. stream->SignalEvent.disconnect(this);
  358. }
  359. return stream;
  360. }
  361. void
  362. HttpBase::send(HttpData* data) {
  363. ASSERT(HM_NONE == mode_);
  364. if (mode_ != HM_NONE) {
  365. return;
  366. } else if (!isConnected()) {
  367. OnHttpStreamEvent(http_stream_, SE_CLOSE, HE_DISCONNECTED);
  368. return;
  369. }
  370. mode_ = HM_SEND;
  371. data_ = data;
  372. len_ = 0;
  373. ignore_data_ = chunk_data_ = false;
  374. if (data_->document) {
  375. data_->document->SignalEvent.connect(this, &HttpBase::OnDocumentEvent);
  376. }
  377. std::string encoding;
  378. if (data_->hasHeader(HH_TRANSFER_ENCODING, &encoding)
  379. && (encoding == "chunked")) {
  380. chunk_data_ = true;
  381. }
  382. len_ = data_->formatLeader(buffer_, sizeof(buffer_));
  383. len_ += strcpyn(buffer_ + len_, sizeof(buffer_) - len_, "\r\n");
  384. header_ = data_->begin();
  385. if (header_ == data_->end()) {
  386. // We must call this at least once, in the case where there are no headers.
  387. queue_headers();
  388. }
  389. flush_data();
  390. }
  391. void
  392. HttpBase::recv(HttpData* data) {
  393. ASSERT(HM_NONE == mode_);
  394. if (mode_ != HM_NONE) {
  395. return;
  396. } else if (!isConnected()) {
  397. OnHttpStreamEvent(http_stream_, SE_CLOSE, HE_DISCONNECTED);
  398. return;
  399. }
  400. mode_ = HM_RECV;
  401. data_ = data;
  402. len_ = 0;
  403. ignore_data_ = chunk_data_ = false;
  404. reset();
  405. if (doc_stream_) {
  406. doc_stream_->SignalEvent(doc_stream_, SE_OPEN | SE_READ, 0);
  407. } else {
  408. read_and_process_data();
  409. }
  410. }
  411. void
  412. HttpBase::abort(HttpError err) {
  413. if (mode_ != HM_NONE) {
  414. if (http_stream_ != NULL) {
  415. http_stream_->Close();
  416. }
  417. do_complete(err);
  418. }
  419. }
  420. StreamInterface* HttpBase::GetDocumentStream() {
  421. if (doc_stream_)
  422. return NULL;
  423. doc_stream_ = new DocumentStream(this);
  424. return doc_stream_;
  425. }
  426. HttpError HttpBase::HandleStreamClose(int error) {
  427. if (http_stream_ != NULL) {
  428. http_stream_->Close();
  429. }
  430. if (error == 0) {
  431. if ((mode_ == HM_RECV) && is_valid_end_of_input()) {
  432. return HE_NONE;
  433. } else {
  434. return HE_DISCONNECTED;
  435. }
  436. } else if (error == SOCKET_EACCES) {
  437. return HE_AUTH;
  438. } else if (error == SEC_E_CERT_EXPIRED) {
  439. return HE_CERTIFICATE_EXPIRED;
  440. }
  441. LOG_F(LS_ERROR) << "(" << error << ")";
  442. return (HM_CONNECT == mode_) ? HE_CONNECT_FAILED : HE_SOCKET_ERROR;
  443. }
  444. bool HttpBase::DoReceiveLoop(HttpError* error) {
  445. ASSERT(HM_RECV == mode_);
  446. ASSERT(NULL != error);
  447. // Do to the latency between receiving read notifications from
  448. // pseudotcpchannel, we rely on repeated calls to read in order to acheive
  449. // ideal throughput. The number of reads is limited to prevent starving
  450. // the caller.
  451. size_t loop_count = 0;
  452. const size_t kMaxReadCount = 20;
  453. bool process_requires_more_data = false;
  454. do {
  455. // The most frequent use of this function is response to new data available
  456. // on http_stream_. Therefore, we optimize by attempting to read from the
  457. // network first (as opposed to processing existing data first).
  458. if (len_ < sizeof(buffer_)) {
  459. // Attempt to buffer more data.
  460. size_t read;
  461. int read_error;
  462. StreamResult read_result = http_stream_->Read(buffer_ + len_,
  463. sizeof(buffer_) - len_,
  464. &read, &read_error);
  465. switch (read_result) {
  466. case SR_SUCCESS:
  467. ASSERT(len_ + read <= sizeof(buffer_));
  468. len_ += read;
  469. break;
  470. case SR_BLOCK:
  471. if (process_requires_more_data) {
  472. // We're can't make progress until more data is available.
  473. return false;
  474. }
  475. // Attempt to process the data already in our buffer.
  476. break;
  477. case SR_EOS:
  478. // Clean close, with no error. Fall through to HandleStreamClose.
  479. read_error = 0;
  480. case SR_ERROR:
  481. *error = HandleStreamClose(read_error);
  482. return true;
  483. }
  484. } else if (process_requires_more_data) {
  485. // We have too much unprocessed data in our buffer. This should only
  486. // occur when a single HTTP header is longer than the buffer size (32K).
  487. // Anything longer than that is almost certainly an error.
  488. *error = HE_OVERFLOW;
  489. return true;
  490. }
  491. // Process data in our buffer. Process is not guaranteed to process all
  492. // the buffered data. In particular, it will wait until a complete
  493. // protocol element (such as http header, or chunk size) is available,
  494. // before processing it in its entirety. Also, it is valid and sometimes
  495. // necessary to call Process with an empty buffer, since the state machine
  496. // may have interrupted state transitions to complete.
  497. size_t processed;
  498. ProcessResult process_result = Process(buffer_, len_, &processed,
  499. error);
  500. ASSERT(processed <= len_);
  501. len_ -= processed;
  502. memmove(buffer_, buffer_ + processed, len_);
  503. switch (process_result) {
  504. case PR_CONTINUE:
  505. // We need more data to make progress.
  506. process_requires_more_data = true;
  507. break;
  508. case PR_BLOCK:
  509. // We're stalled on writing the processed data.
  510. return false;
  511. case PR_COMPLETE:
  512. // *error already contains the correct code.
  513. return true;
  514. }
  515. } while (++loop_count <= kMaxReadCount);
  516. LOG_F(LS_WARNING) << "danger of starvation";
  517. return false;
  518. }
  519. void
  520. HttpBase::read_and_process_data() {
  521. HttpError error;
  522. if (DoReceiveLoop(&error)) {
  523. complete(error);
  524. }
  525. }
  526. void
  527. HttpBase::flush_data() {
  528. ASSERT(HM_SEND == mode_);
  529. // When send_required is true, no more buffering can occur without a network
  530. // write.
  531. bool send_required = (len_ >= sizeof(buffer_));
  532. while (true) {
  533. ASSERT(len_ <= sizeof(buffer_));
  534. // HTTP is inherently sensitive to round trip latency, since a frequent use
  535. // case is for small requests and responses to be sent back and forth, and
  536. // the lack of pipelining forces a single request to take a minimum of the
  537. // round trip time. As a result, it is to our benefit to pack as much data
  538. // into each packet as possible. Thus, we defer network writes until we've
  539. // buffered as much data as possible.
  540. if (!send_required && (header_ != data_->end())) {
  541. // First, attempt to queue more header data.
  542. send_required = queue_headers();
  543. }
  544. if (!send_required && data_->document) {
  545. // Next, attempt to queue document data.
  546. const size_t kChunkDigits = 8;
  547. size_t offset, reserve;
  548. if (chunk_data_) {
  549. // Reserve characters at the start for X-byte hex value and \r\n
  550. offset = len_ + kChunkDigits + 2;
  551. // ... and 2 characters at the end for \r\n
  552. reserve = offset + 2;
  553. } else {
  554. offset = len_;
  555. reserve = offset;
  556. }
  557. if (reserve >= sizeof(buffer_)) {
  558. send_required = true;
  559. } else {
  560. size_t read;
  561. int error;
  562. StreamResult result = data_->document->Read(buffer_ + offset,
  563. sizeof(buffer_) - reserve,
  564. &read, &error);
  565. if (result == SR_SUCCESS) {
  566. ASSERT(reserve + read <= sizeof(buffer_));
  567. if (chunk_data_) {
  568. // Prepend the chunk length in hex.
  569. // Note: sprintfn appends a null terminator, which is why we can't
  570. // combine it with the line terminator.
  571. sprintfn(buffer_ + len_, kChunkDigits + 1, "%.*x",
  572. kChunkDigits, read);
  573. // Add line terminator to the chunk length.
  574. memcpy(buffer_ + len_ + kChunkDigits, "\r\n", 2);
  575. // Add line terminator to the end of the chunk.
  576. memcpy(buffer_ + offset + read, "\r\n", 2);
  577. }
  578. len_ = reserve + read;
  579. } else if (result == SR_BLOCK) {
  580. // Nothing to do but flush data to the network.
  581. send_required = true;
  582. } else if (result == SR_EOS) {
  583. if (chunk_data_) {
  584. // Append the empty chunk and empty trailers, then turn off
  585. // chunking.
  586. ASSERT(len_ + 5 <= sizeof(buffer_));
  587. memcpy(buffer_ + len_, "0\r\n\r\n", 5);
  588. len_ += 5;
  589. chunk_data_ = false;
  590. } else if (0 == len_) {
  591. // No more data to read, and no more data to write.
  592. do_complete();
  593. return;
  594. }
  595. // Although we are done reading data, there is still data which needs
  596. // to be flushed to the network.
  597. send_required = true;
  598. } else {
  599. LOG_F(LS_ERROR) << "Read error: " << error;
  600. do_complete(HE_STREAM);
  601. return;
  602. }
  603. }
  604. }
  605. if (0 == len_) {
  606. // No data currently available to send.
  607. if (!data_->document) {
  608. // If there is no source document, that means we're done.
  609. do_complete();
  610. }
  611. return;
  612. }
  613. size_t written;
  614. int error;
  615. StreamResult result = http_stream_->Write(buffer_, len_, &written, &error);
  616. if (result == SR_SUCCESS) {
  617. ASSERT(written <= len_);
  618. len_ -= written;
  619. memmove(buffer_, buffer_ + written, len_);
  620. send_required = false;
  621. } else if (result == SR_BLOCK) {
  622. if (send_required) {
  623. // Nothing more we can do until network is writeable.
  624. return;
  625. }
  626. } else {
  627. ASSERT(result == SR_ERROR);
  628. LOG_F(LS_ERROR) << "error";
  629. OnHttpStreamEvent(http_stream_, SE_CLOSE, error);
  630. return;
  631. }
  632. }
  633. ASSERT(false);
  634. }
  635. bool
  636. HttpBase::queue_headers() {
  637. ASSERT(HM_SEND == mode_);
  638. while (header_ != data_->end()) {
  639. size_t len = sprintfn(buffer_ + len_, sizeof(buffer_) - len_,
  640. "%.*s: %.*s\r\n",
  641. header_->first.size(), header_->first.data(),
  642. header_->second.size(), header_->second.data());
  643. if (len_ + len < sizeof(buffer_) - 3) {
  644. len_ += len;
  645. ++header_;
  646. } else if (len_ == 0) {
  647. LOG(WARNING) << "discarding header that is too long: " << header_->first;
  648. ++header_;
  649. } else {
  650. // Not enough room for the next header, write to network first.
  651. return true;
  652. }
  653. }
  654. // End of headers
  655. len_ += strcpyn(buffer_ + len_, sizeof(buffer_) - len_, "\r\n");
  656. return false;
  657. }
  658. void
  659. HttpBase::do_complete(HttpError err) {
  660. ASSERT(mode_ != HM_NONE);
  661. HttpMode mode = mode_;
  662. mode_ = HM_NONE;
  663. if (data_ && data_->document) {
  664. data_->document->SignalEvent.disconnect(this);
  665. }
  666. data_ = NULL;
  667. if ((HM_RECV == mode) && doc_stream_) {
  668. ASSERT(HE_NONE != err); // We should have Disconnected doc_stream_ already.
  669. DocumentStream* ds = doc_stream_;
  670. ds->Disconnect(err);
  671. ds->SignalEvent(ds, SE_CLOSE, err);
  672. }
  673. if (notify_) {
  674. notify_->onHttpComplete(mode, err);
  675. }
  676. }
  677. //
  678. // Stream Signals
  679. //
  680. void
  681. HttpBase::OnHttpStreamEvent(StreamInterface* stream, int events, int error) {
  682. ASSERT(stream == http_stream_);
  683. if ((events & SE_OPEN) && (mode_ == HM_CONNECT)) {
  684. do_complete();
  685. return;
  686. }
  687. if ((events & SE_WRITE) && (mode_ == HM_SEND)) {
  688. flush_data();
  689. return;
  690. }
  691. if ((events & SE_READ) && (mode_ == HM_RECV)) {
  692. if (doc_stream_) {
  693. doc_stream_->SignalEvent(doc_stream_, SE_READ, 0);
  694. } else {
  695. read_and_process_data();
  696. }
  697. return;
  698. }
  699. if ((events & SE_CLOSE) == 0)
  700. return;
  701. HttpError http_error = HandleStreamClose(error);
  702. if (mode_ == HM_RECV) {
  703. complete(http_error);
  704. } else if (mode_ != HM_NONE) {
  705. do_complete(http_error);
  706. } else if (notify_) {
  707. notify_->onHttpClosed(http_error);
  708. }
  709. }
  710. void
  711. HttpBase::OnDocumentEvent(StreamInterface* stream, int events, int error) {
  712. ASSERT(stream == data_->document.get());
  713. if ((events & SE_WRITE) && (mode_ == HM_RECV)) {
  714. read_and_process_data();
  715. return;
  716. }
  717. if ((events & SE_READ) && (mode_ == HM_SEND)) {
  718. flush_data();
  719. return;
  720. }
  721. if (events & SE_CLOSE) {
  722. LOG_F(LS_ERROR) << "Read error: " << error;
  723. do_complete(HE_STREAM);
  724. return;
  725. }
  726. }
  727. //
  728. // HttpParser Implementation
  729. //
  730. HttpParser::ProcessResult
  731. HttpBase::ProcessLeader(const char* line, size_t len, HttpError* error) {
  732. *error = data_->parseLeader(line, len);
  733. return (HE_NONE == *error) ? PR_CONTINUE : PR_COMPLETE;
  734. }
  735. HttpParser::ProcessResult
  736. HttpBase::ProcessHeader(const char* name, size_t nlen, const char* value,
  737. size_t vlen, HttpError* error) {
  738. std::string sname(name, nlen), svalue(value, vlen);
  739. data_->addHeader(sname, svalue);
  740. return PR_CONTINUE;
  741. }
  742. HttpParser::ProcessResult
  743. HttpBase::ProcessHeaderComplete(bool chunked, size_t& data_size,
  744. HttpError* error) {
  745. StreamInterface* old_docstream = doc_stream_;
  746. if (notify_) {
  747. *error = notify_->onHttpHeaderComplete(chunked, data_size);
  748. // The request must not be aborted as a result of this callback.
  749. ASSERT(NULL != data_);
  750. }
  751. if ((HE_NONE == *error) && data_->document) {
  752. data_->document->SignalEvent.connect(this, &HttpBase::OnDocumentEvent);
  753. }
  754. if (HE_NONE != *error) {
  755. return PR_COMPLETE;
  756. }
  757. if (old_docstream != doc_stream_) {
  758. // Break out of Process loop, since our I/O model just changed.
  759. return PR_BLOCK;
  760. }
  761. return PR_CONTINUE;
  762. }
  763. HttpParser::ProcessResult
  764. HttpBase::ProcessData(const char* data, size_t len, size_t& read,
  765. HttpError* error) {
  766. #ifndef ANDROID
  767. LOG_F(LS_VERBOSE) << "data: " << std::string(data, len);
  768. #endif // ANDROID
  769. if (ignore_data_ || !data_->document) {
  770. read = len;
  771. return PR_CONTINUE;
  772. }
  773. int write_error = 0;
  774. switch (data_->document->Write(data, len, &read, &write_error)) {
  775. case SR_SUCCESS:
  776. return PR_CONTINUE;
  777. case SR_BLOCK:
  778. return PR_BLOCK;
  779. case SR_EOS:
  780. LOG_F(LS_ERROR) << "Unexpected EOS";
  781. *error = HE_STREAM;
  782. return PR_COMPLETE;
  783. case SR_ERROR:
  784. default:
  785. LOG_F(LS_ERROR) << "Write error: " << write_error;
  786. *error = HE_STREAM;
  787. return PR_COMPLETE;
  788. }
  789. }
  790. void
  791. HttpBase::OnComplete(HttpError err) {
  792. LOG_F(LS_VERBOSE);
  793. do_complete(err);
  794. }
  795. } // namespace talk_base