Repository navigation
Expand file tree
/
Copy pathnetwork.cpp
More file actions
1492 lines (1363 loc) · 43.6 KB
/
Copy pathnetwork.cpp
File metadata and controls
1492 lines (1363 loc) · 43.6 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
/*
* Covariant Script Network Extension
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright (C) 2017-2026 Michael Lee(李登淳)
*
* Email: mikecovlee@163.com
* Github: https://github.com/mikecovlee
* Website: http://covscript.org.cn
*/
#include <covscript/dll.hpp>
#include <covscript/cni.hpp>
#include <network.hpp>
#include <chrono>
#include <optional>
#include <cstdio>
#include <thread>
#include <memory>
#include <mutex>
#include <regex>
#include <array>
inline void cs_runtime_yield()
{
#if COVSCRIPT_ABI_VERSION >= 250908
if (cs::current_process->fiber_stack.empty())
std::this_thread::sleep_for(std::chrono::milliseconds(1));
else
cs::fiber::yield();
#else
std::this_thread::sleep_for(std::chrono::milliseconds(1));
#endif
}
namespace network_cs_ext {
using namespace cs;
std::size_t checked_io_buffer_size(number size)
{
static_assert(NETWORK_MAX_IO_BUFFER_SIZE > 0,
"NETWORK_MAX_IO_BUFFER_SIZE must be greater than zero");
if (size <= 0)
throw lang_error("Buffer size must be greater than zero.");
if (size > NETWORK_MAX_IO_BUFFER_SIZE)
throw lang_error("Buffer size exceeds the configured limit of "
+ std::to_string(NETWORK_MAX_IO_BUFFER_SIZE) + " bytes.");
return static_cast<std::size_t>(size);
}
bool is_null_var(const var &v)
{
if (v.type() == typeid(void))
return true;
if (v.is_type_of<pointer>()) {
const auto &ptr = v.const_val<pointer>();
return !ptr.data.usable();
}
return false;
}
cs_impl::network::ssl_options parse_ssl_options(const var &options_var)
{
cs_impl::network::ssl_options options;
if (is_null_var(options_var))
return options;
if (!options_var.is_type_of<hash_map>())
throw lang_error("TLS options must be null or hash_map.");
const auto &options_map = options_var.const_val<hash_map>();
bool has_trust_mode = false;
for (const auto &entry : options_map) {
if (!entry.first.is_type_of<string>())
throw lang_error("TLS option keys must be strings.");
const auto &key = entry.first.const_val<string>();
const auto &value = entry.second;
if (key == "trust_mode") {
if (!value.is_type_of<string>())
throw lang_error("TLS option \"trust_mode\" must be string.");
const auto &mode = value.const_val<string>();
has_trust_mode = true;
if (mode == "auto")
options.trust_mode = cs_impl::network::ssl_trust_mode::auto_mode;
else if (mode == "openssl")
options.trust_mode = cs_impl::network::ssl_trust_mode::openssl;
else if (mode == "custom")
options.trust_mode = cs_impl::network::ssl_trust_mode::custom;
else if (mode == "insecure") {
options.trust_mode = cs_impl::network::ssl_trust_mode::insecure;
options.verify_peer = false;
options.verify_host = false;
}
else
throw lang_error("Unsupported TLS trust_mode: " + mode);
}
else if (key == "ca_file") {
if (is_null_var(value))
options.ca_file.clear();
else if (value.is_type_of<string>())
options.ca_file = value.const_val<string>();
else
throw lang_error("TLS option \"ca_file\" must be string or null.");
}
else if (key == "ca_path") {
if (is_null_var(value))
options.ca_path.clear();
else if (value.is_type_of<string>())
options.ca_path = value.const_val<string>();
else
throw lang_error("TLS option \"ca_path\" must be string or null.");
}
else if (key == "verify_peer" || key == "verify_host")
throw lang_error("TLS option \"" + key + "\" is not exposed through CNI.");
else
throw lang_error("Unknown TLS option: " + key);
}
if (!options.ca_file.empty() || !options.ca_path.empty()) {
if (!has_trust_mode)
throw lang_error("TLS options \"ca_file\" and \"ca_path\" require trust_mode=\"custom\".");
if (options.trust_mode != cs_impl::network::ssl_trust_mode::custom)
throw lang_error("TLS options \"ca_file\" and \"ca_path\" can only be used with trust_mode=\"custom\".");
}
if (options.trust_mode == cs_impl::network::ssl_trust_mode::custom && options.ca_file.empty() && options.ca_path.empty())
throw lang_error("TLS trust_mode \"custom\" requires ca_file or ca_path.");
if (options.trust_mode == cs_impl::network::ssl_trust_mode::insecure && (!options.ca_file.empty() || !options.ca_path.empty()))
throw lang_error("TLS trust_mode \"insecure\" cannot be combined with ca_file or ca_path.");
return options;
}
std::string to_fixed_hex(const numeric &n)
{
static_assert(NETWORK_FIXED_HEX_SIZE >= 1 && NETWORK_FIXED_HEX_SIZE <= 256,
"NETWORK_FIXED_HEX_SIZE must be between 1 and 256");
if (n.as_integer() < 0)
throw cs::lang_error("Cannot convert negative number to fixed hex string.");
std::array<char, NETWORK_FIXED_HEX_SIZE + 1> buf{};
int written = snprintf(buf.data(), buf.size(), "%0*llX", static_cast<int>(NETWORK_FIXED_HEX_SIZE), static_cast<unsigned long long>(n.as_integer()));
if (written != static_cast<int>(NETWORK_FIXED_HEX_SIZE))
throw cs::lang_error("Failed to convert number to fixed hex string.");
return std::string(buf.data(), NETWORK_FIXED_HEX_SIZE);
}
numeric from_fixed_hex(const std::string &s)
{
if (s.size() != NETWORK_FIXED_HEX_SIZE)
throw cs::lang_error("Invalid byte string size, must be " + std::to_string(NETWORK_FIXED_HEX_SIZE) + ".");
std::size_t idx = 0;
unsigned long long val = 0;
try {
val = std::stoull(s, &idx, 16);
}
catch (const std::exception &e) {
throw cs::lang_error(std::string("Invalid hex string: ") + e.what());
}
if (idx != s.size())
throw cs::lang_error("Invalid hex string: unexpected trailing characters after " + std::to_string(NETWORK_FIXED_HEX_SIZE) + " hex digits.");
return val;
}
string host_name()
{
return asio::ip::host_name();
}
string get_last_global_ssl_trust_report()
{
return cs_impl::network::detail::get_last_tls_trust_report();
}
namespace tcp {
static namespace_t tcp_ext = make_shared_namespace<name_space>();
using socket_t = std::shared_ptr<cs_impl::network::tcp::socket>;
using acceptor_t = std::shared_ptr<asio::ip::tcp::acceptor>;
using endpoint_t = asio::ip::tcp::endpoint;
var acceptor(const endpoint_t &ep)
{
try {
return var::make<acceptor_t>(
std::make_shared<asio::ip::tcp::acceptor>(cs_impl::network::tcp::acceptor(ep)));
}
catch (const std::exception &e) {
throw lang_error(e.what());
}
}
var endpoint(const string &host, number port)
{
if (port < 0 || port > NETWORK_MAX_PORT)
throw lang_error("Port number must be in range [0, " + std::to_string(NETWORK_MAX_PORT) + "].");
else
return var::make<endpoint_t>(cs_impl::network::tcp::endpoint(host, static_cast<unsigned short>(port)));
}
var endpoint_v4(number port)
{
if (port < 0 || port > NETWORK_MAX_PORT)
throw lang_error("Port number must be in range [0, " + std::to_string(NETWORK_MAX_PORT) + "].");
else
return var::make<endpoint_t>(asio::ip::tcp::v4(), static_cast<unsigned short>(port));
}
var endpoint_v6(number port)
{
if (port < 0 || port > NETWORK_MAX_PORT)
throw lang_error("Port number must be in range [0, " + std::to_string(NETWORK_MAX_PORT) + "].");
else
return var::make<endpoint_t>(asio::ip::tcp::v6(), static_cast<unsigned short>(port));
}
var resolve(const string &host, const string &service)
{
try {
return cs_impl::network::tcp::resolve(host, service);
}
catch (const std::exception &e) {
throw lang_error(e.what());
}
}
string get_ssl_trust_report(socket_t &sock)
{
return sock->get_ssl_trust_report();
}
namespace socket {
static namespace_t socket_ext = make_shared_namespace<name_space>();
var socket()
{
return var::make<socket_t>(std::make_shared<cs_impl::network::tcp::socket>());
}
void connect(socket_t &sock, const endpoint_t &ep)
{
try {
sock->connect(ep);
}
catch (const std::exception &e) {
throw lang_error(e.what());
}
}
void connect_ssl(socket_t &sock, const string &host, const var &options)
{
try {
sock->connect_ssl(host, parse_ssl_options(options));
}
catch (const std::exception &e) {
throw lang_error(e.what());
}
}
void accept(socket_t &sock, acceptor_t &a)
{
try {
sock->accept(*a);
}
catch (const std::exception &e) {
throw lang_error(e.what());
}
}
void close(socket_t &sock)
{
try {
sock->close();
}
catch (const std::exception &e) {
throw lang_error(e.what());
}
}
bool is_open(socket_t &sock)
{
return sock->is_open();
}
bool is_ssl(socket_t &sock)
{
return sock->is_ssl();
}
string get_ssl_trust_report(socket_t &sock)
{
return sock->get_ssl_trust_report();
}
void set_opt_reuse_address(socket_t &sock, bool value)
{
sock->set_option(asio::ip::tcp::socket::reuse_address(value));
}
void set_opt_no_delay(socket_t &sock, bool value)
{
sock->set_option(asio::ip::tcp::no_delay(value));
}
void set_opt_keep_alive(socket_t &sock, bool value)
{
sock->set_option(asio::socket_base::keep_alive(value));
}
number available(socket_t &sock)
{
try {
return sock->available();
}
catch (const std::exception &e) {
throw lang_error(e.what());
}
}
bool peer_closed(socket_t &sock)
{
return sock->peer_closed();
}
string receive(socket_t &sock, number max)
{
auto size = checked_io_buffer_size(max);
try {
return sock->receive(size);
}
catch (const std::exception &e) {
throw lang_error(e.what());
}
}
string read(socket_t &sock, number size)
{
auto checked_size = checked_io_buffer_size(size);
try {
return sock->read(checked_size);
}
catch (const std::exception &e) {
throw lang_error(e.what());
}
}
std::size_t send(socket_t &sock, const string &str)
{
try {
return sock->send(str);
}
catch (const std::exception &e) {
throw lang_error(e.what());
}
}
void write(socket_t &sock, const string &str)
{
try {
sock->write(str);
}
catch (const std::exception &e) {
throw lang_error(e.what());
}
}
void shutdown(socket_t &sock)
{
try {
sock->shutdown();
}
catch (const std::exception &e) {
throw lang_error(e.what());
}
}
bool safe_shutdown(socket_t &);
endpoint_t local_endpoint(socket_t &sock)
{
try {
return sock->local_endpoint();
}
catch (const std::exception &e) {
throw lang_error(e.what());
}
}
endpoint_t remote_endpoint(socket_t &sock)
{
try {
return sock->remote_endpoint();
}
catch (const std::exception &e) {
throw lang_error(e.what());
}
}
}
namespace ep {
static namespace_t ep_ext = make_shared_namespace<name_space>();
string address(const endpoint_t &ep)
{
return ep.address().to_string();
}
bool is_v4(const endpoint_t &ep)
{
return ep.address().is_v4();
}
bool is_v6(const endpoint_t &ep)
{
return ep.address().is_v6();
}
number port(const endpoint_t &ep)
{
return ep.port();
}
}
}
namespace udp {
static namespace_t udp_ext = make_shared_namespace<name_space>();
using socket_t = std::shared_ptr<cs_impl::network::udp::socket>;
using endpoint_t = asio::ip::udp::endpoint;
var endpoint(const string &host, number port)
{
if (port < 0 || port > NETWORK_MAX_PORT)
throw lang_error("Port number must be in range [0, " + std::to_string(NETWORK_MAX_PORT) + "].");
else
return var::make<endpoint_t>(cs_impl::network::udp::endpoint(host, static_cast<unsigned short>(port)));
}
var endpoint_v4(number port)
{
if (port < 0 || port > NETWORK_MAX_PORT)
throw lang_error("Port number must be in range [0, " + std::to_string(NETWORK_MAX_PORT) + "].");
else
return var::make<endpoint_t>(asio::ip::udp::v4(), static_cast<unsigned short>(port));
}
var endpoint_broadcast(number port)
{
if (port < 0 || port > NETWORK_MAX_PORT)
throw lang_error("Port number must be in range [0, " + std::to_string(NETWORK_MAX_PORT) + "].");
else
return var::make<endpoint_t>(asio::ip::address_v4::broadcast(), static_cast<unsigned short>(port));
}
var endpoint_v6(number port)
{
if (port < 0 || port > NETWORK_MAX_PORT)
throw lang_error("Port number must be in range [0, " + std::to_string(NETWORK_MAX_PORT) + "].");
else
return var::make<endpoint_t>(asio::ip::udp::v6(), static_cast<unsigned short>(port));
}
var resolve(const string &host, const string &service)
{
try {
return cs_impl::network::udp::resolve(host, service);
}
catch (const std::exception &e) {
throw lang_error(e.what());
}
}
namespace socket {
static namespace_t socket_ext = make_shared_namespace<name_space>();
var socket()
{
return var::make<socket_t>(std::make_shared<cs_impl::network::udp::socket>());
}
void open_v4(socket_t &sock)
{
try {
sock->open_v4();
}
catch (const std::exception &e) {
throw lang_error(e.what());
}
}
void open_v6(socket_t &sock)
{
try {
sock->open_v6();
}
catch (const std::exception &e) {
throw lang_error(e.what());
}
}
void bind(socket_t &sock, const endpoint_t &ep)
{
try {
sock->bind(ep);
}
catch (const std::exception &e) {
throw lang_error(e.what());
}
}
void connect(socket_t &sock, const endpoint_t &ep)
{
try {
sock->connect(ep);
}
catch (const std::exception &e) {
throw lang_error(e.what());
}
}
void close(socket_t &sock)
{
try {
sock->close();
}
catch (const std::exception &e) {
throw lang_error(e.what());
}
}
bool safe_close(socket_t &);
bool is_open(socket_t &sock)
{
return sock->is_open();
}
void set_opt_reuse_address(socket_t &sock, bool value)
{
sock->set_option(asio::ip::udp::socket::reuse_address(value));
}
void set_opt_broadcast(socket_t &sock, bool value)
{
sock->set_option(asio::socket_base::broadcast(value));
}
number available(socket_t &sock)
{
try {
return sock->available();
}
catch (const std::exception &e) {
throw lang_error(e.what());
}
}
string receive_from(socket_t &sock, number max, endpoint_t &ep)
{
auto size = checked_io_buffer_size(max);
try {
return sock->receive_from(size, ep);
}
catch (const std::exception &e) {
throw lang_error(e.what());
}
}
void send_to(socket_t &sock, const string &str, const endpoint_t &ep)
{
try {
sock->send_to(str, ep);
}
catch (const std::exception &e) {
throw lang_error(e.what());
}
}
endpoint_t local_endpoint(socket_t &sock)
{
try {
return sock->local_endpoint();
}
catch (const std::exception &e) {
throw lang_error(e.what());
}
}
endpoint_t remote_endpoint(socket_t &sock)
{
try {
return sock->remote_endpoint();
}
catch (const std::exception &e) {
throw lang_error(e.what());
}
}
}
namespace ep {
static namespace_t ep_ext = make_shared_namespace<name_space>();
string address(const endpoint_t &ep)
{
return ep.address().to_string();
}
bool is_v4(const endpoint_t &ep)
{
return ep.address().is_v4();
}
bool is_v6(const endpoint_t &ep)
{
return ep.address().is_v6();
}
number port(const endpoint_t &ep)
{
return ep.port();
}
}
}
// Asynchronous
namespace async {
class global_settings_type {
friend global_settings_type &get_global_settings();
global_settings_type() = default;
public:
asio::io_context &io = cs_impl::network::get_io_context();
std::atomic<std::size_t> thread_executors{0};
std::mutex lifecycle_mutex;
inline std::size_t poll()
{
if (thread_executors.load(std::memory_order_acquire) != 0)
return 0;
std::lock_guard<std::mutex> lock(lifecycle_mutex);
if (thread_executors.load(std::memory_order_acquire) == 0)
return io.poll();
else
return 0;
}
inline std::size_t poll_one()
{
if (thread_executors.load(std::memory_order_acquire) != 0)
return 0;
std::lock_guard<std::mutex> lock(lifecycle_mutex);
if (thread_executors.load(std::memory_order_acquire) == 0)
return io.poll_one();
else
return 0;
}
};
global_settings_type &get_global_settings()
{
static global_settings_type settings;
return settings;
}
class thread_executor_type {
std::thread worker;
std::atomic<bool> running{true};
std::shared_ptr<asio::executor_work_guard<asio::io_context::executor_type>> work_guard;
public:
void executor()
{
auto &io = cs_impl::network::get_io_context();
while (true) {
// Drain all ready handlers without blocking
while (io.poll_one() > 0);
if (!running.load(std::memory_order_acquire))
break;
// Block until a handler is ready or the timeout expires.
// run_one_for uses the OS-native I/O demux timeout (IOCP /
// epoll / kqueue), so it is NOT affected by the Windows
// default timer resolution (~15.6 ms) the way sleep_for is.
io.run_one_for(std::chrono::milliseconds(NETWORK_THREAD_WORKER_POLL_MS));
}
}
thread_executor_type()
{
auto &settings = get_global_settings();
{
std::lock_guard<std::mutex> lock(settings.lifecycle_mutex);
if (settings.thread_executors.load(std::memory_order_acquire) == 0 && settings.io.stopped())
settings.io.restart();
work_guard = std::make_shared<asio::executor_work_guard<asio::io_context::executor_type>>(settings.io.get_executor());
settings.thread_executors.fetch_add(1, std::memory_order_release);
}
try {
worker = std::thread([this]() {
try {
executor();
}
catch (const std::exception &e) {
// Log or report the error instead of calling
// std::terminate via the uncaught-exception path.
fprintf(stderr, "[network] executor thread"
" terminated by exception: %s\n",
e.what());
}
catch (...) {
fprintf(stderr, "[network] executor thread"
" terminated by unknown exception\n");
}
get_global_settings().thread_executors.fetch_sub(1, std::memory_order_release);
});
}
catch (...) {
get_global_settings().thread_executors.fetch_sub(1, std::memory_order_release);
throw;
}
}
~thread_executor_type()
{
running.store(false, std::memory_order_release);
// Post an empty handler to wake up run_one_for immediately
// so the worker thread can see running == false and exit
// without waiting for the full timeout.
try {
asio::post(cs_impl::network::get_io_context(), [] {});
}
catch (...) {
// Worker will wake on next run_one_for timeout and exit.
}
if (worker.joinable())
worker.join();
}
};
struct state_type {
bool init = false;
bool is_udp = false;
bool is_read = false;
std::atomic<bool> has_done{false};
std::size_t bytes_transferred = 0;
udp::endpoint_t udp_endpoint;
asio::streambuf buffer;
asio::error_code ec;
};
using state_t = std::shared_ptr<state_type>;
state_t create_async_state()
{
return std::make_shared<state_type>();
}
static namespace_t state_ext = make_shared_namespace<name_space>();
bool has_done(const state_t &state)
{
return state->has_done.load(std::memory_order_acquire);
}
cs::var get_result(const state_t &state)
{
if (!state->is_read)
throw cs::lang_error("Asynchronous operation not a read/receive session.");
if (!state->has_done.load(std::memory_order_acquire))
return cs::null_pointer;
if (state->bytes_transferred == 0)
return cs::var::make<cs::string>();
std::string data(asio::buffers_begin(state->buffer.data()), asio::buffers_begin(state->buffer.data()) + state->bytes_transferred);
state->buffer.consume(state->bytes_transferred);
state->bytes_transferred = 0;
return cs::var::make<cs::string>(std::move(data));
}
cs::var get_buffer(const state_t &state, number max_bytes)
{
auto checked_max_bytes = checked_io_buffer_size(max_bytes);
if (!state->is_read)
throw cs::lang_error("Asynchronous operation not a read/receive session.");
if (!state->has_done.load(std::memory_order_acquire))
return cs::null_pointer;
if (state->buffer.size() == 0)
return cs::var::make<cs::string>();
std::size_t to_read = (std::min)(checked_max_bytes, state->buffer.size());
std::string data(asio::buffers_begin(state->buffer.data()), asio::buffers_begin(state->buffer.data()) + to_read);
state->buffer.consume(to_read);
state->bytes_transferred = state->bytes_transferred > to_read ? state->bytes_transferred - to_read : 0;
return cs::var::make<cs::string>(std::move(data));
}
std::size_t available(const state_t &state)
{
if (state->is_read && state->has_done.load(std::memory_order_acquire))
return state->buffer.size();
else
return 0;
}
bool eof(const state_t &state)
{
if (!state->has_done.load(std::memory_order_acquire))
return false;
return state->ec == asio::error::eof || state->ec == asio::error::connection_reset;
}
cs::var get_error(const state_t &state)
{
if (!state->has_done.load(std::memory_order_acquire))
return cs::null_pointer;
if (!state->ec)
return cs::null_pointer;
else
return cs::var::make<cs::string>(state->ec.message());
}
udp::endpoint_t get_endpoint(const state_t &state)
{
if (!state->is_udp || !state->is_read)
throw cs::lang_error("Asynchronous operation not a receive_from session.");
if (!state->has_done.load(std::memory_order_acquire))
throw cs::lang_error("Asynchronous operation not finished.");
if (state->ec)
throw cs::lang_error("Asynchronous operation has encountered an error: " + state->ec.message());
return state->udp_endpoint;
}
bool wait_impl(const state_t &state, std::optional<std::chrono::milliseconds> timeout)
{
auto start = std::chrono::steady_clock::now();
while (true) {
get_global_settings().poll();
if (state->has_done.load(std::memory_order_acquire))
return !state->ec;
if (timeout.has_value()) {
if (std::chrono::steady_clock::now() - start >= *timeout)
return state->has_done.load(std::memory_order_acquire) && !state->ec;
}
cs_runtime_yield();
}
}
bool wait(const state_t &state)
{
return wait_impl(state, std::nullopt);
}
bool wait_for(const state_t &state, std::size_t timeout_ms)
{
return wait_impl(state, std::chrono::milliseconds(timeout_ms));
}
static namespace_t async_ext = make_shared_namespace<name_space>();
template <typename BeginOperation>
void begin_tcp_async_io(BeginOperation &&begin_operation)
{
try {
begin_operation();
}
catch (const std::exception &e) {
throw cs::lang_error(e.what());
}
}
template <typename BeginOperation>
void begin_udp_async_io(BeginOperation &&begin_operation)
{
try {
begin_operation();
}
catch (const std::exception &e) {
throw cs::lang_error(e.what());
}
}
void begin_tcp_tls_handshake(const tcp::socket_t &sock)
{
try {
sock->begin_tls_handshake();
}
catch (const std::exception &e) {
throw cs::lang_error(e.what());
}
}
state_t accept(tcp::socket_t &sock, tcp::acceptor_t &acceptor)
{
state_t state = std::make_shared<state_type>();
state->init = true;
begin_tcp_async_io([&sock] { sock->begin_async_connect(); });
try {
acceptor->async_accept(sock->get_raw(), [sock, state](const asio::error_code &ec) {
state->ec = ec;
sock->end_async_connect();
state->has_done.store(true, std::memory_order_release);
});
}
catch (...) {
sock->end_async_connect();
throw;
}
return state;
}
state_t connect(tcp::socket_t &sock, const tcp::endpoint_t &ep)
{
state_t state = std::make_shared<state_type>();
state->init = true;
begin_tcp_async_io([&sock] { sock->begin_async_connect(); });
try {
sock->get_raw().async_connect(ep, [sock, state](const asio::error_code &ec) {
state->ec = ec;
sock->end_async_connect();
state->has_done.store(true, std::memory_order_release);
});
}
catch (...) {
sock->end_async_connect();
throw;
}
return state;
}
state_t connect_ssl(tcp::socket_t &sock, const std::string &host, const cs::var &options)
{
state_t state = std::make_shared<state_type>();
state->init = true;
auto ssl_options = parse_ssl_options(options);
begin_tcp_tls_handshake(sock);
try {
sock->prepare_ssl(host, ssl_options);
}
catch (const std::exception &e) {
sock->end_tls_handshake();
throw cs::lang_error(e.what());
}
try {
sock->get_tls_raw().async_handshake(asio::ssl::stream_base::client,
asio::bind_executor(sock->get_tls_strand(), [sock, state](const asio::error_code &ec) {
if (ec)
sock->reset_ssl();
state->ec = ec;
sock->end_tls_handshake();
state->has_done.store(true, std::memory_order_release);
}));
}
catch (const std::exception &e) {
sock->reset_ssl();
sock->end_tls_handshake();
throw cs::lang_error(e.what());
}
return state;
}
void read_until(tcp::socket_t &sock, state_t &state, const std::string &pattern)
{
if (state->init && !state->has_done.load(std::memory_order_acquire))
throw cs::lang_error("Last asynchronous operation have not done yet.");
begin_tcp_async_io([&sock] { sock->begin_async_read(); });
const bool previous_init = state->init;
const bool previous_is_read = state->is_read;
const bool previous_has_done = state->has_done.load(std::memory_order_relaxed);
const asio::error_code previous_ec = state->ec;
state->init = true;
state->is_read = true;
state->has_done = false;
state->ec.clear();
try {
auto on_done = [sock, state](const asio::error_code &ec, std::size_t bytes) {
// async_read_until already committed data to the streambuf
// internally; we must NOT call commit() again here.
state->bytes_transferred = bytes;
state->ec = ec;
sock->end_async_read();
state->has_done.store(true, std::memory_order_release);
};
if (sock->is_ssl())
asio::async_read_until(sock->get_tls_raw(), state->buffer, pattern,
asio::bind_executor(sock->get_tls_strand(), on_done));
else
asio::async_read_until(sock->get_raw(), state->buffer, pattern, on_done);
}
catch (...) {
sock->end_async_read();
state->init = previous_init;
state->is_read = previous_is_read;
state->ec = previous_ec;
state->has_done.store(previous_has_done, std::memory_order_release);
throw;
}
}
state_t read(tcp::socket_t &sock, number requested_size)
{
auto n = checked_io_buffer_size(requested_size);