address.c 36.4 KB
Newer Older
1
2
3
4
5
6
7
8
9
/* Copyright (c) 2003-2004, Roger Dingledine
 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
 * Copyright (c) 2007-2008, The Tor Project, Inc. */
/* See LICENSE for licensing information */
/* $Id$ */
const char address_c_id[] =
  "$Id$";

/**
10
 * \file address.c
11
 * \brief Functions to use and manipulate the tor_addr_t structure.
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
 **/

#include "orconfig.h"
#include "compat.h"
#include "util.h"
#include "address.h"
#include "log.h"

#ifdef MS_WINDOWS
#include <process.h>
#include <windows.h>
#endif

#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_ERRNO_H
#include <errno.h>
#endif
#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
#ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
#ifdef HAVE_NETDB_H
#include <netdb.h>
#endif
#ifdef HAVE_SYS_PARAM_H
#include <sys/param.h> /* FreeBSD needs this to know what version it is */
#endif
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>

55
56
57
58
/** Convert the tor_addr_t in <b>a</b>, with port in <b>port</b>, into a
 * socklen object in *<b>sa_out</b> of object size <b>len</b>.  If not enough
 * room is free, or on error, return -1.  Else return the length of the
 * sockaddr. */
59
60
61
socklen_t
tor_addr_to_sockaddr(const tor_addr_t *a,
                     uint16_t port,
62
63
                     struct sockaddr *sa_out,
                     socklen_t len)
64
65
{
  if (a->family == AF_INET) {
66
    struct sockaddr_in *sin;
67
    if (len < (int)sizeof(struct sockaddr_in))
68
69
      return -1;
    sin = (struct sockaddr_in *)sa_out;
70
    sin->sin_family = AF_INET;
71
72
    sin->sin_port = htons(port);
    sin->sin_addr.s_addr = tor_addr_to_ipv4n(a);
73
74
    return sizeof(struct sockaddr_in);
  } else if (a->family == AF_INET6) {
75
    struct sockaddr_in6 *sin6;
76
    if (len < (int)sizeof(struct sockaddr_in6))
77
78
      return -1;
    sin6 = (struct sockaddr_in6 *)sa_out;
79
80
    memset(sin6, 0, sizeof(struct sockaddr_in6));
    sin6->sin6_family = AF_INET6;
81
    sin6->sin6_port = htons(port);
82
83
84
85
86
87
88
    memcpy(&sin6->sin6_addr, &a->addr.in6_addr, sizeof(struct in6_addr));
    return sizeof(struct sockaddr_in6);
  } else {
    return -1;
  }
}

89
90
/** Set the tor_addr_t in <b>a</b> to contain the socket address contained in
 * <b>sa</b>. */
91
int
92
93
tor_addr_from_sockaddr(tor_addr_t *a, const struct sockaddr *sa,
                       uint16_t *port_out)
94
{
95
96
97
  tor_assert(a);
  tor_assert(sa);
  memset(a, 0, sizeof(tor_addr_t));
98
99
100
101
  if (sa->sa_family == AF_INET) {
    struct sockaddr_in *sin = (struct sockaddr_in *) sa;
    a->family = AF_INET;
    a->addr.in_addr.s_addr = sin->sin_addr.s_addr;
102
103
    if (port_out)
      *port_out = ntohs(sin->sin_port);
104
105
106
107
  } else if (sa->sa_family == AF_INET6) {
    struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
    a->family = AF_INET6;
    memcpy(&a->addr.in6_addr, &sin6->sin6_addr, sizeof(struct in6_addr));
108
109
    if (port_out)
      *port_out = ntohs(sin6->sin6_port);
110
111
  } else {
    a->family = AF_UNSPEC;
112
    return -1;
113
  }
114
115
116
117
118
119
120
121
122
123
  return 0;
}

/** Set address <b>a</b> to the unspecified address.  This address belongs to
 * no family. */
void
tor_addr_make_unspec(tor_addr_t *a)
{
  memset(a, 0, sizeof(*a));
  a->family = AF_UNSPEC;
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
}

/** Similar behavior to Unix gethostbyname: resolve <b>name</b>, and set
 * *<b>addr</b> to the proper IP address and family. The <b>family</b>
 * argument (which must be AF_INET, AF_INET6, or AF_UNSPEC) declares a
 * <i>preferred</i> family, though another one may be returned if only one
 * family is implemented for this address.
 *
 * Return 0 on success, -1 on failure; 1 on transient failure.
 */
int
tor_addr_lookup(const char *name, uint16_t family, tor_addr_t *addr)
{
  /* Perhaps eventually this should be replaced by a tor_getaddrinfo or
   * something.
   */
  struct in_addr iaddr;
  struct in6_addr iaddr6;
  tor_assert(name);
  tor_assert(addr);
144
  tor_assert(family == AF_INET || family == AF_INET6 || family == AF_UNSPEC);
145
146
147
148
149
150
  memset(addr, 0, sizeof(addr)); /* Clear the extraneous fields. */
  if (!*name) {
    /* Empty address is an error. */
    return -1;
  } else if (tor_inet_pton(AF_INET, name, &iaddr)) {
    /* It's an IPv4 IP. */
151
152
    if (family == AF_INET6)
      return -1;
153
154
155
156
    addr->family = AF_INET;
    memcpy(&addr->addr.in_addr, &iaddr, sizeof(struct in_addr));
    return 0;
  } else if (tor_inet_pton(AF_INET6, name, &iaddr6)) {
157
158
    if (family == AF_INET)
      return -1;
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
    addr->family = AF_INET6;
    memcpy(&addr->addr.in6_addr, &iaddr6, sizeof(struct in6_addr));
    return 0;
  } else {
#ifdef HAVE_GETADDRINFO
    int err;
    struct addrinfo *res=NULL, *res_p;
    struct addrinfo *best=NULL;
    struct addrinfo hints;
    int result = -1;
    memset(&hints, 0, sizeof(hints));
    hints.ai_family = family;
    hints.ai_socktype = SOCK_STREAM;
    err = getaddrinfo(name, NULL, &hints, &res);
    if (!err) {
      best = NULL;
      for (res_p = res; res_p; res_p = res_p->ai_next) {
        if (family == AF_UNSPEC) {
          if (res_p->ai_family == AF_INET) {
            best = res_p;
            break;
          } else if (res_p->ai_family == AF_INET6 && !best) {
            best = res_p;
          }
        } else if (family == res_p->ai_family) {
          best = res_p;
          break;
        }
      }
      if (!best)
        best = res;
      if (best->ai_family == AF_INET) {
        addr->family = AF_INET;
        memcpy(&addr->addr.in_addr,
               &((struct sockaddr_in*)best->ai_addr)->sin_addr,
               sizeof(struct in_addr));
        result = 0;
      } else if (best->ai_family == AF_INET6) {
        addr->family = AF_INET6;
        memcpy(&addr->addr.in6_addr,
               &((struct sockaddr_in6*)best->ai_addr)->sin6_addr,
               sizeof(struct in6_addr));
        result = 0;
      }
      freeaddrinfo(res);
      return result;
    }
    return (err == EAI_AGAIN) ? 1 : -1;
#else
    struct hostent *ent;
    int err;
#ifdef HAVE_GETHOSTBYNAME_R_6_ARG
    char buf[2048];
    struct hostent hostent;
    int r;
    r = gethostbyname_r(name, &hostent, buf, sizeof(buf), &ent, &err);
#elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
    char buf[2048];
    struct hostent hostent;
    ent = gethostbyname_r(name, &hostent, buf, sizeof(buf), &err);
#elif defined(HAVE_GETHOSTBYNAME_R_3_ARG)
    struct hostent_data data;
    struct hostent hent;
    memset(&data, 0, sizeof(data));
    err = gethostbyname_r(name, &hent, &data);
    ent = err ? NULL : &hent;
#else
    ent = gethostbyname(name);
#ifdef MS_WINDOWS
    err = WSAGetLastError();
#else
    err = h_errno;
#endif
#endif /* endif HAVE_GETHOSTBYNAME_R_6_ARG. */
    if (ent) {
      addr->family = ent->h_addrtype;
      if (ent->h_addrtype == AF_INET) {
        memcpy(&addr->addr.in_addr, ent->h_addr, sizeof(struct in_addr));
      } else if (ent->h_addrtype == AF_INET6) {
        memcpy(&addr->addr.in6_addr, ent->h_addr, sizeof(struct in6_addr));
      } else {
        tor_assert(0); /* gethostbyname() returned a bizarre addrtype */
      }
      return 0;
    }
#ifdef MS_WINDOWS
    return (err == WSATRY_AGAIN) ? 1 : -1;
#else
    return (err == TRY_AGAIN) ? 1 : -1;
#endif
#endif
  }
}

/** Return true iff <b>ip</b> is an IP reserved to localhost or local networks
 * in RFC1918 or RFC4193 or RFC4291. (fec0::/10, deprecated by RFC3879, is
 * also treated as internal for now.)
 */
int
tor_addr_is_internal(const tor_addr_t *addr, int for_listening)
{
  uint32_t iph4 = 0;
  uint32_t iph6[4];
  sa_family_t v_family;
  v_family = tor_addr_family(addr);

  if (v_family == AF_INET) {
    iph4 = tor_addr_to_ipv4h(addr);
  } else if (v_family == AF_INET6) {
    if (tor_addr_is_v4(addr)) { /* v4-mapped */
      v_family = AF_INET;
      iph4 = ntohl(tor_addr_to_in6_addr32(addr)[3]);
    }
  }

  if (v_family == AF_INET6) {
    const uint32_t *a32 = tor_addr_to_in6_addr32(addr);
    iph6[0] = ntohl(a32[0]);
    iph6[1] = ntohl(a32[1]);
    iph6[2] = ntohl(a32[2]);
    iph6[3] = ntohl(a32[3]);
    if (for_listening && !iph6[0] && !iph6[1] && !iph6[2] && !iph6[3]) /* :: */
      return 0;

    if (((iph6[0] & 0xfe000000) == 0xfc000000) || /* fc00/7  - RFC4193 */
        ((iph6[0] & 0xffc00000) == 0xfe800000) || /* fe80/10 - RFC4291 */
        ((iph6[0] & 0xffc00000) == 0xfec00000))   /* fec0/10 D- RFC3879 */
      return 1;

    if (!iph6[0] && !iph6[1] && !iph6[2] &&
        ((iph6[3] & 0xfffffffe) == 0x00000000))  /* ::/127 */
      return 1;

    return 0;
  } else if (v_family == AF_INET) {
    if (for_listening && !iph4) /* special case for binding to 0.0.0.0 */
      return 0;
    if (((iph4 & 0xff000000) == 0x0a000000) || /*       10/8 */
        ((iph4 & 0xff000000) == 0x00000000) || /*        0/8 */
        ((iph4 & 0xff000000) == 0x7f000000) || /*      127/8 */
        ((iph4 & 0xffff0000) == 0xa9fe0000) || /* 169.254/16 */
        ((iph4 & 0xfff00000) == 0xac100000) || /*  172.16/12 */
        ((iph4 & 0xffff0000) == 0xc0a80000))   /* 192.168/16 */
      return 1;
    return 0;
  }

  /* unknown address family... assume it's not safe for external use */
  /* rather than tor_assert(0) */
  log_warn(LD_BUG, "tor_addr_is_internal() called with a non-IP address.");
  return 1;
}

/** Convert a tor_addr_t <b>addr</b> into a string, and store it in
 *  <b>dest</b> of size <b>len</b>.  Returns a pointer to dest on success,
 *  or NULL on failure.  If <b>decorate</b>, surround IPv6 addresses with
 *  brackets.
 */
const char *
tor_addr_to_str(char *dest, const tor_addr_t *addr, int len, int decorate)
{
  const char *ptr;
  tor_assert(addr && dest);

  switch (tor_addr_family(addr)) {
    case AF_INET:
      if (len<3)
        return NULL;
327
328
329
        ptr = tor_inet_ntop(AF_INET, &addr->addr.in_addr, dest, len);
      break;
    case AF_INET6:
330
      if (decorate)
331
        ptr = tor_inet_ntop(AF_INET6, &addr->addr.in6_addr, dest+1, len-2);
332
      else
333
        ptr = tor_inet_ntop(AF_INET6, &addr->addr.in6_addr, dest, len);
334
335
336
      if (ptr && decorate) {
        *dest = '[';
        memcpy(dest+strlen(dest), "]", 2);
337
338
        tor_assert(ptr == dest+1);
        ptr = dest;
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
      }
      break;
    default:
      return NULL;
  }
  return ptr;
}

/** Parse a string <b>s</b> containing an IPv4/IPv6 address, and possibly
 *  a mask and port or port range.  Store the parsed address in
 *  <b>addr_out</b>, a mask (if any) in <b>mask_out</b>, and port(s) (if any)
 *  in <b>port_min_out</b> and <b>port_max_out</b>.
 *
 * The syntax is:
 *   Address OptMask OptPortRange
 *   Address ::= IPv4Address / "[" IPv6Address "]" / "*"
 *   OptMask ::= "/" Integer /
 *   OptPortRange ::= ":*" / ":" Integer / ":" Integer "-" Integer /
 *
 *  - If mask, minport, or maxport are NULL, we do not want these
 *    options to be set; treat them as an error if present.
 *  - If the string has no mask, the mask is set to /32 (IPv4) or /128 (IPv6).
 *  - If the string has one port, it is placed in both min and max port
 *    variables.
 *  - If the string has no port(s), port_(min|max)_out are set to 1 and 65535.
 *
 *  Return an address family on success, or -1 if an invalid address string is
 *  provided.
 */
int
tor_addr_parse_mask_ports(const char *s, tor_addr_t *addr_out,
                          maskbits_t *maskbits_out,
                          uint16_t *port_min_out, uint16_t *port_max_out)
{
  char *base = NULL, *address, *mask = NULL, *port = NULL, *rbracket = NULL;
  char *endptr;
  int any_flag=0, v4map=0;

  tor_assert(s);
  tor_assert(addr_out);

  /* IP, [], /mask, ports */
#define MAX_ADDRESS_LENGTH (TOR_ADDR_BUF_LEN+2+(1+INET_NTOA_BUF_LEN)+12+1)

  if (strlen(s) > MAX_ADDRESS_LENGTH) {
    log_warn(LD_GENERAL, "Impossibly long IP %s; rejecting", escaped(s));
    goto err;
  }
  base = tor_strdup(s);

  /* Break 'base' into separate strings. */
  address = base;
  if (*address == '[') {  /* Probably IPv6 */
    address++;
    rbracket = strchr(address, ']');
    if (!rbracket) {
      log_warn(LD_GENERAL,
               "No closing IPv6 bracket in address pattern; rejecting.");
      goto err;
    }
  }
  mask = strchr((rbracket?rbracket:address),'/');
  port = strchr((mask?mask:(rbracket?rbracket:address)), ':');
  if (port)
    *port++ = '\0';
  if (mask)
    *mask++ = '\0';
  if (rbracket)
    *rbracket = '\0';
  if (port && mask)
    tor_assert(port > mask);
  if (mask && rbracket)
    tor_assert(mask > rbracket);

  /* Now "address" is the a.b.c.d|'*'|abcd::1 part...
   *     "mask" is the Mask|Maskbits part...
   * and "port" is the *|port|min-max part.
   */

  /* Process the address portion */
  memset(addr_out, 0, sizeof(tor_addr_t));

  if (!strcmp(address, "*")) {
    addr_out->family = AF_INET; /* AF_UNSPEC ???? XXXX_IP6 */
    any_flag = 1;
  } else if (tor_inet_pton(AF_INET6, address, &addr_out->addr.in6_addr) > 0) {
    addr_out->family = AF_INET6;
  } else if (tor_inet_pton(AF_INET, address, &addr_out->addr.in_addr) > 0) {
    addr_out->family = AF_INET;
  } else {
    log_warn(LD_GENERAL, "Malformed IP %s in address pattern; rejecting.",
             escaped(address));
    goto err;
  }

  v4map = tor_addr_is_v4(addr_out);

/*
#ifdef ALWAYS_V6_MAP
  if (v_family == AF_INET) {
    v_family = AF_INET6;
    IN_ADDR6(addr_out).s6_addr32[3] = IN6_ADDRESS(addr_out).s_addr;
    memset(&IN6_ADDRESS(addr_out), 0, 10);
    IN_ADDR6(addr_out).s6_addr16[5] = 0xffff;
  }
#else
  if (v_family == AF_INET6 && v4map) {
    v_family = AF_INET;
    IN4_ADDRESS((addr_out).s_addr = IN6_ADDRESS(addr_out).s6_addr32[3];
  }
#endif
*/

  /* Parse mask */
  if (maskbits_out) {
    int bits = 0;
    struct in_addr v4mask;

    if (mask) {  /* the caller (tried to) specify a mask */
      bits = (int) strtol(mask, &endptr, 10);
      if (!*endptr) {  /* strtol converted everything, so it was an integer */
        if ((bits<0 || bits>128) ||
            ((tor_addr_family(addr_out) == AF_INET) && bits > 32)) {
          log_warn(LD_GENERAL,
                   "Bad number of mask bits (%d) on address range; rejecting.",
                   bits);
          goto err;
        }
      } else {  /* mask might still be an address-style mask */
        if (tor_inet_pton(AF_INET, mask, &v4mask) > 0) {
          bits = addr_mask_get_bits(ntohl(v4mask.s_addr));
          if (bits < 0) {
            log_warn(LD_GENERAL,
                     "IPv4-style mask %s is not a prefix address; rejecting.",
                     escaped(mask));
            goto err;
          }
        } else { /* Not IPv4; we don't do address-style IPv6 masks. */
          log_warn(LD_GENERAL,
                   "Malformed mask on address range %s; rejecting.",
                   escaped(s));
          goto err;
        }
      }
      if (tor_addr_family(addr_out) == AF_INET6 && v4map) {
        if (bits > 32 && bits < 96) { /* Crazy */
          log_warn(LD_GENERAL,
                   "Bad mask bits %i for V4-mapped V6 address; rejecting.",
                   bits);
          goto err;
        }
        /* XXXX_IP6 is this really what we want? */
        bits = 96 + bits%32; /* map v4-mapped masks onto 96-128 bits */
      }
    } else { /* pick an appropriate mask, as none was given */
      if (any_flag)
        bits = 0;  /* This is okay whether it's V6 or V4 (FIX V4-mapped V6!) */
      else if (tor_addr_family(addr_out) == AF_INET)
        bits = 32;
      else if (tor_addr_family(addr_out) == AF_INET6)
        bits = 128;
    }
    *maskbits_out = (maskbits_t) bits;
  } else {
    if (mask) {
      log_warn(LD_GENERAL,
               "Unexpected mask in addrss %s; rejecting", escaped(s));
      goto err;
    }
  }

  /* Parse port(s) */
  if (port_min_out) {
    uint16_t port2;
    if (!port_max_out) /* caller specified one port; fake the second one */
      port_max_out = &port2;

    if (parse_port_range(port, port_min_out, port_max_out) < 0) {
      goto err;
    } else if ((*port_min_out != *port_max_out) && port_max_out == &port2) {
      log_warn(LD_GENERAL,
               "Wanted one port from address range, but there are two.");

      port_max_out = NULL;  /* caller specified one port, so set this back */
      goto err;
    }
  } else {
    if (port) {
      log_warn(LD_GENERAL,
               "Unexpected ports in addrss %s; rejecting", escaped(s));
      goto err;
    }
  }

  tor_free(base);
  return tor_addr_family(addr_out);
 err:
  tor_free(base);
  return -1;
}

/** Determine whether an address is IPv4, either native or ipv4-mapped ipv6.
 * Note that this is about representation only, as any decent stack will
 * reject ipv4-mapped addresses received on the wire (and won't use them
 * on the wire either).
 */
int
tor_addr_is_v4(const tor_addr_t *addr)
{
  tor_assert(addr);

  if (tor_addr_family(addr) == AF_INET)
    return 1;

  if (tor_addr_family(addr) == AF_INET6) {
    /* First two don't need to be ordered */
    uint32_t *a32 = tor_addr_to_in6_addr32(addr);
    if (a32[0] == 0 && a32[1] == 0 && ntohl(a32[2]) == 0x0000ffffu)
      return 1;
  }

  return 0; /* Not IPv4 - unknown family or a full-blood IPv6 address */
}

/** Determine whether an address <b>addr</b> is null, either all zeroes or
 *  belonging to family AF_UNSPEC.
 */
int
tor_addr_is_null(const tor_addr_t *addr)
{
  tor_assert(addr);

  switch (tor_addr_family(addr)) {
    case AF_INET6: {
      uint32_t *a32 = tor_addr_to_in6_addr32(addr);
      return (a32[0] == 0) && (a32[1] == 0) && (a32[2] == 0) && (a32[3] == 0);
    }
    case AF_INET:
      return (tor_addr_to_ipv4n(addr) == 0);
    case AF_UNSPEC:
      return 1;
    default:
      log_warn(LD_BUG, "Called with unknown address family %d",
               (int)tor_addr_family(addr));
      return 0;
  }
  //return 1;
}

/** Return true iff <b>addr</b> is a loopback address */
int
tor_addr_is_loopback(const tor_addr_t *addr)
{
  tor_assert(addr);
  switch (tor_addr_family(addr)) {
    case AF_INET6: {
      /* ::1 */
      uint32_t *a32 = tor_addr_to_in6_addr32(addr);
      return (a32[0] == 0) && (a32[1] == 0) && (a32[2] == 0) && (a32[3] == 1);
    }
    case AF_INET:
      /* 127.0.0.1 */
      return (tor_addr_to_ipv4h(addr) & 0xff000000) == 0x7f000000;
    case AF_UNSPEC:
      return 0;
    default:
      tor_fragile_assert();
      return 0;
  }
}

610
611
/** Set <b>dest</b> to equal the IPv4 address in <b>v4addr</b> (given in
 * network order. */
612
void
613
tor_addr_from_ipv4n(tor_addr_t *dest, uint32_t v4addr)
614
615
616
617
{
  tor_assert(dest);
  memset(dest, 0, sizeof(dest));
  dest->family = AF_INET;
618
619
620
621
622
623
624
625
626
627
628
629
630
  dest->addr.in_addr.s_addr = v4addr;
}

/** Set <b>dest</b> to equal the IPv6 address in the 16 bytes at
 * <b>ipv6_bytes</b>. */
void
tor_addr_from_ipv6_bytes(tor_addr_t *dest, const char *ipv6_bytes)
{
  tor_assert(dest);
  tor_assert(ipv6_bytes);
  memset(dest, 0, sizeof(dest));
  dest->family = AF_INET6;
  memcpy(dest->addr.in6_addr.s6_addr, ipv6_bytes, 16);
631
632
}

Nick Mathewson's avatar
Nick Mathewson committed
633
/** Set <b>dest</b> equal to the IPv6 address in the in6_addr <b>in6</b>. */
634
635
636
637
638
639
void
tor_addr_from_in6(tor_addr_t *dest, const struct in6_addr *in6)
{
  tor_addr_from_ipv6_bytes(dest, (const char*)in6->s6_addr);
}

640
641
642
643
644
/** Copy a tor_addr_t from <b>src</b> to <b>dest</b>.
 */
void
tor_addr_copy(tor_addr_t *dest, const tor_addr_t *src)
{
645
646
  tor_assert(src);
  tor_assert(dest);
647
648
649
650
651
652
653
654
  memcpy(dest, src, sizeof(tor_addr_t));
}

/** Given two addresses <b>addr1</b> and <b>addr2</b>, return 0 if the two
 * addresses are equivalent under the mask mbits, less than 0 if addr1
 * preceeds addr2, and greater than 0 otherwise.
 *
 * Different address families (IPv4 vs IPv6) are always considered unequal.
655
 *   NOT QUITE XXXX DOCDOC.
656
657
 */
int
658
659
tor_addr_compare(const tor_addr_t *addr1, const tor_addr_t *addr2,
                 tor_addr_comparison_t how)
660
{
661
  return tor_addr_compare_masked(addr1, addr2, 128, how);
662
663
664
665
666
667
668
669
670
}

/** As tor_addr_compare(), but only looks at the first <b>mask</b> bits of
 * the address.
 *
 * Reduce over-specific masks (>128 for ipv6, >32 for ipv4) to 128 or 32.
 */
int
tor_addr_compare_masked(const tor_addr_t *addr1, const tor_addr_t *addr2,
671
                        maskbits_t mbits, tor_addr_comparison_t how)
672
673
674
675
676
677
678
679
{
  uint32_t ip4a=0, ip4b=0;
  sa_family_t v_family[2];
  int idx;
  uint32_t masked_a, masked_b;

  tor_assert(addr1 && addr2);

680
681
682
683
684
685
686
687
688
  if (how == CMP_EXACT) {
    int r = ((int)addr2->family) - ((int)addr1->family);
    if (r) return r;
    switch (addr1->family) {
      case AF_UNSPEC:
        return 0; /* All unspecified addresses are equal */
      case AF_INET: {
        uint32_t a1 = ntohl(addr1->addr.in_addr.s_addr);
        uint32_t a2 = ntohl(addr2->addr.in_addr.s_addr);
689
690
        if (mbits > 32)
          mbits = 32;
691
692
        a1 >>= (32-mbits);
        a2 >>= (32-mbits);
693
694
695
        return (a1 < a2) ? -1 : (a1 == a2) ? 0 : 1;
      }
      case AF_INET6: {
696
697
        const uint8_t *a1 = addr1->addr.in6_addr.s6_addr;
        const uint8_t *a2 = addr2->addr.in6_addr.s6_addr;
698
699
700
701
702
703
704
705
706
707
708
        const int bytes = mbits >> 3;
        const int leftover_bits = mbits & 7;
        if (bytes && (r = memcmp(a1, a2, bytes))) {
          return r;
        } else if (leftover_bits) {
          uint8_t b1 = a1[bytes] >> (8-leftover_bits);
          uint8_t b2 = a2[bytes] >> (8-leftover_bits);
          return (b1 < b2) ? -1 : (b1 == b2) ? 0 : 1;
        } else {
          return 0;
        }
709
710
711
712
713
714
715
      }
      default:
        tor_fragile_assert();
        return 0;
    }
  }

716
717
718
719
720
721
722
723
724
725
  /* XXXX021 this code doesn't handle mask bits right it's using v4-mapped v6
   * addresses.  If I ask whether ::ffff:1.2.3.4 and ::ffff:1.2.7.8 are the
   * same in the first 16 bits, it will say "yes."  That's not so intuitive.
   *
   * XXXX021 Also, it's way too complicated.
   */

  v_family[0] = tor_addr_family(addr1);
  v_family[1] = tor_addr_family(addr2);

726
  /* All UNSPEC addresses are equal; they are unequal to all other addresses.*/
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
  if (v_family[0] == AF_UNSPEC) {
    if (v_family[1] == AF_UNSPEC)
      return 0;
    else
      return 1;
  } else {
    if (v_family[1] == AF_UNSPEC)
      return -1;
  }

  if (v_family[0] == AF_INET) { /* If this is native IPv4, note the address */
    /* Later we risk overwriting a v4-mapped address */
    ip4a = tor_addr_to_ipv4h(addr1);
  } else if ((v_family[0] == AF_INET6) && tor_addr_is_v4(addr1)) {
    v_family[0] = AF_INET;
    ip4a = tor_addr_to_mapped_ipv4h(addr1);
  }

  if (v_family[1] == AF_INET) { /* If this is native IPv4, note the address */
    /* Later we risk overwriting a v4-mapped address */
    ip4b = tor_addr_to_ipv4h(addr2);
  } else if ((v_family[1] == AF_INET6) && tor_addr_is_v4(addr2)) {
    v_family[1] = AF_INET;
    ip4b = tor_addr_to_mapped_ipv4h(addr2);
  }

  if (v_family[0] > v_family[1]) /* Comparison of virtual families */
    return 1;
  else if (v_family[0] < v_family[1])
    return -1;

  if (mbits == 0)  /* Under a complete wildcard mask, consider them equal */
    return 0;

  if (v_family[0] == AF_INET) { /* Real or mapped IPv4 */
    if (mbits >= 32) {
      masked_a = ip4a;
      masked_b = ip4b;
    } else if (mbits == 0) {
      return 0;
    } else {
      masked_a = ip4a >> (32-mbits);
      masked_b = ip4b >> (32-mbits);
    }
    if (masked_a < masked_b)
      return -1;
    else if (masked_a > masked_b)
      return 1;
    return 0;
  } else if (v_family[0] == AF_INET6) { /* Real IPv6 */
    const uint32_t *a1 = tor_addr_to_in6_addr32(addr1);
    const uint32_t *a2 = tor_addr_to_in6_addr32(addr2);
    for (idx = 0; idx < 4; ++idx) {
      uint32_t masked_a = ntohl(a1[idx]);
      uint32_t masked_b = ntohl(a2[idx]);
      if (!mbits) {
        return 0; /* Mask covers both addresses from here on */
      } else if (mbits < 32) {
        masked_a >>= (32-mbits);
        masked_b >>= (32-mbits);
      }

      if (masked_a > masked_b)
        return 1;
      else if (masked_a < masked_b)
        return -1;

      if (mbits < 32)
        return 0;
      mbits -= 32;
    }
    return 0;
  }

  tor_assert(0);  /* Unknown address family */
  return -1; /* unknown address family, return unequal? */

}

/** Return a hash code based on the address addr */
unsigned int
tor_addr_hash(const tor_addr_t *addr)
{
  switch (tor_addr_family(addr)) {
  case AF_INET:
    return tor_addr_to_ipv4h(addr);
  case AF_UNSPEC:
    return 0x4e4d5342;
  case AF_INET6: {
    const uint32_t *u = tor_addr_to_in6_addr32(addr);
    return u[0] + u[1] + u[2] + u[3];
    }
  default:
    tor_fragile_assert();
    return 0;
  }
}

Roger Dingledine's avatar
Roger Dingledine committed
825
/** Return a newly allocated string with a representation of <b>addr</b>. */
826
827
828
829
830
831
832
833
char *
tor_dup_addr(const tor_addr_t *addr)
{
  char buf[TOR_ADDR_BUF_LEN];
  tor_addr_to_str(buf, addr, sizeof(buf), 0);
  return tor_strdup(buf);
}

834
835
836
837
838
839
840
841
842
843
844
845
846
/** Return a string representing the address <b>addr</b>.  This string is
 * statically allocated, and must not be freed.  Each call to
 * <b>fmt_addr</b> invalidates the last result of the function.  This
 * function is not thread-safe. */
const char *
fmt_addr(const tor_addr_t *addr)
{
  static char buf[TOR_ADDR_BUF_LEN];
  if (!addr) return "<null>";
  tor_addr_to_str(buf, addr, sizeof(buf), 0);
  return buf;
}

847
848
849
/** Convert the string in <b>src</b> to a tor_addr_t <b>addr</b>.  The string
 * may be an IPv4 address, an IPv6 address, or an IPv6 address surrounded by
 * square brackets.
850
851
852
853
854
855
 *
 *  Return an address family on success, or -1 if an invalid address string is
 *  provided. */
int
tor_addr_from_str(tor_addr_t *addr, const char *src)
{
856
857
  char *tmp = NULL; /* Holds substring if we got a dotted quad. */
  int result;
858
  tor_assert(addr && src);
859
860
861
862
863
864
865
866
867
868
869
870
871
  if (src[0] == '[' && src[1])
    src = tmp = tor_strndup(src+1, strlen(src)-2);

  if (tor_inet_pton(AF_INET6, src, &addr->addr.in6_addr) > 0) {
    result = addr->family = AF_INET6;
  } else if (tor_inet_pton(AF_INET, src, &addr->addr.in_addr) > 0) {
    result = addr->family = AF_INET;
  } else {
    result = -1;
  }

  tor_free(tmp);
  return result;
872
873
}

874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
/** Parse an address or address-port combination from <b>s</b>, and put the
    result in <b>addr_out</b? and (optionally) <b>port_out</b>.  Return 0 on
    success, negative on failure.*/
int
tor_addr_port_parse(const char *s, tor_addr_t *addr_out, uint16_t *port_out)
{
  const char *port;
  tor_addr_t addr;
  uint16_t portval;
  char *tmp = NULL;

  tor_assert(s);
  tor_assert(addr_out);

  s = eat_whitespace(s);

  if (*s == '[') {
    port = strstr(s, "]");
    if (!port)
      goto err;
    tmp = tor_strndup(s+1, port-s);
    port = port+1;
    if (*port == ':')
      port++;
    else
      port = NULL;
  } else {
    port = strchr(s, ':');
    if (port)
      tmp = tor_strndup(s, port-s);
    else
      tmp = tor_strdup(s);
    if (port)
      ++port;
  }

  if (tor_addr_lookup(tmp, AF_UNSPEC, &addr) < 0)
    goto err;
  tor_free(tmp);

  if (port) {
    portval = (int) tor_parse_long(port, 10, 1, 65535, NULL, NULL);
    if (!portval)
      goto err;
  } else {
    portval = 0;
  }

922
  if (port_out)
923
924
925
926
927
928
929
930
931
    *port_out = portval;
  tor_addr_copy(addr_out, &addr);

  return 0;
 err:
  tor_free(tmp);
  return -1;
}

932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/** Set *<b>addr</b> to the IP address (if any) of whatever interface
 * connects to the internet.  This address should only be used in checking
 * whether our address has changed.  Return 0 on success, -1 on failure.
 */
int
get_interface_address6(int severity, sa_family_t family, tor_addr_t *addr)
{
  int sock=-1, r=-1;
  struct sockaddr_storage my_addr, target_addr;
  socklen_t my_addr_len;

  tor_assert(addr);

  memset(addr, 0, sizeof(tor_addr_t));
  memset(&target_addr, 0, sizeof(target_addr));
  my_addr_len = (socklen_t)sizeof(my_addr);
  /* Use the "discard" service port */
  ((struct sockaddr_in*)&target_addr)->sin_port = 9;
  /* Don't worry: no packets are sent. We just need to use a real address
   * on the actual internet. */
  if (family == AF_INET6) {
    struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)&target_addr;
    sock = tor_open_socket(PF_INET6,SOCK_DGRAM,IPPROTO_UDP);
    my_addr_len = (socklen_t)sizeof(struct sockaddr_in6);
    sin6->sin6_family = AF_INET6;
    S6_ADDR16(sin6->sin6_addr)[0] = htons(0x2002); /* 2002:: */
  } else if (family == AF_INET) {
    struct sockaddr_in *sin = (struct sockaddr_in*)&target_addr;
    sock = tor_open_socket(PF_INET,SOCK_DGRAM,IPPROTO_UDP);
    my_addr_len = (socklen_t)sizeof(struct sockaddr_in);
    sin->sin_family = AF_INET;
    sin->sin_addr.s_addr = htonl(0x12000001); /* 18.0.0.1 */
  } else {
    return -1;
  }
  if (sock < 0) {
    int e = tor_socket_errno(-1);
    log_fn(severity, LD_NET, "unable to create socket: %s",
           tor_socket_strerror(e));
    goto err;
  }

  if (connect(sock,(struct sockaddr *)&target_addr,
              (socklen_t)sizeof(target_addr))<0) {
    int e = tor_socket_errno(sock);
    log_fn(severity, LD_NET, "connect() failed: %s", tor_socket_strerror(e));
    goto err;
  }

  if (getsockname(sock,(struct sockaddr*)&my_addr, &my_addr_len)) {
    int e = tor_socket_errno(sock);
    log_fn(severity, LD_NET, "getsockname() to determine interface failed: %s",
           tor_socket_strerror(e));
    goto err;
  }

  memcpy(addr, &my_addr, sizeof(tor_addr_t));
  r=0;
 err:
  if (sock >= 0)
    tor_close_socket(sock);
  return r;
}

/* ======
 * IPv4 helpers
 * XXXX021 IPv6 deprecate some of these.
 */