-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvelar.cpp
More file actions
1262 lines (1021 loc) · 35 KB
/
Copy pathvelar.cpp
File metadata and controls
1262 lines (1021 loc) · 35 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
#include <iostream>
#include "velar.h"
#ifdef _WIN32
//These are needed by IPV6
#pragma comment(lib, "ws2_32.lib")
/*
* Use RAII to initialize winsock. Any application using this library won't have to
* worry about that.
*/
class WSInit {
public:
WSInit() {
WSADATA wsa;
if (::WSAStartup(MAKEWORD(2, 2), &wsa) != 0) {
throw std::runtime_error("WSAStartup() failed.");
}
}
~WSInit() {
::WSACleanup();
}
};
static WSInit __wsa_init;
#else
#include <arpa/inet.h>
#include <sys/mman.h>
#include <sys/stat.h>
#endif
ByteBuffer::~ByteBuffer() {}
void ByteBuffer::put(const char* from, size_t offset, size_t length) {
if (length > remaining()) {
throw std::out_of_range("Insufficient space remaining.");
}
::memcpy(m_array + m_position, from + offset, length);
m_position += length;
}
void ByteBuffer::put(std::string_view sv) {
put(sv.data(), 0, sv.length());
}
void ByteBuffer::put(char ch) {
if (!has_remaining()) {
throw std::out_of_range("Insufficient space remaining.");
}
m_array[m_position] = ch;
++m_position;
}
void ByteBuffer::put(uint16_t i) {
uint16_t n = htons(i);
put((const char*)&n, 0, sizeof(uint16_t));
}
void ByteBuffer::put(uint32_t i) {
uint32_t n = htonl(i);
put((const char*)&n, 0, sizeof(uint32_t));
}
void ByteBuffer::put(uint64_t i) {
#if defined _WIN32 || defined __APPLE__
uint64_t n = htonll(i);
#else
uint64_t n = ::htobe64(i);
#endif
put((const char*)&n, 0, sizeof(uint64_t));
}
/*
* Copies length number of bytes from the current position of the buffer
* into the destination at a given offset of the destination.
*
* If insufficient bytes remain in the buffer, that is, remaining() < length, then
* a std::out_of_range exception is thrown. Otherwise, the position is moved
* forward by length.
*/
void ByteBuffer::get(const char* to, size_t offset, size_t length) {
if (remaining() < length) {
throw std::out_of_range("Insufficient data remaining.");
}
::memcpy((void*) (to + offset), m_array + m_position, length);
m_position += length;
}
void ByteBuffer::get(char& ch) {
if (!has_remaining()) {
throw std::out_of_range("Insufficient data remaining.");
}
ch = m_array[m_position];
++m_position;
}
/*
* Shares length bytes from the buffer with the give string_view.
* No data is copied. That makes this one of the fastest ways to read
* data from the buffer.
*
* If there's insufficient data left to be read, that is, remaining() < length,
* then a std::out_of_range exception is thrown. Otherwise, the position is moved
* forward by length.
*/
void ByteBuffer::get(std::string_view& sv, size_t length) {
if (remaining() < length) {
throw std::out_of_range("Insufficient data remaining.");
}
sv = { m_array + m_position, length };
m_position += length;
}
/*
* Shares all the remaining data with the given string_view.
* No data is copied. That makes this one of the fastest ways to read
* data from the buffer.
*
* If there's no remaining data left to be read, that is, has_remaining() == false,
* then a std::out_of_range exception is thrown. Otherwise, the position is moved
* to the end of the buffer.
*/
void ByteBuffer::get(std::string_view& sv) {
if (!has_remaining()) {
throw std::out_of_range("Insufficient data remaining.");
}
sv = { m_array + m_position, remaining()};
m_position += remaining();
}
void ByteBuffer::get(uint16_t& i) {
uint16_t n = 0;
get((const char*)&n, 0, sizeof(uint16_t));
i = ntohs(n);
}
void ByteBuffer::get(uint32_t& i) {
uint32_t n = 0;
get((const char*)&n, 0, sizeof(uint32_t));
i = ntohl(n);
}
void ByteBuffer::get(uint64_t& i) {
uint64_t n = 0;
get((const char*)&n, 0, sizeof(uint64_t));
#if defined _WIN32 || defined __APPLE__
i = ntohll(n);
#else
i = be64toh(n);
#endif
}
HeapByteBuffer::HeapByteBuffer(size_t sz) {
m_array = (char*) ::malloc(sz);
if (m_array == NULL) {
throw std::runtime_error("malloc() failed.");
}
m_capacity = sz;
m_position = 0;
m_limit = sz;
}
HeapByteBuffer::~HeapByteBuffer() {
if (m_array != NULL) {
::free(m_array);
m_array = NULL;
}
}
WrappedByteBuffer::WrappedByteBuffer(char* data, size_t length) {
m_array = data;
m_capacity = length;
m_limit = length;
m_position = 0;
}
MappedByteBuffer::MappedByteBuffer(const char* file_name, bool read_only, size_t max_size) {
#ifdef _WIN32
file_handle = ::CreateFileA(
file_name,
(read_only ? GENERIC_READ : (GENERIC_READ | GENERIC_WRITE)),
0,
NULL,
//If read only, then it must exist. Otherwise, we create it.
(read_only ? OPEN_EXISTING : OPEN_ALWAYS),
FILE_ATTRIBUTE_NORMAL,
NULL);
if (file_handle == INVALID_HANDLE_VALUE) {
cleanup(); //Do manual cleanup. Dtor won't be called.
throw std::system_error(::GetLastError(), std::system_category(), "CreateFileA failed.");
}
LARGE_INTEGER file_size;
if (!::GetFileSizeEx(file_handle, &file_size)) {
cleanup();
throw std::system_error(::GetLastError(), std::system_category(), "GetFileSizeEx failed.");
}
if (read_only && max_size == 0 && file_size.QuadPart == 0) {
cleanup();
throw std::runtime_error("Zero length file cannot be mapped in Windows.");
}
map_handle = ::CreateFileMappingA(
file_handle,
NULL,
(read_only ? PAGE_READONLY : PAGE_READWRITE),
max_size >> 32,
(DWORD) max_size,
NULL);
if (map_handle == NULL) {
cleanup(); //Do manual cleanup. Dtor won't be called.
throw std::system_error(::GetLastError(), std::system_category(), "CreateFileMappingA failed.");
}
m_array = (char*) ::MapViewOfFile(map_handle,
read_only ? FILE_MAP_READ : (FILE_MAP_WRITE),
0,
0,
0);
if (m_array == NULL) {
cleanup();
throw std::system_error(::GetLastError(), std::system_category(), "MapViewOfFile failed.");
}
m_capacity = (max_size == 0 ? file_size.QuadPart : max_size);
m_limit = m_capacity;
m_position = 0;
#else
file_handle = ::open(file_name, read_only ? O_RDONLY : (O_CREAT | O_RDWR), 0666);
if (file_handle < 0) {
cleanup();
throw std::system_error(errno, std::generic_category(), "open() failed");
return;
}
struct stat sbuf;
if (stat(file_name, &sbuf) == -1) {
cleanup();
throw std::system_error(errno, std::generic_category(), "stat() failed");
return;
}
size_t file_size = sbuf.st_size;
if (max_size > file_size) {
//Extend the file to max_size.
if (ftruncate(file_handle, max_size) == -1) {
cleanup();
throw std::system_error(errno, std::generic_category(), "ftruncate() failed");
return;
}
}
void *start = ::mmap(nullptr,
max_size == 0 ? file_size : max_size,
read_only ? PROT_READ : (PROT_READ | PROT_WRITE),
MAP_FILE | MAP_SHARED,
file_handle,
0);
if (start == MAP_FAILED) {
cleanup();
throw std::system_error(errno, std::generic_category(), "mmap() failed");
return;
}
//We can close the file down now
::close(file_handle);
file_handle = -1;
m_array = (char*) start;
m_capacity = (max_size == 0 ? file_size : max_size);
m_limit = m_capacity;
m_position = 0;
#endif
}
MappedByteBuffer::~MappedByteBuffer() {
cleanup();
}
void MappedByteBuffer::cleanup() {
#ifdef _WIN32
BOOL status;
if (map_handle != NULL) {
if (m_array != NULL) {
status = ::UnmapViewOfFile(m_array);
}
status = ::CloseHandle(map_handle);
map_handle = NULL;
m_array = NULL;
}
if (file_handle != INVALID_HANDLE_VALUE) {
status = ::CloseHandle(file_handle);
file_handle = INVALID_HANDLE_VALUE;
}
#else
if (m_array != NULL) {
if (::munmap((void*) m_array, m_capacity) < 0) {
perror("munmap() failed");
}
m_array = NULL;
}
if (file_handle >= 0) {
if (::close(file_handle) < 0) {
perror("close() failed.");
}
file_handle = -1;
}
#endif
}
static void set_nonblocking(SOCKET socket) {
#ifdef _WIN32
u_long non_block = 1;
int status = ::ioctlsocket(socket, FIONBIO, &non_block);
if (status != NO_ERROR) {
throw std::runtime_error("Failed to make socket non-blocking.");
}
#else
int status = ::fcntl(socket, F_SETFL, O_NONBLOCK);
if (status < 0) {
throw std::runtime_error("Failed to make socket non-blocking.");
}
#endif
}
static void check_socket_error(int status, const char* msg) {
#ifdef _WIN32
if (status == SOCKET_ERROR) {
throw std::runtime_error(msg);
}
#else
if (status < 0) {
::perror(msg);
throw std::runtime_error(msg);
}
#endif
}
void free_addrinfo(struct addrinfo* p) {
if (p != NULL) {
freeaddrinfo(p);
}
}
/*
* Creates a UDP socket. The socket remembers the given server address and port.
* Any subsequent call to sendto() will use this address. The address of the server
* can be a hostname, ipv4 or ipv6 address.
*
* After the first call to sendto() a UDP socket gets bound to the server's address and port.
* Which means, if you call recvfrom() after that the data is read from the server.
*
* Once you no longer need to communicate with the server cancel the socket.
*/
std::shared_ptr<DatagramClientSocket> Selector::start_udp_client(const char* address, int port, std::shared_ptr<SocketAttachment> attachment) {
char port_str[128];
snprintf(port_str, sizeof(port_str), "%d", port);
struct addrinfo hints {}, * res{};
/*
* We take a numeric port number and not a
* service name like "http" or "ftp" for port.
* This will tell getaddrinfo() not to do any
* service name resolution making it slightly faster.
*/
hints.ai_flags = AI_NUMERICSERV;
/*
* This will cause getaddrinfo() to return both ipv4 and ipv6
* address if available.
*/
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM; //UDP
int status = ::getaddrinfo(address, port_str, &hints, &res);
/*
* getaddrinfo() is strange in a way since it may return a positive
* value in case of an error. Any non-zero value indicates an error.
*/
if (status != 0 || res == NULL) {
throw std::runtime_error("Failed to resolve address.");
}
/*
* Creating the socket object here willmake sure res gets freed up
* no matter what happens.
*/
auto client = std::make_shared<DatagramClientSocket>(res);
set_nonblocking(client->fd());
client->attachment(attachment);
m_sockets.insert(client);
return client;
}
/*
* Creates a new TCP socket and connects it to a server listening at the given
* address and port. The address can be a host name, ipv4 or ipv6 IP address.
* The attachment is set for the newly created client socket.
*
* To disconnect from the server gracefully, cancel the client socket.
*/
std::shared_ptr<Socket> Selector::start_client(const char* address, int port, std::shared_ptr<SocketAttachment> attachment) {
char port_str[128];
snprintf(port_str, sizeof(port_str), "%d", port);
struct addrinfo hints {}, *res{};
/*
* We take a numeric port number and not a
* service name like "http" or "ftp" for port.
* This will tell getaddrinfo() not to do any
* service name resolution making it slightly faster.
*/
hints.ai_flags = AI_NUMERICSERV;
/*
* This will cause getaddrinfo() to return both ipv4 and ipv6
* address if available.
*/
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
int status = ::getaddrinfo(address, port_str, &hints, &res);
/*
* getaddrinfo() is strange in a way since it may return a positive
* value in case of an error. Any non-zero value indicates an error.
*/
if (status != 0 || res == NULL) {
throw std::runtime_error("Failed to resolve address.");
}
/*
* The addrinfo res object is a linked list. It has all
* resolved addresses. For example, it will have both ipv4 and ipv6
* addresses if available. We can iterate through the addresses using res->next.
* Below, we go with the first address in the list, which can be either ipv4 or ipv6.
* A more robust implementation will try the next address (res->next) if
* connect() fails.
*/
/*
* Use RAII to free the address. This makes the code below much simpler.
*/
auto addr_resource = std::unique_ptr<struct addrinfo, void(*)(struct addrinfo*)>(res, free_addrinfo);
auto client = std::make_shared<Socket>(res->ai_family, res->ai_socktype, res->ai_protocol);
client->attachment(attachment);
client->set_connection_pending(true);
set_nonblocking(client->fd());
status = ::connect(client->fd(), res->ai_addr, res->ai_addrlen);
/*
* It is normal for a nonblocking socket to not complete connection immediately.
* This is indicated by an error but we should not abort.
*
* Checking for in progress connection differes between Winsock and BSD socket.
*/
if (status < 0) {
#ifdef _WIN32
auto err = ::WSAGetLastError();
if (err != WSAEWOULDBLOCK) {
throw std::runtime_error("Failed to connect.");
}
#else
if (errno != EINPROGRESS) {
throw std::runtime_error("Failed to connect.");
}
#endif
}
m_sockets.insert(client);
return client;
}
/*
* Starts a UDP server and makes it join a multicast group identified by the group's
* IP address group_ip. The group's address can be any valid ipv4 or ipv6 IP address.
*/
std::shared_ptr<Socket> Selector::start_multicast_server(const char* group_ip, int port, std::shared_ptr<SocketAttachment> attachment) {
auto receiver = start_udp_server(port, attachment);
// Join the multicast group
struct ipv6_mreq mreq6 {};
struct ip_mreq mreq4 {};
//Set the multicast group address
if (inet_pton(AF_INET6, group_ip, &mreq6.ipv6mr_multiaddr) == 1) {
mreq6.ipv6mr_interface = 0;
//Join the group
int status = ::setsockopt(receiver->fd(), IPPROTO_IPV6, IPV6_JOIN_GROUP, (const char*)&mreq6, sizeof(mreq6));
check_socket_error(status, "Failed to join ipv6 multicast group.");
}
else if (inet_pton(AF_INET, group_ip, &mreq4.imr_multiaddr.s_addr) == 1) {
mreq4.imr_interface.s_addr = INADDR_ANY;
//Join the group
int status = ::setsockopt(receiver->fd(), IPPROTO_IP, IP_ADD_MEMBERSHIP, (const char*)&mreq4, sizeof(mreq4));
check_socket_error(status, "Failed to join ipv4 multicast group.");
}
else {
throw std::runtime_error("The group IP address is not a valid ipv6 or ipv4 address.");
}
return receiver;
}
/*
* Starts a UDP socket and binds to the given port. Clients should be able to
* connect to it using either ipv4 or ipv6 address.
*
* The socket's readbility event reporting is enabled by default. Which means,
* the server can start accepting request messages from clients right away.
*/
std::shared_ptr<Socket> Selector::start_udp_server(int port, std::shared_ptr<SocketAttachment> attachment) {
// Create a UDP socket
auto receiver = std::make_shared<Socket>(AF_INET6, SOCK_DGRAM, 0);
receiver->attachment(attachment);
/*
* This will make the socket bind to both ipv6 and ipv4 address.
* This way, a client can connect using either ipv4 or ipv6 address.
*/
int optval = 0;
int status = ::setsockopt(receiver->fd(), IPPROTO_IPV6, IPV6_V6ONLY, (char*)&optval, sizeof(optval));
check_socket_error(status, "Failed to disable IPV6_V6ONLY.");
int reuse = 1;
status = ::setsockopt(receiver->fd(), SOL_SOCKET, SO_REUSEADDR, (const char*) & reuse, sizeof reuse);
check_socket_error(status, "Failed to set SO_REUSEADDR.");
#ifndef _WIN32
status = ::setsockopt(receiver->fd(), SOL_SOCKET, SO_REUSEPORT, (const char*) &reuse, sizeof reuse);
check_socket_error(receiver->fd(), "Failed to set SO_REUSEPORT.");
#endif
// Bind the socket to the multicast port
struct sockaddr_in6 addr {};
addr.sin6_family = AF_INET6;
addr.sin6_addr = in6addr_any;
addr.sin6_port = htons(port);
status = ::bind(receiver->fd(), (const struct sockaddr*) &addr, sizeof(addr));
check_socket_error(status, "Failed to bind to port.");
//Turn this on since all receivers need to read
receiver->report_readable(true);
m_sockets.insert(receiver);
return receiver;
}
/*
* Starts a TCP socket and binds to the given port. Clients should be able to
* connect to it using either ipv4 or ipv6 address.
*
* The socket's readbility event reporting is enabled by default. Which means,
* the server can start accepting clients right away.
*
* To shutdown the server just cancel the server socket.
*/
std::shared_ptr<Socket> Selector::start_server(int port, std::shared_ptr<SocketAttachment> attachment) {
auto server = std::make_shared<Socket>(AF_INET6, SOCK_STREAM, IPPROTO_TCP);
server->attachment(attachment);
set_nonblocking(server->fd());
int reuse = 1;
int status = ::setsockopt(server->fd(), SOL_SOCKET, SO_REUSEADDR, (const char*) &reuse, sizeof reuse);
check_socket_error(status, "Failed to set SO_REUSEADDR.");
#ifndef _WIN32
status = ::setsockopt(server->fd(), SOL_SOCKET, SO_REUSEPORT, (const char*)&reuse, sizeof reuse);
check_socket_error(status, "Failed to set SO_REUSEPORT.");
#endif
/*
* This will allow IPV4 mapped addresses.
*/
int optval = 0;
status = ::setsockopt(server->fd(), IPPROTO_IPV6, IPV6_V6ONLY, (char*)&optval, sizeof(optval));
check_socket_error(status, "Failed to disable IPV6_V6ONLY.");
struct sockaddr_in6 addr {}; //Important to zero out the address
addr.sin6_family = AF_INET6;
addr.sin6_addr = ::in6addr_any;
addr.sin6_port = htons(port);
status = ::bind(server->fd(), (struct sockaddr*) &addr, sizeof(addr));
check_socket_error(status, "Failed to bind to port.");
status = ::listen(server->fd(), 10);
check_socket_error(status, "Failed to listen.");
//Turn this on since all servers will need to catch accept event
server->report_accpeptable(true);
m_sockets.insert(server);
return server;
}
/*
* Accepts a client that has connected to the given server's socket.
* A new client socket is created and the attachment is set for the client.
* The selector begins monitoring the client socket for events until the client
* socket is cancelled.
*/
std::shared_ptr<Socket> Selector::accept(std::shared_ptr<Socket> server, std::shared_ptr<SocketAttachment> attachment) {
SOCKET client_fd = ::accept(server->fd(), NULL, NULL);
if (client_fd == INVALID_SOCKET) {
throw std::runtime_error("accept() failed.");
}
/*
* Create the Socket early so RAII can clean it up in
* case of a problem.
*/
auto client = std::make_shared<Socket>(client_fd);
client->attachment(attachment);
set_nonblocking(client_fd);
m_sockets.insert(client);
return client;
}
void Selector::populate_fd_set(fd_set& read_fd_set, fd_set& write_fd_set, fd_set& except_fd_set) {
FD_ZERO(&read_fd_set);
FD_ZERO(&write_fd_set);
FD_ZERO(&except_fd_set);
for (auto& s : m_sockets) {
if (s->is_report_readable() || s->is_report_acceptable()) {
FD_SET(s->fd(), &read_fd_set);
}
if (s->is_report_writable()) {
FD_SET(s->fd(), &write_fd_set);
}
if (s->is_connection_pending()) {
/*
* Detecting connect() completion status is platform dependent.
* In Winsock, we use exception fd set for error and write fd set for success.
* In BSD socket, we query writable event and then test for SO_ERROR.
*/
#ifdef _WIN32
FD_SET(s->fd(), &except_fd_set);
#endif
FD_SET(s->fd(), &write_fd_set);
}
}
}
void Selector::purge_sokets() {
for (auto& s : m_canceled_sockets) {
m_sockets.erase(s);
}
m_canceled_sockets.clear();
}
int Selector::select(long timeout) {
fd_set read_fd_set, write_fd_set, except_fd_set;
struct timeval t;
t.tv_sec = timeout;
t.tv_usec = 0;
purge_sokets();
populate_fd_set(read_fd_set, write_fd_set, except_fd_set);
int num_events = ::select(
FD_SETSIZE,
&read_fd_set,
&write_fd_set,
NULL,
timeout > 0 ? &t : NULL);
#ifdef _WIN32
if (num_events == SOCKET_ERROR) {
int status = ::WSAGetLastError();
if (status == WSAEINTR || status == WSAEINPROGRESS) {
return num_events;
}
else {
throw std::runtime_error("select() failed.");
}
}
#else
if (num_events < 0) {
if (errno == EINTR) {
//A signal was handled
return num_events;
}
else {
throw std::runtime_error("select() failed.");
}
}
#endif
if (num_events == 0) {
//Timeout
return num_events;
}
for (auto& s : m_sockets) {
if (s->is_connection_pending()) {
/*
* Test for connect() completion status.
*/
#ifdef _WIN32
/*
* It appears that both write fd set and except fd set are set for
* the socket for a successful connection. We must test for the
* write fd set before except fd set to determine success.
*/
if (FD_ISSET(s->fd(), &write_fd_set)) {
s->set_connection_success(true);
s->set_connection_pending(false);
}
else if ((FD_ISSET(s->fd(), &except_fd_set))) {
//connect() has failed
s->set_connection_failed(true);
s->set_connection_pending(false);
}
#else
if (FD_ISSET(s->fd(), &write_fd_set)) {
int valopt;
socklen_t lon = sizeof(int);
if (::getsockopt(s->fd(), SOL_SOCKET, SO_ERROR, (void*)(&valopt), &lon) < 0) {
throw std::runtime_error("Error in getsockopt().");
}
if (valopt) {
s->set_connection_failed(true);
s->set_connection_pending(false);
}
else {
s->set_connection_success(true);
s->set_connection_pending(false);
}
}
#endif
if (s->is_connection_pending()) {
//This should not happen.
throw std::runtime_error("Invalid state.");
}
}
else {
s->set_connection_success(false);
//For a server socket, readable means new client
//waiting to be accepted
if (s->is_report_acceptable()) {
s->set_acceptable((FD_ISSET(s->fd(), &read_fd_set)));
} else {
s->set_readable((FD_ISSET(s->fd(), &read_fd_set)));
}
s->set_writable((FD_ISSET(s->fd(), &write_fd_set)));
}
}
return num_events;
}
/*
* Removes this socket from the set of sockets monitored by the selector.
* The socket will be eventually closed and destroyed.
*/
void Selector::cancel_socket(std::shared_ptr<Socket> socket) {
m_canceled_sockets.insert(socket);
}
Socket::Socket(SOCKET fd) : m_fd(fd) {
}
Socket::Socket(int domain, int type, int protocol) : m_fd(INVALID_SOCKET) {
m_fd = ::socket(domain, type, protocol);
if (m_fd == INVALID_SOCKET) {
throw std::runtime_error("Failed to create a socket.");
}
m_io_flag.reset();
}
Socket::~Socket() {
if (m_fd != INVALID_SOCKET) {
#ifdef _WIN32
::closesocket(m_fd);
#else
::close(m_fd);
#endif
m_fd = INVALID_SOCKET;
}
}
DatagramClientSocket::DatagramClientSocket(addrinfo* res) :
server_address(res),
Socket(res->ai_family, res->ai_socktype, res->ai_protocol)
{
}
DatagramClientSocket::~DatagramClientSocket() {
if (server_address != NULL) {
::freeaddrinfo(server_address);
server_address = NULL;
}
}
/*
* Writes data from the buffer to the address and port that
* this socket was constructed with. The buffer's position is
* moved forward by the number of bytes written. The limit
* remains unchanged. If not all the data could be written,
* calling has_remaining() on the buffer will return true.
*/
int DatagramClientSocket::sendto(ByteBuffer& b) {
return sendto(b, server_address->ai_addr, server_address->ai_addrlen);
}
/*
* After the first time sendto() is called for a UDP socket it
* gets implicitly bound to the destination server's address and port.
* You can then call recvfrom(). This will receive data from the server where the
* original sendto() request was sent.
*
* The position of the buffer is moved forward by the number of bytes received.
* Limit is left unchanged. You should flip() the buffer before reading
* from it.
*/
int DatagramClientSocket::recvfrom(ByteBuffer& b) {
return recvfrom(b, nullptr, nullptr);
}
/*
* Reads data from this socket into the supplied ByteBuffer at the current position of the buffer.
* Upon a successful read the position of the buffer is incremented but limit remains unchanged.
* Before you retrieve data from the buffer you should call flip().
*
* When you try to read from a socket many things can happen. Winsock and BSD socket deal with
* these situations slightly differently. Here we normalize the situations by returning an
* uniform value for both platforms. Here are the possible cases:
*
* - Read was successful. In this case, the number of bytes read, a positive number, is returned.
* - An attempted read would lead to blocking. In this case 0 is returned.
* - The other party has disconnected gracefully, meaning they have closed their end of the socket. In this
* case a negative value is returned.
* - The other party has disconnected ungracefully, meaning somehow the connection was severed. In this case,
* we return a negative value.
*
* If a negative value is returned, then applications should treat the socket as unusuable.
* They should cancel the socket.
*/
int Socket::read(ByteBuffer& b) {
if (!b.has_remaining()) {
throw std::runtime_error("Buffer is full.");
}
#ifdef _WIN32
int bytes_read = ::recv(
m_fd,
b.array() + b.position(),
b.remaining(),
0);
if (bytes_read == SOCKET_ERROR) {
int err = ::WSAGetLastError();
if (err == WSAECONNRESET) {
//Ungraceful disconnect by the other party
return -1;
}
if (err == WSAEWOULDBLOCK) {
//Not an error really.
return 0;
}
else {
//A real error has taken place.
return -1;
}
}
#else
int bytes_read = ::read(
m_fd,
b.array() + b.position(),
b.remaining());
if (bytes_read < 0) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
//Not an error really.
return 0;
}
else {
//A real error has taken place.
return -1;
}
}
#endif
if (bytes_read == 0) {
/*