This repository was archived by the owner on Jun 14, 2024. It is now read-only.
forked from microsoft/cpprestsdk
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathhttp_server_asio.cpp
More file actions
1480 lines (1290 loc) · 49.5 KB
/
Copy pathhttp_server_asio.cpp
File metadata and controls
1480 lines (1290 loc) · 49.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/***
* Copyright (C) Microsoft. All rights reserved.
* Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
*
* =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
*
* HTTP Library: HTTP listener (server-side) APIs
* This file contains a cross platform implementation based on Boost.ASIO.
*
* For the latest on this and related APIs, please see: https://github.com/Microsoft/cpprestsdk
*
* =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
*/
#include "stdafx.h"
#undef min
#undef max
#include <boost/algorithm/string/find.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/asio/read_until.hpp>
#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wconversion"
#pragma clang diagnostic ignored "-Winfinite-recursion"
#endif
#include <boost/asio.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/filesystem.hpp>
#if defined(__clang__)
#pragma clang diagnostic pop
#endif
#include "cpprest/asyncrt_utils.h"
#include "pplx/threadpool.h"
#include "../common/internal_http_helpers.h"
#include "http_server_impl.h"
#ifdef __ANDROID__
using utility::conversions::details::to_string;
#else
using std::to_string;
#endif
using namespace boost::asio;
using namespace boost::asio::ip;
typedef boost::asio::ip::tcp::socket tcp_socket;
typedef boost::asio::ip::tcp::acceptor tcp_acceptor;
typedef boost::asio::local::stream_protocol::acceptor stream_acceptor;
typedef boost::asio::local::stream_protocol::socket stream_socket;
#define CRLF std::string("\r\n")
#define CRLFCRLF std::string("\r\n\r\n")
namespace listener = web::http::experimental::listener;
namespace chunked_encoding = web::http::details::chunked_encoding;
using web::uri;
using web::http::http_request;
using web::http::http_response;
using web::http::methods;
using web::http::status_codes;
using web::http::header_names;
using web::http::http_exception;
using web::http::experimental::listener::details::http_listener_impl;
using web::http::experimental::listener::http_listener_config;
using utility::details::make_unique;
namespace
{
template<class SOCKET_T, class ACCEPTOR_T> class hostport_listener;
template<class SOCKET_T, class ACCEPTOR_T> class http_linux_server;
template<class SOCKET_T, class ACCEPTOR_T> class asio_server_connection;
}
namespace
{
struct iequal_to
{
bool operator()(const std::string& left, const std::string& right) const
{
return boost::ilexicographical_compare(left, right);
}
};
template<class SOCKET_T, class ACCEPTOR_T>
class http_linux_server : public web::http::experimental::details::http_server
{
private:
friend class asio_server_connection<SOCKET_T, ACCEPTOR_T>;
pplx::extensibility::reader_writer_lock_t m_listeners_lock;
std::map<std::string, std::unique_ptr<hostport_listener<SOCKET_T, ACCEPTOR_T>>, iequal_to> m_listeners;
std::unordered_map<http_listener_impl *, std::unique_ptr<pplx::extensibility::reader_writer_lock_t>> m_registered_listeners;
bool m_started;
public:
http_linux_server()
: m_listeners_lock()
, m_listeners()
, m_started(false)
{}
~http_linux_server()
{
stop();
}
virtual pplx::task<void> start();
virtual pplx::task<void> stop();
virtual pplx::task<void> register_listener(http_listener_impl* listener);
virtual pplx::task<void> unregister_listener(http_listener_impl* listener);
pplx::task<void> respond(http_response response);
};
struct linux_request_context : web::http::details::_http_server_context
{
linux_request_context() {}
pplx::task_completion_event<void> m_response_completed;
private:
linux_request_context(const linux_request_context&) = delete;
linux_request_context& operator=(const linux_request_context&) = delete;
};
template<class SOCKET_T, class ACCEPTOR_T>
class hostport_listener
{
private:
int m_backlog;
std::unique_ptr<ACCEPTOR_T> m_acceptor;
std::map<std::string, http_listener_impl* > m_listeners;
pplx::extensibility::reader_writer_lock_t m_listeners_lock;
std::mutex m_connections_lock;
pplx::extensibility::event_t m_all_connections_complete;
std::set<asio_server_connection<SOCKET_T, ACCEPTOR_T>*> m_connections;
http_linux_server<SOCKET_T, ACCEPTOR_T>* m_p_server;
std::string m_host;
std::string m_port;
bool m_is_https;
const std::function<void(boost::asio::ssl::context&)>& m_ssl_context_callback;
public:
hostport_listener(http_linux_server<SOCKET_T, ACCEPTOR_T>* server, const std::string& hostport, bool is_https, const http_listener_config& config)
: m_backlog(config.backlog())
, m_acceptor()
, m_listeners()
, m_listeners_lock()
, m_connections_lock()
, m_connections()
, m_p_server(server)
, m_is_https(is_https)
, m_ssl_context_callback(config.get_ssl_context_callback())
{
m_all_connections_complete.set();
std::istringstream hostport_in(hostport);
hostport_in.imbue(std::locale::classic());
std::getline(hostport_in, m_host, ':');
std::getline(hostport_in, m_port);
}
~hostport_listener()
{
stop();
}
void start();
void stop();
void add_listener(const std::string& path, http_listener_impl* listener);
void remove_listener(const std::string& path, http_listener_impl* listener);
void internal_erase_connection(asio_server_connection<SOCKET_T, ACCEPTOR_T>*);
http_listener_impl* find_listener(uri const& u)
{
auto path_segments = uri::split_path(uri::decode(u.path()));
for (auto i = static_cast<long>(path_segments.size()); i >= 0; --i)
{
std::string path = "";
for (size_t j = 0; j < static_cast<size_t>(i); ++j)
{
path += "/" + utility::conversions::to_utf8string(path_segments[j]);
}
path += "/";
pplx::extensibility::scoped_read_lock_t lock(m_listeners_lock);
auto it = m_listeners.find(path);
if (it != m_listeners.end())
{
return it->second;
}
}
return nullptr;
}
std::string get_socket_file_path() {
boost::filesystem::path exe_path = boost::filesystem::read_symlink("/proc/self/exe").parent_path();
auto exe_name = boost::filesystem::read_symlink("/proc/self/exe").filename().string();
boost::filesystem::path socket_path = exe_path/"sockets";
boost::filesystem::path socket_file_path;
boost::filesystem::path dsc_config_path = exe_path/"dsc.config";
if (exe_name.find("worker")!=std::string::npos)
{
socket_file_path = socket_path / "gcworker";
}
else
{
socket_file_path = socket_path / "dsc";
}
try {
utility::ifstream_t file_handle(dsc_config_path.string());
utility::stringstream_t contents;
if (file_handle) {
contents << file_handle.rdbuf();
file_handle.close();
web::json::value dsc_config = web::json::value::parse(contents);
if (dsc_config.has_field(U("ServiceType"))) {
utility::string_t service_type = dsc_config.at(U("ServiceType")).as_string();
if(boost::iequals(service_type, U("Extension"))) {
socket_file_path = socket_path / "em";
}
}
}
}
catch (web::json::json_exception excep) {
}
return socket_file_path.string();
}
private:
void on_accept(SOCKET_T* socket, const boost::system::error_code& ec);
};
}
namespace
{
/// This class replaces the regex "\r\n\r\n|[\x00-\x1F]|[\x80-\xFF]"
// It was added due to issues with regex on Android, however since
// regex was rather overkill for such a simple parse it makes sense
// to use it on all *nix platforms.
//
// This is used as part of the async_read_until call below; see the
// following for more details:
// http://www.boost.org/doc/libs/1_55_0/doc/html/boost_asio/reference/async_read_until/overload4.html
struct crlfcrlf_nonascii_searcher_t
{
enum class State
{
none = 0, // ".\r\n\r\n$"
cr = 1, // "\r.\n\r\n$"
// " .\r\n\r\n$"
crlf = 2, // "\r\n.\r\n$"
// " .\r\n\r\n$"
crlfcr = 3 // "\r\n\r.\n$"
// " \r.\n\r\n$"
// " .\r\n\r\n$"
};
// This function implements the searcher which "consumes" a certain amount of the input
// and returns whether or not there was a match (see above).
// From the Boost documentation:
// "The first member of the return value is an iterator marking one-past-the-end of the
// bytes that have been consumed by the match function. This iterator is used to
// calculate the begin parameter for any subsequent invocation of the match condition.
// The second member of the return value is true if a match has been found, false
// otherwise."
template<typename Iter>
std::pair<Iter, bool> operator()(const Iter begin, const Iter end) const
{
// In the case that we end inside a partially parsed match (like abcd\r\n\r),
// we need to signal the matcher to give us the partial match back again (\r\n\r).
// We use the excluded variable to keep track of this sequence point (abcd.\r\n\r
// in the previous example).
Iter excluded = begin;
Iter cur = begin;
State state = State::none;
while (cur != end)
{
char c = *cur;
if (c == '\r')
{
if (state == State::crlf)
{
state = State::crlfcr;
}
else
{
// In the case of State::cr or State::crlfcr, setting the state here
// "skips" a none state and therefore fails to move up the excluded
// counter.
excluded = cur;
state = State::cr;
}
}
else if (c == '\n')
{
if (state == State::cr)
{
state = State::crlf;
}
else if (state == State::crlfcr)
{
++cur;
return std::make_pair(cur, true);
}
else
{
state = State::none;
}
}
else if (c <= '\x1F' && c >= '\x00')
{
++cur;
return std::make_pair(cur, true);
}
else if (c <= '\xFF' && c >= '\x80')
{
++cur;
return std::make_pair(cur, true);
}
else
{
state = State::none;
}
++cur;
if (state == State::none)
excluded = cur;
}
return std::make_pair(excluded, false);
}
} crlfcrlf_nonascii_searcher;
// These structures serve as proof witnesses
struct will_erase_from_parent_t {};
struct will_deref_and_erase_t {};
struct will_deref_t {};
template<class SOCKET_T, class ACCEPTOR_T>
class asio_server_connection
{
private:
typedef void (asio_server_connection<SOCKET_T, ACCEPTOR_T>::*ResponseFuncPtr) (const http_response &response, const boost::system::error_code& ec);
std::unique_ptr<SOCKET_T> m_socket;
boost::asio::streambuf m_request_buf;
boost::asio::streambuf m_response_buf;
http_linux_server<SOCKET_T, ACCEPTOR_T>* m_p_server;
hostport_listener<SOCKET_T, ACCEPTOR_T>* m_p_parent;
http_request m_request;
size_t m_read, m_write;
size_t m_read_size, m_write_size;
bool m_close;
bool m_chunked;
std::atomic<int> m_refs; // track how many threads are still referring to this
using ssl_stream = boost::asio::ssl::stream<boost::asio::ip::tcp::socket&>;
std::unique_ptr<boost::asio::ssl::context> m_ssl_context;
std::unique_ptr<ssl_stream> m_ssl_stream;
public:
asio_server_connection(std::unique_ptr<SOCKET_T> socket, http_linux_server<SOCKET_T, ACCEPTOR_T>* server, hostport_listener<SOCKET_T, ACCEPTOR_T>* parent)
: m_socket(std::move(socket))
, m_request_buf()
, m_response_buf()
, m_p_server(server)
, m_p_parent(parent)
, m_close(false)
, m_refs(1)
{
}
will_deref_and_erase_t start(bool is_https, const std::function<void(boost::asio::ssl::context&)>& ssl_context_callback);
void close();
asio_server_connection(const asio_server_connection&) = delete;
asio_server_connection& operator=(const asio_server_connection&) = delete;
private:
~asio_server_connection() = default;
utility::string_t get_remote_address();
will_deref_and_erase_t start_request_response();
will_deref_and_erase_t handle_http_line(const boost::system::error_code& ec);
will_deref_and_erase_t handle_headers();
will_deref_t handle_body(const boost::system::error_code& ec);
will_deref_t handle_chunked_header(const boost::system::error_code& ec);
will_deref_t handle_chunked_body(const boost::system::error_code& ec, int toWrite);
will_deref_and_erase_t dispatch_request_to_listener();
will_erase_from_parent_t do_response()
{
++m_refs;
m_request.get_response().then([=](pplx::task<http_response> r_task)
{
http_response response;
try
{
response = r_task.get();
}
catch (...)
{
response = http_response(status_codes::InternalError);
}
serialize_headers(response);
// before sending response, the full incoming message need to be processed.
return m_request.content_ready().then([=](pplx::task<http_request>)
{
(will_deref_and_erase_t)this->async_write(&asio_server_connection<SOCKET_T, ACCEPTOR_T>::handle_headers_written, response);
});
});
return will_erase_from_parent_t{};
}
will_erase_from_parent_t do_bad_response()
{
++m_refs;
m_request.get_response().then([=](pplx::task<http_response> r_task)
{
http_response response;
try
{
response = r_task.get();
}
catch (...)
{
response = http_response(status_codes::InternalError);
}
// before sending response, the full incoming message need to be processed.
serialize_headers(response);
(will_deref_and_erase_t)async_write(&asio_server_connection<SOCKET_T, ACCEPTOR_T>::handle_headers_written, response);
});
return will_erase_from_parent_t{};
}
will_deref_t async_handle_chunked_header();
template <typename ReadHandler>
void async_read_until_buffersize(size_t size, const ReadHandler &handler);
void serialize_headers(http_response response);
will_deref_and_erase_t cancel_sending_response_with_error(const http_response &response, const std::exception_ptr &);
will_deref_and_erase_t handle_headers_written(const http_response &response, const boost::system::error_code& ec);
will_deref_and_erase_t handle_write_large_response(const http_response &response, const boost::system::error_code& ec);
will_deref_and_erase_t handle_write_chunked_response(const http_response &response, const boost::system::error_code& ec);
will_deref_and_erase_t handle_response_written(const http_response &response, const boost::system::error_code& ec);
will_deref_and_erase_t finish_request_response();
using WriteFunc = decltype(&asio_server_connection<SOCKET_T, ACCEPTOR_T>::handle_headers_written);
will_deref_and_erase_t async_write(WriteFunc response_func_ptr, const http_response &response);
inline will_deref_t deref()
{
if (--m_refs == 0) delete this;
return will_deref_t{};
}
};
}
namespace boost
{
namespace asio
{
template <> struct is_match_condition<crlfcrlf_nonascii_searcher_t> : public boost::true_type {};
}}
namespace
{
const size_t ChunkSize = 4 * 1024;
template<class SOCKET_T, class ACCEPTOR_T>
void hostport_listener<SOCKET_T, ACCEPTOR_T>::internal_erase_connection(asio_server_connection<SOCKET_T, ACCEPTOR_T>* conn)
{
std::lock_guard<std::mutex> lock(m_connections_lock);
m_connections.erase(conn);
tcp::resolver::query(m_host, m_port);
if (m_connections.empty())
{
m_all_connections_complete.set();
}
}
template<>
void hostport_listener<stream_socket, stream_acceptor>::start()
{
auto& service = crossplat::threadpool::shared_instance().service();
// Remove old socket file.
std::string socket_file_path = get_socket_file_path();
if (boost::filesystem::exists(socket_file_path.c_str()))
{
boost::filesystem::remove_all(socket_file_path.c_str());
}
local::stream_protocol::endpoint endpoint(socket_file_path.c_str());
m_acceptor.reset(new local::stream_protocol::acceptor(service, endpoint));
auto socket = new local::stream_protocol::socket(service);
m_acceptor->async_accept(*socket, [this, socket](const boost::system::error_code& ec)
{
this->on_accept(socket, ec);
});
}
template<>
will_deref_and_erase_t asio_server_connection<stream_socket, stream_acceptor>::start(bool, const std::function<void(boost::asio::ssl::context&)>&)
{
return start_request_response();
}
template<>
void hostport_listener<tcp_socket, tcp_acceptor>::start()
{
// resolve the endpoint address
auto& service = crossplat::threadpool::shared_instance().service();
tcp::resolver resolver(service);
// #446: boost resolver does not recognize "+" as a host wildchar
tcp::resolver::query query = ( "+" == m_host)?
tcp::resolver::query(m_port):
tcp::resolver::query(m_host, m_port);
tcp::endpoint endpoint =
*resolver.resolve(query);
m_acceptor.reset(new tcp::acceptor(service));
m_acceptor->open(endpoint.protocol());
m_acceptor->set_option(socket_base::reuse_address(true));
m_acceptor->bind(endpoint);
m_acceptor->listen(0 != m_backlog ? m_backlog : socket_base::max_connections);
auto socket = new ip::tcp::socket(service);
m_acceptor->async_accept(*socket, [this, socket](const boost::system::error_code& ec)
{
this->on_accept(socket, ec);
});
}
template<>
will_deref_and_erase_t asio_server_connection<tcp_socket, tcp_acceptor>::start(bool is_https, const std::function<void(boost::asio::ssl::context&)>& ssl_context_callback)
{
if (is_https)
{
m_ssl_context = make_unique<boost::asio::ssl::context>(boost::asio::ssl::context::sslv23);
if (ssl_context_callback)
{
ssl_context_callback(*m_ssl_context);
}
m_ssl_stream = make_unique<ssl_stream>(*m_socket, *m_ssl_context);
m_ssl_stream->async_handshake(boost::asio::ssl::stream_base::server, [this](const boost::system::error_code&)
{
(will_deref_and_erase_t)this->start_request_response();
});
return will_deref_and_erase_t{};
}
else
{
return start_request_response();
}
}
template<class SOCKET_T, class ACCEPTOR_T>
void asio_server_connection<SOCKET_T, ACCEPTOR_T>::close()
{
m_close = true;
auto sock = m_socket.get();
if (sock != nullptr)
{
boost::system::error_code ec;
sock->cancel(ec);
sock->shutdown(tcp::socket::shutdown_both, ec);
sock->close(ec);
}
m_request._reply_if_not_already(status_codes::InternalError);
}
template<class SOCKET_T, class ACCEPTOR_T>
will_deref_and_erase_t asio_server_connection<SOCKET_T, ACCEPTOR_T>::start_request_response()
{
m_read_size = 0;
m_read = 0;
m_request_buf.consume(m_request_buf.size()); // clear the buffer
if (m_ssl_stream)
{
boost::asio::async_read_until(*m_ssl_stream, m_request_buf, CRLFCRLF, [this](const boost::system::error_code& ec, std::size_t)
{
(will_deref_and_erase_t)this->handle_http_line(ec);
});
}
else
{
boost::asio::async_read_until(*m_socket, m_request_buf, crlfcrlf_nonascii_searcher, [this](const boost::system::error_code& ec, std::size_t)
{
(will_deref_and_erase_t)this->handle_http_line(ec);
});
}
return will_deref_and_erase_t{};
}
template<class SOCKET_T, class ACCEPTOR_T>
void hostport_listener<SOCKET_T, ACCEPTOR_T>::on_accept(SOCKET_T* socket, const boost::system::error_code& ec)
{
std::unique_ptr<SOCKET_T> usocket(std::move(socket));
if (!ec)
{
auto conn = new asio_server_connection<SOCKET_T, ACCEPTOR_T>(std::move(usocket), m_p_server, this);
std::lock_guard<std::mutex> lock(m_connections_lock);
m_connections.insert(conn);
conn->start(m_is_https, m_ssl_context_callback);
if (m_connections.size() == 1)
m_all_connections_complete.reset();
if (m_acceptor)
{
// spin off another async accept
auto newSocket = new SOCKET_T(crossplat::threadpool::shared_instance().service());
m_acceptor->async_accept(*newSocket, [this, newSocket](const boost::system::error_code& ec)
{
this->on_accept(newSocket, ec);
});
}
}
}
template<class SOCKET_T, class ACCEPTOR_T>
will_deref_and_erase_t asio_server_connection<SOCKET_T, ACCEPTOR_T>::handle_http_line(const boost::system::error_code& ec)
{
m_request = http_request::_create_request(make_unique<linux_request_context>());
if (ec)
{
// client closed connection
if (
ec == boost::asio::error::eof || // peer has performed an orderly shutdown
ec == boost::asio::error::operation_aborted || // this can be removed. ECONNABORTED happens only for accept()
ec == boost::asio::error::connection_reset || // connection reset by peer
ec == boost::asio::error::timed_out // connection timed out
)
{
return finish_request_response();
}
else
{
m_request._reply_if_not_already(status_codes::BadRequest);
m_close = true;
(will_erase_from_parent_t)do_bad_response();
(will_deref_t)deref();
return will_deref_and_erase_t{};
}
}
else
{
// read http status line
std::istream request_stream(&m_request_buf);
request_stream.imbue(std::locale::classic());
std::skipws(request_stream);
web::http::method http_verb;
#ifndef _UTF16_STRINGS
request_stream >> http_verb;
#else
{
std::string tmp;
request_stream >> tmp;
http_verb = utility::conversions::latin1_to_utf16(tmp);
}
#endif
if (boost::iequals(http_verb, methods::GET)) http_verb = methods::GET;
else if (boost::iequals(http_verb, methods::POST)) http_verb = methods::POST;
else if (boost::iequals(http_verb, methods::PUT)) http_verb = methods::PUT;
else if (boost::iequals(http_verb, methods::DEL)) http_verb = methods::DEL;
else if (boost::iequals(http_verb, methods::HEAD)) http_verb = methods::HEAD;
else if (boost::iequals(http_verb, methods::TRCE)) http_verb = methods::TRCE;
else if (boost::iequals(http_verb, methods::CONNECT)) http_verb = methods::CONNECT;
else if (boost::iequals(http_verb, methods::OPTIONS)) http_verb = methods::OPTIONS;
// Check to see if there is not allowed character on the input
if (!web::http::details::validate_method(http_verb))
{
m_request.reply(status_codes::BadRequest);
m_close = true;
(will_erase_from_parent_t)do_bad_response();
(will_deref_t)deref();
return will_deref_and_erase_t{};
}
m_request.set_method(http_verb);
std::string http_path_and_version;
std::getline(request_stream, http_path_and_version);
const size_t VersionPortionSize = sizeof(" HTTP/1.1\r") - 1;
// Make sure path and version is long enough to contain the HTTP version
if(http_path_and_version.size() < VersionPortionSize + 2)
{
m_request.reply(status_codes::BadRequest);
m_close = true;
(will_erase_from_parent_t)do_bad_response();
(will_deref_t)deref();
return will_deref_and_erase_t{};
}
// Get the path - remove the version portion and prefix space
try
{
m_request.set_request_uri(utility::conversions::to_string_t(http_path_and_version.substr(1, http_path_and_version.size() - VersionPortionSize - 1)));
}
catch (const std::exception& e) // may be std::range_error indicating invalid Unicode, or web::uri_exception
{
m_request.reply(status_codes::BadRequest, e.what());
m_close = true;
(will_erase_from_parent_t)do_bad_response();
(will_deref_t)deref();
return will_deref_and_erase_t{};
}
// Get the version
std::string http_version = http_path_and_version.substr(http_path_and_version.size() - VersionPortionSize + 1, VersionPortionSize - 2);
auto m_request_impl = m_request._get_impl().get();
web::http::http_version parsed_version = web::http::http_version::from_string(utility::conversions::to_string_t(http_version));
m_request_impl->_set_http_version(parsed_version);
// if HTTP version is 1.0 then disable pipelining
if (parsed_version == web::http::http_versions::HTTP_1_0)
{
m_close = true;
}
// Get the remote IP address
auto remote_address = get_remote_address();
if (remote_address.size() > 0)
{
m_request._get_impl()->_set_remote_address(remote_address);
}
return handle_headers();
}
}
template<>
utility::string_t asio_server_connection<stream_socket, stream_acceptor>::get_remote_address() {
return _XPLATSTR("127.0.0.1");
}
template<>
utility::string_t asio_server_connection<tcp_socket, tcp_acceptor>::get_remote_address() {
boost::system::error_code socket_ec;
auto endpoint = m_socket->remote_endpoint(socket_ec);
if (!socket_ec) {
return utility::conversions::to_string_t(endpoint.address().to_string());
}
return _XPLATSTR("");
}
template<class SOCKET_T, class ACCEPTOR_T>
will_deref_and_erase_t asio_server_connection<SOCKET_T, ACCEPTOR_T>::handle_headers()
{
std::istream request_stream(&m_request_buf);
request_stream.imbue(std::locale::classic());
std::string header;
auto& headers = m_request.headers();
while (std::getline(request_stream, header) && header != "\r")
{
auto colon = header.find(':');
if (colon != std::string::npos && colon != 0)
{
auto name = utility::conversions::to_string_t(header.substr(0, colon));
auto value = utility::conversions::to_string_t(header.substr(colon + 1, header.length() - (colon + 1))); // also exclude '\r'
web::http::details::trim_whitespace(name);
web::http::details::trim_whitespace(value);
if (boost::iequals(name, header_names::content_length))
{
headers[header_names::content_length] = value;
}
else
{
headers.add(name, value);
}
}
else
{
m_request.reply(status_codes::BadRequest);
m_close = true;
(will_erase_from_parent_t)do_bad_response();
(will_deref_t)deref();
return will_deref_and_erase_t{};
}
}
m_chunked = false;
utility::string_t name;
// check if the client has requested we close the connection
if (m_request.headers().match(header_names::connection, name))
{
m_close = boost::iequals(name, U("close"));
}
if (m_request.headers().match(header_names::transfer_encoding, name))
{
m_chunked = boost::ifind_first(name, U("chunked"));
}
m_request._get_impl()->_prepare_to_receive_data();
if (m_chunked)
{
++m_refs;
(will_deref_t)async_handle_chunked_header();
return dispatch_request_to_listener();
}
if (!m_request.headers().match(header_names::content_length, m_read_size))
{
m_read_size = 0;
}
if (m_read_size == 0)
{
m_request._get_impl()->_complete(0);
}
else // need to read the sent data
{
m_read = 0;
++m_refs;
async_read_until_buffersize(std::min(ChunkSize, m_read_size), [this](const boost::system::error_code& ec, size_t)
{
(will_deref_t)this->handle_body(ec);
});
}
return dispatch_request_to_listener();
}
template<class SOCKET_T, class ACCEPTOR_T>
will_deref_t asio_server_connection<SOCKET_T, ACCEPTOR_T>::handle_chunked_header(const boost::system::error_code& ec)
{
if (ec)
{
m_request._get_impl()->_complete(0, std::make_exception_ptr(http_exception(ec.value())));
return deref();
}
else
{
std::istream is(&m_request_buf);
is.imbue(std::locale::classic());
int len;
is >> std::hex >> len;
m_request_buf.consume(CRLF.size());
m_read += len;
if (len == 0)
{
m_request._get_impl()->_complete(m_read);
return deref();
}
else
{
async_read_until_buffersize(len + 2, [this, len](const boost::system::error_code& ec, size_t)
{
(will_deref_t)this->handle_chunked_body(ec, len);
});
return will_deref_t{};
}
}
}
template<class SOCKET_T, class ACCEPTOR_T>
will_deref_t asio_server_connection<SOCKET_T, ACCEPTOR_T>::handle_chunked_body(const boost::system::error_code& ec, int toWrite)
{
if (ec)
{
m_request._get_impl()->_complete(0, std::make_exception_ptr(http_exception(ec.value())));
return deref();
}
else
{
auto writebuf = m_request._get_impl()->outstream().streambuf();
writebuf.putn_nocopy(buffer_cast<const uint8_t *>(m_request_buf.data()), toWrite).then([=](pplx::task<size_t> writeChunkTask) -> will_deref_t
{
try
{
writeChunkTask.get();
}
catch (...)
{
m_request._get_impl()->_complete(0, std::current_exception());
return deref();
}
m_request_buf.consume(2 + toWrite);
return async_handle_chunked_header();
});
return will_deref_t{};
}
}
template<class SOCKET_T, class ACCEPTOR_T>
will_deref_t asio_server_connection<SOCKET_T, ACCEPTOR_T>::handle_body(const boost::system::error_code& ec)
{
// read body
if (ec)
{
m_request._get_impl()->_complete(0, std::make_exception_ptr(http_exception(ec.value())));
return deref();
}
else if (m_read < m_read_size) // there is more to read
{
auto writebuf = m_request._get_impl()->outstream().streambuf();
writebuf.putn_nocopy(boost::asio::buffer_cast<const uint8_t*>(m_request_buf.data()), std::min(m_request_buf.size(), m_read_size - m_read)).then([=](pplx::task<size_t> writtenSizeTask) -> will_deref_t
{
size_t writtenSize = 0;
try
{
writtenSize = writtenSizeTask.get();
}
catch (...)
{
m_request._get_impl()->_complete(0, std::current_exception());
return deref();
}
m_read += writtenSize;
m_request_buf.consume(writtenSize);
async_read_until_buffersize(std::min(ChunkSize, m_read_size - m_read), [this](const boost::system::error_code& ec, size_t)
{
(will_deref_t) this->handle_body(ec);
});
return will_deref_t{};
});
return will_deref_t{};
}
else // have read request body
{
m_request._get_impl()->_complete(m_read);
return deref();
}
}
template<class SOCKET_T, class ACCEPTOR_T>
will_deref_and_erase_t asio_server_connection<SOCKET_T, ACCEPTOR_T>::async_write(WriteFunc response_func_ptr, const http_response &response)
{
if (m_ssl_stream)
{
boost::asio::async_write(*m_ssl_stream, m_response_buf, [=] (const boost::system::error_code& ec, std::size_t)
{
(this->*response_func_ptr)(response, ec);
});
}
else
{
boost::asio::async_write(*m_socket, m_response_buf, [=] (const boost::system::error_code& ec, std::size_t)
{
(this->*response_func_ptr)(response, ec);
});
}
return will_deref_and_erase_t{};
}
template<class SOCKET_T, class ACCEPTOR_T>
will_deref_t asio_server_connection<SOCKET_T, ACCEPTOR_T>::async_handle_chunked_header()
{
if (m_ssl_stream)
{
boost::asio::async_read_until(*m_ssl_stream, m_request_buf, CRLF, [this](const boost::system::error_code& ec, size_t)
{
(will_deref_t)this->handle_chunked_header(ec);
});
}