main.c 137 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-2017, The Tor Project, Inc. */
5
/* See LICENSE for licensing information */
Roger Dingledine's avatar
Roger Dingledine committed
6

Roger Dingledine's avatar
Roger Dingledine committed
7
8
/**
 * \file main.c
9
10
 * \brief Toplevel module. Handles signals, multiplexes between
 * connections, implements main loop, and drives scheduled events.
Nick Mathewson's avatar
Nick Mathewson committed
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
37
38
39
40
41
42
43
44
45
46
 *
 * For the main loop itself; see run_main_loop_once().  It invokes the rest of
 * Tor mostly through Libevent callbacks.  Libevent callbacks can happen when
 * a timer elapses, a signal is received, a socket is ready to read or write,
 * or an event is manually activated.
 *
 * Most events in Tor are driven from these callbacks:
 *  <ul>
 *   <li>conn_read_callback() and conn_write_callback() here, which are
 *     invoked when a socket is ready to read or write respectively.
 *   <li>signal_callback(), which handles incoming signals.
 *  </ul>
 * Other events are used for specific purposes, or for building more complex
 * control structures.  If you search for usage of tor_libevent_new(), you
 * will find all the events that we construct in Tor.
 *
 * Tor has numerous housekeeping operations that need to happen
 * regularly. They are handled in different ways:
 * <ul>
 *   <li>The most frequent operations are handled after every read or write
 *    event, at the end of connection_handle_read() and
 *    connection_handle_write().
 *
 *   <li>The next most frequent operations happen after each invocation of the
 *     main loop, in run_main_loop_once().
 *
 *   <li>Once per second, we run all of the operations listed in
 *     second_elapsed_callback(), and in its child, run_scheduled_events().
 *
 *   <li>Once-a-second operations are handled in second_elapsed_callback().
 *
 *   <li>More infrequent operations take place based on the periodic event
 *     driver in periodic.c .  These are stored in the periodic_events[]
 *     table.
 * </ul>
 *
Roger Dingledine's avatar
Roger Dingledine committed
47
 **/
48

49
#define MAIN_PRIVATE
Roger Dingledine's avatar
Roger Dingledine committed
50
#include "or.h"
51
#include "addressmap.h"
Nick Mathewson's avatar
Nick Mathewson committed
52
#include "backtrace.h"
53
#include "bridges.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
54
#include "buffers.h"
55
#include "buffers_tls.h"
56
57
#include "channel.h"
#include "channeltls.h"
58
#include "channelpadding.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
59
#include "circuitbuild.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
60
#include "circuitlist.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
61
#include "circuituse.h"
62
#include "circuitmux_ewma.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
63
#include "command.h"
64
#include "compress.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
65
#include "config.h"
66
#include "confparse.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
67
#include "connection.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
68
#include "connection_edge.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
69
#include "connection_or.h"
70
#include "consdiffmgr.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
71
#include "control.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
72
#include "cpuworker.h"
73
#include "crypto_s2k.h"
74
#include "crypto_rand.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
75
#include "directory.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
76
#include "dirserv.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
77
#include "dns.h"
78
#include "dnsserv.h"
79
#include "dos.h"
80
#include "entrynodes.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
81
#include "geoip.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
82
#include "hibernate.h"
83
#include "hs_cache.h"
84
#include "hs_circuitmap.h"
85
#include "hs_client.h"
86
#include "keypin.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
87
#include "main.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
88
#include "microdesc.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
89
#include "networkstatus.h"
90
#include "nodelist.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
91
#include "ntmain.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
92
#include "onion.h"
93
#include "periodic.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
94
#include "policies.h"
95
#include "protover.h"
96
#include "transports.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
97
#include "relay.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
98
#include "rendclient.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
99
#include "rendcommon.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
100
#include "rendservice.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
101
#include "rephist.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
102
#include "router.h"
103
#include "routerkeys.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
104
#include "routerlist.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
105
#include "routerparse.h"
106
#include "scheduler.h"
107
#include "statefile.h"
108
#include "status.h"
109
110
#include "tor_api.h"
#include "tor_api_internal.h"
111
#include "util_process.h"
112
#include "ext_orport.h"
113
114
115
#ifdef USE_DMALLOC
#include <dmalloc.h>
#endif
116
#include "memarea.h"
117
#include "sandbox.h"
118

119
120
#include <event2/event.h>

121
#include "dirauth/dirvote.h"
122
123
#include "dirauth/mode.h"
#include "dirauth/shared_random.h"
124

125
#ifdef HAVE_SYSTEMD
126
127
128
129
130
#   if defined(__COVERITY__) && !defined(__INCLUDE_LEVEL__)
/* Systemd's use of gcc's __INCLUDE_LEVEL__ extension macro appears to confuse
 * Coverity. Here's a kludge to unconfuse it.
 */
#   define __INCLUDE_LEVEL__ 2
131
#endif /* defined(__COVERITY__) && !defined(__INCLUDE_LEVEL__) */
132
#include <systemd/sd-daemon.h>
133
#endif /* defined(HAVE_SYSTEMD) */
134

135
void evdns_shutdown(int);
Roger Dingledine's avatar
Roger Dingledine committed
136

137
#ifdef HAVE_RUST
138
139
// helper function defined in Rust to output a log message indicating if tor is
// running with Rust enabled. See src/rust/tor_util
140
void rust_log_welcome_string(void);
141
#endif
142

143
/********* PROTOTYPES **********/
Roger Dingledine's avatar
Roger Dingledine committed
144

145
static void dumpmemusage(int severity);
146
static void dumpstats(int severity); /* log stats */
147
148
static void conn_read_callback(evutil_socket_t fd, short event, void *_conn);
static void conn_write_callback(evutil_socket_t fd, short event, void *_conn);
149
static void second_elapsed_callback(periodic_timer_t *timer, void *args);
150
static int conn_close_if_marked(int i);
151
static void connection_start_reading_from_linked_conn(connection_t *conn);
152
static int connection_should_read_from_linked_conn(connection_t *conn);
153
static int run_main_loop_until_done(void);
154
static void process_signal(int sig);
155
156
static void shutdown_did_not_work_callback(evutil_socket_t fd, short event,
                                           void *arg) ATTR_NORETURN;
Roger Dingledine's avatar
Roger Dingledine committed
157

Roger Dingledine's avatar
Roger Dingledine committed
158
/********* START VARIABLES **********/
159
160

/* Token bucket for all traffic. */
161
token_bucket_rw_t global_bucket;
162
163

/* Token bucket for relayed traffic. */
164
token_bucket_rw_t global_relayed_bucket;
165

166
/* XXX we might want to keep stats about global_relayed_*_bucket too. Or not.*/
167
/** How many bytes have we read since we started the process? */
168
static uint64_t stats_n_bytes_read = 0;
169
/** How many bytes have we written since we started the process? */
170
static uint64_t stats_n_bytes_written = 0;
171
/** What time did this process start up? */
172
time_t time_of_process_start = 0;
Roger Dingledine's avatar
Roger Dingledine committed
173
/** How many seconds have we been running? */
174
static long stats_n_seconds_working = 0;
Alexander Færøy's avatar
Alexander Færøy committed
175
176
177
178
179
180
/** How many times have we returned from the main loop successfully? */
static uint64_t stats_n_main_loop_successes = 0;
/** How many times have we received an error from the main loop? */
static uint64_t stats_n_main_loop_errors = 0;
/** How many times have we returned from the main loop with no events. */
static uint64_t stats_n_main_loop_idle = 0;
181
182
183
184
185
186
187

/** How often will we honor SIGNEWNYM requests? */
#define MAX_SIGNEWNYM_RATE 10
/** When did we last process a SIGNEWNYM request? */
static time_t time_of_last_signewnym = 0;
/** Is there a signewnym request we're currently waiting to handle? */
static int signewnym_is_pending = 0;
188
189
/** Mainloop event for the deferred signewnym call. */
static mainloop_event_t *handle_deferred_signewnym_ev = NULL;
190
191
/** How many times have we called newnym? */
static unsigned newnym_epoch = 0;
192

193
/** Smartlist of all open connections. */
194
STATIC smartlist_t *connection_array = NULL;
195
196
/** List of connections that have been marked for close and need to be freed
 * and removed from connection_array. */
197
static smartlist_t *closeable_connection_lst = NULL;
198
199
/** List of linked connections that are currently reading data into their
 * inbuf from their partner's outbuf. */
200
static smartlist_t *active_linked_connection_lst = NULL;
201
202
203
/** Flag: Set to true iff we entered the current libevent main loop via
 * <b>loop_once</b>. If so, there's no need to trigger a loopexit in order
 * to handle linked connections. */
204
static int called_loop_once = 0;
205
206
207
208
209
210
211
212
/** Flag: if true, it's time to shut down, so the main loop should exit as
 * soon as possible.
 */
static int main_loop_should_exit = 0;
/** The return value that the main loop should yield when it exits, if
 * main_loop_should_exit is true.
 */
static int main_loop_exit_value = 0;
Roger Dingledine's avatar
Roger Dingledine committed
213

Roger Dingledine's avatar
Roger Dingledine committed
214
/** We set this to 1 when we've opened a circuit, so we can print a log
215
216
217
218
219
 * entry to inform the user that Tor is working.  We set it to 0 when
 * we think the fact that we once opened a circuit doesn't mean we can do so
 * any longer (a big time jump happened, when we notice our directory is
 * heinously out-of-date, etc.
 */
220
static int can_complete_circuits = 0;
221

222
223
224
225
226
227
/** How often do we check for router descriptors that we should download
 * when we have too little directory info? */
#define GREEDY_DESCRIPTOR_RETRY_INTERVAL (10)
/** How often do we check for router descriptors that we should download
 * when we have enough directory info? */
#define LAZY_DESCRIPTOR_RETRY_INTERVAL (60)
228

229
230
231
232
233
234
/** Decides our behavior when no logs are configured/before any
 * logs have been configured.  For 0, we log notice to stdout as normal.
 * For 1, we log warnings only.  For 2, we log nothing.
 */
int quiet_level = 0;

Roger Dingledine's avatar
Roger Dingledine committed
235
236
/********* END VARIABLES ************/

Roger Dingledine's avatar
Roger Dingledine committed
237
/****************************************************************************
238
239
240
241
242
 *
 * This section contains accessors and other methods on the connection_array
 * variables (which are global within this file and unavailable outside it).
 *
 ****************************************************************************/
Roger Dingledine's avatar
Roger Dingledine committed
243

244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
/** Return 1 if we have successfully built a circuit, and nothing has changed
 * to make us think that maybe we can't.
 */
int
have_completed_a_circuit(void)
{
  return can_complete_circuits;
}

/** Note that we have successfully built a circuit, so that reachability
 * testing and introduction points and so on may be attempted. */
void
note_that_we_completed_a_circuit(void)
{
  can_complete_circuits = 1;
}

/** Note that something has happened (like a clock jump, or DisableNetwork) to
 * make us think that maybe we can't complete circuits. */
void
note_that_we_maybe_cant_complete_circuits(void)
{
  can_complete_circuits = 0;
}

Roger Dingledine's avatar
Roger Dingledine committed
269
/** Add <b>conn</b> to the array of connections that we can poll on.  The
270
271
272
 * connection's socket must be set; the connection starts out
 * non-reading and non-writing.
 */
273
int
274
connection_add_impl(connection_t *conn, int is_connecting)
275
{
Roger Dingledine's avatar
Roger Dingledine committed
276
  tor_assert(conn);
277
  tor_assert(SOCKET_OK(conn->s) ||
278
279
             conn->linked ||
             (conn->type == CONN_TYPE_AP &&
280
              TO_EDGE_CONN(conn)->is_dns_request));
Roger Dingledine's avatar
Roger Dingledine committed
281

282
  tor_assert(conn->conn_array_index == -1); /* can only connection_add once */
283
284
  conn->conn_array_index = smartlist_len(connection_array);
  smartlist_add(connection_array, conn);
Roger Dingledine's avatar
Roger Dingledine committed
285

286
  (void) is_connecting;
287

288
  if (SOCKET_OK(conn->s) || conn->linked) {
289
290
291
292
    conn->read_event = tor_event_new(tor_libevent_get_base(),
         conn->s, EV_READ|EV_PERSIST, conn_read_callback, conn);
    conn->write_event = tor_event_new(tor_libevent_get_base(),
         conn->s, EV_WRITE|EV_PERSIST, conn_write_callback, conn);
293
    /* XXXX CHECK FOR NULL RETURN! */
294
  }
Roger Dingledine's avatar
Roger Dingledine committed
295

Roger Dingledine's avatar
Roger Dingledine committed
296
  log_debug(LD_NET,"new conn type %s, socket %d, address %s, n_conns %d.",
297
            conn_type_to_string(conn->type), (int)conn->s, conn->address,
298
            smartlist_len(connection_array));
Roger Dingledine's avatar
Roger Dingledine committed
299
300
301
302

  return 0;
}

303
304
305
306
307
308
/** Tell libevent that we don't care about <b>conn</b> any more. */
void
connection_unregister_events(connection_t *conn)
{
  if (conn->read_event) {
    if (event_del(conn->read_event))
309
      log_warn(LD_BUG, "Error removing read event for %d", (int)conn->s);
310
311
312
313
    tor_free(conn->read_event);
  }
  if (conn->write_event) {
    if (event_del(conn->write_event))
314
      log_warn(LD_BUG, "Error removing write event for %d", (int)conn->s);
315
316
    tor_free(conn->write_event);
  }
317
  if (conn->type == CONN_TYPE_AP_DNS_LISTENER) {
318
319
320
321
    dnsserv_close_listener(conn);
  }
}

Roger Dingledine's avatar
Roger Dingledine committed
322
/** Remove the connection from the global list, and remove the
Nick Mathewson's avatar
Nick Mathewson committed
323
324
325
 * corresponding poll entry.  Calling this function will shift the last
 * connection (if any) into the position occupied by conn.
 */
326
327
328
int
connection_remove(connection_t *conn)
{
Roger Dingledine's avatar
Roger Dingledine committed
329
  int current_index;
330
  connection_t *tmp;
Roger Dingledine's avatar
Roger Dingledine committed
331

Roger Dingledine's avatar
Roger Dingledine committed
332
  tor_assert(conn);
Roger Dingledine's avatar
Roger Dingledine committed
333

334
  log_debug(LD_NET,"removing socket %d (type %s), n_conns now %d",
335
            (int)conn->s, conn_type_to_string(conn->type),
336
            smartlist_len(connection_array));
Roger Dingledine's avatar
Roger Dingledine committed
337

338
  if (conn->type == CONN_TYPE_AP && conn->socket_family == AF_UNIX) {
339
    log_info(LD_NET, "Closing SOCKS Unix socket connection");
340
341
  }

Karsten Loesing's avatar
Karsten Loesing committed
342
343
  control_event_conn_bandwidth(conn);

344
345
  tor_assert(conn->conn_array_index >= 0);
  current_index = conn->conn_array_index;
346
  connection_unregister_events(conn); /* This is redundant, but cheap. */
347
348
  if (current_index == smartlist_len(connection_array)-1) { /* at the end */
    smartlist_del(connection_array, current_index);
Roger Dingledine's avatar
Roger Dingledine committed
349
    return 0;
Roger Dingledine's avatar
Roger Dingledine committed
350
  }
Roger Dingledine's avatar
Roger Dingledine committed
351

352
  /* replace this one with the one at the end */
353
354
355
  smartlist_del(connection_array, current_index);
  tmp = smartlist_get(connection_array, current_index);
  tmp->conn_array_index = current_index;
Roger Dingledine's avatar
Roger Dingledine committed
356

Roger Dingledine's avatar
Roger Dingledine committed
357
  return 0;
Roger Dingledine's avatar
Roger Dingledine committed
358
359
}

360
/** If <b>conn</b> is an edge conn, remove it from the list
361
362
363
 * of conn's on this circuit. If it's not on an edge,
 * flush and send destroys for all circuits on this conn.
 *
364
365
 * Remove it from connection_array (if applicable) and
 * from closeable_connection_list.
366
367
368
 *
 * Then free it.
 */
369
static void
370
connection_unlink(connection_t *conn)
371
{
372
  connection_about_to_close_connection(conn);
373
  if (conn->conn_array_index >= 0) {
374
375
    connection_remove(conn);
  }
376
377
378
379
380
381
382
  if (conn->linked_conn) {
    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;
  }
383
  smartlist_remove(closeable_connection_lst, conn);
384
  smartlist_remove(active_linked_connection_lst, conn);
385
  if (conn->type == CONN_TYPE_EXIT) {
386
    assert_connection_edge_not_dns_pending(TO_EDGE_CONN(conn));
387
  }
388
389
  if (conn->type == CONN_TYPE_OR) {
    if (!tor_digest_is_zero(TO_OR_CONN(conn)->identity_digest))
390
      connection_or_clear_identity(TO_OR_CONN(conn));
391
392
393
394
395
396
397
398
399
400
401
402
    /* connection_unlink() can only get called if the connection
     * was already on the closeable list, and it got there by
     * connection_mark_for_close(), which was called from
     * connection_or_close_normally() or
     * connection_or_close_for_error(), so the channel should
     * already be in CHANNEL_STATE_CLOSING, and then the
     * connection_about_to_close_connection() goes to
     * connection_or_about_to_close(), which calls channel_closed()
     * to notify the channel_t layer, and closed the channel, so
     * nothing more to do here to deal with the channel associated
     * with an orconn.
     */
403
  }
404
405
406
  connection_free(conn);
}

407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
/**
 * Callback: used to activate read events for all linked connections, so
 * libevent knows to call their read callbacks.  This callback run as a
 * postloop event, so that the events _it_ activates don't happen until
 * Libevent has a chance to check for other events.
 */
static void
schedule_active_linked_connections_cb(mainloop_event_t *event, void *arg)
{
  (void)event;
  (void)arg;

  /* All active linked conns should get their read events activated,
   * so that libevent knows to run their callbacks. */
  SMARTLIST_FOREACH(active_linked_connection_lst, connection_t *, conn,
                    event_active(conn->read_event, EV_READ, 1));
}

/** Event that invokes schedule_active_linked_connections_cb. */
static mainloop_event_t *schedule_active_linked_connections_event = NULL;

428
429
430
431
432
433
434
435
436
437
438
439
440
/** Initialize the global connection list, closeable connection list,
 * and active connection list. */
STATIC void
init_connection_lists(void)
{
  if (!connection_array)
    connection_array = smartlist_new();
  if (!closeable_connection_lst)
    closeable_connection_lst = smartlist_new();
  if (!active_linked_connection_lst)
    active_linked_connection_lst = smartlist_new();
}

441
/** Schedule <b>conn</b> to be closed. **/
442
443
444
void
add_connection_to_closeable_list(connection_t *conn)
{
Nick Mathewson's avatar
Nick Mathewson committed
445
  tor_assert(!smartlist_contains(closeable_connection_lst, conn));
446
  tor_assert(conn->marked_for_close);
447
  assert_connection_ok(conn, time(NULL));
448
  smartlist_add(closeable_connection_lst, conn);
449
  mainloop_schedule_postloop_cleanup();
450
451
}

452
/** Return 1 if conn is on the closeable list, else return 0. */
453
454
455
int
connection_is_on_closeable_list(connection_t *conn)
{
Nick Mathewson's avatar
Nick Mathewson committed
456
  return smartlist_contains(closeable_connection_lst, conn);
457
458
}

459
/** Return true iff conn is in the current poll array. */
460
461
462
int
connection_in_array(connection_t *conn)
{
Nick Mathewson's avatar
Nick Mathewson committed
463
  return smartlist_contains(connection_array, conn);
464
465
}

466
/** Set <b>*array</b> to an array of all connections. <b>*array</b> must not
Roger Dingledine's avatar
Roger Dingledine committed
467
 * be modified.
468
 */
469
470
MOCK_IMPL(smartlist_t *,
get_connection_array, (void))
471
{
472
  if (!connection_array)
473
    connection_array = smartlist_new();
474
  return connection_array;
475
476
}

477
478
479
480
/**
 * Return the amount of network traffic read, in bytes, over the life of this
 * process.
 */
481
482
MOCK_IMPL(uint64_t,
get_bytes_read,(void))
483
484
485
486
{
  return stats_n_bytes_read;
}

487
488
489
490
/**
 * Return the amount of network traffic read, in bytes, over the life of this
 * process.
 */
491
492
MOCK_IMPL(uint64_t,
get_bytes_written,(void))
493
494
495
496
{
  return stats_n_bytes_written;
}

497
498
499
500
501
502
503
504
505
506
507
/**
 * Increment the amount of network traffic read and written, over the life of
 * this process.
 */
void
stats_increment_bytes_read_and_written(uint64_t r, uint64_t w)
{
  stats_n_bytes_read += r;
  stats_n_bytes_written += w;
}

508
/** Set the event mask on <b>conn</b> to <b>events</b>.  (The event
509
 * mask is a bitmask whose bits are READ_EVENT and WRITE_EVENT)
510
 */
511
void
512
connection_watch_events(connection_t *conn, watchable_events_t events)
513
{
514
  if (events & READ_EVENT)
515
516
517
518
    connection_start_reading(conn);
  else
    connection_stop_reading(conn);

519
  if (events & WRITE_EVENT)
520
521
522
    connection_start_writing(conn);
  else
    connection_stop_writing(conn);
Roger Dingledine's avatar
Roger Dingledine committed
523
524
}

Roger Dingledine's avatar
Roger Dingledine committed
525
/** Return true iff <b>conn</b> is listening for read events. */
526
527
528
int
connection_is_reading(connection_t *conn)
{
529
  tor_assert(conn);
530

531
532
  return conn->reading_from_linked_conn ||
    (conn->read_event && event_pending(conn->read_event, EV_READ, NULL));
Roger Dingledine's avatar
Roger Dingledine committed
533
534
}

Alexander Færøy's avatar
Alexander Færøy committed
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
/** Reset our main loop counters. */
void
reset_main_loop_counters(void)
{
  stats_n_main_loop_successes = 0;
  stats_n_main_loop_errors = 0;
  stats_n_main_loop_idle = 0;
}

/** Increment the main loop success counter. */
static void
increment_main_loop_success_count(void)
{
  ++stats_n_main_loop_successes;
}

/** Get the main loop success counter. */
uint64_t
get_main_loop_success_count(void)
{
  return stats_n_main_loop_successes;
}

/** Increment the main loop error counter. */
static void
increment_main_loop_error_count(void)
{
  ++stats_n_main_loop_errors;
}

/** Get the main loop error counter. */
uint64_t
get_main_loop_error_count(void)
{
  return stats_n_main_loop_errors;
}

/** Increment the main loop idle counter. */
static void
increment_main_loop_idle_count(void)
{
  ++stats_n_main_loop_idle;
}

/** Get the main loop idle counter. */
uint64_t
get_main_loop_idle_count(void)
{
  return stats_n_main_loop_idle;
}

586
/** Check whether <b>conn</b> is correct in having (or not having) a
587
 * read/write event (passed in <b>ev</b>). On success, return 0. On failure,
588
 * log a warning and return -1. */
589
590
591
592
593
594
static int
connection_check_event(connection_t *conn, struct event *ev)
{
  int bad;

  if (conn->type == CONN_TYPE_AP && TO_EDGE_CONN(conn)->is_dns_request) {
595
596
597
598
    /* DNS requests which we launch through the dnsserv.c module do not have
     * any underlying socket or any underlying linked connection, so they
     * shouldn't have any attached events either.
     */
599
600
    bad = ev != NULL;
  } else {
Chelsea H. Komlo's avatar
Chelsea H. Komlo committed
601
    /* Everything else should have an underlying socket, or a linked
602
603
     * connection (which is also tracked with a read_event/write_event pair).
     */
604
605
606
607
608
609
610
611
612
613
614
    bad = ev == NULL;
  }

  if (bad) {
    log_warn(LD_BUG, "Event missing on connection %p [%s;%s]. "
             "socket=%d. linked=%d. "
             "is_dns_request=%d. Marked_for_close=%s:%d",
             conn,
             conn_type_to_string(conn->type),
             conn_state_to_string(conn->type, conn->state),
             (int)conn->s, (int)conn->linked,
Nick Mathewson's avatar
Nick Mathewson committed
615
616
             (conn->type == CONN_TYPE_AP &&
                               TO_EDGE_CONN(conn)->is_dns_request),
617
618
619
620
621
622
623
624
625
             conn->marked_for_close_file ? conn->marked_for_close_file : "-",
             conn->marked_for_close
             );
    log_backtrace(LOG_WARN, LD_BUG, "Backtrace attached.");
    return -1;
  }
  return 0;
}

Roger Dingledine's avatar
Roger Dingledine committed
626
/** Tell the main loop to stop notifying <b>conn</b> of any read events. */
627
628
MOCK_IMPL(void,
connection_stop_reading,(connection_t *conn))
629
{
630
  tor_assert(conn);
631

632
  if (connection_check_event(conn, conn->read_event) < 0) {
633
634
    return;
  }
635

636
637
638
639
640
641
642
  if (conn->linked) {
    conn->reading_from_linked_conn = 0;
    connection_stop_reading_from_linked_conn(conn);
  } else {
    if (event_del(conn->read_event))
      log_warn(LD_NET, "Error from libevent setting read event state for %d "
               "to unwatched: %s",
643
               (int)conn->s,
644
645
               tor_socket_strerror(tor_socket_errno(conn->s)));
  }
646
647
}

Roger Dingledine's avatar
Roger Dingledine committed
648
/** Tell the main loop to start notifying <b>conn</b> of any read events. */
649
650
MOCK_IMPL(void,
connection_start_reading,(connection_t *conn))
651
{
652
  tor_assert(conn);
653

654
  if (connection_check_event(conn, conn->read_event) < 0) {
655
656
    return;
  }
657

658
659
660
661
662
663
664
665
  if (conn->linked) {
    conn->reading_from_linked_conn = 1;
    if (connection_should_read_from_linked_conn(conn))
      connection_start_reading_from_linked_conn(conn);
  } else {
    if (event_add(conn->read_event, NULL))
      log_warn(LD_NET, "Error from libevent setting read event state for %d "
               "to watched: %s",
666
               (int)conn->s,
667
668
               tor_socket_strerror(tor_socket_errno(conn->s)));
  }
669
670
}

Roger Dingledine's avatar
Roger Dingledine committed
671
/** Return true iff <b>conn</b> is listening for write events. */
672
673
674
int
connection_is_writing(connection_t *conn)
{
675
676
  tor_assert(conn);

677
678
  return conn->writing_to_linked_conn ||
    (conn->write_event && event_pending(conn->write_event, EV_WRITE, NULL));
679
680
}

Roger Dingledine's avatar
Roger Dingledine committed
681
/** Tell the main loop to stop notifying <b>conn</b> of any write events. */
682
683
MOCK_IMPL(void,
connection_stop_writing,(connection_t *conn))
684
{
685
  tor_assert(conn);
686

687
688
689
  if (connection_check_event(conn, conn->write_event) < 0) {
    return;
  }
690

691
692
693
694
695
696
697
698
  if (conn->linked) {
    conn->writing_to_linked_conn = 0;
    if (conn->linked_conn)
      connection_stop_reading_from_linked_conn(conn->linked_conn);
  } else {
    if (event_del(conn->write_event))
      log_warn(LD_NET, "Error from libevent setting write event state for %d "
               "to unwatched: %s",
699
               (int)conn->s,
700
701
               tor_socket_strerror(tor_socket_errno(conn->s)));
  }
702
703
}

Roger Dingledine's avatar
Roger Dingledine committed
704
/** Tell the main loop to start notifying <b>conn</b> of any write events. */
705
706
MOCK_IMPL(void,
connection_start_writing,(connection_t *conn))
707
{
708
  tor_assert(conn);
709

710
711
712
  if (connection_check_event(conn, conn->write_event) < 0) {
    return;
  }
713

714
715
716
717
718
719
720
721
722
  if (conn->linked) {
    conn->writing_to_linked_conn = 1;
    if (conn->linked_conn &&
        connection_should_read_from_linked_conn(conn->linked_conn))
      connection_start_reading_from_linked_conn(conn->linked_conn);
  } else {
    if (event_add(conn->write_event, NULL))
      log_warn(LD_NET, "Error from libevent setting write event state for %d "
               "to watched: %s",
723
               (int)conn->s,
724
725
726
727
               tor_socket_strerror(tor_socket_errno(conn->s)));
  }
}

728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
/** Return true iff <b>conn</b> is linked conn, and reading from the conn
 * linked to it would be good and feasible.  (Reading is "feasible" if the
 * other conn exists and has data in its outbuf, and is "good" if we have our
 * reading_from_linked_conn flag set and the other conn has its
 * writing_to_linked_conn flag set.)*/
static int
connection_should_read_from_linked_conn(connection_t *conn)
{
  if (conn->linked && conn->reading_from_linked_conn) {
    if (! conn->linked_conn ||
        (conn->linked_conn->writing_to_linked_conn &&
         buf_datalen(conn->linked_conn->outbuf)))
      return 1;
  }
  return 0;
}

Nick Mathewson's avatar
Nick Mathewson committed
745
746
747
/** Event to run 'shutdown did not work callback'. */
static struct event *shutdown_did_not_work_event = NULL;

748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
/** Failsafe measure that should never actually be necessary: If
 * tor_shutdown_event_loop_and_exit() somehow doesn't successfully exit the
 * event loop, then this callback will kill Tor with an assertion failure
 * seconds later
 */
static void
shutdown_did_not_work_callback(evutil_socket_t fd, short event, void *arg)
{
  // LCOV_EXCL_START
  (void) fd;
  (void) event;
  (void) arg;
  tor_assert_unreached();
  // LCOV_EXCL_STOP
}

764
765
766
767
768
769
770
771
772
773
774
775
776
777
#ifdef ENABLE_RESTART_DEBUGGING
static struct event *tor_shutdown_event_loop_for_restart_event = NULL;
static void
tor_shutdown_event_loop_for_restart_cb(
                      evutil_socket_t fd, short event, void *arg)
{
  (void)fd;
  (void)event;
  (void)arg;
  tor_event_free(tor_shutdown_event_loop_for_restart_event);
  tor_shutdown_event_loop_and_exit(0);
}
#endif

778
779
780
781
782
783
784
785
786
787
788
789
790
/**
 * After finishing the current callback (if any), shut down the main loop,
 * clean up the process, and exit with <b>exitcode</b>.
 */
void
tor_shutdown_event_loop_and_exit(int exitcode)
{
  if (main_loop_should_exit)
    return; /* Ignore multiple calls to this function. */

  main_loop_should_exit = 1;
  main_loop_exit_value = exitcode;

791
792
  /* Die with an assertion failure in ten seconds, if for some reason we don't
   * exit normally. */
793
  /* XXXX We should consider this code if it's never used. */
794
  struct timeval ten_seconds = { 10, 0 };
Nick Mathewson's avatar
Nick Mathewson committed
795
796
797
798
  shutdown_did_not_work_event = tor_evtimer_new(
                  tor_libevent_get_base(),
                  shutdown_did_not_work_callback, NULL);
  event_add(shutdown_did_not_work_event, &ten_seconds);
799

800
801
802
  /* Unlike exit_loop_after_delay(), exit_loop_after_callback
   * prevents other callbacks from running. */
  tor_libevent_exit_loop_after_callback(tor_libevent_get_base());
803
804
805
806
807
808
809
810
811
}

/** Return true iff tor_shutdown_event_loop_and_exit() has been called. */
int
tor_event_loop_shutdown_is_pending(void)
{
  return main_loop_should_exit;
}

812
813
814
815
/** Helper: Tell the main loop to begin reading bytes into <b>conn</b> from
 * its linked connection, if it is not doing so already.  Called by
 * connection_start_reading and connection_start_writing as appropriate. */
static void
816
817
818
819
820
821
822
823
connection_start_reading_from_linked_conn(connection_t *conn)
{
  tor_assert(conn);
  tor_assert(conn->linked == 1);

  if (!conn->active_on_link) {
    conn->active_on_link = 1;
    smartlist_add(active_linked_connection_lst, conn);
824
    mainloop_event_activate(schedule_active_linked_connections_event);
825
  } else {
Nick Mathewson's avatar
Nick Mathewson committed
826
    tor_assert(smartlist_contains(active_linked_connection_lst, conn));
827
828
829
  }
}

830
831
832
/** Tell the main loop to stop reading bytes into <b>conn</b> from its linked
 * connection, if is currently doing so.  Called by connection_stop_reading,
 * connection_stop_writing, and connection_read. */
833
834
835
836
837
838
839
840
void
connection_stop_reading_from_linked_conn(connection_t *conn)
{
  tor_assert(conn);
  tor_assert(conn->linked == 1);

  if (conn->active_on_link) {
    conn->active_on_link = 0;
841
842
843
    /* FFFF We could keep an index here so we can smartlist_del
     * cleanly.  On the other hand, this doesn't show up on profiles,
     * so let's leave it alone for now. */
844
845
    smartlist_remove(active_linked_connection_lst, conn);
  } else {
Nick Mathewson's avatar
Nick Mathewson committed
846
    tor_assert(!smartlist_contains(active_linked_connection_lst, conn));
847
  }
848
849
}

850
/** Close all connections that have been scheduled to get closed. */
851
STATIC void
852
853
854
855
856
close_closeable_connections(void)
{
  int i;
  for (i = 0; i < smartlist_len(closeable_connection_lst); ) {
    connection_t *conn = smartlist_get(closeable_connection_lst, i);
857
    if (conn->conn_array_index < 0) {
858
      connection_unlink(conn); /* blow it away right now */
859
    } else {
860
      if (!conn_close_if_marked(conn->conn_array_index))
861
862
        ++i;
    }
863
864
865
  }
}

866
/** Count moribund connections for the OOS handler */
867
868
MOCK_IMPL(int,
connection_count_moribund, (void))
869
{
870
  int moribund = 0;
871
872
873
874
875

  /*
   * Count things we'll try to kill when close_closeable_connections()
   * runs next.
   */
876
  SMARTLIST_FOREACH_BEGIN(closeable_connection_lst, connection_t *, conn) {
877
    if (SOCKET_OK(conn->s) && connection_is_moribund(conn)) ++moribund;
878
  } SMARTLIST_FOREACH_END(conn);
879
880
881
882

  return moribund;
}

883
884
/** Libevent callback: this gets invoked when (connection_t*)<b>conn</b> has
 * some data to read. */
885
static void
886
conn_read_callback(evutil_socket_t fd, short event, void *_conn)
887
888
{
  connection_t *conn = _conn;
889
890
  (void)fd;
  (void)event;
891

892
  log_debug(LD_NET,"socket %d wants to read.",(int)conn->s);
893

894
  /* assert_connection_ok(conn, time(NULL)); */
895
896
897

  if (connection_handle_read(conn) < 0) {
    if (!conn->marked_for_close) {
898
#ifndef _WIN32
899
      log_warn(LD_BUG,"Unhandled error on read for %s connection "
900
               "(fd %d); removing",
901
               conn_type_to_string(conn->type), (int)conn->s);
902
      tor_fragile_assert();
903
#endif /* !defined(_WIN32) */
904
      if (CONN_IS_EDGE(conn))
905
        connection_edge_end_errno(TO_EDGE_CONN(conn));
906
907
908
909
910
911
912
913
914
      connection_mark_for_close(conn);
    }
  }
  assert_connection_ok(conn, time(NULL));

  if (smartlist_len(closeable_connection_lst))
    close_closeable_connections();
}

915
916
/** Libevent callback: this gets invoked when (connection_t*)<b>conn</b> has
 * some data to write. */
917
static void
918
conn_write_callback(evutil_socket_t fd, short events, void *_conn)
919
920
{
  connection_t *conn = _conn;
921
922
  (void)fd;
  (void)events;
923

924
925
  LOG_FN_CONN(conn, (LOG_DEBUG, LD_NET, "socket %d wants to write.",
                     (int)conn->s));
926

927
  /* assert_connection_ok(conn, time(NULL)); */
928

929
  if (connection_handle_write(conn, 0) < 0) {
930
931
    if (!conn->marked_for_close) {
      /* this connection is broken. remove it. */
932
      log_fn(LOG_WARN,LD_BUG,
Roger Dingledine's avatar
Roger Dingledine committed
933
             "unhandled error on write for %s connection (fd %d); removing",
934
             conn_type_to_string(conn->type), (int)conn->s);
935
      tor_fragile_assert();
936
937
      if (CONN_IS_EDGE(conn)) {
        /* otherwise we cry wolf about duplicate close */
938
939
940
        edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
        if (!edge_conn->end_reason)
          edge_conn->end_reason = END_STREAM_REASON_INTERNAL;
941
        edge_conn->edge_has_sent_end = 1;
942
      }
943
      connection_close_immediate(conn); /* So we don't try to flush. */
944
945
946
947
948
949
950
951
952
      connection_mark_for_close(conn);
    }
  }
  assert_connection_ok(conn, time(NULL));

  if (smartlist_len(closeable_connection_lst))
    close_closeable_connections();
}

Roger Dingledine's avatar
Roger Dingledine committed
953
/** If the connection at connection_array[i] is marked for close, then:
954
955
956
957
958
 *    - If it has data that it wants to flush, try to flush it.
 *    - If it _still_ has data to flush, and conn->hold_open_until_flushed is
 *      true, then leave the connection open and return.
 *    - Otherwise, remove the connection from connection_array and from
 *      all other lists, close it, and free it.
959
 * Returns 1 if the connection was closed, 0 otherwise.
960
 */
961
962
963
static int
conn_close_if_marked(int i)
{
Roger Dingledine's avatar
Roger Dingledine committed
964
  connection_t *conn;
965
  int retval;
966
  time_t now;
Roger Dingledine's avatar
Roger Dingledine committed
967

968
  conn = smartlist_get(connection_array, i);
969
  if (!conn->marked_for_close)
970
    return 0; /* nothing to see here, move along */
971
972
  now = time(NULL);
  assert_connection_ok(conn, now);
973
  /* assert_all_pending_dns_resolves_ok(); */
974

Nick Mathewson's avatar
Nick Mathewson committed
975
976
  log_debug(LD_NET,"Cleaning up connection (fd "TOR_SOCKET_T_FORMAT").",
            conn->s);
977
978
979

  /* If the connection we are about to close was trying to connect to
  a proxy server and failed, the client won't be able to use that
980
  proxy. We should warn the user about this. */
981
982
  if (conn->proxy_state == PROXY_INFANT)
    log_failed_proxy_connection(conn);
983

984
985
  if ((SOCKET_OK(conn->s) || conn->linked_conn) &&
      connection_wants_to_flush(conn)) {
986
    /* s == -1 means it's an incomplete edge connection, or that the socket
987
     * has already been closed as unflushable. */
988
    ssize_t sz = connection_bucket_write_limit(conn, now);
989
    if (!conn->hold_open_until_flushed)
990
991
992
      log_info(LD_NET,
               "Conn (addr %s, fd %d, type %s, state %d) marked, but wants "
               "to flush %d bytes. (Marked at %s:%d)",
993
               escaped_safe_str_client(conn->address),
994
               (int)conn->s, conn_type_to_string(conn->type), conn->state,
995
996
               (int)conn->outbuf_flushlen,
                conn->marked_for_close_file, conn->marked_for_close);
997
    if (conn->linked_conn) {
998
      retval = buf_move_to_buf(conn->linked_conn->inbuf, conn->outbuf,
999
1000
                               &conn->outbuf_flushlen);
      if (retval >= 0) {