dns.c 30 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
static void init_cache_tree(void) {
95
96
97
  SPLAY_INIT(&cache_root);
}

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

105
106
static void
_free_cached_resolve(struct cached_resolve *r) {
Nick Mathewson's avatar
Nick Mathewson committed
107
  while (r->pending_connections) {
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
    struct pending_connection_t *victim = r->pending_connections;
    r->pending_connections = victim->next;
    tor_free(victim);
  }
  tor_free(r);
}

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);
  }
}

126
/** Linked list of resolved addresses, oldest to newest. */
Roger Dingledine's avatar
Roger Dingledine committed
127
128
static struct cached_resolve *oldest_cached_resolve = NULL;
static struct cached_resolve *newest_cached_resolve = NULL;
129

Nick Mathewson's avatar
Nick Mathewson committed
130
/** Remove every cached_resolve whose <b>expire</b> time is before <b>now</b>
131
 * from the cache. */
132
133
static void purge_expired_resolves(uint32_t now) {
  struct cached_resolve *resolve;
134
135
  struct pending_connection_t *pend;
  connection_t *pendconn;
136
137
138
139

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

172
173
174
static void send_resolved_cell(connection_t *conn, uint8_t answer_type)
{
  char buf[RELAY_PAYLOAD_SIZE];
175
  size_t buflen;
176
177
178
179
180
181
182
183
184
185
186
187
188

  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
189
      strlcpy(buf+2, "error resolving hostname", sizeof(buf)-2);
190
191
192
193
194
      buflen = 26;
      break;
    default:
      tor_assert(0);
    }
195
  connection_edge_send_command(conn, circuit_get_by_edge_conn(conn),
196
197
198
199
                               RELAY_COMMAND_RESOLVED, buf, buflen,
                               conn->cpath_layer);
}

200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
/** 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
216
217
/** 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.
218
 * If resolve failed, unlink exitconn if needed, free it, and return -1.
219
220
221
222
223
224
225
226
227
 *
 * 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.
 */
int dns_resolve(connection_t *exitconn) {
  struct cached_resolve *resolve;
Roger Dingledine's avatar
   
Roger Dingledine committed
228
  struct cached_resolve search;
229
  struct pending_connection_t *pending_connection;
230
  struct in_addr in;
231
  circuit_t *circ;
232
  uint32_t now = time(NULL);
233
  assert_connection_ok(exitconn, 0);
234
  tor_assert(exitconn->s == -1);
235

236
237
238
239
  /* 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);
240
241
    if (exitconn->purpose == EXIT_PURPOSE_RESOLVE)
      send_resolved_cell(exitconn, RESOLVED_TYPE_IPV4);
242
    return 1;
243
244
245
246
  }

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

249
250
251
  /* lower-case exitconn->address, so it's in canonical form */
  tor_strlower(exitconn->address);

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

  /* add us to the pending list */
296
  pending_connection = tor_malloc_zero(sizeof(struct pending_connection_t));
Roger Dingledine's avatar
Roger Dingledine committed
297
298
  pending_connection->conn = exitconn;
  resolve->pending_connections = pending_connection;
299
  exitconn->state = EXIT_CONN_STATE_RESOLVING;
Roger Dingledine's avatar
Roger Dingledine committed
300

301
  insert_resolve(resolve);
Roger Dingledine's avatar
Roger Dingledine committed
302
  return assign_to_dnsworker(exitconn);
303
304
}

Roger Dingledine's avatar
Roger Dingledine committed
305
/** Find or spawn a dns worker process to handle resolving
Nick Mathewson's avatar
Nick Mathewson committed
306
 * <b>exitconn</b>-\>address; tell that dns worker to begin resolving.
307
 */
Roger Dingledine's avatar
Roger Dingledine committed
308
static int assign_to_dnsworker(connection_t *exitconn) {
309
310
  connection_t *dnsconn;
  unsigned char len;
311

Roger Dingledine's avatar
Roger Dingledine committed
312
  tor_assert(exitconn->state == EXIT_CONN_STATE_RESOLVING);
313
  tor_assert(exitconn->s == -1);
314

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

317
  dnsconn = connection_get_by_type_state(CONN_TYPE_DNSWORKER, DNSWORKER_STATE_IDLE);
318

319
  if (!dnsconn) {
Roger Dingledine's avatar
Roger Dingledine committed
320
    log_fn(LOG_WARN,"no idle dns workers. Failing.");
321
322
    if (exitconn->purpose == EXIT_PURPOSE_RESOLVE)
      send_resolved_cell(exitconn, RESOLVED_TYPE_ERROR_TRANSIENT);
323
    dns_cancel_pending_resolve(exitconn->address); /* also sends end and frees! */
324
    return -1;
325
326
  }

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

330
  tor_free(dnsconn->address);
331
  dnsconn->address = tor_strdup(exitconn->address);
332
  dnsconn->state = DNSWORKER_STATE_BUSY;
Roger Dingledine's avatar
Roger Dingledine committed
333
  num_dnsworkers_busy++;
334

335
  len = strlen(dnsconn->address);
336
  connection_write_to_buf((char*)&len, 1, dnsconn);
337
  connection_write_to_buf(dnsconn->address, len, dnsconn);
338
339
340
341

  return 0;
}

Nick Mathewson's avatar
Nick Mathewson committed
342
/** Remove <b>conn</b> from the list of connections waiting for conn-\>address.
343
 */
344
345
346
347
348
349
void connection_dns_remove(connection_t *conn)
{
  struct pending_connection_t *pend, *victim;
  struct cached_resolve search;
  struct cached_resolve *resolve;

350
351
352
  tor_assert(conn->type == CONN_TYPE_EXIT);
  tor_assert(conn->state == EXIT_CONN_STATE_RESOLVING);

Nick Mathewson's avatar
Nick Mathewson committed
353
  strlcpy(search.address, conn->address, sizeof(search.address));
354
355

  resolve = SPLAY_FIND(cache_tree, &cache_root, &search);
356
  if (!resolve) {
357
    log_fn(LOG_NOTICE,"Address '%s' is not pending. Dropping.", safe_str(conn->address));
358
359
360
    return;
  }

Roger Dingledine's avatar
Roger Dingledine committed
361
  tor_assert(resolve->pending_connections);
362
363
364
365
  assert_connection_ok(conn,0);

  pend = resolve->pending_connections;

366
  if (pend->conn == conn) {
367
    resolve->pending_connections = pend->next;
368
    tor_free(pend);
369
    log_fn(LOG_DEBUG, "First connection (fd %d) no longer waiting for resolve of '%s'",
370
           conn->s, safe_str(conn->address));
371
372
    return;
  } else {
373
374
    for ( ; pend->next; pend = pend->next) {
      if (pend->next->conn == conn) {
375
376
        victim = pend->next;
        pend->next = victim->next;
377
        tor_free(victim);
378
        log_fn(LOG_DEBUG, "Connection (fd %d) no longer waiting for resolve of '%s'",
379
               conn->s, safe_str(conn->address));
380
381
382
        return; /* more are pending */
      }
    }
Roger Dingledine's avatar
Roger Dingledine committed
383
    tor_assert(0); /* not reachable unless onlyconn not in pending list */
384
385
386
  }
}

Roger Dingledine's avatar
Roger Dingledine committed
387
/** Log an error and abort if conn is waiting for a DNS resolve.
388
 */
389
390
391
392
393
void assert_connection_edge_not_dns_pending(connection_t *conn) {
  struct pending_connection_t *pend;
  struct cached_resolve *resolve;

  SPLAY_FOREACH(resolve, cache_tree, &cache_root) {
394
    for (pend = resolve->pending_connections;
395
396
         pend;
         pend = pend->next) {
Roger Dingledine's avatar
Roger Dingledine committed
397
      tor_assert(pend->conn != conn);
398
399
400
401
    }
  }
}

Roger Dingledine's avatar
Roger Dingledine committed
402
/** Log an error and abort if any connection waiting for a DNS resolve is
403
 * corrupted. */
404
405
406
407
408
void assert_all_pending_dns_resolves_ok(void) {
  struct pending_connection_t *pend;
  struct cached_resolve *resolve;

  SPLAY_FOREACH(resolve, cache_tree, &cache_root) {
409
    for (pend = resolve->pending_connections;
410
411
         pend;
         pend = pend->next) {
412
      assert_connection_ok(pend->conn, 0);
413
414
      tor_assert(pend->conn->s == -1);
      tor_assert(!connection_in_array(pend->conn));
415
416
417
418
    }
  }
}

Nick Mathewson's avatar
Nick Mathewson committed
419
420
421
/** 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.
422
 */
423
424
void dns_cancel_pending_resolve(char *address) {
  struct pending_connection_t *pend;
425
  struct cached_resolve search;
426
  struct cached_resolve *resolve;
427
  connection_t *pendconn;
428
  circuit_t *circ;
429

Nick Mathewson's avatar
Nick Mathewson committed
430
  strlcpy(search.address, address, sizeof(search.address));
431
432

  resolve = SPLAY_FIND(cache_tree, &cache_root, &search);
433
  if (!resolve) {
434
    log_fn(LOG_NOTICE,"Address '%s' is not pending. Dropping.", safe_str(address));
435
436
437
    return;
  }

438
439
  if (!resolve->pending_connections) {
    /* XXX this should never trigger, but sometimes it does */
440
441
    log_fn(LOG_WARN,"Bug: Address '%s' is pending but has no pending connections!",
           safe_str(address));
442
    tor_fragile_assert();
443
444
    return;
  }
Roger Dingledine's avatar
Roger Dingledine committed
445
  tor_assert(resolve->pending_connections);
446

447
448
  /* mark all pending connections to fail */
  log_fn(LOG_DEBUG, "Failing all connections waiting on DNS resolve of '%s'",
449
         safe_str(address));
450
  while (resolve->pending_connections) {
451
    pend = resolve->pending_connections;
452
    pend->conn->state = EXIT_CONN_STATE_RESOLVEFAILED;
453
    pendconn = pend->conn;
454
    tor_assert(pendconn->s == -1);
455
    if (!pendconn->marked_for_close) {
456
457
      connection_edge_end(pendconn, END_STREAM_REASON_RESOURCELIMIT,
                          pendconn->cpath_layer);
458
    }
459
    circ = circuit_get_by_edge_conn(pendconn);
460
461
    if (circ)
      circuit_detach_stream(circ, pendconn);
462
    connection_free(pendconn);
463
464
    resolve->pending_connections = pend->next;
    tor_free(pend);
465
466
  }

467
468
469
  dns_purge_resolve(resolve);
}

Nick Mathewson's avatar
Nick Mathewson committed
470
/** Remove <b>resolve</b> from the cache.
471
 */
472
473
474
static void dns_purge_resolve(struct cached_resolve *resolve) {
  struct cached_resolve *tmp;

475
  /* remove resolve from the linked list */
476
  if (resolve == oldest_cached_resolve) {
477
    oldest_cached_resolve = resolve->next;
478
    if (oldest_cached_resolve == NULL)
479
      newest_cached_resolve = NULL;
480
  } else {
481
    /* FFFF make it a doubly linked list if this becomes too slow */
482
    for (tmp=oldest_cached_resolve; tmp && tmp->next != resolve; tmp=tmp->next) ;
Roger Dingledine's avatar
Roger Dingledine committed
483
    tor_assert(tmp); /* it's got to be in the list, or we screwed up somewhere else */
484
485
    tmp->next = resolve->next; /* unlink it */

486
    if (newest_cached_resolve == resolve)
487
      newest_cached_resolve = tmp;
488
  }
489
490
491
492

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

493
  tor_free(resolve);
494
495
}

Roger Dingledine's avatar
Roger Dingledine committed
496
/** Called on the OR side when a DNS worker tells us the outcome of a DNS
497
 * resolve: tell all pending connections about the result of the lookup, and
Nick Mathewson's avatar
Nick Mathewson committed
498
499
500
501
 * 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}.
502
 */
503
static void dns_found_answer(char *address, uint32_t addr, char outcome) {
504
505
506
  struct pending_connection_t *pend;
  struct cached_resolve search;
  struct cached_resolve *resolve;
507
  connection_t *pendconn;
508
  circuit_t *circ;
509

Nick Mathewson's avatar
Nick Mathewson committed
510
  strlcpy(search.address, address, sizeof(search.address));
511
512

  resolve = SPLAY_FIND(cache_tree, &cache_root, &search);
513
  if (!resolve) {
514
515
    log_fn(LOG_INFO,"Resolved unasked address '%s'; caching anyway.",
           safe_str(address));
516
517
518
519
520
521
    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);
522
    return;
523
524
  }

525
  if (resolve->state != CACHE_STATE_PENDING) {
526
527
    /* XXXX Maybe update addr? or check addr for consistency? Or let
     * VALID replace FAILED? */
Roger Dingledine's avatar
Roger Dingledine committed
528
    log_fn(LOG_NOTICE, "Resolved '%s' which was already resolved; ignoring",
529
           safe_str(address));
Roger Dingledine's avatar
Roger Dingledine committed
530
    tor_assert(resolve->pending_connections == NULL);
531
532
533
534
535
536
    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
537
  /* tor_assert(resolve->state == CACHE_STATE_PENDING); */
538

539
  resolve->addr = addr;
540
  if (outcome == DNS_RESOLVE_SUCCEEDED)
541
542
543
544
    resolve->state = CACHE_STATE_VALID;
  else
    resolve->state = CACHE_STATE_FAILED;

545
  while (resolve->pending_connections) {
546
    pend = resolve->pending_connections;
547
    assert_connection_ok(pend->conn,time(NULL));
548
    pend->conn->addr = resolve->addr;
549
550
    pendconn = pend->conn; /* don't pass complex things to the
                              connection_mark_for_close macro */
551

552
    if (resolve->state == CACHE_STATE_FAILED) {
553
      /* prevent double-remove. */
554
      pendconn->state = EXIT_CONN_STATE_RESOLVEFAILED;
555
      if (pendconn->purpose == EXIT_PURPOSE_CONNECT) {
556
557
        connection_edge_end(pendconn, END_STREAM_REASON_RESOLVEFAILED, pendconn->cpath_layer);
        /* This detach must happen after we send the end cell. */
558
        circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
559
      } else {
560
        send_resolved_cell(pendconn, RESOLVED_TYPE_ERROR);
561
        /* This detach must happen after we send the resolved cell. */
562
        circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
563
      }
564
      connection_free(pendconn);
Roger Dingledine's avatar
Roger Dingledine committed
565
    } else {
566
567
568
569
      if (pendconn->purpose == EXIT_PURPOSE_CONNECT) {
        /* prevent double-remove. */
        pend->conn->state = EXIT_CONN_STATE_CONNECTING;

570
        circ = circuit_get_by_edge_conn(pend->conn);
571
572
573
574
575
        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;
576
        pend->conn->on_circuit = circ;
577
578
579
580
581
582
583
584
        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);
585
        circ = circuit_get_by_edge_conn(pendconn);
586
587
588
589
        tor_assert(circ);
        circuit_detach_stream(circ, pendconn);
        connection_free(pendconn);
      }
Roger Dingledine's avatar
Roger Dingledine committed
590
    }
591
592
    resolve->pending_connections = pend->next;
    tor_free(pend);
593
  }
594

595
  if (outcome == DNS_RESOLVE_FAILED_TRANSIENT) { /* remove from cache */
596
597
    dns_purge_resolve(resolve);
  }
598
599
}

600
601
/******************************************************************/

Nick Mathewson's avatar
Nick Mathewson committed
602
/*
603
 * Connection between OR and dnsworker
Nick Mathewson's avatar
Nick Mathewson committed
604
 */
605

Roger Dingledine's avatar
Roger Dingledine committed
606
/** Write handler: called when we've pushed a request to a dnsworker. */
607
int connection_dns_finished_flushing(connection_t *conn) {
608
609
  tor_assert(conn);
  tor_assert(conn->type == CONN_TYPE_DNSWORKER);
610
611
612
613
  connection_stop_writing(conn);
  return 0;
}

614
615
int connection_dns_reached_eof(connection_t *conn) {
  log_fn(LOG_WARN,"Read eof. Worker died unexpectedly.");
616
  if (conn->state == DNSWORKER_STATE_BUSY) {
617
618
619
620
    /* don't cancel the resolve here -- it would be cancelled in
     * connection_about_to_close_connection(), since conn is still
     * in state BUSY
     */
621
622
623
624
625
626
627
628
    num_dnsworkers_busy--;
  }
  num_dnsworkers--;
  connection_mark_for_close(conn);
  return 0;
}

/** Read handler: called when we get data from a dnsworker. See
629
630
 * if we have a complete answer.  If so, call dns_found_answer on the
 * result.  If not, wait.  Returns 0. */
631
int connection_dns_process_inbuf(connection_t *conn) {
632
  char success;
633
  uint32_t addr;
634

635
636
  tor_assert(conn);
  tor_assert(conn->type == CONN_TYPE_DNSWORKER);
637

638
  if (conn->state != DNSWORKER_STATE_BUSY && buf_datalen(conn->inbuf)) {
639
    log_fn(LOG_WARN,"Bug: read data (%d bytes) from an idle dns worker (fd %d, address '%s'). Please report.",
640
           (int)buf_datalen(conn->inbuf), conn->s, safe_str(conn->address));
641
    tor_fragile_assert();
642
643
644
645
646
647
648
649

    /* 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.)",
650
             success, addr); // XXX safe_str
651
    }
652
653
    return 0;
  }
654
  if (buf_datalen(conn->inbuf) < 5) /* entire answer available? */
655
    return 0; /* not yet */
656
  tor_assert(conn->state == DNSWORKER_STATE_BUSY);
Roger Dingledine's avatar
Roger Dingledine committed
657
  tor_assert(buf_datalen(conn->inbuf) == 5);
658

659
660
  connection_fetch_from_buf(&success,1,conn);
  connection_fetch_from_buf((char *)&addr,sizeof(uint32_t),conn);
661

662
  log_fn(LOG_DEBUG, "DNSWorker (fd %d) returned answer for '%s'",
663
         conn->s, safe_str(conn->address));
664

Roger Dingledine's avatar
Roger Dingledine committed
665
666
  tor_assert(success >= DNS_RESOLVE_FAILED_TRANSIENT);
  tor_assert(success <= DNS_RESOLVE_SUCCEEDED);
667
  dns_found_answer(conn->address, ntohl(addr), success);
668

669
  tor_free(conn->address);
670
  conn->address = tor_strdup("<idle>");
671
  conn->state = DNSWORKER_STATE_IDLE;
Roger Dingledine's avatar
Roger Dingledine committed
672
  num_dnsworkers_busy--;
673
674
675
676
677
  if (conn->timestamp_created < last_rotation_time) {
    connection_mark_for_close(conn);
    num_dnsworkers--;
    spawn_enough_dnsworkers();
  }
678
679
680
  return 0;
}

681
682
683
684
685
686
/** Close and re-open all idle dnsworkers; schedule busy ones to be closed
 * and re-opened once they're no longer busy.
 **/
void dnsworkers_rotate(void)
{
  connection_t *dnsconn;
687
  log_fn(LOG_INFO, "Rotating DNS workers.");
688
689
690
691
692
693
694
695
696
  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
697
/** Implementation for DNS workers; this code runs in a separate
698
699
700
 * 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
701
702
703
704
705
706
 *    - The OR says:
 *         - ADDRESSLEN [1 byte]
 *         - ADDRESS    [ADDRESSLEN bytes]
 *    - The DNS worker does the lookup, and replies:
 *         - OUTCOME    [1 byte]
 *         - IP         [4 bytes]
707
708
709
710
711
712
713
 *
 * 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.
 */
Nick Mathewson's avatar
Nick Mathewson committed
714
static int dnsworker_main(void *data) {
715
716
  char address[MAX_ADDRESSLEN];
  unsigned char address_len;
717
  char answer[5];
Roger Dingledine's avatar
Roger Dingledine committed
718
  uint32_t ip;
719
  int *fdarray = data;
Roger Dingledine's avatar
Roger Dingledine committed
720
  int fd;
721
  int result;
722

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

725
  fd = fdarray[1]; /* this side is ours */
726
#ifndef TOR_IS_MULTITHREADED
727
  tor_close_socket(fdarray[0]); /* this is the side of the socketpair the parent uses */
728
  tor_free_all(1); /* so the child doesn't hold the parent's fd's open */
729
  handle_signals(0); /* ignore interrupts from the keyboard, etc */
730
731
#endif
  tor_free(data);
732

733
  for (;;) {
734
    int r;
735

736
737
738
739
740
741
742
    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)));
      }
743
      tor_close_socket(fd);
744
      spawn_exit();
745
746
    }

747
    if (address_len && read_all(fd, address, address_len, 1) != address_len) {
748
      log_fn(LOG_ERR,"read hostname failed. Child exiting.");
749
      tor_close_socket(fd);
750
      spawn_exit();
751
    }
752
    address[address_len] = 0; /* null terminate it */
753

754
755
756
757
758
    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) {
759
      case 1:
760
        /* XXX result can never be 1, because we set it to -1 above on error */
761
        log_fn(LOG_INFO,"Could not resolve dest addr %s (transient).",safe_str(address));
762
        answer[0] = DNS_RESOLVE_FAILED_TRANSIENT;
763
764
        break;
      case -1:
765
        log_fn(LOG_INFO,"Could not resolve dest addr %s (permanent).",safe_str(address));
766
        answer[0] = DNS_RESOLVE_FAILED_PERMANENT;
767
        break;
768
      case 0:
769
        log_fn(LOG_INFO,"Resolved address '%s'.",safe_str(address));
770
        answer[0] = DNS_RESOLVE_SUCCEEDED;
771
        break;
772
    }
Roger Dingledine's avatar
Roger Dingledine committed
773
    set_uint32(answer+1, ip);
774
    if (write_all(fd, answer, 5, 1) != 5) {
775
      log_fn(LOG_ERR,"writing answer failed. Child exiting.");
776
      tor_close_socket(fd);
777
778
      spawn_exit();
    }
779
  }
780
  return 0; /* windows wants this function to return an int */
781
782
}

Roger Dingledine's avatar
Roger Dingledine committed
783
/** Launch a new DNS worker; return 0 on success, -1 on failure.
784
 */
Roger Dingledine's avatar
Roger Dingledine committed
785
static int spawn_dnsworker(void) {
786
787
  int *fdarray;
  int fd;
788
789
  connection_t *conn;

790
791
  fdarray = tor_malloc(sizeof(int)*2);
  if (tor_socketpair(AF_UNIX, SOCK_STREAM, 0, fdarray) < 0) {
792
793
    log(LOG_ERR, "Couldn't construct socketpair: %s",
        tor_socket_strerror(tor_socket_errno(-1)));
794
    tor_cleanup();
795
    tor_free(fdarray);
796
797
798
    exit(1);
  }

799
800
801
802
  /* 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
803
  log_fn(LOG_DEBUG,"just spawned a worker.");
804
#ifndef TOR_IS_MULTITHREADED
805
806
  tor_close_socket(fdarray[1]); /* we don't need the worker's side of the pipe */
  tor_free(fdarray);
807
#endif
808
809
810

  conn = connection_new(CONN_TYPE_DNSWORKER);

811
  set_socket_nonblocking(fd);
812
813

  /* set up conn so it's got all the data we need to remember */
814
  conn->s = fd;
Roger Dingledine's avatar
Roger Dingledine committed
815
  conn->address = tor_strdup("<unused>");
816

817
  if (connection_add(conn) < 0) { /* no space, forget it */
Roger Dingledine's avatar
Roger Dingledine committed
818
    log_fn(LOG_WARN,"connection_add failed. Giving up.");
819
    connection_free(conn); /* this closes fd */
820
821
822
823
824
825
826
827
828
    return -1;
  }

  conn->state = DNSWORKER_STATE_IDLE;
  connection_start_reading(conn);

  return 0; /* success */
}

Roger Dingledine's avatar
Roger Dingledine committed
829
/** If we have too many or too few DNS workers, spawn or kill some.
830
 */
Roger Dingledine's avatar
Roger Dingledine committed
831
832
static void spawn_enough_dnsworkers(void) {
  int num_dnsworkers_needed; /* aim to have 1 more than needed,
833
                           * but no less than min and no more than max */
834
835
  connection_t *dnsconn;

836
  /* XXX This may not be the best strategy. Maybe we should queue pending
837
838
839
840
841
842
   *     requests until the old ones finish or time out: otherwise, if
   *     the connection requests come fast enough, we never get any DNS done. -NM
   * XXX But if we queue them, then the adversary can pile even more
   *     queries onto us, blocking legitimate requests for even longer.
   *     Maybe we should compromise and only kill if it's been at it for
   *     more than, e.g., 2 seconds. -RD
843
   */
844
  if (num_dnsworkers_busy == MAX_DNSWORKERS) {