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