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

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

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

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

18
extern or_options_t options; /* command-line and config-file options */
Roger Dingledine's avatar
Roger Dingledine committed
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 50
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. */
Roger Dingledine's avatar
Roger Dingledine committed
38
int num_dnsworkers=0;
39
/** How many of the running dnsworkers have an assigned task right now. */
Roger Dingledine's avatar
Roger Dingledine committed
40
int num_dnsworkers_busy=0;
41

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

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

65
66
67
68
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
69
static int dnsworker_main(void *data);
70
71
72
static int spawn_dnsworker(void);
static void spawn_enough_dnsworkers(void);

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

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

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

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

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

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

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

  /* 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;
114
    log(LOG_DEBUG,"Forgetting old cached resolve (expires %lu)", (unsigned long)resolve->expire);
115
116
    if(resolve->state == CACHE_STATE_PENDING) {
      log_fn(LOG_WARN,"Expiring a dns resolve that's still pending. Forgot to cull it?");
117
118
119
120
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);
        connection_mark_for_close(pendconn);
        connection_free(pendconn);
        tor_free(pend);
      }
132
    }
133
134
135
136
    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);
137
    tor_free(resolve);
138
139
140
  }
}

Nick Mathewson's avatar
Nick Mathewson committed
141
142
/** 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.
143
 * If resolve failed, return -1.
144
145
146
147
148
149
150
151
152
 *
 * 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
153
  struct cached_resolve search;
154
  struct pending_connection_t *pending_connection;
155
  struct in_addr in;
156
  uint32_t now = time(NULL);
157
  assert_connection_ok(exitconn, 0);
158
  tor_assert(exitconn->s == -1);
159

160
161
162
163
164
  /* 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;
165
166
167
168
  }

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

171
172
  /* now check the tree to see if 'address' is already there. */
  strncpy(search.address, exitconn->address, MAX_ADDRESSLEN);
173
  search.address[MAX_ADDRESSLEN-1] = 0;
Roger Dingledine's avatar
   
Roger Dingledine committed
174
  resolve = SPLAY_FIND(cache_tree, &cache_root, &search);
175
  if(resolve) { /* already there */
176
177
178
    switch(resolve->state) {
      case CACHE_STATE_PENDING:
        /* add us to the pending list */
179
        pending_connection = tor_malloc(sizeof(struct pending_connection_t));
180
        pending_connection->conn = exitconn;
Roger Dingledine's avatar
   
Roger Dingledine committed
181
182
        pending_connection->next = resolve->pending_connections;
        resolve->pending_connections = pending_connection;
183
184
        log_fn(LOG_DEBUG,"Connection (fd %d) waiting for pending DNS resolve of '%s'",
               exitconn->s, exitconn->address);
185
        exitconn->state = EXIT_CONN_STATE_RESOLVING;
Roger Dingledine's avatar
   
Roger Dingledine committed
186
        return 0;
187
      case CACHE_STATE_VALID:
188
        exitconn->addr = resolve->addr;
189
190
        log_fn(LOG_DEBUG,"Connection (fd %d) found cached answer for '%s'",
               exitconn->s, exitconn->address);
191
        return 1;
192
193
194
      case CACHE_STATE_FAILED:
        return -1;
    }
Roger Dingledine's avatar
Roger Dingledine committed
195
    tor_assert(0);
Roger Dingledine's avatar
Roger Dingledine committed
196
197
198
199
  }
  /* not there, need to add it */
  resolve = tor_malloc_zero(sizeof(struct cached_resolve));
  resolve->state = CACHE_STATE_PENDING;
200
201
  resolve->expire = now + MAX_DNS_ENTRY_AGE;
  strncpy(resolve->address, exitconn->address, MAX_ADDRESSLEN);
202
  resolve->address[MAX_ADDRESSLEN-1] = 0;
Roger Dingledine's avatar
Roger Dingledine committed
203
204
205
206

  /* add us to the pending list */
  pending_connection = tor_malloc(sizeof(struct pending_connection_t));
  pending_connection->conn = exitconn;
207
  pending_connection->next = NULL;
Roger Dingledine's avatar
Roger Dingledine committed
208
  resolve->pending_connections = pending_connection;
209
  exitconn->state = EXIT_CONN_STATE_RESOLVING;
Roger Dingledine's avatar
Roger Dingledine committed
210
211
212
213
214
215

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

Roger Dingledine's avatar
Roger Dingledine committed
219
220
  SPLAY_INSERT(cache_tree, &cache_root, resolve);
  return assign_to_dnsworker(exitconn);
221
222
}

Roger Dingledine's avatar
Roger Dingledine committed
223
/** Find or spawn a dns worker process to handle resolving
Nick Mathewson's avatar
Nick Mathewson committed
224
 * <b>exitconn</b>-\>address; tell that dns worker to begin resolving.
225
 */
Roger Dingledine's avatar
Roger Dingledine committed
226
static int assign_to_dnsworker(connection_t *exitconn) {
227
228
  connection_t *dnsconn;
  unsigned char len;
229

Roger Dingledine's avatar
Roger Dingledine committed
230
  tor_assert(exitconn->state == EXIT_CONN_STATE_RESOLVING);
231
  tor_assert(exitconn->s == -1);
232

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

235
  dnsconn = connection_get_by_type_state(CONN_TYPE_DNSWORKER, DNSWORKER_STATE_IDLE);
236
237

  if(!dnsconn) {
Roger Dingledine's avatar
Roger Dingledine committed
238
    log_fn(LOG_WARN,"no idle dns workers. Failing.");
239
    dns_cancel_pending_resolve(exitconn->address);
240
    return -1;
241
242
  }

243
244
245
  log_fn(LOG_DEBUG, "Connection (fd %d) needs to resolve '%s'; assigning to DNSWorker (fd %d)",
         exitconn->s, exitconn->address, dnsconn->s);

246
  tor_free(dnsconn->address);
247
  dnsconn->address = tor_strdup(exitconn->address);
248
  dnsconn->state = DNSWORKER_STATE_BUSY;
Roger Dingledine's avatar
Roger Dingledine committed
249
  num_dnsworkers_busy++;
250

251
  len = strlen(dnsconn->address);
252
253
  connection_write_to_buf(&len, 1, dnsconn);
  connection_write_to_buf(dnsconn->address, len, dnsconn);
254

Roger Dingledine's avatar
Roger Dingledine committed
255
//  log_fn(LOG_DEBUG,"submitted '%s'", exitconn->address);
256
257
258
  return 0;
}

Nick Mathewson's avatar
Nick Mathewson committed
259
/** Remove <b>conn</b> from the list of connections waiting for conn-\>address.
260
 */
261
262
263
264
265
266
void connection_dns_remove(connection_t *conn)
{
  struct pending_connection_t *pend, *victim;
  struct cached_resolve search;
  struct cached_resolve *resolve;

267
268
269
  tor_assert(conn->type == CONN_TYPE_EXIT);
  tor_assert(conn->state == EXIT_CONN_STATE_RESOLVING);

270
271
272
273
274
275
276
277
278
  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
279
  tor_assert(resolve->pending_connections);
280
281
282
283
284
285
  assert_connection_ok(conn,0);

  pend = resolve->pending_connections;

  if(pend->conn == conn) {
    resolve->pending_connections = pend->next;
286
    tor_free(pend);
287
    log_fn(LOG_DEBUG, "First connection (fd %d) no longer waiting for resolve of '%s'",
288
289
290
291
292
293
294
           conn->s, conn->address);
    return;
  } else {
    for( ; pend->next; pend = pend->next) {
      if(pend->next->conn == conn) {
        victim = pend->next;
        pend->next = victim->next;
295
        tor_free(victim);
296
297
298
299
300
        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
301
    tor_assert(0); /* not reachable unless onlyconn not in pending list */
302
303
304
  }
}

Roger Dingledine's avatar
Roger Dingledine committed
305
/** Log an error and abort if conn is waiting for a DNS resolve.
306
 */
307
308
309
310
311
312
313
314
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
315
      tor_assert(pend->conn != conn);
316
317
318
319
    }
  }
}

Roger Dingledine's avatar
Roger Dingledine committed
320
/** Log an error and abort if any connection waiting for a DNS resolve is
321
 * corrupted. */
322
323
324
325
326
327
328
329
330
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);
331
332
      tor_assert(pend->conn->s == -1);
      tor_assert(!connection_in_array(pend->conn));
333
334
335
336
    }
  }
}

Nick Mathewson's avatar
Nick Mathewson committed
337
338
339
/** 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.
340
 */
341
342
void dns_cancel_pending_resolve(char *address) {
  struct pending_connection_t *pend;
343
  struct cached_resolve search;
344
  struct cached_resolve *resolve;
345
  connection_t *pendconn;
346

347
  strncpy(search.address, address, MAX_ADDRESSLEN);
348
  search.address[MAX_ADDRESSLEN-1] = 0;
349
350
351

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

Roger Dingledine's avatar
Roger Dingledine committed
356
  tor_assert(resolve->pending_connections);
357

358
359
360
361
  /* mark all pending connections to fail */
  log_fn(LOG_DEBUG, "Failing all connections waiting on DNS resolve of '%s'",
         address);
  while(resolve->pending_connections) {
362
    pend = resolve->pending_connections;
363
364
    /* So that mark_for_close doesn't double-remove the connection. */
    pend->conn->state = EXIT_CONN_STATE_RESOLVEFAILED;
365
366
    pendconn = pend->conn; /* don't pass complex things to the
                              connection_mark_for_close macro */
367
    tor_assert(pendconn->s == -1);
368
369
370
371
    if(!pendconn->marked_for_close) {
      connection_edge_end(pendconn, END_STREAM_REASON_MISC, pendconn->cpath_layer);
      connection_mark_for_close(pendconn);
    }
372
    connection_free(pendconn);
373
374
    resolve->pending_connections = pend->next;
    tor_free(pend);
375
376
  }

377
378
379
  dns_purge_resolve(resolve);
}

Nick Mathewson's avatar
Nick Mathewson committed
380
/** Remove <b>resolve</b> from the cache.
381
 */
382
383
384
static void dns_purge_resolve(struct cached_resolve *resolve) {
  struct cached_resolve *tmp;

385
386
387
388
389
  /* 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;
390
  } else {
391
392
    /* 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
393
    tor_assert(tmp); /* it's got to be in the list, or we screwed up somewhere else */
394
395
396
397
    tmp->next = resolve->next; /* unlink it */

    if(newest_cached_resolve == resolve)
      newest_cached_resolve = tmp;
398
  }
399
400
401
402

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

403
  tor_free(resolve);
404
405
}

Roger Dingledine's avatar
Roger Dingledine committed
406
/** Called on the OR side when a DNS worker tells us the outcome of a DNS
407
 * resolve: tell all pending connections about the result of the lookup, and
Nick Mathewson's avatar
Nick Mathewson committed
408
409
410
411
 * 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}.
412
 */
413
static void dns_found_answer(char *address, uint32_t addr, char outcome) {
414
415
416
  struct pending_connection_t *pend;
  struct cached_resolve search;
  struct cached_resolve *resolve;
417
  connection_t *pendconn;
418
  circuit_t *circ;
419

420
  strncpy(search.address, address, MAX_ADDRESSLEN);
421
  search.address[MAX_ADDRESSLEN-1] = 0;
422
423
424

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

431
  if (resolve->state != CACHE_STATE_PENDING) {
432
433
    /* XXXX Maybe update addr? or check addr for consistency? Or let
     * VALID replace FAILED? */
434
435
    log_fn(LOG_WARN, "Resolved '%s' which was already resolved; ignoring",
           address);
Roger Dingledine's avatar
Roger Dingledine committed
436
    tor_assert(resolve->pending_connections == NULL);
437
438
439
440
441
442
    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
443
  /* tor_assert(resolve->state == CACHE_STATE_PENDING); */
444

445
  resolve->addr = ntohl(addr);
446
  if(outcome == DNS_RESOLVE_SUCCEEDED)
447
448
449
450
451
452
    resolve->state = CACHE_STATE_VALID;
  else
    resolve->state = CACHE_STATE_FAILED;

  while(resolve->pending_connections) {
    pend = resolve->pending_connections;
453
    assert_connection_ok(pend->conn,time(NULL));
454
    pend->conn->addr = resolve->addr;
455

456
    if(resolve->state == CACHE_STATE_FAILED) {
457
458
      pendconn = pend->conn; /* don't pass complex things to the
                                connection_mark_for_close macro */
459
      /* prevent double-remove. */
460
      pendconn->state = EXIT_CONN_STATE_RESOLVEFAILED;
461
      circuit_detach_stream(circuit_get_by_conn(pendconn), pendconn);
462
463
      connection_edge_end(pendconn, END_STREAM_REASON_MISC, pendconn->cpath_layer);
      connection_mark_for_close(pendconn);
464
      connection_free(pendconn);
Roger Dingledine's avatar
Roger Dingledine committed
465
    } else {
466
467
      /* prevent double-remove. */
      pend->conn->state = EXIT_CONN_STATE_CONNECTING;
468
469
470
471
472
473
474
475
476

      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;

477
      connection_exit_connect(pend->conn);
Roger Dingledine's avatar
Roger Dingledine committed
478
    }
479
480
    resolve->pending_connections = pend->next;
    tor_free(pend);
481
  }
482
483
484
485

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

488
489
/******************************************************************/

Nick Mathewson's avatar
Nick Mathewson committed
490
/*
491
 * Connection between OR and dnsworker
Nick Mathewson's avatar
Nick Mathewson committed
492
 */
493

Roger Dingledine's avatar
Roger Dingledine committed
494
/** Write handler: called when we've pushed a request to a dnsworker. */
495
int connection_dns_finished_flushing(connection_t *conn) {
Roger Dingledine's avatar
Roger Dingledine committed
496
  tor_assert(conn && conn->type == CONN_TYPE_DNSWORKER);
497
498
499
500
  connection_stop_writing(conn);
  return 0;
}

Roger Dingledine's avatar
Roger Dingledine committed
501
/** Read handler: called when we get data from a dnsworker.  If the
502
503
504
 * 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. */
505
int connection_dns_process_inbuf(connection_t *conn) {
506
  char success;
507
  uint32_t addr;
508

Roger Dingledine's avatar
Roger Dingledine committed
509
  tor_assert(conn && conn->type == CONN_TYPE_DNSWORKER);
510
511

  if(conn->inbuf_reached_eof) {
512
    log_fn(LOG_WARN,"Read eof. Worker died unexpectedly.");
513
    if(conn->state == DNSWORKER_STATE_BUSY) {
514
      dns_cancel_pending_resolve(conn->address);
Roger Dingledine's avatar
Roger Dingledine committed
515
      num_dnsworkers_busy--;
516
    }
Roger Dingledine's avatar
Roger Dingledine committed
517
    num_dnsworkers--;
518
    connection_mark_for_close(conn);
519
    return 0;
520
521
  }

Roger Dingledine's avatar
Roger Dingledine committed
522
  tor_assert(conn->state == DNSWORKER_STATE_BUSY);
523
  if(buf_datalen(conn->inbuf) < 5) /* entire answer available? */
524
    return 0; /* not yet */
Roger Dingledine's avatar
Roger Dingledine committed
525
  tor_assert(buf_datalen(conn->inbuf) == 5);
526

527
528
  connection_fetch_from_buf(&success,1,conn);
  connection_fetch_from_buf((char *)&addr,sizeof(uint32_t),conn);
529

530
531
532
  log_fn(LOG_DEBUG, "DNSWorker (fd %d) returned answer for '%s'",
         conn->s, conn->address);

Roger Dingledine's avatar
Roger Dingledine committed
533
534
  tor_assert(success >= DNS_RESOLVE_FAILED_TRANSIENT);
  tor_assert(success <= DNS_RESOLVE_SUCCEEDED);
535
  dns_found_answer(conn->address, addr, success);
536

537
  tor_free(conn->address);
538
  conn->address = tor_strdup("<idle>");
539
  conn->state = DNSWORKER_STATE_IDLE;
Roger Dingledine's avatar
Roger Dingledine committed
540
  num_dnsworkers_busy--;
541
542
543
544

  return 0;
}

Roger Dingledine's avatar
Roger Dingledine committed
545
/** Implementation for DNS workers; this code runs in a separate
546
547
548
 * 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
549
550
551
552
553
554
 *    - The OR says:
 *         - ADDRESSLEN [1 byte]
 *         - ADDRESS    [ADDRESSLEN bytes]
 *    - The DNS worker does the lookup, and replies:
 *         - OUTCOME    [1 byte]
 *         - IP         [4 bytes]
555
556
557
558
559
560
561
 *
 * 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
562
static int dnsworker_main(void *data) {
563
564
  char address[MAX_ADDRESSLEN];
  unsigned char address_len;
565
  char answer[5];
Roger Dingledine's avatar
Roger Dingledine committed
566
  uint32_t ip;
567
  int *fdarray = data;
Roger Dingledine's avatar
Roger Dingledine committed
568
  int fd;
569

570
  tor_close_socket(fdarray[0]); /* this is the side of the socketpair the parent uses */
571
  fd = fdarray[1]; /* this side is ours */
572
#ifndef MS_WINDOWS
573
  connection_free_all(); /* so the child doesn't hold the parent's fd's open */
574
#endif
575
576
577

  for(;;) {

578
    if(recv(fd, &address_len, 1, 0) != 1) {
579
      log_fn(LOG_INFO,"dnsworker exiting because tor process died.");
580
      spawn_exit();
581
    }
Roger Dingledine's avatar
Roger Dingledine committed
582
    tor_assert(address_len > 0);
583

584
    if(read_all(fd, address, address_len, 1) != address_len) {
585
      log_fn(LOG_ERR,"read hostname failed. Child exiting.");
586
      spawn_exit();
587
    }
588
    address[address_len] = 0; /* null terminate it */
589

Roger Dingledine's avatar
Roger Dingledine committed
590
    switch (tor_lookup_hostname(address, &ip)) {
591
      case 1:
592
593
        log_fn(LOG_INFO,"Could not resolve dest addr %s (transient).",address);
        answer[0] = DNS_RESOLVE_FAILED_TRANSIENT;
594
595
        break;
      case -1:
596
597
        log_fn(LOG_INFO,"Could not resolve dest addr %s (permanent).",address);
        answer[0] = DNS_RESOLVE_FAILED_PERMANENT;
598
        break;
599
600
601
      case 0:
        log_fn(LOG_INFO,"Resolved address '%s'.",address);
        answer[0] = DNS_RESOLVE_SUCCEEDED;
602
        break;
603
    }
Roger Dingledine's avatar
Roger Dingledine committed
604
    set_uint32(answer+1, ip);
605
606
607
608
    if(write_all(fd, answer, 5, 1) != 5) {
      log_fn(LOG_ERR,"writing answer failed. Child exiting.");
      spawn_exit();
    }
609
  }
610
  return 0; /* windows wants this function to return an int */
611
612
}

Roger Dingledine's avatar
Roger Dingledine committed
613
/** Launch a new DNS worker; return 0 on success, -1 on failure.
614
 */
Roger Dingledine's avatar
Roger Dingledine committed
615
static int spawn_dnsworker(void) {
616
617
618
  int fd[2];
  connection_t *conn;

619
  if(tor_socketpair(AF_UNIX, SOCK_STREAM, 0, fd) < 0) {
620
621
    log(LOG_ERR, "Couldn't construct socketpair: %s",
        tor_socket_strerror(tor_socket_errno(-1)));
622
623
624
    exit(1);
  }

625
  spawn_func(dnsworker_main, (void*)fd);
Roger Dingledine's avatar
Roger Dingledine committed
626
  log_fn(LOG_DEBUG,"just spawned a worker.");
627
  tor_close_socket(fd[1]); /* we don't need the worker's side of the pipe */
628
629
630

  conn = connection_new(CONN_TYPE_DNSWORKER);

631
  set_socket_nonblocking(fd[0]);
632
633
634

  /* 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
635
  conn->address = tor_strdup("<unused>");
636
637

  if(connection_add(conn) < 0) { /* no space, forget it */
Roger Dingledine's avatar
Roger Dingledine committed
638
    log_fn(LOG_WARN,"connection_add failed. Giving up.");
639
640
641
642
643
644
645
646
647
648
    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
649
/** If we have too many or too few DNS workers, spawn or kill some.
650
 */
Roger Dingledine's avatar
Roger Dingledine committed
651
652
static void spawn_enough_dnsworkers(void) {
  int num_dnsworkers_needed; /* aim to have 1 more than needed,
653
                           * but no less than min and no more than max */
654
655
  connection_t *dnsconn;

656
  /* XXX This may not be the best strategy. Maybe we should queue pending
657
658
659
660
661
662
   *     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
663
   */
Roger Dingledine's avatar
Roger Dingledine committed
664
  if(num_dnsworkers_busy == MAX_DNSWORKERS) {
665
666
667
    /* We always want at least one worker idle.
     * So find the oldest busy worker and kill it.
     */
668
669
    dnsconn = connection_get_by_type_state_lastwritten(CONN_TYPE_DNSWORKER,
                                                       DNSWORKER_STATE_BUSY);
Roger Dingledine's avatar
Roger Dingledine committed
670
    tor_assert(dnsconn);
671

672
673
    log_fn(LOG_WARN, "%d DNS workers are spawned; all are busy. Killing one.",
           MAX_DNSWORKERS);
674

675
    connection_mark_for_close(dnsconn);
Roger Dingledine's avatar
Roger Dingledine committed
676
    num_dnsworkers_busy--;
677
    num_dnsworkers--;
678
  }
679

Roger Dingledine's avatar
Roger Dingledine committed
680
681
  if(num_dnsworkers_busy >= MIN_DNSWORKERS)
    num_dnsworkers_needed = num_dnsworkers_busy+1;
682
  else
Roger Dingledine's avatar
Roger Dingledine committed
683
    num_dnsworkers_needed = MIN_DNSWORKERS;
684

Roger Dingledine's avatar
Roger Dingledine committed
685
686
  while(num_dnsworkers < num_dnsworkers_needed) {
    if(spawn_dnsworker() < 0) {
Roger Dingledine's avatar
Roger Dingledine committed
687
      log(LOG_WARN,"spawn_enough_dnsworkers(): spawn failed!");
688
689
      return;
    }
Roger Dingledine's avatar
Roger Dingledine committed
690
    num_dnsworkers++;
691
692
  }

693
  while(num_dnsworkers > num_dnsworkers_busy+MAX_IDLE_DNSWORKERS) { /* too many idle? */
694
    /* cull excess workers */
695
696
    log_fn(LOG_WARN,"%d of %d dnsworkers are idle. Killing one.",
           num_dnsworkers-num_dnsworkers_needed, num_dnsworkers);
697
    dnsconn = connection_get_by_type_state(CONN_TYPE_DNSWORKER, DNSWORKER_STATE_IDLE);
Roger Dingledine's avatar
Roger Dingledine committed
698
    tor_assert(dnsconn);
699
    connection_mark_for_close(dnsconn);
Roger Dingledine's avatar
Roger Dingledine committed
700
    num_dnsworkers--;
701
  }
702
703
}

704
705
706
707
708
709
710
/*
  Local Variables:
  mode:c
  indent-tabs-mode:nil
  c-basic-offset:2
  End:
*/