connection_edge.c 89.6 KB
Newer Older
Roger Dingledine's avatar
Roger Dingledine committed
1
2
/* Copyright (c) 2001 Matej Pfajfar.
 * Copyright (c) 2001-2004, Roger Dingledine.
3
 * Copyright (c) 2004-2007, Roger Dingledine, Nick Mathewson. */
4
5
/* See LICENSE for licensing information */
/* $Id$ */
6
7
const char connection_edge_c_id[] =
  "$Id$";
8

9
10
/**
 * \file connection_edge.c
11
 * \brief Handle edge streams.
12
13
 **/

14
15
#include "or.h"

16
17
18
19
20
21
22
23
24
25
26
#ifdef HAVE_LINUX_NETFILTER_IPV4_H
#include <linux/netfilter_ipv4.h>
#define TRANS_NETFILTER
#endif

#if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
#include <net/if.h>
#include <net/pfvar.h>
#define TRANS_PF
#endif

27
/** List of exit_redirect_t for every configured RedirectExit. */
28
static smartlist_t *redirect_exit_list = NULL;
29

30
static int connection_ap_handshake_process_socks(edge_connection_t *conn);
31
static int connection_ap_process_natd(edge_connection_t *conn);
Roger Dingledine's avatar
Roger Dingledine committed
32
static int connection_exit_connect_dir(edge_connection_t *exitconn);
33

34
35
36
37
38
/** An AP stream has failed/finished. If it hasn't already sent back
 * a socks reply, send one now (based on endreason). Also set
 * has_sent_end to 1, and mark the conn.
 */
void
39
_connection_mark_unattached_ap(edge_connection_t *conn, int endreason,
40
41
                               int line, const char *file)
{
42
43
  tor_assert(conn->_base.type == CONN_TYPE_AP);
  conn->_base.edge_has_sent_end = 1; /* no circ yet */
44

45
  if (conn->_base.marked_for_close) {
46
    /* This call will warn as appropriate. */
47
    _connection_mark_for_close(TO_CONN(conn), line, file);
48
49
50
    return;
  }

51
  if (!conn->socks_request->has_finished) {
52
    if (endreason & END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED)
Roger Dingledine's avatar
Roger Dingledine committed
53
      log_warn(LD_BUG,
54
               "stream (marked at %s:%d) sending two socks replies?",
Roger Dingledine's avatar
Roger Dingledine committed
55
               file, line);
56

57
    if (SOCKS_COMMAND_IS_CONNECT(conn->socks_request->command))
58
      connection_ap_handshake_socks_reply(conn, NULL, 0, endreason);
59
    else if (SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command))
60
61
      connection_ap_handshake_socks_resolved(conn, RESOLVED_TYPE_ERROR,
                                             0, NULL, -1);
62
63
    else /* unknown or no handshake at all. send no response. */
      conn->socks_request->has_finished = 1;
64
  }
65

66
67
  _connection_mark_for_close(TO_CONN(conn), line, file);
  conn->_base.hold_open_until_flushed = 1;
68
  conn->end_reason = endreason;
69
70
}

71
72
/** There was an EOF. Send an end and mark the connection for close.
 */
73
int
74
connection_edge_reached_eof(edge_connection_t *conn)
75
{
76
77
  if (buf_datalen(conn->_base.inbuf) &&
      connection_state_is_open(TO_CONN(conn))) {
Roger Dingledine's avatar
Roger Dingledine committed
78
79
80
    /* it still has stuff to process. don't let it die yet. */
    return 0;
  }
81
82
  log_info(LD_EDGE,"conn (fd %d) reached eof. Closing.", conn->_base.s);
  if (!conn->_base.marked_for_close) {
83
84
    /* only mark it if not already marked. it's possible to
     * get the 'end' right around when the client hangs up on us. */
85
    connection_edge_end(conn, END_STREAM_REASON_DONE);
86
87
    if (conn->socks_request) /* eof, so don't send a socks reply back */
      conn->socks_request->has_finished = 1;
88
    connection_mark_for_close(TO_CONN(conn));
89
90
91
92
93
  }
  return 0;
}

/** Handle new bytes on conn->inbuf based on state:
94
95
 *   - If it's waiting for socks info, try to read another step of the
 *     socks handshake out of conn->inbuf.
96
 *   - If it's waiting for the original destination, fetch it.
97
98
99
100
 *   - If it's open, then package more relay cells from the stream.
 *   - Else, leave the bytes on inbuf alone for now.
 *
 * Mark and return -1 if there was an unexpected error with the conn,
101
102
 * else return 0.
 */
103
int
104
connection_edge_process_inbuf(edge_connection_t *conn, int package_partial)
105
{
Roger Dingledine's avatar
Roger Dingledine committed
106
  tor_assert(conn);
107

108
  switch (conn->_base.state) {
109
    case AP_CONN_STATE_SOCKS_WAIT:
110
      if (connection_ap_handshake_process_socks(conn) < 0) {
111
        /* already marked */
112
113
114
        return -1;
      }
      return 0;
115
116
117
118
119
120
    case AP_CONN_STATE_NATD_WAIT:
      if (connection_ap_process_natd(conn) < 0) {
        /* already marked */
        return -1;
      }
      return 0;
121
122
    case AP_CONN_STATE_OPEN:
    case EXIT_CONN_STATE_OPEN:
123
      if (connection_edge_package_raw_inbuf(conn, package_partial) < 0) {
124
        /* (We already sent an end cell if possible) */
125
        connection_mark_for_close(TO_CONN(conn));
126
127
        return -1;
      }
128
129
      return 0;
    case EXIT_CONN_STATE_CONNECTING:
130
    case AP_CONN_STATE_RENDDESC_WAIT:
131
132
    case AP_CONN_STATE_CIRCUIT_WAIT:
    case AP_CONN_STATE_CONNECT_WAIT:
133
    case AP_CONN_STATE_RESOLVE_WAIT:
134
    case AP_CONN_STATE_CONTROLLER_WAIT:
Roger Dingledine's avatar
Roger Dingledine committed
135
136
      log_info(LD_EDGE,
               "data from edge while in '%s' state. Leaving it on buffer.",
137
               conn_state_to_string(conn->_base.type, conn->_base.state));
138
139
      return 0;
  }
140
  log_warn(LD_BUG,"Got unexpected state %d. Closing.",conn->_base.state);
141
  tor_fragile_assert();
142
  connection_edge_end(conn, END_STREAM_REASON_INTERNAL);
143
  connection_mark_for_close(TO_CONN(conn));
144
  return -1;
145
146
}

147
148
149
/** This edge needs to be closed, because its circuit has closed.
 * Mark it for close and return 0.
 */
150
int
151
connection_edge_destroy(uint16_t circ_id, edge_connection_t *conn)
152
{
153
  if (!conn->_base.marked_for_close) {
Roger Dingledine's avatar
Roger Dingledine committed
154
155
    log_info(LD_EDGE,
             "CircID %d: At an edge. Marking connection for close.", circ_id);
156
    if (conn->_base.type == CONN_TYPE_AP) {
157
158
      connection_mark_unattached_ap(conn, END_STREAM_REASON_DESTROY);
    } else {
159
160
      /* closing the circuit, nothing to send an END to */
      conn->_base.edge_has_sent_end = 1;
161
      conn->end_reason = END_STREAM_REASON_DESTROY;
162
      conn->end_reason |= END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED;
163
164
165
      if (conn->_base.type == CONN_TYPE_AP)
        control_event_stream_status(conn, STREAM_EVENT_CLOSED,
                                    END_STREAM_REASON_DESTROY);
166
167
      connection_mark_for_close(TO_CONN(conn));
      conn->_base.hold_open_until_flushed = 1;
168
    }
169
  }
170
  conn->cpath_layer = NULL;
171
  conn->on_circuit = NULL;
172
173
174
  return 0;
}

175
176
/** Send a relay end cell from stream <b>conn</b> down conn's circuit.  Set
 * the relay end cell's reason for closing as <b>reason</b>.
177
178
179
180
 *
 * Return -1 if this function has already been called on this conn,
 * else return 0.
 */
181
int
182
connection_edge_end(edge_connection_t *conn, char reason)
183
{
184
  char payload[RELAY_PAYLOAD_SIZE];
185
  size_t payload_len=1;
186
  circuit_t *circ;
187

188
  if (conn->_base.edge_has_sent_end) {
189
    log_warn(LD_BUG,"(Harmless.) Calling connection_edge_end (reason %d) "
Roger Dingledine's avatar
Roger Dingledine committed
190
             "on an already ended stream?", reason);
191
    tor_fragile_assert();
192
    return -1;
193
194
  }

195
  if (conn->_base.marked_for_close) {
Roger Dingledine's avatar
Roger Dingledine committed
196
    log_warn(LD_BUG,
197
             "called on conn that's already marked for close at %s:%d.",
198
             conn->_base.marked_for_close_file, conn->_base.marked_for_close);
199
200
201
    return 0;
  }

202
  payload[0] = reason;
203
204
  if (reason == END_STREAM_REASON_EXITPOLICY &&
      !connection_edge_is_rendezvous_stream(conn)) {
205
    set_uint32(payload+1, htonl(conn->_base.addr));
206
    set_uint32(payload+5, htonl(dns_clip_ttl(conn->address_ttl)));
207
    payload_len += 8;
208
209
  }

210
  circ = circuit_get_by_edge_conn(conn);
211
  if (circ && !circ->marked_for_close) {
212
    log_debug(LD_EDGE,"Sending end on conn (fd %d).",conn->_base.s);
213
    connection_edge_send_command(conn, RELAY_COMMAND_END,
214
                                 payload, payload_len);
215
  } else {
216
    log_debug(LD_EDGE,"No circ to send end on conn (fd %d).",
217
              conn->_base.s);
218
219
  }

220
  conn->_base.edge_has_sent_end = 1;
221
  conn->end_reason = reason;
222
  return 0;
223
224
}

225
/** An error has just occured on an operation on an edge connection
226
227
 * <b>conn</b>.  Extract the errno; convert it to an end reason, and send an
 * appropriate relay end cell to the other end of the connection's circuit.
228
 **/
229
int
230
connection_edge_end_errno(edge_connection_t *conn)
231
232
233
{
  uint8_t reason;
  tor_assert(conn);
234
  reason = (uint8_t)errno_to_end_reason(tor_socket_errno(conn->_base.s));
235
  return connection_edge_end(conn, reason);
236
237
}

238
239
240
241
242
243
244
245
246
247
/** Connection <b>conn</b> has finished writing and has no bytes left on
 * its outbuf.
 *
 * If it's in state 'open', stop writing, consider responding with a
 * sendme, and return.
 * Otherwise, stop writing and return.
 *
 * If <b>conn</b> is broken, mark it for close and return -1, else
 * return 0.
 */
248
int
249
connection_edge_finished_flushing(edge_connection_t *conn)
250
{
Roger Dingledine's avatar
Roger Dingledine committed
251
  tor_assert(conn);
252

253
  switch (conn->_base.state) {
254
255
    case AP_CONN_STATE_OPEN:
    case EXIT_CONN_STATE_OPEN:
256
      connection_stop_writing(TO_CONN(conn));
257
      connection_edge_consider_sending_sendme(conn);
258
      return 0;
Roger Dingledine's avatar
Roger Dingledine committed
259
    case AP_CONN_STATE_SOCKS_WAIT:
260
    case AP_CONN_STATE_NATD_WAIT:
261
    case AP_CONN_STATE_RENDDESC_WAIT:
262
    case AP_CONN_STATE_CIRCUIT_WAIT:
263
    case AP_CONN_STATE_CONNECT_WAIT:
264
    case AP_CONN_STATE_CONTROLLER_WAIT:
265
      connection_stop_writing(TO_CONN(conn));
Roger Dingledine's avatar
Roger Dingledine committed
266
      return 0;
267
    default:
268
      log_warn(LD_BUG, "Called in unexpected state %d.",conn->_base.state);
269
      tor_fragile_assert();
270
      return -1;
271
272
273
274
  }
  return 0;
}

275
276
277
/** Connected handler for exit connections: start writing pending
 * data, deliver 'CONNECTED' relay cells as appropriate, and check
 * any pending data that may have been received. */
278
int
279
connection_edge_finished_connecting(edge_connection_t *edge_conn)
280
{
281
  char valbuf[INET_NTOA_BUF_LEN];
282
  connection_t *conn;
Roger Dingledine's avatar
Roger Dingledine committed
283
  struct in_addr in;
284

285
286
287
  tor_assert(edge_conn);
  tor_assert(edge_conn->_base.type == CONN_TYPE_EXIT);
  conn = TO_CONN(edge_conn);
288
289
  tor_assert(conn->state == EXIT_CONN_STATE_CONNECTING);

290
291
  in.s_addr = htonl(conn->addr);
  tor_inet_ntoa(&in,valbuf,sizeof(valbuf));
Roger Dingledine's avatar
Roger Dingledine committed
292
  log_info(LD_EXIT,"Exit connection to %s:%u (%s) established.",
293
           escaped_safe_str(conn->address),conn->port,safe_str(valbuf));
294
295

  conn->state = EXIT_CONN_STATE_OPEN;
296
  connection_watch_events(conn, EV_READ); /* stop writing, continue reading */
297
298
  if (connection_wants_to_flush(conn)) /* in case there are any queued relay
                                        * cells */
299
300
    connection_start_writing(conn);
  /* deliver a 'connected' relay cell back through the circuit. */
301
302
  if (connection_edge_is_rendezvous_stream(edge_conn)) {
    if (connection_edge_send_command(edge_conn,
303
                                     RELAY_COMMAND_CONNECTED, NULL, 0) < 0)
304
305
      return 0; /* circuit is closed, don't continue */
  } else {
306
    char connected_payload[8];
307
    set_uint32(connected_payload, htonl(conn->addr));
308
    set_uint32(connected_payload+4,
309
310
311
               htonl(dns_clip_ttl(edge_conn->address_ttl)));
    if (connection_edge_send_command(edge_conn,
                                     RELAY_COMMAND_CONNECTED,
312
                                     connected_payload, 8) < 0)
313
314
      return 0; /* circuit is closed, don't continue */
  }
315
  tor_assert(edge_conn->package_window > 0);
316
  /* in case the server has written anything */
317
  return connection_edge_process_inbuf(edge_conn, 1);
318
319
}

320
321
/** Define a schedule for how long to wait between retrying
 * application connections. Rather than waiting a fixed amount of
322
 * time between each retry, we wait 10 seconds each for the first
323
 * two tries, and 15 seconds for each retry after
324
 * that. Hopefully this will improve the expected user experience. */
325
static int
326
compute_retry_timeout(edge_connection_t *conn)
327
{
328
  if (conn->num_socks_retries < 2) /* try 0 and try 1 */
329
330
331
332
    return 10;
  return 15;
}

333
334
335
/** Find all general-purpose AP streams waiting for a response that sent their
 * begin/resolve cell >=15 seconds ago. Detach from their current circuit, and
 * mark their current circuit as unsuitable for new streams. Then call
336
337
338
 * connection_ap_handshake_attach_circuit() to attach to a new circuit (if
 * available) or launch a new one.
 *
339
 * For rendezvous streams, simply give up after SocksTimeout seconds (with no
340
341
 * retry attempt).
 */
342
343
344
void
connection_ap_expire_beginning(void)
{
345
  edge_connection_t *conn;
346
  circuit_t *circ;
347
  time_t now = time(NULL);
348
  or_options_t *options = get_options();
349
  int severity;
350
  int cutoff;
351
  int seconds_idle;
352
  smartlist_t *conns = get_connection_array();
353

354
355
356
  SMARTLIST_FOREACH(conns, connection_t *, c,
  {
    if (c->type != CONN_TYPE_AP)
357
      continue;
358
    conn = TO_EDGE_CONN(c);
359
    /* if it's an internal bridge connection, don't yell its status. */
360
361
    severity = (!conn->_base.addr && !conn->_base.port)
      ? LOG_INFO : LOG_NOTICE;
362
363
364
365
    seconds_idle = now - conn->_base.timestamp_lastread;

    if (AP_CONN_STATE_IS_UNATTACHED(conn->_base.state)) {
      if (seconds_idle >= options->SocksTimeout) {
366
367
368
        log_fn(severity, LD_APP,
            "Tried for %d seconds to get a connection to %s:%d. "
            "Giving up. (%s)",
369
            seconds_idle, safe_str(conn->socks_request->address),
370
371
            conn->socks_request->port,
            conn_state_to_string(CONN_TYPE_AP, conn->_base.state));
372
        connection_mark_unattached_ap(conn, END_STREAM_REASON_TIMEOUT);
373
374
375
376
      }
      continue;
    }

377
    if (conn->_base.state == AP_CONN_STATE_OPEN)
378
      continue;
379

380
381
382
383
    /* We're in state connect_wait or resolve_wait now -- waiting for a
     * reply to our relay cell. See if we want to retry/give up. */

    cutoff = compute_retry_timeout(conn);
384
    if (seconds_idle < cutoff)
385
      continue;
386
    circ = circuit_get_by_edge_conn(conn);
387
    if (!circ) { /* it's vanished? */
Roger Dingledine's avatar
Roger Dingledine committed
388
389
      log_info(LD_APP,"Conn is waiting (address %s), but lost its circ.",
               safe_str(conn->socks_request->address));
390
      connection_mark_unattached_ap(conn, END_STREAM_REASON_TIMEOUT);
391
392
      continue;
    }
393
    if (circ->purpose == CIRCUIT_PURPOSE_C_REND_JOINED) {
394
      if (seconds_idle >= options->SocksTimeout) {
395
396
397
        log_fn(severity, LD_REND,
               "Rend stream is %d seconds late. Giving up on address"
               " '%s.onion'.",
398
               seconds_idle,
399
               safe_str(conn->socks_request->address));
400
        connection_edge_end(conn, END_STREAM_REASON_TIMEOUT);
401
        connection_mark_unattached_ap(conn, END_STREAM_REASON_TIMEOUT);
402
403
404
      }
      continue;
    }
Roger Dingledine's avatar
Roger Dingledine committed
405
    tor_assert(circ->purpose == CIRCUIT_PURPOSE_C_GENERAL);
406
    log_fn(cutoff < 15 ? LOG_INFO : severity, LD_APP,
407
408
           "We tried for %d seconds to connect to '%s' using exit '%s'."
           " Retrying on a new circuit.",
409
           seconds_idle, safe_str(conn->socks_request->address),
410
411
           conn->cpath_layer ?
             conn->cpath_layer->extend_info->nickname : "*unnamed*");
412
    /* send an end down the circuit */
413
    connection_edge_end(conn, END_STREAM_REASON_TIMEOUT);
414
    /* un-mark it as ending, since we're going to reuse it */
415
    conn->_base.edge_has_sent_end = 0;
416
    conn->end_reason = 0;
417
418
419
420
    /* kludge to make us not try this circuit again, yet to allow
     * current streams on it to survive if they can: make it
     * unattractive to use for new streams */
    tor_assert(circ->timestamp_dirty);
421
    circ->timestamp_dirty -= options->MaxCircuitDirtiness;
422
    /* give our stream another 'cutoff' seconds to try */
423
    conn->_base.timestamp_lastread += cutoff;
424
425
    if (conn->num_socks_retries < 250) /* avoid overflow */
      conn->num_socks_retries++;
426
    /* move it back into 'pending' state, and try to attach. */
427
428
    if (connection_ap_detach_retriable(conn, TO_ORIGIN_CIRCUIT(circ),
                                       END_STREAM_REASON_TIMEOUT)<0) {
429
      connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
430
    }
431
  }); /* end foreach */
432
433
}

434
435
/** Tell any AP streams that are waiting for a new circuit to try again,
 * either attaching to an available circ or launching a new one.
436
 */
437
438
void
connection_ap_attach_pending(void)
439
{
440
  edge_connection_t *edge_conn;
441
442
443
  smartlist_t *conns = get_connection_array();
  SMARTLIST_FOREACH(conns, connection_t *, conn,
  {
Roger Dingledine's avatar
Roger Dingledine committed
444
445
    if (conn->marked_for_close ||
        conn->type != CONN_TYPE_AP ||
446
        conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
447
      continue;
448
449
450
    edge_conn = TO_EDGE_CONN(conn);
    if (connection_ap_handshake_attach_circuit(edge_conn) < 0) {
      connection_mark_unattached_ap(edge_conn, END_STREAM_REASON_CANT_ATTACH);
451
    }
452
  });
453
454
}

455
456
457
458
459
460
461
462
463
464
/** A circuit failed to finish on its last hop <b>info</b>. If there
 * are any streams waiting with this exit node in mind, but they
 * don't absolutely require it, make them give up on it.
 */
void
circuit_discard_optional_exit_enclaves(extend_info_t *info)
{
  edge_connection_t *edge_conn;
  routerinfo_t *r1, *r2;

465
466
467
  smartlist_t *conns = get_connection_array();
  SMARTLIST_FOREACH(conns, connection_t *, conn,
  {
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
    if (conn->marked_for_close ||
        conn->type != CONN_TYPE_AP ||
        !conn->chosen_exit_optional)
      continue;
    edge_conn = TO_EDGE_CONN(conn);
    r1 = router_get_by_nickname(edge_conn->chosen_exit_name, 0);
    r2 = router_get_by_nickname(info->nickname, 0);
    if (r1 && r2 && r1==r2) {
      tor_assert(edge_conn->socks_request);
      log_info(LD_APP, "Giving up on enclave exit '%s' for destination %s.",
               safe_str(edge_conn->chosen_exit_name),
               escaped_safe_str(edge_conn->socks_request->address));
      conn->chosen_exit_optional = 0;
      tor_free(edge_conn->chosen_exit_name); /* clears it */
    }
483
  });
484
485
}

486
487
/** The AP connection <b>conn</b> has just failed while attaching or
 * sending a BEGIN or resolving on <b>circ</b>, but another circuit
488
 * might work. Detach the circuit, and either reattach it, launch a
489
490
491
 * new circuit, tell the controller, or give up as a appropriate.
 *
 * Returns -1 on err, 1 on success, 0 on not-yet-sure.
492
493
 */
int
494
495
connection_ap_detach_retriable(edge_connection_t *conn, origin_circuit_t *circ,
                               int reason)
496
{
497
  control_event_stream_status(conn, STREAM_EVENT_FAILED_RETRIABLE, reason);
498
  conn->_base.timestamp_lastread = time(NULL);
499
  if (! get_options()->LeaveStreamsUnattached) {
500
    conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
501
    circuit_detach_stream(TO_CIRCUIT(circ),conn);
502
503
    return connection_ap_handshake_attach_circuit(conn);
  } else {
504
    conn->_base.state = AP_CONN_STATE_CONTROLLER_WAIT;
505
    circuit_detach_stream(TO_CIRCUIT(circ),conn);
506
507
508
509
    return 0;
  }
}

510
/** A client-side struct to remember requests to rewrite addresses
511
 * to new addresses. These structs are stored in the hash table
512
 * "addressmap" below.
513
514
515
516
517
518
519
520
521
522
523
 *
 * There are 5 ways to set an address mapping:
 * - A MapAddress command from the controller [permanent]
 * - An AddressMap directive in the torrc [permanent]
 * - When a TrackHostExits torrc directive is triggered [temporary]
 * - When a dns resolve succeeds [temporary]
 * - When a dns resolve fails [temporary]
 *
 * When an addressmap request is made but one is already registered,
 * the new one is replaced only if the currently registered one has
 * no "new_address" (that is, it's in the process of dns resolve),
524
525
526
527
528
 * or if the new one is permanent (expires==0 or 1).
 *
 * (We overload the 'expires' field, using "0" for mappings set via
 * the configuration file, "1" for mappings set from the control
 * interface, and other values for DNS mappings that can expire.)
529
530
531
532
533
534
535
 */
typedef struct {
  char *new_address;
  time_t expires;
  int num_resolve_failures;
} addressmap_entry_t;

536
/** Entry for mapping addresses to which virtual address we mapped them to. */
537
538
539
540
541
typedef struct {
  char *ipv4_address;
  char *hostname_address;
} virtaddress_entry_t;

542
/** A hash table to store client-side address rewrite instructions. */
543
static strmap_t *addressmap=NULL;
544
/**
545
 * Table mapping addresses to which virtual address, if any, we
546
547
548
549
550
551
552
553
 * assigned them to.
 *
 * We maintain the following invariant: if [A,B] is in
 * virtaddress_reversemap, then B must be a virtual address, and [A,B]
 * must be in addressmap.  We do not require that the converse hold:
 * if it fails, then we could end up mapping two virtual addresses to
 * the same address, which is no disaster.
 **/
554
static strmap_t *virtaddress_reversemap=NULL;
555
556

/** Initialize addressmap. */
557
558
559
void
addressmap_init(void)
{
560
  addressmap = strmap_new();
561
  virtaddress_reversemap = strmap_new();
562
563
564
565
}

/** Free the memory associated with the addressmap entry <b>_ent</b>. */
static void
566
567
addressmap_ent_free(void *_ent)
{
568
569
570
571
572
  addressmap_entry_t *ent = _ent;
  tor_free(ent->new_address);
  tor_free(ent);
}

Roger Dingledine's avatar
Roger Dingledine committed
573
/** Free storage held by a virtaddress_entry_t* entry in <b>ent</b>. */
574
static void
575
576
addressmap_virtaddress_ent_free(void *_ent)
{
577
578
579
580
581
582
  virtaddress_entry_t *ent = _ent;
  tor_free(ent->ipv4_address);
  tor_free(ent->hostname_address);
  tor_free(ent);
}

Roger Dingledine's avatar
Roger Dingledine committed
583
/** Free storage held by a virtaddress_entry_t* entry in <b>ent</b>. */
584
static void
585
addressmap_virtaddress_remove(const char *address, addressmap_entry_t *ent)
586
{
587
588
  if (ent && ent->new_address &&
      address_is_in_virtual_range(ent->new_address)) {
589
590
    virtaddress_entry_t *ve =
      strmap_get(virtaddress_reversemap, ent->new_address);
591
    /*log_fn(LOG_NOTICE,"remove reverse mapping for %s",ent->new_address);*/
592
    if (ve) {
593
      if (!strcmp(address, ve->ipv4_address))
594
        tor_free(ve->ipv4_address);
595
      if (!strcmp(address, ve->hostname_address))
596
597
598
599
600
        tor_free(ve->hostname_address);
      if (!ve->ipv4_address && !ve->hostname_address) {
        tor_free(ve);
        strmap_remove(virtaddress_reversemap, ent->new_address);
      }
601
602
603
604
    }
  }
}

605
606
/** Remove <b>ent</b> (which must be mapped to by <b>address</b>) from the
 * client address maps. */
607
static void
608
addressmap_ent_remove(const char *address, addressmap_entry_t *ent)
609
{
610
  addressmap_virtaddress_remove(address, ent);
611
612
  addressmap_ent_free(ent);
}
613

614
615
616
617
618
619
620
621
622
623
624
625
626
/** Remove all entries from the addressmap that were set via the
 * configuration file or the command line. */
void
addressmap_clear_configured(void)
{
  addressmap_get_mappings(NULL, 0, 0);
}

/** Remove all entries from the addressmap that are set to expire, ever. */
void
addressmap_clear_transient(void)
{
  addressmap_get_mappings(NULL, 2, TIME_MAX);
627
628
629
630
631
}

/** Clean out entries from the addressmap cache that were
 * added long enough ago that they are no longer valid.
 */
632
633
634
void
addressmap_clean(time_t now)
{
635
  addressmap_get_mappings(NULL, 2, now);
636
637
638
639
}

/** Free all the elements in the addressmap, and free the addressmap
 * itself. */
640
641
642
void
addressmap_free_all(void)
{
643
644
645
646
647
648
649
650
  if (addressmap) {
    strmap_free(addressmap, addressmap_ent_free);
    addressmap = NULL;
  }
  if (virtaddress_reversemap) {
    strmap_free(virtaddress_reversemap, addressmap_virtaddress_ent_free);
    virtaddress_reversemap = NULL;
  }
651
652
653
654
}

/** Look at address, and rewrite it until it doesn't want any
 * more rewrites; but don't get into an infinite loop.
655
656
 * Don't write more than maxlen chars into address.  Return true if the
 * address changed; false otherwise.
657
 */
658
int
659
660
addressmap_rewrite(char *address, size_t maxlen)
{
661
662
  addressmap_entry_t *ent;
  int rewrites;
663
  char *cp;
664
665
666
667
668

  for (rewrites = 0; rewrites < 16; rewrites++) {
    ent = strmap_get(addressmap, address);

    if (!ent || !ent->new_address)
669
      return (rewrites > 0); /* done, no rewrite needed */
670

671
    cp = tor_strdup(escaped_safe_str(ent->new_address));
672
    log_info(LD_APP, "Addressmap: rewriting %s to %s",
673
674
             escaped_safe_str(address), cp);
    tor_free(cp);
675
676
    strlcpy(address, ent->new_address, maxlen);
  }
Roger Dingledine's avatar
Roger Dingledine committed
677
  log_warn(LD_CONFIG,
678
679
           "Loop detected: we've rewritten %s 16 times! Using it as-is.",
           escaped_safe_str(address));
680
  /* it's fine to rewrite a rewrite, but don't loop forever */
681
  return 1;
682
683
}

684
/** If we have a cached reverse DNS entry for the address stored in the
685
686
 * <b>maxlen</b>-byte buffer <b>address</b> (typically, a dotted quad) then
 * rewrite to the cached value and return 1.  Otherwise return 0. */
687
688
689
690
691
692
693
694
695
696
697
static int
addressmap_rewrite_reverse(char *address, size_t maxlen)
{
  size_t len = maxlen + 16;
  char *s = tor_malloc(len), *cp;
  addressmap_entry_t *ent;
  int r = 0;
  tor_snprintf(s, len, "REVERSE[%s]", address);
  ent = strmap_get(addressmap, s);
  if (ent) {
    cp = tor_strdup(escaped_safe_str(ent->new_address));
698
    log_info(LD_APP, "Rewrote reverse lookup %s -> %s",
699
700
701
702
703
704
705
706
707
             escaped_safe_str(s), cp);
    tor_free(cp);
    strlcpy(address, ent->new_address, maxlen);
    r = 1;
  }
  tor_free(s);
  return r;
}

708
/** Return 1 if <b>address</b> is already registered, else return 0 */
709
int
710
addressmap_have_mapping(const char *address)
711
{
712
  return strmap_get_lc(addressmap, address) ? 1 : 0;
713
714
715
}

/** Register a request to map <b>address</b> to <b>new_address</b>,
716
717
718
 * which will expire on <b>expires</b> (or 0 if never expires from
 * config file, 1 if never expires from controller, 2 if never expires
 * (virtual address mapping) from the controller.)
719
 *
720
 * <b>new_address</b> should be a newly dup'ed string, which we'll use or
721
 * free as appropriate. We will leave address alone.
722
723
724
 *
 * If <b>new_address</b> is NULL, or equal to <b>address</b>, remove
 * any mappings that exist from <b>address</b>.
725
 */
726
727
728
void
addressmap_register(const char *address, char *new_address, time_t expires)
{
729
730
731
  addressmap_entry_t *ent;

  ent = strmap_get(addressmap, address);
732
  if (!new_address || !strcasecmp(address,new_address)) {
733
    /* Remove the mapping, if any. */
734
735
    tor_free(new_address);
    if (ent) {
736
      addressmap_ent_remove(address,ent);
737
738
739
740
      strmap_remove(addressmap, address);
    }
    return;
  }
741
742
743
744
745
  if (!ent) { /* make a new one and register it */
    ent = tor_malloc_zero(sizeof(addressmap_entry_t));
    strmap_set(addressmap, address, ent);
  } else if (ent->new_address) { /* we need to clean up the old mapping. */
    if (expires > 1) {
Roger Dingledine's avatar
Roger Dingledine committed
746
747
      log_info(LD_APP,"Temporary addressmap ('%s' to '%s') not performed, "
               "since it's already mapped to '%s'",
748
      safe_str(address), safe_str(new_address), safe_str(ent->new_address));
749
750
751
      tor_free(new_address);
      return;
    }
752
753
754
755
    if (address_is_in_virtual_range(ent->new_address) &&
        expires != 2) {
      /* XXX This isn't the perfect test; we want to avoid removing
       * mappings set from the control interface _as virtual mapping */
756
      addressmap_virtaddress_remove(address, ent);
757
    }
758
    tor_free(ent->new_address);
759
760
  } /* else { we have an in-progress resolve with no mapping. } */

761
  ent->new_address = new_address;
762
  ent->expires = expires==2 ? 1 : expires;
763
764
  ent->num_resolve_failures = 0;

Roger Dingledine's avatar
Roger Dingledine committed
765
766
  log_info(LD_CONFIG, "Addressmap: (re)mapped '%s' to '%s'",
           safe_str(address), safe_str(ent->new_address));
767
  control_event_address_mapped(address, ent->new_address, expires);
768
769
770
771
772
773
}

/** An attempt to resolve <b>address</b> failed at some OR.
 * Increment the number of resolve failures we have on record
 * for it, and then return that number.
 */
774
775
int
client_dns_incr_failures(const char *address)
776
{
777
  addressmap_entry_t *ent = strmap_get(addressmap, address);
778
779
  if (!ent) {
    ent = tor_malloc_zero(sizeof(addressmap_entry_t));
780
    ent->expires = time(NULL) + MAX_DNS_ENTRY_AGE;
781
782
783
    strmap_set(addressmap,address,ent);
  }
  ++ent->num_resolve_failures;
Roger Dingledine's avatar
Roger Dingledine committed
784
785
  log_info(LD_APP, "Address %s now has %d resolve failures.",
           safe_str(address), ent->num_resolve_failures);
786
787
788
  return ent->num_resolve_failures;
}

789
790
791
792
793
794
795
796
797
798
799
800
801
/** If <b>address</b> is in the client dns addressmap, reset
 * the number of resolve failures we have on record for it.
 * This is used when we fail a stream because it won't resolve:
 * otherwise future attempts on that address will only try once.
 */
void
client_dns_clear_failures(const char *address)
{
  addressmap_entry_t *ent = strmap_get(addressmap, address);
  if (ent)
    ent->num_resolve_failures = 0;
}

802
/** Record the fact that <b>address</b> resolved to <b>name</b>.
803
804
 * We can now use this in subsequent streams via addressmap_rewrite()
 * so we can more correctly choose an exit that will allow <b>address</b>.
805
806
807
 *
 * If <b>exitname</b> is defined, then append the addresses with
 * ".exitname.exit" before registering the mapping.
808
809
 *
 * If <b>ttl</b> is nonnegative, the mapping will be valid for
810
 * <b>ttl</b>seconds; otherwise, we use the default.
811
 */
812
813
814
815
static void
client_dns_set_addressmap_impl(const char *address, const char *name,
                               const char *exitname,
                               int ttl)
816
{
Nick Mathewson's avatar
Nick Mathewson committed
817
  /* <address>.<hex or nickname>.exit\0  or just  <address>\0 */
818
  char extendedaddress[MAX_SOCKS_ADDR_LEN+MAX_VERBOSE_NICKNAME_LEN+10];
Roger Dingledine's avatar
Roger Dingledine committed
819
  /* 123.123.123.123.<hex or nickname>.exit\0  or just  123.123.123.123\0 */
820
  char extendedval[INET_NTOA_BUF_LEN+MAX_VERBOSE_NICKNAME_LEN+10];
821

822
  tor_assert(address);
823
  tor_assert(name);
824

825
826
827
828
  if (ttl<0)
    ttl = DEFAULT_DNS_TTL;
  else
    ttl = dns_clip_ttl(ttl);
829

830
  if (exitname) {
831
832
833
    /* XXXX fails to ever get attempts to get an exit address of
     * google.com.digest[=~]nickname.exit; we need a syntax for this that
     * won't make strict RFC952-compliant applications (like us) barf. */
834
835
836
    tor_snprintf(extendedaddress, sizeof(extendedaddress),
                 "%s.%s.exit", address, exitname);
    tor_snprintf(extendedval, sizeof(extendedval),
837
                 "%s.%s.exit", name, exitname);
838
839
840
841
  } else {
    tor_snprintf(extendedaddress, sizeof(extendedaddress),
                 "%s", address);
    tor_snprintf(extendedval, sizeof(extendedval),
842
                 "%s", name);
843
  }
844
845
  addressmap_register(extendedaddress, tor_strdup(extendedval),
                      time(NULL) + ttl);
846
847
}

848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
/** Record the fact that <b>address</b> resolved to <b>val</b>.
 * We can now use this in subsequent streams via addressmap_rewrite()
 * so we can more correctly choose an exit that will allow <b>address</b>.
 *
 * If <b>exitname</b> is defined, then append the addresses with
 * ".exitname.exit" before registering the mapping.
 *
 * If <b>ttl</b> is nonnegative, the mapping will be valid for
 * <b>ttl</b>seconds; otherwise, we use the default.
 */
void
client_dns_set_addressmap(const char *address, uint32_t val,
                          const char *exitname,
                          int ttl)
{
  struct in_addr in;
  char valbuf[INET_NTOA_BUF_LEN];

  tor_assert(address);

  if (tor_inet_aton(address, &in))
    return; /* If address was an IP address already, don't add a mapping. */
  in.s_addr = htonl(val);
  tor_inet_ntoa(&in,valbuf,sizeof(valbuf));

  client_dns_set_addressmap_impl(address, valbuf, exitname, ttl);
}

876
877
878
879
880
881
882
883
884
/** Add a cache entry noting that <b>address</b> (ordinarily a dotted quad)
 * resolved via a RESOLVE_PTR request to the hostname <b>v</b>.
 *
 * If <b>exitname</b> is defined, then append the addresses with
 * ".exitname.exit" before registering the mapping.
 *
 * If <b>ttl</b> is nonnegative, the mapping will be valid for
 * <b>ttl</b>seconds; otherwise, we use the default.
 */
885
886
887
888
889
890
891
892
893
894
895
896
static void
client_dns_set_reverse_addressmap(const char *address, const char *v,
                                  const char *exitname,
                                  int ttl)
{
  size_t len = strlen(address) + 16;
  char *s = tor_malloc(len);
  tor_snprintf(s, len, "REVERSE[%s]", address);
  client_dns_set_addressmap_impl(s, v, exitname, ttl);
  tor_free(s);
}

897
/* By default, we hand out 127.192.0.1 through 127.254.254.254.
898
899
900
901
 * These addresses should map to localhost, so even if the
 * application accidentally tried to connect to them directly (not
 * via Tor), it wouldn't get too far astray.
 *
902
 * These options are configured by parse_virtual_addr_network().
903
 */