main.c 26 KB

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