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
5
/* See LICENSE for licensing information */
/* $Id$ */

Roger Dingledine's avatar
Roger Dingledine committed
6
7
8
9
/**
 * \file dns.c
 * \brief Resolve hostnames in separate processes.
 **/
10

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

278
  dnsconn = connection_get_by_type_state(CONN_TYPE_DNSWORKER, DNSWORKER_STATE_IDLE);
279

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

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

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

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

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

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

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

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

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

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

  pend = resolve->pending_connections;

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

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

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

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

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

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

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

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

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

417
418
419
  dns_purge_resolve(resolve);
}

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

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

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

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

443
  tor_free(resolve);
444
445
}

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

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

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

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

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

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

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

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

548
549
/******************************************************************/

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

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

562
563
int connection_dns_reached_eof(connection_t *conn) {
  log_fn(LOG_WARN,"Read eof. Worker died unexpectedly.");
564
  if (conn->state == DNSWORKER_STATE_BUSY) {
565
566
567
568
569
570
571
572
573
    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
574
575
 * if we have a complete answer.  If so, call dns_found_answer on the
 * result.  If not, wait.  Returns 0. */
576
int connection_dns_process_inbuf(connection_t *conn) {
577
  char success;
578
  uint32_t addr;
579

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

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

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

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

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

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

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

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

662
  for (;;) {
663

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

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

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

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

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

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

  conn = connection_new(CONN_TYPE_DNSWORKER);

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

  /* 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
726
  conn->address = tor_strdup("<unused>");
727

728
  if (connection_add(conn) < 0) { /* no space, forget it */
Roger Dingledine's avatar
Roger Dingledine committed
729
    log_fn(LOG_WARN,"connection_add failed. Giving up.");
730
731
732
733
734
735
736
737
738
739
    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
740
/** If we have too many or too few DNS workers, spawn or kill some.
741
 */
Roger Dingledine's avatar
Roger Dingledine committed
742
743
static void spawn_enough_dnsworkers(void) {
  int num_dnsworkers_needed; /* aim to have 1 more than needed,
744
                           * but no less than min and no more than max */
745
746
  connection_t *dnsconn;

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

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

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

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

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

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