dns.c 26.5 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) {
120
      log_fn(LOG_WARN,"Expiring a dns resolve that's still pending. Forgot to cull it?");
121
122
123
124
125
126
127
128
129
130
131
    }
    if (resolve->pending_connections) {
      log_fn(LOG_WARN, "Closing pending connections on expiring DNS resolve!");
      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);
132
        circuit_detach_stream(circuit_get_by_conn(pendconn), pendconn);
133
134
135
        connection_free(pendconn);
        tor_free(pend);
      }
136
    }
137
    oldest_cached_resolve = resolve->next;
138
    if (!oldest_cached_resolve) /* if there are no more, */
139
140
      newest_cached_resolve = NULL; /* then make sure the list's tail knows that too */
    SPLAY_REMOVE(cache_tree, &cache_root, resolve);
141
    tor_free(resolve);
142
143
144
  }
}

145
146
147
static void send_resolved_cell(connection_t *conn, uint8_t answer_type)
{
  char buf[RELAY_PAYLOAD_SIZE];
148
  size_t buflen;
149
150
151
152
153
154
155
156
157
158
159
160
161

  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
162
      strlcpy(buf+2, "error resolving hostname", sizeof(buf)-2);
163
164
165
166
167
168
169
170
171
172
      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);
}

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

208
209
210
211
212
  /* 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;
213
214
215
216
  }

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

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

  /* add us to the pending list */
258
  pending_connection = tor_malloc_zero(sizeof(struct pending_connection_t));
Roger Dingledine's avatar
Roger Dingledine committed
259
260
  pending_connection->conn = exitconn;
  resolve->pending_connections = pending_connection;
261
  exitconn->state = EXIT_CONN_STATE_RESOLVING;
Roger Dingledine's avatar
Roger Dingledine committed
262

263
  insert_resolve(resolve);
Roger Dingledine's avatar
Roger Dingledine committed
264
  return assign_to_dnsworker(exitconn);
265
266
}

Roger Dingledine's avatar
Roger Dingledine committed
267
/** Find or spawn a dns worker process to handle resolving
Nick Mathewson's avatar
Nick Mathewson committed
268
 * <b>exitconn</b>-\>address; tell that dns worker to begin resolving.
269
 */
Roger Dingledine's avatar
Roger Dingledine committed
270
static int assign_to_dnsworker(connection_t *exitconn) {
271
272
  connection_t *dnsconn;
  unsigned char len;
273

Roger Dingledine's avatar
Roger Dingledine committed
274
  tor_assert(exitconn->state == EXIT_CONN_STATE_RESOLVING);
275
  tor_assert(exitconn->s == -1);
276

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

279
  dnsconn = connection_get_by_type_state(CONN_TYPE_DNSWORKER, DNSWORKER_STATE_IDLE);
280

281
  if (!dnsconn) {
Roger Dingledine's avatar
Roger Dingledine committed
282
    log_fn(LOG_WARN,"no idle dns workers. Failing.");
283
    dns_cancel_pending_resolve(exitconn->address);
284
    send_resolved_cell(exitconn, RESOLVED_TYPE_ERROR_TRANSIENT);
285
    return -1;
286
287
  }

288
289
290
  log_fn(LOG_DEBUG, "Connection (fd %d) needs to resolve '%s'; assigning to DNSWorker (fd %d)",
         exitconn->s, exitconn->address, dnsconn->s);

291
  tor_free(dnsconn->address);
292
  dnsconn->address = tor_strdup(exitconn->address);
293
  dnsconn->state = DNSWORKER_STATE_BUSY;
Roger Dingledine's avatar
Roger Dingledine committed
294
  num_dnsworkers_busy++;
295

296
  len = strlen(dnsconn->address);
297
298
  connection_write_to_buf(&len, 1, dnsconn);
  connection_write_to_buf(dnsconn->address, len, dnsconn);
299

Roger Dingledine's avatar
Roger Dingledine committed
300
//  log_fn(LOG_DEBUG,"submitted '%s'", exitconn->address);
301
302
303
  return 0;
}

Nick Mathewson's avatar
Nick Mathewson committed
304
/** Remove <b>conn</b> from the list of connections waiting for conn-\>address.
305
 */
306
307
308
309
310
311
void connection_dns_remove(connection_t *conn)
{
  struct pending_connection_t *pend, *victim;
  struct cached_resolve search;
  struct cached_resolve *resolve;

312
313
314
  tor_assert(conn->type == CONN_TYPE_EXIT);
  tor_assert(conn->state == EXIT_CONN_STATE_RESOLVING);

Nick Mathewson's avatar
Nick Mathewson committed
315
  strlcpy(search.address, conn->address, sizeof(search.address));
316
317

  resolve = SPLAY_FIND(cache_tree, &cache_root, &search);
318
  if (!resolve) {
319
320
321
322
    log_fn(LOG_WARN,"Address '%s' is not pending. Dropping.", conn->address);
    return;
  }

Roger Dingledine's avatar
Roger Dingledine committed
323
  tor_assert(resolve->pending_connections);
324
325
326
327
  assert_connection_ok(conn,0);

  pend = resolve->pending_connections;

328
  if (pend->conn == conn) {
329
    resolve->pending_connections = pend->next;
330
    tor_free(pend);
331
    log_fn(LOG_DEBUG, "First connection (fd %d) no longer waiting for resolve of '%s'",
332
333
334
           conn->s, conn->address);
    return;
  } else {
335
336
    for ( ; pend->next; pend = pend->next) {
      if (pend->next->conn == conn) {
337
338
        victim = pend->next;
        pend->next = victim->next;
339
        tor_free(victim);
340
341
342
343
344
        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
345
    tor_assert(0); /* not reachable unless onlyconn not in pending list */
346
347
348
  }
}

Roger Dingledine's avatar
Roger Dingledine committed
349
/** Log an error and abort if conn is waiting for a DNS resolve.
350
 */
351
352
353
354
355
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) {
356
    for (pend = resolve->pending_connections;
357
358
         pend;
         pend = pend->next) {
Roger Dingledine's avatar
Roger Dingledine committed
359
      tor_assert(pend->conn != conn);
360
361
362
363
    }
  }
}

Roger Dingledine's avatar
Roger Dingledine committed
364
/** Log an error and abort if any connection waiting for a DNS resolve is
365
 * corrupted. */
366
367
368
369
370
void assert_all_pending_dns_resolves_ok(void) {
  struct pending_connection_t *pend;
  struct cached_resolve *resolve;

  SPLAY_FOREACH(resolve, cache_tree, &cache_root) {
371
    for (pend = resolve->pending_connections;
372
373
         pend;
         pend = pend->next) {
374
      assert_connection_ok(pend->conn, 0);
375
376
      tor_assert(pend->conn->s == -1);
      tor_assert(!connection_in_array(pend->conn));
377
378
379
380
    }
  }
}

Nick Mathewson's avatar
Nick Mathewson committed
381
382
383
/** 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.
384
 */
385
386
void dns_cancel_pending_resolve(char *address) {
  struct pending_connection_t *pend;
387
  struct cached_resolve search;
388
  struct cached_resolve *resolve;
389
  connection_t *pendconn;
390

Nick Mathewson's avatar
Nick Mathewson committed
391
  strlcpy(search.address, address, sizeof(search.address));
392
393

  resolve = SPLAY_FIND(cache_tree, &cache_root, &search);
394
  if (!resolve) {
395
    log_fn(LOG_WARN,"Address '%s' is not pending. Dropping.", address);
396
397
398
    return;
  }

Roger Dingledine's avatar
Roger Dingledine committed
399
  tor_assert(resolve->pending_connections);
400

401
402
403
  /* mark all pending connections to fail */
  log_fn(LOG_DEBUG, "Failing all connections waiting on DNS resolve of '%s'",
         address);
404
  while (resolve->pending_connections) {
405
    pend = resolve->pending_connections;
406
    pend->conn->state = EXIT_CONN_STATE_RESOLVEFAILED;
407
    pendconn = pend->conn;
408
    tor_assert(pendconn->s == -1);
409
    if (!pendconn->marked_for_close) {
410
411
      connection_edge_end(pendconn, END_STREAM_REASON_MISC, pendconn->cpath_layer);
    }
412
    circuit_detach_stream(circuit_get_by_conn(pendconn), pendconn);
413
    connection_free(pendconn);
414
415
    resolve->pending_connections = pend->next;
    tor_free(pend);
416
417
  }

418
419
420
  dns_purge_resolve(resolve);
}

Nick Mathewson's avatar
Nick Mathewson committed
421
/** Remove <b>resolve</b> from the cache.
422
 */
423
424
425
static void dns_purge_resolve(struct cached_resolve *resolve) {
  struct cached_resolve *tmp;

426
  /* remove resolve from the linked list */
427
  if (resolve == oldest_cached_resolve) {
428
    oldest_cached_resolve = resolve->next;
429
    if (oldest_cached_resolve == NULL)
430
      newest_cached_resolve = NULL;
431
  } else {
432
    /* FFFF make it a doubly linked list if this becomes too slow */
433
    for (tmp=oldest_cached_resolve; tmp && tmp->next != resolve; tmp=tmp->next) ;
Roger Dingledine's avatar
Roger Dingledine committed
434
    tor_assert(tmp); /* it's got to be in the list, or we screwed up somewhere else */
435
436
    tmp->next = resolve->next; /* unlink it */

437
    if (newest_cached_resolve == resolve)
438
      newest_cached_resolve = tmp;
439
  }
440
441
442
443

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

444
  tor_free(resolve);
445
446
}

Roger Dingledine's avatar
Roger Dingledine committed
447
/** Called on the OR side when a DNS worker tells us the outcome of a DNS
448
 * resolve: tell all pending connections about the result of the lookup, and
Nick Mathewson's avatar
Nick Mathewson committed
449
450
451
452
 * 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}.
453
 */
454
static void dns_found_answer(char *address, uint32_t addr, char outcome) {
455
456
457
  struct pending_connection_t *pend;
  struct cached_resolve search;
  struct cached_resolve *resolve;
458
  connection_t *pendconn;
459
  circuit_t *circ;
460

Nick Mathewson's avatar
Nick Mathewson committed
461
  strlcpy(search.address, address, sizeof(search.address));
462
463

  resolve = SPLAY_FIND(cache_tree, &cache_root, &search);
464
  if (!resolve) {
465
466
467
468
469
470
471
    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);
472
    return;
473
474
  }

475
  if (resolve->state != CACHE_STATE_PENDING) {
476
477
    /* XXXX Maybe update addr? or check addr for consistency? Or let
     * VALID replace FAILED? */
478
479
    log_fn(LOG_WARN, "Resolved '%s' which was already resolved; ignoring",
           address);
Roger Dingledine's avatar
Roger Dingledine committed
480
    tor_assert(resolve->pending_connections == NULL);
481
482
483
484
485
486
    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
487
  /* tor_assert(resolve->state == CACHE_STATE_PENDING); */
488

489
  resolve->addr = addr;
490
  if (outcome == DNS_RESOLVE_SUCCEEDED)
491
492
493
494
    resolve->state = CACHE_STATE_VALID;
  else
    resolve->state = CACHE_STATE_FAILED;

495
  while (resolve->pending_connections) {
496
    pend = resolve->pending_connections;
497
    assert_connection_ok(pend->conn,time(NULL));
498
    pend->conn->addr = resolve->addr;
499
500
    pendconn = pend->conn; /* don't pass complex things to the
                              connection_mark_for_close macro */
501

502
    if (resolve->state == CACHE_STATE_FAILED) {
503
      /* prevent double-remove. */
504
      pendconn->state = EXIT_CONN_STATE_RESOLVEFAILED;
505
      if (pendconn->purpose == EXIT_PURPOSE_CONNECT) {
506
507
        connection_edge_end(pendconn, END_STREAM_REASON_RESOLVEFAILED, pendconn->cpath_layer);
        /* This detach must happen after we send the end cell. */
508
509
        circuit_detach_stream(circuit_get_by_conn(pendconn), pendconn);
      } else {
510
        send_resolved_cell(pendconn, RESOLVED_TYPE_ERROR);
511
512
513
        /* This detach must happen after we send the resolved cell. */
        circuit_detach_stream(circuit_get_by_conn(pendconn), pendconn);
      }
514
      connection_free(pendconn);
Roger Dingledine's avatar
Roger Dingledine committed
515
    } else {
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
      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
539
    }
540
541
    resolve->pending_connections = pend->next;
    tor_free(pend);
542
  }
543

544
  if (outcome == DNS_RESOLVE_FAILED_TRANSIENT) { /* remove from cache */
545
546
    dns_purge_resolve(resolve);
  }
547
548
}

549
550
/******************************************************************/

Nick Mathewson's avatar
Nick Mathewson committed
551
/*
552
 * Connection between OR and dnsworker
Nick Mathewson's avatar
Nick Mathewson committed
553
 */
554

Roger Dingledine's avatar
Roger Dingledine committed
555
/** Write handler: called when we've pushed a request to a dnsworker. */
556
int connection_dns_finished_flushing(connection_t *conn) {
557
558
  tor_assert(conn);
  tor_assert(conn->type == CONN_TYPE_DNSWORKER);
559
560
561
562
  connection_stop_writing(conn);
  return 0;
}

563
564
int connection_dns_reached_eof(connection_t *conn) {
  log_fn(LOG_WARN,"Read eof. Worker died unexpectedly.");
565
  if (conn->state == DNSWORKER_STATE_BUSY) {
566
567
568
569
570
571
572
573
574
    dns_cancel_pending_resolve(conn->address);
    num_dnsworkers_busy--;
  }
  num_dnsworkers--;
  connection_mark_for_close(conn);
  return 0;
}

/** Read handler: called when we get data from a dnsworker. See
575
576
 * if we have a complete answer.  If so, call dns_found_answer on the
 * result.  If not, wait.  Returns 0. */
577
int connection_dns_process_inbuf(connection_t *conn) {
578
  char success;
579
  uint32_t addr;
580

581
582
  tor_assert(conn);
  tor_assert(conn->type == CONN_TYPE_DNSWORKER);
583

584
  if (conn->state != DNSWORKER_STATE_BUSY) {
585
586
587
    log_fn(LOG_WARN,"Bug: poll() indicated than an idle dns worker was readable. Please report.");
    return 0;
  }
588
  if (buf_datalen(conn->inbuf) < 5) /* entire answer available? */
589
    return 0; /* not yet */
590
  tor_assert(conn->state == DNSWORKER_STATE_BUSY);
Roger Dingledine's avatar
Roger Dingledine committed
591
  tor_assert(buf_datalen(conn->inbuf) == 5);
592

593
594
  connection_fetch_from_buf(&success,1,conn);
  connection_fetch_from_buf((char *)&addr,sizeof(uint32_t),conn);
595

596
597
598
  log_fn(LOG_DEBUG, "DNSWorker (fd %d) returned answer for '%s'",
         conn->s, conn->address);

Roger Dingledine's avatar
Roger Dingledine committed
599
600
  tor_assert(success >= DNS_RESOLVE_FAILED_TRANSIENT);
  tor_assert(success <= DNS_RESOLVE_SUCCEEDED);
601
  dns_found_answer(conn->address, ntohl(addr), success);
602

603
  tor_free(conn->address);
604
  conn->address = tor_strdup("<idle>");
605
  conn->state = DNSWORKER_STATE_IDLE;
Roger Dingledine's avatar
Roger Dingledine committed
606
  num_dnsworkers_busy--;
607
608
609
610
611
  if (conn->timestamp_created < last_rotation_time) {
    connection_mark_for_close(conn);
    num_dnsworkers--;
    spawn_enough_dnsworkers();
  }
612
613
614
  return 0;
}

615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
/** 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;
  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
630
/** Implementation for DNS workers; this code runs in a separate
631
632
633
 * 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
634
635
636
637
638
639
 *    - The OR says:
 *         - ADDRESSLEN [1 byte]
 *         - ADDRESS    [ADDRESSLEN bytes]
 *    - The DNS worker does the lookup, and replies:
 *         - OUTCOME    [1 byte]
 *         - IP         [4 bytes]
640
641
642
643
644
645
646
 *
 * 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
647
static int dnsworker_main(void *data) {
648
649
  char address[MAX_ADDRESSLEN];
  unsigned char address_len;
650
  char answer[5];
Roger Dingledine's avatar
Roger Dingledine committed
651
  uint32_t ip;
652
  int *fdarray = data;
Roger Dingledine's avatar
Roger Dingledine committed
653
  int fd;
654
  int result;
655

656
  tor_close_socket(fdarray[0]); /* this is the side of the socketpair the parent uses */
657
  fd = fdarray[1]; /* this side is ours */
658
#ifndef MS_WINDOWS
659
  connection_free_all(); /* so the child doesn't hold the parent's fd's open */
660
#endif
661
  handle_signals(0); /* ignore interrupts from the keyboard, etc */
662

663
  for (;;) {
664

665
    if (recv(fd, &address_len, 1, 0) != 1) {
666
      log_fn(LOG_INFO,"dnsworker exiting because tor process closed connection (either pruned idle dnsworker or died).");
667
      spawn_exit();
668
669
    }

670
    if (address_len && read_all(fd, address, address_len, 1) != address_len) {
671
      log_fn(LOG_ERR,"read hostname failed. Child exiting.");
672
      spawn_exit();
673
    }
674
    address[address_len] = 0; /* null terminate it */
675

676
677
678
679
680
    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) {
681
      case 1:
682
        /* XXX result can never be 1, because we set it to -1 above on error */
683
684
        log_fn(LOG_INFO,"Could not resolve dest addr %s (transient).",address);
        answer[0] = DNS_RESOLVE_FAILED_TRANSIENT;
685
686
        break;
      case -1:
687
688
        log_fn(LOG_INFO,"Could not resolve dest addr %s (permanent).",address);
        answer[0] = DNS_RESOLVE_FAILED_PERMANENT;
689
        break;
690
691
692
      case 0:
        log_fn(LOG_INFO,"Resolved address '%s'.",address);
        answer[0] = DNS_RESOLVE_SUCCEEDED;
693
        break;
694
    }
Roger Dingledine's avatar
Roger Dingledine committed
695
    set_uint32(answer+1, ip);
696
    if (write_all(fd, answer, 5, 1) != 5) {
697
698
699
      log_fn(LOG_ERR,"writing answer failed. Child exiting.");
      spawn_exit();
    }
700
  }
701
  return 0; /* windows wants this function to return an int */
702
703
}

Roger Dingledine's avatar
Roger Dingledine committed
704
/** Launch a new DNS worker; return 0 on success, -1 on failure.
705
 */
Roger Dingledine's avatar
Roger Dingledine committed
706
static int spawn_dnsworker(void) {
707
708
709
  int fd[2];
  connection_t *conn;

710
  if (tor_socketpair(AF_UNIX, SOCK_STREAM, 0, fd) < 0) {
711
712
    log(LOG_ERR, "Couldn't construct socketpair: %s",
        tor_socket_strerror(tor_socket_errno(-1)));
713
    tor_cleanup();
714
715
716
    exit(1);
  }

717
  spawn_func(dnsworker_main, (void*)fd);
Roger Dingledine's avatar
Roger Dingledine committed
718
  log_fn(LOG_DEBUG,"just spawned a worker.");
719
  tor_close_socket(fd[1]); /* we don't need the worker's side of the pipe */
720
721
722

  conn = connection_new(CONN_TYPE_DNSWORKER);

723
  set_socket_nonblocking(fd[0]);
724
725
726

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

729
  if (connection_add(conn) < 0) { /* no space, forget it */
Roger Dingledine's avatar
Roger Dingledine committed
730
    log_fn(LOG_WARN,"connection_add failed. Giving up.");
731
732
733
734
735
736
737
738
739
740
    connection_free(conn); /* this closes fd[0] */
    return -1;
  }

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

  return 0; /* success */
}

Roger Dingledine's avatar
Roger Dingledine committed
741
/** If we have too many or too few DNS workers, spawn or kill some.
742
 */
Roger Dingledine's avatar
Roger Dingledine committed
743
744
static void spawn_enough_dnsworkers(void) {
  int num_dnsworkers_needed; /* aim to have 1 more than needed,
745
                           * but no less than min and no more than max */
746
747
  connection_t *dnsconn;

748
  /* XXX This may not be the best strategy. Maybe we should queue pending
749
750
751
752
753
754
   *     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
755
   */
756
  if (num_dnsworkers_busy == MAX_DNSWORKERS) {
757
758
759
    /* We always want at least one worker idle.
     * So find the oldest busy worker and kill it.
     */
760
761
    dnsconn = connection_get_by_type_state_lastwritten(CONN_TYPE_DNSWORKER,
                                                       DNSWORKER_STATE_BUSY);
Roger Dingledine's avatar
Roger Dingledine committed
762
    tor_assert(dnsconn);
763

764
765
    log_fn(LOG_WARN, "%d DNS workers are spawned; all are busy. Killing one.",
           MAX_DNSWORKERS);
766

767
    connection_mark_for_close(dnsconn);
Roger Dingledine's avatar
Roger Dingledine committed
768
    num_dnsworkers_busy--;
769
    num_dnsworkers--;
770
  }
771

772
  if (num_dnsworkers_busy >= MIN_DNSWORKERS)
Roger Dingledine's avatar
Roger Dingledine committed
773
    num_dnsworkers_needed = num_dnsworkers_busy+1;
774
  else
Roger Dingledine's avatar
Roger Dingledine committed
775
    num_dnsworkers_needed = MIN_DNSWORKERS;
776

777
778
  while (num_dnsworkers < num_dnsworkers_needed) {
    if (spawn_dnsworker() < 0) {
Roger Dingledine's avatar
Roger Dingledine committed
779
      log(LOG_WARN,"spawn_enough_dnsworkers(): spawn failed!");
780
781
      return;
    }
Roger Dingledine's avatar
Roger Dingledine committed
782
    num_dnsworkers++;
783
784
  }

785
  while (num_dnsworkers > num_dnsworkers_busy+MAX_IDLE_DNSWORKERS) { /* too many idle? */
786
    /* cull excess workers */
787
788
    log_fn(LOG_WARN,"%d of %d dnsworkers are idle. Killing one.",
           num_dnsworkers-num_dnsworkers_needed, num_dnsworkers);
789
    dnsconn = connection_get_by_type_state(CONN_TYPE_DNSWORKER, DNSWORKER_STATE_IDLE);
Roger Dingledine's avatar
Roger Dingledine committed
790
    tor_assert(dnsconn);
791
    connection_mark_for_close(dnsconn);
Roger Dingledine's avatar
Roger Dingledine committed
792
    num_dnsworkers--;
793
  }
794
795
}