stop the infinite loop of freeing the same connection_t over and
[tor.git] / src / or / main.c
blobedcc0a8dc238c7f45f5744345815f480999bd1d5
1 /* Copyright 2001 Matej Pfajfar.
2 * Copyright 2001-2004 Roger Dingledine.
3 * Copyright 2004 Roger Dingledine, Nick Mathewson. */
4 /* See LICENSE for licensing information */
5 /* $Id$ */
6 const char main_c_id[] = "$Id$";
8 /**
9 * \file main.c
10 * \brief Tor main loop and startup functions.
11 **/
13 #include "or.h"
15 /* These signals are defined to help control_signal_act work. */
16 #ifndef SIGHUP
17 #define SIGHUP 1
18 #endif
19 #ifndef SIGINT
20 #define SIGINT 2
21 #endif
22 #ifndef SIGUSR1
23 #define SIGUSR1 10
24 #endif
25 #ifndef SIGUSR2
26 #define SIGUSR2 12
27 #endif
28 #ifndef SIGTERM
29 #define SIGTERM 15
30 #endif
32 /********* PROTOTYPES **********/
34 static void dumpstats(int severity); /* log stats */
35 static void conn_read_callback(int fd, short event, void *_conn);
36 static void conn_write_callback(int fd, short event, void *_conn);
37 static void signal_callback(int fd, short events, void *arg);
38 static void second_elapsed_callback(int fd, short event, void *args);
39 static int conn_close_if_marked(int i);
41 /********* START VARIABLES **********/
43 int global_read_bucket; /**< Max number of bytes I can read this second. */
44 int global_write_bucket; /**< Max number of bytes I can write this second. */
46 /** What was the read bucket before the last call to prepare_for_pool?
47 * (used to determine how many bytes we've read). */
48 static int stats_prev_global_read_bucket;
49 /** What was the write bucket before the last call to prepare_for_pool?
50 * (used to determine how many bytes we've written). */
51 static int stats_prev_global_write_bucket;
52 /** How many bytes have we read/written since we started the process? */
53 static uint64_t stats_n_bytes_read = 0;
54 static uint64_t stats_n_bytes_written = 0;
55 /** What time did this process start up? */
56 long time_of_process_start = 0;
57 /** How many seconds have we been running? */
58 long stats_n_seconds_working = 0;
59 /** When do we next download a directory? */
60 static time_t time_to_fetch_directory = 0;
61 /** When do we next upload our descriptor? */
62 static time_t time_to_force_upload_descriptor = 0;
63 /** When do we next download a running-routers summary? */
64 static time_t time_to_fetch_running_routers = 0;
66 /** Array of all open connections; each element corresponds to the element of
67 * poll_array in the same position. The first nfds elements are valid. */
68 static connection_t *connection_array[MAXCONNECTIONS+1] =
69 { NULL };
70 static smartlist_t *closeable_connection_lst = NULL;
72 static int nfds=0; /**< Number of connections currently active. */
74 /** We set this to 1 when we've fetched a dir, to know whether to complain
75 * yet about unrecognized nicknames in entrynodes, exitnodes, etc.
76 * Also, we don't try building circuits unless this is 1. */
77 int has_fetched_directory=0;
79 /** We set this to 1 when we've opened a circuit, so we can print a log
80 * entry to inform the user that Tor is working. */
81 int has_completed_circuit=0;
83 /* #define MS_WINDOWS_SERVICE */
84 #ifdef MS_WINDOWS_SERVICE
85 #include <tchar.h>
86 #define GENSRV_SERVICENAME TEXT("tor-"VERSION)
87 #define GENSRV_DISPLAYNAME TEXT("Tor "VERSION" Win32 Service")
88 SERVICE_STATUS service_status;
89 SERVICE_STATUS_HANDLE hStatus;
90 static char **backup_argv;
91 static int backup_argc;
92 static int nt_service_is_stopped(void);
93 #else
94 #define nt_service_is_stopped() (0)
95 #endif
97 #define CHECK_DESCRIPTOR_INTERVAL 60
99 /********* END VARIABLES ************/
101 /****************************************************************************
103 * This section contains accessors and other methods on the connection_array
104 * and poll_array variables (which are global within this file and unavailable
105 * outside it).
107 ****************************************************************************/
109 /** Add <b>conn</b> to the array of connections that we can poll on. The
110 * connection's socket must be set; the connection starts out
111 * non-reading and non-writing.
113 int connection_add(connection_t *conn) {
114 tor_assert(conn);
115 tor_assert(conn->s >= 0);
117 if (nfds >= get_options()->MaxConn-1) {
118 log_fn(LOG_WARN,"Failing because we have %d connections already. Please set MaxConn higher.", nfds);
119 return -1;
122 tor_assert(conn->poll_index == -1); /* can only connection_add once */
123 conn->poll_index = nfds;
124 connection_array[nfds] = conn;
126 conn->read_event = tor_malloc_zero(sizeof(struct event));
127 conn->write_event = tor_malloc_zero(sizeof(struct event));
128 event_set(conn->read_event, conn->s, EV_READ|EV_PERSIST,
129 conn_read_callback, conn);
130 event_set(conn->write_event, conn->s, EV_WRITE|EV_PERSIST,
131 conn_write_callback, conn);
133 nfds++;
135 log_fn(LOG_INFO,"new conn type %s, socket %d, nfds %d.",
136 CONN_TYPE_TO_STRING(conn->type), conn->s, nfds);
138 return 0;
141 /** Remove the connection from the global list, and remove the
142 * corresponding poll entry. Calling this function will shift the last
143 * connection (if any) into the position occupied by conn.
145 int connection_remove(connection_t *conn) {
146 int current_index;
148 tor_assert(conn);
149 tor_assert(nfds>0);
151 log_fn(LOG_INFO,"removing socket %d (type %s), nfds now %d",
152 conn->s, CONN_TYPE_TO_STRING(conn->type), nfds-1);
154 tor_assert(conn->poll_index >= 0);
155 current_index = conn->poll_index;
156 if (current_index == nfds-1) { /* this is the end */
157 nfds--;
158 return 0;
161 if (conn->read_event) {
162 event_del(conn->read_event);
163 tor_free(conn->read_event);
165 if (conn->write_event) {
166 event_del(conn->write_event);
167 tor_free(conn->write_event);
170 /* replace this one with the one at the end */
171 nfds--;
172 connection_array[current_index] = connection_array[nfds];
173 connection_array[current_index]->poll_index = current_index;
175 return 0;
178 /** If it's an edge conn, remove it from the list
179 * of conn's on this circuit. If it's not on an edge,
180 * flush and send destroys for all circuits on this conn.
182 * If <b>remove</b> is non-zero, then remove it from the
183 * connection_array and closeable_connection_lst.
185 * Then free it.
187 static void connection_unlink(connection_t *conn, int remove) {
188 circuit_about_to_close_connection(conn);
189 connection_about_to_close_connection(conn);
190 if (remove) {
191 connection_remove(conn);
193 smartlist_remove(closeable_connection_lst, conn);
194 if (conn->type == CONN_TYPE_EXIT) {
195 assert_connection_edge_not_dns_pending(conn);
197 connection_free(conn);
200 /** DOCDOC **/
201 void
202 add_connection_to_closeable_list(connection_t *conn)
204 tor_assert(!smartlist_isin(closeable_connection_lst, conn));
205 tor_assert(conn->marked_for_close);
206 smartlist_add(closeable_connection_lst, conn);
209 /** Return true iff conn is in the current poll array. */
210 int connection_in_array(connection_t *conn) {
211 int i;
212 for (i=0; i<nfds; ++i) {
213 if (conn==connection_array[i])
214 return 1;
216 return 0;
219 /** Set <b>*array</b> to an array of all connections, and <b>*n</b>
220 * to the length of the array. <b>*array</b> and <b>*n</b> must not
221 * be modified.
223 void get_connection_array(connection_t ***array, int *n) {
224 *array = connection_array;
225 *n = nfds;
228 /** Set the event mask on <b>conn</b> to <b>events</b>. (The form of
229 * the event mask is DOCDOC)
231 void connection_watch_events(connection_t *conn, short events) {
232 tor_assert(conn);
233 tor_assert(conn->read_event);
234 tor_assert(conn->write_event);
236 if (events & EV_READ) {
237 event_add(conn->read_event, NULL);
238 } else {
239 event_del(conn->read_event);
242 if (events & EV_WRITE) {
243 event_add(conn->write_event, NULL);
244 } else {
245 event_del(conn->write_event);
249 /** Return true iff <b>conn</b> is listening for read events. */
250 int connection_is_reading(connection_t *conn) {
251 tor_assert(conn);
253 /* This isn't 100% documented, but it should work. */
254 return conn->read_event &&
255 (conn->read_event->ev_flags & (EVLIST_INSERTED|EVLIST_ACTIVE));
258 /** Tell the main loop to stop notifying <b>conn</b> of any read events. */
259 void connection_stop_reading(connection_t *conn) {
260 tor_assert(conn);
261 tor_assert(conn->read_event);
263 log(LOG_DEBUG,"connection_stop_reading() called.");
264 event_del(conn->read_event);
267 /** Tell the main loop to start notifying <b>conn</b> of any read events. */
268 void connection_start_reading(connection_t *conn) {
269 tor_assert(conn);
270 tor_assert(conn->read_event);
272 event_add(conn->read_event, NULL);
275 /** Return true iff <b>conn</b> is listening for write events. */
276 int connection_is_writing(connection_t *conn) {
277 tor_assert(conn);
279 /* This isn't 100% documented, but it should work. */
280 return conn->write_event &&
281 (conn->write_event->ev_flags & (EVLIST_INSERTED|EVLIST_ACTIVE));
284 /** Tell the main loop to stop notifying <b>conn</b> of any write events. */
285 void connection_stop_writing(connection_t *conn) {
286 tor_assert(conn);
287 tor_assert(conn->write_event);
289 event_del(conn->write_event);
292 /** Tell the main loop to start notifying <b>conn</b> of any write events. */
293 void connection_start_writing(connection_t *conn) {
294 tor_assert(conn);
295 tor_assert(conn->write_event);
297 event_add(conn->write_event, NULL);
300 /** DOCDOC */
301 static void
302 close_closeable_connections(void)
304 int i;
305 if (!smartlist_len(closeable_connection_lst))
306 return;
308 for (i = 0; i < smartlist_len(closeable_connection_lst); ) {
309 connection_t *conn = smartlist_get(closeable_connection_lst, i);
310 if (conn->poll_index < 0) {
311 connection_unlink(conn, 0); /* blow it away right now */
312 } else {
313 if (!conn_close_if_marked(conn->poll_index))
314 ++i;
319 /** DOCDOC */
320 static void
321 conn_read_callback(int fd, short event, void *_conn)
323 connection_t *conn = _conn;
324 if (conn->marked_for_close)
325 return;
327 log_fn(LOG_DEBUG,"socket %d wants to read.",conn->s);
329 assert_connection_ok(conn, time(NULL));
330 assert_all_pending_dns_resolves_ok();
332 if (connection_handle_read(conn) < 0) {
333 if (!conn->marked_for_close) {
334 #ifndef MS_WINDOWS
335 log_fn(LOG_WARN,"Bug: unhandled error on read for %s connection (fd %d); removing",
336 CONN_TYPE_TO_STRING(conn->type), conn->s);
337 #endif
338 connection_mark_for_close(conn);
341 assert_connection_ok(conn, time(NULL));
342 assert_all_pending_dns_resolves_ok();
344 if (smartlist_len(closeable_connection_lst))
345 close_closeable_connections();
348 static void conn_write_callback(int fd, short events, void *_conn)
350 connection_t *conn = _conn;
352 log_fn(LOG_DEBUG,"socket %d wants to write.",conn->s);
353 if (conn->marked_for_close)
354 return;
356 assert_connection_ok(conn, time(NULL));
357 assert_all_pending_dns_resolves_ok();
359 if (connection_handle_write(conn) < 0) {
360 if (!conn->marked_for_close) {
361 /* this connection is broken. remove it. */
362 log_fn(LOG_WARN,"Bug: unhandled error on write for %s connection (fd %d); removing",
363 CONN_TYPE_TO_STRING(conn->type), conn->s);
364 conn->has_sent_end = 1; /* otherwise we cry wolf about duplicate close */
365 /* XXX do we need a close-immediate here, so we don't try to flush? */
366 connection_mark_for_close(conn);
369 assert_connection_ok(conn, time(NULL));
370 assert_all_pending_dns_resolves_ok();
372 if (smartlist_len(closeable_connection_lst))
373 close_closeable_connections();
376 #if 0
377 static void conn_read(int i) {
378 connection_t *conn = connection_array[i];
380 if (conn->marked_for_close)
381 return;
383 /* post 0.0.9, sometimes we get into loops like:
384 Jan 06 13:54:14.999 [debug] connection_consider_empty_buckets(): global bucket exhausted. Pausing.
385 Jan 06 13:54:14.999 [debug] connection_stop_reading() called.
386 Jan 06 13:54:14.999 [debug] conn_read(): socket 14 wants to read.
387 Jan 06 13:54:14.999 [debug] connection_consider_empty_buckets(): global bucket exhausted. Pausing.
389 We finish the loop after a couple of seconds go by, but nothing seems
390 to happen during the loop except tight looping over poll. Perhaps the
391 tls buffer has pending bytes but we don't allow ourselves to read them?
394 /* see http://www.greenend.org.uk/rjk/2001/06/poll.html for
395 * discussion of POLLIN vs POLLHUP */
396 if (!(poll_array[i].revents & (POLLIN|POLLHUP|POLLERR)))
397 /* Sometimes read events get triggered for things that didn't ask
398 * for them (XXX due to unknown poll wonkiness) and sometime we
399 * want to read even though there was no read event (due to
400 * pending TLS data).
403 /* XXX Post 0.0.9, we should rewrite this whole if statement;
404 * something sane may result. Nick suspects that the || below
405 * should be a &&.
407 * No, it should remain a ||. Here's why: when we reach the end
408 * of a read bucket, we stop reading on a conn. We don't want to
409 * read any more bytes on it, until we're allowed to resume reading.
410 * So if !connection_is_reading, then return right then. Also, if
411 * poll() said nothing (true because the if above), and there's
412 * nothing pending, then also return because nothing to do.
414 * If poll *does* have something to say, even though
415 * !connection_is_reading, then we want to handle it in connection.c
416 * to make it stop reading for next time, else we loop.
418 if (!connection_is_reading(conn) ||
419 !connection_has_pending_tls_data(conn))
420 return; /* this conn should not read */
422 log_fn(LOG_DEBUG,"socket %d wants to read.",conn->s);
424 assert_connection_ok(conn, time(NULL));
425 assert_all_pending_dns_resolves_ok();
427 if (
428 /* XXX does POLLHUP also mean it's definitely broken? */
429 #ifdef MS_WINDOWS
430 (poll_array[i].revents & POLLERR) ||
431 #endif
432 connection_handle_read(conn) < 0) {
433 if (!conn->marked_for_close) {
434 /* this connection is broken. remove it */
435 #ifndef MS_WINDOWS
436 log_fn(LOG_WARN,"Bug: unhandled error on read for %s connection (fd %d); removing",
437 CONN_TYPE_TO_STRING(conn->type), conn->s);
438 #endif
439 connection_mark_for_close(conn);
442 assert_connection_ok(conn, time(NULL));
443 assert_all_pending_dns_resolves_ok();
446 /** Called when the connection at connection_array[i] has a write event:
447 * checks for validity, catches numerous errors, and dispatches to
448 * connection_handle_write.
450 static void conn_write(int i) {
451 connection_t *conn;
453 if (!(poll_array[i].revents & POLLOUT))
454 return; /* this conn doesn't want to write */
456 conn = connection_array[i];
457 log_fn(LOG_DEBUG,"socket %d wants to write.",conn->s);
458 if (conn->marked_for_close)
459 return;
461 assert_connection_ok(conn, time(NULL));
462 assert_all_pending_dns_resolves_ok();
464 if (connection_handle_write(conn) < 0) {
465 if (!conn->marked_for_close) {
466 /* this connection is broken. remove it. */
467 log_fn(LOG_WARN,"Bug: unhandled error on write for %s connection (fd %d); removing",
468 CONN_TYPE_TO_STRING(conn->type), conn->s);
469 conn->has_sent_end = 1; /* otherwise we cry wolf about duplicate close */
470 /* XXX do we need a close-immediate here, so we don't try to flush? */
471 connection_mark_for_close(conn);
474 assert_connection_ok(conn, time(NULL));
475 assert_all_pending_dns_resolves_ok();
477 #endif
479 /** If the connection at connection_array[i] is marked for close, then:
480 * - If it has data that it wants to flush, try to flush it.
481 * - If it _still_ has data to flush, and conn->hold_open_until_flushed is
482 * true, then leave the connection open and return.
483 * - Otherwise, remove the connection from connection_array and from
484 * all other lists, close it, and free it.
485 * Returns 1 if the connection was closed, 0 otherwise.
486 * DOCDOC closeable_list
488 static int conn_close_if_marked(int i) {
489 connection_t *conn;
490 int retval;
492 conn = connection_array[i];
493 if (!conn->marked_for_close)
494 return 0; /* nothing to see here, move along */
495 assert_connection_ok(conn, time(NULL));
496 assert_all_pending_dns_resolves_ok();
498 log_fn(LOG_INFO,"Cleaning up connection (fd %d).",conn->s);
499 if (conn->s >= 0 && connection_wants_to_flush(conn)) {
500 /* -1 means it's an incomplete edge connection, or that the socket
501 * has already been closed as unflushable. */
502 if (!conn->hold_open_until_flushed)
503 log_fn(LOG_INFO,
504 "Conn (addr %s, fd %d, type %s, state %d) marked, but wants to flush %d bytes. "
505 "(Marked at %s:%d)",
506 conn->address, conn->s, CONN_TYPE_TO_STRING(conn->type), conn->state,
507 (int)conn->outbuf_flushlen, conn->marked_for_close_file, conn->marked_for_close);
508 if (connection_speaks_cells(conn)) {
509 if (conn->state == OR_CONN_STATE_OPEN) {
510 retval = flush_buf_tls(conn->tls, conn->outbuf, &conn->outbuf_flushlen);
511 } else
512 retval = -1; /* never flush non-open broken tls connections */
513 } else {
514 retval = flush_buf(conn->s, conn->outbuf, &conn->outbuf_flushlen);
516 if (retval >= 0 &&
517 conn->hold_open_until_flushed && connection_wants_to_flush(conn)) {
518 log_fn(LOG_INFO,"Holding conn (fd %d) open for more flushing.",conn->s);
519 /* XXX should we reset timestamp_lastwritten here? */
520 return 0;
522 if (connection_wants_to_flush(conn)) {
523 log_fn(LOG_NOTICE,"Conn (addr %s, fd %d, type %s, state %d) is being closed, but there are still %d bytes we can't write. (Marked at %s:%d)",
524 conn->address, conn->s, CONN_TYPE_TO_STRING(conn->type), conn->state,
525 (int)buf_datalen(conn->outbuf), conn->marked_for_close_file,
526 conn->marked_for_close);
529 connection_unlink(conn, 1); /* unlink, remove, free */
530 return 1;
533 /** We've just tried every dirserver we know about, and none of
534 * them were reachable. Assume the network is down. Change state
535 * so next time an application connection arrives we'll delay it
536 * and try another directory fetch. Kill off all the circuit_wait
537 * streams that are waiting now, since they will all timeout anyway.
539 void directory_all_unreachable(time_t now) {
540 connection_t *conn;
542 has_fetched_directory=0;
543 stats_n_seconds_working=0; /* reset it */
545 while ((conn = connection_get_by_type_state(CONN_TYPE_AP,
546 AP_CONN_STATE_CIRCUIT_WAIT))) {
547 conn->has_sent_end = 1; /* it's not connected anywhere, so no need to end */
548 log_fn(LOG_NOTICE,"Network down? Failing connection to '%s:%d'.",
549 conn->socks_request->address, conn->socks_request->port);
550 connection_mark_for_close(conn);
554 /** This function is called whenever we successfully pull down a directory */
555 void directory_has_arrived(time_t now) {
556 or_options_t *options = get_options();
558 log_fn(LOG_INFO, "A directory has arrived.");
560 has_fetched_directory=1;
561 /* Don't try to upload or download anything for a while
562 * after the directory we had when we started.
564 if (!time_to_fetch_directory)
565 time_to_fetch_directory = now + options->DirFetchPeriod;
567 if (!time_to_force_upload_descriptor)
568 time_to_force_upload_descriptor = now + options->DirPostPeriod;
570 if (!time_to_fetch_running_routers)
571 time_to_fetch_running_routers = now + options->StatusFetchPeriod;
573 if (server_mode(options) &&
574 !we_are_hibernating()) { /* connect to the appropriate routers */
575 router_retry_connections();
579 /** Perform regular maintenance tasks for a single connection. This
580 * function gets run once per second per connection by run_housekeeping.
582 static void run_connection_housekeeping(int i, time_t now) {
583 cell_t cell;
584 connection_t *conn = connection_array[i];
585 or_options_t *options = get_options();
587 /* Expire any directory connections that haven't sent anything for 5 min */
588 if (conn->type == CONN_TYPE_DIR &&
589 !conn->marked_for_close &&
590 conn->timestamp_lastwritten + 5*60 < now) {
591 log_fn(LOG_INFO,"Expiring wedged directory conn (fd %d, purpose %d)", conn->s, conn->purpose);
592 connection_mark_for_close(conn);
593 return;
596 /* If we haven't written to an OR connection for a while, then either nuke
597 the connection or send a keepalive, depending. */
598 if (connection_speaks_cells(conn) &&
599 now >= conn->timestamp_lastwritten + options->KeepalivePeriod) {
600 routerinfo_t *router = router_get_by_digest(conn->identity_digest);
601 if ((!connection_state_is_open(conn)) ||
602 (we_are_hibernating() && !circuit_get_by_conn(conn)) ||
603 (!clique_mode(options) && !circuit_get_by_conn(conn) &&
604 (!router || !server_mode(options) || !router_is_clique_mode(router)))) {
605 /* our handshake has expired; we're hibernating;
606 * or we have no circuits and we're both either OPs or normal ORs,
607 * then kill it. */
608 log_fn(LOG_INFO,"Expiring connection to %d (%s:%d).",
609 i,conn->address, conn->port);
610 /* flush anything waiting, e.g. a destroy for a just-expired circ */
611 connection_mark_for_close(conn);
612 conn->hold_open_until_flushed = 1;
613 } else {
614 /* either in clique mode, or we've got a circuit. send a padding cell. */
615 log_fn(LOG_DEBUG,"Sending keepalive to (%s:%d)",
616 conn->address, conn->port);
617 memset(&cell,0,sizeof(cell_t));
618 cell.command = CELL_PADDING;
619 connection_or_write_cell_to_buf(&cell, conn);
624 #define MIN_BW_TO_PUBLISH_DESC 5000 /* 5000 bytes/s sustained */
625 #define MIN_UPTIME_TO_PUBLISH_DESC (30*60) /* half an hour */
627 /** Decide if we're a publishable server or just a client. We are a server if:
628 * - We have the AuthoritativeDirectory option set.
629 * or
630 * - We don't have the ClientOnly option set; and
631 * - We have ORPort set; and
632 * - We have been up for at least MIN_UPTIME_TO_PUBLISH_DESC seconds; and
633 * - We have processed some suitable minimum bandwidth recently; and
634 * - We believe we are reachable from the outside.
636 static int decide_if_publishable_server(time_t now) {
637 int bw;
638 or_options_t *options = get_options();
640 bw = rep_hist_bandwidth_assess();
641 router_set_bandwidth_capacity(bw);
643 if (options->ClientOnly)
644 return 0;
645 if (!options->ORPort)
646 return 0;
648 /* XXX for now, you're only a server if you're a server */
649 return server_mode(options);
651 /* here, determine if we're reachable */
652 if (0) { /* we've recently failed to reach our IP/ORPort from the outside */
653 return 0;
656 if (bw < MIN_BW_TO_PUBLISH_DESC)
657 return 0;
658 if (options->AuthoritativeDir)
659 return 1;
660 if (stats_n_seconds_working < MIN_UPTIME_TO_PUBLISH_DESC)
661 return 0;
663 return 1;
666 /** Return true iff we believe ourselves to be an authoritative
667 * directory server.
669 int authdir_mode(or_options_t *options) {
670 return options->AuthoritativeDir != 0;
673 /** Return true iff we try to stay connected to all ORs at once.
675 int clique_mode(or_options_t *options) {
676 return authdir_mode(options);
679 /** Return true iff we are trying to be a server.
681 int server_mode(or_options_t *options) {
682 return (options->ORPort != 0 || options->ORBindAddress);
685 /** Remember if we've advertised ourselves to the dirservers. */
686 static int server_is_advertised=0;
688 /** Return true iff we have published our descriptor lately.
690 int advertised_server_mode(void) {
691 return server_is_advertised;
694 /** Return true iff we are trying to be a socks proxy. */
695 int proxy_mode(or_options_t *options) {
696 return (options->SocksPort != 0 || options->SocksBindAddress);
699 /** Perform regular maintenance tasks. This function gets run once per
700 * second by prepare_for_poll.
702 static void run_scheduled_events(time_t now) {
703 static time_t last_rotated_certificate = 0;
704 static time_t time_to_check_listeners = 0;
705 static time_t time_to_check_descriptor = 0;
706 or_options_t *options = get_options();
707 int i;
709 /** 0. See if we've been asked to shut down and our timeout has
710 * expired; or if our bandwidth limits are exhausted and we
711 * should hibernate; or if it's time to wake up from hibernation.
713 consider_hibernation(now);
715 /** 1a. Every MIN_ONION_KEY_LIFETIME seconds, rotate the onion keys,
716 * shut down and restart all cpuworkers, and update the directory if
717 * necessary.
719 if (server_mode(options) &&
720 get_onion_key_set_at()+MIN_ONION_KEY_LIFETIME < now) {
721 log_fn(LOG_INFO,"Rotating onion key.");
722 rotate_onion_key();
723 cpuworkers_rotate();
724 if (router_rebuild_descriptor(1)<0) {
725 log_fn(LOG_WARN, "Couldn't rebuild router descriptor");
727 if (advertised_server_mode())
728 router_upload_dir_desc_to_dirservers(0);
731 /** 1b. Every MAX_SSL_KEY_LIFETIME seconds, we change our TLS context. */
732 if (!last_rotated_certificate)
733 last_rotated_certificate = now;
734 if (last_rotated_certificate+MAX_SSL_KEY_LIFETIME < now) {
735 log_fn(LOG_INFO,"Rotating tls context.");
736 if (tor_tls_context_new(get_identity_key(), 1, options->Nickname,
737 MAX_SSL_KEY_LIFETIME) < 0) {
738 log_fn(LOG_WARN, "Error reinitializing TLS context");
739 /* XXX is it a bug here, that we just keep going? */
741 last_rotated_certificate = now;
742 /* XXXX We should rotate TLS connections as well; this code doesn't change
743 * them at all. */
746 /** 1c. If we have to change the accounting interval or record
747 * bandwidth used in this accounting interval, do so. */
748 if (accounting_is_enabled(options))
749 accounting_run_housekeeping(now);
751 /** 2. Periodically, we consider getting a new directory, getting a
752 * new running-routers list, and/or force-uploading our descriptor
753 * (if we've passed our internal checks). */
754 if (time_to_fetch_directory < now) {
755 /* purge obsolete entries */
756 routerlist_remove_old_routers(ROUTER_MAX_AGE);
758 if (authdir_mode(options)) {
759 /* We're a directory; dump any old descriptors. */
760 dirserv_remove_old_servers(ROUTER_MAX_AGE);
762 if (server_mode(options) && !we_are_hibernating()) {
763 /* dirservers try to reconnect, in case connections have failed;
764 * and normal servers try to reconnect to dirservers */
765 router_retry_connections();
768 directory_get_from_dirserver(DIR_PURPOSE_FETCH_DIR, NULL, 1);
769 time_to_fetch_directory = now + options->DirFetchPeriod;
770 if (time_to_fetch_running_routers < now + options->StatusFetchPeriod) {
771 time_to_fetch_running_routers = now + options->StatusFetchPeriod;
774 /* Also, take this chance to remove old information from rephist. */
775 rep_history_clean(now-24*60*60);
778 if (time_to_fetch_running_routers < now) {
779 if (!authdir_mode(options)) {
780 directory_get_from_dirserver(DIR_PURPOSE_FETCH_RUNNING_LIST, NULL, 1);
782 time_to_fetch_running_routers = now + options->StatusFetchPeriod;
785 if (time_to_force_upload_descriptor < now) {
786 if (decide_if_publishable_server(now)) {
787 server_is_advertised = 1;
788 router_rebuild_descriptor(1);
789 router_upload_dir_desc_to_dirservers(1);
790 } else {
791 server_is_advertised = 0;
794 rend_cache_clean(); /* this should go elsewhere? */
796 time_to_force_upload_descriptor = now + options->DirPostPeriod;
799 /* 2b. Once per minute, regenerate and upload the descriptor if the old
800 * one is inaccurate. */
801 if (time_to_check_descriptor < now) {
802 time_to_check_descriptor = now + CHECK_DESCRIPTOR_INTERVAL;
803 if (decide_if_publishable_server(now)) {
804 server_is_advertised=1;
805 router_rebuild_descriptor(0);
806 router_upload_dir_desc_to_dirservers(0);
807 } else {
808 server_is_advertised=0;
812 /** 3a. Every second, we examine pending circuits and prune the
813 * ones which have been pending for more than a few seconds.
814 * We do this before step 4, so it can try building more if
815 * it's not comfortable with the number of available circuits.
817 circuit_expire_building(now);
819 /** 3b. Also look at pending streams and prune the ones that 'began'
820 * a long time ago but haven't gotten a 'connected' yet.
821 * Do this before step 4, so we can put them back into pending
822 * state to be picked up by the new circuit.
824 connection_ap_expire_beginning();
826 /** 3c. And expire connections that we've held open for too long.
828 connection_expire_held_open();
830 /** 3d. And every 60 seconds, we relaunch listeners if any died. */
831 if (!we_are_hibernating() && time_to_check_listeners < now) {
832 retry_all_listeners(0); /* 0 means "only if some died." */
833 time_to_check_listeners = now+60;
836 /** 4. Every second, we try a new circuit if there are no valid
837 * circuits. Every NewCircuitPeriod seconds, we expire circuits
838 * that became dirty more than MaxCircuitDirtiness seconds ago,
839 * and we make a new circ if there are no clean circuits.
841 if (has_fetched_directory && !we_are_hibernating())
842 circuit_build_needed_circs(now);
844 /** 5. We do housekeeping for each connection... */
845 for (i=0;i<nfds;i++) {
846 run_connection_housekeeping(i, now);
849 /** 6. And remove any marked circuits... */
850 circuit_close_all_marked();
852 /** 7. And upload service descriptors if necessary. */
853 if (has_fetched_directory && !we_are_hibernating())
854 rend_consider_services_upload(now);
856 /** 8. and blow away any connections that need to die. have to do this now,
857 * because if we marked a conn for close and left its socket -1, then
858 * we'll pass it to poll/select and bad things will happen.
860 close_closeable_connections();
863 /** DOCDOC */
864 static void second_elapsed_callback(int fd, short event, void *args)
866 static struct event *timeout_event = NULL;
867 static struct timeval one_second;
868 static long current_second = 0;
869 struct timeval now;
870 size_t bytes_written;
871 size_t bytes_read;
872 int seconds_elapsed;
873 if (!timeout_event) {
874 timeout_event = tor_malloc_zero(sizeof(struct event));
875 evtimer_set(timeout_event, second_elapsed_callback, NULL);
876 one_second.tv_sec = 1;
877 one_second.tv_usec = 0;
880 /* log_fn(LOG_NOTICE, "Tick."); */
881 tor_gettimeofday(&now);
883 /* the second has rolled over. check more stuff. */
884 bytes_written = stats_prev_global_write_bucket - global_write_bucket;
885 bytes_read = stats_prev_global_read_bucket - global_read_bucket;
886 /* XXX below we get suspicious if time jumps forward more than 10
887 * seconds, but we never notice if it jumps *back* more than 10 seconds.
888 * This could be useful for detecting that we just NTP'ed to three
889 * weeks ago and it will be 3 weeks and 15 minutes until any of our
890 * events trigger.
892 seconds_elapsed = current_second ? (now.tv_sec - current_second) : 0;
893 stats_n_bytes_read += bytes_read;
894 stats_n_bytes_written += bytes_written;
895 if (accounting_is_enabled(get_options()))
896 accounting_add_bytes(bytes_read, bytes_written, seconds_elapsed);
897 control_event_bandwidth_used((uint32_t)bytes_read,(uint32_t)bytes_written);
899 connection_bucket_refill(&now);
900 stats_prev_global_read_bucket = global_read_bucket;
901 stats_prev_global_write_bucket = global_write_bucket;
903 /* if more than 10s have elapsed, probably the clock jumped: doesn't count. */
904 if (seconds_elapsed < 10)
905 stats_n_seconds_working += seconds_elapsed;
907 assert_all_pending_dns_resolves_ok();
908 run_scheduled_events(now.tv_sec);
909 assert_all_pending_dns_resolves_ok();
911 current_second = now.tv_sec; /* remember which second it is, for next time */
913 #if 0
914 for (i=0;i<nfds;i++) {
915 conn = connection_array[i];
916 if (connection_has_pending_tls_data(conn) &&
917 connection_is_reading(conn)) {
918 log_fn(LOG_DEBUG,"sock %d has pending bytes.",conn->s);
919 return; /* has pending bytes to read; don't let poll wait. */
922 #endif
924 evtimer_add(timeout_event, &one_second);
927 /** Called when we get a SIGHUP: reload configuration files and keys,
928 * retry all connections, re-upload all descriptors, and so on. */
929 static int do_hup(void) {
930 char keydir[512];
931 or_options_t *options = get_options();
933 log_fn(LOG_NOTICE,"Received sighup. Reloading config.");
934 has_completed_circuit=0;
935 if (accounting_is_enabled(options))
936 accounting_record_bandwidth_usage(time(NULL));
938 /* first, reload config variables, in case they've changed */
939 /* no need to provide argc/v, they've been cached inside init_from_config */
940 if (init_from_config(0, NULL) < 0) {
941 log_fn(LOG_ERR,"Reading config failed--see warnings above. For usage, try -h.");
942 return -1;
944 options = get_options(); /* they have changed now */
945 if (authdir_mode(options)) {
946 /* reload the approved-routers file */
947 tor_snprintf(keydir,sizeof(keydir),"%s/approved-routers", options->DataDirectory);
948 log_fn(LOG_INFO,"Reloading approved fingerprints from %s...",keydir);
949 if (dirserv_parse_fingerprint_file(keydir) < 0) {
950 log_fn(LOG_NOTICE, "Error reloading fingerprints. Continuing with old list.");
953 /* Fetch a new directory. Even authdirservers do this. */
954 directory_get_from_dirserver(DIR_PURPOSE_FETCH_DIR, NULL, 1);
955 if (server_mode(options)) {
956 /* Restart cpuworker and dnsworker processes, so they get up-to-date
957 * configuration options. */
958 cpuworkers_rotate();
959 dnsworkers_rotate();
960 /* Rebuild fresh descriptor. */
961 router_rebuild_descriptor(1);
962 tor_snprintf(keydir,sizeof(keydir),"%s/router.desc", options->DataDirectory);
963 log_fn(LOG_INFO,"Saving descriptor to %s...",keydir);
964 if (write_str_to_file(keydir, router_get_my_descriptor(), 0)) {
965 return -1;
968 return 0;
971 /** Tor main loop. */
972 static int do_main_loop(void) {
973 int loop_result;
975 /* load the private keys, if we're supposed to have them, and set up the
976 * TLS context. */
977 if (! identity_key_is_set()) {
978 if (init_keys() < 0) {
979 log_fn(LOG_ERR,"Error initializing keys; exiting");
980 return -1;
984 /* Set up our buckets */
985 connection_bucket_init();
986 stats_prev_global_read_bucket = global_read_bucket;
987 stats_prev_global_write_bucket = global_write_bucket;
989 /* load the routers file, or assign the defaults. */
990 if (router_reload_router_list()) {
991 return -1;
994 if (authdir_mode(get_options())) {
995 /* the directory is already here, run startup things */
996 router_retry_connections();
999 if (server_mode(get_options())) {
1000 /* launch cpuworkers. Need to do this *after* we've read the onion key. */
1001 cpu_init();
1004 /* set up once-a-second callback. */
1005 second_elapsed_callback(0,0,NULL);
1007 for (;;) {
1008 if (nt_service_is_stopped())
1009 return 0;
1010 /* poll until we have an event, or the second ends */
1011 loop_result = event_dispatch();
1013 /* let catch() handle things like ^c, and otherwise don't worry about it */
1014 if (loop_result < 0) {
1015 int e = errno;
1016 /* let the program survive things like ^z */
1017 if (e != EINTR) {
1018 log_fn(LOG_ERR,"poll failed: %s [%d]",
1019 tor_socket_strerror(e), e);
1020 return -1;
1021 } else {
1022 log_fn(LOG_DEBUG,"poll interrupted.");
1023 /* You can't trust the results of this poll(). Go back to the
1024 * top of the big for loop. */
1025 continue;
1029 /* refilling buckets and sending cells happens at the beginning of the
1030 * next iteration of the loop, inside prepare_for_poll()
1031 * XXXX No longer so.
1036 /** Used to implement the SIGNAL control command: if we accept
1037 * <b>the_signal</b> as a remote pseudo-signal, then act on it and
1038 * return 0. Else return -1. */
1039 /* We don't re-use catch() here because:
1040 * 1. We handle a different set of signals than those allowed in catch.
1041 * 2. Platforms without signal() are unlikely to define SIGfoo.
1042 * 3. The control spec is defined to use fixed numeric signal values
1043 * which just happen to match the unix values.
1046 control_signal_act(int the_signal)
1048 switch(the_signal)
1050 case 1:
1051 signal_callback(0,0,(void*)(uintptr_t)SIGHUP);
1052 break;
1053 case 2:
1054 signal_callback(0,0,(void*)(uintptr_t)SIGINT);
1055 break;
1056 case 10:
1057 signal_callback(0,0,(void*)(uintptr_t)SIGUSR1);
1058 break;
1059 case 12:
1060 signal_callback(0,0,(void*)(uintptr_t)SIGUSR2);
1061 break;
1062 case 15:
1063 signal_callback(0,0,(void*)(uintptr_t)SIGTERM);
1064 break;
1065 default:
1066 return -1;
1068 return 0;
1071 static void signal_callback(int fd, short events, void *arg)
1073 uintptr_t sig = (uintptr_t)arg;
1074 switch (sig)
1076 case SIGTERM:
1077 log(LOG_ERR,"Catching signal TERM, exiting cleanly.");
1078 tor_cleanup();
1079 exit(0);
1080 break;
1081 case SIGINT:
1082 if (!server_mode(get_options())) { /* do it now */
1083 log(LOG_NOTICE,"Interrupt: exiting cleanly.");
1084 tor_cleanup();
1085 exit(0);
1087 hibernate_begin_shutdown();
1088 break;
1089 #ifdef SIGPIPE
1090 case SIGPIPE:
1091 log(LOG_NOTICE,"Caught sigpipe. Ignoring.");
1092 break;
1093 #endif
1094 case SIGUSR1:
1095 /* prefer to log it at INFO, but make sure we always see it */
1096 dumpstats(get_min_log_level()<LOG_INFO ? get_min_log_level() : LOG_INFO);
1097 break;
1098 case SIGUSR2:
1099 switch_logs_debug();
1100 log(LOG_NOTICE,"Caught USR2. Going to loglevel debug.");
1101 break;
1102 case SIGHUP:
1103 if (do_hup() < 0) {
1104 log_fn(LOG_WARN,"Restart failed (config error?). Exiting.");
1105 tor_cleanup();
1106 exit(1);
1108 break;
1109 #ifdef SIGCHLD
1110 case SIGCHLD:
1111 while (waitpid(-1,NULL,WNOHANG) > 0) ; /* keep reaping until no more zombies */
1112 break;
1114 #endif
1117 /** Write all statistics to the log, with log level 'severity'. Called
1118 * in response to a SIGUSR1. */
1119 static void dumpstats(int severity) {
1120 int i;
1121 connection_t *conn;
1122 time_t now = time(NULL);
1123 time_t elapsed;
1125 log(severity, "Dumping stats:");
1127 for (i=0;i<nfds;i++) {
1128 conn = connection_array[i];
1129 log(severity, "Conn %d (socket %d) type %d (%s), state %d (%s), created %d secs ago",
1130 i, conn->s, conn->type, CONN_TYPE_TO_STRING(conn->type),
1131 conn->state, conn_state_to_string[conn->type][conn->state], (int)(now - conn->timestamp_created));
1132 if (!connection_is_listener(conn)) {
1133 log(severity,"Conn %d is to '%s:%d'.",i,conn->address, conn->port);
1134 log(severity,"Conn %d: %d bytes waiting on inbuf (last read %d secs ago)",i,
1135 (int)buf_datalen(conn->inbuf),
1136 (int)(now - conn->timestamp_lastread));
1137 log(severity,"Conn %d: %d bytes waiting on outbuf (last written %d secs ago)",i,
1138 (int)buf_datalen(conn->outbuf), (int)(now - conn->timestamp_lastwritten));
1140 circuit_dump_by_conn(conn, severity); /* dump info about all the circuits using this conn */
1142 log(severity,
1143 "Cells processed: %10lu padding\n"
1144 " %10lu create\n"
1145 " %10lu created\n"
1146 " %10lu relay\n"
1147 " (%10lu relayed)\n"
1148 " (%10lu delivered)\n"
1149 " %10lu destroy",
1150 stats_n_padding_cells_processed,
1151 stats_n_create_cells_processed,
1152 stats_n_created_cells_processed,
1153 stats_n_relay_cells_processed,
1154 stats_n_relay_cells_relayed,
1155 stats_n_relay_cells_delivered,
1156 stats_n_destroy_cells_processed);
1157 if (stats_n_data_cells_packaged)
1158 log(severity,"Average packaged cell fullness: %2.3f%%",
1159 100*(((double)stats_n_data_bytes_packaged) /
1160 (stats_n_data_cells_packaged*RELAY_PAYLOAD_SIZE)) );
1161 if (stats_n_data_cells_received)
1162 log(severity,"Average delivered cell fullness: %2.3f%%",
1163 100*(((double)stats_n_data_bytes_received) /
1164 (stats_n_data_cells_received*RELAY_PAYLOAD_SIZE)) );
1166 if (now - time_of_process_start >= 0)
1167 elapsed = now - time_of_process_start;
1168 else
1169 elapsed = 0;
1171 if (elapsed) {
1172 log(severity,
1173 "Average bandwidth: "U64_FORMAT"/%d = %d bytes/sec reading",
1174 U64_PRINTF_ARG(stats_n_bytes_read),
1175 (int)elapsed,
1176 (int) (stats_n_bytes_read/elapsed));
1177 log(severity,
1178 "Average bandwidth: "U64_FORMAT"/%d = %d bytes/sec writing",
1179 U64_PRINTF_ARG(stats_n_bytes_written),
1180 (int)elapsed,
1181 (int) (stats_n_bytes_written/elapsed));
1184 rep_hist_dump_stats(now,severity);
1185 rend_service_dump_stats(severity);
1188 /** Called by exit() as we shut down the process.
1190 static void exit_function(void)
1192 /* NOTE: If we ever daemonize, this gets called immediately. That's
1193 * okay for now, because we only use this on Windows. */
1194 #ifdef MS_WINDOWS
1195 WSACleanup();
1196 #endif
1199 /** Set up the signal handlers for either parent or child. */
1200 void handle_signals(int is_parent)
1202 #ifndef MS_WINDOWS /* do signal stuff only on unix */
1203 int i;
1204 static int signals[] = {
1205 SIGINT, /* do a controlled slow shutdown */
1206 SIGTERM, /* to terminate now */
1207 SIGPIPE, /* otherwise sigpipe kills us */
1208 SIGUSR1, /* dump stats */
1209 SIGUSR2, /* go to loglevel debug */
1210 SIGHUP, /* to reload config, retry conns, etc */
1211 #ifdef SIGXFSZ
1212 SIGXFSZ, /* handle file-too-big resource exhaustion */
1213 #endif
1214 SIGCHLD, /* handle dns/cpu workers that exit */
1215 -1 };
1216 static struct event signal_events[16]; /* bigger than it has to be. */
1217 if (is_parent) {
1218 for (i = 0; signals[i] >= 0; ++i) {
1219 signal_set(&signal_events[i], signals[i], signal_callback,
1220 (void*)(uintptr_t)signals[i]);
1221 signal_add(&signal_events[i], NULL);
1223 } else {
1224 struct sigaction action;
1225 action.sa_flags = 0;
1226 sigemptyset(&action.sa_mask);
1227 action.sa_handler = SIG_IGN;
1228 sigaction(SIGINT, &action, NULL);
1229 sigaction(SIGTERM, &action, NULL);
1230 sigaction(SIGPIPE, &action, NULL);
1231 sigaction(SIGUSR1, &action, NULL);
1232 sigaction(SIGUSR2, &action, NULL);
1233 sigaction(SIGHUP, &action, NULL);
1234 #ifdef SIGXFSZ
1235 sigaction(SIGXFSZ, &action, NULL);
1236 #endif
1237 #endif /* signal stuff */
1241 /** Main entry point for the Tor command-line client.
1243 static int tor_init(int argc, char *argv[]) {
1244 time_of_process_start = time(NULL);
1245 closeable_connection_lst = smartlist_create();
1246 /* Initialize the history structures. */
1247 rep_hist_init();
1248 /* Initialize the service cache. */
1249 rend_cache_init();
1250 client_dns_init(); /* Init the client dns cache. Do it always, since it's cheap. */
1252 /* give it somewhere to log to initially */
1253 add_temp_log();
1255 log_fn(LOG_NOTICE,"Tor v%s. This is experimental software. Do not rely on it for strong anonymity.",VERSION);
1257 if (network_init()<0) {
1258 log_fn(LOG_ERR,"Error initializing network; exiting.");
1259 return -1;
1261 atexit(exit_function);
1263 if (init_from_config(argc,argv) < 0) {
1264 log_fn(LOG_ERR,"Reading config failed--see warnings above. For usage, try -h.");
1265 return -1;
1268 #ifndef MS_WINDOWS
1269 if (geteuid()==0)
1270 log_fn(LOG_WARN,"You are running Tor as root. You don't need to, and you probably shouldn't.");
1271 #endif
1273 /* only spawn dns handlers if we're a router */
1274 if (server_mode(get_options()) && get_options()->command == CMD_RUN_TOR) {
1275 dns_init(); /* initialize the dns resolve tree, and spawn workers */
1276 /* XXX really, this should get moved to do_main_loop */
1279 handle_signals(1);
1281 crypto_global_init();
1282 crypto_seed_rng();
1283 return 0;
1286 /** Do whatever cleanup is necessary before shutting Tor down. */
1287 void tor_cleanup(void) {
1288 or_options_t *options = get_options();
1289 /* Remove our pid file. We don't care if there was an error when we
1290 * unlink, nothing we could do about it anyways. */
1291 if (options->PidFile && options->command == CMD_RUN_TOR)
1292 unlink(options->PidFile);
1293 crypto_global_cleanup();
1294 if (accounting_is_enabled(options))
1295 accounting_record_bandwidth_usage(time(NULL));
1298 /** Read/create keys as needed, and echo our fingerprint to stdout. */
1299 static void do_list_fingerprint(void)
1301 char buf[FINGERPRINT_LEN+1];
1302 crypto_pk_env_t *k;
1303 const char *nickname = get_options()->Nickname;
1304 if (!server_mode(get_options())) {
1305 printf("Clients don't have long-term identity keys. Exiting.\n");
1306 return;
1308 tor_assert(nickname);
1309 if (init_keys() < 0) {
1310 log_fn(LOG_ERR,"Error initializing keys; exiting");
1311 return;
1313 if (!(k = get_identity_key())) {
1314 log_fn(LOG_ERR,"Error: missing identity key.");
1315 return;
1317 if (crypto_pk_get_fingerprint(k, buf, 1)<0) {
1318 log_fn(LOG_ERR, "Error computing fingerprint");
1319 return;
1321 printf("%s %s\n", nickname, buf);
1324 /** Entry point for password hashing: take the desired password from
1325 * the command line, and print its salted hash to stdout. **/
1326 static void do_hash_password(void)
1329 char output[256];
1330 char key[S2K_SPECIFIER_LEN+DIGEST_LEN];
1332 crypto_rand(key, S2K_SPECIFIER_LEN-1);
1333 key[S2K_SPECIFIER_LEN-1] = (uint8_t)96; /* Hash 64 K of data. */
1334 secret_to_key(key+S2K_SPECIFIER_LEN, DIGEST_LEN,
1335 get_options()->command_arg, strlen(get_options()->command_arg),
1336 key);
1337 if (base64_encode(output, sizeof(output), key, sizeof(key))<0) {
1338 log_fn(LOG_ERR, "Unable to compute base64");
1339 } else {
1340 printf("%s",output);
1344 #ifdef MS_WINDOWS_SERVICE
1345 /** If we're compile to run as an NT service, and the service has been
1346 * shut down, then change our current status and return 1. Else
1347 * return 0.
1349 static int
1350 nt_service_is_stopped(void)
1352 if (service_status.dwCurrentState == SERVICE_STOP_PENDING) {
1353 service_status.dwWin32ExitCode = 0;
1354 service_status.dwCurrentState = SERVICE_STOPPED;
1355 SetServiceStatus(hStatus, &service_status);
1356 return 1;
1358 return 0;
1361 void nt_service_control(DWORD request)
1363 switch (request) {
1364 case SERVICE_CONTROL_STOP:
1365 case SERVICE_CONTROL_SHUTDOWN:
1366 log(LOG_ERR, "Got stop/shutdown request; shutting down cleanly.");
1367 service_status.dwCurrentState = SERVICE_STOP_PENDING;
1368 return;
1370 SetServiceStatus(hStatus, &service_status);
1373 void nt_service_body(int argc, char **argv)
1375 int err;
1376 service_status.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
1377 service_status.dwCurrentState = SERVICE_START_PENDING;
1378 service_status.dwControlsAccepted =
1379 SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
1380 service_status.dwWin32ExitCode = 0;
1381 service_status.dwServiceSpecificExitCode = 0;
1382 service_status.dwCheckPoint = 0;
1383 service_status.dwWaitHint = 1000;
1384 hStatus = RegisterServiceCtrlHandler(GENSRV_SERVICENAME, (LPHANDLER_FUNCTION) nt_service_control);
1386 if (hStatus == 0) {
1387 // failed;
1388 return;
1391 err = tor_init(backup_argc, backup_argv); // refactor this part out of tor_main and do_main_loop
1392 if (err) {
1393 // failed.
1394 service_status.dwCurrentState = SERVICE_STOPPED;
1395 service_status.dwWin32ExitCode = -1;
1396 SetServiceStatus(hStatus, &service_status);
1397 return;
1399 service_status.dwCurrentState = SERVICE_RUNNING;
1400 SetServiceStatus(hStatus, &service_status);
1401 do_main_loop();
1402 tor_cleanup();
1403 return;
1406 void nt_service_main(void)
1408 SERVICE_TABLE_ENTRY table[2];
1409 DWORD result = 0;
1410 table[0].lpServiceName = GENSRV_SERVICENAME;
1411 table[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTION)nt_service_body;
1412 table[1].lpServiceName = NULL;
1413 table[1].lpServiceProc = NULL;
1415 if (!StartServiceCtrlDispatcher(table)) {
1416 result = GetLastError();
1417 printf("Error was %d\n",result);
1418 if (result == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) {
1419 if (tor_init(backup_argc, backup_argv) < 0)
1420 return;
1421 switch (get_options()->command) {
1422 case CMD_RUN_TOR:
1423 do_main_loop();
1424 break;
1425 case CMD_LIST_FINGERPRINT:
1426 do_list_fingerprint();
1427 break;
1428 case CMD_HASH_PASSWORD:
1429 do_hash_password();
1430 break;
1431 default:
1432 log_fn(LOG_ERR, "Illegal command number %d: internal error.", get_options()->command);
1434 tor_cleanup();
1439 int nt_service_install()
1441 /* XXXX Problems with NT services:
1442 * 1. The configuration file needs to be in the same directory as the .exe
1444 * 2. The exe and the configuration file can't be on any directory path
1445 * that contains a space.
1446 * mje - you can quote the string (i.e., "c:\program files")
1448 * 3. Ideally, there should be one EXE that can either run as a
1449 * separate process (as now) or that can install and run itself
1450 * as an NT service. I have no idea how hard this is.
1451 * mje - should be done. It can install and run itself as a service
1453 * Notes about developing NT services:
1455 * 1. Don't count on your CWD. If an absolute path is not given, the
1456 * fopen() function goes wrong.
1457 * 2. The parameters given to the nt_service_body() function differ
1458 * from those given to main() function.
1461 SC_HANDLE hSCManager = NULL;
1462 SC_HANDLE hService = NULL;
1463 TCHAR szPath[_MAX_PATH];
1464 TCHAR szDrive[_MAX_DRIVE];
1465 TCHAR szDir[_MAX_DIR];
1466 char cmd1[] = " -f ";
1467 char cmd2[] = "\\torrc";
1468 char *command;
1469 int len = 0;
1471 if (0 == GetModuleFileName(NULL, szPath, MAX_PATH))
1472 return 0;
1474 _tsplitpath(szPath, szDrive, szDir, NULL, NULL);
1476 /* Account for the extra quotes */
1477 //len = _MAX_PATH + strlen(cmd1) + _MAX_DRIVE + _MAX_DIR + strlen(cmd2);
1478 len = _MAX_PATH + strlen(cmd1) + _MAX_DRIVE + _MAX_DIR + strlen(cmd2) + 4;
1479 command = tor_malloc(len);
1481 /* Create a quoted command line, like "c:\with spaces\tor.exe" -f
1482 * "c:\with spaces\tor.exe"
1484 if (tor_snprintf(command, len, "\"%s\" -f \"%s%storrc\"",
1485 szPath, szDrive, szDir)<0) {
1486 printf("Failed: tor_snprinf()\n");
1487 free(command);
1488 return 0;
1491 if ((hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE)) == NULL) {
1492 printf("Failed: OpenSCManager()\n");
1493 free(command);
1494 return 0;
1497 /* 1/26/2005 mje
1498 * - changed the service start type to auto
1499 * - and changed the lpPassword param to "" instead of NULL as per an
1500 * MSDN article.
1502 if ((hService = CreateService(hSCManager, GENSRV_SERVICENAME, GENSRV_DISPLAYNAME,
1503 SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,
1504 SERVICE_AUTO_START, SERVICE_ERROR_IGNORE, command,
1505 NULL, NULL, NULL, NULL, "")) == NULL) {
1506 printf("Failed: CreateService()\n");
1507 CloseServiceHandle(hSCManager);
1508 free(command);
1509 return 0;
1512 /* Start the service initially, so you don't have to muck with it in the SCM
1514 if(!StartService(hService, 0, NULL))
1515 printf("Service installed, but not started.\n");
1516 else
1517 printf("Service installed and started successfully!\n");
1519 CloseServiceHandle(hService);
1520 CloseServiceHandle(hSCManager);
1521 tor_free(command);
1523 return 0;
1526 int nt_service_remove()
1528 SC_HANDLE hSCManager = NULL;
1529 SC_HANDLE hService = NULL;
1530 SERVICE_STATUS service_status;
1531 BOOL result = FALSE;
1533 if ((hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE)) == NULL) {
1534 printf("Failed: OpenSCManager()\n");
1535 return 0;
1538 if ((hService = OpenService(hSCManager, GENSRV_SERVICENAME, SERVICE_ALL_ACCESS)) == NULL) {
1539 printf("Failed: OpenService()\n");
1540 CloseServiceHandle(hSCManager);
1543 result = ControlService(hService, SERVICE_CONTROL_STOP, &service_status);
1544 if (result) {
1545 while (QueryServiceStatus(hService, &service_status))
1547 if (service_status.dwCurrentState == SERVICE_STOP_PENDING)
1548 Sleep(500);
1549 else
1550 break;
1552 if (DeleteService(hService))
1553 printf("Remove service successfully\n");
1554 else
1555 printf("Failed: DeleteService()\n");
1556 } else {
1557 result = DeleteService(hService);
1558 if (result)
1559 printf("Remove service successfully\n");
1560 else
1561 printf("Failed: DeleteService()\n");
1564 CloseServiceHandle(hService);
1565 CloseServiceHandle(hSCManager);
1567 return 0;
1569 #endif
1571 int tor_main(int argc, char *argv[]) {
1572 #ifdef MS_WINDOWS_SERVICE
1573 backup_argv = argv;
1574 backup_argc = argc;
1575 if ((argc >= 2) && !strcmp(argv[1], "-install"))
1576 return nt_service_install();
1577 if ((argc >= 2) && !strcmp(argv[1], "-remove"))
1578 return nt_service_remove();
1579 nt_service_main();
1580 return 0;
1581 #else
1582 if (tor_init(argc, argv)<0)
1583 return -1;
1584 switch (get_options()->command) {
1585 case CMD_RUN_TOR:
1586 do_main_loop();
1587 break;
1588 case CMD_LIST_FINGERPRINT:
1589 do_list_fingerprint();
1590 break;
1591 case CMD_HASH_PASSWORD:
1592 do_hash_password();
1593 break;
1594 default:
1595 log_fn(LOG_ERR, "Illegal command number %d: internal error.",
1596 get_options()->command);
1598 tor_cleanup();
1599 return -1;
1600 #endif