main.c 24 KB

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