main.c 71.3 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 since we started the process? */
56
static uint64_t stats_n_bytes_read = 0;
57
/** How many bytes have we written since we started the process? */
58
static uint64_t stats_n_bytes_written = 0;
59
/** What time did this process start up? */
60
time_t time_of_process_start = 0;
Roger Dingledine's avatar
Roger Dingledine committed
61
/** How many seconds have we been running? */
62
long stats_n_seconds_working = 0;
63
64
/** When do we next launch DNS wildcarding checks? */
static time_t time_to_check_for_correct_dns = 0;
65
66
67
68
69
70
71

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

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

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

90
91
92
93
94
95
/** 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)
96
97
98
99
100
101
102
/** 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
103
104
 * too old for new circuits? */
#define TIME_BEFORE_OR_CONN_IS_TOO_OLD (60*60*24*7)
Roger Dingledine's avatar
Roger Dingledine committed
105
106
/** How long do we let OR connections handshake before we decide that
 * they are obsolete? */
107
#define TLS_HANDSHAKE_TIMEOUT (60)
108

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

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

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

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

135
  if (conn->s >= 0 || conn->linked) {
136
137
138
139
140
141
142
    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
143

Roger Dingledine's avatar
Roger Dingledine committed
144
145
  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,
146
            smartlist_len(connection_array));
Roger Dingledine's avatar
Roger Dingledine committed
147
148
149
150

  return 0;
}

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

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

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

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

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

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

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

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

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

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

Roger Dingledine's avatar
Roger Dingledine committed
242
243
244
/** 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.
245
 */
246
247
smartlist_t *
get_connection_array(void)
248
{
249
250
  if (!connection_array)
    connection_array = smartlist_create();
251
  return connection_array;
252
253
}

254
/** Set the event mask on <b>conn</b> to <b>events</b>.  (The event
255
 * mask is a bitmask whose bits are EV_READ and EV_WRITE.)
256
 */
257
258
259
void
connection_watch_events(connection_t *conn, short events)
{
260
261
262
263
264
265
266
267
268
  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
269
270
}

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

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

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

288
289
290
291
292
293
294
295
296
297
  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)));
  }
298
299
}

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

307
308
309
310
311
312
313
314
315
316
317
  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)));
  }
318
319
}

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

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

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

337
338
339
340
341
342
343
344
345
346
347
  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)));
  }
348
349
}

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

357
358
359
360
361
362
363
364
365
366
367
368
369
370
  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)));
  }
}

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

388
389
390
391
/** 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
392
393
394
395
396
397
398
399
400
401
402
403
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
404
       * lets us activate read events for linked connections. */
405
406
407
408
409
410
411
412
      struct timeval tv = { 0, 0 };
      event_loopexit(&tv);
    }
  } else {
    tor_assert(smartlist_isin(active_linked_connection_lst, conn));
  }
}

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

433
/** Close all connections that have been scheduled to get closed. */
434
435
436
437
438
439
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);
440
    if (conn->conn_array_index < 0) {
441
      connection_unlink(conn); /* blow it away right now */
442
    } else {
443
      if (!conn_close_if_marked(conn->conn_array_index))
444
445
        ++i;
    }
446
447
448
  }
}

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

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

  assert_connection_ok(conn, time(NULL));

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

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

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

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

  assert_connection_ok(conn, time(NULL));

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

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

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

612
613
614
615
616
617
/** 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.
 */
618
619
620
void
directory_all_unreachable(time_t now)
{
621
  connection_t *conn;
622
  (void)now;
623

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

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

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

647
  if (!router_have_minimum_dir_info()) {
648
    int quiet = directory_too_idle_to_fetch_descriptors(options, now);
649
    log(quiet ? LOG_INFO : LOG_NOTICE, LD_DIR,
650
        "I learned some more directory information, but not enough to "
651
        "build a circuit: %s", get_dir_info_status_string());
652
    update_router_descriptor_downloads(now);
653
    return;
654
  } else {
655
656
657
    if (directory_fetches_from_authorities(options))
      update_router_descriptor_downloads(now);

658
659
660
    /* if we have enough dir info, then update our guard status with
     * whatever we just learned. */
    entry_guards_compute_status();
661
662
663
664
    /* 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);
665
  }
666

667
  if (server_mode(options) && !we_are_hibernating() && !from_cache &&
Roger Dingledine's avatar
Roger Dingledine committed
668
      (has_completed_circuit || !any_predicted_circuits(now)))
669
    consider_testing_reachability(1, 1);
670
671
}

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

683
684
  if (conn->outbuf && !buf_datalen(conn->outbuf) && conn->type == CONN_TYPE_OR)
    TO_OR_CONN(conn)->timestamp_lastempty = now;
685

686
687
688
689
690
  if (conn->marked_for_close) {
    /* nothing to do here */
    return;
  }

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

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

716
717
  or_conn = TO_OR_CONN(conn);

718
719
  if (!or_conn->is_bad_for_new_circs) {
    if (conn->timestamp_created + TIME_BEFORE_OR_CONN_IS_TOO_OLD < now) {
720
      log_info(LD_OR,
721
722
               "Marking OR conn to %s:%d as too old for new circuits "
               "(fd %d, %d secs old).",
723
724
               conn->address, conn->port, conn->s,
               (int)(now - conn->timestamp_created));
725
      or_conn->is_bad_for_new_circs = 1;
726
    } else {
727
728
729
      or_connection_t *best =
        connection_or_get_by_identity_digest(or_conn->identity_digest);
      if (best && best != or_conn &&
730
          (conn->state == OR_CONN_STATE_OPEN ||
731
           now > conn->timestamp_created + TLS_HANDSHAKE_TIMEOUT)) {
732
733
          /* We only mark as obsolete connections that already are in
           * OR_CONN_STATE_OPEN, i.e. that have finished their TLS handshaking.
734
           * This is necessary because authorities judge whether a router is
735
736
737
738
           * 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.
           */
739
        log_info(LD_OR,
740
                 "Marking duplicate conn to %s:%d as too old for new circuits "
741
742
743
                 "(fd %d, %d secs old).",
                 conn->address, conn->port, conn->s,
                 (int)(now - conn->timestamp_created));
744
        or_conn->is_bad_for_new_circs = 1;
745
      }
746
    }
747
748
  }

749
  if (or_conn->is_bad_for_new_circs && !or_conn->n_circuits) {
750
    /* no unmarked circs -- mark it now */
751
    log_info(LD_OR,
752
             "Expiring non-used OR connection to fd %d (%s:%d) [Too old].",
753
             conn->s, conn->address, conn->port);
754
755
756
757
    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");
758
759
760
761
762
    connection_mark_for_close(conn);
    conn->hold_open_until_flushed = 1;
    return;
  }

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

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

852
  /** 0. See if we've been asked to shut down and our timeout has
853
854
   * expired; or if our bandwidth limits are exhausted and we
   * should hibernate; or if it's time to wake up from hibernation.
855
   */
856
  consider_hibernation(now);
857

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

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

882
883
  if (time_to_try_getting_descriptors < now) {
    update_router_descriptor_downloads(now);
884
    update_extrainfo_downloads(now);
885
886
    if (options->UseBridges)
      fetch_bridge_descriptors(now);
887
888
889
890
    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;
891
892
893
894
  }

  if (time_to_reset_descriptor_failures < now) {
    router_reset_descriptor_download_failures();
895
896
    time_to_reset_descriptor_failures =
      now + DESCRIPTOR_FAILURE_RESET_INTERVAL;
897
898
  }

Roger Dingledine's avatar
Roger Dingledine committed
899
  /** 1b. Every MAX_SSL_KEY_LIFETIME seconds, we change our TLS context. */