-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsockets.h
5570 lines (4538 loc) · 150 KB
/
sockets.h
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
////////////////////////////////////////////////////////////////////////////////
// MIT License //
// //
// Copyright (c) 2024 Erich Erstu //
// //
// Permission is hereby granted, free of charge, to any person obtaining a //
// copy of this software and associated documentation files (the "Software"), //
// to deal in the Software without restriction, including without limitation //
// the rights to use, copy, modify, merge, publish, distribute, sublicense, //
// and/or sell copies of the Software, and to permit persons to whom the //
// Software is furnished to do so, subject to the following conditions: //
// //
// The above copyright notice and this permission notice shall be included in //
// all copies or substantial portions of the Software. //
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL //
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING //
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER //
// DEALINGS IN THE SOFTWARE. //
////////////////////////////////////////////////////////////////////////////////
#ifndef SOCKETS_H_05_01_2023
#define SOCKETS_H_05_01_2023
#include <algorithm>
#include <limits>
#include <csignal>
#include <cstring>
#include <cstdarg>
#include <cerrno>
#include <cstdio>
#include <cstdint>
#include <sys/epoll.h>
#include <netdb.h>
#include <unistd.h>
class SOCKETS final {
public:
static constexpr const char *const VERSION = "1.04";
enum class ERROR : uint8_t {
NONE = 0,
BAD_TIMING, // Try again later.
PENDING_ALERT, // Handle all the pending alerts and try again.
OUT_OF_MEMORY, // Free some memory and then try again.
RES_LIMIT_MET, // System lacks resources to complete a task.
LIBRARY, // There is a bug in this library.
BAD_REQUEST, // There is a bug in the caller's application.
SYSTEM, // Standard Library's system call failed with an error.
UNKNOWN // Standard Library call failed for an unknown reason.
};
static constexpr const ERROR
NO_ERROR = ERROR::NONE,
BAD_TIMING = ERROR::BAD_TIMING,
PENDING_ALERT = ERROR::PENDING_ALERT,
OUT_OF_MEMORY = ERROR::OUT_OF_MEMORY,
RES_LIMIT_MET = ERROR::RES_LIMIT_MET,
LIBRARY_ERROR = ERROR::LIBRARY,
BAD_REQUEST = ERROR::BAD_REQUEST,
SYSTEM_ERROR = ERROR::SYSTEM,
UNKNOWN_ERROR = ERROR::UNKNOWN;
static constexpr const char *to_string(ERROR) noexcept;
struct SESSION {
size_t id;
ERROR error;
bool valid:1;
};
enum class EVENT : uint8_t {
NONE = 0,
// Do not change the order of the events above this line.
READ,
WRITE,
ACCEPT,
CONNECTION,
DISCONNECTION,
CLOSE,
INCOMING,
// Do not change the order of the events below this line.
EPOLL,
MAX_EVENTS
};
static constexpr const EVENT
NO_EVENT = EVENT::NONE,
CONNECTION = EVENT::CONNECTION,
DISCONNECTION = EVENT::DISCONNECTION,
INCOMING = EVENT::INCOMING;
struct ALERT {
size_t session;
EVENT event;
bool valid:1;
};
struct RESULT{
int value;
int code;
const char *text;
const char *call;
const char *file;
int line;
ERROR error;
};
SOCKETS() noexcept;
~SOCKETS();
bool init() noexcept;
bool deinit() noexcept;
void set_logger(void (*callback)(SESSION, const char *) noexcept) noexcept;
void set_memcap(size_t bytes) noexcept;
ERROR set_intake(
size_t session_id, size_t bytes,
const char *file =LEAF(__builtin_FILE()), int line =__builtin_LINE()
) noexcept;
size_t get_memcap() const noexcept;
size_t get_memtop() const noexcept;
SESSION listen(
const char *port, int family =AF_UNSPEC,
const std::initializer_list<int> options ={SO_REUSEADDR}, int flags =0
) noexcept;
SESSION connect(
const char *host, const char *port, int family =AF_UNSPEC
) noexcept;
[[nodiscard]] bool idle() const noexcept;
ERROR next_error(int timeout_milliseconds =-1) noexcept;
ERROR last_error() noexcept;
ALERT next_alert() noexcept;
[[nodiscard]] size_t get_incoming_size(size_t session_id) const noexcept;
[[nodiscard]] size_t get_outgoing_size(size_t session_id) const noexcept;
size_t read(size_t session_id, void *buf, size_t count) noexcept;
const char *read(size_t session_id) noexcept;
const char *peek(size_t session_id) noexcept;
ERROR write(size_t session_id, const void *buf, size_t count) noexcept;
ERROR write(size_t session_id, const char *text) noexcept;
ERROR writef(
size_t session_id, const char *fmt, ...
) noexcept __attribute__((format(printf, 3, 4)));
[[nodiscard]] bool is_listener(size_t session_id) const noexcept;
[[nodiscard]] bool is_frozen(size_t session_id) const noexcept;
[[nodiscard]] SESSION get_listener(size_t session_id) const noexcept;
[[nodiscard]] const char *get_host(size_t session_id) const noexcept;
[[nodiscard]] const char *get_port(size_t session_id) const noexcept;
[[nodiscard]] SESSION get_session(int descriptor) const noexcept;
void freeze(size_t session_id) noexcept;
void unfreeze(size_t session_id) noexcept;
void disconnect(size_t session_id) noexcept;
static constexpr const size_t BITS_PER_BYTE{
std::numeric_limits<unsigned char>::digits
};
private:
enum class BUFFER : uint8_t {
NEXT_ERROR,
// Do not change the order of items below this line.
MAX_BUFFERS
};
struct MEMORY {
size_t size;
void *data;
MEMORY *next;
MEMORY *prev;
bool indexed:1;
bool recycled:1;
};
struct KEY {
uintptr_t value;
};
struct PIPE {
enum class TYPE : uint8_t {
NONE = 0,
UINT8,
UINT64,
INT,
PTR,
JACK_PTR,
MEMORY_PTR,
KEY,
EPOLL_EVENT
};
struct ENTRY {
union {
uint8_t as_uint8;
uint64_t as_uint64;
int as_int;
void *as_ptr;
KEY as_key;
epoll_event as_epoll_event;
};
TYPE type;
};
size_t capacity;
size_t size;
void *data;
TYPE type;
MEMORY *memory;
};
struct INDEX {
enum class TYPE : uint8_t {
NONE = 0,
// Do not change the order of the types above this line.
EVENT_DESCRIPTOR,
DESCRIPTOR_JACK,
SESSION_JACK,
RESOURCE_MEMORY,
// Do not change the order of the types below this line.
MAX_TYPES
};
struct ENTRY {
PIPE *key_pipe;
PIPE *val_pipe;
size_t index;
ERROR error;
bool valid:1;
};
size_t buckets;
size_t entries;
struct TABLE {
PIPE key;
PIPE value;
} *table;
TYPE type;
bool multimap:1;
bool autogrow:1;
};
struct JACK {
size_t id;
size_t intake;
unsigned event_lookup[ static_cast<size_t>(EVENT::MAX_EVENTS) ];
PIPE epoll_ev;
PIPE children;
PIPE incoming;
PIPE outgoing;
PIPE host;
PIPE port;
int descriptor;
struct PARENT {
int descriptor;
int child_index;
} parent;
int ai_family;
int ai_flags;
struct addrinfo *blacklist;
struct BITSET {
bool frozen:1;
bool connecting:1;
bool may_shutdown:1;
bool reconnect:1;
bool listener:1;
} bitset;
};
struct QUERY {
enum class TYPE : uint8_t {
DESCRIPTOR,
SESSION,
EVENT
};
union {
int descriptor;
size_t session;
EVENT event;
};
TYPE type;
};
static constexpr KEY make_key(uintptr_t) noexcept;
static constexpr KEY make_key(EVENT) noexcept;
static constexpr struct JACK make_jack(
int descriptor, int parent =-1
) noexcept;
static constexpr struct ALERT make_alert(
size_t session, EVENT type, bool valid =true
) noexcept;
static constexpr struct SESSION make_session(ERROR) noexcept;
static constexpr struct SESSION make_session(
size_t id, ERROR error =ERROR::NONE, bool valid =true
) noexcept;
static constexpr struct INDEX::ENTRY make_index_entry(
PIPE &keys, PIPE &values, size_t index, ERROR, bool valid
) noexcept;
static constexpr struct INDEX::ENTRY make_index_entry(
PIPE &keys, PIPE &values, size_t index, ERROR
) noexcept;
static constexpr PIPE make_pipe(
const uint8_t *data, size_t size
) noexcept;
static constexpr PIPE make_pipe(PIPE::TYPE) noexcept;
static constexpr PIPE::ENTRY make_pipe_entry(PIPE::TYPE) noexcept;
static constexpr PIPE::ENTRY make_pipe_entry(uint64_t ) noexcept;
static constexpr PIPE::ENTRY make_pipe_entry(int ) noexcept;
static constexpr PIPE::ENTRY make_pipe_entry(KEY ) noexcept;
static constexpr PIPE::ENTRY make_pipe_entry(JACK * ) noexcept;
static constexpr PIPE::ENTRY make_pipe_entry(MEMORY * ) noexcept;
static constexpr epoll_data_t make_epoll_data(int fd) noexcept;
static constexpr epoll_event make_epoll_event(
int descriptor, uint32_t events
) noexcept;
static constexpr struct addrinfo make_addrinfo(
int ai_family, int ai_flags
) noexcept;
static constexpr QUERY make_descriptor_query(int) noexcept;
static constexpr QUERY make_session_query(size_t) noexcept;
static constexpr QUERY make_session_query(SESSION) noexcept;
static constexpr QUERY make_event_query(EVENT) noexcept;
static bool is_listed(
const addrinfo &info, const addrinfo *list
) noexcept;
static constexpr bool is_descriptor(int) noexcept;
static constexpr EVENT next(EVENT) noexcept;
static constexpr size_t size(PIPE::TYPE) noexcept;
static constexpr size_t align(PIPE::TYPE) noexcept;
static constexpr auto fmt_bytes(size_t) noexcept;
static constexpr const char *LEAF(const char *path) noexcept;
static constexpr const char *TAIL(const char *, char neck) noexcept;
static int clz(unsigned int) noexcept;
static int clz(unsigned long) noexcept;
static int clz(unsigned long long) noexcept;
static unsigned int next_pow2(unsigned int) noexcept;
static unsigned long next_pow2(unsigned long) noexcept;
static unsigned long long next_pow2(unsigned long long) noexcept;
ERROR handle_close (JACK &) noexcept;
ERROR handle_epoll (JACK &, int timeout) noexcept;
ERROR handle_read (JACK &) noexcept;
ERROR handle_write (JACK &) noexcept;
ERROR handle_accept(JACK &) noexcept;
SESSION connect(
const char *host, const char *port, int family, int flags,
JACK *predecessor =nullptr,
const char *file =LEAF(__builtin_FILE()), int line =__builtin_LINE()
) noexcept;
SESSION listen(
const char *host, const char *port, int family, int flags,
const std::initializer_list<int> options, JACK *predecessor =nullptr,
const char *file =LEAF(__builtin_FILE()), int line =__builtin_LINE()
) noexcept;
void terminate(
int descriptor,
const char *file =LEAF(__builtin_FILE()), int line =__builtin_LINE()
) noexcept;
size_t next_connection() noexcept;
size_t next_disconnection() noexcept;
size_t next_incoming() noexcept;
SESSION create_epoll() noexcept;
ERROR operate_epoll(int operation, epoll_event event) noexcept;
ERROR bind_to_epoll(
int descriptor,
const char *file =LEAF(__builtin_FILE()), int line =__builtin_LINE()
) noexcept;
ERROR modify_epoll(
int descriptor, uint32_t events,
const char *file =LEAF(__builtin_FILE()), int line =__builtin_LINE()
) noexcept;
ERROR block_signals(sigset_t &sigset_orig) noexcept;
ERROR unblock_signals(sigset_t &sigset_orig) noexcept;
SESSION open_and_capture(
const char *host, const char *port, int family, int flags,
const std::initializer_list<int> options ={}, JACK *predecessor=nullptr,
const char *file =LEAF(__builtin_FILE()), int line =__builtin_LINE()
) noexcept;
void close_and_release(
JACK&,
const char *file =LEAF(__builtin_FILE()), int line =__builtin_LINE()
) noexcept;
void close_descriptor(int) noexcept;
[[nodiscard]] SESSION capture(const JACK ©) noexcept;
void release(JACK *) noexcept;
JACK *find_jack(const QUERY &) const noexcept;
JACK *find_epoll_jack() const noexcept;
JACK &get_jack(const QUERY &) const noexcept;
JACK &get_epoll_jack() const noexcept;
const PIPE *find_descriptors(EVENT) const noexcept;
void set_event(JACK &, EVENT, bool val =true) noexcept;
void rem_event(JACK &, EVENT) noexcept;
[[nodiscard]] bool has_event(const JACK &, EVENT) const noexcept;
void rem_child(JACK &, JACK &child) const noexcept;
[[nodiscard]] bool is_listener(const JACK &) const noexcept;
size_t count(INDEX::TYPE, KEY key) const noexcept;
INDEX::ENTRY find(
INDEX::TYPE, KEY key, PIPE::ENTRY value ={},
size_t start_i =std::numeric_limits<size_t>::max(),
size_t iterations =std::numeric_limits<size_t>::max()
) const noexcept;
size_t erase(
INDEX::TYPE, KEY key, PIPE::ENTRY value ={},
size_t start_i =std::numeric_limits<size_t>::max(),
size_t iterations =std::numeric_limits<size_t>::max()
) noexcept;
[[nodiscard]] ERROR reserve(INDEX::TYPE, KEY key, size_t capacity) noexcept;
[[nodiscard]] INDEX::ENTRY insert(
INDEX::TYPE, KEY key, PIPE::ENTRY value
) noexcept;
[[nodiscard]] ERROR reindex() noexcept;
void erase(PIPE &pipe, size_t index) const noexcept;
void destroy(PIPE &pipe) noexcept;
void set_value(INDEX::ENTRY, PIPE::ENTRY) noexcept;
PIPE::ENTRY get_value(INDEX::ENTRY) const noexcept;
PIPE::ENTRY get_entry(const PIPE &pipe, size_t index) const noexcept;
PIPE::ENTRY get_last(const PIPE &pipe) const noexcept;
PIPE::ENTRY pop_back(PIPE &pipe) const noexcept;
[[nodiscard]] ERROR reserve(PIPE&, size_t capacity) noexcept;
[[nodiscard]] ERROR insert(PIPE&, PIPE::ENTRY) noexcept;
[[nodiscard]] ERROR insert(PIPE&, size_t index, PIPE::ENTRY) noexcept;
[[nodiscard]] ERROR copy(const PIPE &src, PIPE &dst) noexcept;
[[nodiscard]] ERROR append(const PIPE &src, PIPE &dst) noexcept;
void replace(PIPE&, size_t index, PIPE::ENTRY) const noexcept;
bool swap_sessions(JACK *, JACK *) noexcept;
ERROR swap(PIPE &, PIPE &) noexcept;
PIPE &get_buffer(BUFFER) noexcept;
INDEX &get_index(INDEX::TYPE) noexcept;
KEY to_key (PIPE::ENTRY) const noexcept;
JACK *to_jack (PIPE::ENTRY) const noexcept;
MEMORY *to_memory(PIPE::ENTRY) const noexcept;
int to_int (PIPE::ENTRY) const noexcept;
uint64_t to_uint64(PIPE::ENTRY) const noexcept;
int *to_int (const PIPE &) const noexcept;
char *to_char (const PIPE &) const noexcept;
uint8_t *to_uint8 (const PIPE &) const noexcept;
uint64_t *to_uint64 (const PIPE &) const noexcept;
KEY *to_key (const PIPE &) const noexcept;
void **to_ptr (const PIPE &) const noexcept;
epoll_event *to_epoll_event(const PIPE &) const noexcept;
void *to_ptr(PIPE::ENTRY &) const noexcept;
void *to_ptr(PIPE &, size_t index) const noexcept;
const void *to_ptr(const PIPE &, size_t index) const noexcept;
void enlist(MEMORY &, MEMORY *&list) noexcept;
void unlist(MEMORY &, MEMORY *&list) noexcept;
const MEMORY *find_memory(const void *) const noexcept;
MEMORY *find_memory(const void *) noexcept;
const MEMORY &get_memory(const void *) const noexcept;
MEMORY &get_memory(const void *) noexcept;
[[nodiscard]] INDEX::TABLE *allocate_tables(size_t count) noexcept;
void destroy_and_delete(INDEX::TABLE *tables, size_t count) noexcept;
[[nodiscard]] MEMORY *allocate_and_index(
size_t byte_count, size_t alignment, const void *copy =nullptr
) noexcept;
[[nodiscard]] MEMORY *allocate(const size_t bytes, size_t align) noexcept;
void deallocate(MEMORY &) noexcept;
void recycle(MEMORY &) noexcept;
[[nodiscard]] JACK *new_jack(const JACK *copy =nullptr) noexcept;
ERROR report(
SESSION, const char *fmt, ...
) const noexcept __attribute__((format(printf, 3, 4)));
template<class... Args>
void log(const char *fmt, Args&&... args) const noexcept {
report(make_session(ERROR::NONE), fmt, std::forward<Args>(args)...);
}
ERROR report(
ERROR,
int line =__builtin_LINE(), const char *file =LEAF(__builtin_FILE()),
char const *function = __builtin_FUNCTION()
) const noexcept;
ERROR report(
ERROR, int code, char const *function, const char *message,
const char *file =LEAF(__builtin_FILE()), int line =__builtin_LINE()
) const noexcept;
ERROR report_bug(
const char *comment =nullptr,
const char *file =LEAF(__builtin_FILE()), int line =__builtin_LINE()
) const noexcept;
ERROR report_bad_request(
const char *comment =nullptr,
const char *file =LEAF(__builtin_FILE()), int line =__builtin_LINE()
) const noexcept;
ERROR report_memory_exhaustion(
const char *comment =nullptr,
const char *file =LEAF(__builtin_FILE()), int line =__builtin_LINE()
) const noexcept;
const RESULT &report(const RESULT &) noexcept;
const RESULT &report(size_t session_id, const RESULT &) noexcept;
const RESULT &report(const JACK *, const RESULT &) noexcept;
bool fuse(
const char *file =LEAF(__builtin_FILE()), int line =__builtin_LINE()
) const noexcept;
[[noreturn]] void die(
const char *file =LEAF(__builtin_FILE()), int line =__builtin_LINE()
) const noexcept;
static constexpr RESULT make_result(
int value, int, ERROR,
const char *comment, const char *function, const char *file, int line
) noexcept;
RESULT call_sigfillset(
sigset_t *set,
const char *file =LEAF(__builtin_FILE()), int line =__builtin_LINE()
) noexcept;
RESULT call_sigemptyset(
sigset_t *set,
const char *file =LEAF(__builtin_FILE()), int line =__builtin_LINE()
) noexcept;
RESULT call_epoll_create1(
int flags,
const char *file =LEAF(__builtin_FILE()), int line =__builtin_LINE()
) noexcept;
RESULT call_epoll_pwait(
int epfd, struct epoll_event *events, int maxevents, int timeout,
const sigset_t *sigmask,
const char *file =LEAF(__builtin_FILE()), int line =__builtin_LINE()
) noexcept;
RESULT call_getsockopt(
int sockfd, int level, int optname, void *optval, socklen_t *optlen,
const char *file =LEAF(__builtin_FILE()), int line =__builtin_LINE()
) noexcept;
RESULT call_accept4(
int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags,
const char *file =LEAF(__builtin_FILE()), int line =__builtin_LINE()
) noexcept;
RESULT call_getnameinfo(
const struct sockaddr *addr, socklen_t addrlen, char *host,
socklen_t hostlen, char *serv, socklen_t servlen, int flags,
const char *file =LEAF(__builtin_FILE()), int line =__builtin_LINE()
) noexcept;
RESULT call_shutdown(
int sockfd, int how,
const char *file =LEAF(__builtin_FILE()), int line =__builtin_LINE()
) noexcept;
RESULT call_listen(
int sockfd, int backlog,
const char *file =LEAF(__builtin_FILE()), int line =__builtin_LINE()
) noexcept;
RESULT call_getsockname(
int sockfd, struct sockaddr *addr, socklen_t *addrlen,
const char *file =LEAF(__builtin_FILE()), int line =__builtin_LINE()
) noexcept;
RESULT call_epoll_ctl(
int epfd, int op, int fd, struct epoll_event *event,
const char *file =LEAF(__builtin_FILE()), int line =__builtin_LINE()
) noexcept;
RESULT call_pthread_sigmask(
int how, const sigset_t *set, sigset_t *oldset,
const char *file =LEAF(__builtin_FILE()), int line =__builtin_LINE()
) const noexcept;
RESULT call_getaddrinfo(
const char *node, const char *service, const struct addrinfo *hints,
struct addrinfo **res,
const char *file =LEAF(__builtin_FILE()), int line =__builtin_LINE()
) noexcept;
RESULT call_socket(
int domain, int type, int protocol,
const char *file =LEAF(__builtin_FILE()), int line =__builtin_LINE()
) noexcept;
RESULT call_setsockopt(
int sockfd, int level, int optname, const void *optval,
socklen_t optlen,
const char *file =LEAF(__builtin_FILE()), int line =__builtin_LINE()
) noexcept;
RESULT call_bind(
int sockfd, const struct sockaddr *addr, socklen_t addrlen,
const char *file =LEAF(__builtin_FILE()), int line =__builtin_LINE()
) noexcept;
RESULT call_connect(
int sockfd, const struct sockaddr *addr, socklen_t addrlen,
const char *file =LEAF(__builtin_FILE()), int line =__builtin_LINE()
) noexcept;
RESULT call_close(
int fd,
const char *file =LEAF(__builtin_FILE()), int line =__builtin_LINE()
) noexcept;
void clear() noexcept;
ERROR err(ERROR) noexcept;
void (*log_callback)(SESSION, const char *text) noexcept;
INDEX indices[static_cast<size_t>(INDEX::TYPE::MAX_TYPES)];
PIPE buffers[static_cast<size_t>(BUFFER::MAX_BUFFERS)];
struct MEMPOOL {
MEMORY *free[sizeof(size_t) * BITS_PER_BYTE];
MEMORY *list;
size_t usage;
size_t top;
size_t cap;
bool oom:1;
} mempool;
static constexpr struct MEMPOOL make_mempool() noexcept;
EVENT handled;
ERROR errored;
size_t last_jack_id;
size_t jack_count;
struct BITSET {
bool alerted:1;
bool timeout:1;
bool reindex:1;
} bitset;
sigset_t sigset_all;
sigset_t sigset_none;
public:
mutable uint8_t fuses[768];
};
inline bool operator!(SOCKETS::ERROR error) noexcept {
return error == static_cast<SOCKETS::ERROR>(0);
}
inline bool operator!(SOCKETS::RESULT result) noexcept {
return result.error != SOCKETS::ERROR::NONE || result.code != 0;
}
inline bool operator!(SOCKETS::SESSION session) noexcept {
return session.valid == false;
}
inline SOCKETS::SOCKETS() noexcept :
log_callback(nullptr), indices{}, buffers{}, mempool{make_mempool()},
handled{}, errored{}, last_jack_id{}, jack_count{}, bitset{}, sigset_all{},
sigset_none{}, fuses{} {
}
inline SOCKETS::~SOCKETS() {
if (mempool.usage > sizeof(SOCKETS)) {
log(
"memory usage remains at %lu byte%s (leak?)",
mempool.usage, mempool.usage == 1 ? "" : "s"
);
}
for (INDEX &index : indices) {
if (index.type == INDEX::TYPE::NONE) {
continue;
}
log(
"%s\n", "destroying instance without having it deinitialized first"
);
break;
}
}
inline void SOCKETS::clear() noexcept {
errored = ERROR::NONE;
handled = EVENT::NONE;
for (PIPE &buffer : buffers) {
destroy(buffer);
}
for (INDEX &index : indices) {
if (index.table) {
destroy_and_delete(index.table, index.buckets);
index.table = nullptr;
}
index.buckets = 0;
index.entries = 0;
index.type = INDEX::TYPE::NONE;
}
if (mempool.list) {
report_bug(
// We should have already explicitly deallocated all memory.
);
while (mempool.list) {
deallocate(*mempool.list);
}
}
for (MEMORY *&free : mempool.free) {
while (free) {
deallocate(*free);
}
}
mempool.usage = sizeof(SOCKETS);
mempool.top = mempool.usage;
last_jack_id = 0;
jack_count = 0;
bitset = {};
std::fill(fuses, fuses+sizeof(fuses), 0);
}
inline bool SOCKETS::init() noexcept {
for (INDEX &index : indices) {
if (index.type != INDEX::TYPE::NONE) {
log("%s: already initialized", __FUNCTION__);
return false;
}
}
if (!report(call_sigfillset(&sigset_all))
|| !report(call_sigemptyset(&sigset_none))) {
return false;
}
clear();
for (INDEX &index : indices) {
index.type = static_cast<INDEX::TYPE>(&index - &indices[0]);
switch (index.type) {
default: {
index.buckets = 1;
index.multimap = false;
index.autogrow = true;
break;
}
case INDEX::TYPE::EVENT_DESCRIPTOR: {
index.buckets = static_cast<size_t>(EVENT::MAX_EVENTS);
index.multimap = true;
index.autogrow = false;
break;
}
}
switch (index.type) {
case INDEX::TYPE::NONE: continue;
case INDEX::TYPE::EVENT_DESCRIPTOR:
case INDEX::TYPE::DESCRIPTOR_JACK:
case INDEX::TYPE::SESSION_JACK:
case INDEX::TYPE::RESOURCE_MEMORY: {
index.table = allocate_tables(index.buckets);
break;
}
default: die();
}
if (index.table == nullptr) {
report_memory_exhaustion();
clear();
return false;
}
for (size_t j=0; j<index.buckets; ++j) {
INDEX::TABLE &table = index.table[j];
PIPE &key_pipe = table.key;
PIPE &val_pipe = table.value;
key_pipe.type = PIPE::TYPE::KEY;
switch (index.type) {
case INDEX::TYPE::SESSION_JACK:
case INDEX::TYPE::DESCRIPTOR_JACK: {
val_pipe.type = PIPE::TYPE::JACK_PTR;
break;
}
case INDEX::TYPE::RESOURCE_MEMORY: {
val_pipe.type = PIPE::TYPE::MEMORY_PTR;
break;
}
case INDEX::TYPE::EVENT_DESCRIPTOR: {
val_pipe.type = PIPE::TYPE::INT;
break;
}
default: die();
}
if (val_pipe.type == PIPE::TYPE::NONE) {
clear();
report_bug();
return false;
}
}
}
for (PIPE &pipe : buffers) {
switch (static_cast<BUFFER>(&pipe - &buffers[0])) {
case BUFFER::NEXT_ERROR: {
pipe.type = PIPE::TYPE::INT;
break;
}
case BUFFER::MAX_BUFFERS: die();
}
}
SESSION epoll_session{ create_epoll() };
if (!epoll_session.valid) {
log(
"%s: %s, %s (%s:%d)", __FUNCTION__,
"epoll jack could not be created", to_string(epoll_session.error),
LEAF(__FILE__), __LINE__
);
return false;
}
return true;
}
inline bool SOCKETS::deinit() noexcept {
if (!find_epoll_jack()) {
log("%s: already deinitialized", __FUNCTION__);
return false;
}
bool success = true;
INDEX &descriptor_jack = get_index(INDEX::TYPE::DESCRIPTOR_JACK);
for (size_t bucket=0; bucket<descriptor_jack.buckets; ++bucket) {
while (descriptor_jack.table[bucket].key.size) {
JACK *const jack{
to_jack(
get_last(descriptor_jack.table[bucket].value)
)
};
close_and_release(*jack);
}
}
clear();
return success;
}
inline void SOCKETS::set_logger(
void (*callback)(SOCKETS::SESSION, const char *) noexcept
) noexcept {
log_callback = callback;
}
inline void SOCKETS::set_memcap(size_t bytes) noexcept {
mempool.cap = bytes;
}
inline size_t SOCKETS::get_memcap() const noexcept {
return mempool.cap;
}
inline size_t SOCKETS::get_memtop() const noexcept {
return mempool.top;
}
inline SOCKETS::ERROR SOCKETS::set_intake(
size_t sid, size_t bytes, const char *file, int line
) noexcept {
JACK *jack = find_jack(make_session_query(sid));
if (jack) {
jack->intake = bytes;
return ERROR::NONE;
}
return fuse() ? report(
make_session(sid, ERROR::BAD_REQUEST),
"session not found (%s:%d)", file, line
) : ERROR::BAD_REQUEST;
}
inline SOCKETS::SESSION SOCKETS::listen(
const char *port, int family, const std::initializer_list<int> options,
int flags
) noexcept {
return listen(nullptr, port, family, AI_PASSIVE|flags, options);
}
inline struct SOCKETS::ALERT SOCKETS::next_alert() noexcept {
size_t session;
bitset.alerted = false;
while (( session = next_connection() ) != 0) {
return make_alert(session, EVENT::CONNECTION);
}
while (( session = next_incoming() ) != 0) {
return make_alert(session, EVENT::INCOMING);
}
while (( session = next_disconnection() ) != 0) {
return make_alert(session, EVENT::DISCONNECTION);
}
return make_alert(0, EVENT::NONE, false);
}
inline size_t SOCKETS::next_connection() noexcept {
JACK *const jack = find_jack(make_event_query(EVENT::CONNECTION));
if (jack) {
rem_event(*jack, EVENT::CONNECTION);
return jack->id;
}
return 0;
}
inline size_t SOCKETS::next_disconnection() noexcept {
if (find_jack(make_event_query(EVENT::CONNECTION))) {
// We postpone reporting any disconnections until the application
// has acknowledged all the new incoming connections. This prevents
// us from reporting a disconnection event before its respective
// connection event is reported.
return 0;
}
JACK *const jack = find_jack(make_event_query(EVENT::DISCONNECTION));
if (jack) {
set_event(*jack, EVENT::CLOSE);
rem_event(*jack, EVENT::DISCONNECTION);
return jack->id;
}
return 0;
}
inline size_t SOCKETS::next_incoming() noexcept {
JACK *const jack = find_jack(make_event_query(EVENT::INCOMING));
if (jack) {
rem_event(*jack, EVENT::INCOMING);
return jack->id;
}
return 0;
}
inline bool SOCKETS::is_listener(const JACK &jack) const noexcept {
return jack.bitset.listener;
}
inline bool SOCKETS::is_listener(size_t sid) const noexcept {
const JACK *const jack = find_jack(make_session_query(sid));
return jack ? is_listener(*jack) : false;
}
inline SOCKETS::SESSION SOCKETS::get_listener(size_t sid) const noexcept {
const JACK *const jack = find_jack(make_session_query(sid));
if (!jack) {
return make_session(ERROR::NONE);
}
const JACK *const parent{
find_jack(make_descriptor_query(jack->parent.descriptor))
};