connection.c 99.1 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-2008, The Tor Project, Inc. */
5
6
/* See LICENSE for licensing information */
/* $Id$ */
7
8
const char connection_c_id[] =
  "$Id$";
Roger Dingledine's avatar
Roger Dingledine committed
9

10
11
/**
 * \file connection.c
12
13
 * \brief General high-level functions to handle reading and writing
 * on connections.
14
15
 **/

Roger Dingledine's avatar
Roger Dingledine committed
16
17
#include "or.h"

18
19
20
static connection_t *connection_create_listener(
                               struct sockaddr *listensockaddr, int type,
                               char* address);
21
22
static int connection_init_accepted_conn(connection_t *conn,
                                         uint8_t listener_type);
Nick Mathewson's avatar
Nick Mathewson committed
23
static int connection_handle_listener_read(connection_t *conn, int new_type);
24
static int connection_read_bucket_should_increase(or_connection_t *conn);
25
static int connection_finished_flushing(connection_t *conn);
26
static int connection_flushed_some(connection_t *conn);
27
static int connection_finished_connecting(connection_t *conn);
28
static int connection_reached_eof(connection_t *conn);
29
30
static int connection_read_to_buf(connection_t *conn, int *max_to_read);
static int connection_process_inbuf(connection_t *conn, int package_partial);
31
static void client_check_address_changed(int sock);
32
static void set_constrained_socket_buffers(int sock, int size);
33
34
35

static uint32_t last_interface_ip = 0;
static smartlist_t *outgoing_addrs = NULL;
36
37
38

/**************************************************************/

39
40
41
/**
 * Return the human-readable name for the connection type <b>type</b>
 */
42
43
44
45
46
47
48
49
const char *
conn_type_to_string(int type)
{
  static char buf[64];
  switch (type) {
    case CONN_TYPE_OR_LISTENER: return "OR listener";
    case CONN_TYPE_OR: return "OR";
    case CONN_TYPE_EXIT: return "Exit";
50
    case CONN_TYPE_AP_LISTENER: return "Socks listener";
51
52
53
    case CONN_TYPE_AP_TRANS_LISTENER:
      return "Transparent pf/netfilter listener";
    case CONN_TYPE_AP_NATD_LISTENER: return "Transparent natd listener";
54
    case CONN_TYPE_AP_DNS_LISTENER: return "DNS listener";
55
56
57
    case CONN_TYPE_AP: return "Socks";
    case CONN_TYPE_DIR_LISTENER: return "Directory listener";
    case CONN_TYPE_DIR: return "Directory";
58
59
60
61
    case CONN_TYPE_CPUWORKER: return "CPU worker";
    case CONN_TYPE_CONTROL_LISTENER: return "Control listener";
    case CONN_TYPE_CONTROL: return "Control";
    default:
62
      log_warn(LD_BUG, "unknown connection type %d", type);
63
64
65
66
67
      tor_snprintf(buf, sizeof(buf), "unknown [%d]", type);
      return buf;
  }
}

68
69
70
71
/**
 * Return the human-readable name for the connection state <b>state</b>
 * for the connection type <b>type</b>
 */
72
const char *
73
74
conn_state_to_string(int type, int state)
{
75
76
77
78
  static char buf[96];
  switch (type) {
    case CONN_TYPE_OR_LISTENER:
    case CONN_TYPE_AP_LISTENER:
79
    case CONN_TYPE_AP_TRANS_LISTENER:
80
    case CONN_TYPE_AP_NATD_LISTENER:
81
    case CONN_TYPE_AP_DNS_LISTENER:
82
83
84
85
86
87
88
89
90
91
    case CONN_TYPE_DIR_LISTENER:
    case CONN_TYPE_CONTROL_LISTENER:
      if (state == LISTENER_STATE_READY)
        return "ready";
      break;
    case CONN_TYPE_OR:
      switch (state) {
        case OR_CONN_STATE_CONNECTING: return "connect()ing";
        case OR_CONN_STATE_PROXY_FLUSHING: return "proxy flushing";
        case OR_CONN_STATE_PROXY_READING: return "proxy reading";
92
        case OR_CONN_STATE_TLS_HANDSHAKING: return "handshaking (TLS)";
93
94
95
96
        case OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING:
          return "renegotiating (TLS)";
        case OR_CONN_STATE_TLS_SERVER_RENEGOTIATING:
          return "waiting for renegotiation (TLS)";
97
        case OR_CONN_STATE_OR_HANDSHAKING: return "handshaking (Tor)";
98
99
100
101
102
103
104
105
106
107
108
109
110
        case OR_CONN_STATE_OPEN: return "open";
      }
      break;
    case CONN_TYPE_EXIT:
      switch (state) {
        case EXIT_CONN_STATE_RESOLVING: return "waiting for dest info";
        case EXIT_CONN_STATE_CONNECTING: return "connecting";
        case EXIT_CONN_STATE_OPEN: return "open";
        case EXIT_CONN_STATE_RESOLVEFAILED: return "resolve failed";
      }
      break;
    case CONN_TYPE_AP:
      switch (state) {
111
        case AP_CONN_STATE_SOCKS_WAIT: return "waiting for socks info";
112
        case AP_CONN_STATE_NATD_WAIT: return "waiting for natd dest info";
113
114
        case AP_CONN_STATE_RENDDESC_WAIT: return "waiting for rendezvous desc";
        case AP_CONN_STATE_CONTROLLER_WAIT: return "waiting for controller";
115
116
117
        case AP_CONN_STATE_CIRCUIT_WAIT: return "waiting for circuit";
        case AP_CONN_STATE_CONNECT_WAIT: return "waiting for connect response";
        case AP_CONN_STATE_RESOLVE_WAIT: return "waiting for resolve response";
118
119
120
121
122
123
124
        case AP_CONN_STATE_OPEN: return "open";
      }
      break;
    case CONN_TYPE_DIR:
      switch (state) {
        case DIR_CONN_STATE_CONNECTING: return "connecting";
        case DIR_CONN_STATE_CLIENT_SENDING: return "client sending";
Roger Dingledine's avatar
Roger Dingledine committed
125
        case DIR_CONN_STATE_CLIENT_READING: return "client reading";
126
        case DIR_CONN_STATE_CLIENT_FINISHED: return "client finished";
127
128
129
130
131
132
133
134
135
136
137
138
        case DIR_CONN_STATE_SERVER_COMMAND_WAIT: return "waiting for command";
        case DIR_CONN_STATE_SERVER_WRITING: return "writing";
      }
      break;
    case CONN_TYPE_CPUWORKER:
      switch (state) {
        case CPUWORKER_STATE_IDLE: return "idle";
        case CPUWORKER_STATE_BUSY_ONION: return "busy with onion";
      }
      break;
    case CONN_TYPE_CONTROL:
      switch (state) {
139
140
        case CONTROL_CONN_STATE_OPEN: return "open (protocol v1)";
        case CONTROL_CONN_STATE_NEEDAUTH:
141
          return "waiting for authentication (protocol v1)";
142
143
144
145
      }
      break;
  }

146
  log_warn(LD_BUG, "unknown connection state %d (type %d)", state, type);
147
148
149
150
151
152
  tor_snprintf(buf, sizeof(buf),
               "unknown state [%d] on unknown [%s] connection",
               state, conn_type_to_string(type));
  return buf;
}

153
/** Allocate space for a new connection_t. This function just initializes
154
155
 * conn; you must call connection_add() to link it into the main array.
 *
156
 * Set conn-\>type to <b>type</b>. Set conn-\>s and conn-\>conn_array_index to
157
158
159
160
161
162
163
164
165
 * -1 to signify they are not yet assigned.
 *
 * If conn is not a listener type, allocate buffers for it. If it's
 * an AP type, allocate space to store the socks_request.
 *
 * Assign a pseudorandom next_circ_id between 0 and 2**15.
 *
 * Initialize conn's timestamps to now.
 */
166
connection_t *
167
connection_new(int type, int socket_family)
168
{
169
  static uint32_t n_connections_allocated = 1;
Roger Dingledine's avatar
Roger Dingledine committed
170
  connection_t *conn;
171
  time_t now = time(NULL);
172
173
  size_t length;
  uint32_t magic;
Roger Dingledine's avatar
Roger Dingledine committed
174

175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
  switch (type) {
    case CONN_TYPE_OR:
      length = sizeof(or_connection_t);
      magic = OR_CONNECTION_MAGIC;
      break;
    case CONN_TYPE_EXIT:
    case CONN_TYPE_AP:
      length = sizeof(edge_connection_t);
      magic = EDGE_CONNECTION_MAGIC;
      break;
    case CONN_TYPE_DIR:
      length = sizeof(dir_connection_t);
      magic = DIR_CONNECTION_MAGIC;
      break;
    case CONN_TYPE_CONTROL:
      length = sizeof(control_connection_t);
      magic = CONTROL_CONNECTION_MAGIC;
      break;
    default:
      length = sizeof(connection_t);
      magic = BASE_CONNECTION_MAGIC;
      break;
  }

  conn = tor_malloc_zero(length);
  conn->magic = magic;
201
  conn->s = -1; /* give it a default of 'not used' */
202
  conn->conn_array_index = -1; /* also default to 'not used' */
Roger Dingledine's avatar
Roger Dingledine committed
203
204

  conn->type = type;
205
  conn->socket_family = socket_family;
206
  if (!connection_is_listener(conn)) { /* listeners never use their buf */
207
208
209
    conn->inbuf = buf_new();
    conn->outbuf = buf_new();
  }
210
  if (type == CONN_TYPE_AP) {
211
212
    TO_EDGE_CONN(conn)->socks_request =
      tor_malloc_zero(sizeof(socks_request_t));
213
  }
214
215
216
  if (CONN_IS_EDGE(conn)) {
    TO_EDGE_CONN(conn)->global_identifier = n_connections_allocated++;
  }
217
218
  if (type == CONN_TYPE_OR) {
    TO_OR_CONN(conn)->timestamp_last_added_nonpadding = now;
219
    TO_OR_CONN(conn)->next_circ_id = crypto_rand_int(1<<15);
220
  }
221

222
223
224
  conn->timestamp_created = now;
  conn->timestamp_lastread = now;
  conn->timestamp_lastwritten = now;
225

Roger Dingledine's avatar
Roger Dingledine committed
226
227
228
  return conn;
}

Roger Dingledine's avatar
Roger Dingledine committed
229
/** Create a link between <b>conn_a</b> and <b>conn_b</b>. */
230
231
232
233
234
235
236
237
238
239
240
241
void
connection_link_connections(connection_t *conn_a, connection_t *conn_b)
{
  tor_assert(conn_a->s < 0);
  tor_assert(conn_b->s < 0);

  conn_a->linked = 1;
  conn_b->linked = 1;
  conn_a->linked_conn = conn_b;
  conn_b->linked_conn = conn_a;
}

242
243
/** Tell libevent that we don't care about <b>conn</b> any more. */
void
244
connection_unregister_events(connection_t *conn)
245
246
247
{
  if (conn->read_event) {
    if (event_del(conn->read_event))
Roger Dingledine's avatar
Roger Dingledine committed
248
      log_warn(LD_BUG, "Error removing read event for %d", conn->s);
249
250
251
252
    tor_free(conn->read_event);
  }
  if (conn->write_event) {
    if (event_del(conn->write_event))
Roger Dingledine's avatar
Roger Dingledine committed
253
      log_warn(LD_BUG, "Error removing write event for %d", conn->s);
254
255
    tor_free(conn->write_event);
  }
256
257
258
  if (conn->dns_server_port) {
    dnsserv_close_listener(conn);
  }
259
260
}

261
262
263
/** Deallocate memory used by <b>conn</b>. Deallocate its buffers if
 * necessary, close its socket if necessary, and mark the directory as dirty
 * if <b>conn</b> is an OR or OP connection.
264
 */
265
static void
266
267
_connection_free(connection_t *conn)
{
268
  void *mem;
269
  size_t memlen;
270
271
272
273
  switch (conn->type) {
    case CONN_TYPE_OR:
      tor_assert(conn->magic == OR_CONNECTION_MAGIC);
      mem = TO_OR_CONN(conn);
274
      memlen = sizeof(or_connection_t);
275
276
277
278
279
      break;
    case CONN_TYPE_AP:
    case CONN_TYPE_EXIT:
      tor_assert(conn->magic == EDGE_CONNECTION_MAGIC);
      mem = TO_EDGE_CONN(conn);
280
      memlen = sizeof(edge_connection_t);
281
282
283
284
      break;
    case CONN_TYPE_DIR:
      tor_assert(conn->magic == DIR_CONNECTION_MAGIC);
      mem = TO_DIR_CONN(conn);
285
      memlen = sizeof(dir_connection_t);
286
287
288
289
      break;
    case CONN_TYPE_CONTROL:
      tor_assert(conn->magic == CONTROL_CONNECTION_MAGIC);
      mem = TO_CONTROL_CONN(conn);
290
      memlen = sizeof(control_connection_t);
291
292
293
294
      break;
    default:
      tor_assert(conn->magic == BASE_CONNECTION_MAGIC);
      mem = conn;
295
      memlen = sizeof(connection_t);
296
297
      break;
  }
Roger Dingledine's avatar
Roger Dingledine committed
298

299
  if (conn->linked) {
300
301
302
303
304
    log_info(LD_GENERAL, "Freeing linked %s connection [%s] with %d "
             "bytes on inbuf, %d on outbuf.",
             conn_type_to_string(conn->type),
             conn_state_to_string(conn->type, conn->state),
             (int)buf_datalen(conn->inbuf), (int)buf_datalen(conn->outbuf));
305
306
  }

307
  if (!connection_is_listener(conn)) {
308
309
    buf_free(conn->inbuf);
    buf_free(conn->outbuf);
310
  } else {
311
    if (conn->socket_family == AF_UNIX) {
312
313
314
315
316
317
318
319
320
      /* For now only control ports can be unix domain sockets
       * and listeners at the same time */
      tor_assert(conn->type == CONN_TYPE_CONTROL_LISTENER);

      if (unlink(conn->address) < 0 && errno != ENOENT) {
        log_warn(LD_NET, "Could not unlink %s: %s", conn->address,
                         strerror(errno));
      }
    }
321
  }
322

323
  tor_free(conn->address);
Roger Dingledine's avatar
Roger Dingledine committed
324

325
  if (connection_speaks_cells(conn)) {
326
327
328
329
    or_connection_t *or_conn = TO_OR_CONN(conn);
    if (or_conn->tls) {
      tor_tls_free(or_conn->tls);
      or_conn->tls = NULL;
330
    }
331
332
333
334
    if (or_conn->handshake_state) {
      or_handshake_state_free(or_conn->handshake_state);
      or_conn->handshake_state = NULL;
    }
335
336
337
338
339
    tor_free(or_conn->nickname);
  }
  if (CONN_IS_EDGE(conn)) {
    edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
    tor_free(edge_conn->chosen_exit_name);
340
341
342
343
    if (edge_conn->socks_request) {
      memset(edge_conn->socks_request, 0xcc, sizeof(socks_request_t));
      tor_free(edge_conn->socks_request);
    }
344
345
346
347
  }
  if (conn->type == CONN_TYPE_CONTROL) {
    control_connection_t *control_conn = TO_CONTROL_CONN(conn);
    tor_free(control_conn->incoming_cmd);
Roger Dingledine's avatar
Roger Dingledine committed
348
349
  }

350
351
  tor_free(conn->read_event); /* Probably already freed by connection_free. */
  tor_free(conn->write_event); /* Probably already freed by connection_free. */
352
353
354
355
356
357
358
359
360
361
362
363
364

  if (conn->type == CONN_TYPE_DIR) {
    dir_connection_t *dir_conn = TO_DIR_CONN(conn);
    tor_free(dir_conn->requested_resource);
    if (dir_conn->zlib_state)
      tor_zlib_free(dir_conn->zlib_state);
    if (dir_conn->fingerprint_stack) {
      SMARTLIST_FOREACH(dir_conn->fingerprint_stack, char *, cp, tor_free(cp));
      smartlist_free(dir_conn->fingerprint_stack);
    }
    if (dir_conn->cached_dir)
      cached_dir_decref(dir_conn->cached_dir);
  }
365

366
  if (conn->s >= 0) {
Roger Dingledine's avatar
Roger Dingledine committed
367
    log_debug(LD_NET,"closing fd %d.",conn->s);
368
    tor_close_socket(conn->s);
369
    conn->s = -1;
370
371
  }

372
  if (conn->type == CONN_TYPE_OR &&
373
      !tor_digest_is_zero(TO_OR_CONN(conn)->identity_digest)) {
Roger Dingledine's avatar
Roger Dingledine committed
374
    log_warn(LD_BUG, "called on OR conn with non-zeroed identity_digest");
375
    connection_or_remove_from_identity_map(TO_OR_CONN(conn));
376
  }
377

378
  memset(conn, 0xAA, memlen); /* poison memory */
379
  tor_free(mem);
Roger Dingledine's avatar
Roger Dingledine committed
380
381
}

382
383
/** Make sure <b>conn</b> isn't in any of the global conn lists; then free it.
 */
384
385
386
void
connection_free(connection_t *conn)
{
387
388
389
  tor_assert(conn);
  tor_assert(!connection_is_on_closeable_list(conn));
  tor_assert(!connection_in_array(conn));
390
391
392
393
394
395
396
397
398
  if (conn->linked_conn) {
    log_err(LD_BUG, "Called with conn->linked_conn still set.");
    tor_fragile_assert();
    conn->linked_conn->linked_conn = NULL;
    if (! conn->linked_conn->marked_for_close &&
        conn->linked_conn->reading_from_linked_conn)
      connection_start_reading(conn->linked_conn);
    conn->linked_conn = NULL;
  }
399
  if (connection_speaks_cells(conn)) {
400
401
    if (!tor_digest_is_zero(TO_OR_CONN(conn)->identity_digest)) {
      connection_or_remove_from_identity_map(TO_OR_CONN(conn));
402
    }
403
  }
404
  if (conn->type == CONN_TYPE_CONTROL) {
405
    TO_CONTROL_CONN(conn)->event_mask = 0;
406
407
    control_update_global_event_mask();
  }
408
  connection_unregister_events(conn);
409
410
411
  _connection_free(conn);
}

412
413
414
415
/** Call _connection_free() on every connection in our array, and release all
 * storage helpd by connection.c. This is used by cpuworkers and dnsworkers
 * when they fork, so they don't keep resources held open (especially
 * sockets).
416
417
418
 *
 * Don't do the checks in connection_free(), because they will
 * fail.
419
 */
420
421
422
void
connection_free_all(void)
{
423
  smartlist_t *conns = get_connection_array();
424

425
  /* We don't want to log any messages to controllers. */
426
427
428
429
  SMARTLIST_FOREACH(conns, connection_t *, conn,
    if (conn->type == CONN_TYPE_CONTROL)
      TO_CONTROL_CONN(conn)->event_mask = 0);

430
431
  control_update_global_event_mask();

432
433
434
  /* Unlink everything from the identity map. */
  connection_or_clear_identity_map();

435
  SMARTLIST_FOREACH(conns, connection_t *, conn, _connection_free(conn));
436
437
438
439
440
441

  if (outgoing_addrs) {
    SMARTLIST_FOREACH(outgoing_addrs, void*, addr, tor_free(addr));
    smartlist_free(outgoing_addrs);
    outgoing_addrs = NULL;
  }
442
443
}

444
445
446
447
448
449
450
451
/** Do any cleanup needed:
 *   - Directory conns that failed to fetch a rendezvous descriptor
 *     need to inform pending rendezvous streams.
 *   - OR conns need to call rep_hist_note_*() to record status.
 *   - AP conns need to send a socks reject if necessary.
 *   - Exit conns need to call connection_dns_remove() if necessary.
 *   - AP and Exit conns need to send an end cell if they can.
 *   - DNS conns need to fail any resolves that are pending on them.
452
 *   - OR and edge connections need to be unlinked from circuits.
453
 */
454
455
void
connection_about_to_close_connection(connection_t *conn)
456
{
457
  circuit_t *circ;
458
459
460
  dir_connection_t *dir_conn;
  or_connection_t *or_conn;
  edge_connection_t *edge_conn;
461
  time_t now = time(NULL);
462

463
  tor_assert(conn->marked_for_close);
464

465
  if (CONN_IS_EDGE(conn)) {
466
    if (!conn->edge_has_sent_end) {
467
      log_warn(LD_BUG, "(Harmless.) Edge connection (marked at %s:%d) "
Roger Dingledine's avatar
Roger Dingledine committed
468
469
               "hasn't sent end yet?",
               conn->marked_for_close_file, conn->marked_for_close);
470
      tor_fragile_assert();
471
    }
472
473
  }

474
  switch (conn->type) {
475
    case CONN_TYPE_DIR:
476
      dir_conn = TO_DIR_CONN(conn);
477
478
479
      if (conn->state < DIR_CONN_STATE_CLIENT_FINISHED) {
        /* It's a directory connection and connecting or fetching
         * failed: forget about this router, and maybe try again. */
480
        connection_dir_request_failed(dir_conn);
481
      }
482
      if (conn->purpose == DIR_PURPOSE_FETCH_RENDDESC)
483
        rend_client_desc_here(dir_conn->rend_query); /* give it a try */
484
485
486
487
488
489
      /* If we were trying to fetch a v2 rend desc and did not succeed,
       * retry as needed. (If a fetch is successful, the connection state
       * is changed to DIR_PURPOSE_HAS_FETCHED_RENDDESC to mark that
       * refetching is unnecessary.) */
      if (conn->purpose == DIR_PURPOSE_FETCH_RENDDESC_V2)
        rend_client_refetch_v2_renddesc(dir_conn->rend_query);
490
      break;
491
    case CONN_TYPE_OR:
492
      or_conn = TO_OR_CONN(conn);
493
494
      /* Remember why we're closing this connection. */
      if (conn->state != OR_CONN_STATE_OPEN) {
495
        if (connection_or_nonopen_was_started_here(or_conn)) {
496
497
          rep_hist_note_connect_failed(or_conn->identity_digest, now);
          entry_guard_register_connect_status(or_conn->identity_digest,0,now);
498
          router_set_status(or_conn->identity_digest, 0);
499
          control_event_or_conn_status(or_conn, OR_CONN_EVENT_FAILED,
500
                  control_tls_error_to_reason(or_conn->tls_error));
501
        }
502
503
504
        /* Inform any pending (not attached) circs that they should
         * give up. */
        circuit_n_conn_done(TO_OR_CONN(conn), 0);
505
      } else if (conn->hold_open_until_flushed) {
506
507
        /* We only set hold_open_until_flushed when we're intentionally
         * closing a connection. */
508
        rep_hist_note_disconnect(or_conn->identity_digest, now);
509
510
        control_event_or_conn_status(or_conn, OR_CONN_EVENT_CLOSED,
                control_tls_error_to_reason(or_conn->tls_error));
511
      } else if (or_conn->identity_digest) {
512
        rep_hist_note_connection_died(or_conn->identity_digest, now);
513
514
        control_event_or_conn_status(or_conn, OR_CONN_EVENT_CLOSED,
                control_tls_error_to_reason(or_conn->tls_error));
515
      }
516
517
518
      /* Now close all the attached circuits on it. */
      circuit_unlink_all_from_or_conn(TO_OR_CONN(conn),
                                      END_CIRC_REASON_OR_CONN_CLOSED);
519
      break;
520
    case CONN_TYPE_AP:
521
522
      edge_conn = TO_EDGE_CONN(conn);
      if (edge_conn->socks_request->has_finished == 0) {
523
524
        /* since conn gets removed right after this function finishes,
         * there's no point trying to send back a reply at this point. */
525
        log_warn(LD_BUG,"Closing stream (marked at %s:%d) without sending"
Roger Dingledine's avatar
Roger Dingledine committed
526
527
                 " back a socks reply.",
                 conn->marked_for_close_file, conn->marked_for_close);
528
      }
529
      if (!edge_conn->end_reason) {
530
        log_warn(LD_BUG,"Closing stream (marked at %s:%d) without having"
531
                 " set end_reason.",
532
533
                 conn->marked_for_close_file, conn->marked_for_close);
      }
534
535
536
537
538
539
      if (edge_conn->dns_server_request) {
        log_warn(LD_BUG,"Closing stream (marked at %s:%d) without having"
                 " replied to DNS request.",
                 conn->marked_for_close_file, conn->marked_for_close);
        dnsserv_reject_request(edge_conn);
      }
540
      control_event_stream_status(edge_conn, STREAM_EVENT_CLOSED,
541
                                  edge_conn->end_reason);
542
543
544
      circ = circuit_get_by_edge_conn(edge_conn);
      if (circ)
        circuit_detach_stream(circ, edge_conn);
545
      break;
546
    case CONN_TYPE_EXIT:
547
      edge_conn = TO_EDGE_CONN(conn);
548
549
550
      circ = circuit_get_by_edge_conn(edge_conn);
      if (circ)
        circuit_detach_stream(circ, edge_conn);
551
      if (conn->state == EXIT_CONN_STATE_RESOLVING) {
552
        connection_dns_remove(edge_conn);
553
      }
554
      break;
555
  }
556
557
}

Roger Dingledine's avatar
Roger Dingledine committed
558
559
/** Return true iff connection_close_immediate() has been called on this
 * connection. */
560
561
562
#define CONN_IS_CLOSED(c) \
  ((c)->linked ? ((c)->linked_conn_is_closed) : ((c)->s < 0))

563
564
565
/** Close the underlying socket for <b>conn</b>, so we don't try to
 * flush it. Must be used in conjunction with (right before)
 * connection_mark_for_close().
566
 */
567
568
void
connection_close_immediate(connection_t *conn)
569
570
{
  assert_connection_ok(conn,0);
571
  if (CONN_IS_CLOSED(conn)) {
572
    log_err(LD_BUG,"Attempt to close already-closed connection.");
573
    tor_fragile_assert();
574
575
    return;
  }
576
  if (conn->outbuf_flushlen) {
Roger Dingledine's avatar
Roger Dingledine committed
577
578
579
580
    log_info(LD_NET,"fd %d, type %s, state %s, %d bytes on outbuf.",
             conn->s, conn_type_to_string(conn->type),
             conn_state_to_string(conn->type, conn->state),
             (int)conn->outbuf_flushlen);
581
  }
582

583
  connection_unregister_events(conn);
584

585
586
  if (conn->s >= 0)
    tor_close_socket(conn->s);
587
  conn->s = -1;
588
589
  if (conn->linked)
    conn->linked_conn_is_closed = 1;
590
  if (!connection_is_listener(conn)) {
591
592
593
    buf_clear(conn->outbuf);
    conn->outbuf_flushlen = 0;
  }
594
595
}

596
/** Mark <b>conn</b> to be closed next time we loop through
597
 * conn_close_if_marked() in main.c. */
598
599
void
_connection_mark_for_close(connection_t *conn, int line, const char *file)
600
601
{
  assert_connection_ok(conn,0);
602
  tor_assert(line);
603
  tor_assert(line < 1<<16); /* marked_for_close can only fit a uint16_t. */
604
  tor_assert(file);
605
606

  if (conn->marked_for_close) {
607
    log(LOG_WARN,LD_BUG,"Duplicate call to connection_mark_for_close at %s:%d"
608
609
        " (first at %s:%d)", file, line, conn->marked_for_close_file,
        conn->marked_for_close);
610
    tor_fragile_assert();
611
    return;
612
613
  }

614
615
  conn->marked_for_close = line;
  conn->marked_for_close_file = file;
616
  add_connection_to_closeable_list(conn);
617
618
619
620
621

  /* in case we're going to be held-open-til-flushed, reset
   * the number of seconds since last successful write, so
   * we get our whole 15 seconds */
  conn->timestamp_lastwritten = time(NULL);
622
623
}

624
625
626
627
628
/** Find each connection that has hold_open_until_flushed set to
 * 1 but hasn't written in the past 15 seconds, and set
 * hold_open_until_flushed to 0. This means it will get cleaned
 * up in the next loop through close_if_marked() in main.c.
 */
629
630
void
connection_expire_held_open(void)
631
632
{
  time_t now;
633
  smartlist_t *conns = get_connection_array();
634
635
636

  now = time(NULL);

637
638
  SMARTLIST_FOREACH(conns, connection_t *, conn,
  {
639
640
641
    /* If we've been holding the connection open, but we haven't written
     * for 15 seconds...
     */
642
    if (conn->hold_open_until_flushed) {
Roger Dingledine's avatar
Roger Dingledine committed
643
      tor_assert(conn->marked_for_close);
644
      if (now - conn->timestamp_lastwritten >= 15) {
Roger Dingledine's avatar
Roger Dingledine committed
645
646
        int severity;
        if (conn->type == CONN_TYPE_EXIT ||
647
648
            (conn->type == CONN_TYPE_DIR &&
             conn->purpose == DIR_PURPOSE_SERVER))
Roger Dingledine's avatar
Roger Dingledine committed
649
650
651
          severity = LOG_INFO;
        else
          severity = LOG_NOTICE;
652
        log_fn(severity, LD_NET,
653
654
               "Giving up on marked_for_close conn that's been flushing "
               "for 15s (fd %d, type %s, state %s).",
655
656
               conn->s, conn_type_to_string(conn->type),
               conn_state_to_string(conn->type, conn->state));
657
658
        conn->hold_open_until_flushed = 0;
      }
659
    }
660
  });
661
662
}

663
664
665
666
667
668
669
/** Create an AF_INET listenaddr struct.
 * <b>listenaddress</b> provides the host and optionally the port information
 * for the new structure.  If no port is provided in <b>listenaddress</b> then
 * <b>listenport</b> is used.
 *
 * If not NULL <b>readable_addrress</b> will contain a copy of the host part of
 * <b>listenaddress</b>.
Nick Mathewson's avatar
Nick Mathewson committed
670
 *
671
 * The listenaddr struct has to be freed by the caller.
672
 */
673
674
675
676
static struct sockaddr_in *
create_inet_sockaddr(const char *listenaddress, uint16_t listenport,
                     char **readable_address) {
  struct sockaddr_in *listenaddr = NULL;
677
  uint32_t addr;
678
  uint16_t usePort = 0;
Roger Dingledine's avatar
Roger Dingledine committed
679

680
681
  if (parse_addr_port(LOG_WARN,
                      listenaddress, readable_address, &addr, &usePort)<0) {
Roger Dingledine's avatar
Roger Dingledine committed
682
683
    log_warn(LD_CONFIG,
             "Error parsing/resolving ListenAddress %s", listenaddress);
684
    goto err;
685
  }
686
  if (usePort==0)
687
    usePort = listenport;
688

689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
  listenaddr = tor_malloc_zero(sizeof(struct sockaddr_in));
  listenaddr->sin_addr.s_addr = htonl(addr);
  listenaddr->sin_family = AF_INET;
  listenaddr->sin_port = htons((uint16_t) usePort);

  return listenaddr;

 err:
  tor_free(listenaddr);
  return NULL;
}

#ifdef HAVE_SYS_UN_H
/** Create an AF_UNIX listenaddr struct.
 * <b>listenaddress</b> provides the path to the unix socket.
 *
 * Eventually <b>listenaddress</b> will also optionally contain user, group,
 * and file permissions for the new socket.  But not yet. XXX
 * Also, since we do not create the socket here the information doesn't help
 * here.
 *
 * If not NULL <b>readable_addrress</b> will contain a copy of the path part of
 * <b>listenaddress</b>.
 *
 * The listenaddr struct has to be freed by the caller.
 */
static struct sockaddr_un *
create_unix_sockaddr(const char *listenaddress, char **readable_address)
{
  struct sockaddr_un *sockaddr = NULL;

  sockaddr = tor_malloc_zero(sizeof(struct sockaddr_un));
  sockaddr->sun_family = AF_UNIX;
  strncpy(sockaddr->sun_path, listenaddress, sizeof(sockaddr->sun_path));

  if (readable_address)
    *readable_address = tor_strdup(listenaddress);

  return sockaddr;
}
#else
static struct sockaddr *
create_unix_sockaddr(const char *listenaddress, char **readable_address)
{
733
734
  (void)listenaddress;
  (void)readable_address;
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
  log_fn(LOG_ERR, LD_BUG,
         "Unix domain sockets not supported, yet we tried to create one.");
  assert(0);
};
#endif /* HAVE_SYS_UN_H */

/** Bind a new non-blocking socket listening to the socket described
 * by <b>listensockaddr</b>.
 *
 * <b>address</b> is only used for logging purposes and to add the information
 * to the conn.
 */
static connection_t *
connection_create_listener(struct sockaddr *listensockaddr, int type,
  char* address)
{
  connection_t *conn;
  int s; /* the socket we're going to make */
  uint16_t usePort = 0;
  int start_reading = 0;
Nick Mathewson's avatar
Nick Mathewson committed
755

756
757
758
759
760
761
762
763
764
  if (get_n_open_sockets() >= get_options()->_ConnLimit-1) {
    int n_conns = get_n_open_sockets();
    log_warn(LD_NET,"Failing because we have %d connections already. Please "
             "raise your ulimit -n.", n_conns);
    control_event_general_status(LOG_WARN, "TOO_MANY_CONNECTIONS CURRENT=%d",
                                 n_conns);
    return NULL;
  }

765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
  if (listensockaddr->sa_family == AF_INET) {
    int is_tcp = (type != CONN_TYPE_AP_DNS_LISTENER);
#ifndef MS_WINDOWS
    int one=1;
#endif
    if (is_tcp)
      start_reading = 1;

    usePort = ntohs( (uint16_t)
                     ((struct sockaddr_in *)listensockaddr)->sin_port);

    log_notice(LD_NET, "Opening %s on %s:%d",
               conn_type_to_string(type), address, usePort);

    s = tor_open_socket(PF_INET,
                        is_tcp ? SOCK_STREAM : SOCK_DGRAM,
                        is_tcp ? IPPROTO_TCP: IPPROTO_UDP);
    if (s < 0) {
      log_warn(LD_NET,"Socket creation failed.");
      goto err;
    }
Roger Dingledine's avatar
Roger Dingledine committed
786

787
#ifndef MS_WINDOWS
788
789
790
791
    /* REUSEADDR on normal places means you can rebind to the port
     * right after somebody else has let it go. But REUSEADDR on win32
     * means you can bind to the port _even when somebody else
     * already has it bound_. So, don't do that on Win32. */
792
793
    setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (void*) &one,
               (socklen_t)sizeof(one));
794
#endif
Roger Dingledine's avatar
Roger Dingledine committed
795

796
    if (bind(s,listensockaddr,(socklen_t)sizeof(struct sockaddr_in)) < 0) {
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
      const char *helpfulhint = "";
      int e = tor_socket_errno(s);
      if (ERRNO_IS_EADDRINUSE(e))
        helpfulhint = ". Is Tor already running?";
      log_warn(LD_NET, "Could not bind to %s:%u: %s%s", address, usePort,
               tor_socket_strerror(e), helpfulhint);
      tor_close_socket(s);
      goto err;
    }

    if (is_tcp) {
      if (listen(s,SOMAXCONN) < 0) {
        log_warn(LD_NET, "Could not listen on %s:%u: %s", address, usePort,
                 tor_socket_strerror(tor_socket_errno(s)));
        tor_close_socket(s);
        goto err;
      }
    }
#ifdef HAVE_SYS_UN_H
  } else if (listensockaddr->sa_family == AF_UNIX) {
    int len;
    start_reading = 1;

    /* For now only control ports can be unix domain sockets
     * and listeners at the same time */
    tor_assert(type == CONN_TYPE_CONTROL_LISTENER);

    log_notice(LD_NET, "Opening %s on %s",
               conn_type_to_string(type), address);

    if (unlink(address) < 0 && errno != ENOENT) {
      log_warn(LD_NET, "Could not unlink %s: %s", address,
                       strerror(errno));
      goto err;
    }
    s = tor_open_socket(AF_UNIX, SOCK_STREAM, 0);
    if (s < 0) {
      log_warn(LD_NET,"Socket creation failed: %s.", strerror(errno));
      goto err;
    }

    len = strlen(((struct sockaddr_un *)listensockaddr)->sun_path) +
          sizeof(((struct sockaddr_un *)listensockaddr)->sun_family);
    if (bind(s, listensockaddr, len) == -1) {
      log_warn(LD_NET,"Bind to %s failed: %s.", address,
               tor_socket_strerror(tor_socket_errno(s)));
      goto err;
    }
Roger Dingledine's avatar
Roger Dingledine committed
845

846
    if (listen(s,SOMAXCONN) < 0) {
847
      log_warn(LD_NET, "Could not listen on %s: %s", address,
848
849
850
851
               tor_socket_strerror(tor_socket_errno(s)));
      tor_close_socket(s);
      goto err;
    }
852
853
854
855
856
#endif /* HAVE_SYS_UN_H */
  } else {
      log_err(LD_BUG,"Got unexpected address family %d.",
              listensockaddr->sa_family);
      tor_assert(0);
Roger Dingledine's avatar
Roger Dingledine committed
857
858
  }

859
  set_socket_nonblocking(s);
Roger Dingledine's avatar
Roger Dingledine committed
860

861
  conn = connection_new(type, listensockaddr->sa_family);
862
  conn->socket_family = listensockaddr->sa_family;
Roger Dingledine's avatar
Roger Dingledine committed
863
  conn->s = s;
864
  conn->address = tor_strdup(address);
865
  conn->port = usePort;
Roger Dingledine's avatar
Roger Dingledine committed
866

867
  if (connection_add(conn) < 0) { /* no space, forget it */
868
    log_warn(LD_NET,"connection_add for listener failed. Giving up.");
Roger Dingledine's avatar
Roger Dingledine committed
869
    connection_free(conn);
870
    goto err;
Roger Dingledine's avatar
Roger Dingledine committed
871
872
  }

Roger Dingledine's avatar
Roger Dingledine committed
873
874
  log_debug(LD_NET,"%s listening on port %u.",
            conn_type_to_string(type), usePort);
Roger Dingledine's avatar
Roger Dingledine committed
875
876

  conn->state = LISTENER_STATE_READY;
877
  if (start_reading) {
878
879
880
881
882
    connection_start_reading(conn);
  } else {
    tor_assert(type == CONN_TYPE_AP_DNS_LISTENER);
    dnsserv_configure_listener(conn);
  }
Roger Dingledine's avatar
Roger Dingledine committed
883

884
  return conn;
885
886

 err:
887
  return NULL;
Roger Dingledine's avatar
Roger Dingledine committed
888
889
}

890
891
892
893
894
895
896
897
898
/** Do basic sanity checking on a newly received socket. Return 0
 * if it looks ok, else return -1. */
static int
check_sockaddr_in(struct sockaddr *sa, int len, int level)
{
  int ok = 1;
  struct sockaddr_in *sin=(struct sockaddr_in*)sa;

  if (len != sizeof(struct sockaddr_in)) {
899
    log_fn(level, LD_NET, "Length of address not as expected: %d vs %d",
900
901
902
903
           len,(int)sizeof(struct sockaddr_in));
    ok = 0;
  }
  if (sa->sa_family != AF_INET) {
904
    log_fn(level, LD_NET, "Family of address not as expected: %d vs %d",
905
906
907
908
           sa->sa_family, AF_INET);
    ok = 0;
  }
  if (sin->sin_addr.s_addr == 0 || sin->sin_port == 0) {
909
910
    log_fn(level, LD_NET,
           "Address for new connection has address/port equal to zero.");
911
912
913
914
915
    ok = 0;
  }
  return ok ? 0 : -1;
}

916
/** The listener connection <b>conn</b> told poll() it wanted to read.
Nick Mathewson's avatar
Nick Mathewson committed
917
 * Call accept() on conn-\>s, and add the new connection if necessary.
918
 */
919
920
921
static int
connection_handle_listener_read(connection_t *conn, int new_type)
{
Roger Dingledine's avatar
Roger Dingledine committed
922
923
  int news; /* the new socket */
  connection_t *newconn;
924
925
  /* information about the remote peer when connecting to other routers */
  struct sockaddr_in remote;
926
  char addrbuf[256];
927
  /* length of the remote address. Must be whatever accept() needs. */
928
  socklen_t remotelen = sizeof(addrbuf);
929
  char tmpbuf[INET_NTOA_BUF_LEN];
930
931
  or_options_t *options = get_options();

Nick Mathewson's avatar
Nick Mathewson committed
932
  tor_assert((size_t)remotelen >= sizeof(struct sockaddr_in));
933
  memset(addrbuf, 0, sizeof(addrbuf));
Roger Dingledine's avatar
Roger Dingledine committed
934

935
  news = tor_accept_socket(conn->s,(struct sockaddr *)&addrbuf,&remotelen);
Roger Dingledine's avatar
tweak    
Roger Dingledine committed
936
  if (news < 0) { /* accept() error */
937
    int e = tor_socket_errno(conn->s);
938
    if (ERRNO_IS_ACCEPT_EAGAIN(e)) {
Roger Dingledine's avatar
Roger Dingledine committed
939
      return 0; /* he hung up before we could accept(). that's fine. */
940
    } else if (ERRNO_IS_ACCEPT_RESOURCE_LIMIT(e)) {
Roger Dingledine's avatar
Roger Dingledine committed
941
942
      log_notice(LD_NET,"accept failed: %s. Dropping incoming connection.",
                 tor_socket_strerror(e));
943
      return 0;
944
    }
Roger Dingledine's avatar
Roger Dingledine committed
945
    /* else there was a real error. */
Roger Dingledine's avatar
Roger Dingledine committed
946
947
    log_warn(LD_NET,"accept() failed: %s. Closing listener.",
             tor_socket_strerror(e));
948
    connection_mark_for_close(conn);
Roger Dingledine's avatar
Roger Dingledine committed
949
950
    return -1;
  }
Roger Dingledine's avatar
Roger Dingledine committed
951
952
953
  log_debug(LD_NET,
            "Connection accepted on socket %d (child of fd %d).",
            news,conn->s);
Roger Dingledine's avatar
Roger Dingledine committed
954

955
  set_socket_nonblocking(news);
956

957
958
  if (options->ConstrainedSockets)
    set_constrained_socket_buffers(news, (int)options->ConstrainedSockSize);
959

960
  if (((struct sockaddr*)addrbuf)->sa_family != conn->socket_family) {
961
962
    /* This is annoying, but can apparently happen on some Darwins. */
    log_info(LD_BUG, "A listener connection returned a socket with a "
963
             "mismatched family. %s for addr_family %d gave us a socket "
964
965
             "with address family %d.  Dropping.",
             conn_type_to_string(conn->type),
966
967
968
969
970
             (int)conn->socket_family,
             (int)((struct sockaddr*)addrbuf)->sa_family);
    tor_close_socket(news);
    return 0;
  }
971

972
  if (conn->socket_family == AF_INET) {
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
    if (check_sockaddr_in((struct sockaddr*)addrbuf, remotelen, LOG_INFO)<0) {
      log_info(LD_NET,
               "accept() returned a strange address; trying getsockname().");
      remotelen=256;
      memset(addrbuf, 0, sizeof(addrbuf));
      if (getsockname(news, (struct sockaddr*)addrbuf, &remotelen)<0) {
        int e = tor_socket_errno(news);
        log_warn(LD_NET, "getsockname() for new connection failed: %s",
                 tor_socket_strerror(e));
      } else {
        if (check_sockaddr_in((struct sockaddr*)addrbuf, remotelen,
                              LOG_WARN) < 0) {
          log_warn(LD_NET,"Something's wrong with this conn. Closing it.");
          tor_close_socket(news);
          return 0;
        }
      }
    }
    memcpy(&remote, addrbuf, sizeof(struct sockaddr_in));

    /* process entrance policies here, before we even create the connection */
    if (new_type == CONN_TYPE_AP) {
      /* check sockspolicy to see if we should accept it */
      if (socks_policy_permits_address(ntohl(remote.sin_addr.s_addr)) == 0) {
        tor_inet_ntoa(&remote.sin_addr, tmpbuf, sizeof(tmpbuf));
        log_notice(LD_APP,
                   "Denying socks connection from untrusted address %s.",
                   tmpbuf);