connection.c 184 KB
Newer Older
1
/* Copyright (c) 2001 Matej Pfajfar.
Roger Dingledine's avatar
Roger Dingledine committed
2
 * Copyright (c) 2001-2004, Roger Dingledine.
3
 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
Nick Mathewson's avatar
Nick Mathewson committed
4
 * Copyright (c) 2007-2019, 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
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
 *
 * Each connection (ideally) represents a TLS connection, a TCP socket, a unix
 * socket, or a UDP socket on which reads and writes can occur.  (But see
 * connection_edge.c for cases where connections can also represent streams
 * that do not have a corresponding socket.)
 *
 * The module implements the abstract type, connection_t.  The subtypes are:
 *  <ul>
 *   <li>listener_connection_t, implemented here in connection.c
 *   <li>dir_connection_t, implemented in directory.c
 *   <li>or_connection_t, implemented in connection_or.c
 *   <li>edge_connection_t, implemented in connection_edge.c, along with
 *      its subtype(s):
 *      <ul><li>entry_connection_t, also implemented in connection_edge.c
 *      </ul>
 *   <li>control_connection_t, implemented in control.c
 *  </ul>
 *
 * The base type implemented in this module is responsible for basic
 * rate limiting, flow control, and marshalling bytes onto and off of the
 * network (either directly or via TLS).
 *
 * Connections are registered with the main loop with connection_add(). As
 * they become able to read or write register the fact with the event main
 * loop by calling connection_watch_events(), connection_start_reading(), or
 * connection_start_writing().  When they no longer want to read or write,
Chelsea H. Komlo's avatar
Chelsea H. Komlo committed
37
 * they call connection_stop_reading() or connection_stop_writing().
38
39
 *
 * To queue data to be written on a connection, call
40
 * connection_buf_add().  When data arrives, the
41
42
43
44
45
46
47
48
49
50
51
52
53
54
 * connection_process_inbuf() callback is invoked, which dispatches to a
 * type-specific function (such as connection_edge_process_inbuf() for
 * example). Connection types that need notice of when data has been written
 * receive notification via connection_flushed_some() and
 * connection_finished_flushing().  These functions all delegate to
 * type-specific implementations.
 *
 * Additionally, beyond the core of connection_t, this module also implements:
 * <ul>
 * <li>Listeners, which wait for incoming sockets and launch connections
 * <li>Outgoing SOCKS proxy support
 * <li>Outgoing HTTP proxy support
 * <li>An out-of-sockets handler for dealing with socket exhaustion
 * </ul>
55
56
 **/

Nick Mathewson's avatar
Nick Mathewson committed
57
#define CONNECTION_PRIVATE
58
59
#include "core/or/or.h"
#include "feature/client/bridges.h"
60
#include "lib/container/buffers.h"
61
#include "lib/tls/buffers_tls.h"
62
63
#include "lib/err/backtrace.h"

64
65
66
67
/*
 * Define this so we get channel internal functions, since we're implementing
 * part of a subclass (channel_tls_t).
 */
68
#define TOR_CHANNEL_INTERNAL_
69
#define CONNECTION_PRIVATE
70
71
72
73
#include "app/config/config.h"
#include "core/mainloop/connection.h"
#include "core/mainloop/mainloop.h"
#include "core/mainloop/netstatus.h"
74
75
76
77
78
79
80
#include "core/or/channel.h"
#include "core/or/channeltls.h"
#include "core/or/circuitbuild.h"
#include "core/or/circuitlist.h"
#include "core/or/circuituse.h"
#include "core/or/connection_edge.h"
#include "core/or/connection_or.h"
81
82
83
84
85
86
87
88
89
#include "core/or/dos.h"
#include "core/or/policies.h"
#include "core/or/reasons.h"
#include "core/or/relay.h"
#include "core/proto/proto_http.h"
#include "core/proto/proto_socks.h"
#include "feature/client/dnsserv.h"
#include "feature/client/entrynodes.h"
#include "feature/client/transports.h"
90
#include "feature/control/control.h"
91
#include "feature/dirauth/authmode.h"
92
#include "feature/dircache/dirserv.h"
93
#include "feature/dircommon/directory.h"
94
95
96
97
#include "feature/hibernate/hibernate.h"
#include "feature/hs/hs_common.h"
#include "feature/hs/hs_ident.h"
#include "feature/nodelist/nodelist.h"
98
99
100
101
#include "feature/nodelist/routerlist.h"
#include "feature/relay/dns.h"
#include "feature/relay/ext_orport.h"
#include "feature/relay/routermode.h"
102
103
104
#include "feature/rend/rendclient.h"
#include "feature/rend/rendcommon.h"
#include "feature/stats/rephist.h"
105
#include "lib/crypt_ops/crypto_util.h"
106
#include "lib/geoip/geoip.h"
107

108
#include "lib/sandbox/sandbox.h"
Nick Mathewson's avatar
Nick Mathewson committed
109
#include "lib/net/buffers_net.h"
110
#include "lib/tls/tortls.h"
111
#include "lib/evloop/compat_libevent.h"
112
#include "lib/compress/compress.h"
Roger Dingledine's avatar
Roger Dingledine committed
113

114
115
116
117
#ifdef HAVE_PWD_H
#include <pwd.h>
#endif

118
119
120
121
122
123
124
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_SYS_STAT_H
#include <sys/stat.h>
#endif

125
126
127
128
129
#ifdef HAVE_SYS_UN_H
#include <sys/socket.h>
#include <sys/un.h>
#endif

130
131
132
133
134
135
136
137
#include "feature/dircommon/dir_connection_st.h"
#include "feature/control/control_connection_st.h"
#include "core/or/entry_connection_st.h"
#include "core/or/listener_connection_st.h"
#include "core/or/or_connection_st.h"
#include "core/or/port_cfg_st.h"
#include "feature/nodelist/routerinfo_st.h"
#include "core/or/socks_request_st.h"
138

rl1987's avatar
rl1987 committed
139
140
141
142
143
144
145
146
147
148
149
150
151
/**
 * On Windows and Linux we cannot reliably bind() a socket to an
 * address and port if: 1) There's already a socket bound to wildcard
 * address (0.0.0.0 or ::) with the same port; 2) We try to bind()
 * to wildcard address and there's another socket bound to a
 * specific address and the same port.
 *
 * To address this problem on these two platforms we implement a
 * routine that:
 * 1) Checks if first attempt to bind() a new socket  failed with
 * EADDRINUSE.
 * 2) If so, it will close the appropriate old listener connection and
 * 3) Attempts bind()'ing the new listener socket again.
rl1987's avatar
rl1987 committed
152
153
154
 *
 * Just to be safe, we are enabling listener rebind code on all platforms,
 * to account for unexpected cases where it may be needed.
rl1987's avatar
rl1987 committed
155
 */
156
157
#define ENABLE_LISTENER_REBIND

158
static connection_t *connection_listener_new(
159
                               const struct sockaddr *listensockaddr,
160
                               socklen_t listensocklen, int type,
161
                               const char *address,
162
163
164
165
166
                               const port_cfg_t *portcfg,
                               int *addr_in_use);
static connection_t *connection_listener_new_for_port(
                               const port_cfg_t *port,
                               int *defer, int *addr_in_use);
167
168
static void connection_init(time_t now, connection_t *conn, int type,
                            int socket_family);
Nick Mathewson's avatar
Nick Mathewson committed
169
static int connection_handle_listener_read(connection_t *conn, int new_type);
170
static int connection_finished_flushing(connection_t *conn);
171
static int connection_flushed_some(connection_t *conn);
172
static int connection_finished_connecting(connection_t *conn);
173
static int connection_reached_eof(connection_t *conn);
174
175
176
static int connection_buf_read_from_socket(connection_t *conn,
                                           ssize_t *max_to_read,
                                           int *socket_error);
177
static int connection_process_inbuf(connection_t *conn, int package_partial);
178
179
static void client_check_address_changed(tor_socket_t sock);
static void set_constrained_socket_buffers(tor_socket_t sock, int size);
180

181
182
183
static const char *connection_proxy_state_to_string(int state);
static int connection_read_https_proxy_response(connection_t *conn);
static void connection_send_socks5_connect(connection_t *conn);
184
static const char *proxy_type_to_string(int proxy_type);
185
static int conn_get_proxy_type(const connection_t *conn);
186
187
const tor_addr_t *conn_get_outbound_address(sa_family_t family,
                  const or_options_t *options, unsigned int conn_type);
188
189
static void reenable_blocked_connection_init(const or_options_t *options);
static void reenable_blocked_connection_schedule(void);
190

191
192
193
/** The last addresses that our network interface seemed to have been
 * binding to.  We use this as one way to detect when our IP changes.
 *
194
 * XXXX+ We should really use the entire list of interfaces here.
195
196
 **/
static tor_addr_t *last_interface_ipv4 = NULL;
197
/* DOCDOC last_interface_ipv6 */
198
199
static tor_addr_t *last_interface_ipv6 = NULL;
/** A list of tor_addr_t for addresses we've used in outgoing connections.
200
 * Used to detect IP address changes. */
201
static smartlist_t *outgoing_addrs = NULL;
202

203
204
#define CASE_ANY_LISTENER_TYPE \
    case CONN_TYPE_OR_LISTENER: \
205
    case CONN_TYPE_EXT_OR_LISTENER: \
206
207
208
209
210
    case CONN_TYPE_AP_LISTENER: \
    case CONN_TYPE_DIR_LISTENER: \
    case CONN_TYPE_CONTROL_LISTENER: \
    case CONN_TYPE_AP_TRANS_LISTENER: \
    case CONN_TYPE_AP_NATD_LISTENER: \
211
212
    case CONN_TYPE_AP_DNS_LISTENER: \
    case CONN_TYPE_AP_HTTP_CONNECT_LISTENER
213

214
215
/**************************************************************/

216
217
218
219
220
221
222
223
224
/** Convert a connection_t* to an listener_connection_t*; assert if the cast
 * is invalid. */
listener_connection_t *
TO_LISTENER_CONN(connection_t *c)
{
  tor_assert(c->magic == LISTENER_CONNECTION_MAGIC);
  return DOWNCAST(listener_connection_t, c);
}

225
226
227
228
229
230
231
232
233
234
235
236
size_t
connection_get_inbuf_len(connection_t *conn)
{
  return conn->inbuf ? buf_datalen(conn->inbuf) : 0;
}

size_t
connection_get_outbuf_len(connection_t *conn)
{
    return conn->outbuf ? buf_datalen(conn->outbuf) : 0;
}

237
238
239
/**
 * Return the human-readable name for the connection type <b>type</b>
 */
240
241
242
243
244
245
246
247
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";
248
    case CONN_TYPE_AP_LISTENER: return "Socks listener";
249
250
251
    case CONN_TYPE_AP_TRANS_LISTENER:
      return "Transparent pf/netfilter listener";
    case CONN_TYPE_AP_NATD_LISTENER: return "Transparent natd listener";
252
    case CONN_TYPE_AP_DNS_LISTENER: return "DNS listener";
253
254
255
    case CONN_TYPE_AP: return "Socks";
    case CONN_TYPE_DIR_LISTENER: return "Directory listener";
    case CONN_TYPE_DIR: return "Directory";
256
257
    case CONN_TYPE_CONTROL_LISTENER: return "Control listener";
    case CONN_TYPE_CONTROL: return "Control";
258
259
    case CONN_TYPE_EXT_OR: return "Extended OR";
    case CONN_TYPE_EXT_OR_LISTENER: return "Extended OR listener";
260
    case CONN_TYPE_AP_HTTP_CONNECT_LISTENER: return "HTTP tunnel listener";
261
    default:
262
      log_warn(LD_BUG, "unknown connection type %d", type);
263
264
265
266
267
      tor_snprintf(buf, sizeof(buf), "unknown [%d]", type);
      return buf;
  }
}

268
269
270
271
/**
 * Return the human-readable name for the connection state <b>state</b>
 * for the connection type <b>type</b>
 */
272
const char *
273
274
conn_state_to_string(int type, int state)
{
275
276
  static char buf[96];
  switch (type) {
277
    CASE_ANY_LISTENER_TYPE:
278
279
280
281
282
283
      if (state == LISTENER_STATE_READY)
        return "ready";
      break;
    case CONN_TYPE_OR:
      switch (state) {
        case OR_CONN_STATE_CONNECTING: return "connect()ing";
284
        case OR_CONN_STATE_PROXY_HANDSHAKING: return "handshaking (proxy)";
285
        case OR_CONN_STATE_TLS_HANDSHAKING: return "handshaking (TLS)";
286
        case OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING:
287
          return "renegotiating (TLS, v2 handshake)";
288
        case OR_CONN_STATE_TLS_SERVER_RENEGOTIATING:
289
290
291
292
293
          return "waiting for renegotiation or V3 handshake";
        case OR_CONN_STATE_OR_HANDSHAKING_V2:
          return "handshaking (Tor, v2 handshake)";
        case OR_CONN_STATE_OR_HANDSHAKING_V3:
          return "handshaking (Tor, v3 handshake)";
294
295
296
        case OR_CONN_STATE_OPEN: return "open";
      }
      break;
297
298
    case CONN_TYPE_EXT_OR:
      switch (state) {
299
300
301
302
303
304
        case EXT_OR_CONN_STATE_AUTH_WAIT_AUTH_TYPE:
          return "waiting for authentication type";
        case EXT_OR_CONN_STATE_AUTH_WAIT_CLIENT_NONCE:
          return "waiting for client nonce";
        case EXT_OR_CONN_STATE_AUTH_WAIT_CLIENT_HASH:
          return "waiting for client hash";
305
306
307
308
        case EXT_OR_CONN_STATE_OPEN: return "open";
        case EXT_OR_CONN_STATE_FLUSHING: return "flushing final OKAY";
      }
      break;
309
310
311
312
313
314
315
316
317
318
    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) {
319
        case AP_CONN_STATE_SOCKS_WAIT: return "waiting for socks info";
320
        case AP_CONN_STATE_NATD_WAIT: return "waiting for natd dest info";
321
322
        case AP_CONN_STATE_RENDDESC_WAIT: return "waiting for rendezvous desc";
        case AP_CONN_STATE_CONTROLLER_WAIT: return "waiting for controller";
323
324
325
        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";
326
327
328
329
330
331
332
        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
333
        case DIR_CONN_STATE_CLIENT_READING: return "client reading";
334
        case DIR_CONN_STATE_CLIENT_FINISHED: return "client finished";
335
336
337
338
339
340
        case DIR_CONN_STATE_SERVER_COMMAND_WAIT: return "waiting for command";
        case DIR_CONN_STATE_SERVER_WRITING: return "writing";
      }
      break;
    case CONN_TYPE_CONTROL:
      switch (state) {
341
342
        case CONTROL_CONN_STATE_OPEN: return "open (protocol v1)";
        case CONTROL_CONN_STATE_NEEDAUTH:
343
          return "waiting for authentication (protocol v1)";
344
345
346
347
      }
      break;
  }

348
  log_warn(LD_BUG, "unknown connection state %d (type %d)", state, type);
349
350
351
352
353
354
  tor_snprintf(buf, sizeof(buf),
               "unknown state [%d] on unknown [%s] connection",
               state, conn_type_to_string(type));
  return buf;
}

355
356
/** Allocate and return a new dir_connection_t, initialized as by
 * connection_init(). */
357
358
359
360
361
362
363
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;
}
364
365

/** Allocate and return a new or_connection_t, initialized as by
Nick Mathewson's avatar
Nick Mathewson committed
366
 * connection_init().
367
368
369
370
371
 *
 * Initialize active_circuit_pqueue.
 *
 * Set active_circuit_pqueue_last_recalibrated to current cell_ewma tick.
 */
372
or_connection_t *
373
or_connection_new(int type, int socket_family)
374
375
376
{
  or_connection_t *or_conn = tor_malloc_zero(sizeof(or_connection_t));
  time_t now = time(NULL);
377
378
  tor_assert(type == CONN_TYPE_OR || type == CONN_TYPE_EXT_OR);
  connection_init(now, TO_CONN(or_conn), type, socket_family);
379

380
  connection_or_set_canonical(or_conn, 0);
381

382
383
384
  if (type == CONN_TYPE_EXT_OR)
    connection_or_set_ext_or_identifier(or_conn);

385
386
  return or_conn;
}
387

388
/** Allocate and return a new entry_connection_t, initialized as by
389
390
391
392
 * connection_init().
 *
 * Allocate space to store the socks_request.
 */
393
394
395
396
397
398
entry_connection_t *
entry_connection_new(int type, int socket_family)
{
  entry_connection_t *entry_conn = tor_malloc_zero(sizeof(entry_connection_t));
  tor_assert(type == CONN_TYPE_AP);
  connection_init(time(NULL), ENTRY_TO_CONN(entry_conn), type, socket_family);
399
  entry_conn->socks_request = socks_request_new();
400
401
402
403
  /* If this is coming from a listener, we'll set it up based on the listener
   * in a little while.  Otherwise, we're doing this as a linked connection
   * of some kind, and we should set it up here based on the socket family */
  if (socket_family == AF_INET)
404
    entry_conn->entry_cfg.ipv4_traffic = 1;
405
  else if (socket_family == AF_INET6)
406
    entry_conn->entry_cfg.ipv6_traffic = 1;
407
408
409
  return entry_conn;
}

410
411
/** Allocate and return a new edge_connection_t, initialized as by
 * connection_init(). */
412
413
414
415
edge_connection_t *
edge_connection_new(int type, int socket_family)
{
  edge_connection_t *edge_conn = tor_malloc_zero(sizeof(edge_connection_t));
416
  tor_assert(type == CONN_TYPE_EXIT);
417
418
419
  connection_init(time(NULL), TO_CONN(edge_conn), type, socket_family);
  return edge_conn;
}
420
421
422

/** Allocate and return a new control_connection_t, initialized as by
 * connection_init(). */
423
424
425
426
427
428
429
430
431
432
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;
}

433
434
435
436
437
438
439
440
441
442
443
/** Allocate and return a new listener_connection_t, initialized as by
 * connection_init(). */
listener_connection_t *
listener_connection_new(int type, int socket_family)
{
  listener_connection_t *listener_conn =
    tor_malloc_zero(sizeof(listener_connection_t));
  connection_init(time(NULL), TO_CONN(listener_conn), type, socket_family);
  return listener_conn;
}

444
445
446
/** 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. */
447
448
449
450
451
connection_t *
connection_new(int type, int socket_family)
{
  switch (type) {
    case CONN_TYPE_OR:
452
453
    case CONN_TYPE_EXT_OR:
      return TO_CONN(or_connection_new(type, socket_family));
454
455
456
457

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

458
459
460
    case CONN_TYPE_AP:
      return ENTRY_TO_CONN(entry_connection_new(type, socket_family));

461
462
463
464
465
466
    case CONN_TYPE_DIR:
      return TO_CONN(dir_connection_new(socket_family));

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

467
468
469
    CASE_ANY_LISTENER_TYPE:
      return TO_CONN(listener_connection_new(type, socket_family));

470
471
472
473
474
475
476
477
478
479
    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).
480
 *
481
482
 * Set conn-\>magic to the correct value.
 *
483
 * Set conn-\>type to <b>type</b>. Set conn-\>s and conn-\>conn_array_index to
484
485
486
487
 * -1 to signify they are not yet assigned.
 *
 * Initialize conn's timestamps to now.
 */
488
489
static void
connection_init(time_t now, connection_t *conn, int type, int socket_family)
490
{
491
492
  static uint64_t n_connections_allocated = 1;

493
494
  switch (type) {
    case CONN_TYPE_OR:
495
    case CONN_TYPE_EXT_OR:
496
      conn->magic = OR_CONNECTION_MAGIC;
497
498
      break;
    case CONN_TYPE_EXIT:
499
      conn->magic = EDGE_CONNECTION_MAGIC;
500
501
      break;
    case CONN_TYPE_AP:
502
      conn->magic = ENTRY_CONNECTION_MAGIC;
503
504
      break;
    case CONN_TYPE_DIR:
505
      conn->magic = DIR_CONNECTION_MAGIC;
506
507
      break;
    case CONN_TYPE_CONTROL:
508
      conn->magic = CONTROL_CONNECTION_MAGIC;
509
      break;
510
511
    CASE_ANY_LISTENER_TYPE:
      conn->magic = LISTENER_CONNECTION_MAGIC;
512
      break;
513
    default:
514
      conn->magic = BASE_CONNECTION_MAGIC;
515
516
517
      break;
  }

518
  conn->s = TOR_INVALID_SOCKET; /* give it a default of 'not used' */
519
  conn->conn_array_index = -1; /* also default to 'not used' */
520
  conn->global_identifier = n_connections_allocated++;
Roger Dingledine's avatar
Roger Dingledine committed
521
522

  conn->type = type;
523
  conn->socket_family = socket_family;
524
525
  if (!connection_is_listener(conn)) {
    /* listeners never use their buf */
526
527
528
    conn->inbuf = buf_new();
    conn->outbuf = buf_new();
  }
529

530
  conn->timestamp_created = now;
531
532
  conn->timestamp_last_read_allowed = now;
  conn->timestamp_last_write_allowed = now;
Roger Dingledine's avatar
Roger Dingledine committed
533
534
}

Roger Dingledine's avatar
Roger Dingledine committed
535
/** Create a link between <b>conn_a</b> and <b>conn_b</b>. */
536
537
538
void
connection_link_connections(connection_t *conn_a, connection_t *conn_b)
{
539
540
  tor_assert(! SOCKET_OK(conn_a->s));
  tor_assert(! SOCKET_OK(conn_b->s));
541
542
543
544
545
546
547

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

548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
/** Return true iff the provided connection listener type supports AF_UNIX
 * sockets. */
int
conn_listener_type_supports_af_unix(int type)
{
  /* For now only control ports or SOCKS ports can be Unix domain sockets
   * and listeners at the same time */
  switch (type) {
    case CONN_TYPE_CONTROL_LISTENER:
    case CONN_TYPE_AP_LISTENER:
      return 1;
    default:
      return 0;
  }
}

564
565
566
/** 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.
567
 */
Nick Mathewson's avatar
Nick Mathewson committed
568
STATIC void
569
connection_free_minimal(connection_t *conn)
570
{
571
  void *mem;
572
  size_t memlen;
573
574
575
  if (!conn)
    return;

576
577
  switch (conn->type) {
    case CONN_TYPE_OR:
578
    case CONN_TYPE_EXT_OR:
579
580
      tor_assert(conn->magic == OR_CONNECTION_MAGIC);
      mem = TO_OR_CONN(conn);
581
      memlen = sizeof(or_connection_t);
582
583
      break;
    case CONN_TYPE_AP:
584
585
586
587
      tor_assert(conn->magic == ENTRY_CONNECTION_MAGIC);
      mem = TO_ENTRY_CONN(conn);
      memlen = sizeof(entry_connection_t);
      break;
588
589
590
    case CONN_TYPE_EXIT:
      tor_assert(conn->magic == EDGE_CONNECTION_MAGIC);
      mem = TO_EDGE_CONN(conn);
591
      memlen = sizeof(edge_connection_t);
592
593
594
595
      break;
    case CONN_TYPE_DIR:
      tor_assert(conn->magic == DIR_CONNECTION_MAGIC);
      mem = TO_DIR_CONN(conn);
596
      memlen = sizeof(dir_connection_t);
597
598
599
600
      break;
    case CONN_TYPE_CONTROL:
      tor_assert(conn->magic == CONTROL_CONNECTION_MAGIC);
      mem = TO_CONTROL_CONN(conn);
601
      memlen = sizeof(control_connection_t);
602
      break;
603
604
605
606
607
    CASE_ANY_LISTENER_TYPE:
      tor_assert(conn->magic == LISTENER_CONNECTION_MAGIC);
      mem = TO_LISTENER_CONN(conn);
      memlen = sizeof(listener_connection_t);
      break;
608
609
610
    default:
      tor_assert(conn->magic == BASE_CONNECTION_MAGIC);
      mem = conn;
611
      memlen = sizeof(connection_t);
612
613
      break;
  }
Roger Dingledine's avatar
Roger Dingledine committed
614

615
  if (conn->linked) {
616
617
618
619
    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),
620
621
             (int)connection_get_inbuf_len(conn),
             (int)connection_get_outbuf_len(conn));
622
623
  }

624
  if (!connection_is_listener(conn)) {
625
626
    buf_free(conn->inbuf);
    buf_free(conn->outbuf);
627
  } else {
628
    if (conn->socket_family == AF_UNIX) {
629
      /* For now only control and SOCKS ports can be Unix domain sockets
630
       * and listeners at the same time */
631
      tor_assert(conn_listener_type_supports_af_unix(conn->type));
632
633
634
635
636
637

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

640
  tor_free(conn->address);
Roger Dingledine's avatar
Roger Dingledine committed
641

642
  if (connection_speaks_cells(conn)) {
643
    or_connection_t *or_conn = TO_OR_CONN(conn);
644
645
646
647
648
649
650
651
    if (or_conn->tls) {
      if (! SOCKET_OK(conn->s)) {
        /* The socket has been closed by somebody else; we must tell the
         * TLS object not to close it. */
        tor_tls_release_socket(or_conn->tls);
      } else {
        /* The tor_tls_free() call below will close the socket; we must tell
         * the code below not to close it a second time. */
652
        tor_release_socket_ownership(conn->s);
653
654
655
656
657
        conn->s = TOR_INVALID_SOCKET;
      }
      tor_tls_free(or_conn->tls);
      or_conn->tls = NULL;
    }
658
659
    or_handshake_state_free(or_conn->handshake_state);
    or_conn->handshake_state = NULL;
660
    tor_free(or_conn->nickname);
661
662
    if (or_conn->chan) {
      /* Owww, this shouldn't happen, but... */
663
664
      channel_t *base_chan = TLS_CHAN_TO_BASE(or_conn->chan);
      tor_assert(base_chan);
665
666
      log_info(LD_CHANNEL,
               "Freeing orconn at %p, saw channel %p with ID "
667
               "%"PRIu64 " left un-NULLed",
668
669
670
671
               or_conn, base_chan,
               base_chan->global_identifier);
      if (!CHANNEL_FINISHED(base_chan)) {
        channel_close_for_error(base_chan);
672
673
674
675
676
      }

      or_conn->chan->conn = NULL;
      or_conn->chan = NULL;
    }
677
  }
678
679
680
681
682
683
684
  if (conn->type == CONN_TYPE_AP) {
    entry_connection_t *entry_conn = TO_ENTRY_CONN(conn);
    tor_free(entry_conn->chosen_exit_name);
    tor_free(entry_conn->original_dest_address);
    if (entry_conn->socks_request)
      socks_request_free(entry_conn->socks_request);
    if (entry_conn->pending_optimistic_data) {
685
      buf_free(entry_conn->pending_optimistic_data);
686
    }
687
    if (entry_conn->sending_optimistic_data) {
688
      buf_free(entry_conn->sending_optimistic_data);
689
    }
690
691
692
  }
  if (CONN_IS_EDGE(conn)) {
    rend_data_free(TO_EDGE_CONN(conn)->rend_data);
693
    hs_ident_edge_conn_free(TO_EDGE_CONN(conn)->hs_ident);
694
695
696
  }
  if (conn->type == CONN_TYPE_CONTROL) {
    control_connection_t *control_conn = TO_CONTROL_CONN(conn);
697
    tor_free(control_conn->safecookie_client_hash);
698
    tor_free(control_conn->incoming_cmd);
699
700
701
702
703
704
705
    if (control_conn->ephemeral_onion_services) {
      SMARTLIST_FOREACH(control_conn->ephemeral_onion_services, char *, cp, {
        memwipe(cp, 0, strlen(cp));
        tor_free(cp);
      });
      smartlist_free(control_conn->ephemeral_onion_services);
    }
Roger Dingledine's avatar
Roger Dingledine committed
706
707
  }

708
709
710
711
  /* Probably already freed by connection_free. */
  tor_event_free(conn->read_event);
  tor_event_free(conn->write_event);
  conn->read_event = conn->write_event = NULL;
712
713
714
715

  if (conn->type == CONN_TYPE_DIR) {
    dir_connection_t *dir_conn = TO_DIR_CONN(conn);
    tor_free(dir_conn->requested_resource);
716

717
    tor_compress_free(dir_conn->compress_state);
718
719
720
721
    if (dir_conn->spool) {
      SMARTLIST_FOREACH(dir_conn->spool, spooled_resource_t *, spooled,
                        spooled_resource_free(spooled));
      smartlist_free(dir_conn->spool);
722
    }
723
724

    rend_data_free(dir_conn->rend_data);
725
    hs_ident_dir_conn_free(dir_conn->hs_ident);
726
727
    if (dir_conn->guard_state) {
      /* Cancel before freeing, if it's still there. */
728
      entry_guard_cancel(&dir_conn->guard_state);
729
    }
730
    circuit_guard_state_free(dir_conn->guard_state);
731
  }
732

733
  if (SOCKET_OK(conn->s)) {
734
735
736
    log_debug(LD_NET,"closing fd %d.",(int)conn->s);
    tor_close_socket(conn->s);
    conn->s = TOR_INVALID_SOCKET;
737
738
  }

739
  if (conn->type == CONN_TYPE_OR &&
740
      !tor_digest_is_zero(TO_OR_CONN(conn)->identity_digest)) {
Roger Dingledine's avatar
Roger Dingledine committed
741
    log_warn(LD_BUG, "called on OR conn with non-zeroed identity_digest");
742
    connection_or_clear_identity(TO_OR_CONN(conn));
743
  }
744
  if (conn->type == CONN_TYPE_OR || conn->type == CONN_TYPE_EXT_OR) {
745
    connection_or_remove_from_ext_or_id_map(TO_OR_CONN(conn));
746
    tor_free(TO_OR_CONN(conn)->ext_or_conn_id);
747
    tor_free(TO_OR_CONN(conn)->ext_or_auth_correct_client_hash);
748
    tor_free(TO_OR_CONN(conn)->ext_or_transport);
749
  }
750

751
  memwipe(mem, 0xCC, memlen); /* poison memory */
752
  tor_free(mem);
Roger Dingledine's avatar
Roger Dingledine committed
753
754
}

755
756
/** Make sure <b>conn</b> isn't in any of the global conn lists; then free it.
 */
757
MOCK_IMPL(void,
758
connection_free_,(connection_t *conn))
759
{
760
761
  if (!conn)
    return;
762
763
  tor_assert(!connection_is_on_closeable_list(conn));
  tor_assert(!connection_in_array(conn));
764
  if (BUG(conn->linked_conn)) {
765
766
767
768
769
770
    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;
  }
771
  if (connection_speaks_cells(conn)) {
772
    if (!tor_digest_is_zero(TO_OR_CONN(conn)->identity_digest)) {
773
      connection_or_clear_identity(TO_OR_CONN(conn));
774
    }
775
  }
776
  if (conn->type == CONN_TYPE_CONTROL) {
777
    connection_control_closed(TO_CONTROL_CONN(conn));
778
  }
779
780
781
782
783
784
#if 1
  /* DEBUGGING */
  if (conn->type == CONN_TYPE_AP) {
    connection_ap_warn_and_unmark_if_pending_circ(TO_ENTRY_CONN(conn),
                                                  "connection_free");
  }
785
#endif /* 1 */
786
787
788
789
790
791
792

  /* Notify the circuit creation DoS mitigation subsystem that an OR client
   * connection has been closed. And only do that if we track it. */
  if (conn->type == CONN_TYPE_OR) {
    dos_close_client_conn(TO_OR_CONN(conn));
  }

793
  connection_unregister_events(conn);
794
  connection_free_minimal(conn);
795
796
}

797
798
799
/**
 * Called when we're about to finally unlink and free a connection:
 * perform necessary accounting and cleanup
800
801
802
803
804
805
806
 *   - 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.
807
 *   - OR and edge connections need to be unlinked from circuits.
808
 */
809
810
void
connection_about_to_close_connection(connection_t *conn)
811
{
812
  tor_assert(conn->marked_for_close);
813

814
  switch (conn->type) {
815
    case CONN_TYPE_DIR:
816
      connection_dir_about_to_close(TO_DIR_CONN(conn));
817
      break;
818
    case CONN_TYPE_OR:
819
    case CONN_TYPE_EXT_OR:
820
      connection_or_about_to_close(TO_OR_CONN(conn));
821
      break;
822
    case CONN_TYPE_AP:
823
      connection_ap_about_to_close(TO_ENTRY_CONN(conn));
824
      break;
825
    case CONN_TYPE_EXIT:
826
      connection_exit_about_to_close(TO_EDGE_CONN(conn));
827
      break;
828
  }
829
830
}

Roger Dingledine's avatar
Roger Dingledine committed
831
832
/** Return true iff connection_close_immediate() has been called on this
 * connection. */
833
#define CONN_IS_CLOSED(c) \
834
  ((c)->linked ? ((c)->linked_conn_is_closed) : (! SOCKET_OK(c->s)))
835

836
837
838
/** 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().
839
 */
840
841
void
connection_close_immediate(connection_t *conn)
842
843
{
  assert_connection_ok(conn,0);
844
  if (CONN_IS_CLOSED(conn)) {
845
    log_err(LD_BUG,"Attempt to close already-closed connection.");
846
    tor_fragile_assert();
847
848
    return;
  }
849
  if (conn->outbuf_flushlen) {
Roger Dingledine's avatar
Roger Dingledine committed
850
    log_info(LD_NET,"fd %d, type %s, state %s, %d bytes on outbuf.",
851
             (int)conn->s, conn_type_to_string(conn->type),
Roger Dingledine's avatar
Roger Dingledine committed
852
853
             conn_state_to_string(conn->type, conn->state),
             (int)conn->outbuf_flushlen);
854
  }
855

856
  connection_unregister_events(conn);
857

858
  /* Prevent the event from getting unblocked. */
859
860
  conn->read_blocked_on_bw = 0;
  conn->write_blocked_on_bw = 0;
861

862
863
864
  if (SOCKET_OK(conn->s))
    tor_close_socket(conn->s);
  conn->s = TOR_INVALID_SOCKET;
865
866
  if (conn->linked)
    conn->linked_conn_is_closed = 1;
867
  if (conn->outbuf)
868
    buf_clear(conn->outbuf);
869
  conn->outbuf_flushlen = 0;
870
871
}

872
/** Mark <b>conn</b> to be closed next time we loop through
873
 * conn_close_if_marked() in main.c. */
874
void
875
connection_mark_for_close_(connection_t *conn, int line, const char *file)
876
877
{
  assert_connection_ok(conn,0);
878
  tor_assert(line);
879
  tor_assert(line < 1<<16); /* marked_for_close can only fit a uint16_t. */
880
  tor_assert(file);
881

882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
  if (conn->type == CONN_TYPE_OR) {
    /*
     * An or_connection should have been closed through one of the channel-
     * aware functions in connection_or.c.  We'll assume this is an error
     * close and do that, and log a bug warning.
     */
    log_warn(LD_CHANNEL | LD_BUG,
             "Something tried to close an or_connection_t without going "
             "through channels at %s:%d",
             file, line);
    connection_or_close_for_error(TO_OR_CONN(conn), 0);
  } else {
    /* Pass it down to the real function */
    connection_mark_for_close_internal_(conn, line, file);
  }
}

/** Mark <b>conn</b> to be closed next time we loop through
900
901
902
903
904
905
 * conn_close_if_marked() in main.c.
 *
 * This _internal version bypasses the CONN_TYPE_OR checks; this should be
 * called when you either are sure that if this is an or_connection_t the
 * controlling channel has been notified (e.g. with
 * connection_or_notify_error()), or you actually are the
906
 * connection_or_close_for_error() or connection_or_close_normally() function.
907
908
909
910
911
912
 * For all other cases, use connection_mark_and_flush() which checks for
 * or_connection_t properly, instead.  See below.
 *
 * We want to keep this function simple and quick, since it can be called from
 * quite deep in the call chain, and hence it should avoid having side-effects
 * that interfere with its callers view of the connection.
913
 */
914
915
916
MOCK_IMPL(void,
connection_mark_for_close_internal_, (connection_t *conn,
                                      int line, const char *file))
917
918
919
920
921
922
{
  assert_connection_ok(conn,0);
  tor_assert(line);
  tor_assert(line < 1<<16); /* marked_for_close can only fit a uint16_t. */
  tor_assert(file);

923
  if (conn->marked_for_close) {
924
    log_warn(LD_BUG,"Duplicate call to connection_mark_for_close at %s:%d"
925
926
        " (first at %s:%d)", file, line, conn->marked_for_close_file,
        conn->marked_for_close);
927
    tor_fragile_assert();
928
    return;
929
930
  }

931
932
933
934
935
936
  if (conn->type == CONN_TYPE_OR) {
    /*
     * Bad news if this happens without telling the controlling channel; do
     * this so we can find things that call this wrongly when the asserts hit.
     */
    log_debug(LD_CHANNEL,
937
938
              "Calling connection_mark_for_close_internal_() on an OR conn "
              "at %s:%d",
939
940
941
              file, line);
  }

942
943
  conn->marked_for_close = line;
  conn->marked_for_close_file = file;
944
  add_connection_to_closeable_list(conn);
945
946
947
948

  /* 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 */
949
  conn->timestamp_last_write_allowed = time(NULL);
950
951
}

952
953
954
955
956
/** 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.
 */
957
958
void
connection_expire_held_open(void)
959
960
{
  time_t now;
961
  smartlist_t *conns = get_connection_array();
962
963
964

  now = time(NULL);

965
  SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
966
967
968
    /* If we've been holding the connection open, but we haven't written
     * for 15 seconds...
     */
969
    if (conn->hold_open_until_flushed) {
Roger Dingledine's avatar
Roger Dingledine committed
970
      tor_assert(conn->marked_for_close);
971
      if (now - conn->timestamp_last_write_allowed >= 15) {
Roger Dingledine's avatar
Roger Dingledine committed
972
973
        int severity;
        if (conn->type == CONN_TYPE_EXIT ||
974
975
            (conn->type == CONN_TYPE_DIR &&
             conn->purpose == DIR_PURPOSE_SERVER))
Roger Dingledine's avatar
Roger Dingledine committed
976
977
978
          severity = LOG_INFO;
        else
          severity = LOG_NOTICE;
979
        log_fn(severity, LD_NET,
980
981
               "Giving up on marked_for_close conn that's been flushing "
               "for 15s (fd %d, type %s, state %s).",
982
               (int)conn->s, conn_type_to_string(conn->type),
983
               conn_state_to_string(conn->type, conn->state));
984
985
        conn->hold_open_until_flushed = 0;
      }
986
    }
987
  } SMARTLIST_FOREACH_END(conn);
988
989
}

990
#if defined(HAVE_SYS_UN_H) || defined(RUNNING_DOXYGEN)
991
/** Create an AF_UNIX listenaddr struct.
Nick Mathewson's avatar
Nick Mathewson committed
992
 * <b>listenaddress</b> provides the path to the Unix socket.
993
994
995
996
997
998
 *
 * 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
999
 * If not NULL <b>readable_address</b> will contain a copy of the path part of
1000
 * <b>listenaddress</b>.
For faster browsing, not all history is shown. View entire blame