connection_edge.c 104 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-2006, Roger Dingledine, Nick Mathewson.
Karsten Loesing's avatar
Karsten Loesing committed
4
 * Copyright (c) 2007-2009, The Tor Project, Inc. */
5
6
/* See LICENSE for licensing information */

7
8
/**
 * \file connection_edge.c
9
 * \brief Handle edge streams.
10
11
 **/

12
13
#include "or.h"

14
15
16
#ifdef HAVE_LINUX_TYPES_H
#include <linux/types.h>
#endif
17
18
19
20
21
22
23
24
25
26
27
#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

28
29
30
#define SOCKS4_GRANTED          90
#define SOCKS4_REJECT           91

31
static int connection_ap_handshake_process_socks(edge_connection_t *conn);
32
static int connection_ap_process_natd(edge_connection_t *conn);
Roger Dingledine's avatar
Roger Dingledine committed
33
static int connection_exit_connect_dir(edge_connection_t *exitconn);
34
static int address_is_in_virtual_range(const char *addr);
35
static int consider_plaintext_ports(edge_connection_t *conn, uint16_t port);
36
static void clear_trackexithost_mappings(const char *exitname);
37

38
39
40
41
42
/** 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
43
_connection_mark_unattached_ap(edge_connection_t *conn, int endreason,
44
45
                               int line, const char *file)
{
46
  tor_assert(conn->_base.type == CONN_TYPE_AP);
47
  conn->edge_has_sent_end = 1; /* no circ yet */
48

49
  if (conn->_base.marked_for_close) {
50
    /* This call will warn as appropriate. */
51
    _connection_mark_for_close(TO_CONN(conn), line, file);
52
53
54
    return;
  }

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

61
    if (SOCKS_COMMAND_IS_CONNECT(conn->socks_request->command))
62
      connection_ap_handshake_socks_reply(conn, NULL, 0, endreason);
63
    else if (SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command))
64
65
      connection_ap_handshake_socks_resolved(conn,
                                             RESOLVED_TYPE_ERROR_TRANSIENT,
66
                                             0, NULL, -1, -1);
67
68
    else /* unknown or no handshake at all. send no response. */
      conn->socks_request->has_finished = 1;
69
  }
70

71
72
  _connection_mark_for_close(TO_CONN(conn), line, file);
  conn->_base.hold_open_until_flushed = 1;
73
  conn->end_reason = endreason;
74
75
}

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

/** Handle new bytes on conn->inbuf based on state:
99
100
 *   - If it's waiting for socks info, try to read another step of the
 *     socks handshake out of conn->inbuf.
101
 *   - If it's waiting for the original destination, fetch it.
102
103
104
105
 *   - 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,
106
107
 * else return 0.
 */
108
int
109
connection_edge_process_inbuf(edge_connection_t *conn, int package_partial)
110
{
Roger Dingledine's avatar
Roger Dingledine committed
111
  tor_assert(conn);
112

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

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

181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
/** Send a raw end cell to the stream with ID <b>stream_id</b> out over the
 * <b>circ</b> towards the hop identified with <b>cpath_layer</b>. If this
 * is not a client connection, set the relay end cell's reason for closing
 * as <b>reason</b> */
static int
relay_send_end_cell_from_edge(streamid_t stream_id, circuit_t *circ,
                              uint8_t reason, crypt_path_t *cpath_layer)
{
  char payload[1];

  if (CIRCUIT_PURPOSE_IS_CLIENT(circ->purpose)) {
    /* Never send the server an informative reason code; it doesn't need to
     * know why the client stream is failing. */
    reason = END_STREAM_REASON_MISC;
  }

  payload[0] = (char) reason;

  return relay_send_command_from_edge(stream_id, circ, RELAY_COMMAND_END,
                                      payload, 1, cpath_layer);
}

/** Send a relay end cell from stream <b>conn</b> down conn's circuit, and
 * remember that we've done so.  If this is not a client connection, set the
 * relay end cell's reason for closing as <b>reason</b>.
206
207
208
209
 *
 * Return -1 if this function has already been called on this conn,
 * else return 0.
 */
210
int
211
connection_edge_end(edge_connection_t *conn, uint8_t reason)
212
{
213
  char payload[RELAY_PAYLOAD_SIZE];
214
  size_t payload_len=1;
215
  circuit_t *circ;
Mike Perry's avatar
   
Mike Perry committed
216
  uint8_t control_reason = reason;
217

218
  if (conn->edge_has_sent_end) {
219
    log_warn(LD_BUG,"(Harmless.) Calling connection_edge_end (reason %d) "
Roger Dingledine's avatar
Roger Dingledine committed
220
             "on an already ended stream?", reason);
221
    tor_fragile_assert();
222
    return -1;
223
224
  }

225
  if (conn->_base.marked_for_close) {
Roger Dingledine's avatar
Roger Dingledine committed
226
    log_warn(LD_BUG,
227
             "called on conn that's already marked for close at %s:%d.",
228
             conn->_base.marked_for_close_file, conn->_base.marked_for_close);
229
230
231
    return 0;
  }

232
233
234
235
236
237
238
239
240
  circ = circuit_get_by_edge_conn(conn);
  if (circ && CIRCUIT_PURPOSE_IS_CLIENT(circ->purpose)) {
    /* If this is a client circuit, don't send the server an informative
     * reason code; it doesn't need to know why the client stream is
     * failing. */
    reason = END_STREAM_REASON_MISC;
  }

  payload[0] = (char)reason;
241
242
  if (reason == END_STREAM_REASON_EXITPOLICY &&
      !connection_edge_is_rendezvous_stream(conn)) {
243
244
245
246
247
248
249
250
251
252
    int addrlen;
    if (tor_addr_family(&conn->_base.addr) == AF_INET) {
      set_uint32(payload+1, tor_addr_to_ipv4n(&conn->_base.addr));
      addrlen = 4;
    } else {
      memcpy(payload+1, tor_addr_to_in6_addr8(&conn->_base.addr), 16);
      addrlen = 16;
    }
    set_uint32(payload+1+addrlen, htonl(dns_clip_ttl(conn->address_ttl)));
    payload_len += 4+addrlen;
253
254
  }

255
  if (circ && !circ->marked_for_close) {
256
    log_debug(LD_EDGE,"Sending end on conn (fd %d).",conn->_base.s);
257
    connection_edge_send_command(conn, RELAY_COMMAND_END,
258
                                 payload, payload_len);
259
  } else {
260
    log_debug(LD_EDGE,"No circ to send end on conn (fd %d).",
261
              conn->_base.s);
262
263
  }

264
  conn->edge_has_sent_end = 1;
Mike Perry's avatar
   
Mike Perry committed
265
  conn->end_reason = control_reason;
266
  return 0;
267
268
}

Nick Mathewson's avatar
Nick Mathewson committed
269
/** An error has just occurred on an operation on an edge connection
270
271
 * <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.
272
 **/
273
int
274
connection_edge_end_errno(edge_connection_t *conn)
275
276
277
{
  uint8_t reason;
  tor_assert(conn);
278
  reason = errno_to_stream_end_reason(tor_socket_errno(conn->_base.s));
279
  return connection_edge_end(conn, reason);
280
281
}

282
283
284
285
286
287
288
289
290
291
/** 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.
 */
292
int
293
connection_edge_finished_flushing(edge_connection_t *conn)
294
{
Roger Dingledine's avatar
Roger Dingledine committed
295
  tor_assert(conn);
296

297
  switch (conn->_base.state) {
298
299
    case AP_CONN_STATE_OPEN:
    case EXIT_CONN_STATE_OPEN:
300
      connection_stop_writing(TO_CONN(conn));
301
      connection_edge_consider_sending_sendme(conn);
302
      return 0;
Roger Dingledine's avatar
Roger Dingledine committed
303
    case AP_CONN_STATE_SOCKS_WAIT:
304
    case AP_CONN_STATE_NATD_WAIT:
305
    case AP_CONN_STATE_RENDDESC_WAIT:
306
    case AP_CONN_STATE_CIRCUIT_WAIT:
307
    case AP_CONN_STATE_CONNECT_WAIT:
308
    case AP_CONN_STATE_CONTROLLER_WAIT:
309
      connection_stop_writing(TO_CONN(conn));
Roger Dingledine's avatar
Roger Dingledine committed
310
      return 0;
311
    default:
312
      log_warn(LD_BUG, "Called in unexpected state %d.",conn->_base.state);
313
      tor_fragile_assert();
314
      return -1;
315
316
317
318
  }
  return 0;
}

319
320
321
/** 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. */
322
int
323
connection_edge_finished_connecting(edge_connection_t *edge_conn)
324
{
325
  connection_t *conn;
326

327
328
329
  tor_assert(edge_conn);
  tor_assert(edge_conn->_base.type == CONN_TYPE_EXIT);
  conn = TO_CONN(edge_conn);
330
331
  tor_assert(conn->state == EXIT_CONN_STATE_CONNECTING);

Roger Dingledine's avatar
Roger Dingledine committed
332
  log_info(LD_EXIT,"Exit connection to %s:%u (%s) established.",
333
           escaped_safe_str(conn->address),conn->port,
334
           safe_str(fmt_addr(&conn->addr)));
335

336
  rep_hist_note_exit_stream_opened(conn->port);
337

338
  conn->state = EXIT_CONN_STATE_OPEN;
339
  connection_watch_events(conn, READ_EVENT); /* stop writing, keep reading */
340
341
  if (connection_wants_to_flush(conn)) /* in case there are any queued relay
                                        * cells */
342
343
    connection_start_writing(conn);
  /* deliver a 'connected' relay cell back through the circuit. */
344
345
  if (connection_edge_is_rendezvous_stream(edge_conn)) {
    if (connection_edge_send_command(edge_conn,
346
                                     RELAY_COMMAND_CONNECTED, NULL, 0) < 0)
347
348
      return 0; /* circuit is closed, don't continue */
  } else {
349
350
351
352
353
354
355
356
357
358
359
360
361
    char connected_payload[20];
    int connected_payload_len;
    if (tor_addr_family(&conn->addr) == AF_INET) {
      set_uint32(connected_payload, tor_addr_to_ipv4n(&conn->addr));
      set_uint32(connected_payload+4,
                 htonl(dns_clip_ttl(edge_conn->address_ttl)));
      connected_payload_len = 8;
    } else {
      memcpy(connected_payload, tor_addr_to_in6_addr8(&conn->addr), 16);
      set_uint32(connected_payload+16,
                 htonl(dns_clip_ttl(edge_conn->address_ttl)));
      connected_payload_len = 20;
    }
362
    if (connection_edge_send_command(edge_conn,
363
364
                                 RELAY_COMMAND_CONNECTED,
                                 connected_payload, connected_payload_len) < 0)
365
366
      return 0; /* circuit is closed, don't continue */
  }
367
  tor_assert(edge_conn->package_window > 0);
368
  /* in case the server has written anything */
369
  return connection_edge_process_inbuf(edge_conn, 1);
370
371
}

372
373
/** Define a schedule for how long to wait between retrying
 * application connections. Rather than waiting a fixed amount of
374
 * time between each retry, we wait 10 seconds each for the first
375
 * two tries, and 15 seconds for each retry after
376
 * that. Hopefully this will improve the expected user experience. */
377
static int
378
compute_retry_timeout(edge_connection_t *conn)
379
{
380
381
382
  int timeout = get_options()->CircuitStreamTimeout;
  if (timeout) /* if our config options override the default, use them */
    return timeout;
383
  if (conn->num_socks_retries < 2) /* try 0 and try 1 */
384
385
386
387
    return 10;
  return 15;
}

388
/** Find all general-purpose AP streams waiting for a response that sent their
389
 * begin/resolve cell too long ago. Detach from their current circuit, and
390
 * mark their current circuit as unsuitable for new streams. Then call
391
392
393
 * connection_ap_handshake_attach_circuit() to attach to a new circuit (if
 * available) or launch a new one.
 *
394
 * For rendezvous streams, simply give up after SocksTimeout seconds (with no
395
396
 * retry attempt).
 */
397
398
399
void
connection_ap_expire_beginning(void)
{
400
  edge_connection_t *conn;
401
  circuit_t *circ;
402
  time_t now = time(NULL);
403
  or_options_t *options = get_options();
404
  int severity;
405
  int cutoff;
406
  int seconds_idle, seconds_since_born;
407
  smartlist_t *conns = get_connection_array();
408

409
  SMARTLIST_FOREACH_BEGIN(conns, connection_t *, c) {
410
    if (c->type != CONN_TYPE_AP || c->marked_for_close)
411
      continue;
412
    conn = TO_EDGE_CONN(c);
413
    /* if it's an internal linked connection, don't yell its status. */
414
    severity = (tor_addr_is_null(&conn->_base.addr) && !conn->_base.port)
415
      ? LOG_INFO : LOG_NOTICE;
416
    seconds_idle = (int)( now - conn->_base.timestamp_lastread );
417
    seconds_since_born = (int)( now - conn->_base.timestamp_created );
418

419
420
421
422
423
424
425
    if (conn->_base.state == AP_CONN_STATE_OPEN)
      continue;

    /* We already consider SocksTimeout in
     * connection_ap_handshake_attach_circuit(), but we need to consider
     * it here too because controllers that put streams in controller_wait
     * state never ask Tor to attach the circuit. */
426
    if (AP_CONN_STATE_IS_UNATTACHED(conn->_base.state)) {
427
      if (seconds_since_born >= options->SocksTimeout) {
428
429
430
        log_fn(severity, LD_APP,
            "Tried for %d seconds to get a connection to %s:%d. "
            "Giving up. (%s)",
431
            seconds_since_born, safe_str(conn->socks_request->address),
432
433
            conn->socks_request->port,
            conn_state_to_string(CONN_TYPE_AP, conn->_base.state));
434
        connection_mark_unattached_ap(conn, END_STREAM_REASON_TIMEOUT);
435
436
437
438
      }
      continue;
    }

439
440
441
442
    /* 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);
443
    if (seconds_idle < cutoff)
444
      continue;
445
    circ = circuit_get_by_edge_conn(conn);
446
    if (!circ) { /* it's vanished? */
Roger Dingledine's avatar
Roger Dingledine committed
447
448
      log_info(LD_APP,"Conn is waiting (address %s), but lost its circ.",
               safe_str(conn->socks_request->address));
449
      connection_mark_unattached_ap(conn, END_STREAM_REASON_TIMEOUT);
450
451
      continue;
    }
452
    if (circ->purpose == CIRCUIT_PURPOSE_C_REND_JOINED) {
453
      if (seconds_idle >= options->SocksTimeout) {
454
455
456
        log_fn(severity, LD_REND,
               "Rend stream is %d seconds late. Giving up on address"
               " '%s.onion'.",
457
               seconds_idle,
458
               safe_str(conn->socks_request->address));
459
        connection_edge_end(conn, END_STREAM_REASON_TIMEOUT);
460
        connection_mark_unattached_ap(conn, END_STREAM_REASON_TIMEOUT);
461
462
463
      }
      continue;
    }
Roger Dingledine's avatar
Roger Dingledine committed
464
    tor_assert(circ->purpose == CIRCUIT_PURPOSE_C_GENERAL);
465
    log_fn(cutoff < 15 ? LOG_INFO : severity, LD_APP,
466
467
           "We tried for %d seconds to connect to '%s' using exit '%s'."
           " Retrying on a new circuit.",
468
           seconds_idle, safe_str(conn->socks_request->address),
469
470
           conn->cpath_layer ?
             conn->cpath_layer->extend_info->nickname : "*unnamed*");
471
    /* send an end down the circuit */
472
    connection_edge_end(conn, END_STREAM_REASON_TIMEOUT);
473
    /* un-mark it as ending, since we're going to reuse it */
474
    conn->edge_has_sent_end = 0;
475
    conn->end_reason = 0;
476
477
478
479
    /* 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);
480
    circ->timestamp_dirty -= options->MaxCircuitDirtiness;
481
    /* give our stream another 'cutoff' seconds to try */
482
    conn->_base.timestamp_lastread += cutoff;
483
484
    if (conn->num_socks_retries < 250) /* avoid overflow */
      conn->num_socks_retries++;
485
    /* move it back into 'pending' state, and try to attach. */
486
487
    if (connection_ap_detach_retriable(conn, TO_ORIGIN_CIRCUIT(circ),
                                       END_STREAM_REASON_TIMEOUT)<0) {
488
489
      if (!conn->_base.marked_for_close)
        connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
490
    }
491
  } SMARTLIST_FOREACH_END(conn);
492
493
}

494
495
/** 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.
496
 */
497
498
void
connection_ap_attach_pending(void)
499
{
500
  edge_connection_t *edge_conn;
501
502
503
  smartlist_t *conns = get_connection_array();
  SMARTLIST_FOREACH(conns, connection_t *, conn,
  {
Roger Dingledine's avatar
Roger Dingledine committed
504
505
    if (conn->marked_for_close ||
        conn->type != CONN_TYPE_AP ||
506
        conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
507
      continue;
508
509
    edge_conn = TO_EDGE_CONN(conn);
    if (connection_ap_handshake_attach_circuit(edge_conn) < 0) {
510
511
512
      if (!edge_conn->_base.marked_for_close)
        connection_mark_unattached_ap(edge_conn,
                                      END_STREAM_REASON_CANT_ATTACH);
513
    }
514
  });
515
516
}

Nick Mathewson's avatar
Nick Mathewson committed
517
/** Tell any AP streams that are waiting for a one-hop tunnel to
518
 * <b>failed_digest</b> that they are going to fail. */
519
/* XXX022 We should get rid of this function, and instead attach
Nick Mathewson's avatar
Nick Mathewson committed
520
 * one-hop streams to circ->p_streams so they get marked in
521
522
 * circuit_mark_for_close like normal p_streams. */
void
523
524
connection_ap_fail_onehop(const char *failed_digest,
                          cpath_build_state_t *build_state)
525
526
527
528
{
  edge_connection_t *edge_conn;
  char digest[DIGEST_LEN];
  smartlist_t *conns = get_connection_array();
529
  SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
530
531
532
533
534
535
536
    if (conn->marked_for_close ||
        conn->type != CONN_TYPE_AP ||
        conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
      continue;
    edge_conn = TO_EDGE_CONN(conn);
    if (!edge_conn->want_onehop)
      continue;
537
538
539
540
541
    if (hexdigest_to_digest(edge_conn->chosen_exit_name, digest) < 0 ||
        memcmp(digest, failed_digest, DIGEST_LEN))
      continue;
    if (tor_digest_is_zero(digest)) {
      /* we don't know the digest; have to compare addr:port */
542
      tor_addr_t addr;
543
      if (!build_state || !build_state->chosen_exit ||
544
545
546
547
          !edge_conn->socks_request || !edge_conn->socks_request->address)
        continue;
      if (tor_addr_from_str(&addr, edge_conn->socks_request->address)<0 ||
          !tor_addr_eq(&build_state->chosen_exit->addr, &addr) ||
548
549
          build_state->chosen_exit->port != edge_conn->socks_request->port)
        continue;
550
    }
Nick Mathewson's avatar
Nick Mathewson committed
551
    log_info(LD_APP, "Closing one-hop stream to '%s/%s' because the OR conn "
552
553
554
                     "just failed.", edge_conn->chosen_exit_name,
                     edge_conn->socks_request->address);
    connection_mark_unattached_ap(edge_conn, END_STREAM_REASON_TIMEOUT);
555
  } SMARTLIST_FOREACH_END(conn);
556
557
}

558
559
560
561
562
563
564
565
566
567
/** 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;

568
  smartlist_t *conns = get_connection_array();
569
  SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
570
571
    if (conn->marked_for_close ||
        conn->type != CONN_TYPE_AP ||
572
        conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
573
574
      continue;
    edge_conn = TO_EDGE_CONN(conn);
575
576
577
    if (!edge_conn->chosen_exit_optional &&
        !edge_conn->chosen_exit_retries)
      continue;
578
579
    r1 = router_get_by_nickname(edge_conn->chosen_exit_name, 0);
    r2 = router_get_by_nickname(info->nickname, 0);
580
581
582
    if (!r1 || !r2 || r1 != r2)
      continue;
    tor_assert(edge_conn->socks_request);
583
    if (edge_conn->chosen_exit_optional) {
584
585
586
      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));
587
      edge_conn->chosen_exit_optional = 0;
588
      tor_free(edge_conn->chosen_exit_name); /* clears it */
589
590
591
      /* if this port is dangerous, warn or reject it now that we don't
       * think it'll be using an enclave. */
      consider_plaintext_ports(edge_conn, edge_conn->socks_request->port);
592
    }
593
594
    if (edge_conn->chosen_exit_retries) {
      if (--edge_conn->chosen_exit_retries == 0) { /* give up! */
595
        clear_trackexithost_mappings(edge_conn->chosen_exit_name);
596
597
598
599
600
601
        tor_free(edge_conn->chosen_exit_name); /* clears it */
        /* if this port is dangerous, warn or reject it now that we don't
         * think it'll be using an enclave. */
        consider_plaintext_ports(edge_conn, edge_conn->socks_request->port);
      }
    }
602
  } SMARTLIST_FOREACH_END(conn);
603
604
}

605
606
/** The AP connection <b>conn</b> has just failed while attaching or
 * sending a BEGIN or resolving on <b>circ</b>, but another circuit
607
 * might work. Detach the circuit, and either reattach it, launch a
608
609
610
 * new circuit, tell the controller, or give up as a appropriate.
 *
 * Returns -1 on err, 1 on success, 0 on not-yet-sure.
611
612
 */
int
613
614
connection_ap_detach_retriable(edge_connection_t *conn, origin_circuit_t *circ,
                               int reason)
615
{
616
  control_event_stream_status(conn, STREAM_EVENT_FAILED_RETRIABLE, reason);
617
  conn->_base.timestamp_lastread = time(NULL);
618
619
620
  if (!get_options()->LeaveStreamsUnattached || conn->use_begindir) {
    /* If we're attaching streams ourself, or if this connection is
     * a tunneled directory connection, then just attach it. */
621
    conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
622
    circuit_detach_stream(TO_CIRCUIT(circ),conn);
623
624
    return connection_ap_handshake_attach_circuit(conn);
  } else {
625
    conn->_base.state = AP_CONN_STATE_CONTROLLER_WAIT;
626
    circuit_detach_stream(TO_CIRCUIT(circ),conn);
627
628
629
630
    return 0;
  }
}

631
/** A client-side struct to remember requests to rewrite addresses
632
 * to new addresses. These structs are stored in the hash table
633
 * "addressmap" below.
634
635
636
637
638
 *
 * 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]
Nick Mathewson's avatar
Nick Mathewson committed
639
640
 * - When a DNS resolve succeeds [temporary]
 * - When a DNS resolve fails [temporary]
641
642
643
 *
 * When an addressmap request is made but one is already registered,
 * the new one is replaced only if the currently registered one has
Nick Mathewson's avatar
Nick Mathewson committed
644
 * no "new_address" (that is, it's in the process of DNS resolve),
645
646
647
648
 * 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
649
650
 * interface, and other values for DNS and TrackHostExit mappings that can
 * expire.)
651
652
653
654
 */
typedef struct {
  char *new_address;
  time_t expires;
655
656
  addressmap_entry_source_t source:3;
  short num_resolve_failures;
657
658
} addressmap_entry_t;

659
/** Entry for mapping addresses to which virtual address we mapped them to. */
660
661
662
663
664
typedef struct {
  char *ipv4_address;
  char *hostname_address;
} virtaddress_entry_t;

665
/** A hash table to store client-side address rewrite instructions. */
666
static strmap_t *addressmap=NULL;
667
/**
668
 * Table mapping addresses to which virtual address, if any, we
669
670
671
672
673
674
675
676
 * 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.
 **/
677
static strmap_t *virtaddress_reversemap=NULL;
678
679

/** Initialize addressmap. */
680
681
682
void
addressmap_init(void)
{
683
  addressmap = strmap_new();
684
  virtaddress_reversemap = strmap_new();
685
686
687
688
}

/** Free the memory associated with the addressmap entry <b>_ent</b>. */
static void
689
690
addressmap_ent_free(void *_ent)
{
691
692
693
694
695
  addressmap_entry_t *ent;
  if (!_ent)
    return;

  ent = _ent;
696
697
698
699
  tor_free(ent->new_address);
  tor_free(ent);
}

Roger Dingledine's avatar
Roger Dingledine committed
700
/** Free storage held by a virtaddress_entry_t* entry in <b>ent</b>. */
701
static void
702
703
addressmap_virtaddress_ent_free(void *_ent)
{
704
705
706
707
708
  virtaddress_entry_t *ent;
  if (!_ent)
    return;

  ent = _ent;
709
710
711
712
713
  tor_free(ent->ipv4_address);
  tor_free(ent->hostname_address);
  tor_free(ent);
}

Roger Dingledine's avatar
Roger Dingledine committed
714
/** Free storage held by a virtaddress_entry_t* entry in <b>ent</b>. */
715
static void
716
addressmap_virtaddress_remove(const char *address, addressmap_entry_t *ent)
717
{
718
719
  if (ent && ent->new_address &&
      address_is_in_virtual_range(ent->new_address)) {
720
721
    virtaddress_entry_t *ve =
      strmap_get(virtaddress_reversemap, ent->new_address);
722
    /*log_fn(LOG_NOTICE,"remove reverse mapping for %s",ent->new_address);*/
723
    if (ve) {
724
      if (!strcmp(address, ve->ipv4_address))
725
        tor_free(ve->ipv4_address);
726
      if (!strcmp(address, ve->hostname_address))
727
728
729
730
731
        tor_free(ve->hostname_address);
      if (!ve->ipv4_address && !ve->hostname_address) {
        tor_free(ve);
        strmap_remove(virtaddress_reversemap, ent->new_address);
      }
732
733
734
735
    }
  }
}

736
737
/** Remove <b>ent</b> (which must be mapped to by <b>address</b>) from the
 * client address maps. */
738
static void
739
addressmap_ent_remove(const char *address, addressmap_entry_t *ent)
740
{
741
  addressmap_virtaddress_remove(address, ent);
742
743
  addressmap_ent_free(ent);
}
744

745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
/** Unregister all TrackHostExits mappings from any address to
 * *.exitname.exit. */
static void
clear_trackexithost_mappings(const char *exitname)
{
  char *suffix;
  size_t suffix_len;
  if (!addressmap || !exitname)
    return;
  suffix_len = strlen(exitname) + 16;
  suffix = tor_malloc(suffix_len);
  tor_snprintf(suffix, suffix_len, ".%s.exit", exitname);
  tor_strlower(suffix);

  STRMAP_FOREACH_MODIFY(addressmap, address, addressmap_entry_t *, ent) {
    if (ent->source == ADDRMAPSRC_TRACKEXIT && !strcmpend(address, suffix)) {
      addressmap_ent_remove(address, ent);
      MAP_DEL_CURRENT(address);
    }
  } STRMAP_FOREACH_END;
765
766

  tor_free(suffix);
767
768
}

769
770
771
772
773
/** Remove all entries from the addressmap that were set via the
 * configuration file or the command line. */
void
addressmap_clear_configured(void)
{
774
  addressmap_get_mappings(NULL, 0, 0, 0);
775
776
777
778
779
780
}

/** Remove all entries from the addressmap that are set to expire, ever. */
void
addressmap_clear_transient(void)
{
781
  addressmap_get_mappings(NULL, 2, TIME_MAX, 0);
782
783
784
785
786
}

/** Clean out entries from the addressmap cache that were
 * added long enough ago that they are no longer valid.
 */
787
788
789
void
addressmap_clean(time_t now)
{
790
  addressmap_get_mappings(NULL, 2, now, 0);
791
792
793
794
}

/** Free all the elements in the addressmap, and free the addressmap
 * itself. */
795
796
797
void
addressmap_free_all(void)
{
798
799
800
801
802
803
804
805
  if (addressmap) {
    strmap_free(addressmap, addressmap_ent_free);
    addressmap = NULL;
  }
  if (virtaddress_reversemap) {
    strmap_free(virtaddress_reversemap, addressmap_virtaddress_ent_free);
    virtaddress_reversemap = NULL;
  }
806
807
808
809
}

/** Look at address, and rewrite it until it doesn't want any
 * more rewrites; but don't get into an infinite loop.
810
 * Don't write more than maxlen chars into address.  Return true if the
811
812
813
 * address changed; false otherwise.  Set *<b>expires_out</b> to the
 * expiry time of the result, or to <b>time_max</b> if the result does
 * not expire.
814
 */
815
int
816
addressmap_rewrite(char *address, size_t maxlen, time_t *expires_out)
817
{
818
819
  addressmap_entry_t *ent;
  int rewrites;
820
  char *cp;
821
  time_t expires = TIME_MAX;
822
823
824
825

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

826
827
828
    if (!ent || !ent->new_address) {
      if (expires_out)
        *expires_out = expires;
829
      return (rewrites > 0); /* done, no rewrite needed */
830
    }
831

832
    cp = tor_strdup(escaped_safe_str(ent->new_address));
833
    log_info(LD_APP, "Addressmap: rewriting %s to %s",
834
             escaped_safe_str(address), cp);
835
836
    if (ent->expires > 1 && ent->expires < expires)
      expires = ent->expires;
837
    tor_free(cp);
838
839
    strlcpy(address, ent->new_address, maxlen);
  }
Roger Dingledine's avatar
Roger Dingledine committed
840
  log_warn(LD_CONFIG,
841
842
           "Loop detected: we've rewritten %s 16 times! Using it as-is.",
           escaped_safe_str(address));
843
  /* it's fine to rewrite a rewrite, but don't loop forever */
844
845
  if (expires_out)
    *expires_out = TIME_MAX;
846
  return 1;
847
848
}

849
/** If we have a cached reverse DNS entry for the address stored in the
850
 * <b>maxlen</b>-byte buffer <b>address</b> (typically, a dotted quad) then
851
852
853
 * rewrite to the cached value and return 1.  Otherwise return 0.  Set
 * *<b>expires_out</b> to the expiry time of the result, or to <b>time_max</b>
 * if the result does not expire. */
854
static int
855
addressmap_rewrite_reverse(char *address, size_t maxlen, time_t *expires_out)
856
857
858
859
860
861
862
863
864
{
  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));
865
    log_info(LD_APP, "Rewrote reverse lookup %s -> %s",
866
867
868
869
870
             escaped_safe_str(s), cp);
    tor_free(cp);
    strlcpy(address, ent->new_address, maxlen);
    r = 1;
  }
871
872
873
874

  if (expires_out)
    *expires_out = (ent && ent->expires > 1) ? ent->expires : TIME_MAX;

875
876
877
878
  tor_free(s);
  return r;
}

879
880
881
882
/** Return 1 if <b>address</b> is already registered, else return 0. If address
 * is already registered, and <b>update_expires</b> is non-zero, then update
 * the expiry time on the mapping with update_expires if it is a
 * mapping created by TrackHostExits. */
883
int
884
addressmap_have_mapping(const char *address, int update_expiry)
885
{
886
887
888
889
890
891
  addressmap_entry_t *ent;
  if (!(ent=strmap_get_lc(addressmap, address)))
    return 0;
  if (update_expiry && ent->source==ADDRMAPSRC_TRACKEXIT)
    ent->expires=time(NULL) + update_expiry;
  return 1;