dns.c 35.5 KB
Newer Older
Roger Dingledine's avatar
Roger Dingledine committed
1
/* Copyright 2003-2004 Roger Dingledine.
Roger Dingledine's avatar
Roger Dingledine committed
2
 * Copyright 2004-2006 Roger Dingledine, Nick Mathewson. */
3
4
/* See LICENSE for licensing information */
/* $Id$ */
5
6
const char dns_c_id[] =
  "$Id$";
7

Roger Dingledine's avatar
Roger Dingledine committed
8
9
/**
 * \file dns.c
10
11
12
13
 * \brief Implements a farm of 'DNS worker' threads or processes to
 * perform DNS lookups for onion routers and cache the results.
 * [This needs to be done in the background because of the lack of a
 * good, ubiquitous asynchronous DNS implementation.]
Roger Dingledine's avatar
Roger Dingledine committed
14
 **/
15

16
17
/* See
 * http://elvin.dstc.com/ListArchive/elvin-dev/archive/2001/09/msg00027.html
18
19
20
21
 * for some approaches to asynchronous dns. We will want to switch once one of
 * them becomes more commonly available.
 */

22
#include "or.h"
23
#include "../common/ht.h"
24
25
26
#ifdef USE_EVENTDNS
#include "eventdns.h"
#endif
27

Roger Dingledine's avatar
Roger Dingledine committed
28
/** Longest hostname we're willing to resolve. */
29
30
#define MAX_ADDRESSLEN 256

Roger Dingledine's avatar
Roger Dingledine committed
31
/** Maximum DNS processes to spawn. */
32
#define MAX_DNSWORKERS 100
Roger Dingledine's avatar
Roger Dingledine committed
33
/** Minimum DNS processes to spawn. */
34
#define MIN_DNSWORKERS 3
35

Roger Dingledine's avatar
Roger Dingledine committed
36
/** If more than this many processes are idle, shut down the extras. */
37
#define MAX_IDLE_DNSWORKERS 10
38

Roger Dingledine's avatar
Roger Dingledine committed
39
/** Possible outcomes from hostname lookup: permanent failure,
40
 * transient (retryable) failure, and success. */
41
42
43
44
#define DNS_RESOLVE_FAILED_TRANSIENT 1
#define DNS_RESOLVE_FAILED_PERMANENT 2
#define DNS_RESOLVE_SUCCEEDED 3

45
#ifndef USE_EVENTDNS
46
/** How many dnsworkers we have running right now. */
47
static int num_dnsworkers=0;
48
/** How many of the running dnsworkers have an assigned task right now. */
49
50
51
static int num_dnsworkers_busy=0;
/** When did we last rotate the dnsworkers? */
static time_t last_rotation_time=0;
52
#endif
53

Roger Dingledine's avatar
Roger Dingledine committed
54
/** Linked list of connections waiting for a DNS answer. */
55
56
typedef struct pending_connection_t {
  connection_t *conn;
57
  struct pending_connection_t *next;
58
} pending_connection_t;
59

Roger Dingledine's avatar
Roger Dingledine committed
60
/** A DNS request: possibly completed, possibly pending; cached_resolve
61
 * structs are stored at the OR side in a hash table, and as a linked
62
63
 * list from oldest to newest.
 */
64
typedef struct cached_resolve_t {
65
  HT_ENTRY(cached_resolve_t) node;
66
  char address[MAX_ADDRESSLEN]; /**< The hostname to be resolved. */
67
  uint32_t addr; /**< IPv4 addr for <b>address</b>. */
68
69
  char state; /**< 0 is pending; 1 means answer is valid; 2 means resolve
               * failed. */
70
71
72
#define CACHE_STATE_PENDING 0
#define CACHE_STATE_VALID 1
#define CACHE_STATE_FAILED 2
73
  uint32_t expire; /**< Remove items from cache after this time. */
74
  uint32_t ttl; /**< What TTL did the nameserver tell us? */
75
76
77
  pending_connection_t *pending_connections;
  struct cached_resolve_t *next;
} cached_resolve_t;
78

79
static void purge_expired_resolves(uint32_t now);
80
static void dns_purge_resolve(cached_resolve_t *resolve);
81
82
static void dns_found_answer(char *address, uint32_t addr, char outcome,
                             uint32_t ttl);
83
static void send_resolved_cell(connection_t *conn, uint8_t answer_type);
84
85
static int assign_to_dnsworker(connection_t *exitconn);
#ifndef USE_EVENTDNS
Nick Mathewson's avatar
Nick Mathewson committed
86
static int dnsworker_main(void *data);
87
static int spawn_dnsworker(void);
88
static int spawn_enough_dnsworkers(void);
89
#endif
90

91
92
/** Hash table of cached_resolve objects. */
static HT_HEAD(cache_map, cached_resolve_t) cache_root;
93

Roger Dingledine's avatar
Roger Dingledine committed
94
/** Function to compare hashed resolves on their addresses; used to
95
 * implement hash tables. */
96
97
static INLINE int
cached_resolves_eq(cached_resolve_t *a, cached_resolve_t *b)
98
{
99
  /* make this smarter one day? */
100
101
102
103
104
105
106
  return !strncmp(a->address, b->address, MAX_ADDRESSLEN);
}

static INLINE unsigned int
cached_resolve_hash(cached_resolve_t *a)
{
  return ht_string_hash(a->address);
107
108
}

109
HT_PROTOTYPE(cache_map, cached_resolve_t, node, cached_resolve_hash,
110
             cached_resolves_eq);
111
HT_GENERATE(cache_map, cached_resolve_t, node, cached_resolve_hash,
112
            cached_resolves_eq, 0.6, malloc, realloc, free);
113

114
/** Initialize the DNS cache. */
115
static void
116
init_cache_map(void)
117
{
118
  HT_INIT(&cache_root);
119
120
}

Roger Dingledine's avatar
Roger Dingledine committed
121
/** Initialize the DNS subsystem; called by the OR process. */
122
123
124
void
dns_init(void)
{
125
  init_cache_map();
126
  dnsworkers_rotate();
127
128
129
130
#ifdef USE_EVENTDNS
  eventdns_resolv_conf_parse(DNS_OPTION_NAMESERVERS|DNS_OPTION_MISC,
                             "/etc/resolv.conf");
#endif
131
}
132

133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
uint32_t
dns_clip_ttl(uint32_t ttl)
{
  if (ttl < MIN_DNS_TTL)
    return MIN_DNS_TTL;
  else if (ttl > MAX_DNS_TTL)
    return MAX_DNS_TTL;
  else
    return ttl;
}

static uint32_t
dns_get_expiry_ttl(uint32_t ttl)
{
  if (ttl < MIN_DNS_TTL)
    return MIN_DNS_TTL;
  else if (ttl > MAX_DNS_ENTRY_AGE)
    return MAX_DNS_ENTRY_AGE;
  else
    return ttl;
}

155
/** Helper: free storage held by an entry in the DNS cache. */
156
static void
157
_free_cached_resolve(cached_resolve_t *r)
158
{
Nick Mathewson's avatar
Nick Mathewson committed
159
  while (r->pending_connections) {
160
    pending_connection_t *victim = r->pending_connections;
161
162
163
164
165
166
    r->pending_connections = victim->next;
    tor_free(victim);
  }
  tor_free(r);
}

167
/** Free all storage held in the DNS cache */
168
169
170
void
dns_free_all(void)
{
171
  cached_resolve_t **ptr, **next, *item;
172
  for (ptr = HT_START(cache_map, &cache_root); ptr != NULL; ptr = next) {
173
    item = *ptr;
174
    next = HT_NEXT_RMV(cache_map, &cache_root, ptr);
175
    _free_cached_resolve(item);
176
  }
177
  HT_CLEAR(cache_map, &cache_root);
178
179
}

180
/** Linked list of resolved addresses, oldest to newest. */
181
182
static cached_resolve_t *oldest_cached_resolve = NULL;
static cached_resolve_t *newest_cached_resolve = NULL;
183

Nick Mathewson's avatar
Nick Mathewson committed
184
/** Remove every cached_resolve whose <b>expire</b> time is before <b>now</b>
185
 * from the cache. */
186
187
188
static void
purge_expired_resolves(uint32_t now)
{
189
190
  cached_resolve_t *resolve;
  pending_connection_t *pend;
191
  connection_t *pendconn;
192
193
194
195

  /* this is fast because the linked list
   * oldest_cached_resolve is ordered by when they came in.
   */
196
  while (oldest_cached_resolve && (oldest_cached_resolve->expire < now)) {
197
    resolve = oldest_cached_resolve;
198
199
    log_debug(LD_EXIT,
              "Forgetting old cached resolve (address %s, expires %lu)",
200
201
              escaped_safe_str(resolve->address),
              (unsigned long)resolve->expire);
202
    if (resolve->state == CACHE_STATE_PENDING) {
203
      log_debug(LD_EXIT,
204
205
                "Bug: Expiring a dns resolve %s that's still pending."
                " Forgot to cull it?", escaped_safe_str(resolve->address));
206
      tor_fragile_assert();
207
208
    }
    if (resolve->pending_connections) {
209
210
      log_debug(LD_EXIT,
                "Closing pending connections on expiring DNS resolve!");
211
      tor_fragile_assert();
212
213
214
215
216
217
      while (resolve->pending_connections) {
        pend = resolve->pending_connections;
        resolve->pending_connections = pend->next;
        /* Connections should only be pending if they have no socket. */
        tor_assert(pend->conn->s == -1);
        pendconn = pend->conn;
218
        connection_edge_end(pendconn, END_STREAM_REASON_TIMEOUT,
219
                            pendconn->cpath_layer);
220
        circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
221
222
223
        connection_free(pendconn);
        tor_free(pend);
      }
224
    }
225
    oldest_cached_resolve = resolve->next;
226
    if (!oldest_cached_resolve) /* if there are no more, */
227
228
      newest_cached_resolve = NULL; /* then make sure the list's tail knows
                                     * that too */
229
    HT_REMOVE(cache_map, &cache_root, resolve);
230
    tor_free(resolve);
231
232
233
  }
}

234
235
236
/** Send a response to the RESOVLE request of a connection. answer_type must
 *  be one of RESOLVED_TYPE_(IPV4|ERROR|ERROR_TRANSIENT) */
static void
237
send_resolved_cell(connection_t *conn, uint8_t answer_type)
238
239
{
  char buf[RELAY_PAYLOAD_SIZE];
240
  size_t buflen;
241
  uint32_t ttl;
242
243

  buf[0] = answer_type;
244
  ttl = dns_clip_ttl(conn->address_ttl);
245
246
247
248
249
250

  switch (answer_type)
    {
    case RESOLVED_TYPE_IPV4:
      buf[1] = 4;
      set_uint32(buf+2, htonl(conn->addr));
251
      set_uint32(buf+6, htonl(ttl));
252
      buflen = 10;
253
254
255
      break;
    case RESOLVED_TYPE_ERROR_TRANSIENT:
    case RESOLVED_TYPE_ERROR:
256
257
258
      {
        const char *errmsg = "Error resolving hostname";
        int msglen = strlen(errmsg);
259

260
261
        buf[1] = msglen;
        strlcpy(buf+2, errmsg, sizeof(buf)-2);
262
        set_uint32(buf+2+msglen, htonl(ttl));
263
264
265
        buflen = 6+msglen;
        break;
      }
266
267
268
    default:
      tor_assert(0);
    }
269
  connection_edge_send_command(conn, circuit_get_by_edge_conn(conn),
270
271
272
273
                               RELAY_COMMAND_RESOLVED, buf, buflen,
                               conn->cpath_layer);
}

274
275
/** Link <b>r</b> into the hash table of address-to-result mappings, and add it
 * to the linked list of resolves-by-age. */
276
static void
277
insert_resolve(cached_resolve_t *r)
278
279
280
281
282
283
284
285
286
{
  /* add us to the linked list of resolves */
  if (!oldest_cached_resolve) {
    oldest_cached_resolve = r;
  } else {
    newest_cached_resolve->next = r;
  }
  newest_cached_resolve = r;

287
  HT_INSERT(cache_map, &cache_root, r);
288
289
}

Nick Mathewson's avatar
Nick Mathewson committed
290
291
/** See if we have a cache entry for <b>exitconn</b>-\>address. if so,
 * if resolve valid, put it into <b>exitconn</b>-\>addr and return 1.
292
 * If resolve failed, unlink exitconn if needed, free it, and return -1.
293
294
295
296
297
298
299
 *
 * Else, if seen before and pending, add conn to the pending list,
 * and return 0.
 *
 * Else, if not seen before, add conn to pending list, hand to
 * dns farm, and return 0.
 */
300
301
302
int
dns_resolve(connection_t *exitconn)
{
303
304
305
  cached_resolve_t *resolve;
  cached_resolve_t search;
  pending_connection_t *pending_connection;
306
  struct in_addr in;
307
  circuit_t *circ;
308
  uint32_t now = time(NULL);
309
  assert_connection_ok(exitconn, 0);
310
  tor_assert(exitconn->s == -1);
311

312
313
314
315
  /* first check if exitconn->address is an IP. If so, we already
   * know the answer. */
  if (tor_inet_aton(exitconn->address, &in) != 0) {
    exitconn->addr = ntohl(in.s_addr);
316
    exitconn->address_ttl = DEFAULT_DNS_TTL;
317
    if (exitconn->purpose == EXIT_PURPOSE_RESOLVE)
318
      send_resolved_cell(exitconn, RESOLVED_TYPE_IPV4);
319
    return 1;
320
321
322
  }

  /* then take this opportunity to see if there are any expired
323
   * resolves in the hash table. */
324
  purge_expired_resolves(now);
325

326
327
328
  /* lower-case exitconn->address, so it's in canonical form */
  tor_strlower(exitconn->address);

329
  /* now check the hash table to see if 'address' is already there. */
Nick Mathewson's avatar
Nick Mathewson committed
330
  strlcpy(search.address, exitconn->address, sizeof(search.address));
331
  resolve = HT_FIND(cache_map, &cache_root, &search);
332
  if (resolve && resolve->expire > now) { /* already there */
333
    switch (resolve->state) {
334
335
      case CACHE_STATE_PENDING:
        /* add us to the pending list */
336
        pending_connection = tor_malloc_zero(
337
                                      sizeof(pending_connection_t));
338
        pending_connection->conn = exitconn;
Roger Dingledine's avatar
   
Roger Dingledine committed
339
340
        pending_connection->next = resolve->pending_connections;
        resolve->pending_connections = pending_connection;
341
        log_debug(LD_EXIT,"Connection (fd %d) waiting for pending DNS "
342
343
                  "resolve of %s",
                  exitconn->s, escaped_safe_str(exitconn->address));
344
        exitconn->state = EXIT_CONN_STATE_RESOLVING;
Roger Dingledine's avatar
   
Roger Dingledine committed
345
        return 0;
346
      case CACHE_STATE_VALID:
347
        exitconn->addr = resolve->addr;
348
        exitconn->address_ttl = resolve->ttl;
349
350
        log_debug(LD_EXIT,"Connection (fd %d) found cached answer for %s",
                  exitconn->s, escaped_safe_str(exitconn->address));
351
        if (exitconn->purpose == EXIT_PURPOSE_RESOLVE)
352
          send_resolved_cell(exitconn, RESOLVED_TYPE_IPV4);
353
        return 1;
354
      case CACHE_STATE_FAILED:
355
356
        log_debug(LD_EXIT,"Connection (fd %d) found cached error for %s",
                  exitconn->s, escaped_safe_str(exitconn->address));
357
        if (exitconn->purpose == EXIT_PURPOSE_RESOLVE)
358
          send_resolved_cell(exitconn, RESOLVED_TYPE_ERROR);
359
        circ = circuit_get_by_edge_conn(exitconn);
360
361
        if (circ)
          circuit_detach_stream(circ, exitconn);
362
363
        if (!exitconn->marked_for_close)
          connection_free(exitconn);
364
365
        return -1;
    }
Roger Dingledine's avatar
Roger Dingledine committed
366
    tor_assert(0);
Roger Dingledine's avatar
Roger Dingledine committed
367
368
  }
  /* not there, need to add it */
369
  resolve = tor_malloc_zero(sizeof(cached_resolve_t));
Roger Dingledine's avatar
Roger Dingledine committed
370
  resolve->state = CACHE_STATE_PENDING;
371
  resolve->expire = now + DEFAULT_DNS_TTL; /* this will get replaced. */
Nick Mathewson's avatar
Nick Mathewson committed
372
  strlcpy(resolve->address, exitconn->address, sizeof(resolve->address));
Roger Dingledine's avatar
Roger Dingledine committed
373
374

  /* add us to the pending list */
375
  pending_connection = tor_malloc_zero(sizeof(pending_connection_t));
Roger Dingledine's avatar
Roger Dingledine committed
376
377
  pending_connection->conn = exitconn;
  resolve->pending_connections = pending_connection;
378
  exitconn->state = EXIT_CONN_STATE_RESOLVING;
Roger Dingledine's avatar
Roger Dingledine committed
379

380
  insert_resolve(resolve);
381
382
  log_debug(LD_EXIT,"Assigning question %s to dnsworker.",
            escaped_safe_str(exitconn->address));
Roger Dingledine's avatar
Roger Dingledine committed
383
  return assign_to_dnsworker(exitconn);
384
385
}

386
/** Log an error and abort if conn is waiting for a DNS resolve.
387
 */
388
389
void
assert_connection_edge_not_dns_pending(connection_t *conn)
390
{
391
392
  pending_connection_t *pend;
  cached_resolve_t **resolve;
393

394
395
396
397
398
399
  HT_FOREACH(resolve, cache_map, &cache_root) {
    for (pend = (*resolve)->pending_connections;
         pend;
         pend = pend->next) {
      tor_assert(pend->conn != conn);
    }
400
  }
401
}
402

403
404
405
406
407
408
409
/** Log an error and abort if any connection waiting for a DNS resolve is
 * corrupted. */
void
assert_all_pending_dns_resolves_ok(void)
{
  pending_connection_t *pend;
  cached_resolve_t **resolve;
410

411
412
413
414
415
416
417
418
  HT_FOREACH(resolve, cache_map, &cache_root) {
    for (pend = (*resolve)->pending_connections;
         pend;
         pend = pend->next) {
      assert_connection_ok(pend->conn, 0);
      tor_assert(pend->conn->s == -1);
      tor_assert(!connection_in_array(pend->conn));
    }
419
420
421
  }
}

Nick Mathewson's avatar
Nick Mathewson committed
422
/** Remove <b>conn</b> from the list of connections waiting for conn-\>address.
423
 */
424
425
void
connection_dns_remove(connection_t *conn)
426
{
427
428
429
  pending_connection_t *pend, *victim;
  cached_resolve_t search;
  cached_resolve_t *resolve;
430

431
432
433
  tor_assert(conn->type == CONN_TYPE_EXIT);
  tor_assert(conn->state == EXIT_CONN_STATE_RESOLVING);

Nick Mathewson's avatar
Nick Mathewson committed
434
  strlcpy(search.address, conn->address, sizeof(search.address));
435

436
  resolve = HT_FIND(cache_map, &cache_root, &search);
437
  if (!resolve) {
438
439
    log_notice(LD_BUG, "Address %s is not pending. Dropping.",
               escaped_safe_str(conn->address));
440
441
442
    return;
  }

Roger Dingledine's avatar
Roger Dingledine committed
443
  tor_assert(resolve->pending_connections);
444
445
446
447
  assert_connection_ok(conn,0);

  pend = resolve->pending_connections;

448
  if (pend->conn == conn) {
449
    resolve->pending_connections = pend->next;
450
    tor_free(pend);
451
    log_debug(LD_EXIT, "First connection (fd %d) no longer waiting "
452
453
              "for resolve of %s",
              conn->s, escaped_safe_str(conn->address));
454
455
    return;
  } else {
456
457
    for ( ; pend->next; pend = pend->next) {
      if (pend->next->conn == conn) {
458
459
        victim = pend->next;
        pend->next = victim->next;
460
        tor_free(victim);
461
        log_debug(LD_EXIT,
462
463
                  "Connection (fd %d) no longer waiting for resolve of %s",
                  conn->s, escaped_safe_str(conn->address));
464
465
466
        return; /* more are pending */
      }
    }
Roger Dingledine's avatar
Roger Dingledine committed
467
    tor_assert(0); /* not reachable unless onlyconn not in pending list */
468
469
470
  }
}

Nick Mathewson's avatar
Nick Mathewson committed
471
472
473
/** Mark all connections waiting for <b>address</b> for close.  Then cancel
 * the resolve for <b>address</b> itself, and remove any cached results for
 * <b>address</b> from the cache.
474
 */
475
476
477
void
dns_cancel_pending_resolve(char *address)
{
478
479
480
  pending_connection_t *pend;
  cached_resolve_t search;
  cached_resolve_t *resolve;
481
  connection_t *pendconn;
482
  circuit_t *circ;
483

Nick Mathewson's avatar
Nick Mathewson committed
484
  strlcpy(search.address, address, sizeof(search.address));
485

486
  resolve = HT_FIND(cache_map, &cache_root, &search);
487
  if (!resolve) {
488
489
    log_notice(LD_BUG,"Address %s is not pending. Dropping.",
               escaped_safe_str(address));
490
491
492
    return;
  }

493
494
  if (!resolve->pending_connections) {
    /* XXX this should never trigger, but sometimes it does */
495
    log_warn(LD_BUG,
496
497
             "Bug: Address %s is pending but has no pending connections!",
             escaped_safe_str(address));
498
    tor_fragile_assert();
499
500
    return;
  }
Roger Dingledine's avatar
Roger Dingledine committed
501
  tor_assert(resolve->pending_connections);
502

503
  /* mark all pending connections to fail */
504
  log_debug(LD_EXIT,
505
506
             "Failing all connections waiting on DNS resolve of %s",
             escaped_safe_str(address));
507
  while (resolve->pending_connections) {
508
    pend = resolve->pending_connections;
509
    pend->conn->state = EXIT_CONN_STATE_RESOLVEFAILED;
510
    pendconn = pend->conn;
511
    tor_assert(pendconn->s == -1);
512
    if (!pendconn->marked_for_close) {
513
514
      connection_edge_end(pendconn, END_STREAM_REASON_RESOURCELIMIT,
                          pendconn->cpath_layer);
515
    }
516
    circ = circuit_get_by_edge_conn(pendconn);
517
518
    if (circ)
      circuit_detach_stream(circ, pendconn);
519
    connection_free(pendconn);
520
521
    resolve->pending_connections = pend->next;
    tor_free(pend);
522
523
  }

524
525
526
  dns_purge_resolve(resolve);
}

Nick Mathewson's avatar
Nick Mathewson committed
527
/** Remove <b>resolve</b> from the cache.
528
 */
529
static void
530
dns_purge_resolve(cached_resolve_t *resolve)
531
{
532
  cached_resolve_t *tmp;
533

534
  /* remove resolve from the linked list */
535
  if (resolve == oldest_cached_resolve) {
536
    oldest_cached_resolve = resolve->next;
537
    if (oldest_cached_resolve == NULL)
538
      newest_cached_resolve = NULL;
539
  } else {
540
    /* FFFF make it a doubly linked list if this becomes too slow */
541
542
543
544
    for (tmp=oldest_cached_resolve; tmp && tmp->next != resolve; tmp=tmp->next)
      ;
    tor_assert(tmp); /* it's got to be in the list, or we screwed up somewhere
                      * else */
545
546
    tmp->next = resolve->next; /* unlink it */

547
    if (newest_cached_resolve == resolve)
548
      newest_cached_resolve = tmp;
549
  }
550

551
  /* remove resolve from the map */
552
  HT_REMOVE(cache_map, &cache_root, resolve);
553

554
  tor_free(resolve);
555
556
}

Roger Dingledine's avatar
Roger Dingledine committed
557
/** Called on the OR side when a DNS worker tells us the outcome of a DNS
558
 * resolve: tell all pending connections about the result of the lookup, and
Nick Mathewson's avatar
Nick Mathewson committed
559
560
561
562
 * cache the value.  (<b>address</b> is a NUL-terminated string containing the
 * address to look up; <b>addr</b> is an IPv4 address in host order;
 * <b>outcome</b> is one of
 * DNS_RESOLVE_{FAILED_TRANSIENT|FAILED_PERMANENT|SUCCEEDED}.
563
 */
564
static void
565
dns_found_answer(char *address, uint32_t addr, char outcome, uint32_t ttl)
566
{
567
568
569
  pending_connection_t *pend;
  cached_resolve_t search;
  cached_resolve_t *resolve;
570
  connection_t *pendconn;
571
  circuit_t *circ;
572

Nick Mathewson's avatar
Nick Mathewson committed
573
  strlcpy(search.address, address, sizeof(search.address));
574

575
  resolve = HT_FIND(cache_map, &cache_root, &search);
576
  if (!resolve) {
577
578
    log_info(LD_EXIT,"Resolved unasked address %s; caching anyway.",
             escaped_safe_str(address));
579
    resolve = tor_malloc_zero(sizeof(cached_resolve_t));
580
581
582
    resolve->state = (outcome == DNS_RESOLVE_SUCCEEDED) ?
      CACHE_STATE_VALID : CACHE_STATE_FAILED;
    resolve->addr = addr;
583
584
    resolve->expire = time(NULL) + dns_get_expiry_ttl(ttl);
    resolve->ttl = ttl;
585
    insert_resolve(resolve);
586
    return;
587
588
  }

589
  if (resolve->state != CACHE_STATE_PENDING) {
590
591
    /* XXXX Maybe update addr? or check addr for consistency? Or let
     * VALID replace FAILED? */
592
593
    log_notice(LD_EXIT, "Resolved %s which was already resolved; ignoring",
               escaped_safe_str(address));
Roger Dingledine's avatar
Roger Dingledine committed
594
    tor_assert(resolve->pending_connections == NULL);
595
596
597
598
599
600
    return;
  }
  /* Removed this assertion: in fact, we'll sometimes get a double answer
   * to the same question.  This can happen when we ask one worker to resolve
   * X.Y.Z., then we cancel the request, and then we ask another worker to
   * resolve X.Y.Z. */
Roger Dingledine's avatar
Roger Dingledine committed
601
  /* tor_assert(resolve->state == CACHE_STATE_PENDING); */
602

603
  resolve->addr = addr;
604
605
  resolve->expire = time(NULL) + dns_get_expiry_ttl(ttl);
  resolve->ttl = ttl;
606
  if (outcome == DNS_RESOLVE_SUCCEEDED)
607
608
609
610
    resolve->state = CACHE_STATE_VALID;
  else
    resolve->state = CACHE_STATE_FAILED;

611
  while (resolve->pending_connections) {
612
    pend = resolve->pending_connections;
613
    assert_connection_ok(pend->conn,time(NULL));
614
    pend->conn->addr = resolve->addr;
615
    pend->conn->address_ttl = resolve->ttl;
616
617
    pendconn = pend->conn; /* don't pass complex things to the
                              connection_mark_for_close macro */
618

619
    if (resolve->state == CACHE_STATE_FAILED) {
620
      /* prevent double-remove. */
621
      pendconn->state = EXIT_CONN_STATE_RESOLVEFAILED;
622
      if (pendconn->purpose == EXIT_PURPOSE_CONNECT) {
623
624
        connection_edge_end(pendconn, END_STREAM_REASON_RESOLVEFAILED,
                            pendconn->cpath_layer);
625
        /* This detach must happen after we send the end cell. */
626
        circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
627
      } else {
628
        send_resolved_cell(pendconn, RESOLVED_TYPE_ERROR);
629
        /* This detach must happen after we send the resolved cell. */
630
        circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
631
      }
632
      connection_free(pendconn);
Roger Dingledine's avatar
Roger Dingledine committed
633
    } else {
634
635
636
637
      if (pendconn->purpose == EXIT_PURPOSE_CONNECT) {
        /* prevent double-remove. */
        pend->conn->state = EXIT_CONN_STATE_CONNECTING;

638
        circ = circuit_get_by_edge_conn(pend->conn);
639
640
641
642
643
        tor_assert(circ);
        /* unlink pend->conn from resolving_streams, */
        circuit_detach_stream(circ, pend->conn);
        /* and link it to n_streams */
        pend->conn->next_stream = circ->n_streams;
644
        pend->conn->on_circuit = circ;
645
646
647
648
649
650
651
        circ->n_streams = pend->conn;

        connection_exit_connect(pend->conn);
      } else {
        /* prevent double-remove.  This isn't really an accurate state,
         * but it does the right thing. */
        pendconn->state = EXIT_CONN_STATE_RESOLVEFAILED;
652
        send_resolved_cell(pendconn, RESOLVED_TYPE_IPV4);
653
        circ = circuit_get_by_edge_conn(pendconn);
654
655
656
657
        tor_assert(circ);
        circuit_detach_stream(circ, pendconn);
        connection_free(pendconn);
      }
Roger Dingledine's avatar
Roger Dingledine committed
658
    }
659
660
    resolve->pending_connections = pend->next;
    tor_free(pend);
661
  }
662

663
  if (outcome == DNS_RESOLVE_FAILED_TRANSIENT) { /* remove from cache */
664
665
    dns_purge_resolve(resolve);
  }
666
667
}

668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
#ifndef USE_EVENTDNS
/** Find or spawn a dns worker process to handle resolving
 * <b>exitconn</b>-\>address; tell that dns worker to begin resolving.
 */
static int
assign_to_dnsworker(connection_t *exitconn)
{
  connection_t *dnsconn;
  unsigned char len;

  tor_assert(exitconn->state == EXIT_CONN_STATE_RESOLVING);
  tor_assert(exitconn->s == -1);

  /* respawn here, to be sure there are enough */
  if (spawn_enough_dnsworkers() < 0) {
    goto err;
  }

  dnsconn = connection_get_by_type_state(CONN_TYPE_DNSWORKER,
                                         DNSWORKER_STATE_IDLE);

  if (!dnsconn) {
    log_warn(LD_EXIT,"no idle dns workers. Failing.");
    if (exitconn->purpose == EXIT_PURPOSE_RESOLVE)
692
      send_resolved_cell(exitconn, RESOLVED_TYPE_ERROR_TRANSIENT);
693
694
695
696
697
698
699
700
701
702
703
    goto err;
  }

  log_debug(LD_EXIT,
            "Connection (fd %d) needs to resolve %s; assigning "
            "to DNSWorker (fd %d)", exitconn->s,
            escaped_safe_str(exitconn->address), dnsconn->s);

  tor_free(dnsconn->address);
  dnsconn->address = tor_strdup(exitconn->address);
  dnsconn->state = DNSWORKER_STATE_BUSY;
704
705
706
707
  /* touch the lastwritten timestamp, since that's how we check to
   * see how long it's been since we asked the question, and sometimes
   * we check before the first call to connection_handle_write(). */
  dnsconn->timestamp_lastwritten = time(NULL);
708
709
710
711
712
713
714
715
716
717
718
719
  num_dnsworkers_busy++;

  len = strlen(dnsconn->address);
  connection_write_to_buf((char*)&len, 1, dnsconn);
  connection_write_to_buf(dnsconn->address, len, dnsconn);

  return 0;
err:
  dns_cancel_pending_resolve(exitconn->address); /* also sends end and frees */
  return -1;
}

720
721
/******************************************************************/

Nick Mathewson's avatar
Nick Mathewson committed
722
/*
723
 * Connection between OR and dnsworker
Nick Mathewson's avatar
Nick Mathewson committed
724
 */
725

Roger Dingledine's avatar
Roger Dingledine committed
726
/** Write handler: called when we've pushed a request to a dnsworker. */
727
728
729
int
connection_dns_finished_flushing(connection_t *conn)
{
730
731
  tor_assert(conn);
  tor_assert(conn->type == CONN_TYPE_DNSWORKER);
732
733
734
735
  connection_stop_writing(conn);
  return 0;
}

736
737
738
int
connection_dns_reached_eof(connection_t *conn)
{
739
  log_warn(LD_EXIT,"Read eof. Worker died unexpectedly.");
740
  if (conn->state == DNSWORKER_STATE_BUSY) {
741
742
743
744
    /* don't cancel the resolve here -- it would be cancelled in
     * connection_about_to_close_connection(), since conn is still
     * in state BUSY
     */
745
746
747
748
749
750
751
752
    num_dnsworkers_busy--;
  }
  num_dnsworkers--;
  connection_mark_for_close(conn);
  return 0;
}

/** Read handler: called when we get data from a dnsworker. See
753
754
 * if we have a complete answer.  If so, call dns_found_answer on the
 * result.  If not, wait.  Returns 0. */
755
756
757
int
connection_dns_process_inbuf(connection_t *conn)
{
758
  char success;
759
  uint32_t addr;
760
  int ttl;
761

762
763
  tor_assert(conn);
  tor_assert(conn->type == CONN_TYPE_DNSWORKER);
764

765
  if (conn->state != DNSWORKER_STATE_BUSY && buf_datalen(conn->inbuf)) {
766
767
    log_warn(LD_BUG,
             "Bug: read data (%d bytes) from an idle dns worker (fd %d, "
768
769
             "address %s). Please report.", (int)buf_datalen(conn->inbuf),
             conn->s, escaped_safe_str(conn->address));
770
    tor_fragile_assert();
771
772
773
774
775
776
777

    /* Pull it off the buffer anyway, or it will just stay there.
     * Keep pulling things off because sometimes we get several
     * answers at once (!). */
    while (buf_datalen(conn->inbuf)) {
      connection_fetch_from_buf(&success,1,conn);
      connection_fetch_from_buf((char *)&addr,sizeof(uint32_t),conn);
778
      log_warn(LD_EXIT,"Discarding idle dns answer (success %d, addr %d.)",
779
               success, addr);
780
    }
781
782
    return 0;
  }
783
  if (buf_datalen(conn->inbuf) < 5) /* entire answer available? */
784
    return 0; /* not yet */
785
  tor_assert(conn->state == DNSWORKER_STATE_BUSY);
Roger Dingledine's avatar
Roger Dingledine committed
786
  tor_assert(buf_datalen(conn->inbuf) == 5);
787

788
789
  connection_fetch_from_buf(&success,1,conn);
  connection_fetch_from_buf((char *)&addr,sizeof(uint32_t),conn);
790

791
792
  log_debug(LD_EXIT, "DNSWorker (fd %d) returned answer for %s",
            conn->s, escaped_safe_str(conn->address));
793

Roger Dingledine's avatar
Roger Dingledine committed
794
795
  tor_assert(success >= DNS_RESOLVE_FAILED_TRANSIENT);
  tor_assert(success <= DNS_RESOLVE_SUCCEEDED);
796
797
798

  ttl = (success == DNS_RESOLVE_FAILED_TRANSIENT) ? 0 : MAX_DNS_ENTRY_AGE;
  dns_found_answer(conn->address, ntohl(addr), success, ttl);
799

800
  tor_free(conn->address);
801
  conn->address = tor_strdup("<idle>");
802
  conn->state = DNSWORKER_STATE_IDLE;
Roger Dingledine's avatar
Roger Dingledine committed
803
  num_dnsworkers_busy--;
804
805
806
807
808
  if (conn->timestamp_created < last_rotation_time) {
    connection_mark_for_close(conn);
    num_dnsworkers--;
    spawn_enough_dnsworkers();
  }
809
810
811
  return 0;
}

812
813
814
/** Close and re-open all idle dnsworkers; schedule busy ones to be closed
 * and re-opened once they're no longer busy.
 **/
815
816
void
dnsworkers_rotate(void)
817
818
819
820
821
822
823
824
{
  connection_t *dnsconn;
  while ((dnsconn = connection_get_by_type_state(CONN_TYPE_DNSWORKER,
                                                 DNSWORKER_STATE_IDLE))) {
    connection_mark_for_close(dnsconn);
    num_dnsworkers--;
  }
  last_rotation_time = time(NULL);
825
826
  if (server_mode(get_options()))
    spawn_enough_dnsworkers();
827
828
}

Roger Dingledine's avatar
Roger Dingledine committed
829
/** Implementation for DNS workers; this code runs in a separate
830
831
832
 * execution context.  It takes as its argument an fdarray as returned
 * by socketpair(), and communicates via fdarray[1].  The protocol is
 * as follows:
Nick Mathewson's avatar
Nick Mathewson committed
833
834
835
836
837
838
 *    - The OR says:
 *         - ADDRESSLEN [1 byte]
 *         - ADDRESS    [ADDRESSLEN bytes]
 *    - The DNS worker does the lookup, and replies:
 *         - OUTCOME    [1 byte]
 *         - IP         [4 bytes]
839
840
841
842
843
844
845
 *
 * OUTCOME is one of DNS_RESOLVE_{FAILED_TRANSIENT|FAILED_PERMANENT|SUCCEEDED}.
 * IP is in host order.
 *
 * The dnsworker runs indefinitely, until its connection is closed or an error
 * occurs.
 */
846
847
848
static int
dnsworker_main(void *data)
{
849
850
  char address[MAX_ADDRESSLEN];
  unsigned char address_len;
851
  char *log_address;
852
  char answer[5];
Roger Dingledine's avatar
Roger Dingledine committed
853
  uint32_t ip;
854
  int *fdarray = data;
Roger Dingledine's avatar
Roger Dingledine committed
855
  int fd;
856
  int result;
857

858
859
  /* log_fn(LOG_NOTICE,"After spawn: fdarray @%d has %d:%d", (int)fdarray,
   * fdarray[0],fdarray[1]); */
860

861
  fd = fdarray[1]; /* this side is ours */
862
#ifndef TOR_IS_MULTITHREADED
863
864