connection_edge.c 113 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.
4
 * Copyright (c) 2007-2011, 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
#include "or.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
13
#include "buffers.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
14
#include "circuitlist.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
15
#include "circuituse.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
16
#include "config.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
17
#include "connection.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
18
#include "connection_edge.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
19
#include "connection_or.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
20
#include "control.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
21
#include "dns.h"
22
#include "dnsserv.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
23
#include "dirserv.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
24
#include "hibernate.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
25
#include "main.h"
26
#include "nodelist.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
27
#include "policies.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
28
#include "reasons.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
29
#include "relay.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
30
#include "rendclient.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
31
#include "rendcommon.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
32
#include "rendservice.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
33
#include "rephist.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
34
#include "router.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
35
#include "routerlist.h"
36

37
38
39
#ifdef HAVE_LINUX_TYPES_H
#include <linux/types.h>
#endif
40
41
42
43
44
45
46
47
48
49
50
#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

51
52
53
#define SOCKS4_GRANTED          90
#define SOCKS4_REJECT           91

54
static int connection_ap_handshake_process_socks(edge_connection_t *conn);
55
static int connection_ap_process_natd(edge_connection_t *conn);
Roger Dingledine's avatar
Roger Dingledine committed
56
static int connection_exit_connect_dir(edge_connection_t *exitconn);
57
static int address_is_in_virtual_range(const char *addr);
58
static int consider_plaintext_ports(edge_connection_t *conn, uint16_t port);
59
static void clear_trackexithost_mappings(const char *exitname);
60

61
62
63
64
65
/** 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
66
_connection_mark_unattached_ap(edge_connection_t *conn, int endreason,
67
68
                               int line, const char *file)
{
69
  tor_assert(conn->_base.type == CONN_TYPE_AP);
70
  conn->edge_has_sent_end = 1; /* no circ yet */
71

72
  if (conn->_base.marked_for_close) {
73
    /* This call will warn as appropriate. */
74
    _connection_mark_for_close(TO_CONN(conn), line, file);
75
76
77
    return;
  }

78
  if (!conn->socks_request->has_finished) {
79
    if (endreason & END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED)
Roger Dingledine's avatar
Roger Dingledine committed
80
      log_warn(LD_BUG,
81
               "stream (marked at %s:%d) sending two socks replies?",
Roger Dingledine's avatar
Roger Dingledine committed
82
               file, line);
83

84
    if (SOCKS_COMMAND_IS_CONNECT(conn->socks_request->command))
85
      connection_ap_handshake_socks_reply(conn, NULL, 0, endreason);
86
    else if (SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command))
87
88
      connection_ap_handshake_socks_resolved(conn,
                                             RESOLVED_TYPE_ERROR_TRANSIENT,
89
                                             0, NULL, -1, -1);
90
91
    else /* unknown or no handshake at all. send no response. */
      conn->socks_request->has_finished = 1;
92
  }
93

94
95
  _connection_mark_and_flush(TO_CONN(conn), line, file);

96
  conn->end_reason = endreason;
97
98
}

99
100
/** There was an EOF. Send an end and mark the connection for close.
 */
101
int
102
connection_edge_reached_eof(edge_connection_t *conn)
103
{
104
  if (connection_get_inbuf_len(TO_CONN(conn)) &&
105
      connection_state_is_open(TO_CONN(conn))) {
Roger Dingledine's avatar
Roger Dingledine committed
106
107
108
    /* it still has stuff to process. don't let it die yet. */
    return 0;
  }
109
110
  log_info(LD_EDGE,"conn (fd %d) reached eof. Closing.", conn->_base.s);
  if (!conn->_base.marked_for_close) {
111
112
    /* only mark it if not already marked. it's possible to
     * get the 'end' right around when the client hangs up on us. */
113
    connection_edge_end(conn, END_STREAM_REASON_DONE);
114
115
    if (conn->socks_request) /* eof, so don't send a socks reply back */
      conn->socks_request->has_finished = 1;
116
    connection_mark_for_close(TO_CONN(conn));
117
118
119
120
121
  }
  return 0;
}

/** Handle new bytes on conn->inbuf based on state:
122
123
 *   - If it's waiting for socks info, try to read another step of the
 *     socks handshake out of conn->inbuf.
124
 *   - If it's waiting for the original destination, fetch it.
125
126
127
128
 *   - 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,
129
130
 * else return 0.
 */
131
int
132
connection_edge_process_inbuf(edge_connection_t *conn, int package_partial)
133
{
Roger Dingledine's avatar
Roger Dingledine committed
134
  tor_assert(conn);
135

136
  switch (conn->_base.state) {
137
    case AP_CONN_STATE_SOCKS_WAIT:
138
      if (connection_ap_handshake_process_socks(conn) < 0) {
139
        /* already marked */
140
141
142
        return -1;
      }
      return 0;
143
144
145
146
147
148
    case AP_CONN_STATE_NATD_WAIT:
      if (connection_ap_process_natd(conn) < 0) {
        /* already marked */
        return -1;
      }
      return 0;
149
150
    case AP_CONN_STATE_OPEN:
    case EXIT_CONN_STATE_OPEN:
151
      if (connection_edge_package_raw_inbuf(conn, package_partial, NULL) < 0) {
152
        /* (We already sent an end cell if possible) */
153
        connection_mark_for_close(TO_CONN(conn));
154
155
        return -1;
      }
156
157
      return 0;
    case EXIT_CONN_STATE_CONNECTING:
158
    case AP_CONN_STATE_RENDDESC_WAIT:
159
160
    case AP_CONN_STATE_CIRCUIT_WAIT:
    case AP_CONN_STATE_CONNECT_WAIT:
161
    case AP_CONN_STATE_RESOLVE_WAIT:
162
    case AP_CONN_STATE_CONTROLLER_WAIT:
Roger Dingledine's avatar
Roger Dingledine committed
163
164
      log_info(LD_EDGE,
               "data from edge while in '%s' state. Leaving it on buffer.",
165
               conn_state_to_string(conn->_base.type, conn->_base.state));
166
167
      return 0;
  }
168
  log_warn(LD_BUG,"Got unexpected state %d. Closing.",conn->_base.state);
169
  tor_fragile_assert();
170
  connection_edge_end(conn, END_STREAM_REASON_INTERNAL);
171
  connection_mark_for_close(TO_CONN(conn));
172
  return -1;
173
174
}

175
176
177
/** This edge needs to be closed, because its circuit has closed.
 * Mark it for close and return 0.
 */
178
int
179
connection_edge_destroy(circid_t circ_id, edge_connection_t *conn)
180
{
181
  if (!conn->_base.marked_for_close) {
Roger Dingledine's avatar
Roger Dingledine committed
182
183
    log_info(LD_EDGE,
             "CircID %d: At an edge. Marking connection for close.", circ_id);
184
    if (conn->_base.type == CONN_TYPE_AP) {
185
      connection_mark_unattached_ap(conn, END_STREAM_REASON_DESTROY);
186
      control_event_stream_bandwidth(conn);
187
188
189
      control_event_stream_status(conn, STREAM_EVENT_CLOSED,
                                  END_STREAM_REASON_DESTROY);
      conn->end_reason |= END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED;
190
    } else {
191
      /* closing the circuit, nothing to send an END to */
192
      conn->edge_has_sent_end = 1;
193
      conn->end_reason = END_STREAM_REASON_DESTROY;
194
      conn->end_reason |= END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED;
195
      connection_mark_and_flush(TO_CONN(conn));
196
    }
197
  }
198
  conn->cpath_layer = NULL;
199
  conn->on_circuit = NULL;
200
201
202
  return 0;
}

203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
/** 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>.
228
229
230
231
 *
 * Return -1 if this function has already been called on this conn,
 * else return 0.
 */
232
int
233
connection_edge_end(edge_connection_t *conn, uint8_t reason)
234
{
235
  char payload[RELAY_PAYLOAD_SIZE];
236
  size_t payload_len=1;
237
  circuit_t *circ;
Mike Perry's avatar
   
Mike Perry committed
238
  uint8_t control_reason = reason;
239

240
  if (conn->edge_has_sent_end) {
241
    log_warn(LD_BUG,"(Harmless.) Calling connection_edge_end (reason %d) "
Roger Dingledine's avatar
Roger Dingledine committed
242
             "on an already ended stream?", reason);
243
    tor_fragile_assert();
244
    return -1;
245
246
  }

247
  if (conn->_base.marked_for_close) {
Roger Dingledine's avatar
Roger Dingledine committed
248
    log_warn(LD_BUG,
249
             "called on conn that's already marked for close at %s:%d.",
250
             conn->_base.marked_for_close_file, conn->_base.marked_for_close);
251
252
253
    return 0;
  }

254
255
256
257
258
259
260
261
262
  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;
263
264
  if (reason == END_STREAM_REASON_EXITPOLICY &&
      !connection_edge_is_rendezvous_stream(conn)) {
265
266
267
268
269
270
271
272
273
274
    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;
275
276
  }

277
  if (circ && !circ->marked_for_close) {
278
    log_debug(LD_EDGE,"Sending end on conn (fd %d).",conn->_base.s);
279
    connection_edge_send_command(conn, RELAY_COMMAND_END,
280
                                 payload, payload_len);
281
  } else {
282
    log_debug(LD_EDGE,"No circ to send end on conn (fd %d).",
283
              conn->_base.s);
284
285
  }

286
  conn->edge_has_sent_end = 1;
Mike Perry's avatar
   
Mike Perry committed
287
  conn->end_reason = control_reason;
288
  return 0;
289
290
}

Nick Mathewson's avatar
Nick Mathewson committed
291
/** An error has just occurred on an operation on an edge connection
292
293
 * <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.
294
 **/
295
int
296
connection_edge_end_errno(edge_connection_t *conn)
297
298
299
{
  uint8_t reason;
  tor_assert(conn);
300
  reason = errno_to_stream_end_reason(tor_socket_errno(conn->_base.s));
301
  return connection_edge_end(conn, reason);
302
303
}

304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
/** We just wrote some data to <b>conn</b>; act appropriately.
 *
 * (That is, if it's open, consider sending a stream-level sendme cell if we
 * have just flushed enough.)
 */
int
connection_edge_flushed_some(edge_connection_t *conn)
{
  switch (conn->_base.state) {
    case AP_CONN_STATE_OPEN:
    case EXIT_CONN_STATE_OPEN:
      connection_edge_consider_sending_sendme(conn);
      break;
  }
  return 0;
}

321
322
323
324
325
326
327
328
329
330
/** 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.
 */
331
int
332
connection_edge_finished_flushing(edge_connection_t *conn)
333
{
Roger Dingledine's avatar
Roger Dingledine committed
334
  tor_assert(conn);
335

336
  switch (conn->_base.state) {
337
338
    case AP_CONN_STATE_OPEN:
    case EXIT_CONN_STATE_OPEN:
339
      connection_edge_consider_sending_sendme(conn);
340
      return 0;
Roger Dingledine's avatar
Roger Dingledine committed
341
    case AP_CONN_STATE_SOCKS_WAIT:
342
    case AP_CONN_STATE_NATD_WAIT:
343
    case AP_CONN_STATE_RENDDESC_WAIT:
344
    case AP_CONN_STATE_CIRCUIT_WAIT:
345
    case AP_CONN_STATE_CONNECT_WAIT:
346
    case AP_CONN_STATE_CONTROLLER_WAIT:
347
    case AP_CONN_STATE_RESOLVE_WAIT:
Roger Dingledine's avatar
Roger Dingledine committed
348
      return 0;
349
    default:
350
      log_warn(LD_BUG, "Called in unexpected state %d.",conn->_base.state);
351
      tor_fragile_assert();
352
      return -1;
353
354
355
356
  }
  return 0;
}

357
358
359
/** 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. */
360
int
361
connection_edge_finished_connecting(edge_connection_t *edge_conn)
362
{
363
  connection_t *conn;
364

365
366
367
  tor_assert(edge_conn);
  tor_assert(edge_conn->_base.type == CONN_TYPE_EXIT);
  conn = TO_CONN(edge_conn);
368
369
  tor_assert(conn->state == EXIT_CONN_STATE_CONNECTING);

Roger Dingledine's avatar
Roger Dingledine committed
370
  log_info(LD_EXIT,"Exit connection to %s:%u (%s) established.",
371
           escaped_safe_str(conn->address), conn->port,
372
           safe_str(fmt_addr(&conn->addr)));
373

374
  rep_hist_note_exit_stream_opened(conn->port);
375

376
  conn->state = EXIT_CONN_STATE_OPEN;
377
378
379
  IF_HAS_NO_BUFFEREVENT(conn)
    connection_watch_events(conn, READ_EVENT); /* stop writing, keep reading */
  if (connection_get_outbuf_len(conn)) /* in case there are any queued relay
380
                                        * cells */
381
382
    connection_start_writing(conn);
  /* deliver a 'connected' relay cell back through the circuit. */
383
384
  if (connection_edge_is_rendezvous_stream(edge_conn)) {
    if (connection_edge_send_command(edge_conn,
385
                                     RELAY_COMMAND_CONNECTED, NULL, 0) < 0)
386
387
      return 0; /* circuit is closed, don't continue */
  } else {
388
389
390
391
392
393
394
395
396
397
398
399
400
    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;
    }
401
    if (connection_edge_send_command(edge_conn,
402
403
                                 RELAY_COMMAND_CONNECTED,
                                 connected_payload, connected_payload_len) < 0)
404
405
      return 0; /* circuit is closed, don't continue */
  }
406
  tor_assert(edge_conn->package_window > 0);
407
  /* in case the server has written anything */
408
  return connection_edge_process_inbuf(edge_conn, 1);
409
410
}

411
412
/** Define a schedule for how long to wait between retrying
 * application connections. Rather than waiting a fixed amount of
413
 * time between each retry, we wait 10 seconds each for the first
414
 * two tries, and 15 seconds for each retry after
415
 * that. Hopefully this will improve the expected user experience. */
416
static int
417
compute_retry_timeout(edge_connection_t *conn)
418
{
419
420
421
  int timeout = get_options()->CircuitStreamTimeout;
  if (timeout) /* if our config options override the default, use them */
    return timeout;
422
  if (conn->num_socks_retries < 2) /* try 0 and try 1 */
423
424
425
426
    return 10;
  return 15;
}

427
/** Find all general-purpose AP streams waiting for a response that sent their
428
 * begin/resolve cell too long ago. Detach from their current circuit, and
429
 * mark their current circuit as unsuitable for new streams. Then call
430
431
432
 * connection_ap_handshake_attach_circuit() to attach to a new circuit (if
 * available) or launch a new one.
 *
433
 * For rendezvous streams, simply give up after SocksTimeout seconds (with no
434
435
 * retry attempt).
 */
436
437
438
void
connection_ap_expire_beginning(void)
{
439
  edge_connection_t *conn;
440
  circuit_t *circ;
441
  time_t now = time(NULL);
442
  const or_options_t *options = get_options();
443
  int severity;
444
  int cutoff;
445
  int seconds_idle, seconds_since_born;
446
  smartlist_t *conns = get_connection_array();
447

448
  SMARTLIST_FOREACH_BEGIN(conns, connection_t *, c) {
449
    if (c->type != CONN_TYPE_AP || c->marked_for_close)
450
      continue;
451
    conn = TO_EDGE_CONN(c);
452
    /* if it's an internal linked connection, don't yell its status. */
453
    severity = (tor_addr_is_null(&conn->_base.addr) && !conn->_base.port)
454
      ? LOG_INFO : LOG_NOTICE;
455
    seconds_idle = (int)( now - conn->_base.timestamp_lastread );
456
    seconds_since_born = (int)( now - conn->_base.timestamp_created );
457

458
459
460
461
462
463
464
    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. */
465
    if (AP_CONN_STATE_IS_UNATTACHED(conn->_base.state)) {
466
      if (seconds_since_born >= options->SocksTimeout) {
467
468
469
        log_fn(severity, LD_APP,
            "Tried for %d seconds to get a connection to %s:%d. "
            "Giving up. (%s)",
470
            seconds_since_born,
471
            safe_str_client(conn->socks_request->address),
472
473
            conn->socks_request->port,
            conn_state_to_string(CONN_TYPE_AP, conn->_base.state));
474
        connection_mark_unattached_ap(conn, END_STREAM_REASON_TIMEOUT);
475
476
477
478
      }
      continue;
    }

479
480
481
482
    /* 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);
483
    if (seconds_idle < cutoff)
484
      continue;
485
    circ = circuit_get_by_edge_conn(conn);
486
    if (!circ) { /* it's vanished? */
Roger Dingledine's avatar
Roger Dingledine committed
487
      log_info(LD_APP,"Conn is waiting (address %s), but lost its circ.",
488
               safe_str_client(conn->socks_request->address));
489
      connection_mark_unattached_ap(conn, END_STREAM_REASON_TIMEOUT);
490
491
      continue;
    }
492
    if (circ->purpose == CIRCUIT_PURPOSE_C_REND_JOINED) {
493
      if (seconds_idle >= options->SocksTimeout) {
494
495
496
        log_fn(severity, LD_REND,
               "Rend stream is %d seconds late. Giving up on address"
               " '%s.onion'.",
497
               seconds_idle,
498
               safe_str_client(conn->socks_request->address));
499
        connection_edge_end(conn, END_STREAM_REASON_TIMEOUT);
500
        connection_mark_unattached_ap(conn, END_STREAM_REASON_TIMEOUT);
501
502
503
      }
      continue;
    }
Roger Dingledine's avatar
Roger Dingledine committed
504
    tor_assert(circ->purpose == CIRCUIT_PURPOSE_C_GENERAL);
505
    log_fn(cutoff < 15 ? LOG_INFO : severity, LD_APP,
506
           "We tried for %d seconds to connect to '%s' using exit %s."
507
           " Retrying on a new circuit.",
508
           seconds_idle,
509
           safe_str_client(conn->socks_request->address),
510
           conn->cpath_layer ?
511
           extend_info_describe(conn->cpath_layer->extend_info): "*unnamed*");
512
    /* send an end down the circuit */
513
    connection_edge_end(conn, END_STREAM_REASON_TIMEOUT);
514
    /* un-mark it as ending, since we're going to reuse it */
515
    conn->edge_has_sent_end = 0;
516
    conn->end_reason = 0;
517
518
519
    /* 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 */
520
    /* XXXX023 this is a kludgy way to do this. */
521
    tor_assert(circ->timestamp_dirty);
522
    circ->timestamp_dirty -= options->MaxCircuitDirtiness;
523
    /* give our stream another 'cutoff' seconds to try */
524
    conn->_base.timestamp_lastread += cutoff;
525
526
    if (conn->num_socks_retries < 250) /* avoid overflow */
      conn->num_socks_retries++;
527
    /* move it back into 'pending' state, and try to attach. */
528
529
    if (connection_ap_detach_retriable(conn, TO_ORIGIN_CIRCUIT(circ),
                                       END_STREAM_REASON_TIMEOUT)<0) {
530
531
      if (!conn->_base.marked_for_close)
        connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
532
    }
533
  } SMARTLIST_FOREACH_END(conn);
534
535
}

536
537
/** 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.
538
 */
539
540
void
connection_ap_attach_pending(void)
541
{
542
  edge_connection_t *edge_conn;
543
544
545
  smartlist_t *conns = get_connection_array();
  SMARTLIST_FOREACH(conns, connection_t *, conn,
  {
Roger Dingledine's avatar
Roger Dingledine committed
546
547
    if (conn->marked_for_close ||
        conn->type != CONN_TYPE_AP ||
548
        conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
549
      continue;
550
551
    edge_conn = TO_EDGE_CONN(conn);
    if (connection_ap_handshake_attach_circuit(edge_conn) < 0) {
552
553
554
      if (!edge_conn->_base.marked_for_close)
        connection_mark_unattached_ap(edge_conn,
                                      END_STREAM_REASON_CANT_ATTACH);
555
    }
556
  });
557
558
}

Nick Mathewson's avatar
Nick Mathewson committed
559
/** Tell any AP streams that are waiting for a one-hop tunnel to
560
 * <b>failed_digest</b> that they are going to fail. */
561
/* XXX023 We should get rid of this function, and instead attach
Nick Mathewson's avatar
Nick Mathewson committed
562
 * one-hop streams to circ->p_streams so they get marked in
563
564
 * circuit_mark_for_close like normal p_streams. */
void
565
566
connection_ap_fail_onehop(const char *failed_digest,
                          cpath_build_state_t *build_state)
567
568
569
570
{
  edge_connection_t *edge_conn;
  char digest[DIGEST_LEN];
  smartlist_t *conns = get_connection_array();
571
  SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
572
573
574
575
576
577
578
    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;
579
    if (hexdigest_to_digest(edge_conn->chosen_exit_name, digest) < 0 ||
580
        tor_memneq(digest, failed_digest, DIGEST_LEN))
581
582
583
      continue;
    if (tor_digest_is_zero(digest)) {
      /* we don't know the digest; have to compare addr:port */
584
      tor_addr_t addr;
585
      if (!build_state || !build_state->chosen_exit ||
586
587
588
589
          !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) ||
590
591
          build_state->chosen_exit->port != edge_conn->socks_request->port)
        continue;
592
    }
Nick Mathewson's avatar
Nick Mathewson committed
593
    log_info(LD_APP, "Closing one-hop stream to '%s/%s' because the OR conn "
594
595
596
                     "just failed.", edge_conn->chosen_exit_name,
                     edge_conn->socks_request->address);
    connection_mark_unattached_ap(edge_conn, END_STREAM_REASON_TIMEOUT);
597
  } SMARTLIST_FOREACH_END(conn);
598
599
}

600
601
602
603
604
605
606
607
/** 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;
608
  const node_t *r1, *r2;
609

610
  smartlist_t *conns = get_connection_array();
611
  SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
612
613
    if (conn->marked_for_close ||
        conn->type != CONN_TYPE_AP ||
614
        conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
615
616
      continue;
    edge_conn = TO_EDGE_CONN(conn);
617
618
619
    if (!edge_conn->chosen_exit_optional &&
        !edge_conn->chosen_exit_retries)
      continue;
620
    r1 = node_get_by_nickname(edge_conn->chosen_exit_name, 0);
621
    r2 = node_get_by_id(info->identity_digest);
622
623
624
    if (!r1 || !r2 || r1 != r2)
      continue;
    tor_assert(edge_conn->socks_request);
625
    if (edge_conn->chosen_exit_optional) {
626
      log_info(LD_APP, "Giving up on enclave exit '%s' for destination %s.",
627
628
               safe_str_client(edge_conn->chosen_exit_name),
               escaped_safe_str_client(edge_conn->socks_request->address));
629
      edge_conn->chosen_exit_optional = 0;
630
      tor_free(edge_conn->chosen_exit_name); /* clears it */
631
632
633
      /* 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);
634
    }
635
636
    if (edge_conn->chosen_exit_retries) {
      if (--edge_conn->chosen_exit_retries == 0) { /* give up! */
637
        clear_trackexithost_mappings(edge_conn->chosen_exit_name);
638
639
640
641
642
643
        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);
      }
    }
644
  } SMARTLIST_FOREACH_END(conn);
645
646
}

647
648
/** The AP connection <b>conn</b> has just failed while attaching or
 * sending a BEGIN or resolving on <b>circ</b>, but another circuit
649
 * might work. Detach the circuit, and either reattach it, launch a
650
651
652
 * new circuit, tell the controller, or give up as a appropriate.
 *
 * Returns -1 on err, 1 on success, 0 on not-yet-sure.
653
654
 */
int
655
656
connection_ap_detach_retriable(edge_connection_t *conn, origin_circuit_t *circ,
                               int reason)
657
{
658
  control_event_stream_status(conn, STREAM_EVENT_FAILED_RETRIABLE, reason);
659
  conn->_base.timestamp_lastread = time(NULL);
660
661
662
  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. */
663
    conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
664
    circuit_detach_stream(TO_CIRCUIT(circ),conn);
665
666
    return connection_ap_handshake_attach_circuit(conn);
  } else {
667
    conn->_base.state = AP_CONN_STATE_CONTROLLER_WAIT;
668
    circuit_detach_stream(TO_CIRCUIT(circ),conn);
669
670
671
672
    return 0;
  }
}

673
/** A client-side struct to remember requests to rewrite addresses
674
 * to new addresses. These structs are stored in the hash table
675
 * "addressmap" below.
676
677
678
679
680
 *
 * 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
681
682
 * - When a DNS resolve succeeds [temporary]
 * - When a DNS resolve fails [temporary]
683
684
685
 *
 * 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
686
 * no "new_address" (that is, it's in the process of DNS resolve),
687
688
689
690
 * 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
691
692
 * interface, and other values for DNS and TrackHostExit mappings that can
 * expire.)
693
694
695
696
 */
typedef struct {
  char *new_address;
  time_t expires;
697
698
  addressmap_entry_source_t source:3;
  short num_resolve_failures;
699
700
} addressmap_entry_t;

701
/** Entry for mapping addresses to which virtual address we mapped them to. */
702
703
704
705
706
typedef struct {
  char *ipv4_address;
  char *hostname_address;
} virtaddress_entry_t;

707
/** A hash table to store client-side address rewrite instructions. */
708
static strmap_t *addressmap=NULL;
709
/**
710
 * Table mapping addresses to which virtual address, if any, we
711
712
713
714
715
716
717
718
 * 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.
 **/
719
static strmap_t *virtaddress_reversemap=NULL;
720
721

/** Initialize addressmap. */
722
723
724
void
addressmap_init(void)
{
725
  addressmap = strmap_new();
726
  virtaddress_reversemap = strmap_new();
727
728
729
730
}

/** Free the memory associated with the addressmap entry <b>_ent</b>. */
static void
731
732
addressmap_ent_free(void *_ent)
{
733
734
735
736
737
  addressmap_entry_t *ent;
  if (!_ent)
    return;

  ent = _ent;
738
739
740
741
  tor_free(ent->new_address);
  tor_free(ent);
}

Roger Dingledine's avatar
Roger Dingledine committed
742
/** Free storage held by a virtaddress_entry_t* entry in <b>ent</b>. */
743
static void
744
745
addressmap_virtaddress_ent_free(void *_ent)
{
746
747
748
749
750
  virtaddress_entry_t *ent;
  if (!_ent)
    return;

  ent = _ent;
751
752
753
754
755
  tor_free(ent->ipv4_address);
  tor_free(ent->hostname_address);
  tor_free(ent);
}

Roger Dingledine's avatar
Roger Dingledine committed
756
/** Free storage held by a virtaddress_entry_t* entry in <b>ent</b>. */
757
static void
758
addressmap_virtaddress_remove(const char *address, addressmap_entry_t *ent)
759
{
760
761
  if (ent && ent->new_address &&
      address_is_in_virtual_range(ent->new_address)) {
762
763
    virtaddress_entry_t *ve =
      strmap_get(virtaddress_reversemap, ent->new_address);
764
    /*log_fn(LOG_NOTICE,"remove reverse mapping for %s",ent->new_address);*/
765
    if (ve) {
766
      if (!strcmp(address, ve->ipv4_address))
767
        tor_free(ve->ipv4_address);
768
      if (!strcmp(address, ve->hostname_address))
769
770
771
772
773
        tor_free(ve->hostname_address);
      if (!ve->ipv4_address && !ve->hostname_address) {
        tor_free(ve);
        strmap_remove(virtaddress_reversemap, ent->new_address);
      }
774
775
776
777
    }
  }
}

778
779
/** Remove <b>ent</b> (which must be mapped to by <b>address</b>) from the
 * client address maps. */
780
static void
781
addressmap_ent_remove(const char *address, addressmap_entry_t *ent)
782
{
783
  addressmap_virtaddress_remove(address, ent);
784
785
  addressmap_ent_free(ent);
}
786

787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
/** 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) {
802
803
    if (ent->source == ADDRMAPSRC_TRACKEXIT &&
        !strcmpend(ent->new_address, suffix)) {
804
805
806
807
      addressmap_ent_remove(address, ent);
      MAP_DEL_CURRENT(address);
    }
  } STRMAP_FOREACH_END;
808
809

  tor_free(suffix);
810
811
}

812
/** Remove all TRACKEXIT mappings from the addressmap for which the target
813
814
 * host is unknown or no longer allowed, or for which the source address
 * is no longer in trackexithosts. */
815
void
816
addressmap_clear_excluded_trackexithosts(const or_options_t *options)
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
{
  const routerset_t *allow_nodes = options->ExitNodes;
  const routerset_t *exclude_nodes = options->_ExcludeExitNodesUnion;

  if (!addressmap)
    return;
  if (routerset_is_empty(allow_nodes))
    allow_nodes = NULL;
  if (allow_nodes == NULL && routerset_is_empty(exclude_nodes))
    return;

  STRMAP_FOREACH_MODIFY(addressmap, address, addressmap_entry_t *, ent) {
    size_t len;
    const char *target = ent->new_address, *dot;
    char *nodename;
832
    const node_t *node;
833
834
835
836
837
838
839
840
841
842
843
844

    if (strcmpend(target, ".exit")) {
      /* Not a .exit mapping */
      continue;
    } else if (ent->source != ADDRMAPSRC_TRACKEXIT) {
      /* Not a trackexit mapping. */
      continue;
    }
    len = strlen(target);
    if (len < 6)
      continue; /* malformed. */
    dot = target + len - 6; /* dot now points to just before .exit */
Sebastian Hahn's avatar
Sebastian Hahn committed
845
    dot = strrchr(dot, '.'); /* dot now points to the . before .exit or NULL */
846
847
848
849
850
    if (!dot) {
      nodename = tor_strndup(target, len-5);
    } else {
      nodename = tor_strndup(dot+1, strlen(dot+1)-5);
    }
851
    node = node_get_by_nickname(nodename, 0);
852
    tor_free(nodename);
853
854
    if (!node ||
        (allow_nodes && !routerset_contains_node(allow_nodes, node)) ||
855
        routerset_contains_node(exclude_nodes, node) ||
856
        !hostname_in_track_host_exits(options, address)) {
857
858
859
860
861
862
863
      /* We don't know this one, or we want to be rid of it. */
      addressmap_ent_remove(address, ent);
      MAP_DEL_CURRENT(address);
    }
  } STRMAP_FOREACH_END;
}

864
865
866
867
868
/** Remove all AUTOMAP mappings from the addressmap for which the
 * source address no longer matches AutomapHostsSuffixes, which is
 * no longer allowed by AutomapHostsOnResolve, or for which the
 * target address is no longer in the virtual network. */
void
869
addressmap_clear_invalid_automaps(const or_options_t *options)
870
871
872
873
874