connection.c 103 KB
Newer Older
Roger Dingledine's avatar
Roger Dingledine committed
1
2
/* Copyright (c) 2001 Matej Pfajfar.
 * Copyright (c) 2001-2004, Roger Dingledine.
3
 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
Karsten Loesing's avatar
Karsten Loesing committed
4
 * Copyright (c) 2007-2009, The Tor Project, Inc. */
5
/* See LICENSE for licensing information */
Roger Dingledine's avatar
Roger Dingledine committed
6

7
8
/**
 * \file connection.c
9
10
 * \brief General high-level functions to handle reading and writing
 * on connections.
11
12
 **/

Roger Dingledine's avatar
Roger Dingledine committed
13
14
#include "or.h"

15
static connection_t *connection_create_listener(
16
17
                               struct sockaddr *listensockaddr,
                               socklen_t listensocklen, int type,
18
                               char* address);
19
20
static void connection_init(time_t now, connection_t *conn, int type,
                            int socket_family);
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,
                                  int *socket_error);
31
static int connection_process_inbuf(connection_t *conn, int package_partial);
32
static void client_check_address_changed(int sock);
33
static void set_constrained_socket_buffers(int sock, int size);
34

35
36
/** The last IPv4 address that our network interface seemed to have been
 * binding to, in host order.  We use this to detect when our IP changes. */
37
static uint32_t last_interface_ip = 0;
38
39
/** A list of uint32_ts for addresses we've used in outgoing connections.
 * Used to detect IP address changes. */
40
static smartlist_t *outgoing_addrs = NULL;
41
42
43

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

44
45
46
/**
 * Return the human-readable name for the connection type <b>type</b>
 */
47
48
49
50
51
52
53
54
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";
55
    case CONN_TYPE_AP_LISTENER: return "Socks listener";
56
57
58
    case CONN_TYPE_AP_TRANS_LISTENER:
      return "Transparent pf/netfilter listener";
    case CONN_TYPE_AP_NATD_LISTENER: return "Transparent natd listener";
59
    case CONN_TYPE_AP_DNS_LISTENER: return "DNS listener";
60
61
62
    case CONN_TYPE_AP: return "Socks";
    case CONN_TYPE_DIR_LISTENER: return "Directory listener";
    case CONN_TYPE_DIR: return "Directory";
63
64
65
66
    case CONN_TYPE_CPUWORKER: return "CPU worker";
    case CONN_TYPE_CONTROL_LISTENER: return "Control listener";
    case CONN_TYPE_CONTROL: return "Control";
    default:
67
      log_warn(LD_BUG, "unknown connection type %d", type);
68
69
70
71
72
      tor_snprintf(buf, sizeof(buf), "unknown [%d]", type);
      return buf;
  }
}

73
74
75
76
/**
 * Return the human-readable name for the connection state <b>state</b>
 * for the connection type <b>type</b>
 */
77
const char *
78
79
conn_state_to_string(int type, int state)
{
80
81
82
83
  static char buf[96];
  switch (type) {
    case CONN_TYPE_OR_LISTENER:
    case CONN_TYPE_AP_LISTENER:
84
    case CONN_TYPE_AP_TRANS_LISTENER:
85
    case CONN_TYPE_AP_NATD_LISTENER:
86
    case CONN_TYPE_AP_DNS_LISTENER:
87
88
89
90
91
92
93
94
95
96
    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";
97
        case OR_CONN_STATE_TLS_HANDSHAKING: return "handshaking (TLS)";
98
99
100
101
        case OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING:
          return "renegotiating (TLS)";
        case OR_CONN_STATE_TLS_SERVER_RENEGOTIATING:
          return "waiting for renegotiation (TLS)";
102
        case OR_CONN_STATE_OR_HANDSHAKING: return "handshaking (Tor)";
103
104
105
106
107
108
109
110
111
112
113
114
115
        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) {
116
        case AP_CONN_STATE_SOCKS_WAIT: return "waiting for socks info";
117
        case AP_CONN_STATE_NATD_WAIT: return "waiting for natd dest info";
118
119
        case AP_CONN_STATE_RENDDESC_WAIT: return "waiting for rendezvous desc";
        case AP_CONN_STATE_CONTROLLER_WAIT: return "waiting for controller";
120
121
122
        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";
123
124
125
126
127
128
129
        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
130
        case DIR_CONN_STATE_CLIENT_READING: return "client reading";
131
        case DIR_CONN_STATE_CLIENT_FINISHED: return "client finished";
132
133
134
135
136
137
138
139
140
141
142
143
        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) {
144
145
        case CONTROL_CONN_STATE_OPEN: return "open (protocol v1)";
        case CONTROL_CONN_STATE_NEEDAUTH:
146
          return "waiting for authentication (protocol v1)";
147
148
149
150
      }
      break;
  }

151
  log_warn(LD_BUG, "unknown connection state %d (type %d)", state, type);
152
153
154
155
156
157
  tor_snprintf(buf, sizeof(buf),
               "unknown state [%d] on unknown [%s] connection",
               state, conn_type_to_string(type));
  return buf;
}

158
159
/** Allocate and return a new dir_connection_t, initialized as by
 * connection_init(). */
160
161
162
163
164
165
166
dir_connection_t *
dir_connection_new(int socket_family)
{
  dir_connection_t *dir_conn = tor_malloc_zero(sizeof(dir_connection_t));
  connection_init(time(NULL), TO_CONN(dir_conn), CONN_TYPE_DIR, socket_family);
  return dir_conn;
}
167
168
169

/** Allocate and return a new or_connection_t, initialized as by
 * connection_init(). */
170
171
172
173
174
175
176
177
178
179
180
181
or_connection_t *
or_connection_new(int socket_family)
{
  or_connection_t *or_conn = tor_malloc_zero(sizeof(or_connection_t));
  time_t now = time(NULL);
  connection_init(now, TO_CONN(or_conn), CONN_TYPE_OR, socket_family);

  or_conn->timestamp_last_added_nonpadding = time(NULL);
  or_conn->next_circ_id = crypto_rand_int(1<<15);

  return or_conn;
}
182
183
184

/** Allocate and return a new edge_connection_t, initialized as by
 * connection_init(). */
185
186
187
188
189
190
191
192
193
194
edge_connection_t *
edge_connection_new(int type, int socket_family)
{
  edge_connection_t *edge_conn = tor_malloc_zero(sizeof(edge_connection_t));
  tor_assert(type == CONN_TYPE_EXIT || type == CONN_TYPE_AP);
  connection_init(time(NULL), TO_CONN(edge_conn), type, socket_family);
  if (type == CONN_TYPE_AP)
    edge_conn->socks_request = tor_malloc_zero(sizeof(socks_request_t));
  return edge_conn;
}
195
196
197

/** Allocate and return a new control_connection_t, initialized as by
 * connection_init(). */
198
199
200
201
202
203
204
205
206
207
control_connection_t *
control_connection_new(int socket_family)
{
  control_connection_t *control_conn =
    tor_malloc_zero(sizeof(control_connection_t));
  connection_init(time(NULL),
                  TO_CONN(control_conn), CONN_TYPE_CONTROL, socket_family);
  return control_conn;
}

208
209
210
/** Allocate, initialize, and return a new connection_t subtype of <b>type</b>
 * to make or receive connections of address family <b>socket_family</b>.  The
 * type should be one of the CONN_TYPE_* constants. */
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
connection_t *
connection_new(int type, int socket_family)
{
  switch (type) {
    case CONN_TYPE_OR:
      return TO_CONN(or_connection_new(socket_family));

    case CONN_TYPE_EXIT:
    case CONN_TYPE_AP:
      return TO_CONN(edge_connection_new(type, socket_family));

    case CONN_TYPE_DIR:
      return TO_CONN(dir_connection_new(socket_family));

    case CONN_TYPE_CONTROL:
      return TO_CONN(control_connection_new(socket_family));

    default: {
      connection_t *conn = tor_malloc_zero(sizeof(connection_t));
      connection_init(time(NULL), conn, type, socket_family);
      return conn;
    }
  }
}

/** Initializes conn. (you must call connection_add() to link it into the main
 * array).
238
 *
239
 * Set conn-\>type to <b>type</b>. Set conn-\>s and conn-\>conn_array_index to
240
241
242
243
244
245
246
247
248
 * -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.
 */
249
250
static void
connection_init(time_t now, connection_t *conn, int type, int socket_family)
251
{
252
253
  static uint64_t n_connections_allocated = 1;

254
255
  switch (type) {
    case CONN_TYPE_OR:
256
      conn->magic = OR_CONNECTION_MAGIC;
257
258
259
      break;
    case CONN_TYPE_EXIT:
    case CONN_TYPE_AP:
260
      conn->magic = EDGE_CONNECTION_MAGIC;
261
262
      break;
    case CONN_TYPE_DIR:
263
      conn->magic = DIR_CONNECTION_MAGIC;
264
265
      break;
    case CONN_TYPE_CONTROL:
266
      conn->magic = CONTROL_CONNECTION_MAGIC;
267
268
      break;
    default:
269
      conn->magic = BASE_CONNECTION_MAGIC;
270
271
272
      break;
  }

273
  conn->s = -1; /* give it a default of 'not used' */
274
  conn->conn_array_index = -1; /* also default to 'not used' */
275
  conn->global_identifier = n_connections_allocated++;
Roger Dingledine's avatar
Roger Dingledine committed
276
277

  conn->type = type;
278
  conn->socket_family = socket_family;
279
  if (!connection_is_listener(conn)) { /* listeners never use their buf */
280
281
282
    conn->inbuf = buf_new();
    conn->outbuf = buf_new();
  }
283

284
285
286
  conn->timestamp_created = now;
  conn->timestamp_lastread = now;
  conn->timestamp_lastwritten = now;
Roger Dingledine's avatar
Roger Dingledine committed
287
288
}

Roger Dingledine's avatar
Roger Dingledine committed
289
/** Create a link between <b>conn_a</b> and <b>conn_b</b>. */
290
291
292
293
294
295
296
297
298
299
300
301
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;
}

302
303
304
/** 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.
305
 */
306
static void
307
308
_connection_free(connection_t *conn)
{
309
  void *mem;
310
  size_t memlen;
311
312
313
314
  switch (conn->type) {
    case CONN_TYPE_OR:
      tor_assert(conn->magic == OR_CONNECTION_MAGIC);
      mem = TO_OR_CONN(conn);
315
      memlen = sizeof(or_connection_t);
316
317
318
319
320
      break;
    case CONN_TYPE_AP:
    case CONN_TYPE_EXIT:
      tor_assert(conn->magic == EDGE_CONNECTION_MAGIC);
      mem = TO_EDGE_CONN(conn);
321
      memlen = sizeof(edge_connection_t);
322
323
324
325
      break;
    case CONN_TYPE_DIR:
      tor_assert(conn->magic == DIR_CONNECTION_MAGIC);
      mem = TO_DIR_CONN(conn);
326
      memlen = sizeof(dir_connection_t);
327
328
329
330
      break;
    case CONN_TYPE_CONTROL:
      tor_assert(conn->magic == CONTROL_CONNECTION_MAGIC);
      mem = TO_CONTROL_CONN(conn);
331
      memlen = sizeof(control_connection_t);
332
333
334
335
      break;
    default:
      tor_assert(conn->magic == BASE_CONNECTION_MAGIC);
      mem = conn;
336
      memlen = sizeof(connection_t);
337
338
      break;
  }
Roger Dingledine's avatar
Roger Dingledine committed
339

340
  if (conn->linked) {
341
342
343
344
345
    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));
346
347
  }

348
  if (!connection_is_listener(conn)) {
349
350
    buf_free(conn->inbuf);
    buf_free(conn->outbuf);
351
  } else {
352
    if (conn->socket_family == AF_UNIX) {
Nick Mathewson's avatar
Nick Mathewson committed
353
      /* For now only control ports can be Unix domain sockets
354
355
356
357
358
359
360
361
       * 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));
      }
    }
362
  }
363

364
  tor_free(conn->address);
Roger Dingledine's avatar
Roger Dingledine committed
365

366
  if (connection_speaks_cells(conn)) {
367
368
369
370
    or_connection_t *or_conn = TO_OR_CONN(conn);
    if (or_conn->tls) {
      tor_tls_free(or_conn->tls);
      or_conn->tls = NULL;
371
    }
372
373
374
375
    if (or_conn->handshake_state) {
      or_handshake_state_free(or_conn->handshake_state);
      or_conn->handshake_state = NULL;
    }
376
377
378
379
380
    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);
381
382
383
384
    if (edge_conn->socks_request) {
      memset(edge_conn->socks_request, 0xcc, sizeof(socks_request_t));
      tor_free(edge_conn->socks_request);
    }
385
386
    if (edge_conn->rend_data)
      rend_data_free(edge_conn->rend_data);
387
388
389
390
  }
  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
391
392
  }

393
394
  tor_free(conn->read_event); /* Probably already freed by connection_free. */
  tor_free(conn->write_event); /* Probably already freed by connection_free. */
395
396
397
398
399
400
401
402
403
404
405
406

  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);
407
408
    if (dir_conn->rend_data)
      rend_data_free(dir_conn->rend_data);
409
  }
410

411
  if (conn->s >= 0) {
Roger Dingledine's avatar
Roger Dingledine committed
412
    log_debug(LD_NET,"closing fd %d.",conn->s);
413
    tor_close_socket(conn->s);
414
    conn->s = -1;
415
416
  }

417
  if (conn->type == CONN_TYPE_OR &&
418
      !tor_digest_is_zero(TO_OR_CONN(conn)->identity_digest)) {
Roger Dingledine's avatar
Roger Dingledine committed
419
    log_warn(LD_BUG, "called on OR conn with non-zeroed identity_digest");
420
    connection_or_remove_from_identity_map(TO_OR_CONN(conn));
421
  }
422

423
  memset(conn, 0xAA, memlen); /* poison memory */
424
  tor_free(mem);
Roger Dingledine's avatar
Roger Dingledine committed
425
426
}

427
428
/** Make sure <b>conn</b> isn't in any of the global conn lists; then free it.
 */
429
430
431
void
connection_free(connection_t *conn)
{
432
433
434
  tor_assert(conn);
  tor_assert(!connection_is_on_closeable_list(conn));
  tor_assert(!connection_in_array(conn));
435
436
437
438
439
440
441
442
443
  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;
  }
444
  if (connection_speaks_cells(conn)) {
445
446
    if (!tor_digest_is_zero(TO_OR_CONN(conn)->identity_digest)) {
      connection_or_remove_from_identity_map(TO_OR_CONN(conn));
447
    }
448
  }
449
  if (conn->type == CONN_TYPE_CONTROL) {
450
    TO_CONTROL_CONN(conn)->event_mask = 0;
451
452
    control_update_global_event_mask();
  }
453
  connection_unregister_events(conn);
454
455
456
  _connection_free(conn);
}

457
/** Call _connection_free() on every connection in our array, and release all
Nick Mathewson's avatar
Nick Mathewson committed
458
 * storage held by connection.c. This is used by cpuworkers and dnsworkers
459
460
 * when they fork, so they don't keep resources held open (especially
 * sockets).
461
462
463
 *
 * Don't do the checks in connection_free(), because they will
 * fail.
464
 */
465
466
467
void
connection_free_all(void)
{
468
  smartlist_t *conns = get_connection_array();
469

470
  /* We don't want to log any messages to controllers. */
471
472
473
474
  SMARTLIST_FOREACH(conns, connection_t *, conn,
    if (conn->type == CONN_TYPE_CONTROL)
      TO_CONTROL_CONN(conn)->event_mask = 0);

475
476
  control_update_global_event_mask();

477
478
479
  /* Unlink everything from the identity map. */
  connection_or_clear_identity_map();

480
  SMARTLIST_FOREACH(conns, connection_t *, conn, _connection_free(conn));
481
482
483
484
485
486

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

489
490
491
492
493
494
495
496
/** 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.
497
 *   - OR and edge connections need to be unlinked from circuits.
498
 */
499
500
void
connection_about_to_close_connection(connection_t *conn)
501
{
502
  circuit_t *circ;
503
504
505
  dir_connection_t *dir_conn;
  or_connection_t *or_conn;
  edge_connection_t *edge_conn;
506
  time_t now = time(NULL);
507

508
  tor_assert(conn->marked_for_close);
509

510
  if (CONN_IS_EDGE(conn)) {
511
512
    edge_conn = TO_EDGE_CONN(conn);
    if (!edge_conn->edge_has_sent_end) {
513
      log_warn(LD_BUG, "(Harmless.) Edge connection (marked at %s:%d) "
Roger Dingledine's avatar
Roger Dingledine committed
514
515
               "hasn't sent end yet?",
               conn->marked_for_close_file, conn->marked_for_close);
516
      tor_fragile_assert();
517
    }
518
519
  }

520
  switch (conn->type) {
521
    case CONN_TYPE_DIR:
522
      dir_conn = TO_DIR_CONN(conn);
523
524
525
      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. */
526
        connection_dir_request_failed(dir_conn);
527
      }
528
529
530
531
      /* 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.) */
Karsten Loesing's avatar
Karsten Loesing committed
532
      if (conn->purpose == DIR_PURPOSE_FETCH_RENDDESC_V2 &&
533
534
535
536
          dir_conn->rend_data &&
          strlen(dir_conn->rend_data->onion_address) ==
              REND_SERVICE_ID_LEN_BASE32)
        rend_client_refetch_v2_renddesc(dir_conn->rend_data);
537
      break;
538
    case CONN_TYPE_OR:
539
      or_conn = TO_OR_CONN(conn);
540
541
      /* Remember why we're closing this connection. */
      if (conn->state != OR_CONN_STATE_OPEN) {
542
543
544
545
        /* Inform any pending (not attached) circs that they should
         * give up. */
        circuit_n_conn_done(TO_OR_CONN(conn), 0);
        /* now mark things down as needed */
546
        if (connection_or_nonopen_was_started_here(or_conn)) {
547
          or_options_t *options = get_options();
548
          rep_hist_note_connect_failed(or_conn->identity_digest, now);
549
550
          entry_guard_register_connect_status(or_conn->identity_digest,0,
                                              !options->HttpsProxy, now);
551
          if (conn->state >= OR_CONN_STATE_TLS_HANDSHAKING) {
552
            int reason = tls_error_to_orconn_end_reason(or_conn->tls_error);
553
554
            control_event_or_conn_status(or_conn, OR_CONN_EVENT_FAILED,
                                         reason);
555
556
557
            if (!authdir_mode_tests_reachability(options))
              control_event_bootstrap_problem(
                orconn_end_reason_to_control_string(reason), reason);
558
          }
559
        }
560
      } else if (conn->hold_open_until_flushed) {
561
562
        /* We only set hold_open_until_flushed when we're intentionally
         * closing a connection. */
563
        rep_hist_note_disconnect(or_conn->identity_digest, now);
564
        control_event_or_conn_status(or_conn, OR_CONN_EVENT_CLOSED,
565
                tls_error_to_orconn_end_reason(or_conn->tls_error));
566
      } else if (or_conn->identity_digest) {
567
        rep_hist_note_connection_died(or_conn->identity_digest, now);
568
        control_event_or_conn_status(or_conn, OR_CONN_EVENT_CLOSED,
569
                tls_error_to_orconn_end_reason(or_conn->tls_error));
570
      }
571
572
573
      /* Now close all the attached circuits on it. */
      circuit_unlink_all_from_or_conn(TO_OR_CONN(conn),
                                      END_CIRC_REASON_OR_CONN_CLOSED);
574
      break;
575
    case CONN_TYPE_AP:
576
577
      edge_conn = TO_EDGE_CONN(conn);
      if (edge_conn->socks_request->has_finished == 0) {
578
579
        /* since conn gets removed right after this function finishes,
         * there's no point trying to send back a reply at this point. */
580
        log_warn(LD_BUG,"Closing stream (marked at %s:%d) without sending"
Roger Dingledine's avatar
Roger Dingledine committed
581
582
                 " back a socks reply.",
                 conn->marked_for_close_file, conn->marked_for_close);
583
      }
584
      if (!edge_conn->end_reason) {
585
        log_warn(LD_BUG,"Closing stream (marked at %s:%d) without having"
586
                 " set end_reason.",
587
588
                 conn->marked_for_close_file, conn->marked_for_close);
      }
589
590
591
592
593
594
      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);
      }
595
      control_event_stream_bandwidth(edge_conn);
596
      control_event_stream_status(edge_conn, STREAM_EVENT_CLOSED,
597
                                  edge_conn->end_reason);
598
599
600
      circ = circuit_get_by_edge_conn(edge_conn);
      if (circ)
        circuit_detach_stream(circ, edge_conn);
601
      break;
602
    case CONN_TYPE_EXIT:
603
      edge_conn = TO_EDGE_CONN(conn);
604
605
606
      circ = circuit_get_by_edge_conn(edge_conn);
      if (circ)
        circuit_detach_stream(circ, edge_conn);
607
      if (conn->state == EXIT_CONN_STATE_RESOLVING) {
608
        connection_dns_remove(edge_conn);
609
      }
610
      break;
611
  }
612
613
}

Roger Dingledine's avatar
Roger Dingledine committed
614
615
/** Return true iff connection_close_immediate() has been called on this
 * connection. */
616
617
618
#define CONN_IS_CLOSED(c) \
  ((c)->linked ? ((c)->linked_conn_is_closed) : ((c)->s < 0))

619
620
621
/** 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().
622
 */
623
624
void
connection_close_immediate(connection_t *conn)
625
626
{
  assert_connection_ok(conn,0);
627
  if (CONN_IS_CLOSED(conn)) {
628
    log_err(LD_BUG,"Attempt to close already-closed connection.");
629
    tor_fragile_assert();
630
631
    return;
  }
632
  if (conn->outbuf_flushlen) {
Roger Dingledine's avatar
Roger Dingledine committed
633
634
635
636
    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);
637
  }
638

639
  connection_unregister_events(conn);
640

641
642
  if (conn->s >= 0)
    tor_close_socket(conn->s);
643
  conn->s = -1;
644
645
  if (conn->linked)
    conn->linked_conn_is_closed = 1;
646
  if (!connection_is_listener(conn)) {
647
648
649
    buf_clear(conn->outbuf);
    conn->outbuf_flushlen = 0;
  }
650
651
}

652
/** Mark <b>conn</b> to be closed next time we loop through
653
 * conn_close_if_marked() in main.c. */
654
655
void
_connection_mark_for_close(connection_t *conn, int line, const char *file)
656
657
{
  assert_connection_ok(conn,0);
658
  tor_assert(line);
659
  tor_assert(line < 1<<16); /* marked_for_close can only fit a uint16_t. */
660
  tor_assert(file);
661
662

  if (conn->marked_for_close) {
663
    log(LOG_WARN,LD_BUG,"Duplicate call to connection_mark_for_close at %s:%d"
664
665
        " (first at %s:%d)", file, line, conn->marked_for_close_file,
        conn->marked_for_close);
666
    tor_fragile_assert();
667
    return;
668
669
  }

670
671
  conn->marked_for_close = line;
  conn->marked_for_close_file = file;
672
  add_connection_to_closeable_list(conn);
673
674
675
676
677

  /* 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);
678
679
}

680
681
682
683
684
/** 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.
 */
685
686
void
connection_expire_held_open(void)
687
688
{
  time_t now;
689
  smartlist_t *conns = get_connection_array();
690
691
692

  now = time(NULL);

693
694
  SMARTLIST_FOREACH(conns, connection_t *, conn,
  {
695
696
697
    /* If we've been holding the connection open, but we haven't written
     * for 15 seconds...
     */
698
    if (conn->hold_open_until_flushed) {
Roger Dingledine's avatar
Roger Dingledine committed
699
      tor_assert(conn->marked_for_close);
700
      if (now - conn->timestamp_lastwritten >= 15) {
Roger Dingledine's avatar
Roger Dingledine committed
701
702
        int severity;
        if (conn->type == CONN_TYPE_EXIT ||
703
704
            (conn->type == CONN_TYPE_DIR &&
             conn->purpose == DIR_PURPOSE_SERVER))
Roger Dingledine's avatar
Roger Dingledine committed
705
706
707
          severity = LOG_INFO;
        else
          severity = LOG_NOTICE;
708
        log_fn(severity, LD_NET,
709
710
               "Giving up on marked_for_close conn that's been flushing "
               "for 15s (fd %d, type %s, state %s).",
711
712
               conn->s, conn_type_to_string(conn->type),
               conn_state_to_string(conn->type, conn->state));
713
714
        conn->hold_open_until_flushed = 0;
      }
715
    }
716
  });
717
718
}

719
720
721
722
723
/** 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.
 *
Nick Mathewson's avatar
Nick Mathewson committed
724
 * If not NULL <b>readable_address</b> will contain a copy of the host part of
725
 * <b>listenaddress</b>.
Nick Mathewson's avatar
Nick Mathewson committed
726
 *
727
 * The listenaddr struct has to be freed by the caller.
728
 */
729
730
static struct sockaddr_in *
create_inet_sockaddr(const char *listenaddress, uint16_t listenport,
731
                     char **readable_address, socklen_t *socklen_out) {
732
  struct sockaddr_in *listenaddr = NULL;
733
  uint32_t addr;
734
  uint16_t usePort = 0;
Roger Dingledine's avatar
Roger Dingledine committed
735

736
737
  if (parse_addr_port(LOG_WARN,
                      listenaddress, readable_address, &addr, &usePort)<0) {
Roger Dingledine's avatar
Roger Dingledine committed
738
739
    log_warn(LD_CONFIG,
             "Error parsing/resolving ListenAddress %s", listenaddress);
740
    goto err;
741
  }
742
  if (usePort==0)
743
    usePort = listenport;
744

745
746
747
748
749
  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);

750
751
  *socklen_out = sizeof(struct sockaddr_in);

752
753
754
755
756
757
758
759
760
  return listenaddr;

 err:
  tor_free(listenaddr);
  return NULL;
}

#ifdef HAVE_SYS_UN_H
/** Create an AF_UNIX listenaddr struct.
Nick Mathewson's avatar
Nick Mathewson committed
761
 * <b>listenaddress</b> provides the path to the Unix socket.
762
763
764
765
766
767
 *
 * 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.
 *
Nick Mathewson's avatar
Nick Mathewson committed
768
 * If not NULL <b>readable_address</b> will contain a copy of the path part of
769
770
771
772
773
 * <b>listenaddress</b>.
 *
 * The listenaddr struct has to be freed by the caller.
 */
static struct sockaddr_un *
774
775
create_unix_sockaddr(const char *listenaddress, char **readable_address,
                     socklen_t *len_out)
776
777
778
779
780
781
782
783
784
785
{
  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);

786
  *len_out = sizeof(struct sockaddr_un);
787
788
789
790
  return sockaddr;
}
#else
static struct sockaddr *
791
792
create_unix_sockaddr(const char *listenaddress, char **readable_address,
                     socklen_t *len_out)
793
{
794
795
  (void)listenaddress;
  (void)readable_address;
796
797
  log_fn(LOG_ERR, LD_BUG,
         "Unix domain sockets not supported, yet we tried to create one.");
798
  *len_out = 0;
799
  tor_assert(0);
800
801
802
};
#endif /* HAVE_SYS_UN_H */

803
804
805
/** Warn that an accept or a connect has failed because we're running up
 * against our ulimit.  Rate-limit these warnings so that we don't spam
 * the log. */
Nick Mathewson's avatar
Nick Mathewson committed
806
807
808
809
static void
warn_too_many_conns(void)
{
#define WARN_TOO_MANY_CONNS_INTERVAL (6*60*60)
810
811
  static time_t last_warned = 0;
  time_t now = time(NULL);
812
  int n_conns = get_n_open_sockets();
Nick Mathewson's avatar
Nick Mathewson committed
813
814
815
816
817
818
819
820
821
  if (last_warned + WARN_TOO_MANY_CONNS_INTERVAL < now) {
    log_warn(LD_NET,"Failing because we have %d connections already. Please "
             "raise your ulimit -n.", n_conns);
    last_warned = now;
  }
  control_event_general_status(LOG_WARN, "TOO_MANY_CONNECTIONS CURRENT=%d",
                               n_conns);
}

822
823
824
825
826
827
828
/** 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 *
829
830
connection_create_listener(struct sockaddr *listensockaddr, socklen_t socklen,
                           int type, char* address)
831
832
833
834
835
{
  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
836

837
  if (get_n_open_sockets() >= get_options()->_ConnLimit-1) {
Nick Mathewson's avatar
Nick Mathewson committed
838
    warn_too_many_conns();
839
840
841
    return NULL;
  }

842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
  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
863

864
#ifndef MS_WINDOWS
865
866
867
868
    /* 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. */
869
870
    setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (void*) &one,
               (socklen_t)sizeof(one));
871
#endif
Roger Dingledine's avatar
Roger Dingledine committed
872

873
    if (bind(s,listensockaddr,socklen) < 0) {
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
      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) {
    start_reading = 1;

Nick Mathewson's avatar
Nick Mathewson committed
896
    /* For now only control ports can be Unix domain sockets
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
     * 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;
    }

914
    if (bind(s, listensockaddr, (socklen_t)sizeof(struct sockaddr_un)) == -1) {
915
916
917
918
      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
919

920
    if (listen(s,SOMAXCONN) < 0) {
921
      log_warn(LD_NET, "Could not listen on %s: %s", address,
922
923
924
925
               tor_socket_strerror(tor_socket_errno(s)));
      tor_close_socket(s);
      goto err;
    }
926
927
928
929
930
#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
931
932
  }

933
  set_socket_nonblocking(s);
Roger Dingledine's avatar
Roger Dingledine committed
934

935
  conn = connection_new(type, listensockaddr->sa_family);
936
  conn->socket_family = listensockaddr->sa_family;
Roger Dingledine's avatar
Roger Dingledine committed
937
  conn->s = s;
938
  conn->address = tor_strdup(address);
939
  conn->port = usePort;
Roger Dingledine's avatar
Roger Dingledine committed
940

941
  if (connection_add(conn) < 0) { /* no space, forget it */
942
    log_warn(LD_NET,"connection_add for listener failed. Giving up.");
Roger Dingledine's avatar
Roger Dingledine committed
943
    connection_free(conn);
944
    goto err;
Roger Dingledine's avatar
Roger Dingledine committed
945
946
  }

Roger Dingledine's avatar
Roger Dingledine committed
947
948
  log_debug(LD_NET,"%s listening on port %u.",
            conn_type_to_string(type), usePort);
Roger Dingledine's avatar
Roger Dingledine committed
949
950

  conn->state = LISTENER_STATE_READY;
951
  if (start_reading) {
952
953
954
955
956
    connection_start_reading(conn);
  } else {
    tor_assert(type == CONN_TYPE_AP_DNS_LISTENER);
    dnsserv_configure_listener(conn);
  }
Roger Dingledine's avatar
Roger Dingledine committed
957

958
  return conn;
959
960

 err:
961
  return NULL;
Roger Dingledine's avatar
Roger Dingledine committed
962
963
}

964
965
966
/** Do basic sanity checking on a newly received socket. Return 0
 * if it looks ok, else return -1. */
static int
967
check_sockaddr(struct sockaddr *sa, int len, int level)
968
969
970
{
  int ok = 1;

971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
  if (sa->sa_family == AF_INET) {
    struct sockaddr_in *sin=(struct sockaddr_in*)sa;
    if (len != sizeof(struct sockaddr_in)) {
      log_fn(level, LD_NET, "Length of address not as expected: %d vs %d",
             len,(int)sizeof(struct sockaddr_in));
      ok = 0;
    }
    if (sin->sin_addr.s_addr == 0 || sin->sin_port == 0) {
      log_fn(level, LD_NET,
             "Address for new connection has address/port equal to zero.");
      ok = 0;
    }
  } else if (sa->sa_family == AF_INET6) {
    struct sockaddr_in6 *sin6=(struct sockaddr_in6*)sa;
    if (len != sizeof(struct sockaddr_in6)) {
      log_fn(level, LD_NET, "Length of address not as expected: %d vs %d",
             len,(int)sizeof(struct sockaddr_in6));
      ok = 0;
    }
    if (tor_mem_is_zero((void*)sin6->sin6_addr.s6_addr, 16) ||
        sin6->sin6_port == 0) {
      log_fn(level, LD_NET,
             "Address for new connection has address/port equal to zero.");
      ok = 0;
    }
  } else {
997
998
999
1000
    ok = 0;
  }
  return ok ? 0 : -1;
}