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

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

13
14
#include "or.h"

15
static addr_policy_t *socks_policy = NULL;
16
17
/* List of exit_redirect_t */
static smartlist_t *redirect_exit_list = NULL;
18

19
20
static int connection_ap_handshake_process_socks(connection_t *conn);

21
22
23
24
25
/** 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
26
_connection_mark_unattached_ap(connection_t *conn, int endreason,
27
28
                               int line, const char *file)
{
29
30
  tor_assert(conn->type == CONN_TYPE_AP);
  conn->has_sent_end = 1; /* no circ yet */
31

32
  if (conn->marked_for_close) {
33
34
    /* This call will warn as appropriate. */
    _connection_mark_for_close(conn, line, file);
35
36
37
    return;
  }

38
39
40
  if (!conn->socks_request->has_finished) {
    socks5_reply_status_t socksreason =
      connection_edge_end_reason_socks5_response(endreason);
41
42

    if (endreason == END_STREAM_REASON_ALREADY_SOCKS_REPLIED)
43
44
      warn(LD_BUG,"Bug: stream (marked at %s:%d) sending two socks replies?",
           file, line);
45

46
47
48
    if (conn->socks_request->command == SOCKS_COMMAND_CONNECT)
      connection_ap_handshake_socks_reply(conn, NULL, 0, socksreason);
    else
49
      connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_ERROR,0,NULL,-1);
50
  }
51

52
  _connection_mark_for_close(conn, line, file);
53
54
55
  conn->hold_open_until_flushed = 1;
}

56
57
/** There was an EOF. Send an end and mark the connection for close.
 */
58
59
60
int
connection_edge_reached_eof(connection_t *conn)
{
61
62
63
64
65
66
67
68
#ifdef HALF_OPEN
  /* eof reached; we're done reading, but we might want to write more. */
  conn->done_receiving = 1;
  shutdown(conn->s, 0); /* XXX check return, refactor NM */
  if (conn->done_sending) {
    connection_edge_end(conn, END_STREAM_REASON_DONE, conn->cpath_layer);
    connection_mark_for_close(conn);
  } else {
69
70
    connection_edge_send_command(conn, circuit_get_by_edge_conn(conn),
                                 RELAY_COMMAND_END,
71
72
73
74
                                 NULL, 0, conn->cpath_layer);
  }
  return 0;
#else
75
  if (buf_datalen(conn->inbuf) && connection_state_is_open(conn)) {
Roger Dingledine's avatar
Roger Dingledine committed
76
77
78
    /* it still has stuff to process. don't let it die yet. */
    return 0;
  }
79
  info(LD_EDGE,"conn (fd %d) reached eof. Closing.", conn->s);
80
  if (!conn->marked_for_close) {
81
82
    /* only mark it if not already marked. it's possible to
     * get the 'end' right around when the client hangs up on us. */
83
    connection_edge_end(conn, END_STREAM_REASON_DONE, conn->cpath_layer);
84
85
    if (conn->socks_request) /* eof, so don't send a socks reply back */
      conn->socks_request->has_finished = 1;
86
87
88
89
90
91
92
    connection_mark_for_close(conn);
  }
  return 0;
#endif
}

/** Handle new bytes on conn->inbuf based on state:
93
94
95
96
97
98
 *   - If it's waiting for socks info, try to read another step of the
 *     socks handshake out of conn->inbuf.
 *   - 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,
99
100
 * else return 0.
 */
101
102
103
int
connection_edge_process_inbuf(connection_t *conn, int package_partial)
{
Roger Dingledine's avatar
Roger Dingledine committed
104
  tor_assert(conn);
105
  tor_assert(CONN_IS_EDGE(conn));
106

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

139
140
141
/** This edge needs to be closed, because its circuit has closed.
 * Mark it for close and return 0.
 */
142
143
144
int
connection_edge_destroy(uint16_t circ_id, connection_t *conn)
{
145
  tor_assert(CONN_IS_EDGE(conn));
146

147
  if (!conn->marked_for_close) {
148
149
    info(LD_EDGE,
         "CircID %d: At an edge. Marking connection for close.", circ_id);
150
151
152
153
154
155
156
    if (conn->type == CONN_TYPE_AP) {
      connection_mark_unattached_ap(conn, END_STREAM_REASON_DESTROY);
    } else {
      conn->has_sent_end = 1; /* we're closing the circuit, nothing to send to */
      connection_mark_for_close(conn);
      conn->hold_open_until_flushed = 1;
    }
157
  }
158
  conn->cpath_layer = NULL;
159
  conn->on_circuit = NULL;
160
161
162
  return 0;
}

163
164
165
166
167
168
169
170
/** Send a relay end cell from stream <b>conn</b> to conn's circuit,
 * with a destination of cpath_layer. (If cpath_layer is NULL, the
 * destination is the circuit's origin.) Mark the relay end cell as
 * closing because of <b>reason</b>.
 *
 * Return -1 if this function has already been called on this conn,
 * else return 0.
 */
171
172
173
int
connection_edge_end(connection_t *conn, char reason, crypt_path_t *cpath_layer)
{
174
  char payload[RELAY_PAYLOAD_SIZE];
175
  size_t payload_len=1;
176
  circuit_t *circ;
177

178
  if (conn->has_sent_end) {
179
    warn(LD_BUG,"Harmless bug: Calling connection_edge_end (reason %d) on an already ended stream?", reason);
180
    tor_fragile_assert();
181
    return -1;
182
183
  }

184
  if (conn->marked_for_close) {
185
    warn(LD_BUG,"Bug: called on conn that's already marked for close at %s:%d.",
186
187
188
189
           conn->marked_for_close_file, conn->marked_for_close);
    return 0;
  }

190
  payload[0] = reason;
191
192
  if (reason == END_STREAM_REASON_EXITPOLICY &&
      !connection_edge_is_rendezvous_stream(conn)) {
193
    set_uint32(payload+1, htonl(conn->addr));
194
195
    set_uint32(payload+5, htonl(MAX_DNS_ENTRY_AGE)); /* XXXXfill with a real TTL*/
    payload_len += 8;
196
197
  }

198
  circ = circuit_get_by_edge_conn(conn);
199
  if (circ && !circ->marked_for_close) {
200
    debug(LD_EDGE,"Marking conn (fd %d) and sending end.",conn->s);
201
202
    connection_edge_send_command(conn, circ, RELAY_COMMAND_END,
                                 payload, payload_len, cpath_layer);
203
  } else {
204
    debug(LD_EDGE,"Marking conn (fd %d); no circ to send end.",conn->s);
205
206
207
  }

  conn->has_sent_end = 1;
208
  return 0;
209
210
}

211
212
213
214
/** An error has just occured on an operation on an edge connection
 * <b>conn</b>.  Extract the errno; convert it to an end reason, and send
 * an appropriate relay end cell to <b>cpath_layer</b>.
 **/
215
216
217
218
219
220
221
222
223
int
connection_edge_end_errno(connection_t *conn, crypt_path_t *cpath_layer)
{
  uint8_t reason;
  tor_assert(conn);
  reason = (uint8_t)errno_to_end_reason(tor_socket_errno(conn->s));
  return connection_edge_end(conn, reason, cpath_layer);
}

224
225
226
227
228
229
230
231
232
233
/** 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.
 */
234
235
236
int
connection_edge_finished_flushing(connection_t *conn)
{
Roger Dingledine's avatar
Roger Dingledine committed
237
  tor_assert(conn);
238
  tor_assert(CONN_IS_EDGE(conn));
239

240
  switch (conn->state) {
241
242
243
    case AP_CONN_STATE_OPEN:
    case EXIT_CONN_STATE_OPEN:
      connection_stop_writing(conn);
244
      connection_edge_consider_sending_sendme(conn);
245
      return 0;
Roger Dingledine's avatar
Roger Dingledine committed
246
    case AP_CONN_STATE_SOCKS_WAIT:
247
    case AP_CONN_STATE_RENDDESC_WAIT:
248
    case AP_CONN_STATE_CIRCUIT_WAIT:
249
    case AP_CONN_STATE_CONNECT_WAIT:
250
    case AP_CONN_STATE_CONTROLLER_WAIT:
Roger Dingledine's avatar
Roger Dingledine committed
251
252
      connection_stop_writing(conn);
      return 0;
253
    default:
254
      warn(LD_BUG,"BUG: called in unexpected state %d.", conn->state);
255
      tor_fragile_assert();
256
      return -1;
257
258
259
260
  }
  return 0;
}

261
262
263
/** 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. */
264
265
int
connection_edge_finished_connecting(connection_t *conn)
266
{
267
  char valbuf[INET_NTOA_BUF_LEN];
Roger Dingledine's avatar
Roger Dingledine committed
268
  struct in_addr in;
269
270
271
272
273

  tor_assert(conn);
  tor_assert(conn->type == CONN_TYPE_EXIT);
  tor_assert(conn->state == EXIT_CONN_STATE_CONNECTING);

274
275
  in.s_addr = htonl(conn->addr);
  tor_inet_ntoa(&in,valbuf,sizeof(valbuf));
276
  info(LD_EXIT,"Exit connection to %s:%u (%s) established.",
277
         safe_str(conn->address),conn->port,safe_str(valbuf));
278
279

  conn->state = EXIT_CONN_STATE_OPEN;
280
  connection_watch_events(conn, EV_READ); /* stop writing, continue reading */
281
  if (connection_wants_to_flush(conn)) /* in case there are any queued relay cells */
282
283
    connection_start_writing(conn);
  /* deliver a 'connected' relay cell back through the circuit. */
284
  if (connection_edge_is_rendezvous_stream(conn)) {
285
    if (connection_edge_send_command(conn, circuit_get_by_edge_conn(conn),
286
                                     RELAY_COMMAND_CONNECTED, NULL, 0, conn->cpath_layer) < 0)
287
288
      return 0; /* circuit is closed, don't continue */
  } else {
289
    char connected_payload[8];
290
    set_uint32(connected_payload, htonl(conn->addr));
291
292
    set_uint32(connected_payload+4,
               htonl(MAX_DNS_ENTRY_AGE)); /* XXXX fill with a real TTL */
293
    if (connection_edge_send_command(conn, circuit_get_by_edge_conn(conn),
294
        RELAY_COMMAND_CONNECTED, connected_payload, 8, conn->cpath_layer) < 0)
295
296
297
      return 0; /* circuit is closed, don't continue */
  }
  tor_assert(conn->package_window > 0);
298
299
  /* in case the server has written anything */
  return connection_edge_process_inbuf(conn, 1);
300
301
}

302
303
/** Find all general-purpose AP streams waiting for a response that sent
 * their begin/resolve cell >=15 seconds ago. Detach from their current circuit,
304
305
306
307
308
309
310
 * and mark their current circuit as unsuitable for new streams. Then call
 * connection_ap_handshake_attach_circuit() to attach to a new circuit (if
 * available) or launch a new one.
 *
 * For rendezvous streams, simply give up after 45 seconds (with no
 * retry attempt).
 */
311
312
313
void
connection_ap_expire_beginning(void)
{
314
315
  connection_t **carray;
  connection_t *conn;
316
  circuit_t *circ;
317
318
  int n, i;
  time_t now = time(NULL);
319
  or_options_t *options = get_options();
320
321
322
323
324

  get_connection_array(&carray, &n);

  for (i = 0; i < n; ++i) {
    conn = carray[i];
325
326
    if (conn->type != CONN_TYPE_AP)
      continue;
327
328
    if (conn->state == AP_CONN_STATE_CONTROLLER_WAIT) {
      if (now - conn->timestamp_lastread >= 120) {
329
        notice(LD_APP, "Closing unattached stream.");
330
        connection_mark_unattached_ap(conn, END_STREAM_REASON_TIMEOUT);
331
332
333
334
335
      }
      continue;
    }

    else if (conn->state != AP_CONN_STATE_RESOLVE_WAIT &&
336
        conn->state != AP_CONN_STATE_CONNECT_WAIT)
337
      continue;
338
339
    if (now - conn->timestamp_lastread < 15)
      continue;
340
    circ = circuit_get_by_edge_conn(conn);
341
    if (!circ) { /* it's vanished? */
342
      info(LD_APP,"Conn is waiting (address %s), but lost its circ.",
343
             safe_str(conn->socks_request->address));
344
      connection_mark_unattached_ap(conn, END_STREAM_REASON_TIMEOUT);
345
346
      continue;
    }
347
    if (circ->purpose == CIRCUIT_PURPOSE_C_REND_JOINED) {
348
      if (now - conn->timestamp_lastread > 45) {
349
        notice(LD_REND,"Rend stream is %d seconds late. Giving up on address '%s'.",
350
351
               (int)(now - conn->timestamp_lastread),
               safe_str(conn->socks_request->address));
352
        connection_edge_end(conn, END_STREAM_REASON_TIMEOUT, conn->cpath_layer);
353
        connection_mark_unattached_ap(conn, END_STREAM_REASON_TIMEOUT);
354
355
356
      }
      continue;
    }
Roger Dingledine's avatar
Roger Dingledine committed
357
    tor_assert(circ->purpose == CIRCUIT_PURPOSE_C_GENERAL);
358
    notice(LD_APP,"We tried for %d seconds to connect to '%s'. Retrying on a new circuit.",
359
360
           (int)(now - conn->timestamp_lastread),
           safe_str(conn->socks_request->address));
361
362
363
364
365
366
367
368
    /* send an end down the circuit */
    connection_edge_end(conn, END_STREAM_REASON_TIMEOUT, conn->cpath_layer);
    /* un-mark it as ending, since we're going to reuse it */
    conn->has_sent_end = 0;
    /* 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);
369
    circ->timestamp_dirty -= options->MaxCircuitDirtiness;
370
371
    /* give our stream another 15 seconds to try */
    conn->timestamp_lastread += 15;
372
373
    /* move it back into 'pending' state, and try to attach. */
    if (connection_ap_detach_retriable(conn, circ)<0) {
374
      connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
375
    }
376
  } /* end for */
377
378
}

379
/** Tell any AP streams that are waiting for a new circuit that one is
380
381
 * available.
 */
382
383
void
connection_ap_attach_pending(void)
384
{
385
  connection_t **carray;
386
  connection_t *conn;
387
388
389
390
391
  int n, i;

  get_connection_array(&carray, &n);

  for (i = 0; i < n; ++i) {
392
    conn = carray[i];
Roger Dingledine's avatar
Roger Dingledine committed
393
394
    if (conn->marked_for_close ||
        conn->type != CONN_TYPE_AP ||
395
        conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
396
      continue;
397
    if (connection_ap_handshake_attach_circuit(conn) < 0) {
398
      connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
399
    }
400
401
402
  }
}

403
404
405
406
407
408
/** The AP connection <b>conn</b> has just failed while attaching or
 * sending a BEGIN or resolving on <b>circ</b>, but another circuit
 * might work.  Detach the circuit, and either reattach it, launch a
 * new circuit, tell the controller, or give up as a appropriate.
 *
 * Returns -1 on err, 1 on success, 0 on not-yet-sure.
409
410
411
412
413
 */
int
connection_ap_detach_retriable(connection_t *conn, circuit_t *circ)
{
  control_event_stream_status(conn, STREAM_EVENT_FAILED_RETRIABLE);
414
  conn->timestamp_lastread = time(NULL);
415
  if (! get_options()->LeaveStreamsUnattached) {
416
417
418
419
420
421
422
423
424
425
    conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
    circuit_detach_stream(circ,conn);
    return connection_ap_handshake_attach_circuit(conn);
  } else {
    conn->state = AP_CONN_STATE_CONTROLLER_WAIT;
    circuit_detach_stream(circ,conn);
    return 0;
  }
}

426
/** A client-side struct to remember requests to rewrite addresses
427
428
 * to new addresses. These structs are stored the hash table
 * "addressmap" below.
429
430
431
432
433
434
435
436
437
438
439
 *
 * There are 5 ways to set an address mapping:
 * - A MapAddress command from the controller [permanent]
 * - An AddressMap directive in the torrc [permanent]
 * - When a TrackHostExits torrc directive is triggered [temporary]
 * - When a dns resolve succeeds [temporary]
 * - When a dns resolve fails [temporary]
 *
 * When an addressmap request is made but one is already registered,
 * the new one is replaced only if the currently registered one has
 * no "new_address" (that is, it's in the process of dns resolve),
440
441
442
443
444
 * or if the new one is permanent (expires==0 or 1).
 *
 * (We overload the 'expires' field, using "0" for mappings set via
 * the configuration file, "1" for mappings set from the control
 * interface, and other values for DNS mappings that can expire.)
445
446
447
448
449
450
451
 */
typedef struct {
  char *new_address;
  time_t expires;
  int num_resolve_failures;
} addressmap_entry_t;

452
/** Entry for mapping addresses to which virtual address we mapped them to. */
453
454
455
456
457
typedef struct {
  char *ipv4_address;
  char *hostname_address;
} virtaddress_entry_t;

458
/** A hash table to store client-side address rewrite instructions. */
459
static strmap_t *addressmap=NULL;
460
/**
461
 * Table mapping addresses to which virtual address, if any, we
462
463
464
465
466
467
468
469
 * 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.
 **/
470
static strmap_t *virtaddress_reversemap=NULL;
471
472

/** Initialize addressmap. */
473
474
475
void
addressmap_init(void)
{
476
  addressmap = strmap_new();
477
  virtaddress_reversemap = strmap_new();
478
479
480
481
}

/** Free the memory associated with the addressmap entry <b>_ent</b>. */
static void
482
483
addressmap_ent_free(void *_ent)
{
484
485
486
487
488
  addressmap_entry_t *ent = _ent;
  tor_free(ent->new_address);
  tor_free(ent);
}

489
/** Free storage held by a virtaddress_entry_t* entry in <b>ent</b> */
490
static void
491
492
addressmap_virtaddress_ent_free(void *_ent)
{
493
494
495
496
497
498
  virtaddress_entry_t *ent = _ent;
  tor_free(ent->ipv4_address);
  tor_free(ent->hostname_address);
  tor_free(ent);
}

499
/** Free storage held by a virtaddress_entry_t* entry in <b>ent</b> */
500
static void
501
addressmap_virtaddress_remove(const char *address, addressmap_entry_t *ent)
502
{
503
  if (ent && ent->new_address && address_is_in_virtual_range(ent->new_address)) {
504
505
    virtaddress_entry_t *ve =
      strmap_get(virtaddress_reversemap, ent->new_address);
506
    /*log_fn(LOG_NOTICE,"remove reverse mapping for %s",ent->new_address);*/
507
    if (ve) {
508
      if (!strcmp(address, ve->ipv4_address))
509
        tor_free(ve->ipv4_address);
510
      if (!strcmp(address, ve->hostname_address))
511
512
513
514
515
        tor_free(ve->hostname_address);
      if (!ve->ipv4_address && !ve->hostname_address) {
        tor_free(ve);
        strmap_remove(virtaddress_reversemap, ent->new_address);
      }
516
517
518
519
    }
  }
}

520
/* DOCDOC */
521
static void
522
addressmap_ent_remove(const char *address, addressmap_entry_t *ent)
523
{
524
  addressmap_virtaddress_remove(address, ent);
525
526
  addressmap_ent_free(ent);
}
527

528
529
530
531
532
533
534
535
536
537
538
539
540
/** Remove all entries from the addressmap that were set via the
 * configuration file or the command line. */
void
addressmap_clear_configured(void)
{
  addressmap_get_mappings(NULL, 0, 0);
}

/** Remove all entries from the addressmap that are set to expire, ever. */
void
addressmap_clear_transient(void)
{
  addressmap_get_mappings(NULL, 2, TIME_MAX);
541
542
543
544
545
}

/** Clean out entries from the addressmap cache that were
 * added long enough ago that they are no longer valid.
 */
546
547
548
void
addressmap_clean(time_t now)
{
549
  addressmap_get_mappings(NULL, 2, now);
550
551
552
553
}

/** Free all the elements in the addressmap, and free the addressmap
 * itself. */
554
555
556
void
addressmap_free_all(void)
{
557
558
559
560
561
562
563
564
  if (addressmap) {
    strmap_free(addressmap, addressmap_ent_free);
    addressmap = NULL;
  }
  if (virtaddress_reversemap) {
    strmap_free(virtaddress_reversemap, addressmap_virtaddress_ent_free);
    virtaddress_reversemap = NULL;
  }
565
566
567
568
569
570
}

/** Look at address, and rewrite it until it doesn't want any
 * more rewrites; but don't get into an infinite loop.
 * Don't write more than maxlen chars into address.
 */
571
572
573
void
addressmap_rewrite(char *address, size_t maxlen)
{
574
575
576
577
578
579
580
581
582
  addressmap_entry_t *ent;
  int rewrites;

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

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

583
584
    info(LD_APP, "Addressmap: rewriting '%s' to '%s'",
         safe_str(address), safe_str(ent->new_address));
585
586
    strlcpy(address, ent->new_address, maxlen);
  }
587
  warn(LD_CONFIG,"Loop detected: we've rewritten '%s' 16 times! Using it as-is.",
588
         safe_str(address));
589
590
591
592
  /* it's fine to rewrite a rewrite, but don't loop forever */
}

/** Return 1 if <b>address</b> is already registered, else return 0 */
593
594
595
int
addressmap_already_mapped(const char *address)
{
596
597
598
599
  return strmap_get(addressmap, address) ? 1 : 0;
}

/** Register a request to map <b>address</b> to <b>new_address</b>,
600
601
602
 * 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.)
603
 *
604
 * <b>new_address</b> should be a newly dup'ed string, which we'll use or
605
 * free as appropriate. We will leave address alone.
606
607
608
 *
 * If <b>new_address</b> is NULL, or equal to <b>address</b>, remove
 * any mappings that exist from <b>address</b>.
609
 */
610
611
612
void
addressmap_register(const char *address, char *new_address, time_t expires)
{
613
614
615
  addressmap_entry_t *ent;

  ent = strmap_get(addressmap, address);
616
  if (!new_address || !strcasecmp(address,new_address)) {
617
    /* Remove the mapping, if any. */
618
619
    tor_free(new_address);
    if (ent) {
620
      addressmap_ent_remove(address,ent);
621
622
623
624
      strmap_remove(addressmap, address);
    }
    return;
  }
625
626
627
628
629
  if (!ent) { /* make a new one and register it */
    ent = tor_malloc_zero(sizeof(addressmap_entry_t));
    strmap_set(addressmap, address, ent);
  } else if (ent->new_address) { /* we need to clean up the old mapping. */
    if (expires > 1) {
630
      info(LD_APP,"Temporary addressmap ('%s' to '%s') not performed, since it's already mapped to '%s'",
631
      safe_str(address), safe_str(new_address), safe_str(ent->new_address));
632
633
634
      tor_free(new_address);
      return;
    }
635
636
637
638
    if (address_is_in_virtual_range(ent->new_address) &&
        expires != 2) {
      /* XXX This isn't the perfect test; we want to avoid removing
       * mappings set from the control interface _as virtual mapping */
639
      addressmap_virtaddress_remove(address, ent);
640
    }
641
    tor_free(ent->new_address);
642
643
  } /* else { we have an in-progress resolve with no mapping. } */

644
  ent->new_address = new_address;
645
  ent->expires = expires==2 ? 1 : expires;
646
647
  ent->num_resolve_failures = 0;

648
649
  info(LD_CONFIG, "Addressmap: (re)mapped '%s' to '%s'",
       safe_str(address), safe_str(ent->new_address));
650
  control_event_address_mapped(address, ent->new_address, expires);
651
652
653
654
655
656
}

/** An attempt to resolve <b>address</b> failed at some OR.
 * Increment the number of resolve failures we have on record
 * for it, and then return that number.
 */
657
658
int
client_dns_incr_failures(const char *address)
659
{
660
  addressmap_entry_t *ent = strmap_get(addressmap, address);
661
662
663
664
665
666
  if (!ent) {
    ent = tor_malloc_zero(sizeof(addressmap_entry_t));
    ent->expires = time(NULL)+MAX_DNS_ENTRY_AGE;
    strmap_set(addressmap,address,ent);
  }
  ++ent->num_resolve_failures;
667
  info(LD_APP, "Address %s now has %d resolve failures.",
668
         safe_str(address), ent->num_resolve_failures);
669
670
671
  return ent->num_resolve_failures;
}

672
673
674
675
676
677
678
679
680
681
682
683
684
/** If <b>address</b> is in the client dns addressmap, reset
 * the number of resolve failures we have on record for it.
 * This is used when we fail a stream because it won't resolve:
 * otherwise future attempts on that address will only try once.
 */
void
client_dns_clear_failures(const char *address)
{
  addressmap_entry_t *ent = strmap_get(addressmap, address);
  if (ent)
    ent->num_resolve_failures = 0;
}

685
686
687
/** Record the fact that <b>address</b> resolved to <b>val</b>.
 * We can now use this in subsequent streams via addressmap_rewrite()
 * so we can more correctly choose an exit that will allow <b>address</b>.
688
689
690
 *
 * If <b>exitname</b> is defined, then append the addresses with
 * ".exitname.exit" before registering the mapping.
691
692
693
 *
 * If <b>ttl</b> is nonnegative, the mapping will be valid for
 * <b>ttl</b>seconds.
694
 */
695
void
696
697
client_dns_set_addressmap(const char *address, uint32_t val, const char *exitname,
                          int ttl)
698
699
{
  struct in_addr in;
700
701
702
  char extendedaddress[MAX_SOCKS_ADDR_LEN+MAX_HEX_NICKNAME_LEN+10];
  char valbuf[INET_NTOA_BUF_LEN];
  char extendedval[INET_NTOA_BUF_LEN+MAX_HEX_NICKNAME_LEN+10];
703
704
705

  tor_assert(address); tor_assert(val);

706
707
708
  if (ttl<0 || ttl>MAX_DNS_ENTRY_AGE)
    ttl = MAX_DNS_ENTRY_AGE;

709
  if (tor_inet_aton(address, &in))
Nick Mathewson's avatar
Nick Mathewson committed
710
    return; /* If address was an IP address already, don't add a mapping. */
711
  in.s_addr = htonl(val);
712
713
714
715
716
717
718
719
720
721
722
723
  tor_inet_ntoa(&in,valbuf,sizeof(valbuf));
  if (exitname) {
    tor_snprintf(extendedaddress, sizeof(extendedaddress),
                 "%s.%s.exit", address, exitname);
    tor_snprintf(extendedval, sizeof(extendedval),
                 "%s.%s.exit", valbuf, exitname);
  } else {
    tor_snprintf(extendedaddress, sizeof(extendedaddress),
                 "%s", address);
    tor_snprintf(extendedval, sizeof(extendedval),
                 "%s", valbuf);
  }
724
  addressmap_register(extendedaddress, tor_strdup(extendedval), time(NULL) + ttl);
725
726
}

727
728
729
730
731
732
733
734
735
736
737
738
/* Currently, we hand out 127.192.0.1 through 127.254.254.254.
 * These addresses should map to localhost, so even if the
 * application accidentally tried to connect to them directly (not
 * via Tor), it wouldn't get too far astray.
 *
 * Eventually, we should probably make this configurable.
 */
#define MIN_UNUSED_IPV4 0x7fc00001u
#define MAX_UNUSED_IPV4 0x7ffefefeu

/**
 * Return true iff <b>addr</b> is likely to have been returned by
739
 * client_dns_get_unused_address.
740
 **/
741
int
742
address_is_in_virtual_range(const char *address)
743
744
{
  struct in_addr in;
745
746
  tor_assert(address);
  if (!strcasecmpend(address, ".virtual")) {
747
    return 1;
748
749
750
  } else if (tor_inet_aton(address, &in)) {
    uint32_t addr = ntohl(in.s_addr);
    if (addr >= MIN_UNUSED_IPV4 && addr <= MAX_UNUSED_IPV4)
751
752
753
754
755
756
757
758
759
      return 1;
  }
  return 0;
}

/** Return a newly allocated string holding an address of <b>type</b>
 * (one of RESOLVED_TYPE_{IPV4|HOSTNAME}) that has not yet been mapped,
 * and that is very unlikely to be the address of any real host.
 */
760
761
static char *
addressmap_get_virtual_address(int type)
762
763
764
765
766
767
{
  char buf[64];
  static uint32_t next_ipv4 = MIN_UNUSED_IPV4;
  struct in_addr in;

  if (type == RESOLVED_TYPE_HOSTNAME) {
768
    char rand[10];
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
    do {
      crypto_rand(rand, sizeof(rand));
      base32_encode(buf,sizeof(buf),rand,sizeof(rand));
      strlcat(buf, ".virtual", sizeof(buf));
    } while (strmap_get(addressmap, buf));
    return tor_strdup(buf);
  } else if (type == RESOLVED_TYPE_IPV4) {
    while (1) {
      /* Don't hand out any .0 or .255 address. */
      while ((next_ipv4 & 0xff) == 0 ||
             (next_ipv4 & 0xff) == 0xff)
        ++next_ipv4;
      in.s_addr = htonl(next_ipv4);
      tor_inet_ntoa(&in, buf, sizeof(buf));
      if (!strmap_get(addressmap, buf))
        break;

      ++next_ipv4;
      if (next_ipv4 > MAX_UNUSED_IPV4)
        next_ipv4 = MIN_UNUSED_IPV4;
    }
    return tor_strdup(buf);
  } else {
792
    warn(LD_BUG, "Called with unsupported address type (%d)", type);
793
794
795
796
    return NULL;
  }
}

797
798
799
800
801
802
803
804
805
/** A controller has requested that we map some address of type
 * <b>type</b> to the address <b>new_address</b>.  Choose an address
 * that is unlikely to be used, and map it, and return it in a newly
 * allocated string.  If another address of the same type is already
 * mapped to <b>new_address</b>, try to return a copy of that address.
 *
 * The string in <b>new_address</b> may be freed, or inserted into a map
 * as appropriate.
 **/
806
const char *
807
808
addressmap_register_virtual_address(int type, char *new_address)
{
809
810
811
  char **addrp;
  virtaddress_entry_t *vent;

812
  tor_assert(new_address);
813
814
  tor_assert(addressmap);
  tor_assert(virtaddress_reversemap);
815

816
  vent = strmap_get(virtaddress_reversemap, new_address);
817
  if (!vent) {
818
    vent = tor_malloc_zero(sizeof(virtaddress_entry_t));
819
820
    strmap_set(virtaddress_reversemap, new_address, vent);
  }
821
822
823
824
825

  addrp = (type == RESOLVED_TYPE_IPV4) ?
    &vent->ipv4_address : &vent->hostname_address;
  if (*addrp) {
    addressmap_entry_t *ent = strmap_get(addressmap, *addrp);
826
    if (ent && ent->new_address && !strcasecmp(new_address, ent->new_address)) {
827
      tor_free(new_address);
828
      return tor_strdup(*addrp);
829
    } else
830
831
832
      warn(LD_BUG, "Internal confusion: I thought that '%s' was mapped to by '%s', but '%s' really maps to '%s'. This is a harmless bug.",
           safe_str(new_address), safe_str(*addrp), safe_str(*addrp),
           ent?safe_str(ent->new_address):"(nothing)");
833
834
  }

835
836
  tor_free(*addrp);
  *addrp = addressmap_get_virtual_address(type);
837
838
839
840
  addressmap_register(*addrp, new_address, 2);

#if 0
  {
841
    /* Try to catch possible bugs */
842
843
844
845
846
847
848
849
850
    addressmap_entry_t *ent;
    ent = strmap_get(addressmap, *addrp);
    tor_assert(ent);
    tor_assert(!strcasecmp(ent->new_address,new_address));
    vent = strmap_get(virtaddress_reversemap, new_address);
    tor_assert(vent);
    tor_assert(!strcasecmp(*addrp,
                           (type == RESOLVED_TYPE_IPV4) ?
                           vent->ipv4_address : vent->hostname_address));
851
852
    log_fn(LOG_INFO, "Map from %s to %s okay.",
           safe_str(*addrp),safe_str(new_address));
853
854
855
  }
#endif

856
  return *addrp;
857
858
}

859
860
861
862
/** Return 1 if <b>address</b> has funny characters in it like
 * colons. Return 0 if it's fine.
 */
static int
863
864
address_is_invalid_destination(const char *address)
{
865
866
867
868
869
870
  /* FFFF should flesh this out */
  if (strchr(address,':'))
    return 1;
  return 0;
}

Roger Dingledine's avatar
Roger Dingledine committed
871
/** Iterate over all address mapings which have expiry times between
872
873
874
875
 * min_expires and max_expires, inclusive.  If sl is provided, add an
 * "old-addr new-addr" string to sl for each mapping.  If sl is NULL,
 * remove the mappings.
 */
876
877
878
879
880
881
882
883
void
addressmap_get_mappings(smartlist_t *sl, time_t min_expires, time_t max_expires)
{
   strmap_iter_t *iter;
   const char *key;
   void *_val;
   addressmap_entry_t *val;

884
885
886
   if (!addressmap)
     addressmap_init();

887
   for (iter = strmap_iter_init(addressmap); !strmap_iter_done(iter); ) {
888
889
890
     strmap_iter_get(iter, &key, &_val);
     val = _val;
     if (val->expires >= min_expires && val->expires <= max_expires) {
891
892
       if (!sl) {
         iter = strmap_iter_next_rmv(addressmap,iter);
893
         addressmap_ent_remove(key, val);
894
         continue;
895
       } else if (val->new_address) {
896
897
898
899
900
         size_t len = strlen(key)+strlen(val->new_address)+2;
         char *line = tor_malloc(len);
         tor_snprintf(line, len, "%s %s", key, val->new_address);
         smartlist_add(sl, line);
       }
901
     }
902
     iter = strmap_iter_next(addressmap,iter);
903
904
905
   }
}

906
907
908
909
910
911
912
913
914
915
916
917
918
/** connection_edge_process_inbuf() found a conn in state
 * socks_wait. See if conn->inbuf has the right bytes to proceed with
 * the socks handshake.
 *
 * If the handshake is complete, and it's for a general circuit, then
 * try to attach it to a circuit (or launch one as needed). If it's for
 * a rendezvous circuit, then fetch a rendezvous descriptor first (or
 * attach/launch a circuit if the rendezvous descriptor is already here
 * and fresh enough).
 *
 * Return -1 if an unexpected error with conn (and it should be marked
 * for close), else return 0.
 */
919
920
921
static int
connection_ap_handshake_process_socks(connection_t *conn)
{
922
  socks_request_t *socks;
Roger Dingledine's avatar
Roger Dingledine committed
923
  int sockshere;
924
  hostname_type_t addresstype;
925
926
  or_options_t *options = get_options();
  int tor_should_handle_stream = !options->LeaveStreamsUnattached;
927

Roger Dingledine's avatar
Roger Dingledine committed
928
929
930
931
  tor_assert(conn);
  tor_assert(conn->type == CONN_TYPE_AP);
  tor_assert(conn->state == AP_CONN_STATE_SOCKS_WAIT);
  tor_assert(conn->socks_request);
932
  socks = conn->socks_request;
933

934
  debug(LD_APP,"entered.");
935

936
  sockshere = fetch_from_buf_socks(conn->inbuf, socks, options->TestSocks);
937
938
939
  if (sockshere == 0) {
    if (socks->replylen) {
      connection_write_to_buf(socks->reply, socks->replylen, conn);
940
      socks->replylen = 0; /* zero it out so we can do another round of negotiation */
941
    } else {
942
      debug(LD_APP,"socks handshake not all here yet.");
943
944
945
    }
    return 0;
  } else if (sockshere == -1) {
946
    if (socks->replylen) { /* we should send reply back */
947
      debug(LD_APP,"reply is already set for us. Using it.");
948
949
      connection_ap_handshake_socks_reply(conn, socks->reply, socks->replylen,
                                          SOCKS5_GENERAL_ERROR);
Roger Dingledine's avatar
Roger Dingledine committed
950
    } else {
951
      warn(LD_APP,"Fetching socks handshake failed. Closing.");
952
      connection_ap_handshake_socks_reply(conn, NULL, 0, SOCKS5_GENERAL_ERROR);
Roger Dingledine's avatar
Roger Dingledine committed
953
    }
954
    connection_mark_unattached_ap(conn, END_STREAM_REASON_ALREADY_SOCKS_REPLIED);
955
    return -1;
Roger Dingledine's avatar
Roger Dingledine committed
956
  } /* else socks handshake is done, continue processing */
957

958
  tor_strlower(socks->address); /* normalize it */
959
  debug(LD_APP,"Client asked for %s:%d", safe_str(socks->address),
960
         socks->port);
961
962
963
964

  /* For address map controls, remap the address */
  addressmap_rewrite(socks->address, sizeof(socks->address));

965
966
  if (tor_should_handle_stream &&
      address_is_in_virtual_range(socks->address)) {
967
968
969
970
971
    /* This address was probably handed out by client_dns_get_unmapped_address,
     * but the mapping was discarded for some reason.  We *don't* want to send
     * the address through tor; that's likely to fail, and may leak
     * information.
     */
972
    warn(LD_APP,"Missing mapping for virtual address '%s'. Refusing.",
973
           socks->address); /* don't safe_str() this yet. */
974
    connection_mark_unattached_ap(conn, END_STREAM_REASON_INTERNAL);
975
976
977
    return -1;
  }

978
979
980
  /* Parse the address provided by SOCKS.  Modify it in-place if it
   * specifies a hidden-service (.onion) or particular exit node (.exit).
   */
981
  addresstype = parse_extended_hostname(socks->address);
982

983
  if (tor_should_handle_stream && addresstype == BAD_HOSTNAME) {
984
    warn(LD_APP, "Invalid hostname %s; rejecting", socks->address);
985
986
987
988
    connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
    return -1;
  }

989
  if (addresstype == EXIT_HOSTNAME) {
990
991
    /* foo.exit -- modify conn->chosen_exit_node to specify the exit
     * node, and conn->address to hold only the address portion.*/
992
    char *s = strrchr(socks->address,'.');
Nick Mathewson's avatar
Nick Mathewson committed
993
994
995
996
997
    if (s) {
      if (s[1] != '\0') {
        conn->chosen_exit_name = tor_strdup(s+1);
        *s = 0;
      } else {
998
999
        warn(LD_APP,"Malformed exit address '%s.exit'. Refusing.",
             safe_str(socks->address));