1 /* Copyright 2001,2002,2003 Roger Dingledine, Matej Pfajfar. */
2 /* See LICENSE for licensing information */
7 /********* PROTOTYPES **********/
9 static void dumpstats(int severity
); /* log stats */
10 static int init_from_config(int argc
, char **argv
);
12 /********* START VARIABLES **********/
14 extern char *conn_state_to_string
[][_CONN_TYPE_MAX
+1];
16 or_options_t options
; /* command-line and config-file options */
17 int global_read_bucket
; /* max number of bytes I can read this second */
19 static int stats_prev_global_read_bucket
;
20 static uint64_t stats_n_bytes_read
= 0;
21 static long stats_n_seconds_reading
= 0;
23 static connection_t
*connection_array
[MAXCONNECTIONS
] =
26 static struct pollfd poll_array
[MAXCONNECTIONS
];
28 static int nfds
=0; /* number of connections currently active */
30 #ifndef MS_WINDOWS /* do signal stuff only on unix */
31 static int please_dumpstats
=0; /* whether we should dump stats during the loop */
32 static int please_reset
=0; /* whether we just got a sighup */
33 static int please_reap_children
=0; /* whether we should waitpid for exited children */
34 #endif /* signal stuff */
36 int has_fetched_directory
=0;
37 /* we set this to 1 when we've fetched a dir, to know whether to complain
38 * yet about unrecognized nicknames in entrynodes, exitnodes, etc.
39 * Also, we don't try building circuits unless this is 1. */
41 int has_completed_circuit
=0;
42 /* we set this to 1 when we've opened a circuit, so we can print a log
43 * entry to inform the user that Tor is working. */
45 /********* END VARIABLES ************/
47 /****************************************************************************
49 * This section contains accessors and other methods on the connection_array
50 * and poll_array variables (which are global within this file and unavailable
53 ****************************************************************************/
55 int connection_add(connection_t
*conn
) {
58 if(nfds
>= options
.MaxConn
-1) {
59 log_fn(LOG_WARN
,"failing because nfds is too high.");
63 conn
->poll_index
= nfds
;
64 connection_set_poll_socket(conn
);
65 connection_array
[nfds
] = conn
;
67 /* zero these out here, because otherwise we'll inherit values from the previously freed one */
68 poll_array
[nfds
].events
= 0;
69 poll_array
[nfds
].revents
= 0;
73 log_fn(LOG_INFO
,"new conn type %s, socket %d, nfds %d.",
74 CONN_TYPE_TO_STRING(conn
->type
), conn
->s
, nfds
);
79 void connection_set_poll_socket(connection_t
*conn
) {
80 poll_array
[conn
->poll_index
].fd
= conn
->s
;
83 /* Remove the connection from the global list, and remove the
84 * corresponding poll entry. Calling this function will shift the last
85 * connection (if any) into the position occupied by conn.
87 int connection_remove(connection_t
*conn
) {
93 log_fn(LOG_INFO
,"removing socket %d (type %s), nfds now %d",
94 conn
->s
, CONN_TYPE_TO_STRING(conn
->type
), nfds
-1);
95 /* if it's an edge conn, remove it from the list
96 * of conn's on this circuit. If it's not on an edge,
97 * flush and send destroys for all circuits on this conn
99 circuit_about_to_close_connection(conn
);
101 current_index
= conn
->poll_index
;
102 if(current_index
== nfds
-1) { /* this is the end */
107 /* replace this one with the one at the end */
109 poll_array
[current_index
].fd
= poll_array
[nfds
].fd
;
110 poll_array
[current_index
].events
= poll_array
[nfds
].events
;
111 poll_array
[current_index
].revents
= poll_array
[nfds
].revents
;
112 connection_array
[current_index
] = connection_array
[nfds
];
113 connection_array
[current_index
]->poll_index
= current_index
;
118 void get_connection_array(connection_t
***array
, int *n
) {
119 *array
= connection_array
;
123 void connection_watch_events(connection_t
*conn
, short events
) {
125 assert(conn
&& conn
->poll_index
< nfds
);
127 poll_array
[conn
->poll_index
].events
= events
;
130 int connection_is_reading(connection_t
*conn
) {
131 return poll_array
[conn
->poll_index
].events
& POLLIN
;
134 void connection_stop_reading(connection_t
*conn
) {
136 assert(conn
&& conn
->poll_index
< nfds
);
138 log(LOG_DEBUG
,"connection_stop_reading() called.");
139 if(poll_array
[conn
->poll_index
].events
& POLLIN
)
140 poll_array
[conn
->poll_index
].events
-= POLLIN
;
143 void connection_start_reading(connection_t
*conn
) {
145 assert(conn
&& conn
->poll_index
< nfds
);
147 poll_array
[conn
->poll_index
].events
|= POLLIN
;
150 int connection_is_writing(connection_t
*conn
) {
151 return poll_array
[conn
->poll_index
].events
& POLLOUT
;
154 void connection_stop_writing(connection_t
*conn
) {
156 assert(conn
&& conn
->poll_index
< nfds
);
158 if(poll_array
[conn
->poll_index
].events
& POLLOUT
)
159 poll_array
[conn
->poll_index
].events
-= POLLOUT
;
162 void connection_start_writing(connection_t
*conn
) {
164 assert(conn
&& conn
->poll_index
< nfds
);
166 poll_array
[conn
->poll_index
].events
|= POLLOUT
;
169 static void conn_read(int i
) {
170 connection_t
*conn
= connection_array
[i
];
172 if (conn
->marked_for_close
)
175 /* see http://www.greenend.org.uk/rjk/2001/06/poll.html for
176 * discussion of POLLIN vs POLLHUP */
177 if(!(poll_array
[i
].revents
& (POLLIN
|POLLHUP
|POLLERR
)))
178 if(!connection_is_reading(conn
) ||
179 !connection_has_pending_tls_data(conn
))
180 return; /* this conn should not read */
182 log_fn(LOG_DEBUG
,"socket %d wants to read.",conn
->s
);
184 assert_connection_ok(conn
, time(NULL
));
185 assert_all_pending_dns_resolves_ok();
188 /* XXX does POLLHUP also mean it's definitely broken? */
190 (poll_array
[i
].revents
& POLLERR
) ||
192 connection_handle_read(conn
) < 0) {
193 if (!conn
->marked_for_close
) {
194 /* this connection is broken. remove it */
195 /* XXX This shouldn't ever happen anymore. */
196 /* XXX but it'll clearly happen on MS_WINDOWS from POLLERR, right? */
197 log_fn(LOG_ERR
,"Unhandled error on read for %s connection (fd %d); removing",
198 CONN_TYPE_TO_STRING(conn
->type
), conn
->s
);
199 connection_mark_for_close(conn
,0);
202 assert_connection_ok(conn
, time(NULL
));
203 assert_all_pending_dns_resolves_ok();
206 static void conn_write(int i
) {
209 if(!(poll_array
[i
].revents
& POLLOUT
))
210 return; /* this conn doesn't want to write */
212 conn
= connection_array
[i
];
213 log_fn(LOG_DEBUG
,"socket %d wants to write.",conn
->s
);
214 if (conn
->marked_for_close
)
217 assert_connection_ok(conn
, time(NULL
));
218 assert_all_pending_dns_resolves_ok();
220 if (connection_handle_write(conn
) < 0) {
221 if (!conn
->marked_for_close
) {
222 /* this connection is broken. remove it. */
223 log_fn(LOG_WARN
,"Unhandled error on read for %s connection (fd %d); removing",
224 CONN_TYPE_TO_STRING(conn
->type
), conn
->s
);
225 conn
->has_sent_end
= 1; /* otherwise we cry wolf about duplicate close */
226 connection_mark_for_close(conn
,0);
229 assert_connection_ok(conn
, time(NULL
));
230 assert_all_pending_dns_resolves_ok();
233 static void conn_close_if_marked(int i
) {
237 conn
= connection_array
[i
];
238 assert_connection_ok(conn
, time(NULL
));
239 assert_all_pending_dns_resolves_ok();
240 if(!conn
->marked_for_close
)
241 return; /* nothing to see here, move along */
243 log_fn(LOG_INFO
,"Cleaning up connection (fd %d).",conn
->s
);
244 if(conn
->s
>= 0 && connection_wants_to_flush(conn
)) {
245 /* -1 means it's an incomplete edge connection, or that the socket
246 * has already been closed as unflushable. */
247 if(!conn
->hold_open_until_flushed
)
249 "Conn (fd %d, type %s, state %d) marked, but wants to flush %d bytes. "
251 conn
->s
, CONN_TYPE_TO_STRING(conn
->type
), conn
->state
,
252 conn
->outbuf_flushlen
, conn
->marked_for_close_file
, conn
->marked_for_close
);
253 if(connection_speaks_cells(conn
)) {
254 if(conn
->state
== OR_CONN_STATE_OPEN
) {
255 retval
= flush_buf_tls(conn
->tls
, conn
->outbuf
, &conn
->outbuf_flushlen
);
256 /* XXX actually, some non-zero results are maybe ok. which ones? */
258 retval
= -1; /* never flush non-open broken tls connections */
260 retval
= flush_buf(conn
->s
, conn
->outbuf
, &conn
->outbuf_flushlen
);
263 conn
->hold_open_until_flushed
&& connection_wants_to_flush(conn
)) {
264 log_fn(LOG_INFO
,"Holding conn (fd %d) open for more flushing.",conn
->s
);
265 /* XXX should we reset timestamp_lastwritten here? */
268 if(connection_wants_to_flush(conn
)) {
269 log_fn(LOG_WARN
,"Conn (fd %d, type %s, state %d) still wants to flush. Losing %d bytes! (Marked at %s:%d)",
270 conn
->s
, CONN_TYPE_TO_STRING(conn
->type
), conn
->state
,
271 (int)buf_datalen(conn
->outbuf
), conn
->marked_for_close_file
,
272 conn
->marked_for_close
);
275 connection_remove(conn
);
276 if(conn
->type
== CONN_TYPE_EXIT
) {
277 assert_connection_edge_not_dns_pending(conn
);
279 connection_free(conn
);
280 if(i
<nfds
) { /* we just replaced the one at i with a new one.
282 conn_close_if_marked(i
);
286 /* This function is called whenever we successfully pull
287 * down a directory */
288 void directory_has_arrived(void) {
290 log_fn(LOG_INFO
, "A directory has arrived.");
292 /* just for testing */
293 // directory_initiate_command(router_pick_directory_server(),
294 // DIR_PURPOSE_FETCH_RENDDESC, "foo", 3);
296 has_fetched_directory
=1;
298 if(options
.ORPort
) { /* connect to them all */
299 router_retry_connections();
303 /* Perform regular maintenance tasks for a single connection. This
304 * function gets run once per second per connection by run_housekeeping.
306 static void run_connection_housekeeping(int i
, time_t now
) {
308 connection_t
*conn
= connection_array
[i
];
310 if(conn
->type
== CONN_TYPE_DIR
&&
311 !conn
->marked_for_close
&&
312 conn
->timestamp_lastwritten
+ 5*60 < now
) {
313 log_fn(LOG_WARN
,"Expiring wedged directory conn (purpose %d)", conn
->purpose
);
314 connection_mark_for_close(conn
,0);
315 conn
->hold_open_until_flushed
= 1; /* give it a last chance */
319 /* check connections to see whether we should send a keepalive, expire, or wait */
320 if(!connection_speaks_cells(conn
))
323 if(now
>= conn
->timestamp_lastwritten
+ options
.KeepalivePeriod
) {
324 if((!options
.ORPort
&& !circuit_get_by_conn(conn
)) ||
325 (!connection_state_is_open(conn
))) {
326 /* we're an onion proxy, with no circuits; or our handshake has expired. kill it. */
327 log_fn(LOG_INFO
,"Expiring connection to %d (%s:%d).",
328 i
,conn
->address
, conn
->port
);
329 /* flush anything waiting, e.g. a destroy for a just-expired circ */
330 connection_mark_for_close(conn
,CLOSE_REASON_UNUSED_OR_CONN
);
331 conn
->hold_open_until_flushed
= 1;
333 /* either a full router, or we've got a circuit. send a padding cell. */
334 log_fn(LOG_DEBUG
,"Sending keepalive to (%s:%d)",
335 conn
->address
, conn
->port
);
336 memset(&cell
,0,sizeof(cell_t
));
337 cell
.command
= CELL_PADDING
;
338 connection_or_write_cell_to_buf(&cell
, conn
);
343 /* Perform regular maintenance tasks. This function gets run once per
344 * second by prepare_for_poll.
346 static void run_scheduled_events(time_t now
) {
347 static long time_to_fetch_directory
= 0;
348 static time_t last_uploaded_services
= 0;
349 static time_t last_rotated_certificate
= 0;
353 /* 1a. Every MIN_ONION_KEY_LIFETIME seconds, rotate the onion keys,
354 * shut down and restart all cpuworkers, and update the directory if
357 if (options
.ORPort
&& get_onion_key_set_at()+MIN_ONION_KEY_LIFETIME
< now
) {
360 if (router_rebuild_descriptor()<0) {
361 log_fn(LOG_WARN
, "Couldn't rebuild router descriptor");
363 router_rebuild_descriptor();
364 router_upload_dir_desc_to_dirservers();
367 /* 1b. Every MAX_LINK_KEY_LIFETIME seconds, we change our TLS context. */
368 if (!last_rotated_certificate
)
369 last_rotated_certificate
= now
;
370 if (options
.ORPort
&& last_rotated_certificate
+MAX_SSL_KEY_LIFETIME
< now
) {
371 if (tor_tls_context_new(get_identity_key(), 1, options
.Nickname
,
372 MAX_SSL_KEY_LIFETIME
) < 0) {
373 log_fn(LOG_WARN
, "Error reinitializing TLS context");
375 last_rotated_certificate
= now
;
376 /* XXXX We should rotate TLS connections as well; this code doesn't change
377 * XXXX them at all. */
380 /* 1c. Every DirFetchPostPeriod seconds, we get a new directory and upload
381 * our descriptor (if any). */
382 if(time_to_fetch_directory
< now
) {
383 /* it's time to fetch a new directory and/or post our descriptor */
385 router_rebuild_descriptor();
386 router_upload_dir_desc_to_dirservers();
388 if(!options
.DirPort
) {
389 /* NOTE directory servers do not currently fetch directories.
390 * Hope this doesn't bite us later. */
391 directory_initiate_command(router_pick_directory_server(),
392 DIR_PURPOSE_FETCH_DIR
, NULL
, 0);
394 /* We're a directory; dump any old descriptors. */
395 dirserv_remove_old_servers();
397 /* Force an upload of our descriptors every DirFetchPostPeriod seconds. */
398 rend_services_upload(1);
399 last_uploaded_services
= now
;
400 rend_cache_clean(); /* should this go elsewhere? */
401 time_to_fetch_directory
= now
+ options
.DirFetchPostPeriod
;
405 /* 2. Every second, we examine pending circuits and prune the
406 * ones which have been pending for more than a few seconds.
407 * We do this before step 3, so it can try building more if
408 * it's not comfortable with the number of available circuits.
410 circuit_expire_building(now
);
412 /* 2b. Also look at pending streams and prune the ones that 'began'
413 * a long time ago but haven't gotten a 'connected' yet.
414 * Do this before step 3, so we can put them back into pending
415 * state to be picked up by the new circuit.
417 connection_ap_expire_beginning();
420 /* 2c. And expire connections that we've held open for too long.
422 connection_expire_held_open();
424 /* 3. Every second, we try a new circuit if there are no valid
425 * circuits. Every NewCircuitPeriod seconds, we expire circuits
426 * that became dirty more than NewCircuitPeriod seconds ago,
427 * and we make a new circ if there are no clean circuits.
429 if(has_fetched_directory
)
430 circuit_build_needed_circs(now
);
432 /* 4. We do housekeeping for each connection... */
433 for(i
=0;i
<nfds
;i
++) {
434 run_connection_housekeeping(i
, now
);
437 /* 5. And remove any marked circuits... */
438 circuit_close_all_marked();
440 /* 6. And upload service descriptors for any services whose intro points
441 * have changed in the last second. */
442 if (last_uploaded_services
< now
-5) {
443 rend_services_upload(0);
444 last_uploaded_services
= now
;
448 /* 6. and blow away any connections that need to die. can't do this later
449 * because we might open up a circuit and not realize we're about to cull
450 * the connection it's running over.
451 * XXX we can remove this step once we audit circuit-building to make sure
452 * it doesn't pick a marked-for-close conn. -RD
455 conn_close_if_marked(i
);
459 static int prepare_for_poll(void) {
460 static long current_second
= 0; /* from previous calls to gettimeofday */
465 tor_gettimeofday(&now
);
467 /* Check how much bandwidth we've consumed,
468 * and increment the token buckets. */
469 stats_n_bytes_read
+= stats_prev_global_read_bucket
-global_read_bucket
;
470 connection_bucket_refill(&now
);
471 stats_prev_global_read_bucket
= global_read_bucket
;
473 if(now
.tv_sec
> current_second
) { /* the second has rolled over. check more stuff. */
475 ++stats_n_seconds_reading
;
476 assert_all_pending_dns_resolves_ok();
477 run_scheduled_events(now
.tv_sec
);
478 assert_all_pending_dns_resolves_ok();
480 current_second
= now
.tv_sec
; /* remember which second it is, for next time */
483 for(i
=0;i
<nfds
;i
++) {
484 conn
= connection_array
[i
];
485 if(connection_has_pending_tls_data(conn
) &&
486 connection_is_reading(conn
)) {
487 log_fn(LOG_DEBUG
,"sock %d has pending bytes.",conn
->s
);
488 return 0; /* has pending bytes to read; don't let poll wait. */
492 return (1000 - (now
.tv_usec
/ 1000)); /* how many milliseconds til the next second? */
495 static int init_from_config(int argc
, char **argv
) {
496 if(getconfig(argc
,argv
,&options
)) {
497 log_fn(LOG_ERR
,"Reading config failed. For usage, try -h.");
500 close_logs(); /* we'll close, then open with correct loglevel if necessary */
502 if(options
.User
|| options
.Group
) {
503 if(switch_id(options
.User
, options
.Group
) != 0) {
508 if (options
.RunAsDaemon
) {
509 start_daemon(options
.DataDirectory
);
512 if(!options
.LogFile
&& !options
.RunAsDaemon
)
513 add_stream_log(options
.loglevel
, "<stdout>", stdout
);
514 if(options
.LogFile
) {
515 if (add_file_log(options
.loglevel
, options
.LogFile
) != 0) {
516 /* opening the log file failed! Use stderr and log a warning */
517 add_stream_log(options
.loglevel
, "<stderr>", stderr
);
518 log_fn(LOG_WARN
, "Cannot write to LogFile '%s': %s.", options
.LogFile
, strerror(errno
));
520 log_fn(LOG_NOTICE
, "Successfully opened LogFile '%s', redirecting output.",
523 if(options
.DebugLogFile
) {
524 if (add_file_log(LOG_DEBUG
, options
.DebugLogFile
) != 0)
525 log_fn(LOG_WARN
, "Cannot write to DebugLogFile '%s': %s.", options
.DebugLogFile
, strerror(errno
));
526 log_fn(LOG_DEBUG
, "Successfully opened DebugLogFile '%s'.", options
.DebugLogFile
);
529 connection_bucket_init();
530 stats_prev_global_read_bucket
= global_read_bucket
;
532 if(options
.RunAsDaemon
) {
533 /* XXXX Can we delay this any more? */
537 /* write our pid to the pid file, if we do not have write permissions we will log a warning */
539 write_pidfile(options
.PidFile
);
544 static int do_hup(void) {
547 log_fn(LOG_NOTICE
,"Received sighup. Reloading config.");
548 has_completed_circuit
=0;
549 /* first, reload config variables, in case they've changed */
550 /* no need to provide argc/v, they've been cached inside init_from_config */
551 if (init_from_config(0, NULL
) < 0) {
554 /* reload keys as needed for rendezvous services. */
555 if (rend_service_load_keys()<0) {
556 log_fn(LOG_ERR
,"Error reloading rendezvous service keys");
559 if(retry_all_connections() < 0) {
560 log_fn(LOG_ERR
,"Failed to bind one of the listener ports.");
563 if(options
.DirPort
) {
564 /* reload the approved-routers file */
565 sprintf(keydir
,"%s/approved-routers", options
.DataDirectory
);
566 log_fn(LOG_INFO
,"Reloading approved fingerprints from %s...",keydir
);
567 if(dirserv_parse_fingerprint_file(keydir
) < 0) {
568 log_fn(LOG_WARN
, "Error reloading fingerprints. Continuing with old list.");
570 /* Since we aren't fetching a directory, we won't retry rendezvous points
571 * when it gets in. Try again now. */
572 rend_services_introduce();
574 /* fetch a new directory */
575 directory_initiate_command(router_pick_directory_server(),
576 DIR_PURPOSE_FETCH_DIR
, NULL
, 0);
579 router_rebuild_descriptor();
580 sprintf(keydir
,"%s/router.desc", options
.DataDirectory
);
581 log_fn(LOG_INFO
,"Dumping descriptor to %s...",keydir
);
582 if (write_str_to_file(keydir
, router_get_my_descriptor())) {
589 static int do_main_loop(void) {
594 /* Initialize the history structures. */
596 /* Intialize the service cache. */
599 /* load the private keys, if we're supposed to have them, and set up the
601 if (init_keys() < 0 || rend_service_load_keys() < 0) {
602 log_fn(LOG_ERR
,"Error initializing keys; exiting");
606 /* load the routers file */
607 if(options
.RouterFile
&&
608 router_set_routerlist_from_file(options
.RouterFile
) < 0) {
609 log_fn(LOG_ERR
,"Error loading router list.");
613 if(options
.DirPort
) { /* the directory is already here, run startup things */
614 has_fetched_directory
= 1;
615 directory_has_arrived();
619 cpu_init(); /* launch cpuworkers. Need to do this *after* we've read the onion key. */
622 /* start up the necessary connections based on which ports are
623 * non-zero. This is where we try to connect to all the other ORs,
624 * and start the listeners.
626 if(retry_all_connections() < 0) {
627 log_fn(LOG_ERR
,"Failed to bind one of the listener ports.");
632 #ifndef MS_WINDOWS /* do signal stuff only on unix */
633 if(please_dumpstats
) {
634 /* prefer to log it at INFO, but make sure we always see it */
635 dumpstats(options
.loglevel
>LOG_INFO
? options
.loglevel
: LOG_INFO
);
636 please_dumpstats
= 0;
642 if(please_reap_children
) {
643 while(waitpid(-1,NULL
,WNOHANG
)) ; /* keep reaping until no more zombies */
644 please_reap_children
= 0;
646 #endif /* signal stuff */
648 timeout
= prepare_for_poll();
650 /* poll until we have an event, or the second ends */
651 poll_result
= tor_poll(poll_array
, nfds
, timeout
);
653 /* let catch() handle things like ^c, and otherwise don't worry about it */
654 if(poll_result
< 0) {
655 if(errno
!= EINTR
) { /* let the program survive things like ^z */
656 log_fn(LOG_ERR
,"poll failed: %s",strerror(errno
));
659 log_fn(LOG_DEBUG
,"poll interrupted.");
663 /* do all the reads and errors first, so we can detect closed sockets */
665 conn_read(i
); /* this also marks broken connections */
667 /* then do the writes */
671 /* any of the conns need to be closed now? */
673 conn_close_if_marked(i
);
675 /* refilling buckets and sending cells happens at the beginning of the
676 * next iteration of the loop, inside prepare_for_poll()
681 static void catch(int the_signal
) {
683 #ifndef MS_WINDOWS /* do signal stuff only on unix */
688 log(LOG_ERR
,"Catching signal %d, exiting cleanly.", the_signal
);
689 /* we don't care if there was an error when we unlink, nothing
690 we could do about it anyways */
692 unlink(options
.PidFile
);
695 log(LOG_WARN
,"Bug: caught sigpipe. Ignoring.");
701 please_dumpstats
= 1;
704 please_reap_children
= 1;
707 log(LOG_WARN
,"Caught signal %d that we can't handle??", the_signal
);
709 #endif /* signal stuff */
712 static void dumpstats(int severity
) {
715 time_t now
= time(NULL
);
717 log(severity
, "Dumping stats:");
719 for(i
=0;i
<nfds
;i
++) {
720 conn
= connection_array
[i
];
721 log(severity
, "Conn %d (socket %d) type %d (%s), state %d (%s), created %d secs ago",
722 i
, conn
->s
, conn
->type
, CONN_TYPE_TO_STRING(conn
->type
),
723 conn
->state
, conn_state_to_string
[conn
->type
][conn
->state
], (int)(now
- conn
->timestamp_created
));
724 if(!connection_is_listener(conn
)) {
725 log(severity
,"Conn %d is to '%s:%d'.",i
,conn
->address
, conn
->port
);
726 log(severity
,"Conn %d: %d bytes waiting on inbuf (last read %d secs ago)",i
,
727 (int)buf_datalen(conn
->inbuf
),
728 (int)(now
- conn
->timestamp_lastread
));
729 log(severity
,"Conn %d: %d bytes waiting on outbuf (last written %d secs ago)",i
,
730 (int)buf_datalen(conn
->outbuf
), (int)(now
- conn
->timestamp_lastwritten
));
732 circuit_dump_by_conn(conn
, severity
); /* dump info about all the circuits using this conn */
735 "Cells processed: %10lu padding\n"
740 " (%10lu delivered)\n"
742 stats_n_padding_cells_processed
,
743 stats_n_create_cells_processed
,
744 stats_n_created_cells_processed
,
745 stats_n_relay_cells_processed
,
746 stats_n_relay_cells_relayed
,
747 stats_n_relay_cells_delivered
,
748 stats_n_destroy_cells_processed
);
749 if (stats_n_data_cells_packaged
)
750 log(severity
,"Average packaged cell fullness: %2.3f%%",
751 100*(((double)stats_n_data_bytes_packaged
) /
752 (stats_n_data_cells_packaged
*RELAY_PAYLOAD_SIZE
)) );
753 if (stats_n_data_cells_received
)
754 log(severity
,"Average delivered cell fullness: %2.3f%%",
755 100*(((double)stats_n_data_bytes_received
) /
756 (stats_n_data_cells_received
*RELAY_PAYLOAD_SIZE
)) );
758 if (stats_n_seconds_reading
)
759 log(severity
,"Average bandwidth used: %d bytes/sec",
760 (int) (stats_n_bytes_read
/stats_n_seconds_reading
));
762 rep_hist_dump_stats(now
,severity
);
763 rend_service_dump_stats(severity
);
766 int network_init(void)
769 /* This silly exercise is necessary before windows will allow gethostbyname to work.
773 r
= WSAStartup(0x101,&WSAData
);
775 log_fn(LOG_WARN
,"Error initializing windows network layer: code was %d",r
);
778 /* XXXX We should call WSACleanup on exit, I think. */
783 void exit_function(void)
790 int tor_main(int argc
, char *argv
[]) {
792 /* give it somewhere to log to initially */
793 add_stream_log(LOG_INFO
, "<stdout>", stdout
);
794 log_fn(LOG_NOTICE
,"Tor v%s. This is experimental software. Do not use it if you need anonymity.",VERSION
);
796 if (network_init()<0) {
797 log_fn(LOG_ERR
,"Error initializing network; exiting.");
800 atexit(exit_function
);
802 if (init_from_config(argc
,argv
) < 0)
807 log_fn(LOG_WARN
,"You are running Tor as root. You don't need to, and you probably shouldn't.");
810 if(options
.ORPort
) { /* only spawn dns handlers if we're a router */
811 dns_init(); /* initialize the dns resolve tree, and spawn workers */
813 if(options
.SocksPort
) {
814 client_dns_init(); /* init the client dns cache */
817 #ifndef MS_WINDOWS /* do signal stuff only on unix */
819 struct sigaction action
;
821 sigemptyset(&action
.sa_mask
);
823 action
.sa_handler
= catch;
824 sigaction(SIGINT
, &action
, NULL
);
825 sigaction(SIGTERM
, &action
, NULL
);
826 sigaction(SIGPIPE
, &action
, NULL
);
827 sigaction(SIGUSR1
, &action
, NULL
);
828 sigaction(SIGHUP
, &action
, NULL
); /* to reload config, retry conns, etc */
829 sigaction(SIGCHLD
, &action
, NULL
); /* handle dns/cpu workers that exit */
831 #endif /* signal stuff */
833 crypto_global_init();
836 crypto_global_cleanup();