Debian Codegraph @

monero/contrib/epee/include/net/http_client.h

raw symbols SCIP
1 // Copyright (c) 2006-2013, Andrey N. Sabelnikov, www.sabelnikov.net
2 // All rights reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are met:
6 // * Redistributions of source code must retain the above copyright
7 // notice, this list of conditions and the following disclaimer.
8 // * Redistributions in binary form must reproduce the above copyright
9 // notice, this list of conditions and the following disclaimer in the
10 // documentation and/or other materials provided with the distribution.
11 // * Neither the name of the Andrey N. Sabelnikov nor the
12 // names of its contributors may be used to endorse or promote products
13 // derived from this software without specific prior written permission.
14 //
15 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
16 // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
17 // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
18 // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER BE LIABLE FOR ANY
19 // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
20 // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
21 // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
22 // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
24 // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25 //
26
27
28
29 #pragma once
30 #include <ctype.h>
31 #include <boost/shared_ptr.hpp>
32 #include <boost/regex.hpp>
33 #include <boost/optional/optional.hpp>
34 #include <boost/utility/string_ref.hpp>
35 //#include <mbstring.h>
36 #include <algorithm>
37 #include <cctype>
38 #include <functional>
39
40 #include "net_helper.h"
41 #include "http_client_base.h"
42 #include "string_tools.h"
43 #include "string_tools_lexical.h"
44 #include "reg_exp_definer.h"
45 #include "abstract_http_client.h"
46 #include "http_base.h"
47 #include "http_auth.h"
48 #include "net_parse_helpers.h"
49 #include "syncobj.h"
50
51 //#include "shlwapi.h"
52
53 //#pragma comment(lib, "shlwapi.lib")
54
55 #undef MONERO_DEFAULT_LOG_CATEGORY
56 #define MONERO_DEFAULT_LOG_CATEGORY "net.http"
57
58 extern epee::critical_section gregexp_lock;
59
60
61 namespace epee
62 {
63 namespace net_utils
64 {
65
66 /*struct url
67 {
68 public:
69 void parse(const std::string& url_s)
70 {
71 const string prot_end("://");
72 string::const_iterator prot_i = search(url_s.begin(), url_s.end(),
73 prot_end.begin(), prot_end.end());
74 protocol_.reserve(distance(url_s.begin(), prot_i));
75 transform(url_s.begin(), prot_i,
76 back_inserter(protocol_),
77 ptr_fun<int,int>(tolower)); // protocol is icase
78 if( prot_i == url_s.end() )
79 return;
80 advance(prot_i, prot_end.length());
81 string::const_iterator path_i = find(prot_i, url_s.end(), '/');
82 host_.reserve(distance(prot_i, path_i));
83 transform(prot_i, path_i,
84 back_inserter(host_),
85 ptr_fun<int,int>(tolower)); // host is icase
86 string::const_iterator query_i = find(path_i, url_s.end(), '?');
87 path_.assign(path_i, query_i);
88 if( query_i != url_s.end() )
89 ++query_i;
90 query_.assign(query_i, url_s.end());
91 }
92
93 std::string protocol_;
94 std::string host_;
95 std::string path_;
96 std::string query_;
97 };*/
98
99
100
101
102 //---------------------------------------------------------------------------
103 namespace http
104 {
105
106 template<typename net_client_type>
107 class http_simple_client_template : public i_target_handler, public abstract_http_client
108 {
109 private:
110 enum reciev_machine_state
111 {
112 reciev_machine_state_header,
113 reciev_machine_state_body_content_len,
114 reciev_machine_state_body_connection_close,
115 reciev_machine_state_body_chunked,
116 reciev_machine_state_done,
117 reciev_machine_state_error
118 };
119
120
121
122 enum chunked_state{
123 http_chunked_state_chunk_head,
124 http_chunked_state_chunk_body,
125 http_chunked_state_done,
126 http_chunked_state_undefined
127 };
128
129
130 net_client_type m_net_client;
131 std::string m_host_buff;
132 std::string m_port;
133 http_client_auth m_auth;
134 std::string m_header_cache;
135 http_response_info m_response_info;
136 size_t m_len_in_summary;
137 size_t m_len_in_remain;
138 //std::string* m_ptarget_buffer;
139 boost::shared_ptr<i_sub_handler> m_pcontent_encoding_handler;
140 reciev_machine_state m_state;
141 chunked_state m_chunked_state;
142 std::string m_chunked_cache;
143 bool m_auto_connect;
144 critical_section m_lock;
145 bool m_reconnect = true;
146
147 public:
148 explicit http_simple_client_template()
149 : i_target_handler(), abstract_http_client()
150 , m_net_client()
151 , m_host_buff()
152 , m_port()
153 , m_auth()
154 , m_header_cache()
155 , m_response_info()
156 , m_len_in_summary(0)
157 , m_len_in_remain(0)
158 , m_pcontent_encoding_handler(nullptr)
159 , m_state()
160 , m_chunked_state()
161 , m_chunked_cache()
162 , m_auto_connect(true)
163 , m_lock()
164 {}
165
166 const std::string &get_host() const { return m_host_buff; };
167 const std::string &get_port() const { return m_port; };
168
169 using abstract_http_client::set_server;
170
171 void set_server(std::string host, std::string port, boost::optional<login> user, ssl_options_t ssl_options = ssl_support_t::e_ssl_support_autodetect) override
172 {
173 CRITICAL_REGION_LOCAL(m_lock);
174 disconnect();
175 m_host_buff = std::move(host);
176 m_port = std::move(port);
177 m_auth = user ? http_client_auth{std::move(*user)} : http_client_auth{};
178 m_net_client.set_ssl(std::move(ssl_options));
179 }
180
181 void set_auto_connect(bool auto_connect) override
182 {
183 m_auto_connect = auto_connect;
184 }
185
186 template<typename F>
187 void set_connector(F connector)
188 {
189 CRITICAL_REGION_LOCAL(m_lock);
190 m_net_client.set_connector(std::move(connector));
191 }
192
193 bool connect(std::chrono::milliseconds timeout) override
194 {
195 CRITICAL_REGION_LOCAL(m_lock);
196 return m_net_client.connect(m_host_buff, m_port, timeout);
197 }
198 //---------------------------------------------------------------------------
199 bool disconnect() override
200 {
201 CRITICAL_REGION_LOCAL(m_lock);
202 return m_net_client.disconnect();
203 }
204 //---------------------------------------------------------------------------
205 bool cancel_read() override
206 {
207 m_reconnect = false;
208 return m_net_client.cancel_read();
209 }
210 //---------------------------------------------------------------------------
211 bool is_connected(bool *ssl = NULL) override
212 {
213 CRITICAL_REGION_LOCAL(m_lock);
214 return m_net_client.is_connected(ssl);
215 }
216 //---------------------------------------------------------------------------
217 virtual bool handle_target_data(std::string& piece_of_transfer) override
218 {
219 CRITICAL_REGION_LOCAL(m_lock);
220 m_response_info.m_body += piece_of_transfer;
221 piece_of_transfer.clear();
222 return true;
223 }
224 //---------------------------------------------------------------------------
225 virtual bool on_header(const http_response_info &headers)
226 {
227 return true;
228 }
229 //---------------------------------------------------------------------------
230 inline bool invoke_get(const boost::string_ref uri, std::chrono::milliseconds timeout, const std::string& body = std::string(), const http_response_info** ppresponse_info = NULL, const fields_list& additional_params = fields_list()) override
231 {
232 CRITICAL_REGION_LOCAL(m_lock);
233 return invoke(uri, "GET", body, timeout, ppresponse_info, additional_params);
234 }
235
236 //---------------------------------------------------------------------------
237 inline bool invoke(const boost::string_ref uri, const boost::string_ref method, const boost::string_ref body, std::chrono::milliseconds timeout, const http_response_info** ppresponse_info = NULL, const fields_list& additional_params = fields_list()) override
238 {
239 CRITICAL_REGION_LOCAL(m_lock);
240 if(!is_connected())
241 {
242 if (!m_reconnect) {
243 MDEBUG("Read cancelled, not reconnecting");
244 return false;
245 }
246
247 if (!m_auto_connect)
248 {
249 MWARNING("Auto connect attempt to " << m_host_buff << ":" << m_port << " disabled");
250 return false;
251 }
252 MDEBUG("Reconnecting...");
253 if(!connect(timeout))
254 {
255 MDEBUG("Failed to connect to " << m_host_buff << ":" << m_port);
256 return false;
257 }
258 }
259
260 std::string req_buff{};
261 req_buff.reserve(2048);
262 req_buff.append(method.data(), method.size()).append(" ").append(uri.data(), uri.size()).append(" HTTP/1.1\r\n");
263 add_field(req_buff, "Host", m_host_buff);
264 add_field(req_buff, "Content-Length", std::to_string(body.size()));
265
266 //handle "additional_params"
267 for(const auto& field : additional_params)
268 add_field(req_buff, field);
269
270 for (unsigned sends = 0; sends < 2; ++sends)
271 {
272 const std::size_t initial_size = req_buff.size();
273 const auto auth = m_auth.get_auth_field(method, uri);
274 if (auth)
275 add_field(req_buff, *auth);
276
277 req_buff += "\r\n";
278 //--
279
280 bool res = m_net_client.send(req_buff, timeout);
281 CHECK_AND_ASSERT_MES(res, false, "HTTP_CLIENT: Failed to SEND");
282 if(body.size())
283 res = m_net_client.send(body, timeout);
284 CHECK_AND_ASSERT_MES(res, false, "HTTP_CLIENT: Failed to SEND");
285
286 m_response_info.clear();
287 m_state = reciev_machine_state_header;
288 if (!handle_reciev(timeout))
289 return false;
290 if (m_response_info.m_response_code != 401)
291 {
292 if(ppresponse_info)
293 *ppresponse_info = std::addressof(m_response_info);
294 return true;
295 }
296
297 switch (m_auth.handle_401(m_response_info))
298 {
299 case http_client_auth::kSuccess:
300 break;
301 case http_client_auth::kBadPassword:
302 sends = 2;
303 break;
304 default:
305 case http_client_auth::kParseFailure:
306 LOG_ERROR("Bad server response for authentication");
307 return false;
308 }
309 req_buff.resize(initial_size); // rollback for new auth generation
310 }
311 LOG_ERROR("Client has incorrect username/password for server requiring authentication");
312 return false;
313 }
314 //---------------------------------------------------------------------------
315 inline bool invoke_post(const boost::string_ref uri, const std::string& body, std::chrono::milliseconds timeout, const http_response_info** ppresponse_info = NULL, const fields_list& additional_params = fields_list()) override
316 {
317 CRITICAL_REGION_LOCAL(m_lock);
318 return invoke(uri, "POST", body, timeout, ppresponse_info, additional_params);
319 }
320 //---------------------------------------------------------------------------
321 bool test(const std::string &s, std::chrono::milliseconds timeout) // TEST FUNC ONLY
322 {
323 CRITICAL_REGION_LOCAL(m_lock);
324 m_net_client.set_test_data(s);
325 m_state = reciev_machine_state_header;
326 return handle_reciev(timeout);
327 }
328 //---------------------------------------------------------------------------
329 uint64_t get_bytes_sent() const override
330 {
331 return m_net_client.get_bytes_sent();
332 }
333 //---------------------------------------------------------------------------
334 uint64_t get_bytes_received() const override
335 {
336 return m_net_client.get_bytes_received();
337 }
338 //---------------------------------------------------------------------------
339 void wipe_response()
340 {
341 m_response_info.wipe();
342 }
343 //---------------------------------------------------------------------------
344 private:
345 //---------------------------------------------------------------------------
346 inline bool handle_reciev(std::chrono::milliseconds timeout)
347 {
348 CRITICAL_REGION_LOCAL(m_lock);
349 bool keep_handling = true;
350 bool need_more_data = true;
351 std::string recv_buffer;
352 while(keep_handling)
353 {
354 if(need_more_data)
355 {
356 if(!m_net_client.recv(recv_buffer, timeout))
357 {
358 MERROR("Unexpected recv fail");
359 m_state = reciev_machine_state_error;
360 }
361 if(!recv_buffer.size())
362 {
363 //connection is going to be closed
364 if(reciev_machine_state_body_connection_close != m_state)
365 {
366 m_state = reciev_machine_state_error;
367 }
368 }
369 need_more_data = false;
370 }
371 switch(m_state)
372 {
373 case reciev_machine_state_header:
374 keep_handling = handle_header(recv_buffer, need_more_data);
375 break;
376 case reciev_machine_state_body_content_len:
377 keep_handling = handle_body_content_len(recv_buffer, need_more_data);
378 break;
379 case reciev_machine_state_body_connection_close:
380 keep_handling = handle_body_connection_close(recv_buffer, need_more_data);
381 break;
382 case reciev_machine_state_body_chunked:
383 keep_handling = handle_body_body_chunked(recv_buffer, need_more_data);
384 break;
385 case reciev_machine_state_done:
386 keep_handling = false;
387 break;
388 case reciev_machine_state_error:
389 keep_handling = false;
390 break;
391 }
392
393 }
394 m_header_cache.clear();
395 if(m_state != reciev_machine_state_error)
396 {
397 if(m_response_info.m_header_info.m_connection.size() && !string_tools::compare_no_case("close", m_response_info.m_header_info.m_connection))
398 disconnect();
399
400 return true;
401 }
402 else
403 {
404 LOG_PRINT_L3("Returning false because of wrong state machine. state: " << m_state);
405 return false;
406 }
407 }
408 //---------------------------------------------------------------------------
409 inline
410 bool handle_header(std::string& recv_buff, bool& need_more_data)
411 {
412
413 CRITICAL_REGION_LOCAL(m_lock);
414 if(!recv_buff.size())
415 {
416 LOG_ERROR("Connection closed at handle_header");
417 m_state = reciev_machine_state_error;
418 return false;
419 }
420
421 m_header_cache += recv_buff;
422 recv_buff.clear();
423 std::string::size_type pos = m_header_cache.find("\r\n\r\n");
424 if(pos != std::string::npos)
425 {
426 recv_buff.assign(m_header_cache.begin()+pos+4, m_header_cache.end());
427 m_header_cache.erase(m_header_cache.begin()+pos+4, m_header_cache.end());
428
429 analize_cached_header_and_invoke_state();
430 if (!on_header(m_response_info))
431 {
432 MDEBUG("Connection cancelled by on_header");
433 m_state = reciev_machine_state_done;
434 return false;
435 }
436 m_header_cache.clear();
437 if(!recv_buff.size() && (m_state != reciev_machine_state_error && m_state != reciev_machine_state_done))
438 need_more_data = true;
439
440 return true;
441 }else
442 need_more_data = true;
443 return true;
444 }
445 //---------------------------------------------------------------------------
446 inline
447 bool handle_body_content_len(std::string& recv_buff, bool& need_more_data)
448 {
449 CRITICAL_REGION_LOCAL(m_lock);
450 if(!recv_buff.size())
451 {
452 MERROR("Warning: Content-Len mode, but connection unexpectedly closed");
453 m_state = reciev_machine_state_done;
454 return true;
455 }
456 CHECK_AND_ASSERT_MES(m_len_in_remain >= recv_buff.size(), false, "m_len_in_remain >= recv_buff.size()");
457 m_len_in_remain -= recv_buff.size();
458 if (!m_pcontent_encoding_handler->update_in(recv_buff))
459 {
460 m_state = reciev_machine_state_done;
461 return false;
462 }
463
464 if(m_len_in_remain == 0)
465 m_state = reciev_machine_state_done;
466 else
467 need_more_data = true;
468
469 return true;
470 }
471 //---------------------------------------------------------------------------
472 inline
473 bool handle_body_connection_close(std::string& recv_buff, bool& need_more_data)
474 {
475 CRITICAL_REGION_LOCAL(m_lock);
476 if(!recv_buff.size())
477 {
478 m_state = reciev_machine_state_done;
479 return true;
480 }
481 need_more_data = true;
482 m_pcontent_encoding_handler->update_in(recv_buff);
483
484
485 return true;
486 }
487 //---------------------------------------------------------------------------
488 inline bool is_hex_symbol(char ch)
489 {
490
491 if( (ch >= '0' && ch <='9')||(ch >= 'A' && ch <='F')||(ch >= 'a' && ch <='f'))
492 return true;
493 else
494 return false;
495 }
496 //---------------------------------------------------------------------------
497 inline
498 bool get_len_from_chunk_head(const std::string &chunk_head, size_t& result_size)
499 {
500 std::stringstream str_stream;
501 str_stream << std::hex;
502 if(!(str_stream << chunk_head && str_stream >> result_size))
503 return false;
504
505 return true;
506 }
507 //---------------------------------------------------------------------------
508 inline
509 bool get_chunk_head(std::string& buff, size_t& chunk_size, bool& is_matched)
510 {
511 is_matched = false;
512 size_t offset = 0;
513 for(std::string::iterator it = buff.begin(); it!= buff.end(); it++, offset++)
514 {
515 if(!is_hex_symbol(*it))
516 {
517 if(*it == '\r' || *it == ' ' )
518 {
519 offset--;
520 continue;
521 }
522 else if(*it == '\n')
523 {
524 std::string chunk_head = buff.substr(0, offset);
525 if(!get_len_from_chunk_head(chunk_head, chunk_size))
526 return false;
527
528 if(0 == chunk_size)
529 {
530 //Here is a small confusion
531 //In brief - if the chunk is the last one we need to get terminating sequence
532 //along with the cipher, generally in the "ddd\r\n\r\n" form
533
534 for(it++;it != buff.end(); it++)
535 {
536 if('\r' == *it)
537 continue;
538 else if('\n' == *it)
539 break;
540 else
541 {
542 LOG_ERROR("http_stream_filter: Wrong last chunk terminator");
543 return false;
544 }
545 }
546
547 if(it == buff.end())
548 return true;
549 }
550
551 buff.erase(buff.begin(), ++it);
552
553 is_matched = true;
554 return true;
555 }
556 else
557 return false;
558 }
559 }
560
561 return true;
562 }
563 //---------------------------------------------------------------------------
564 inline
565 bool handle_body_body_chunked(std::string& recv_buff, bool& need_more_data)
566 {
567 CRITICAL_REGION_LOCAL(m_lock);
568 if(!recv_buff.size())
569 {
570 MERROR("Warning: CHUNKED mode, but connection unexpectedly closed");
571 m_state = reciev_machine_state_done;
572 return true;
573 }
574 m_chunked_cache += recv_buff;
575 recv_buff.clear();
576 bool is_matched = false;
577
578 while(true)
579 {
580 if(!m_chunked_cache.size())
581 {
582 need_more_data = true;
583 break;
584 }
585
586 switch(m_chunked_state)
587 {
588 case http_chunked_state_chunk_head:
589 if(m_chunked_cache[0] == '\n' || m_chunked_cache[0] == '\r')
590 {
591 //optimize a bit
592 if(m_chunked_cache[0] == '\r' && m_chunked_cache.size()>1 && m_chunked_cache[1] == '\n')
593 m_chunked_cache.erase(0, 2);
594 else
595 m_chunked_cache.erase(0, 1);
596 break;
597 }
598 if(!get_chunk_head(m_chunked_cache, m_len_in_remain, is_matched))
599 {
600 LOG_ERROR("http_stream_filter::handle_chunked(*) Failed to get length from chunked head:" << m_chunked_cache);
601 m_state = reciev_machine_state_error;
602 return false;
603 }
604
605 if(!is_matched)
606 {
607 need_more_data = true;
608 return true;
609 }else
610 {
611 m_chunked_state = http_chunked_state_chunk_body;
612 if(m_len_in_remain == 0)
613 {//last chunk, let stop the stream and fix the chunk queue.
614 m_state = reciev_machine_state_done;
615 return true;
616 }
617 m_chunked_state = http_chunked_state_chunk_body;
618 break;
619 }
620 break;
621 case http_chunked_state_chunk_body:
622 {
623 std::string chunk_body;
624 if(m_len_in_remain >= m_chunked_cache.size())
625 {
626 m_len_in_remain -= m_chunked_cache.size();
627 chunk_body.swap(m_chunked_cache);
628 }else
629 {
630 chunk_body.assign(m_chunked_cache, 0, m_len_in_remain);
631 m_chunked_cache.erase(0, m_len_in_remain);
632 m_len_in_remain = 0;
633 }
634
635 if (!m_pcontent_encoding_handler->update_in(chunk_body))
636 {
637 m_state = reciev_machine_state_error;
638 return false;
639 }
640
641 if(!m_len_in_remain)
642 m_chunked_state = http_chunked_state_chunk_head;
643 }
644 break;
645 case http_chunked_state_done:
646 m_state = reciev_machine_state_done;
647 return true;
648 case http_chunked_state_undefined:
649 default:
650 LOG_ERROR("http_stream_filter::handle_chunked(): Wrong state" << m_chunked_state);
651 return false;
652 }
653 }
654
655 return true;
656 }
657 //---------------------------------------------------------------------------
658 inline bool parse_header(http_header_info& body_info, const std::string& m_cache_to_process)
659 {
660 MTRACE("http_stream_filter::parse_cached_header(*)");
661
662 const char *ptr = m_cache_to_process.c_str();
663 while (ptr[0] != '\r' || ptr[1] != '\n')
664 {
665 // optional \n
666 if (*ptr == '\n')
667 ++ptr;
668 // an identifier composed of letters or -
669 const char *key_pos = ptr;
670 while (isalnum(*ptr) || *ptr == '_' || *ptr == '-')
671 ++ptr;
672 const char *key_end = ptr;
673 // optional space (not in RFC, but in previous code)
674 if (*ptr == ' ')
675 ++ptr;
676 CHECK_AND_ASSERT_MES(*ptr == ':', true, "http_stream_filter::parse_cached_header() invalid header in: " << m_cache_to_process);
677 ++ptr;
678 // optional whitespace, but not newlines - line folding is obsolete, let's ignore it
679 while (isblank(*ptr))
680 ++ptr;
681 const char *value_pos = ptr;
682 while (*ptr != '\r' && *ptr != '\n')
683 ++ptr;
684 const char *value_end = ptr;
685 // optional trailing whitespace
686 while (value_end > value_pos && isblank(*(value_end-1)))
687 --value_end;
688 if (*ptr == '\r')
689 ++ptr;
690 CHECK_AND_ASSERT_MES(*ptr == '\n', true, "http_stream_filter::parse_cached_header() invalid header in: " << m_cache_to_process);
691 ++ptr;
692
693 const std::string key = std::string(key_pos, key_end - key_pos);
694 const std::string value = std::string(value_pos, value_end - value_pos);
695 if (!key.empty())
696 {
697 if (!string_tools::compare_no_case(key, "Connection"))
698 body_info.m_connection = value;
699 else if(!string_tools::compare_no_case(key, "Referrer"))
700 body_info.m_referer = value;
701 else if(!string_tools::compare_no_case(key, "Content-Length"))
702 body_info.m_content_length = value;
703 else if(!string_tools::compare_no_case(key, "Content-Type"))
704 body_info.m_content_type = value;
705 else if(!string_tools::compare_no_case(key, "Transfer-Encoding"))
706 body_info.m_transfer_encoding = value;
707 else if(!string_tools::compare_no_case(key, "Content-Encoding"))
708 body_info.m_content_encoding = value;
709 else if(!string_tools::compare_no_case(key, "Host"))
710 body_info.m_host = value;
711 else if(!string_tools::compare_no_case(key, "Cookie"))
712 body_info.m_cookie = value;
713 else if(!string_tools::compare_no_case(key, "User-Agent"))
714 body_info.m_user_agent = value;
715 else if(!string_tools::compare_no_case(key, "Origin"))
716 body_info.m_origin = value;
717 else
718 body_info.m_etc_fields.emplace_back(key, value);
719 }
720 }
721 return true;
722 }
723 //---------------------------------------------------------------------------
724 inline bool analize_first_response_line()
725 {
726 //First line response, look like this: "HTTP/1.1 200 OK"
727 const char *ptr = m_header_cache.c_str();
728 CHECK_AND_ASSERT_MES(!memcmp(ptr, "HTTP/", 5), false, "Invalid first response line: " + m_header_cache);
729 ptr += 5;
730 CHECK_AND_ASSERT_MES(epee::misc_utils::parse::isdigit(*ptr), false, "Invalid first response line: " + m_header_cache);
731 unsigned long ul;
732 char *end;
733 ul = strtoul(ptr, &end, 10);
734 CHECK_AND_ASSERT_MES(ul <= INT_MAX && *end =='.', false, "Invalid first response line: " + m_header_cache);
735 m_response_info.m_http_ver_hi = ul;
736 ptr = end + 1;
737 CHECK_AND_ASSERT_MES(epee::misc_utils::parse::isdigit(*ptr), false, "Invalid first response line: " + m_header_cache + ", ptr: " << ptr);
738 ul = strtoul(ptr, &end, 10);
739 CHECK_AND_ASSERT_MES(ul <= INT_MAX && isblank(*end), false, "Invalid first response line: " + m_header_cache + ", ptr: " << ptr);
740 m_response_info.m_http_ver_lo = ul;
741 ptr = end + 1;
742 while (isblank(*ptr))
743 ++ptr;
744 CHECK_AND_ASSERT_MES(epee::misc_utils::parse::isdigit(*ptr), false, "Invalid first response line: " + m_header_cache);
745 ul = strtoul(ptr, &end, 10);
746 CHECK_AND_ASSERT_MES(ul >= 100 && ul <= 999 && isspace(*end), false, "Invalid first response line: " + m_header_cache);
747 m_response_info.m_response_code = ul;
748 ptr = end;
749 // ignore the optional text, till the end
750 while (*ptr != '\r' && *ptr != '\n')
751 ++ptr;
752 if (*ptr == '\r')
753 ++ptr;
754 CHECK_AND_ASSERT_MES(*ptr == '\n', false, "Invalid first response line: " << m_header_cache);
755 ++ptr;
756
757 m_header_cache.erase(0, ptr - m_header_cache.c_str());
758 return true;
759 }
760 inline
761 bool set_reply_content_encoder()
762 {
763 STATIC_REGEXP_EXPR_1(rexp_match_gzip, "^.*?((gzip)|(deflate))", boost::regex::icase | boost::regex::normal);
764 boost::smatch result; // 12 3
765 if(boost::regex_search( m_response_info.m_header_info.m_content_encoding, result, rexp_match_gzip, boost::match_default) && result[0].matched)
766 {
767 m_pcontent_encoding_handler.reset(new do_nothing_sub_handler(this));
768 LOG_ERROR("GZIP encoding not supported");
769 return false;
770 }
771 else
772 {
773 m_pcontent_encoding_handler.reset(new do_nothing_sub_handler(this));
774 }
775
776 return true;
777 }
778 inline
779 bool analize_cached_header_and_invoke_state()
780 {
781 m_response_info.clear();
782 analize_first_response_line();
783 std::string fake_str; //gcc error workaround
784
785 bool res = parse_header(m_response_info.m_header_info, m_header_cache);
786 CHECK_AND_ASSERT_MES(res, false, "http_stream_filter::analize_cached_reply_header_and_invoke_state(): failed to anilize reply header: " << m_header_cache);
787
788 set_reply_content_encoder();
789
790 m_len_in_summary = 0;
791 bool content_len_valid = false;
792 if(m_response_info.m_header_info.m_content_length.size())
793 content_len_valid = string_tools::get_xtype_from_string(m_len_in_summary, m_response_info.m_header_info.m_content_length);
794
795
796
797 if(!m_len_in_summary && ((m_response_info.m_response_code>=100&&m_response_info.m_response_code<200)
798 || 204 == m_response_info.m_response_code
799 || 304 == m_response_info.m_response_code) )
800 {//There will be no response body, server will display the local page with error
801 m_state = reciev_machine_state_done;
802 return true;
803 }else if(m_response_info.m_header_info.m_transfer_encoding.size())
804 {
805 string_tools::trim(m_response_info.m_header_info.m_transfer_encoding);
806 if(string_tools::compare_no_case(m_response_info.m_header_info.m_transfer_encoding, "chunked"))
807 {
808 LOG_ERROR("Wrong Transfer-Encoding:" << m_response_info.m_header_info.m_transfer_encoding);
809 m_state = reciev_machine_state_error;
810 return false;
811 }
812 m_state = reciev_machine_state_body_chunked;
813 m_chunked_state = http_chunked_state_chunk_head;
814 return true;
815 }
816 else if(!m_response_info.m_header_info.m_content_length.empty())
817 {
818 //In the response header the length was specified
819 if(!content_len_valid)
820 {
821 LOG_ERROR("http_stream_filter::analize_cached_reply_header_and_invoke_state(): Failed to get_len_from_content_lenght();, m_query_info.m_content_length="<<m_response_info.m_header_info.m_content_length);
822 m_state = reciev_machine_state_error;
823 return false;
824 }
825 if(!m_len_in_summary)
826 {
827 m_state = reciev_machine_state_done;
828 return true;
829 }
830 else
831 {
832 m_len_in_remain = m_len_in_summary;
833 m_state = reciev_machine_state_body_content_len;
834 return true;
835 }
836 }else if(!m_response_info.m_header_info.m_connection.empty() && is_connection_close_field(m_response_info.m_header_info.m_connection))
837 { //By indirect signs we suspect that data transfer will end with a connection break
838 m_state = reciev_machine_state_body_connection_close;
839 }else if(is_multipart_body(m_response_info.m_header_info, fake_str))
840 {
841 m_state = reciev_machine_state_error;
842 LOG_ERROR("Unsupported MULTIPART BODY.");
843 return false;
844 }else
845 { //Apparently there are no signs of the form of transfer, will receive data until the connection is closed
846 m_state = reciev_machine_state_error;
847 MERROR("Undefined transfer type, consider http_body_transfer_connection_close method. header: " << m_header_cache);
848 return false;
849 }
850 return false;
851 }
852 inline
853 bool is_connection_close_field(const std::string& str)
854 {
855 STATIC_REGEXP_EXPR_1(rexp_match_close, "^\\s*close", boost::regex::icase | boost::regex::normal);
856 boost::smatch result;
857 if(boost::regex_search( str, result, rexp_match_close, boost::match_default) && result[0].matched)
858 return true;
859 else
860 return false;
861 }
862 inline
863 bool is_multipart_body(const http_header_info& head_info, OUT std::string& boundary)
864 {
865 //Check whether this is multi part - if yes, capture boundary immediately
866 STATIC_REGEXP_EXPR_1(rexp_match_multipart_type, "^\\s*multipart/([\\w\\-]+); boundary=((\"(.*?)\")|(\\\\\"(.*?)\\\\\")|([^\\s;]*))", boost::regex::icase | boost::regex::normal);
867 boost::smatch result;
868 if(boost::regex_search(head_info.m_content_type, result, rexp_match_multipart_type, boost::match_default) && result[0].matched)
869 {
870 if(result[4].matched)
871 boundary = result[4];
872 else if(result[6].matched)
873 boundary = result[6];
874 else if(result[7].matched)
875 boundary = result[7];
876 else
877 {
878 LOG_ERROR("Failed to match boundary in content-type=" << head_info.m_content_type);
879 return false;
880 }
881 return true;
882 }
883 else
884 return false;
885
886 return true;
887 }
888 };
889 typedef http_simple_client_template<blocked_mode_client> http_simple_client;
890 }
891 }
892 }