dns.c 29.9 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
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_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
static int compare_cached_resolves(cached_resolve_t *a,
                                   cached_resolve_t *b) {
86
  /* make this smarter one day? */
87
  return strncmp(a->address, b->address, MAX_ADDRESSLEN);
88
89
}

90
91
SPLAY_PROTOTYPE(cache_tree, cached_resolve_t, node, compare_cached_resolves);
SPLAY_GENERATE(cache_tree, cached_resolve_t, node, compare_cached_resolves);
92

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
105
  init_cache_tree();
}
106

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

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

131
/** Linked list of resolved addresses, oldest to newest. */
132
133
static cached_resolve_t *oldest_cached_resolve = NULL;
static cached_resolve_t *newest_cached_resolve = NULL;
134

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

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

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

  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
199
      strlcpy(buf+2, "error resolving hostname", sizeof(buf)-2);
200
201
202
203
204
      buflen = 26;
      break;
    default:
      tor_assert(0);
    }
205
  connection_edge_send_command(conn, circuit_get_by_edge_conn(conn),
206
207
208
209
                               RELAY_COMMAND_RESOLVED, buf, buflen,
                               conn->cpath_layer);
}

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

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

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

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

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

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

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

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

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

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

331
  dnsconn = connection_get_by_type_state(CONN_TYPE_DNSWORKER, DNSWORKER_STATE_IDLE);
332

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

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

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

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

  return 0;
}

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

365
366
367
  tor_assert(conn->type == CONN_TYPE_EXIT);
  tor_assert(conn->state == EXIT_CONN_STATE_RESOLVING);

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

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

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

  pend = resolve->pending_connections;

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

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

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

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

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

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

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

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

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

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

488
489
490
  dns_purge_resolve(resolve);
}

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

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

509
    if (newest_cached_resolve == resolve)
510
      newest_cached_resolve = tmp;
511
  }
512
513
514
515

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

516
  tor_free(resolve);
517
518
}

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

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

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

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

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

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

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

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

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

625
626
/******************************************************************/

Nick Mathewson's avatar
Nick Mathewson committed
627
/*
628
 * Connection between OR and dnsworker
Nick Mathewson's avatar
Nick Mathewson committed
629
 */
630

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

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

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

666
667
  tor_assert(conn);
  tor_assert(conn->type == CONN_TYPE_DNSWORKER);
668

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

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

690
691
  connection_fetch_from_buf(&success,1,conn);
  connection_fetch_from_buf((char *)&addr,sizeof(uint32_t),conn);
692

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

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

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

712
713
714
/** Close and re-open all idle dnsworkers; schedule busy ones to be closed
 * and re-opened once they're no longer busy.
 **/
715
716
void
dnsworkers_rotate(void)
717
718
719
720
721
722
723
724
725
726
727
{
  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);
  spawn_enough_dnsworkers();
}

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

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

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

766
  for (;;) {
767
    int r;
768

769
770
771
772
773
774
775
    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)));
      }
776
      tor_close_socket(fd);
777
      spawn_exit();
778
779
    }

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

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

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