main.c 70.5 KB
Newer Older
Roger Dingledine's avatar
Roger Dingledine committed
1
2
/* Copyright (c) 2001 Matej Pfajfar.
 * Copyright (c) 2001-2004, Roger Dingledine.
3
 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
4
 * Copyright (c) 2007-2008, The Tor Project, Inc. */
5
6
/* See LICENSE for licensing information */
/* $Id$ */
Nick Mathewson's avatar
Nick Mathewson committed
7
8
const char main_c_id[] =
  "$Id$";
Roger Dingledine's avatar
Roger Dingledine committed
9

Roger Dingledine's avatar
Roger Dingledine committed
10
11
/**
 * \file main.c
12
13
 * \brief Toplevel module. Handles signals, multiplexes between
 * connections, implements main loop, and drives scheduled events.
Roger Dingledine's avatar
Roger Dingledine committed
14
 **/
15

Nick Mathewson's avatar
Nick Mathewson committed
16
#define MAIN_PRIVATE
Roger Dingledine's avatar
Roger Dingledine committed
17
#include "or.h"
18
19
#ifdef USE_DMALLOC
#include <dmalloc.h>
20
#include <openssl/crypto.h>
21
#endif
22
#include "memarea.h"
23

24
void evdns_shutdown(int);
Roger Dingledine's avatar
Roger Dingledine committed
25

26
/********* PROTOTYPES **********/
Roger Dingledine's avatar
Roger Dingledine committed
27

28
static void dumpmemusage(int severity);
29
static void dumpstats(int severity); /* log stats */
30
31
32
33
34
static void conn_read_callback(int fd, short event, void *_conn);
static void conn_write_callback(int fd, short event, void *_conn);
static void signal_callback(int fd, short events, void *arg);
static void second_elapsed_callback(int fd, short event, void *args);
static int conn_close_if_marked(int i);
35
static void connection_start_reading_from_linked_conn(connection_t *conn);
36
static int connection_should_read_from_linked_conn(connection_t *conn);
Roger Dingledine's avatar
Roger Dingledine committed
37

Roger Dingledine's avatar
Roger Dingledine committed
38
39
/********* START VARIABLES **********/

40
int global_read_bucket; /**< Max number of bytes I can read this second. */
41
int global_write_bucket; /**< Max number of bytes I can write this second. */
Roger Dingledine's avatar
Roger Dingledine committed
42

43
44
45
46
47
/** Max number of relayed (bandwidth class 1) bytes I can read this second. */
int global_relayed_read_bucket;
/** Max number of relayed (bandwidth class 1) bytes I can write this second. */
int global_relayed_write_bucket;

48
/** What was the read bucket before the last second_elapsed_callback() call?
49
 * (used to determine how many bytes we've read). */
50
static int stats_prev_global_read_bucket;
51
/** What was the write bucket before the last second_elapsed_callback() call?
52
53
 * (used to determine how many bytes we've written). */
static int stats_prev_global_write_bucket;
54
/* XXX we might want to keep stats about global_relayed_*_bucket too. Or not.*/
55
/** How many bytes have we read/written since we started the process? */
56
static uint64_t stats_n_bytes_read = 0;
57
static uint64_t stats_n_bytes_written = 0;
58
/** What time did this process start up? */
59
time_t time_of_process_start = 0;
Roger Dingledine's avatar
Roger Dingledine committed
60
/** How many seconds have we been running? */
61
long stats_n_seconds_working = 0;
62
63
/** When do we next launch DNS wildcarding checks? */
static time_t time_to_check_for_correct_dns = 0;
64
65
66
67
68
69
70

/** 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;
71

72
73
/** Smartlist of all open connections. */
static smartlist_t *connection_array = NULL;
74
75
/** List of connections that have been marked for close and need to be freed
 * and removed from connection_array. */
76
static smartlist_t *closeable_connection_lst = NULL;
77
78
/** List of linked connections that are currently reading data into their
 * inbuf from their partner's outbuf. */
79
static smartlist_t *active_linked_connection_lst = NULL;
80
81
82
/** 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. */
83
static int called_loop_once = 0;
Roger Dingledine's avatar
Roger Dingledine committed
84

Roger Dingledine's avatar
Roger Dingledine committed
85
/** We set this to 1 when we've opened a circuit, so we can print a log
86
 * entry to inform the user that Tor is working. */
87
int has_completed_circuit=0;
88

89
90
91
92
93
94
/** 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)
95
96
97
98
99
100
101
102
103
/** How often do we 'forgive' undownloadable router descriptors and attempt
 * to download them again? */
#define DESCRIPTOR_FAILURE_RESET_INTERVAL (60*60)
/** How long do we let a directory connection stall before expiring it? */
#define DIR_CONN_MAX_STALL (5*60)

/** How old do we let a connection to an OR get before deciding it's
 * obsolete? */
#define TIME_BEFORE_OR_CONN_IS_OBSOLETE (60*60*24*7)
Roger Dingledine's avatar
Roger Dingledine committed
104
105
/** How long do we let OR connections handshake before we decide that
 * they are obsolete? */
106
#define TLS_HANDSHAKE_TIMEOUT (60)
107

Roger Dingledine's avatar
Roger Dingledine committed
108
109
/********* END VARIABLES ************/

Roger Dingledine's avatar
Roger Dingledine committed
110
111
112
/****************************************************************************
*
* This section contains accessors and other methods on the connection_array
113
* variables (which are global within this file and unavailable outside it).
Roger Dingledine's avatar
Roger Dingledine committed
114
115
116
*
****************************************************************************/

Roger Dingledine's avatar
Roger Dingledine committed
117
/** Add <b>conn</b> to the array of connections that we can poll on.  The
118
119
120
 * connection's socket must be set; the connection starts out
 * non-reading and non-writing.
 */
121
122
123
int
connection_add(connection_t *conn)
{
Roger Dingledine's avatar
Roger Dingledine committed
124
  tor_assert(conn);
125
126
127
  tor_assert(conn->s >= 0 ||
             conn->linked ||
             (conn->type == CONN_TYPE_AP &&
128
              TO_EDGE_CONN(conn)->is_dns_request));
Roger Dingledine's avatar
Roger Dingledine committed
129

130
  tor_assert(conn->conn_array_index == -1); /* can only connection_add once */
131
132
  conn->conn_array_index = smartlist_len(connection_array);
  smartlist_add(connection_array, conn);
Roger Dingledine's avatar
Roger Dingledine committed
133

134
  if (conn->s >= 0 || conn->linked) {
135
136
137
138
139
140
141
    conn->read_event = tor_malloc_zero(sizeof(struct event));
    conn->write_event = tor_malloc_zero(sizeof(struct event));
    event_set(conn->read_event, conn->s, EV_READ|EV_PERSIST,
              conn_read_callback, conn);
    event_set(conn->write_event, conn->s, EV_WRITE|EV_PERSIST,
              conn_write_callback, conn);
  }
Roger Dingledine's avatar
Roger Dingledine committed
142

Roger Dingledine's avatar
Roger Dingledine committed
143
144
  log_debug(LD_NET,"new conn type %s, socket %d, address %s, n_conns %d.",
            conn_type_to_string(conn->type), conn->s, conn->address,
145
            smartlist_len(connection_array));
Roger Dingledine's avatar
Roger Dingledine committed
146
147
148
149

  return 0;
}

Roger Dingledine's avatar
Roger Dingledine committed
150
/** Remove the connection from the global list, and remove the
Nick Mathewson's avatar
Nick Mathewson committed
151
152
153
 * corresponding poll entry.  Calling this function will shift the last
 * connection (if any) into the position occupied by conn.
 */
154
155
156
int
connection_remove(connection_t *conn)
{
Roger Dingledine's avatar
Roger Dingledine committed
157
  int current_index;
158
  connection_t *tmp;
Roger Dingledine's avatar
Roger Dingledine committed
159

Roger Dingledine's avatar
Roger Dingledine committed
160
  tor_assert(conn);
Roger Dingledine's avatar
Roger Dingledine committed
161

162
  log_debug(LD_NET,"removing socket %d (type %s), n_conns now %d",
163
164
            conn->s, conn_type_to_string(conn->type),
            smartlist_len(connection_array));
Roger Dingledine's avatar
Roger Dingledine committed
165

166
167
  tor_assert(conn->conn_array_index >= 0);
  current_index = conn->conn_array_index;
168
  connection_unregister_events(conn); /* This is redundant, but cheap. */
169
170
  if (current_index == smartlist_len(connection_array)-1) { /* at the end */
    smartlist_del(connection_array, current_index);
Roger Dingledine's avatar
Roger Dingledine committed
171
    return 0;
Roger Dingledine's avatar
Roger Dingledine committed
172
  }
Roger Dingledine's avatar
Roger Dingledine committed
173

174
  /* replace this one with the one at the end */
175
176
177
  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
178

Roger Dingledine's avatar
Roger Dingledine committed
179
  return 0;
Roger Dingledine's avatar
Roger Dingledine committed
180
181
}

182
/** If <b>conn</b> is an edge conn, remove it from the list
183
184
185
 * of conn's on this circuit. If it's not on an edge,
 * flush and send destroys for all circuits on this conn.
 *
186
187
 * Remove it from connection_array (if applicable) and
 * from closeable_connection_list.
188
189
190
 *
 * Then free it.
 */
191
static void
192
connection_unlink(connection_t *conn)
193
{
194
  connection_about_to_close_connection(conn);
195
  if (conn->conn_array_index >= 0) {
196
197
    connection_remove(conn);
  }
198
199
200
201
202
203
204
  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;
  }
205
  smartlist_remove(closeable_connection_lst, conn);
206
  smartlist_remove(active_linked_connection_lst, conn);
207
  if (conn->type == CONN_TYPE_EXIT) {
208
    assert_connection_edge_not_dns_pending(TO_EDGE_CONN(conn));
209
  }
210
211
212
  if (conn->type == CONN_TYPE_OR) {
    if (!tor_digest_is_zero(TO_OR_CONN(conn)->identity_digest))
      connection_or_remove_from_identity_map(TO_OR_CONN(conn));
213
  }
214
215
216
  connection_free(conn);
}

217
/** Schedule <b>conn</b> to be closed. **/
218
219
220
221
222
void
add_connection_to_closeable_list(connection_t *conn)
{
  tor_assert(!smartlist_isin(closeable_connection_lst, conn));
  tor_assert(conn->marked_for_close);
223
  assert_connection_ok(conn, time(NULL));
224
225
226
  smartlist_add(closeable_connection_lst, conn);
}

227
/** Return 1 if conn is on the closeable list, else return 0. */
228
229
230
int
connection_is_on_closeable_list(connection_t *conn)
{
231
232
233
  return smartlist_isin(closeable_connection_lst, conn);
}

234
/** Return true iff conn is in the current poll array. */
235
236
237
int
connection_in_array(connection_t *conn)
{
238
  return smartlist_isin(connection_array, conn);
239
240
}

Roger Dingledine's avatar
Roger Dingledine committed
241
242
243
/** Set <b>*array</b> to an array of all connections, and <b>*n</b>
 * to the length of the array. <b>*array</b> and <b>*n</b> must not
 * be modified.
244
 */
245
246
smartlist_t *
get_connection_array(void)
247
{
248
249
  if (!connection_array)
    connection_array = smartlist_create();
250
  return connection_array;
251
252
}

253
/** Set the event mask on <b>conn</b> to <b>events</b>.  (The event
254
 * mask is a bitmask whose bits are EV_READ and EV_WRITE.)
255
 */
256
257
258
void
connection_watch_events(connection_t *conn, short events)
{
259
260
261
262
263
264
265
266
267
  if (events & EV_READ)
    connection_start_reading(conn);
  else
    connection_stop_reading(conn);

  if (events & EV_WRITE)
    connection_start_writing(conn);
  else
    connection_stop_writing(conn);
Roger Dingledine's avatar
Roger Dingledine committed
268
269
}

Roger Dingledine's avatar
Roger Dingledine committed
270
/** Return true iff <b>conn</b> is listening for read events. */
271
272
273
int
connection_is_reading(connection_t *conn)
{
274
  tor_assert(conn);
275

276
277
  return conn->reading_from_linked_conn ||
    (conn->read_event && event_pending(conn->read_event, EV_READ, NULL));
Roger Dingledine's avatar
Roger Dingledine committed
278
279
}

Roger Dingledine's avatar
Roger Dingledine committed
280
/** Tell the main loop to stop notifying <b>conn</b> of any read events. */
281
282
283
void
connection_stop_reading(connection_t *conn)
{
284
  tor_assert(conn);
285
  tor_assert(conn->read_event);
286

287
288
289
290
291
292
293
294
295
296
  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",
               conn->s,
               tor_socket_strerror(tor_socket_errno(conn->s)));
  }
297
298
}

Roger Dingledine's avatar
Roger Dingledine committed
299
/** Tell the main loop to start notifying <b>conn</b> of any read events. */
300
301
302
void
connection_start_reading(connection_t *conn)
{
303
  tor_assert(conn);
304
305
  tor_assert(conn->read_event);

306
307
308
309
310
311
312
313
314
315
316
  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",
               conn->s,
               tor_socket_strerror(tor_socket_errno(conn->s)));
  }
317
318
}

Roger Dingledine's avatar
Roger Dingledine committed
319
/** Return true iff <b>conn</b> is listening for write events. */
320
321
322
int
connection_is_writing(connection_t *conn)
{
323
324
  tor_assert(conn);

325
326
  return conn->writing_to_linked_conn ||
    (conn->write_event && event_pending(conn->write_event, EV_WRITE, NULL));
327
328
}

Roger Dingledine's avatar
Roger Dingledine committed
329
/** Tell the main loop to stop notifying <b>conn</b> of any write events. */
330
331
332
void
connection_stop_writing(connection_t *conn)
{
333
  tor_assert(conn);
334
335
  tor_assert(conn->write_event);

336
337
338
339
340
341
342
343
344
345
346
  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",
               conn->s,
               tor_socket_strerror(tor_socket_errno(conn->s)));
  }
347
348
}

Roger Dingledine's avatar
Roger Dingledine committed
349
/** Tell the main loop to start notifying <b>conn</b> of any write events. */
350
351
352
void
connection_start_writing(connection_t *conn)
{
353
  tor_assert(conn);
354
355
  tor_assert(conn->write_event);

356
357
358
359
360
361
362
363
364
365
366
367
368
369
  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",
               conn->s,
               tor_socket_strerror(tor_socket_errno(conn->s)));
  }
}

370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
/** 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;
}

387
388
389
390
/** 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
391
392
393
394
395
396
397
398
399
400
401
402
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);
    if (!called_loop_once) {
      /* This is the first event on the list; we won't be in LOOP_ONCE mode,
       * so we need to make sure that the event_loop() actually exits at the
       * end of its run through the current connections and
403
       * lets us activate read events for linked connections. */
404
405
406
407
408
409
410
411
      struct timeval tv = { 0, 0 };
      event_loopexit(&tv);
    }
  } else {
    tor_assert(smartlist_isin(active_linked_connection_lst, conn));
  }
}

412
413
414
/** 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. */
415
416
417
418
419
420
421
422
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;
423
424
425
    /* 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. */
426
427
428
429
    smartlist_remove(active_linked_connection_lst, conn);
  } else {
    tor_assert(!smartlist_isin(active_linked_connection_lst, conn));
  }
430
431
}

432
/** Close all connections that have been scheduled to get closed. */
433
434
435
436
437
438
static void
close_closeable_connections(void)
{
  int i;
  for (i = 0; i < smartlist_len(closeable_connection_lst); ) {
    connection_t *conn = smartlist_get(closeable_connection_lst, i);
439
    if (conn->conn_array_index < 0) {
440
      connection_unlink(conn); /* blow it away right now */
441
    } else {
442
      if (!conn_close_if_marked(conn->conn_array_index))
443
444
        ++i;
    }
445
446
447
  }
}

448
449
/** Libevent callback: this gets invoked when (connection_t*)<b>conn</b> has
 * some data to read. */
450
451
452
453
static void
conn_read_callback(int fd, short event, void *_conn)
{
  connection_t *conn = _conn;
454
455
  (void)fd;
  (void)event;
456

457
  log_debug(LD_NET,"socket %d wants to read.",conn->s);
458
459
460
461
462
463

  assert_connection_ok(conn, time(NULL));

  if (connection_handle_read(conn) < 0) {
    if (!conn->marked_for_close) {
#ifndef MS_WINDOWS
464
      log_warn(LD_BUG,"Unhandled error on read for %s connection "
465
466
               "(fd %d); removing",
               conn_type_to_string(conn->type), conn->s);
467
      tor_fragile_assert();
468
#endif
469
      if (CONN_IS_EDGE(conn))
470
        connection_edge_end_errno(TO_EDGE_CONN(conn));
471
472
473
474
475
476
477
478
479
      connection_mark_for_close(conn);
    }
  }
  assert_connection_ok(conn, time(NULL));

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

480
481
/** Libevent callback: this gets invoked when (connection_t*)<b>conn</b> has
 * some data to write. */
482
483
static void
conn_write_callback(int fd, short events, void *_conn)
484
485
{
  connection_t *conn = _conn;
486
487
  (void)fd;
  (void)events;
488

489
  LOG_FN_CONN(conn, (LOG_DEBUG, LD_NET, "socket %d wants to write.",conn->s));
490
491
492

  assert_connection_ok(conn, time(NULL));

493
  if (connection_handle_write(conn, 0) < 0) {
494
495
    if (!conn->marked_for_close) {
      /* this connection is broken. remove it. */
496
      log_fn(LOG_WARN,LD_BUG,
Roger Dingledine's avatar
Roger Dingledine committed
497
498
             "unhandled error on write for %s connection (fd %d); removing",
             conn_type_to_string(conn->type), conn->s);
499
      tor_fragile_assert();
500
501
      if (CONN_IS_EDGE(conn)) {
        /* otherwise we cry wolf about duplicate close */
502
503
504
        edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
        if (!edge_conn->end_reason)
          edge_conn->end_reason = END_STREAM_REASON_INTERNAL;
505
506
        conn->edge_has_sent_end = 1;
      }
507
      connection_close_immediate(conn); /* So we don't try to flush. */
508
509
510
511
512
513
514
515
516
      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
517
/** If the connection at connection_array[i] is marked for close, then:
518
519
520
521
522
 *    - 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.
523
 * Returns 1 if the connection was closed, 0 otherwise.
524
 */
525
526
527
static int
conn_close_if_marked(int i)
{
Roger Dingledine's avatar
Roger Dingledine committed
528
  connection_t *conn;
529
  int retval;
530
  time_t now;
Roger Dingledine's avatar
Roger Dingledine committed
531

532
  conn = smartlist_get(connection_array, i);
533
  if (!conn->marked_for_close)
534
    return 0; /* nothing to see here, move along */
535
536
  now = time(NULL);
  assert_connection_ok(conn, now);
537
  assert_all_pending_dns_resolves_ok();
538

539
  log_debug(LD_NET,"Cleaning up connection (fd %d).",conn->s);
540
  if ((conn->s >= 0 || conn->linked_conn) && connection_wants_to_flush(conn)) {
541
    /* s == -1 means it's an incomplete edge connection, or that the socket
542
     * has already been closed as unflushable. */
543
    ssize_t sz = connection_bucket_write_limit(conn, now);
544
    if (!conn->hold_open_until_flushed)
545
546
547
      log_info(LD_NET,
               "Conn (addr %s, fd %d, type %s, state %d) marked, but wants "
               "to flush %d bytes. (Marked at %s:%d)",
548
549
               escaped_safe_str(conn->address),
               conn->s, conn_type_to_string(conn->type), conn->state,
550
551
               (int)conn->outbuf_flushlen,
                conn->marked_for_close_file, conn->marked_for_close);
552
553
554
555
556
557
558
559
    if (conn->linked_conn) {
      retval = move_buf_to_buf(conn->linked_conn->inbuf, conn->outbuf,
                               &conn->outbuf_flushlen);
      if (retval >= 0) {
        /* The linked conn will notice that it has data when it notices that
         * we're gone. */
        connection_start_reading_from_linked_conn(conn->linked_conn);
      }
560
      log_debug(LD_GENERAL, "Flushed last %d bytes from a linked conn; "
561
562
563
               "%d left; flushlen %d; wants-to-flush==%d", retval,
               (int)buf_datalen(conn->outbuf),
               (int)conn->outbuf_flushlen,
564
                connection_wants_to_flush(conn));
565
    } else if (connection_speaks_cells(conn)) {
566
      if (conn->state == OR_CONN_STATE_OPEN) {
567
        retval = flush_buf_tls(TO_OR_CONN(conn)->tls, conn->outbuf, sz,
568
                               &conn->outbuf_flushlen);
569
      } else
570
        retval = -1; /* never flush non-open broken tls connections */
571
    } else {
572
      retval = flush_buf(conn->s, conn->outbuf, sz, &conn->outbuf_flushlen);
573
    }
574
575
576
    if (retval >= 0 && /* Technically, we could survive things like
                          TLS_WANT_WRITE here. But don't bother for now. */
        conn->hold_open_until_flushed && connection_wants_to_flush(conn)) {
577
      if (retval > 0) {
578
579
580
        LOG_FN_CONN(conn, (LOG_INFO,LD_NET,
                           "Holding conn (fd %d) open for more flushing.",
                           conn->s));
581
582
        conn->timestamp_lastwritten = now; /* reset so we can flush more */
      }
583
      return 0;
584
    }
585
    if (connection_wants_to_flush(conn)) {
586
587
      int severity;
      if (conn->type == CONN_TYPE_EXIT ||
588
          (conn->type == CONN_TYPE_OR && server_mode(get_options())) ||
589
590
591
592
          (conn->type == CONN_TYPE_DIR && conn->purpose == DIR_PURPOSE_SERVER))
        severity = LOG_INFO;
      else
        severity = LOG_NOTICE;
593
594
595
      /* XXXX Maybe allow this to happen a certain amount per hour; it usually
       * is meaningless. */
      log_fn(severity, LD_NET, "We stalled too much while trying to write %d "
596
             "bytes to address %s.  If this happens a lot, either "
597
598
599
             "something is wrong with your network connection, or "
             "something is wrong with theirs. "
             "(fd %d, type %s, state %d, marked at %s:%d).",
600
             (int)buf_datalen(conn->outbuf),
601
602
             escaped_safe_str(conn->address), conn->s,
             conn_type_to_string(conn->type), conn->state,
603
             conn->marked_for_close_file,
604
             conn->marked_for_close);
Roger Dingledine's avatar
Roger Dingledine committed
605
606
    }
  }
607
  connection_unlink(conn); /* unlink, remove, free */
608
  return 1;
Roger Dingledine's avatar
Roger Dingledine committed
609
610
}

611
612
613
614
615
616
/** We've just tried every dirserver we know about, and none of
 * them were reachable. Assume the network is down. Change state
 * so next time an application connection arrives we'll delay it
 * and try another directory fetch. Kill off all the circuit_wait
 * streams that are waiting now, since they will all timeout anyway.
 */
617
618
619
void
directory_all_unreachable(time_t now)
{
620
  connection_t *conn;
621
  (void)now;
622

623
  stats_n_seconds_working=0; /* reset it */
624
625
626

  while ((conn = connection_get_by_type_state(CONN_TYPE_AP,
                                              AP_CONN_STATE_CIRCUIT_WAIT))) {
627
    edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
628
629
630
    log_notice(LD_NET,
               "Is your network connection down? "
               "Failing connection to '%s:%d'.",
631
632
               safe_str(edge_conn->socks_request->address),
               edge_conn->socks_request->port);
633
634
    connection_mark_unattached_ap(edge_conn,
                                  END_STREAM_REASON_NET_UNREACHABLE);
635
  }
636
  control_event_general_status(LOG_ERR, "DIR_ALL_UNREACHABLE");
637
638
}

639
640
/** This function is called whenever we successfully pull down some new
 * network statuses or server descriptors. */
641
void
642
directory_info_has_arrived(time_t now, int from_cache)
643
{
644
  or_options_t *options = get_options();
645

646
  if (!router_have_minimum_dir_info()) {
647
    int quiet = directory_too_idle_to_fetch_descriptors(options, now);
648
    log(quiet ? LOG_INFO : LOG_NOTICE, LD_DIR,
649
        "I learned some more directory information, but not enough to "
650
        "build a circuit: %s", get_dir_info_status_string());
651
    update_router_descriptor_downloads(now);
652
    return;
653
  } else {
654
655
656
    /* if we have enough dir info, then update our guard status with
     * whatever we just learned. */
    entry_guards_compute_status();
657
658
659
660
    /* Don't even bother trying to get extrainfo until the rest of our
     * directory info is up-to-date */
    if (options->DownloadExtraInfo)
      update_extrainfo_downloads(now);
661
  }
662

663
  if (server_mode(options) && !we_are_hibernating() && !from_cache &&
Roger Dingledine's avatar
Roger Dingledine committed
664
      (has_completed_circuit || !any_predicted_circuits(now)))
665
    consider_testing_reachability(1, 1);
666
667
}

Roger Dingledine's avatar
Roger Dingledine committed
668
/** Perform regular maintenance tasks for a single connection.  This
669
 * function gets run once per second per connection by run_scheduled_events.
Nick Mathewson's avatar
Nick Mathewson committed
670
 */
671
672
673
static void
run_connection_housekeeping(int i, time_t now)
{
Nick Mathewson's avatar
Nick Mathewson committed
674
  cell_t cell;
675
  connection_t *conn = smartlist_get(connection_array, i);
676
  or_options_t *options = get_options();
677
  or_connection_t *or_conn;
Roger Dingledine's avatar
Roger Dingledine committed
678

679
680
  if (conn->outbuf && !buf_datalen(conn->outbuf) && conn->type == CONN_TYPE_OR)
    TO_OR_CONN(conn)->timestamp_lastempty = now;
681

682
683
684
685
686
  if (conn->marked_for_close) {
    /* nothing to do here */
    return;
  }

687
688
  /* Expire any directory connections that haven't been active (sent
   * if a server or received if a client) for 5 min */
689
690
691
692
693
  if (conn->type == CONN_TYPE_DIR &&
      ((DIR_CONN_IS_SERVER(conn) &&
        conn->timestamp_lastwritten + DIR_CONN_MAX_STALL < now) ||
       (!DIR_CONN_IS_SERVER(conn) &&
        conn->timestamp_lastread + DIR_CONN_MAX_STALL < now))) {
694
695
    log_info(LD_DIR,"Expiring wedged directory conn (fd %d, purpose %d)",
             conn->s, conn->purpose);
696
697
    /* This check is temporary; it's to let us know whether we should consider
     * parsing partial serverdesc responses. */
698
    if (conn->purpose == DIR_PURPOSE_FETCH_SERVERDESC &&
699
        buf_datalen(conn->inbuf)>=1024) {
700
701
      log_info(LD_DIR,"Trying to extract information from wedged server desc "
               "download.");
702
      connection_dir_reached_eof(TO_DIR_CONN(conn));
703
704
    } else {
      connection_mark_for_close(conn);
705
    }
706
707
708
    return;
  }

709
710
711
  if (!connection_speaks_cells(conn))
    return; /* we're all done here, the rest is just for OR conns */

712
713
714
  or_conn = TO_OR_CONN(conn);

  if (!conn->or_is_obsolete) {
715
    if (conn->timestamp_created + TIME_BEFORE_OR_CONN_IS_OBSOLETE < now) {
716
717
718
719
      log_info(LD_OR,
               "Marking OR conn to %s:%d obsolete (fd %d, %d secs old).",
               conn->address, conn->port, conn->s,
               (int)(now - conn->timestamp_created));
720
      conn->or_is_obsolete = 1;
721
    } else {
722
723
724
      or_connection_t *best =
        connection_or_get_by_identity_digest(or_conn->identity_digest);
      if (best && best != or_conn &&
725
          (conn->state == OR_CONN_STATE_OPEN ||
726
           now > conn->timestamp_created + TLS_HANDSHAKE_TIMEOUT)) {
727
728
          /* We only mark as obsolete connections that already are in
           * OR_CONN_STATE_OPEN, i.e. that have finished their TLS handshaking.
729
           * This is necessary because authorities judge whether a router is
730
731
732
733
           * reachable based on whether they were able to TLS handshake with it
           * recently.  Without this check we would expire connections too
           * early for router->last_reachable to be updated.
           */
734
735
736
737
738
        log_info(LD_OR,
                 "Marking duplicate conn to %s:%d obsolete "
                 "(fd %d, %d secs old).",
                 conn->address, conn->port, conn->s,
                 (int)(now - conn->timestamp_created));
739
        conn->or_is_obsolete = 1;
740
      }
741
    }
742
743
  }

744
  if (conn->or_is_obsolete && !or_conn->n_circuits) {
745
    /* no unmarked circs -- mark it now */
746
747
    log_info(LD_OR,
             "Expiring non-used OR connection to fd %d (%s:%d) [Obsolete].",
748
             conn->s, conn->address, conn->port);
749
750
751
752
    if (conn->state == OR_CONN_STATE_CONNECTING)
      connection_or_connect_failed(TO_OR_CONN(conn),
                                   END_OR_CONN_REASON_TIMEOUT,
                                   "Tor gave up on the connection");
753
754
755
756
757
    connection_mark_for_close(conn);
    conn->hold_open_until_flushed = 1;
    return;
  }

758
759
  /* If we haven't written to an OR connection for a while, then either nuke
     the connection or send a keepalive, depending. */
760
  if (now >= conn->timestamp_lastwritten + options->KeepalivePeriod) {
761
    routerinfo_t *router = router_get_by_digest(or_conn->identity_digest);
762
    int maxCircuitlessPeriod = options->MaxCircuitDirtiness*3/2;
763
    if (!connection_state_is_open(conn)) {
764
      /* We never managed to actually get this connection open and happy. */
765
766
      log_info(LD_OR,"Expiring non-open OR connection to fd %d (%s:%d).",
               conn->s,conn->address, conn->port);
767
      connection_mark_for_close(conn);
768
      conn->hold_open_until_flushed = 1;
769
    } else if (we_are_hibernating() && !or_conn->n_circuits &&
770
               !buf_datalen(conn->outbuf)) {
771
      /* We're hibernating, there's no circuits, and nothing to flush.*/
772
773
774
      log_info(LD_OR,"Expiring non-used OR connection to fd %d (%s:%d) "
               "[Hibernating or exiting].",
               conn->s,conn->address, conn->port);
775
776
      connection_mark_for_close(conn);
      conn->hold_open_until_flushed = 1;
777
    } else if (!clique_mode(options) && !or_conn->n_circuits &&
778
779
               now >= or_conn->timestamp_last_added_nonpadding +
                                           maxCircuitlessPeriod &&
780
781
               (!router || !server_mode(options) ||
                !router_is_clique_mode(router))) {
782
783
784
      log_info(LD_OR,"Expiring non-used OR connection to fd %d (%s:%d) "
               "[Not in clique mode].",
               conn->s,conn->address, conn->port);
785
786
      connection_mark_for_close(conn);
      conn->hold_open_until_flushed = 1;
787
    } else if (
788
         now >= or_conn->timestamp_lastempty + options->KeepalivePeriod*10 &&
789
         now >= conn->timestamp_lastwritten + options->KeepalivePeriod*10) {
790
791
792
      log_fn(LOG_PROTOCOL_WARN,LD_PROTOCOL,
             "Expiring stuck OR connection to fd %d (%s:%d). (%d bytes to "
             "flush; %d seconds since last write)",
793
             conn->s, conn->address, conn->port,
794
             (int)buf_datalen(conn->outbuf),
795
             (int)(now-conn->timestamp_lastwritten));
796
      connection_mark_for_close(conn);
797
    } else if (!buf_datalen(conn->outbuf)) {
798
      /* either in clique mode, or we've got a circuit. send a padding cell. */
799
      log_fn(LOG_DEBUG,LD_OR,"Sending keepalive to (%s:%d)",
Nick Mathewson's avatar
Nick Mathewson committed
800
801
802
             conn->address, conn->port);
      memset(&cell,0,sizeof(cell_t));
      cell.command = CELL_PADDING;
803
      connection_or_write_cell_to_buf(&cell, or_conn);
Nick Mathewson's avatar
Nick Mathewson committed
804
805
806
807
    }
  }
}

808
809
810
811
812
813
814
815
816
817
818
/** Honor a NEWNYM request: make future requests unlinkability to past
 * requests. */
static void
signewnym_impl(time_t now)
{
  circuit_expire_all_dirty_circs();
  addressmap_clear_transient();
  time_of_last_signewnym = now;
  signewnym_is_pending = 0;
}

Roger Dingledine's avatar
Roger Dingledine committed
819
/** Perform regular maintenance tasks.  This function gets run once per
820
 * second by second_elapsed_callback().
Nick Mathewson's avatar
Nick Mathewson committed
821
 */
822
823
824
static void
run_scheduled_events(time_t now)
{
825
826
  static time_t last_rotated_x509_certificate = 0;
  static time_t time_to_check_v3_certificate = 0;
827
  static time_t time_to_check_listeners = 0;
828
  static time_t time_to_check_descriptor = 0;
829
  static time_t time_to_check_ipaddress = 0;
830
  static time_t time_to_shrink_memory = 0;
831
832
  static time_t time_to_try_getting_descriptors = 0;
  static time_t time_to_reset_descriptor_failures = 0;
833
  static time_t time_to_add_entropy = 0;
834
  static time_t time_to_write_hs_statistics = 0;
835
  static time_t time_to_write_bridge_status_file = 0;
836
  static time_t time_to_downrate_stability = 0;
837
  static time_t time_to_save_stability = 0;
Roger Dingledine's avatar
Roger Dingledine committed
838
  static time_t time_to_clean_caches = 0;
839
  static time_t time_to_recheck_bandwidth = 0;
840
  static time_t time_to_check_for_expired_networkstatus = 0;
841
  static time_t time_to_dump_geoip_stats = 0;
842
  static time_t time_to_retry_dns_init = 0;
843
  or_options_t *options = get_options();
Nick Mathewson's avatar
Nick Mathewson committed
844
  int i;
845
  int have_dir_info;
846

847
  /** 0. See if we've been asked to shut down and our timeout has
848
849
   * expired; or if our bandwidth limits are exhausted and we
   * should hibernate; or if it's time to wake up from hibernation.
850
   */
851
  consider_hibernation(now);
852

853
  /* 0b. If we've deferred a signewnym, make sure it gets handled
854
   * eventually. */
855
  if (signewnym_is_pending &&
856
857
      time_of_last_signewnym + MAX_SIGNEWNYM_RATE <= now) {
    log(LOG_INFO, LD_CONTROL, "Honoring delayed NEWNYM request");
858
    signewnym_impl(now);
859
860
  }

Roger Dingledine's avatar
Roger Dingledine committed
861
  /** 1a. Every MIN_ONION_KEY_LIFETIME seconds, rotate the onion keys,
862
863
864
   *  shut down and restart all cpuworkers, and update the directory if
   *  necessary.
   */
865
866
  if (server_mode(options) &&
      get_onion_key_set_at()+MIN_ONION_KEY_LIFETIME < now) {
867
    log_info(LD_GENERAL,"Rotating onion key.");
868
869
    rotate_onion_key();
    cpuworkers_rotate();
870
    if (router_rebuild_descriptor(1)<0) {
871
      log_info(LD_CONFIG, "Couldn't rebuild router descriptor");
872
    }
873
    if (advertised_server_mode())
874
      router_upload_dir_desc_to_dirservers(0);
875
876
  }

877
878
  if (time_to_try_getting_descriptors < now) {
    update_router_descriptor_downloads(now);
879
    update_extrainfo_downloads(now);
880
881
    if (options->UseBridges)
      fetch_bridge_descriptors(now);
882
883
884
885
    if (router_have_minimum_dir_info())
      time_to_try_getting_descriptors = now + LAZY_DESCRIPTOR_RETRY_INTERVAL;
    else
      time_to_try_getting_descriptors = now + GREEDY_DESCRIPTOR_RETRY_INTERVAL;
886
887
888
889
  }

  if (time_to_reset_descriptor_failures < now) {
    router_reset_descriptor_download_failures();
890
891
    time_to_reset_descriptor_failures =
      now + DESCRIPTOR_FAILURE_RESET_INTERVAL;
892
893
  }

Roger Dingledine's avatar
Roger Dingledine committed
894
  /** 1b. Every MAX_SSL_KEY_LIFETIME seconds, we change our TLS context. */
895
896
897
  if (!last_rotated_x509_certificate)
    last_rotated_x509_certificate = now;
  if (last_rotated_x509_certificate+MAX_SSL_KEY_LIFETIME < now) {
898
    log_info(LD_GENERAL,"Rotating tls context.");
899
    if (tor_tls_context_new(get_identity_key(), MAX_SSL_KEY_LIFETIME) < 0) {
900
      log_warn(LD_BUG, "Error reinitializing TLS context");
901
      /* XXX is it a bug here, that we just keep going? -RD */
902
    }
903
    last_rotated_x509_certificate = now;
904
905
906
    /* We also make sure to rotate the TLS connections themselves if they've
     * been up for too long -- but that's done via or_is_obsolete in
     * connection_run_housekeeping() above. */
907
908
  }

909
  if (time_to_add_entropy < now) {
910
911
    if (time_to_add_entropy) {
      /* We already seeded once, so don't die on failure. */