main.c 24 KB

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