Make windows version correct; initialize windows foolishness so that gethostbyname...
[tor.git] / src / or / main.c
blobe0777200c97ff7de189e1ae5c2dc3f24517f5944
1 /* Copyright 2001,2002,2003 Roger Dingledine, Matej Pfajfar. */
2 /* See LICENSE for licensing information */
3 /* $Id$ */
5 #include "or.h"
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_type_to_string[];
15 extern char *conn_state_to_string[][_CONN_TYPE_MAX+1];
17 or_options_t options; /* command-line and config-file options */
18 int global_read_bucket; /* max number of bytes I can read this second */
20 static int stats_prev_global_read_bucket;
21 static uint64_t stats_n_bytes_read = 0;
22 static long stats_n_seconds_reading = 0;
24 static connection_t *connection_array[MAXCONNECTIONS] =
25 { NULL };
27 static struct pollfd poll_array[MAXCONNECTIONS];
29 static int nfds=0; /* number of connections currently active */
31 #ifndef MS_WINDOWS /* do signal stuff only on unix */
32 static int please_dumpstats=0; /* whether we should dump stats during the loop */
33 static int please_reset=0; /* whether we just got a sighup */
34 static int please_reap_children=0; /* whether we should waitpid for exited children */
35 #endif /* signal stuff */
37 int has_fetched_directory=0;
38 /* we set this to 1 when we've fetched a dir, to know whether to complain
39 * yet about unrecognized nicknames in entrynodes, exitnodes, etc. */
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
51 * outside it).
53 ****************************************************************************/
55 int connection_add(connection_t *conn) {
57 if(nfds >= options.MaxConn-1) {
58 log(LOG_WARN,"connection_add(): failing because nfds is too high.");
59 return -1;
62 conn->poll_index = nfds;
63 connection_set_poll_socket(conn);
64 connection_array[nfds] = conn;
66 /* zero these out here, because otherwise we'll inherit values from the previously freed one */
67 poll_array[nfds].events = 0;
68 poll_array[nfds].revents = 0;
70 nfds++;
72 log(LOG_INFO,"connection_add(): new conn type %d, socket %d, nfds %d.",conn->type, conn->s, nfds);
74 return 0;
77 void connection_set_poll_socket(connection_t *conn) {
78 poll_array[conn->poll_index].fd = conn->s;
81 /* Remove the connection from the global list, and remove the
82 * corresponding poll entry. Calling this function will shift the last
83 * connection (if any) into the position occupied by conn.
85 int connection_remove(connection_t *conn) {
86 int current_index;
88 assert(conn);
89 assert(nfds>0);
91 log(LOG_INFO,"connection_remove(): removing socket %d, nfds now %d",conn->s, nfds-1);
92 /* if it's an edge conn, remove it from the list
93 * of conn's on this circuit. If it's not on an edge,
94 * flush and send destroys for all circuits on this conn
96 circuit_about_to_close_connection(conn);
98 current_index = conn->poll_index;
99 if(current_index == nfds-1) { /* this is the end */
100 nfds--;
101 return 0;
104 /* we replace this one with the one at the end, then free it */
105 nfds--;
106 poll_array[current_index].fd = poll_array[nfds].fd;
107 poll_array[current_index].events = poll_array[nfds].events;
108 poll_array[current_index].revents = poll_array[nfds].revents;
109 connection_array[current_index] = connection_array[nfds];
110 connection_array[current_index]->poll_index = current_index;
112 return 0;
115 void get_connection_array(connection_t ***array, int *n) {
116 *array = connection_array;
117 *n = nfds;
120 void connection_watch_events(connection_t *conn, short events) {
122 assert(conn && conn->poll_index < nfds);
124 poll_array[conn->poll_index].events = events;
127 int connection_is_reading(connection_t *conn) {
128 return poll_array[conn->poll_index].events & POLLIN;
131 void connection_stop_reading(connection_t *conn) {
133 assert(conn && conn->poll_index < nfds);
135 log(LOG_DEBUG,"connection_stop_reading() called.");
136 if(poll_array[conn->poll_index].events & POLLIN)
137 poll_array[conn->poll_index].events -= POLLIN;
140 void connection_start_reading(connection_t *conn) {
142 assert(conn && conn->poll_index < nfds);
144 poll_array[conn->poll_index].events |= POLLIN;
147 int connection_is_writing(connection_t *conn) {
148 return poll_array[conn->poll_index].events & POLLOUT;
151 void connection_stop_writing(connection_t *conn) {
153 assert(conn && conn->poll_index < nfds);
155 if(poll_array[conn->poll_index].events & POLLOUT)
156 poll_array[conn->poll_index].events -= POLLOUT;
159 void connection_start_writing(connection_t *conn) {
161 assert(conn && conn->poll_index < nfds);
163 poll_array[conn->poll_index].events |= POLLOUT;
166 static void conn_read(int i) {
167 connection_t *conn = connection_array[i];
169 if (conn->marked_for_close)
170 return;
172 /* see http://www.greenend.org.uk/rjk/2001/06/poll.html for
173 * discussion of POLLIN vs POLLHUP */
174 if(!(poll_array[i].revents & (POLLIN|POLLHUP|POLLERR)))
175 if(!connection_is_reading(conn) ||
176 !connection_has_pending_tls_data(conn))
177 return; /* this conn should not read */
179 log_fn(LOG_DEBUG,"socket %d wants to read.",conn->s);
181 assert_connection_ok(conn, time(NULL));
184 /* XXX does POLLHUP also mean it's definitely broken? */
185 #ifdef MS_WINDOWS
186 (poll_array[i].revents & POLLERR) ||
187 #endif
188 connection_handle_read(conn) < 0) {
189 if (!conn->marked_for_close) {
190 /* this connection is broken. remove it */
191 /* XXX This shouldn't ever happen anymore. */
192 /* XXX but it'll clearly happen on MS_WINDOWS from POLLERR, right? */
193 log_fn(LOG_ERR,"Unhandled error on read for %s connection (fd %d); removing",
194 conn_type_to_string[conn->type], conn->s);
195 connection_mark_for_close(conn,0);
198 assert_connection_ok(conn, time(NULL));
201 static void conn_write(int i) {
202 connection_t *conn;
204 if(!(poll_array[i].revents & POLLOUT))
205 return; /* this conn doesn't want to write */
207 conn = connection_array[i];
208 log_fn(LOG_DEBUG,"socket %d wants to write.",conn->s);
209 if (conn->marked_for_close)
210 return;
212 assert_connection_ok(conn, time(NULL));
214 if (connection_handle_write(conn) < 0) {
215 if (!conn->marked_for_close) {
216 /* this connection is broken. remove it. */
217 log_fn(LOG_WARN,"Unhandled error on read for %s connection (fd %d); removing",
218 conn_type_to_string[conn->type], conn->s);
219 conn->has_sent_end = 1; /* otherwise we cry wolf about duplicate close */
220 connection_mark_for_close(conn,0);
223 assert_connection_ok(conn, time(NULL));
226 static void conn_close_if_marked(int i) {
227 connection_t *conn;
228 int retval;
230 conn = connection_array[i];
231 assert_connection_ok(conn, time(NULL));
232 if(!conn->marked_for_close)
233 return; /* nothing to see here, move along */
235 log_fn(LOG_INFO,"Cleaning up connection (fd %d).",conn->s);
236 if(conn->s >= 0 && connection_wants_to_flush(conn)) {
237 /* -1 means it's an incomplete edge connection, or that the socket
238 * has already been closed as unflushable. */
239 if(!conn->hold_open_until_flushed)
240 log_fn(LOG_WARN,
241 "Conn (fd %d, type %d, state %d) marked, but wants to flush %d bytes. "
242 "(Marked at %s:%d)",
243 conn->s, conn->type, conn->state,
244 conn->outbuf_flushlen, conn->marked_for_close_file, conn->marked_for_close);
245 if(connection_speaks_cells(conn)) {
246 if(conn->state == OR_CONN_STATE_OPEN) {
247 retval = flush_buf_tls(conn->tls, conn->outbuf, &conn->outbuf_flushlen);
248 /* XXX actually, some non-zero results are maybe ok. which ones? */
249 } else
250 retval = -1; /* never flush non-open broken tls connections */
251 } else {
252 retval = flush_buf(conn->s, conn->outbuf, &conn->outbuf_flushlen);
254 if(retval >= 0 &&
255 conn->hold_open_until_flushed && connection_wants_to_flush(conn)) {
256 log_fn(LOG_INFO,"Holding conn (fd %d) open for more flushing.",conn->s);
257 /* XXX should we reset timestamp_lastwritten here? */
258 return;
260 if(connection_wants_to_flush(conn)) {
261 log_fn(LOG_WARN,"Conn (fd %d) still wants to flush. Losing %d bytes!",
262 conn->s, (int)buf_datalen(conn->outbuf));
265 connection_remove(conn);
266 connection_free(conn);
267 if(i<nfds) { /* we just replaced the one at i with a new one.
268 process it too. */
269 conn_close_if_marked(i);
273 /* Perform regular maintenance tasks for a single connection. This
274 * function gets run once per second per connection by run_housekeeping.
276 static void run_connection_housekeeping(int i, time_t now) {
277 cell_t cell;
278 connection_t *conn = connection_array[i];
280 if(connection_receiver_bucket_should_increase(conn)) {
281 conn->receiver_bucket += conn->bandwidth;
282 // log_fn(LOG_DEBUG,"Receiver bucket %d now %d.", i, conn->receiver_bucket);
285 if(conn->wants_to_read == 1 /* it's marked to turn reading back on now */
286 && global_read_bucket > 0 /* and we're allowed to read */
287 && (!connection_speaks_cells(conn) || conn->receiver_bucket > 0)) {
288 /* and either a non-cell conn or a cell conn with non-empty bucket */
289 conn->wants_to_read = 0;
290 connection_start_reading(conn);
291 if(conn->wants_to_write == 1) {
292 conn->wants_to_write = 0;
293 connection_start_writing(conn);
297 /* check connections to see whether we should send a keepalive, expire, or wait */
298 if(!connection_speaks_cells(conn))
299 return;
301 if(now >= conn->timestamp_lastwritten + options.KeepalivePeriod) {
302 if((!options.ORPort && !circuit_get_by_conn(conn)) ||
303 (!connection_state_is_open(conn))) {
304 /* we're an onion proxy, with no circuits; or our handshake has expired. kill it. */
305 log_fn(LOG_INFO,"Expiring connection to %d (%s:%d).",
306 i,conn->address, conn->port);
307 /* flush anything waiting, e.g. a destroy for a just-expired circ */
308 connection_mark_for_close(conn,0);
309 conn->hold_open_until_flushed = 1;
310 } else {
311 /* either a full router, or we've got a circuit. send a padding cell. */
312 log_fn(LOG_DEBUG,"Sending keepalive to (%s:%d)",
313 conn->address, conn->port);
314 memset(&cell,0,sizeof(cell_t));
315 cell.command = CELL_PADDING;
316 connection_or_write_cell_to_buf(&cell, conn);
321 /* Perform regular maintenance tasks. This function gets run once per
322 * second by prepare_for_poll.
324 static void run_scheduled_events(time_t now) {
325 static long time_to_fetch_directory = 0;
326 static long time_to_new_circuit = 0;
327 circuit_t *circ;
328 int i;
330 /* 1. Every DirFetchPostPeriod seconds, we get a new directory and upload
331 * our descriptor (if any). */
332 if(time_to_fetch_directory < now) {
333 /* it's time to fetch a new directory and/or post our descriptor */
334 if(options.ORPort) {
335 router_rebuild_descriptor();
336 router_upload_desc_to_dirservers();
338 if(!options.DirPort) {
339 /* NOTE directory servers do not currently fetch directories.
340 * Hope this doesn't bite us later. */
341 directory_initiate_command(router_pick_directory_server(),
342 DIR_CONN_STATE_CONNECTING_FETCH);
344 time_to_fetch_directory = now + options.DirFetchPostPeriod;
347 /* 2. Every second, we examine pending circuits and prune the
348 * ones which have been pending for more than 3 seconds.
349 * We do this before step 3, so it can try building more if
350 * it's not comfortable with the number of available circuits.
352 circuit_expire_building();
354 /* 2b. Also look at pending streams and prune the ones that 'began'
355 * a long time ago but haven't gotten a 'connected' yet.
356 * Do this before step 3, so we can put them back into pending
357 * state to be picked up by the new circuit.
359 connection_ap_expire_beginning();
362 /* 2c. And expire connections that we've held open for too long.
364 connection_expire_held_open();
366 /* 3. Every second, we try a new circuit if there are no valid
367 * circuits. Every NewCircuitPeriod seconds, we expire circuits
368 * that became dirty more than NewCircuitPeriod seconds ago,
369 * and we make a new circ if there are no clean circuits.
371 if(options.SocksPort) {
373 /* launch a new circ for any pending streams that need one */
374 connection_ap_attach_pending();
376 circ = circuit_get_newest(NULL, 1);
377 if(time_to_new_circuit < now) {
378 client_dns_clean();
379 circuit_expire_unused_circuits();
380 circuit_reset_failure_count();
381 if(circ && circ->timestamp_dirty) {
382 log_fn(LOG_INFO,"Youngest circuit dirty; launching replacement.");
383 circuit_launch_new(); /* make a new circuit */
385 time_to_new_circuit = now + options.NewCircuitPeriod;
387 #define CIRCUIT_MIN_BUILDING 3
388 if(!circ && circuit_count_building() < CIRCUIT_MIN_BUILDING) {
389 /* if there's no open circ, and less than 3 are on the way,
390 * go ahead and try another.
392 circuit_launch_new();
396 /* 4. Every second, we check how much bandwidth we've consumed and
397 * increment global_read_bucket.
399 stats_n_bytes_read += stats_prev_global_read_bucket-global_read_bucket;
400 if(global_read_bucket < options.BandwidthBurst) {
401 global_read_bucket += options.BandwidthRate;
402 log_fn(LOG_DEBUG,"global_read_bucket now %d.", global_read_bucket);
404 stats_prev_global_read_bucket = global_read_bucket;
406 /* 5. We do housekeeping for each connection... */
407 for(i=0;i<nfds;i++) {
408 run_connection_housekeeping(i, now);
411 /* 6. And remove any marked circuits... */
412 circuit_close_all_marked();
414 /* 7. and blow away any connections that need to die. can't do this later
415 * because we might open up a circuit and not realize we're about to cull
416 * the connection it's running over.
417 * XXX we can remove this step once we audit circuit-building to make sure
418 * it doesn't pick a marked-for-close conn. -RD
420 for(i=0;i<nfds;i++)
421 conn_close_if_marked(i);
424 static int prepare_for_poll(void) {
425 static long current_second = 0; /* from previous calls to gettimeofday */
426 connection_t *conn;
427 struct timeval now;
428 int i;
430 tor_gettimeofday(&now);
432 if(now.tv_sec > current_second) { /* the second has rolled over. check more stuff. */
434 ++stats_n_seconds_reading;
435 run_scheduled_events(now.tv_sec);
437 current_second = now.tv_sec; /* remember which second it is, for next time */
440 for(i=0;i<nfds;i++) {
441 conn = connection_array[i];
442 if(connection_has_pending_tls_data(conn)) {
443 log_fn(LOG_DEBUG,"sock %d has pending bytes.",conn->s);
444 return 0; /* has pending bytes to read; don't let poll wait. */
448 return (1000 - (now.tv_usec / 1000)); /* how many milliseconds til the next second? */
451 static int init_from_config(int argc, char **argv) {
452 if(getconfig(argc,argv,&options)) {
453 log_fn(LOG_ERR,"Reading config failed. For usage, try -h.");
454 return -1;
456 close_logs(); /* we'll close, then open with correct loglevel if necessary */
458 if(options.User || options.Group) {
459 if(switch_id(options.User, options.Group) != 0) {
460 return -1;
464 if (options.RunAsDaemon) {
465 start_daemon(options.DataDirectory);
468 if(!options.LogFile && !options.RunAsDaemon)
469 add_stream_log(options.loglevel, "<stdout>", stdout);
470 if(options.LogFile) {
471 if (add_file_log(options.loglevel, options.LogFile) != 0) {
472 /* opening the log file failed! Use stderr and log a warning */
473 add_stream_log(options.loglevel, "<stderr>", stderr);
474 log_fn(LOG_WARN, "Cannot write to LogFile '%s': %s.", options.LogFile, strerror(errno));
476 log_fn(LOG_WARN, "Successfully opened LogFile '%s', redirecting output.",
477 options.LogFile);
479 if(options.DebugLogFile) {
480 if (add_file_log(LOG_DEBUG, options.DebugLogFile) != 0)
481 log_fn(LOG_WARN, "Cannot write to DebugLogFile '%s': %s.", options.DebugLogFile, strerror(errno));
482 log_fn(LOG_DEBUG, "Successfully opened DebugLogFile '%s'.", options.DebugLogFile);
485 global_read_bucket = options.BandwidthBurst; /* start it at max traffic */
486 stats_prev_global_read_bucket = global_read_bucket;
488 if(options.RunAsDaemon) {
489 /* XXXX Can we delay this any more? */
490 finish_daemon();
493 /* write our pid to the pid file, if we do not have write permissions we will log a warning */
494 if(options.PidFile)
495 write_pidfile(options.PidFile);
497 return 0;
500 static int do_hup(void) {
501 char keydir[512];
503 log_fn(LOG_WARN,"Received sighup. Reloading config.");
504 has_completed_circuit=0;
505 /* first, reload config variables, in case they've changed */
506 /* no need to provide argc/v, they've been cached inside init_from_config */
507 if (init_from_config(0, NULL) < 0) {
508 exit(1);
510 if(retry_all_connections() < 0) {
511 log_fn(LOG_ERR,"Failed to bind one of the listener ports.");
512 return -1;
514 if(options.DirPort) {
515 /* reload the approved-routers file */
516 sprintf(keydir,"%s/approved-routers", options.DataDirectory);
517 log_fn(LOG_INFO,"Reloading approved fingerprints from %s...",keydir);
518 if(dirserv_parse_fingerprint_file(keydir) < 0) {
519 log_fn(LOG_WARN, "Error reloading fingerprints. Continuing with old list.");
521 } else {
522 /* fetch a new directory */
523 directory_initiate_command(router_pick_directory_server(), DIR_CONN_STATE_CONNECTING_FETCH);
525 if(options.ORPort) {
526 router_rebuild_descriptor();
527 sprintf(keydir,"%s/router.desc", options.DataDirectory);
528 log_fn(LOG_INFO,"Dumping descriptor to %s...",keydir);
529 if (write_str_to_file(keydir, router_get_my_descriptor())) {
530 return -1;
533 return 0;
536 static int do_main_loop(void) {
537 int i;
538 int timeout;
539 int poll_result;
541 /* load the routers file */
542 if(options.RouterFile &&
543 router_set_routerlist_from_file(options.RouterFile) < 0) {
544 log_fn(LOG_ERR,"Error loading router list.");
545 return -1;
548 /* load the private keys, if we're supposed to have them, and set up the
549 * TLS context. */
550 if (init_keys() < 0) {
551 log_fn(LOG_ERR,"Error initializing keys; exiting");
552 return -1;
555 if(options.ORPort) {
556 cpu_init(); /* launch cpuworkers. Need to do this *after* we've read the onion key. */
557 router_upload_desc_to_dirservers(); /* upload our descriptor to all dirservers */
560 /* start up the necessary connections based on which ports are
561 * non-zero. This is where we try to connect to all the other ORs,
562 * and start the listeners.
564 if(retry_all_connections() < 0) {
565 log_fn(LOG_ERR,"Failed to bind one of the listener ports.");
566 return -1;
569 for(;;) {
570 #ifndef MS_WINDOWS /* do signal stuff only on unix */
571 if(please_dumpstats) {
572 /* prefer to log it at INFO, but make sure we always see it */
573 dumpstats(options.loglevel>LOG_INFO ? options.loglevel : LOG_INFO);
574 please_dumpstats = 0;
576 if(please_reset) {
577 do_hup();
578 please_reset = 0;
580 if(please_reap_children) {
581 while(waitpid(-1,NULL,WNOHANG)) ; /* keep reaping until no more zombies */
582 please_reap_children = 0;
584 #endif /* signal stuff */
586 timeout = prepare_for_poll();
588 /* poll until we have an event, or the second ends */
589 poll_result = tor_poll(poll_array, nfds, timeout);
591 /* let catch() handle things like ^c, and otherwise don't worry about it */
592 if(poll_result < 0) {
593 if(errno != EINTR) { /* let the program survive things like ^z */
594 log_fn(LOG_ERR,"poll failed: %s",strerror(errno));
595 return -1;
596 } else {
597 log_fn(LOG_DEBUG,"poll interrupted.");
601 /* do all the reads and errors first, so we can detect closed sockets */
602 for(i=0;i<nfds;i++)
603 conn_read(i); /* this also marks broken connections */
605 /* then do the writes */
606 for(i=0;i<nfds;i++)
607 conn_write(i);
609 /* any of the conns need to be closed now? */
610 for(i=0;i<nfds;i++)
611 conn_close_if_marked(i);
613 /* refilling buckets and sending cells happens at the beginning of the
614 * next iteration of the loop, inside prepare_for_poll()
619 static void catch(int the_signal) {
621 #ifndef MS_WINDOWS /* do signal stuff only on unix */
622 switch(the_signal) {
623 // case SIGABRT:
624 case SIGTERM:
625 case SIGINT:
626 log(LOG_ERR,"Catching signal %d, exiting cleanly.", the_signal);
627 /* we don't care if there was an error when we unlink, nothing
628 we could do about it anyways */
629 if(options.PidFile)
630 unlink(options.PidFile);
631 exit(0);
632 case SIGHUP:
633 please_reset = 1;
634 break;
635 case SIGUSR1:
636 please_dumpstats = 1;
637 break;
638 case SIGCHLD:
639 please_reap_children = 1;
640 break;
641 default:
642 log(LOG_WARN,"Caught signal %d that we can't handle??", the_signal);
644 #endif /* signal stuff */
647 static void dumpstats(int severity) {
648 int i;
649 connection_t *conn;
650 time_t now = time(NULL);
652 log(severity, "Dumping stats:");
654 for(i=0;i<nfds;i++) {
655 conn = connection_array[i];
656 log(severity, "Conn %d (socket %d) type %d (%s), state %d (%s), created %ld secs ago",
657 i, conn->s, conn->type, conn_type_to_string[conn->type],
658 conn->state, conn_state_to_string[conn->type][conn->state], now - conn->timestamp_created);
659 if(!connection_is_listener(conn)) {
660 log(severity,"Conn %d is to '%s:%d'.",i,conn->address, conn->port);
661 log(severity,"Conn %d: %d bytes waiting on inbuf (last read %ld secs ago)",i,
662 (int)buf_datalen(conn->inbuf),
663 now - conn->timestamp_lastread);
664 log(severity,"Conn %d: %d bytes waiting on outbuf (last written %ld secs ago)",i,
665 (int)buf_datalen(conn->outbuf), now - conn->timestamp_lastwritten);
667 circuit_dump_by_conn(conn, severity); /* dump info about all the circuits using this conn */
669 log(severity,
670 "Cells processed: %10lu padding\n"
671 " %10lu create\n"
672 " %10lu created\n"
673 " %10lu relay\n"
674 " (%10lu relayed)\n"
675 " (%10lu delivered)\n"
676 " %10lu destroy",
677 stats_n_padding_cells_processed,
678 stats_n_create_cells_processed,
679 stats_n_created_cells_processed,
680 stats_n_relay_cells_processed,
681 stats_n_relay_cells_relayed,
682 stats_n_relay_cells_delivered,
683 stats_n_destroy_cells_processed);
684 if (stats_n_data_cells_packaged)
685 log(severity,"Average packaged cell fullness: %2.3f%%",
686 100*(((double)stats_n_data_bytes_packaged) /
687 (stats_n_data_cells_packaged*RELAY_PAYLOAD_SIZE)) );
688 if (stats_n_data_cells_received)
689 log(severity,"Average delivered cell fullness: %2.3f%%",
690 100*(((double)stats_n_data_bytes_received) /
691 (stats_n_data_cells_received*RELAY_PAYLOAD_SIZE)) );
693 if (stats_n_seconds_reading)
694 log(severity,"Average bandwidth used: %d bytes/sec",
695 (int) (stats_n_bytes_read/stats_n_seconds_reading));
698 int network_init(void)
700 #ifdef MS_WINDOWS
701 /* This silly exercise is necessary before windows will allow gethostbyname to work.
703 WSADATA WSAData;
704 int r;
705 r = WSAStartup(0x101,&WSAData);
706 if (r) {
707 log_fn(LOG_WARN,"Error initializing windows network layer: code was %d",r);
708 return -1;
710 /* XXXX We should call WSACleanup on exit, I think. */
711 #endif
712 return 0;
715 void exit_function(void)
717 #ifdef MS_WINDOWS
718 WSACleanup();
719 #endif
722 int tor_main(int argc, char *argv[]) {
724 /* give it somewhere to log to initially */
725 add_stream_log(LOG_INFO, "<stdout>", stdout);
726 log_fn(LOG_WARN,"Tor v%s. This is experimental software. Do not use it if you need anonymity.",VERSION);
728 if (network_init()<0) {
729 log_fn(LOG_ERR,"Error initializing network; exiting.");
730 return 1;
732 atexit(exit_function);
734 if (init_from_config(argc,argv) < 0)
735 return -1;
737 #ifndef MS_WINDOWS
738 if(geteuid()==0)
739 log_fn(LOG_WARN,"You are running Tor as root. You don't need to, and you probably shouldn't.");
740 #endif
742 if(options.ORPort) { /* only spawn dns handlers if we're a router */
743 dns_init(); /* initialize the dns resolve tree, and spawn workers */
745 if(options.SocksPort) {
746 client_dns_init(); /* init the client dns cache */
749 #ifndef MS_WINDOWS /* do signal stuff only on unix */
750 signal (SIGINT, catch); /* catch kills so we can exit cleanly */
751 signal (SIGTERM, catch);
752 signal (SIGUSR1, catch); /* to dump stats */
753 signal (SIGHUP, catch); /* to reload directory */
754 signal (SIGCHLD, catch); /* for exiting dns/cpu workers */
755 #endif /* signal stuff */
757 crypto_global_init();
758 crypto_seed_rng();
759 do_main_loop();
760 crypto_global_cleanup();
761 return -1;
765 Local Variables:
766 mode:c
767 indent-tabs-mode:nil
768 c-basic-offset:2
769 End: