Make new logging stuff work on windows; fix a couple of windows typos.
[tor.git] / src / or / main.c
blob013965db776b08e363e6bcc18fd2edbf603490c3
1 /* Copyright 2001 Matej Pfajfar.
2 * Copyright 2001-2004 Roger Dingledine.
3 * Copyright 2004-2005 Roger Dingledine, Nick Mathewson. */
4 /* See LICENSE for licensing information */
5 /* $Id$ */
6 const char main_c_id[] = "$Id$";
8 /**
9 * \file main.c
10 * \brief Toplevel module. Handles signals, multiplexes between
11 * connections, implements main loop, and drives scheduled events.
12 **/
14 #include "or.h"
15 #ifdef USE_DMALLOC
16 #include <dmalloc.h>
17 #endif
19 /********* PROTOTYPES **********/
21 static void dumpmemusage(int severity);
22 static void dumpstats(int severity); /* log stats */
23 static void conn_read_callback(int fd, short event, void *_conn);
24 static void conn_write_callback(int fd, short event, void *_conn);
25 static void signal_callback(int fd, short events, void *arg);
26 static void second_elapsed_callback(int fd, short event, void *args);
27 static int conn_close_if_marked(int i);
29 /********* START VARIABLES **********/
31 int global_read_bucket; /**< Max number of bytes I can read this second. */
32 int global_write_bucket; /**< Max number of bytes I can write this second. */
34 /** What was the read bucket before the last call to prepare_for_pool?
35 * (used to determine how many bytes we've read). */
36 static int stats_prev_global_read_bucket;
37 /** What was the write bucket before the last call to prepare_for_pool?
38 * (used to determine how many bytes we've written). */
39 static int stats_prev_global_write_bucket;
40 /** How many bytes have we read/written since we started the process? */
41 static uint64_t stats_n_bytes_read = 0;
42 static uint64_t stats_n_bytes_written = 0;
43 /** What time did this process start up? */
44 long time_of_process_start = 0;
45 /** How many seconds have we been running? */
46 long stats_n_seconds_working = 0;
47 /** When do we next download a directory? */
48 static time_t time_to_fetch_directory = 0;
49 /** When do we next download a running-routers summary? */
50 static time_t time_to_fetch_running_routers = 0;
52 /** Array of all open connections; each element corresponds to the element of
53 * poll_array in the same position. The first nfds elements are valid. */
54 static connection_t *connection_array[MAXCONNECTIONS+1] =
55 { NULL };
56 static smartlist_t *closeable_connection_lst = NULL;
58 static int nfds=0; /**< Number of connections currently active. */
60 /** We set this to 1 when we've fetched a dir, to know whether to complain
61 * yet about unrecognized nicknames in entrynodes, exitnodes, etc.
62 * Also, we don't try building circuits unless this is 1. */
63 int has_fetched_directory=0;
65 /** We set this to 1 when we've opened a circuit, so we can print a log
66 * entry to inform the user that Tor is working. */
67 int has_completed_circuit=0;
69 #ifdef MS_WINDOWS
70 #define MS_WINDOWS_SERVICE
71 #endif
73 #ifdef MS_WINDOWS_SERVICE
74 #include <tchar.h>
75 #define GENSRV_SERVICENAME TEXT("tor")
76 #define GENSRV_DISPLAYNAME TEXT("Tor Win32 Service")
77 #define GENSRV_DESCRIPTION TEXT("Provides an anonymous Internet communication system")
79 // Cheating: using the pre-defined error codes, tricks Windows into displaying
80 // a semi-related human-readable error message if startup fails as
81 // opposed to simply scaring people with Error: 0xffffffff
82 #define NT_SERVICE_ERROR_NO_TORRC ERROR_FILE_NOT_FOUND
83 #define NT_SERVICE_ERROR_TORINIT_FAILED ERROR_EXCEPTION_IN_SERVICE
85 SERVICE_STATUS service_status;
86 SERVICE_STATUS_HANDLE hStatus;
87 static char **backup_argv;
88 static int backup_argc;
89 static int nt_service_is_stopped(void);
90 static char* nt_strerror(uint32_t errnum);
91 #else
92 #define nt_service_is_stopped() (0)
93 #endif
95 #define FORCE_REGENERATE_DESCRIPTOR_INTERVAL 18*60*60 /* 18 hours */
96 #define CHECK_DESCRIPTOR_INTERVAL 60 /* one minute */
97 #define CHECK_IPADDRESS_INTERVAL (5*60) /* five minutes */
98 #define BUF_SHRINK_INTERVAL 60 /* one minute */
99 #define DESCRIPTOR_RETRY_INTERVAL 10
100 #define DESCRIPTOR_FAILURE_RESET_INTERVAL 60*60
101 #define TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT (20*60) /* 20 minutes */
102 #define ENTROPY_INTERVAL 60*60
104 /********* END VARIABLES ************/
106 /****************************************************************************
108 * This section contains accessors and other methods on the connection_array
109 * and poll_array variables (which are global within this file and unavailable
110 * outside it).
112 ****************************************************************************/
114 /** Add <b>conn</b> to the array of connections that we can poll on. The
115 * connection's socket must be set; the connection starts out
116 * non-reading and non-writing.
119 connection_add(connection_t *conn)
121 tor_assert(conn);
122 tor_assert(conn->s >= 0);
124 if (nfds >= get_options()->_ConnLimit-1) {
125 warn(LD_NET,"Failing because we have %d connections already. Please raise your ulimit -n.", nfds);
126 return -1;
129 tor_assert(conn->poll_index == -1); /* can only connection_add once */
130 conn->poll_index = nfds;
131 connection_array[nfds] = conn;
133 conn->read_event = tor_malloc_zero(sizeof(struct event));
134 conn->write_event = tor_malloc_zero(sizeof(struct event));
135 event_set(conn->read_event, conn->s, EV_READ|EV_PERSIST,
136 conn_read_callback, conn);
137 event_set(conn->write_event, conn->s, EV_WRITE|EV_PERSIST,
138 conn_write_callback, conn);
140 nfds++;
142 debug(LD_NET,"new conn type %s, socket %d, nfds %d.",
143 conn_type_to_string(conn->type), conn->s, nfds);
145 return 0;
148 /** Remove the connection from the global list, and remove the
149 * corresponding poll entry. Calling this function will shift the last
150 * connection (if any) into the position occupied by conn.
153 connection_remove(connection_t *conn)
155 int current_index;
157 tor_assert(conn);
158 tor_assert(nfds>0);
160 debug(LD_NET,"removing socket %d (type %s), nfds now %d",
161 conn->s, conn_type_to_string(conn->type), nfds-1);
163 tor_assert(conn->poll_index >= 0);
164 current_index = conn->poll_index;
165 if (current_index == nfds-1) { /* this is the end */
166 nfds--;
167 return 0;
170 connection_unregister(conn);
172 /* replace this one with the one at the end */
173 nfds--;
174 connection_array[current_index] = connection_array[nfds];
175 connection_array[current_index]->poll_index = current_index;
177 return 0;
180 /** If it's an edge conn, remove it from the list
181 * of conn's on this circuit. If it's not on an edge,
182 * flush and send destroys for all circuits on this conn.
184 * If <b>remove</b> is non-zero, then remove it from the
185 * connection_array and closeable_connection_lst.
187 * Then free it.
189 static void
190 connection_unlink(connection_t *conn, int remove)
192 circuit_about_to_close_connection(conn);
193 connection_about_to_close_connection(conn);
194 if (remove) {
195 connection_remove(conn);
197 smartlist_remove(closeable_connection_lst, conn);
198 if (conn->type == CONN_TYPE_EXIT) {
199 assert_connection_edge_not_dns_pending(conn);
201 connection_free(conn);
204 /** Schedule <b>conn</b> to be closed. **/
205 void
206 add_connection_to_closeable_list(connection_t *conn)
208 tor_assert(!smartlist_isin(closeable_connection_lst, conn));
209 tor_assert(conn->marked_for_close);
210 assert_connection_ok(conn, time(NULL));
211 smartlist_add(closeable_connection_lst, conn);
214 /** Return 1 if conn is on the closeable list, else return 0. */
216 connection_is_on_closeable_list(connection_t *conn)
218 return smartlist_isin(closeable_connection_lst, conn);
221 /** Return true iff conn is in the current poll array. */
223 connection_in_array(connection_t *conn)
225 int i;
226 for (i=0; i<nfds; ++i) {
227 if (conn==connection_array[i])
228 return 1;
230 return 0;
233 /** Set <b>*array</b> to an array of all connections, and <b>*n</b>
234 * to the length of the array. <b>*array</b> and <b>*n</b> must not
235 * be modified.
237 void
238 get_connection_array(connection_t ***array, int *n)
240 *array = connection_array;
241 *n = nfds;
244 /** Set the event mask on <b>conn</b> to <b>events</b>. (The event
245 * mask is a bitmask whose bits are EV_READ and EV_WRITE.)
247 void
248 connection_watch_events(connection_t *conn, short events)
250 int r;
252 tor_assert(conn);
253 tor_assert(conn->read_event);
254 tor_assert(conn->write_event);
256 if (events & EV_READ) {
257 r = event_add(conn->read_event, NULL);
258 } else {
259 r = event_del(conn->read_event);
262 if (r<0)
263 warn(LD_NET,
264 "Error from libevent setting read event state for %d to %swatched.",
265 conn->s, (events & EV_READ)?"":"un");
267 if (events & EV_WRITE) {
268 r = event_add(conn->write_event, NULL);
269 } else {
270 r = event_del(conn->write_event);
273 if (r<0)
274 warn(LD_NET,
275 "Error from libevent setting read event state for %d to %swatched.",
276 conn->s, (events & EV_WRITE)?"":"un");
279 /** Return true iff <b>conn</b> is listening for read events. */
281 connection_is_reading(connection_t *conn)
283 tor_assert(conn);
285 return conn->read_event && event_pending(conn->read_event, EV_READ, NULL);
288 /** Tell the main loop to stop notifying <b>conn</b> of any read events. */
289 void
290 connection_stop_reading(connection_t *conn)
292 tor_assert(conn);
293 tor_assert(conn->read_event);
295 debug(LD_NET,"connection_stop_reading() called.");
296 if (event_del(conn->read_event))
297 warn(LD_NET, "Error from libevent setting read event state for %d to unwatched.",
298 conn->s);
301 /** Tell the main loop to start notifying <b>conn</b> of any read events. */
302 void
303 connection_start_reading(connection_t *conn)
305 tor_assert(conn);
306 tor_assert(conn->read_event);
308 if (event_add(conn->read_event, NULL))
309 warn(LD_NET, "Error from libevent setting read event state for %d to watched.",
310 conn->s);
313 /** Return true iff <b>conn</b> is listening for write events. */
315 connection_is_writing(connection_t *conn)
317 tor_assert(conn);
319 return conn->write_event && event_pending(conn->write_event, EV_WRITE, NULL);
322 /** Tell the main loop to stop notifying <b>conn</b> of any write events. */
323 void
324 connection_stop_writing(connection_t *conn)
326 tor_assert(conn);
327 tor_assert(conn->write_event);
329 if (event_del(conn->write_event))
330 warn(LD_NET, "Error from libevent setting write event state for %d to unwatched.",
331 conn->s);
335 /** Tell the main loop to start notifying <b>conn</b> of any write events. */
336 void
337 connection_start_writing(connection_t *conn)
339 tor_assert(conn);
340 tor_assert(conn->write_event);
342 if (event_add(conn->write_event, NULL))
343 warn(LD_NET, "Error from libevent setting write event state for %d to watched.",
344 conn->s);
347 /** Close all connections that have been scheduled to get closed */
348 static void
349 close_closeable_connections(void)
351 int i;
352 for (i = 0; i < smartlist_len(closeable_connection_lst); ) {
353 connection_t *conn = smartlist_get(closeable_connection_lst, i);
354 if (conn->poll_index < 0) {
355 connection_unlink(conn, 0); /* blow it away right now */
356 } else {
357 if (!conn_close_if_marked(conn->poll_index))
358 ++i;
363 /** Libevent callback: this gets invoked when (connection_t*)<b>conn</b> has
364 * some data to read. */
365 static void
366 conn_read_callback(int fd, short event, void *_conn)
368 connection_t *conn = _conn;
370 debug(LD_NET,"socket %d wants to read.",conn->s);
372 assert_connection_ok(conn, time(NULL));
374 if (connection_handle_read(conn) < 0) {
375 if (!conn->marked_for_close) {
376 #ifndef MS_WINDOWS
377 warn(LD_BUG,"Bug: unhandled error on read for %s connection (fd %d); removing",
378 conn_type_to_string(conn->type), conn->s);
379 tor_fragile_assert();
380 #endif
381 if (CONN_IS_EDGE(conn))
382 connection_edge_end_errno(conn, conn->cpath_layer);
383 connection_mark_for_close(conn);
386 assert_connection_ok(conn, time(NULL));
388 if (smartlist_len(closeable_connection_lst))
389 close_closeable_connections();
392 /** Libevent callback: this gets invoked when (connection_t*)<b>conn</b> has
393 * some data to write. */
394 static void
395 conn_write_callback(int fd, short events, void *_conn)
397 connection_t *conn = _conn;
399 LOG_FN_CONN(conn, (LOG_DEBUG, LD_NET, "socket %d wants to write.",conn->s));
401 assert_connection_ok(conn, time(NULL));
403 if (connection_handle_write(conn) < 0) {
404 if (!conn->marked_for_close) {
405 /* this connection is broken. remove it. */
406 log_fn(LOG_WARN,LD_BUG,"Bug: unhandled error on write for %s connection (fd %d); removing",
407 conn_type_to_string(conn->type), conn->s);
408 tor_fragile_assert();
409 conn->has_sent_end = 1; /* otherwise we cry wolf about duplicate close */
410 /* XXX do we need a close-immediate here, so we don't try to flush? */
411 connection_mark_for_close(conn);
414 assert_connection_ok(conn, time(NULL));
416 if (smartlist_len(closeable_connection_lst))
417 close_closeable_connections();
420 /** If the connection at connection_array[i] is marked for close, then:
421 * - If it has data that it wants to flush, try to flush it.
422 * - If it _still_ has data to flush, and conn->hold_open_until_flushed is
423 * true, then leave the connection open and return.
424 * - Otherwise, remove the connection from connection_array and from
425 * all other lists, close it, and free it.
426 * Returns 1 if the connection was closed, 0 otherwise.
428 static int
429 conn_close_if_marked(int i)
431 connection_t *conn;
432 int retval;
434 conn = connection_array[i];
435 if (!conn->marked_for_close)
436 return 0; /* nothing to see here, move along */
437 assert_connection_ok(conn, time(NULL));
438 assert_all_pending_dns_resolves_ok();
440 debug(LD_NET,"Cleaning up connection (fd %d).",conn->s);
441 if (conn->s >= 0 && connection_wants_to_flush(conn)) {
442 /* s == -1 means it's an incomplete edge connection, or that the socket
443 * has already been closed as unflushable. */
444 int sz = connection_bucket_write_limit(conn);
445 if (!conn->hold_open_until_flushed)
446 info(LD_NET,
447 "Conn (addr %s, fd %d, type %s, state %d) marked, but wants to flush %d bytes. "
448 "(Marked at %s:%d)",
449 conn->address, conn->s, conn_type_to_string(conn->type), conn->state,
450 (int)conn->outbuf_flushlen, conn->marked_for_close_file, conn->marked_for_close);
451 if (connection_speaks_cells(conn)) {
452 if (conn->state == OR_CONN_STATE_OPEN) {
453 retval = flush_buf_tls(conn->tls, conn->outbuf, sz, &conn->outbuf_flushlen);
454 } else
455 retval = -1; /* never flush non-open broken tls connections */
456 } else {
457 retval = flush_buf(conn->s, conn->outbuf, sz, &conn->outbuf_flushlen);
459 if (retval >= 0 && /* Technically, we could survive things like
460 TLS_WANT_WRITE here. But don't bother for now. */
461 conn->hold_open_until_flushed && connection_wants_to_flush(conn)) {
462 LOG_FN_CONN(conn,
463 (LOG_INFO,LD_NET,"Holding conn (fd %d) open for more flushing.",conn->s));
464 /* XXX should we reset timestamp_lastwritten here? */
465 return 0;
467 if (connection_wants_to_flush(conn)) {
468 int severity;
469 if (conn->type == CONN_TYPE_EXIT ||
470 (conn->type == CONN_TYPE_DIR && conn->purpose == DIR_PURPOSE_SERVER))
471 severity = LOG_INFO;
472 else
473 severity = LOG_NOTICE;
474 log_fn(severity, LD_NET, "Something wrong with your network connection? Conn (addr %s, fd %d, type %s, state %d) tried to write %d bytes but timed out. (Marked at %s:%d)",
475 safe_str(conn->address), conn->s, conn_type_to_string(conn->type),
476 conn->state,
477 (int)buf_datalen(conn->outbuf), conn->marked_for_close_file,
478 conn->marked_for_close);
481 connection_unlink(conn, 1); /* unlink, remove, free */
482 return 1;
485 /** We've just tried every dirserver we know about, and none of
486 * them were reachable. Assume the network is down. Change state
487 * so next time an application connection arrives we'll delay it
488 * and try another directory fetch. Kill off all the circuit_wait
489 * streams that are waiting now, since they will all timeout anyway.
491 void
492 directory_all_unreachable(time_t now)
494 connection_t *conn;
495 /* XXXX011 NM Update this to reflect new directories? */
497 has_fetched_directory=0;
498 stats_n_seconds_working=0; /* reset it */
500 while ((conn = connection_get_by_type_state(CONN_TYPE_AP,
501 AP_CONN_STATE_CIRCUIT_WAIT))) {
502 notice(LD_NET,"Network down? Failing connection to '%s:%d'.",
503 safe_str(conn->socks_request->address), conn->socks_request->port);
504 connection_mark_unattached_ap(conn, END_STREAM_REASON_NET_UNREACHABLE);
509 * Return the interval to wait betweeen directory downloads, in seconds.
511 static INLINE int
512 get_dir_fetch_period(or_options_t *options)
514 if (options->DirFetchPeriod)
515 /* Value from config file. */
516 return options->DirFetchPeriod;
517 else if (options->DirPort)
518 /* Default for directory server */
519 return 20*60;
520 else
521 /* Default for average user. */
522 return 40*60;
526 * Return the interval to wait betweeen router status downloads, in seconds.
528 static INLINE int
529 get_status_fetch_period(or_options_t *options)
531 if (options->StatusFetchPeriod)
532 /* Value from config file. */
533 return options->StatusFetchPeriod;
534 else if (options->DirPort)
535 /* Default for directory server */
536 return 15*60;
537 else
538 /* Default for average user. */
539 return 30*60;
542 /** This function is called whenever we successfully pull down some new
543 * network statuses or server descriptors. */
544 void
545 directory_info_has_arrived(time_t now, int from_cache)
547 or_options_t *options = get_options();
549 if (!router_have_minimum_dir_info()) {
550 log(LOG_NOTICE, LD_DIR, "I learned some more directory information, but not enough to build a circuit.");
551 return;
554 if (!has_fetched_directory) {
555 log(LOG_NOTICE, LD_DIR, "We have enough directory information to build circuits.");
558 has_fetched_directory=1;
560 if (server_mode(options) &&
561 !we_are_hibernating()) { /* connect to the appropriate routers */
562 if (!authdir_mode(options))
563 router_retry_connections(0);
564 if (!from_cache)
565 consider_testing_reachability();
569 /** Perform regular maintenance tasks for a single connection. This
570 * function gets run once per second per connection by run_scheduled_events.
572 static void
573 run_connection_housekeeping(int i, time_t now)
575 cell_t cell;
576 connection_t *conn = connection_array[i];
577 or_options_t *options = get_options();
579 if (conn->outbuf && !buf_datalen(conn->outbuf))
580 conn->timestamp_lastempty = now;
582 /* Expire any directory connections that haven't sent anything for 5 min */
583 if (conn->type == CONN_TYPE_DIR &&
584 !conn->marked_for_close &&
585 conn->timestamp_lastwritten + 5*60 < now) {
586 info(LD_DIR,"Expiring wedged directory conn (fd %d, purpose %d)",
587 conn->s, conn->purpose);
588 /* This check is temporary; it's to let us know whether we should consider
589 * parsing partial serverdesc responses. */
590 if (conn->purpose == DIR_PURPOSE_FETCH_SERVERDESC &&
591 buf_datalen(conn->inbuf)>=1024) {
592 info(LD_DIR,"Trying to extract information from wedged server desc download.");
593 connection_dir_reached_eof(conn);
594 } else {
595 connection_mark_for_close(conn);
597 return;
600 /* If we haven't written to an OR connection for a while, then either nuke
601 the connection or send a keepalive, depending. */
602 if (connection_speaks_cells(conn) &&
603 now >= conn->timestamp_lastwritten + options->KeepalivePeriod) {
604 routerinfo_t *router = router_get_by_digest(conn->identity_digest);
605 if (!connection_state_is_open(conn)) {
606 info(LD_OR,"Expiring non-open OR connection to fd %d (%s:%d).",
607 conn->s,conn->address, conn->port);
608 connection_mark_for_close(conn);
609 conn->hold_open_until_flushed = 1;
610 } else if (we_are_hibernating() && !circuit_get_by_conn(conn) &&
611 !buf_datalen(conn->outbuf)) {
612 info(LD_OR,"Expiring non-used OR connection to fd %d (%s:%d) [Hibernating or exiting].",
613 conn->s,conn->address, conn->port);
614 connection_mark_for_close(conn);
615 conn->hold_open_until_flushed = 1;
616 } else if (!clique_mode(options) && !circuit_get_by_conn(conn) &&
617 (!router || !server_mode(options) || !router_is_clique_mode(router))) {
618 info(LD_OR,"Expiring non-used OR connection to fd %d (%s:%d) [Not in clique mode].",
619 conn->s,conn->address, conn->port);
620 connection_mark_for_close(conn);
621 conn->hold_open_until_flushed = 1;
622 } else if (
623 now >= conn->timestamp_lastempty + options->KeepalivePeriod*10 &&
624 now >= conn->timestamp_lastwritten + options->KeepalivePeriod*10) {
625 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)",
626 conn->s, conn->address, conn->port,
627 (int)buf_datalen(conn->outbuf),
628 (int)(now-conn->timestamp_lastwritten));
629 connection_mark_for_close(conn);
630 } else if (!buf_datalen(conn->outbuf)) {
631 /* either in clique mode, or we've got a circuit. send a padding cell. */
632 log_fn(LOG_DEBUG,LD_OR,"Sending keepalive to (%s:%d)",
633 conn->address, conn->port);
634 memset(&cell,0,sizeof(cell_t));
635 cell.command = CELL_PADDING;
636 connection_or_write_cell_to_buf(&cell, conn);
641 /** Perform regular maintenance tasks. This function gets run once per
642 * second by prepare_for_poll.
644 static void
645 run_scheduled_events(time_t now)
647 static time_t last_rotated_certificate = 0;
648 static time_t time_to_check_listeners = 0;
649 static time_t time_to_check_descriptor = 0;
650 static time_t time_to_check_ipaddress = 0;
651 static time_t time_to_shrink_buffers = 0;
652 static time_t time_to_try_getting_descriptors = 0;
653 static time_t time_to_reset_descriptor_failures = 0;
654 static time_t time_to_add_entropy = 0;
655 or_options_t *options = get_options();
656 int i;
658 /** 0. See if we've been asked to shut down and our timeout has
659 * expired; or if our bandwidth limits are exhausted and we
660 * should hibernate; or if it's time to wake up from hibernation.
662 consider_hibernation(now);
664 /** 1a. Every MIN_ONION_KEY_LIFETIME seconds, rotate the onion keys,
665 * shut down and restart all cpuworkers, and update the directory if
666 * necessary.
668 if (server_mode(options) &&
669 get_onion_key_set_at()+MIN_ONION_KEY_LIFETIME < now) {
670 info(LD_GENERAL,"Rotating onion key.");
671 rotate_onion_key();
672 cpuworkers_rotate();
673 if (router_rebuild_descriptor(1)<0) {
674 warn(LD_BUG, "Couldn't rebuild router descriptor");
676 if (advertised_server_mode())
677 router_upload_dir_desc_to_dirservers(0);
680 if (time_to_try_getting_descriptors < now) {
681 update_router_descriptor_downloads(now);
682 time_to_try_getting_descriptors = now + DESCRIPTOR_RETRY_INTERVAL;
685 if (time_to_reset_descriptor_failures < now) {
686 router_reset_descriptor_download_failures();
687 time_to_reset_descriptor_failures = now + DESCRIPTOR_FAILURE_RESET_INTERVAL;
690 /** 1b. Every MAX_SSL_KEY_LIFETIME seconds, we change our TLS context. */
691 if (!last_rotated_certificate)
692 last_rotated_certificate = now;
693 if (last_rotated_certificate+MAX_SSL_KEY_LIFETIME < now) {
694 info(LD_GENERAL,"Rotating tls context.");
695 if (tor_tls_context_new(get_identity_key(), 1, options->Nickname,
696 MAX_SSL_KEY_LIFETIME) < 0) {
697 warn(LD_BUG, "Error reinitializing TLS context");
698 /* XXX is it a bug here, that we just keep going? */
700 last_rotated_certificate = now;
701 /* XXXX We should rotate TLS connections as well; this code doesn't change
702 * them at all. */
705 if (time_to_add_entropy == 0)
706 time_to_add_entropy = now + ENTROPY_INTERVAL;
707 if (time_to_add_entropy < now) {
708 /* We already seeded once, so don't die on failure. */
709 crypto_seed_rng();
710 time_to_add_entropy = now + ENTROPY_INTERVAL;
713 /** 1c. If we have to change the accounting interval or record
714 * bandwidth used in this accounting interval, do so. */
715 if (accounting_is_enabled(options))
716 accounting_run_housekeeping(now);
718 /** 2. Periodically, we consider getting a new directory, getting a
719 * new running-routers list, and/or force-uploading our descriptor
720 * (if we've passed our internal checks). */
721 if (time_to_fetch_directory < now) {
722 /* purge obsolete entries */
723 routerlist_remove_old_routers();
724 networkstatus_list_clean(now);
726 if (authdir_mode(options)) {
727 if (!we_are_hibernating()) { /* try to determine reachability */
728 router_retry_connections(1);
732 /* Only caches actually need to fetch directories now. */
733 if (options->DirPort && !options->V1AuthoritativeDir) {
734 directory_get_from_dirserver(DIR_PURPOSE_FETCH_DIR, NULL, 1);
737 time_to_fetch_directory = now + get_dir_fetch_period(options);
739 /* Also, take this chance to remove old information from rephist
740 * and the rend cache. */
741 rep_history_clean(now - options->RephistTrackTime);
742 rend_cache_clean();
745 /* Caches need to fetch running_routers; directory clients don't. */
746 if (options->DirPort && time_to_fetch_running_routers < now) {
747 if (!authdir_mode(options) || !options->V1AuthoritativeDir) {
748 directory_get_from_dirserver(DIR_PURPOSE_FETCH_RUNNING_LIST, NULL, 1);
750 time_to_fetch_running_routers = now + get_status_fetch_period(options);
753 /* 2b. Once per minute, regenerate and upload the descriptor if the old
754 * one is inaccurate. */
755 if (time_to_check_descriptor < now) {
756 time_to_check_descriptor = now + CHECK_DESCRIPTOR_INTERVAL;
757 check_descriptor_bandwidth_changed(now);
758 if (time_to_check_ipaddress < now) {
759 time_to_check_ipaddress = now + CHECK_IPADDRESS_INTERVAL;
760 check_descriptor_ipaddress_changed(now);
762 mark_my_descriptor_dirty_if_older_than(
763 now - FORCE_REGENERATE_DESCRIPTOR_INTERVAL);
764 consider_publishable_server(now, 0);
765 /* also, check religiously for reachability, if it's within the first
766 * 20 minutes of our uptime. */
767 if (server_mode(options) &&
768 stats_n_seconds_working < TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT &&
769 !we_are_hibernating())
770 consider_testing_reachability();
772 /* If any networkstatus documents are no longer recent, we need to
773 * update all the descriptors' running status. */
774 networkstatus_list_update_recent(now);
775 routers_update_all_from_networkstatus();
777 /* Also, once per minute, check whether we want to download any
778 * networkstatus documents.
780 update_networkstatus_downloads(now);
783 /** 3a. Every second, we examine pending circuits and prune the
784 * ones which have been pending for more than a few seconds.
785 * We do this before step 4, so it can try building more if
786 * it's not comfortable with the number of available circuits.
788 circuit_expire_building(now);
790 /** 3b. Also look at pending streams and prune the ones that 'began'
791 * a long time ago but haven't gotten a 'connected' yet.
792 * Do this before step 4, so we can put them back into pending
793 * state to be picked up by the new circuit.
795 connection_ap_expire_beginning();
797 /** 3c. And expire connections that we've held open for too long.
799 connection_expire_held_open();
801 /** 3d. And every 60 seconds, we relaunch listeners if any died. */
802 if (!we_are_hibernating() && time_to_check_listeners < now) {
803 /* 0 means "only launch the ones that died." */
804 retry_all_listeners(0, NULL, NULL);
805 time_to_check_listeners = now+60;
808 /** 4. Every second, we try a new circuit if there are no valid
809 * circuits. Every NewCircuitPeriod seconds, we expire circuits
810 * that became dirty more than MaxCircuitDirtiness seconds ago,
811 * and we make a new circ if there are no clean circuits.
813 if (has_fetched_directory && !we_are_hibernating())
814 circuit_build_needed_circs(now);
816 /** 5. We do housekeeping for each connection... */
817 for (i=0;i<nfds;i++) {
818 run_connection_housekeeping(i, now);
820 if (time_to_shrink_buffers < now) {
821 for (i=0;i<nfds;i++) {
822 connection_t *conn = connection_array[i];
823 if (conn->outbuf)
824 buf_shrink(conn->outbuf);
825 if (conn->inbuf)
826 buf_shrink(conn->inbuf);
828 time_to_shrink_buffers = now + BUF_SHRINK_INTERVAL;
831 /** 6. And remove any marked circuits... */
832 circuit_close_all_marked();
834 /** 7. And upload service descriptors if necessary. */
835 if (has_fetched_directory && !we_are_hibernating())
836 rend_consider_services_upload(now);
838 /** 8. and blow away any connections that need to die. have to do this now,
839 * because if we marked a conn for close and left its socket -1, then
840 * we'll pass it to poll/select and bad things will happen.
842 close_closeable_connections();
845 static struct event *timeout_event = NULL;
846 static int n_libevent_errors = 0;
848 /** Libevent callback: invoked once every second. */
849 static void
850 second_elapsed_callback(int fd, short event, void *args)
852 static struct timeval one_second;
853 static long current_second = 0;
854 struct timeval now;
855 size_t bytes_written;
856 size_t bytes_read;
857 int seconds_elapsed;
858 or_options_t *options = get_options();
859 if (!timeout_event) {
860 timeout_event = tor_malloc_zero(sizeof(struct event));
861 evtimer_set(timeout_event, second_elapsed_callback, NULL);
862 one_second.tv_sec = 1;
863 one_second.tv_usec = 0;
866 n_libevent_errors = 0;
868 /* log_fn(LOG_NOTICE, "Tick."); */
869 tor_gettimeofday(&now);
871 /* the second has rolled over. check more stuff. */
872 bytes_written = stats_prev_global_write_bucket - global_write_bucket;
873 bytes_read = stats_prev_global_read_bucket - global_read_bucket;
874 /* XXX below we get suspicious if time jumps forward more than 10
875 * seconds, but we never notice if it jumps *back* more than 10 seconds.
876 * This could be useful for detecting that we just NTP'ed to three
877 * weeks ago and it will be 3 weeks and 15 minutes until any of our
878 * events trigger.
880 seconds_elapsed = current_second ? (now.tv_sec - current_second) : 0;
881 stats_n_bytes_read += bytes_read;
882 stats_n_bytes_written += bytes_written;
883 if (accounting_is_enabled(options))
884 accounting_add_bytes(bytes_read, bytes_written, seconds_elapsed);
885 control_event_bandwidth_used((uint32_t)bytes_read,(uint32_t)bytes_written);
887 connection_bucket_refill(&now);
888 stats_prev_global_read_bucket = global_read_bucket;
889 stats_prev_global_write_bucket = global_write_bucket;
891 if (server_mode(options) &&
892 !we_are_hibernating() &&
893 stats_n_seconds_working / TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT !=
894 (stats_n_seconds_working+seconds_elapsed) /
895 TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT) {
896 /* every 20 minutes, check and complain if necessary */
897 routerinfo_t *me = router_get_my_routerinfo();
898 if (me && !check_whether_orport_reachable())
899 warn(LD_CONFIG,"Your server (%s:%d) has not managed to confirm that its ORPort is reachable. Please check your firewalls, ports, address, /etc/hosts file, etc.",
900 me->address, me->or_port);
901 if (me && !check_whether_dirport_reachable())
902 warn(LD_CONFIG,"Your server (%s:%d) has not managed to confirm that its DirPort is reachable. Please check your firewalls, ports, address, /etc/hosts file, etc.",
903 me->address, me->dir_port);
906 /* if more than 100s have elapsed, probably the clock jumped: doesn't count. */
907 if (seconds_elapsed < 100)
908 stats_n_seconds_working += seconds_elapsed;
909 else
910 circuit_note_clock_jumped(seconds_elapsed);
912 run_scheduled_events(now.tv_sec);
914 current_second = now.tv_sec; /* remember which second it is, for next time */
916 #if 0
917 if (current_second % 300 == 0) {
918 rep_history_clean(current_second - options->RephistTrackTime);
919 dumpmemusage(get_min_log_level()<LOG_INFO ? get_min_log_level() : LOG_INFO);
921 #endif
923 if (evtimer_add(timeout_event, &one_second))
924 err(LD_NET,
925 "Error from libevent when setting one-second timeout event");
928 /** Called when a possibly ignorable libevent error occurs; ensures that we
929 * don't get into an infinite loop by ignoring too many errors from
930 * libevent. */
931 static int
932 got_libevent_error(void)
934 if (++n_libevent_errors > 8) {
935 err(LD_NET, "Too many libevent errors in one second; dying");
936 return -1;
938 return 0;
941 /** Called when we get a SIGHUP: reload configuration files and keys,
942 * retry all connections, re-upload all descriptors, and so on. */
943 static int
944 do_hup(void)
946 char keydir[512];
947 or_options_t *options = get_options();
949 notice(LD_GENERAL,"Received sighup. Reloading config.");
950 has_completed_circuit=0;
951 if (accounting_is_enabled(options))
952 accounting_record_bandwidth_usage(time(NULL));
954 router_reset_warnings();
955 routerlist_reset_warnings();
956 addressmap_clear_transient();
957 /* first, reload config variables, in case they've changed */
958 /* no need to provide argc/v, they've been cached inside init_from_config */
959 if (options_init_from_torrc(0, NULL) < 0) {
960 err(LD_CONFIG,"Reading config failed--see warnings above. For usage, try -h.");
961 return -1;
963 options = get_options(); /* they have changed now */
964 if (authdir_mode(options)) {
965 /* reload the approved-routers file */
966 tor_snprintf(keydir,sizeof(keydir),"%s/approved-routers", options->DataDirectory);
967 info(LD_GENERAL,"Reloading approved fingerprints from \"%s\"...",keydir);
968 if (dirserv_parse_fingerprint_file(keydir) < 0) {
969 info(LD_GENERAL, "Error reloading fingerprints. Continuing with old list.");
973 /* Rotate away from the old dirty circuits. This has to be done
974 * after we've read the new options, but before we start using
975 * circuits for directory fetches. */
976 circuit_expire_all_dirty_circs();
978 /* retry appropriate downloads */
979 router_reset_status_download_failures();
980 router_reset_descriptor_download_failures();
981 update_networkstatus_downloads(time(NULL));
983 /* We'll retry routerstatus downloads in about 10 seconds; no need to
984 * force a retry there. */
986 if (server_mode(options)) {
987 const char *descriptor;
988 /* Restart cpuworker and dnsworker processes, so they get up-to-date
989 * configuration options. */
990 cpuworkers_rotate();
991 dnsworkers_rotate();
992 /* Write out a fresh descriptor, but leave old one on failure. */
993 router_rebuild_descriptor(1);
994 descriptor = router_get_my_descriptor();
995 if (descriptor) {
996 tor_snprintf(keydir,sizeof(keydir),"%s/router.desc",
997 options->DataDirectory);
998 info(LD_OR,"Saving descriptor to \"%s\"...",keydir);
999 if (write_str_to_file(keydir, descriptor, 0)) {
1000 return 0;
1004 return 0;
1007 /** Tor main loop. */
1008 static int
1009 do_main_loop(void)
1011 int loop_result;
1013 dns_init(); /* initialize dns resolve tree, spawn workers if needed */
1015 handle_signals(1);
1017 /* load the private keys, if we're supposed to have them, and set up the
1018 * TLS context. */
1019 if (! identity_key_is_set()) {
1020 if (init_keys() < 0) {
1021 err(LD_GENERAL,"Error initializing keys; exiting");
1022 return -1;
1026 /* Set up our buckets */
1027 connection_bucket_init();
1028 stats_prev_global_read_bucket = global_read_bucket;
1029 stats_prev_global_write_bucket = global_write_bucket;
1031 /* load the routers file, or assign the defaults. */
1032 if (router_reload_router_list()) {
1033 return -1;
1035 /* load the networkstatuses. (This launches a download for new routers as
1036 * appropriate.)
1038 if (router_reload_networkstatus()) {
1039 return -1;
1041 directory_info_has_arrived(time(NULL),1);
1043 if (authdir_mode(get_options())) {
1044 /* the directory is already here, run startup things */
1045 router_retry_connections(1);
1048 if (server_mode(get_options())) {
1049 /* launch cpuworkers. Need to do this *after* we've read the onion key. */
1050 cpu_init();
1053 /* set up once-a-second callback. */
1054 second_elapsed_callback(0,0,NULL);
1056 for (;;) {
1057 if (nt_service_is_stopped())
1058 return 0;
1060 #ifndef MS_WINDOWS
1061 /* Make it easier to tell whether libevent failure is our fault or not. */
1062 errno = 0;
1063 #endif
1064 /* poll until we have an event, or the second ends */
1065 loop_result = event_dispatch();
1067 /* let catch() handle things like ^c, and otherwise don't worry about it */
1068 if (loop_result < 0) {
1069 int e = tor_socket_errno(-1);
1070 /* let the program survive things like ^z */
1071 if (e != EINTR && !ERRNO_IS_EINPROGRESS(e)) {
1072 #ifdef HAVE_EVENT_GET_METHOD
1073 err(LD_NET,"libevent poll with %s failed: %s [%d]",
1074 event_get_method(), tor_socket_strerror(e), e);
1075 #else
1076 err(LD_NET,"libevent poll failed: %s [%d]",
1077 tor_socket_strerror(e), e);
1078 #endif
1079 return -1;
1080 #ifndef MS_WINDOWS
1081 } else if (e == EINVAL) {
1082 warn(LD_NET, "EINVAL from libevent: should you upgrade libevent?");
1083 if (got_libevent_error())
1084 return -1;
1085 #endif
1086 } else {
1087 if (ERRNO_IS_EINPROGRESS(e))
1088 warn(LD_BUG,"libevent poll returned EINPROGRESS? Please report.");
1089 debug(LD_NET,"event poll interrupted.");
1090 /* You can't trust the results of this poll(). Go back to the
1091 * top of the big for loop. */
1092 continue;
1096 /* refilling buckets and sending cells happens at the beginning of the
1097 * next iteration of the loop, inside prepare_for_poll()
1098 * XXXX No longer so.
1103 /** Used to implement the SIGNAL control command: if we accept
1104 * <b>the_signal</b> as a remote pseudo-signal, then act on it and
1105 * return 0. Else return -1. */
1106 /* We don't re-use catch() here because:
1107 * 1. We handle a different set of signals than those allowed in catch.
1108 * 2. Platforms without signal() are unlikely to define SIGfoo.
1109 * 3. The control spec is defined to use fixed numeric signal values
1110 * which just happen to match the unix values.
1113 control_signal_act(int the_signal)
1115 switch (the_signal)
1117 case 1:
1118 signal_callback(0,0,(void*)(uintptr_t)SIGHUP);
1119 break;
1120 case 2:
1121 signal_callback(0,0,(void*)(uintptr_t)SIGINT);
1122 break;
1123 case 10:
1124 signal_callback(0,0,(void*)(uintptr_t)SIGUSR1);
1125 break;
1126 case 12:
1127 signal_callback(0,0,(void*)(uintptr_t)SIGUSR2);
1128 break;
1129 case 15:
1130 signal_callback(0,0,(void*)(uintptr_t)SIGTERM);
1131 break;
1132 default:
1133 return -1;
1135 return 0;
1138 /** Libevent callback: invoked when we get a signal.
1140 static void
1141 signal_callback(int fd, short events, void *arg)
1143 uintptr_t sig = (uintptr_t)arg;
1144 switch (sig)
1146 case SIGTERM:
1147 err(LD_GENERAL,"Catching signal TERM, exiting cleanly.");
1148 tor_cleanup();
1149 exit(0);
1150 break;
1151 case SIGINT:
1152 if (!server_mode(get_options())) { /* do it now */
1153 notice(LD_GENERAL,"Interrupt: exiting cleanly.");
1154 tor_cleanup();
1155 exit(0);
1157 hibernate_begin_shutdown();
1158 break;
1159 #ifdef SIGPIPE
1160 case SIGPIPE:
1161 debug(LD_GENERAL,"Caught sigpipe. Ignoring.");
1162 break;
1163 #endif
1164 case SIGUSR1:
1165 /* prefer to log it at INFO, but make sure we always see it */
1166 dumpstats(get_min_log_level()<LOG_INFO ? get_min_log_level() : LOG_INFO);
1167 break;
1168 case SIGUSR2:
1169 switch_logs_debug();
1170 debug(LD_GENERAL,"Caught USR2, going to loglevel debug. Send HUP to change back.");
1171 break;
1172 case SIGHUP:
1173 if (do_hup() < 0) {
1174 warn(LD_CONFIG,"Restart failed (config error?). Exiting.");
1175 tor_cleanup();
1176 exit(1);
1178 break;
1179 #ifdef SIGCHLD
1180 case SIGCHLD:
1181 while (waitpid(-1,NULL,WNOHANG) > 0) ; /* keep reaping until no more zombies */
1182 break;
1183 #endif
1188 * Write current memory uusage information to the log.
1190 static void
1191 dumpmemusage(int severity)
1193 extern uint64_t buf_total_used;
1194 extern uint64_t buf_total_alloc;
1195 extern uint64_t rephist_total_alloc;
1196 extern uint32_t rephist_total_num;
1198 log(severity, LD_GENERAL, "In buffers: "U64_FORMAT" used/"U64_FORMAT" allocated (%d conns).",
1199 U64_PRINTF_ARG(buf_total_used), U64_PRINTF_ARG(buf_total_alloc),
1200 nfds);
1201 log(severity, LD_GENERAL, "In rephist: "U64_FORMAT" used by %d Tors.",
1202 U64_PRINTF_ARG(rephist_total_alloc), rephist_total_num);
1205 /** Write all statistics to the log, with log level 'severity'. Called
1206 * in response to a SIGUSR1. */
1207 static void
1208 dumpstats(int severity)
1210 int i;
1211 connection_t *conn;
1212 time_t now = time(NULL);
1213 time_t elapsed;
1215 log(severity, LD_GENERAL, "Dumping stats:");
1217 for (i=0;i<nfds;i++) {
1218 conn = connection_array[i];
1219 log(severity, LD_GENERAL, "Conn %d (socket %d) type %d (%s), state %d (%s), created %d secs ago",
1220 i, conn->s, conn->type, conn_type_to_string(conn->type),
1221 conn->state, conn_state_to_string(conn->type, conn->state), (int)(now - conn->timestamp_created));
1222 if (!connection_is_listener(conn)) {
1223 log(severity,LD_GENERAL,"Conn %d is to '%s:%d'.",i,safe_str(conn->address), conn->port);
1224 log(severity,LD_GENERAL, "Conn %d: %d bytes waiting on inbuf (len %d, last read %d secs ago)",i,
1225 (int)buf_datalen(conn->inbuf),
1226 (int)buf_capacity(conn->inbuf),
1227 (int)(now - conn->timestamp_lastread));
1228 log(severity,LD_GENERAL, "Conn %d: %d bytes waiting on outbuf (len %d, last written %d secs ago)",i,
1229 (int)buf_datalen(conn->outbuf),
1230 (int)buf_capacity(conn->outbuf),
1231 (int)(now - conn->timestamp_lastwritten));
1233 circuit_dump_by_conn(conn, severity); /* dump info about all the circuits using this conn */
1235 log(severity, LD_NET,
1236 "Cells processed: %10lu padding\n"
1237 " %10lu create\n"
1238 " %10lu created\n"
1239 " %10lu relay\n"
1240 " (%10lu relayed)\n"
1241 " (%10lu delivered)\n"
1242 " %10lu destroy",
1243 stats_n_padding_cells_processed,
1244 stats_n_create_cells_processed,
1245 stats_n_created_cells_processed,
1246 stats_n_relay_cells_processed,
1247 stats_n_relay_cells_relayed,
1248 stats_n_relay_cells_delivered,
1249 stats_n_destroy_cells_processed);
1250 if (stats_n_data_cells_packaged)
1251 log(severity,LD_NET,"Average packaged cell fullness: %2.3f%%",
1252 100*(((double)stats_n_data_bytes_packaged) /
1253 (stats_n_data_cells_packaged*RELAY_PAYLOAD_SIZE)) );
1254 if (stats_n_data_cells_received)
1255 log(severity,LD_NET,"Average delivered cell fullness: %2.3f%%",
1256 100*(((double)stats_n_data_bytes_received) /
1257 (stats_n_data_cells_received*RELAY_PAYLOAD_SIZE)) );
1259 if (now - time_of_process_start >= 0)
1260 elapsed = now - time_of_process_start;
1261 else
1262 elapsed = 0;
1264 if (elapsed) {
1265 log(severity, LD_NET,
1266 "Average bandwidth: "U64_FORMAT"/%d = %d bytes/sec reading",
1267 U64_PRINTF_ARG(stats_n_bytes_read),
1268 (int)elapsed,
1269 (int) (stats_n_bytes_read/elapsed));
1270 log(severity, LD_NET,
1271 "Average bandwidth: "U64_FORMAT"/%d = %d bytes/sec writing",
1272 U64_PRINTF_ARG(stats_n_bytes_written),
1273 (int)elapsed,
1274 (int) (stats_n_bytes_written/elapsed));
1277 log(severity, LD_NET, "--------------- Dumping memory information:");
1278 dumpmemusage(severity);
1280 rep_hist_dump_stats(now,severity);
1281 rend_service_dump_stats(severity);
1284 /** Called by exit() as we shut down the process.
1286 static void
1287 exit_function(void)
1289 /* NOTE: If we ever daemonize, this gets called immediately. That's
1290 * okay for now, because we only use this on Windows. */
1291 #ifdef MS_WINDOWS
1292 WSACleanup();
1293 #endif
1296 /** Set up the signal handlers for either parent or child. */
1297 void
1298 handle_signals(int is_parent)
1300 #ifndef MS_WINDOWS /* do signal stuff only on unix */
1301 int i;
1302 static int signals[] = {
1303 SIGINT, /* do a controlled slow shutdown */
1304 SIGTERM, /* to terminate now */
1305 SIGPIPE, /* otherwise sigpipe kills us */
1306 SIGUSR1, /* dump stats */
1307 SIGUSR2, /* go to loglevel debug */
1308 SIGHUP, /* to reload config, retry conns, etc */
1309 #ifdef SIGXFSZ
1310 SIGXFSZ, /* handle file-too-big resource exhaustion */
1311 #endif
1312 SIGCHLD, /* handle dns/cpu workers that exit */
1313 -1 };
1314 static struct event signal_events[16]; /* bigger than it has to be. */
1315 if (is_parent) {
1316 for (i = 0; signals[i] >= 0; ++i) {
1317 signal_set(&signal_events[i], signals[i], signal_callback,
1318 (void*)(uintptr_t)signals[i]);
1319 if (signal_add(&signal_events[i], NULL))
1320 warn(LD_BUG, "Error from libevent when adding event for signal %d",
1321 signals[i]);
1323 } else {
1324 struct sigaction action;
1325 action.sa_flags = 0;
1326 sigemptyset(&action.sa_mask);
1327 action.sa_handler = SIG_IGN;
1328 sigaction(SIGINT, &action, NULL);
1329 sigaction(SIGTERM, &action, NULL);
1330 sigaction(SIGPIPE, &action, NULL);
1331 sigaction(SIGUSR1, &action, NULL);
1332 sigaction(SIGUSR2, &action, NULL);
1333 sigaction(SIGHUP, &action, NULL);
1334 #ifdef SIGXFSZ
1335 sigaction(SIGXFSZ, &action, NULL);
1336 #endif
1338 #endif /* signal stuff */
1341 /** Main entry point for the Tor command-line client.
1343 static int
1344 tor_init(int argc, char *argv[])
1346 time_of_process_start = time(NULL);
1347 if (!closeable_connection_lst)
1348 closeable_connection_lst = smartlist_create();
1349 /* Initialize the history structures. */
1350 rep_hist_init();
1351 /* Initialize the service cache. */
1352 rend_cache_init();
1353 addressmap_init(); /* Init the client dns cache. Do it always, since it's cheap. */
1355 /* give it somewhere to log to initially */
1356 add_temp_log();
1358 log(LOG_NOTICE, LD_GENERAL, "Tor v%s. This is experimental software. Do not rely on it for strong anonymity.",VERSION);
1360 if (network_init()<0) {
1361 err(LD_NET,"Error initializing network; exiting.");
1362 return -1;
1364 atexit(exit_function);
1366 if (options_init_from_torrc(argc,argv) < 0) {
1367 err(LD_CONFIG,"Reading config failed--see warnings above. For usage, try -h.");
1368 return -1;
1371 #ifndef MS_WINDOWS
1372 if (geteuid()==0)
1373 warn(LD_GENERAL,"You are running Tor as root. You don't need to, and you probably shouldn't.");
1374 #endif
1376 crypto_global_init(get_options()->HardwareAccel);
1377 if (crypto_seed_rng()) {
1378 err(LD_BUG, "Unable to seed random number generator. Exiting.");
1379 return -1;
1382 return 0;
1385 /** Free all memory that we might have allocated somewhere.
1386 * Helps us find the real leaks with dmalloc and the like.
1388 * Also valgrind should then report 0 reachable in its
1389 * leak report */
1390 void
1391 tor_free_all(int postfork)
1393 routerlist_free_all();
1394 addressmap_free_all();
1395 set_exit_redirects(NULL); /* free the registered exit redirects */
1396 free_socks_policy();
1397 free_dir_policy();
1398 dirserv_free_all();
1399 rend_service_free_all();
1400 rend_cache_free_all();
1401 rep_hist_free_all();
1402 dns_free_all();
1403 clear_pending_onions();
1404 circuit_free_all();
1405 helper_nodes_free_all();
1406 connection_free_all();
1407 if (!postfork) {
1408 config_free_all();
1409 router_free_all();
1411 tor_tls_free_all();
1412 /* stuff in main.c */
1413 smartlist_free(closeable_connection_lst);
1414 tor_free(timeout_event);
1416 if (!postfork) {
1417 close_logs(); /* free log strings. do this last so logs keep working. */
1421 /** Do whatever cleanup is necessary before shutting Tor down. */
1422 void
1423 tor_cleanup(void)
1425 or_options_t *options = get_options();
1426 /* Remove our pid file. We don't care if there was an error when we
1427 * unlink, nothing we could do about it anyways. */
1428 if (options->PidFile && options->command == CMD_RUN_TOR)
1429 unlink(options->PidFile);
1430 if (accounting_is_enabled(options))
1431 accounting_record_bandwidth_usage(time(NULL));
1432 tor_free_all(0); /* move tor_free_all back into the ifdef below later. XXX*/
1433 crypto_global_cleanup();
1434 #ifdef USE_DMALLOC
1435 dmalloc_log_unfreed();
1436 dmalloc_shutdown();
1437 #endif
1440 /** Read/create keys as needed, and echo our fingerprint to stdout. */
1441 static void
1442 do_list_fingerprint(void)
1444 char buf[FINGERPRINT_LEN+1];
1445 crypto_pk_env_t *k;
1446 const char *nickname = get_options()->Nickname;
1447 if (!server_mode(get_options())) {
1448 printf("Clients don't have long-term identity keys. Exiting.\n");
1449 return;
1451 tor_assert(nickname);
1452 if (init_keys() < 0) {
1453 err(LD_BUG,"Error initializing keys; exiting");
1454 return;
1456 if (!(k = get_identity_key())) {
1457 err(LD_GENERAL,"Error: missing identity key.");
1458 return;
1460 if (crypto_pk_get_fingerprint(k, buf, 1)<0) {
1461 warn(LD_BUG, "Error computing fingerprint");
1462 return;
1464 printf("%s %s\n", nickname, buf);
1467 /** Entry point for password hashing: take the desired password from
1468 * the command line, and print its salted hash to stdout. **/
1469 static void
1470 do_hash_password(void)
1473 char output[256];
1474 char key[S2K_SPECIFIER_LEN+DIGEST_LEN];
1476 crypto_rand(key, S2K_SPECIFIER_LEN-1);
1477 key[S2K_SPECIFIER_LEN-1] = (uint8_t)96; /* Hash 64 K of data. */
1478 secret_to_key(key+S2K_SPECIFIER_LEN, DIGEST_LEN,
1479 get_options()->command_arg, strlen(get_options()->command_arg),
1480 key);
1481 base16_encode(output, sizeof(output), key, sizeof(key));
1482 printf("16:%s\n",output);
1485 #ifdef MS_WINDOWS_SERVICE
1486 /** Checks if torrc is present in the same directory
1487 * as the service executable.
1488 * Return 1 if it is, 0 if it is not present. */
1489 static int
1490 nt_torrc_is_present()
1492 HANDLE hFile;
1493 TCHAR szPath[_MAX_PATH];
1494 TCHAR szDrive[_MAX_DRIVE];
1495 TCHAR szDir[_MAX_DIR];
1496 char torrc[] = "torrc";
1497 char *path_to_torrc;
1498 int len = 0;
1500 /* Get the service executable path */
1501 if (0 == GetModuleFileName(NULL, szPath, MAX_PATH))
1502 return 0;
1503 _tsplitpath(szPath, szDrive, szDir, NULL, NULL);
1505 /* Build the path to the torrc file */
1506 len = _MAX_PATH + _MAX_DRIVE + _MAX_DIR + strlen(torrc) + 1;
1507 path_to_torrc = tor_malloc(len);
1508 if (tor_snprintf(path_to_torrc, len, "%s%s%s", szDrive, szDir, torrc)<0) {
1509 printf("Failed: tor_snprinf()\n");
1510 tor_free(path_to_torrc);
1511 return 0;
1514 /* See if torrc is present */
1515 hFile = CreateFile(TEXT(path_to_torrc),
1516 GENERIC_READ, FILE_SHARE_READ, NULL,
1517 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL,
1518 NULL);
1520 tor_free(path_to_torrc);
1522 if (hFile == INVALID_HANDLE_VALUE) {
1523 return 0;
1525 CloseHandle(hFile);
1526 return 1;
1529 /** If we're compile to run as an NT service, and the service has been
1530 * shut down, then change our current status and return 1. Else
1531 * return 0.
1533 static int
1534 nt_service_is_stopped(void)
1536 if (service_status.dwCurrentState == SERVICE_STOP_PENDING) {
1537 service_status.dwWin32ExitCode = 0;
1538 service_status.dwCurrentState = SERVICE_STOPPED;
1539 SetServiceStatus(hStatus, &service_status);
1540 return 1;
1541 } else if (service_status.dwCurrentState == SERVICE_STOPPED) {
1542 return 1;
1544 return 0;
1547 /** DOCDOC */
1548 void
1549 nt_service_control(DWORD request)
1551 static struct timeval exit_now;
1552 exit_now.tv_sec = 0;
1553 exit_now.tv_usec = 0;
1555 switch (request) {
1556 case SERVICE_CONTROL_STOP:
1557 case SERVICE_CONTROL_SHUTDOWN:
1558 err(LD_GENERAL, "Got stop/shutdown request; shutting down cleanly.");
1559 service_status.dwCurrentState = SERVICE_STOP_PENDING;
1560 event_loopexit(&exit_now);
1561 return;
1563 SetServiceStatus(hStatus, &service_status);
1566 /** DOCDOC */
1567 void
1568 nt_service_body(int argc, char **argv)
1570 int r;
1571 service_status.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
1572 service_status.dwCurrentState = SERVICE_START_PENDING;
1573 service_status.dwControlsAccepted =
1574 SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
1575 service_status.dwWin32ExitCode = 0;
1576 service_status.dwServiceSpecificExitCode = 0;
1577 service_status.dwCheckPoint = 0;
1578 service_status.dwWaitHint = 1000;
1579 hStatus = RegisterServiceCtrlHandler(GENSRV_SERVICENAME, (LPHANDLER_FUNCTION) nt_service_control);
1581 if (hStatus == 0) {
1582 // failed;
1583 return;
1586 // check for torrc
1587 if (nt_torrc_is_present()) {
1588 r = tor_init(backup_argc, backup_argv); // refactor this part out of tor_main and do_main_loop
1589 if (r) {
1590 r = NT_SERVICE_ERROR_TORINIT_FAILED;
1593 else {
1594 err(LD_CONFIG, "torrc is not in the current working directory. The Tor service will not start.");
1595 r = NT_SERVICE_ERROR_NO_TORRC;
1598 if (r) {
1599 // failed.
1600 service_status.dwCurrentState = SERVICE_STOPPED;
1601 service_status.dwWin32ExitCode = r;
1602 service_status.dwServiceSpecificExitCode = r;
1603 SetServiceStatus(hStatus, &service_status);
1604 return;
1606 service_status.dwCurrentState = SERVICE_RUNNING;
1607 SetServiceStatus(hStatus, &service_status);
1608 do_main_loop();
1609 tor_cleanup();
1610 return;
1613 /** DOCDOC */
1614 void
1615 nt_service_main(void)
1617 SERVICE_TABLE_ENTRY table[2];
1618 DWORD result = 0;
1619 char *errmsg;
1620 table[0].lpServiceName = GENSRV_SERVICENAME;
1621 table[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTION)nt_service_body;
1622 table[1].lpServiceName = NULL;
1623 table[1].lpServiceProc = NULL;
1625 if (!StartServiceCtrlDispatcher(table)) {
1626 result = GetLastError();
1627 errmsg = nt_strerror(result);
1628 printf("Service error %d : %s\n", result, errmsg);
1629 LocalFree(errmsg);
1630 if (result == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) {
1631 if (tor_init(backup_argc, backup_argv) < 0)
1632 return;
1633 switch (get_options()->command) {
1634 case CMD_RUN_TOR:
1635 do_main_loop();
1636 break;
1637 case CMD_LIST_FINGERPRINT:
1638 do_list_fingerprint();
1639 break;
1640 case CMD_HASH_PASSWORD:
1641 do_hash_password();
1642 break;
1643 case CMD_VERIFY_CONFIG:
1644 printf("Configuration was valid\n");
1645 break;
1646 default:
1647 err(LD_CONFIG, "Illegal command number %d: internal error.", get_options()->command);
1649 tor_cleanup();
1654 /** DOCDOC */
1655 SC_HANDLE
1656 nt_service_open_scm(void)
1658 SC_HANDLE hSCManager;
1659 char *errmsg = NULL;
1661 if ((hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE)) == NULL) {
1662 errmsg = nt_strerror(GetLastError());
1663 printf("OpenSCManager() failed : %s\n", errmsg);
1664 LocalFree(errmsg);
1666 return hSCManager;
1669 /** DOCDOC */
1670 SC_HANDLE
1671 nt_service_open(SC_HANDLE hSCManager)
1673 SC_HANDLE hService;
1674 char *errmsg = NULL;
1676 if ((hService = OpenService(hSCManager, GENSRV_SERVICENAME, SERVICE_ALL_ACCESS)) == NULL) {
1677 errmsg = nt_strerror(GetLastError());
1678 printf("OpenService() failed : %s\n", errmsg);
1679 LocalFree(errmsg);
1681 return hService;
1684 /** DOCDOC */
1686 nt_service_start(SC_HANDLE hService)
1688 char *errmsg = NULL;
1690 QueryServiceStatus(hService, &service_status);
1691 if (service_status.dwCurrentState == SERVICE_RUNNING) {
1692 printf("Service is already running\n");
1693 return 1;
1696 if (StartService(hService, 0, NULL)) {
1697 /* Loop until the service has finished attempting to start */
1698 while (QueryServiceStatus(hService, &service_status)) {
1699 if (service_status.dwCurrentState == SERVICE_START_PENDING)
1700 Sleep(500);
1701 else
1702 break;
1705 /* Check if it started successfully or not */
1706 if (service_status.dwCurrentState == SERVICE_RUNNING) {
1707 printf("Service started successfully\n");
1708 return 1;
1710 else {
1711 errmsg = nt_strerror(service_status.dwWin32ExitCode);
1712 printf("Service failed to start : %s\n", errmsg);
1713 LocalFree(errmsg);
1716 else {
1717 errmsg = nt_strerror(GetLastError());
1718 printf("StartService() failed : %s\n", errmsg);
1719 LocalFree(errmsg);
1721 return 0;
1724 /** DOCDOC */
1726 nt_service_stop(SC_HANDLE hService)
1728 char *errmsg = NULL;
1730 QueryServiceStatus(hService, &service_status);
1731 if (service_status.dwCurrentState == SERVICE_STOPPED) {
1732 printf("Service is already stopped\n");
1733 return 1;
1736 if (ControlService(hService, SERVICE_CONTROL_STOP, &service_status)) {
1737 while (QueryServiceStatus(hService, &service_status)) {
1738 if (service_status.dwCurrentState == SERVICE_STOP_PENDING)
1739 Sleep(500);
1740 else
1741 break;
1743 if (service_status.dwCurrentState == SERVICE_STOPPED) {
1744 printf("Service stopped successfully\n");
1745 return 1;
1747 else {
1748 errmsg = nt_strerror(GetLastError());
1749 printf("Service failed to stop : %s\n");
1750 LocalFree(errmsg);
1753 else {
1754 errmsg = nt_strerror(GetLastError());
1755 printf("ControlService() failed : %s\n", errmsg);
1756 LocalFree(errmsg);
1758 return 0;
1761 /** DOCDOC */
1763 nt_service_install(void)
1765 /* XXXX Problems with NT services:
1766 * 1. The configuration file needs to be in the same directory as the .exe
1768 * 2. The exe and the configuration file can't be on any directory path
1769 * that contains a space.
1770 * mje - you can quote the string (i.e., "c:\program files")
1772 * 3. Ideally, there should be one EXE that can either run as a
1773 * separate process (as now) or that can install and run itself
1774 * as an NT service. I have no idea how hard this is.
1775 * mje - should be done. It can install and run itself as a service
1777 * Notes about developing NT services:
1779 * 1. Don't count on your CWD. If an absolute path is not given, the
1780 * fopen() function goes wrong.
1781 * 2. The parameters given to the nt_service_body() function differ
1782 * from those given to main() function.
1785 SC_HANDLE hSCManager = NULL;
1786 SC_HANDLE hService = NULL;
1787 SERVICE_DESCRIPTION sdBuff;
1788 TCHAR szPath[_MAX_PATH];
1789 TCHAR szDrive[_MAX_DRIVE];
1790 TCHAR szDir[_MAX_DIR];
1791 char cmd1[] = " -f ";
1792 char cmd2[] = "\\torrc";
1793 char *command;
1794 char *errmsg;
1795 int len = 0;
1797 if (0 == GetModuleFileName(NULL, szPath, MAX_PATH))
1798 return 0;
1800 _tsplitpath(szPath, szDrive, szDir, NULL, NULL);
1802 /* Account for the extra quotes */
1803 //len = _MAX_PATH + strlen(cmd1) + _MAX_DRIVE + _MAX_DIR + strlen(cmd2);
1804 len = _MAX_PATH + strlen(cmd1) + _MAX_DRIVE + _MAX_DIR + strlen(cmd2) + 64;
1805 command = tor_malloc(len);
1807 /* Create a quoted command line, like "c:\with spaces\tor.exe" -f
1808 * "c:\with spaces\tor.exe"
1810 if (tor_snprintf(command, len, "\"%s\" --nt-service -f \"%s%storrc\"",
1811 szPath, szDrive, szDir)<0) {
1812 printf("Failed: tor_snprinf()\n");
1813 tor_free(command);
1814 return 0;
1817 if ((hSCManager = nt_service_open_scm()) == NULL) {
1818 tor_free(command);
1819 return 0;
1822 /* 1/26/2005 mje
1823 * - changed the service start type to auto
1824 * - and changed the lpPassword param to "" instead of NULL as per an
1825 * MSDN article.
1827 if ((hService = CreateService(hSCManager, GENSRV_SERVICENAME, GENSRV_DISPLAYNAME,
1828 SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,
1829 SERVICE_AUTO_START, SERVICE_ERROR_IGNORE, command,
1830 NULL, NULL, NULL, NULL, "")) == NULL) {
1831 errmsg = nt_strerror(GetLastError());
1832 printf("CreateService() failed : %s\n", errmsg);
1833 CloseServiceHandle(hSCManager);
1834 LocalFree(errmsg);
1835 tor_free(command);
1836 return 0;
1839 /* Set the service's description */
1840 sdBuff.lpDescription = GENSRV_DESCRIPTION;
1841 ChangeServiceConfig2(hService, SERVICE_CONFIG_DESCRIPTION, &sdBuff);
1842 printf("Service installed successfully\n");
1844 /* Start the service initially */
1845 nt_service_start(hService);
1847 CloseServiceHandle(hService);
1848 CloseServiceHandle(hSCManager);
1849 tor_free(command);
1851 return 0;
1854 /** DOCDOC */
1856 nt_service_remove(void)
1858 SC_HANDLE hSCManager = NULL;
1859 SC_HANDLE hService = NULL;
1860 BOOL result = FALSE;
1861 char *errmsg;
1863 if ((hSCManager = nt_service_open_scm()) == NULL) {
1864 return 0;
1867 if ((hService = nt_service_open(hSCManager)) == NULL) {
1868 CloseServiceHandle(hSCManager);
1869 return 0;
1872 if (nt_service_stop(hService)) {
1873 if (DeleteService(hService)) {
1874 printf("Removed service successfully\n");
1876 else {
1877 errmsg = nt_strerror(GetLastError());
1878 printf("DeleteService() failed : %s\n", errmsg);
1879 LocalFree(errmsg);
1882 else {
1883 printf("Service could not be removed\n");
1886 CloseServiceHandle(hService);
1887 CloseServiceHandle(hSCManager);
1889 return 0;
1892 /** DOCDOC */
1894 nt_service_cmd_start(void)
1896 SC_HANDLE hSCManager;
1897 SC_HANDLE hService;
1898 int start;
1900 if ((hSCManager = nt_service_open_scm()) == NULL)
1901 return -1;
1902 if ((hService = nt_service_open(hSCManager)) == NULL) {
1903 CloseHandle(hSCManager);
1904 return -1;
1907 start = nt_service_start(hService);
1908 CloseHandle(hService);
1909 CloseHandle(hSCManager);
1911 return start;
1914 /** DOCDOC */
1916 nt_service_cmd_stop(void)
1918 SC_HANDLE hSCManager;
1919 SC_HANDLE hService;
1920 int stop;
1922 if ((hSCManager = nt_service_open_scm()) == NULL)
1923 return -1;
1924 if ((hService = nt_service_open(hSCManager)) == NULL) {
1925 CloseHandle(hSCManager);
1926 return -1;
1929 stop = nt_service_stop(hService);
1930 CloseHandle(hService);
1931 CloseHandle(hSCManager);
1933 return stop;
1936 /** Given a Win32 error code, this attempts to make Windows
1937 * return a human-readable error message. The char* returned
1938 * is allocated by Windows, but should be freed with LocalFree()
1939 * when finished with it. */
1940 static char*
1941 nt_strerror(uint32_t errnum)
1943 char *msgbuf;
1944 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
1945 NULL, errnum, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1946 (LPSTR)&msgbuf, 0, NULL);
1947 return msgbuf;
1949 #endif
1951 #ifdef USE_DMALLOC
1952 #include <openssl/crypto.h>
1953 static void
1954 _tor_dmalloc_free(void *p)
1956 tor_free(p);
1958 #endif
1960 /** DOCDOC */
1962 tor_main(int argc, char *argv[])
1964 #ifdef USE_DMALLOC
1965 int r = CRYPTO_set_mem_ex_functions(_tor_malloc, _tor_realloc, _tor_dmalloc_free);
1966 notice(LD_CONFIG, "Set up damalloc; returned %d", r);
1967 #endif
1968 #ifdef MS_WINDOWS_SERVICE
1969 backup_argv = argv;
1970 backup_argc = argc;
1971 if ((argc >= 3) && (!strcmp(argv[1], "-service") || !strcmp(argv[1], "--service"))) {
1972 if (!strcmp(argv[2], "install"))
1973 return nt_service_install();
1974 if (!strcmp(argv[2], "remove"))
1975 return nt_service_remove();
1976 if (!strcmp(argv[2], "start"))
1977 return nt_service_cmd_start();
1978 if (!strcmp(argv[2], "stop"))
1979 return nt_service_cmd_stop();
1980 printf("Unrecognized service command '%s'\n", argv[2]);
1981 return -1;
1983 // These are left so as not to confuse people who are used to these options
1984 if (argc >= 2) {
1985 if (!strcmp(argv[1], "-install") || !strcmp(argv[1], "--install"))
1986 return nt_service_install();
1987 if (!strcmp(argv[1], "-remove") || !strcmp(argv[1], "--remove"))
1988 return nt_service_remove();
1989 if (!strcmp(argv[1], "-nt-service") || !strcmp(argv[1], "--nt-service")) {
1990 nt_service_main();
1991 return 0;
1994 #endif
1995 if (tor_init(argc, argv)<0)
1996 return -1;
1997 switch (get_options()->command) {
1998 case CMD_RUN_TOR:
1999 #ifdef MS_WINDOWS_SERVICE
2000 service_status.dwCurrentState = SERVICE_RUNNING;
2001 #endif
2002 do_main_loop();
2003 break;
2004 case CMD_LIST_FINGERPRINT:
2005 do_list_fingerprint();
2006 break;
2007 case CMD_HASH_PASSWORD:
2008 do_hash_password();
2009 break;
2010 case CMD_VERIFY_CONFIG:
2011 printf("Configuration was valid\n");
2012 break;
2013 default:
2014 warn(LD_BUG,"Illegal command number %d: internal error.",
2015 get_options()->command);
2017 tor_cleanup();
2018 return -1;