main.c 26 KB

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