r11646@catbus: nickm | 2007-02-05 16:15:48 -0500
[tor.git] / src / or / main.c
bloba1b145bf7129dabddde24a701c169c63cc35f80b
1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson. */
4 /* See LICENSE for licensing information */
5 /* $Id$ */
6 const char main_c_id[] =
7 "$Id$";
9 /**
10 * \file main.c
11 * \brief Toplevel module. Handles signals, multiplexes between
12 * connections, implements main loop, and drives scheduled events.
13 **/
15 #include "or.h"
16 #ifdef USE_DMALLOC
17 #include <dmalloc.h>
18 #endif
19 #ifdef USE_EVENTDNS
20 void evdns_shutdown(int);
21 #endif
23 /********* PROTOTYPES **********/
25 static void dumpmemusage(int severity);
26 static void dumpstats(int severity); /* log stats */
27 static void conn_read_callback(int fd, short event, void *_conn);
28 static void conn_write_callback(int fd, short event, void *_conn);
29 static void signal_callback(int fd, short events, void *arg);
30 static void second_elapsed_callback(int fd, short event, void *args);
31 static int conn_close_if_marked(int i);
33 /********* START VARIABLES **********/
35 int global_read_bucket; /**< Max number of bytes I can read this second. */
36 int global_write_bucket; /**< Max number of bytes I can write this second. */
38 /** What was the read bucket before the last call to prepare_for_pool?
39 * (used to determine how many bytes we've read). */
40 static int stats_prev_global_read_bucket;
41 /** What was the write bucket before the last call to prepare_for_pool?
42 * (used to determine how many bytes we've written). */
43 static int stats_prev_global_write_bucket;
44 /** How many bytes have we read/written since we started the process? */
45 static uint64_t stats_n_bytes_read = 0;
46 static uint64_t stats_n_bytes_written = 0;
47 /** What time did this process start up? */
48 long time_of_process_start = 0;
49 /** How many seconds have we been running? */
50 long stats_n_seconds_working = 0;
51 /** When do we next download a directory? */
52 static time_t time_to_fetch_directory = 0;
53 /** When do we next download a running-routers summary? */
54 static time_t time_to_fetch_running_routers = 0;
55 /** When do we next launch DNS wildcarding checks? */
56 static time_t time_to_check_for_correct_dns = 0;
58 /** Array of all open connections. The first n_conns elements are valid. */
59 static connection_t *connection_array[MAXCONNECTIONS+1] =
60 { NULL };
61 /** DOCDOC */
62 static smartlist_t *closeable_connection_lst = NULL;
64 static int n_conns=0; /**< Number of connections currently active. */
66 /** We set this to 1 when we've opened a circuit, so we can print a log
67 * entry to inform the user that Tor is working. */
68 int has_completed_circuit=0;
70 #ifdef MS_WINDOWS
71 #define MS_WINDOWS_SERVICE
72 #endif
74 #ifdef MS_WINDOWS_SERVICE
75 #include <tchar.h>
76 #define GENSRV_SERVICENAME TEXT("tor")
77 #define GENSRV_DISPLAYNAME TEXT("Tor Win32 Service")
78 #define GENSRV_DESCRIPTION \
79 TEXT("Provides an anonymous Internet communication system")
80 #define GENSRV_USERACCT TEXT("NT AUTHORITY\\LocalService")
82 // Cheating: using the pre-defined error codes, tricks Windows into displaying
83 // a semi-related human-readable error message if startup fails as
84 // opposed to simply scaring people with Error: 0xffffffff
85 #define NT_SERVICE_ERROR_TORINIT_FAILED ERROR_EXCEPTION_IN_SERVICE
87 SERVICE_STATUS service_status;
88 SERVICE_STATUS_HANDLE hStatus;
89 static char **backup_argv;
90 static int backup_argc;
91 static int nt_service_is_stopped(void);
92 static char* nt_strerror(uint32_t errnum);
93 #else
94 #define nt_service_is_stopped() (0)
95 #endif
97 /** If our router descriptor ever goes this long without being regenerated
98 * because something changed, we force an immediate regenerate-and-upload. */
99 #define FORCE_REGENERATE_DESCRIPTOR_INTERVAL (18*60*60)
100 /** How often do we check whether part of our router info has changed in a way
101 * that would require an upload? */
102 #define CHECK_DESCRIPTOR_INTERVAL (60)
103 /** How often do we (as a router) check whether our IP address has changed? */
104 #define CHECK_IPADDRESS_INTERVAL (15*60)
105 /** How often do we check buffers for empty space that can be deallocated? */
106 #define BUF_SHRINK_INTERVAL (60)
107 /** How often do we check for router descriptors that we should download? */
108 #define DESCRIPTOR_RETRY_INTERVAL (10)
109 /** How often do we 'forgive' undownloadable router descriptors and attempt
110 * to download them again? */
111 #define DESCRIPTOR_FAILURE_RESET_INTERVAL (60*60)
112 /** How often do we add more entropy to OpenSSL's RNG pool? */
113 #define ENTROPY_INTERVAL (60*60)
114 /** How long do we let a directory connection stall before expiring it? */
115 #define DIR_CONN_MAX_STALL (5*60)
117 /** How old do we let a connection to an OR get before deciding it's
118 * obsolete? */
119 #define TIME_BEFORE_OR_CONN_IS_OBSOLETE (60*60*24*7)
120 /** How long do we let OR connections handshake before we decide that
121 * they are obsolete? */
122 #define TLS_HANDSHAKE_TIMEOUT (60)
124 /********* END VARIABLES ************/
126 /****************************************************************************
128 * This section contains accessors and other methods on the connection_array
129 * variables (which are global within this file and unavailable outside it).
131 ****************************************************************************/
133 /** Add <b>conn</b> to the array of connections that we can poll on. The
134 * connection's socket must be set; the connection starts out
135 * non-reading and non-writing.
138 connection_add(connection_t *conn)
140 tor_assert(conn);
141 tor_assert(conn->s >= 0);
143 if (n_conns >= get_options()->_ConnLimit-1) {
144 log_warn(LD_NET,"Failing because we have %d connections already. Please "
145 "raise your ulimit -n.", n_conns);
146 control_event_general_status(LOG_WARN, "TOO_MANY_CONNECTIONS CURRENT=%d",
147 n_conns);
148 return -1;
151 tor_assert(conn->conn_array_index == -1); /* can only connection_add once */
152 conn->conn_array_index = n_conns;
153 connection_array[n_conns] = conn;
155 conn->read_event = tor_malloc_zero(sizeof(struct event));
156 conn->write_event = tor_malloc_zero(sizeof(struct event));
157 event_set(conn->read_event, conn->s, EV_READ|EV_PERSIST,
158 conn_read_callback, conn);
159 event_set(conn->write_event, conn->s, EV_WRITE|EV_PERSIST,
160 conn_write_callback, conn);
162 n_conns++;
164 log_debug(LD_NET,"new conn type %s, socket %d, n_conns %d.",
165 conn_type_to_string(conn->type), conn->s, n_conns);
167 return 0;
170 /** Remove the connection from the global list, and remove the
171 * corresponding poll entry. Calling this function will shift the last
172 * connection (if any) into the position occupied by conn.
175 connection_remove(connection_t *conn)
177 int current_index;
179 tor_assert(conn);
180 tor_assert(n_conns>0);
182 log_debug(LD_NET,"removing socket %d (type %s), n_conns now %d",
183 conn->s, conn_type_to_string(conn->type), n_conns-1);
185 tor_assert(conn->conn_array_index >= 0);
186 current_index = conn->conn_array_index;
187 if (current_index == n_conns-1) { /* this is the end */
188 n_conns--;
189 return 0;
192 connection_unregister(conn);
194 /* replace this one with the one at the end */
195 n_conns--;
196 connection_array[current_index] = connection_array[n_conns];
197 connection_array[current_index]->conn_array_index = current_index;
199 return 0;
202 /** If it's an edge conn, remove it from the list
203 * of conn's on this circuit. If it's not on an edge,
204 * flush and send destroys for all circuits on this conn.
206 * If <b>remove</b> is non-zero, then remove it from the
207 * connection_array and closeable_connection_lst.
209 * Then free it.
211 static void
212 connection_unlink(connection_t *conn, int remove)
214 connection_about_to_close_connection(conn);
215 if (remove) {
216 connection_remove(conn);
218 smartlist_remove(closeable_connection_lst, conn);
219 if (conn->type == CONN_TYPE_EXIT) {
220 assert_connection_edge_not_dns_pending(TO_EDGE_CONN(conn));
222 if (conn->type == CONN_TYPE_OR) {
223 if (!tor_digest_is_zero(TO_OR_CONN(conn)->identity_digest))
224 connection_or_remove_from_identity_map(TO_OR_CONN(conn));
226 connection_free(conn);
229 /** Schedule <b>conn</b> to be closed. **/
230 void
231 add_connection_to_closeable_list(connection_t *conn)
233 tor_assert(!smartlist_isin(closeable_connection_lst, conn));
234 tor_assert(conn->marked_for_close);
235 assert_connection_ok(conn, time(NULL));
236 smartlist_add(closeable_connection_lst, conn);
239 /** Return 1 if conn is on the closeable list, else return 0. */
241 connection_is_on_closeable_list(connection_t *conn)
243 return smartlist_isin(closeable_connection_lst, conn);
246 /** Return true iff conn is in the current poll array. */
248 connection_in_array(connection_t *conn)
250 int i;
251 for (i=0; i<n_conns; ++i) {
252 if (conn==connection_array[i])
253 return 1;
255 return 0;
258 /** Set <b>*array</b> to an array of all connections, and <b>*n</b>
259 * to the length of the array. <b>*array</b> and <b>*n</b> must not
260 * be modified.
262 void
263 get_connection_array(connection_t ***array, int *n)
265 *array = connection_array;
266 *n = n_conns;
269 /** Set the event mask on <b>conn</b> to <b>events</b>. (The event
270 * mask is a bitmask whose bits are EV_READ and EV_WRITE.)
272 void
273 connection_watch_events(connection_t *conn, short events)
275 int r;
277 tor_assert(conn);
278 tor_assert(conn->read_event);
279 tor_assert(conn->write_event);
281 if (events & EV_READ) {
282 r = event_add(conn->read_event, NULL);
283 } else {
284 r = event_del(conn->read_event);
287 if (r<0)
288 log_warn(LD_NET,
289 "Error from libevent setting read event state for %d to "
290 "%swatched: %s",
291 conn->s, (events & EV_READ)?"":"un",
292 tor_socket_strerror(tor_socket_errno(conn->s)));
294 if (events & EV_WRITE) {
295 r = event_add(conn->write_event, NULL);
296 } else {
297 r = event_del(conn->write_event);
300 if (r<0)
301 log_warn(LD_NET,
302 "Error from libevent setting read event state for %d to "
303 "%swatched: %s",
304 conn->s, (events & EV_WRITE)?"":"un",
305 tor_socket_strerror(tor_socket_errno(conn->s)));
308 /** Return true iff <b>conn</b> is listening for read events. */
310 connection_is_reading(connection_t *conn)
312 tor_assert(conn);
314 return conn->read_event && event_pending(conn->read_event, EV_READ, NULL);
317 /** Tell the main loop to stop notifying <b>conn</b> of any read events. */
318 void
319 connection_stop_reading(connection_t *conn)
321 tor_assert(conn);
322 tor_assert(conn->read_event);
324 log_debug(LD_NET,"entering.");
325 if (event_del(conn->read_event))
326 log_warn(LD_NET, "Error from libevent setting read event state for %d "
327 "to unwatched: %s",
328 conn->s,
329 tor_socket_strerror(tor_socket_errno(conn->s)));
332 /** Tell the main loop to start notifying <b>conn</b> of any read events. */
333 void
334 connection_start_reading(connection_t *conn)
336 tor_assert(conn);
337 tor_assert(conn->read_event);
339 if (event_add(conn->read_event, NULL))
340 log_warn(LD_NET, "Error from libevent setting read event state for %d "
341 "to watched: %s",
342 conn->s,
343 tor_socket_strerror(tor_socket_errno(conn->s)));
346 /** Return true iff <b>conn</b> is listening for write events. */
348 connection_is_writing(connection_t *conn)
350 tor_assert(conn);
352 return conn->write_event && event_pending(conn->write_event, EV_WRITE, NULL);
355 /** Tell the main loop to stop notifying <b>conn</b> of any write events. */
356 void
357 connection_stop_writing(connection_t *conn)
359 tor_assert(conn);
360 tor_assert(conn->write_event);
362 if (event_del(conn->write_event))
363 log_warn(LD_NET, "Error from libevent setting write event state for %d "
364 "to unwatched: %s",
365 conn->s,
366 tor_socket_strerror(tor_socket_errno(conn->s)));
369 /** Tell the main loop to start notifying <b>conn</b> of any write events. */
370 void
371 connection_start_writing(connection_t *conn)
373 tor_assert(conn);
374 tor_assert(conn->write_event);
376 if (event_add(conn->write_event, NULL))
377 log_warn(LD_NET, "Error from libevent setting write event state for %d "
378 "to watched: %s",
379 conn->s,
380 tor_socket_strerror(tor_socket_errno(conn->s)));
383 /** Close all connections that have been scheduled to get closed */
384 static void
385 close_closeable_connections(void)
387 int i;
388 for (i = 0; i < smartlist_len(closeable_connection_lst); ) {
389 connection_t *conn = smartlist_get(closeable_connection_lst, i);
390 if (conn->conn_array_index < 0) {
391 connection_unlink(conn, 0); /* blow it away right now */
392 } else {
393 if (!conn_close_if_marked(conn->conn_array_index))
394 ++i;
399 /** Libevent callback: this gets invoked when (connection_t*)<b>conn</b> has
400 * some data to read. */
401 static void
402 conn_read_callback(int fd, short event, void *_conn)
404 connection_t *conn = _conn;
405 (void)fd;
406 (void)event;
408 log_debug(LD_NET,"socket %d wants to read.",conn->s);
410 assert_connection_ok(conn, time(NULL));
412 if (connection_handle_read(conn) < 0) {
413 if (!conn->marked_for_close) {
414 #ifndef MS_WINDOWS
415 log_warn(LD_BUG,"Bug: unhandled error on read for %s connection "
416 "(fd %d); removing",
417 conn_type_to_string(conn->type), conn->s);
418 tor_fragile_assert();
419 #endif
420 if (CONN_IS_EDGE(conn))
421 connection_edge_end_errno(TO_EDGE_CONN(conn),
422 TO_EDGE_CONN(conn)->cpath_layer);
423 connection_mark_for_close(conn);
426 assert_connection_ok(conn, time(NULL));
428 if (smartlist_len(closeable_connection_lst))
429 close_closeable_connections();
432 /** Libevent callback: this gets invoked when (connection_t*)<b>conn</b> has
433 * some data to write. */
434 static void
435 conn_write_callback(int fd, short events, void *_conn)
437 connection_t *conn = _conn;
438 (void)fd;
439 (void)events;
441 LOG_FN_CONN(conn, (LOG_DEBUG, LD_NET, "socket %d wants to write.",conn->s));
443 assert_connection_ok(conn, time(NULL));
445 if (connection_handle_write(conn, 0) < 0) {
446 if (!conn->marked_for_close) {
447 /* this connection is broken. remove it. */
448 log_fn(LOG_WARN,LD_BUG,
449 "Bug: unhandled error on write for %s connection (fd %d); removing",
450 conn_type_to_string(conn->type), conn->s);
451 tor_fragile_assert();
452 if (CONN_IS_EDGE(conn)) {
453 /* otherwise we cry wolf about duplicate close */
454 edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
455 if (!edge_conn->end_reason)
456 edge_conn->end_reason = END_STREAM_REASON_INTERNAL;
457 conn->edge_has_sent_end = 1;
459 /* XXX do we need a close-immediate here, so we don't try to flush? */
460 connection_mark_for_close(conn);
463 assert_connection_ok(conn, time(NULL));
465 if (smartlist_len(closeable_connection_lst))
466 close_closeable_connections();
469 /** If the connection at connection_array[i] is marked for close, then:
470 * - If it has data that it wants to flush, try to flush it.
471 * - If it _still_ has data to flush, and conn->hold_open_until_flushed is
472 * true, then leave the connection open and return.
473 * - Otherwise, remove the connection from connection_array and from
474 * all other lists, close it, and free it.
475 * Returns 1 if the connection was closed, 0 otherwise.
477 static int
478 conn_close_if_marked(int i)
480 connection_t *conn;
481 int retval;
483 conn = connection_array[i];
484 if (!conn->marked_for_close)
485 return 0; /* nothing to see here, move along */
486 assert_connection_ok(conn, time(NULL));
487 assert_all_pending_dns_resolves_ok();
489 log_debug(LD_NET,"Cleaning up connection (fd %d).",conn->s);
490 if (conn->s >= 0 && connection_wants_to_flush(conn)) {
491 /* s == -1 means it's an incomplete edge connection, or that the socket
492 * has already been closed as unflushable. */
493 int sz = connection_bucket_write_limit(conn);
494 if (!conn->hold_open_until_flushed)
495 log_info(LD_NET,
496 "Conn (addr %s, fd %d, type %s, state %d) marked, but wants "
497 "to flush %d bytes. (Marked at %s:%d)",
498 escaped_safe_str(conn->address),
499 conn->s, conn_type_to_string(conn->type), conn->state,
500 (int)conn->outbuf_flushlen,
501 conn->marked_for_close_file, conn->marked_for_close);
502 if (connection_speaks_cells(conn)) {
503 if (conn->state == OR_CONN_STATE_OPEN) {
504 retval = flush_buf_tls(TO_OR_CONN(conn)->tls, conn->outbuf, sz,
505 &conn->outbuf_flushlen);
506 } else
507 retval = -1; /* never flush non-open broken tls connections */
508 } else {
509 retval = flush_buf(conn->s, conn->outbuf, sz, &conn->outbuf_flushlen);
511 if (retval >= 0 && /* Technically, we could survive things like
512 TLS_WANT_WRITE here. But don't bother for now. */
513 conn->hold_open_until_flushed && connection_wants_to_flush(conn)) {
514 if (retval > 0)
515 LOG_FN_CONN(conn, (LOG_INFO,LD_NET,
516 "Holding conn (fd %d) open for more flushing.",
517 conn->s));
518 /* XXX should we reset timestamp_lastwritten here? */
519 return 0;
521 if (connection_wants_to_flush(conn)) {
522 int severity;
523 if (conn->type == CONN_TYPE_EXIT ||
524 (conn->type == CONN_TYPE_OR && server_mode(get_options())) ||
525 (conn->type == CONN_TYPE_DIR && conn->purpose == DIR_PURPOSE_SERVER))
526 severity = LOG_INFO;
527 else
528 severity = LOG_NOTICE;
529 log_fn(severity, LD_NET, "Something wrong with your network connection? "
530 "We tried to write %d bytes to addr %s (fd %d, type %s, state %d)"
531 " but timed out. (Marked at %s:%d)",
532 (int)buf_datalen(conn->outbuf),
533 escaped_safe_str(conn->address), conn->s,
534 conn_type_to_string(conn->type), conn->state,
535 conn->marked_for_close_file,
536 conn->marked_for_close);
539 connection_unlink(conn, 1); /* unlink, remove, free */
540 return 1;
543 /** We've just tried every dirserver we know about, and none of
544 * them were reachable. Assume the network is down. Change state
545 * so next time an application connection arrives we'll delay it
546 * and try another directory fetch. Kill off all the circuit_wait
547 * streams that are waiting now, since they will all timeout anyway.
549 void
550 directory_all_unreachable(time_t now)
552 connection_t *conn;
553 (void)now;
555 stats_n_seconds_working=0; /* reset it */
557 while ((conn = connection_get_by_type_state(CONN_TYPE_AP,
558 AP_CONN_STATE_CIRCUIT_WAIT))) {
559 edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
560 log_notice(LD_NET,
561 "Is your network connection down? "
562 "Failing connection to '%s:%d'.",
563 safe_str(edge_conn->socks_request->address),
564 edge_conn->socks_request->port);
565 connection_mark_unattached_ap(edge_conn,
566 END_STREAM_REASON_NET_UNREACHABLE);
568 control_event_general_status(LOG_ERR, "DIR_ALL_UNREACHABLE");
571 /** This function is called whenever we successfully pull down some new
572 * network statuses or server descriptors. */
573 void
574 directory_info_has_arrived(time_t now, int from_cache)
576 or_options_t *options = get_options();
578 if (!router_have_minimum_dir_info()) {
579 log(LOG_NOTICE, LD_DIR,
580 "I learned some more directory information, but not enough to "
581 "build a circuit.");
582 update_router_descriptor_downloads(now);
583 return;
586 if (server_mode(options) && !we_are_hibernating() && !from_cache &&
587 (has_completed_circuit || !any_predicted_circuits(now)))
588 consider_testing_reachability(1, 1);
591 /** Perform regular maintenance tasks for a single connection. This
592 * function gets run once per second per connection by run_scheduled_events.
594 static void
595 run_connection_housekeeping(int i, time_t now)
597 cell_t cell;
598 connection_t *conn = connection_array[i];
599 or_options_t *options = get_options();
600 or_connection_t *or_conn;
602 if (conn->outbuf && !buf_datalen(conn->outbuf) && conn->type == CONN_TYPE_OR)
603 TO_OR_CONN(conn)->timestamp_lastempty = now;
605 if (conn->marked_for_close) {
606 /* nothing to do here */
607 return;
610 /* Expire any directory connections that haven't been active (sent
611 * if a server or received if a client) for 5 min */
612 if (conn->type == CONN_TYPE_DIR &&
613 ((DIR_CONN_IS_SERVER(conn) &&
614 conn->timestamp_lastwritten + DIR_CONN_MAX_STALL < now) ||
615 (!DIR_CONN_IS_SERVER(conn) &&
616 conn->timestamp_lastread + DIR_CONN_MAX_STALL < now))) {
617 log_info(LD_DIR,"Expiring wedged directory conn (fd %d, purpose %d)",
618 conn->s, conn->purpose);
619 /* This check is temporary; it's to let us know whether we should consider
620 * parsing partial serverdesc responses. */
621 if (conn->purpose == DIR_PURPOSE_FETCH_SERVERDESC &&
622 buf_datalen(conn->inbuf)>=1024) {
623 log_info(LD_DIR,"Trying to extract information from wedged server desc "
624 "download.");
625 connection_dir_reached_eof(TO_DIR_CONN(conn));
626 } else {
627 connection_mark_for_close(conn);
629 return;
632 if (!connection_speaks_cells(conn))
633 return; /* we're all done here, the rest is just for OR conns */
635 or_conn = TO_OR_CONN(conn);
637 if (!conn->or_is_obsolete) {
638 if (conn->timestamp_created + TIME_BEFORE_OR_CONN_IS_OBSOLETE < now) {
639 log_info(LD_OR,
640 "Marking OR conn to %s:%d obsolete (fd %d, %d secs old).",
641 conn->address, conn->port, conn->s,
642 (int)(now - conn->timestamp_created));
643 conn->or_is_obsolete = 1;
644 } else {
645 or_connection_t *best =
646 connection_or_get_by_identity_digest(or_conn->identity_digest);
647 if (best && best != or_conn &&
648 (conn->state == OR_CONN_STATE_OPEN ||
649 now > conn->timestamp_created + TLS_HANDSHAKE_TIMEOUT)) {
650 /* We only mark as obsolete connections that already are in
651 * OR_CONN_STATE_OPEN, i.e. that have finished their TLS handshaking.
652 * This is necessary because authorities judge whether a router is
653 * reachable based on whether they were able to TLS handshake with it
654 * recently. Without this check we would expire connections too
655 * early for router->last_reachable to be updated.
657 log_info(LD_OR,
658 "Marking duplicate conn to %s:%d obsolete "
659 "(fd %d, %d secs old).",
660 conn->address, conn->port, conn->s,
661 (int)(now - conn->timestamp_created));
662 conn->or_is_obsolete = 1;
667 if (conn->or_is_obsolete && !or_conn->n_circuits) {
668 /* no unmarked circs -- mark it now */
669 log_info(LD_OR,
670 "Expiring non-used OR connection to fd %d (%s:%d) [Obsolete].",
671 conn->s, conn->address, conn->port);
672 connection_mark_for_close(conn);
673 conn->hold_open_until_flushed = 1;
674 return;
677 /* If we haven't written to an OR connection for a while, then either nuke
678 the connection or send a keepalive, depending. */
679 if (now >= conn->timestamp_lastwritten + options->KeepalivePeriod) {
680 routerinfo_t *router = router_get_by_digest(or_conn->identity_digest);
681 if (!connection_state_is_open(conn)) {
682 log_info(LD_OR,"Expiring non-open OR connection to fd %d (%s:%d).",
683 conn->s,conn->address, conn->port);
684 connection_mark_for_close(conn);
685 conn->hold_open_until_flushed = 1;
686 } else if (we_are_hibernating() && !or_conn->n_circuits &&
687 !buf_datalen(conn->outbuf)) {
688 log_info(LD_OR,"Expiring non-used OR connection to fd %d (%s:%d) "
689 "[Hibernating or exiting].",
690 conn->s,conn->address, conn->port);
691 connection_mark_for_close(conn);
692 conn->hold_open_until_flushed = 1;
693 } else if (!clique_mode(options) && !or_conn->n_circuits &&
694 (!router || !server_mode(options) ||
695 !router_is_clique_mode(router))) {
696 log_info(LD_OR,"Expiring non-used OR connection to fd %d (%s:%d) "
697 "[Not in clique mode].",
698 conn->s,conn->address, conn->port);
699 connection_mark_for_close(conn);
700 conn->hold_open_until_flushed = 1;
701 } else if (
702 now >= or_conn->timestamp_lastempty + options->KeepalivePeriod*10 &&
703 now >= conn->timestamp_lastwritten + options->KeepalivePeriod*10) {
704 log_fn(LOG_PROTOCOL_WARN,LD_PROTOCOL,
705 "Expiring stuck OR connection to fd %d (%s:%d). (%d bytes to "
706 "flush; %d seconds since last write)",
707 conn->s, conn->address, conn->port,
708 (int)buf_datalen(conn->outbuf),
709 (int)(now-conn->timestamp_lastwritten));
710 connection_mark_for_close(conn);
711 } else if (!buf_datalen(conn->outbuf)) {
712 /* either in clique mode, or we've got a circuit. send a padding cell. */
713 log_fn(LOG_DEBUG,LD_OR,"Sending keepalive to (%s:%d)",
714 conn->address, conn->port);
715 memset(&cell,0,sizeof(cell_t));
716 cell.command = CELL_PADDING;
717 connection_or_write_cell_to_buf(&cell, or_conn);
722 /** Perform regular maintenance tasks. This function gets run once per
723 * second by prepare_for_poll.
725 static void
726 run_scheduled_events(time_t now)
728 static time_t last_rotated_certificate = 0;
729 static time_t time_to_check_listeners = 0;
730 static time_t time_to_check_descriptor = 0;
731 static time_t time_to_check_ipaddress = 0;
732 static time_t time_to_shrink_buffers = 0;
733 static time_t time_to_try_getting_descriptors = 0;
734 static time_t time_to_reset_descriptor_failures = 0;
735 static time_t time_to_add_entropy = 0;
736 or_options_t *options = get_options();
737 int i;
738 int have_dir_info;
740 /** 0. See if we've been asked to shut down and our timeout has
741 * expired; or if our bandwidth limits are exhausted and we
742 * should hibernate; or if it's time to wake up from hibernation.
744 consider_hibernation(now);
746 /** 1a. Every MIN_ONION_KEY_LIFETIME seconds, rotate the onion keys,
747 * shut down and restart all cpuworkers, and update the directory if
748 * necessary.
750 if (server_mode(options) &&
751 get_onion_key_set_at()+MIN_ONION_KEY_LIFETIME < now) {
752 log_info(LD_GENERAL,"Rotating onion key.");
753 rotate_onion_key();
754 cpuworkers_rotate();
755 if (router_rebuild_descriptor(1)<0) {
756 log_info(LD_CONFIG, "Couldn't rebuild router descriptor");
758 if (advertised_server_mode())
759 router_upload_dir_desc_to_dirservers(0);
762 if (time_to_try_getting_descriptors < now) {
763 /* XXXX Maybe we should do this every 10sec when not enough info,
764 * and every 60sec when we have enough info -NM */
765 update_router_descriptor_downloads(now);
766 time_to_try_getting_descriptors = now + DESCRIPTOR_RETRY_INTERVAL;
769 if (time_to_reset_descriptor_failures < now) {
770 router_reset_descriptor_download_failures();
771 time_to_reset_descriptor_failures =
772 now + DESCRIPTOR_FAILURE_RESET_INTERVAL;
775 /** 1b. Every MAX_SSL_KEY_LIFETIME seconds, we change our TLS context. */
776 if (!last_rotated_certificate)
777 last_rotated_certificate = now;
778 if (last_rotated_certificate+MAX_SSL_KEY_LIFETIME < now) {
779 log_info(LD_GENERAL,"Rotating tls context.");
780 if (tor_tls_context_new(get_identity_key(), options->Nickname,
781 MAX_SSL_KEY_LIFETIME) < 0) {
782 log_warn(LD_BUG, "Error reinitializing TLS context");
783 /* XXX is it a bug here, that we just keep going? */
785 last_rotated_certificate = now;
786 /* XXXX We should rotate TLS connections as well; this code doesn't change
787 * them at all. */
790 if (time_to_add_entropy == 0)
791 time_to_add_entropy = now + ENTROPY_INTERVAL;
792 if (time_to_add_entropy < now) {
793 /* We already seeded once, so don't die on failure. */
794 crypto_seed_rng();
795 time_to_add_entropy = now + ENTROPY_INTERVAL;
798 /** 1c. If we have to change the accounting interval or record
799 * bandwidth used in this accounting interval, do so. */
800 if (accounting_is_enabled(options))
801 accounting_run_housekeeping(now);
803 if (now % 10 == 0 && authdir_mode(options) && !we_are_hibernating()) {
804 /* try to determine reachability of the other Tor servers */
805 dirserv_test_reachability(0);
808 /** 2. Periodically, we consider getting a new directory, getting a
809 * new running-routers list, and/or force-uploading our descriptor
810 * (if we've passed our internal checks). */
811 if (time_to_fetch_directory < now) {
812 /* Only caches actually need to fetch directories now. */
813 if (options->DirPort && !options->V1AuthoritativeDir) {
814 /* XXX actually, we should only do this if we want to advertise
815 * our dirport. not simply if we configured one. -RD */
816 if (any_trusted_dir_is_v1_authority())
817 directory_get_from_dirserver(DIR_PURPOSE_FETCH_DIR, NULL, 1);
819 /** DOCDOC */
820 #define V1_DIR_FETCH_PERIOD (6*60*60)
821 time_to_fetch_directory = now + V1_DIR_FETCH_PERIOD;
824 /* Caches need to fetch running_routers; directory clients don't. */
825 if (options->DirPort && time_to_fetch_running_routers < now) {
826 if (!authdir_mode(options) || !options->V1AuthoritativeDir) {
827 directory_get_from_dirserver(DIR_PURPOSE_FETCH_RUNNING_LIST, NULL, 1);
829 /** DOCDOC */
830 #define V1_RUNNINGROUTERS_FETCH_PERIOD (30*60)
831 time_to_fetch_running_routers = now + V1_RUNNINGROUTERS_FETCH_PERIOD;
833 /* Also, take this chance to remove old information from rephist
834 * and the rend cache. */
835 rep_history_clean(now - options->RephistTrackTime);
836 rend_cache_clean();
839 /* 2b. Once per minute, regenerate and upload the descriptor if the old
840 * one is inaccurate. */
841 if (time_to_check_descriptor < now) {
842 static int dirport_reachability_count = 0;
843 time_to_check_descriptor = now + CHECK_DESCRIPTOR_INTERVAL;
844 check_descriptor_bandwidth_changed(now);
845 if (time_to_check_ipaddress < now) {
846 time_to_check_ipaddress = now + CHECK_IPADDRESS_INTERVAL;
847 check_descriptor_ipaddress_changed(now);
849 mark_my_descriptor_dirty_if_older_than(
850 now - FORCE_REGENERATE_DESCRIPTOR_INTERVAL);
851 consider_publishable_server(0);
852 /* also, check religiously for reachability, if it's within the first
853 * 20 minutes of our uptime. */
854 if (server_mode(options) &&
855 (has_completed_circuit || !any_predicted_circuits(now)) &&
856 stats_n_seconds_working < TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT &&
857 !we_are_hibernating()) {
858 consider_testing_reachability(1, dirport_reachability_count==0);
859 if (++dirport_reachability_count > 5)
860 dirport_reachability_count = 0;
863 /* If any networkstatus documents are no longer recent, we need to
864 * update all the descriptors' running status. */
865 /* purge obsolete entries */
866 routerlist_remove_old_routers();
867 networkstatus_list_clean(now);
868 networkstatus_list_update_recent(now);
869 routers_update_all_from_networkstatus();
871 /* Also, once per minute, check whether we want to download any
872 * networkstatus documents.
874 update_networkstatus_downloads(now);
877 /** 3a. Every second, we examine pending circuits and prune the
878 * ones which have been pending for more than a few seconds.
879 * We do this before step 4, so it can try building more if
880 * it's not comfortable with the number of available circuits.
882 circuit_expire_building(now);
884 /** 3b. Also look at pending streams and prune the ones that 'began'
885 * a long time ago but haven't gotten a 'connected' yet.
886 * Do this before step 4, so we can put them back into pending
887 * state to be picked up by the new circuit.
889 connection_ap_expire_beginning();
891 /** 3c. And expire connections that we've held open for too long.
893 connection_expire_held_open();
895 /** 3d. And every 60 seconds, we relaunch listeners if any died. */
896 if (!we_are_hibernating() && time_to_check_listeners < now) {
897 /* 0 means "only launch the ones that died." */
898 retry_all_listeners(0, NULL, NULL);
899 time_to_check_listeners = now+60;
902 /** 4. Every second, we try a new circuit if there are no valid
903 * circuits. Every NewCircuitPeriod seconds, we expire circuits
904 * that became dirty more than MaxCircuitDirtiness seconds ago,
905 * and we make a new circ if there are no clean circuits.
907 have_dir_info = router_have_minimum_dir_info();
908 if (have_dir_info && !we_are_hibernating())
909 circuit_build_needed_circs(now);
911 /** 5. We do housekeeping for each connection... */
912 for (i=0;i<n_conns;i++) {
913 run_connection_housekeeping(i, now);
915 if (time_to_shrink_buffers < now) {
916 for (i=0;i<n_conns;i++) {
917 connection_t *conn = connection_array[i];
918 if (conn->outbuf)
919 buf_shrink(conn->outbuf);
920 if (conn->inbuf)
921 buf_shrink(conn->inbuf);
923 time_to_shrink_buffers = now + BUF_SHRINK_INTERVAL;
926 /** 6. And remove any marked circuits... */
927 circuit_close_all_marked();
929 /** 7. And upload service descriptors if necessary. */
930 if (has_completed_circuit && !we_are_hibernating())
931 rend_consider_services_upload(now);
933 /** 8. and blow away any connections that need to die. have to do this now,
934 * because if we marked a conn for close and left its socket -1, then
935 * we'll pass it to poll/select and bad things will happen.
937 close_closeable_connections();
939 /** 8b. And if anything in our state is ready to get flushed to disk, we
940 * flush it. */
941 or_state_save(now);
943 /** 9. and if we're a server, check whether our DNS is telling stories to
944 * us. */
945 if (server_mode(options) && time_to_check_for_correct_dns < now) {
946 if (!time_to_check_for_correct_dns) {
947 time_to_check_for_correct_dns = now + 60 + crypto_rand_int(120);
948 } else {
949 dns_launch_correctness_checks();
950 time_to_check_for_correct_dns = now + 12*3600 +
951 crypto_rand_int(12*3600);
956 /** DOCDOC */
957 static struct event *timeout_event = NULL;
958 /** DOCDOC */
959 static int n_libevent_errors = 0;
961 /** Libevent callback: invoked once every second. */
962 static void
963 second_elapsed_callback(int fd, short event, void *args)
965 /* XXXX This could be sensibly refactored into multiple callbacks, and we
966 * could use libevent's timers for this rather than checking the current
967 * time against a bunch of timeouts every second. */
968 static struct timeval one_second;
969 static long current_second = 0;
970 struct timeval now;
971 size_t bytes_written;
972 size_t bytes_read;
973 int seconds_elapsed;
974 or_options_t *options = get_options();
975 (void)fd;
976 (void)event;
977 (void)args;
978 if (!timeout_event) {
979 timeout_event = tor_malloc_zero(sizeof(struct event));
980 evtimer_set(timeout_event, second_elapsed_callback, NULL);
981 one_second.tv_sec = 1;
982 one_second.tv_usec = 0;
985 n_libevent_errors = 0;
987 /* log_fn(LOG_NOTICE, "Tick."); */
988 tor_gettimeofday(&now);
990 /* the second has rolled over. check more stuff. */
991 bytes_written = stats_prev_global_write_bucket - global_write_bucket;
992 bytes_read = stats_prev_global_read_bucket - global_read_bucket;
993 seconds_elapsed = current_second ? (now.tv_sec - current_second) : 0;
994 stats_n_bytes_read += bytes_read;
995 stats_n_bytes_written += bytes_written;
996 if (accounting_is_enabled(options) && seconds_elapsed >= 0)
997 accounting_add_bytes(bytes_read, bytes_written, seconds_elapsed);
998 control_event_bandwidth_used((uint32_t)bytes_read,(uint32_t)bytes_written);
1000 if (seconds_elapsed > 0)
1001 connection_bucket_refill(seconds_elapsed);
1002 stats_prev_global_read_bucket = global_read_bucket;
1003 stats_prev_global_write_bucket = global_write_bucket;
1005 if (server_mode(options) &&
1006 !we_are_hibernating() &&
1007 seconds_elapsed > 0 &&
1008 stats_n_seconds_working / TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT !=
1009 (stats_n_seconds_working+seconds_elapsed) /
1010 TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT) {
1011 /* every 20 minutes, check and complain if necessary */
1012 routerinfo_t *me = router_get_my_routerinfo();
1013 if (me && !check_whether_orport_reachable())
1014 log_warn(LD_CONFIG,"Your server (%s:%d) has not managed to confirm that "
1015 "its ORPort is reachable. Please check your firewalls, ports, "
1016 "address, /etc/hosts file, etc.",
1017 me->address, me->or_port);
1018 if (me && !check_whether_dirport_reachable())
1019 log_warn(LD_CONFIG,
1020 "Your server (%s:%d) has not managed to confirm that its "
1021 "DirPort is reachable. Please check your firewalls, ports, "
1022 "address, /etc/hosts file, etc.",
1023 me->address, me->dir_port);
1026 /** If more than this many seconds have elapsed, probably the clock
1027 * jumped: doesn't count. */
1028 #define NUM_JUMPED_SECONDS_BEFORE_WARN 100
1029 if (seconds_elapsed < -NUM_JUMPED_SECONDS_BEFORE_WARN ||
1030 seconds_elapsed >= NUM_JUMPED_SECONDS_BEFORE_WARN) {
1031 circuit_note_clock_jumped(seconds_elapsed);
1032 /* XXX if the time jumps *back* many months, do our events in
1033 * run_scheduled_events() recover? I don't think they do. -RD */
1034 } else if (seconds_elapsed > 0)
1035 stats_n_seconds_working += seconds_elapsed;
1037 run_scheduled_events(now.tv_sec);
1039 current_second = now.tv_sec; /* remember which second it is, for next time */
1041 #if 0
1042 if (current_second % 300 == 0) {
1043 rep_history_clean(current_second - options->RephistTrackTime);
1044 dumpmemusage(get_min_log_level()<LOG_INFO ?
1045 get_min_log_level() : LOG_INFO);
1047 #endif
1049 if (evtimer_add(timeout_event, &one_second))
1050 log_err(LD_NET,
1051 "Error from libevent when setting one-second timeout event");
1054 #ifndef MS_WINDOWS
1055 /** Called when a possibly ignorable libevent error occurs; ensures that we
1056 * don't get into an infinite loop by ignoring too many errors from
1057 * libevent. */
1058 static int
1059 got_libevent_error(void)
1061 if (++n_libevent_errors > 8) {
1062 log_err(LD_NET, "Too many libevent errors in one second; dying");
1063 return -1;
1065 return 0;
1067 #endif
1069 #define UPTIME_CUTOFF_FOR_NEW_BANDWIDTH_TEST (6*60*60)
1071 /** Called when our IP address seems to have changed. <b>at_interface</b>
1072 * should be true if we detected a change in our interface, and false if we
1073 * detected a change in our published address. */
1074 void
1075 ip_address_changed(int at_interface)
1077 int server = server_mode(get_options());
1079 if (at_interface) {
1080 if (! server) {
1081 /* Okay, change our keys. */
1082 init_keys();
1084 } else {
1085 if (server) {
1086 if (stats_n_seconds_working > UPTIME_CUTOFF_FOR_NEW_BANDWIDTH_TEST)
1087 reset_bandwidth_test();
1088 stats_n_seconds_working = 0;
1089 router_reset_reachability();
1090 mark_my_descriptor_dirty();
1094 dns_servers_relaunch_checks();
1097 /** Forget what we've learned about the correctness of our DNS servers, and
1098 * start learning again. */
1099 void
1100 dns_servers_relaunch_checks(void)
1102 if (server_mode(get_options())) {
1103 dns_reset_correctness_checks();
1104 time_to_check_for_correct_dns = 0;
1108 /** Called when we get a SIGHUP: reload configuration files and keys,
1109 * retry all connections, re-upload all descriptors, and so on. */
1110 static int
1111 do_hup(void)
1113 or_options_t *options = get_options();
1115 log_notice(LD_GENERAL,"Received reload signal (hup). Reloading config.");
1116 if (accounting_is_enabled(options))
1117 accounting_record_bandwidth_usage(time(NULL), get_or_state());
1119 router_reset_warnings();
1120 routerlist_reset_warnings();
1121 addressmap_clear_transient();
1122 /* first, reload config variables, in case they've changed */
1123 /* no need to provide argc/v, they've been cached inside init_from_config */
1124 if (options_init_from_torrc(0, NULL) < 0) {
1125 log_err(LD_CONFIG,"Reading config failed--see warnings above. "
1126 "For usage, try -h.");
1127 return -1;
1129 options = get_options(); /* they have changed now */
1130 if (authdir_mode(options)) {
1131 /* reload the approved-routers file */
1132 if (dirserv_load_fingerprint_file() < 0) {
1133 /* warnings are logged from dirserv_load_fingerprint_file() directly */
1134 log_info(LD_GENERAL, "Error reloading fingerprints. "
1135 "Continuing with old list.");
1139 /* Rotate away from the old dirty circuits. This has to be done
1140 * after we've read the new options, but before we start using
1141 * circuits for directory fetches. */
1142 circuit_expire_all_dirty_circs();
1144 /* retry appropriate downloads */
1145 router_reset_status_download_failures();
1146 router_reset_descriptor_download_failures();
1147 update_networkstatus_downloads(time(NULL));
1149 /* We'll retry routerstatus downloads in about 10 seconds; no need to
1150 * force a retry there. */
1152 if (server_mode(options)) {
1153 // const char *descriptor;
1154 mark_my_descriptor_dirty();
1155 /* Restart cpuworker and dnsworker processes, so they get up-to-date
1156 * configuration options. */
1157 cpuworkers_rotate();
1158 dns_reset();
1159 #if 0
1160 const char *descriptor;
1161 char keydir[512];
1162 /* Write out a fresh descriptor, but leave old one on failure. */
1163 router_rebuild_descriptor(1);
1164 descriptor = router_get_my_descriptor();
1165 if (descriptor) {
1166 tor_snprintf(keydir,sizeof(keydir),"%s/router.desc",
1167 options->DataDirectory);
1168 log_info(LD_OR,"Saving descriptor to \"%s\"...",keydir);
1169 if (write_str_to_file(keydir, descriptor, 0)) {
1170 return 0;
1173 #endif
1175 return 0;
1178 /** Tor main loop. */
1179 static int
1180 do_main_loop(void)
1182 int loop_result;
1184 /* initialize dns resolve map, spawn workers if needed */
1185 if (dns_init() < 0) {
1186 log_err(LD_GENERAL,"Error initializing dns subsystem; exiting");
1187 return -1;
1190 handle_signals(1);
1192 /* load the private keys, if we're supposed to have them, and set up the
1193 * TLS context. */
1194 if (! identity_key_is_set()) {
1195 if (init_keys() < 0) {
1196 log_err(LD_BUG,"Error initializing keys; exiting");
1197 return -1;
1201 /* Set up our buckets */
1202 connection_bucket_init();
1203 stats_prev_global_read_bucket = global_read_bucket;
1204 stats_prev_global_write_bucket = global_write_bucket;
1206 /* load the routers file, or assign the defaults. */
1207 if (router_reload_router_list()) {
1208 return -1;
1210 /* load the networkstatuses. (This launches a download for new routers as
1211 * appropriate.)
1213 if (router_reload_networkstatus()) {
1214 return -1;
1216 directory_info_has_arrived(time(NULL),1);
1218 if (authdir_mode(get_options())) {
1219 /* the directory is already here, run startup things */
1220 dirserv_test_reachability(1);
1223 if (server_mode(get_options())) {
1224 /* launch cpuworkers. Need to do this *after* we've read the onion key. */
1225 cpu_init();
1228 /* set up once-a-second callback. */
1229 second_elapsed_callback(0,0,NULL);
1231 for (;;) {
1232 if (nt_service_is_stopped())
1233 return 0;
1235 #ifndef MS_WINDOWS
1236 /* Make it easier to tell whether libevent failure is our fault or not. */
1237 errno = 0;
1238 #endif
1239 /* poll until we have an event, or the second ends */
1240 loop_result = event_dispatch();
1242 /* let catch() handle things like ^c, and otherwise don't worry about it */
1243 if (loop_result < 0) {
1244 int e = tor_socket_errno(-1);
1245 /* let the program survive things like ^z */
1246 if (e != EINTR && !ERRNO_IS_EINPROGRESS(e)) {
1247 #ifdef HAVE_EVENT_GET_METHOD
1248 log_err(LD_NET,"libevent call with %s failed: %s [%d]",
1249 event_get_method(), tor_socket_strerror(e), e);
1250 #else
1251 log_err(LD_NET,"libevent call failed: %s [%d]",
1252 tor_socket_strerror(e), e);
1253 #endif
1254 return -1;
1255 #ifndef MS_WINDOWS
1256 } else if (e == EINVAL) {
1257 log_warn(LD_NET, "EINVAL from libevent: should you upgrade libevent?");
1258 if (got_libevent_error())
1259 return -1;
1260 #endif
1261 } else {
1262 if (ERRNO_IS_EINPROGRESS(e))
1263 log_warn(LD_BUG,
1264 "libevent call returned EINPROGRESS? Please report.");
1265 log_debug(LD_NET,"libevent call interrupted.");
1266 /* You can't trust the results of this poll(). Go back to the
1267 * top of the big for loop. */
1268 continue;
1272 /* refilling buckets and sending cells happens at the beginning of the
1273 * next iteration of the loop, inside prepare_for_poll()
1274 * XXXX No longer so.
1279 /** Used to implement the SIGNAL control command: if we accept
1280 * <b>the_signal</b> as a remote pseudo-signal, act on it. */
1281 /* We don't re-use catch() here because:
1282 * 1. We handle a different set of signals than those allowed in catch.
1283 * 2. Platforms without signal() are unlikely to define SIGfoo.
1284 * 3. The control spec is defined to use fixed numeric signal values
1285 * which just happen to match the unix values.
1287 void
1288 control_signal_act(int the_signal)
1290 switch (the_signal)
1292 case 1:
1293 signal_callback(0,0,(void*)(uintptr_t)SIGHUP);
1294 break;
1295 case 2:
1296 signal_callback(0,0,(void*)(uintptr_t)SIGINT);
1297 break;
1298 case 10:
1299 signal_callback(0,0,(void*)(uintptr_t)SIGUSR1);
1300 break;
1301 case 12:
1302 signal_callback(0,0,(void*)(uintptr_t)SIGUSR2);
1303 break;
1304 case 15:
1305 signal_callback(0,0,(void*)(uintptr_t)SIGTERM);
1306 break;
1307 case SIGNEWNYM:
1308 signal_callback(0,0,(void*)(uintptr_t)SIGNEWNYM);
1309 break;
1310 case SIGCLEARDNSCACHE:
1311 signal_callback(0,0,(void*)(uintptr_t)SIGCLEARDNSCACHE);
1312 break;
1313 default:
1314 log_warn(LD_BUG, "Unrecognized signal number %d.", the_signal);
1315 break;
1319 /** Libevent callback: invoked when we get a signal.
1321 static void
1322 signal_callback(int fd, short events, void *arg)
1324 uintptr_t sig = (uintptr_t)arg;
1325 (void)fd;
1326 (void)events;
1327 switch (sig)
1329 case SIGTERM:
1330 log_err(LD_GENERAL,"Catching signal TERM, exiting cleanly.");
1331 tor_cleanup();
1332 exit(0);
1333 break;
1334 case SIGINT:
1335 if (!server_mode(get_options())) { /* do it now */
1336 log_notice(LD_GENERAL,"Interrupt: exiting cleanly.");
1337 tor_cleanup();
1338 exit(0);
1340 hibernate_begin_shutdown();
1341 break;
1342 #ifdef SIGPIPE
1343 case SIGPIPE:
1344 log_debug(LD_GENERAL,"Caught sigpipe. Ignoring.");
1345 break;
1346 #endif
1347 case SIGUSR1:
1348 /* prefer to log it at INFO, but make sure we always see it */
1349 dumpstats(get_min_log_level()<LOG_INFO ? get_min_log_level() : LOG_INFO);
1350 break;
1351 case SIGUSR2:
1352 switch_logs_debug();
1353 log_debug(LD_GENERAL,"Caught USR2, going to loglevel debug. "
1354 "Send HUP to change back.");
1355 break;
1356 case SIGHUP:
1357 if (do_hup() < 0) {
1358 log_warn(LD_CONFIG,"Restart failed (config error?). Exiting.");
1359 tor_cleanup();
1360 exit(1);
1362 break;
1363 #ifdef SIGCHLD
1364 case SIGCHLD:
1365 while (waitpid(-1,NULL,WNOHANG) > 0) ; /* keep reaping until no more
1366 zombies */
1367 break;
1368 #endif
1369 case SIGNEWNYM:
1370 circuit_expire_all_dirty_circs();
1371 addressmap_clear_transient();
1372 break;
1373 case SIGCLEARDNSCACHE:
1374 addressmap_clear_transient();
1375 break;
1379 extern uint64_t buf_total_used;
1380 extern uint64_t buf_total_alloc;
1381 extern uint64_t rephist_total_alloc;
1382 extern uint32_t rephist_total_num;
1385 * Write current memory usage information to the log.
1387 static void
1388 dumpmemusage(int severity)
1390 log(severity, LD_GENERAL,
1391 "In buffers: "U64_FORMAT" used/"U64_FORMAT" allocated (%d conns).",
1392 U64_PRINTF_ARG(buf_total_used), U64_PRINTF_ARG(buf_total_alloc),
1393 n_conns);
1394 log(severity, LD_GENERAL, "In rephist: "U64_FORMAT" used by %d Tors.",
1395 U64_PRINTF_ARG(rephist_total_alloc), rephist_total_num);
1396 dump_routerlist_mem_usage(severity);
1399 /** Write all statistics to the log, with log level 'severity'. Called
1400 * in response to a SIGUSR1. */
1401 static void
1402 dumpstats(int severity)
1404 int i;
1405 connection_t *conn;
1406 time_t now = time(NULL);
1407 time_t elapsed;
1409 log(severity, LD_GENERAL, "Dumping stats:");
1411 for (i=0;i<n_conns;i++) {
1412 conn = connection_array[i];
1413 log(severity, LD_GENERAL,
1414 "Conn %d (socket %d) type %d (%s), state %d (%s), created %d secs ago",
1415 i, conn->s, conn->type, conn_type_to_string(conn->type),
1416 conn->state, conn_state_to_string(conn->type, conn->state),
1417 (int)(now - conn->timestamp_created));
1418 if (!connection_is_listener(conn)) {
1419 log(severity,LD_GENERAL,
1420 "Conn %d is to %s:%d.", i,
1421 safe_str(conn->address), conn->port);
1422 log(severity,LD_GENERAL,
1423 "Conn %d: %d bytes waiting on inbuf (len %d, last read %d secs ago)",
1425 (int)buf_datalen(conn->inbuf),
1426 (int)buf_capacity(conn->inbuf),
1427 (int)(now - conn->timestamp_lastread));
1428 log(severity,LD_GENERAL,
1429 "Conn %d: %d bytes waiting on outbuf "
1430 "(len %d, last written %d secs ago)",i,
1431 (int)buf_datalen(conn->outbuf),
1432 (int)buf_capacity(conn->outbuf),
1433 (int)(now - conn->timestamp_lastwritten));
1435 circuit_dump_by_conn(conn, severity); /* dump info about all the circuits
1436 * using this conn */
1438 log(severity, LD_NET,
1439 "Cells processed: "U64_FORMAT" padding\n"
1440 " "U64_FORMAT" create\n"
1441 " "U64_FORMAT" created\n"
1442 " "U64_FORMAT" relay\n"
1443 " ("U64_FORMAT" relayed)\n"
1444 " ("U64_FORMAT" delivered)\n"
1445 " "U64_FORMAT" destroy",
1446 U64_PRINTF_ARG(stats_n_padding_cells_processed),
1447 U64_PRINTF_ARG(stats_n_create_cells_processed),
1448 U64_PRINTF_ARG(stats_n_created_cells_processed),
1449 U64_PRINTF_ARG(stats_n_relay_cells_processed),
1450 U64_PRINTF_ARG(stats_n_relay_cells_relayed),
1451 U64_PRINTF_ARG(stats_n_relay_cells_delivered),
1452 U64_PRINTF_ARG(stats_n_destroy_cells_processed));
1453 if (stats_n_data_cells_packaged)
1454 log(severity,LD_NET,"Average packaged cell fullness: %2.3f%%",
1455 100*(U64_TO_DBL(stats_n_data_bytes_packaged) /
1456 U64_TO_DBL(stats_n_data_cells_packaged*RELAY_PAYLOAD_SIZE)) );
1457 if (stats_n_data_cells_received)
1458 log(severity,LD_NET,"Average delivered cell fullness: %2.3f%%",
1459 100*(U64_TO_DBL(stats_n_data_bytes_received) /
1460 U64_TO_DBL(stats_n_data_cells_received*RELAY_PAYLOAD_SIZE)) );
1462 if (now - time_of_process_start >= 0)
1463 elapsed = now - time_of_process_start;
1464 else
1465 elapsed = 0;
1467 if (elapsed) {
1468 log(severity, LD_NET,
1469 "Average bandwidth: "U64_FORMAT"/%d = %d bytes/sec reading",
1470 U64_PRINTF_ARG(stats_n_bytes_read),
1471 (int)elapsed,
1472 (int) (stats_n_bytes_read/elapsed));
1473 log(severity, LD_NET,
1474 "Average bandwidth: "U64_FORMAT"/%d = %d bytes/sec writing",
1475 U64_PRINTF_ARG(stats_n_bytes_written),
1476 (int)elapsed,
1477 (int) (stats_n_bytes_written/elapsed));
1480 log(severity, LD_NET, "--------------- Dumping memory information:");
1481 dumpmemusage(severity);
1483 rep_hist_dump_stats(now,severity);
1484 rend_service_dump_stats(severity);
1485 dump_pk_ops(severity);
1486 dump_distinct_digest_count(severity);
1489 /** Called by exit() as we shut down the process.
1491 static void
1492 exit_function(void)
1494 /* NOTE: If we ever daemonize, this gets called immediately. That's
1495 * okay for now, because we only use this on Windows. */
1496 #ifdef MS_WINDOWS
1497 WSACleanup();
1498 #endif
1501 /** Set up the signal handlers for either parent or child. */
1502 void
1503 handle_signals(int is_parent)
1505 #ifndef MS_WINDOWS /* do signal stuff only on unix */
1506 int i;
1507 static int signals[] = {
1508 SIGINT, /* do a controlled slow shutdown */
1509 SIGTERM, /* to terminate now */
1510 SIGPIPE, /* otherwise sigpipe kills us */
1511 SIGUSR1, /* dump stats */
1512 SIGUSR2, /* go to loglevel debug */
1513 SIGHUP, /* to reload config, retry conns, etc */
1514 #ifdef SIGXFSZ
1515 SIGXFSZ, /* handle file-too-big resource exhaustion */
1516 #endif
1517 SIGCHLD, /* handle dns/cpu workers that exit */
1518 -1 };
1519 static struct event signal_events[16]; /* bigger than it has to be. */
1520 if (is_parent) {
1521 for (i = 0; signals[i] >= 0; ++i) {
1522 signal_set(&signal_events[i], signals[i], signal_callback,
1523 (void*)(uintptr_t)signals[i]);
1524 if (signal_add(&signal_events[i], NULL))
1525 log_warn(LD_BUG, "Error from libevent when adding event for signal %d",
1526 signals[i]);
1528 } else {
1529 struct sigaction action;
1530 action.sa_flags = 0;
1531 sigemptyset(&action.sa_mask);
1532 action.sa_handler = SIG_IGN;
1533 sigaction(SIGINT, &action, NULL);
1534 sigaction(SIGTERM, &action, NULL);
1535 sigaction(SIGPIPE, &action, NULL);
1536 sigaction(SIGUSR1, &action, NULL);
1537 sigaction(SIGUSR2, &action, NULL);
1538 sigaction(SIGHUP, &action, NULL);
1539 #ifdef SIGXFSZ
1540 sigaction(SIGXFSZ, &action, NULL);
1541 #endif
1543 #endif /* signal stuff */
1546 /** Main entry point for the Tor command-line client.
1548 static int
1549 tor_init(int argc, char *argv[])
1551 time_of_process_start = time(NULL);
1552 if (!closeable_connection_lst)
1553 closeable_connection_lst = smartlist_create();
1554 /* Initialize the history structures. */
1555 rep_hist_init();
1556 /* Initialize the service cache. */
1557 rend_cache_init();
1558 addressmap_init(); /* Init the client dns cache. Do it always, since it's
1559 * cheap. */
1561 /* give it somewhere to log to initially */
1562 add_temp_log();
1564 log(LOG_NOTICE, LD_GENERAL, "Tor v%s. This is experimental software. "
1565 "Do not rely on it for strong anonymity.",VERSION);
1567 if (network_init()<0) {
1568 log_err(LD_BUG,"Error initializing network; exiting.");
1569 return -1;
1571 atexit(exit_function);
1573 if (options_init_from_torrc(argc,argv) < 0) {
1574 log_err(LD_CONFIG,"Reading config failed--see warnings above.");
1575 return -1;
1578 #ifndef MS_WINDOWS
1579 if (geteuid()==0)
1580 log_warn(LD_GENERAL,"You are running Tor as root. You don't need to, "
1581 "and you probably shouldn't.");
1582 #endif
1584 crypto_global_init(get_options()->HardwareAccel);
1585 if (crypto_seed_rng()) {
1586 log_err(LD_BUG, "Unable to seed random number generator. Exiting.");
1587 return -1;
1590 return 0;
1593 /** Free all memory that we might have allocated somewhere.
1594 * Helps us find the real leaks with dmalloc and the like.
1596 * Also valgrind should then report 0 reachable in its
1597 * leak report */
1598 void
1599 tor_free_all(int postfork)
1601 #ifdef USE_EVENTDNS
1602 if (!postfork) {
1603 evdns_shutdown(1);
1605 #endif
1606 routerlist_free_all();
1607 addressmap_free_all();
1608 set_exit_redirects(NULL); /* free the registered exit redirects */
1609 dirserv_free_all();
1610 rend_service_free_all();
1611 rend_cache_free_all();
1612 rep_hist_free_all();
1613 dns_free_all();
1614 clear_pending_onions();
1615 circuit_free_all();
1616 entry_guards_free_all();
1617 connection_free_all();
1618 policies_free_all();
1619 if (!postfork) {
1620 config_free_all();
1621 router_free_all();
1623 tor_tls_free_all();
1624 /* stuff in main.c */
1625 smartlist_free(closeable_connection_lst);
1626 tor_free(timeout_event);
1627 /* Stuff in util.c */
1628 escaped(NULL);
1629 if (!postfork) {
1630 close_logs(); /* free log strings. do this last so logs keep working. */
1634 /** Do whatever cleanup is necessary before shutting Tor down. */
1635 void
1636 tor_cleanup(void)
1638 or_options_t *options = get_options();
1639 /* Remove our pid file. We don't care if there was an error when we
1640 * unlink, nothing we could do about it anyways. */
1641 if (options->command == CMD_RUN_TOR) {
1642 if (options->PidFile)
1643 unlink(options->PidFile);
1644 if (accounting_is_enabled(options))
1645 accounting_record_bandwidth_usage(time(NULL), get_or_state());
1646 or_state_mark_dirty(get_or_state(), 0); /* force an immediate save. */
1647 or_state_save(time(NULL));
1649 tor_free_all(0); /* move tor_free_all back into the ifdef below later. XXX*/
1650 crypto_global_cleanup();
1651 #ifdef USE_DMALLOC
1652 dmalloc_log_unfreed();
1653 dmalloc_shutdown();
1654 #endif
1657 /** Read/create keys as needed, and echo our fingerprint to stdout. */
1658 static int
1659 do_list_fingerprint(void)
1661 char buf[FINGERPRINT_LEN+1];
1662 crypto_pk_env_t *k;
1663 const char *nickname = get_options()->Nickname;
1664 if (!server_mode(get_options())) {
1665 log_err(LD_GENERAL,
1666 "Clients don't have long-term identity keys. Exiting.\n");
1667 return -1;
1669 tor_assert(nickname);
1670 if (init_keys() < 0) {
1671 log_err(LD_BUG,"Error initializing keys; can't display fingerprint");
1672 return -1;
1674 if (!(k = get_identity_key())) {
1675 log_err(LD_GENERAL,"Error: missing identity key.");
1676 return -1;
1678 if (crypto_pk_get_fingerprint(k, buf, 1)<0) {
1679 log_err(LD_BUG, "Error computing fingerprint");
1680 return -1;
1682 printf("%s %s\n", nickname, buf);
1683 return 0;
1686 /** Entry point for password hashing: take the desired password from
1687 * the command line, and print its salted hash to stdout. **/
1688 static void
1689 do_hash_password(void)
1692 char output[256];
1693 char key[S2K_SPECIFIER_LEN+DIGEST_LEN];
1695 crypto_rand(key, S2K_SPECIFIER_LEN-1);
1696 key[S2K_SPECIFIER_LEN-1] = (uint8_t)96; /* Hash 64 K of data. */
1697 secret_to_key(key+S2K_SPECIFIER_LEN, DIGEST_LEN,
1698 get_options()->command_arg, strlen(get_options()->command_arg),
1699 key);
1700 base16_encode(output, sizeof(output), key, sizeof(key));
1701 printf("16:%s\n",output);
1704 #ifdef MS_WINDOWS_SERVICE
1706 struct service_fns {
1707 int loaded;
1709 BOOL (WINAPI *ChangeServiceConfig2A_fn)(
1710 SC_HANDLE hService,
1711 DWORD dwInfoLevel,
1712 LPVOID lpInfo);
1714 BOOL (WINAPI *CloseServiceHandle_fn)(
1715 SC_HANDLE hSCObject);
1717 BOOL (WINAPI *ControlService_fn)(
1718 SC_HANDLE hService,
1719 DWORD dwControl,
1720 LPSERVICE_STATUS lpServiceStatus);
1722 SC_HANDLE (WINAPI *CreateServiceA_fn)(
1723 SC_HANDLE hSCManager,
1724 LPCTSTR lpServiceName,
1725 LPCTSTR lpDisplayName,
1726 DWORD dwDesiredAccess,
1727 DWORD dwServiceType,
1728 DWORD dwStartType,
1729 DWORD dwErrorControl,
1730 LPCTSTR lpBinaryPathName,
1731 LPCTSTR lpLoadOrderGroup,
1732 LPDWORD lpdwTagId,
1733 LPCTSTR lpDependencies,
1734 LPCTSTR lpServiceStartName,
1735 LPCTSTR lpPassword);
1737 BOOL (WINAPI *DeleteService_fn)(
1738 SC_HANDLE hService);
1740 SC_HANDLE (WINAPI *OpenSCManagerA_fn)(
1741 LPCTSTR lpMachineName,
1742 LPCTSTR lpDatabaseName,
1743 DWORD dwDesiredAccess);
1745 SC_HANDLE (WINAPI *OpenServiceA_fn)(
1746 SC_HANDLE hSCManager,
1747 LPCTSTR lpServiceName,
1748 DWORD dwDesiredAccess);
1750 BOOL (WINAPI *QueryServiceStatus_fn)(
1751 SC_HANDLE hService,
1752 LPSERVICE_STATUS lpServiceStatus);
1754 SERVICE_STATUS_HANDLE (WINAPI *RegisterServiceCtrlHandlerA_fn)(
1755 LPCTSTR lpServiceName,
1756 LPHANDLER_FUNCTION lpHandlerProc);
1758 BOOL (WINAPI *SetServiceStatus_fn)(SERVICE_STATUS_HANDLE,
1759 LPSERVICE_STATUS);
1761 BOOL (WINAPI *StartServiceCtrlDispatcherA_fn)(
1762 const SERVICE_TABLE_ENTRY* lpServiceTable);
1764 BOOL (WINAPI *StartServiceA_fn)(
1765 SC_HANDLE hService,
1766 DWORD dwNumServiceArgs,
1767 LPCTSTR* lpServiceArgVectors);
1769 BOOL (WINAPI *LookupAccountNameA_fn)(
1770 LPCTSTR lpSystemName,
1771 LPCTSTR lpAccountName,
1772 PSID Sid,
1773 LPDWORD cbSid,
1774 LPTSTR ReferencedDomainName,
1775 LPDWORD cchReferencedDomainName,
1776 PSID_NAME_USE peUse);
1777 } service_fns = { 0,
1778 NULL, NULL, NULL, NULL, NULL, NULL,
1779 NULL, NULL, NULL, NULL, NULL, NULL,
1780 NULL};
1782 /** Loads functions used by NT services. Returns 0 on success, or -1 on
1783 * error. */
1784 static int
1785 nt_service_loadlibrary(void)
1787 HMODULE library = 0;
1788 void *fn;
1790 if (service_fns.loaded)
1791 return 0;
1793 /* XXXX Possibly, we should hardcode the location of this DLL. */
1794 if (!(library = LoadLibrary("advapi32.dll"))) {
1795 log_err(LD_GENERAL, "Couldn't open advapi32.dll. Are you trying to use "
1796 "NT services on Windows 98? That doesn't work.");
1797 return -1;
1800 #define LOAD(f) do { \
1801 if (!(fn = GetProcAddress(library, #f))) { \
1802 log_err(LD_BUG, \
1803 "Couldn't find %s in advapi32.dll! We probably got the " \
1804 "name wrong.", #f); \
1805 return -1; \
1806 } else { \
1807 service_fns.f ## _fn = fn; \
1809 } while (0)
1811 LOAD(ChangeServiceConfig2A);
1812 LOAD(CloseServiceHandle);
1813 LOAD(ControlService);
1814 LOAD(CreateServiceA);
1815 LOAD(DeleteService);
1816 LOAD(OpenSCManagerA);
1817 LOAD(OpenServiceA);
1818 LOAD(QueryServiceStatus);
1819 LOAD(RegisterServiceCtrlHandlerA);
1820 LOAD(SetServiceStatus);
1821 LOAD(StartServiceCtrlDispatcherA);
1822 LOAD(StartServiceA);
1823 LOAD(LookupAccountNameA);
1825 service_fns.loaded = 1;
1827 return 0;
1830 /** If we're compiled to run as an NT service, and the service has been
1831 * shut down, then change our current status and return 1. Else
1832 * return 0.
1834 static int
1835 nt_service_is_stopped(void)
1837 if (nt_service_loadlibrary()<0)
1838 return -1;
1840 if (service_status.dwCurrentState == SERVICE_STOP_PENDING) {
1841 service_status.dwWin32ExitCode = 0;
1842 service_status.dwCurrentState = SERVICE_STOPPED;
1843 service_fns.SetServiceStatus_fn(hStatus, &service_status);
1844 return 1;
1845 } else if (service_status.dwCurrentState == SERVICE_STOPPED) {
1846 return 1;
1848 return 0;
1851 /** Handles service control requests, such as stopping or starting the
1852 * Tor service. */
1853 void
1854 nt_service_control(DWORD request)
1856 static struct timeval exit_now;
1857 exit_now.tv_sec = 0;
1858 exit_now.tv_usec = 0;
1860 if (nt_service_loadlibrary()<0)
1861 return;
1863 switch (request) {
1864 case SERVICE_CONTROL_STOP:
1865 case SERVICE_CONTROL_SHUTDOWN:
1866 log_err(LD_GENERAL,
1867 "Got stop/shutdown request; shutting down cleanly.");
1868 service_status.dwCurrentState = SERVICE_STOP_PENDING;
1869 event_loopexit(&exit_now);
1870 return;
1872 service_fns.SetServiceStatus_fn(hStatus, &service_status);
1875 /** Called when the service is started via the system's service control
1876 * manager. This calls tor_init() and starts the main event loop. If
1877 * tor_init() fails, the service will be stopped and exit code set to
1878 * NT_SERVICE_ERROR_TORINIT_FAILED. */
1879 void
1880 nt_service_body(int argc, char **argv)
1882 int r;
1883 if (nt_service_loadlibrary()<0)
1884 return;
1885 service_status.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
1886 service_status.dwCurrentState = SERVICE_START_PENDING;
1887 service_status.dwControlsAccepted =
1888 SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
1889 service_status.dwWin32ExitCode = 0;
1890 service_status.dwServiceSpecificExitCode = 0;
1891 service_status.dwCheckPoint = 0;
1892 service_status.dwWaitHint = 1000;
1893 hStatus = service_fns.RegisterServiceCtrlHandlerA_fn(GENSRV_SERVICENAME,
1894 (LPHANDLER_FUNCTION) nt_service_control);
1896 if (hStatus == 0) {
1897 /* Failed to register the service control handler function */
1898 return;
1901 r = tor_init(backup_argc, backup_argv);
1902 if (r) {
1903 /* Failed to start the Tor service */
1904 r = NT_SERVICE_ERROR_TORINIT_FAILED;
1905 service_status.dwCurrentState = SERVICE_STOPPED;
1906 service_status.dwWin32ExitCode = r;
1907 service_status.dwServiceSpecificExitCode = r;
1908 service_fns.SetServiceStatus_fn(hStatus, &service_status);
1909 return;
1912 /* Set the service's status to SERVICE_RUNNING and start the main
1913 * event loop */
1914 service_status.dwCurrentState = SERVICE_RUNNING;
1915 service_fns.SetServiceStatus_fn(hStatus, &service_status);
1916 do_main_loop();
1917 tor_cleanup();
1920 /** Main service entry point. Starts the service control dispatcher and waits
1921 * until the service status is set to SERVICE_STOPPED. */
1922 void
1923 nt_service_main(void)
1925 SERVICE_TABLE_ENTRY table[2];
1926 DWORD result = 0;
1927 char *errmsg;
1928 if (nt_service_loadlibrary()<0)
1929 return;
1930 table[0].lpServiceName = GENSRV_SERVICENAME;
1931 table[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTION)nt_service_body;
1932 table[1].lpServiceName = NULL;
1933 table[1].lpServiceProc = NULL;
1935 if (!service_fns.StartServiceCtrlDispatcherA_fn(table)) {
1936 result = GetLastError();
1937 errmsg = nt_strerror(result);
1938 printf("Service error %d : %s\n", (int) result, errmsg);
1939 LocalFree(errmsg);
1940 if (result == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) {
1941 if (tor_init(backup_argc, backup_argv) < 0)
1942 return;
1943 switch (get_options()->command) {
1944 case CMD_RUN_TOR:
1945 do_main_loop();
1946 break;
1947 case CMD_LIST_FINGERPRINT:
1948 do_list_fingerprint();
1949 break;
1950 case CMD_HASH_PASSWORD:
1951 do_hash_password();
1952 break;
1953 case CMD_VERIFY_CONFIG:
1954 printf("Configuration was valid\n");
1955 break;
1956 default:
1957 log_err(LD_CONFIG, "Illegal command number %d: internal error.",
1958 get_options()->command);
1960 tor_cleanup();
1965 /** Return a handle to the service control manager on success, or NULL on
1966 * failure. */
1967 SC_HANDLE
1968 nt_service_open_scm(void)
1970 SC_HANDLE hSCManager;
1971 char *errmsg = NULL;
1973 if (nt_service_loadlibrary()<0)
1974 return 0;
1975 if ((hSCManager = service_fns.OpenSCManagerA_fn(
1976 NULL, NULL, SC_MANAGER_CREATE_SERVICE)) == NULL) {
1977 errmsg = nt_strerror(GetLastError());
1978 printf("OpenSCManager() failed : %s\n", errmsg);
1979 LocalFree(errmsg);
1981 return hSCManager;
1984 /** Open a handle to the Tor service using <b>hSCManager</b>. Return NULL
1985 * on failure. */
1986 SC_HANDLE
1987 nt_service_open(SC_HANDLE hSCManager)
1989 SC_HANDLE hService;
1990 char *errmsg = NULL;
1992 if (nt_service_loadlibrary()<0)
1993 return 0;
1994 if ((hService = service_fns.OpenServiceA_fn(hSCManager, GENSRV_SERVICENAME,
1995 SERVICE_ALL_ACCESS)) == NULL) {
1996 errmsg = nt_strerror(GetLastError());
1997 printf("OpenService() failed : %s\n", errmsg);
1998 LocalFree(errmsg);
2000 return hService;
2003 /** Start the Tor service. Return 0 if the service is started or was
2004 * previously running. Return -1 on error. */
2006 nt_service_start(SC_HANDLE hService)
2008 char *errmsg = NULL;
2010 if (nt_service_loadlibrary()<0)
2011 return -1;
2013 service_fns.QueryServiceStatus_fn(hService, &service_status);
2014 if (service_status.dwCurrentState == SERVICE_RUNNING) {
2015 printf("Service is already running\n");
2016 return 0;
2019 if (service_fns.StartServiceA_fn(hService, 0, NULL)) {
2020 /* Loop until the service has finished attempting to start */
2021 while (service_fns.QueryServiceStatus_fn(hService, &service_status) &&
2022 (service_status.dwCurrentState == SERVICE_START_PENDING)) {
2023 Sleep(500);
2026 /* Check if it started successfully or not */
2027 if (service_status.dwCurrentState == SERVICE_RUNNING) {
2028 printf("Service started successfully\n");
2029 return 0;
2030 } else {
2031 errmsg = nt_strerror(service_status.dwWin32ExitCode);
2032 printf("Service failed to start : %s\n", errmsg);
2033 LocalFree(errmsg);
2035 } else {
2036 errmsg = nt_strerror(GetLastError());
2037 printf("StartService() failed : %s\n", errmsg);
2038 LocalFree(errmsg);
2040 return -1;
2043 /** Stop the Tor service. Return 0 if the service is stopped or was not
2044 * previously running. Return -1 on error. */
2046 nt_service_stop(SC_HANDLE hService)
2048 /** Wait at most 10 seconds for the service to stop. */
2049 #define MAX_SERVICE_WAIT_TIME 10
2050 int wait_time;
2051 char *errmsg = NULL;
2052 if (nt_service_loadlibrary()<0)
2053 return -1;
2055 service_fns.QueryServiceStatus_fn(hService, &service_status);
2056 if (service_status.dwCurrentState == SERVICE_STOPPED) {
2057 printf("Service is already stopped\n");
2058 return 0;
2061 if (service_fns.ControlService_fn(hService, SERVICE_CONTROL_STOP,
2062 &service_status)) {
2063 wait_time = 0;
2064 while (service_fns.QueryServiceStatus_fn(hService, &service_status) &&
2065 (service_status.dwCurrentState != SERVICE_STOPPED) &&
2066 (wait_time < MAX_SERVICE_WAIT_TIME)) {
2067 Sleep(1000);
2068 wait_time++;
2070 if (service_status.dwCurrentState == SERVICE_STOPPED) {
2071 printf("Service stopped successfully\n");
2072 return 0;
2073 } else if (wait_time == MAX_SERVICE_WAIT_TIME) {
2074 printf("Service did not stop within %d seconds.\n", wait_time);
2075 } else {
2076 errmsg = nt_strerror(GetLastError());
2077 printf("QueryServiceStatus() failed : %s\n",errmsg);
2078 LocalFree(errmsg);
2080 } else {
2081 errmsg = nt_strerror(GetLastError());
2082 printf("ControlService() failed : %s\n", errmsg);
2083 LocalFree(errmsg);
2085 return -1;
2088 /** Build a formatted command line used for the NT service. Return a
2089 * pointer to the formatted string on success, or NULL on failure. */
2090 char *
2091 nt_service_command_line(void)
2093 TCHAR tor_exe[MAX_PATH+1];
2094 char *command, *options;
2095 const char *torrc;
2096 smartlist_t *sl;
2097 int i, cmdlen;
2098 int use_default_torrc = 1;
2100 /* Get the location of tor.exe */
2101 if (0 == GetModuleFileName(NULL, tor_exe, MAX_PATH))
2102 return NULL;
2104 /* Get the service arguments */
2105 sl = smartlist_create();
2106 torrc = get_torrc_fname();
2107 for (i = 1; i < backup_argc; ++i) {
2108 if (!strcmp(backup_argv[i], "--options") ||
2109 !strcmp(backup_argv[i], "-options")) {
2110 while (++i < backup_argc) {
2111 if (!strcmp(backup_argv[i], "-f"))
2112 use_default_torrc = 0;
2113 smartlist_add(sl, backup_argv[i]);
2117 if (use_default_torrc) {
2118 smartlist_add(sl, "-f");
2119 smartlist_add(sl, (char*)torrc);
2121 tor_assert(smartlist_len(sl));
2122 options = smartlist_join_strings(sl,"\" \"",0,NULL);
2123 smartlist_free(sl);
2125 /* Allocate a string for the NT service command line */
2126 cmdlen = strlen(tor_exe) + strlen(options) + 32;
2127 command = tor_malloc(cmdlen);
2129 /* Format the service command */
2130 if (tor_snprintf(command, cmdlen, "\"%s\" --nt-service \"%s\"",
2131 tor_exe, options)<0) {
2132 tor_free(command); /* sets command to NULL. */
2134 tor_free(options);
2135 return command;
2138 /** Creates a Tor NT service, set to start on boot. The service will be
2139 * started if installation succeeds. Returns 0 on success, or -1 on
2140 * failure. */
2142 nt_service_install(int argc, char **argv)
2144 /* Notes about developing NT services:
2146 * 1. Don't count on your CWD. If an absolute path is not given, the
2147 * fopen() function goes wrong.
2148 * 2. The parameters given to the nt_service_body() function differ
2149 * from those given to main() function.
2152 SC_HANDLE hSCManager = NULL;
2153 SC_HANDLE hService = NULL;
2154 SERVICE_DESCRIPTION sdBuff;
2155 char *command;
2156 char *errmsg;
2157 const char *user_acct = GENSRV_USERACCT;
2158 int i,r;
2159 SID_NAMED_USE sidUse;
2161 if (nt_service_loadlibrary()<0)
2162 return -1;
2164 /* Open the service control manager so we can create a new service */
2165 if ((hSCManager = nt_service_open_scm()) == NULL)
2166 return -1;
2167 /* Build the command line used for the service */
2168 if ((command = nt_service_command_line()) == NULL) {
2169 printf("Unable to build service command line.\n");
2170 service_fns.CloseServiceHandle_fn(hSCManager);
2171 return -1;
2173 for (i=1; i < argc, ++i) {
2174 if (!strcmp(i, "--user") && i+1<argc) {
2175 user_acct = argv[i+1];
2176 ++i;
2180 if (service_fns.LookupAccountNameA_fn(NULL, // On this system
2181 user_acct,
2182 NULL, 0, // Don't care about the SID
2183 NULL, 0, // Don't care about the domain
2184 &sidUse) == 0) {
2185 printf("User \"%s\" doesn't seem to exist.\n", user_acct);
2186 if (user_acct != GENSRV_USERACCT)
2187 return -1;
2188 /* On Win2k, there is no LocalService account, so we actually need to
2189 * check for it. Yay win2k. */
2190 printf("Falling back to SYSTEM account.\n");
2191 user_acct = NULL;
2194 /* Create the Tor service, set to auto-start on boot */
2195 if ((hService = service_fns.CreateServiceA_fn(hSCManager, GENSRV_SERVICENAME,
2196 GENSRV_DISPLAYNAME,
2197 SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,
2198 SERVICE_AUTO_START, SERVICE_ERROR_IGNORE,
2199 command,
2200 NULL, NULL, NULL, user_acct, "")) == NULL) {
2201 errmsg = nt_strerror(GetLastError());
2202 printf("CreateService() failed : %s\n", errmsg);
2203 service_fns.CloseServiceHandle_fn(hSCManager);
2204 LocalFree(errmsg);
2205 tor_free(command);
2206 return -1;
2209 /* Set the service's description */
2210 sdBuff.lpDescription = GENSRV_DESCRIPTION;
2211 service_fns.ChangeServiceConfig2A_fn(hService, SERVICE_CONFIG_DESCRIPTION,
2212 &sdBuff);
2213 printf("Service installed successfully\n");
2215 /* Start the service initially */
2216 nt_service_start(hService);
2218 service_fns.CloseServiceHandle_fn(hService);
2219 service_fns.CloseServiceHandle_fn(hSCManager);
2220 tor_free(command);
2222 return 0;
2225 /** Removes the Tor NT service. Returns 0 if the service was successfully
2226 * removed, or -1 on error. */
2228 nt_service_remove(void)
2230 SC_HANDLE hSCManager = NULL;
2231 SC_HANDLE hService = NULL;
2232 char *errmsg;
2234 if (nt_service_loadlibrary()<0)
2235 return -1;
2236 if ((hSCManager = nt_service_open_scm()) == NULL)
2237 return -1;
2238 if ((hService = nt_service_open(hSCManager)) == NULL) {
2239 service_fns.CloseServiceHandle_fn(hSCManager);
2240 return -1;
2243 nt_service_stop(hService);
2244 if (service_fns.DeleteService_fn(hService) == FALSE) {
2245 errmsg = nt_strerror(GetLastError());
2246 printf("DeleteService() failed : %s\n", errmsg);
2247 LocalFree(errmsg);
2248 service_fns.CloseServiceHandle_fn(hService);
2249 service_fns.CloseServiceHandle_fn(hSCManager);
2250 return -1;
2253 service_fns.CloseServiceHandle_fn(hService);
2254 service_fns.CloseServiceHandle_fn(hSCManager);
2255 printf("Service removed successfully\n");
2257 return 0;
2260 /** Starts the Tor service. Returns 0 on success, or -1 on error. */
2262 nt_service_cmd_start(void)
2264 SC_HANDLE hSCManager;
2265 SC_HANDLE hService;
2266 int start;
2268 if ((hSCManager = nt_service_open_scm()) == NULL)
2269 return -1;
2270 if ((hService = nt_service_open(hSCManager)) == NULL) {
2271 service_fns.CloseServiceHandle_fn(hSCManager);
2272 return -1;
2275 start = nt_service_start(hService);
2276 service_fns.CloseServiceHandle_fn(hService);
2277 service_fns.CloseServiceHandle_fn(hSCManager);
2279 return start;
2282 /** Stops the Tor service. Returns 0 on success, or -1 on error. */
2284 nt_service_cmd_stop(void)
2286 SC_HANDLE hSCManager;
2287 SC_HANDLE hService;
2288 int stop;
2290 if ((hSCManager = nt_service_open_scm()) == NULL)
2291 return -1;
2292 if ((hService = nt_service_open(hSCManager)) == NULL) {
2293 service_fns.CloseServiceHandle_fn(hSCManager);
2294 return -1;
2297 stop = nt_service_stop(hService);
2298 service_fns.CloseServiceHandle_fn(hService);
2299 service_fns.CloseServiceHandle_fn(hSCManager);
2301 return stop;
2304 /** Given a Win32 error code, this attempts to make Windows
2305 * return a human-readable error message. The char* returned
2306 * is allocated by Windows, but should be freed with LocalFree()
2307 * when finished with it. */
2308 static char*
2309 nt_strerror(uint32_t errnum)
2311 char *msgbuf;
2312 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
2313 NULL, errnum, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
2314 (LPSTR)&msgbuf, 0, NULL);
2315 return msgbuf;
2317 #endif
2319 #ifdef USE_DMALLOC
2320 #include <openssl/crypto.h>
2321 static void
2322 _tor_dmalloc_free(void *p)
2324 tor_free(p);
2326 #endif
2328 /** Main entry point for the Tor process. Called from main(). */
2329 /* This function is distinct from main() only so we can link main.c into
2330 * the unittest binary without conflicting with the unittests' main. */
2332 tor_main(int argc, char *argv[])
2334 int result = 0;
2335 #ifdef USE_DMALLOC
2336 int r = CRYPTO_set_mem_ex_functions(_tor_malloc, _tor_realloc,
2337 _tor_dmalloc_free);
2338 log_notice(LD_CONFIG, "Set up dmalloc; returned %d", r);
2339 #endif
2340 #ifdef MS_WINDOWS_SERVICE
2341 backup_argv = argv;
2342 backup_argc = argc;
2343 if ((argc >= 3) &&
2344 (!strcmp(argv[1], "-service") || !strcmp(argv[1], "--service"))) {
2345 if (nt_service_loadlibrary() < 0) {
2346 printf("Unable to load library support for NT services.\n");
2347 return -1;
2349 if (!strcmp(argv[2], "install"))
2350 return nt_service_install(argc, argv);
2351 if (!strcmp(argv[2], "remove"))
2352 return nt_service_remove();
2353 if (!strcmp(argv[2], "start"))
2354 return nt_service_cmd_start();
2355 if (!strcmp(argv[2], "stop"))
2356 return nt_service_cmd_stop();
2357 printf("Unrecognized service command '%s'\n", argv[2]);
2358 return -1;
2360 if (argc >= 2) {
2361 if (nt_service_loadlibrary() < 0) {
2362 printf("Unable to load library support for NT services.\n");
2363 return -1;
2365 if (!strcmp(argv[1], "-nt-service") || !strcmp(argv[1], "--nt-service")) {
2366 nt_service_main();
2367 return 0;
2369 // These values have been deprecated since 0.1.1.2-alpha; we've warned
2370 // about them since 0.1.2.7-alpha.
2371 if (!strcmp(argv[1], "-install") || !strcmp(argv[1], "--install")) {
2372 fprintf(stderr,
2373 "The %s option is deprecated; use \"--service install\" instead.",
2374 argv[1]);
2375 return nt_service_install();
2377 if (!strcmp(argv[1], "-remove") || !strcmp(argv[1], "--remove")) {
2378 fprintf(stderr,
2379 "The %s option is deprecated; use \"--service remove\" instead.",
2380 argv[1]);
2381 return nt_service_remove();
2384 #endif
2385 if (tor_init(argc, argv)<0)
2386 return -1;
2387 switch (get_options()->command) {
2388 case CMD_RUN_TOR:
2389 #ifdef MS_WINDOWS_SERVICE
2390 service_status.dwCurrentState = SERVICE_RUNNING;
2391 #endif
2392 result = do_main_loop();
2393 break;
2394 case CMD_LIST_FINGERPRINT:
2395 result = do_list_fingerprint();
2396 break;
2397 case CMD_HASH_PASSWORD:
2398 do_hash_password();
2399 result = 0;
2400 break;
2401 case CMD_VERIFY_CONFIG:
2402 printf("Configuration was valid\n");
2403 result = 0;
2404 break;
2405 case CMD_RUN_UNITTESTS: /* only set by test.c */
2406 default:
2407 log_warn(LD_BUG,"Illegal command number %d: internal error.",
2408 get_options()->command);
2409 result = -1;
2411 tor_cleanup();
2412 return result;