forked from cloudflarearchive/kyototycoon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ktsocket.cc
2084 lines (1931 loc) · 49.8 KB
/
ktsocket.cc
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
/*************************************************************************************************
* Network functions
* Copyright (C) 2009-2012 FAL Labs
* This file is part of Kyoto Tycoon.
* This program is free software: you can redistribute it and/or modify it under the terms of
* the GNU General Public License as published by the Free Software Foundation, either version
* 3 of the License, or any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License along with this program.
* If not, see <http://www.gnu.org/licenses/>.
*************************************************************************************************/
#include "ktsocket.h"
#include "ktsocketsec.h"
#include "myconf.h"
#if defined(_KT_EVENT_EPOLL)
extern "C" {
#include <sys/epoll.h>
}
#elif defined(_KT_EVENT_KQUEUE)
#include <sys/event.h>
#endif
namespace kyototycoon { // common namespace
/**
* Constants for implementation.
*/
namespace {
const int32_t BACKLOG = 1024; ///< backlog param for listen
const int32_t NAMEBUFSIZ = 256; ///< size of the name buffer
const int32_t IOBUFSIZ = 4096; ///< size of the IO buffer
const double WAITTIME = 0.1; ///< interval to check timeout
const int32_t RECVMAXSIZ = 1 << 30; ///< maximum size to receive
}
/**
* Hidden initializer.
*/
static int32_t _init_func() {
struct ::sigaction sa;
std::memset(&sa, 0, sizeof(sa));
sa.sa_handler = SIG_IGN;
sigemptyset(&sa.sa_mask);
::sigaction(SIGPIPE, &sa, NULL);
::sigset_t sigmask;
sigemptyset(&sigmask);
sigaddset(&sigmask, SIGPIPE);
::pthread_sigmask(SIG_BLOCK, &sigmask, NULL);
return 0;
}
int32_t _init_var = _init_func();
/**
* Socket internal.
*/
struct SocketCore {
const char* errmsg; ///< error message
int32_t fd; ///< file descriptor
std::string expr; ///< address expression
double timeout; ///< timeout
bool aborted; ///< flag for abortion
uint32_t evflags; ///< event flags
#if HAVE_SEC_CHANNEL
SecChannel *chan; ///< secure channel
#endif
char* buf; ///< receiving buffer
const char* rp; ///< reading pointer
const char* ep; ///< end pointer
};
/**
* ServerSocket internal.
*/
struct ServerSocketCore {
const char* errmsg; ///< error message
int32_t fd; ///< file descriptor
std::string expr; ///< address expression
double timeout; ///< timeout
bool aborted; ///< flag for abortion
uint32_t evflags; ///< event flags
#if HAVE_SEC_CHANNEL
SecChannel *chan; ///< secure channel
#endif
};
/**
* Poller internal.
*/
struct PollerCore {
#if defined(_KT_EVENT_EPOLL)
const char* errmsg; ///< error message
int32_t fd; ///< file descriptor
std::set<Pollable*> events; ///< monitored events
std::set<Pollable*> hits; ///< notified file descriptors
kc::SpinLock elock; ///< lock for events
bool aborted; ///< flag for abortion
#elif defined(_KT_EVENT_KQUEUE)
const char* errmsg; ///< error message
int32_t fd; ///< file descriptor
std::set<Pollable*> events; ///< monitored events
std::set<Pollable*> hits; ///< notified file descriptors
kc::SpinLock elock; ///< lock for events
bool aborted; ///< flag for abortion
#else
const char* errmsg; ///< error message
bool open; ///< flag for open
std::set<Pollable*> events; ///< monitored events
std::set<Pollable*> hits; ///< notified file descriptors
kc::SpinLock elock; ///< lock for events
::pthread_t th; ///< main thread ID
bool aborted; ///< flag for abortion
#endif
};
/**
* Dummy signal handler.
* @param signum the signal number.
*/
static void dummysighandler(int signum);
/**
* Parse an address expression.
* @param expr an address expression.
* @param buf the pointer to the buffer into which the address is written.
* @param portp the pointer to the variable into which the port is assigned.
*/
static void parseaddr(const char* expr, char* addr, int32_t* portp);
/**
* Check whether an error code is retriable.
* @param ecode the error code.
* @return true if the error code is retriable, or false if not.
*/
static bool checkerrnoretriable(int32_t ecode);
/**
* Set options of a sockeet.
* @param fd the file descriptor of the socket.
* @return true on success, or false on failure.
*/
static bool setsocketoptions(int32_t fd);
/**
* Clear the error status of a socket.
* @param fd the file descriptor of the socket.
*/
static void clearsocketerror(int32_t fd);
/**
* Wait an I/O event of a socket.
* @param fd the file descriptor of the socket.
* @param mode the kind of events: 0 for reading, 1 for writing, 2 for exception.
* @param timeout the timeout in seconds.
* @return true on success, or false on failure.
*/
static bool waitsocket(int32_t fd, uint32_t mode, double timeout);
/**
* Set the error message of a socket.
* @param core the inner condition of the socket.
* @param msg the error message.
*/
static void sockseterrmsg(SocketCore* core, const char* msg);
/**
* Receive one byte from a socket.
* @param core the inner condition of the socket.
* @return the received byte or -1 on failure.
*/
static int32_t sockgetc(SocketCore* core);
/**
* Set the error message of a server.
* @param core the inner condition of the server.
* @param msg the error message.
*/
static void servseterrmsg(ServerSocketCore* core, const char* msg);
/**
* Set the error message of a poller.
* @param core the inner condition of the poller.
* @param msg the error message.
*/
static void pollseterrmsg(PollerCore* core, const char* msg);
/**
* Default constructor.
*/
Socket::Socket() {
_assert_(true);
SocketCore* core = new SocketCore;
core->errmsg = NULL;
core->fd = -1;
core->timeout = kc::UINT32MAX;
core->aborted = false;
core->buf = NULL;
core->rp = NULL;
core->ep = NULL;
core->evflags = 0;
#if HAVE_SEC_CHANNEL
core->chan = new SecChannel;
#endif
opq_ = core;
}
/**
* Destructor.
*/
Socket::~Socket() {
_assert_(true);
SocketCore* core = (SocketCore*)opq_;
if (core->fd >= 0) close();
delete core;
}
/**
* Get the last happened error information.
* @return the last happened error information.
*/
const char* Socket::error() {
_assert_(true);
SocketCore* core = (SocketCore*)opq_;
if (!core->errmsg) return "no error";
return core->errmsg;
}
// This is a wrapper for the more complex signature for Socket::open below
// which always sets up an INSECURE connection. This is done for backwards
// compatibility.
bool Socket::open(const std::string& expr) {
return this->open(expr, false, NULL, NULL, NULL);
}
/**
* Open a client socket.
*/
bool Socket::open(const std::string& expr, bool secure,
const char* ca, const char* pk, const char* cert) {
_assert_(true);
SocketCore* core = (SocketCore*)opq_;
if (core->fd > 0) {
sockseterrmsg(core, "already opened");
return false;
}
char addr[NAMEBUFSIZ];
int32_t port;
parseaddr(expr.c_str(), addr, &port);
if (kc::atoi(addr) < 1 || port < 1 || port > kc::UINT16MAX) {
sockseterrmsg(core, "invalid address expression");
return false;
}
struct ::sockaddr_in sain;
std::memset(&sain, 0, sizeof(sain));
sain.sin_family = AF_INET;
if (::inet_aton(addr, &sain.sin_addr) == 0) {
sockseterrmsg(core, "inet_aton failed");
return false;
}
uint16_t snum = port;
sain.sin_port = htons(snum);
int32_t fd = ::socket(PF_INET, SOCK_STREAM, 0);
if (fd < 0) {
sockseterrmsg(core, "socket failed");
return false;
}
if (!setsocketoptions(fd)) {
sockseterrmsg(core, "setsocketoptions failed");
::close(fd);
return false;
}
int32_t flags = ::fcntl(fd, F_GETFL, NULL);
if (::fcntl(fd, F_SETFL, flags | O_NONBLOCK) != 0) {
sockseterrmsg(core, "fcntl failed");
::close(fd);
return false;
}
double ct = kc::time();
while (true) {
if (::connect(fd, (struct sockaddr*)&sain, sizeof(sain)) == 0 || errno == EISCONN) break;
if (!checkerrnoretriable(errno)) {
sockseterrmsg(core, "connect failed");
::close(fd);
return false;
}
if (kc::time() > ct + core->timeout) {
sockseterrmsg(core, "operation timed out");
::close(fd);
return false;
}
if (core->aborted) {
sockseterrmsg(core, "operation was aborted");
::close(fd);
return false;
}
if (!waitsocket(fd, 1, WAITTIME)) {
sockseterrmsg(core, "waitsocket failed");
::close(fd);
return false;
}
}
if (::fcntl(fd, F_SETFL, flags) != 0) {
sockseterrmsg(core, "fcntl failed");
::close(fd);
return false;
}
core->expr.clear();
kc::strprintf(&core->expr, "%s:%d", addr, port);
#if HAVE_SEC_CHANNEL
if (secure) {
if (core->chan->bind_client(fd, ca, pk, cert) != true) {
sockseterrmsg(core, "SSL bind failed");
::close(fd);
return false;
}
while (true) {
if (core->chan->connect()) break;
if (core->chan->error() != SecChannel::SEWantRead &&
core->chan->error() != SecChannel::SEWantWrite) {
sockseterrmsg(core, core->chan->error_msg());
core->chan->close();
::close(fd);
return false;
}
if (kc::time() > ct + core->timeout) {
sockseterrmsg(core, "operation timed out");
::close(fd);
return false;
}
if (core->aborted) {
sockseterrmsg(core, "operation was aborted");
::close(fd);
return false;
}
if (!waitsocket(fd, 1, WAITTIME)) {
sockseterrmsg(core, "waitsocket failed");
::close(fd);
return false;
}
}
}
#endif
core->fd = fd;
return true;
}
/**
* Close the socket.
*/
bool Socket::close(bool grace) {
_assert_(true);
SocketCore* core = (SocketCore*)opq_;
if (core->fd < 1) {
sockseterrmsg(core, "not opened");
return false;
}
bool err = false;
int32_t flags = ::fcntl(core->fd, F_GETFL, NULL);
if (::fcntl(core->fd, F_SETFL, flags | O_NONBLOCK) != 0) {
sockseterrmsg(core, "fcntl failed");
err = true;
}
if (grace) {
double ct = kc::time();
while (true) {
int32_t rv = ::shutdown(core->fd, SHUT_RDWR);
if (rv == 0 || !checkerrnoretriable(errno)) break;
if (kc::time() > ct + core->timeout) {
sockseterrmsg(core, "operation timed out");
err = true;
break;
}
if (core->aborted) break;
if (!waitsocket(core->fd, 1, WAITTIME)) {
sockseterrmsg(core, "waitsocket failed");
break;
}
}
} else {
struct ::linger optli;
optli.l_onoff = 1;
optli.l_linger = 0;
::setsockopt(core->fd, SOL_SOCKET, SO_LINGER, (char*)&optli, sizeof(optli));
}
if (::close(core->fd) != 0) {
sockseterrmsg(core, "close failed");
err = true;
}
core->fd = -1;
delete[] core->buf;
core->buf = NULL;
core->rp = NULL;
core->ep = NULL;
core->aborted = false;
#if HAVE_SEC_CHANNEL
if (core->chan->secstate() != SecChannel::SSUNSET) {
core->chan->close();
}
delete core->chan;
#endif
return !err;
}
/**
* Send data.
*/
bool Socket::send(const void* buf, size_t size) {
_assert_(buf && size <= kc::MEMMAXSIZ);
SocketCore* core = (SocketCore*)opq_;
if (core->fd < 1) {
sockseterrmsg(core, "not opened");
return false;
}
const char* rp = (const char*)buf;
double ct = kc::time();
while (size > 0) {
int32_t wb;
#if HAVE_SEC_CHANNEL
if (core->chan->secstate() == SecChannel::SSESTABLISHED) {
wb = core->chan->send(rp, size);
}
else
#endif
wb = ::send(core->fd, rp, size, 0);
switch (wb) {
case -1: {
if (!checkerrnoretriable(errno)) {
sockseterrmsg(core, "send failed");
return false;
}
if (kc::time() > ct + core->timeout) {
sockseterrmsg(core, "operation timed out");
return false;
}
if (core->aborted) {
sockseterrmsg(core, "operation was aborted");
return false;
}
if (!waitsocket(core->fd, 1, WAITTIME)) {
sockseterrmsg(core, "waitsocket failed");
return false;
}
break;
}
case 0: {
break;
}
default: {
rp += wb;
size -= wb;
break;
}
}
}
return true;
}
/**
* Send data.
*/
bool Socket::send(const std::string& str) {
_assert_(true);
return send(str.data(), str.size());
}
/**
* Send formatted data.
*/
bool Socket::printf(const char* format, ...) {
_assert_(format);
va_list ap;
va_start(ap, format);
bool rv = vprintf(format, ap);
va_end(ap);
return rv;
}
/**
* Send formatted data.
*/
bool Socket::vprintf(const char* format, va_list ap) {
_assert_(format);
std::string str;
kc::vstrprintf(&str, format, ap);
return send(str);
}
/**
* Receive data.
*/
bool Socket::receive(void* buf, size_t size) {
_assert_(buf && size <= kc::MEMMAXSIZ);
SocketCore* core = (SocketCore*)opq_;
if (core->fd < 1) {
sockseterrmsg(core, "not opened");
return false;
}
if (core->rp + size <= core->ep) {
std::memcpy(buf, core->rp, size);
core->rp += size;
return true;
}
bool err = false;
char* wp = (char*)buf;
while (size > 0) {
int32_t c = sockgetc(core);
if (c < 0) {
err = true;
break;
}
*(wp++) = c;
size--;
}
return !err;
}
/**
* Receive one byte.
*/
int32_t Socket::receive_byte() {
_assert_(true);
SocketCore* core = (SocketCore*)opq_;
if (core->fd < 1) {
sockseterrmsg(core, "not opened");
return false;
}
return sockgetc(core);
}
/**
* Push one byte back.
*/
bool Socket::undo_receive_byte(int32_t c) {
_assert_(true);
SocketCore* core = (SocketCore*)opq_;
if (core->fd < 1) {
sockseterrmsg(core, "not opened");
return false;
}
if (core->rp <= core->buf) return false;
core->rp--;
*(unsigned char*)core->rp = c;
return true;
}
/**
* Receive one line of characters.
*/
bool Socket::receive_line(void* buf, size_t max) {
_assert_(buf && max > 0 && max <= kc::MEMMAXSIZ);
SocketCore* core = (SocketCore*)opq_;
if (core->fd < 1) {
sockseterrmsg(core, "not opened");
return false;
}
bool err = false;
char* wp = (char*)buf;
while (max > 1) {
int32_t c = sockgetc(core);
if (c == '\n') break;
if (c < 0) {
err = true;
break;
}
if (c != '\r') {
*(wp++) = c;
max--;
}
}
*wp = '\0';
return !err;
}
/**
* Get the size of left data in the receiving buffer.
*/
size_t Socket::left_size() {
_assert_(true);
SocketCore* core = (SocketCore*)opq_;
return core->ep - core->rp;
}
/**
* Abort the current operation.
*/
bool Socket::abort() {
_assert_(true);
SocketCore* core = (SocketCore*)opq_;
if (core->fd < 1) {
sockseterrmsg(core, "not opened");
return false;
}
core->aborted = true;
return true;
}
/**
* Set the timeout of each operation.
*/
bool Socket::set_timeout(double timeout) {
_assert_(true);
SocketCore* core = (SocketCore*)opq_;
if (core->fd > 0) {
sockseterrmsg(core, "already opened");
return false;
}
core->timeout = timeout > 0 ? timeout : kc::UINT32MAX;
if (timeout > kc::UINT32MAX) timeout = kc::UINT32MAX;
return true;
}
/**
* Get the expression of the socket.
*/
const std::string Socket::expression() {
_assert_(true);
SocketCore* core = (SocketCore*)opq_;
if (core->fd < 0) {
sockseterrmsg(core, "not opened");
return "";
}
return core->expr;
}
/**
* Get the descriptor integer.
*/
int32_t Socket::descriptor() {
_assert_(true);
SocketCore* core = (SocketCore*)opq_;
if (core->fd < 0) {
sockseterrmsg(core, "not opened");
return -1;
}
return core->fd;
}
/**
* Set event flags.
*/
void Socket::set_event_flags(uint32_t flags) {
_assert_(true);
SocketCore* core = (SocketCore*)opq_;
core->evflags = flags;
}
/**
* Get the current event flags.
*/
uint32_t Socket::event_flags() {
_assert_(true);
SocketCore* core = (SocketCore*)opq_;
return core->evflags;
}
/**
* Get the primary name of the local host.
*/
std::string Socket::get_local_host_name() {
_assert_(true);
char name[NAMEBUFSIZ];
if (::gethostname(name, sizeof(name) - 1) != 0) return "";
return name;
}
/**
* Get the address of a host.
*/
std::string Socket::get_host_address(const std::string& name) {
_assert_(true);
struct ::addrinfo hints, *result;
std::memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = 0;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_canonname = NULL;
hints.ai_addr = NULL;
hints.ai_next = NULL;
if (::getaddrinfo(name.c_str(), NULL, &hints, &result) != 0) return "";
if (!result || result->ai_addr->sa_family != AF_INET) {
::freeaddrinfo(result);
return "";
}
char addr[NAMEBUFSIZ];
if (::getnameinfo(result->ai_addr, result->ai_addrlen,
addr, sizeof(addr) - 1, NULL, 0, NI_NUMERICHOST) != 0) {
::freeaddrinfo(result);
return "";
}
::freeaddrinfo(result);
return addr;
}
/**
* Default constructor.
*/
ServerSocket::ServerSocket() {
_assert_(true);
ServerSocketCore* core = new ServerSocketCore;
core->errmsg = NULL;
core->fd = -1;
core->timeout = kc::UINT32MAX;
core->aborted = false;
core->evflags = 0;
#if HAVE_SEC_CHANNEL
core->chan = NULL;
#endif
opq_ = core;
}
/**
* Destructor.
*/
ServerSocket::~ServerSocket() {
_assert_(true);
ServerSocketCore* core = (ServerSocketCore*)opq_;
if (core->fd >= 0) close();
delete core;
}
/**
* Get the last happened error information.
*/
const char* ServerSocket::error() {
_assert_(true);
ServerSocketCore* core = (ServerSocketCore*)opq_;
if (!core->errmsg) return "no error";
return core->errmsg;
}
/**
* Open a server socket.
*/
bool ServerSocket::open(const std::string& expr) {
_assert_(true);
ServerSocketCore* core = (ServerSocketCore*)opq_;
if (core->fd > 0) {
servseterrmsg(core, "already opened");
return false;
}
char addr[NAMEBUFSIZ];
int32_t port;
int len = sizeof(struct sockaddr);
parseaddr(expr.c_str(), addr, &port);
if (*addr == '\0') {
std::sprintf(addr, "0.0.0.0");
} else if (kc::atoi(addr) < 1) {
servseterrmsg(core, "invalid address expression");
return false;
}
if (port < 0 || port > kc::INT16MAX) {
servseterrmsg(core, "invalid address expression");
return false;
}
struct ::sockaddr_in sain;
std::memset(&sain, 0, sizeof(sain));
sain.sin_family = AF_INET;
if (::inet_aton(addr, &sain.sin_addr) == 0) {
servseterrmsg(core, "inet_aton failed");
return false;
}
uint16_t snum = port;
sain.sin_port = htons(snum);
int32_t fd = ::socket(PF_INET, SOCK_STREAM, 0);
if (fd < 0) {
servseterrmsg(core, "socket failed");
return false;
}
int32_t optint = 1;
::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char*)&optint, sizeof(optint));
if (::bind(fd, (struct sockaddr*)&sain, len) != 0) {
servseterrmsg(core, "bind failed");
::close(fd);
return false;
}
if (::listen(fd, BACKLOG) != 0) {
servseterrmsg(core, "listen failed");
::close(fd);
return -1;
}
int32_t flags = ::fcntl(fd, F_GETFL, NULL);
if (::fcntl(fd, F_SETFL, flags | O_NONBLOCK) != 0) {
servseterrmsg(core, "fcntl failed");
::close(fd);
return false;
}
core->fd = fd;
#if HAVE_SEC_CHANNEL
core->chan = new SecChannel;
#endif
core->expr.clear();
if (::getsockname(fd, (struct sockaddr*)&sain, (socklen_t*)&len) != 0) {
servseterrmsg(core, "getsockname failed");
::close(fd);
return false;
}
port = ntohs(sain.sin_port);
kc::strprintf(&core->expr, "%s:%d", addr, port);
core->aborted = false;
return true;
}
/**
* Close the socket.
*/
bool ServerSocket::close() {
_assert_(true);
ServerSocketCore* core = (ServerSocketCore*)opq_;
if (core->fd < 1) {
servseterrmsg(core, "not opened");
return false;
}
bool err = false;
if (::close(core->fd) != 0) {
servseterrmsg(core, "close failed");
err = true;
}
core->fd = -1;
core->aborted = false;
#if HAVE_SEC_CHANNEL
if (core->chan != NULL) {
if (core->chan->secstate() != SecChannel::SSUNSET) {
core->chan->close();
}
delete core->chan;
}
#endif
return !err;
}
/**
* Accept a connection from a client.
*/
bool ServerSocket::accept(Socket* sock, bool secure,
const char* ca, const char* pk, const char* cert) {
_assert_(sock);
ServerSocketCore* core = (ServerSocketCore*)opq_;
if (core->fd < 1) {
servseterrmsg(core, "not opened");
return false;
}
SocketCore* sockcore = (SocketCore*)sock->opq_;
if (sockcore->fd >= 0) {
servseterrmsg(core, "socket was already opened");
return false;
}
double ct = kc::time();
int32_t fd;
while (true) {
struct sockaddr_in sain;
std::memset(&sain, 0, sizeof(sain));
sain.sin_family = AF_INET;
::socklen_t slen = sizeof(sain);
fd = ::accept(core->fd, (struct sockaddr*)&sain, &slen);
if (fd >= 0) {
if (!setsocketoptions(fd)) {
servseterrmsg(core, "setsocketoptions failed");
::close(fd);
return false;
}
char addr[NAMEBUFSIZ];
if (::getnameinfo((struct sockaddr*)&sain, sizeof(sain), addr, sizeof(addr),
NULL, 0, NI_NUMERICHOST) != 0) std::sprintf(addr, "0.0.0.0");
int32_t port = ntohs(sain.sin_port);
sockcore->expr.clear();
kc::strprintf(&sockcore->expr, "%s:%d", addr, port);
sockcore->aborted = false;
break;
} else {
if (!checkerrnoretriable(errno)) {
servseterrmsg(core, "accept failed");
return false;
}
if (kc::time() > ct + core->timeout) {
servseterrmsg(core, "operation timed out");
return false;
}
if (core->aborted) {
servseterrmsg(core, "operation was aborted");
return false;
}
if (!waitsocket(core->fd, 1, WAITTIME)) {
servseterrmsg(core, "waitsocket failed");
return false;
}
}
}
#if HAVE_SEC_CHANNEL
if (secure) {
if (core->chan->bind_server(fd, ca, pk, cert) != true) {
servseterrmsg(core, core->chan->error_msg());
::close(fd);
return false;
}
while (true) {
if (core->chan->accept()) break;
if (core->chan->error() != SecChannel::SEWantRead &&
core->chan->error() != SecChannel::SEWantWrite) {
servseterrmsg(core, core->chan->error_msg());
core->chan->close();
::close(fd);
return false;
}
if (kc::time() > ct + core->timeout) {
servseterrmsg(core, "operation timed out");
::close(fd);
return false;
}
if (core->aborted) {
servseterrmsg(core, "operation was aborted");
::close(fd);
return false;
}
if (!waitsocket(fd, 0, WAITTIME)) {
servseterrmsg(core, "waitsocket failed");
::close(fd);
return false;
}
}
sockcore->chan = core->chan;
core->chan = new SecChannel;
}
#endif // HAVE_SEC_CHANNEL
sockcore->fd = fd;
return true;
}
/**
* Abort the current operation.
*/
bool ServerSocket::abort() {
_assert_(true);
ServerSocketCore* core = (ServerSocketCore*)opq_;
if (core->fd < 1) {
servseterrmsg(core, "not opened");
return false;
}
core->aborted = true;
return true;
}
/**
* Set the timeout of each operation.
*/
bool ServerSocket::set_timeout(double timeout) {
_assert_(true);
ServerSocketCore* core = (ServerSocketCore*)opq_;
if (core->fd > 0) {
servseterrmsg(core, "already opened");