dns.c 28 KB
Newer Older
Roger Dingledine's avatar
Roger Dingledine committed
1
2
/* Copyright 2003-2004 Roger Dingledine.
 * Copyright 2004 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
9
10
/**
 * \file dns.c
 * \brief Resolve hostnames in separate processes.
 **/
11

12
13
14
15
16
/* 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.
 */

17
#include "or.h"
18
#include "tree.h"
19

Roger Dingledine's avatar
Roger Dingledine committed
20
/** Longest hostname we're willing to resolve. */
21
22
#define MAX_ADDRESSLEN 256

Roger Dingledine's avatar
Roger Dingledine committed
23
/** Maximum DNS processes to spawn. */
24
#define MAX_DNSWORKERS 100
Roger Dingledine's avatar
Roger Dingledine committed
25
/** Minimum DNS processes to spawn. */
26
#define MIN_DNSWORKERS 3
27

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

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

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

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

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

67
68
69
70
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
71
static int dnsworker_main(void *data);
72
73
static int spawn_dnsworker(void);
static void spawn_enough_dnsworkers(void);
74
static void send_resolved_cell(connection_t *conn, uint8_t answer_type);
75

76
/** Splay tree of cached_resolve objects. */
77
static SPLAY_HEAD(cache_tree, cached_resolve) cache_root;
78

Roger Dingledine's avatar
Roger Dingledine committed
79
/** Function to compare hashed resolves on their addresses; used to
80
 * implement splay trees. */
81
82
static int compare_cached_resolves(struct cached_resolve *a,
                                   struct cached_resolve *b) {
83
  /* make this smarter one day? */
84
  return strncasecmp(a->address, b->address, MAX_ADDRESSLEN);
85
86
87
88
89
}

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

90
/** Initialize the DNS cache. */
91
static void init_cache_tree(void) {
92
93
94
  SPLAY_INIT(&cache_root);
}

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

102
/** Linked list of resolved addresses, oldest to newest. */
Roger Dingledine's avatar
Roger Dingledine committed
103
104
static struct cached_resolve *oldest_cached_resolve = NULL;
static struct cached_resolve *newest_cached_resolve = NULL;
105

Nick Mathewson's avatar
Nick Mathewson committed
106
/** Remove every cached_resolve whose <b>expire</b> time is before <b>now</b>
107
 * from the cache. */
108
109
static void purge_expired_resolves(uint32_t now) {
  struct cached_resolve *resolve;
110
111
  struct pending_connection_t *pend;
  connection_t *pendconn;
112
113
114
115

  /* this is fast because the linked list
   * oldest_cached_resolve is ordered by when they came in.
   */
116
  while (oldest_cached_resolve && (oldest_cached_resolve->expire < now)) {
117
    resolve = oldest_cached_resolve;
118
    log(LOG_DEBUG,"Forgetting old cached resolve (expires %lu)", (unsigned long)resolve->expire);
119
    if (resolve->state == CACHE_STATE_PENDING) {
Roger Dingledine's avatar
Roger Dingledine committed
120
      log_fn(LOG_WARN,"Bug: Expiring a dns resolve that's still pending. Forgot to cull it?");
121
122
123
#ifdef TOR_FRAGILE
      tor_assert(0);
#endif
124
125
126
    }
    if (resolve->pending_connections) {
      log_fn(LOG_WARN, "Closing pending connections on expiring DNS resolve!");
127
128
129
#ifdef TOR_FRAGILE
      tor_assert(0);
#endif
130
131
132
133
134
135
136
137
      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;
        connection_edge_end(pendconn, END_STREAM_REASON_MISC,
                            pendconn->cpath_layer);
138
        circuit_detach_stream(circuit_get_by_conn(pendconn), pendconn);
139
140
141
        connection_free(pendconn);
        tor_free(pend);
      }
142
    }
143
    oldest_cached_resolve = resolve->next;
144
    if (!oldest_cached_resolve) /* if there are no more, */
145
146
      newest_cached_resolve = NULL; /* then make sure the list's tail knows that too */
    SPLAY_REMOVE(cache_tree, &cache_root, resolve);
147
    tor_free(resolve);
148
149
150
  }
}

151
152
153
static void send_resolved_cell(connection_t *conn, uint8_t answer_type)
{
  char buf[RELAY_PAYLOAD_SIZE];
154
  size_t buflen;
155
156
157
158
159
160
161
162
163
164
165
166
167

  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
168
      strlcpy(buf+2, "error resolving hostname", sizeof(buf)-2);
169
170
171
172
173
174
175
176
177
178
      buflen = 26;
      break;
    default:
      tor_assert(0);
    }
  connection_edge_send_command(conn, circuit_get_by_conn(conn),
                               RELAY_COMMAND_RESOLVED, buf, buflen,
                               conn->cpath_layer);
}

179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
/** 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
195
196
/** 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.
197
 * If resolve failed, return -1.
198
199
200
201
202
203
204
205
206
 *
 * 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
207
  struct cached_resolve search;
208
  struct pending_connection_t *pending_connection;
209
  struct in_addr in;
210
  uint32_t now = time(NULL);
211
  assert_connection_ok(exitconn, 0);
212
  tor_assert(exitconn->s == -1);
213

214
215
216
217
218
  /* 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);
    return 1;
219
220
221
222
  }

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

225
  /* now check the tree to see if 'address' is already there. */
Nick Mathewson's avatar
Nick Mathewson committed
226
  strlcpy(search.address, exitconn->address, sizeof(search.address));
Roger Dingledine's avatar
   
Roger Dingledine committed
227
  resolve = SPLAY_FIND(cache_tree, &cache_root, &search);
228
229
  if (resolve) { /* already there */
    switch (resolve->state) {
230
231
      case CACHE_STATE_PENDING:
        /* add us to the pending list */
232
233
        pending_connection = tor_malloc_zero(
                                      sizeof(struct pending_connection_t));
234
        pending_connection->conn = exitconn;
Roger Dingledine's avatar
   
Roger Dingledine committed
235
236
        pending_connection->next = resolve->pending_connections;
        resolve->pending_connections = pending_connection;
237
238
        log_fn(LOG_DEBUG,"Connection (fd %d) waiting for pending DNS resolve of '%s'",
               exitconn->s, exitconn->address);
239
        exitconn->state = EXIT_CONN_STATE_RESOLVING;
Roger Dingledine's avatar
   
Roger Dingledine committed
240
        return 0;
241
      case CACHE_STATE_VALID:
242
        exitconn->addr = resolve->addr;
243
244
        log_fn(LOG_DEBUG,"Connection (fd %d) found cached answer for '%s'",
               exitconn->s, exitconn->address);
245
246
        if (exitconn->purpose == EXIT_PURPOSE_RESOLVE)
          send_resolved_cell(exitconn, RESOLVED_TYPE_IPV4);
247
        return 1;
248
      case CACHE_STATE_FAILED:
249
250
        log_fn(LOG_DEBUG,"Connection (fd %d) found cached error for '%s'",
               exitconn->s, exitconn->address);
251
252
        if (exitconn->purpose == EXIT_PURPOSE_RESOLVE)
          send_resolved_cell(exitconn, RESOLVED_TYPE_ERROR);
253
254
        return -1;
    }
Roger Dingledine's avatar
Roger Dingledine committed
255
    tor_assert(0);
Roger Dingledine's avatar
Roger Dingledine committed
256
257
258
259
  }
  /* not there, need to add it */
  resolve = tor_malloc_zero(sizeof(struct cached_resolve));
  resolve->state = CACHE_STATE_PENDING;
260
  resolve->expire = now + MAX_DNS_ENTRY_AGE;
Nick Mathewson's avatar
Nick Mathewson committed
261
  strlcpy(resolve->address, exitconn->address, sizeof(resolve->address));
Roger Dingledine's avatar
Roger Dingledine committed
262
263

  /* add us to the pending list */
264
  pending_connection = tor_malloc_zero(sizeof(struct pending_connection_t));
Roger Dingledine's avatar
Roger Dingledine committed
265
266
  pending_connection->conn = exitconn;
  resolve->pending_connections = pending_connection;
267
  exitconn->state = EXIT_CONN_STATE_RESOLVING;
Roger Dingledine's avatar
Roger Dingledine committed
268

269
  insert_resolve(resolve);
Roger Dingledine's avatar
Roger Dingledine committed
270
  return assign_to_dnsworker(exitconn);
271
272
}

Roger Dingledine's avatar
Roger Dingledine committed
273
/** Find or spawn a dns worker process to handle resolving
Nick Mathewson's avatar
Nick Mathewson committed
274
 * <b>exitconn</b>-\>address; tell that dns worker to begin resolving.
275
 */
Roger Dingledine's avatar
Roger Dingledine committed
276
static int assign_to_dnsworker(connection_t *exitconn) {
277
278
  connection_t *dnsconn;
  unsigned char len;
279

Roger Dingledine's avatar
Roger Dingledine committed
280
  tor_assert(exitconn->state == EXIT_CONN_STATE_RESOLVING);
281
  tor_assert(exitconn->s == -1);
282

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

285
  dnsconn = connection_get_by_type_state(CONN_TYPE_DNSWORKER, DNSWORKER_STATE_IDLE);
286

287
  if (!dnsconn) {
Roger Dingledine's avatar
Roger Dingledine committed
288
    log_fn(LOG_WARN,"no idle dns workers. Failing.");
289
290
291
    if (exitconn->purpose == EXIT_PURPOSE_RESOLVE)
      send_resolved_cell(exitconn, RESOLVED_TYPE_ERROR_TRANSIENT);
    dns_cancel_pending_resolve(exitconn->address); /* also sends end */
292
    return -1;
293
294
  }

295
296
297
  log_fn(LOG_DEBUG, "Connection (fd %d) needs to resolve '%s'; assigning to DNSWorker (fd %d)",
         exitconn->s, exitconn->address, dnsconn->s);

298
  tor_free(dnsconn->address);
299
  dnsconn->address = tor_strdup(exitconn->address);
300
  dnsconn->state = DNSWORKER_STATE_BUSY;
Roger Dingledine's avatar
Roger Dingledine committed
301
  num_dnsworkers_busy++;
302

303
  len = strlen(dnsconn->address);
304
305
  connection_write_to_buf(&len, 1, dnsconn);
  connection_write_to_buf(dnsconn->address, len, dnsconn);
306

Roger Dingledine's avatar
Roger Dingledine committed
307
//  log_fn(LOG_DEBUG,"submitted '%s'", exitconn->address);
308
309
310
  return 0;
}

Nick Mathewson's avatar
Nick Mathewson committed
311
/** Remove <b>conn</b> from the list of connections waiting for conn-\>address.
312
 */
313
314
315
316
317
318
void connection_dns_remove(connection_t *conn)
{
  struct pending_connection_t *pend, *victim;
  struct cached_resolve search;
  struct cached_resolve *resolve;

319
320
321
  tor_assert(conn->type == CONN_TYPE_EXIT);
  tor_assert(conn->state == EXIT_CONN_STATE_RESOLVING);

Nick Mathewson's avatar
Nick Mathewson committed
322
  strlcpy(search.address, conn->address, sizeof(search.address));
323
324

  resolve = SPLAY_FIND(cache_tree, &cache_root, &search);
325
  if (!resolve) {
Roger Dingledine's avatar
Roger Dingledine committed
326
    log_fn(LOG_NOTICE,"Address '%s' is not pending. Dropping.", conn->address);
327
328
329
    return;
  }

Roger Dingledine's avatar
Roger Dingledine committed
330
  tor_assert(resolve->pending_connections);
331
332
333
334
  assert_connection_ok(conn,0);

  pend = resolve->pending_connections;

335
  if (pend->conn == conn) {
336
    resolve->pending_connections = pend->next;
337
    tor_free(pend);
338
    log_fn(LOG_DEBUG, "First connection (fd %d) no longer waiting for resolve of '%s'",
339
340
341
           conn->s, conn->address);
    return;
  } else {
342
343
    for ( ; pend->next; pend = pend->next) {
      if (pend->next->conn == conn) {
344
345
        victim = pend->next;
        pend->next = victim->next;
346
        tor_free(victim);
347
348
349
350
351
        log_fn(LOG_DEBUG, "Connection (fd %d) no longer waiting for resolve of '%s'",
               conn->s, conn->address);
        return; /* more are pending */
      }
    }
Roger Dingledine's avatar
Roger Dingledine committed
352
    tor_assert(0); /* not reachable unless onlyconn not in pending list */
353
354
355
  }
}

Roger Dingledine's avatar
Roger Dingledine committed
356
/** Log an error and abort if conn is waiting for a DNS resolve.
357
 */
358
359
360
361
362
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) {
363
    for (pend = resolve->pending_connections;
364
365
         pend;
         pend = pend->next) {
Roger Dingledine's avatar
Roger Dingledine committed
366
      tor_assert(pend->conn != conn);
367
368
369
370
    }
  }
}

Roger Dingledine's avatar
Roger Dingledine committed
371
/** Log an error and abort if any connection waiting for a DNS resolve is
372
 * corrupted. */
373
374
375
376
377
void assert_all_pending_dns_resolves_ok(void) {
  struct pending_connection_t *pend;
  struct cached_resolve *resolve;

  SPLAY_FOREACH(resolve, cache_tree, &cache_root) {
378
    for (pend = resolve->pending_connections;
379
380
         pend;
         pend = pend->next) {
381
      assert_connection_ok(pend->conn, 0);
382
383
      tor_assert(pend->conn->s == -1);
      tor_assert(!connection_in_array(pend->conn));
384
385
386
387
    }
  }
}

Nick Mathewson's avatar
Nick Mathewson committed
388
389
390
/** 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.
391
 */
392
393
void dns_cancel_pending_resolve(char *address) {
  struct pending_connection_t *pend;
394
  struct cached_resolve search;
395
  struct cached_resolve *resolve;
396
  connection_t *pendconn;
397
  circuit_t *circ;
398

Nick Mathewson's avatar
Nick Mathewson committed
399
  strlcpy(search.address, address, sizeof(search.address));
400
401

  resolve = SPLAY_FIND(cache_tree, &cache_root, &search);
402
  if (!resolve) {
Roger Dingledine's avatar
Roger Dingledine committed
403
    log_fn(LOG_NOTICE,"Address '%s' is not pending. Dropping.", address);
404
405
406
    return;
  }

407
408
409
  if (!resolve->pending_connections) {
    /* XXX this should never trigger, but sometimes it does */
    log_fn(LOG_WARN,"Bug: Address '%s' is pending but has no pending connections!", address);
410
411
412
#ifdef TOR_FRAGILE
    tor_assert(0);
#endif
413
414
    return;
  }
Roger Dingledine's avatar
Roger Dingledine committed
415
  tor_assert(resolve->pending_connections);
416

417
418
419
  /* mark all pending connections to fail */
  log_fn(LOG_DEBUG, "Failing all connections waiting on DNS resolve of '%s'",
         address);
420
  while (resolve->pending_connections) {
421
    pend = resolve->pending_connections;
422
    pend->conn->state = EXIT_CONN_STATE_RESOLVEFAILED;
423
    pendconn = pend->conn;
424
    tor_assert(pendconn->s == -1);
425
    if (!pendconn->marked_for_close) {
426
427
      connection_edge_end(pendconn, END_STREAM_REASON_RESOURCELIMIT,
                          pendconn->cpath_layer);
428
    }
429
430
431
    circ = circuit_get_by_conn(pendconn);
    if (circ)
      circuit_detach_stream(circ, pendconn);
432
    connection_free(pendconn);
433
434
    resolve->pending_connections = pend->next;
    tor_free(pend);
435
436
  }

437
438
439
  dns_purge_resolve(resolve);
}

Nick Mathewson's avatar
Nick Mathewson committed
440
/** Remove <b>resolve</b> from the cache.
441
 */
442
443
444
static void dns_purge_resolve(struct cached_resolve *resolve) {
  struct cached_resolve *tmp;

445
  /* remove resolve from the linked list */
446
  if (resolve == oldest_cached_resolve) {
447
    oldest_cached_resolve = resolve->next;
448
    if (oldest_cached_resolve == NULL)
449
      newest_cached_resolve = NULL;
450
  } else {
451
    /* FFFF make it a doubly linked list if this becomes too slow */
452
    for (tmp=oldest_cached_resolve; tmp && tmp->next != resolve; tmp=tmp->next) ;
Roger Dingledine's avatar
Roger Dingledine committed
453
    tor_assert(tmp); /* it's got to be in the list, or we screwed up somewhere else */
454
455
    tmp->next = resolve->next; /* unlink it */

456
    if (newest_cached_resolve == resolve)
457
      newest_cached_resolve = tmp;
458
  }
459
460
461
462

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

463
  tor_free(resolve);
464
465
}

Roger Dingledine's avatar
Roger Dingledine committed
466
/** Called on the OR side when a DNS worker tells us the outcome of a DNS
467
 * resolve: tell all pending connections about the result of the lookup, and
Nick Mathewson's avatar
Nick Mathewson committed
468
469
470
471
 * 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}.
472
 */
473
static void dns_found_answer(char *address, uint32_t addr, char outcome) {
474
475
476
  struct pending_connection_t *pend;
  struct cached_resolve search;
  struct cached_resolve *resolve;
477
  connection_t *pendconn;
478
  circuit_t *circ;
479

Nick Mathewson's avatar
Nick Mathewson committed
480
  strlcpy(search.address, address, sizeof(search.address));
481
482

  resolve = SPLAY_FIND(cache_tree, &cache_root, &search);
483
  if (!resolve) {
484
485
486
487
488
489
490
    log_fn(LOG_INFO,"Resolved unasked address '%s'; caching anyway.", address);
    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);
491
    return;
492
493
  }

494
  if (resolve->state != CACHE_STATE_PENDING) {
495
496
    /* XXXX Maybe update addr? or check addr for consistency? Or let
     * VALID replace FAILED? */
Roger Dingledine's avatar
Roger Dingledine committed
497
    log_fn(LOG_NOTICE, "Resolved '%s' which was already resolved; ignoring",
498
           address);
Roger Dingledine's avatar
Roger Dingledine committed
499
    tor_assert(resolve->pending_connections == NULL);
500
501
502
503
504
505
    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
506
  /* tor_assert(resolve->state == CACHE_STATE_PENDING); */
507

508
  resolve->addr = addr;
509
  if (outcome == DNS_RESOLVE_SUCCEEDED)
510
511
512
513
    resolve->state = CACHE_STATE_VALID;
  else
    resolve->state = CACHE_STATE_FAILED;

514
  while (resolve->pending_connections) {
515
    pend = resolve->pending_connections;
516
    assert_connection_ok(pend->conn,time(NULL));
517
    pend->conn->addr = resolve->addr;
518
519
    pendconn = pend->conn; /* don't pass complex things to the
                              connection_mark_for_close macro */
520

521
    if (resolve->state == CACHE_STATE_FAILED) {
522
      /* prevent double-remove. */
523
      pendconn->state = EXIT_CONN_STATE_RESOLVEFAILED;
524
      if (pendconn->purpose == EXIT_PURPOSE_CONNECT) {
525
526
        connection_edge_end(pendconn, END_STREAM_REASON_RESOLVEFAILED, pendconn->cpath_layer);
        /* This detach must happen after we send the end cell. */
527
528
        circuit_detach_stream(circuit_get_by_conn(pendconn), pendconn);
      } else {
529
        send_resolved_cell(pendconn, RESOLVED_TYPE_ERROR);
530
531
532
        /* This detach must happen after we send the resolved cell. */
        circuit_detach_stream(circuit_get_by_conn(pendconn), pendconn);
      }
533
      connection_free(pendconn);
Roger Dingledine's avatar
Roger Dingledine committed
534
    } else {
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
      if (pendconn->purpose == EXIT_PURPOSE_CONNECT) {
        /* prevent double-remove. */
        pend->conn->state = EXIT_CONN_STATE_CONNECTING;

        circ = circuit_get_by_conn(pend->conn);
        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;
        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);
        circ = circuit_get_by_conn(pendconn);
        tor_assert(circ);
        circuit_detach_stream(circ, pendconn);
        connection_free(pendconn);
      }
Roger Dingledine's avatar
Roger Dingledine committed
558
    }
559
560
    resolve->pending_connections = pend->next;
    tor_free(pend);
561
  }
562

563
  if (outcome == DNS_RESOLVE_FAILED_TRANSIENT) { /* remove from cache */
564
565
    dns_purge_resolve(resolve);
  }
566
567
}

568
569
/******************************************************************/

Nick Mathewson's avatar
Nick Mathewson committed
570
/*
571
 * Connection between OR and dnsworker
Nick Mathewson's avatar
Nick Mathewson committed
572
 */
573

Roger Dingledine's avatar
Roger Dingledine committed
574
/** Write handler: called when we've pushed a request to a dnsworker. */
575
int connection_dns_finished_flushing(connection_t *conn) {
576
577
  tor_assert(conn);
  tor_assert(conn->type == CONN_TYPE_DNSWORKER);
578
579
580
581
  connection_stop_writing(conn);
  return 0;
}

582
583
int connection_dns_reached_eof(connection_t *conn) {
  log_fn(LOG_WARN,"Read eof. Worker died unexpectedly.");
584
  if (conn->state == DNSWORKER_STATE_BUSY) {
585
586
587
588
    /* don't cancel the resolve here -- it would be cancelled in
     * connection_about_to_close_connection(), since conn is still
     * in state BUSY
     */
589
590
591
592
593
594
595
596
    num_dnsworkers_busy--;
  }
  num_dnsworkers--;
  connection_mark_for_close(conn);
  return 0;
}

/** Read handler: called when we get data from a dnsworker. See
597
598
 * if we have a complete answer.  If so, call dns_found_answer on the
 * result.  If not, wait.  Returns 0. */
599
int connection_dns_process_inbuf(connection_t *conn) {
600
  char success;
601
  uint32_t addr;
602

603
604
  tor_assert(conn);
  tor_assert(conn->type == CONN_TYPE_DNSWORKER);
605

606
607
  if (conn->state != DNSWORKER_STATE_BUSY && buf_datalen(conn->inbuf)) {
    log_fn(LOG_WARN,"Bug: read data from an idle dns worker.  Please report.");
608
609
610
#ifdef TOR_FRAGILE
    tor_assert(0);
#endif
611
612
    return 0;
  }
613
  if (buf_datalen(conn->inbuf) < 5) /* entire answer available? */
614
    return 0; /* not yet */
615
  tor_assert(conn->state == DNSWORKER_STATE_BUSY);
Roger Dingledine's avatar
Roger Dingledine committed
616
  tor_assert(buf_datalen(conn->inbuf) == 5);
617

618
619
  connection_fetch_from_buf(&success,1,conn);
  connection_fetch_from_buf((char *)&addr,sizeof(uint32_t),conn);
620

621
622
623
  log_fn(LOG_DEBUG, "DNSWorker (fd %d) returned answer for '%s'",
         conn->s, conn->address);

Roger Dingledine's avatar
Roger Dingledine committed
624
625
  tor_assert(success >= DNS_RESOLVE_FAILED_TRANSIENT);
  tor_assert(success <= DNS_RESOLVE_SUCCEEDED);
626
  dns_found_answer(conn->address, ntohl(addr), success);
627

628
  tor_free(conn->address);
629
  conn->address = tor_strdup("<idle>");
630
  conn->state = DNSWORKER_STATE_IDLE;
Roger Dingledine's avatar
Roger Dingledine committed
631
  num_dnsworkers_busy--;
632
633
634
635
636
  if (conn->timestamp_created < last_rotation_time) {
    connection_mark_for_close(conn);
    num_dnsworkers--;
    spawn_enough_dnsworkers();
  }
637
638
639
  return 0;
}

640
641
642
643
644
645
/** 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;
646
  log_fn(LOG_INFO, "Rotating DNS workers.");
647
648
649
650
651
652
653
654
655
  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
656
/** Implementation for DNS workers; this code runs in a separate
657
658
659
 * 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
660
661
662
663
664
665
 *    - The OR says:
 *         - ADDRESSLEN [1 byte]
 *         - ADDRESS    [ADDRESSLEN bytes]
 *    - The DNS worker does the lookup, and replies:
 *         - OUTCOME    [1 byte]
 *         - IP         [4 bytes]
666
667
668
669
670
671
672
 *
 * 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
673
static int dnsworker_main(void *data) {
674
675
  char address[MAX_ADDRESSLEN];
  unsigned char address_len;
676
  char answer[5];
Roger Dingledine's avatar
Roger Dingledine committed
677
  uint32_t ip;
678
  int *fdarray = data;
Roger Dingledine's avatar
Roger Dingledine committed
679
  int fd;
680
  int result;
681

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

684
  fd = fdarray[1]; /* this side is ours */
685
#ifndef TOR_IS_MULTITHREADED
686
  tor_close_socket(fdarray[0]); /* this is the side of the socketpair the parent uses */
687
  connection_free_all(); /* so the child doesn't hold the parent's fd's open */
688
  handle_signals(0); /* ignore interrupts from the keyboard, etc */
689
690
#endif
  tor_free(data);
691

692
  for (;;) {
693
    int r;
694

695
696
697
698
699
700
701
    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)));
      }
702
      spawn_exit();
703
704
    }

705
    if (address_len && read_all(fd, address, address_len, 1) != address_len) {
706
      log_fn(LOG_ERR,"read hostname failed. Child exiting.");
707
      spawn_exit();
708
    }
709
    address[address_len] = 0; /* null terminate it */
710

711
712
713
714
715
    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) {
716
      case 1:
717
        /* XXX result can never be 1, because we set it to -1 above on error */
718
719
        log_fn(LOG_INFO,"Could not resolve dest addr %s (transient).",address);
        answer[0] = DNS_RESOLVE_FAILED_TRANSIENT;
720
721
        break;
      case -1:
722
723
        log_fn(LOG_INFO,"Could not resolve dest addr %s (permanent).",address);
        answer[0] = DNS_RESOLVE_FAILED_PERMANENT;
724
        break;
725
726
727
      case 0:
        log_fn(LOG_INFO,"Resolved address '%s'.",address);
        answer[0] = DNS_RESOLVE_SUCCEEDED;
728
        break;
729
    }
Roger Dingledine's avatar
Roger Dingledine committed
730
    set_uint32(answer+1, ip);
731
    if (write_all(fd, answer, 5, 1) != 5) {
732
733
734
      log_fn(LOG_ERR,"writing answer failed. Child exiting.");
      spawn_exit();
    }
735
  }
736
  return 0; /* windows wants this function to return an int */
737
738
}

Roger Dingledine's avatar
Roger Dingledine committed
739
/** Launch a new DNS worker; return 0 on success, -1 on failure.
740
 */
Roger Dingledine's avatar
Roger Dingledine committed
741
static int spawn_dnsworker(void) {
742
743
  int *fdarray;
  int fd;
744
745
  connection_t *conn;

746
747
  fdarray = tor_malloc(sizeof(int)*2);
  if (tor_socketpair(AF_UNIX, SOCK_STREAM, 0, fdarray) < 0) {
748
749
    log(LOG_ERR, "Couldn't construct socketpair: %s",
        tor_socket_strerror(tor_socket_errno(-1)));
750
    tor_cleanup();
751
    tor_free(fdarray);
752
753
754
    exit(1);
  }

755
756
757
758
  /* 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
759
  log_fn(LOG_DEBUG,"just spawned a worker.");
760
#ifndef TOR_IS_MULTITHREADED
761
762
  tor_close_socket(fdarray[1]); /* we don't need the worker's side of the pipe */
  tor_free(fdarray);
763
#endif
764
765
766

  conn = connection_new(CONN_TYPE_DNSWORKER);

767
  set_socket_nonblocking(fd);
768
769

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

773
  if (connection_add(conn) < 0) { /* no space, forget it */
Roger Dingledine's avatar
Roger Dingledine committed
774
    log_fn(LOG_WARN,"connection_add failed. Giving up.");
775
    connection_free(conn); /* this closes fd */
776
777
778
779
780
781
782
783
784
    return -1;
  }

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

  return 0; /* success */
}

Roger Dingledine's avatar
Roger Dingledine committed
785
/** If we have too many or too few DNS workers, spawn or kill some.
786
 */
Roger Dingledine's avatar
Roger Dingledine committed
787
788
static void spawn_enough_dnsworkers(void) {
  int num_dnsworkers_needed; /* aim to have 1 more than needed,
789
                           * but no less than min and no more than max */
790
791
  connection_t *dnsconn;

792
  /* XXX This may not be the best strategy. Maybe we should queue pending
793
794
795
796
797
798
   *     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
799
   */
800
  if (num_dnsworkers_busy == MAX_DNSWORKERS) {
801
802
803
    /* We always want at least one worker idle.
     * So find the oldest busy worker and kill it.
     */
804
805
    dnsconn = connection_get_by_type_state_lastwritten(CONN_TYPE_DNSWORKER,
                                                       DNSWORKER_STATE_BUSY);
Roger Dingledine's avatar
Roger Dingledine committed
806
    tor_assert(dnsconn);
807

808
809
    log_fn(LOG_WARN, "%d DNS workers are spawned; all are busy. Killing one.",
           MAX_DNSWORKERS);
810

811
    connection_mark_for_close(dnsconn);
Roger Dingledine's avatar
Roger Dingledine committed
812
    num_dnsworkers_busy--;
813
    num_dnsworkers--;
814
  }
815

816
  if (num_dnsworkers_busy >= MIN_DNSWORKERS)
Roger Dingledine's avatar
Roger Dingledine committed
817
    num_dnsworkers_needed = num_dnsworkers_busy+1;
818
  else
Roger Dingledine's avatar
Roger Dingledine committed
819
    num_dnsworkers_needed = MIN_DNSWORKERS;
820

821
822
  while (num_dnsworkers < num_dnsworkers_needed) {
    if (spawn_dnsworker() < 0) {
Roger Dingledine's avatar
Roger Dingledine committed
823
      log(LOG_WARN,"spawn_enough_dnsworkers(): spawn failed!");
824
825
      return;
    }
Roger Dingledine's avatar
Roger Dingledine committed
826
    num_dnsworkers++;
827
828
  }

829
  while (num_dnsworkers > num_dnsworkers_busy+MAX_IDLE_DNSWORKERS) { /* too many idle? */
830
    /* cull excess workers */
Roger Dingledine's avatar
Roger Dingledine committed
831
    log_fn(LOG_NOTICE,"%d of %d dnsworkers are idle. Killing one.",
832
           num_dnsworkers-num_dnsworkers_needed, num_dnsworkers);
833
    dnsconn = connection_get_by_type_state(CONN_TYPE_DNSWORKER, DNSWORKER_STATE_IDLE);
Roger Dingledine's avatar
Roger Dingledine committed
834
    tor_assert(dnsconn);
835
    connection_mark_for_close(dnsconn);
Roger Dingledine's avatar
Roger Dingledine committed
836
    num_dnsworkers--;
837
  }
838
839
}