main.c 22 KB

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