forked from cesanta/fossa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfossa.c
7458 lines (6570 loc) · 219 KB
/
fossa.c
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 "fossa.h"
#ifdef NS_MODULE_LINES
#line 1 "src/internal.h"
/**/
#endif
/*
* Copyright (c) 2014 Cesanta Software Limited
* All rights reserved
*/
#ifndef NS_INTERNAL_HEADER_INCLUDED
#define NS_INTERNAL_HEADER_INCLUDED
#ifndef NS_MALLOC
#define NS_MALLOC malloc
#endif
#ifndef NS_CALLOC
#define NS_CALLOC calloc
#endif
#ifndef NS_REALLOC
#define NS_REALLOC realloc
#endif
#ifndef NS_FREE
#define NS_FREE free
#endif
#define NS_SET_PTRPTR(_ptr, _v) \
do { \
if (_ptr) *(_ptr) = _v; \
} while (0)
#ifndef NS_INTERNAL
#define NS_INTERNAL static
#endif
/* internals that need to be accessible in unit tests */
NS_INTERNAL struct ns_connection *ns_finish_connect(struct ns_connection *nc,
int proto,
union socket_address *sa,
struct ns_add_sock_opts);
NS_INTERNAL int ns_parse_address(const char *str, union socket_address *sa,
int *proto, char *host, size_t host_len);
#ifdef _WIN32
NS_INTERNAL void to_wchar(const char *path, wchar_t *wbuf, size_t wbuf_len);
#endif
#endif /* NS_INTERNAL_HEADER_INCLUDED */
#ifdef NS_MODULE_LINES
#line 1 "src/iobuf.c"
/**/
#endif
/* Copyright (c) 2014 Cesanta Software Limited
* All rights reserved
*
* This software is dual-licensed: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation. For the terms of this
* license, see <http://www.gnu.org/licenses/>.
*
* You are free to use this software under the terms of the GNU General
* Public License, 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.
*
* Alternatively, you can license this software under a commercial
* license, as set out in <http://cesanta.com/>.
*/
/*
* == IO Buffers
*/
/* Initializes an IO buffer. */
void iobuf_init(struct iobuf *iobuf, size_t initial_size) {
iobuf->len = iobuf->size = 0;
iobuf->buf = NULL;
iobuf_resize(iobuf, initial_size);
}
/* Frees the space allocated for the iobuffer and resets the iobuf structure. */
void iobuf_free(struct iobuf *iobuf) {
if (iobuf != NULL) {
NS_FREE(iobuf->buf);
iobuf_init(iobuf, 0);
}
}
/*
* Appends data to the IO buffer.
*
* It returns the amount of bytes appended.
*/
size_t iobuf_append(struct iobuf *io, const void *buf, size_t len) {
return iobuf_insert(io, io->len, buf, len);
}
/*
* Inserts data at a specified offset in the IO buffer.
*
* Existing data will be shifted forwards and the buffer will
* be grown if necessary.
* It returns the amount of bytes inserted.
*/
size_t iobuf_insert(struct iobuf *io, size_t off, const void *buf, size_t len) {
char *p = NULL;
assert(io != NULL);
assert(io->len <= io->size);
assert(off <= io->len);
/* check overflow */
if (len > ~(size_t) 0 - (size_t)(io->buf + io->len)) {
return 0;
}
if (io->len + len <= io->size) {
memmove(io->buf + off + len, io->buf + off, io->len - off);
if (buf != NULL) {
memcpy(io->buf + off, buf, len);
}
io->len += len;
} else if ((p = (char *) NS_REALLOC(io->buf, io->len + len)) != NULL) {
io->buf = p;
memmove(io->buf + off + len, io->buf + off, io->len - off);
if (buf != NULL) {
memcpy(io->buf + off, buf, len);
}
io->len += len;
io->size = io->len;
} else {
len = 0;
}
return len;
}
/* Removes `n` bytes from the beginning of the buffer. */
void iobuf_remove(struct iobuf *io, size_t n) {
if (n > 0 && n <= io->len) {
memmove(io->buf, io->buf + n, io->len - n);
io->len -= n;
}
}
/*
* Resize an IO buffer.
*
* If `new_size` is smaller than buffer's `len`, the
* resize is not performed.
*/
void iobuf_resize(struct iobuf *io, size_t new_size) {
char *p;
if ((new_size > io->size || (new_size < io->size && new_size >= io->len)) &&
(p = (char *) NS_REALLOC(io->buf, new_size)) != NULL) {
io->size = new_size;
io->buf = p;
}
}
#ifdef NS_MODULE_LINES
#line 1 "src/net.c"
/**/
#endif
/*
* Copyright (c) 2014 Cesanta Software Limited
* All rights reserved
*
* This software is dual-licensed: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation. For the terms of this
* license, see <http://www.gnu.org/licenses/>.
*
* You are free to use this software under the terms of the GNU General
* Public License, 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.
*
* Alternatively, you can license this software under a commercial
* license, as set out in <http://cesanta.com/>.
*/
/*
* == Core API: TCP/UDP/SSL
*
* CAUTION: Fossa manager is single threaded. It does not protect
* it's data structures by mutexes, therefore all functions that are dealing
* with particular event manager should be called from the same thread,
* with exception of `mg_broadcast()` function. It is fine to have different
* event managers handled by different threads.
*/
#define NS_CTL_MSG_MESSAGE_SIZE 8192
#define NS_READ_BUFFER_SIZE 2048
#define NS_UDP_RECEIVE_BUFFER_SIZE 2000
#define NS_VPRINTF_BUFFER_SIZE 500
#define NS_MAX_HOST_LEN 200
struct ctl_msg {
ns_event_handler_t callback;
char message[NS_CTL_MSG_MESSAGE_SIZE];
};
static void ns_add_conn(struct ns_mgr *mgr, struct ns_connection *c) {
c->next = mgr->active_connections;
mgr->active_connections = c;
c->prev = NULL;
if (c->next != NULL) c->next->prev = c;
}
static void ns_remove_conn(struct ns_connection *conn) {
if (conn->prev == NULL) conn->mgr->active_connections = conn->next;
if (conn->prev) conn->prev->next = conn->next;
if (conn->next) conn->next->prev = conn->prev;
}
static void ns_call(struct ns_connection *nc, int ev, void *ev_data) {
ns_event_handler_t ev_handler;
#ifndef NS_DISABLE_FILESYSTEM
/* LCOV_EXCL_START */
if (nc->mgr->hexdump_file != NULL && ev != NS_POLL) {
int len = (ev == NS_RECV || ev == NS_SEND) ? *(int *) ev_data : 0;
ns_hexdump_connection(nc, nc->mgr->hexdump_file, len, ev);
}
/* LCOV_EXCL_STOP */
#endif
/*
* If protocol handler is specified, call it. Otherwise, call user-specified
* event handler.
*/
ev_handler = nc->proto_handler ? nc->proto_handler : nc->handler;
if (ev_handler != NULL) {
ev_handler(nc, ev, ev_data);
}
}
static size_t ns_out(struct ns_connection *nc, const void *buf, size_t len) {
if (nc->flags & NSF_UDP) {
int n = sendto(nc->sock, buf, len, 0, &nc->sa.sa, sizeof(nc->sa.sin));
DBG(("%p %d %d %d %s:%hu", nc, nc->sock, n, errno,
inet_ntoa(nc->sa.sin.sin_addr), ntohs(nc->sa.sin.sin_port)));
return n < 0 ? 0 : n;
} else {
return iobuf_append(&nc->send_iobuf, buf, len);
}
}
static void ns_destroy_conn(struct ns_connection *conn) {
if (conn->sock != INVALID_SOCKET) {
closesocket(conn->sock);
/*
* avoid users accidentally double close a socket
* because it can lead to difficult to debug situations.
* It would happen only if reusing a destroyed ns_connection
* but it's not always possible to run the code through an
* address sanitizer.
*/
conn->sock = INVALID_SOCKET;
}
iobuf_free(&conn->recv_iobuf);
iobuf_free(&conn->send_iobuf);
#ifdef NS_ENABLE_SSL
if (conn->ssl != NULL) {
SSL_free(conn->ssl);
}
if (conn->ssl_ctx != NULL) {
SSL_CTX_free(conn->ssl_ctx);
}
#endif
NS_FREE(conn);
}
static void ns_close_conn(struct ns_connection *conn) {
DBG(("%p %lu", conn, conn->flags));
ns_call(conn, NS_CLOSE, NULL);
ns_remove_conn(conn);
ns_destroy_conn(conn);
}
/* Initializes Fossa manager. */
void ns_mgr_init(struct ns_mgr *s, void *user_data) {
memset(s, 0, sizeof(*s));
s->ctl[0] = s->ctl[1] = INVALID_SOCKET;
s->user_data = user_data;
#ifdef _WIN32
{
WSADATA data;
WSAStartup(MAKEWORD(2, 2), &data);
}
#elif !defined(AVR_LIBC)
/* Ignore SIGPIPE signal, so if client cancels the request, it
* won't kill the whole process. */
signal(SIGPIPE, SIG_IGN);
#endif
#ifndef NS_DISABLE_SOCKETPAIR
do {
ns_socketpair(s->ctl, SOCK_DGRAM);
} while (s->ctl[0] == INVALID_SOCKET);
#endif
#ifdef NS_ENABLE_SSL
{
static int init_done;
if (!init_done) {
SSL_library_init();
init_done++;
}
}
#endif
}
/*
* De-initializes fossa manager.
*
* Closes and deallocates all active connections.
*/
void ns_mgr_free(struct ns_mgr *s) {
struct ns_connection *conn, *tmp_conn;
DBG(("%p", s));
if (s == NULL) return;
/* Do one last poll, see https://github.com/cesanta/mongoose/issues/286 */
ns_mgr_poll(s, 0);
if (s->ctl[0] != INVALID_SOCKET) closesocket(s->ctl[0]);
if (s->ctl[1] != INVALID_SOCKET) closesocket(s->ctl[1]);
s->ctl[0] = s->ctl[1] = INVALID_SOCKET;
for (conn = s->active_connections; conn != NULL; conn = tmp_conn) {
tmp_conn = conn->next;
ns_close_conn(conn);
}
}
/*
* Send `printf`-style formatted data to the connection.
*
* See `ns_send` for more details on send semantics.
*/
int ns_vprintf(struct ns_connection *nc, const char *fmt, va_list ap) {
char mem[NS_VPRINTF_BUFFER_SIZE], *buf = mem;
int len;
if ((len = ns_avprintf(&buf, sizeof(mem), fmt, ap)) > 0) {
ns_out(nc, buf, len);
}
if (buf != mem && buf != NULL) {
NS_FREE(buf); /* LCOV_EXCL_LINE */
} /* LCOV_EXCL_LINE */
return len;
}
/*
* Send `printf`-style formatted data to the connection.
*
* See `ns_send` for more details on send semantics.
*/
int ns_printf(struct ns_connection *conn, const char *fmt, ...) {
int len;
va_list ap;
va_start(ap, fmt);
len = ns_vprintf(conn, fmt, ap);
va_end(ap);
return len;
}
static void ns_set_non_blocking_mode(sock_t sock) {
#ifdef _WIN32
unsigned long on = 1;
ioctlsocket(sock, FIONBIO, &on);
#else
int flags = fcntl(sock, F_GETFL, 0);
fcntl(sock, F_SETFL, flags | O_NONBLOCK);
#endif
}
#ifndef NS_DISABLE_SOCKETPAIR
/*
* Create a socket pair.
* `proto` can be either `SOCK_STREAM` or `SOCK_DGRAM`.
* Return 0 on failure, 1 on success.
*/
int ns_socketpair(sock_t sp[2], int sock_type) {
union socket_address sa;
sock_t sock;
socklen_t len = sizeof(sa.sin);
int ret = 0;
sock = sp[0] = sp[1] = INVALID_SOCKET;
(void) memset(&sa, 0, sizeof(sa));
sa.sin.sin_family = AF_INET;
sa.sin.sin_port = htons(0);
sa.sin.sin_addr.s_addr = htonl(0x7f000001);
if ((sock = socket(AF_INET, sock_type, 0)) == INVALID_SOCKET) {
} else if (bind(sock, &sa.sa, len) != 0) {
} else if (sock_type == SOCK_STREAM && listen(sock, 1) != 0) {
} else if (getsockname(sock, &sa.sa, &len) != 0) {
} else if ((sp[0] = socket(AF_INET, sock_type, 0)) == INVALID_SOCKET) {
} else if (connect(sp[0], &sa.sa, len) != 0) {
} else if (sock_type == SOCK_DGRAM &&
(getsockname(sp[0], &sa.sa, &len) != 0 ||
connect(sock, &sa.sa, len) != 0)) {
} else if ((sp[1] = (sock_type == SOCK_DGRAM ? sock
: accept(sock, &sa.sa, &len))) ==
INVALID_SOCKET) {
} else {
ns_set_close_on_exec(sp[0]);
ns_set_close_on_exec(sp[1]);
if (sock_type == SOCK_STREAM) closesocket(sock);
ret = 1;
}
if (!ret) {
if (sp[0] != INVALID_SOCKET) closesocket(sp[0]);
if (sp[1] != INVALID_SOCKET) closesocket(sp[1]);
if (sock != INVALID_SOCKET) closesocket(sock);
sock = sp[0] = sp[1] = INVALID_SOCKET;
}
return ret;
}
#endif /* NS_DISABLE_SOCKETPAIR */
/* TODO(lsm): use non-blocking resolver */
static int ns_resolve2(const char *host, struct in_addr *ina) {
#ifdef NS_ENABLE_GETADDRINFO
int rv = 0;
struct addrinfo hints, *servinfo, *p;
struct sockaddr_in *h = NULL;
char *ip = NS_MALLOC(17);
memset(ip, '\0', 17);
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
if ((rv = getaddrinfo(host, NULL, NULL, &servinfo)) != 0) {
DBG(("getaddrinfo(%s) failed: %s", host, strerror(errno)));
return 0;
}
for (p = servinfo; p != NULL; p = p->ai_next) {
memcpy(&h, &p->ai_addr, sizeof(struct sockaddr_in *));
memcpy(ina, &h->sin_addr, sizeof(ina));
}
freeaddrinfo(servinfo);
return 1;
#else
struct hostent *he;
if ((he = gethostbyname(host)) == NULL) {
DBG(("gethostbyname(%s) failed: %s", host, strerror(errno)));
} else {
memcpy(ina, he->h_addr_list[0], sizeof(*ina));
return 1;
}
return 0;
#endif
}
/*
* Converts domain name into IP address.
*
* This is a blocking call. Returns 1 on success, 0 on failure.
*/
int ns_resolve(const char *host, char *buf, size_t n) {
struct in_addr ad;
return ns_resolve2(host, &ad) ? snprintf(buf, n, "%s", inet_ntoa(ad)) : 0;
}
NS_INTERNAL struct ns_connection *ns_create_connection(
struct ns_mgr *mgr, ns_event_handler_t callback,
struct ns_add_sock_opts opts) {
struct ns_connection *conn;
if ((conn = (struct ns_connection *) NS_MALLOC(sizeof(*conn))) != NULL) {
memset(conn, 0, sizeof(*conn));
conn->sock = INVALID_SOCKET;
conn->handler = callback;
conn->mgr = mgr;
conn->last_io_time = time(NULL);
conn->flags = opts.flags;
conn->user_data = opts.user_data;
/*
* SIZE_MAX is defined as a long long constant in
* system headers on some platforms and so it
* doesn't compile with pedantic ansi flags.
*/
conn->recv_iobuf_limit = ~0;
}
return conn;
}
/* Associate a socket to a connection and and add to the manager. */
NS_INTERNAL void ns_set_sock(struct ns_connection *nc, sock_t sock) {
ns_set_non_blocking_mode(sock);
ns_set_close_on_exec(sock);
nc->sock = sock;
ns_add_conn(nc->mgr, nc);
DBG(("%p %d", nc, sock));
}
/*
* Address format: [PROTO://][HOST]:PORT
*
* HOST could be IPv4/IPv6 address or a host name.
* `host` is a destination buffer to hold parsed HOST part. Shoud be at least
* NS_MAX_HOST_LEN bytes long.
* `proto` is a returned socket type, either SOCK_STREAM or SOCK_DGRAM
*
* Return:
* -1 on parse error
* 0 if HOST needs DNS lookup
* >0 length of the address string
*/
NS_INTERNAL int ns_parse_address(const char *str, union socket_address *sa,
int *proto, char *host, size_t host_len) {
unsigned int a, b, c, d, port = 0;
int len = 0;
#ifdef NS_ENABLE_IPV6
char buf[100];
#endif
/*
* MacOS needs that. If we do not zero it, subsequent bind() will fail.
* Also, all-zeroes in the socket address means binding to all addresses
* for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT).
*/
memset(sa, 0, sizeof(*sa));
sa->sin.sin_family = AF_INET;
*proto = SOCK_STREAM;
if (strncmp(str, "udp://", 6) == 0) {
str += 6;
*proto = SOCK_DGRAM;
} else if (strncmp(str, "tcp://", 6) == 0) {
str += 6;
}
if (sscanf(str, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len) == 5) {
/* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
sa->sin.sin_addr.s_addr =
htonl(((uint32_t) a << 24) | ((uint32_t) b << 16) | c << 8 | d);
sa->sin.sin_port = htons((uint16_t) port);
#ifdef NS_ENABLE_IPV6
} else if (sscanf(str, "[%99[^]]]:%u%n", buf, &port, &len) == 2 &&
inet_pton(AF_INET6, buf, &sa->sin6.sin6_addr)) {
/* IPv6 address, e.g. [3ffe:2a00:100:7031::1]:8080 */
sa->sin6.sin6_family = AF_INET6;
sa->sin.sin_port = htons((uint16_t) port);
#endif
#ifndef NS_DISABLE_RESOLVER
} else if (strlen(str) < host_len &&
sscanf(str, "%[^ :]:%u%n", host, &port, &len) == 2) {
sa->sin.sin_port = htons((uint16_t) port);
if (ns_resolve_from_hosts_file(host, sa) != 0) {
return 0;
}
#endif
} else if (sscanf(str, ":%u%n", &port, &len) == 1 ||
sscanf(str, "%u%n", &port, &len) == 1) {
/* If only port is specified, bind to IPv4, INADDR_ANY */
sa->sin.sin_port = htons((uint16_t) port);
} else {
return -1;
}
return port < 0xffffUL && str[len] == '\0' ? len : -1;
}
/* 'sa' must be an initialized address to bind to */
static sock_t ns_open_listening_socket(union socket_address *sa, int proto) {
socklen_t sa_len =
(sa->sa.sa_family == AF_INET) ? sizeof(sa->sin) : sizeof(sa->sin6);
sock_t sock = INVALID_SOCKET;
int on = 1;
if ((sock = socket(sa->sa.sa_family, proto, 0)) != INVALID_SOCKET &&
#if defined(_WIN32) && defined(SO_EXCLUSIVEADDRUSE)
/* "Using SO_REUSEADDR and SO_EXCLUSIVEADDRUSE" http://goo.gl/RmrFTm */
!setsockopt(sock, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (void *) &on,
sizeof(on)) &&
#endif
#if 1 || !defined(_WIN32) || defined(SO_EXCLUSIVEADDRUSE)
/*
* SO_RESUSEADDR is not enabled on Windows because the semantics of
* SO_REUSEADDR on UNIX and Windows is different. On Windows,
* SO_REUSEADDR allows to bind a socket to a port without error even if
* the port is already open by another program. This is not the behavior
* SO_REUSEADDR was designed for, and leads to hard-to-track failure
* scenarios. Therefore, SO_REUSEADDR was disabled on Windows unless
* SO_EXCLUSIVEADDRUSE is supported and set on a socket.
*/
!setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *) &on, sizeof(on)) &&
#endif
!bind(sock, &sa->sa, sa_len) &&
(proto == SOCK_DGRAM || listen(sock, SOMAXCONN) == 0)) {
ns_set_non_blocking_mode(sock);
/* In case port was set to 0, get the real port number */
(void) getsockname(sock, &sa->sa, &sa_len);
} else if (sock != INVALID_SOCKET) {
closesocket(sock);
sock = INVALID_SOCKET;
}
return sock;
}
#ifdef NS_ENABLE_SSL
/* Certificate generation script is at */
/* https://github.com/cesanta/fossa/blob/master/scripts/gen_certs.sh */
static int ns_use_ca_cert(SSL_CTX *ctx, const char *cert) {
if (ctx == NULL) {
return -1;
} else if (cert == NULL || cert[0] == '\0') {
return 0;
}
SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, 0);
return SSL_CTX_load_verify_locations(ctx, cert, NULL) == 1 ? 0 : -2;
}
static int ns_use_cert(SSL_CTX *ctx, const char *pem_file) {
if (ctx == NULL) {
return -1;
} else if (pem_file == NULL || pem_file[0] == '\0') {
return 0;
} else if (SSL_CTX_use_certificate_file(ctx, pem_file, 1) == 0 ||
SSL_CTX_use_PrivateKey_file(ctx, pem_file, 1) == 0) {
return -2;
} else {
SSL_CTX_set_mode(ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
SSL_CTX_use_certificate_chain_file(ctx, pem_file);
return 0;
}
}
/*
* Turn the connection into SSL mode.
* `cert` is the certificate file in PEM format. For listening connections,
* certificate file must contain private key and server certificate,
* concatenated. `ca_cert` is a certificate authority (CA) PEM file, and
* it is optional (can be set to NULL). If `ca_cert` is non-NULL, then
* the connection is so-called two-way-SSL: other peer's certificate is
* checked against the `ca_cert`.
*
* Handy OpenSSL command to generate test self-signed certificate:
*
* openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 999
*
* Return NULL on success, or error message on failure.
*/
const char *ns_set_ssl(struct ns_connection *nc, const char *cert,
const char *ca_cert) {
const char *result = NULL;
if ((nc->flags & NSF_LISTENING) &&
(nc->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
result = "SSL_CTX_new() failed";
} else if (!(nc->flags & NSF_LISTENING) &&
(nc->ssl_ctx = SSL_CTX_new(SSLv23_client_method())) == NULL) {
result = "SSL_CTX_new() failed";
} else if (ns_use_cert(nc->ssl_ctx, cert) != 0) {
result = "Invalid ssl cert";
} else if (ns_use_ca_cert(nc->ssl_ctx, ca_cert) != 0) {
result = "Invalid CA cert";
} else if (!(nc->flags & NSF_LISTENING) &&
(nc->ssl = SSL_new(nc->ssl_ctx)) == NULL) {
result = "SSL_new() failed";
} else if (!(nc->flags & NSF_LISTENING)) {
SSL_set_fd(nc->ssl, nc->sock);
}
return result;
}
static int ns_ssl_err(struct ns_connection *conn, int res) {
int ssl_err = SSL_get_error(conn->ssl, res);
if (ssl_err == SSL_ERROR_WANT_READ) conn->flags |= NSF_WANT_READ;
if (ssl_err == SSL_ERROR_WANT_WRITE) conn->flags |= NSF_WANT_WRITE;
return ssl_err;
}
#endif /* NS_ENABLE_SSL */
static struct ns_connection *accept_conn(struct ns_connection *ls) {
struct ns_connection *c = NULL;
union socket_address sa;
socklen_t len = sizeof(sa);
sock_t sock = INVALID_SOCKET;
/* NOTE(lsm): on Windows, sock is always > FD_SETSIZE */
if ((sock = accept(ls->sock, &sa.sa, &len)) == INVALID_SOCKET) {
} else if ((c = ns_add_sock(ls->mgr, sock, ls->handler)) == NULL) {
closesocket(sock);
#ifdef NS_ENABLE_SSL
} else if (ls->ssl_ctx != NULL && ((c->ssl = SSL_new(ls->ssl_ctx)) == NULL ||
SSL_set_fd(c->ssl, sock) != 1)) {
DBG(("SSL error"));
ns_close_conn(c);
c = NULL;
#endif
} else {
c->listener = ls;
c->proto_data = ls->proto_data;
c->proto_handler = ls->proto_handler;
c->user_data = ls->user_data;
c->recv_iobuf_limit = ls->recv_iobuf_limit;
ns_call(c, NS_ACCEPT, &sa);
DBG(("%p %d %p %p", c, c->sock, c->ssl_ctx, c->ssl));
}
return c;
}
static int ns_is_error(int n) {
return n == 0 || (n < 0 && errno != EINTR && errno != EINPROGRESS &&
errno != EAGAIN && errno != EWOULDBLOCK
#ifdef _WIN32
&& WSAGetLastError() != WSAEINTR &&
WSAGetLastError() != WSAEWOULDBLOCK
#endif
);
}
static size_t recv_avail_size(struct ns_connection *conn, size_t max) {
size_t avail;
if (conn->recv_iobuf_limit < conn->recv_iobuf.len) return 0;
avail = conn->recv_iobuf_limit - conn->recv_iobuf.len;
return avail > max ? max : avail;
}
static void ns_read_from_socket(struct ns_connection *conn) {
char buf[NS_READ_BUFFER_SIZE];
int n = 0;
if (conn->flags & NSF_CONNECTING) {
int ok = 1, ret;
socklen_t len = sizeof(ok);
ret = getsockopt(conn->sock, SOL_SOCKET, SO_ERROR, (char *) &ok, &len);
#ifdef NS_ENABLE_SSL
if (ret == 0 && ok == 0 && conn->ssl != NULL) {
int res = SSL_connect(conn->ssl);
int ssl_err = ns_ssl_err(conn, res);
if (res == 1) {
conn->flags |= NSF_SSL_HANDSHAKE_DONE;
conn->flags &= ~(NSF_WANT_READ | NSF_WANT_WRITE);
} else if (ssl_err == SSL_ERROR_WANT_READ ||
ssl_err == SSL_ERROR_WANT_WRITE) {
return; /* Call us again */
} else {
ok = 1;
}
}
#endif
(void) ret;
conn->flags &= ~NSF_CONNECTING;
DBG(("%p ok=%d", conn, ok));
if (ok != 0) {
conn->flags |= NSF_CLOSE_IMMEDIATELY;
}
ns_call(conn, NS_CONNECT, &ok);
return;
}
#ifdef NS_ENABLE_SSL
if (conn->ssl != NULL) {
if (conn->flags & NSF_SSL_HANDSHAKE_DONE) {
/* SSL library may have more bytes ready to read then we ask to read.
* Therefore, read in a loop until we read everything. Without the loop,
* we skip to the next select() cycle which can just timeout. */
while ((n = SSL_read(conn->ssl, buf, sizeof(buf))) > 0) {
DBG(("%p %lu <- %d bytes (SSL)", conn, conn->flags, n));
iobuf_append(&conn->recv_iobuf, buf, n);
ns_call(conn, NS_RECV, &n);
}
ns_ssl_err(conn, n);
} else {
int res = SSL_accept(conn->ssl);
int ssl_err = ns_ssl_err(conn, res);
if (res == 1) {
conn->flags |= NSF_SSL_HANDSHAKE_DONE;
conn->flags &= ~(NSF_WANT_READ | NSF_WANT_WRITE);
} else if (ssl_err == SSL_ERROR_WANT_READ ||
ssl_err == SSL_ERROR_WANT_WRITE) {
return; /* Call us again */
} else {
conn->flags |= NSF_CLOSE_IMMEDIATELY;
}
return;
}
} else
#endif
{
while ((n = (int) recv(conn->sock, buf, recv_avail_size(conn, sizeof(buf)),
0)) > 0) {
DBG(("%p %lu <- %d bytes (PLAIN)", conn, conn->flags, n));
iobuf_append(&conn->recv_iobuf, buf, n);
ns_call(conn, NS_RECV, &n);
}
}
if (ns_is_error(n)) {
conn->flags |= NSF_CLOSE_IMMEDIATELY;
}
}
static void ns_write_to_socket(struct ns_connection *conn) {
struct iobuf *io = &conn->send_iobuf;
int n = 0;
#ifdef NS_ENABLE_SSL
if (conn->ssl != NULL) {
n = SSL_write(conn->ssl, io->buf, io->len);
if (n <= 0) {
int ssl_err = ns_ssl_err(conn, n);
if (ssl_err == SSL_ERROR_WANT_READ || ssl_err == SSL_ERROR_WANT_WRITE) {
return; /* Call us again */
} else {
conn->flags |= NSF_CLOSE_IMMEDIATELY;
}
} else {
/* Successful SSL operation, clear off SSL wait flags */
conn->flags &= ~(NSF_WANT_READ | NSF_WANT_WRITE);
}
} else
#endif
{
n = (int) send(conn->sock, io->buf, io->len, 0);
}
DBG(("%p %lu -> %d bytes", conn, conn->flags, n));
ns_call(conn, NS_SEND, &n);
if (ns_is_error(n)) {
conn->flags |= NSF_CLOSE_IMMEDIATELY;
} else if (n > 0) {
iobuf_remove(io, n);
}
}
/*
* Send data to the connection.
*
* Number of written bytes is returned. Note that these sending
* functions do not actually push data to the sockets, they just append data
* to the output buffer. The exception is UDP connections. For UDP, data is
* sent immediately, and returned value indicates an actual number of bytes
* sent to the socket.
*/
int ns_send(struct ns_connection *conn, const void *buf, int len) {
return (int) ns_out(conn, buf, len);
}
static void ns_handle_udp(struct ns_connection *ls) {
struct ns_connection nc;
char buf[NS_UDP_RECEIVE_BUFFER_SIZE];
int n;
socklen_t s_len = sizeof(nc.sa);
memset(&nc, 0, sizeof(nc));
n = recvfrom(ls->sock, buf, sizeof(buf), 0, &nc.sa.sa, &s_len);
if (n <= 0) {
DBG(("%p recvfrom: %s", ls, strerror(errno)));
} else {
union socket_address sa = nc.sa;
/* Copy all attributes, preserving sender address */
nc = *ls;
/* Then override some */
nc.sa = sa;
nc.recv_iobuf.buf = buf;
nc.recv_iobuf.len = nc.recv_iobuf.size = n;
nc.listener = ls;
nc.flags = NSF_UDP;
/* Call NS_RECV handler */
DBG(("%p %d bytes received", ls, n));
ns_call(&nc, NS_RECV, &n);
/*
* See https://github.com/cesanta/fossa/issues/207
* ns_call migth set flags. They need to be synced back to ls.
*/
ls->flags = nc.flags;
}
}
static void ns_add_to_set(sock_t sock, fd_set *set, sock_t *max_fd) {
if (sock != INVALID_SOCKET) {
FD_SET(sock, set);
if (*max_fd == INVALID_SOCKET || sock > *max_fd) {
*max_fd = sock;
}
}
}
/*
* This function performs the actual IO, and must be called in a loop
* (an event loop). Returns the current timestamp.
*/
time_t ns_mgr_poll(struct ns_mgr *mgr, int milli) {
struct ns_connection *nc, *tmp;
struct timeval tv;
fd_set read_set, write_set, err_set;
sock_t max_fd = INVALID_SOCKET;
time_t current_time = time(NULL);
FD_ZERO(&read_set);
FD_ZERO(&write_set);
FD_ZERO(&err_set);
ns_add_to_set(mgr->ctl[1], &read_set, &max_fd);
for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
tmp = nc->next;
if (!(nc->flags & (NSF_LISTENING | NSF_CONNECTING))) {
ns_call(nc, NS_POLL, ¤t_time);
}
/*
* NS_POLL handler could have signaled us to close the connection
* by setting NSF_CLOSE_IMMEDIATELY flag. In this case, we don't want to
* trigger any other events on that connection, but close it right away.
*/
if (nc->flags & NSF_CLOSE_IMMEDIATELY) {
/* NOTE(lsm): this call removes nc from the mgr->active_connections */
ns_close_conn(nc);
continue;
}
if (!(nc->flags & NSF_WANT_WRITE) &&
nc->recv_iobuf.len < nc->recv_iobuf_limit) {
ns_add_to_set(nc->sock, &read_set, &max_fd);
}
if (((nc->flags & NSF_CONNECTING) && !(nc->flags & NSF_WANT_READ)) ||
(nc->send_iobuf.len > 0 && !(nc->flags & NSF_CONNECTING) &&
!(nc->flags & NSF_DONT_SEND))) {
ns_add_to_set(nc->sock, &write_set, &max_fd);
ns_add_to_set(nc->sock, &err_set, &max_fd);
}
}
tv.tv_sec = milli / 1000;
tv.tv_usec = (milli % 1000) * 1000;
if (select((int) max_fd + 1, &read_set, &write_set, &err_set, &tv) > 0) {
/* select() might have been waiting for a long time, reset current_time
* now to prevent last_io_time being set to the past. */
current_time = time(NULL);
#ifndef __AVR__
/*
* Note: it seems, avr-gcc breaks on long functions
* As workaround unused (on AVR) part just excluded
* TODO(alashkin): investigate this
*/
/* Read wakeup messages */
if (mgr->ctl[1] != INVALID_SOCKET && FD_ISSET(mgr->ctl[1], &read_set)) {
struct ctl_msg ctl_msg;
int len = (int) recv(mgr->ctl[1], (char *) &ctl_msg, sizeof(ctl_msg), 0);
send(mgr->ctl[1], ctl_msg.message, 1, 0);
if (len >= (int) sizeof(ctl_msg.callback) && ctl_msg.callback != NULL) {
struct ns_connection *c;
for (c = ns_next(mgr, NULL); c != NULL; c = ns_next(mgr, c)) {
ctl_msg.callback(c, NS_POLL, ctl_msg.message);
}
}
}
#endif
for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
tmp = nc->next;
/* Windows reports failed connect() requests in err_set */
if (FD_ISSET(nc->sock, &err_set) && (nc->flags & NSF_CONNECTING)) {
nc->last_io_time = current_time;
ns_read_from_socket(nc);
}
if (FD_ISSET(nc->sock, &read_set)) {
nc->last_io_time = current_time;
if (nc->flags & NSF_UDP) {
ns_handle_udp(nc);
} else if (nc->flags & NSF_LISTENING) {
/*
* We're not looping here, and accepting just one connection at