dns.c 30.2 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
50
51
52
struct pending_connection_t {
  struct connection_t *conn;
  struct pending_connection_t *next;
};

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
struct cached_resolve {
  SPLAY_ENTRY(cached_resolve) 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
69
  struct pending_connection_t *pending_connections;
  struct cached_resolve *next;
};

70
71
72
73
static void purge_expired_resolves(uint32_t now);
static int assign_to_dnsworker(connection_t *exitconn);
static void dns_purge_resolve(struct cached_resolve *resolve);
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
76
static int spawn_dnsworker(void);
static void 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) 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
static int compare_cached_resolves(struct cached_resolve *a,
                                   struct cached_resolve *b) {
86
  /* make this smarter one day? */
87
  return strncmp(a->address, b->address, MAX_ADDRESSLEN);
88
89
90
91
92
}

SPLAY_PROTOTYPE(cache_tree, cached_resolve, node, compare_cached_resolves);
SPLAY_GENERATE(cache_tree, cached_resolve, node, compare_cached_resolves);

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

Roger Dingledine's avatar
Roger Dingledine committed
100
/** Initialize the DNS subsystem; called by the OR process. */
101
102
103
void
dns_init(void)
{
104
  init_cache_tree();
105
  last_rotation_time=time(NULL);
Roger Dingledine's avatar
Roger Dingledine committed
106
  spawn_enough_dnsworkers();
107
}
108

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

121
/** Free all storage held in the DNS cache */
122
123
124
125
126
127
128
129
130
131
132
void
dns_free_all(void)
{
  struct cached_resolve *ptr, *next;
  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);
  }
}

133
/** Linked list of resolved addresses, oldest to newest. */
Roger Dingledine's avatar
Roger Dingledine committed
134
135
static struct cached_resolve *oldest_cached_resolve = NULL;
static struct cached_resolve *newest_cached_resolve = NULL;
136

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

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

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

  buf[0] = answer_type;

  switch (answer_type)
    {
    case RESOLVED_TYPE_IPV4:
      buf[1] = 4;
      set_uint32(buf+2, htonl(conn->addr));
      buflen = 6;
      break;
    case RESOLVED_TYPE_ERROR_TRANSIENT:
    case RESOLVED_TYPE_ERROR:
      buf[1] = 24; /* length of "error resolving hostname" */
Nick Mathewson's avatar
Nick Mathewson committed
201
      strlcpy(buf+2, "error resolving hostname", sizeof(buf)-2);
202
203
204
205
206
      buflen = 26;
      break;
    default:
      tor_assert(0);
    }
207
  connection_edge_send_command(conn, circuit_get_by_edge_conn(conn),
208
209
210
211
                               RELAY_COMMAND_RESOLVED, buf, buflen,
                               conn->cpath_layer);
}

212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
/** 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
insert_resolve(struct cached_resolve *r)
{
  /* 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
228
229
/** 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.
230
 * If resolve failed, unlink exitconn if needed, free it, and return -1.
231
232
233
234
235
236
237
 *
 * 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.
 */
238
239
240
int
dns_resolve(connection_t *exitconn)
{
241
  struct cached_resolve *resolve;
Roger Dingledine's avatar
   
Roger Dingledine committed
242
  struct cached_resolve search;
243
  struct pending_connection_t *pending_connection;
244
  struct in_addr in;
245
  circuit_t *circ;
246
  uint32_t now = time(NULL);
247
  assert_connection_ok(exitconn, 0);
248
  tor_assert(exitconn->s == -1);
249

250
251
252
253
  /* 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);
254
255
    if (exitconn->purpose == EXIT_PURPOSE_RESOLVE)
      send_resolved_cell(exitconn, RESOLVED_TYPE_IPV4);
256
    return 1;
257
258
259
260
  }

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

263
264
265
  /* lower-case exitconn->address, so it's in canonical form */
  tor_strlower(exitconn->address);

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

  /* add us to the pending list */
310
  pending_connection = tor_malloc_zero(sizeof(struct pending_connection_t));
Roger Dingledine's avatar
Roger Dingledine committed
311
312
  pending_connection->conn = exitconn;
  resolve->pending_connections = pending_connection;
313
  exitconn->state = EXIT_CONN_STATE_RESOLVING;
Roger Dingledine's avatar
Roger Dingledine committed
314

315
  insert_resolve(resolve);
Roger Dingledine's avatar
Roger Dingledine committed
316
  return assign_to_dnsworker(exitconn);
317
318
}

Roger Dingledine's avatar
Roger Dingledine committed
319
/** Find or spawn a dns worker process to handle resolving
Nick Mathewson's avatar
Nick Mathewson committed
320
 * <b>exitconn</b>-\>address; tell that dns worker to begin resolving.
321
 */
322
323
324
static int
assign_to_dnsworker(connection_t *exitconn)
{
325
326
  connection_t *dnsconn;
  unsigned char len;
327

Roger Dingledine's avatar
Roger Dingledine committed
328
  tor_assert(exitconn->state == EXIT_CONN_STATE_RESOLVING);
329
  tor_assert(exitconn->s == -1);
330

Roger Dingledine's avatar
Roger Dingledine committed
331
  spawn_enough_dnsworkers(); /* respawn here, to be sure there are enough */
332

333
  dnsconn = connection_get_by_type_state(CONN_TYPE_DNSWORKER, DNSWORKER_STATE_IDLE);
334

335
  if (!dnsconn) {
Roger Dingledine's avatar
Roger Dingledine committed
336
    log_fn(LOG_WARN,"no idle dns workers. Failing.");
337
338
    if (exitconn->purpose == EXIT_PURPOSE_RESOLVE)
      send_resolved_cell(exitconn, RESOLVED_TYPE_ERROR_TRANSIENT);
339
    dns_cancel_pending_resolve(exitconn->address); /* also sends end and frees! */
340
    return -1;
341
342
  }

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

346
  tor_free(dnsconn->address);
347
  dnsconn->address = tor_strdup(exitconn->address);
348
  dnsconn->state = DNSWORKER_STATE_BUSY;
Roger Dingledine's avatar
Roger Dingledine committed
349
  num_dnsworkers_busy++;
350

351
  len = strlen(dnsconn->address);
352
  connection_write_to_buf((char*)&len, 1, dnsconn);
353
  connection_write_to_buf(dnsconn->address, len, dnsconn);
354
355
356
357

  return 0;
}

Nick Mathewson's avatar
Nick Mathewson committed
358
/** Remove <b>conn</b> from the list of connections waiting for conn-\>address.
359
 */
360
361
void
connection_dns_remove(connection_t *conn)
362
363
364
365
366
{
  struct pending_connection_t *pend, *victim;
  struct cached_resolve search;
  struct cached_resolve *resolve;

367
368
369
  tor_assert(conn->type == CONN_TYPE_EXIT);
  tor_assert(conn->state == EXIT_CONN_STATE_RESOLVING);

Nick Mathewson's avatar
Nick Mathewson committed
370
  strlcpy(search.address, conn->address, sizeof(search.address));
371
372

  resolve = SPLAY_FIND(cache_tree, &cache_root, &search);
373
  if (!resolve) {
374
    log_fn(LOG_NOTICE,"Address '%s' is not pending. Dropping.", safe_str(conn->address));
375
376
377
    return;
  }

Roger Dingledine's avatar
Roger Dingledine committed
378
  tor_assert(resolve->pending_connections);
379
380
381
382
  assert_connection_ok(conn,0);

  pend = resolve->pending_connections;

383
  if (pend->conn == conn) {
384
    resolve->pending_connections = pend->next;
385
    tor_free(pend);
386
    log_fn(LOG_DEBUG, "First connection (fd %d) no longer waiting for resolve of '%s'",
387
           conn->s, safe_str(conn->address));
388
389
    return;
  } else {
390
391
    for ( ; pend->next; pend = pend->next) {
      if (pend->next->conn == conn) {
392
393
        victim = pend->next;
        pend->next = victim->next;
394
        tor_free(victim);
395
        log_fn(LOG_DEBUG, "Connection (fd %d) no longer waiting for resolve of '%s'",
396
               conn->s, safe_str(conn->address));
397
398
399
        return; /* more are pending */
      }
    }
Roger Dingledine's avatar
Roger Dingledine committed
400
    tor_assert(0); /* not reachable unless onlyconn not in pending list */
401
402
403
  }
}

Roger Dingledine's avatar
Roger Dingledine committed
404
/** Log an error and abort if conn is waiting for a DNS resolve.
405
 */
406
407
408
void
assert_connection_edge_not_dns_pending(connection_t *conn)
{
409
410
411
412
  struct pending_connection_t *pend;
  struct cached_resolve *resolve;

  SPLAY_FOREACH(resolve, cache_tree, &cache_root) {
413
    for (pend = resolve->pending_connections;
414
415
         pend;
         pend = pend->next) {
Roger Dingledine's avatar
Roger Dingledine committed
416
      tor_assert(pend->conn != conn);
417
418
419
420
    }
  }
}

Roger Dingledine's avatar
Roger Dingledine committed
421
/** Log an error and abort if any connection waiting for a DNS resolve is
422
 * corrupted. */
423
424
425
void
assert_all_pending_dns_resolves_ok(void)
{
426
427
428
429
  struct pending_connection_t *pend;
  struct cached_resolve *resolve;

  SPLAY_FOREACH(resolve, cache_tree, &cache_root) {
430
    for (pend = resolve->pending_connections;
431
432
         pend;
         pend = pend->next) {
433
      assert_connection_ok(pend->conn, 0);
434
435
      tor_assert(pend->conn->s == -1);
      tor_assert(!connection_in_array(pend->conn));
436
437
438
439
    }
  }
}

Nick Mathewson's avatar
Nick Mathewson committed
440
441
442
/** 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.
443
 */
444
445
446
void
dns_cancel_pending_resolve(char *address)
{
447
  struct pending_connection_t *pend;
448
  struct cached_resolve search;
449
  struct cached_resolve *resolve;
450
  connection_t *pendconn;
451
  circuit_t *circ;
452

Nick Mathewson's avatar
Nick Mathewson committed
453
  strlcpy(search.address, address, sizeof(search.address));
454
455

  resolve = SPLAY_FIND(cache_tree, &cache_root, &search);
456
  if (!resolve) {
457
    log_fn(LOG_NOTICE,"Address '%s' is not pending. Dropping.", safe_str(address));
458
459
460
    return;
  }

461
462
  if (!resolve->pending_connections) {
    /* XXX this should never trigger, but sometimes it does */
463
464
    log_fn(LOG_WARN,"Bug: Address '%s' is pending but has no pending connections!",
           safe_str(address));
465
    tor_fragile_assert();
466
467
    return;
  }
Roger Dingledine's avatar
Roger Dingledine committed
468
  tor_assert(resolve->pending_connections);
469

470
471
  /* mark all pending connections to fail */
  log_fn(LOG_DEBUG, "Failing all connections waiting on DNS resolve of '%s'",
472
         safe_str(address));
473
  while (resolve->pending_connections) {
474
    pend = resolve->pending_connections;
475
    pend->conn->state = EXIT_CONN_STATE_RESOLVEFAILED;
476
    pendconn = pend->conn;
477
    tor_assert(pendconn->s == -1);
478
    if (!pendconn->marked_for_close) {
479
480
      connection_edge_end(pendconn, END_STREAM_REASON_RESOURCELIMIT,
                          pendconn->cpath_layer);
481
    }
482
    circ = circuit_get_by_edge_conn(pendconn);
483
484
    if (circ)
      circuit_detach_stream(circ, pendconn);
485
    connection_free(pendconn);
486
487
    resolve->pending_connections = pend->next;
    tor_free(pend);
488
489
  }

490
491
492
  dns_purge_resolve(resolve);
}

Nick Mathewson's avatar
Nick Mathewson committed
493
/** Remove <b>resolve</b> from the cache.
494
 */
495
496
497
static void
dns_purge_resolve(struct cached_resolve *resolve)
{
498
499
  struct cached_resolve *tmp;

500
  /* remove resolve from the linked list */
501
  if (resolve == oldest_cached_resolve) {
502
    oldest_cached_resolve = resolve->next;
503
    if (oldest_cached_resolve == NULL)
504
      newest_cached_resolve = NULL;
505
  } else {
506
    /* FFFF make it a doubly linked list if this becomes too slow */
507
    for (tmp=oldest_cached_resolve; tmp && tmp->next != resolve; tmp=tmp->next) ;
Roger Dingledine's avatar
Roger Dingledine committed
508
    tor_assert(tmp); /* it's got to be in the list, or we screwed up somewhere else */
509
510
    tmp->next = resolve->next; /* unlink it */

511
    if (newest_cached_resolve == resolve)
512
      newest_cached_resolve = tmp;
513
  }
514
515
516
517

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

518
  tor_free(resolve);
519
520
}

Roger Dingledine's avatar
Roger Dingledine committed
521
/** Called on the OR side when a DNS worker tells us the outcome of a DNS
522
 * resolve: tell all pending connections about the result of the lookup, and
Nick Mathewson's avatar
Nick Mathewson committed
523
524
525
526
 * 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}.
527
 */
528
529
530
static void
dns_found_answer(char *address, uint32_t addr, char outcome)
{
531
532
533
  struct pending_connection_t *pend;
  struct cached_resolve search;
  struct cached_resolve *resolve;
534
  connection_t *pendconn;
535
  circuit_t *circ;
536

Nick Mathewson's avatar
Nick Mathewson committed
537
  strlcpy(search.address, address, sizeof(search.address));
538
539

  resolve = SPLAY_FIND(cache_tree, &cache_root, &search);
540
  if (!resolve) {
541
542
    log_fn(LOG_INFO,"Resolved unasked address '%s'; caching anyway.",
           safe_str(address));
543
544
545
546
547
548
    resolve = tor_malloc_zero(sizeof(struct cached_resolve));
    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);
549
    return;
550
551
  }

552
  if (resolve->state != CACHE_STATE_PENDING) {
553
554
    /* XXXX Maybe update addr? or check addr for consistency? Or let
     * VALID replace FAILED? */
Roger Dingledine's avatar
Roger Dingledine committed
555
    log_fn(LOG_NOTICE, "Resolved '%s' which was already resolved; ignoring",
556
           safe_str(address));
Roger Dingledine's avatar
Roger Dingledine committed
557
    tor_assert(resolve->pending_connections == NULL);
558
559
560
561
562
563
    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
564
  /* tor_assert(resolve->state == CACHE_STATE_PENDING); */
565

566
  resolve->addr = addr;
567
  if (outcome == DNS_RESOLVE_SUCCEEDED)
568
569
570
571
    resolve->state = CACHE_STATE_VALID;
  else
    resolve->state = CACHE_STATE_FAILED;

572
  while (resolve->pending_connections) {
573
    pend = resolve->pending_connections;
574
    assert_connection_ok(pend->conn,time(NULL));
575
    pend->conn->addr = resolve->addr;
576
577
    pendconn = pend->conn; /* don't pass complex things to the
                              connection_mark_for_close macro */
578

579
    if (resolve->state == CACHE_STATE_FAILED) {
580
      /* prevent double-remove. */
581
      pendconn->state = EXIT_CONN_STATE_RESOLVEFAILED;
582
      if (pendconn->purpose == EXIT_PURPOSE_CONNECT) {
583
584
        connection_edge_end(pendconn, END_STREAM_REASON_RESOLVEFAILED, pendconn->cpath_layer);
        /* This detach must happen after we send the end cell. */
585
        circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
586
      } else {
587
        send_resolved_cell(pendconn, RESOLVED_TYPE_ERROR);
588
        /* This detach must happen after we send the resolved cell. */
589
        circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
590
      }
591
      connection_free(pendconn);
Roger Dingledine's avatar
Roger Dingledine committed
592
    } else {
593
594
595
596
      if (pendconn->purpose == EXIT_PURPOSE_CONNECT) {
        /* prevent double-remove. */
        pend->conn->state = EXIT_CONN_STATE_CONNECTING;

597
        circ = circuit_get_by_edge_conn(pend->conn);
598
599
600
601
602
        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;
603
        pend->conn->on_circuit = circ;
604
605
606
607
608
609
610
611
        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);
612
        circ = circuit_get_by_edge_conn(pendconn);
613
614
615
616
        tor_assert(circ);
        circuit_detach_stream(circ, pendconn);
        connection_free(pendconn);
      }
Roger Dingledine's avatar
Roger Dingledine committed
617
    }
618
619
    resolve->pending_connections = pend->next;
    tor_free(pend);
620
  }
621

622
  if (outcome == DNS_RESOLVE_FAILED_TRANSIENT) { /* remove from cache */
623
624
    dns_purge_resolve(resolve);
  }
625
626
}

627
628
/******************************************************************/

Nick Mathewson's avatar
Nick Mathewson committed
629
/*
630
 * Connection between OR and dnsworker
Nick Mathewson's avatar
Nick Mathewson committed
631
 */
632

Roger Dingledine's avatar
Roger Dingledine committed
633
/** Write handler: called when we've pushed a request to a dnsworker. */
634
635
636
int
connection_dns_finished_flushing(connection_t *conn)
{
637
638
  tor_assert(conn);
  tor_assert(conn->type == CONN_TYPE_DNSWORKER);
639
640
641
642
  connection_stop_writing(conn);
  return 0;
}

643
644
645
int
connection_dns_reached_eof(connection_t *conn)
{
646
  log_fn(LOG_WARN,"Read eof. Worker died unexpectedly.");
647
  if (conn->state == DNSWORKER_STATE_BUSY) {
648
649
650
651
    /* don't cancel the resolve here -- it would be cancelled in
     * connection_about_to_close_connection(), since conn is still
     * in state BUSY
     */
652
653
654
655
656
657
658
659
    num_dnsworkers_busy--;
  }
  num_dnsworkers--;
  connection_mark_for_close(conn);
  return 0;
}

/** Read handler: called when we get data from a dnsworker. See
660
661
 * if we have a complete answer.  If so, call dns_found_answer on the
 * result.  If not, wait.  Returns 0. */
662
663
664
int
connection_dns_process_inbuf(connection_t *conn)
{
665
  char success;
666
  uint32_t addr;
667

668
669
  tor_assert(conn);
  tor_assert(conn->type == CONN_TYPE_DNSWORKER);
670

671
  if (conn->state != DNSWORKER_STATE_BUSY && buf_datalen(conn->inbuf)) {
672
    log_fn(LOG_WARN,"Bug: read data (%d bytes) from an idle dns worker (fd %d, address '%s'). Please report.",
673
           (int)buf_datalen(conn->inbuf), conn->s, safe_str(conn->address));
674
    tor_fragile_assert();
675
676
677
678
679
680
681
682

    /* 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.)",
683
             success, addr); // XXX safe_str
684
    }
685
686
    return 0;
  }
687
  if (buf_datalen(conn->inbuf) < 5) /* entire answer available? */
688
    return 0; /* not yet */
689
  tor_assert(conn->state == DNSWORKER_STATE_BUSY);
Roger Dingledine's avatar
Roger Dingledine committed
690
  tor_assert(buf_datalen(conn->inbuf) == 5);
691

692
693
  connection_fetch_from_buf(&success,1,conn);
  connection_fetch_from_buf((char *)&addr,sizeof(uint32_t),conn);
694

695
  log_fn(LOG_DEBUG, "DNSWorker (fd %d) returned answer for '%s'",
696
         conn->s, safe_str(conn->address));
697

Roger Dingledine's avatar
Roger Dingledine committed
698
699
  tor_assert(success >= DNS_RESOLVE_FAILED_TRANSIENT);
  tor_assert(success <= DNS_RESOLVE_SUCCEEDED);
700
  dns_found_answer(conn->address, ntohl(addr), success);
701

702
  tor_free(conn->address);
703
  conn->address = tor_strdup("<idle>");
704
  conn->state = DNSWORKER_STATE_IDLE;
Roger Dingledine's avatar
Roger Dingledine committed
705
  num_dnsworkers_busy--;
706
707
708
709
710
  if (conn->timestamp_created < last_rotation_time) {
    connection_mark_for_close(conn);
    num_dnsworkers--;
    spawn_enough_dnsworkers();
  }
711
712
713
  return 0;
}

714
715
716
/** Close and re-open all idle dnsworkers; schedule busy ones to be closed
 * and re-opened once they're no longer busy.
 **/
717
718
void
dnsworkers_rotate(void)
719
720
{
  connection_t *dnsconn;
721
  log_fn(LOG_INFO, "Rotating DNS workers.");
722
723
724
725
726
727
728
729
730
  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);
  spawn_enough_dnsworkers();
}

Roger Dingledine's avatar
Roger Dingledine committed
731
/** Implementation for DNS workers; this code runs in a separate
732
733
734
 * 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
735
736
737
738
739
740
 *    - The OR says:
 *         - ADDRESSLEN [1 byte]
 *         - ADDRESS    [ADDRESSLEN bytes]
 *    - The DNS worker does the lookup, and replies:
 *         - OUTCOME    [1 byte]
 *         - IP         [4 bytes]
741
742
743
744
745
746
747
 *
 * 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.
 */
748
749
750
static int
dnsworker_main(void *data)
{
751
752
  char address[MAX_ADDRESSLEN];
  unsigned char address_len;
753
  char answer[5];
Roger Dingledine's avatar
Roger Dingledine committed
754
  uint32_t ip;
755
  int *fdarray = data;
Roger Dingledine's avatar
Roger Dingledine committed
756
  int fd;
757
  int result;
758

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

761
  fd = fdarray[1]; /* this side is ours */
762
#ifndef TOR_IS_MULTITHREADED
763
  tor_close_socket(fdarray[0]); /* this is the side of the socketpair the parent uses */
764
  tor_free_all(1); /* so the child doesn't hold the parent's fd's open */
765
  handle_signals(0); /* ignore interrupts from the keyboard, etc */
766
767
#endif
  tor_free(data);
768

769
  for (;;) {
770
    int r;
771

772
773
774
775
776
777
778
    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)));
      }
779
      tor_close_socket(fd);
780
      spawn_exit();
781
782
    }

783
    if (address_len && read_all(fd, address, address_len, 1) != address_len) {
784
      log_fn(LOG_ERR,"read hostname failed. Child exiting.");
785
      tor_close_socket(fd);
786
      spawn_exit();
787
    }
788
    address[address_len] = 0; /* null terminate it */
789

790
791
792
793
794
    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) {
795
      case 1:
796
        /* XXX result can never be 1, because we set it to -1 above on error */
797
        log_fn(LOG_INFO,"Could not resolve dest addr %s (transient).",safe_str(address));
798
        answer[0] = DNS_RESOLVE_FAILED_TRANSIENT;
799
800
        break;
      case -1:
801
        log_fn(LOG_INFO,"Could not resolve dest addr %s (permanent).",safe_str(address));
802
        answer[0] = DNS_RESOLVE_FAILED_PERMANENT;
803
        break;
804
      case 0:
805
        log_fn(LOG_INFO,"Resolved address '%s'.",safe_str(address));
806
        answer[0] = DNS_RESOLVE_SUCCEEDED;
807
        break;
808
    }
Roger Dingledine's avatar
Roger Dingledine committed
809
    set_uint32(answer+1, ip);
810
    if (write_all(fd, answer, 5, 1) != 5) {
811
      log_fn(LOG_ERR,"writing answer failed. Child exiting.");
812
      tor_close_socket(fd);
813
814
      spawn_exit();
    }
815
  }
816
  return 0; /* windows wants this function to return an int */
817
818
}

Roger Dingledine's avatar
Roger Dingledine committed
819
/** Launch a new DNS worker; return 0 on success, -1 on failure.
820
 */
821
822
823
static int
spawn_dnsworker(void)
{
824
825
  int *fdarray;
  int fd;
826
  connection_t *conn;
827
  int err;
828

829
  fdarray = tor_malloc(sizeof(int)*2);
830
831
  if ((err = tor_socketpair(AF_UNIX, SOCK_STREAM, 0, fdarray)) < 0) {
    log(LOG_ERR, "Couldn't construct socketpair: %s", tor_socket_strerror(-err));
832
    tor_cleanup();
833
    tor_free(fdarray);
834
835
836
    exit(1);
  }

837
838
839
840
  /* log_fn(LOG_NOTICE,"Before spawn: fdarray @%d has %d:%d", (int)fdarray, fdarray[0],fdarray[1]); */

  fd = fdarray[0]; /* We copy this out here, since dnsworker_main may free fdarray */
  spawn_func(dnsworker_main, (void*)fdarray);
Roger Dingledine's avatar
Roger Dingledine committed
841
  log_fn(LOG_DEBUG,"just spawned a worker.");
842
#ifndef TOR_IS_MULTITHREADED
843
844
  tor_close_socket(fdarray[1]); /* we don't need the worker's side of the pipe */
  tor_free(fdarray);
845
#endif
846
847