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 */
6 const char main_c_id
[] = "$Id$";
10 * \brief Toplevel module. Handles signals, multiplexes between
11 * connections, implements main loop, and drives scheduled events.
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] =
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;
70 #define MS_WINDOWS_SERVICE
73 #ifdef MS_WINDOWS_SERVICE
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
);
92 #define nt_service_is_stopped() (0)
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
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
)
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
);
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
);
142 debug(LD_NET
,"new conn type %s, socket %d, nfds %d.",
143 conn_type_to_string(conn
->type
), conn
->s
, nfds
);
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
)
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 */
170 connection_unregister(conn
);
172 /* replace this one with the one at the end */
174 connection_array
[current_index
] = connection_array
[nfds
];
175 connection_array
[current_index
]->poll_index
= current_index
;
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.
190 connection_unlink(connection_t
*conn
, int remove
)
192 circuit_about_to_close_connection(conn
);
193 connection_about_to_close_connection(conn
);
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. **/
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
)
226 for (i
=0; i
<nfds
; ++i
) {
227 if (conn
==connection_array
[i
])
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
238 get_connection_array(connection_t
***array
, int *n
)
240 *array
= connection_array
;
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.)
248 connection_watch_events(connection_t
*conn
, short events
)
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
);
259 r
= event_del(conn
->read_event
);
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
);
270 r
= event_del(conn
->write_event
);
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
)
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. */
290 connection_stop_reading(connection_t
*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.",
301 /** Tell the main loop to start notifying <b>conn</b> of any read events. */
303 connection_start_reading(connection_t
*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.",
313 /** Return true iff <b>conn</b> is listening for write events. */
315 connection_is_writing(connection_t
*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. */
324 connection_stop_writing(connection_t
*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.",
335 /** Tell the main loop to start notifying <b>conn</b> of any write events. */
337 connection_start_writing(connection_t
*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.",
347 /** Close all connections that have been scheduled to get closed */
349 close_closeable_connections(void)
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 */
357 if (!conn_close_if_marked(conn
->poll_index
))
363 /** Libevent callback: this gets invoked when (connection_t*)<b>conn</b> has
364 * some data to read. */
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
) {
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();
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. */
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.
429 conn_close_if_marked(int i
)
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 /* -1 means it's an incomplete edge connection, or that the socket
443 * has already been closed as unflushable. */
444 if (!conn
->hold_open_until_flushed
)
446 "Conn (addr %s, fd %d, type %s, state %d) marked, but wants to flush %d bytes. "
448 conn
->address
, conn
->s
, conn_type_to_string(conn
->type
), conn
->state
,
449 (int)conn
->outbuf_flushlen
, conn
->marked_for_close_file
, conn
->marked_for_close
);
450 if (connection_speaks_cells(conn
)) {
451 if (conn
->state
== OR_CONN_STATE_OPEN
) {
452 retval
= flush_buf_tls(conn
->tls
, conn
->outbuf
, &conn
->outbuf_flushlen
);
454 retval
= -1; /* never flush non-open broken tls connections */
456 retval
= flush_buf(conn
->s
, conn
->outbuf
, &conn
->outbuf_flushlen
);
459 conn
->hold_open_until_flushed
&& connection_wants_to_flush(conn
)) {
461 (LOG_INFO
,LD_NET
,"Holding conn (fd %d) open for more flushing.",conn
->s
));
462 /* XXX should we reset timestamp_lastwritten here? */
465 if (connection_wants_to_flush(conn
)) {
467 if (conn
->type
== CONN_TYPE_EXIT
||
468 (conn
->type
== CONN_TYPE_DIR
&& conn
->purpose
== DIR_PURPOSE_SERVER
))
471 severity
= LOG_NOTICE
;
472 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)",
473 safe_str(conn
->address
), conn
->s
, conn_type_to_string(conn
->type
),
475 (int)buf_datalen(conn
->outbuf
), conn
->marked_for_close_file
,
476 conn
->marked_for_close
);
479 connection_unlink(conn
, 1); /* unlink, remove, free */
483 /** We've just tried every dirserver we know about, and none of
484 * them were reachable. Assume the network is down. Change state
485 * so next time an application connection arrives we'll delay it
486 * and try another directory fetch. Kill off all the circuit_wait
487 * streams that are waiting now, since they will all timeout anyway.
490 directory_all_unreachable(time_t now
)
493 /* XXXX011 NM Update this to reflect new directories? */
495 has_fetched_directory
=0;
496 stats_n_seconds_working
=0; /* reset it */
498 while ((conn
= connection_get_by_type_state(CONN_TYPE_AP
,
499 AP_CONN_STATE_CIRCUIT_WAIT
))) {
500 notice(LD_NET
,"Network down? Failing connection to '%s:%d'.",
501 safe_str(conn
->socks_request
->address
), conn
->socks_request
->port
);
502 connection_mark_unattached_ap(conn
, END_STREAM_REASON_NET_UNREACHABLE
);
507 * Return the interval to wait betweeen directory downloads, in seconds.
510 get_dir_fetch_period(or_options_t
*options
)
512 if (options
->DirFetchPeriod
)
513 /* Value from config file. */
514 return options
->DirFetchPeriod
;
515 else if (options
->DirPort
)
516 /* Default for directory server */
519 /* Default for average user. */
524 * Return the interval to wait betweeen router status downloads, in seconds.
527 get_status_fetch_period(or_options_t
*options
)
529 if (options
->StatusFetchPeriod
)
530 /* Value from config file. */
531 return options
->StatusFetchPeriod
;
532 else if (options
->DirPort
)
533 /* Default for directory server */
536 /* Default for average user. */
540 /** This function is called whenever we successfully pull down some new
541 * network statuses or server descriptors. */
543 directory_info_has_arrived(time_t now
, int from_cache
)
545 or_options_t
*options
= get_options();
547 if (!router_have_minimum_dir_info()) {
548 notice(LD_DIR
, "I learned some more directory information, but not enough to build a circuit.");
552 if (!has_fetched_directory
) {
553 notice(LD_DIR
, "We have enough directory information to build circuits.");
556 has_fetched_directory
=1;
558 if (server_mode(options
) &&
559 !we_are_hibernating()) { /* connect to the appropriate routers */
560 if (!authdir_mode(options
))
561 router_retry_connections(0);
563 consider_testing_reachability();
567 /** Perform regular maintenance tasks for a single connection. This
568 * function gets run once per second per connection by run_scheduled_events.
571 run_connection_housekeeping(int i
, time_t now
)
574 connection_t
*conn
= connection_array
[i
];
575 or_options_t
*options
= get_options();
577 if (conn
->outbuf
&& !buf_datalen(conn
->outbuf
))
578 conn
->timestamp_lastempty
= now
;
580 /* Expire any directory connections that haven't sent anything for 5 min */
581 if (conn
->type
== CONN_TYPE_DIR
&&
582 !conn
->marked_for_close
&&
583 conn
->timestamp_lastwritten
+ 5*60 < now
) {
584 info(LD_DIR
,"Expiring wedged directory conn (fd %d, purpose %d)",
585 conn
->s
, conn
->purpose
);
586 /* This check is temporary; it's to let us know whether we should consider
587 * parsing partial serverdesc responses. */
588 if (conn
->purpose
== DIR_PURPOSE_FETCH_SERVERDESC
&&
589 buf_datalen(conn
->inbuf
)>=1024) {
590 info(LD_DIR
,"Trying to extract information from wedged server desc download.");
591 connection_dir_reached_eof(conn
);
593 connection_mark_for_close(conn
);
597 /* If we haven't written to an OR connection for a while, then either nuke
598 the connection or send a keepalive, depending. */
599 if (connection_speaks_cells(conn
) &&
600 now
>= conn
->timestamp_lastwritten
+ options
->KeepalivePeriod
) {
601 routerinfo_t
*router
= router_get_by_digest(conn
->identity_digest
);
602 if (!connection_state_is_open(conn
)) {
603 info(LD_OR
,"Expiring non-open OR connection to fd %d (%s:%d).",
604 conn
->s
,conn
->address
, conn
->port
);
605 connection_mark_for_close(conn
);
606 conn
->hold_open_until_flushed
= 1;
607 } else if (we_are_hibernating() && !circuit_get_by_conn(conn
) &&
608 !buf_datalen(conn
->outbuf
)) {
609 info(LD_OR
,"Expiring non-used OR connection to fd %d (%s:%d) [Hibernating or exiting].",
610 conn
->s
,conn
->address
, conn
->port
);
611 connection_mark_for_close(conn
);
612 conn
->hold_open_until_flushed
= 1;
613 } else if (!clique_mode(options
) && !circuit_get_by_conn(conn
) &&
614 (!router
|| !server_mode(options
) || !router_is_clique_mode(router
))) {
615 info(LD_OR
,"Expiring non-used OR connection to fd %d (%s:%d) [Not in clique mode].",
616 conn
->s
,conn
->address
, conn
->port
);
617 connection_mark_for_close(conn
);
618 conn
->hold_open_until_flushed
= 1;
620 now
>= conn
->timestamp_lastempty
+ options
->KeepalivePeriod
*10 &&
621 now
>= conn
->timestamp_lastwritten
+ options
->KeepalivePeriod
*10) {
622 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)",
623 conn
->s
, conn
->address
, conn
->port
,
624 (int)buf_datalen(conn
->outbuf
),
625 (int)(now
-conn
->timestamp_lastwritten
));
626 connection_mark_for_close(conn
);
627 } else if (!buf_datalen(conn
->outbuf
)) {
628 /* either in clique mode, or we've got a circuit. send a padding cell. */
629 log_fn(LOG_DEBUG
,LD_OR
,"Sending keepalive to (%s:%d)",
630 conn
->address
, conn
->port
);
631 memset(&cell
,0,sizeof(cell_t
));
632 cell
.command
= CELL_PADDING
;
633 connection_or_write_cell_to_buf(&cell
, conn
);
638 /** Perform regular maintenance tasks. This function gets run once per
639 * second by prepare_for_poll.
642 run_scheduled_events(time_t now
)
644 static time_t last_rotated_certificate
= 0;
645 static time_t time_to_check_listeners
= 0;
646 static time_t time_to_check_descriptor
= 0;
647 static time_t time_to_check_ipaddress
= 0;
648 static time_t time_to_shrink_buffers
= 0;
649 static time_t time_to_try_getting_descriptors
= 0;
650 static time_t time_to_reset_descriptor_failures
= 0;
651 static time_t time_to_add_entropy
= 0;
652 or_options_t
*options
= get_options();
655 /** 0. See if we've been asked to shut down and our timeout has
656 * expired; or if our bandwidth limits are exhausted and we
657 * should hibernate; or if it's time to wake up from hibernation.
659 consider_hibernation(now
);
661 /** 1a. Every MIN_ONION_KEY_LIFETIME seconds, rotate the onion keys,
662 * shut down and restart all cpuworkers, and update the directory if
665 if (server_mode(options
) &&
666 get_onion_key_set_at()+MIN_ONION_KEY_LIFETIME
< now
) {
667 info(LD_GENERAL
,"Rotating onion key.");
670 if (router_rebuild_descriptor(1)<0) {
671 warn(LD_BUG
, "Couldn't rebuild router descriptor");
673 if (advertised_server_mode())
674 router_upload_dir_desc_to_dirservers(0);
677 if (time_to_try_getting_descriptors
< now
) {
678 update_router_descriptor_downloads(now
);
679 time_to_try_getting_descriptors
= now
+ DESCRIPTOR_RETRY_INTERVAL
;
682 if (time_to_reset_descriptor_failures
< now
) {
683 router_reset_descriptor_download_failures();
684 time_to_reset_descriptor_failures
= now
+ DESCRIPTOR_FAILURE_RESET_INTERVAL
;
687 /** 1b. Every MAX_SSL_KEY_LIFETIME seconds, we change our TLS context. */
688 if (!last_rotated_certificate
)
689 last_rotated_certificate
= now
;
690 if (last_rotated_certificate
+MAX_SSL_KEY_LIFETIME
< now
) {
691 info(LD_GENERAL
,"Rotating tls context.");
692 if (tor_tls_context_new(get_identity_key(), 1, options
->Nickname
,
693 MAX_SSL_KEY_LIFETIME
) < 0) {
694 warn(LD_BUG
, "Error reinitializing TLS context");
695 /* XXX is it a bug here, that we just keep going? */
697 last_rotated_certificate
= now
;
698 /* XXXX We should rotate TLS connections as well; this code doesn't change
702 if (time_to_add_entropy
== 0)
703 time_to_add_entropy
= now
+ ENTROPY_INTERVAL
;
704 if (time_to_add_entropy
< now
) {
705 /* We already seeded once, so don't die on failure. */
707 time_to_add_entropy
= now
+ ENTROPY_INTERVAL
;
710 /** 1c. If we have to change the accounting interval or record
711 * bandwidth used in this accounting interval, do so. */
712 if (accounting_is_enabled(options
))
713 accounting_run_housekeeping(now
);
715 /** 2. Periodically, we consider getting a new directory, getting a
716 * new running-routers list, and/or force-uploading our descriptor
717 * (if we've passed our internal checks). */
718 if (time_to_fetch_directory
< now
) {
719 /* purge obsolete entries */
720 routerlist_remove_old_routers(ROUTER_MAX_AGE
);
721 networkstatus_list_clean(now
);
723 if (authdir_mode(options
)) {
724 if (!we_are_hibernating()) { /* try to determine reachability */
725 router_retry_connections(1);
729 /* Only caches actually need to fetch directories now. */
730 if (options
->DirPort
&& !options
->V1AuthoritativeDir
) {
731 directory_get_from_dirserver(DIR_PURPOSE_FETCH_DIR
, NULL
, 1);
734 time_to_fetch_directory
= now
+ get_dir_fetch_period(options
);
736 /* Also, take this chance to remove old information from rephist
737 * and the rend cache. */
738 rep_history_clean(now
- options
->RephistTrackTime
);
742 /* Caches need to fetch running_routers; directory clients don't. */
743 if (options
->DirPort
&& time_to_fetch_running_routers
< now
) {
744 if (!authdir_mode(options
) || !options
->V1AuthoritativeDir
) {
745 directory_get_from_dirserver(DIR_PURPOSE_FETCH_RUNNING_LIST
, NULL
, 1);
747 time_to_fetch_running_routers
= now
+ get_status_fetch_period(options
);
750 /* 2b. Once per minute, regenerate and upload the descriptor if the old
751 * one is inaccurate. */
752 if (time_to_check_descriptor
< now
) {
753 time_to_check_descriptor
= now
+ CHECK_DESCRIPTOR_INTERVAL
;
754 check_descriptor_bandwidth_changed(now
);
755 if (time_to_check_ipaddress
< now
) {
756 time_to_check_ipaddress
= now
+ CHECK_IPADDRESS_INTERVAL
;
757 check_descriptor_ipaddress_changed(now
);
759 mark_my_descriptor_dirty_if_older_than(
760 now
- FORCE_REGENERATE_DESCRIPTOR_INTERVAL
);
761 consider_publishable_server(now
, 0);
762 /* also, check religiously for reachability, if it's within the first
763 * 20 minutes of our uptime. */
764 if (server_mode(options
) &&
765 stats_n_seconds_working
< TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT
&&
766 !we_are_hibernating())
767 consider_testing_reachability();
769 /* If any networkstatus documents are no longer recent, we need to
770 * update all the descriptors' running status. */
771 networkstatus_list_update_recent(now
);
772 routers_update_all_from_networkstatus();
774 /* Also, once per minute, check whether we want to download any
775 * networkstatus documents.
777 update_networkstatus_downloads(now
);
780 /** 3a. Every second, we examine pending circuits and prune the
781 * ones which have been pending for more than a few seconds.
782 * We do this before step 4, so it can try building more if
783 * it's not comfortable with the number of available circuits.
785 circuit_expire_building(now
);
787 /** 3b. Also look at pending streams and prune the ones that 'began'
788 * a long time ago but haven't gotten a 'connected' yet.
789 * Do this before step 4, so we can put them back into pending
790 * state to be picked up by the new circuit.
792 connection_ap_expire_beginning();
794 /** 3c. And expire connections that we've held open for too long.
796 connection_expire_held_open();
798 /** 3d. And every 60 seconds, we relaunch listeners if any died. */
799 if (!we_are_hibernating() && time_to_check_listeners
< now
) {
800 /* 0 means "only launch the ones that died." */
801 retry_all_listeners(0, NULL
, NULL
);
802 time_to_check_listeners
= now
+60;
805 /** 4. Every second, we try a new circuit if there are no valid
806 * circuits. Every NewCircuitPeriod seconds, we expire circuits
807 * that became dirty more than MaxCircuitDirtiness seconds ago,
808 * and we make a new circ if there are no clean circuits.
810 if (has_fetched_directory
&& !we_are_hibernating())
811 circuit_build_needed_circs(now
);
813 /** 5. We do housekeeping for each connection... */
814 for (i
=0;i
<nfds
;i
++) {
815 run_connection_housekeeping(i
, now
);
817 if (time_to_shrink_buffers
< now
) {
818 for (i
=0;i
<nfds
;i
++) {
819 connection_t
*conn
= connection_array
[i
];
821 buf_shrink(conn
->outbuf
);
823 buf_shrink(conn
->inbuf
);
825 time_to_shrink_buffers
= now
+ BUF_SHRINK_INTERVAL
;
828 /** 6. And remove any marked circuits... */
829 circuit_close_all_marked();
831 /** 7. And upload service descriptors if necessary. */
832 if (has_fetched_directory
&& !we_are_hibernating())
833 rend_consider_services_upload(now
);
835 /** 8. and blow away any connections that need to die. have to do this now,
836 * because if we marked a conn for close and left its socket -1, then
837 * we'll pass it to poll/select and bad things will happen.
839 close_closeable_connections();
842 static struct event
*timeout_event
= NULL
;
843 static int n_libevent_errors
= 0;
845 /** Libevent callback: invoked once every second. */
847 second_elapsed_callback(int fd
, short event
, void *args
)
849 static struct timeval one_second
;
850 static long current_second
= 0;
852 size_t bytes_written
;
855 or_options_t
*options
= get_options();
856 if (!timeout_event
) {
857 timeout_event
= tor_malloc_zero(sizeof(struct event
));
858 evtimer_set(timeout_event
, second_elapsed_callback
, NULL
);
859 one_second
.tv_sec
= 1;
860 one_second
.tv_usec
= 0;
863 n_libevent_errors
= 0;
865 /* log_fn(LOG_NOTICE, "Tick."); */
866 tor_gettimeofday(&now
);
868 /* the second has rolled over. check more stuff. */
869 bytes_written
= stats_prev_global_write_bucket
- global_write_bucket
;
870 bytes_read
= stats_prev_global_read_bucket
- global_read_bucket
;
871 /* XXX below we get suspicious if time jumps forward more than 10
872 * seconds, but we never notice if it jumps *back* more than 10 seconds.
873 * This could be useful for detecting that we just NTP'ed to three
874 * weeks ago and it will be 3 weeks and 15 minutes until any of our
877 seconds_elapsed
= current_second
? (now
.tv_sec
- current_second
) : 0;
878 stats_n_bytes_read
+= bytes_read
;
879 stats_n_bytes_written
+= bytes_written
;
880 if (accounting_is_enabled(options
))
881 accounting_add_bytes(bytes_read
, bytes_written
, seconds_elapsed
);
882 control_event_bandwidth_used((uint32_t)bytes_read
,(uint32_t)bytes_written
);
884 connection_bucket_refill(&now
);
885 stats_prev_global_read_bucket
= global_read_bucket
;
886 stats_prev_global_write_bucket
= global_write_bucket
;
888 if (server_mode(options
) &&
889 !we_are_hibernating() &&
890 stats_n_seconds_working
/ TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT
!=
891 (stats_n_seconds_working
+seconds_elapsed
) /
892 TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT
) {
893 /* every 20 minutes, check and complain if necessary */
894 routerinfo_t
*me
= router_get_my_routerinfo();
895 if (me
&& !check_whether_orport_reachable())
896 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.",
897 me
->address
, me
->or_port
);
898 if (me
&& !check_whether_dirport_reachable())
899 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.",
900 me
->address
, me
->dir_port
);
903 /* if more than 100s have elapsed, probably the clock jumped: doesn't count. */
904 if (seconds_elapsed
< 100)
905 stats_n_seconds_working
+= seconds_elapsed
;
907 circuit_note_clock_jumped(seconds_elapsed
);
909 run_scheduled_events(now
.tv_sec
);
911 current_second
= now
.tv_sec
; /* remember which second it is, for next time */
914 if (current_second
% 300 == 0) {
915 rep_history_clean(current_second
- options
->RephistTrackTime
);
916 dumpmemusage(get_min_log_level()<LOG_INFO
? get_min_log_level() : LOG_INFO
);
920 if (evtimer_add(timeout_event
, &one_second
))
922 "Error from libevent when setting one-second timeout event");
925 /** Called when a possibly ignorable libevent error occurs; ensures that we
926 * don't get into an infinite loop by ignoring too many errors from
929 got_libevent_error(void)
931 if (++n_libevent_errors
> 8) {
932 err(LD_NET
, "Too many libevent errors in one second; dying");
938 /** Called when we get a SIGHUP: reload configuration files and keys,
939 * retry all connections, re-upload all descriptors, and so on. */
944 or_options_t
*options
= get_options();
946 notice(LD_GENERAL
,"Received sighup. Reloading config.");
947 has_completed_circuit
=0;
948 if (accounting_is_enabled(options
))
949 accounting_record_bandwidth_usage(time(NULL
));
951 router_reset_warnings();
952 routerlist_reset_warnings();
953 addressmap_clear_transient();
954 /* first, reload config variables, in case they've changed */
955 /* no need to provide argc/v, they've been cached inside init_from_config */
956 if (options_init_from_torrc(0, NULL
) < 0) {
957 err(LD_CONFIG
,"Reading config failed--see warnings above. For usage, try -h.");
960 options
= get_options(); /* they have changed now */
961 if (authdir_mode(options
)) {
962 /* reload the approved-routers file */
963 tor_snprintf(keydir
,sizeof(keydir
),"%s/approved-routers", options
->DataDirectory
);
964 info(LD_GENERAL
,"Reloading approved fingerprints from \"%s\"...",keydir
);
965 if (dirserv_parse_fingerprint_file(keydir
) < 0) {
966 info(LD_GENERAL
, "Error reloading fingerprints. Continuing with old list.");
970 /* Rotate away from the old dirty circuits. This has to be done
971 * after we've read the new options, but before we start using
972 * circuits for directory fetches. */
973 circuit_expire_all_dirty_circs();
975 /* retry appropriate downloads */
976 router_reset_status_download_failures();
977 router_reset_descriptor_download_failures();
978 update_networkstatus_downloads(time(NULL
));
980 /* We'll retry routerstatus downloads in about 10 seconds; no need to
981 * force a retry there. */
983 if (server_mode(options
)) {
984 const char *descriptor
;
985 /* Restart cpuworker and dnsworker processes, so they get up-to-date
986 * configuration options. */
989 /* Write out a fresh descriptor, but leave old one on failure. */
990 router_rebuild_descriptor(1);
991 descriptor
= router_get_my_descriptor();
993 tor_snprintf(keydir
,sizeof(keydir
),"%s/router.desc",
994 options
->DataDirectory
);
995 info(LD_OR
,"Saving descriptor to \"%s\"...",keydir
);
996 if (write_str_to_file(keydir
, descriptor
, 0)) {
1004 /** Tor main loop. */
1010 dns_init(); /* initialize dns resolve tree, spawn workers if needed */
1014 /* load the private keys, if we're supposed to have them, and set up the
1016 if (! identity_key_is_set()) {
1017 if (init_keys() < 0) {
1018 err(LD_GENERAL
,"Error initializing keys; exiting");
1023 /* Set up our buckets */
1024 connection_bucket_init();
1025 stats_prev_global_read_bucket
= global_read_bucket
;
1026 stats_prev_global_write_bucket
= global_write_bucket
;
1028 /* load the routers file, or assign the defaults. */
1029 if (router_reload_router_list()) {
1032 /* load the networkstatuses. (This launches a download for new routers as
1035 if (router_reload_networkstatus()) {
1038 directory_info_has_arrived(time(NULL
),1);
1040 if (authdir_mode(get_options())) {
1041 /* the directory is already here, run startup things */
1042 router_retry_connections(1);
1045 if (server_mode(get_options())) {
1046 /* launch cpuworkers. Need to do this *after* we've read the onion key. */
1050 /* set up once-a-second callback. */
1051 second_elapsed_callback(0,0,NULL
);
1054 if (nt_service_is_stopped())
1058 /* Make it easier to tell whether libevent failure is our fault or not. */
1061 /* poll until we have an event, or the second ends */
1062 loop_result
= event_dispatch();
1064 /* let catch() handle things like ^c, and otherwise don't worry about it */
1065 if (loop_result
< 0) {
1066 int e
= tor_socket_errno(-1);
1067 /* let the program survive things like ^z */
1068 if (e
!= EINTR
&& !ERRNO_IS_EINPROGRESS(e
)) {
1069 #ifdef HAVE_EVENT_GET_METHOD
1070 err(LD_NET
,"libevent poll with %s failed: %s [%d]",
1071 event_get_method(), tor_socket_strerror(e
), e
);
1073 err(LD_NET
,"libevent poll failed: %s [%d]",
1074 tor_socket_strerror(e
), e
);
1078 } else if (e
== EINVAL
) {
1079 warn(LD_NET
, "EINVAL from libevent: should you upgrade libevent?");
1080 if (got_libevent_error())
1084 if (ERRNO_IS_EINPROGRESS(e
))
1085 warn(LD_BUG
,"libevent poll returned EINPROGRESS? Please report.");
1086 debug(LD_NET
,"event poll interrupted.");
1087 /* You can't trust the results of this poll(). Go back to the
1088 * top of the big for loop. */
1093 /* refilling buckets and sending cells happens at the beginning of the
1094 * next iteration of the loop, inside prepare_for_poll()
1095 * XXXX No longer so.
1100 /** Used to implement the SIGNAL control command: if we accept
1101 * <b>the_signal</b> as a remote pseudo-signal, then act on it and
1102 * return 0. Else return -1. */
1103 /* We don't re-use catch() here because:
1104 * 1. We handle a different set of signals than those allowed in catch.
1105 * 2. Platforms without signal() are unlikely to define SIGfoo.
1106 * 3. The control spec is defined to use fixed numeric signal values
1107 * which just happen to match the unix values.
1110 control_signal_act(int the_signal
)
1115 signal_callback(0,0,(void*)(uintptr_t)SIGHUP
);
1118 signal_callback(0,0,(void*)(uintptr_t)SIGINT
);
1121 signal_callback(0,0,(void*)(uintptr_t)SIGUSR1
);
1124 signal_callback(0,0,(void*)(uintptr_t)SIGUSR2
);
1127 signal_callback(0,0,(void*)(uintptr_t)SIGTERM
);
1135 /** Libevent callback: invoked when we get a signal.
1138 signal_callback(int fd
, short events
, void *arg
)
1140 uintptr_t sig
= (uintptr_t)arg
;
1144 err(LD_GENERAL
,"Catching signal TERM, exiting cleanly.");
1149 if (!server_mode(get_options())) { /* do it now */
1150 notice(LD_GENERAL
,"Interrupt: exiting cleanly.");
1154 hibernate_begin_shutdown();
1158 debug(LD_GENERAL
,"Caught sigpipe. Ignoring.");
1162 /* prefer to log it at INFO, but make sure we always see it */
1163 dumpstats(get_min_log_level()<LOG_INFO
? get_min_log_level() : LOG_INFO
);
1166 switch_logs_debug();
1167 debug(LD_GENERAL
,"Caught USR2, going to loglevel debug. Send HUP to change back.");
1171 warn(LD_CONFIG
,"Restart failed (config error?). Exiting.");
1178 while (waitpid(-1,NULL
,WNOHANG
) > 0) ; /* keep reaping until no more zombies */
1185 * Write current memory uusage information to the log.
1188 dumpmemusage(int severity
)
1190 extern uint64_t buf_total_used
;
1191 extern uint64_t buf_total_alloc
;
1192 extern uint64_t rephist_total_alloc
;
1193 extern uint32_t rephist_total_num
;
1195 log(severity
, LD_GENERAL
, "In buffers: "U64_FORMAT
" used/"U64_FORMAT
" allocated (%d conns).",
1196 U64_PRINTF_ARG(buf_total_used
), U64_PRINTF_ARG(buf_total_alloc
),
1198 log(severity
, LD_GENERAL
, "In rephist: "U64_FORMAT
" used by %d Tors.",
1199 U64_PRINTF_ARG(rephist_total_alloc
), rephist_total_num
);
1202 /** Write all statistics to the log, with log level 'severity'. Called
1203 * in response to a SIGUSR1. */
1205 dumpstats(int severity
)
1209 time_t now
= time(NULL
);
1212 log(severity
, LD_GENERAL
, "Dumping stats:");
1214 for (i
=0;i
<nfds
;i
++) {
1215 conn
= connection_array
[i
];
1216 log(severity
, LD_GENERAL
, "Conn %d (socket %d) type %d (%s), state %d (%s), created %d secs ago",
1217 i
, conn
->s
, conn
->type
, conn_type_to_string(conn
->type
),
1218 conn
->state
, conn_state_to_string(conn
->type
, conn
->state
), (int)(now
- conn
->timestamp_created
));
1219 if (!connection_is_listener(conn
)) {
1220 log(severity
,LD_GENERAL
,"Conn %d is to '%s:%d'.",i
,safe_str(conn
->address
), conn
->port
);
1221 log(severity
,LD_GENERAL
, "Conn %d: %d bytes waiting on inbuf (len %d, last read %d secs ago)",i
,
1222 (int)buf_datalen(conn
->inbuf
),
1223 (int)buf_capacity(conn
->inbuf
),
1224 (int)(now
- conn
->timestamp_lastread
));
1225 log(severity
,LD_GENERAL
, "Conn %d: %d bytes waiting on outbuf (len %d, last written %d secs ago)",i
,
1226 (int)buf_datalen(conn
->outbuf
),
1227 (int)buf_capacity(conn
->outbuf
),
1228 (int)(now
- conn
->timestamp_lastwritten
));
1230 circuit_dump_by_conn(conn
, severity
); /* dump info about all the circuits using this conn */
1232 log(severity
, LD_NET
,
1233 "Cells processed: %10lu padding\n"
1237 " (%10lu relayed)\n"
1238 " (%10lu delivered)\n"
1240 stats_n_padding_cells_processed
,
1241 stats_n_create_cells_processed
,
1242 stats_n_created_cells_processed
,
1243 stats_n_relay_cells_processed
,
1244 stats_n_relay_cells_relayed
,
1245 stats_n_relay_cells_delivered
,
1246 stats_n_destroy_cells_processed
);
1247 if (stats_n_data_cells_packaged
)
1248 log(severity
,LD_NET
,"Average packaged cell fullness: %2.3f%%",
1249 100*(((double)stats_n_data_bytes_packaged
) /
1250 (stats_n_data_cells_packaged
*RELAY_PAYLOAD_SIZE
)) );
1251 if (stats_n_data_cells_received
)
1252 log(severity
,LD_NET
,"Average delivered cell fullness: %2.3f%%",
1253 100*(((double)stats_n_data_bytes_received
) /
1254 (stats_n_data_cells_received
*RELAY_PAYLOAD_SIZE
)) );
1256 if (now
- time_of_process_start
>= 0)
1257 elapsed
= now
- time_of_process_start
;
1262 log(severity
, LD_NET
,
1263 "Average bandwidth: "U64_FORMAT
"/%d = %d bytes/sec reading",
1264 U64_PRINTF_ARG(stats_n_bytes_read
),
1266 (int) (stats_n_bytes_read
/elapsed
));
1267 log(severity
, LD_NET
,
1268 "Average bandwidth: "U64_FORMAT
"/%d = %d bytes/sec writing",
1269 U64_PRINTF_ARG(stats_n_bytes_written
),
1271 (int) (stats_n_bytes_written
/elapsed
));
1274 log(severity
, LD_NET
, "--------------- Dumping memory information:");
1275 dumpmemusage(severity
);
1277 rep_hist_dump_stats(now
,severity
);
1278 rend_service_dump_stats(severity
);
1281 /** Called by exit() as we shut down the process.
1286 /* NOTE: If we ever daemonize, this gets called immediately. That's
1287 * okay for now, because we only use this on Windows. */
1293 /** Set up the signal handlers for either parent or child. */
1295 handle_signals(int is_parent
)
1297 #ifndef MS_WINDOWS /* do signal stuff only on unix */
1299 static int signals
[] = {
1300 SIGINT
, /* do a controlled slow shutdown */
1301 SIGTERM
, /* to terminate now */
1302 SIGPIPE
, /* otherwise sigpipe kills us */
1303 SIGUSR1
, /* dump stats */
1304 SIGUSR2
, /* go to loglevel debug */
1305 SIGHUP
, /* to reload config, retry conns, etc */
1307 SIGXFSZ
, /* handle file-too-big resource exhaustion */
1309 SIGCHLD
, /* handle dns/cpu workers that exit */
1311 static struct event signal_events
[16]; /* bigger than it has to be. */
1313 for (i
= 0; signals
[i
] >= 0; ++i
) {
1314 signal_set(&signal_events
[i
], signals
[i
], signal_callback
,
1315 (void*)(uintptr_t)signals
[i
]);
1316 if (signal_add(&signal_events
[i
], NULL
))
1317 warn(LD_BUG
, "Error from libevent when adding event for signal %d",
1321 struct sigaction action
;
1322 action
.sa_flags
= 0;
1323 sigemptyset(&action
.sa_mask
);
1324 action
.sa_handler
= SIG_IGN
;
1325 sigaction(SIGINT
, &action
, NULL
);
1326 sigaction(SIGTERM
, &action
, NULL
);
1327 sigaction(SIGPIPE
, &action
, NULL
);
1328 sigaction(SIGUSR1
, &action
, NULL
);
1329 sigaction(SIGUSR2
, &action
, NULL
);
1330 sigaction(SIGHUP
, &action
, NULL
);
1332 sigaction(SIGXFSZ
, &action
, NULL
);
1335 #endif /* signal stuff */
1338 /** Main entry point for the Tor command-line client.
1341 tor_init(int argc
, char *argv
[])
1343 time_of_process_start
= time(NULL
);
1344 if (!closeable_connection_lst
)
1345 closeable_connection_lst
= smartlist_create();
1346 /* Initialize the history structures. */
1348 /* Initialize the service cache. */
1350 addressmap_init(); /* Init the client dns cache. Do it always, since it's cheap. */
1352 /* give it somewhere to log to initially */
1355 log(LOG_NOTICE
, LD_GENERAL
, "Tor v%s. This is experimental software. Do not rely on it for strong anonymity.",VERSION
);
1357 if (network_init()<0) {
1358 err(LD_NET
,"Error initializing network; exiting.");
1361 atexit(exit_function
);
1363 if (options_init_from_torrc(argc
,argv
) < 0) {
1364 err(LD_CONFIG
,"Reading config failed--see warnings above. For usage, try -h.");
1370 warn(LD_GENERAL
,"You are running Tor as root. You don't need to, and you probably shouldn't.");
1373 crypto_global_init(get_options()->HardwareAccel
);
1374 if (crypto_seed_rng()) {
1375 err(LD_BUG
, "Unable to seed random number generator. Exiting.");
1382 /** Free all memory that we might have allocated somewhere.
1383 * Helps us find the real leaks with dmalloc and the like.
1385 * Also valgrind should then report 0 reachable in its
1388 tor_free_all(int postfork
)
1390 routerlist_free_all();
1391 addressmap_free_all();
1392 set_exit_redirects(NULL
); /* free the registered exit redirects */
1393 free_socks_policy();
1396 rend_service_free_all();
1397 rend_cache_free_all();
1398 rep_hist_free_all();
1400 clear_pending_onions();
1402 helper_nodes_free_all();
1403 connection_free_all();
1409 /* stuff in main.c */
1410 smartlist_free(closeable_connection_lst
);
1411 tor_free(timeout_event
);
1414 close_logs(); /* free log strings. do this last so logs keep working. */
1418 /** Do whatever cleanup is necessary before shutting Tor down. */
1422 or_options_t
*options
= get_options();
1423 /* Remove our pid file. We don't care if there was an error when we
1424 * unlink, nothing we could do about it anyways. */
1425 if (options
->PidFile
&& options
->command
== CMD_RUN_TOR
)
1426 unlink(options
->PidFile
);
1427 if (accounting_is_enabled(options
))
1428 accounting_record_bandwidth_usage(time(NULL
));
1429 tor_free_all(0); /* move tor_free_all back into the ifdef below later. XXX*/
1430 crypto_global_cleanup();
1432 dmalloc_log_unfreed();
1437 /** Read/create keys as needed, and echo our fingerprint to stdout. */
1439 do_list_fingerprint(void)
1441 char buf
[FINGERPRINT_LEN
+1];
1443 const char *nickname
= get_options()->Nickname
;
1444 if (!server_mode(get_options())) {
1445 printf("Clients don't have long-term identity keys. Exiting.\n");
1448 tor_assert(nickname
);
1449 if (init_keys() < 0) {
1450 err(LD_BUG
,"Error initializing keys; exiting");
1453 if (!(k
= get_identity_key())) {
1454 err(LD_GENERAL
,"Error: missing identity key.");
1457 if (crypto_pk_get_fingerprint(k
, buf
, 1)<0) {
1458 warn(LD_BUG
, "Error computing fingerprint");
1461 printf("%s %s\n", nickname
, buf
);
1464 /** Entry point for password hashing: take the desired password from
1465 * the command line, and print its salted hash to stdout. **/
1467 do_hash_password(void)
1471 char key
[S2K_SPECIFIER_LEN
+DIGEST_LEN
];
1473 crypto_rand(key
, S2K_SPECIFIER_LEN
-1);
1474 key
[S2K_SPECIFIER_LEN
-1] = (uint8_t)96; /* Hash 64 K of data. */
1475 secret_to_key(key
+S2K_SPECIFIER_LEN
, DIGEST_LEN
,
1476 get_options()->command_arg
, strlen(get_options()->command_arg
),
1478 base16_encode(output
, sizeof(output
), key
, sizeof(key
));
1479 printf("16:%s\n",output
);
1482 #ifdef MS_WINDOWS_SERVICE
1483 /** Checks if torrc is present in the same directory
1484 * as the service executable.
1485 * Return 1 if it is, 0 if it is not present. */
1487 nt_torrc_is_present()
1490 TCHAR szPath
[_MAX_PATH
];
1491 TCHAR szDrive
[_MAX_DRIVE
];
1492 TCHAR szDir
[_MAX_DIR
];
1493 char torrc
[] = "torrc";
1494 char *path_to_torrc
;
1497 /* Get the service executable path */
1498 if (0 == GetModuleFileName(NULL
, szPath
, MAX_PATH
))
1500 _tsplitpath(szPath
, szDrive
, szDir
, NULL
, NULL
);
1502 /* Build the path to the torrc file */
1503 len
= _MAX_PATH
+ _MAX_DRIVE
+ _MAX_DIR
+ strlen(torrc
) + 1;
1504 path_to_torrc
= tor_malloc(len
);
1505 if (tor_snprintf(path_to_torrc
, len
, "%s%s%s", szDrive
, szDir
, torrc
)<0) {
1506 printf("Failed: tor_snprinf()\n");
1507 tor_free(path_to_torrc
);
1511 /* See if torrc is present */
1512 hFile
= CreateFile(TEXT(path_to_torrc
),
1513 GENERIC_READ
, FILE_SHARE_READ
, NULL
,
1514 OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
,
1517 tor_free(path_to_torrc
);
1519 if (hFile
== INVALID_HANDLE_VALUE
) {
1526 /** If we're compile to run as an NT service, and the service has been
1527 * shut down, then change our current status and return 1. Else
1531 nt_service_is_stopped(void)
1533 if (service_status
.dwCurrentState
== SERVICE_STOP_PENDING
) {
1534 service_status
.dwWin32ExitCode
= 0;
1535 service_status
.dwCurrentState
= SERVICE_STOPPED
;
1536 SetServiceStatus(hStatus
, &service_status
);
1538 } else if (service_status
.dwCurrentState
== SERVICE_STOPPED
) {
1546 nt_service_control(DWORD request
)
1548 static struct timeval exit_now
;
1549 exit_now
.tv_sec
= 0;
1550 exit_now
.tv_usec
= 0;
1553 case SERVICE_CONTROL_STOP
:
1554 case SERVICE_CONTROL_SHUTDOWN
:
1555 err(LD_GENERAL
, "Got stop/shutdown request; shutting down cleanly.");
1556 service_status
.dwCurrentState
= SERVICE_STOP_PENDING
;
1557 event_loopexit(&exit_now
);
1560 SetServiceStatus(hStatus
, &service_status
);
1565 nt_service_body(int argc
, char **argv
)
1568 service_status
.dwServiceType
= SERVICE_WIN32_OWN_PROCESS
;
1569 service_status
.dwCurrentState
= SERVICE_START_PENDING
;
1570 service_status
.dwControlsAccepted
=
1571 SERVICE_ACCEPT_STOP
| SERVICE_ACCEPT_SHUTDOWN
;
1572 service_status
.dwWin32ExitCode
= 0;
1573 service_status
.dwServiceSpecificExitCode
= 0;
1574 service_status
.dwCheckPoint
= 0;
1575 service_status
.dwWaitHint
= 1000;
1576 hStatus
= RegisterServiceCtrlHandler(GENSRV_SERVICENAME
, (LPHANDLER_FUNCTION
) nt_service_control
);
1584 if (nt_torrc_is_present()) {
1585 err
= tor_init(backup_argc
, backup_argv
); // refactor this part out of tor_main and do_main_loop
1587 err
= NT_SERVICE_ERROR_TORINIT_FAILED
;
1591 err(LD_CONFIG
, "torrc is not in the current working directory. The Tor service will not start.");
1592 err
= NT_SERVICE_ERROR_NO_TORRC
;
1597 service_status
.dwCurrentState
= SERVICE_STOPPED
;
1598 service_status
.dwWin32ExitCode
= err
;
1599 service_status
.dwServiceSpecificExitCode
= err
;
1600 SetServiceStatus(hStatus
, &service_status
);
1603 service_status
.dwCurrentState
= SERVICE_RUNNING
;
1604 SetServiceStatus(hStatus
, &service_status
);
1612 nt_service_main(void)
1614 SERVICE_TABLE_ENTRY table
[2];
1617 table
[0].lpServiceName
= GENSRV_SERVICENAME
;
1618 table
[0].lpServiceProc
= (LPSERVICE_MAIN_FUNCTION
)nt_service_body
;
1619 table
[1].lpServiceName
= NULL
;
1620 table
[1].lpServiceProc
= NULL
;
1622 if (!StartServiceCtrlDispatcher(table
)) {
1623 result
= GetLastError();
1624 errmsg
= nt_strerror(result
);
1625 printf("Service error %d : %s\n", result
, errmsg
);
1627 if (result
== ERROR_FAILED_SERVICE_CONTROLLER_CONNECT
) {
1628 if (tor_init(backup_argc
, backup_argv
) < 0)
1630 switch (get_options()->command
) {
1634 case CMD_LIST_FINGERPRINT
:
1635 do_list_fingerprint();
1637 case CMD_HASH_PASSWORD
:
1640 case CMD_VERIFY_CONFIG
:
1641 printf("Configuration was valid\n");
1644 err(LD_CONFIG
, "Illegal command number %d: internal error.", get_options()->command
);
1653 nt_service_open_scm(void)
1655 SC_HANDLE hSCManager
;
1656 char *errmsg
= NULL
;
1658 if ((hSCManager
= OpenSCManager(NULL
, NULL
, SC_MANAGER_CREATE_SERVICE
)) == NULL
) {
1659 errmsg
= nt_strerror(GetLastError());
1660 printf("OpenSCManager() failed : %s\n", errmsg
);
1668 nt_service_open(SC_HANDLE hSCManager
)
1671 char *errmsg
= NULL
;
1673 if ((hService
= OpenService(hSCManager
, GENSRV_SERVICENAME
, SERVICE_ALL_ACCESS
)) == NULL
) {
1674 errmsg
= nt_strerror(GetLastError());
1675 printf("OpenService() failed : %s\n", errmsg
);
1683 nt_service_start(SC_HANDLE hService
)
1685 char *errmsg
= NULL
;
1687 QueryServiceStatus(hService
, &service_status
);
1688 if (service_status
.dwCurrentState
== SERVICE_RUNNING
) {
1689 printf("Service is already running\n");
1693 if (StartService(hService
, 0, NULL
)) {
1694 /* Loop until the service has finished attempting to start */
1695 while (QueryServiceStatus(hService
, &service_status
)) {
1696 if (service_status
.dwCurrentState
== SERVICE_START_PENDING
)
1702 /* Check if it started successfully or not */
1703 if (service_status
.dwCurrentState
== SERVICE_RUNNING
) {
1704 printf("Service started successfully\n");
1708 errmsg
= nt_strerror(service_status
.dwWin32ExitCode
);
1709 printf("Service failed to start : %s\n", errmsg
);
1714 errmsg
= nt_strerror(GetLastError());
1715 printf("StartService() failed : %s\n", errmsg
);
1723 nt_service_stop(SC_HANDLE hService
)
1725 char *errmsg
= NULL
;
1727 QueryServiceStatus(hService
, &service_status
);
1728 if (service_status
.dwCurrentState
== SERVICE_STOPPED
) {
1729 printf("Service is already stopped\n");
1733 if (ControlService(hService
, SERVICE_CONTROL_STOP
, &service_status
)) {
1734 while (QueryServiceStatus(hService
, &service_status
)) {
1735 if (service_status
.dwCurrentState
== SERVICE_STOP_PENDING
)
1740 if (service_status
.dwCurrentState
== SERVICE_STOPPED
) {
1741 printf("Service stopped successfully\n");
1745 errmsg
= nt_strerror(GetLastError());
1746 printf("Service failed to stop : %s\n");
1751 errmsg
= nt_strerror(GetLastError());
1752 printf("ControlService() failed : %s\n", errmsg
);
1760 nt_service_install(void)
1762 /* XXXX Problems with NT services:
1763 * 1. The configuration file needs to be in the same directory as the .exe
1765 * 2. The exe and the configuration file can't be on any directory path
1766 * that contains a space.
1767 * mje - you can quote the string (i.e., "c:\program files")
1769 * 3. Ideally, there should be one EXE that can either run as a
1770 * separate process (as now) or that can install and run itself
1771 * as an NT service. I have no idea how hard this is.
1772 * mje - should be done. It can install and run itself as a service
1774 * Notes about developing NT services:
1776 * 1. Don't count on your CWD. If an absolute path is not given, the
1777 * fopen() function goes wrong.
1778 * 2. The parameters given to the nt_service_body() function differ
1779 * from those given to main() function.
1782 SC_HANDLE hSCManager
= NULL
;
1783 SC_HANDLE hService
= NULL
;
1784 SERVICE_DESCRIPTION sdBuff
;
1785 TCHAR szPath
[_MAX_PATH
];
1786 TCHAR szDrive
[_MAX_DRIVE
];
1787 TCHAR szDir
[_MAX_DIR
];
1788 char cmd1
[] = " -f ";
1789 char cmd2
[] = "\\torrc";
1794 if (0 == GetModuleFileName(NULL
, szPath
, MAX_PATH
))
1797 _tsplitpath(szPath
, szDrive
, szDir
, NULL
, NULL
);
1799 /* Account for the extra quotes */
1800 //len = _MAX_PATH + strlen(cmd1) + _MAX_DRIVE + _MAX_DIR + strlen(cmd2);
1801 len
= _MAX_PATH
+ strlen(cmd1
) + _MAX_DRIVE
+ _MAX_DIR
+ strlen(cmd2
) + 64;
1802 command
= tor_malloc(len
);
1804 /* Create a quoted command line, like "c:\with spaces\tor.exe" -f
1805 * "c:\with spaces\tor.exe"
1807 if (tor_snprintf(command
, len
, "\"%s\" --nt-service -f \"%s%storrc\"",
1808 szPath
, szDrive
, szDir
)<0) {
1809 printf("Failed: tor_snprinf()\n");
1814 if ((hSCManager
= nt_service_open_scm()) == NULL
) {
1820 * - changed the service start type to auto
1821 * - and changed the lpPassword param to "" instead of NULL as per an
1824 if ((hService
= CreateService(hSCManager
, GENSRV_SERVICENAME
, GENSRV_DISPLAYNAME
,
1825 SERVICE_ALL_ACCESS
, SERVICE_WIN32_OWN_PROCESS
,
1826 SERVICE_AUTO_START
, SERVICE_ERROR_IGNORE
, command
,
1827 NULL
, NULL
, NULL
, NULL
, "")) == NULL
) {
1828 errmsg
= nt_strerror(GetLastError());
1829 printf("CreateService() failed : %s\n", errmsg
);
1830 CloseServiceHandle(hSCManager
);
1836 /* Set the service's description */
1837 sdBuff
.lpDescription
= GENSRV_DESCRIPTION
;
1838 ChangeServiceConfig2(hService
, SERVICE_CONFIG_DESCRIPTION
, &sdBuff
);
1839 printf("Service installed successfully\n");
1841 /* Start the service initially */
1842 nt_service_start(hService
);
1844 CloseServiceHandle(hService
);
1845 CloseServiceHandle(hSCManager
);
1853 nt_service_remove(void)
1855 SC_HANDLE hSCManager
= NULL
;
1856 SC_HANDLE hService
= NULL
;
1857 BOOL result
= FALSE
;
1860 if ((hSCManager
= nt_service_open_scm()) == NULL
) {
1864 if ((hService
= nt_service_open(hSCManager
)) == NULL
) {
1865 CloseServiceHandle(hSCManager
);
1869 if (nt_service_stop(hService
)) {
1870 if (DeleteService(hService
)) {
1871 printf("Removed service successfully\n");
1874 errmsg
= nt_strerror(GetLastError());
1875 printf("DeleteService() failed : %s\n", errmsg
);
1880 printf("Service could not be removed\n");
1883 CloseServiceHandle(hService
);
1884 CloseServiceHandle(hSCManager
);
1891 nt_service_cmd_start(void)
1893 SC_HANDLE hSCManager
;
1897 if ((hSCManager
= nt_service_open_scm()) == NULL
)
1899 if ((hService
= nt_service_open(hSCManager
)) == NULL
) {
1900 CloseHandle(hSCManager
);
1904 start
= nt_service_start(hService
);
1905 CloseHandle(hService
);
1906 CloseHandle(hSCManager
);
1913 nt_service_cmd_stop(void)
1915 SC_HANDLE hSCManager
;
1919 if ((hSCManager
= nt_service_open_scm()) == NULL
)
1921 if ((hService
= nt_service_open(hSCManager
)) == NULL
) {
1922 CloseHandle(hSCManager
);
1926 stop
= nt_service_stop(hService
);
1927 CloseHandle(hService
);
1928 CloseHandle(hSCManager
);
1933 /** Given a Win32 error code, this attempts to make Windows
1934 * return a human-readable error message. The char* returned
1935 * is allocated by Windows, but should be freed with LocalFree()
1936 * when finished with it. */
1938 nt_strerror(uint32_t errnum
)
1941 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
,
1942 NULL
, errnum
, MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
1943 (LPSTR
)&msgbuf
, 0, NULL
);
1949 #include <openssl/crypto.h>
1951 _tor_dmalloc_free(void *p
)
1959 tor_main(int argc
, char *argv
[])
1962 int r
= CRYPTO_set_mem_ex_functions(_tor_malloc
, _tor_realloc
, _tor_dmalloc_free
);
1963 notice(LD_CONFIG
, "Set up damalloc; returned %d", r
);
1965 #ifdef MS_WINDOWS_SERVICE
1968 if ((argc
>= 3) && (!strcmp(argv
[1], "-service") || !strcmp(argv
[1], "--service"))) {
1969 if (!strcmp(argv
[2], "install"))
1970 return nt_service_install();
1971 if (!strcmp(argv
[2], "remove"))
1972 return nt_service_remove();
1973 if (!strcmp(argv
[2], "start"))
1974 return nt_service_cmd_start();
1975 if (!strcmp(argv
[2], "stop"))
1976 return nt_service_cmd_stop();
1977 printf("Unrecognized service command '%s'\n", argv
[2]);
1980 // These are left so as not to confuse people who are used to these options
1982 if (!strcmp(argv
[1], "-install") || !strcmp(argv
[1], "--install"))
1983 return nt_service_install();
1984 if (!strcmp(argv
[1], "-remove") || !strcmp(argv
[1], "--remove"))
1985 return nt_service_remove();
1986 if (!strcmp(argv
[1], "-nt-service") || !strcmp(argv
[1], "--nt-service")) {
1992 if (tor_init(argc
, argv
)<0)
1994 switch (get_options()->command
) {
1996 #ifdef MS_WINDOWS_SERVICE
1997 service_status
.dwCurrentState
= SERVICE_RUNNING
;
2001 case CMD_LIST_FINGERPRINT
:
2002 do_list_fingerprint();
2004 case CMD_HASH_PASSWORD
:
2007 case CMD_VERIFY_CONFIG
:
2008 printf("Configuration was valid\n");
2011 warn(LD_BUG
,"Illegal command number %d: internal error.",
2012 get_options()->command
);