Coverage Report

Created: 2025-11-24 06:26

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