dns.c 31.4 KB
Newer Older
Roger Dingledine's avatar
Roger Dingledine committed
1
/* Copyright 2003-2004 Roger Dingledine.
Roger Dingledine's avatar
Roger Dingledine committed
2
 * Copyright 2004-2006 Roger Dingledine, Nick Mathewson. */
3
4
/* See LICENSE for licensing information */
/* $Id$ */
5
6
const char dns_c_id[] =
  "$Id$";
7

Roger Dingledine's avatar
Roger Dingledine committed
8
9
/**
 * \file dns.c
10
11
12
13
 * \brief Implements a farm of 'DNS worker' threads or processes to
 * perform DNS lookups for onion routers and cache the results.
 * [This needs to be done in the background because of the lack of a
 * good, ubiquitous asynchronous DNS implementation.]
Roger Dingledine's avatar
Roger Dingledine committed
14
 **/
15

16
17
/* See
 * http://elvin.dstc.com/ListArchive/elvin-dev/archive/2001/09/msg00027.html
18
19
20
21
 * for some approaches to asynchronous dns. We will want to switch once one of
 * them becomes more commonly available.
 */

22
#include "or.h"
23
#include "../common/ht.h"
24

Roger Dingledine's avatar
Roger Dingledine committed
25
/** Longest hostname we're willing to resolve. */
26
27
#define MAX_ADDRESSLEN 256

Roger Dingledine's avatar
Roger Dingledine committed
28
/** Maximum DNS processes to spawn. */
29
#define MAX_DNSWORKERS 100
Roger Dingledine's avatar
Roger Dingledine committed
30
/** Minimum DNS processes to spawn. */
31
#define MIN_DNSWORKERS 3
32

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

Roger Dingledine's avatar
Roger Dingledine committed
36
/** Possible outcomes from hostname lookup: permanent failure,
37
 * transient (retryable) failure, and success. */
38
39
40
41
#define DNS_RESOLVE_FAILED_TRANSIENT 1
#define DNS_RESOLVE_FAILED_PERMANENT 2
#define DNS_RESOLVE_SUCCEEDED 3

42
/** How many dnsworkers we have running right now. */
43
static int num_dnsworkers=0;
44
/** How many of the running dnsworkers have an assigned task right now. */
45
46
47
static int num_dnsworkers_busy=0;
/** When did we last rotate the dnsworkers? */
static time_t last_rotation_time=0;
48

Roger Dingledine's avatar
Roger Dingledine committed
49
/** Linked list of connections waiting for a DNS answer. */
50
51
typedef struct pending_connection_t {
  connection_t *conn;
52
  struct pending_connection_t *next;
53
} pending_connection_t;
54

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

73
74
static void purge_expired_resolves(uint32_t now);
static int assign_to_dnsworker(connection_t *exitconn);
75
static void dns_purge_resolve(cached_resolve_t *resolve);
76
static void dns_found_answer(char *address, uint32_t addr, char outcome);
Nick Mathewson's avatar
Nick Mathewson committed
77
static int dnsworker_main(void *data);
78
static int spawn_dnsworker(void);
79
static int spawn_enough_dnsworkers(void);
80
static void send_resolved_cell(connection_t *conn, uint8_t answer_type);
81

82
83
/** Hash table of cached_resolve objects. */
static HT_HEAD(cache_map, cached_resolve_t) cache_root;
84

Roger Dingledine's avatar
Roger Dingledine committed
85
/** Function to compare hashed resolves on their addresses; used to
86
 * implement hash tables. */
87
88
static INLINE int
cached_resolves_eq(cached_resolve_t *a, cached_resolve_t *b)
89
{
90
  /* make this smarter one day? */
91
92
93
94
95
96
97
  return !strncmp(a->address, b->address, MAX_ADDRESSLEN);
}

static INLINE unsigned int
cached_resolve_hash(cached_resolve_t *a)
{
  return ht_string_hash(a->address);
98
99
}

100
HT_PROTOTYPE(cache_map, cached_resolve_t, node, cached_resolve_hash,
101
             cached_resolves_eq);
102
HT_GENERATE(cache_map, cached_resolve_t, node, cached_resolve_hash,
103
            cached_resolves_eq, 0.6, malloc, realloc, free);
104

105
/** Initialize the DNS cache. */
106
static void
107
init_cache_map(void)
108
{
109
  HT_INIT(&cache_root);
110
111
}

Roger Dingledine's avatar
Roger Dingledine committed
112
/** Initialize the DNS subsystem; called by the OR process. */
113
114
115
void
dns_init(void)
{
116
  init_cache_map();
117
  dnsworkers_rotate();
118
}
119

120
/** Helper: free storage held by an entry in the DNS cache. */
121
static void
122
_free_cached_resolve(cached_resolve_t *r)
123
{
Nick Mathewson's avatar
Nick Mathewson committed
124
  while (r->pending_connections) {
125
    pending_connection_t *victim = r->pending_connections;
126
127
128
129
130
131
    r->pending_connections = victim->next;
    tor_free(victim);
  }
  tor_free(r);
}

132
/** Free all storage held in the DNS cache */
133
134
135
void
dns_free_all(void)
{
136
  cached_resolve_t **ptr, **next, *item;
137
  for (ptr = HT_START(cache_map, &cache_root); ptr != NULL; ptr = next) {
138
    item = *ptr;
139
    next = HT_NEXT_RMV(cache_map, &cache_root, ptr);
140
    _free_cached_resolve(item);
141
  }
142
  HT_CLEAR(cache_map, &cache_root);
143
144
}

145
/** Linked list of resolved addresses, oldest to newest. */
146
147
static cached_resolve_t *oldest_cached_resolve = NULL;
static cached_resolve_t *newest_cached_resolve = NULL;
148

Nick Mathewson's avatar
Nick Mathewson committed
149
/** Remove every cached_resolve whose <b>expire</b> time is before <b>now</b>
150
 * from the cache. */
151
152
153
static void
purge_expired_resolves(uint32_t now)
{
154
155
  cached_resolve_t *resolve;
  pending_connection_t *pend;
156
  connection_t *pendconn;
157
158
159
160

  /* this is fast because the linked list
   * oldest_cached_resolve is ordered by when they came in.
   */
161
  while (oldest_cached_resolve && (oldest_cached_resolve->expire < now)) {
162
    resolve = oldest_cached_resolve;
163
164
165
    log_debug(LD_EXIT,
              "Forgetting old cached resolve (address %s, expires %lu)",
              safe_str(resolve->address), (unsigned long)resolve->expire);
166
    if (resolve->state == CACHE_STATE_PENDING) {
167
168
169
      log_debug(LD_EXIT,
                "Bug: Expiring a dns resolve ('%s') that's still pending."
                " Forgot to cull it?", safe_str(resolve->address));
170
      tor_fragile_assert();
171
172
    }
    if (resolve->pending_connections) {
173
174
      log_debug(LD_EXIT,
                "Closing pending connections on expiring DNS resolve!");
175
      tor_fragile_assert();
176
177
178
179
180
181
      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;
182
        connection_edge_end(pendconn, END_STREAM_REASON_TIMEOUT,
183
                            pendconn->cpath_layer);
184
        circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
185
186
187
        connection_free(pendconn);
        tor_free(pend);
      }
188
    }
189
    oldest_cached_resolve = resolve->next;
190
    if (!oldest_cached_resolve) /* if there are no more, */
191
192
      newest_cached_resolve = NULL; /* then make sure the list's tail knows
                                     * that too */
193
    HT_REMOVE(cache_map, &cache_root, resolve);
194
    tor_free(resolve);
195
196
197
  }
}

198
199
200
201
/** Send a response to the RESOVLE request of a connection. answer_type must
 *  be one of RESOLVED_TYPE_(IPV4|ERROR|ERROR_TRANSIENT) */
static void
send_resolved_cell(connection_t *conn, uint8_t answer_type)
202
203
{
  char buf[RELAY_PAYLOAD_SIZE];
204
  size_t buflen;
205
206
207
208
209
210
211
212

  buf[0] = answer_type;

  switch (answer_type)
    {
    case RESOLVED_TYPE_IPV4:
      buf[1] = 4;
      set_uint32(buf+2, htonl(conn->addr));
213
214
      set_uint32(buf+6, htonl(MAX_DNS_ENTRY_AGE)); /*XXXX send a real TTL*/
      buflen = 10;
215
216
217
      break;
    case RESOLVED_TYPE_ERROR_TRANSIENT:
    case RESOLVED_TYPE_ERROR:
218
219
220
221
222
223
224
225
226
227
      {
        const char *errmsg = "Error resolving hostname";
        int msglen = strlen(errmsg);
        int ttl = (answer_type == RESOLVED_TYPE_ERROR ? MAX_DNS_ENTRY_AGE : 0);
        buf[1] = msglen;
        strlcpy(buf+2, errmsg, sizeof(buf)-2);
        set_uint32(buf+2+msglen, htonl((uint32_t)ttl));
        buflen = 6+msglen;
        break;
      }
228
229
230
    default:
      tor_assert(0);
    }
231
  connection_edge_send_command(conn, circuit_get_by_edge_conn(conn),
232
233
234
235
                               RELAY_COMMAND_RESOLVED, buf, buflen,
                               conn->cpath_layer);
}

236
237
/** Link <b>r</b> into the hash table of address-to-result mappings, and add it
 * to the linked list of resolves-by-age. */
238
static void
239
insert_resolve(cached_resolve_t *r)
240
241
242
243
244
245
246
247
248
{
  /* 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;

249
  HT_INSERT(cache_map, &cache_root, r);
250
251
}

Nick Mathewson's avatar
Nick Mathewson committed
252
253
/** 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.
254
 * If resolve failed, unlink exitconn if needed, free it, and return -1.
255
256
257
258
259
260
261
 *
 * 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.
 */
262
263
264
int
dns_resolve(connection_t *exitconn)
{
265
266
267
  cached_resolve_t *resolve;
  cached_resolve_t search;
  pending_connection_t *pending_connection;
268
  struct in_addr in;
269
  circuit_t *circ;
270
  uint32_t now = time(NULL);
271
  assert_connection_ok(exitconn, 0);
272
  tor_assert(exitconn->s == -1);
273

274
275
276
277
  /* 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);
278
279
    if (exitconn->purpose == EXIT_PURPOSE_RESOLVE)
      send_resolved_cell(exitconn, RESOLVED_TYPE_IPV4);
280
    return 1;
281
282
283
  }

  /* then take this opportunity to see if there are any expired
284
   * resolves in the hash table. */
285
  purge_expired_resolves(now);
286

287
288
289
  /* lower-case exitconn->address, so it's in canonical form */
  tor_strlower(exitconn->address);

290
  /* now check the hash table to see if 'address' is already there. */
Nick Mathewson's avatar
Nick Mathewson committed
291
  strlcpy(search.address, exitconn->address, sizeof(search.address));
292
  resolve = HT_FIND(cache_map, &cache_root, &search);
293
294
  if (resolve) { /* already there */
    switch (resolve->state) {
295
296
      case CACHE_STATE_PENDING:
        /* add us to the pending list */
297
        pending_connection = tor_malloc_zero(
298
                                      sizeof(pending_connection_t));
299
        pending_connection->conn = exitconn;
Roger Dingledine's avatar
   
Roger Dingledine committed
300
301
        pending_connection->next = resolve->pending_connections;
        resolve->pending_connections = pending_connection;
302
303
304
        log_debug(LD_EXIT,"Connection (fd %d) waiting for pending DNS "
                  "resolve of '%s'",
                  exitconn->s, safe_str(exitconn->address));
305
        exitconn->state = EXIT_CONN_STATE_RESOLVING;
Roger Dingledine's avatar
   
Roger Dingledine committed
306
        return 0;
307
      case CACHE_STATE_VALID:
308
        exitconn->addr = resolve->addr;
309
310
        log_debug(LD_EXIT,"Connection (fd %d) found cached answer for '%s'",
                  exitconn->s, safe_str(exitconn->address));
311
312
        if (exitconn->purpose == EXIT_PURPOSE_RESOLVE)
          send_resolved_cell(exitconn, RESOLVED_TYPE_IPV4);
313
        return 1;
314
      case CACHE_STATE_FAILED:
315
316
        log_debug(LD_EXIT,"Connection (fd %d) found cached error for '%s'",
                  exitconn->s, safe_str(exitconn->address));
317
318
        if (exitconn->purpose == EXIT_PURPOSE_RESOLVE)
          send_resolved_cell(exitconn, RESOLVED_TYPE_ERROR);
319
        circ = circuit_get_by_edge_conn(exitconn);
320
321
        if (circ)
          circuit_detach_stream(circ, exitconn);
322
323
        if (!exitconn->marked_for_close)
          connection_free(exitconn);
324
325
        return -1;
    }
Roger Dingledine's avatar
Roger Dingledine committed
326
    tor_assert(0);
Roger Dingledine's avatar
Roger Dingledine committed
327
328
  }
  /* not there, need to add it */
329
  resolve = tor_malloc_zero(sizeof(cached_resolve_t));
Roger Dingledine's avatar
Roger Dingledine committed
330
  resolve->state = CACHE_STATE_PENDING;
331
  resolve->expire = now + MAX_DNS_ENTRY_AGE;
Nick Mathewson's avatar
Nick Mathewson committed
332
  strlcpy(resolve->address, exitconn->address, sizeof(resolve->address));
Roger Dingledine's avatar
Roger Dingledine committed
333
334

  /* add us to the pending list */
335
  pending_connection = tor_malloc_zero(sizeof(pending_connection_t));
Roger Dingledine's avatar
Roger Dingledine committed
336
337
  pending_connection->conn = exitconn;
  resolve->pending_connections = pending_connection;
338
  exitconn->state = EXIT_CONN_STATE_RESOLVING;
Roger Dingledine's avatar
Roger Dingledine committed
339

340
  insert_resolve(resolve);
Roger Dingledine's avatar
Roger Dingledine committed
341
  return assign_to_dnsworker(exitconn);
342
343
}

Roger Dingledine's avatar
Roger Dingledine committed
344
/** Find or spawn a dns worker process to handle resolving
Nick Mathewson's avatar
Nick Mathewson committed
345
 * <b>exitconn</b>-\>address; tell that dns worker to begin resolving.
346
 */
347
348
349
static int
assign_to_dnsworker(connection_t *exitconn)
{
350
351
  connection_t *dnsconn;
  unsigned char len;
352

Roger Dingledine's avatar
Roger Dingledine committed
353
  tor_assert(exitconn->state == EXIT_CONN_STATE_RESOLVING);
354
  tor_assert(exitconn->s == -1);
355

356
357
358
359
  /* respawn here, to be sure there are enough */
  if (spawn_enough_dnsworkers() < 0) {
    goto err;
  }
360

361
362
  dnsconn = connection_get_by_type_state(CONN_TYPE_DNSWORKER,
                                         DNSWORKER_STATE_IDLE);
363

364
  if (!dnsconn) {
365
    log_warn(LD_EXIT,"no idle dns workers. Failing.");
366
367
    if (exitconn->purpose == EXIT_PURPOSE_RESOLVE)
      send_resolved_cell(exitconn, RESOLVED_TYPE_ERROR_TRANSIENT);
368
    goto err;
369
370
  }

371
372
373
374
  log_debug(LD_EXIT,
            "Connection (fd %d) needs to resolve '%s'; assigning "
            "to DNSWorker (fd %d)",
            exitconn->s, safe_str(exitconn->address), dnsconn->s);
375

376
  tor_free(dnsconn->address);
377
  dnsconn->address = tor_strdup(exitconn->address);
378
  dnsconn->state = DNSWORKER_STATE_BUSY;
Roger Dingledine's avatar
Roger Dingledine committed
379
  num_dnsworkers_busy++;
380

381
  len = strlen(dnsconn->address);
382
  connection_write_to_buf((char*)&len, 1, dnsconn);
383
  connection_write_to_buf(dnsconn->address, len, dnsconn);
384
385

  return 0;
386
err:
387
  dns_cancel_pending_resolve(exitconn->address); /* also sends end and frees */
388
  return -1;
389
390
}

Nick Mathewson's avatar
Nick Mathewson committed
391
/** Remove <b>conn</b> from the list of connections waiting for conn-\>address.
392
 */
393
394
void
connection_dns_remove(connection_t *conn)
395
{
396
397
398
  pending_connection_t *pend, *victim;
  cached_resolve_t search;
  cached_resolve_t *resolve;
399

400
401
402
  tor_assert(conn->type == CONN_TYPE_EXIT);
  tor_assert(conn->state == EXIT_CONN_STATE_RESOLVING);

Nick Mathewson's avatar
Nick Mathewson committed
403
  strlcpy(search.address, conn->address, sizeof(search.address));
404

405
  resolve = HT_FIND(cache_map, &cache_root, &search);
406
  if (!resolve) {
407
    /* XXXX RD This *is* a bug, right? -NM */
408
409
    log_notice(LD_BUG, "Address '%s' is not pending. Dropping.",
               safe_str(conn->address));
410
411
412
    return;
  }

Roger Dingledine's avatar
Roger Dingledine committed
413
  tor_assert(resolve->pending_connections);
414
415
416
417
  assert_connection_ok(conn,0);

  pend = resolve->pending_connections;

418
  if (pend->conn == conn) {
419
    resolve->pending_connections = pend->next;
420
    tor_free(pend);
421
422
423
    log_debug(LD_EXIT, "First connection (fd %d) no longer waiting "
              "for resolve of '%s'",
              conn->s, safe_str(conn->address));
424
425
    return;
  } else {
426
427
    for ( ; pend->next; pend = pend->next) {
      if (pend->next->conn == conn) {
428
429
        victim = pend->next;
        pend->next = victim->next;
430
        tor_free(victim);
431
432
433
        log_debug(LD_EXIT,
                  "Connection (fd %d) no longer waiting for resolve of '%s'",
                  conn->s, safe_str(conn->address));
434
435
436
        return; /* more are pending */
      }
    }
Roger Dingledine's avatar
Roger Dingledine committed
437
    tor_assert(0); /* not reachable unless onlyconn not in pending list */
438
439
440
  }
}

Roger Dingledine's avatar
Roger Dingledine committed
441
/** Log an error and abort if conn is waiting for a DNS resolve.
442
 */
443
444
445
void
assert_connection_edge_not_dns_pending(connection_t *conn)
{
446
  pending_connection_t *pend;
447
  cached_resolve_t **resolve;
448

449
  HT_FOREACH(resolve, cache_map, &cache_root) {
450
    for (pend = (*resolve)->pending_connections;
451
452
         pend;
         pend = pend->next) {
Roger Dingledine's avatar
Roger Dingledine committed
453
      tor_assert(pend->conn != conn);
454
455
456
457
    }
  }
}

Roger Dingledine's avatar
Roger Dingledine committed
458
/** Log an error and abort if any connection waiting for a DNS resolve is
459
 * corrupted. */
460
461
462
void
assert_all_pending_dns_resolves_ok(void)
{
463
  pending_connection_t *pend;
464
  cached_resolve_t **resolve;
465

466
  HT_FOREACH(resolve, cache_map, &cache_root) {
467
    for (pend = (*resolve)->pending_connections;
468
469
         pend;
         pend = pend->next) {
470
      assert_connection_ok(pend->conn, 0);
471
472
      tor_assert(pend->conn->s == -1);
      tor_assert(!connection_in_array(pend->conn));
473
474
475
476
    }
  }
}

Nick Mathewson's avatar
Nick Mathewson committed
477
478
479
/** 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.
480
 */
481
482
483
void
dns_cancel_pending_resolve(char *address)
{
484
485
486
  pending_connection_t *pend;
  cached_resolve_t search;
  cached_resolve_t *resolve;
487
  connection_t *pendconn;
488
  circuit_t *circ;
489

Nick Mathewson's avatar
Nick Mathewson committed
490
  strlcpy(search.address, address, sizeof(search.address));
491

492
  resolve = HT_FIND(cache_map, &cache_root, &search);
493
  if (!resolve) {
494
    /* XXXX RD This *is* a bug, right? -NM */
495
496
    log_notice(LD_BUG,"Address '%s' is not pending. Dropping.",
               safe_str(address));
497
498
499
    return;
  }

500
501
  if (!resolve->pending_connections) {
    /* XXX this should never trigger, but sometimes it does */
502
503
504
    log_warn(LD_BUG,
             "Bug: Address '%s' is pending but has no pending connections!",
             safe_str(address));
505
    tor_fragile_assert();
506
507
    return;
  }
Roger Dingledine's avatar
Roger Dingledine committed
508
  tor_assert(resolve->pending_connections);
509

510
  /* mark all pending connections to fail */
511
512
513
  log_debug(LD_EXIT,
             "Failing all connections waiting on DNS resolve of '%s'",
             safe_str(address));
514
  while (resolve->pending_connections) {
515
    pend = resolve->pending_connections;
516
    pend->conn->state = EXIT_CONN_STATE_RESOLVEFAILED;
517
    pendconn = pend->conn;
518
    tor_assert(pendconn->s == -1);
519
    if (!pendconn->marked_for_close) {
520
521
      connection_edge_end(pendconn, END_STREAM_REASON_RESOURCELIMIT,
                          pendconn->cpath_layer);
522
    }
523
    circ = circuit_get_by_edge_conn(pendconn);
524
525
    if (circ)
      circuit_detach_stream(circ, pendconn);
526
    connection_free(pendconn);
527
528
    resolve->pending_connections = pend->next;
    tor_free(pend);
529
530
  }

531
532
533
  dns_purge_resolve(resolve);
}

Nick Mathewson's avatar
Nick Mathewson committed
534
/** Remove <b>resolve</b> from the cache.
535
 */
536
static void
537
dns_purge_resolve(cached_resolve_t *resolve)
538
{
539
  cached_resolve_t *tmp;
540

541
  /* remove resolve from the linked list */
542
  if (resolve == oldest_cached_resolve) {
543
    oldest_cached_resolve = resolve->next;
544
    if (oldest_cached_resolve == NULL)
545
      newest_cached_resolve = NULL;
546
  } else {
547
    /* FFFF make it a doubly linked list if this becomes too slow */
548
549
550
551
    for (tmp=oldest_cached_resolve; tmp && tmp->next != resolve; tmp=tmp->next)
      ;
    tor_assert(tmp); /* it's got to be in the list, or we screwed up somewhere
                      * else */
552
553
    tmp->next = resolve->next; /* unlink it */

554
    if (newest_cached_resolve == resolve)
555
      newest_cached_resolve = tmp;
556
  }
557

558
  /* remove resolve from the map */
559
  HT_REMOVE(cache_map, &cache_root, resolve);
560

561
  tor_free(resolve);
562
563
}

Roger Dingledine's avatar
Roger Dingledine committed
564
/** Called on the OR side when a DNS worker tells us the outcome of a DNS
565
 * resolve: tell all pending connections about the result of the lookup, and
Nick Mathewson's avatar
Nick Mathewson committed
566
567
568
569
 * 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}.
570
 */
571
572
573
static void
dns_found_answer(char *address, uint32_t addr, char outcome)
{
574
575
576
  pending_connection_t *pend;
  cached_resolve_t search;
  cached_resolve_t *resolve;
577
  connection_t *pendconn;
578
  circuit_t *circ;
579

Nick Mathewson's avatar
Nick Mathewson committed
580
  strlcpy(search.address, address, sizeof(search.address));
581

582
  resolve = HT_FIND(cache_map, &cache_root, &search);
583
  if (!resolve) {
584
585
    log_info(LD_EXIT,"Resolved unasked address '%s'; caching anyway.",
             safe_str(address));
586
    resolve = tor_malloc_zero(sizeof(cached_resolve_t));
587
588
589
590
591
    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);
592
    return;
593
594
  }

595
  if (resolve->state != CACHE_STATE_PENDING) {
596
597
    /* XXXX Maybe update addr? or check addr for consistency? Or let
     * VALID replace FAILED? */
598
599
    log_notice(LD_EXIT, "Resolved '%s' which was already resolved; ignoring",
               safe_str(address));
Roger Dingledine's avatar
Roger Dingledine committed
600
    tor_assert(resolve->pending_connections == NULL);
601
602
603
604
605
606
    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
607
  /* tor_assert(resolve->state == CACHE_STATE_PENDING); */
608

609
  resolve->addr = addr;
610
  if (outcome == DNS_RESOLVE_SUCCEEDED)
611
612
613
614
    resolve->state = CACHE_STATE_VALID;
  else
    resolve->state = CACHE_STATE_FAILED;

615
  while (resolve->pending_connections) {
616
    pend = resolve->pending_connections;
617
    assert_connection_ok(pend->conn,time(NULL));
618
    pend->conn->addr = resolve->addr;
619
620
    pendconn = pend->conn; /* don't pass complex things to the
                              connection_mark_for_close macro */
621

622
    if (resolve->state == CACHE_STATE_FAILED) {
623
      /* prevent double-remove. */
624
      pendconn->state = EXIT_CONN_STATE_RESOLVEFAILED;
625
      if (pendconn->purpose == EXIT_PURPOSE_CONNECT) {
626
627
        connection_edge_end(pendconn, END_STREAM_REASON_RESOLVEFAILED,
                            pendconn->cpath_layer);
628
        /* This detach must happen after we send the end cell. */
629
        circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
630
      } else {
631
        send_resolved_cell(pendconn, RESOLVED_TYPE_ERROR);
632
        /* This detach must happen after we send the resolved cell. */
633
        circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
634
      }
635
      connection_free(pendconn);
Roger Dingledine's avatar
Roger Dingledine committed
636
    } else {
637
638
639
640
      if (pendconn->purpose == EXIT_PURPOSE_CONNECT) {
        /* prevent double-remove. */
        pend->conn->state = EXIT_CONN_STATE_CONNECTING;

641
        circ = circuit_get_by_edge_conn(pend->conn);
642
643
644
645
646
        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;
647
        pend->conn->on_circuit = circ;
648
649
650
651
652
653
654
655
        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);
656
        circ = circuit_get_by_edge_conn(pendconn);
657
658
659
660
        tor_assert(circ);
        circuit_detach_stream(circ, pendconn);
        connection_free(pendconn);
      }
Roger Dingledine's avatar
Roger Dingledine committed
661
    }
662
663
    resolve->pending_connections = pend->next;
    tor_free(pend);
664
  }
665

666
  if (outcome == DNS_RESOLVE_FAILED_TRANSIENT) { /* remove from cache */
667
668
    dns_purge_resolve(resolve);
  }
669
670
}

671
672
/******************************************************************/

Nick Mathewson's avatar
Nick Mathewson committed
673
/*
674
 * Connection between OR and dnsworker
Nick Mathewson's avatar
Nick Mathewson committed
675
 */
676

Roger Dingledine's avatar
Roger Dingledine committed
677
/** Write handler: called when we've pushed a request to a dnsworker. */
678
679
680
int
connection_dns_finished_flushing(connection_t *conn)
{
681
682
  tor_assert(conn);
  tor_assert(conn->type == CONN_TYPE_DNSWORKER);
683
684
685
686
  connection_stop_writing(conn);
  return 0;
}

687
688
689
int
connection_dns_reached_eof(connection_t *conn)
{
690
  log_warn(LD_EXIT,"Read eof. Worker died unexpectedly.");
691
  if (conn->state == DNSWORKER_STATE_BUSY) {
692
693
694
695
    /* don't cancel the resolve here -- it would be cancelled in
     * connection_about_to_close_connection(), since conn is still
     * in state BUSY
     */
696
697
698
699
700
701
702
703
    num_dnsworkers_busy--;
  }
  num_dnsworkers--;
  connection_mark_for_close(conn);
  return 0;
}

/** Read handler: called when we get data from a dnsworker. See
704
705
 * if we have a complete answer.  If so, call dns_found_answer on the
 * result.  If not, wait.  Returns 0. */
706
707
708
int
connection_dns_process_inbuf(connection_t *conn)
{
709
  char success;
710
  uint32_t addr;
711

712
713
  tor_assert(conn);
  tor_assert(conn->type == CONN_TYPE_DNSWORKER);
714

715
  if (conn->state != DNSWORKER_STATE_BUSY && buf_datalen(conn->inbuf)) {
716
717
718
719
    log_warn(LD_BUG,
             "Bug: read data (%d bytes) from an idle dns worker (fd %d, "
             "address '%s'). Please report.",
             (int)buf_datalen(conn->inbuf), conn->s, safe_str(conn->address));
720
    tor_fragile_assert();
721
722
723
724
725
726
727

    /* Pull it off the buffer anyway, or it will just stay there.
     * Keep pulling things off because sometimes we get several
     * answers at once (!). */
    while (buf_datalen(conn->inbuf)) {
      connection_fetch_from_buf(&success,1,conn);
      connection_fetch_from_buf((char *)&addr,sizeof(uint32_t),conn);
728
729
      log_warn(LD_EXIT,"Discarding idle dns answer (success %d, addr %d.)",
               success, addr); // XXX safe_str
730
    }
731
732
    return 0;
  }
733
  if (buf_datalen(conn->inbuf) < 5) /* entire answer available? */
734
    return 0; /* not yet */
735
  tor_assert(conn->state == DNSWORKER_STATE_BUSY);
Roger Dingledine's avatar
Roger Dingledine committed
736
  tor_assert(buf_datalen(conn->inbuf) == 5);
737

738
739
  connection_fetch_from_buf(&success,1,conn);
  connection_fetch_from_buf((char *)&addr,sizeof(uint32_t),conn);
740

741
742
  log_debug(LD_EXIT, "DNSWorker (fd %d) returned answer for '%s'",
            conn->s, safe_str(conn->address));
743

Roger Dingledine's avatar
Roger Dingledine committed
744
745
  tor_assert(success >= DNS_RESOLVE_FAILED_TRANSIENT);
  tor_assert(success <= DNS_RESOLVE_SUCCEEDED);
746
  dns_found_answer(conn->address, ntohl(addr), success);
747

748
  tor_free(conn->address);
749
  conn->address = tor_strdup("<idle>");
750
  conn->state = DNSWORKER_STATE_IDLE;
Roger Dingledine's avatar
Roger Dingledine committed
751
  num_dnsworkers_busy--;
752
753
754
755
756
  if (conn->timestamp_created < last_rotation_time) {
    connection_mark_for_close(conn);
    num_dnsworkers--;
    spawn_enough_dnsworkers();
  }
757
758
759
  return 0;
}

760
761
762
/** Close and re-open all idle dnsworkers; schedule busy ones to be closed
 * and re-opened once they're no longer busy.
 **/
763
764
void
dnsworkers_rotate(void)
765
766
767
768
769
770
771
772
{
  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);
773
774
  if (server_mode(get_options()))
    spawn_enough_dnsworkers();
775
776
}

Roger Dingledine's avatar
Roger Dingledine committed
777
/** Implementation for DNS workers; this code runs in a separate
778
779
780
 * 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
781
782
783
784
785
786
 *    - The OR says:
 *         - ADDRESSLEN [1 byte]
 *         - ADDRESS    [ADDRESSLEN bytes]
 *    - The DNS worker does the lookup, and replies:
 *         - OUTCOME    [1 byte]
 *         - IP         [4 bytes]
787
788
789
790
791
792
793
 *
 * 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.
 */
794
795
796
static int
dnsworker_main(void *data)
{
797
798
  char address[MAX_ADDRESSLEN];
  unsigned char address_len;
799
  char answer[5];
Roger Dingledine's avatar
Roger Dingledine committed
800
  uint32_t ip;
801
  int *fdarray = data;
Roger Dingledine's avatar
Roger Dingledine committed
802
  int fd;
803
  int result;
804

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

808
  fd = fdarray[1]; /* this side is ours */
809
#ifndef TOR_IS_MULTITHREADED
810
811
  tor_close_socket(fdarray[0]); /* this is the side of the socketpair the
                                 * parent uses */
812
  tor_free_all(1); /* so the child doesn't hold the parent's fd's open */
813
  handle_signals(0); /* ignore interrupts from the keyboard, etc */
814
815
#endif
  tor_free(data);
816

817
  for (;;) {
818
    int r;
819

820
821
    if ((r = recv(fd, &address_len, 1, 0)) != 1) {
      if (r == 0) {
822
823
        log_info(LD_EXIT,"DNS worker exiting because Tor process closed "
                 "connection (either pruned idle dnsworker or died).");
824
      } else {
825
826
827
828
        log_info(LD_EXIT,"DNS worker exiting because of error on connection "
                 "to Tor process.");
        log_info(LD_EXIT,"(Error on %d was %s)", fd,
                 tor_socket_strerror(tor_socket_errno(fd)));
Nick Mathewson's avatar