Coverage Report

Created: 2023-04-12 06:22

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