Coverage Report

Created: 2024-02-25 06:25

/src/libevent/evutil.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
 * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
3
 *
4
 * Redistribution and use in source and binary forms, with or without
5
 * modification, are permitted provided that the following conditions
6
 * are met:
7
 * 1. Redistributions of source code must retain the above copyright
8
 *    notice, this list of conditions and the following disclaimer.
9
 * 2. Redistributions in binary form must reproduce the above copyright
10
 *    notice, this list of conditions and the following disclaimer in the
11
 *    documentation and/or other materials provided with the distribution.
12
 * 3. The name of the author may not be used to endorse or promote products
13
 *    derived from this software without specific prior written permission.
14
 *
15
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25
 */
26
27
#ifdef _WIN32
28
#ifndef _WIN32_WINNT
29
/* For structs needed by GetAdaptersAddresses and AI_NUMERICSERV */
30
#define _WIN32_WINNT 0x0600
31
#endif
32
#define WIN32_LEAN_AND_MEAN
33
#endif
34
35
#include "event2/event-config.h"
36
#include "evconfig-private.h"
37
38
#ifdef _WIN32
39
#include <winsock2.h>
40
#include <winerror.h>
41
#include <ws2tcpip.h>
42
#ifdef EVENT__HAVE_AFUNIX_H
43
#include <afunix.h>
44
#endif
45
#include <windows.h>
46
#include <io.h>
47
#include <tchar.h>
48
#include <process.h>
49
#include <iphlpapi.h>
50
#include <netioapi.h>
51
#endif
52
53
#include <sys/types.h>
54
#ifdef EVENT__HAVE_SYS_SOCKET_H
55
#include <sys/socket.h>
56
#endif
57
#ifdef EVENT__HAVE_UNISTD_H
58
#include <unistd.h>
59
#endif
60
#ifdef EVENT__HAVE_FCNTL_H
61
#include <fcntl.h>
62
#endif
63
#ifdef EVENT__HAVE_STDLIB_H
64
#include <stdlib.h>
65
#endif
66
#include <errno.h>
67
#include <limits.h>
68
#include <stdio.h>
69
#include <string.h>
70
#ifdef EVENT__HAVE_NETINET_IN_H
71
#include <netinet/in.h>
72
#endif
73
#ifdef EVENT__HAVE_NETINET_IN6_H
74
#include <netinet/in6.h>
75
#endif
76
#ifdef EVENT__HAVE_NETINET_TCP_H
77
#include <netinet/tcp.h>
78
#endif
79
#ifdef EVENT__HAVE_ARPA_INET_H
80
#include <arpa/inet.h>
81
#endif
82
#include <time.h>
83
#include <sys/stat.h>
84
#ifndef _WIN32
85
#include <net/if.h>
86
#endif
87
#ifdef EVENT__HAVE_IFADDRS_H
88
#include <ifaddrs.h>
89
#endif
90
91
#include "event2/util.h"
92
#include "util-internal.h"
93
#include "log-internal.h"
94
#include "mm-internal.h"
95
#include "evthread-internal.h"
96
97
#include "strlcpy-internal.h"
98
#include "ipv6-internal.h"
99
100
#ifdef _WIN32
101
#define HT_NO_CACHE_HASH_VALUES
102
#include "ht-internal.h"
103
#define open _open
104
#define read _read
105
#define close _close
106
#ifndef fstat
107
#define fstat _fstati64
108
#endif
109
#ifndef stat
110
#define stat _stati64
111
#endif
112
#define mode_t int
113
#endif
114
115
#ifndef O_RDONLY
116
#define O_RDONLY _O_RDONLY
117
#endif
118
119
#ifdef EVENT__HAVE_AFUNIX_H
120
int have_working_afunix_ = -1;
121
#endif
122
123
int
124
evutil_open_closeonexec_(const char *pathname, int flags, unsigned mode)
125
128
{
126
128
  int fd;
127
128
128
#ifdef O_CLOEXEC
129
128
  fd = open(pathname, flags|O_CLOEXEC, (mode_t)mode);
130
128
  if (fd >= 0 || errno == EINVAL)
131
96
    return fd;
132
  /* If we got an EINVAL, fall through and try without O_CLOEXEC */
133
32
#endif
134
32
  fd = open(pathname, flags, (mode_t)mode);
135
32
  if (fd < 0)
136
32
    return -1;
137
138
0
#if defined(FD_CLOEXEC)
139
0
  if (fcntl(fd, F_SETFD, FD_CLOEXEC) < 0) {
140
0
    close(fd);
141
0
    return -1;
142
0
  }
143
0
#endif
144
145
0
  return fd;
146
0
}
147
148
/**
149
   Read the contents of 'filename' into a newly allocated NUL-terminated
150
   string.  Set *content_out to hold this string, and *len_out to hold its
151
   length (not including the appended NUL).  If 'is_binary', open the file in
152
   binary mode.
153
154
   Returns 0 on success, -1 if the open fails, and -2 for all other failures.
155
156
   Used internally only; may go away in a future version.
157
 */
158
int
159
evutil_read_file_(const char *filename, char **content_out, size_t *len_out,
160
    int is_binary)
161
0
{
162
0
  int fd, r;
163
0
  struct stat st;
164
0
  char *mem;
165
0
  size_t read_so_far=0;
166
0
  int mode = O_RDONLY;
167
168
0
  EVUTIL_ASSERT(content_out);
169
0
  EVUTIL_ASSERT(len_out);
170
0
  *content_out = NULL;
171
0
  *len_out = 0;
172
173
#ifdef O_BINARY
174
  if (is_binary)
175
    mode |= O_BINARY;
176
#endif
177
178
0
  fd = evutil_open_closeonexec_(filename, mode, 0);
179
0
  if (fd < 0)
180
0
    return -1;
181
0
  if (fstat(fd, &st) || st.st_size < 0 ||
182
0
      st.st_size > EV_SSIZE_MAX-1 ) {
183
0
    close(fd);
184
0
    return -2;
185
0
  }
186
0
  mem = mm_malloc((size_t)st.st_size + 1);
187
0
  if (!mem) {
188
0
    close(fd);
189
0
    return -2;
190
0
  }
191
0
  read_so_far = 0;
192
#ifdef _WIN32
193
#define N_TO_READ(x) ((x) > INT_MAX) ? INT_MAX : ((int)(x))
194
#else
195
0
#define N_TO_READ(x) (x)
196
0
#endif
197
0
  while ((r = read(fd, mem+read_so_far, N_TO_READ(st.st_size - read_so_far))) > 0) {
198
0
    read_so_far += r;
199
0
    if (read_so_far >= (size_t)st.st_size)
200
0
      break;
201
0
    EVUTIL_ASSERT(read_so_far < (size_t)st.st_size);
202
0
  }
203
0
  close(fd);
204
0
  if (r < 0) {
205
0
    mm_free(mem);
206
0
    return -2;
207
0
  }
208
0
  mem[read_so_far] = 0;
209
210
0
  *len_out = read_so_far;
211
0
  *content_out = mem;
212
0
  return 0;
213
0
}
214
215
#ifdef _WIN32
216
217
static int
218
create_tmpfile(WCHAR tmpfile[MAX_PATH])
219
{
220
  WCHAR short_path[MAX_PATH] = {0};
221
  WCHAR long_path[MAX_PATH] = {0};
222
  WCHAR prefix[4] = {0};
223
  // GetTempFileNameW() uses up to the first three characters of the prefix
224
  // and windows filesystems are case-insensitive
225
  const WCHAR *base32set = L"abcdefghijklmnopqrstuvwxyz012345";
226
  ev_uint16_t rnd;
227
228
  evutil_secure_rng_get_bytes(&rnd, sizeof(rnd));
229
  prefix[0] = base32set[(rnd      ) & 31];
230
  prefix[1] = base32set[(rnd >>  5) & 31];
231
  prefix[2] = base32set[(rnd >> 10) & 31];
232
  prefix[3] = '\0';
233
234
  GetTempPathW(MAX_PATH, short_path);
235
  GetLongPathNameW(short_path, long_path, MAX_PATH);
236
  if (!GetTempFileNameW(long_path, prefix, 0, tmpfile)) {
237
    event_warnx("GetTempFileName failed: %d", EVUTIL_SOCKET_ERROR());
238
    return -1;
239
  }
240
  return 0;
241
}
242
243
#ifdef EVENT__HAVE_AFUNIX_H
244
/* Test whether Unix domain socket works.
245
 * Return 1 if it works, otherwise 0    */
246
int
247
evutil_check_working_afunix_()
248
{
249
  /* Windows 10 began to support Unix domain socket. Let's just try
250
   * socket(AF_UNIX, , ) and fall back to socket(AF_INET, , ).
251
   * https://devblogs.microsoft.com/commandline/af_unix-comes-to-windows/
252
   */
253
  evutil_socket_t sd = -1;
254
  if (have_working_afunix_ < 0) {
255
    if ((sd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
256
      have_working_afunix_ = 0;
257
    } else {
258
      have_working_afunix_ = 1;
259
      evutil_closesocket(sd);
260
    }
261
  }
262
  return have_working_afunix_;
263
}
264
265
/* XXX Copy from evutil_ersatz_socketpair_() */
266
static int
267
evutil_win_socketpair_afunix(int family, int type, int protocol,
268
    evutil_socket_t fd[2])
269
{
270
#undef ERR
271
#define ERR(e) WSA##e
272
  evutil_socket_t listener = -1;
273
  evutil_socket_t connector = -1;
274
  evutil_socket_t acceptor = -1;
275
276
  struct sockaddr_un listen_addr;
277
  struct sockaddr_un connect_addr;
278
  WCHAR tmp_file[MAX_PATH] = {0};
279
  char tmp_file_utf8[MAX_PATH] = {0};
280
281
  ev_socklen_t size;
282
  int saved_errno = -1;
283
284
  if (!fd) {
285
    EVUTIL_SET_SOCKET_ERROR(ERR(EINVAL));
286
    return -1;
287
  }
288
289
  listener = socket(family, type, 0);
290
  if (listener < 0)
291
    return -1;
292
  memset(&listen_addr, 0, sizeof(listen_addr));
293
294
  if (create_tmpfile(tmp_file)) {
295
    goto tidy_up_and_fail;
296
  }
297
  DeleteFileW(tmp_file);
298
299
  /* Windows requires `sun_path` to be encoded by UTF-8 */
300
  WideCharToMultiByte(
301
    CP_UTF8, 0, tmp_file, MAX_PATH, tmp_file_utf8, MAX_PATH, NULL, NULL);
302
303
  listen_addr.sun_family = AF_UNIX;
304
  if (strlcpy(listen_addr.sun_path, tmp_file_utf8, UNIX_PATH_MAX) >=
305
    UNIX_PATH_MAX) {
306
    event_warnx("Temp file name is too long");
307
    goto tidy_up_and_fail;
308
  }
309
310
  if (bind(listener, (struct sockaddr *) &listen_addr, sizeof (listen_addr))
311
    == -1)
312
    goto tidy_up_and_fail;
313
  if (listen(listener, 1) == -1)
314
    goto tidy_up_and_fail;
315
316
  connector = socket(family, type, 0);
317
  if (connector < 0)
318
    goto tidy_up_and_fail;
319
320
  memset(&connect_addr, 0, sizeof(connect_addr));
321
322
  /* We want to find out the port number to connect to.  */
323
  size = sizeof(connect_addr);
324
  if (getsockname(listener, (struct sockaddr *) &connect_addr, &size) == -1)
325
    goto tidy_up_and_fail;
326
327
  if (connect(connector, (struct sockaddr *) &connect_addr,
328
        sizeof(connect_addr)) == -1)
329
    goto tidy_up_and_fail;
330
331
  size = sizeof(listen_addr);
332
  acceptor = accept(listener, (struct sockaddr *) &listen_addr, &size);
333
  if (acceptor < 0)
334
    goto tidy_up_and_fail;
335
  if (size != sizeof(listen_addr))
336
    goto abort_tidy_up_and_fail;
337
  /* Now check we are talking to ourself by matching port and host on the
338
     two sockets.  */
339
  if (getsockname(connector, (struct sockaddr *) &connect_addr, &size) == -1)
340
    goto tidy_up_and_fail;
341
342
  if (size != sizeof(connect_addr) ||
343
      listen_addr.sun_family != connect_addr.sun_family ||
344
      evutil_ascii_strcasecmp(listen_addr.sun_path, connect_addr.sun_path))
345
    goto abort_tidy_up_and_fail;
346
347
  evutil_closesocket(listener);
348
  fd[0] = connector;
349
  fd[1] = acceptor;
350
351
  return 0;
352
353
 abort_tidy_up_and_fail:
354
  saved_errno = ERR(ECONNABORTED);
355
 tidy_up_and_fail:
356
  if (saved_errno < 0)
357
    saved_errno = EVUTIL_SOCKET_ERROR();
358
  if (listener != -1)
359
    evutil_closesocket(listener);
360
  if (connector != -1)
361
    evutil_closesocket(connector);
362
  if (acceptor != -1)
363
    evutil_closesocket(acceptor);
364
  if (tmp_file[0])
365
    DeleteFileW(tmp_file);
366
367
  EVUTIL_SET_SOCKET_ERROR(saved_errno);
368
  return -1;
369
#undef ERR
370
}
371
#endif
372
373
static int
374
evutil_win_socketpair(int family, int type, int protocol,
375
    evutil_socket_t fd[2])
376
{
377
#ifdef EVENT__HAVE_AFUNIX_H
378
  /* The family only support AF_UNIX and AF_INET */
379
  if (protocol || (family != AF_UNIX && family != AF_INET)) {
380
    EVUTIL_SET_SOCKET_ERROR(WSAEAFNOSUPPORT);
381
    return -1;
382
  }
383
  if (evutil_check_working_afunix_()) {
384
    /* If the AF_UNIX socket works, we will change the family to
385
     * AF_UNIX forcely. */
386
    family = AF_UNIX;
387
    if (type != SOCK_STREAM) {
388
      /* Win10 does not support AF_UNIX socket of a type other
389
       * than SOCK_STREAM still now. */
390
      EVUTIL_SET_SOCKET_ERROR(WSAEAFNOSUPPORT);
391
      return -1;
392
    }
393
  } else {
394
    /* If the AF_UNIX socket does not work, we will change the
395
     * family to AF_INET forcely. */
396
    family = AF_INET;
397
  }
398
  if (family == AF_UNIX)
399
    return evutil_win_socketpair_afunix(family, type, protocol, fd);
400
401
#endif
402
  return evutil_ersatz_socketpair_(family, type, protocol, fd);
403
}
404
#endif
405
406
int
407
evutil_socketpair(int family, int type, int protocol, evutil_socket_t fd[2])
408
0
{
409
#if defined(_WIN32)
410
  return evutil_win_socketpair(family, type, protocol, fd);
411
#elif defined(EVENT__HAVE_SOCKETPAIR)
412
0
  return socketpair(family, type, protocol, fd);
413
#else
414
  return evutil_ersatz_socketpair_(family, type, protocol, fd);
415
#endif
416
0
}
417
418
int
419
evutil_ersatz_socketpair_(int family, int type, int protocol,
420
    evutil_socket_t fd[2])
421
0
{
422
  /* This code is originally from Tor.  Used with permission. */
423
424
  /* This socketpair does not work when localhost is down. So
425
   * it's really not the same thing at all. But it's close enough
426
   * for now, and really, when localhost is down sometimes, we
427
   * have other problems too.
428
   */
429
0
#undef ERR
430
#ifdef _WIN32
431
#define ERR(e) WSA##e
432
#else
433
0
#define ERR(e) e
434
0
#endif
435
0
  evutil_socket_t listener = -1;
436
0
  evutil_socket_t connector = -1;
437
0
  evutil_socket_t acceptor = -1;
438
0
  struct sockaddr_in listen_addr;
439
0
  struct sockaddr_in connect_addr;
440
0
  ev_socklen_t size;
441
0
  int saved_errno = -1;
442
0
  int family_test;
443
444
0
  family_test = family != AF_INET;
445
0
#ifdef AF_UNIX
446
0
  family_test = family_test && (family != AF_UNIX);
447
0
#endif
448
0
  if (protocol || family_test) {
449
0
    EVUTIL_SET_SOCKET_ERROR(ERR(EAFNOSUPPORT));
450
0
    return -1;
451
0
  }
452
453
0
  if (!fd) {
454
0
    EVUTIL_SET_SOCKET_ERROR(ERR(EINVAL));
455
0
    return -1;
456
0
  }
457
458
0
  listener = socket(AF_INET, type, 0);
459
0
  if (listener < 0)
460
0
    return -1;
461
0
  memset(&listen_addr, 0, sizeof(listen_addr));
462
0
  listen_addr.sin_family = AF_INET;
463
0
  listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
464
0
  listen_addr.sin_port = 0; /* kernel chooses port.  */
465
0
  if (bind(listener, (struct sockaddr *) &listen_addr, sizeof (listen_addr))
466
0
    == -1)
467
0
    goto tidy_up_and_fail;
468
0
  if (listen(listener, 1) == -1)
469
0
    goto tidy_up_and_fail;
470
471
0
  connector = socket(AF_INET, type, 0);
472
0
  if (connector < 0)
473
0
    goto tidy_up_and_fail;
474
475
0
  memset(&connect_addr, 0, sizeof(connect_addr));
476
477
  /* We want to find out the port number to connect to.  */
478
0
  size = sizeof(connect_addr);
479
0
  if (getsockname(listener, (struct sockaddr *) &connect_addr, &size) == -1)
480
0
    goto tidy_up_and_fail;
481
0
  if (size != sizeof (connect_addr))
482
0
    goto abort_tidy_up_and_fail;
483
0
  if (connect(connector, (struct sockaddr *) &connect_addr,
484
0
        sizeof(connect_addr)) == -1)
485
0
    goto tidy_up_and_fail;
486
487
0
  size = sizeof(listen_addr);
488
0
  acceptor = accept(listener, (struct sockaddr *) &listen_addr, &size);
489
0
  if (acceptor < 0)
490
0
    goto tidy_up_and_fail;
491
0
  if (size != sizeof(listen_addr))
492
0
    goto abort_tidy_up_and_fail;
493
  /* Now check we are talking to ourself by matching port and host on the
494
     two sockets.  */
495
0
  if (getsockname(connector, (struct sockaddr *) &connect_addr, &size) == -1)
496
0
    goto tidy_up_and_fail;
497
0
  if (size != sizeof (connect_addr)
498
0
    || listen_addr.sin_family != connect_addr.sin_family
499
0
    || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
500
0
    || listen_addr.sin_port != connect_addr.sin_port)
501
0
    goto abort_tidy_up_and_fail;
502
0
  evutil_closesocket(listener);
503
0
  fd[0] = connector;
504
0
  fd[1] = acceptor;
505
506
0
  return 0;
507
508
0
 abort_tidy_up_and_fail:
509
0
  saved_errno = ERR(ECONNABORTED);
510
0
 tidy_up_and_fail:
511
0
  if (saved_errno < 0)
512
0
    saved_errno = EVUTIL_SOCKET_ERROR();
513
0
  if (listener != -1)
514
0
    evutil_closesocket(listener);
515
0
  if (connector != -1)
516
0
    evutil_closesocket(connector);
517
0
  if (acceptor != -1)
518
0
    evutil_closesocket(acceptor);
519
520
0
  EVUTIL_SET_SOCKET_ERROR(saved_errno);
521
0
  return -1;
522
0
#undef ERR
523
0
}
524
525
int
526
evutil_make_socket_nonblocking(evutil_socket_t fd)
527
0
{
528
#ifdef _WIN32
529
  {
530
    unsigned long nonblocking = 1;
531
    if (ioctlsocket(fd, FIONBIO, &nonblocking) == SOCKET_ERROR) {
532
      event_sock_warn(fd, "ioctlsocket(%d, FIONBIO, &%lu)", (int)fd, (unsigned long)nonblocking);
533
      return -1;
534
    }
535
  }
536
#else
537
0
  {
538
0
    int flags;
539
0
    if ((flags = fcntl(fd, F_GETFL, NULL)) < 0) {
540
0
      event_warn("fcntl(%d, F_GETFL)", fd);
541
0
      return -1;
542
0
    }
543
0
    if (!(flags & O_NONBLOCK)) {
544
0
      if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) {
545
0
        event_warn("fcntl(%d, F_SETFL)", fd);
546
0
        return -1;
547
0
      }
548
0
    }
549
0
  }
550
0
#endif
551
0
  return 0;
552
0
}
553
554
/* Faster version of evutil_make_socket_nonblocking for internal use.
555
 *
556
 * Requires that no F_SETFL flags were previously set on the fd.
557
 */
558
static int
559
evutil_fast_socket_nonblocking(evutil_socket_t fd)
560
0
{
561
#ifdef _WIN32
562
  return evutil_make_socket_nonblocking(fd);
563
#else
564
0
  if (fcntl(fd, F_SETFL, O_NONBLOCK) == -1) {
565
0
    event_warn("fcntl(%d, F_SETFL)", fd);
566
0
    return -1;
567
0
  }
568
0
  return 0;
569
0
#endif
570
0
}
571
572
int
573
evutil_make_listen_socket_reuseable(evutil_socket_t sock)
574
0
{
575
0
#if defined(SO_REUSEADDR) && !defined(_WIN32)
576
0
  int one = 1;
577
  /* REUSEADDR on Unix means, "don't hang on to this address after the
578
   * listener is closed."  On Windows, though, it means "don't keep other
579
   * processes from binding to this address while we're using it. */
580
0
  return setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void*) &one,
581
0
      (ev_socklen_t)sizeof(one));
582
#else
583
  return 0;
584
#endif
585
0
}
586
587
int
588
evutil_make_listen_socket_reuseable_port(evutil_socket_t sock)
589
0
{
590
0
#if defined __linux__ && defined(SO_REUSEPORT)
591
0
  int one = 1;
592
  /* REUSEPORT on Linux 3.9+ means, "Multiple servers (processes or
593
   * threads) can bind to the same port if they each set the option. */
594
0
  return setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, (void*) &one,
595
0
      (ev_socklen_t)sizeof(one));
596
#else
597
  return 0;
598
#endif
599
0
}
600
601
int
602
evutil_make_listen_socket_ipv6only(evutil_socket_t sock)
603
0
{
604
0
#if defined(IPV6_V6ONLY)
605
0
  int one = 1;
606
0
  return setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (void*) &one,
607
0
      (ev_socklen_t)sizeof(one));
608
0
#endif
609
0
  return 0;
610
0
}
611
612
int
613
evutil_make_listen_socket_not_ipv6only(evutil_socket_t sock)
614
0
{
615
0
#if defined(IPV6_V6ONLY)
616
0
  int zero = 0;
617
0
  return setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&zero,
618
0
    (ev_socklen_t)sizeof(zero));
619
0
#endif
620
0
  return 0;
621
0
}
622
623
int
624
evutil_make_tcp_listen_socket_deferred(evutil_socket_t sock)
625
0
{
626
0
#if defined(EVENT__HAVE_NETINET_TCP_H) && defined(TCP_DEFER_ACCEPT)
627
0
  int one = 1;
628
629
  /* TCP_DEFER_ACCEPT tells the kernel to call defer accept() only after data
630
   * has arrived and ready to read */
631
0
  return setsockopt(sock, IPPROTO_TCP, TCP_DEFER_ACCEPT, &one,
632
0
    (ev_socklen_t)sizeof(one));
633
0
#endif
634
0
  return 0;
635
0
}
636
637
int
638
evutil_make_socket_closeonexec(evutil_socket_t fd)
639
0
{
640
0
#if !defined(_WIN32) && defined(EVENT__HAVE_SETFD)
641
0
  int flags;
642
0
  if ((flags = fcntl(fd, F_GETFD, NULL)) < 0) {
643
0
    event_warn("fcntl(%d, F_GETFD)", fd);
644
0
    return -1;
645
0
  }
646
0
  if (!(flags & FD_CLOEXEC)) {
647
0
    if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == -1) {
648
0
      event_warn("fcntl(%d, F_SETFD)", fd);
649
0
      return -1;
650
0
    }
651
0
  }
652
0
#endif
653
0
  return 0;
654
0
}
655
656
/* Faster version of evutil_make_socket_closeonexec for internal use.
657
 *
658
 * Requires that no F_SETFD flags were previously set on the fd.
659
 */
660
static int
661
evutil_fast_socket_closeonexec(evutil_socket_t fd)
662
0
{
663
0
#if !defined(_WIN32) && defined(EVENT__HAVE_SETFD)
664
0
  if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1) {
665
0
    event_warn("fcntl(%d, F_SETFD)", fd);
666
0
    return -1;
667
0
  }
668
0
#endif
669
0
  return 0;
670
0
}
671
672
int
673
evutil_closesocket(evutil_socket_t sock)
674
0
{
675
0
#ifndef _WIN32
676
0
  return close(sock);
677
#else
678
  return closesocket(sock);
679
#endif
680
0
}
681
682
ev_int64_t
683
evutil_strtoll(const char *s, char **endptr, int base)
684
0
{
685
0
#ifdef EVENT__HAVE_STRTOLL
686
0
  return (ev_int64_t)strtoll(s, endptr, base);
687
#elif EVENT__SIZEOF_LONG == 8
688
  return (ev_int64_t)strtol(s, endptr, base);
689
#elif defined(_WIN32) && defined(_MSC_VER) && _MSC_VER < 1300
690
  /* XXXX on old versions of MS APIs, we only support base
691
   * 10. */
692
  ev_int64_t r;
693
  if (base != 10)
694
    return 0;
695
  r = (ev_int64_t) _atoi64(s);
696
  while (isspace(*s))
697
    ++s;
698
  if (*s == '-')
699
    ++s;
700
  while (isdigit(*s))
701
    ++s;
702
  if (endptr)
703
    *endptr = (char*) s;
704
  return r;
705
#elif defined(_WIN32)
706
  return (ev_int64_t) _strtoi64(s, endptr, base);
707
#elif defined(EVENT__SIZEOF_LONG_LONG) && EVENT__SIZEOF_LONG_LONG == 8
708
  long long r;
709
  int n;
710
  if (base != 10 && base != 16)
711
    return 0;
712
  if (base == 10) {
713
    n = sscanf(s, "%lld", &r);
714
  } else {
715
    unsigned long long ru=0;
716
    n = sscanf(s, "%llx", &ru);
717
    if (ru > EV_INT64_MAX)
718
      return 0;
719
    r = (long long) ru;
720
  }
721
  if (n != 1)
722
    return 0;
723
  while (EVUTIL_ISSPACE_(*s))
724
    ++s;
725
  if (*s == '-')
726
    ++s;
727
  if (base == 10) {
728
    while (EVUTIL_ISDIGIT_(*s))
729
      ++s;
730
  } else {
731
    while (EVUTIL_ISXDIGIT_(*s))
732
      ++s;
733
  }
734
  if (endptr)
735
    *endptr = (char*) s;
736
  return r;
737
#else
738
#error "I don't know how to parse 64-bit integers."
739
#endif
740
0
}
741
742
#ifdef _WIN32
743
int
744
evutil_socket_geterror(evutil_socket_t sock)
745
{
746
  int optval, optvallen=sizeof(optval);
747
  int err = WSAGetLastError();
748
  if (err == WSAEWOULDBLOCK && sock >= 0) {
749
    if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)&optval,
750
             &optvallen))
751
      return err;
752
    if (optval)
753
      return optval;
754
  }
755
  return err;
756
}
757
#endif
758
759
/* XXX we should use an enum here. */
760
/* 2 for connection refused, 1 for connected, 0 for not yet, -1 for error. */
761
int
762
evutil_socket_connect_(evutil_socket_t *fd_ptr, const struct sockaddr *sa, int socklen)
763
0
{
764
0
  int made_fd = 0;
765
766
0
  if (*fd_ptr < 0) {
767
0
    if ((*fd_ptr = socket(sa->sa_family, SOCK_STREAM, 0)) < 0)
768
0
      goto err;
769
0
    made_fd = 1;
770
0
    if (evutil_make_socket_nonblocking(*fd_ptr) < 0) {
771
0
      goto err;
772
0
    }
773
0
  }
774
775
0
  if (connect(*fd_ptr, sa, socklen) < 0) {
776
0
    int e = evutil_socket_geterror(*fd_ptr);
777
0
    if (EVUTIL_ERR_CONNECT_RETRIABLE(e))
778
0
      return 0;
779
0
    if (EVUTIL_ERR_CONNECT_REFUSED(e))
780
0
      return 2;
781
0
    goto err;
782
0
  } else {
783
0
    return 1;
784
0
  }
785
786
0
err:
787
0
  if (made_fd) {
788
0
    evutil_closesocket(*fd_ptr);
789
0
    *fd_ptr = -1;
790
0
  }
791
0
  return -1;
792
0
}
793
794
/* Check whether a socket on which we called connect() is done
795
   connecting. Return 1 for connected, 0 for not yet, -1 for error.  In the
796
   error case, set the current socket errno to the error that happened during
797
   the connect operation. */
798
int
799
evutil_socket_finished_connecting_(evutil_socket_t fd)
800
0
{
801
0
  int e;
802
0
  ev_socklen_t elen = sizeof(e);
803
804
0
  if (getsockopt(fd, SOL_SOCKET, SO_ERROR, (void*)&e, &elen) < 0)
805
0
    return -1;
806
807
0
  if (e) {
808
0
    if (EVUTIL_ERR_CONNECT_RETRIABLE(e))
809
0
      return 0;
810
0
    EVUTIL_SET_SOCKET_ERROR(e);
811
0
    return -1;
812
0
  }
813
814
0
  return 1;
815
0
}
816
817
#if (EVUTIL_AI_PASSIVE|EVUTIL_AI_CANONNAME|EVUTIL_AI_NUMERICHOST| \
818
     EVUTIL_AI_NUMERICSERV|EVUTIL_AI_V4MAPPED|EVUTIL_AI_ALL| \
819
     EVUTIL_AI_ADDRCONFIG) != \
820
    (EVUTIL_AI_PASSIVE^EVUTIL_AI_CANONNAME^EVUTIL_AI_NUMERICHOST^ \
821
     EVUTIL_AI_NUMERICSERV^EVUTIL_AI_V4MAPPED^EVUTIL_AI_ALL^ \
822
     EVUTIL_AI_ADDRCONFIG)
823
#error "Some of our EVUTIL_AI_* flags seem to overlap with system AI_* flags"
824
#endif
825
826
/* We sometimes need to know whether we have an ipv4 address and whether we
827
   have an ipv6 address. If 'have_checked_interfaces', then we've already done
828
   the test.  If 'had_ipv4_address', then it turns out we had an ipv4 address.
829
   If 'had_ipv6_address', then it turns out we had an ipv6 address.   These are
830
   set by evutil_check_interfaces. */
831
static int have_checked_interfaces, had_ipv4_address, had_ipv6_address;
832
833
/* True iff the IPv4 address 'addr', in host order, is in 127.0.0.0/8 */
834
static inline int evutil_v4addr_is_localhost(ev_uint32_t addr)
835
0
{ return addr>>24 == 127; }
836
837
/* True iff the IPv4 address 'addr', in host order, is link-local
838
 * 169.254.0.0/16 (RFC3927) */
839
static inline int evutil_v4addr_is_linklocal(ev_uint32_t addr)
840
0
{ return ((addr & 0xffff0000U) == 0xa9fe0000U); }
841
842
/* True iff the IPv4 address 'addr', in host order, is a class D
843
 * (multiclass) address.  */
844
static inline int evutil_v4addr_is_classd(ev_uint32_t addr)
845
0
{ return ((addr>>24) & 0xf0) == 0xe0; }
846
847
int
848
evutil_v4addr_is_local_(const struct in_addr *in)
849
0
{
850
0
  const ev_uint32_t addr = ntohl(in->s_addr);
851
0
  return addr == INADDR_ANY ||
852
0
    evutil_v4addr_is_localhost(addr) ||
853
0
    evutil_v4addr_is_linklocal(addr) ||
854
0
    evutil_v4addr_is_classd(addr);
855
0
}
856
int
857
evutil_v6addr_is_local_(const struct in6_addr *in)
858
0
{
859
0
  static const char ZEROES[] =
860
0
    "\x00\x00\x00\x00\x00\x00\x00\x00"
861
0
    "\x00\x00\x00\x00\x00\x00\x00\x00";
862
863
0
  const unsigned char *addr = (const unsigned char *)in->s6_addr;
864
0
  return !memcmp(addr, ZEROES, 8) ||
865
0
    ((addr[0] & 0xfe) == 0xfc) ||
866
0
    (addr[0] == 0xfe && (addr[1] & 0xc0) == 0x80) ||
867
0
    (addr[0] == 0xfe && (addr[1] & 0xc0) == 0xc0) ||
868
0
    (addr[0] == 0xff);
869
0
}
870
871
static void
872
evutil_found_ifaddr(const struct sockaddr *sa)
873
0
{
874
0
  if (sa->sa_family == AF_INET) {
875
0
    const struct sockaddr_in *sin = (struct sockaddr_in *)sa;
876
0
    if (!evutil_v4addr_is_local_(&sin->sin_addr)) {
877
0
      event_debug(("Detected an IPv4 interface"));
878
0
      had_ipv4_address = 1;
879
0
    }
880
0
  } else if (sa->sa_family == AF_INET6) {
881
0
    const struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)sa;
882
0
    if (!evutil_v6addr_is_local_(&sin6->sin6_addr)) {
883
0
      event_debug(("Detected an IPv6 interface"));
884
0
      had_ipv6_address = 1;
885
0
    }
886
0
  }
887
0
}
888
889
#ifdef _WIN32
890
typedef ULONG (WINAPI *GetAdaptersAddresses_fn_t)(
891
              ULONG, ULONG, PVOID, PIP_ADAPTER_ADDRESSES, PULONG);
892
#endif
893
894
static int
895
evutil_check_ifaddrs(void)
896
0
{
897
0
#if defined(EVENT__HAVE_GETIFADDRS)
898
  /* Most free Unixy systems provide getifaddrs, which gives us a linked list
899
   * of struct ifaddrs. */
900
0
  struct ifaddrs *ifa = NULL;
901
0
  const struct ifaddrs *i;
902
0
  if (getifaddrs(&ifa) < 0) {
903
0
    event_warn("Unable to call getifaddrs()");
904
0
    return -1;
905
0
  }
906
907
0
  for (i = ifa; i; i = i->ifa_next) {
908
0
    if (!i->ifa_addr)
909
0
      continue;
910
0
    evutil_found_ifaddr(i->ifa_addr);
911
0
  }
912
913
0
  freeifaddrs(ifa);
914
0
  return 0;
915
#elif defined(_WIN32)
916
  /* Windows XP began to provide GetAdaptersAddresses. Windows 2000 had a
917
     "GetAdaptersInfo", but that's deprecated; let's just try
918
     GetAdaptersAddresses and fall back to connect+getsockname.
919
  */
920
  HMODULE lib = evutil_load_windows_system_library_(TEXT("iphlpapi.dll"));
921
  GetAdaptersAddresses_fn_t fn;
922
  ULONG size, res;
923
  IP_ADAPTER_ADDRESSES *addresses = NULL, *address;
924
  int result = -1;
925
926
#define FLAGS (GAA_FLAG_SKIP_ANYCAST | \
927
               GAA_FLAG_SKIP_MULTICAST | \
928
               GAA_FLAG_SKIP_DNS_SERVER)
929
930
  if (!lib)
931
    goto done;
932
933
  if (!(fn = (GetAdaptersAddresses_fn_t) GetProcAddress(lib, "GetAdaptersAddresses")))
934
    goto done;
935
936
  /* Guess how much space we need. */
937
  size = 15*1024;
938
  addresses = mm_malloc(size);
939
  if (!addresses)
940
    goto done;
941
  res = fn(AF_UNSPEC, FLAGS, NULL, addresses, &size);
942
  if (res == ERROR_BUFFER_OVERFLOW) {
943
    /* we didn't guess that we needed enough space; try again */
944
    mm_free(addresses);
945
    addresses = mm_malloc(size);
946
    if (!addresses)
947
      goto done;
948
    res = fn(AF_UNSPEC, FLAGS, NULL, addresses, &size);
949
  }
950
  if (res != NO_ERROR)
951
    goto done;
952
953
  for (address = addresses; address; address = address->Next) {
954
    IP_ADAPTER_UNICAST_ADDRESS *a;
955
    for (a = address->FirstUnicastAddress; a; a = a->Next) {
956
      /* Yes, it's a linked list inside a linked list */
957
      struct sockaddr *sa = a->Address.lpSockaddr;
958
      evutil_found_ifaddr(sa);
959
    }
960
  }
961
962
  result = 0;
963
done:
964
  if (lib)
965
    FreeLibrary(lib);
966
  if (addresses)
967
    mm_free(addresses);
968
  return result;
969
#else
970
  return -1;
971
#endif
972
0
}
973
974
/* Test whether we have an ipv4 interface and an ipv6 interface.  Return 0 if
975
 * the test seemed successful. */
976
static int
977
evutil_check_interfaces(void)
978
0
{
979
0
  evutil_socket_t fd = -1;
980
0
  struct sockaddr_in sin, sin_out;
981
0
  struct sockaddr_in6 sin6, sin6_out;
982
0
  ev_socklen_t sin_out_len = sizeof(sin_out);
983
0
  ev_socklen_t sin6_out_len = sizeof(sin6_out);
984
0
  int r;
985
0
  if (have_checked_interfaces)
986
0
    return 0;
987
988
  /* From this point on we have done the ipv4/ipv6 interface check */
989
0
  have_checked_interfaces = 1;
990
991
0
  if (evutil_check_ifaddrs() == 0) {
992
    /* Use a nice sane interface, if this system has one. */
993
0
    return 0;
994
0
  }
995
996
  /* Ugh. There was no nice sane interface.  So to check whether we have
997
   * an interface open for a given protocol, will try to make a UDP
998
   * 'connection' to a remote host on the internet.  We don't actually
999
   * use it, so the address doesn't matter, but we want to pick one that
1000
   * keep us from using a host- or link-local interface. */
1001
0
  memset(&sin, 0, sizeof(sin));
1002
0
  sin.sin_family = AF_INET;
1003
0
  sin.sin_port = htons(53);
1004
0
  r = evutil_inet_pton(AF_INET, "18.244.0.188", &sin.sin_addr);
1005
0
  EVUTIL_ASSERT(r);
1006
1007
0
  memset(&sin6, 0, sizeof(sin6));
1008
0
  sin6.sin6_family = AF_INET6;
1009
0
  sin6.sin6_port = htons(53);
1010
0
  r = evutil_inet_pton(AF_INET6, "2001:4860:b002::68", &sin6.sin6_addr);
1011
0
  EVUTIL_ASSERT(r);
1012
1013
0
  memset(&sin_out, 0, sizeof(sin_out));
1014
0
  memset(&sin6_out, 0, sizeof(sin6_out));
1015
1016
  /* XXX some errnos mean 'no address'; some mean 'not enough sockets'. */
1017
0
  if ((fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) >= 0 &&
1018
0
      connect(fd, (struct sockaddr*)&sin, sizeof(sin)) == 0 &&
1019
0
      getsockname(fd, (struct sockaddr*)&sin_out, &sin_out_len) == 0) {
1020
    /* We might have an IPv4 interface. */
1021
0
    evutil_found_ifaddr((struct sockaddr*) &sin_out);
1022
0
  }
1023
0
  if (fd >= 0)
1024
0
    evutil_closesocket(fd);
1025
1026
0
  if ((fd = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP)) >= 0 &&
1027
0
      connect(fd, (struct sockaddr*)&sin6, sizeof(sin6)) == 0 &&
1028
0
      getsockname(fd, (struct sockaddr*)&sin6_out, &sin6_out_len) == 0) {
1029
    /* We might have an IPv6 interface. */
1030
0
    evutil_found_ifaddr((struct sockaddr*) &sin6_out);
1031
0
  }
1032
1033
0
  if (fd >= 0)
1034
0
    evutil_closesocket(fd);
1035
1036
0
  return 0;
1037
0
}
1038
1039
/* Internal addrinfo flag.  This one is set when we allocate the addrinfo from
1040
 * inside libevent.  Otherwise, the built-in getaddrinfo() function allocated
1041
 * it, and we should trust what they said.
1042
 **/
1043
0
#define EVUTIL_AI_LIBEVENT_ALLOCATED 0x80000000
1044
1045
/* Helper: construct a new addrinfo containing the socket address in
1046
 * 'sa', which must be a sockaddr_in or a sockaddr_in6.  Take the
1047
 * socktype and protocol info from hints.  If they weren't set, then
1048
 * allocate both a TCP and a UDP addrinfo.
1049
 */
1050
struct evutil_addrinfo *
1051
evutil_new_addrinfo_(struct sockaddr *sa, ev_socklen_t socklen,
1052
    const struct evutil_addrinfo *hints)
1053
0
{
1054
0
  struct evutil_addrinfo *res;
1055
0
  EVUTIL_ASSERT(hints);
1056
1057
0
  if (hints->ai_socktype == 0 && hints->ai_protocol == 0) {
1058
    /* Indecisive user! Give them a UDP and a TCP. */
1059
0
    struct evutil_addrinfo *r1, *r2;
1060
0
    struct evutil_addrinfo tmp;
1061
0
    memcpy(&tmp, hints, sizeof(tmp));
1062
0
    tmp.ai_socktype = SOCK_STREAM; tmp.ai_protocol = IPPROTO_TCP;
1063
0
    r1 = evutil_new_addrinfo_(sa, socklen, &tmp);
1064
0
    if (!r1)
1065
0
      return NULL;
1066
0
    tmp.ai_socktype = SOCK_DGRAM; tmp.ai_protocol = IPPROTO_UDP;
1067
0
    r2 = evutil_new_addrinfo_(sa, socklen, &tmp);
1068
0
    if (!r2) {
1069
0
      evutil_freeaddrinfo(r1);
1070
0
      return NULL;
1071
0
    }
1072
0
    r1->ai_next = r2;
1073
0
    return r1;
1074
0
  }
1075
1076
  /* We're going to allocate extra space to hold the sockaddr. */
1077
0
  res = mm_calloc(1,sizeof(struct evutil_addrinfo)+socklen);
1078
0
  if (!res)
1079
0
    return NULL;
1080
0
  res->ai_addr = (struct sockaddr*)
1081
0
      (((char*)res) + sizeof(struct evutil_addrinfo));
1082
0
  memcpy(res->ai_addr, sa, socklen);
1083
0
  res->ai_addrlen = socklen;
1084
0
  res->ai_family = sa->sa_family; /* Same or not? XXX */
1085
0
  res->ai_flags = EVUTIL_AI_LIBEVENT_ALLOCATED;
1086
0
  res->ai_socktype = hints->ai_socktype;
1087
0
  res->ai_protocol = hints->ai_protocol;
1088
1089
0
  return res;
1090
0
}
1091
1092
/* Append the addrinfo 'append' to the end of 'first', and return the start of
1093
 * the list.  Either element can be NULL, in which case we return the element
1094
 * that is not NULL. */
1095
struct evutil_addrinfo *
1096
evutil_addrinfo_append_(struct evutil_addrinfo *first,
1097
    struct evutil_addrinfo *append)
1098
0
{
1099
0
  struct evutil_addrinfo *ai = first;
1100
0
  if (!ai)
1101
0
    return append;
1102
0
  while (ai->ai_next)
1103
0
    ai = ai->ai_next;
1104
0
  ai->ai_next = append;
1105
1106
0
  return first;
1107
0
}
1108
1109
static int
1110
parse_numeric_servname(const char *servname)
1111
0
{
1112
0
  int n;
1113
0
  char *endptr=NULL;
1114
0
  n = (int) strtol(servname, &endptr, 10);
1115
0
  if (n>=0 && n <= 65535 && servname[0] && endptr && !endptr[0])
1116
0
    return n;
1117
0
  else
1118
0
    return -1;
1119
0
}
1120
1121
/** Parse a service name in 'servname', which can be a decimal port.
1122
 * Return the port number, or -1 on error.
1123
 */
1124
static int
1125
evutil_parse_servname(const char *servname, const char *protocol,
1126
    const struct evutil_addrinfo *hints)
1127
0
{
1128
0
  int n = parse_numeric_servname(servname);
1129
0
  if (n>=0)
1130
0
    return n;
1131
0
#if defined(EVENT__HAVE_GETSERVBYNAME) || defined(_WIN32)
1132
0
  if (!(hints->ai_flags & EVUTIL_AI_NUMERICSERV)) {
1133
0
    struct servent *ent = getservbyname(servname, protocol);
1134
0
    if (ent) {
1135
0
      return ntohs(ent->s_port);
1136
0
    }
1137
0
  }
1138
0
#endif
1139
0
  return -1;
1140
0
}
1141
1142
/* Return a string corresponding to a protocol number that we can pass to
1143
 * getservyname.  */
1144
static const char *
1145
evutil_unparse_protoname(int proto)
1146
0
{
1147
0
  switch (proto) {
1148
0
  case 0:
1149
0
    return NULL;
1150
0
  case IPPROTO_TCP:
1151
0
    return "tcp";
1152
0
  case IPPROTO_UDP:
1153
0
    return "udp";
1154
0
#ifdef IPPROTO_SCTP
1155
0
  case IPPROTO_SCTP:
1156
0
    return "sctp";
1157
0
#endif
1158
0
  default:
1159
0
#ifdef EVENT__HAVE_GETPROTOBYNUMBER
1160
0
    {
1161
0
      struct protoent *ent = getprotobynumber(proto);
1162
0
      if (ent)
1163
0
        return ent->p_name;
1164
0
    }
1165
0
#endif
1166
0
    return NULL;
1167
0
  }
1168
0
}
1169
1170
static void
1171
evutil_getaddrinfo_infer_protocols(struct evutil_addrinfo *hints)
1172
0
{
1173
  /* If we can guess the protocol from the socktype, do so. */
1174
0
  if (!hints->ai_protocol && hints->ai_socktype) {
1175
0
    if (hints->ai_socktype == SOCK_DGRAM)
1176
0
      hints->ai_protocol = IPPROTO_UDP;
1177
0
    else if (hints->ai_socktype == SOCK_STREAM)
1178
0
      hints->ai_protocol = IPPROTO_TCP;
1179
0
  }
1180
1181
  /* Set the socktype if it isn't set. */
1182
0
  if (!hints->ai_socktype && hints->ai_protocol) {
1183
0
    if (hints->ai_protocol == IPPROTO_UDP)
1184
0
      hints->ai_socktype = SOCK_DGRAM;
1185
0
    else if (hints->ai_protocol == IPPROTO_TCP)
1186
0
      hints->ai_socktype = SOCK_STREAM;
1187
0
#ifdef IPPROTO_SCTP
1188
0
    else if (hints->ai_protocol == IPPROTO_SCTP)
1189
0
      hints->ai_socktype = SOCK_STREAM;
1190
0
#endif
1191
0
  }
1192
0
}
1193
1194
#if AF_UNSPEC != PF_UNSPEC
1195
#error "I cannot build on a system where AF_UNSPEC != PF_UNSPEC"
1196
#endif
1197
1198
/** Implements the part of looking up hosts by name that's common to both
1199
 * the blocking and nonblocking resolver:
1200
 *   - Adjust 'hints' to have a reasonable socktype and protocol.
1201
 *   - Look up the port based on 'servname', and store it in *portnum,
1202
 *   - Handle the nodename==NULL case
1203
 *   - Handle some invalid arguments cases.
1204
 *   - Handle the cases where nodename is an IPv4 or IPv6 address.
1205
 *
1206
 * If we need the resolver to look up the hostname, we return
1207
 * EVUTIL_EAI_NEED_RESOLVE.  Otherwise, we can completely implement
1208
 * getaddrinfo: we return 0 or an appropriate EVUTIL_EAI_* error, and
1209
 * set *res as getaddrinfo would.
1210
 */
1211
int
1212
evutil_getaddrinfo_common_(const char *nodename, const char *servname,
1213
    struct evutil_addrinfo *hints, struct evutil_addrinfo **res, int *portnum)
1214
0
{
1215
0
  int port = 0;
1216
0
  unsigned int if_index;
1217
0
  const char *pname;
1218
1219
0
  if (nodename == NULL && servname == NULL)
1220
0
    return EVUTIL_EAI_NONAME;
1221
1222
  /* We only understand 3 families */
1223
0
  if (hints->ai_family != PF_UNSPEC && hints->ai_family != PF_INET &&
1224
0
      hints->ai_family != PF_INET6)
1225
0
    return EVUTIL_EAI_FAMILY;
1226
1227
0
  evutil_getaddrinfo_infer_protocols(hints);
1228
1229
  /* Look up the port number and protocol, if possible. */
1230
0
  pname = evutil_unparse_protoname(hints->ai_protocol);
1231
0
  if (servname) {
1232
    /* XXXX We could look at the protocol we got back from
1233
     * getservbyname, but it doesn't seem too useful. */
1234
0
    port = evutil_parse_servname(servname, pname, hints);
1235
0
    if (port < 0) {
1236
0
      return EVUTIL_EAI_NONAME;
1237
0
    }
1238
0
  }
1239
1240
  /* If we have no node name, then we're supposed to bind to 'any' and
1241
   * connect to localhost. */
1242
0
  if (nodename == NULL) {
1243
0
    struct evutil_addrinfo *res4=NULL, *res6=NULL;
1244
0
    if (hints->ai_family != PF_INET) { /* INET6 or UNSPEC. */
1245
0
      struct sockaddr_in6 sin6;
1246
0
      memset(&sin6, 0, sizeof(sin6));
1247
0
      sin6.sin6_family = AF_INET6;
1248
0
      sin6.sin6_port = htons(port);
1249
0
      if (hints->ai_flags & EVUTIL_AI_PASSIVE) {
1250
        /* Bind to :: */
1251
0
      } else {
1252
        /* connect to ::1 */
1253
0
        sin6.sin6_addr.s6_addr[15] = 1;
1254
0
      }
1255
0
      res6 = evutil_new_addrinfo_((struct sockaddr*)&sin6,
1256
0
          sizeof(sin6), hints);
1257
0
      if (!res6)
1258
0
        return EVUTIL_EAI_MEMORY;
1259
0
    }
1260
1261
0
    if (hints->ai_family != PF_INET6) { /* INET or UNSPEC */
1262
0
      struct sockaddr_in sin;
1263
0
      memset(&sin, 0, sizeof(sin));
1264
0
      sin.sin_family = AF_INET;
1265
0
      sin.sin_port = htons(port);
1266
0
      if (hints->ai_flags & EVUTIL_AI_PASSIVE) {
1267
        /* Bind to 0.0.0.0 */
1268
0
      } else {
1269
        /* connect to 127.0.0.1 */
1270
0
        sin.sin_addr.s_addr = htonl(0x7f000001);
1271
0
      }
1272
0
      res4 = evutil_new_addrinfo_((struct sockaddr*)&sin,
1273
0
          sizeof(sin), hints);
1274
0
      if (!res4) {
1275
0
        if (res6)
1276
0
          evutil_freeaddrinfo(res6);
1277
0
        return EVUTIL_EAI_MEMORY;
1278
0
      }
1279
0
    }
1280
0
    *res = evutil_addrinfo_append_(res4, res6);
1281
0
    return 0;
1282
0
  }
1283
1284
  /* If we can, we should try to parse the hostname without resolving
1285
   * it. */
1286
  /* Try ipv6. */
1287
0
  if (hints->ai_family == PF_INET6 || hints->ai_family == PF_UNSPEC) {
1288
0
    struct sockaddr_in6 sin6;
1289
0
    memset(&sin6, 0, sizeof(sin6));
1290
0
    if (1 == evutil_inet_pton_scope(
1291
0
      AF_INET6, nodename, &sin6.sin6_addr, &if_index)) {
1292
      /* Got an ipv6 address. */
1293
0
      sin6.sin6_family = AF_INET6;
1294
0
      sin6.sin6_port = htons(port);
1295
0
      sin6.sin6_scope_id = if_index;
1296
0
      *res = evutil_new_addrinfo_((struct sockaddr*)&sin6,
1297
0
          sizeof(sin6), hints);
1298
0
      if (!*res)
1299
0
        return EVUTIL_EAI_MEMORY;
1300
0
      return 0;
1301
0
    }
1302
0
  }
1303
1304
  /* Try ipv4. */
1305
0
  if (hints->ai_family == PF_INET || hints->ai_family == PF_UNSPEC) {
1306
0
    struct sockaddr_in sin;
1307
0
    memset(&sin, 0, sizeof(sin));
1308
0
    if (1==evutil_inet_pton(AF_INET, nodename, &sin.sin_addr)) {
1309
      /* Got an ipv4 address. */
1310
0
      sin.sin_family = AF_INET;
1311
0
      sin.sin_port = htons(port);
1312
0
      *res = evutil_new_addrinfo_((struct sockaddr*)&sin,
1313
0
          sizeof(sin), hints);
1314
0
      if (!*res)
1315
0
        return EVUTIL_EAI_MEMORY;
1316
0
      return 0;
1317
0
    }
1318
0
  }
1319
1320
1321
  /* If we have reached this point, we definitely need to do a DNS
1322
   * lookup. */
1323
0
  if ((hints->ai_flags & EVUTIL_AI_NUMERICHOST)) {
1324
    /* If we're not allowed to do one, then say so. */
1325
0
    return EVUTIL_EAI_NONAME;
1326
0
  }
1327
0
  *portnum = port;
1328
0
  return EVUTIL_EAI_NEED_RESOLVE;
1329
0
}
1330
1331
#ifdef EVENT__HAVE_GETADDRINFO
1332
#define USE_NATIVE_GETADDRINFO
1333
#endif
1334
1335
#ifdef USE_NATIVE_GETADDRINFO
1336
/* A mask of all the flags that we declare, so we can clear them before calling
1337
 * the native getaddrinfo */
1338
static const unsigned int ALL_NONNATIVE_AI_FLAGS =
1339
#ifndef AI_PASSIVE
1340
    EVUTIL_AI_PASSIVE |
1341
#endif
1342
#ifndef AI_CANONNAME
1343
    EVUTIL_AI_CANONNAME |
1344
#endif
1345
#ifndef AI_NUMERICHOST
1346
    EVUTIL_AI_NUMERICHOST |
1347
#endif
1348
#ifndef AI_NUMERICSERV
1349
    EVUTIL_AI_NUMERICSERV |
1350
#endif
1351
#ifndef AI_ADDRCONFIG
1352
    EVUTIL_AI_ADDRCONFIG |
1353
#endif
1354
#ifndef AI_ALL
1355
    EVUTIL_AI_ALL |
1356
#endif
1357
#ifndef AI_V4MAPPED
1358
    EVUTIL_AI_V4MAPPED |
1359
#endif
1360
    EVUTIL_AI_LIBEVENT_ALLOCATED;
1361
1362
static const unsigned int ALL_NATIVE_AI_FLAGS =
1363
#ifdef AI_PASSIVE
1364
    AI_PASSIVE |
1365
#endif
1366
#ifdef AI_CANONNAME
1367
    AI_CANONNAME |
1368
#endif
1369
#ifdef AI_NUMERICHOST
1370
    AI_NUMERICHOST |
1371
#endif
1372
#ifdef AI_NUMERICSERV
1373
    AI_NUMERICSERV |
1374
#endif
1375
#ifdef AI_ADDRCONFIG
1376
    AI_ADDRCONFIG |
1377
#endif
1378
#ifdef AI_ALL
1379
    AI_ALL |
1380
#endif
1381
#ifdef AI_V4MAPPED
1382
    AI_V4MAPPED |
1383
#endif
1384
    0;
1385
#endif
1386
1387
#ifndef USE_NATIVE_GETADDRINFO
1388
/* Helper for systems with no getaddrinfo(): make one or more addrinfos out of
1389
 * a struct hostent.
1390
 */
1391
static struct evutil_addrinfo *
1392
addrinfo_from_hostent(const struct hostent *ent,
1393
    int port, const struct evutil_addrinfo *hints)
1394
{
1395
  int i;
1396
  struct sockaddr_in sin;
1397
  struct sockaddr_in6 sin6;
1398
  struct sockaddr *sa;
1399
  int socklen;
1400
  struct evutil_addrinfo *res=NULL, *ai;
1401
  void *addrp;
1402
1403
  if (ent->h_addrtype == PF_INET) {
1404
    memset(&sin, 0, sizeof(sin));
1405
    sin.sin_family = AF_INET;
1406
    sin.sin_port = htons(port);
1407
    sa = (struct sockaddr *)&sin;
1408
    socklen = sizeof(struct sockaddr_in);
1409
    addrp = &sin.sin_addr;
1410
    if (ent->h_length != sizeof(sin.sin_addr)) {
1411
      event_warnx("Weird h_length from gethostbyname");
1412
      return NULL;
1413
    }
1414
  } else if (ent->h_addrtype == PF_INET6) {
1415
    memset(&sin6, 0, sizeof(sin6));
1416
    sin6.sin6_family = AF_INET6;
1417
    sin6.sin6_port = htons(port);
1418
    sa = (struct sockaddr *)&sin6;
1419
    socklen = sizeof(struct sockaddr_in6);
1420
    addrp = &sin6.sin6_addr;
1421
    if (ent->h_length != sizeof(sin6.sin6_addr)) {
1422
      event_warnx("Weird h_length from gethostbyname");
1423
      return NULL;
1424
    }
1425
  } else
1426
    return NULL;
1427
1428
  for (i = 0; ent->h_addr_list[i]; ++i) {
1429
    memcpy(addrp, ent->h_addr_list[i], ent->h_length);
1430
    ai = evutil_new_addrinfo_(sa, socklen, hints);
1431
    if (!ai) {
1432
      evutil_freeaddrinfo(res);
1433
      return NULL;
1434
    }
1435
    res = evutil_addrinfo_append_(res, ai);
1436
  }
1437
1438
  if (res && ((hints->ai_flags & EVUTIL_AI_CANONNAME) && ent->h_name)) {
1439
    res->ai_canonname = mm_strdup(ent->h_name);
1440
    if (res->ai_canonname == NULL) {
1441
      evutil_freeaddrinfo(res);
1442
      return NULL;
1443
    }
1444
  }
1445
1446
  return res;
1447
}
1448
#endif
1449
1450
/* If the EVUTIL_AI_ADDRCONFIG flag is set on hints->ai_flags, and
1451
 * hints->ai_family is PF_UNSPEC, then revise the value of hints->ai_family so
1452
 * that we'll only get addresses we could maybe connect to.
1453
 */
1454
void
1455
evutil_adjust_hints_for_addrconfig_(struct evutil_addrinfo *hints)
1456
0
{
1457
0
  if (!(hints->ai_flags & EVUTIL_AI_ADDRCONFIG))
1458
0
    return;
1459
0
  if (hints->ai_family != PF_UNSPEC)
1460
0
    return;
1461
0
  evutil_check_interfaces();
1462
0
  if (had_ipv4_address && !had_ipv6_address) {
1463
0
    hints->ai_family = PF_INET;
1464
0
  } else if (!had_ipv4_address && had_ipv6_address) {
1465
0
    hints->ai_family = PF_INET6;
1466
0
  }
1467
0
}
1468
1469
#ifdef USE_NATIVE_GETADDRINFO
1470
static int need_numeric_port_hack_=0;
1471
static int need_socktype_protocol_hack_=0;
1472
static int tested_for_getaddrinfo_hacks=0;
1473
1474
/* Some older BSDs (like OpenBSD up to 4.6) used to believe that
1475
   giving a numeric port without giving an ai_socktype was verboten.
1476
   We test for this so we can apply an appropriate workaround.  If it
1477
   turns out that the bug is present, then:
1478
1479
    - If nodename==NULL and servname is numeric, we build an answer
1480
      ourselves using evutil_getaddrinfo_common_().
1481
1482
    - If nodename!=NULL and servname is numeric, then we set
1483
      servname=NULL when calling getaddrinfo, and post-process the
1484
      result to set the ports on it.
1485
1486
   We test for this bug at runtime, since otherwise we can't have the
1487
   same binary run on multiple BSD versions.
1488
1489
   - Some versions of Solaris believe that it's nice to leave to protocol
1490
     field set to 0.  We test for this so we can apply an appropriate
1491
     workaround.
1492
*/
1493
static struct evutil_addrinfo *ai_find_protocol(struct evutil_addrinfo *ai)
1494
0
{
1495
0
  while (ai) {
1496
0
    if (ai->ai_protocol)
1497
0
      return ai;
1498
0
    ai = ai->ai_next;
1499
0
  }
1500
0
  return NULL;
1501
0
}
1502
static void
1503
test_for_getaddrinfo_hacks(void)
1504
0
{
1505
0
  int r, r2;
1506
0
  struct evutil_addrinfo *ai=NULL, *ai2=NULL, *ai3=NULL;
1507
0
  struct evutil_addrinfo hints;
1508
1509
0
  memset(&hints,0,sizeof(hints));
1510
0
  hints.ai_family = PF_UNSPEC;
1511
0
  hints.ai_flags =
1512
0
#ifdef AI_NUMERICHOST
1513
0
      AI_NUMERICHOST |
1514
0
#endif
1515
0
#ifdef AI_NUMERICSERV
1516
0
      AI_NUMERICSERV |
1517
0
#endif
1518
0
      0;
1519
0
  r = getaddrinfo("1.2.3.4", "80", &hints, &ai);
1520
0
  getaddrinfo("1.2.3.4", NULL, &hints, &ai3);
1521
0
  hints.ai_socktype = SOCK_STREAM;
1522
0
  r2 = getaddrinfo("1.2.3.4", "80", &hints, &ai2);
1523
0
  if (r2 == 0 && r != 0) {
1524
0
    need_numeric_port_hack_=1;
1525
0
  }
1526
0
  if (!ai_find_protocol(ai2) || !ai_find_protocol(ai3)) {
1527
0
    need_socktype_protocol_hack_=1;
1528
0
  }
1529
1530
0
  if (ai)
1531
0
    freeaddrinfo(ai);
1532
0
  if (ai2)
1533
0
    freeaddrinfo(ai2);
1534
0
  if (ai3)
1535
0
    freeaddrinfo(ai3);
1536
0
  tested_for_getaddrinfo_hacks=1;
1537
0
}
1538
1539
static inline int
1540
need_numeric_port_hack(void)
1541
0
{
1542
0
  if (!tested_for_getaddrinfo_hacks)
1543
0
    test_for_getaddrinfo_hacks();
1544
0
  return need_numeric_port_hack_;
1545
0
}
1546
1547
static inline int
1548
need_socktype_protocol_hack(void)
1549
0
{
1550
0
  if (!tested_for_getaddrinfo_hacks)
1551
0
    test_for_getaddrinfo_hacks();
1552
0
  return need_socktype_protocol_hack_;
1553
0
}
1554
1555
static void
1556
apply_numeric_port_hack(int port, struct evutil_addrinfo **ai)
1557
0
{
1558
  /* Now we run through the list and set the ports on all of the
1559
   * results where ports would make sense. */
1560
0
  for ( ; *ai; ai = &(*ai)->ai_next) {
1561
0
    struct sockaddr *sa = (*ai)->ai_addr;
1562
0
    if (sa && sa->sa_family == AF_INET) {
1563
0
      struct sockaddr_in *sin = (struct sockaddr_in*)sa;
1564
0
      sin->sin_port = htons(port);
1565
0
    } else if (sa && sa->sa_family == AF_INET6) {
1566
0
      struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)sa;
1567
0
      sin6->sin6_port = htons(port);
1568
0
    } else {
1569
      /* A numeric port makes no sense here; remove this one
1570
       * from the list. */
1571
0
      struct evutil_addrinfo *victim = *ai;
1572
0
      *ai = victim->ai_next;
1573
0
      victim->ai_next = NULL;
1574
0
      freeaddrinfo(victim);
1575
0
    }
1576
0
  }
1577
0
}
1578
1579
static int
1580
apply_socktype_protocol_hack(struct evutil_addrinfo *ai)
1581
0
{
1582
0
  struct evutil_addrinfo *ai_new;
1583
0
  for (; ai; ai = ai->ai_next) {
1584
0
    evutil_getaddrinfo_infer_protocols(ai);
1585
0
    if (ai->ai_socktype || ai->ai_protocol)
1586
0
      continue;
1587
0
    ai_new = mm_malloc(sizeof(*ai_new));
1588
0
    if (!ai_new)
1589
0
      return -1;
1590
0
    memcpy(ai_new, ai, sizeof(*ai_new));
1591
0
    ai->ai_socktype = SOCK_STREAM;
1592
0
    ai->ai_protocol = IPPROTO_TCP;
1593
0
    ai_new->ai_socktype = SOCK_DGRAM;
1594
0
    ai_new->ai_protocol = IPPROTO_UDP;
1595
0
    ai_new->ai_flags = EVUTIL_AI_LIBEVENT_ALLOCATED;
1596
0
    if (ai_new->ai_canonname != NULL) {
1597
0
      ai_new->ai_canonname = mm_strdup(ai_new->ai_canonname);
1598
0
      if (ai_new->ai_canonname == NULL) {
1599
0
        mm_free(ai_new);
1600
0
        return -1;
1601
0
      }
1602
0
    }
1603
1604
0
    ai_new->ai_next = ai->ai_next;
1605
0
    ai->ai_next = ai_new;
1606
0
  }
1607
0
  return 0;
1608
0
}
1609
#endif
1610
1611
int
1612
evutil_getaddrinfo(const char *nodename, const char *servname,
1613
    const struct evutil_addrinfo *hints_in, struct evutil_addrinfo **res)
1614
0
{
1615
0
#ifdef USE_NATIVE_GETADDRINFO
1616
0
  struct evutil_addrinfo hints;
1617
0
  int portnum=-1, need_np_hack, err;
1618
1619
0
  if (hints_in) {
1620
0
    memcpy(&hints, hints_in, sizeof(hints));
1621
0
  } else {
1622
0
    memset(&hints, 0, sizeof(hints));
1623
0
    hints.ai_family = PF_UNSPEC;
1624
0
  }
1625
1626
#ifndef AI_ADDRCONFIG
1627
  /* Not every system has AI_ADDRCONFIG, so fake it. */
1628
  if (hints.ai_family == PF_UNSPEC &&
1629
      (hints.ai_flags & EVUTIL_AI_ADDRCONFIG)) {
1630
    evutil_adjust_hints_for_addrconfig_(&hints);
1631
  }
1632
#endif
1633
1634
#ifndef AI_NUMERICSERV
1635
  /* Not every system has AI_NUMERICSERV, so fake it. */
1636
  if (hints.ai_flags & EVUTIL_AI_NUMERICSERV) {
1637
    if (servname && parse_numeric_servname(servname)<0)
1638
      return EVUTIL_EAI_NONAME;
1639
  }
1640
#endif
1641
1642
  /* Enough operating systems handle enough common non-resolve
1643
   * cases here weirdly enough that we are better off just
1644
   * overriding them.  For example:
1645
   *
1646
   * - Windows doesn't like to infer the protocol from the
1647
   *   socket type, or fill in socket or protocol types much at
1648
   *   all.  It also seems to do its own broken implicit
1649
   *   always-on version of AI_ADDRCONFIG that keeps it from
1650
   *   ever resolving even a literal IPv6 address when
1651
   *   ai_addrtype is PF_UNSPEC.
1652
   */
1653
#ifdef _WIN32
1654
  {
1655
    int tmp_port;
1656
    err = evutil_getaddrinfo_common_(nodename,servname,&hints,
1657
        res, &tmp_port);
1658
    if (err == 0 ||
1659
        err == EVUTIL_EAI_MEMORY ||
1660
        err == EVUTIL_EAI_NONAME)
1661
      return err;
1662
    /* If we make it here, the system getaddrinfo can
1663
     * have a crack at it. */
1664
  }
1665
#endif
1666
1667
  /* See documentation for need_numeric_port_hack above.*/
1668
0
  need_np_hack = need_numeric_port_hack() && servname && !hints.ai_socktype
1669
0
      && ((portnum=parse_numeric_servname(servname)) >= 0);
1670
0
  if (need_np_hack) {
1671
0
    if (!nodename)
1672
0
      return evutil_getaddrinfo_common_(
1673
0
        NULL,servname,&hints, res, &portnum);
1674
0
    servname = NULL;
1675
0
  }
1676
1677
0
  if (need_socktype_protocol_hack()) {
1678
0
    evutil_getaddrinfo_infer_protocols(&hints);
1679
0
  }
1680
1681
  /* Make sure that we didn't actually steal any AI_FLAGS values that
1682
   * the system is using.  (This is a constant expression, and should ge
1683
   * optimized out.)
1684
   *
1685
   * XXXX Turn this into a compile-time failure rather than a run-time
1686
   * failure.
1687
   */
1688
0
  EVUTIL_ASSERT((ALL_NONNATIVE_AI_FLAGS & ALL_NATIVE_AI_FLAGS) == 0);
1689
1690
  /* Clear any flags that only libevent understands. */
1691
0
  hints.ai_flags &= ~ALL_NONNATIVE_AI_FLAGS;
1692
1693
0
  err = getaddrinfo(nodename, servname, &hints, res);
1694
0
  if (need_np_hack)
1695
0
    apply_numeric_port_hack(portnum, res);
1696
1697
0
  if (need_socktype_protocol_hack()) {
1698
0
    if (apply_socktype_protocol_hack(*res) < 0) {
1699
0
      evutil_freeaddrinfo(*res);
1700
0
      *res = NULL;
1701
0
      return EVUTIL_EAI_MEMORY;
1702
0
    }
1703
0
  }
1704
0
  return err;
1705
#else
1706
  int port=0, err;
1707
  struct hostent *ent = NULL;
1708
  struct evutil_addrinfo hints;
1709
1710
  if (hints_in) {
1711
    memcpy(&hints, hints_in, sizeof(hints));
1712
  } else {
1713
    memset(&hints, 0, sizeof(hints));
1714
    hints.ai_family = PF_UNSPEC;
1715
  }
1716
1717
  evutil_adjust_hints_for_addrconfig_(&hints);
1718
1719
  err = evutil_getaddrinfo_common_(nodename, servname, &hints, res, &port);
1720
  if (err != EVUTIL_EAI_NEED_RESOLVE) {
1721
    /* We either succeeded or failed.  No need to continue */
1722
    return err;
1723
  }
1724
1725
  err = 0;
1726
  /* Use any of the various gethostbyname_r variants as available. */
1727
  {
1728
#ifdef EVENT__HAVE_GETHOSTBYNAME_R_6_ARG
1729
    /* This one is what glibc provides. */
1730
    char buf[2048];
1731
    struct hostent hostent;
1732
    int r;
1733
    r = gethostbyname_r(nodename, &hostent, buf, sizeof(buf), &ent,
1734
        &err);
1735
#elif defined(EVENT__HAVE_GETHOSTBYNAME_R_5_ARG)
1736
    char buf[2048];
1737
    struct hostent hostent;
1738
    ent = gethostbyname_r(nodename, &hostent, buf, sizeof(buf),
1739
        &err);
1740
#elif defined(EVENT__HAVE_GETHOSTBYNAME_R_3_ARG)
1741
    struct hostent_data data;
1742
    struct hostent hostent;
1743
    memset(&data, 0, sizeof(data));
1744
    err = gethostbyname_r(nodename, &hostent, &data);
1745
    ent = err ? NULL : &hostent;
1746
#else
1747
    /* fall back to gethostbyname. */
1748
    /* XXXX This needs a lock everywhere but Windows. */
1749
    ent = gethostbyname(nodename);
1750
#ifdef _WIN32
1751
    err = WSAGetLastError();
1752
#else
1753
    err = h_errno;
1754
#endif
1755
#endif
1756
1757
    /* Now we have either ent or err set. */
1758
    if (!ent) {
1759
      /* XXX is this right for windows ? */
1760
      switch (err) {
1761
      case TRY_AGAIN:
1762
        return EVUTIL_EAI_AGAIN;
1763
      case NO_RECOVERY:
1764
      default:
1765
        return EVUTIL_EAI_FAIL;
1766
      case HOST_NOT_FOUND:
1767
        return EVUTIL_EAI_NONAME;
1768
      case NO_ADDRESS:
1769
#if NO_DATA != NO_ADDRESS
1770
      case NO_DATA:
1771
#endif
1772
        return EVUTIL_EAI_NODATA;
1773
      }
1774
    }
1775
1776
    if (ent->h_addrtype != hints.ai_family &&
1777
        hints.ai_family != PF_UNSPEC) {
1778
      /* This wasn't the type we were hoping for.  Too bad
1779
       * we never had a chance to ask gethostbyname for what
1780
       * we wanted. */
1781
      return EVUTIL_EAI_NONAME;
1782
    }
1783
1784
    /* Make sure we got _some_ answers. */
1785
    if (ent->h_length == 0)
1786
      return EVUTIL_EAI_NODATA;
1787
1788
    /* If we got an address type we don't know how to make a
1789
       sockaddr for, give up. */
1790
    if (ent->h_addrtype != PF_INET && ent->h_addrtype != PF_INET6)
1791
      return EVUTIL_EAI_FAMILY;
1792
1793
    *res = addrinfo_from_hostent(ent, port, &hints);
1794
    if (! *res)
1795
      return EVUTIL_EAI_MEMORY;
1796
  }
1797
1798
  return 0;
1799
#endif
1800
0
}
1801
1802
void
1803
evutil_freeaddrinfo(struct evutil_addrinfo *ai)
1804
0
{
1805
0
#ifdef EVENT__HAVE_GETADDRINFO
1806
0
  struct evutil_addrinfo *ai_prev = NULL;
1807
0
  struct evutil_addrinfo *ai_temp = ai;
1808
  /* Linked list may be the result of a native getaddrinfo() call plus
1809
   * locally allocated nodes, Before releasing it using freeaddrinfo(),
1810
   * these custom structs need to be freed separately.
1811
   */
1812
0
  while (ai_temp) {
1813
0
    struct evutil_addrinfo *next = ai_temp->ai_next;
1814
0
    if (ai_temp->ai_flags & EVUTIL_AI_LIBEVENT_ALLOCATED) {
1815
      /* Remove this node from the linked list */
1816
0
      if (ai_temp->ai_canonname)
1817
0
        mm_free(ai_temp->ai_canonname);
1818
0
      mm_free(ai_temp);
1819
0
      if (ai_prev == NULL) {
1820
0
        ai = next;
1821
0
      } else {
1822
0
        ai_prev->ai_next = next;
1823
0
      }
1824
1825
0
    } else {
1826
0
      ai_prev = ai_temp;
1827
0
    }
1828
0
    ai_temp = next;
1829
0
  }
1830
0
  if (ai != NULL)
1831
0
    freeaddrinfo(ai);
1832
#else
1833
  while (ai) {
1834
    struct evutil_addrinfo *next = ai->ai_next;
1835
    if (ai->ai_canonname)
1836
      mm_free(ai->ai_canonname);
1837
    mm_free(ai);
1838
    ai = next;
1839
  }
1840
#endif
1841
0
}
1842
1843
static evdns_getaddrinfo_fn evdns_getaddrinfo_impl = NULL;
1844
static evdns_getaddrinfo_cancel_fn evdns_getaddrinfo_cancel_impl = NULL;
1845
1846
void
1847
evutil_set_evdns_getaddrinfo_fn_(evdns_getaddrinfo_fn fn)
1848
0
{
1849
0
  if (!evdns_getaddrinfo_impl)
1850
0
    evdns_getaddrinfo_impl = fn;
1851
0
}
1852
void
1853
evutil_set_evdns_getaddrinfo_cancel_fn_(evdns_getaddrinfo_cancel_fn fn)
1854
0
{
1855
0
  if (!evdns_getaddrinfo_cancel_impl)
1856
0
    evdns_getaddrinfo_cancel_impl = fn;
1857
0
}
1858
1859
static const char *evutil_custom_resolvconf_filename = NULL;
1860
1861
void
1862
evutil_set_resolvconf_filename_(const char *filename)
1863
0
{
1864
0
  evutil_custom_resolvconf_filename = filename;
1865
0
}
1866
1867
const char *
1868
evutil_resolvconf_filename_(void)
1869
0
{
1870
0
  if (evutil_custom_resolvconf_filename)
1871
0
    return evutil_custom_resolvconf_filename;
1872
1873
0
  return "/etc/resolv.conf";
1874
0
}
1875
1876
/* Internal helper function: act like evdns_getaddrinfo if dns_base is set;
1877
 * otherwise do a blocking resolve and pass the result to the callback in the
1878
 * way that evdns_getaddrinfo would.
1879
 */
1880
struct evdns_getaddrinfo_request *evutil_getaddrinfo_async_(
1881
    struct evdns_base *dns_base,
1882
    const char *nodename, const char *servname,
1883
    const struct evutil_addrinfo *hints_in,
1884
    void (*cb)(int, struct evutil_addrinfo *, void *), void *arg)
1885
0
{
1886
0
  if (dns_base && evdns_getaddrinfo_impl) {
1887
0
    return evdns_getaddrinfo_impl(
1888
0
      dns_base, nodename, servname, hints_in, cb, arg);
1889
0
  } else {
1890
0
    struct evutil_addrinfo *ai=NULL;
1891
0
    int err;
1892
0
    err = evutil_getaddrinfo(nodename, servname, hints_in, &ai);
1893
0
    cb(err, ai, arg);
1894
0
    return NULL;
1895
0
  }
1896
0
}
1897
1898
void evutil_getaddrinfo_cancel_async_(struct evdns_getaddrinfo_request *data)
1899
0
{
1900
0
  if (evdns_getaddrinfo_cancel_impl && data) {
1901
0
    evdns_getaddrinfo_cancel_impl(data);
1902
0
  }
1903
0
}
1904
1905
const char *
1906
evutil_gai_strerror(int err)
1907
0
{
1908
  /* As a sneaky side-benefit, this case statement will get most
1909
   * compilers to tell us if any of the error codes we defined
1910
   * conflict with the platform's native error codes. */
1911
0
  switch (err) {
1912
0
  case EVUTIL_EAI_CANCEL:
1913
0
    return "Request canceled";
1914
0
  case 0:
1915
0
    return "No error";
1916
1917
0
  case EVUTIL_EAI_ADDRFAMILY:
1918
0
    return "address family for nodename not supported";
1919
0
  case EVUTIL_EAI_AGAIN:
1920
0
    return "temporary failure in name resolution";
1921
0
  case EVUTIL_EAI_BADFLAGS:
1922
0
    return "invalid value for ai_flags";
1923
0
  case EVUTIL_EAI_FAIL:
1924
0
    return "non-recoverable failure in name resolution";
1925
0
  case EVUTIL_EAI_FAMILY:
1926
0
    return "ai_family not supported";
1927
0
  case EVUTIL_EAI_MEMORY:
1928
0
    return "memory allocation failure";
1929
0
  case EVUTIL_EAI_NODATA:
1930
0
    return "no address associated with nodename";
1931
0
  case EVUTIL_EAI_NONAME:
1932
0
    return "nodename nor servname provided, or not known";
1933
0
  case EVUTIL_EAI_SERVICE:
1934
0
    return "servname not supported for ai_socktype";
1935
0
  case EVUTIL_EAI_SOCKTYPE:
1936
0
    return "ai_socktype not supported";
1937
0
  case EVUTIL_EAI_SYSTEM:
1938
0
    return "system error";
1939
0
  default:
1940
#if defined(USE_NATIVE_GETADDRINFO) && defined(_WIN32)
1941
    return gai_strerrorA(err);
1942
#elif defined(USE_NATIVE_GETADDRINFO)
1943
0
    return gai_strerror(err);
1944
#else
1945
    return "Unknown error code";
1946
#endif
1947
0
  }
1948
0
}
1949
1950
#ifdef _WIN32
1951
/* destructively remove a trailing line terminator from s */
1952
static void
1953
chomp (char *s)
1954
{
1955
  size_t len;
1956
  if (s && (len = strlen (s)) > 0 && s[len - 1] == '\n') {
1957
    s[--len] = 0;
1958
    if (len > 0 && s[len - 1] == '\r')
1959
      s[--len] = 0;
1960
  }
1961
}
1962
1963
/* FormatMessage returns allocated strings, but evutil_socket_error_to_string
1964
 * is supposed to return a string which is good indefinitely without having
1965
 * to be freed.  To make this work without leaking memory, we cache the
1966
 * string the first time FormatMessage is called on a particular error
1967
 * code, and then return the cached string on subsequent calls with the
1968
 * same code.  The strings aren't freed until libevent_global_shutdown
1969
 * (or never).  We use a linked list to cache the errors, because we
1970
 * only expect there to be a few dozen, and that should be fast enough.
1971
 */
1972
1973
struct cached_sock_errs_entry {
1974
  HT_ENTRY(cached_sock_errs_entry) node;
1975
  DWORD code;
1976
  char *msg; /* allocated with LocalAlloc; free with LocalFree */
1977
};
1978
1979
static inline unsigned
1980
hash_cached_sock_errs(const struct cached_sock_errs_entry *e)
1981
{
1982
  /* Use Murmur3's 32-bit finalizer as an integer hash function */
1983
  DWORD h = e->code;
1984
  h ^= h >> 16;
1985
  h *= 0x85ebca6b;
1986
  h ^= h >> 13;
1987
  h *= 0xc2b2ae35;
1988
  h ^= h >> 16;
1989
  return h;
1990
}
1991
1992
static inline int
1993
eq_cached_sock_errs(const struct cached_sock_errs_entry *a,
1994
        const struct cached_sock_errs_entry *b)
1995
{
1996
  return a->code == b->code;
1997
}
1998
1999
#ifndef EVENT__DISABLE_THREAD_SUPPORT
2000
static void *windows_socket_errors_lock_ = NULL;
2001
#endif
2002
2003
static HT_HEAD(cached_sock_errs_map, cached_sock_errs_entry)
2004
     windows_socket_errors = HT_INITIALIZER();
2005
2006
HT_PROTOTYPE(cached_sock_errs_map,
2007
       cached_sock_errs_entry,
2008
       node,
2009
       hash_cached_sock_errs,
2010
       eq_cached_sock_errs);
2011
2012
HT_GENERATE(cached_sock_errs_map,
2013
      cached_sock_errs_entry,
2014
      node,
2015
      hash_cached_sock_errs,
2016
      eq_cached_sock_errs,
2017
      0.5,
2018
      mm_malloc,
2019
      mm_realloc,
2020
      mm_free);
2021
2022
/** Equivalent to strerror, but for windows socket errors. */
2023
const char *
2024
evutil_socket_error_to_string(int errcode)
2025
{
2026
  struct cached_sock_errs_entry *errs, *newerr, find;
2027
  char *msg = NULL;
2028
2029
  EVLOCK_LOCK(windows_socket_errors_lock_, 0);
2030
2031
  find.code = errcode;
2032
  errs = HT_FIND(cached_sock_errs_map, &windows_socket_errors, &find);
2033
  if (errs) {
2034
    msg = errs->msg;
2035
    goto done;
2036
  }
2037
2038
  if (0 != FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM |
2039
             FORMAT_MESSAGE_IGNORE_INSERTS |
2040
             FORMAT_MESSAGE_ALLOCATE_BUFFER,
2041
             NULL, errcode, 0, (char *)&msg, 0, NULL))
2042
    chomp (msg);  /* because message has trailing newline */
2043
  else {
2044
    size_t len = 50;
2045
    /* use LocalAlloc because FormatMessage does */
2046
    msg = LocalAlloc(LMEM_FIXED, len);
2047
    if (!msg) {
2048
      msg = (char *)"LocalAlloc failed during Winsock error";
2049
      goto done;
2050
    }
2051
    evutil_snprintf(msg, len, "winsock error 0x%08x", errcode);
2052
  }
2053
2054
  newerr = (struct cached_sock_errs_entry *)
2055
    mm_malloc(sizeof (struct cached_sock_errs_entry));
2056
2057
  if (!newerr) {
2058
    LocalFree(msg);
2059
    msg = (char *)"malloc failed during Winsock error";
2060
    goto done;
2061
  }
2062
2063
  newerr->code = errcode;
2064
  newerr->msg = msg;
2065
  HT_INSERT(cached_sock_errs_map, &windows_socket_errors, newerr);
2066
2067
 done:
2068
  EVLOCK_UNLOCK(windows_socket_errors_lock_, 0);
2069
2070
  return msg;
2071
}
2072
2073
#ifndef EVENT__DISABLE_THREAD_SUPPORT
2074
int
2075
evutil_global_setup_locks_(const int enable_locks)
2076
{
2077
  EVTHREAD_SETUP_GLOBAL_LOCK(windows_socket_errors_lock_, 0);
2078
  return 0;
2079
}
2080
#endif
2081
2082
static void
2083
evutil_free_sock_err_globals(void)
2084
{
2085
  struct cached_sock_errs_entry **errs, *tofree;
2086
2087
  for (errs = HT_START(cached_sock_errs_map, &windows_socket_errors)
2088
         ; errs; ) {
2089
    tofree = *errs;
2090
    errs = HT_NEXT_RMV(cached_sock_errs_map,
2091
           &windows_socket_errors,
2092
           errs);
2093
    LocalFree(tofree->msg);
2094
    mm_free(tofree);
2095
  }
2096
2097
  HT_CLEAR(cached_sock_errs_map, &windows_socket_errors);
2098
2099
#ifndef EVENT__DISABLE_THREAD_SUPPORT
2100
  if (windows_socket_errors_lock_ != NULL) {
2101
    EVTHREAD_FREE_LOCK(windows_socket_errors_lock_, 0);
2102
    windows_socket_errors_lock_ = NULL;
2103
  }
2104
#endif
2105
}
2106
2107
#else
2108
2109
#ifndef EVENT__DISABLE_THREAD_SUPPORT
2110
int
2111
evutil_global_setup_locks_(const int enable_locks)
2112
0
{
2113
0
  return 0;
2114
0
}
2115
#endif
2116
2117
static void
2118
evutil_free_sock_err_globals(void)
2119
0
{
2120
0
}
2121
2122
#endif
2123
2124
int
2125
evutil_snprintf(char *buf, size_t buflen, const char *format, ...)
2126
0
{
2127
0
  int r;
2128
0
  va_list ap;
2129
0
  va_start(ap, format);
2130
0
  r = evutil_vsnprintf(buf, buflen, format, ap);
2131
0
  va_end(ap);
2132
0
  return r;
2133
0
}
2134
2135
int
2136
evutil_vsnprintf(char *buf, size_t buflen, const char *format, va_list ap)
2137
0
{
2138
0
  int r;
2139
0
  if (!buflen)
2140
0
    return 0;
2141
#if defined(_MSC_VER) || defined(_WIN32)
2142
  r = _vsnprintf(buf, buflen, format, ap);
2143
  if (r < 0)
2144
    r = _vscprintf(format, ap);
2145
#elif defined(sgi)
2146
  /* Make sure we always use the correct vsnprintf on IRIX */
2147
  extern int      _xpg5_vsnprintf(char * __restrict,
2148
    __SGI_LIBC_NAMESPACE_QUALIFIER size_t,
2149
    const char * __restrict, /* va_list */ char *);
2150
2151
  r = _xpg5_vsnprintf(buf, buflen, format, ap);
2152
#else
2153
0
  r = vsnprintf(buf, buflen, format, ap);
2154
0
#endif
2155
0
  buf[buflen-1] = '\0';
2156
0
  return r;
2157
0
}
2158
2159
#define USE_INTERNAL_NTOP
2160
#define USE_INTERNAL_PTON
2161
2162
const char *
2163
evutil_inet_ntop(int af, const void *src, char *dst, size_t len)
2164
0
{
2165
#if defined(EVENT__HAVE_INET_NTOP) && !defined(USE_INTERNAL_NTOP)
2166
  return inet_ntop(af, src, dst, len);
2167
#else
2168
0
  if (af == AF_INET) {
2169
0
    const struct in_addr *in = src;
2170
0
    const ev_uint32_t a = ntohl(in->s_addr);
2171
0
    int r;
2172
0
    r = evutil_snprintf(dst, len, "%d.%d.%d.%d",
2173
0
        (int)(ev_uint8_t)((a>>24)&0xff),
2174
0
        (int)(ev_uint8_t)((a>>16)&0xff),
2175
0
        (int)(ev_uint8_t)((a>>8 )&0xff),
2176
0
        (int)(ev_uint8_t)((a    )&0xff));
2177
0
    if (r<0||(size_t)r>=len)
2178
0
      return NULL;
2179
0
    else
2180
0
      return dst;
2181
0
#ifdef AF_INET6
2182
0
  } else if (af == AF_INET6) {
2183
0
    const struct in6_addr *addr = src;
2184
0
    char buf[64], *cp;
2185
0
    int longestGapLen = 0, longestGapPos = -1, i,
2186
0
      curGapPos = -1, curGapLen = 0;
2187
0
    ev_uint16_t words[8];
2188
0
    for (i = 0; i < 8; ++i) {
2189
0
      words[i] =
2190
0
          (((ev_uint16_t)addr->s6_addr[2*i])<<8) + addr->s6_addr[2*i+1];
2191
0
    }
2192
0
    if (words[0] == 0 && words[1] == 0 && words[2] == 0 && words[3] == 0 &&
2193
0
        words[4] == 0 && ((words[5] == 0 && words[6] && words[7]) ||
2194
0
      (words[5] == 0xffff))) {
2195
      /* This is an IPv4 address. */
2196
0
      if (words[5] == 0) {
2197
0
        evutil_snprintf(buf, sizeof(buf), "::%d.%d.%d.%d",
2198
0
            addr->s6_addr[12], addr->s6_addr[13],
2199
0
            addr->s6_addr[14], addr->s6_addr[15]);
2200
0
      } else {
2201
0
        evutil_snprintf(buf, sizeof(buf), "::%x:%d.%d.%d.%d", words[5],
2202
0
            addr->s6_addr[12], addr->s6_addr[13],
2203
0
            addr->s6_addr[14], addr->s6_addr[15]);
2204
0
      }
2205
0
      if (strlen(buf) > len)
2206
0
        return NULL;
2207
0
      strlcpy(dst, buf, len);
2208
0
      return dst;
2209
0
    }
2210
0
    i = 0;
2211
0
    while (i < 8) {
2212
0
      if (words[i] == 0) {
2213
0
        curGapPos = i++;
2214
0
        curGapLen = 1;
2215
0
        while (i<8 && words[i] == 0) {
2216
0
          ++i; ++curGapLen;
2217
0
        }
2218
0
        if (curGapLen > longestGapLen) {
2219
0
          longestGapPos = curGapPos;
2220
0
          longestGapLen = curGapLen;
2221
0
        }
2222
0
      } else {
2223
0
        ++i;
2224
0
      }
2225
0
    }
2226
0
    if (longestGapLen<=1)
2227
0
      longestGapPos = -1;
2228
2229
0
    cp = buf;
2230
0
    for (i = 0; i < 8; ++i) {
2231
0
      if (words[i] == 0 && longestGapPos == i) {
2232
0
        if (i == 0)
2233
0
          *cp++ = ':';
2234
0
        *cp++ = ':';
2235
0
        while (i < 8 && words[i] == 0)
2236
0
          ++i;
2237
0
        --i; /* to compensate for loop increment. */
2238
0
      } else {
2239
0
        evutil_snprintf(cp,
2240
0
                sizeof(buf)-(cp-buf), "%x", (unsigned)words[i]);
2241
0
        cp += strlen(cp);
2242
0
        if (i != 7)
2243
0
          *cp++ = ':';
2244
0
      }
2245
0
    }
2246
0
    *cp = '\0';
2247
0
    if (strlen(buf) > len)
2248
0
      return NULL;
2249
0
    strlcpy(dst, buf, len);
2250
0
    return dst;
2251
0
#endif
2252
0
  } else {
2253
0
    return NULL;
2254
0
  }
2255
0
#endif
2256
0
}
2257
2258
int
2259
evutil_inet_pton_scope(int af, const char *src, void *dst, unsigned *indexp)
2260
0
{
2261
0
  int r;
2262
0
  unsigned if_index;
2263
0
  char *check, *cp, *tmp_src;
2264
2265
0
  *indexp = 0; /* Reasonable default */
2266
2267
  /* Bail out if not IPv6 */
2268
0
  if (af != AF_INET6)
2269
0
    return evutil_inet_pton(af, src, dst);
2270
2271
0
  cp = strchr(src, '%');
2272
2273
  /* Bail out if no zone ID */
2274
0
  if (cp == NULL)
2275
0
    return evutil_inet_pton(af, src, dst);
2276
2277
0
  if_index = if_nametoindex(cp + 1);
2278
0
  if (if_index == 0) {
2279
    /* Could be numeric */
2280
0
    if_index = strtoul(cp + 1, &check, 10);
2281
0
    if (check[0] != '\0')
2282
0
      return 0;
2283
0
  }
2284
0
  *indexp = if_index;
2285
0
  if (!(tmp_src = mm_strdup(src))) {
2286
0
    return -1;
2287
0
  }
2288
0
  cp = strchr(tmp_src, '%');
2289
  // The check had been already done above against original src
2290
0
  *cp = '\0';
2291
0
  r = evutil_inet_pton(af, tmp_src, dst);
2292
0
  mm_free(tmp_src);
2293
0
  return r;
2294
0
}
2295
2296
int
2297
evutil_inet_pton(int af, const char *src, void *dst)
2298
0
{
2299
#if defined(EVENT__HAVE_INET_PTON) && !defined(USE_INTERNAL_PTON)
2300
  return inet_pton(af, src, dst);
2301
#else
2302
0
  if (af == AF_INET) {
2303
0
    unsigned a,b,c,d;
2304
0
    char more;
2305
0
    struct in_addr *addr = dst;
2306
0
    if (sscanf(src, "%u.%u.%u.%u%c", &a,&b,&c,&d,&more) != 4)
2307
0
      return 0;
2308
0
    if (a > 255) return 0;
2309
0
    if (b > 255) return 0;
2310
0
    if (c > 255) return 0;
2311
0
    if (d > 255) return 0;
2312
0
    addr->s_addr = htonl((a<<24) | (b<<16) | (c<<8) | d);
2313
0
    return 1;
2314
0
#ifdef AF_INET6
2315
0
  } else if (af == AF_INET6) {
2316
0
    struct in6_addr *out = dst;
2317
0
    ev_uint16_t words[8];
2318
0
    int gapPos = -1, i, setWords=0;
2319
0
    const char *dot = strchr(src, '.');
2320
0
    const char *eow; /* end of words. */
2321
0
    if (dot == src)
2322
0
      return 0;
2323
0
    else if (!dot)
2324
0
      eow = src+strlen(src);
2325
0
    else {
2326
0
      unsigned byte1,byte2,byte3,byte4;
2327
0
      char more;
2328
0
      for (eow = dot-1; eow >= src && EVUTIL_ISDIGIT_(*eow); --eow)
2329
0
        ;
2330
0
      ++eow;
2331
2332
      /* We use "scanf" because some platform inet_aton()s are too lax
2333
       * about IPv4 addresses of the form "1.2.3" */
2334
0
      if (sscanf(eow, "%u.%u.%u.%u%c",
2335
0
             &byte1,&byte2,&byte3,&byte4,&more) != 4)
2336
0
        return 0;
2337
2338
0
      if (byte1 > 255 ||
2339
0
          byte2 > 255 ||
2340
0
          byte3 > 255 ||
2341
0
          byte4 > 255)
2342
0
        return 0;
2343
2344
0
      words[6] = (byte1<<8) | byte2;
2345
0
      words[7] = (byte3<<8) | byte4;
2346
0
      setWords += 2;
2347
0
    }
2348
2349
0
    i = 0;
2350
0
    while (src < eow) {
2351
0
      if (i > 7)
2352
0
        return 0;
2353
0
      if (EVUTIL_ISXDIGIT_(*src)) {
2354
0
        char *next;
2355
0
        long r = strtol(src, &next, 16);
2356
0
        if (next > 4+src)
2357
0
          return 0;
2358
0
        if (next == src)
2359
0
          return 0;
2360
0
        if (r<0 || r>65536)
2361
0
          return 0;
2362
2363
0
        words[i++] = (ev_uint16_t)r;
2364
0
        setWords++;
2365
0
        src = next;
2366
0
        if (*src != ':' && src != eow)
2367
0
          return 0;
2368
0
        ++src;
2369
0
      } else if (*src == ':' && i > 0 && gapPos==-1) {
2370
0
        gapPos = i;
2371
0
        ++src;
2372
0
      } else if (*src == ':' && i == 0 && src[1] == ':' && gapPos==-1) {
2373
0
        gapPos = i;
2374
0
        src += 2;
2375
0
      } else {
2376
0
        return 0;
2377
0
      }
2378
0
    }
2379
2380
0
    if (setWords > 8 ||
2381
0
      (setWords == 8 && gapPos != -1) ||
2382
0
      (setWords < 8 && gapPos == -1))
2383
0
      return 0;
2384
2385
0
    if (gapPos >= 0) {
2386
0
      int nToMove = setWords - (dot ? 2 : 0) - gapPos;
2387
0
      int gapLen = 8 - setWords;
2388
      /* assert(nToMove >= 0); */
2389
0
      if (nToMove < 0)
2390
0
        return -1; /* should be impossible */
2391
0
      memmove(&words[gapPos+gapLen], &words[gapPos],
2392
0
          sizeof(ev_uint16_t)*nToMove);
2393
0
      memset(&words[gapPos], 0, sizeof(ev_uint16_t)*gapLen);
2394
0
    }
2395
0
    for (i = 0; i < 8; ++i) {
2396
0
      out->s6_addr[2*i  ] = words[i] >> 8;
2397
0
      out->s6_addr[2*i+1] = words[i] & 0xff;
2398
0
    }
2399
2400
0
    return 1;
2401
0
#endif
2402
0
  } else {
2403
0
    return -1;
2404
0
  }
2405
0
#endif
2406
0
}
2407
2408
int
2409
evutil_parse_sockaddr_port(const char *ip_as_string, struct sockaddr *out, int *outlen)
2410
0
{
2411
0
  int port;
2412
0
  unsigned int if_index;
2413
0
  char buf[128];
2414
0
  const char *cp, *addr_part, *port_part;
2415
0
  int is_ipv6;
2416
  /* recognized formats are:
2417
   * [ipv6]:port
2418
   * ipv6
2419
   * [ipv6]
2420
   * ipv4:port
2421
   * ipv4
2422
   */
2423
2424
0
  cp = strchr(ip_as_string, ':');
2425
0
  if (*ip_as_string == '[') {
2426
0
    size_t len;
2427
0
    if (!(cp = strchr(ip_as_string, ']'))) {
2428
0
      return -1;
2429
0
    }
2430
0
    len = ( cp-(ip_as_string + 1) );
2431
0
    if (len > sizeof(buf)-1) {
2432
0
      return -1;
2433
0
    }
2434
0
    memcpy(buf, ip_as_string+1, len);
2435
0
    buf[len] = '\0';
2436
0
    addr_part = buf;
2437
0
    if (cp[1] == ':')
2438
0
      port_part = cp+2;
2439
0
    else
2440
0
      port_part = NULL;
2441
0
    is_ipv6 = 1;
2442
0
  } else if (cp && strchr(cp+1, ':')) {
2443
0
    is_ipv6 = 1;
2444
0
    addr_part = ip_as_string;
2445
0
    port_part = NULL;
2446
0
  } else if (cp) {
2447
0
    is_ipv6 = 0;
2448
0
    if (cp - ip_as_string > (int)sizeof(buf)-1) {
2449
0
      return -1;
2450
0
    }
2451
0
    memcpy(buf, ip_as_string, cp-ip_as_string);
2452
0
    buf[cp-ip_as_string] = '\0';
2453
0
    addr_part = buf;
2454
0
    port_part = cp+1;
2455
0
  } else {
2456
0
    addr_part = ip_as_string;
2457
0
    port_part = NULL;
2458
0
    is_ipv6 = 0;
2459
0
  }
2460
2461
0
  if (port_part == NULL) {
2462
0
    port = 0;
2463
0
  } else {
2464
0
    port = atoi(port_part);
2465
0
    if (port <= 0 || port > 65535) {
2466
0
      return -1;
2467
0
    }
2468
0
  }
2469
2470
0
  if (!addr_part)
2471
0
    return -1; /* Should be impossible. */
2472
0
#ifdef AF_INET6
2473
0
  if (is_ipv6)
2474
0
  {
2475
0
    struct sockaddr_in6 sin6;
2476
0
    memset(&sin6, 0, sizeof(sin6));
2477
#ifdef EVENT__HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN
2478
    sin6.sin6_len = sizeof(sin6);
2479
#endif
2480
0
    sin6.sin6_family = AF_INET6;
2481
0
    sin6.sin6_port = htons(port);
2482
0
    if (1 != evutil_inet_pton_scope(
2483
0
      AF_INET6, addr_part, &sin6.sin6_addr, &if_index)) {
2484
0
      return -1;
2485
0
    }
2486
0
    if ((int)sizeof(sin6) > *outlen)
2487
0
      return -1;
2488
0
    sin6.sin6_scope_id = if_index;
2489
0
    memset(out, 0, *outlen);
2490
0
    memcpy(out, &sin6, sizeof(sin6));
2491
0
    *outlen = sizeof(sin6);
2492
0
    return 0;
2493
0
  }
2494
0
  else
2495
0
#endif
2496
0
  {
2497
0
    struct sockaddr_in sin;
2498
0
    memset(&sin, 0, sizeof(sin));
2499
#ifdef EVENT__HAVE_STRUCT_SOCKADDR_IN_SIN_LEN
2500
    sin.sin_len = sizeof(sin);
2501
#endif
2502
0
    sin.sin_family = AF_INET;
2503
0
    sin.sin_port = htons(port);
2504
0
    if (1 != evutil_inet_pton(AF_INET, addr_part, &sin.sin_addr))
2505
0
      return -1;
2506
0
    if ((int)sizeof(sin) > *outlen)
2507
0
      return -1;
2508
0
    memset(out, 0, *outlen);
2509
0
    memcpy(out, &sin, sizeof(sin));
2510
0
    *outlen = sizeof(sin);
2511
0
    return 0;
2512
0
  }
2513
0
}
2514
2515
const char *
2516
evutil_format_sockaddr_port_(const struct sockaddr *sa, char *out, size_t outlen)
2517
0
{
2518
0
  char b[128];
2519
0
  const char *res=NULL;
2520
0
  int port;
2521
0
  if (sa->sa_family == AF_INET) {
2522
0
    const struct sockaddr_in *sin = (const struct sockaddr_in*)sa;
2523
0
    res = evutil_inet_ntop(AF_INET, &sin->sin_addr,b,sizeof(b));
2524
0
    port = ntohs(sin->sin_port);
2525
0
    if (res) {
2526
0
      evutil_snprintf(out, outlen, "%s:%d", b, port);
2527
0
      return out;
2528
0
    }
2529
0
  } else if (sa->sa_family == AF_INET6) {
2530
0
    const struct sockaddr_in6 *sin6 = (const struct sockaddr_in6*)sa;
2531
0
    res = evutil_inet_ntop(AF_INET6, &sin6->sin6_addr,b,sizeof(b));
2532
0
    port = ntohs(sin6->sin6_port);
2533
0
    if (res) {
2534
0
      evutil_snprintf(out, outlen, "[%s]:%d", b, port);
2535
0
      return out;
2536
0
    }
2537
0
  }
2538
2539
0
  evutil_snprintf(out, outlen, "<addr with socktype %d>",
2540
0
      (int)sa->sa_family);
2541
0
  return out;
2542
0
}
2543
2544
int
2545
evutil_sockaddr_cmp(const struct sockaddr *sa1, const struct sockaddr *sa2,
2546
    int include_port)
2547
0
{
2548
0
  int r;
2549
0
  if (0 != (r = (sa1->sa_family - sa2->sa_family)))
2550
0
    return r;
2551
2552
0
  if (sa1->sa_family == AF_INET) {
2553
0
    const struct sockaddr_in *sin1, *sin2;
2554
0
    sin1 = (const struct sockaddr_in *)sa1;
2555
0
    sin2 = (const struct sockaddr_in *)sa2;
2556
0
    if (sin1->sin_addr.s_addr < sin2->sin_addr.s_addr)
2557
0
      return -1;
2558
0
    else if (sin1->sin_addr.s_addr > sin2->sin_addr.s_addr)
2559
0
      return 1;
2560
0
    else if (include_port &&
2561
0
        (r = ((int)sin1->sin_port - (int)sin2->sin_port)))
2562
0
      return r;
2563
0
    else
2564
0
      return 0;
2565
0
  }
2566
0
#ifdef AF_INET6
2567
0
  else if (sa1->sa_family == AF_INET6) {
2568
0
    const struct sockaddr_in6 *sin1, *sin2;
2569
0
    sin1 = (const struct sockaddr_in6 *)sa1;
2570
0
    sin2 = (const struct sockaddr_in6 *)sa2;
2571
0
    if ((r = memcmp(sin1->sin6_addr.s6_addr, sin2->sin6_addr.s6_addr, 16)))
2572
0
      return r;
2573
0
    else if (include_port &&
2574
0
        (r = ((int)sin1->sin6_port - (int)sin2->sin6_port)))
2575
0
      return r;
2576
0
    else
2577
0
      return 0;
2578
0
  }
2579
0
#endif
2580
0
  return 1;
2581
0
}
2582
2583
/* Tables to implement ctypes-replacement EVUTIL_IS*() functions.  Each table
2584
 * has 256 bits to look up whether a character is in some set or not.  This
2585
 * fails on non-ASCII platforms, but so does every other place where we
2586
 * take a char and write it onto the network.
2587
 **/
2588
static const ev_uint32_t EVUTIL_ISALPHA_TABLE[8] =
2589
  { 0, 0, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 };
2590
static const ev_uint32_t EVUTIL_ISALNUM_TABLE[8] =
2591
  { 0, 0x3ff0000, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 };
2592
static const ev_uint32_t EVUTIL_ISSPACE_TABLE[8] = { 0x3e00, 0x1, 0, 0, 0, 0, 0, 0 };
2593
static const ev_uint32_t EVUTIL_ISXDIGIT_TABLE[8] =
2594
  { 0, 0x3ff0000, 0x7e, 0x7e, 0, 0, 0, 0 };
2595
static const ev_uint32_t EVUTIL_ISDIGIT_TABLE[8] = { 0, 0x3ff0000, 0, 0, 0, 0, 0, 0 };
2596
static const ev_uint32_t EVUTIL_ISPRINT_TABLE[8] =
2597
  { 0, 0xffffffff, 0xffffffff, 0x7fffffff, 0, 0, 0, 0x0 };
2598
static const ev_uint32_t EVUTIL_ISUPPER_TABLE[8] = { 0, 0, 0x7fffffe, 0, 0, 0, 0, 0 };
2599
static const ev_uint32_t EVUTIL_ISLOWER_TABLE[8] = { 0, 0, 0, 0x7fffffe, 0, 0, 0, 0 };
2600
/* Upper-casing and lowercasing tables to map characters to upper/lowercase
2601
 * equivalents. */
2602
static const unsigned char EVUTIL_TOUPPER_TABLE[256] = {
2603
  0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
2604
  16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
2605
  32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
2606
  48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
2607
  64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
2608
  80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,
2609
  96,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
2610
  80,81,82,83,84,85,86,87,88,89,90,123,124,125,126,127,
2611
  128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
2612
  144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
2613
  160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
2614
  176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
2615
  192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
2616
  208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
2617
  224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
2618
  240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
2619
};
2620
static const unsigned char EVUTIL_TOLOWER_TABLE[256] = {
2621
  0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
2622
  16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
2623
  32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
2624
  48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
2625
  64,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
2626
  112,113,114,115,116,117,118,119,120,121,122,91,92,93,94,95,
2627
  96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
2628
  112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
2629
  128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
2630
  144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
2631
  160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
2632
  176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
2633
  192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
2634
  208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
2635
  224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
2636
  240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
2637
};
2638
2639
#define IMPL_CTYPE_FN(name)           \
2640
2.36k
  int EVUTIL_##name##_(char c) {         \
2641
2.36k
    ev_uint8_t u = c;         \
2642
2.36k
    return !!(EVUTIL_##name##_TABLE[(u >> 5) & 7] & (1U << (u & 31))); \
2643
2.36k
  }
Unexecuted instantiation: EVUTIL_ISALPHA_
Unexecuted instantiation: EVUTIL_ISALNUM_
Unexecuted instantiation: EVUTIL_ISSPACE_
Unexecuted instantiation: EVUTIL_ISDIGIT_
EVUTIL_ISXDIGIT_
Line
Count
Source
2640
2.36k
  int EVUTIL_##name##_(char c) {         \
2641
2.36k
    ev_uint8_t u = c;         \
2642
2.36k
    return !!(EVUTIL_##name##_TABLE[(u >> 5) & 7] & (1U << (u & 31))); \
2643
2.36k
  }
Unexecuted instantiation: EVUTIL_ISPRINT_
Unexecuted instantiation: EVUTIL_ISLOWER_
Unexecuted instantiation: EVUTIL_ISUPPER_
2644
IMPL_CTYPE_FN(ISALPHA)
2645
IMPL_CTYPE_FN(ISALNUM)
2646
IMPL_CTYPE_FN(ISSPACE)
2647
IMPL_CTYPE_FN(ISDIGIT)
2648
IMPL_CTYPE_FN(ISXDIGIT)
2649
IMPL_CTYPE_FN(ISPRINT)
2650
IMPL_CTYPE_FN(ISLOWER)
2651
IMPL_CTYPE_FN(ISUPPER)
2652
2653
char EVUTIL_TOLOWER_(char c)
2654
0
{
2655
0
  return ((char)EVUTIL_TOLOWER_TABLE[(ev_uint8_t)c]);
2656
0
}
2657
char EVUTIL_TOUPPER_(char c)
2658
0
{
2659
0
  return ((char)EVUTIL_TOUPPER_TABLE[(ev_uint8_t)c]);
2660
0
}
2661
int
2662
evutil_ascii_strcasecmp(const char *s1, const char *s2)
2663
0
{
2664
0
  char c1, c2;
2665
0
  while (1) {
2666
0
    c1 = EVUTIL_TOLOWER_(*s1++);
2667
0
    c2 = EVUTIL_TOLOWER_(*s2++);
2668
0
    if (c1 < c2)
2669
0
      return -1;
2670
0
    else if (c1 > c2)
2671
0
      return 1;
2672
0
    else if (c1 == 0)
2673
0
      return 0;
2674
0
  }
2675
0
}
2676
int evutil_ascii_strncasecmp(const char *s1, const char *s2, size_t n)
2677
0
{
2678
0
  char c1, c2;
2679
0
  while (n--) {
2680
0
    c1 = EVUTIL_TOLOWER_(*s1++);
2681
0
    c2 = EVUTIL_TOLOWER_(*s2++);
2682
0
    if (c1 < c2)
2683
0
      return -1;
2684
0
    else if (c1 > c2)
2685
0
      return 1;
2686
0
    else if (c1 == 0)
2687
0
      return 0;
2688
0
  }
2689
0
  return 0;
2690
0
}
2691
2692
void
2693
evutil_rtrim_lws_(char *str)
2694
0
{
2695
0
  char *cp;
2696
2697
0
  if (str == NULL)
2698
0
    return;
2699
2700
0
  if ((cp = strchr(str, '\0')) == NULL || (cp == str))
2701
0
    return;
2702
2703
0
  --cp;
2704
2705
0
  while (*cp == ' ' || *cp == '\t') {
2706
0
    *cp = '\0';
2707
0
    if (cp == str)
2708
0
      break;
2709
0
    --cp;
2710
0
  }
2711
0
}
2712
2713
static int
2714
evutil_issetugid(void)
2715
0
{
2716
#ifdef EVENT__HAVE_ISSETUGID
2717
  return issetugid();
2718
#else
2719
2720
0
#ifdef EVENT__HAVE_GETEUID
2721
0
  if (getuid() != geteuid())
2722
0
    return 1;
2723
0
#endif
2724
0
#ifdef EVENT__HAVE_GETEGID
2725
0
  if (getgid() != getegid())
2726
0
    return 1;
2727
0
#endif
2728
0
  return 0;
2729
0
#endif
2730
0
}
2731
2732
const char *
2733
evutil_getenv_(const char *varname)
2734
0
{
2735
0
  if (evutil_issetugid())
2736
0
    return NULL;
2737
2738
0
  return getenv(varname);
2739
0
}
2740
2741
ev_uint32_t
2742
evutil_weakrand_seed_(struct evutil_weakrand_state *state, ev_uint32_t seed)
2743
0
{
2744
0
  if (seed == 0) {
2745
0
    struct timeval tv;
2746
0
    evutil_gettimeofday(&tv, NULL);
2747
0
    seed = (ev_uint32_t)tv.tv_sec + (ev_uint32_t)tv.tv_usec;
2748
#ifdef _WIN32
2749
    seed += (ev_uint32_t) _getpid();
2750
#else
2751
0
    seed += (ev_uint32_t) getpid();
2752
0
#endif
2753
0
  }
2754
0
  state->seed = seed;
2755
0
  return seed;
2756
0
}
2757
2758
ev_int32_t
2759
evutil_weakrand_(struct evutil_weakrand_state *state)
2760
0
{
2761
  /* This RNG implementation is a linear congruential generator, with
2762
   * modulus 2^31, multiplier 1103515245, and addend 12345.  It's also
2763
   * used by OpenBSD, and by Glibc's TYPE_0 RNG.
2764
   *
2765
   * The linear congruential generator is not an industrial-strength
2766
   * RNG!  It's fast, but it can have higher-order patterns.  Notably,
2767
   * the low bits tend to have periodicity.
2768
   */
2769
0
  state->seed = ((state->seed) * 1103515245 + 12345) & 0x7fffffff;
2770
0
  return (ev_int32_t)(state->seed);
2771
0
}
2772
2773
ev_int32_t
2774
evutil_weakrand_range_(struct evutil_weakrand_state *state, ev_int32_t top)
2775
0
{
2776
0
  ev_int32_t divisor, result;
2777
2778
  /* We can't just do weakrand() % top, since the low bits of the LCG
2779
   * are less random than the high ones.  (Specifically, since the LCG
2780
   * modulus is 2^N, every 2^m for m<N will divide the modulus, and so
2781
   * therefore the low m bits of the LCG will have period 2^m.) */
2782
0
  divisor = EVUTIL_WEAKRAND_MAX / top;
2783
0
  do {
2784
0
    result = evutil_weakrand_(state) / divisor;
2785
0
  } while (result >= top);
2786
0
  return result;
2787
0
}
2788
2789
/**
2790
 * Volatile pointer to memset: we use this to keep the compiler from
2791
 * eliminating our call to memset.
2792
 */
2793
void * (*volatile evutil_memset_volatile_)(void *, int, size_t) = memset;
2794
2795
void
2796
evutil_memclear_(void *mem, size_t len)
2797
128
{
2798
128
  evutil_memset_volatile_(mem, 0, len);
2799
128
}
2800
2801
int
2802
evutil_sockaddr_is_loopback_(const struct sockaddr *addr)
2803
0
{
2804
0
  static const char LOOPBACK_S6[16] =
2805
0
      "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\1";
2806
0
  if (addr->sa_family == AF_INET) {
2807
0
    struct sockaddr_in *sin = (struct sockaddr_in *)addr;
2808
0
    return (ntohl(sin->sin_addr.s_addr) & 0xff000000) == 0x7f000000;
2809
0
  } else if (addr->sa_family == AF_INET6) {
2810
0
    struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)addr;
2811
0
    return !memcmp(sin6->sin6_addr.s6_addr, LOOPBACK_S6, 16);
2812
0
  }
2813
0
  return 0;
2814
0
}
2815
2816
int
2817
evutil_hex_char_to_int_(char c)
2818
2.04k
{
2819
2.04k
  switch(c)
2820
2.04k
  {
2821
120
    case '0': return 0;
2822
110
    case '1': return 1;
2823
122
    case '2': return 2;
2824
116
    case '3': return 3;
2825
180
    case '4': return 4;
2826
127
    case '5': return 5;
2827
108
    case '6': return 6;
2828
114
    case '7': return 7;
2829
150
    case '8': return 8;
2830
155
    case '9': return 9;
2831
128
    case 'A': case 'a': return 10;
2832
118
    case 'B': case 'b': return 11;
2833
134
    case 'C': case 'c': return 12;
2834
120
    case 'D': case 'd': return 13;
2835
144
    case 'E': case 'e': return 14;
2836
102
    case 'F': case 'f': return 15;
2837
2.04k
  }
2838
0
  return -1;
2839
2.04k
}
2840
2841
#ifdef _WIN32
2842
HMODULE
2843
evutil_load_windows_system_library_(const TCHAR *library_name)
2844
{
2845
  TCHAR path[MAX_PATH];
2846
  unsigned n;
2847
  n = GetSystemDirectory(path, MAX_PATH);
2848
  if (n == 0 || n + _tcslen(library_name) + 2 >= MAX_PATH)
2849
    return 0;
2850
  _tcscat(path, TEXT("\\"));
2851
  _tcscat(path, library_name);
2852
  return LoadLibrary(path);
2853
}
2854
#endif
2855
2856
/* Internal wrapper around 'socket' to provide Linux-style support for
2857
 * syscall-saving methods where available.
2858
 *
2859
 * In addition to regular socket behavior, you can use a bitwise or to set the
2860
 * flags EVUTIL_SOCK_NONBLOCK and EVUTIL_SOCK_CLOEXEC in the 'type' argument,
2861
 * to make the socket nonblocking or close-on-exec with as few syscalls as
2862
 * possible.
2863
 */
2864
evutil_socket_t
2865
evutil_socket_(int domain, int type, int protocol)
2866
0
{
2867
0
  evutil_socket_t r;
2868
0
#if defined(SOCK_NONBLOCK) && defined(SOCK_CLOEXEC)
2869
0
  r = socket(domain, type, protocol);
2870
0
  if (r >= 0)
2871
0
    return r;
2872
0
  else if ((type & (SOCK_NONBLOCK|SOCK_CLOEXEC)) == 0)
2873
0
    return -1;
2874
0
#endif
2875
0
#define SOCKET_TYPE_MASK (~(EVUTIL_SOCK_NONBLOCK|EVUTIL_SOCK_CLOEXEC))
2876
0
  r = socket(domain, type & SOCKET_TYPE_MASK, protocol);
2877
0
  if (r < 0)
2878
0
    return -1;
2879
0
  if (type & EVUTIL_SOCK_NONBLOCK) {
2880
0
    if (evutil_fast_socket_nonblocking(r) < 0) {
2881
0
      evutil_closesocket(r);
2882
0
      return -1;
2883
0
    }
2884
0
  }
2885
0
  if (type & EVUTIL_SOCK_CLOEXEC) {
2886
0
    if (evutil_fast_socket_closeonexec(r) < 0) {
2887
0
      evutil_closesocket(r);
2888
0
      return -1;
2889
0
    }
2890
0
  }
2891
0
  return r;
2892
0
}
2893
2894
/* Internal wrapper around 'accept' or 'accept4' to provide Linux-style
2895
 * support for syscall-saving methods where available.
2896
 *
2897
 * In addition to regular accept behavior, you can set one or more of flags
2898
 * EVUTIL_SOCK_NONBLOCK and EVUTIL_SOCK_CLOEXEC in the 'flags' argument, to
2899
 * make the socket nonblocking or close-on-exec with as few syscalls as
2900
 * possible.
2901
 */
2902
evutil_socket_t
2903
evutil_accept4_(evutil_socket_t sockfd, struct sockaddr *addr,
2904
    ev_socklen_t *addrlen, int flags)
2905
0
{
2906
0
  evutil_socket_t result;
2907
0
#if defined(EVENT__HAVE_ACCEPT4) && defined(SOCK_CLOEXEC) && defined(SOCK_NONBLOCK)
2908
0
  result = accept4(sockfd, addr, addrlen, flags);
2909
0
  if (result >= 0 || (errno != EINVAL && errno != ENOSYS)) {
2910
    /* A nonnegative result means that we succeeded, so return.
2911
     * Failing with EINVAL means that an option wasn't supported,
2912
     * and failing with ENOSYS means that the syscall wasn't
2913
     * there: in those cases we want to fall back.  Otherwise, we
2914
     * got a real error, and we should return. */
2915
0
    return result;
2916
0
  }
2917
0
#endif
2918
0
  result = accept(sockfd, addr, addrlen);
2919
0
  if (result < 0)
2920
0
    return result;
2921
2922
0
  if (flags & EVUTIL_SOCK_CLOEXEC) {
2923
0
    if (evutil_fast_socket_closeonexec(result) < 0) {
2924
0
      evutil_closesocket(result);
2925
0
      return -1;
2926
0
    }
2927
0
  }
2928
0
  if (flags & EVUTIL_SOCK_NONBLOCK) {
2929
0
    if (evutil_fast_socket_nonblocking(result) < 0) {
2930
0
      evutil_closesocket(result);
2931
0
      return -1;
2932
0
    }
2933
0
  }
2934
0
  return result;
2935
0
}
2936
2937
/* Internal function: Set fd[0] and fd[1] to a pair of fds such that writes on
2938
 * fd[1] get read from fd[0].  Make both fds nonblocking and close-on-exec.
2939
 * Return 0 on success, -1 on failure.
2940
 */
2941
int
2942
evutil_make_internal_pipe_(evutil_socket_t fd[2])
2943
0
{
2944
  /*
2945
    Making the second socket nonblocking is a bit subtle, given that we
2946
    ignore any EAGAIN returns when writing to it, and you don't usally
2947
    do that for a nonblocking socket. But if the kernel gives us EAGAIN,
2948
    then there's no need to add any more data to the buffer, since
2949
    the main thread is already either about to wake up and drain it,
2950
    or woken up and in the process of draining it.
2951
  */
2952
2953
0
#if defined(EVENT__HAVE_PIPE2)
2954
0
  if (pipe2(fd, O_NONBLOCK|O_CLOEXEC) == 0)
2955
0
    return 0;
2956
0
#endif
2957
0
#if defined(EVENT__HAVE_PIPE)
2958
0
  if (pipe(fd) == 0) {
2959
0
    if (evutil_fast_socket_nonblocking(fd[0]) < 0 ||
2960
0
        evutil_fast_socket_nonblocking(fd[1]) < 0 ||
2961
0
        evutil_fast_socket_closeonexec(fd[0]) < 0 ||
2962
0
        evutil_fast_socket_closeonexec(fd[1]) < 0) {
2963
0
      close(fd[0]);
2964
0
      close(fd[1]);
2965
0
      fd[0] = fd[1] = -1;
2966
0
      return -1;
2967
0
    }
2968
0
    return 0;
2969
0
  } else {
2970
0
    event_warn("%s: pipe", __func__);
2971
0
  }
2972
0
#endif
2973
2974
#if defined(_WIN32) && !defined(EVENT__HAVE_AFUNIX_H)
2975
#define LOCAL_SOCKETPAIR_AF AF_INET
2976
#else
2977
0
#define LOCAL_SOCKETPAIR_AF AF_UNIX
2978
0
#endif
2979
0
  if (evutil_socketpair(LOCAL_SOCKETPAIR_AF, SOCK_STREAM, 0, fd) == 0) {
2980
0
    if (evutil_fast_socket_nonblocking(fd[0]) < 0 ||
2981
0
        evutil_fast_socket_nonblocking(fd[1]) < 0 ||
2982
0
        evutil_fast_socket_closeonexec(fd[0]) < 0 ||
2983
0
        evutil_fast_socket_closeonexec(fd[1]) < 0) {
2984
0
      evutil_closesocket(fd[0]);
2985
0
      evutil_closesocket(fd[1]);
2986
0
      fd[0] = fd[1] = -1;
2987
0
      return -1;
2988
0
    }
2989
0
    return 0;
2990
0
  }
2991
0
  fd[0] = fd[1] = -1;
2992
0
  return -1;
2993
0
}
2994
2995
/* Wrapper around eventfd on systems that provide it.  Unlike the system
2996
 * eventfd, it always supports EVUTIL_EFD_CLOEXEC and EVUTIL_EFD_NONBLOCK as
2997
 * flags.  Returns -1 on error or if eventfd is not supported.
2998
 */
2999
evutil_socket_t
3000
evutil_eventfd_(unsigned initval, int flags)
3001
0
{
3002
0
#if defined(EVENT__HAVE_EVENTFD) && defined(EVENT__HAVE_SYS_EVENTFD_H)
3003
0
  int r;
3004
0
#if defined(EFD_CLOEXEC) && defined(EFD_NONBLOCK)
3005
0
  r = eventfd(initval, flags);
3006
0
  if (r >= 0 || flags == 0)
3007
0
    return r;
3008
0
#endif
3009
0
  r = eventfd(initval, 0);
3010
0
  if (r < 0)
3011
0
    return r;
3012
0
  if (flags & EVUTIL_EFD_CLOEXEC) {
3013
0
    if (evutil_fast_socket_closeonexec(r) < 0) {
3014
0
      evutil_closesocket(r);
3015
0
      return -1;
3016
0
    }
3017
0
  }
3018
0
  if (flags & EVUTIL_EFD_NONBLOCK) {
3019
0
    if (evutil_fast_socket_nonblocking(r) < 0) {
3020
0
      evutil_closesocket(r);
3021
0
      return -1;
3022
0
    }
3023
0
  }
3024
0
  return r;
3025
#else
3026
  return -1;
3027
#endif
3028
0
}
3029
3030
void
3031
evutil_free_globals_(void)
3032
0
{
3033
0
  evutil_free_secure_rng_globals_();
3034
0
  evutil_free_sock_err_globals();
3035
0
}
3036
3037
int
3038
evutil_set_tcp_keepalive(evutil_socket_t fd, int on, int timeout)
3039
0
{
3040
0
  int idle;
3041
0
  int intvl;
3042
0
  int cnt;
3043
3044
  /* Prevent compiler from complaining unused variables warnings. */
3045
0
  (void) idle;
3046
0
  (void) intvl;
3047
0
  (void) cnt;
3048
3049
0
  if (timeout <= 0)
3050
0
    return 0;
3051
3052
0
  if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on)))
3053
0
    return -1;
3054
0
  if (!on)
3055
0
    return 0;
3056
3057
  /* Unlike Unix-like OS's, TCP keep-alive mechanism on Windows is kind of a mess,
3058
   * setting TCP_KEEPIDLE, TCP_KEEPINTVL and TCP_KEEPCNT on Windows could be a bit tricky.
3059
   * Check out https://learn.microsoft.com/en-us/windows/win32/winsock/sio-keepalive-vals,
3060
   * https://learn.microsoft.com/en-us/windows/win32/winsock/ipproto-tcp-socket-options.
3061
   * These three options are not available until Windows 10, version 1709 where we set them
3062
   * by `setsockopt` (slightly different from Unix-like OS's pattern), while on older Windows,
3063
   * we have to use `WSAIoctl` instead.
3064
   * Therefore, we skip setting those three options on Windows for now.
3065
   * TODO(panjf2000): enable the full TCP keep-alive mechanism on Windows when we find a feasible way to do it.
3066
   */
3067
0
#ifndef _WIN32
3068
3069
#ifdef __sun
3070
  /* The implementation of TCP keep-alive on Solaris/SmartOS is a bit unusual
3071
   * compared to other Unix-like systems.
3072
   * Thus, we need to specialize it on Solaris.
3073
   *
3074
   * There are two keep-alive mechanisms on Solaris:
3075
   * - By default, the first keep-alive probe is sent out after a TCP connection is idle for two hours.
3076
   * If the peer does not respond to the probe within eight minutes, the TCP connection is aborted.
3077
   * You can alter the interval for sending out the first probe using the socket option TCP_KEEPALIVE_THRESHOLD
3078
   * in milliseconds or TCP_KEEPIDLE in seconds.
3079
   * The system default is controlled by the TCP ndd parameter tcp_keepalive_interval. The minimum value is ten seconds.
3080
   * The maximum is ten days, while the default is two hours. If you receive no response to the probe,
3081
   * you can use the TCP_KEEPALIVE_ABORT_THRESHOLD socket option to change the time threshold for aborting a TCP connection.
3082
   * The option value is an unsigned integer in milliseconds. The value zero indicates that TCP should never time out and
3083
   * abort the connection when probing. The system default is controlled by the TCP ndd parameter tcp_keepalive_abort_interval.
3084
   * The default is eight minutes.
3085
   *
3086
   * - The second implementation is activated if socket option TCP_KEEPINTVL and/or TCP_KEEPCNT are set.
3087
   * The time between each consequent probes is set by TCP_KEEPINTVL in seconds.
3088
   * The minimum value is ten seconds. The maximum is ten days, while the default is two hours.
3089
   * The TCP connection will be aborted after certain amount of probes, which is set by TCP_KEEPCNT, without receiving response.
3090
   */
3091
3092
  idle = timeout;
3093
  /* Kernel expects at least 10 seconds. */
3094
  if (idle < 10)
3095
    idle = 10;
3096
  /* Kernel expects at most 10 days. */
3097
  if (idle > 10*24*60*60)
3098
    idle = 10*24*60*60;
3099
3100
  /* `TCP_KEEPIDLE`, `TCP_KEEPINTVL`, and `TCP_KEEPCNT` were not available on Solaris
3101
   * until version 11.4, but let's gamble here.
3102
   */
3103
#if defined(TCP_KEEPIDLE) && defined(TCP_KEEPINTVL) && defined(TCP_KEEPCNT)
3104
  if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, &idle, sizeof(idle)))
3105
    return -1;
3106
3107
  intvl = idle/3;
3108
  if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, &intvl, sizeof(intvl)))
3109
    return -1;
3110
3111
  cnt = 3;
3112
  if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPCNT, &cnt, sizeof(cnt)))
3113
    return -1;
3114
#else
3115
  /* Fall back to the first implementation of tcp-alive mechanism for older Solaris,
3116
   * simulate the tcp-alive mechanism on other platforms via `TCP_KEEPALIVE_THRESHOLD` + `TCP_KEEPALIVE_ABORT_THRESHOLD`.
3117
   */
3118
  idle *= 1000; /* kernel expects milliseconds */
3119
  if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPALIVE_THRESHOLD, &idle, sizeof(idle)))
3120
    return -1;
3121
3122
  /* Note that the consequent probes will not be sent at equal intervals on Solaris,
3123
   * but will be sent using the exponential backoff algorithm.
3124
   */
3125
  intvl = idle/3;
3126
  cnt = 3;
3127
  int time_to_abort = intvl * cnt;
3128
  if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPALIVE_ABORT_THRESHOLD, &time_to_abort, sizeof(time_to_abort)))
3129
    return -1;
3130
#endif
3131
3132
#else /* !__sun */
3133
3134
0
#ifdef TCP_KEEPIDLE
3135
0
  idle = timeout;
3136
0
  if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, &idle, sizeof(idle)))
3137
0
    return -1;
3138
#elif defined(TCP_KEEPALIVE)
3139
  /* Darwin/macOS uses TCP_KEEPALIVE in place of TCP_KEEPIDLE. */
3140
  idle = timeout;
3141
  if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPALIVE, &idle, sizeof(idle)))
3142
    return -1;
3143
#endif
3144
3145
0
#ifdef TCP_KEEPINTVL
3146
  /* Set the interval between individual keep-alive probes as timeout / 3
3147
   * and the maximum number of keepalive probes as 3 to make it double timeout
3148
   * before aborting a dead connection.
3149
   */
3150
0
  intvl = timeout/3;
3151
0
  if (intvl == 0)
3152
0
    intvl = 1;
3153
0
  if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, &intvl, sizeof(intvl)))
3154
0
    return -1;
3155
0
#endif
3156
3157
0
#ifdef TCP_KEEPCNT
3158
  /* Set the maximum number of keepalive probes as 3 to collaborate with
3159
   * TCP_KEEPINTVL, see the previous comment.
3160
   */
3161
0
  cnt = 3;
3162
0
  if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPCNT, &cnt, sizeof(cnt)))
3163
0
    return -1;
3164
0
#endif
3165
3166
0
#endif /* !__sun */
3167
3168
0
#endif /* !_WIN32 */
3169
3170
0
  return 0;
3171
0
}