main.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671
  1. /* Copyright 2001,2002,2003 Roger Dingledine, Matej Pfajfar. */
  2. /* See LICENSE for licensing information */
  3. /* $Id$ */
  4. #include "or.h"
  5. /********* START PROTOTYPES **********/
  6. static void dumpstats(int severity); /* log stats */
  7. static int init_from_config(int argc, char **argv);
  8. /********* START VARIABLES **********/
  9. extern char *conn_type_to_string[];
  10. extern char *conn_state_to_string[][_CONN_TYPE_MAX+1];
  11. or_options_t options; /* command-line and config-file options */
  12. int global_read_bucket; /* max number of bytes I can read this second */
  13. static int stats_prev_global_read_bucket;
  14. static uint64_t stats_n_bytes_read = 0;
  15. static long stats_n_seconds_reading = 0;
  16. static connection_t *connection_array[MAXCONNECTIONS] =
  17. { NULL };
  18. static struct pollfd poll_array[MAXCONNECTIONS];
  19. static int nfds=0; /* number of connections currently active */
  20. #ifndef MS_WINDOWS /* do signal stuff only on unix */
  21. static int please_dumpstats=0; /* whether we should dump stats during the loop */
  22. static int please_reset=0; /* whether we just got a sighup */
  23. static int please_reap_children=0; /* whether we should waitpid for exited children */
  24. #endif /* signal stuff */
  25. /********* END VARIABLES ************/
  26. /****************************************************************************
  27. *
  28. * This section contains accessors and other methods on the connection_array
  29. * and poll_array variables (which are global within this file and unavailable
  30. * outside it).
  31. *
  32. ****************************************************************************/
  33. int connection_add(connection_t *conn) {
  34. if(nfds >= options.MaxConn-1) {
  35. log(LOG_WARN,"connection_add(): failing because nfds is too high.");
  36. return -1;
  37. }
  38. conn->poll_index = nfds;
  39. connection_set_poll_socket(conn);
  40. connection_array[nfds] = conn;
  41. /* zero these out here, because otherwise we'll inherit values from the previously freed one */
  42. poll_array[nfds].events = 0;
  43. poll_array[nfds].revents = 0;
  44. nfds++;
  45. log(LOG_INFO,"connection_add(): new conn type %d, socket %d, nfds %d.",conn->type, conn->s, nfds);
  46. return 0;
  47. }
  48. void connection_set_poll_socket(connection_t *conn) {
  49. poll_array[conn->poll_index].fd = conn->s;
  50. }
  51. /* Remove the connection from the global list, and remove the
  52. * corresponding poll entry. Calling this function will shift the last
  53. * connection (if any) into the position occupied by conn.
  54. */
  55. int connection_remove(connection_t *conn) {
  56. int current_index;
  57. assert(conn);
  58. assert(nfds>0);
  59. log(LOG_INFO,"connection_remove(): removing socket %d, nfds now %d",conn->s, nfds-1);
  60. /* if it's an edge conn, remove it from the list
  61. * of conn's on this circuit. If it's not on an edge,
  62. * flush and send destroys for all circuits on this conn
  63. */
  64. circuit_about_to_close_connection(conn);
  65. current_index = conn->poll_index;
  66. if(current_index == nfds-1) { /* this is the end */
  67. nfds--;
  68. return 0;
  69. }
  70. /* we replace this one with the one at the end, then free it */
  71. nfds--;
  72. poll_array[current_index].fd = poll_array[nfds].fd;
  73. poll_array[current_index].events = poll_array[nfds].events;
  74. poll_array[current_index].revents = poll_array[nfds].revents;
  75. connection_array[current_index] = connection_array[nfds];
  76. connection_array[current_index]->poll_index = current_index;
  77. return 0;
  78. }
  79. void get_connection_array(connection_t ***array, int *n) {
  80. *array = connection_array;
  81. *n = nfds;
  82. }
  83. void connection_watch_events(connection_t *conn, short events) {
  84. assert(conn && conn->poll_index < nfds);
  85. poll_array[conn->poll_index].events = events;
  86. }
  87. int connection_is_reading(connection_t *conn) {
  88. return poll_array[conn->poll_index].events & POLLIN;
  89. }
  90. void connection_stop_reading(connection_t *conn) {
  91. assert(conn && conn->poll_index < nfds);
  92. log(LOG_DEBUG,"connection_stop_reading() called.");
  93. if(poll_array[conn->poll_index].events & POLLIN)
  94. poll_array[conn->poll_index].events -= POLLIN;
  95. }
  96. void connection_start_reading(connection_t *conn) {
  97. assert(conn && conn->poll_index < nfds);
  98. poll_array[conn->poll_index].events |= POLLIN;
  99. }
  100. void connection_stop_writing(connection_t *conn) {
  101. assert(conn && conn->poll_index < nfds);
  102. if(poll_array[conn->poll_index].events & POLLOUT)
  103. poll_array[conn->poll_index].events -= POLLOUT;
  104. }
  105. void connection_start_writing(connection_t *conn) {
  106. assert(conn && conn->poll_index < nfds);
  107. poll_array[conn->poll_index].events |= POLLOUT;
  108. }
  109. static void conn_read(int i) {
  110. connection_t *conn = connection_array[i];
  111. /* see http://www.greenend.org.uk/rjk/2001/06/poll.html for
  112. * discussion of POLLIN vs POLLHUP */
  113. if(!(poll_array[i].revents & (POLLIN|POLLHUP|POLLERR)))
  114. if(!connection_is_reading(conn) ||
  115. !connection_has_pending_tls_data(conn))
  116. return; /* this conn should not read */
  117. log_fn(LOG_DEBUG,"socket %d wants to read.",conn->s);
  118. assert_connection_ok(conn, time(NULL));
  119. if(
  120. /* XXX does POLLHUP also mean it's definitely broken? */
  121. #ifdef MS_WINDOWS
  122. (poll_array[i].revents & POLLERR) ||
  123. #endif
  124. connection_handle_read(conn) < 0)
  125. {
  126. /* this connection is broken. remove it */
  127. log_fn(LOG_INFO,"%s connection broken, removing.",
  128. conn_type_to_string[conn->type]);
  129. connection_remove(conn);
  130. connection_free(conn);
  131. if(i<nfds) {
  132. /* we just replaced the one at i with a new one. process it too. */
  133. conn_read(i);
  134. }
  135. } else assert_connection_ok(conn, time(NULL));
  136. }
  137. static void conn_write(int i) {
  138. connection_t *conn;
  139. if(!(poll_array[i].revents & POLLOUT))
  140. return; /* this conn doesn't want to write */
  141. conn = connection_array[i];
  142. log_fn(LOG_DEBUG,"socket %d wants to write.",conn->s);
  143. assert_connection_ok(conn, time(NULL));
  144. if(connection_handle_write(conn) < 0) { /* this connection is broken. remove it. */
  145. log_fn(LOG_INFO,"%s connection broken, removing.", conn_type_to_string[conn->type]);
  146. connection_remove(conn);
  147. connection_free(conn);
  148. if(i<nfds) { /* we just replaced the one at i with a new one. process it too. */
  149. conn_write(i);
  150. }
  151. } else assert_connection_ok(conn, time(NULL));
  152. }
  153. static void conn_close_if_marked(int i) {
  154. connection_t *conn;
  155. conn = connection_array[i];
  156. assert_connection_ok(conn, time(NULL));
  157. if(conn->marked_for_close) {
  158. log_fn(LOG_INFO,"Cleaning up connection (fd %d).",conn->s);
  159. if(conn->s >= 0) { /* might be an incomplete edge connection */
  160. /* FIXME there's got to be a better way to check for this -- and make other checks? */
  161. if(connection_speaks_cells(conn)) {
  162. if(conn->state == OR_CONN_STATE_OPEN)
  163. flush_buf_tls(conn->tls, conn->outbuf, &conn->outbuf_flushlen);
  164. } else {
  165. flush_buf(conn->s, conn->outbuf, &conn->outbuf_flushlen);
  166. }
  167. if(connection_wants_to_flush(conn) && buf_datalen(conn->outbuf)) {
  168. log_fn(LOG_WARN,"Conn (socket %d) still wants to flush. Losing %d bytes!",
  169. conn->s, (int)buf_datalen(conn->outbuf));
  170. }
  171. }
  172. connection_remove(conn);
  173. connection_free(conn);
  174. if(i<nfds) { /* we just replaced the one at i with a new one.
  175. process it too. */
  176. conn_close_if_marked(i);
  177. }
  178. }
  179. }
  180. /* Perform regular maintenance tasks for a single connection. This
  181. * function gets run once per second per connection by run_housekeeping.
  182. */
  183. static void run_connection_housekeeping(int i, time_t now) {
  184. cell_t cell;
  185. connection_t *conn = connection_array[i];
  186. if(connection_receiver_bucket_should_increase(conn)) {
  187. conn->receiver_bucket += conn->bandwidth;
  188. // log_fn(LOG_DEBUG,"Receiver bucket %d now %d.", i, conn->receiver_bucket);
  189. }
  190. if(conn->wants_to_read == 1 /* it's marked to turn reading back on now */
  191. && global_read_bucket > 0 /* and we're allowed to read */
  192. && (!connection_speaks_cells(conn) || conn->receiver_bucket > 0)) {
  193. /* and either a non-cell conn or a cell conn with non-empty bucket */
  194. conn->wants_to_read = 0;
  195. connection_start_reading(conn);
  196. if(conn->wants_to_write == 1) {
  197. conn->wants_to_write = 0;
  198. connection_start_writing(conn);
  199. }
  200. }
  201. /* check connections to see whether we should send a keepalive, expire, or wait */
  202. if(!connection_speaks_cells(conn))
  203. return;
  204. if(now >= conn->timestamp_lastwritten + options.KeepalivePeriod) {
  205. if((!options.ORPort && !circuit_get_by_conn(conn)) ||
  206. (!connection_state_is_open(conn))) {
  207. /* we're an onion proxy, with no circuits; or our handshake has expired. kill it. */
  208. log_fn(LOG_INFO,"Expiring connection to %d (%s:%d).",
  209. i,conn->address, conn->port);
  210. conn->marked_for_close = 1;
  211. } else {
  212. /* either a full router, or we've got a circuit. send a padding cell. */
  213. log_fn(LOG_DEBUG,"Sending keepalive to (%s:%d)",
  214. conn->address, conn->port);
  215. memset(&cell,0,sizeof(cell_t));
  216. cell.command = CELL_PADDING;
  217. connection_or_write_cell_to_buf(&cell, conn);
  218. }
  219. }
  220. }
  221. /* Perform regular maintenance tasks. This function gets run once per
  222. * second by prepare_for_poll.
  223. */
  224. static void run_scheduled_events(time_t now) {
  225. static long time_to_fetch_directory = 0;
  226. static long time_to_new_circuit = 0;
  227. circuit_t *circ;
  228. int i;
  229. /* 1. Every DirFetchPostPeriod seconds, we get a new directory and upload
  230. * our descriptor (if any). */
  231. if(time_to_fetch_directory < now) {
  232. /* it's time to fetch a new directory and/or post our descriptor */
  233. if(options.ORPort) {
  234. router_rebuild_descriptor();
  235. router_upload_desc_to_dirservers();
  236. }
  237. if(!options.DirPort) {
  238. /* NOTE directory servers do not currently fetch directories.
  239. * Hope this doesn't bite us later. */
  240. directory_initiate_command(router_pick_directory_server(),
  241. DIR_CONN_STATE_CONNECTING_FETCH);
  242. }
  243. time_to_fetch_directory = now + options.DirFetchPostPeriod;
  244. }
  245. /* 2. Every second, we examine pending circuits and prune the
  246. * ones which have been pending for more than 3 seconds.
  247. * We do this before step 3, so it can try building more if
  248. * it's not comfortable with the number of available circuits.
  249. */
  250. circuit_expire_building();
  251. /* 3. Every second, we try a new circuit if there are no valid
  252. * circuits. Every NewCircuitPeriod seconds, we expire circuits
  253. * that became dirty more than NewCircuitPeriod seconds ago,
  254. * and we make a new circ if there are no clean circuits.
  255. */
  256. if(options.SocksPort) {
  257. /* launch a new circ for any pending streams that need one */
  258. connection_ap_attach_pending();
  259. circ = circuit_get_newest(NULL, 1);
  260. if(time_to_new_circuit < now) {
  261. client_dns_clean();
  262. circuit_expire_unused_circuits();
  263. circuit_reset_failure_count();
  264. if(circ && circ->timestamp_dirty) {
  265. log_fn(LOG_INFO,"Youngest circuit dirty; launching replacement.");
  266. circuit_launch_new(); /* make a new circuit */
  267. }
  268. time_to_new_circuit = now + options.NewCircuitPeriod;
  269. }
  270. #define CIRCUIT_MIN_BUILDING 2
  271. if(!circ && circuit_count_building() < CIRCUIT_MIN_BUILDING) {
  272. /* if there's no open circ, and less than 2 are on the way,
  273. * go ahead and try another.
  274. */
  275. circuit_launch_new();
  276. }
  277. }
  278. /* 4. Every second, we check how much bandwidth we've consumed and
  279. * increment global_read_bucket.
  280. */
  281. stats_n_bytes_read += stats_prev_global_read_bucket-global_read_bucket;
  282. if(global_read_bucket < options.BandwidthBurst) {
  283. global_read_bucket += options.BandwidthRate;
  284. log_fn(LOG_DEBUG,"global_read_bucket now %d.", global_read_bucket);
  285. }
  286. stats_prev_global_read_bucket = global_read_bucket;
  287. /* 5. We do housekeeping for each connection... */
  288. for(i=0;i<nfds;i++) {
  289. run_connection_housekeeping(i, now);
  290. }
  291. /* 6. and blow away any connections that need to die. can't do this later
  292. * because we might open up a circuit and not realize we're about to cull
  293. * the connection it's running over.
  294. * XXX we can remove this step once we audit circuit-building to make sure
  295. * it doesn't pick a marked-for-close conn. -RD
  296. */
  297. for(i=0;i<nfds;i++)
  298. conn_close_if_marked(i);
  299. }
  300. static int prepare_for_poll(void) {
  301. static long current_second = 0; /* from previous calls to gettimeofday */
  302. connection_t *conn;
  303. struct timeval now;
  304. int i;
  305. tor_gettimeofday(&now);
  306. if(now.tv_sec > current_second) { /* the second has rolled over. check more stuff. */
  307. ++stats_n_seconds_reading;
  308. run_scheduled_events(now.tv_sec);
  309. current_second = now.tv_sec; /* remember which second it is, for next time */
  310. }
  311. for(i=0;i<nfds;i++) {
  312. conn = connection_array[i];
  313. if(connection_has_pending_tls_data(conn)) {
  314. log_fn(LOG_DEBUG,"sock %d has pending bytes.",conn->s);
  315. return 0; /* has pending bytes to read; don't let poll wait. */
  316. }
  317. }
  318. return (1000 - (now.tv_usec / 1000)); /* how many milliseconds til the next second? */
  319. }
  320. static int init_from_config(int argc, char **argv) {
  321. if(getconfig(argc,argv,&options)) {
  322. log_fn(LOG_ERR,"Reading config failed. For usage, try -h.");
  323. return -1;
  324. }
  325. close_logs(); /* we'll close, then open with correct loglevel if necessary */
  326. if(!options.LogFile && !options.RunAsDaemon)
  327. add_stream_log(options.loglevel, "<stdout>", stdout);
  328. if(options.LogFile) {
  329. if (add_file_log(options.loglevel, options.LogFile) != 0) {
  330. /* opening the log file failed! Use stderr and log a warning */
  331. add_stream_log(options.loglevel, "<stderr>", stderr);
  332. log_fn(LOG_WARN, "Cannot write to LogFile '%s': %s.", options.LogFile, strerror(errno));
  333. }
  334. log_fn(LOG_WARN, "Successfully opened LogFile '%s', redirecting output.",
  335. options.LogFile);
  336. }
  337. if(options.DebugLogFile) {
  338. if (add_file_log(LOG_DEBUG, options.DebugLogFile) != 0)
  339. log_fn(LOG_WARN, "Cannot write to DebugLogFile '%s': %s.", options.DebugLogFile, strerror(errno));
  340. log_fn(LOG_DEBUG, "Successfully opened DebugLogFile '%s'.", options.DebugLogFile);
  341. }
  342. global_read_bucket = options.BandwidthBurst; /* start it at max traffic */
  343. stats_prev_global_read_bucket = global_read_bucket;
  344. if(options.User || options.Group) {
  345. if(switch_id(options.User, options.Group) != 0) {
  346. return -1;
  347. }
  348. }
  349. if(options.RunAsDaemon) {
  350. /* XXXX Can we delay this any more? */
  351. finish_daemon();
  352. }
  353. /* write our pid to the pid file, if we do not have write permissions we will log a warning */
  354. if(options.PidFile)
  355. write_pidfile(options.PidFile);
  356. return 0;
  357. }
  358. static int do_main_loop(void) {
  359. int i;
  360. int timeout;
  361. int poll_result;
  362. /* load the routers file */
  363. if(router_set_routerlist_from_file(options.RouterFile) < 0) {
  364. log_fn(LOG_ERR,"Error loading router list.");
  365. return -1;
  366. }
  367. /* load the private keys, if we're supposed to have them, and set up the
  368. * TLS context. */
  369. if (init_keys() < 0) {
  370. log_fn(LOG_ERR,"Error initializing keys; exiting");
  371. return -1;
  372. }
  373. if(options.ORPort) {
  374. cpu_init(); /* launch cpuworkers. Need to do this *after* we've read the onion key. */
  375. router_upload_desc_to_dirservers(); /* upload our descriptor to all dirservers */
  376. }
  377. /* start up the necessary connections based on which ports are
  378. * non-zero. This is where we try to connect to all the other ORs,
  379. * and start the listeners.
  380. */
  381. if(retry_all_connections() < 0) {
  382. log_fn(LOG_ERR,"Failed to bind one of the listener ports.");
  383. return -1;
  384. }
  385. for(;;) {
  386. #ifndef MS_WINDOWS /* do signal stuff only on unix */
  387. if(please_dumpstats) {
  388. /* prefer to log it at INFO, but make sure we always see it */
  389. dumpstats(options.loglevel>LOG_INFO ? options.loglevel : LOG_INFO);
  390. please_dumpstats = 0;
  391. }
  392. if(please_reset) {
  393. log_fn(LOG_WARN,"Received sighup. Reloading config.");
  394. /* first, reload config variables, in case they've changed */
  395. if (init_from_config(0, NULL) < 0) {
  396. /* no need to provide argc/v, they've been cached inside init_from_config */
  397. exit(1);
  398. }
  399. if(retry_all_connections() < 0) {
  400. log_fn(LOG_ERR,"Failed to bind one of the listener ports.");
  401. return -1;
  402. }
  403. if(options.DirPort) {
  404. /* reload the fingerprint file */
  405. char keydir[512];
  406. sprintf(keydir,"%s/approved-routers", options.DataDirectory);
  407. log_fn(LOG_INFO,"Reloading approved fingerprints from %s...",keydir);
  408. if(dirserv_parse_fingerprint_file(keydir) < 0) {
  409. log_fn(LOG_WARN, "Error reloading fingerprints. Continuing with old list.");
  410. }
  411. } else {
  412. /* fetch a new directory */
  413. directory_initiate_command(router_pick_directory_server(), DIR_CONN_STATE_CONNECTING_FETCH);
  414. }
  415. please_reset = 0;
  416. }
  417. if(please_reap_children) {
  418. while(waitpid(-1,NULL,WNOHANG)) ; /* keep reaping until no more zombies */
  419. please_reap_children = 0;
  420. }
  421. #endif /* signal stuff */
  422. timeout = prepare_for_poll();
  423. /* poll until we have an event, or the second ends */
  424. poll_result = poll(poll_array, nfds, timeout);
  425. /* let catch() handle things like ^c, and otherwise don't worry about it */
  426. if(poll_result < 0) {
  427. if(errno != EINTR) { /* let the program survive things like ^z */
  428. log_fn(LOG_ERR,"poll failed.");
  429. return -1;
  430. } else {
  431. log_fn(LOG_DEBUG,"poll interrupted.");
  432. }
  433. }
  434. /* do all the reads and errors first, so we can detect closed sockets */
  435. for(i=0;i<nfds;i++)
  436. conn_read(i); /* this also blows away broken connections */
  437. /* then do the writes */
  438. for(i=0;i<nfds;i++)
  439. conn_write(i);
  440. /* any of the conns need to be closed now? */
  441. for(i=0;i<nfds;i++)
  442. conn_close_if_marked(i);
  443. /* refilling buckets and sending cells happens at the beginning of the
  444. * next iteration of the loop, inside prepare_for_poll()
  445. */
  446. }
  447. }
  448. static void catch(int the_signal) {
  449. #ifndef MS_WINDOWS /* do signal stuff only on unix */
  450. switch(the_signal) {
  451. // case SIGABRT:
  452. case SIGTERM:
  453. case SIGINT:
  454. log(LOG_ERR,"Catching signal %d, exiting cleanly.", the_signal);
  455. /* we don't care if there was an error when we unlink, nothing
  456. we could do about it anyways */
  457. if(options.PidFile)
  458. unlink(options.PidFile);
  459. exit(0);
  460. case SIGHUP:
  461. please_reset = 1;
  462. break;
  463. case SIGUSR1:
  464. please_dumpstats = 1;
  465. break;
  466. case SIGCHLD:
  467. please_reap_children = 1;
  468. break;
  469. default:
  470. log(LOG_WARN,"Caught signal %d that we can't handle??", the_signal);
  471. }
  472. #endif /* signal stuff */
  473. }
  474. static void dumpstats(int severity) {
  475. int i;
  476. connection_t *conn;
  477. time_t now = time(NULL);
  478. log(severity, "Dumping stats:");
  479. for(i=0;i<nfds;i++) {
  480. conn = connection_array[i];
  481. log(severity, "Conn %d (socket %d) type %d (%s), state %d (%s), created %ld secs ago",
  482. i, conn->s, conn->type, conn_type_to_string[conn->type],
  483. conn->state, conn_state_to_string[conn->type][conn->state], now - conn->timestamp_created);
  484. if(!connection_is_listener(conn)) {
  485. log(severity,"Conn %d is to '%s:%d'.",i,conn->address, conn->port);
  486. log(severity,"Conn %d: %d bytes waiting on inbuf (last read %ld secs ago)",i,
  487. (int)buf_datalen(conn->inbuf),
  488. now - conn->timestamp_lastread);
  489. log(severity,"Conn %d: %d bytes waiting on outbuf (last written %ld secs ago)",i,
  490. (int)buf_datalen(conn->outbuf), now - conn->timestamp_lastwritten);
  491. }
  492. circuit_dump_by_conn(conn, severity); /* dump info about all the circuits using this conn */
  493. }
  494. log(severity,
  495. "Cells processed: %10lu padding\n"
  496. " %10lu create\n"
  497. " %10lu created\n"
  498. " %10lu relay\n"
  499. " (%10lu relayed)\n"
  500. " (%10lu delivered)\n"
  501. " %10lud destroy",
  502. stats_n_padding_cells_processed,
  503. stats_n_create_cells_processed,
  504. stats_n_created_cells_processed,
  505. stats_n_relay_cells_processed,
  506. stats_n_relay_cells_relayed,
  507. stats_n_relay_cells_delivered,
  508. stats_n_destroy_cells_processed);
  509. if (stats_n_data_cells_packaged)
  510. log(severity,"Average outgoing cell fullness: %2.3f%%",
  511. 100*(((double)stats_n_data_bytes_packaged) /
  512. (stats_n_data_cells_packaged*RELAY_PAYLOAD_SIZE)) );
  513. if (stats_n_data_cells_received)
  514. log(severity,"Average incoming cell fullness: %2.3f%%",
  515. 100*(((double)stats_n_data_bytes_received) /
  516. (stats_n_data_cells_received*RELAY_PAYLOAD_SIZE)) );
  517. if (stats_n_seconds_reading)
  518. log(severity,"Average bandwidth used: %d bytes/sec",
  519. (int) (stats_n_bytes_read/stats_n_seconds_reading));
  520. }
  521. int tor_main(int argc, char *argv[]) {
  522. /* give it somewhere to log to initially */
  523. add_stream_log(LOG_INFO, "<stdout>", stdout);
  524. log_fn(LOG_WARN,"Tor v%s. This is experimental software. Do not use it if you need anonymity.",VERSION);
  525. #ifndef MS_WINDOWS
  526. if(geteuid()==0)
  527. log_fn(LOG_WARN,"You are running Tor as root. You don't need to, and you probably shouldn't.");
  528. #endif
  529. if (init_from_config(argc,argv) < 0)
  530. return -1;
  531. if (options.RunAsDaemon) {
  532. start_daemon();
  533. }
  534. if(options.ORPort) { /* only spawn dns handlers if we're a router */
  535. dns_init(); /* initialize the dns resolve tree, and spawn workers */
  536. }
  537. if(options.SocksPort) {
  538. client_dns_init(); /* init the client dns cache */
  539. }
  540. #ifndef MS_WINDOWS /* do signal stuff only on unix */
  541. signal (SIGINT, catch); /* catch kills so we can exit cleanly */
  542. signal (SIGTERM, catch);
  543. signal (SIGUSR1, catch); /* to dump stats */
  544. signal (SIGHUP, catch); /* to reload directory */
  545. signal (SIGCHLD, catch); /* for exiting dns/cpu workers */
  546. #endif /* signal stuff */
  547. crypto_global_init();
  548. crypto_seed_rng();
  549. do_main_loop();
  550. crypto_global_cleanup();
  551. return -1;
  552. }
  553. /*
  554. Local Variables:
  555. mode:c
  556. indent-tabs-mode:nil
  557. c-basic-offset:2
  558. End:
  559. */