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

Roger Dingledine's avatar
Roger Dingledine committed
7
8
/**
 * \file dns.c
9
10
11
12
 * \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
13
 **/
14

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

20
#include "or.h"
21
#include "../common/ht.h"
22

Roger Dingledine's avatar
Roger Dingledine committed
23
/** Longest hostname we're willing to resolve. */
24
25
#define MAX_ADDRESSLEN 256

Roger Dingledine's avatar
Roger Dingledine committed
26
/** Maximum DNS processes to spawn. */
27
#define MAX_DNSWORKERS 100
Roger Dingledine's avatar
Roger Dingledine committed
28
/** Minimum DNS processes to spawn. */
29
#define MIN_DNSWORKERS 3
30

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

Roger Dingledine's avatar
Roger Dingledine committed
34
/** Possible outcomes from hostname lookup: permanent failure,
35
 * transient (retryable) failure, and success. */
36
37
38
39
#define DNS_RESOLVE_FAILED_TRANSIENT 1
#define DNS_RESOLVE_FAILED_PERMANENT 2
#define DNS_RESOLVE_SUCCEEDED 3

40
/** How many dnsworkers we have running right now. */
41
static int num_dnsworkers=0;
42
/** How many of the running dnsworkers have an assigned task right now. */
43
44
45
static int num_dnsworkers_busy=0;
/** When did we last rotate the dnsworkers? */
static time_t last_rotation_time=0;
46

Roger Dingledine's avatar
Roger Dingledine committed
47
/** Linked list of connections waiting for a DNS answer. */
48
49
typedef struct pending_connection_t {
  connection_t *conn;
50
  struct pending_connection_t *next;
51
} pending_connection_t;
52

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

70
71
static void purge_expired_resolves(uint32_t now);
static int assign_to_dnsworker(connection_t *exitconn);
72
static void dns_purge_resolve(cached_resolve_t *resolve);
73
static void dns_found_answer(char *address, uint32_t addr, char outcome);
Nick Mathewson's avatar
Nick Mathewson committed
74
static int dnsworker_main(void *data);
75
static int spawn_dnsworker(void);
76
static int spawn_enough_dnsworkers(void);
77
static void send_resolved_cell(connection_t *conn, uint8_t answer_type);
78

79
80
/** Hash table of cached_resolve objects. */
static HT_HEAD(cache_map, cached_resolve_t) cache_root;
81

Roger Dingledine's avatar
Roger Dingledine committed
82
/** Function to compare hashed resolves on their addresses; used to
83
 * implement hash tables. */
84
85
static INLINE int
cached_resolves_eq(cached_resolve_t *a, cached_resolve_t *b)
86
{
87
  /* make this smarter one day? */
88
89
90
91
92
93
94
  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);
95
96
}

97
HT_PROTOTYPE(cache_map, cached_resolve_t, node, cached_resolve_hash,
98
             cached_resolves_eq);
99
HT_GENERATE(cache_map, cached_resolve_t, node, cached_resolve_hash,
100
            cached_resolves_eq, 0.6, malloc, realloc, free);
101

102
/** Initialize the DNS cache. */
103
static void
104
init_cache_map(void)
105
{
106
  HT_INIT(&cache_root);
107
108
}

Roger Dingledine's avatar
Roger Dingledine committed
109
/** Initialize the DNS subsystem; called by the OR process. */
110
111
112
void
dns_init(void)
{
113
  init_cache_map();
114
  dnsworkers_rotate();
115
}
116

117
/** Helper: free storage held by an entry in the DNS cache. */
118
static void
119
_free_cached_resolve(cached_resolve_t *r)
120
{
Nick Mathewson's avatar
Nick Mathewson committed
121
  while (r->pending_connections) {
122
    pending_connection_t *victim = r->pending_connections;
123
124
125
126
127
128
    r->pending_connections = victim->next;
    tor_free(victim);
  }
  tor_free(r);
}

129
/** Free all storage held in the DNS cache */
130
131
132
void
dns_free_all(void)
{
133
  cached_resolve_t **ptr, **next, *item;
134
  for (ptr = HT_START(cache_map, &cache_root); ptr != NULL; ptr = next) {
135
    item = *ptr;
136
    next = HT_NEXT_RMV(cache_map, &cache_root, ptr);
137
    _free_cached_resolve(item);
138
  }
139
  HT_CLEAR(cache_map, &cache_root);
140
141
}

142
/** Linked list of resolved addresses, oldest to newest. */
143
144
static cached_resolve_t *oldest_cached_resolve = NULL;
static cached_resolve_t *newest_cached_resolve = NULL;
145

Nick Mathewson's avatar
Nick Mathewson committed
146
/** Remove every cached_resolve whose <b>expire</b> time is before <b>now</b>
147
 * from the cache. */
148
149
150
static void
purge_expired_resolves(uint32_t now)
{
151
152
  cached_resolve_t *resolve;
  pending_connection_t *pend;
153
  connection_t *pendconn;
154
155
156
157

  /* this is fast because the linked list
   * oldest_cached_resolve is ordered by when they came in.
   */
158
  while (oldest_cached_resolve && (oldest_cached_resolve->expire < now)) {
159
    resolve = oldest_cached_resolve;
160
    debug(LD_EXIT,"Forgetting old cached resolve (address %s, expires %lu)",
161
          safe_str(resolve->address), (unsigned long)resolve->expire);
162
    if (resolve->state == CACHE_STATE_PENDING) {
163
      debug(LD_EXIT,"Bug: Expiring a dns resolve ('%s') that's still pending. Forgot to cull it?", safe_str(resolve->address));
164
      tor_fragile_assert();
165
166
    }
    if (resolve->pending_connections) {
167
      debug(LD_EXIT, "Closing pending connections on expiring DNS resolve!");
168
      tor_fragile_assert();
169
170
171
172
173
174
      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;
175
        connection_edge_end(pendconn, END_STREAM_REASON_TIMEOUT,
176
                            pendconn->cpath_layer);
177
        circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
178
179
180
        connection_free(pendconn);
        tor_free(pend);
      }
181
    }
182
    oldest_cached_resolve = resolve->next;
183
    if (!oldest_cached_resolve) /* if there are no more, */
184
      newest_cached_resolve = NULL; /* then make sure the list's tail knows that too */
185
    HT_REMOVE(cache_map, &cache_root, resolve);
186
    tor_free(resolve);
187
188
189
  }
}

190
191
192
193
/** Send a response to the RESOVLE request of a connection. answer_type must
 *  be one of RESOLVED_TYPE_(IPV4|ERROR|ERROR_TRANSIENT) */
static void
send_resolved_cell(connection_t *conn, uint8_t answer_type)
194
195
{
  char buf[RELAY_PAYLOAD_SIZE];
196
  size_t buflen;
197
198
199
200
201
202
203
204

  buf[0] = answer_type;

  switch (answer_type)
    {
    case RESOLVED_TYPE_IPV4:
      buf[1] = 4;
      set_uint32(buf+2, htonl(conn->addr));
205
206
      set_uint32(buf+6, htonl(MAX_DNS_ENTRY_AGE)); /*XXXX send a real TTL*/
      buflen = 10;
207
208
209
      break;
    case RESOLVED_TYPE_ERROR_TRANSIENT:
    case RESOLVED_TYPE_ERROR:
210
211
212
213
214
215
216
217
218
219
      {
        const char *errmsg = "Error resolving hostname";
        int msglen = strlen(errmsg);
        int ttl = (answer_type == RESOLVED_TYPE_ERROR ? MAX_DNS_ENTRY_AGE : 0);
        buf[1] = msglen;
        strlcpy(buf+2, errmsg, sizeof(buf)-2);
        set_uint32(buf+2+msglen, htonl((uint32_t)ttl));
        buflen = 6+msglen;
        break;
      }
220
221
222
    default:
      tor_assert(0);
    }
223
  connection_edge_send_command(conn, circuit_get_by_edge_conn(conn),
224
225
226
227
                               RELAY_COMMAND_RESOLVED, buf, buflen,
                               conn->cpath_layer);
}

228
229
/** Link <b>r</b> into the hash table of address-to-result mappings, and add it
 * to the linked list of resolves-by-age. */
230
static void
231
insert_resolve(cached_resolve_t *r)
232
233
234
235
236
237
238
239
240
{
  /* 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;

241
  HT_INSERT(cache_map, &cache_root, r);
242
243
}

Nick Mathewson's avatar
Nick Mathewson committed
244
245
/** 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.
246
 * If resolve failed, unlink exitconn if needed, free it, and return -1.
247
248
249
250
251
252
253
 *
 * 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.
 */
254
255
256
int
dns_resolve(connection_t *exitconn)
{
257
258
259
  cached_resolve_t *resolve;
  cached_resolve_t search;
  pending_connection_t *pending_connection;
260
  struct in_addr in;
261
  circuit_t *circ;
262
  uint32_t now = time(NULL);
263
  assert_connection_ok(exitconn, 0);
264
  tor_assert(exitconn->s == -1);
265

266
267
268
269
  /* 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);
270
271
    if (exitconn->purpose == EXIT_PURPOSE_RESOLVE)
      send_resolved_cell(exitconn, RESOLVED_TYPE_IPV4);
272
    return 1;
273
274
275
  }

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

279
280
281
  /* lower-case exitconn->address, so it's in canonical form */
  tor_strlower(exitconn->address);

282
  /* now check the hash table to see if 'address' is already there. */
Nick Mathewson's avatar
Nick Mathewson committed
283
  strlcpy(search.address, exitconn->address, sizeof(search.address));
284
  resolve = HT_FIND(cache_map, &cache_root, &search);
285
286
  if (resolve) { /* already there */
    switch (resolve->state) {
287
288
      case CACHE_STATE_PENDING:
        /* add us to the pending list */
289
        pending_connection = tor_malloc_zero(
290
                                      sizeof(pending_connection_t));
291
        pending_connection->conn = exitconn;
Roger Dingledine's avatar
   
Roger Dingledine committed
292
293
        pending_connection->next = resolve->pending_connections;
        resolve->pending_connections = pending_connection;
294
        debug(LD_EXIT,"Connection (fd %d) waiting for pending DNS resolve of '%s'",
295
              exitconn->s, safe_str(exitconn->address));
296
        exitconn->state = EXIT_CONN_STATE_RESOLVING;
Roger Dingledine's avatar
   
Roger Dingledine committed
297
        return 0;
298
      case CACHE_STATE_VALID:
299
        exitconn->addr = resolve->addr;
300
        debug(LD_EXIT,"Connection (fd %d) found cached answer for '%s'",
301
              exitconn->s, safe_str(exitconn->address));
302
303
        if (exitconn->purpose == EXIT_PURPOSE_RESOLVE)
          send_resolved_cell(exitconn, RESOLVED_TYPE_IPV4);
304
        return 1;
305
      case CACHE_STATE_FAILED:
306
        debug(LD_EXIT,"Connection (fd %d) found cached error for '%s'",
307
              exitconn->s, safe_str(exitconn->address));
308
309
        if (exitconn->purpose == EXIT_PURPOSE_RESOLVE)
          send_resolved_cell(exitconn, RESOLVED_TYPE_ERROR);
310
        circ = circuit_get_by_edge_conn(exitconn);
311
312
        if (circ)
          circuit_detach_stream(circ, exitconn);
313
314
        if (!exitconn->marked_for_close)
          connection_free(exitconn);
315
316
        return -1;
    }
Roger Dingledine's avatar
Roger Dingledine committed
317
    tor_assert(0);
Roger Dingledine's avatar
Roger Dingledine committed
318
319
  }
  /* not there, need to add it */
320
  resolve = tor_malloc_zero(sizeof(cached_resolve_t));
Roger Dingledine's avatar
Roger Dingledine committed
321
  resolve->state = CACHE_STATE_PENDING;
322
  resolve->expire = now + MAX_DNS_ENTRY_AGE;
Nick Mathewson's avatar
Nick Mathewson committed
323
  strlcpy(resolve->address, exitconn->address, sizeof(resolve->address));
Roger Dingledine's avatar
Roger Dingledine committed
324
325

  /* add us to the pending list */
326
  pending_connection = tor_malloc_zero(sizeof(pending_connection_t));
Roger Dingledine's avatar
Roger Dingledine committed
327
328
  pending_connection->conn = exitconn;
  resolve->pending_connections = pending_connection;
329
  exitconn->state = EXIT_CONN_STATE_RESOLVING;
Roger Dingledine's avatar
Roger Dingledine committed
330

331
  insert_resolve(resolve);
Roger Dingledine's avatar
Roger Dingledine committed
332
  return assign_to_dnsworker(exitconn);
333
334
}

Roger Dingledine's avatar
Roger Dingledine committed
335
/** Find or spawn a dns worker process to handle resolving
Nick Mathewson's avatar
Nick Mathewson committed
336
 * <b>exitconn</b>-\>address; tell that dns worker to begin resolving.
337
 */
338
339
340
static int
assign_to_dnsworker(connection_t *exitconn)
{
341
342
  connection_t *dnsconn;
  unsigned char len;
343

Roger Dingledine's avatar
Roger Dingledine committed
344
  tor_assert(exitconn->state == EXIT_CONN_STATE_RESOLVING);
345
  tor_assert(exitconn->s == -1);
346

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

352
  dnsconn = connection_get_by_type_state(CONN_TYPE_DNSWORKER, DNSWORKER_STATE_IDLE);
353

354
  if (!dnsconn) {
355
    warn(LD_EXIT,"no idle dns workers. Failing.");
356
357
    if (exitconn->purpose == EXIT_PURPOSE_RESOLVE)
      send_resolved_cell(exitconn, RESOLVED_TYPE_ERROR_TRANSIENT);
358
    goto err;
359
360
  }

361
  debug(LD_EXIT,
362
363
        "Connection (fd %d) needs to resolve '%s'; assigning "
        "to DNSWorker (fd %d)",
364
        exitconn->s, safe_str(exitconn->address), dnsconn->s);
365

366
  tor_free(dnsconn->address);
367
  dnsconn->address = tor_strdup(exitconn->address);
368
  dnsconn->state = DNSWORKER_STATE_BUSY;
Roger Dingledine's avatar
Roger Dingledine committed
369
  num_dnsworkers_busy++;
370

371
  len = strlen(dnsconn->address);
372
  connection_write_to_buf((char*)&len, 1, dnsconn);
373
  connection_write_to_buf(dnsconn->address, len, dnsconn);
374
375

  return 0;
376
377
378
err:
  dns_cancel_pending_resolve(exitconn->address); /* also sends end and frees! */
  return -1;
379
380
}

Nick Mathewson's avatar
Nick Mathewson committed
381
/** Remove <b>conn</b> from the list of connections waiting for conn-\>address.
382
 */
383
384
void
connection_dns_remove(connection_t *conn)
385
{
386
387
388
  pending_connection_t *pend, *victim;
  cached_resolve_t search;
  cached_resolve_t *resolve;
389

390
391
392
  tor_assert(conn->type == CONN_TYPE_EXIT);
  tor_assert(conn->state == EXIT_CONN_STATE_RESOLVING);

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

395
  resolve = HT_FIND(cache_map, &cache_root, &search);
396
  if (!resolve) {
397
398
    /* XXXX RD This *is* a bug, right? -NM */
    notice(LD_BUG,"Address '%s' is not pending. Dropping.", safe_str(conn->address));
399
400
401
    return;
  }

Roger Dingledine's avatar
Roger Dingledine committed
402
  tor_assert(resolve->pending_connections);
403
404
405
406
  assert_connection_ok(conn,0);

  pend = resolve->pending_connections;

407
  if (pend->conn == conn) {
408
    resolve->pending_connections = pend->next;
409
    tor_free(pend);
410
    debug(LD_EXIT, "First connection (fd %d) no longer waiting for resolve of '%s'",
411
          conn->s, safe_str(conn->address));
412
413
    return;
  } else {
414
415
    for ( ; pend->next; pend = pend->next) {
      if (pend->next->conn == conn) {
416
417
        victim = pend->next;
        pend->next = victim->next;
418
        tor_free(victim);
419
        debug(LD_EXIT, "Connection (fd %d) no longer waiting for resolve of '%s'",
420
              conn->s, safe_str(conn->address));
421
422
423
        return; /* more are pending */
      }
    }
Roger Dingledine's avatar
Roger Dingledine committed
424
    tor_assert(0); /* not reachable unless onlyconn not in pending list */
425
426
427
  }
}

Roger Dingledine's avatar
Roger Dingledine committed
428
/** Log an error and abort if conn is waiting for a DNS resolve.
429
 */
430
431
432
void
assert_connection_edge_not_dns_pending(connection_t *conn)
{
433
  pending_connection_t *pend;
434
  cached_resolve_t **resolve;
435

436
  HT_FOREACH(resolve, cache_map, &cache_root) {
437
    for (pend = (*resolve)->pending_connections;
438
439
         pend;
         pend = pend->next) {
Roger Dingledine's avatar
Roger Dingledine committed
440
      tor_assert(pend->conn != conn);
441
442
443
444
    }
  }
}

Roger Dingledine's avatar
Roger Dingledine committed
445
/** Log an error and abort if any connection waiting for a DNS resolve is
446
 * corrupted. */
447
448
449
void
assert_all_pending_dns_resolves_ok(void)
{
450
  pending_connection_t *pend;
451
  cached_resolve_t **resolve;
452

453
  HT_FOREACH(resolve, cache_map, &cache_root) {
454
    for (pend = (*resolve)->pending_connections;
455
456
         pend;
         pend = pend->next) {
457
      assert_connection_ok(pend->conn, 0);
458
459
      tor_assert(pend->conn->s == -1);
      tor_assert(!connection_in_array(pend->conn));
460
461
462
463
    }
  }
}

Nick Mathewson's avatar
Nick Mathewson committed
464
465
466
/** 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.
467
 */
468
469
470
void
dns_cancel_pending_resolve(char *address)
{
471
472
473
  pending_connection_t *pend;
  cached_resolve_t search;
  cached_resolve_t *resolve;
474
  connection_t *pendconn;
475
  circuit_t *circ;
476

Nick Mathewson's avatar
Nick Mathewson committed
477
  strlcpy(search.address, address, sizeof(search.address));
478

479
  resolve = HT_FIND(cache_map, &cache_root, &search);
480
  if (!resolve) {
481
482
    /* XXXX RD This *is* a bug, right? -NM */
    notice(LD_BUG,"Address '%s' is not pending. Dropping.", safe_str(address));
483
484
485
    return;
  }

486
487
  if (!resolve->pending_connections) {
    /* XXX this should never trigger, but sometimes it does */
488
    warn(LD_BUG,"Bug: Address '%s' is pending but has no pending connections!",
489
         safe_str(address));
490
    tor_fragile_assert();
491
492
    return;
  }
Roger Dingledine's avatar
Roger Dingledine committed
493
  tor_assert(resolve->pending_connections);
494

495
  /* mark all pending connections to fail */
496
497
  debug(LD_EXIT, "Failing all connections waiting on DNS resolve of '%s'",
        safe_str(address));
498
  while (resolve->pending_connections) {
499
    pend = resolve->pending_connections;
500
    pend->conn->state = EXIT_CONN_STATE_RESOLVEFAILED;
501
    pendconn = pend->conn;
502
    tor_assert(pendconn->s == -1);
503
    if (!pendconn->marked_for_close) {
504
505
      connection_edge_end(pendconn, END_STREAM_REASON_RESOURCELIMIT,
                          pendconn->cpath_layer);
506
    }
507
    circ = circuit_get_by_edge_conn(pendconn);
508
509
    if (circ)
      circuit_detach_stream(circ, pendconn);
510
    connection_free(pendconn);
511
512
    resolve->pending_connections = pend->next;
    tor_free(pend);
513
514
  }

515
516
517
  dns_purge_resolve(resolve);
}

Nick Mathewson's avatar
Nick Mathewson committed
518
/** Remove <b>resolve</b> from the cache.
519
 */
520
static void
521
dns_purge_resolve(cached_resolve_t *resolve)
522
{
523
  cached_resolve_t *tmp;
524

525
  /* remove resolve from the linked list */
526
  if (resolve == oldest_cached_resolve) {
527
    oldest_cached_resolve = resolve->next;
528
    if (oldest_cached_resolve == NULL)
529
      newest_cached_resolve = NULL;
530
  } else {
531
    /* FFFF make it a doubly linked list if this becomes too slow */
532
    for (tmp=oldest_cached_resolve; tmp && tmp->next != resolve; tmp=tmp->next) ;
Roger Dingledine's avatar
Roger Dingledine committed
533
    tor_assert(tmp); /* it's got to be in the list, or we screwed up somewhere else */
534
535
    tmp->next = resolve->next; /* unlink it */

536
    if (newest_cached_resolve == resolve)
537
      newest_cached_resolve = tmp;
538
  }
539

540
  /* remove resolve from the map */
541
  HT_REMOVE(cache_map, &cache_root, resolve);
542

543
  tor_free(resolve);
544
545
}

Roger Dingledine's avatar
Roger Dingledine committed
546
/** Called on the OR side when a DNS worker tells us the outcome of a DNS
547
 * resolve: tell all pending connections about the result of the lookup, and
Nick Mathewson's avatar
Nick Mathewson committed
548
549
550
551
 * 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}.
552
 */
553
554
555
static void
dns_found_answer(char *address, uint32_t addr, char outcome)
{
556
557
558
  pending_connection_t *pend;
  cached_resolve_t search;
  cached_resolve_t *resolve;
559
  connection_t *pendconn;
560
  circuit_t *circ;
561

Nick Mathewson's avatar
Nick Mathewson committed
562
  strlcpy(search.address, address, sizeof(search.address));
563

564
  resolve = HT_FIND(cache_map, &cache_root, &search);
565
  if (!resolve) {
566
567
    info(LD_EXIT,"Resolved unasked address '%s'; caching anyway.",
         safe_str(address));
568
    resolve = tor_malloc_zero(sizeof(cached_resolve_t));
569
570
571
572
573
    resolve->state = (outcome == DNS_RESOLVE_SUCCEEDED) ?
      CACHE_STATE_VALID : CACHE_STATE_FAILED;
    resolve->addr = addr;
    resolve->expire = time(NULL) + MAX_DNS_ENTRY_AGE;
    insert_resolve(resolve);
574
    return;
575
576
  }

577
  if (resolve->state != CACHE_STATE_PENDING) {
578
579
    /* XXXX Maybe update addr? or check addr for consistency? Or let
     * VALID replace FAILED? */
580
    notice(LD_EXIT, "Resolved '%s' which was already resolved; ignoring",
581
           safe_str(address));
Roger Dingledine's avatar
Roger Dingledine committed
582
    tor_assert(resolve->pending_connections == NULL);
583
584
585
586
587
588
    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
589
  /* tor_assert(resolve->state == CACHE_STATE_PENDING); */
590

591
  resolve->addr = addr;
592
  if (outcome == DNS_RESOLVE_SUCCEEDED)
593
594
595
596
    resolve->state = CACHE_STATE_VALID;
  else
    resolve->state = CACHE_STATE_FAILED;

597
  while (resolve->pending_connections) {
598
    pend = resolve->pending_connections;
599
    assert_connection_ok(pend->conn,time(NULL));
600
    pend->conn->addr = resolve->addr;
601
602
    pendconn = pend->conn; /* don't pass complex things to the
                              connection_mark_for_close macro */
603

604
    if (resolve->state == CACHE_STATE_FAILED) {
605
      /* prevent double-remove. */
606
      pendconn->state = EXIT_CONN_STATE_RESOLVEFAILED;
607
      if (pendconn->purpose == EXIT_PURPOSE_CONNECT) {
608
609
        connection_edge_end(pendconn, END_STREAM_REASON_RESOLVEFAILED, pendconn->cpath_layer);
        /* This detach must happen after we send the end cell. */
610
        circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
611
      } else {
612
        send_resolved_cell(pendconn, RESOLVED_TYPE_ERROR);
613
        /* This detach must happen after we send the resolved cell. */
614
        circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
615
      }
616
      connection_free(pendconn);
Roger Dingledine's avatar
Roger Dingledine committed
617
    } else {
618
619
620
621
      if (pendconn->purpose == EXIT_PURPOSE_CONNECT) {
        /* prevent double-remove. */
        pend->conn->state = EXIT_CONN_STATE_CONNECTING;

622
        circ = circuit_get_by_edge_conn(pend->conn);
623
624
625
626
627
        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;
628
        pend->conn->on_circuit = circ;
629
630
631
632
633
634
635
636
        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;
        send_resolved_cell(pendconn, RESOLVED_TYPE_IPV4);
637
        circ = circuit_get_by_edge_conn(pendconn);
638
639
640
641
        tor_assert(circ);
        circuit_detach_stream(circ, pendconn);
        connection_free(pendconn);
      }
Roger Dingledine's avatar
Roger Dingledine committed
642
    }
643
644
    resolve->pending_connections = pend->next;
    tor_free(pend);
645
  }
646

647
  if (outcome == DNS_RESOLVE_FAILED_TRANSIENT) { /* remove from cache */
648
649
    dns_purge_resolve(resolve);
  }
650
651
}

652
653
/******************************************************************/

Nick Mathewson's avatar
Nick Mathewson committed
654
/*
655
 * Connection between OR and dnsworker
Nick Mathewson's avatar
Nick Mathewson committed
656
 */
657

Roger Dingledine's avatar
Roger Dingledine committed
658
/** Write handler: called when we've pushed a request to a dnsworker. */
659
660
661
int
connection_dns_finished_flushing(connection_t *conn)
{
662
663
  tor_assert(conn);
  tor_assert(conn->type == CONN_TYPE_DNSWORKER);
664
665
666
667
  connection_stop_writing(conn);
  return 0;
}

668
669
670
int
connection_dns_reached_eof(connection_t *conn)
{
671
  warn(LD_EXIT,"Read eof. Worker died unexpectedly.");
672
  if (conn->state == DNSWORKER_STATE_BUSY) {
673
674
675
676
    /* don't cancel the resolve here -- it would be cancelled in
     * connection_about_to_close_connection(), since conn is still
     * in state BUSY
     */
677
678
679
680
681
682
683
684
    num_dnsworkers_busy--;
  }
  num_dnsworkers--;
  connection_mark_for_close(conn);
  return 0;
}

/** Read handler: called when we get data from a dnsworker. See
685
686
 * if we have a complete answer.  If so, call dns_found_answer on the
 * result.  If not, wait.  Returns 0. */
687
688
689
int
connection_dns_process_inbuf(connection_t *conn)
{
690
  char success;
691
  uint32_t addr;
692

693
694
  tor_assert(conn);
  tor_assert(conn->type == CONN_TYPE_DNSWORKER);
695

696
  if (conn->state != DNSWORKER_STATE_BUSY && buf_datalen(conn->inbuf)) {
697
698
    warn(LD_BUG,"Bug: read data (%d bytes) from an idle dns worker (fd %d, address '%s'). Please report.",
         (int)buf_datalen(conn->inbuf), conn->s, safe_str(conn->address));
699
    tor_fragile_assert();
700
701
702
703
704
705
706

    /* 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);
707
      warn(LD_EXIT,"Discarding idle dns answer (success %d, addr %d.)",
708
           success, addr); // XXX safe_str
709
    }
710
711
    return 0;
  }
712
  if (buf_datalen(conn->inbuf) < 5) /* entire answer available? */
713
    return 0; /* not yet */
714
  tor_assert(conn->state == DNSWORKER_STATE_BUSY);
Roger Dingledine's avatar
Roger Dingledine committed
715
  tor_assert(buf_datalen(conn->inbuf) == 5);
716

717
718
  connection_fetch_from_buf(&success,1,conn);
  connection_fetch_from_buf((char *)&addr,sizeof(uint32_t),conn);
719

720
721
  debug(LD_EXIT, "DNSWorker (fd %d) returned answer for '%s'",
        conn->s, safe_str(conn->address));
722

Roger Dingledine's avatar
Roger Dingledine committed
723
724
  tor_assert(success >= DNS_RESOLVE_FAILED_TRANSIENT);
  tor_assert(success <= DNS_RESOLVE_SUCCEEDED);
725
  dns_found_answer(conn->address, ntohl(addr), success);
726

727
  tor_free(conn->address);
728
  conn->address = tor_strdup("<idle>");
729
  conn->state = DNSWORKER_STATE_IDLE;
Roger Dingledine's avatar
Roger Dingledine committed
730
  num_dnsworkers_busy--;
731
732
733
734
735
  if (conn->timestamp_created < last_rotation_time) {
    connection_mark_for_close(conn);
    num_dnsworkers--;
    spawn_enough_dnsworkers();
  }
736
737
738
  return 0;
}

739
740
741
/** Close and re-open all idle dnsworkers; schedule busy ones to be closed
 * and re-opened once they're no longer busy.
 **/
742
743
void
dnsworkers_rotate(void)
744
745
746
747
748
749
750
751
{
  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);
752
753
  if (server_mode(get_options()))
    spawn_enough_dnsworkers();
754
755
}

Roger Dingledine's avatar
Roger Dingledine committed
756
/** Implementation for DNS workers; this code runs in a separate
757
758
759
 * 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
760
761
762
763
764
765
 *    - The OR says:
 *         - ADDRESSLEN [1 byte]
 *         - ADDRESS    [ADDRESSLEN bytes]
 *    - The DNS worker does the lookup, and replies:
 *         - OUTCOME    [1 byte]
 *         - IP         [4 bytes]
766
767
768
769
770
771
772
 *
 * 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.
 */
773
774
775
static int
dnsworker_main(void *data)
{
776
777
  char address[MAX_ADDRESSLEN];
  unsigned char address_len;
778
  char answer[5];
Roger Dingledine's avatar
Roger Dingledine committed
779
  uint32_t ip;
780
  int *fdarray = data;
Roger Dingledine's avatar
Roger Dingledine committed
781
  int fd;
782
  int result;
783

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

786
  fd = fdarray[1]; /* this side is ours */
787
#ifndef TOR_IS_MULTITHREADED
788
  tor_close_socket(fdarray[0]); /* this is the side of the socketpair the parent uses */
789
  tor_free_all(1); /* so the child doesn't hold the parent's fd's open */
790
  handle_signals(0); /* ignore interrupts from the keyboard, etc */
791
792
#endif
  tor_free(data);
793

794
  for (;;) {
795
    int r;
796

797
798
    if ((r = recv(fd, &address_len, 1, 0)) != 1) {
      if (r == 0) {
799
        info(LD_EXIT,"DNS worker exiting because Tor process closed connection (either pruned idle dnsworker or died).");
800
      } else {
801
802
        info(LD_EXIT,"DNS worker exiting because of error on connection to Tor process.");
        info(