dns.c 30.4 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 "tree.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
55
56
 * structs are stored at the OR side in a splay tree, and as a linked
 * list from oldest to newest.
 */
57
58
typedef struct cached_resolve_t {
  SPLAY_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
/** Splay tree of cached_resolve objects. */
80
static SPLAY_HEAD(cache_tree, 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 splay trees. */
84
85
86
87
static int
compare_cached_resolves(cached_resolve_t *a,
                        cached_resolve_t *b)
{
88
  /* make this smarter one day? */
89
  return strncmp(a->address, b->address, MAX_ADDRESSLEN);
90
91
}

92
93
SPLAY_PROTOTYPE(cache_tree, cached_resolve_t, node, compare_cached_resolves);
SPLAY_GENERATE(cache_tree, cached_resolve_t, node, compare_cached_resolves);
94

95
/** Initialize the DNS cache. */
96
97
98
static void
init_cache_tree(void)
{
99
100
101
  SPLAY_INIT(&cache_root);
}

Roger Dingledine's avatar
Roger Dingledine committed
102
/** Initialize the DNS subsystem; called by the OR process. */
103
104
105
void
dns_init(void)
{
106
  init_cache_tree();
107
  dnsworkers_rotate();
108
}
109

110
/** Helper: free storage held by an entry in the DNS cache. */
111
static void
112
_free_cached_resolve(cached_resolve_t *r)
113
{
Nick Mathewson's avatar
Nick Mathewson committed
114
  while (r->pending_connections) {
115
    pending_connection_t *victim = r->pending_connections;
116
117
118
119
120
121
    r->pending_connections = victim->next;
    tor_free(victim);
  }
  tor_free(r);
}

122
/** Free all storage held in the DNS cache */
123
124
125
void
dns_free_all(void)
{
126
  cached_resolve_t *ptr, *next;
127
128
129
130
131
132
133
  for (ptr = SPLAY_MIN(cache_tree, &cache_root); ptr != NULL; ptr = next) {
    next = SPLAY_NEXT(cache_tree, &cache_root, ptr);
    SPLAY_REMOVE(cache_tree, &cache_root, ptr);
    _free_cached_resolve(ptr);
  }
}

134
/** Linked list of resolved addresses, oldest to newest. */
135
136
static cached_resolve_t *oldest_cached_resolve = NULL;
static cached_resolve_t *newest_cached_resolve = NULL;
137

Nick Mathewson's avatar
Nick Mathewson committed
138
/** Remove every cached_resolve whose <b>expire</b> time is before <b>now</b>
139
 * from the cache. */
140
141
142
static void
purge_expired_resolves(uint32_t now)
{
143
144
  cached_resolve_t *resolve;
  pending_connection_t *pend;
145
  connection_t *pendconn;
146
147
148
149

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

182
183
184
185
/** 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)
186
187
{
  char buf[RELAY_PAYLOAD_SIZE];
188
  size_t buflen;
189
190
191
192
193
194
195
196

  buf[0] = answer_type;

  switch (answer_type)
    {
    case RESOLVED_TYPE_IPV4:
      buf[1] = 4;
      set_uint32(buf+2, htonl(conn->addr));
197
198
      set_uint32(buf+6, htonl(MAX_DNS_ENTRY_AGE)); /*XXXX send a real TTL*/
      buflen = 10;
199
200
201
      break;
    case RESOLVED_TYPE_ERROR_TRANSIENT:
    case RESOLVED_TYPE_ERROR:
202
203
204
205
206
207
208
209
210
211
      {
        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;
      }
212
213
214
    default:
      tor_assert(0);
    }
215
  connection_edge_send_command(conn, circuit_get_by_edge_conn(conn),
216
217
218
219
                               RELAY_COMMAND_RESOLVED, buf, buflen,
                               conn->cpath_layer);
}

220
221
222
/** Link <b>r</b> into the tree of address-to-result mappings, and add it to
 * the linked list of resolves-by-age. */
static void
223
insert_resolve(cached_resolve_t *r)
224
225
226
227
228
229
230
231
232
233
234
235
{
  /* 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;

  SPLAY_INSERT(cache_tree, &cache_root, r);
}

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

258
259
260
261
  /* 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);
262
263
    if (exitconn->purpose == EXIT_PURPOSE_RESOLVE)
      send_resolved_cell(exitconn, RESOLVED_TYPE_IPV4);
264
    return 1;
265
266
267
268
  }

  /* then take this opportunity to see if there are any expired
   * resolves in the tree. */
269
  purge_expired_resolves(now);
270

271
272
273
  /* lower-case exitconn->address, so it's in canonical form */
  tor_strlower(exitconn->address);

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

  /* add us to the pending list */
318
  pending_connection = tor_malloc_zero(sizeof(pending_connection_t));
Roger Dingledine's avatar
Roger Dingledine committed
319
320
  pending_connection->conn = exitconn;
  resolve->pending_connections = pending_connection;
321
  exitconn->state = EXIT_CONN_STATE_RESOLVING;
Roger Dingledine's avatar
Roger Dingledine committed
322

323
  insert_resolve(resolve);
Roger Dingledine's avatar
Roger Dingledine committed
324
  return assign_to_dnsworker(exitconn);
325
326
}

Roger Dingledine's avatar
Roger Dingledine committed
327
/** Find or spawn a dns worker process to handle resolving
Nick Mathewson's avatar
Nick Mathewson committed
328
 * <b>exitconn</b>-\>address; tell that dns worker to begin resolving.
329
 */
330
331
332
static int
assign_to_dnsworker(connection_t *exitconn)
{
333
334
  connection_t *dnsconn;
  unsigned char len;
335

Roger Dingledine's avatar
Roger Dingledine committed
336
  tor_assert(exitconn->state == EXIT_CONN_STATE_RESOLVING);
337
  tor_assert(exitconn->s == -1);
338

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

344
  dnsconn = connection_get_by_type_state(CONN_TYPE_DNSWORKER, DNSWORKER_STATE_IDLE);
345

346
  if (!dnsconn) {
Roger Dingledine's avatar
Roger Dingledine committed
347
    log_fn(LOG_WARN,"no idle dns workers. Failing.");
348
349
    if (exitconn->purpose == EXIT_PURPOSE_RESOLVE)
      send_resolved_cell(exitconn, RESOLVED_TYPE_ERROR_TRANSIENT);
350
    goto err;
351
352
  }

353
  log_fn(LOG_DEBUG, "Connection (fd %d) needs to resolve '%s'; assigning to DNSWorker (fd %d)",
354
         exitconn->s, safe_str(exitconn->address), dnsconn->s);
355

356
  tor_free(dnsconn->address);
357
  dnsconn->address = tor_strdup(exitconn->address);
358
  dnsconn->state = DNSWORKER_STATE_BUSY;
Roger Dingledine's avatar
Roger Dingledine committed
359
  num_dnsworkers_busy++;
360

361
  len = strlen(dnsconn->address);
362
  connection_write_to_buf((char*)&len, 1, dnsconn);
363
  connection_write_to_buf(dnsconn->address, len, dnsconn);
364
365

  return 0;
366
367
368
err:
  dns_cancel_pending_resolve(exitconn->address); /* also sends end and frees! */
  return -1;
369
370
}

Nick Mathewson's avatar
Nick Mathewson committed
371
/** Remove <b>conn</b> from the list of connections waiting for conn-\>address.
372
 */
373
374
void
connection_dns_remove(connection_t *conn)
375
{
376
377
378
  pending_connection_t *pend, *victim;
  cached_resolve_t search;
  cached_resolve_t *resolve;
379

380
381
382
  tor_assert(conn->type == CONN_TYPE_EXIT);
  tor_assert(conn->state == EXIT_CONN_STATE_RESOLVING);

Nick Mathewson's avatar
Nick Mathewson committed
383
  strlcpy(search.address, conn->address, sizeof(search.address));
384
385

  resolve = SPLAY_FIND(cache_tree, &cache_root, &search);
386
  if (!resolve) {
387
    log_fn(LOG_NOTICE,"Address '%s' is not pending. Dropping.", safe_str(conn->address));
388
389
390
    return;
  }

Roger Dingledine's avatar
Roger Dingledine committed
391
  tor_assert(resolve->pending_connections);
392
393
394
395
  assert_connection_ok(conn,0);

  pend = resolve->pending_connections;

396
  if (pend->conn == conn) {
397
    resolve->pending_connections = pend->next;
398
    tor_free(pend);
399
    log_fn(LOG_DEBUG, "First connection (fd %d) no longer waiting for resolve of '%s'",
400
           conn->s, safe_str(conn->address));
401
402
    return;
  } else {
403
404
    for ( ; pend->next; pend = pend->next) {
      if (pend->next->conn == conn) {
405
406
        victim = pend->next;
        pend->next = victim->next;
407
        tor_free(victim);
408
        log_fn(LOG_DEBUG, "Connection (fd %d) no longer waiting for resolve of '%s'",
409
               conn->s, safe_str(conn->address));
410
411
412
        return; /* more are pending */
      }
    }
Roger Dingledine's avatar
Roger Dingledine committed
413
    tor_assert(0); /* not reachable unless onlyconn not in pending list */
414
415
416
  }
}

Roger Dingledine's avatar
Roger Dingledine committed
417
/** Log an error and abort if conn is waiting for a DNS resolve.
418
 */
419
420
421
void
assert_connection_edge_not_dns_pending(connection_t *conn)
{
422
423
  pending_connection_t *pend;
  cached_resolve_t *resolve;
424
425

  SPLAY_FOREACH(resolve, cache_tree, &cache_root) {
426
    for (pend = resolve->pending_connections;
427
428
         pend;
         pend = pend->next) {
Roger Dingledine's avatar
Roger Dingledine committed
429
      tor_assert(pend->conn != conn);
430
431
432
433
    }
  }
}

Roger Dingledine's avatar
Roger Dingledine committed
434
/** Log an error and abort if any connection waiting for a DNS resolve is
435
 * corrupted. */
436
437
438
void
assert_all_pending_dns_resolves_ok(void)
{
439
440
  pending_connection_t *pend;
  cached_resolve_t *resolve;
441
442

  SPLAY_FOREACH(resolve, cache_tree, &cache_root) {
443
    for (pend = resolve->pending_connections;
444
445
         pend;
         pend = pend->next) {
446
      assert_connection_ok(pend->conn, 0);
447
448
      tor_assert(pend->conn->s == -1);
      tor_assert(!connection_in_array(pend->conn));
449
450
451
452
    }
  }
}

Nick Mathewson's avatar
Nick Mathewson committed
453
454
455
/** 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.
456
 */
457
458
459
void
dns_cancel_pending_resolve(char *address)
{
460
461
462
  pending_connection_t *pend;
  cached_resolve_t search;
  cached_resolve_t *resolve;
463
  connection_t *pendconn;
464
  circuit_t *circ;
465

Nick Mathewson's avatar
Nick Mathewson committed
466
  strlcpy(search.address, address, sizeof(search.address));
467
468

  resolve = SPLAY_FIND(cache_tree, &cache_root, &search);
469
  if (!resolve) {
470
    log_fn(LOG_NOTICE,"Address '%s' is not pending. Dropping.", safe_str(address));
471
472
473
    return;
  }

474
475
  if (!resolve->pending_connections) {
    /* XXX this should never trigger, but sometimes it does */
476
477
    log_fn(LOG_WARN,"Bug: Address '%s' is pending but has no pending connections!",
           safe_str(address));
478
    tor_fragile_assert();
479
480
    return;
  }
Roger Dingledine's avatar
Roger Dingledine committed
481
  tor_assert(resolve->pending_connections);
482

483
484
  /* mark all pending connections to fail */
  log_fn(LOG_DEBUG, "Failing all connections waiting on DNS resolve of '%s'",
485
         safe_str(address));
486
  while (resolve->pending_connections) {
487
    pend = resolve->pending_connections;
488
    pend->conn->state = EXIT_CONN_STATE_RESOLVEFAILED;
489
    pendconn = pend->conn;
490
    tor_assert(pendconn->s == -1);
491
    if (!pendconn->marked_for_close) {
492
493
      connection_edge_end(pendconn, END_STREAM_REASON_RESOURCELIMIT,
                          pendconn->cpath_layer);
494
    }
495
    circ = circuit_get_by_edge_conn(pendconn);
496
497
    if (circ)
      circuit_detach_stream(circ, pendconn);
498
    connection_free(pendconn);
499
500
    resolve->pending_connections = pend->next;
    tor_free(pend);
501
502
  }

503
504
505
  dns_purge_resolve(resolve);
}

Nick Mathewson's avatar
Nick Mathewson committed
506
/** Remove <b>resolve</b> from the cache.
507
 */
508
static void
509
dns_purge_resolve(cached_resolve_t *resolve)
510
{
511
  cached_resolve_t *tmp;
512

513
  /* remove resolve from the linked list */
514
  if (resolve == oldest_cached_resolve) {
515
    oldest_cached_resolve = resolve->next;
516
    if (oldest_cached_resolve == NULL)
517
      newest_cached_resolve = NULL;
518
  } else {
519
    /* FFFF make it a doubly linked list if this becomes too slow */
520
    for (tmp=oldest_cached_resolve; tmp && tmp->next != resolve; tmp=tmp->next) ;
Roger Dingledine's avatar
Roger Dingledine committed
521
    tor_assert(tmp); /* it's got to be in the list, or we screwed up somewhere else */
522
523
    tmp->next = resolve->next; /* unlink it */

524
    if (newest_cached_resolve == resolve)
525
      newest_cached_resolve = tmp;
526
  }
527
528
529
530

  /* remove resolve from the tree */
  SPLAY_REMOVE(cache_tree, &cache_root, resolve);

531
  tor_free(resolve);
532
533
}

Roger Dingledine's avatar
Roger Dingledine committed
534
/** Called on the OR side when a DNS worker tells us the outcome of a DNS
535
 * resolve: tell all pending connections about the result of the lookup, and
Nick Mathewson's avatar
Nick Mathewson committed
536
537
538
539
 * 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}.
540
 */
541
542
543
static void
dns_found_answer(char *address, uint32_t addr, char outcome)
{
544
545
546
  pending_connection_t *pend;
  cached_resolve_t search;
  cached_resolve_t *resolve;
547
  connection_t *pendconn;
548
  circuit_t *circ;
549

Nick Mathewson's avatar
Nick Mathewson committed
550
  strlcpy(search.address, address, sizeof(search.address));
551
552

  resolve = SPLAY_FIND(cache_tree, &cache_root, &search);
553
  if (!resolve) {
554
555
    log_fn(LOG_INFO,"Resolved unasked address '%s'; caching anyway.",
           safe_str(address));
556
    resolve = tor_malloc_zero(sizeof(cached_resolve_t));
557
558
559
560
561
    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);
562
    return;
563
564
  }

565
  if (resolve->state != CACHE_STATE_PENDING) {
566
567
    /* XXXX Maybe update addr? or check addr for consistency? Or let
     * VALID replace FAILED? */
Roger Dingledine's avatar
Roger Dingledine committed
568
    log_fn(LOG_NOTICE, "Resolved '%s' which was already resolved; ignoring",
569
           safe_str(address));
Roger Dingledine's avatar
Roger Dingledine committed
570
    tor_assert(resolve->pending_connections == NULL);
571
572
573
574
575
576
    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
577
  /* tor_assert(resolve->state == CACHE_STATE_PENDING); */
578

579
  resolve->addr = addr;
580
  if (outcome == DNS_RESOLVE_SUCCEEDED)
581
582
583
584
    resolve->state = CACHE_STATE_VALID;
  else
    resolve->state = CACHE_STATE_FAILED;

585
  while (resolve->pending_connections) {
586
    pend = resolve->pending_connections;
587
    assert_connection_ok(pend->conn,time(NULL));
588
    pend->conn->addr = resolve->addr;
589
590
    pendconn = pend->conn; /* don't pass complex things to the
                              connection_mark_for_close macro */
591

592
    if (resolve->state == CACHE_STATE_FAILED) {
593
      /* prevent double-remove. */
594
      pendconn->state = EXIT_CONN_STATE_RESOLVEFAILED;
595
      if (pendconn->purpose == EXIT_PURPOSE_CONNECT) {
596
597
        connection_edge_end(pendconn, END_STREAM_REASON_RESOLVEFAILED, pendconn->cpath_layer);
        /* This detach must happen after we send the end cell. */
598
        circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
599
      } else {
600
        send_resolved_cell(pendconn, RESOLVED_TYPE_ERROR);
601
        /* This detach must happen after we send the resolved cell. */
602
        circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
603
      }
604
      connection_free(pendconn);
Roger Dingledine's avatar
Roger Dingledine committed
605
    } else {
606
607
608
609
      if (pendconn->purpose == EXIT_PURPOSE_CONNECT) {
        /* prevent double-remove. */
        pend->conn->state = EXIT_CONN_STATE_CONNECTING;

610
        circ = circuit_get_by_edge_conn(pend->conn);
611
612
613
614
615
        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;
616
        pend->conn->on_circuit = circ;
617
618
619
620
621
622
623
624
        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);
625
        circ = circuit_get_by_edge_conn(pendconn);
626
627
628
629
        tor_assert(circ);
        circuit_detach_stream(circ, pendconn);
        connection_free(pendconn);
      }
Roger Dingledine's avatar
Roger Dingledine committed
630
    }
631
632
    resolve->pending_connections = pend->next;
    tor_free(pend);
633
  }
634

635
  if (outcome == DNS_RESOLVE_FAILED_TRANSIENT) { /* remove from cache */
636
637
    dns_purge_resolve(resolve);
  }
638
639
}

640
641
/******************************************************************/

Nick Mathewson's avatar
Nick Mathewson committed
642
/*
643
 * Connection between OR and dnsworker
Nick Mathewson's avatar
Nick Mathewson committed
644
 */
645

Roger Dingledine's avatar
Roger Dingledine committed
646
/** Write handler: called when we've pushed a request to a dnsworker. */
647
648
649
int
connection_dns_finished_flushing(connection_t *conn)
{
650
651
  tor_assert(conn);
  tor_assert(conn->type == CONN_TYPE_DNSWORKER);
652
653
654
655
  connection_stop_writing(conn);
  return 0;
}

656
657
658
int
connection_dns_reached_eof(connection_t *conn)
{
659
  log_fn(LOG_WARN,"Read eof. Worker died unexpectedly.");
660
  if (conn->state == DNSWORKER_STATE_BUSY) {
661
662
663
664
    /* don't cancel the resolve here -- it would be cancelled in
     * connection_about_to_close_connection(), since conn is still
     * in state BUSY
     */
665
666
667
668
669
670
671
672
    num_dnsworkers_busy--;
  }
  num_dnsworkers--;
  connection_mark_for_close(conn);
  return 0;
}

/** Read handler: called when we get data from a dnsworker. See
673
674
 * if we have a complete answer.  If so, call dns_found_answer on the
 * result.  If not, wait.  Returns 0. */
675
676
677
int
connection_dns_process_inbuf(connection_t *conn)
{
678
  char success;
679
  uint32_t addr;
680

681
682
  tor_assert(conn);
  tor_assert(conn->type == CONN_TYPE_DNSWORKER);
683

684
  if (conn->state != DNSWORKER_STATE_BUSY && buf_datalen(conn->inbuf)) {
685
    log_fn(LOG_WARN,"Bug: read data (%d bytes) from an idle dns worker (fd %d, address '%s'). Please report.",
686
           (int)buf_datalen(conn->inbuf), conn->s, safe_str(conn->address));
687
    tor_fragile_assert();
688
689
690
691
692
693
694
695

    /* 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);
      log_fn(LOG_WARN,"Discarding idle dns answer (success %d, addr %d.)",
696
             success, addr); // XXX safe_str
697
    }
698
699
    return 0;
  }
700
  if (buf_datalen(conn->inbuf) < 5) /* entire answer available? */
701
    return 0; /* not yet */
702
  tor_assert(conn->state == DNSWORKER_STATE_BUSY);
Roger Dingledine's avatar
Roger Dingledine committed
703
  tor_assert(buf_datalen(conn->inbuf) == 5);
704

705
706
  connection_fetch_from_buf(&success,1,conn);
  connection_fetch_from_buf((char *)&addr,sizeof(uint32_t),conn);
707

708
  log_fn(LOG_DEBUG, "DNSWorker (fd %d) returned answer for '%s'",
709
         conn->s, safe_str(conn->address));
710

Roger Dingledine's avatar
Roger Dingledine committed
711
712
  tor_assert(success >= DNS_RESOLVE_FAILED_TRANSIENT);
  tor_assert(success <= DNS_RESOLVE_SUCCEEDED);
713
  dns_found_answer(conn->address, ntohl(addr), success);
714

715
  tor_free(conn->address);
716
  conn->address = tor_strdup("<idle>");
717
  conn->state = DNSWORKER_STATE_IDLE;
Roger Dingledine's avatar
Roger Dingledine committed
718
  num_dnsworkers_busy--;
719
720
721
722
723
  if (conn->timestamp_created < last_rotation_time) {
    connection_mark_for_close(conn);
    num_dnsworkers--;
    spawn_enough_dnsworkers();
  }
724
725
726
  return 0;
}

727
728
729
/** Close and re-open all idle dnsworkers; schedule busy ones to be closed
 * and re-opened once they're no longer busy.
 **/
730
731
void
dnsworkers_rotate(void)
732
733
734
735
736
737
738
739
{
  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);
740
741
  if (server_mode(get_options()))
    spawn_enough_dnsworkers();
742
743
}

Roger Dingledine's avatar
Roger Dingledine committed
744
/** Implementation for DNS workers; this code runs in a separate
745
746
747
 * 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
748
749
750
751
752
753
 *    - The OR says:
 *         - ADDRESSLEN [1 byte]
 *         - ADDRESS    [ADDRESSLEN bytes]
 *    - The DNS worker does the lookup, and replies:
 *         - OUTCOME    [1 byte]
 *         - IP         [4 bytes]
754
755
756
757
758
759
760
 *
 * 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.
 */
761
762
763
static int
dnsworker_main(void *data)
{
764
765
  char address[MAX_ADDRESSLEN];
  unsigned char address_len;
766
  char answer[5];
Roger Dingledine's avatar
Roger Dingledine committed
767
  uint32_t ip;
768
  int *fdarray = data;
Roger Dingledine's avatar
Roger Dingledine committed
769
  int fd;
770
  int result;
771

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

774
  fd = fdarray[1]; /* this side is ours */
775
#ifndef TOR_IS_MULTITHREADED
776
  tor_close_socket(fdarray[0]); /* this is the side of the socketpair the parent uses */
777
  tor_free_all(1); /* so the child doesn't hold the parent's fd's open */
778
  handle_signals(0); /* ignore interrupts from the keyboard, etc */
779
780
#endif
  tor_free(data);
781

782
  for (;;) {
783
    int r;
784

785
786
787
788
789
790
791
    if ((r = recv(fd, &address_len, 1, 0)) != 1) {
      if (r == 0) {
        log_fn(LOG_INFO,"DNS worker exiting because Tor process closed connection (either pruned idle dnsworker or died).");
      } else {
        log_fn(LOG_INFO,"DNS worker exiting because of error on connection to Tor process.");
        log_fn(LOG_INFO,"(Error on %d was %s)", fd, tor_socket_strerror(tor_socket_errno(fd)));
      }
792
      tor_close_socket(fd);
793
      spawn_exit();
794
795
    }

796
    if (address_len && read_all(fd, address, address_len, 1) != address_len) {
797
      log_fn(LOG_ERR,"read hostname failed. Child exiting.");
798
      tor_close_socket(fd);
799
      spawn_exit();
800
    }
801
    address[address_len] = 0; /* null terminate it */
802

803
804
805
806
807
    result = tor_lookup_hostname(address, &ip);
    /* Make 0.0.0.0 an error, so that we can use "0" to mean "no addr") */
    if (!ip)
      result = -1;
    switch (result) {
808
      case 1:
809
        /* XXX result can never be 1, because we set it to -1 above on error */
810
        log_fn(LOG_INFO,"Could not resolve dest addr %s (transient).",safe_str(address));
811
        answer[0] = DNS_RESOLVE_FAILED_TRANSIENT;
812
813
        break;
      case -1:
814
        log_fn(LOG_INFO,"Could not resolve dest addr %s (permanent).",safe_str(address));
815
        answer[0] = DNS_RESOLVE_FAILED_PERMANENT;
816
        break;
817
      case 0:
818
        log_fn(LOG_INFO,"Resolved address '%s'.",safe_str(address));
819
        answer[0] = DNS_RESOLVE_SUCCEEDED;
820
        break;
821
    }
Roger Dingledine's avatar
Roger Dingledine committed
822
    set_uint32(answer+1, ip);
823
    if (write_all(fd, answer, 5, 1) != 5) {
824
      log_fn(LOG_ERR,"writing answer failed. Child exiting.");
825
      tor_close_socket(fd);