dns.c 22 KB
Newer Older
1
2
3
4
/* Copyright 2003 Roger Dingledine. */
/* See LICENSE for licensing information */
/* $Id$ */

5
6
7
8
/*****
 * dns.c: Resolve hostnames in separate processes.
 *****/

9
10
11
12
13
/* 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.
 */

14
#include "or.h"
15
#include "tree.h"
16

Roger Dingledine's avatar
Roger Dingledine committed
17
18
extern or_options_t options; /* command-line and config-file options */

19
/* Longest hostname we're willing to resolve. */
20
21
#define MAX_ADDRESSLEN 256

22
/* Maximum DNS processes to spawn. */
23
#define MAX_DNSWORKERS 50
24
/* Minimum DNS processes to spawn. */
25
#define MIN_DNSWORKERS 3
26
27

/* If more than this many processes are idle, shut down the extras. */
28
#define MAX_IDLE_DNSWORKERS 10
29

30
31
/* Possible outcomes from hostname lookup: permanent failure,
 * 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

Roger Dingledine's avatar
Roger Dingledine committed
36
37
int num_dnsworkers=0;
int num_dnsworkers_busy=0;
38

39
/* Linked list of connections waiting for a DNS answer. */
40
41
42
43
44
struct pending_connection_t {
  struct connection_t *conn;
  struct pending_connection_t *next;
};

45
46
47
48
/* A DNS request: possibly completed, possibly pending; cached_resolve
 * structs are stored at the OR side in a splay tree, and as a linked
 * list from oldest to newest.
 */
49
50
struct cached_resolve {
  SPLAY_ENTRY(cached_resolve) node;
51
52
  char address[MAX_ADDRESSLEN]; /* the hostname to be resolved */
  uint32_t addr; /* in host order. I know I'm horrible for assuming ipv4 */
53
54
55
56
  char state; /* 0 is pending; 1 means answer is valid; 2 means resolve failed */
#define CACHE_STATE_PENDING 0
#define CACHE_STATE_VALID 1
#define CACHE_STATE_FAILED 2
57
  uint32_t expire; /* remove items from cache after this time */
58
59
60
61
  struct pending_connection_t *pending_connections;
  struct cached_resolve *next;
};

62
63
64
65
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);
int dnsworker_main(void *data);
static int spawn_dnsworker(void);
static void spawn_enough_dnsworkers(void);

70
/* Splay tree of cached_resolve objects */
71
static SPLAY_HEAD(cache_tree, cached_resolve) cache_root;
72

73
74
/* Function to compare hashed resolves on their addresses; used to
 * implement splay trees. */
75
76
static int compare_cached_resolves(struct cached_resolve *a,
                                   struct cached_resolve *b) {
77
  /* make this smarter one day? */
78
  return strncasecmp(a->address, b->address, MAX_ADDRESSLEN);
79
80
81
82
83
}

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

84
/* Initialize the DNS cache */
85
static void init_cache_tree(void) {
86
87
88
  SPLAY_INIT(&cache_root);
}

89
/* Initialize the DNS subsystem; called by the OR process. */
90
91
void dns_init(void) {
  init_cache_tree();
Roger Dingledine's avatar
Roger Dingledine committed
92
  spawn_enough_dnsworkers();
93
}
94

95
96
97
static struct cached_resolve *oldest_cached_resolve = NULL; /* linked list, */
static struct cached_resolve *newest_cached_resolve = NULL; /* oldest to newest */

98
99
/* Remove every cached_resolve whose 'expire' time is before 'now'
 * from the cache. */
100
101
102
103
104
105
106
107
static void purge_expired_resolves(uint32_t now) {
  struct cached_resolve *resolve;

  /* this is fast because the linked list
   * oldest_cached_resolve is ordered by when they came in.
   */
  while(oldest_cached_resolve && (oldest_cached_resolve->expire < now)) {
    resolve = oldest_cached_resolve;
108
    log(LOG_DEBUG,"Forgetting old cached resolve (expires %lu)", (unsigned long)resolve->expire);
109
110
111
112
113
114
    if(resolve->state == CACHE_STATE_PENDING) {
      log_fn(LOG_WARN,"Expiring a dns resolve that's still pending. Forgot to cull it?");
      /* XXX if resolve->pending_connections is used, then we're probably
       * introducing bugs by closing resolve without notifying those streams.
       */
    }
115
116
117
118
    oldest_cached_resolve = resolve->next;
    if(!oldest_cached_resolve) /* if there are no more, */
      newest_cached_resolve = NULL; /* then make sure the list's tail knows that too */
    SPLAY_REMOVE(cache_tree, &cache_root, resolve);
119
    tor_free(resolve);
120
121
122
  }
}

123
/* See if we have a cache entry for 'exitconn->address'. if so,
124
125
 * if resolve valid, put it into exitconn->addr and return 1.
 * If resolve failed, return -1.
126
127
128
129
130
131
132
133
134
 *
 * 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
135
  struct cached_resolve search;
136
  struct pending_connection_t *pending_connection;
137
  struct in_addr in;
138
  uint32_t now = time(NULL);
139
  assert_connection_ok(exitconn, 0);
140

141
142
143
144
145
  /* 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;
146
147
148
149
  }

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

152
153
  /* now check the tree to see if 'address' is already there. */
  strncpy(search.address, exitconn->address, MAX_ADDRESSLEN);
154
  search.address[MAX_ADDRESSLEN-1] = 0;
Roger Dingledine's avatar
   
Roger Dingledine committed
155
  resolve = SPLAY_FIND(cache_tree, &cache_root, &search);
156
  if(resolve) { /* already there */
157
158
159
    switch(resolve->state) {
      case CACHE_STATE_PENDING:
        /* add us to the pending list */
160
        pending_connection = tor_malloc(sizeof(struct pending_connection_t));
161
        pending_connection->conn = exitconn;
Roger Dingledine's avatar
   
Roger Dingledine committed
162
163
        pending_connection->next = resolve->pending_connections;
        resolve->pending_connections = pending_connection;
164
165
        log_fn(LOG_DEBUG,"Connection (fd %d) waiting for pending DNS resolve of '%s'",
               exitconn->s, exitconn->address);
166
        exitconn->state = EXIT_CONN_STATE_RESOLVING;
Roger Dingledine's avatar
   
Roger Dingledine committed
167
        return 0;
168
      case CACHE_STATE_VALID:
169
        exitconn->addr = resolve->addr;
170
171
        log_fn(LOG_DEBUG,"Connection (fd %d) found cached answer for '%s'",
               exitconn->s, exitconn->address);
172
        return 1;
173
174
175
      case CACHE_STATE_FAILED:
        return -1;
    }
Roger Dingledine's avatar
Roger Dingledine committed
176
    tor_assert(0);
Roger Dingledine's avatar
Roger Dingledine committed
177
178
179
180
  }
  /* not there, need to add it */
  resolve = tor_malloc_zero(sizeof(struct cached_resolve));
  resolve->state = CACHE_STATE_PENDING;
181
182
  resolve->expire = now + MAX_DNS_ENTRY_AGE;
  strncpy(resolve->address, exitconn->address, MAX_ADDRESSLEN);
183
  resolve->address[MAX_ADDRESSLEN-1] = 0;
Roger Dingledine's avatar
Roger Dingledine committed
184
185
186
187

  /* add us to the pending list */
  pending_connection = tor_malloc(sizeof(struct pending_connection_t));
  pending_connection->conn = exitconn;
188
  pending_connection->next = NULL;
Roger Dingledine's avatar
Roger Dingledine committed
189
  resolve->pending_connections = pending_connection;
190
  exitconn->state = EXIT_CONN_STATE_RESOLVING;
Roger Dingledine's avatar
Roger Dingledine committed
191
192
193
194
195
196

  /* add us to the linked list of resolves */
  if (!oldest_cached_resolve) {
    oldest_cached_resolve = resolve;
  } else {
    newest_cached_resolve->next = resolve;
197
  }
Roger Dingledine's avatar
Roger Dingledine committed
198
  newest_cached_resolve = resolve;
199

Roger Dingledine's avatar
Roger Dingledine committed
200
201
  SPLAY_INSERT(cache_tree, &cache_root, resolve);
  return assign_to_dnsworker(exitconn);
202
203
}

204
205
206
/* Find or spawn a dns worker process to handle resolving
 * exitconn->address; tell that dns worker to begin resolving.
 */
Roger Dingledine's avatar
Roger Dingledine committed
207
static int assign_to_dnsworker(connection_t *exitconn) {
208
209
  connection_t *dnsconn;
  unsigned char len;
210

Roger Dingledine's avatar
Roger Dingledine committed
211
  tor_assert(exitconn->state == EXIT_CONN_STATE_RESOLVING);
212

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

215
  dnsconn = connection_get_by_type_state(CONN_TYPE_DNSWORKER, DNSWORKER_STATE_IDLE);
216
217

  if(!dnsconn) {
Roger Dingledine's avatar
Roger Dingledine committed
218
    log_fn(LOG_WARN,"no idle dns workers. Failing.");
219
    dns_cancel_pending_resolve(exitconn->address);
220
    return -1;
221
222
  }

223
224
225
  log_fn(LOG_DEBUG, "Connection (fd %d) needs to resolve '%s'; assigning to DNSWorker (fd %d)",
         exitconn->s, exitconn->address, dnsconn->s);

226
  tor_free(dnsconn->address);
227
  dnsconn->address = tor_strdup(exitconn->address);
228
  dnsconn->state = DNSWORKER_STATE_BUSY;
Roger Dingledine's avatar
Roger Dingledine committed
229
  num_dnsworkers_busy++;
230

231
  len = strlen(dnsconn->address);
232
233
  connection_write_to_buf(&len, 1, dnsconn);
  connection_write_to_buf(dnsconn->address, len, dnsconn);
234

Roger Dingledine's avatar
Roger Dingledine committed
235
//  log_fn(LOG_DEBUG,"submitted '%s'", exitconn->address);
236
237
238
  return 0;
}

239
240
/* Remove 'conn' from the list of connections waiting for conn->address.
 */
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
void connection_dns_remove(connection_t *conn)
{
  struct pending_connection_t *pend, *victim;
  struct cached_resolve search;
  struct cached_resolve *resolve;

  strncpy(search.address, conn->address, MAX_ADDRESSLEN);
  search.address[MAX_ADDRESSLEN-1] = 0;

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

Roger Dingledine's avatar
Roger Dingledine committed
256
  tor_assert(resolve->pending_connections);
257
258
259
260
261
262
  assert_connection_ok(conn,0);

  pend = resolve->pending_connections;

  if(pend->conn == conn) {
    resolve->pending_connections = pend->next;
263
    tor_free(pend);
264
    log_fn(LOG_DEBUG, "First connection (fd %d) no longer waiting for resolve of '%s'",
265
266
267
268
269
270
271
           conn->s, conn->address);
    return;
  } else {
    for( ; pend->next; pend = pend->next) {
      if(pend->next->conn == conn) {
        victim = pend->next;
        pend->next = victim->next;
272
        tor_free(victim);
273
274
275
276
277
        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
278
    tor_assert(0); /* not reachable unless onlyconn not in pending list */
279
280
281
  }
}

282
283
/* Log an error and abort if conn is waiting for a DNS resolve.
 */
284
285
286
287
288
289
290
291
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) {
    for(pend = resolve->pending_connections;
        pend;
        pend = pend->next) {
Roger Dingledine's avatar
Roger Dingledine committed
292
      tor_assert(pend->conn != conn);
293
294
295
296
    }
  }
}

297
298
/* Log an error and abort if any connection waiting for a DNS resolve is
 * corrupted. */
299
300
301
302
303
304
305
306
307
308
309
310
311
void assert_all_pending_dns_resolves_ok(void) {
  struct pending_connection_t *pend;
  struct cached_resolve *resolve;

  SPLAY_FOREACH(resolve, cache_tree, &cache_root) {
    for(pend = resolve->pending_connections;
        pend;
        pend = pend->next) {
      assert_connection_ok(pend->conn, 0);
    }
  }
}

312
313
314
/* Mark all connections waiting for 'address' for close.  Then cancel
 * the resolve for 'address' itself, and remove any cached results for
 * 'address' from the cache.
315
 */
316
317
void dns_cancel_pending_resolve(char *address) {
  struct pending_connection_t *pend;
318
  struct cached_resolve search;
319
  struct cached_resolve *resolve;
320
  connection_t *pendconn;
321

322
  strncpy(search.address, address, MAX_ADDRESSLEN);
323
  search.address[MAX_ADDRESSLEN-1] = 0;
324
325
326

  resolve = SPLAY_FIND(cache_tree, &cache_root, &search);
  if(!resolve) {
327
    log_fn(LOG_WARN,"Address '%s' is not pending. Dropping.", address);
328
329
330
    return;
  }

Roger Dingledine's avatar
Roger Dingledine committed
331
  tor_assert(resolve->pending_connections);
332

333
334
335
336
  /* mark all pending connections to fail */
  log_fn(LOG_DEBUG, "Failing all connections waiting on DNS resolve of '%s'",
         address);
  while(resolve->pending_connections) {
337
    pend = resolve->pending_connections;
338
339
    /* So that mark_for_close doesn't double-remove the connection. */
    pend->conn->state = EXIT_CONN_STATE_RESOLVEFAILED;
340
341
342
    pendconn = pend->conn; /* don't pass complex things to the
                              connection_mark_for_close macro */
    connection_mark_for_close(pendconn, END_STREAM_REASON_MISC);
343
344
    resolve->pending_connections = pend->next;
    tor_free(pend);
345
346
  }

347
348
349
  dns_purge_resolve(resolve);
}

350
351
/* Remove 'resolve' from the cache.
 */
352
353
354
static void dns_purge_resolve(struct cached_resolve *resolve) {
  struct cached_resolve *tmp;

355
356
357
358
359
  /* remove resolve from the linked list */
  if(resolve == oldest_cached_resolve) {
    oldest_cached_resolve = resolve->next;
    if(oldest_cached_resolve == NULL)
      newest_cached_resolve = NULL;
360
  } else {
361
362
    /* FFFF make it a doubly linked list if this becomes too slow */
    for(tmp=oldest_cached_resolve; tmp && tmp->next != resolve; tmp=tmp->next) ;
Roger Dingledine's avatar
Roger Dingledine committed
363
    tor_assert(tmp); /* it's got to be in the list, or we screwed up somewhere else */
364
365
366
367
    tmp->next = resolve->next; /* unlink it */

    if(newest_cached_resolve == resolve)
      newest_cached_resolve = tmp;
368
  }
369
370
371
372

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

373
  tor_free(resolve);
374
375
}

376
377
378
379
380
381
/* Called on the OR side when a DNS worker tells us the outcome of a DNS
 * resolve: tell all pending connections about the result of the lookup, and
 * cache the value.  ('address' is a NUL-terminated string containing the
 * address to look up; 'addr' is an IPv4 address in host order; 'outcome' is
 * one of DNS_RESOLVE_{FAILED_TRANSIENT|FAILED_PERMANENT|SUCCEEDED}.
 */
382
static void dns_found_answer(char *address, uint32_t addr, char outcome) {
383
384
385
  struct pending_connection_t *pend;
  struct cached_resolve search;
  struct cached_resolve *resolve;
386
  connection_t *pendconn;
387
  circuit_t *circ;
388

389
  strncpy(search.address, address, MAX_ADDRESSLEN);
390
  search.address[MAX_ADDRESSLEN-1] = 0;
391
392
393

  resolve = SPLAY_FIND(cache_tree, &cache_root, &search);
  if(!resolve) {
394
    log_fn(LOG_INFO,"Resolved unasked address '%s'? Dropping.", address);
395
396
    /* XXX Why drop?  Just because we don't care now doesn't mean we shouldn't
     * XXX cache the result for later. */
397
    return;
398
399
  }

400
  if (resolve->state != CACHE_STATE_PENDING) {
401
402
    /* XXXX Maybe update addr? or check addr for consistency? Or let
     * VALID replace FAILED? */
403
404
    log_fn(LOG_WARN, "Resolved '%s' which was already resolved; ignoring",
           address);
Roger Dingledine's avatar
Roger Dingledine committed
405
    tor_assert(resolve->pending_connections == NULL);
406
407
408
409
410
411
    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
412
  /* tor_assert(resolve->state == CACHE_STATE_PENDING); */
413

414
  resolve->addr = ntohl(addr);
415
  if(outcome == DNS_RESOLVE_SUCCEEDED)
416
417
418
419
420
421
    resolve->state = CACHE_STATE_VALID;
  else
    resolve->state = CACHE_STATE_FAILED;

  while(resolve->pending_connections) {
    pend = resolve->pending_connections;
422
    assert_connection_ok(pend->conn,time(NULL));
423
    pend->conn->addr = resolve->addr;
424
425


426
    if(resolve->state == CACHE_STATE_FAILED) {
427
428
      pendconn = pend->conn; /* don't pass complex things to the
                                connection_mark_for_close macro */
429
      /* prevent double-remove. */
430
      pendconn->state = EXIT_CONN_STATE_RESOLVEFAILED;
431
      connection_mark_for_close(pendconn, END_STREAM_REASON_RESOLVEFAILED);
432
      connection_free(pendconn);
Roger Dingledine's avatar
Roger Dingledine committed
433
    } else {
434
435
      /* prevent double-remove. */
      pend->conn->state = EXIT_CONN_STATE_CONNECTING;
436
437
438
439
440
441
442
443
444

      circ = circuit_get_by_conn(pend->conn);
      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;

445
      connection_exit_connect(pend->conn);
Roger Dingledine's avatar
Roger Dingledine committed
446
    }
447
448
    resolve->pending_connections = pend->next;
    tor_free(pend);
449
  }
450
451
452
453

  if(outcome == DNS_RESOLVE_FAILED_TRANSIENT) { /* remove from cache */
    dns_purge_resolve(resolve);
  }
454
455
}

456
457
/******************************************************************/

458
459
460
461
462
/*****
 * Connection between OR and dnsworker
 *****/

/* Write handler: called when we've pushed a request to a dnsworker. */
463
int connection_dns_finished_flushing(connection_t *conn) {
Roger Dingledine's avatar
Roger Dingledine committed
464
  tor_assert(conn && conn->type == CONN_TYPE_DNSWORKER);
465
466
467
468
  connection_stop_writing(conn);
  return 0;
}

469
470
471
472
/* Read handler: called when we get data from a dnsworker.  If the
 * connection is closed, mark the dnsworker as dead.  Otherwise, see
 * if we have a complete answer.  If so, call dns_found_answer on the
 * result.  If not, wait.  Returns 0. */
473
int connection_dns_process_inbuf(connection_t *conn) {
474
  char success;
475
  uint32_t addr;
476

Roger Dingledine's avatar
Roger Dingledine committed
477
  tor_assert(conn && conn->type == CONN_TYPE_DNSWORKER);
478
479

  if(conn->inbuf_reached_eof) {
480
    log_fn(LOG_WARN,"Read eof. Worker died unexpectedly.");
481
    if(conn->state == DNSWORKER_STATE_BUSY) {
482
      dns_cancel_pending_resolve(conn->address);
Roger Dingledine's avatar
Roger Dingledine committed
483
      num_dnsworkers_busy--;
484
    }
Roger Dingledine's avatar
Roger Dingledine committed
485
    num_dnsworkers--;
486
487
    connection_mark_for_close(conn,0);
    return 0;
488
489
  }

Roger Dingledine's avatar
Roger Dingledine committed
490
  tor_assert(conn->state == DNSWORKER_STATE_BUSY);
491
  if(buf_datalen(conn->inbuf) < 5) /* entire answer available? */
492
    return 0; /* not yet */
Roger Dingledine's avatar
Roger Dingledine committed
493
  tor_assert(buf_datalen(conn->inbuf) == 5);
494

495
496
  connection_fetch_from_buf(&success,1,conn);
  connection_fetch_from_buf((char *)&addr,sizeof(uint32_t),conn);
497

498
499
500
  log_fn(LOG_DEBUG, "DNSWorker (fd %d) returned answer for '%s'",
         conn->s, conn->address);

Roger Dingledine's avatar
Roger Dingledine committed
501
502
  tor_assert(success >= DNS_RESOLVE_FAILED_TRANSIENT);
  tor_assert(success <= DNS_RESOLVE_SUCCEEDED);
503
  dns_found_answer(conn->address, addr, success);
504

505
  tor_free(conn->address);
506
  conn->address = tor_strdup("<idle>");
507
  conn->state = DNSWORKER_STATE_IDLE;
Roger Dingledine's avatar
Roger Dingledine committed
508
  num_dnsworkers_busy--;
509
510
511
512

  return 0;
}

513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
/* Implementation for DNS workers; this code runs in a separate
 * execution context.  It takes as its argument an fdarray as returned
 * by socketpair(), and communicates via fdarray[1].  The protocol is
 * as follows:
 *     The OR says:
 *           ADDRESSLEN [1 byte]
 *           ADDRESS    [ADDRESSLEN bytes]
 *     The DNS worker does the lookup, and replies:
 *           OUTCOME    [1 byte]
 *           IP         [4 bytes]
 *
 * 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.
 */
530
int dnsworker_main(void *data) {
531
532
  char address[MAX_ADDRESSLEN];
  unsigned char address_len;
533
  char answer[5];
Roger Dingledine's avatar
Roger Dingledine committed
534
  uint32_t ip;
535
  int *fdarray = data;
Roger Dingledine's avatar
Roger Dingledine committed
536
  int fd;
537

538
  tor_close_socket(fdarray[0]); /* this is the side of the socketpair the parent uses */
539
  fd = fdarray[1]; /* this side is ours */
540
#ifndef MS_WINDOWS
541
  connection_free_all(); /* so the child doesn't hold the parent's fd's open */
542
#endif
543
544
545

  for(;;) {

546
    if(recv(fd, &address_len, 1, 0) != 1) {
547
      log_fn(LOG_INFO,"dnsworker exiting because tor process died.");
548
      spawn_exit();
549
    }
Roger Dingledine's avatar
Roger Dingledine committed
550
    tor_assert(address_len > 0);
551

552
    if(read_all(fd, address, address_len, 1) != address_len) {
553
      log_fn(LOG_ERR,"read hostname failed. Child exiting.");
554
      spawn_exit();
555
    }
556
    address[address_len] = 0; /* null terminate it */
557

Roger Dingledine's avatar
Roger Dingledine committed
558
    switch (tor_lookup_hostname(address, &ip)) {
559
      case 1:
560
561
        log_fn(LOG_INFO,"Could not resolve dest addr %s (transient).",address);
        answer[0] = DNS_RESOLVE_FAILED_TRANSIENT;
562
563
        break;
      case -1:
564
565
        log_fn(LOG_INFO,"Could not resolve dest addr %s (permanent).",address);
        answer[0] = DNS_RESOLVE_FAILED_PERMANENT;
566
        break;
567
568
569
      case 0:
        log_fn(LOG_INFO,"Resolved address '%s'.",address);
        answer[0] = DNS_RESOLVE_SUCCEEDED;
570
        break;
571
    }
Roger Dingledine's avatar
Roger Dingledine committed
572
    set_uint32(answer+1, ip);
573
574
575
576
    if(write_all(fd, answer, 5, 1) != 5) {
      log_fn(LOG_ERR,"writing answer failed. Child exiting.");
      spawn_exit();
    }
577
  }
578
  return 0; /* windows wants this function to return an int */
579
580
}

581
582
/* Launch a new DNS worker; return 0 on success, -1 on failure.
 */
Roger Dingledine's avatar
Roger Dingledine committed
583
static int spawn_dnsworker(void) {
584
585
586
  int fd[2];
  connection_t *conn;

587
  if(tor_socketpair(AF_UNIX, SOCK_STREAM, 0, fd) < 0) {
588
589
    log(LOG_ERR, "Couldn't construct socketpair: %s",
        tor_socket_strerror(tor_socket_errno(-1)));
590
591
592
    exit(1);
  }

593
  spawn_func(dnsworker_main, (void*)fd);
Roger Dingledine's avatar
Roger Dingledine committed
594
  log_fn(LOG_DEBUG,"just spawned a worker.");
595
  tor_close_socket(fd[1]); /* we don't need the worker's side of the pipe */
596
597
598

  conn = connection_new(CONN_TYPE_DNSWORKER);

599
  set_socket_nonblocking(fd[0]);
600
601
602

  /* 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
603
  conn->address = tor_strdup("<unused>");
604
605

  if(connection_add(conn) < 0) { /* no space, forget it */
Roger Dingledine's avatar
Roger Dingledine committed
606
    log_fn(LOG_WARN,"connection_add failed. Giving up.");
607
608
609
610
611
612
613
614
615
616
    connection_free(conn); /* this closes fd[0] */
    return -1;
  }

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

  return 0; /* success */
}

617
618
/* If we have too many or too few DNS workers, spawn or kill some.
 */
Roger Dingledine's avatar
Roger Dingledine committed
619
620
static void spawn_enough_dnsworkers(void) {
  int num_dnsworkers_needed; /* aim to have 1 more than needed,
621
                           * but no less than min and no more than max */
622
623
  connection_t *dnsconn;

624
  /* XXX This may not be the best strategy. Maybe we should queue pending
625
626
627
628
629
630
   *     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
631
   */
Roger Dingledine's avatar
Roger Dingledine committed
632
  if(num_dnsworkers_busy == MAX_DNSWORKERS) {
633
634
635
    /* We always want at least one worker idle.
     * So find the oldest busy worker and kill it.
     */
636
637
    dnsconn = connection_get_by_type_state_lastwritten(CONN_TYPE_DNSWORKER,
                                                       DNSWORKER_STATE_BUSY);
Roger Dingledine's avatar
Roger Dingledine committed
638
    tor_assert(dnsconn);
639

640
641
    log_fn(LOG_WARN, "%d DNS workers are spawned; all are busy. Killing one.",
           MAX_DNSWORKERS);
642

643
    connection_mark_for_close(dnsconn,0);
Roger Dingledine's avatar
Roger Dingledine committed
644
    num_dnsworkers_busy--;
645
    num_dnsworkers--;
646
  }
647

Roger Dingledine's avatar
Roger Dingledine committed
648
649
  if(num_dnsworkers_busy >= MIN_DNSWORKERS)
    num_dnsworkers_needed = num_dnsworkers_busy+1;
650
  else
Roger Dingledine's avatar
Roger Dingledine committed
651
    num_dnsworkers_needed = MIN_DNSWORKERS;
652

Roger Dingledine's avatar
Roger Dingledine committed
653
654
  while(num_dnsworkers < num_dnsworkers_needed) {
    if(spawn_dnsworker() < 0) {
Roger Dingledine's avatar
Roger Dingledine committed
655
      log(LOG_WARN,"spawn_enough_dnsworkers(): spawn failed!");
656
657
      return;
    }
Roger Dingledine's avatar
Roger Dingledine committed
658
    num_dnsworkers++;
659
660
  }

661
  while(num_dnsworkers > num_dnsworkers_busy+MAX_IDLE_DNSWORKERS) { /* too many idle? */
662
    /* cull excess workers */
663
664
    log_fn(LOG_WARN,"%d of %d dnsworkers are idle. Killing one.",
           num_dnsworkers-num_dnsworkers_needed, num_dnsworkers);
665
    dnsconn = connection_get_by_type_state(CONN_TYPE_DNSWORKER, DNSWORKER_STATE_IDLE);
Roger Dingledine's avatar
Roger Dingledine committed
666
    tor_assert(dnsconn);
667
    connection_mark_for_close(dnsconn,0);
Roger Dingledine's avatar
Roger Dingledine committed
668
    num_dnsworkers--;
669
  }
670
671
}

672
673
674
675
676
677
678
/*
  Local Variables:
  mode:c
  indent-tabs-mode:nil
  c-basic-offset:2
  End:
*/