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
337
  rep_hist_note_exit_stream_opened(conn->port, approx_time());

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
  if (conn->num_socks_retries < 2) /* try 0 and try 1 */
381
382
383
384
    return 10;
  return 15;
}

385
386
387
/** 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
388
389
390
 * connection_ap_handshake_attach_circuit() to attach to a new circuit (if
 * available) or launch a new one.
 *
391
 * For rendezvous streams, simply give up after SocksTimeout seconds (with no
392
393
 * retry attempt).
 */
394
395
396
void
connection_ap_expire_beginning(void)
{
397
  edge_connection_t *conn;
398
  circuit_t *circ;
399
  time_t now = time(NULL);
400
  or_options_t *options = get_options();
401
  int severity;
402
  int cutoff;
403
  int seconds_idle, seconds_since_born;
404
  smartlist_t *conns = get_connection_array();
405

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

416
417
418
419
420
421
422
    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. */
423
    if (AP_CONN_STATE_IS_UNATTACHED(conn->_base.state)) {
424
      if (seconds_since_born >= options->SocksTimeout) {
425
426
427
        log_fn(severity, LD_APP,
            "Tried for %d seconds to get a connection to %s:%d. "
            "Giving up. (%s)",
428
            seconds_since_born, safe_str(conn->socks_request->address),
429
430
            conn->socks_request->port,
            conn_state_to_string(CONN_TYPE_AP, conn->_base.state));
431
        connection_mark_unattached_ap(conn, END_STREAM_REASON_TIMEOUT);
432
433
434
435
      }
      continue;
    }

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

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

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

555
556
557
558
559
560
561
562
563
564
/** 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;

565
  smartlist_t *conns = get_connection_array();
566
  SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
567
568
    if (conn->marked_for_close ||
        conn->type != CONN_TYPE_AP ||
569
        conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
570
571
      continue;
    edge_conn = TO_EDGE_CONN(conn);
572
573
574
    if (!edge_conn->chosen_exit_optional &&
        !edge_conn->chosen_exit_retries)
      continue;
575
576
    r1 = router_get_by_nickname(edge_conn->chosen_exit_name, 0);
    r2 = router_get_by_nickname(info->nickname, 0);
577
578
579
    if (!r1 || !r2 || r1 != r2)
      continue;
    tor_assert(edge_conn->socks_request);
580
    if (edge_conn->chosen_exit_optional) {
581
582
583
      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));
584
      edge_conn->chosen_exit_optional = 0;
585
      tor_free(edge_conn->chosen_exit_name); /* clears it */
586
587
588
      /* 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);
589
    }
590
591
    if (edge_conn->chosen_exit_retries) {
      if (--edge_conn->chosen_exit_retries == 0) { /* give up! */
592
        clear_trackexithost_mappings(edge_conn->chosen_exit_name);
593
594
595
596
597
598
        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);
      }
    }
599
  } SMARTLIST_FOREACH_END(conn);
600
601
}

602
603
/** The AP connection <b>conn</b> has just failed while attaching or
 * sending a BEGIN or resolving on <b>circ</b>, but another circuit
604
 * might work. Detach the circuit, and either reattach it, launch a
605
606
607
 * new circuit, tell the controller, or give up as a appropriate.
 *
 * Returns -1 on err, 1 on success, 0 on not-yet-sure.
608
609
 */
int
610
611
connection_ap_detach_retriable(edge_connection_t *conn, origin_circuit_t *circ,
                               int reason)
612
{
613
  control_event_stream_status(conn, STREAM_EVENT_FAILED_RETRIABLE, reason);
614
  conn->_base.timestamp_lastread = time(NULL);
615
616
617
  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. */
618
    conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
619
    circuit_detach_stream(TO_CIRCUIT(circ),conn);
620
621
    return connection_ap_handshake_attach_circuit(conn);
  } else {
622
    conn->_base.state = AP_CONN_STATE_CONTROLLER_WAIT;
623
    circuit_detach_stream(TO_CIRCUIT(circ),conn);
624
625
626
627
    return 0;
  }
}

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

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

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

/** Initialize addressmap. */
677
678
679
void
addressmap_init(void)
{
680
  addressmap = strmap_new();
681
  virtaddress_reversemap = strmap_new();
682
683
684
685
}

/** Free the memory associated with the addressmap entry <b>_ent</b>. */
static void
686
687
addressmap_ent_free(void *_ent)
{
688
689
690
691
692
  addressmap_entry_t *ent = _ent;
  tor_free(ent->new_address);
  tor_free(ent);
}

Roger Dingledine's avatar
Roger Dingledine committed
693
/** Free storage held by a virtaddress_entry_t* entry in <b>ent</b>. */
694
static void
695
696
addressmap_virtaddress_ent_free(void *_ent)
{
697
698
699
700
701
702
  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
703
/** Free storage held by a virtaddress_entry_t* entry in <b>ent</b>. */
704
static void
705
addressmap_virtaddress_remove(const char *address, addressmap_entry_t *ent)
706
{
707
708
  if (ent && ent->new_address &&
      address_is_in_virtual_range(ent->new_address)) {
709
710
    virtaddress_entry_t *ve =
      strmap_get(virtaddress_reversemap, ent->new_address);
711
    /*log_fn(LOG_NOTICE,"remove reverse mapping for %s",ent->new_address);*/
712
    if (ve) {
713
      if (!strcmp(address, ve->ipv4_address))
714
        tor_free(ve->ipv4_address);
715
      if (!strcmp(address, ve->hostname_address))
716
717
718
719
720
        tor_free(ve->hostname_address);
      if (!ve->ipv4_address && !ve->hostname_address) {
        tor_free(ve);
        strmap_remove(virtaddress_reversemap, ent->new_address);
      }
721
722
723
724
    }
  }
}

725
726
/** Remove <b>ent</b> (which must be mapped to by <b>address</b>) from the
 * client address maps. */
727
static void
728
addressmap_ent_remove(const char *address, addressmap_entry_t *ent)
729
{
730
  addressmap_virtaddress_remove(address, ent);
731
732
  addressmap_ent_free(ent);
}
733

734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
/** 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;
754
755

  tor_free(suffix);
756
757
}

758
759
760
761
762
/** Remove all entries from the addressmap that were set via the
 * configuration file or the command line. */
void
addressmap_clear_configured(void)
{
763
  addressmap_get_mappings(NULL, 0, 0, 0);
764
765
766
767
768
769
}

/** Remove all entries from the addressmap that are set to expire, ever. */
void
addressmap_clear_transient(void)
{
770
  addressmap_get_mappings(NULL, 2, TIME_MAX, 0);
771
772
773
774
775
}

/** Clean out entries from the addressmap cache that were
 * added long enough ago that they are no longer valid.
 */
776
777
778
void
addressmap_clean(time_t now)
{
779
  addressmap_get_mappings(NULL, 2, now, 0);
780
781
782
783
}

/** Free all the elements in the addressmap, and free the addressmap
 * itself. */
784
785
786
void
addressmap_free_all(void)
{
787
788
789
790
791
792
793
794
  if (addressmap) {
    strmap_free(addressmap, addressmap_ent_free);
    addressmap = NULL;
  }
  if (virtaddress_reversemap) {
    strmap_free(virtaddress_reversemap, addressmap_virtaddress_ent_free);
    virtaddress_reversemap = NULL;
  }
795
796
797
798
}

/** Look at address, and rewrite it until it doesn't want any
 * more rewrites; but don't get into an infinite loop.
799
 * Don't write more than maxlen chars into address.  Return true if the
800
801
802
 * 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.
803
 */
804
int
805
addressmap_rewrite(char *address, size_t maxlen, time_t *expires_out)
806
{
807
808
  addressmap_entry_t *ent;
  int rewrites;
809
  char *cp;
810
  time_t expires = TIME_MAX;
811
812
813
814

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

815
816
817
    if (!ent || !ent->new_address) {
      if (expires_out)
        *expires_out = expires;
818
      return (rewrites > 0); /* done, no rewrite needed */
819
    }
820

821
    cp = tor_strdup(escaped_safe_str(ent->new_address));
822
    log_info(LD_APP, "Addressmap: rewriting %s to %s",
823
             escaped_safe_str(address), cp);
824
825
    if (ent->expires > 1 && ent->expires < expires)
      expires = ent->expires;
826
    tor_free(cp);
827
828
    strlcpy(address, ent->new_address, maxlen);
  }
Roger Dingledine's avatar
Roger Dingledine committed
829
  log_warn(LD_CONFIG,
830
831
           "Loop detected: we've rewritten %s 16 times! Using it as-is.",
           escaped_safe_str(address));
832
  /* it's fine to rewrite a rewrite, but don't loop forever */
833
834
  if (expires_out)
    *expires_out = TIME_MAX;
835
  return 1;
836
837
}

838
/** If we have a cached reverse DNS entry for the address stored in the
839
 * <b>maxlen</b>-byte buffer <b>address</b> (typically, a dotted quad) then
840
841
842
 * 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. */
843
static int
844
addressmap_rewrite_reverse(char *address, size_t maxlen, time_t *expires_out)
845
846
847
848
849
850
851
852
853
{
  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));
854
    log_info(LD_APP, "Rewrote reverse lookup %s -> %s",
855
856
857
858
859
             escaped_safe_str(s), cp);
    tor_free(cp);
    strlcpy(address, ent->new_address, maxlen);
    r = 1;
  }
860
861
862
863

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

864
865
866
867
  tor_free(s);
  return r;
}

868
869
870
871
/** 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. */
872
int
873
addressmap_have_mapping(const char *address, int update_expiry)
874
{
875
876
877
878
879
880
  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;
881
882
883
}

/** Register a request to map <b>address</b> to <b>new_address</b>,
884
885
886
 * 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.)