main.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833
  1. /* Copyright 2001,2002,2003 Roger Dingledine, Matej Pfajfar. */
  2. /* See LICENSE for licensing information */
  3. /* $Id$ */
  4. #include "or.h"
  5. /********* START PROTOTYPES **********/
  6. static void dumpstats(int severity); /* log stats */
  7. /********* START VARIABLES **********/
  8. extern char *conn_type_to_string[];
  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. /* private keys */
  25. static crypto_pk_env_t *onionkey=NULL;
  26. static crypto_pk_env_t *linkkey=NULL;
  27. static crypto_pk_env_t *identitykey=NULL;
  28. /********* END VARIABLES ************/
  29. void set_onion_key(crypto_pk_env_t *k) {
  30. onionkey = k;
  31. }
  32. crypto_pk_env_t *get_onion_key(void) {
  33. assert(onionkey);
  34. return onionkey;
  35. }
  36. void set_link_key(crypto_pk_env_t *k)
  37. {
  38. linkkey = k;
  39. }
  40. crypto_pk_env_t *get_link_key(void)
  41. {
  42. assert(linkkey);
  43. return linkkey;
  44. }
  45. void set_identity_key(crypto_pk_env_t *k) {
  46. identitykey = k;
  47. }
  48. crypto_pk_env_t *get_identity_key(void) {
  49. assert(identitykey);
  50. return identitykey;
  51. }
  52. /****************************************************************************
  53. *
  54. * This section contains accessors and other methods on the connection_array
  55. * and poll_array variables (which are global within this file and unavailable
  56. * outside it).
  57. *
  58. ****************************************************************************/
  59. int connection_add(connection_t *conn) {
  60. if(nfds >= options.MaxConn-1) {
  61. log(LOG_WARN,"connection_add(): failing because nfds is too high.");
  62. return -1;
  63. }
  64. conn->poll_index = nfds;
  65. connection_set_poll_socket(conn);
  66. connection_array[nfds] = conn;
  67. /* zero these out here, because otherwise we'll inherit values from the previously freed one */
  68. poll_array[nfds].events = 0;
  69. poll_array[nfds].revents = 0;
  70. nfds++;
  71. log(LOG_INFO,"connection_add(): new conn type %d, socket %d, nfds %d.",conn->type, conn->s, nfds);
  72. return 0;
  73. }
  74. void connection_set_poll_socket(connection_t *conn) {
  75. poll_array[conn->poll_index].fd = conn->s;
  76. }
  77. /* Remove the connection from the global list, and remove the
  78. * corresponding poll entry. Calling this function will shift the last
  79. * connection (if any) into the position occupied by conn.
  80. */
  81. int connection_remove(connection_t *conn) {
  82. int current_index;
  83. assert(conn);
  84. assert(nfds>0);
  85. log(LOG_INFO,"connection_remove(): removing socket %d, nfds now %d",conn->s, nfds-1);
  86. /* if it's an edge conn, remove it from the list
  87. * of conn's on this circuit. If it's not on an edge,
  88. * flush and send destroys for all circuits on this conn
  89. */
  90. circuit_about_to_close_connection(conn);
  91. current_index = conn->poll_index;
  92. if(current_index == nfds-1) { /* this is the end */
  93. nfds--;
  94. return 0;
  95. }
  96. /* we replace this one with the one at the end, then free it */
  97. nfds--;
  98. poll_array[current_index].fd = poll_array[nfds].fd;
  99. poll_array[current_index].events = poll_array[nfds].events;
  100. poll_array[current_index].revents = poll_array[nfds].revents;
  101. connection_array[current_index] = connection_array[nfds];
  102. connection_array[current_index]->poll_index = current_index;
  103. return 0;
  104. }
  105. void get_connection_array(connection_t ***array, int *n) {
  106. *array = connection_array;
  107. *n = nfds;
  108. }
  109. void connection_watch_events(connection_t *conn, short events) {
  110. assert(conn && conn->poll_index < nfds);
  111. poll_array[conn->poll_index].events = events;
  112. }
  113. int connection_is_reading(connection_t *conn) {
  114. return poll_array[conn->poll_index].events & POLLIN;
  115. }
  116. void connection_stop_reading(connection_t *conn) {
  117. assert(conn && conn->poll_index < nfds);
  118. log(LOG_DEBUG,"connection_stop_reading() called.");
  119. if(poll_array[conn->poll_index].events & POLLIN)
  120. poll_array[conn->poll_index].events -= POLLIN;
  121. }
  122. void connection_start_reading(connection_t *conn) {
  123. assert(conn && conn->poll_index < nfds);
  124. poll_array[conn->poll_index].events |= POLLIN;
  125. }
  126. void connection_stop_writing(connection_t *conn) {
  127. assert(conn && conn->poll_index < nfds);
  128. if(poll_array[conn->poll_index].events & POLLOUT)
  129. poll_array[conn->poll_index].events -= POLLOUT;
  130. }
  131. void connection_start_writing(connection_t *conn) {
  132. assert(conn && conn->poll_index < nfds);
  133. poll_array[conn->poll_index].events |= POLLOUT;
  134. }
  135. static void conn_read(int i) {
  136. connection_t *conn = connection_array[i];
  137. /* see http://www.greenend.org.uk/rjk/2001/06/poll.html for
  138. * discussion of POLLIN vs POLLHUP */
  139. if(!(poll_array[i].revents & (POLLIN|POLLHUP|POLLERR)))
  140. if(!connection_is_reading(conn) ||
  141. !connection_has_pending_tls_data(conn))
  142. return; /* this conn should not read */
  143. log_fn(LOG_DEBUG,"socket %d wants to read.",conn->s);
  144. assert_connection_ok(conn, time(NULL));
  145. if(
  146. /* XXX does POLLHUP also mean it's definitely broken? */
  147. #ifdef MS_WINDOWS
  148. (poll_array[i].revents & POLLERR) ||
  149. #endif
  150. connection_handle_read(conn) < 0)
  151. {
  152. /* this connection is broken. remove it */
  153. log_fn(LOG_INFO,"%s connection broken, removing.", conn_type_to_string[conn->type]);
  154. connection_remove(conn);
  155. connection_free(conn);
  156. if(i<nfds) { /* we just replaced the one at i with a new one. process it too. */
  157. conn_read(i);
  158. }
  159. } else assert_connection_ok(conn, time(NULL));
  160. }
  161. static void conn_write(int i) {
  162. connection_t *conn;
  163. if(!(poll_array[i].revents & POLLOUT))
  164. return; /* this conn doesn't want to write */
  165. conn = connection_array[i];
  166. log_fn(LOG_DEBUG,"socket %d wants to write.",conn->s);
  167. assert_connection_ok(conn, time(NULL));
  168. if(connection_handle_write(conn) < 0) { /* this connection is broken. remove it. */
  169. log_fn(LOG_INFO,"%s connection broken, removing.", conn_type_to_string[conn->type]);
  170. connection_remove(conn);
  171. connection_free(conn);
  172. if(i<nfds) { /* we just replaced the one at i with a new one. process it too. */
  173. conn_write(i);
  174. }
  175. } else assert_connection_ok(conn, time(NULL));
  176. }
  177. static void conn_close_if_marked(int i) {
  178. connection_t *conn;
  179. conn = connection_array[i];
  180. assert_connection_ok(conn, time(NULL));
  181. if(conn->marked_for_close) {
  182. log_fn(LOG_INFO,"Cleaning up connection (fd %d).",conn->s);
  183. if(conn->s >= 0) { /* might be an incomplete edge connection */
  184. /* FIXME there's got to be a better way to check for this -- and make other checks? */
  185. if(connection_speaks_cells(conn)) {
  186. if(conn->state == OR_CONN_STATE_OPEN)
  187. flush_buf_tls(conn->tls, conn->outbuf, &conn->outbuf_flushlen);
  188. } else {
  189. flush_buf(conn->s, conn->outbuf, &conn->outbuf_flushlen);
  190. }
  191. if(connection_wants_to_flush(conn)) /* not done flushing */
  192. log_fn(LOG_WARN,"Conn (socket %d) still wants to flush. Losing %d bytes!",conn->s, (int)buf_datalen(conn->inbuf));
  193. }
  194. connection_remove(conn);
  195. connection_free(conn);
  196. if(i<nfds) { /* we just replaced the one at i with a new one.
  197. process it too. */
  198. conn_close_if_marked(i);
  199. }
  200. }
  201. }
  202. /* Perform regular maintenance tasks for a single connection. This
  203. * function gets run once per second per connection by run_housekeeping.
  204. */
  205. static void run_connection_housekeeping(int i, time_t now) {
  206. cell_t cell;
  207. connection_t *conn = connection_array[i];
  208. if(connection_receiver_bucket_should_increase(conn)) {
  209. conn->receiver_bucket += conn->bandwidth;
  210. // log_fn(LOG_DEBUG,"Receiver bucket %d now %d.", i, conn->receiver_bucket);
  211. }
  212. if(conn->wants_to_read == 1 /* it's marked to turn reading back on now */
  213. && global_read_bucket > 0 /* and we're allowed to read */
  214. && (!connection_speaks_cells(conn) || conn->receiver_bucket > 0)) {
  215. /* and either a non-cell conn or a cell conn with non-empty bucket */
  216. conn->wants_to_read = 0;
  217. connection_start_reading(conn);
  218. if(conn->wants_to_write == 1) {
  219. conn->wants_to_write = 0;
  220. connection_start_writing(conn);
  221. }
  222. }
  223. /* check connections to see whether we should send a keepalive, expire, or wait */
  224. if(!connection_speaks_cells(conn))
  225. return;
  226. if(now >= conn->timestamp_lastwritten + options.KeepalivePeriod) {
  227. if((!options.OnionRouter && !circuit_get_by_conn(conn)) ||
  228. (!connection_state_is_open(conn))) {
  229. /* we're an onion proxy, with no circuits; or our handshake has expired. kill it. */
  230. log_fn(LOG_INFO,"Expiring connection to %d (%s:%d).",
  231. i,conn->address, conn->port);
  232. conn->marked_for_close = 1;
  233. } else {
  234. /* either a full router, or we've got a circuit. send a padding cell. */
  235. log_fn(LOG_DEBUG,"Sending keepalive to (%s:%d)",
  236. conn->address, conn->port);
  237. memset(&cell,0,sizeof(cell_t));
  238. cell.command = CELL_PADDING;
  239. connection_or_write_cell_to_buf(&cell, conn);
  240. }
  241. }
  242. }
  243. /* Perform regular maintenance tasks. This function gets run once per
  244. * second by prepare_for_poll.
  245. */
  246. static void run_scheduled_events(time_t now) {
  247. static long time_to_fetch_directory = 0;
  248. static long time_to_new_circuit = 0;
  249. circuit_t *circ;
  250. int i;
  251. /* 1. Every DirFetchPostPeriod seconds, we get a new directory and upload
  252. * our descriptor (if any). */
  253. if(time_to_fetch_directory < now) {
  254. /* it's time to fetch a new directory and/or post our descriptor */
  255. if(options.OnionRouter) {
  256. router_rebuild_descriptor();
  257. router_upload_desc_to_dirservers();
  258. }
  259. if(!options.DirPort) {
  260. /* NOTE directory servers do not currently fetch directories.
  261. * Hope this doesn't bite us later. */
  262. directory_initiate_command(router_pick_directory_server(),
  263. DIR_CONN_STATE_CONNECTING_FETCH);
  264. }
  265. time_to_fetch_directory = now + options.DirFetchPostPeriod;
  266. }
  267. /* 2. Every NewCircuitPeriod seconds, we expire old circuits and make a
  268. * new one as needed.
  269. */
  270. if(options.APPort && time_to_new_circuit < now) {
  271. circuit_expire_unused_circuits();
  272. circuit_launch_new(-1); /* tell it to forget about previous failures */
  273. circ = circuit_get_newest_open();
  274. if(!circ || circ->dirty) {
  275. log_fn(LOG_INFO,"Youngest circuit %s; launching replacement.", circ ? "dirty" : "missing");
  276. circuit_launch_new(0); /* make an onion and lay the circuit */
  277. }
  278. time_to_new_circuit = now + options.NewCircuitPeriod;
  279. }
  280. /* 3. Every second, we check how much bandwidth we've consumed and
  281. * increment global_read_bucket.
  282. */
  283. stats_n_bytes_read += stats_prev_global_read_bucket-global_read_bucket;
  284. if(global_read_bucket < 9*options.TotalBandwidth) {
  285. global_read_bucket += options.TotalBandwidth;
  286. log_fn(LOG_DEBUG,"global_read_bucket now %d.", global_read_bucket);
  287. }
  288. stats_prev_global_read_bucket = global_read_bucket;
  289. /* 4. We do houskeeping for each connection... */
  290. for(i=0;i<nfds;i++) {
  291. run_connection_housekeeping(i, now);
  292. }
  293. /* 5. and blow away any connections that need to die. can't do this later
  294. * because we might open up a circuit and not realize we're about to cull
  295. * the connection it's running over.
  296. */
  297. for(i=0;i<nfds;i++)
  298. conn_close_if_marked(i);
  299. }
  300. static int prepare_for_poll(void) {
  301. static long current_second = 0; /* from previous calls to gettimeofday */
  302. connection_t *conn;
  303. struct timeval now;
  304. int i;
  305. tor_gettimeofday(&now);
  306. if(now.tv_sec > current_second) { /* the second has rolled over. check more stuff. */
  307. ++stats_n_seconds_reading;
  308. run_scheduled_events(now.tv_sec);
  309. current_second = now.tv_sec; /* remember which second it is, for next time */
  310. }
  311. for(i=0;i<nfds;i++) {
  312. conn = connection_array[i];
  313. if(connection_has_pending_tls_data(conn)) {
  314. log_fn(LOG_DEBUG,"sock %d has pending bytes.",conn->s);
  315. return 0; /* has pending bytes to read; don't let poll wait. */
  316. }
  317. }
  318. return (1000 - (now.tv_usec / 1000)); /* how many milliseconds til the next second? */
  319. }
  320. static crypto_pk_env_t *init_key_from_file(const char *fname)
  321. {
  322. crypto_pk_env_t *prkey = NULL;
  323. int fd = -1;
  324. FILE *file = NULL;
  325. if (!(prkey = crypto_new_pk_env(CRYPTO_PK_RSA))) {
  326. log(LOG_ERR, "Error creating crypto environment.");
  327. goto error;
  328. }
  329. switch(file_status(fname)) {
  330. case FN_DIR:
  331. case FN_ERROR:
  332. log(LOG_ERR, "Can't read key from %s", fname);
  333. goto error;
  334. case FN_NOENT:
  335. log(LOG_INFO, "No key found in %s; generating fresh key.", fname);
  336. if (crypto_pk_generate_key(prkey)) {
  337. log(LOG_ERR, "Error generating key: %s", crypto_perror());
  338. goto error;
  339. }
  340. if (crypto_pk_check_key(prkey) <= 0) {
  341. log(LOG_ERR, "Generated key seems invalid");
  342. goto error;
  343. }
  344. log(LOG_INFO, "Generated key seems valid");
  345. if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
  346. log(LOG_ERR, "Couldn't write generated key to %s.", fname);
  347. goto error;
  348. }
  349. return prkey;
  350. case FN_FILE:
  351. if (crypto_pk_read_private_key_from_filename(prkey, fname)) {
  352. log(LOG_ERR, "Error loading private key.");
  353. goto error;
  354. }
  355. return prkey;
  356. default:
  357. assert(0);
  358. }
  359. error:
  360. if (prkey)
  361. crypto_free_pk_env(prkey);
  362. if (fd >= 0 && !file)
  363. close(fd);
  364. if (file)
  365. fclose(file);
  366. return NULL;
  367. }
  368. static int init_keys(void)
  369. {
  370. char keydir[512];
  371. char fingerprint[FINGERPRINT_LEN+MAX_NICKNAME_LEN+3];
  372. char *cp;
  373. const char *tmp, *mydesc;
  374. crypto_pk_env_t *prkey;
  375. /* OP's don't need keys. Just initialize the TLS context.*/
  376. if (!options.OnionRouter) {
  377. assert(!options.DirPort);
  378. if (tor_tls_context_new(NULL, 0, NULL)<0) {
  379. log_fn(LOG_ERR, "Error creating TLS context for OP.");
  380. return -1;
  381. }
  382. return 0;
  383. }
  384. assert(options.DataDirectory);
  385. if (strlen(options.DataDirectory) > (512-128)) {
  386. log_fn(LOG_ERR, "DataDirectory is too long.");
  387. return -1;
  388. }
  389. if (check_private_dir(options.DataDirectory, 1)) {
  390. return -1;
  391. }
  392. sprintf(keydir,"%s/keys",options.DataDirectory);
  393. if (check_private_dir(keydir, 1)) {
  394. return -1;
  395. }
  396. cp = keydir + strlen(keydir); /* End of string. */
  397. /* 1. Read identity key. Make it if none is found. */
  398. strcpy(cp, "/identity.key");
  399. log_fn(LOG_INFO,"Reading/making identity key %s...",keydir);
  400. prkey = init_key_from_file(keydir);
  401. if (!prkey) return -1;
  402. set_identity_key(prkey);
  403. /* 2. Read onion key. Make it if none is found. */
  404. strcpy(cp, "/onion.key");
  405. log_fn(LOG_INFO,"Reading/making onion key %s...",keydir);
  406. prkey = init_key_from_file(keydir);
  407. if (!prkey) return -1;
  408. set_onion_key(prkey);
  409. /* 3. Initialize link key and TLS context. */
  410. strcpy(cp, "/link.key");
  411. log_fn(LOG_INFO,"Reading/making link key %s...",keydir);
  412. prkey = init_key_from_file(keydir);
  413. if (!prkey) return -1;
  414. set_link_key(prkey);
  415. if (tor_tls_context_new(prkey, 1, options.Nickname) < 0) {
  416. log_fn(LOG_ERR, "Error initializing TLS context");
  417. return -1;
  418. }
  419. /* 4. Dump router descriptor to 'router.desc' */
  420. /* Must be called after keys are initialized. */
  421. if (!(router_get_my_descriptor())) {
  422. log_fn(LOG_ERR, "Error initializing descriptor.");
  423. return -1;
  424. }
  425. /* We need to add our own fingerprint so it gets recognized. */
  426. if (dirserv_add_own_fingerprint(options.Nickname, get_identity_key())) {
  427. log_fn(LOG_ERR, "Error adding own fingerprint to approved set");
  428. return -1;
  429. }
  430. tmp = mydesc = router_get_my_descriptor();
  431. if (dirserv_add_descriptor(&tmp)) {
  432. log(LOG_ERR, "Unable to add own descriptor to directory.");
  433. return -1;
  434. }
  435. sprintf(keydir,"%s/router.desc", options.DataDirectory);
  436. log_fn(LOG_INFO,"Dumping descriptor to %s...",keydir);
  437. if (write_str_to_file(keydir, mydesc)) {
  438. return -1;
  439. }
  440. /* 5. Dump fingerprint to 'fingerprint' */
  441. sprintf(keydir,"%s/fingerprint", options.DataDirectory);
  442. log_fn(LOG_INFO,"Dumping fingerprint to %s...",keydir);
  443. assert(strlen(options.Nickname) <= MAX_NICKNAME_LEN);
  444. strcpy(fingerprint, options.Nickname);
  445. strcat(fingerprint, " ");
  446. if (crypto_pk_get_fingerprint(get_identity_key(),
  447. fingerprint+strlen(fingerprint))<0) {
  448. log_fn(LOG_ERR, "Error computing fingerprint");
  449. return -1;
  450. }
  451. strcat(fingerprint, "\n");
  452. if (write_str_to_file(keydir, fingerprint))
  453. return -1;
  454. if(!options.DirPort)
  455. return 0;
  456. /* 6. [dirserver only] load approved-routers file */
  457. sprintf(keydir,"%s/approved-routers", options.DataDirectory);
  458. log_fn(LOG_INFO,"Loading approved fingerprints from %s...",keydir);
  459. if(dirserv_parse_fingerprint_file(keydir) < 0) {
  460. log_fn(LOG_ERR, "Error loading fingerprints");
  461. return -1;
  462. }
  463. /* 7. [dirserver only] load old directory, if it's there */
  464. sprintf(keydir,"%s/cached-directory", options.DataDirectory);
  465. log_fn(LOG_INFO,"Loading cached directory from %s...",keydir);
  466. cp = read_file_to_str(keydir);
  467. if(!cp) {
  468. log_fn(LOG_INFO,"Cached directory %s not present. Ok.",keydir);
  469. } else {
  470. if(dirserv_init_from_directory_string(cp) < 0) {
  471. log_fn(LOG_ERR, "Cached directory %s is corrupt", keydir);
  472. free(cp);
  473. return -1;
  474. }
  475. free(cp);
  476. }
  477. /* success */
  478. return 0;
  479. }
  480. static int do_main_loop(void) {
  481. int i;
  482. int timeout;
  483. int poll_result;
  484. /* load the routers file */
  485. if(router_get_list_from_file(options.RouterFile) < 0) {
  486. log_fn(LOG_ERR,"Error loading router list.");
  487. return -1;
  488. }
  489. /* load the private keys, if we're supposed to have them, and set up the
  490. * TLS context. */
  491. if (init_keys() < 0) {
  492. log_fn(LOG_ERR,"Error initializing keys; exiting");
  493. return -1;
  494. }
  495. if(options.OnionRouter) {
  496. cpu_init(); /* launch cpuworkers. Need to do this *after* we've read the onion key. */
  497. router_upload_desc_to_dirservers(); /* upload our descriptor to all dirservers */
  498. }
  499. /* start up the necessary connections based on which ports are
  500. * non-zero. This is where we try to connect to all the other ORs,
  501. * and start the listeners.
  502. */
  503. retry_all_connections((uint16_t) options.ORPort,
  504. (uint16_t) options.APPort,
  505. (uint16_t) options.DirPort);
  506. for(;;) {
  507. #ifndef MS_WIN32 /* do signal stuff only on unix */
  508. if(please_dumpstats) {
  509. /* prefer to log it at INFO, but make sure we always see it */
  510. dumpstats(options.loglevel>LOG_INFO ? options.loglevel : LOG_INFO);
  511. please_dumpstats = 0;
  512. }
  513. if(please_reset) {
  514. /* fetch a new directory */
  515. if(options.DirPort) {
  516. /* reload the fingerprint file */
  517. char keydir[512];
  518. sprintf(keydir,"%s/approved-routers", options.DataDirectory);
  519. log_fn(LOG_INFO,"Reloading approved fingerprints from %s...",keydir);
  520. if(dirserv_parse_fingerprint_file(keydir) < 0) {
  521. log_fn(LOG_WARN, "Error reloading fingerprints. Continuing with old list.");
  522. }
  523. if(router_get_list_from_file(options.RouterFile) < 0) {
  524. log(LOG_WARN,"Error reloading router list. Continuing with old list.");
  525. }
  526. } else {
  527. directory_initiate_command(router_pick_directory_server(), DIR_CONN_STATE_CONNECTING_FETCH);
  528. }
  529. /* close and reopen the log files */
  530. reset_logs();
  531. please_reset = 0;
  532. }
  533. if(please_reap_children) {
  534. while(waitpid(-1,NULL,WNOHANG)) ; /* keep reaping until no more zombies */
  535. please_reap_children = 0;
  536. }
  537. #endif /* signal stuff */
  538. timeout = prepare_for_poll();
  539. /* poll until we have an event, or the second ends */
  540. poll_result = poll(poll_array, nfds, timeout);
  541. /* let catch() handle things like ^c, and otherwise don't worry about it */
  542. if(poll_result < 0) {
  543. if(errno != EINTR) { /* let the program survive things like ^z */
  544. log_fn(LOG_ERR,"poll failed.");
  545. return -1;
  546. } else {
  547. log_fn(LOG_DEBUG,"poll interrupted.");
  548. }
  549. }
  550. /* do all the reads and errors first, so we can detect closed sockets */
  551. for(i=0;i<nfds;i++)
  552. conn_read(i); /* this also blows away broken connections */
  553. /* then do the writes */
  554. for(i=0;i<nfds;i++)
  555. conn_write(i);
  556. /* any of the conns need to be closed now? */
  557. for(i=0;i<nfds;i++)
  558. conn_close_if_marked(i);
  559. /* refilling buckets and sending cells happens at the beginning of the
  560. * next iteration of the loop, inside prepare_for_poll()
  561. */
  562. }
  563. }
  564. static void catch(int the_signal) {
  565. #ifndef MS_WIN32 /* do signal stuff only on unix */
  566. switch(the_signal) {
  567. // case SIGABRT:
  568. case SIGTERM:
  569. case SIGINT:
  570. log(LOG_ERR,"Catching signal %d, exiting cleanly.", the_signal);
  571. /* we don't care if there was an error when we unlink,
  572. nothing we could do about it anyways */
  573. unlink(options.PidFile);
  574. exit(0);
  575. case SIGHUP:
  576. please_reset = 1;
  577. break;
  578. case SIGUSR1:
  579. please_dumpstats = 1;
  580. break;
  581. case SIGCHLD:
  582. please_reap_children = 1;
  583. break;
  584. default:
  585. log(LOG_WARN,"Caught signal %d that we can't handle??", the_signal);
  586. }
  587. #endif /* signal stuff */
  588. }
  589. static void dumpstats(int severity) {
  590. int i;
  591. connection_t *conn;
  592. time_t now = time(NULL);
  593. log(severity, "Dumping stats:");
  594. for(i=0;i<nfds;i++) {
  595. conn = connection_array[i];
  596. log(severity, "Conn %d (socket %d) type %d (%s), state %d (%s), created %ld secs ago",
  597. i, conn->s, conn->type, conn_type_to_string[conn->type],
  598. conn->state, conn_state_to_string[conn->type][conn->state], now - conn->timestamp_created);
  599. if(!connection_is_listener(conn)) {
  600. log(severity,"Conn %d is to '%s:%d'.",i,conn->address, conn->port);
  601. log(severity,"Conn %d: %d bytes waiting on inbuf (last read %ld secs ago)",i,
  602. (int)buf_datalen(conn->inbuf),
  603. now - conn->timestamp_lastread);
  604. log(severity,"Conn %d: %d bytes waiting on outbuf (last written %ld secs ago)",i,
  605. (int)buf_datalen(conn->outbuf), now - conn->timestamp_lastwritten);
  606. }
  607. circuit_dump_by_conn(conn, severity); /* dump info about all the circuits using this conn */
  608. }
  609. log(severity,
  610. "Cells processed: %10lu padding\n"
  611. " %10lu create\n"
  612. " %10lu created\n"
  613. " %10lu relay\n"
  614. " (%10lu relayed)\n"
  615. " (%10lu delivered)\n"
  616. " %10lud destroy",
  617. stats_n_padding_cells_processed,
  618. stats_n_create_cells_processed,
  619. stats_n_created_cells_processed,
  620. stats_n_relay_cells_processed,
  621. stats_n_relay_cells_relayed,
  622. stats_n_relay_cells_delivered,
  623. stats_n_destroy_cells_processed);
  624. if (stats_n_data_cells_packaged)
  625. log(severity,"Average outgoing cell fullness: %2.3f%%",
  626. 100*(((double)stats_n_data_bytes_packaged) /
  627. (stats_n_data_cells_packaged*(CELL_PAYLOAD_SIZE-RELAY_HEADER_SIZE))) );
  628. if (stats_n_data_cells_received)
  629. log(severity,"Average incoming cell fullness: %2.3f%%",
  630. 100*(((double)stats_n_data_bytes_received) /
  631. (stats_n_data_cells_received*(CELL_PAYLOAD_SIZE-RELAY_HEADER_SIZE))) );
  632. if (stats_n_seconds_reading)
  633. log(severity,"Average bandwidth used: %d bytes/sec",
  634. (int) (stats_n_bytes_read/stats_n_seconds_reading));
  635. }
  636. void daemonize(void) {
  637. #ifndef MS_WINDOWS
  638. /* Fork; parent exits. */
  639. if (fork())
  640. exit(0);
  641. /* Create new session; make sure we never get a terminal */
  642. setsid();
  643. if (fork())
  644. exit(0);
  645. chdir("/");
  646. umask(000);
  647. fclose(stdin);
  648. fclose(stdout);
  649. fclose(stderr);
  650. #endif
  651. }
  652. void write_pidfile(char *filename) {
  653. FILE *pidfile;
  654. if ((pidfile = fopen(filename, "w")) == NULL) {
  655. log_fn(LOG_WARN, "unable to open %s for writing: %s", filename,
  656. strerror(errno));
  657. } else {
  658. fprintf(pidfile, "%d", getpid());
  659. fclose(pidfile);
  660. }
  661. }
  662. int tor_main(int argc, char *argv[]) {
  663. /* give it somewhere to log to initially */
  664. add_stream_log(LOG_INFO, "<stdout>", stdout);
  665. if(getconfig(argc,argv,&options)) {
  666. log_fn(LOG_ERR,"Reading config file failed. exiting.");
  667. return -1;
  668. }
  669. log_set_severity(options.loglevel); /* assign logging severity level from options */
  670. close_logs(); /* close stdout, then open with correct loglevel if necessary */
  671. if(!options.LogFile && !options.RunAsDaemon)
  672. add_stream_log(options.loglevel, "<stdout>", stdout);
  673. if(options.DebugLogFile)
  674. add_file_log(LOG_DEBUG, options.DebugLogFile);
  675. if(options.LogFile)
  676. add_file_log(options.loglevel, options.LogFile);
  677. global_read_bucket = options.TotalBandwidth; /* start it at 1 second of traffic */
  678. stats_prev_global_read_bucket = global_read_bucket;
  679. /* write our pid to the pid file */
  680. write_pidfile(options.PidFile);
  681. if(options.RunAsDaemon)
  682. daemonize();
  683. if(options.OnionRouter) { /* only spawn dns handlers if we're a router */
  684. dns_init(); /* initialize the dns resolve tree, and spawn workers */
  685. }
  686. #ifndef MS_WINDOWS /* do signal stuff only on unix */
  687. signal (SIGINT, catch); /* catch kills so we can exit cleanly */
  688. signal (SIGTERM, catch);
  689. signal (SIGUSR1, catch); /* to dump stats */
  690. signal (SIGHUP, catch); /* to reload directory */
  691. signal (SIGCHLD, catch); /* for exiting dns/cpu workers */
  692. #endif /* signal stuff */
  693. crypto_global_init();
  694. crypto_seed_rng();
  695. do_main_loop();
  696. crypto_global_cleanup();
  697. return -1;
  698. }
  699. /*
  700. Local Variables:
  701. mode:c
  702. indent-tabs-mode:nil
  703. c-basic-offset:2
  704. End:
  705. */