1 /* Copyright 2001 Matej Pfajfar.
2 * Copyright 2001-2004 Roger Dingledine.
3 * Copyright 2004 Roger Dingledine, Nick Mathewson. */
4 /* See LICENSE for licensing information */
9 * \brief Tor main loop and startup functions.
14 /********* PROTOTYPES **********/
16 static void dumpstats(int severity
); /* log stats */
18 /********* START VARIABLES **********/
20 int global_read_bucket
; /**< Max number of bytes I can read this second. */
21 int global_write_bucket
; /**< Max number of bytes I can write this second. */
23 /** What was the read bucket before the last call to prepare_for_pool?
24 * (used to determine how many bytes we've read). */
25 static int stats_prev_global_read_bucket
;
26 /** What was the write bucket before the last call to prepare_for_pool?
27 * (used to determine how many bytes we've written). */
28 static int stats_prev_global_write_bucket
;
29 /** How many bytes have we read/written since we started the process? */
30 static uint64_t stats_n_bytes_read
= 0;
31 static uint64_t stats_n_bytes_written
= 0;
32 /** How many seconds have we been running? */
33 long stats_n_seconds_uptime
= 0;
34 /** When do we next download a directory? */
35 static time_t time_to_fetch_directory
= 0;
36 /** When do we next upload our descriptor? */
37 static time_t time_to_force_upload_descriptor
= 0;
38 /** When do we next download a running-routers summary? */
39 static time_t time_to_fetch_running_routers
= 0;
41 /** Array of all open connections; each element corresponds to the element of
42 * poll_array in the same position. The first nfds elements are valid. */
43 static connection_t
*connection_array
[MAXCONNECTIONS
] =
46 /** Array of pollfd objects for calls to poll(). */
47 static struct pollfd poll_array
[MAXCONNECTIONS
];
49 static int nfds
=0; /**< Number of connections currently active. */
51 #ifndef MS_WINDOWS /* do signal stuff only on unix */
52 static int please_dumpstats
=0; /**< Whether we should dump stats during the loop. */
53 static int please_debug
=0; /**< Whether we should switch all logs to -l debug. */
54 static int please_reset
=0; /**< Whether we just got a sighup. */
55 static int please_reap_children
=0; /**< Whether we should waitpid for exited children. */
56 static int please_sigpipe
=0; /**< Whether we've caught a sigpipe lately. */
57 static int please_shutdown
=0; /**< Whether we should shut down Tor. */
58 #endif /* signal stuff */
60 /** We set this to 1 when we've fetched a dir, to know whether to complain
61 * yet about unrecognized nicknames in entrynodes, exitnodes, etc.
62 * Also, we don't try building circuits unless this is 1. */
63 int has_fetched_directory
=0;
65 /** We set this to 1 when we've opened a circuit, so we can print a log
66 * entry to inform the user that Tor is working. */
67 int has_completed_circuit
=0;
69 /* #define MS_WINDOWS_SERVICE */
70 #ifdef MS_WINDOWS_SERVICE
72 #define GENSRV_SERVICENAME TEXT("tor-"VERSION)
73 #define GENSRV_DISPLAYNAME TEXT("Tor "VERSION" Win32 Service")
74 SERVICE_STATUS service_status
;
75 SERVICE_STATUS_HANDLE hStatus
;
76 static char **backup_argv
;
77 static int backup_argc
;
80 #define CHECK_DESCRIPTOR_INTERVAL 60
82 /********* END VARIABLES ************/
84 /****************************************************************************
86 * This section contains accessors and other methods on the connection_array
87 * and poll_array variables (which are global within this file and unavailable
90 ****************************************************************************/
92 /** Add <b>conn</b> to the array of connections that we can poll on. The
93 * connection's socket must be set; the connection starts out
94 * non-reading and non-writing.
96 int connection_add(connection_t
*conn
) {
98 tor_assert(conn
->s
>= 0);
100 if (nfds
>= get_options()->MaxConn
-1) {
101 log_fn(LOG_WARN
,"failing because nfds is too high.");
105 tor_assert(conn
->poll_index
== -1); /* can only connection_add once */
106 conn
->poll_index
= nfds
;
107 connection_array
[nfds
] = conn
;
109 poll_array
[nfds
].fd
= conn
->s
;
111 /* zero these out here, because otherwise we'll inherit values from the previously freed one */
112 poll_array
[nfds
].events
= 0;
113 poll_array
[nfds
].revents
= 0;
117 log_fn(LOG_INFO
,"new conn type %s, socket %d, nfds %d.",
118 CONN_TYPE_TO_STRING(conn
->type
), conn
->s
, nfds
);
123 /** Remove the connection from the global list, and remove the
124 * corresponding poll entry. Calling this function will shift the last
125 * connection (if any) into the position occupied by conn.
127 int connection_remove(connection_t
*conn
) {
133 log_fn(LOG_INFO
,"removing socket %d (type %s), nfds now %d",
134 conn
->s
, CONN_TYPE_TO_STRING(conn
->type
), nfds
-1);
136 tor_assert(conn
->poll_index
>= 0);
137 current_index
= conn
->poll_index
;
138 if (current_index
== nfds
-1) { /* this is the end */
143 /* replace this one with the one at the end */
145 poll_array
[current_index
].fd
= poll_array
[nfds
].fd
;
146 poll_array
[current_index
].events
= poll_array
[nfds
].events
;
147 poll_array
[current_index
].revents
= poll_array
[nfds
].revents
;
148 connection_array
[current_index
] = connection_array
[nfds
];
149 connection_array
[current_index
]->poll_index
= current_index
;
154 /** Return true iff conn is in the current poll array. */
155 int connection_in_array(connection_t
*conn
) {
157 for (i
=0; i
<nfds
; ++i
) {
158 if (conn
==connection_array
[i
])
164 /** Set <b>*array</b> to an array of all connections, and <b>*n</b>
165 * to the length of the array. <b>*array</b> and <b>*n</b> must not
168 void get_connection_array(connection_t
***array
, int *n
) {
169 *array
= connection_array
;
173 /** Set the event mask on <b>conn</b> to <b>events</b>. (The form of
174 * the event mask is as for poll().)
176 void connection_watch_events(connection_t
*conn
, short events
) {
179 tor_assert(conn
->poll_index
>= 0);
180 tor_assert(conn
->poll_index
< nfds
);
182 poll_array
[conn
->poll_index
].events
= events
;
185 /** Return true iff <b>conn</b> is listening for read events. */
186 int connection_is_reading(connection_t
*conn
) {
188 tor_assert(conn
->poll_index
>= 0);
189 return poll_array
[conn
->poll_index
].events
& POLLIN
;
192 /** Tell the main loop to stop notifying <b>conn</b> of any read events. */
193 void connection_stop_reading(connection_t
*conn
) {
195 tor_assert(conn
->poll_index
>= 0);
196 tor_assert(conn
->poll_index
< nfds
);
198 log(LOG_DEBUG
,"connection_stop_reading() called.");
199 poll_array
[conn
->poll_index
].events
&= ~POLLIN
;
202 /** Tell the main loop to start notifying <b>conn</b> of any read events. */
203 void connection_start_reading(connection_t
*conn
) {
205 tor_assert(conn
->poll_index
>= 0);
206 tor_assert(conn
->poll_index
< nfds
);
207 poll_array
[conn
->poll_index
].events
|= POLLIN
;
210 /** Return true iff <b>conn</b> is listening for write events. */
211 int connection_is_writing(connection_t
*conn
) {
212 return poll_array
[conn
->poll_index
].events
& POLLOUT
;
215 /** Tell the main loop to stop notifying <b>conn</b> of any write events. */
216 void connection_stop_writing(connection_t
*conn
) {
218 tor_assert(conn
->poll_index
>= 0);
219 tor_assert(conn
->poll_index
< nfds
);
220 poll_array
[conn
->poll_index
].events
&= ~POLLOUT
;
223 /** Tell the main loop to start notifying <b>conn</b> of any write events. */
224 void connection_start_writing(connection_t
*conn
) {
226 tor_assert(conn
->poll_index
>= 0);
227 tor_assert(conn
->poll_index
< nfds
);
228 poll_array
[conn
->poll_index
].events
|= POLLOUT
;
231 /** Called when the connection at connection_array[i] has a read event,
232 * or it has pending tls data waiting to be read: checks for validity,
233 * catches numerous errors, and dispatches to connection_handle_read.
235 static void conn_read(int i
) {
236 connection_t
*conn
= connection_array
[i
];
238 if (conn
->marked_for_close
)
241 /* see http://www.greenend.org.uk/rjk/2001/06/poll.html for
242 * discussion of POLLIN vs POLLHUP */
243 if (!(poll_array
[i
].revents
& (POLLIN
|POLLHUP
|POLLERR
)))
244 /* Sometimes read events get triggered for things that didn't ask
245 * for them (XXX due to unknown poll wonkiness) and sometime we
246 * want to read even though there was no read event (due to
250 /* XXX Post 0.0.9, we should rewrite this whole if statement;
251 * something sane may result. Nick suspects that the || below
254 if (!connection_is_reading(conn
) ||
255 !connection_has_pending_tls_data(conn
))
256 return; /* this conn should not read */
258 log_fn(LOG_DEBUG
,"socket %d wants to read.",conn
->s
);
260 assert_connection_ok(conn
, time(NULL
));
261 assert_all_pending_dns_resolves_ok();
264 /* XXX does POLLHUP also mean it's definitely broken? */
266 (poll_array
[i
].revents
& POLLERR
) ||
268 connection_handle_read(conn
) < 0) {
269 if (!conn
->marked_for_close
) {
270 /* this connection is broken. remove it */
271 log_fn(LOG_WARN
,"Unhandled error on read for %s connection (fd %d); removing",
272 CONN_TYPE_TO_STRING(conn
->type
), conn
->s
);
273 connection_mark_for_close(conn
);
276 assert_connection_ok(conn
, time(NULL
));
277 assert_all_pending_dns_resolves_ok();
280 /** Called when the connection at connection_array[i] has a write event:
281 * checks for validity, catches numerous errors, and dispatches to
282 * connection_handle_write.
284 static void conn_write(int i
) {
287 if (!(poll_array
[i
].revents
& POLLOUT
))
288 return; /* this conn doesn't want to write */
290 conn
= connection_array
[i
];
291 log_fn(LOG_DEBUG
,"socket %d wants to write.",conn
->s
);
292 if (conn
->marked_for_close
)
295 assert_connection_ok(conn
, time(NULL
));
296 assert_all_pending_dns_resolves_ok();
298 if (connection_handle_write(conn
) < 0) {
299 if (!conn
->marked_for_close
) {
300 /* this connection is broken. remove it. */
301 log_fn(LOG_WARN
,"Unhandled error on write for %s connection (fd %d); removing",
302 CONN_TYPE_TO_STRING(conn
->type
), conn
->s
);
303 conn
->has_sent_end
= 1; /* otherwise we cry wolf about duplicate close */
304 /* XXX do we need a close-immediate here, so we don't try to flush? */
305 connection_mark_for_close(conn
);
308 assert_connection_ok(conn
, time(NULL
));
309 assert_all_pending_dns_resolves_ok();
312 /** If the connection at connection_array[i] is marked for close, then:
313 * - If it has data that it wants to flush, try to flush it.
314 * - If it _still_ has data to flush, and conn->hold_open_until_flushed is
315 * true, then leave the connection open and return.
316 * - Otherwise, remove the connection from connection_array and from
317 * all other lists, close it, and free it.
318 * If we remove the connection, then call conn_closed_if_marked at the new
319 * connection at position i.
321 static void conn_close_if_marked(int i
) {
325 conn
= connection_array
[i
];
326 assert_connection_ok(conn
, time(NULL
));
327 assert_all_pending_dns_resolves_ok();
328 if (!conn
->marked_for_close
)
329 return; /* nothing to see here, move along */
331 log_fn(LOG_INFO
,"Cleaning up connection (fd %d).",conn
->s
);
332 if (conn
->s
>= 0 && connection_wants_to_flush(conn
)) {
333 /* -1 means it's an incomplete edge connection, or that the socket
334 * has already been closed as unflushable. */
335 if (!conn
->hold_open_until_flushed
)
337 "Conn (addr %s, fd %d, type %s, state %d) marked, but wants to flush %d bytes. "
339 conn
->address
, conn
->s
, CONN_TYPE_TO_STRING(conn
->type
), conn
->state
,
340 (int)conn
->outbuf_flushlen
, conn
->marked_for_close_file
, conn
->marked_for_close
);
341 if (connection_speaks_cells(conn
)) {
342 if (conn
->state
== OR_CONN_STATE_OPEN
) {
343 retval
= flush_buf_tls(conn
->tls
, conn
->outbuf
, &conn
->outbuf_flushlen
);
345 retval
= -1; /* never flush non-open broken tls connections */
347 retval
= flush_buf(conn
->s
, conn
->outbuf
, &conn
->outbuf_flushlen
);
350 conn
->hold_open_until_flushed
&& connection_wants_to_flush(conn
)) {
351 log_fn(LOG_INFO
,"Holding conn (fd %d) open for more flushing.",conn
->s
);
352 /* XXX should we reset timestamp_lastwritten here? */
355 if (connection_wants_to_flush(conn
)) {
356 log_fn(LOG_WARN
,"Conn (addr %s, fd %d, type %s, state %d) still wants to flush. Losing %d bytes! (Marked at %s:%d)",
357 conn
->address
, conn
->s
, CONN_TYPE_TO_STRING(conn
->type
), conn
->state
,
358 (int)buf_datalen(conn
->outbuf
), conn
->marked_for_close_file
,
359 conn
->marked_for_close
);
362 /* if it's an edge conn, remove it from the list
363 * of conn's on this circuit. If it's not on an edge,
364 * flush and send destroys for all circuits on this conn
366 circuit_about_to_close_connection(conn
);
367 connection_about_to_close_connection(conn
);
368 connection_remove(conn
);
369 if (conn
->type
== CONN_TYPE_EXIT
) {
370 assert_connection_edge_not_dns_pending(conn
);
372 connection_free(conn
);
373 if (i
<nfds
) { /* we just replaced the one at i with a new one.
375 conn_close_if_marked(i
);
379 /** This function is called whenever we successfully pull down a directory */
380 void directory_has_arrived(time_t now
) {
381 or_options_t
*options
= get_options();
383 log_fn(LOG_INFO
, "A directory has arrived.");
385 has_fetched_directory
=1;
386 /* Don't try to upload or download anything for a while
387 * after the directory we had when we started.
389 if (!time_to_fetch_directory
)
390 time_to_fetch_directory
= now
+ options
->DirFetchPeriod
;
392 if (!time_to_force_upload_descriptor
)
393 time_to_force_upload_descriptor
= now
+ options
->DirPostPeriod
;
395 if (!time_to_fetch_running_routers
)
396 time_to_fetch_running_routers
= now
+ options
->StatusFetchPeriod
;
398 if (server_mode(options
) &&
399 !we_are_hibernating()) { /* connect to the appropriate routers */
400 router_retry_connections();
404 /** Perform regular maintenance tasks for a single connection. This
405 * function gets run once per second per connection by run_housekeeping.
407 static void run_connection_housekeeping(int i
, time_t now
) {
409 connection_t
*conn
= connection_array
[i
];
410 or_options_t
*options
= get_options();
412 /* Expire any directory connections that haven't sent anything for 5 min */
413 if (conn
->type
== CONN_TYPE_DIR
&&
414 !conn
->marked_for_close
&&
415 conn
->timestamp_lastwritten
+ 5*60 < now
) {
416 log_fn(LOG_INFO
,"Expiring wedged directory conn (fd %d, purpose %d)", conn
->s
, conn
->purpose
);
417 connection_mark_for_close(conn
);
421 /* If we haven't written to an OR connection for a while, then either nuke
422 the connection or send a keepalive, depending. */
423 if (connection_speaks_cells(conn
) &&
424 now
>= conn
->timestamp_lastwritten
+ options
->KeepalivePeriod
) {
425 routerinfo_t
*router
= router_get_by_digest(conn
->identity_digest
);
426 if ((!connection_state_is_open(conn
)) ||
427 (we_are_hibernating() && !circuit_get_by_conn(conn
)) ||
428 (!clique_mode(options
) && !circuit_get_by_conn(conn
) &&
429 (!router
|| !server_mode(options
) || !router_is_clique_mode(router
)))) {
430 /* our handshake has expired; we're hibernating;
431 * or we have no circuits and we're both either OPs or normal ORs,
433 log_fn(LOG_INFO
,"Expiring connection to %d (%s:%d).",
434 i
,conn
->address
, conn
->port
);
435 /* flush anything waiting, e.g. a destroy for a just-expired circ */
436 connection_mark_for_close(conn
);
437 conn
->hold_open_until_flushed
= 1;
439 /* either in clique mode, or we've got a circuit. send a padding cell. */
440 log_fn(LOG_DEBUG
,"Sending keepalive to (%s:%d)",
441 conn
->address
, conn
->port
);
442 memset(&cell
,0,sizeof(cell_t
));
443 cell
.command
= CELL_PADDING
;
444 connection_or_write_cell_to_buf(&cell
, conn
);
449 #define MIN_BW_TO_PUBLISH_DESC 5000 /* 5000 bytes/s sustained */
450 #define MIN_UPTIME_TO_PUBLISH_DESC (30*60) /* half an hour */
452 /** Decide if we're a publishable server or just a client. We are a server if:
453 * - We have the AuthoritativeDirectory option set.
455 * - We don't have the ClientOnly option set; and
456 * - We have ORPort set; and
457 * - We have been up for at least MIN_UPTIME_TO_PUBLISH_DESC seconds; and
458 * - We have processed some suitable minimum bandwidth recently; and
459 * - We believe we are reachable from the outside.
461 static int decide_if_publishable_server(time_t now
) {
463 or_options_t
*options
= get_options();
465 bw
= rep_hist_bandwidth_assess();
466 router_set_bandwidth_capacity(bw
);
468 if (options
->ClientOnly
)
470 if (!options
->ORPort
)
473 /* XXX for now, you're only a server if you're a server */
474 return server_mode(options
);
476 /* here, determine if we're reachable */
477 if (0) { /* we've recently failed to reach our IP/ORPort from the outside */
481 if (bw
< MIN_BW_TO_PUBLISH_DESC
)
483 if (options
->AuthoritativeDir
)
485 if (stats_n_seconds_uptime
< MIN_UPTIME_TO_PUBLISH_DESC
)
491 /** Return true iff we believe ourselves to be an authoritative
494 int authdir_mode(or_options_t
*options
) {
495 return options
->AuthoritativeDir
!= 0;
498 /** Return true iff we try to stay connected to all ORs at once.
500 int clique_mode(or_options_t
*options
) {
501 return authdir_mode(options
);
504 /** Return true iff we are trying to be a server.
506 int server_mode(or_options_t
*options
) {
507 return (options
->ORPort
!= 0 || options
->ORBindAddress
);
510 /** Remember if we've advertised ourselves to the dirservers. */
511 static int server_is_advertised
=0;
513 /** Return true iff we have published our descriptor lately.
515 int advertised_server_mode(void) {
516 return server_is_advertised
;
519 /** Return true iff we are trying to be a socks proxy. */
520 int proxy_mode(or_options_t
*options
) {
521 return (options
->SocksPort
!= 0 || options
->SocksBindAddress
);
524 /** Perform regular maintenance tasks. This function gets run once per
525 * second by prepare_for_poll.
527 static void run_scheduled_events(time_t now
) {
528 static time_t last_rotated_certificate
= 0;
529 static time_t time_to_check_listeners
= 0;
530 static time_t time_to_check_descriptor
= 0;
531 or_options_t
*options
= get_options();
534 /** 0. See if we've been asked to shut down and our timeout has
535 * expired; or if our bandwidth limits are exhausted and we
536 * should hibernate; or if it's time to wake up from hibernation.
538 consider_hibernation(now
);
540 /** 1a. Every MIN_ONION_KEY_LIFETIME seconds, rotate the onion keys,
541 * shut down and restart all cpuworkers, and update the directory if
544 if (server_mode(options
) &&
545 get_onion_key_set_at()+MIN_ONION_KEY_LIFETIME
< now
) {
546 log_fn(LOG_INFO
,"Rotating onion key.");
549 if (router_rebuild_descriptor(1)<0) {
550 log_fn(LOG_WARN
, "Couldn't rebuild router descriptor");
552 if (advertised_server_mode())
553 router_upload_dir_desc_to_dirservers(0);
556 /** 1b. Every MAX_SSL_KEY_LIFETIME seconds, we change our TLS context. */
557 if (!last_rotated_certificate
)
558 last_rotated_certificate
= now
;
559 if (last_rotated_certificate
+MAX_SSL_KEY_LIFETIME
< now
) {
560 log_fn(LOG_INFO
,"Rotating tls context.");
561 if (tor_tls_context_new(get_identity_key(), 1, options
->Nickname
,
562 MAX_SSL_KEY_LIFETIME
) < 0) {
563 log_fn(LOG_WARN
, "Error reinitializing TLS context");
565 last_rotated_certificate
= now
;
566 /* XXXX We should rotate TLS connections as well; this code doesn't change
567 * XXXX them at all. */
570 /** 1c. If we have to change the accounting interval or record
571 * bandwidth used in this accounting interval, do so. */
572 if (accounting_is_enabled(options
))
573 accounting_run_housekeeping(now
);
575 /** 2. Periodically, we consider getting a new directory, getting a
576 * new running-routers list, and/or force-uploading our descriptor
577 * (if we've passed our internal checks). */
578 if (time_to_fetch_directory
< now
) {
579 /* purge obsolete entries */
580 routerlist_remove_old_routers(ROUTER_MAX_AGE
);
582 if (authdir_mode(options
)) {
583 /* We're a directory; dump any old descriptors. */
584 dirserv_remove_old_servers(ROUTER_MAX_AGE
);
586 if (server_mode(options
) && !we_are_hibernating()) {
587 /* dirservers try to reconnect, in case connections have failed;
588 * and normal servers try to reconnect to dirservers */
589 router_retry_connections();
592 directory_get_from_dirserver(DIR_PURPOSE_FETCH_DIR
, NULL
);
593 time_to_fetch_directory
= now
+ options
->DirFetchPeriod
;
594 if (time_to_fetch_running_routers
< now
+ options
->StatusFetchPeriod
) {
595 time_to_fetch_running_routers
= now
+ options
->StatusFetchPeriod
;
598 /* Also, take this chance to remove old information from rephist. */
599 rep_history_clean(now
-24*60*60);
602 if (time_to_fetch_running_routers
< now
) {
603 if (!authdir_mode(options
)) {
604 directory_get_from_dirserver(DIR_PURPOSE_FETCH_RUNNING_LIST
, NULL
);
606 time_to_fetch_running_routers
= now
+ options
->StatusFetchPeriod
;
609 if (time_to_force_upload_descriptor
< now
) {
610 if (decide_if_publishable_server(now
)) {
611 server_is_advertised
= 1;
612 router_rebuild_descriptor(1);
613 router_upload_dir_desc_to_dirservers(1);
615 server_is_advertised
= 0;
618 rend_cache_clean(); /* this should go elsewhere? */
620 time_to_force_upload_descriptor
= now
+ options
->DirPostPeriod
;
623 /* 2b. Once per minute, regenerate and upload the descriptor if the old
624 * one is inaccurate. */
625 if (time_to_check_descriptor
< now
) {
626 time_to_check_descriptor
= now
+ CHECK_DESCRIPTOR_INTERVAL
;
627 if (decide_if_publishable_server(now
)) {
628 server_is_advertised
=1;
629 router_rebuild_descriptor(0);
630 router_upload_dir_desc_to_dirservers(0);
632 server_is_advertised
=0;
636 /** 3a. Every second, we examine pending circuits and prune the
637 * ones which have been pending for more than a few seconds.
638 * We do this before step 4, so it can try building more if
639 * it's not comfortable with the number of available circuits.
641 circuit_expire_building(now
);
643 /** 3b. Also look at pending streams and prune the ones that 'began'
644 * a long time ago but haven't gotten a 'connected' yet.
645 * Do this before step 4, so we can put them back into pending
646 * state to be picked up by the new circuit.
648 connection_ap_expire_beginning();
650 /** 3c. And expire connections that we've held open for too long.
652 connection_expire_held_open();
654 /** 3d. And every 60 seconds, we relaunch listeners if any died. */
655 if (!we_are_hibernating() && time_to_check_listeners
< now
) {
656 retry_all_listeners(0); /* 0 means "only if some died." */
657 time_to_check_listeners
= now
+60;
660 /** 4. Every second, we try a new circuit if there are no valid
661 * circuits. Every NewCircuitPeriod seconds, we expire circuits
662 * that became dirty more than NewCircuitPeriod seconds ago,
663 * and we make a new circ if there are no clean circuits.
665 if (has_fetched_directory
&& !we_are_hibernating())
666 circuit_build_needed_circs(now
);
668 /** 5. We do housekeeping for each connection... */
669 for (i
=0;i
<nfds
;i
++) {
670 run_connection_housekeeping(i
, now
);
673 /** 6. And remove any marked circuits... */
674 circuit_close_all_marked();
676 /** 7. And upload service descriptors if necessary. */
677 if (!we_are_hibernating())
678 rend_consider_services_upload(now
);
680 /** 8. and blow away any connections that need to die. have to do this now,
681 * because if we marked a conn for close and left its socket -1, then
682 * we'll pass it to poll/select and bad things will happen.
685 conn_close_if_marked(i
);
688 /** Called every time we're about to call tor_poll. Increments statistics,
689 * and adjusts token buckets. Returns the number of milliseconds to use for
690 * the poll() timeout.
692 static int prepare_for_poll(void) {
693 static long current_second
= 0; /* from previous calls to gettimeofday */
698 tor_gettimeofday(&now
);
700 if (now
.tv_sec
> current_second
) {
701 /* the second has rolled over. check more stuff. */
702 size_t bytes_written
;
705 bytes_written
= stats_prev_global_write_bucket
- global_write_bucket
;
706 bytes_read
= stats_prev_global_read_bucket
- global_read_bucket
;
707 seconds_elapsed
= current_second
? (now
.tv_sec
- current_second
) : 0;
708 stats_n_bytes_read
+= bytes_read
;
709 stats_n_bytes_written
+= bytes_written
;
710 if (accounting_is_enabled(get_options()))
711 accounting_add_bytes(bytes_read
, bytes_written
, seconds_elapsed
);
712 control_event_bandwidth_used((uint32_t)bytes_read
,(uint32_t)bytes_written
);
714 connection_bucket_refill(&now
);
715 stats_prev_global_read_bucket
= global_read_bucket
;
716 stats_prev_global_write_bucket
= global_write_bucket
;
718 stats_n_seconds_uptime
+= seconds_elapsed
;
720 assert_all_pending_dns_resolves_ok();
721 run_scheduled_events(now
.tv_sec
);
722 assert_all_pending_dns_resolves_ok();
724 current_second
= now
.tv_sec
; /* remember which second it is, for next time */
727 for (i
=0;i
<nfds
;i
++) {
728 conn
= connection_array
[i
];
729 if (connection_has_pending_tls_data(conn
) &&
730 connection_is_reading(conn
)) {
731 log_fn(LOG_DEBUG
,"sock %d has pending bytes.",conn
->s
);
732 return 0; /* has pending bytes to read; don't let poll wait. */
736 return (1000 - (now
.tv_usec
/ 1000)); /* how many milliseconds til the next second? */
739 /** Called when we get a SIGHUP: reload configuration files and keys,
740 * retry all connections, re-upload all descriptors, and so on. */
741 static int do_hup(void) {
743 or_options_t
*options
= get_options();
745 log_fn(LOG_NOTICE
,"Received sighup. Reloading config.");
746 has_completed_circuit
=0;
747 if (accounting_is_enabled(options
))
748 accounting_record_bandwidth_usage(time(NULL
));
750 /* first, reload config variables, in case they've changed */
751 /* no need to provide argc/v, they've been cached inside init_from_config */
752 if (init_from_config(0, NULL
) < 0) {
753 log_fn(LOG_ERR
,"Reading config failed--see warnings above. For usage, try -h.");
756 options
= get_options();
757 if (authdir_mode(options
)) {
758 /* reload the approved-routers file */
759 tor_snprintf(keydir
,sizeof(keydir
),"%s/approved-routers", options
->DataDirectory
);
760 log_fn(LOG_INFO
,"Reloading approved fingerprints from %s...",keydir
);
761 if (dirserv_parse_fingerprint_file(keydir
) < 0) {
762 log_fn(LOG_WARN
, "Error reloading fingerprints. Continuing with old list.");
765 /* Fetch a new directory. Even authdirservers do this. */
766 directory_get_from_dirserver(DIR_PURPOSE_FETCH_DIR
, NULL
);
767 if (server_mode(options
)) {
768 /* Restart cpuworker and dnsworker processes, so they get up-to-date
769 * configuration options. */
772 /* Rebuild fresh descriptor. */
773 router_rebuild_descriptor(1);
774 tor_snprintf(keydir
,sizeof(keydir
),"%s/router.desc", options
->DataDirectory
);
775 log_fn(LOG_INFO
,"Saving descriptor to %s...",keydir
);
776 if (write_str_to_file(keydir
, router_get_my_descriptor(), 0)) {
783 /** Tor main loop. */
784 static int do_main_loop(void) {
789 /* load the private keys, if we're supposed to have them, and set up the
791 if (! identity_key_is_set()) {
792 if (init_keys() < 0) {
793 log_fn(LOG_ERR
,"Error initializing keys; exiting");
798 /* Set up our buckets */
799 connection_bucket_init();
800 stats_prev_global_read_bucket
= global_read_bucket
;
801 stats_prev_global_write_bucket
= global_write_bucket
;
803 /* load the routers file, or assign the defaults. */
804 if (router_reload_router_list()) {
808 if (authdir_mode(get_options())) {
809 /* the directory is already here, run startup things */
810 router_retry_connections();
813 if (server_mode(get_options())) {
814 /* launch cpuworkers. Need to do this *after* we've read the onion key. */
819 #ifdef MS_WINDOWS_SERVICE /* Do service stuff only on windows. */
820 if (service_status
.dwCurrentState
== SERVICE_STOP_PENDING
) {
821 service_status
.dwWin32ExitCode
= 0;
822 service_status
.dwCurrentState
= SERVICE_STOPPED
;
823 SetServiceStatus(hStatus
, &service_status
);
827 #ifndef MS_WINDOWS /* do signal stuff only on unix */
828 if (please_shutdown
) {
829 if (!server_mode(get_options())) { /* do it now */
830 log(LOG_NOTICE
,"Interrupt: exiting cleanly.");
834 hibernate_begin_shutdown();
837 if (please_sigpipe
) {
838 log(LOG_NOTICE
,"Caught sigpipe. Ignoring.");
841 if (please_dumpstats
) {
842 /* prefer to log it at INFO, but make sure we always see it */
843 dumpstats(get_min_log_level()<LOG_INFO
? get_min_log_level() : LOG_INFO
);
844 please_dumpstats
= 0;
848 log(LOG_NOTICE
,"Caught USR2. Going to loglevel debug.");
853 log_fn(LOG_WARN
,"Restart failed (config error?). Exiting.");
859 if (please_reap_children
) {
860 while (waitpid(-1,NULL
,WNOHANG
) > 0) ; /* keep reaping until no more zombies */
861 please_reap_children
= 0;
863 #endif /* signal stuff */
865 timeout
= prepare_for_poll();
867 /* poll until we have an event, or the second ends */
868 poll_result
= tor_poll(poll_array
, nfds
, timeout
);
870 /* let catch() handle things like ^c, and otherwise don't worry about it */
871 if (poll_result
< 0) {
872 int e
= tor_socket_errno(-1);
873 /* let the program survive things like ^z */
875 log_fn(LOG_ERR
,"poll failed: %s [%d]",
876 tor_socket_strerror(e
), e
);
879 log_fn(LOG_DEBUG
,"poll interrupted.");
880 /* You can't trust the results of this poll(). Go back to the
881 * top of the big for loop. */
886 /* do all the reads and errors first, so we can detect closed sockets */
888 conn_read(i
); /* this also marks broken connections */
890 /* then do the writes */
894 /* any of the conns need to be closed now? */
896 conn_close_if_marked(i
);
898 /* refilling buckets and sending cells happens at the beginning of the
899 * next iteration of the loop, inside prepare_for_poll()
904 /** Unix signal handler. */
905 static void catch(int the_signal
) {
907 #ifndef MS_WINDOWS /* do signal stuff only on unix */
908 switch (the_signal
) {
911 log(LOG_ERR
,"Catching signal %d, exiting cleanly.", the_signal
);
918 /* don't log here, since it's possible you got the sigpipe because
919 * your log failed! */
926 please_dumpstats
= 1;
932 please_reap_children
= 1;
935 case SIGXFSZ
: /* this happens when write fails with etoobig */
936 break; /* ignore; write will fail and we'll look at errno. */
939 log(LOG_WARN
,"Caught signal %d that we can't handle??", the_signal
);
943 #endif /* signal stuff */
946 /** Write all statistics to the log, with log level 'severity'. Called
947 * in response to a SIGUSR1. */
948 static void dumpstats(int severity
) {
951 time_t now
= time(NULL
);
953 log(severity
, "Dumping stats:");
955 for (i
=0;i
<nfds
;i
++) {
956 conn
= connection_array
[i
];
957 log(severity
, "Conn %d (socket %d) type %d (%s), state %d (%s), created %d secs ago",
958 i
, conn
->s
, conn
->type
, CONN_TYPE_TO_STRING(conn
->type
),
959 conn
->state
, conn_state_to_string
[conn
->type
][conn
->state
], (int)(now
- conn
->timestamp_created
));
960 if (!connection_is_listener(conn
)) {
961 log(severity
,"Conn %d is to '%s:%d'.",i
,conn
->address
, conn
->port
);
962 log(severity
,"Conn %d: %d bytes waiting on inbuf (last read %d secs ago)",i
,
963 (int)buf_datalen(conn
->inbuf
),
964 (int)(now
- conn
->timestamp_lastread
));
965 log(severity
,"Conn %d: %d bytes waiting on outbuf (last written %d secs ago)",i
,
966 (int)buf_datalen(conn
->outbuf
), (int)(now
- conn
->timestamp_lastwritten
));
968 circuit_dump_by_conn(conn
, severity
); /* dump info about all the circuits using this conn */
971 "Cells processed: %10lu padding\n"
976 " (%10lu delivered)\n"
978 stats_n_padding_cells_processed
,
979 stats_n_create_cells_processed
,
980 stats_n_created_cells_processed
,
981 stats_n_relay_cells_processed
,
982 stats_n_relay_cells_relayed
,
983 stats_n_relay_cells_delivered
,
984 stats_n_destroy_cells_processed
);
985 if (stats_n_data_cells_packaged
)
986 log(severity
,"Average packaged cell fullness: %2.3f%%",
987 100*(((double)stats_n_data_bytes_packaged
) /
988 (stats_n_data_cells_packaged
*RELAY_PAYLOAD_SIZE
)) );
989 if (stats_n_data_cells_received
)
990 log(severity
,"Average delivered cell fullness: %2.3f%%",
991 100*(((double)stats_n_data_bytes_received
) /
992 (stats_n_data_cells_received
*RELAY_PAYLOAD_SIZE
)) );
994 if (stats_n_seconds_uptime
)
996 "Average bandwidth used: "U64_FORMAT
"/%ld = %d bytes/sec",
997 U64_PRINTF_ARG(stats_n_bytes_read
),
998 stats_n_seconds_uptime
,
999 (int) (stats_n_bytes_read
/stats_n_seconds_uptime
));
1001 rep_hist_dump_stats(now
,severity
);
1002 rend_service_dump_stats(severity
);
1005 /** Called before we make any calls to network-related functions.
1006 * (Some operating systems require their network libraries to be
1008 static int network_init(void)
1011 /* This silly exercise is necessary before windows will allow gethostbyname to work.
1015 r
= WSAStartup(0x101,&WSAData
);
1017 log_fn(LOG_WARN
,"Error initializing windows network layer: code was %d",r
);
1024 /** Called by exit() as we shut down the process.
1026 static void exit_function(void)
1028 /* NOTE: If we ever daemonize, this gets called immediately. That's
1029 * okay for now, because we only use this on Windows. */
1035 /** Set up the signal handlers for either parent or child. */
1036 void handle_signals(int is_parent
)
1038 #ifndef MS_WINDOWS /* do signal stuff only on unix */
1039 struct sigaction action
;
1040 action
.sa_flags
= 0;
1041 sigemptyset(&action
.sa_mask
);
1043 action
.sa_handler
= is_parent
? catch : SIG_IGN
;
1044 sigaction(SIGINT
, &action
, NULL
); /* do a controlled slow shutdown */
1045 sigaction(SIGTERM
, &action
, NULL
); /* to terminate now */
1046 sigaction(SIGPIPE
, &action
, NULL
); /* otherwise sigpipe kills us */
1047 sigaction(SIGUSR1
, &action
, NULL
); /* dump stats */
1048 sigaction(SIGUSR2
, &action
, NULL
); /* go to loglevel debug */
1049 sigaction(SIGHUP
, &action
, NULL
); /* to reload config, retry conns, etc */
1051 sigaction(SIGXFSZ
, &action
, NULL
); /* handle file-too-big resource exhaustion */
1054 sigaction(SIGCHLD
, &action
, NULL
); /* handle dns/cpu workers that exit */
1055 #endif /* signal stuff */
1058 /** Main entry point for the Tor command-line client.
1060 static int tor_init(int argc
, char *argv
[]) {
1062 /* Initialize the history structures. */
1064 /* Initialize the service cache. */
1066 client_dns_init(); /* Init the client dns cache. Do it always, since it's cheap. */
1068 /* give it somewhere to log to initially */
1070 log_fn(LOG_NOTICE
,"Tor v%s. This is experimental software. Do not rely on it for strong anonymity.",VERSION
);
1072 if (network_init()<0) {
1073 log_fn(LOG_ERR
,"Error initializing network; exiting.");
1076 atexit(exit_function
);
1078 if (init_from_config(argc
,argv
) < 0) {
1079 log_fn(LOG_ERR
,"Reading config failed--see warnings above. For usage, try -h.");
1085 log_fn(LOG_WARN
,"You are running Tor as root. You don't need to, and you probably shouldn't.");
1088 if (server_mode(get_options())) { /* only spawn dns handlers if we're a router */
1089 dns_init(); /* initialize the dns resolve tree, and spawn workers */
1094 crypto_global_init();
1099 /** Do whatever cleanup is necessary before shutting Tor down. */
1100 void tor_cleanup(void) {
1101 or_options_t
*options
= get_options();
1102 /* Remove our pid file. We don't care if there was an error when we
1103 * unlink, nothing we could do about it anyways. */
1104 if (options
->PidFile
&& options
->command
== CMD_RUN_TOR
)
1105 unlink(options
->PidFile
);
1106 crypto_global_cleanup();
1107 if (accounting_is_enabled(options
))
1108 accounting_record_bandwidth_usage(time(NULL
));
1111 /** Read/create keys as needed, and echo our fingerprint to stdout. */
1112 static void do_list_fingerprint(void)
1114 char buf
[FINGERPRINT_LEN
+1];
1116 const char *nickname
= get_options()->Nickname
;
1117 if (!server_mode(get_options())) {
1118 printf("Clients don't have long-term identity keys. Exiting.\n");
1121 tor_assert(nickname
);
1122 if (init_keys() < 0) {
1123 log_fn(LOG_ERR
,"Error initializing keys; exiting");
1126 if (!(k
= get_identity_key())) {
1127 log_fn(LOG_ERR
,"Error: missing identity key.");
1130 if (crypto_pk_get_fingerprint(k
, buf
, 1)<0) {
1131 log_fn(LOG_ERR
, "Error computing fingerprint");
1134 printf("%s %s\n", nickname
, buf
);
1137 /** Entry point for password hashing: take the desired password from
1138 * the command line, and print its salted hash to stdout. **/
1139 static void do_hash_password(void)
1143 char key
[S2K_SPECIFIER_LEN
+DIGEST_LEN
];
1145 crypto_rand(key
, S2K_SPECIFIER_LEN
-1);
1146 key
[S2K_SPECIFIER_LEN
-1] = (uint8_t)96; /* Hash 64 K of data. */
1147 secret_to_key(key
+S2K_SPECIFIER_LEN
, DIGEST_LEN
,
1148 get_options()->command_arg
, strlen(get_options()->command_arg
),
1150 if (base64_encode(output
, sizeof(output
), key
, sizeof(key
))<0) {
1151 log_fn(LOG_ERR
, "Unable to compute base64");
1153 printf("%s",output
);
1157 #ifdef MS_WINDOWS_SERVICE
1158 void nt_service_control(DWORD request
)
1161 case SERVICE_CONTROL_STOP
:
1162 case SERVICE_CONTROL_SHUTDOWN
:
1163 log(LOG_ERR
, "Got stop/shutdown request; shutting down cleanly.");
1164 service_status
.dwCurrentState
= SERVICE_STOP_PENDING
;
1167 SetServiceStatus(hStatus
, &service_status
);
1170 void nt_service_body(int argc
, char **argv
)
1174 service_status
.dwServiceType
= SERVICE_WIN32_OWN_PROCESS
;
1175 service_status
.dwCurrentState
= SERVICE_START_PENDING
;
1176 service_status
.dwControlsAccepted
=
1177 SERVICE_ACCEPT_STOP
|
1178 SERVICE_ACCEPT_SHUTDOWN
;
1179 service_status
.dwWin32ExitCode
= 0;
1180 service_status
.dwServiceSpecificExitCode
= 0;
1181 service_status
.dwCheckPoint
= 0;
1182 service_status
.dwWaitHint
= 1000;
1183 hStatus
= RegisterServiceCtrlHandler(GENSRV_SERVICENAME
, (LPHANDLER_FUNCTION
) nt_service_control
);
1188 err
= tor_init(backup_argc
, backup_argv
); // refactor this part out of tor_main and do_main_loop
1191 service_status
.dwCurrentState
= SERVICE_STOPPED
;
1192 service_status
.dwWin32ExitCode
= -1;
1193 SetServiceStatus(hStatus
, &service_status
);
1196 service_status
.dwCurrentState
= SERVICE_RUNNING
;
1197 SetServiceStatus(hStatus
, &service_status
);
1203 void nt_service_main(void)
1205 SERVICE_TABLE_ENTRY table
[2];
1207 table
[0].lpServiceName
= GENSRV_SERVICENAME
;
1208 table
[0].lpServiceProc
= (LPSERVICE_MAIN_FUNCTION
)nt_service_body
;
1209 table
[1].lpServiceName
= NULL
;
1210 table
[1].lpServiceProc
= NULL
;
1211 if (!StartServiceCtrlDispatcher(table
)) {
1212 result
= GetLastError();
1213 printf("Error was %d\n",result
);
1214 if (result
== ERROR_FAILED_SERVICE_CONTROLLER_CONNECT
) {
1215 if (tor_init(backup_argc
, backup_argv
) < 0)
1217 switch (get_options()->command
) {
1221 case CMD_LIST_FINGERPRINT
:
1222 do_list_fingerprint();
1224 case CMD_HASH_PASSWORD
:
1228 log_fn(LOG_ERR
, "Illegal command number %d: internal error.", get_options()->command
);
1235 int nt_service_install()
1237 /* XXXX Problems with NT services:
1238 * 1. The configuration file needs to be in the same directory as the .exe
1239 * 2. The exe and the configuration file can't be on any directory path
1240 * that contains a space.
1241 * 3. Ideally, there should be one EXE that can either run as a
1242 * separate process (as now) or that can install and run itself
1243 * as an NT service. I have no idea how hard this is.
1245 * Notes about develiping NT services:
1247 * 1. Don't count on your CWD. If an abolute path is not given, the
1248 * fopen() function goes wrong.
1249 * 2. The parameters given to the nt_service_body() function differ
1250 * from those given to main() function.
1253 SC_HANDLE hSCManager
= NULL
;
1254 SC_HANDLE hService
= NULL
;
1255 TCHAR szPath
[_MAX_PATH
];
1256 TCHAR szDrive
[_MAX_DRIVE
];
1257 TCHAR szDir
[_MAX_DIR
];
1258 char cmd1
[] = " -f ";
1259 char cmd2
[] = "\\torrc";
1263 if (0 == GetModuleFileName(NULL
, szPath
, MAX_PATH
))
1266 _tsplitpath(szPath
, szDrive
, szDir
, NULL
, NULL
);
1267 len
= _MAX_PATH
+ strlen(cmd1
) + _MAX_DRIVE
+ _MAX_DIR
+ strlen(cmd2
);
1268 command
= tor_malloc(len
);
1270 strlcpy(command
, szPath
, len
);
1271 strlcat(command
, " -f ", len
);
1272 strlcat(command
, szDrive
, len
);
1273 strlcat(command
, szDir
, len
);
1274 strlcat(command
, "\\torrc", len
);
1276 if ((hSCManager
= OpenSCManager(NULL
, NULL
, SC_MANAGER_CREATE_SERVICE
)) == NULL
) {
1277 printf("Failed: OpenSCManager()\n");
1282 if ((hService
= CreateService(hSCManager
, GENSRV_SERVICENAME
, GENSRV_DISPLAYNAME
,
1283 SERVICE_ALL_ACCESS
, SERVICE_WIN32_OWN_PROCESS
, SERVICE_DEMAND_START
,
1284 SERVICE_ERROR_IGNORE
, command
, NULL
, NULL
,
1285 NULL
, NULL
, NULL
)) == NULL
) {
1286 printf("Failed: CreateService()\n");
1287 CloseServiceHandle(hSCManager
);
1292 CloseServiceHandle(hService
);
1293 CloseServiceHandle(hSCManager
);
1296 printf("Install service successfully\n");
1301 int nt_service_remove()
1303 SC_HANDLE hSCManager
= NULL
;
1304 SC_HANDLE hService
= NULL
;
1305 SERVICE_STATUS service_status
;
1306 BOOL result
= FALSE
;
1308 if ((hSCManager
= OpenSCManager(NULL
, NULL
, SC_MANAGER_CREATE_SERVICE
)) == NULL
) {
1309 printf("Failed: OpenSCManager()\n");
1313 if ((hService
= OpenService(hSCManager
, GENSRV_SERVICENAME
, SERVICE_ALL_ACCESS
)) == NULL
) {
1314 printf("Failed: OpenService()\n");
1315 CloseServiceHandle(hSCManager
);
1318 result
= ControlService(hService
, SERVICE_CONTROL_STOP
, &service_status
);
1320 while (QueryServiceStatus(hService
, &service_status
))
1322 if (service_status
.dwCurrentState
== SERVICE_STOP_PENDING
)
1327 if (DeleteService(hService
))
1328 printf("Remove service successfully\n");
1330 printf("Failed: DeleteService()\n");
1332 result
= DeleteService(hService
);
1334 printf("Remove service successfully\n");
1336 printf("Failed: DeleteService()\n");
1339 CloseServiceHandle(hService
);
1340 CloseServiceHandle(hSCManager
);
1346 int tor_main(int argc
, char *argv
[]) {
1347 #ifdef MS_WINDOWS_SERVICE
1350 if ((argc
>= 2) && !strcmp(argv
[1], "-install"))
1351 return nt_service_install();
1352 if ((argc
>= 2) && !strcmp(argv
[1], "-remove"))
1353 return nt_service_remove();
1357 if (tor_init(argc
, argv
)<0)
1359 switch (get_options()->command
) {
1363 case CMD_LIST_FINGERPRINT
:
1364 do_list_fingerprint();
1366 case CMD_HASH_PASSWORD
:
1370 log_fn(LOG_ERR
, "Illegal command number %d: internal error.",
1371 get_options()->command
);