main.c 27 KB

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