-
Notifications
You must be signed in to change notification settings - Fork 3.4k
/
evutil.c
3368 lines (3065 loc) · 88.2 KB
/
evutil.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
/*
* Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef _WIN32
#ifndef _WIN32_WINNT
/* For structs needed by GetAdaptersAddresses and AI_NUMERICSERV */
#define _WIN32_WINNT 0x0600
#endif
#define WIN32_LEAN_AND_MEAN
#endif
#include "event2/event-config.h"
#include "evconfig-private.h"
#ifdef _WIN32
#include <winsock2.h>
#include <winerror.h>
#include <ws2tcpip.h>
#ifdef _MSC_VER /* mstcpip.h is missing on MinGW */
#include <mstcpip.h> /* for SIO_KEEPALIVE_VALS and tcp_keepalive struct */
#endif
#ifdef EVENT__HAVE_AFUNIX_H
#include <afunix.h>
#endif
#include <windows.h>
#include <io.h>
#include <tchar.h>
#include <process.h>
#include <iphlpapi.h>
#include <netioapi.h>
#endif
#ifdef EVENT__HAVE_SYS_PARAM_H
#include <sys/param.h>
#endif
#include <sys/types.h>
#ifdef EVENT__HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
#ifdef EVENT__HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef EVENT__HAVE_FCNTL_H
#include <fcntl.h>
#endif
#ifdef EVENT__HAVE_STDLIB_H
#include <stdlib.h>
#endif
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <string.h>
#ifdef EVENT__HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
#ifdef EVENT__HAVE_NETINET_IN6_H
#include <netinet/in6.h>
#endif
#ifdef EVENT__HAVE_NETINET_TCP_H
#include <netinet/tcp.h>
#endif
#ifdef EVENT__HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
#include <time.h>
#include <sys/stat.h>
#ifndef _WIN32
#include <net/if.h>
#endif
#ifdef EVENT__HAVE_IFADDRS_H
#include <ifaddrs.h>
#endif
#include "event2/util.h"
#include "util-internal.h"
#include "log-internal.h"
#include "mm-internal.h"
#include "evthread-internal.h"
#include "strlcpy-internal.h"
#include "ipv6-internal.h"
#ifdef _WIN32
#define HT_NO_CACHE_HASH_VALUES
#include "ht-internal.h"
#define open _open
#define read _read
#define close _close
#ifndef fstat
// i64 suffix is for 64-bit filesize support
#define fstat _fstati64
#endif
#ifndef stat
#define stat _stati64
#endif
#define mode_t int
#endif
#if defined(_WIN32) && !defined(SIO_KEEPALIVE_VALS)
#define SIO_KEEPALIVE_VALS _WSAIOW(IOC_VENDOR,4)
struct tcp_keepalive {
u_long onoff;
u_long keepalivetime;
u_long keepaliveinterval;
};
#endif
#ifndef O_RDONLY
#define O_RDONLY _O_RDONLY
#endif
#ifdef EVENT__HAVE_AFUNIX_H
int have_working_afunix_ = -1;
#endif
int
evutil_open_closeonexec_(const char *pathname, int flags, unsigned mode)
{
int fd;
#ifdef O_CLOEXEC
fd = open(pathname, flags|O_CLOEXEC, (mode_t)mode);
if (fd >= 0 || errno == EINVAL)
return fd;
/* If we got an EINVAL, fall through and try without O_CLOEXEC */
#endif
fd = open(pathname, flags, (mode_t)mode);
if (fd < 0)
return -1;
#if defined(FD_CLOEXEC)
if (fcntl(fd, F_SETFD, FD_CLOEXEC) < 0) {
close(fd);
return -1;
}
#endif
return fd;
}
ev_off_t evutil_fd_filesize(evutil_socket_t fd)
{
struct stat st;
if (fstat(fd, &st) < 0)
return -1;
return st.st_size;
}
/**
Read the contents of 'filename' into a newly allocated NUL-terminated
string. Set *content_out to hold this string, and *len_out to hold its
length (not including the appended NUL). If 'is_binary', open the file in
binary mode.
Returns 0 on success, -1 if the open fails, and -2 for all other failures.
Used internally only; may go away in a future version.
*/
int
evutil_read_file_(const char *filename, char **content_out, size_t *len_out,
int is_binary)
{
int fd;
ev_ssize_t r;
ev_off_t length;
char *mem;
size_t read_so_far = 0;
int mode = O_RDONLY;
EVUTIL_ASSERT(content_out);
EVUTIL_ASSERT(len_out);
*content_out = NULL;
*len_out = 0;
#ifdef O_BINARY
if (is_binary)
mode |= O_BINARY;
#endif
fd = evutil_open_closeonexec_(filename, mode, 0);
if (fd < 0)
return -1;
length = evutil_fd_filesize(fd);
if (length < 0 || length > EV_SSIZE_MAX-1) {
close(fd);
return -2;
}
mem = mm_malloc(length + 1);
if (!mem) {
close(fd);
return -2;
}
read_so_far = 0;
#ifdef _WIN32
#define N_TO_READ(x) ((x) > INT_MAX) ? INT_MAX : ((int)(x))
#else
#define N_TO_READ(x) (x)
#endif
while ((r = read(fd, mem+read_so_far, N_TO_READ(length - read_so_far))) > 0) {
read_so_far += r;
if (read_so_far >= (size_t)length)
break;
}
close(fd);
if (r < 0) {
mm_free(mem);
return -2;
}
mem[read_so_far] = 0;
*len_out = read_so_far;
*content_out = mem;
return 0;
}
#ifdef _WIN32
static int
create_tmpfile(WCHAR tmpfile[MAX_PATH])
{
WCHAR short_path[MAX_PATH] = {0};
WCHAR long_path[MAX_PATH] = {0};
WCHAR prefix[4] = {0};
// GetTempFileNameW() uses up to the first three characters of the prefix
// and windows filesystems are case-insensitive
const WCHAR *base32set = L"abcdefghijklmnopqrstuvwxyz012345";
ev_uint16_t rnd;
evutil_secure_rng_get_bytes(&rnd, sizeof(rnd));
prefix[0] = base32set[(rnd ) & 31];
prefix[1] = base32set[(rnd >> 5) & 31];
prefix[2] = base32set[(rnd >> 10) & 31];
prefix[3] = '\0';
GetTempPathW(MAX_PATH, short_path);
GetLongPathNameW(short_path, long_path, MAX_PATH);
if (!GetTempFileNameW(long_path, prefix, 0, tmpfile)) {
event_warnx("GetTempFileName failed: %d", EVUTIL_SOCKET_ERROR());
return -1;
}
return 0;
}
#ifdef EVENT__HAVE_AFUNIX_H
/* Test whether Unix domain socket works.
* Return 1 if it works, otherwise 0 */
int
evutil_check_working_afunix_()
{
/* Windows 10 began to support Unix domain socket. Let's just try
* socket(AF_UNIX, , ) and fall back to socket(AF_INET, , ).
* https://devblogs.microsoft.com/commandline/af_unix-comes-to-windows/
*/
evutil_socket_t sd = -1;
if (have_working_afunix_ < 0) {
if ((sd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
have_working_afunix_ = 0;
} else {
have_working_afunix_ = 1;
evutil_closesocket(sd);
}
}
return have_working_afunix_;
}
/* XXX Copy from evutil_ersatz_socketpair_() */
static int
evutil_win_socketpair_afunix(int family, int type, int protocol,
evutil_socket_t fd[2])
{
#undef ERR
#define ERR(e) WSA##e
evutil_socket_t listener = -1;
evutil_socket_t connector = -1;
evutil_socket_t acceptor = -1;
struct sockaddr_un listen_addr;
struct sockaddr_un connect_addr;
WCHAR tmp_file[MAX_PATH] = {0};
char tmp_file_utf8[MAX_PATH] = {0};
ev_socklen_t size;
int saved_errno = -1;
if (!fd) {
EVUTIL_SET_SOCKET_ERROR(ERR(EINVAL));
return -1;
}
listener = socket(family, type, 0);
if (listener < 0)
return -1;
memset(&listen_addr, 0, sizeof(listen_addr));
if (create_tmpfile(tmp_file)) {
goto tidy_up_and_fail;
}
DeleteFileW(tmp_file);
/* Windows requires `sun_path` to be encoded by UTF-8 */
WideCharToMultiByte(
CP_UTF8, 0, tmp_file, MAX_PATH, tmp_file_utf8, MAX_PATH, NULL, NULL);
listen_addr.sun_family = AF_UNIX;
if (strlcpy(listen_addr.sun_path, tmp_file_utf8, UNIX_PATH_MAX) >=
UNIX_PATH_MAX) {
event_warnx("Temp file name is too long");
goto tidy_up_and_fail;
}
if (bind(listener, (struct sockaddr *) &listen_addr, sizeof (listen_addr))
== -1)
goto tidy_up_and_fail;
if (listen(listener, 1) == -1)
goto tidy_up_and_fail;
connector = socket(family, type, 0);
if (connector < 0)
goto tidy_up_and_fail;
memset(&connect_addr, 0, sizeof(connect_addr));
/* We want to find out the port number to connect to. */
size = sizeof(connect_addr);
if (getsockname(listener, (struct sockaddr *) &connect_addr, &size) == -1)
goto tidy_up_and_fail;
if (connect(connector, (struct sockaddr *) &connect_addr,
sizeof(connect_addr)) == -1)
goto tidy_up_and_fail;
size = sizeof(listen_addr);
acceptor = accept(listener, (struct sockaddr *) &listen_addr, &size);
if (acceptor < 0)
goto tidy_up_and_fail;
if (size != sizeof(listen_addr))
goto abort_tidy_up_and_fail;
/* Now check we are talking to ourself by matching port and host on the
two sockets. */
if (getsockname(connector, (struct sockaddr *) &connect_addr, &size) == -1)
goto tidy_up_and_fail;
if (size != sizeof(connect_addr) ||
listen_addr.sun_family != connect_addr.sun_family ||
evutil_ascii_strcasecmp(listen_addr.sun_path, connect_addr.sun_path))
goto abort_tidy_up_and_fail;
evutil_closesocket(listener);
fd[0] = connector;
fd[1] = acceptor;
return 0;
abort_tidy_up_and_fail:
saved_errno = ERR(ECONNABORTED);
tidy_up_and_fail:
if (saved_errno < 0)
saved_errno = EVUTIL_SOCKET_ERROR();
if (listener != -1)
evutil_closesocket(listener);
if (connector != -1)
evutil_closesocket(connector);
if (acceptor != -1)
evutil_closesocket(acceptor);
if (tmp_file[0])
DeleteFileW(tmp_file);
EVUTIL_SET_SOCKET_ERROR(saved_errno);
return -1;
#undef ERR
}
#endif
static int
evutil_win_socketpair(int family, int type, int protocol,
evutil_socket_t fd[2])
{
#ifdef EVENT__HAVE_AFUNIX_H
/* The family only support AF_UNIX and AF_INET */
if (protocol || (family != AF_UNIX && family != AF_INET)) {
EVUTIL_SET_SOCKET_ERROR(WSAEAFNOSUPPORT);
return -1;
}
if (evutil_check_working_afunix_()) {
/* If the AF_UNIX socket works, we will change the family to
* AF_UNIX forcely. */
family = AF_UNIX;
if (type != SOCK_STREAM) {
/* Win10 does not support AF_UNIX socket of a type other
* than SOCK_STREAM still now. */
EVUTIL_SET_SOCKET_ERROR(WSAEAFNOSUPPORT);
return -1;
}
} else {
/* If the AF_UNIX socket does not work, we will change the
* family to AF_INET forcely. */
family = AF_INET;
}
if (family == AF_UNIX)
return evutil_win_socketpair_afunix(family, type, protocol, fd);
#endif
return evutil_ersatz_socketpair_(family, type, protocol, fd);
}
#endif
int
evutil_make_socket_nonblocking(evutil_socket_t fd)
{
#ifdef _WIN32
{
unsigned long nonblocking = 1;
if (ioctlsocket(fd, FIONBIO, &nonblocking) == SOCKET_ERROR) {
event_sock_warn(fd, "ioctlsocket(%d, FIONBIO, &%lu)", (int)fd, (unsigned long)nonblocking);
return -1;
}
}
#else
{
int flags;
if ((flags = fcntl(fd, F_GETFL, NULL)) < 0) {
event_warn("fcntl(%d, F_GETFL)", fd);
return -1;
}
if (!(flags & O_NONBLOCK)) {
if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) {
event_warn("fcntl(%d, F_SETFL)", fd);
return -1;
}
}
}
#endif
return 0;
}
/* Faster version of evutil_make_socket_nonblocking for internal use.
*
* Requires that no F_SETFL flags were previously set on the fd.
*/
static int
evutil_fast_socket_nonblocking(evutil_socket_t fd)
{
#ifdef _WIN32
return evutil_make_socket_nonblocking(fd);
#else
if (fcntl(fd, F_SETFL, O_NONBLOCK) == -1) {
event_warn("fcntl(%d, F_SETFL)", fd);
return -1;
}
return 0;
#endif
}
int
evutil_make_listen_socket_reuseable(evutil_socket_t sock)
{
#if defined(SO_REUSEADDR) && !defined(_WIN32)
int one = 1;
/* REUSEADDR on Unix means, "don't hang on to this address after the
* listener is closed." On Windows, though, it means "don't keep other
* processes from binding to this address while we're using it. */
return setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void*) &one,
(ev_socklen_t)sizeof(one));
#else
return 0;
#endif
}
int
evutil_make_listen_socket_reuseable_port(evutil_socket_t sock)
{
#if defined(__FreeBSD__) && __FreeBSD__ >= 12 && defined(SO_REUSEPORT_LB)
/* FreeBSD 12 introduced a new socket option named SO_REUSEPORT_LB
* with the capability of load balancing, it's the equivalent of
* the SO_REUSEPORTs on Linux and DragonFlyBSD. */
int enabled = 1;
return setsockopt(sock, SOL_SOCKET, SO_REUSEPORT_LB, (void*)&enabled,
(ev_socklen_t)sizeof(enabled));
#elif (defined(__linux__) || \
defined(_AIX73) || \
(defined(__DragonFly__) && __DragonFly_version >= 300600) || \
(defined(EVENT__SOLARIS_11_4) && EVENT__SOLARIS_11_4)) && \
defined(SO_REUSEPORT)
int enabled = 1;
/* SO_REUSEPORT on Linux 3.9+ means, "Multiple servers (processes or
* threads) can bind to the same port if they each set the option".
* In addition, the SO_REUSEPORT implementation distributes connections
* or datagrams evenly across all of the threads (or processes).
*
* DragonFlyBSD 3.6.0 extended SO_REUSEPORT to distribute workload to
* available sockets, which make it the same as Linux's SO_REUSEPORT.
*
* AIX 7.2.5 added the feature that would add the capability to distribute
* incoming connections across all listening ports for SO_REUSEPORT.
*
* Solaris 11 supported SO_REUSEPORT, but it's implemented only for
* binding to the same address and port, without load balancing.
* Solaris 11.4 extended SO_REUSEPORT with the capability of load balancing.
*/
return setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, (void*)&enabled,
(ev_socklen_t)sizeof(enabled));
#else
/* SO_REUSEPORTs on macOS and other BSDs only enable duplicate address and
* port bindings, load balancing is not included. Therefore, only the last
* socket that binds to a given address and port will receive all the traffic,
* which means that incoming connections/datagrams will be shifted from the
* old thread (or process) to the new one. That's not what we want, so we fail
* this operation on these systems to indicate that SO_REUSEPORT without load
* balancing is not supported. Otherwise, the callers would expected the load
* balancing capability when they get 0 as the return value of this function.
*/
return -1;
#endif
}
int
evutil_make_listen_socket_ipv6only(evutil_socket_t sock)
{
#if defined(IPV6_V6ONLY)
int one = 1;
return setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (void*) &one,
(ev_socklen_t)sizeof(one));
#endif
return 0;
}
int
evutil_make_listen_socket_not_ipv6only(evutil_socket_t sock)
{
#if defined(IPV6_V6ONLY)
int zero = 0;
return setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&zero,
(ev_socklen_t)sizeof(zero));
#endif
return 0;
}
int
evutil_make_tcp_listen_socket_deferred(evutil_socket_t sock)
{
#if defined(EVENT__HAVE_NETINET_TCP_H) && defined(TCP_DEFER_ACCEPT)
int one = 1;
/* TCP_DEFER_ACCEPT tells the kernel to call defer accept() only after data
* has arrived and ready to read */
return setsockopt(sock, IPPROTO_TCP, TCP_DEFER_ACCEPT, &one,
(ev_socklen_t)sizeof(one));
#endif
return 0;
}
int
evutil_make_socket_closeonexec(evutil_socket_t fd)
{
#if !defined(_WIN32) && defined(EVENT__HAVE_SETFD)
int flags;
if ((flags = fcntl(fd, F_GETFD, NULL)) < 0) {
event_warn("fcntl(%d, F_GETFD)", fd);
return -1;
}
if (!(flags & FD_CLOEXEC)) {
if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == -1) {
event_warn("fcntl(%d, F_SETFD)", fd);
return -1;
}
}
#endif
return 0;
}
/* Faster version of evutil_make_socket_closeonexec for internal use.
*
* Requires that no F_SETFD flags were previously set on the fd.
*/
static int
evutil_fast_socket_closeonexec(evutil_socket_t fd)
{
#if !defined(_WIN32) && defined(EVENT__HAVE_SETFD)
if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1) {
event_warn("fcntl(%d, F_SETFD)", fd);
return -1;
}
#endif
return 0;
}
int
evutil_closesocket(evutil_socket_t sock)
{
#ifndef _WIN32
return close(sock);
#else
return closesocket(sock);
#endif
}
ev_int64_t
evutil_strtoll(const char *s, char **endptr, int base)
{
#ifdef EVENT__HAVE_STRTOLL
return (ev_int64_t)strtoll(s, endptr, base);
#elif EVENT__SIZEOF_LONG == 8
return (ev_int64_t)strtol(s, endptr, base);
#elif defined(_WIN32) && defined(_MSC_VER) && _MSC_VER < 1300
/* XXXX on old versions of MS APIs, we only support base
* 10. */
ev_int64_t r;
if (base != 10)
return 0;
r = (ev_int64_t) _atoi64(s);
while (isspace(*s))
++s;
if (*s == '-')
++s;
while (isdigit(*s))
++s;
if (endptr)
*endptr = (char*) s;
return r;
#elif defined(_WIN32)
return (ev_int64_t) _strtoi64(s, endptr, base);
#elif defined(EVENT__SIZEOF_LONG_LONG) && EVENT__SIZEOF_LONG_LONG == 8
long long r;
int n;
if (base != 10 && base != 16)
return 0;
if (base == 10) {
n = sscanf(s, "%lld", &r);
} else {
unsigned long long ru=0;
n = sscanf(s, "%llx", &ru);
if (ru > EV_INT64_MAX)
return 0;
r = (long long) ru;
}
if (n != 1)
return 0;
while (EVUTIL_ISSPACE_(*s))
++s;
if (*s == '-')
++s;
if (base == 10) {
while (EVUTIL_ISDIGIT_(*s))
++s;
} else {
while (EVUTIL_ISXDIGIT_(*s))
++s;
}
if (endptr)
*endptr = (char*) s;
return r;
#else
#error "I don't know how to parse 64-bit integers."
#endif
}
#ifdef _WIN32
int
evutil_socket_geterror(evutil_socket_t sock)
{
int optval, optvallen=sizeof(optval);
int err = WSAGetLastError();
if (err == WSAEWOULDBLOCK && sock >= 0) {
if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)&optval,
&optvallen))
return err;
if (optval)
return optval;
}
return err;
}
#endif
/* XXX we should use an enum here. */
/* 2 for connection refused, 1 for connected, 0 for not yet, -1 for error. */
int
evutil_socket_connect_(evutil_socket_t *fd_ptr, const struct sockaddr *sa, int socklen)
{
int made_fd = 0;
if (*fd_ptr < 0) {
if ((*fd_ptr = socket(sa->sa_family, SOCK_STREAM, 0)) < 0)
goto err;
made_fd = 1;
if (evutil_make_socket_nonblocking(*fd_ptr) < 0) {
goto err;
}
}
if (connect(*fd_ptr, sa, socklen) < 0) {
int e = evutil_socket_geterror(*fd_ptr);
if (EVUTIL_ERR_CONNECT_RETRIABLE(e))
return 0;
if (EVUTIL_ERR_CONNECT_REFUSED(e))
return 2;
goto err;
} else {
return 1;
}
err:
if (made_fd) {
evutil_closesocket(*fd_ptr);
*fd_ptr = -1;
}
return -1;
}
/* Check whether a socket on which we called connect() is done
connecting. Return 1 for connected, 0 for not yet, -1 for error. In the
error case, set the current socket errno to the error that happened during
the connect operation. */
int
evutil_socket_finished_connecting_(evutil_socket_t fd)
{
int e;
ev_socklen_t elen = sizeof(e);
if (getsockopt(fd, SOL_SOCKET, SO_ERROR, (void*)&e, &elen) < 0)
return -1;
if (e) {
if (EVUTIL_ERR_CONNECT_RETRIABLE(e))
return 0;
EVUTIL_SET_SOCKET_ERROR(e);
return -1;
}
return 1;
}
#if (EVUTIL_AI_PASSIVE|EVUTIL_AI_CANONNAME|EVUTIL_AI_NUMERICHOST| \
EVUTIL_AI_NUMERICSERV|EVUTIL_AI_V4MAPPED|EVUTIL_AI_ALL| \
EVUTIL_AI_ADDRCONFIG) != \
(EVUTIL_AI_PASSIVE^EVUTIL_AI_CANONNAME^EVUTIL_AI_NUMERICHOST^ \
EVUTIL_AI_NUMERICSERV^EVUTIL_AI_V4MAPPED^EVUTIL_AI_ALL^ \
EVUTIL_AI_ADDRCONFIG)
#error "Some of our EVUTIL_AI_* flags seem to overlap with system AI_* flags"
#endif
/* We sometimes need to know whether we have an ipv4 address and whether we
have an ipv6 address. If 'have_checked_interfaces', then we've already done
the test. If 'had_ipv4_address', then it turns out we had an ipv4 address.
If 'had_ipv6_address', then it turns out we had an ipv6 address. These are
set by evutil_check_interfaces. */
static int have_checked_interfaces, had_ipv4_address, had_ipv6_address;
/* True iff the IPv4 address 'addr', in host order, is in 127.0.0.0/8 */
static inline int evutil_v4addr_is_localhost(ev_uint32_t addr)
{ return addr>>24 == 127; }
/* True iff the IPv4 address 'addr', in host order, is link-local
* 169.254.0.0/16 (RFC3927) */
static inline int evutil_v4addr_is_linklocal(ev_uint32_t addr)
{ return ((addr & 0xffff0000U) == 0xa9fe0000U); }
/* True iff the IPv4 address 'addr', in host order, is a class D
* (multiclass) address. */
static inline int evutil_v4addr_is_classd(ev_uint32_t addr)
{ return ((addr>>24) & 0xf0) == 0xe0; }
int
evutil_v4addr_is_local_(const struct in_addr *in)
{
const ev_uint32_t addr = ntohl(in->s_addr);
return addr == INADDR_ANY ||
evutil_v4addr_is_localhost(addr) ||
evutil_v4addr_is_linklocal(addr) ||
evutil_v4addr_is_classd(addr);
}
int
evutil_v6addr_is_local_(const struct in6_addr *in)
{
static const char ZEROES[] =
"\x00\x00\x00\x00\x00\x00\x00\x00"
"\x00\x00\x00\x00\x00\x00\x00\x00";
const unsigned char *addr = (const unsigned char *)in->s6_addr;
return !memcmp(addr, ZEROES, 8) ||
((addr[0] & 0xfe) == 0xfc) ||
(addr[0] == 0xfe && (addr[1] & 0xc0) == 0x80) ||
(addr[0] == 0xfe && (addr[1] & 0xc0) == 0xc0) ||
(addr[0] == 0xff);
}
static void
evutil_found_ifaddr(const struct sockaddr *sa)
{
if (sa->sa_family == AF_INET) {
const struct sockaddr_in *sin = (struct sockaddr_in *)sa;
if (!evutil_v4addr_is_local_(&sin->sin_addr)) {
event_debug(("Detected an IPv4 interface"));
had_ipv4_address = 1;
}
} else if (sa->sa_family == AF_INET6) {
const struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)sa;
if (!evutil_v6addr_is_local_(&sin6->sin6_addr)) {
event_debug(("Detected an IPv6 interface"));
had_ipv6_address = 1;
}
}
}
#ifdef _WIN32
typedef ULONG (WINAPI *GetAdaptersAddresses_fn_t)(
ULONG, ULONG, PVOID, PIP_ADAPTER_ADDRESSES, PULONG);
#endif
static int
evutil_check_ifaddrs(void)
{
#if defined(EVENT__HAVE_GETIFADDRS)
/* Most free Unixy systems provide getifaddrs, which gives us a linked list
* of struct ifaddrs. */
struct ifaddrs *ifa = NULL;
const struct ifaddrs *i;
if (getifaddrs(&ifa) < 0) {
event_warn("Unable to call getifaddrs()");
return -1;
}
for (i = ifa; i; i = i->ifa_next) {
if (!i->ifa_addr)
continue;
evutil_found_ifaddr(i->ifa_addr);
}
freeifaddrs(ifa);
return 0;
#elif defined(_WIN32)
/* Windows XP began to provide GetAdaptersAddresses. Windows 2000 had a
"GetAdaptersInfo", but that's deprecated; let's just try
GetAdaptersAddresses and fall back to connect+getsockname.
*/
HMODULE lib = evutil_load_windows_system_library_(TEXT("iphlpapi.dll"));
GetAdaptersAddresses_fn_t fn;
ULONG size, res;
IP_ADAPTER_ADDRESSES *addresses = NULL, *address;
int result = -1;
#define FLAGS (GAA_FLAG_SKIP_ANYCAST | \
GAA_FLAG_SKIP_MULTICAST | \
GAA_FLAG_SKIP_DNS_SERVER)
if (!lib)
goto done;
if (!(fn = (GetAdaptersAddresses_fn_t) GetProcAddress(lib, "GetAdaptersAddresses")))
goto done;
/* Guess how much space we need. */
size = 15*1024;
addresses = mm_malloc(size);
if (!addresses)
goto done;
res = fn(AF_UNSPEC, FLAGS, NULL, addresses, &size);
if (res == ERROR_BUFFER_OVERFLOW) {
/* we didn't guess that we needed enough space; try again */
mm_free(addresses);
addresses = mm_malloc(size);
if (!addresses)
goto done;
res = fn(AF_UNSPEC, FLAGS, NULL, addresses, &size);
}
if (res != NO_ERROR)
goto done;
for (address = addresses; address; address = address->Next) {
IP_ADAPTER_UNICAST_ADDRESS *a;
for (a = address->FirstUnicastAddress; a; a = a->Next) {
/* Yes, it's a linked list inside a linked list */
struct sockaddr *sa = a->Address.lpSockaddr;
evutil_found_ifaddr(sa);
}
}
result = 0;
done:
if (lib)
FreeLibrary(lib);
if (addresses)
mm_free(addresses);
return result;
#else
return -1;
#endif
}
/* Test whether we have an ipv4 interface and an ipv6 interface. Return 0 if
* the test seemed successful. */
static int
evutil_check_interfaces(void)
{
evutil_socket_t fd = -1;
struct sockaddr_in sin, sin_out;
struct sockaddr_in6 sin6, sin6_out;
ev_socklen_t sin_out_len = sizeof(sin_out);
ev_socklen_t sin6_out_len = sizeof(sin6_out);
int r;
if (have_checked_interfaces)
return 0;
/* From this point on we have done the ipv4/ipv6 interface check */
have_checked_interfaces = 1;
if (evutil_check_ifaddrs() == 0) {
/* Use a nice sane interface, if this system has one. */
return 0;
}
/* Ugh. There was no nice sane interface. So to check whether we have
* an interface open for a given protocol, will try to make a UDP
* 'connection' to a remote host on the internet. We don't actually
* use it, so the address doesn't matter, but we want to pick one that
* keep us from using a host- or link-local interface. */
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_port = htons(53);
r = evutil_inet_pton(AF_INET, "18.244.0.188", &sin.sin_addr);
EVUTIL_ASSERT(r);
memset(&sin6, 0, sizeof(sin6));
sin6.sin6_family = AF_INET6;
sin6.sin6_port = htons(53);
r = evutil_inet_pton(AF_INET6, "2001:4860:b002::68", &sin6.sin6_addr);
EVUTIL_ASSERT(r);
memset(&sin_out, 0, sizeof(sin_out));
memset(&sin6_out, 0, sizeof(sin6_out));
/* XXX some errnos mean 'no address'; some mean 'not enough sockets'. */
if ((fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) >= 0 &&
connect(fd, (struct sockaddr*)&sin, sizeof(sin)) == 0 &&
getsockname(fd, (struct sockaddr*)&sin_out, &sin_out_len) == 0) {
/* We might have an IPv4 interface. */
evutil_found_ifaddr((struct sockaddr*) &sin_out);
}
if (fd >= 0)
evutil_closesocket(fd);
if ((fd = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP)) >= 0 &&
connect(fd, (struct sockaddr*)&sin6, sizeof(sin6)) == 0 &&
getsockname(fd, (struct sockaddr*)&sin6_out, &sin6_out_len) == 0) {
/* We might have an IPv6 interface. */
evutil_found_ifaddr((struct sockaddr*) &sin6_out);
}
if (fd >= 0)
evutil_closesocket(fd);
return 0;
}
/* Internal addrinfo flag. This one is set when we allocate the addrinfo from
* inside libevent. Otherwise, the built-in getaddrinfo() function allocated
* it, and we should trust what they said.
**/
#define EVUTIL_AI_LIBEVENT_ALLOCATED 0x80000000
/* Helper: construct a new addrinfo containing the socket address in
* 'sa', which must be a sockaddr_in or a sockaddr_in6. Take the
* socktype and protocol info from hints. If they weren't set, then
* allocate both a TCP and a UDP addrinfo.
*/
struct evutil_addrinfo *
evutil_new_addrinfo_(struct sockaddr *sa, ev_socklen_t socklen,
const struct evutil_addrinfo *hints)
{
struct evutil_addrinfo *res;
EVUTIL_ASSERT(hints);
if (hints->ai_socktype == 0 && hints->ai_protocol == 0) {
/* Indecisive user! Give them a UDP and a TCP. */
struct evutil_addrinfo *r1, *r2;
struct evutil_addrinfo tmp;
memcpy(&tmp, hints, sizeof(tmp));
tmp.ai_socktype = SOCK_STREAM; tmp.ai_protocol = IPPROTO_TCP;