main.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732
  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_upload_desc_to_dirservers();
  212. }
  213. if(!options.DirPort) {
  214. /* NOTE directory servers do not currently fetch directories.
  215. * Hope this doesn't bite us later. */
  216. directory_initiate_command(router_pick_directory_server(),
  217. DIR_CONN_STATE_CONNECTING_FETCH);
  218. }
  219. time_to_fetch_directory = now.tv_sec + options.DirFetchPostPeriod;
  220. }
  221. if(options.APPort && time_to_new_circuit < now.tv_sec) {
  222. circuit_expire_unused_circuits();
  223. circuit_launch_new(-1); /* tell it to forget about previous failures */
  224. circ = circuit_get_newest_open();
  225. if(!circ || circ->dirty) {
  226. log_fn(LOG_INFO,"Youngest circuit %s; launching replacement.", circ ? "dirty" : "missing");
  227. circuit_launch_new(0); /* make an onion and lay the circuit */
  228. }
  229. time_to_new_circuit = now.tv_sec + options.NewCircuitPeriod;
  230. }
  231. if(global_read_bucket < 9*options.TotalBandwidth) {
  232. global_read_bucket += options.TotalBandwidth;
  233. log_fn(LOG_DEBUG,"global_read_bucket now %d.", global_read_bucket);
  234. }
  235. /* do housekeeping for each connection */
  236. for(i=0;i<nfds;i++) {
  237. conn = connection_array[i];
  238. if(connection_receiver_bucket_should_increase(conn)) {
  239. conn->receiver_bucket += conn->bandwidth;
  240. // log_fn(LOG_DEBUG,"Receiver bucket %d now %d.", i, conn->receiver_bucket);
  241. }
  242. if(conn->wants_to_read == 1 /* it's marked to turn reading back on now */
  243. && global_read_bucket > 0 /* and we're allowed to read */
  244. && (!connection_speaks_cells(conn) || conn->receiver_bucket > 0)) {
  245. /* and either a non-cell conn or a cell conn with non-empty bucket */
  246. conn->wants_to_read = 0;
  247. connection_start_reading(conn);
  248. if(conn->wants_to_write == 1) {
  249. conn->wants_to_write = 0;
  250. connection_start_writing(conn);
  251. }
  252. }
  253. /* check connections to see whether we should send a keepalive, expire, or wait */
  254. if(!connection_speaks_cells(conn))
  255. continue; /* this conn type doesn't send cells */
  256. if(now.tv_sec >= conn->timestamp_lastwritten + options.KeepalivePeriod) {
  257. if((!options.OnionRouter && !circuit_get_by_conn(conn)) ||
  258. (!connection_state_is_open(conn))) {
  259. /* we're an onion proxy, with no circuits; or our handshake has expired. kill it. */
  260. log_fn(LOG_INFO,"Expiring connection to %d (%s:%d).",
  261. i,conn->address, conn->port);
  262. conn->marked_for_close = 1;
  263. } else {
  264. /* either a full router, or we've got a circuit. send a padding cell. */
  265. log_fn(LOG_DEBUG,"Sending keepalive to (%s:%d)",
  266. conn->address, conn->port);
  267. memset(&cell,0,sizeof(cell_t));
  268. cell.command = CELL_PADDING;
  269. if(connection_write_cell_to_buf(&cell, conn) < 0)
  270. conn->marked_for_close = 1;
  271. }
  272. }
  273. }
  274. /* blow away any connections that need to die. can't do this later
  275. * because we might open up a circuit and not realize we're about to cull
  276. * the connection it's running over.
  277. */
  278. for(i=0;i<nfds;i++)
  279. check_conn_marked(i);
  280. current_second = now.tv_sec; /* remember which second it is, for next time */
  281. }
  282. for(i=0;i<nfds;i++) {
  283. conn = connection_array[i];
  284. if(connection_speaks_cells(conn) &&
  285. connection_state_is_open(conn) &&
  286. tor_tls_get_pending_bytes(conn->tls)) {
  287. log_fn(LOG_DEBUG,"sock %d has pending bytes.",conn->s);
  288. return 0; /* has pending bytes to read; don't let poll wait. */
  289. }
  290. }
  291. return (1000 - (now.tv_usec / 1000)); /* how many milliseconds til the next second? */
  292. }
  293. static crypto_pk_env_t *init_key_from_file(const char *fname)
  294. {
  295. crypto_pk_env_t *prkey = NULL;
  296. int fd = -1;
  297. FILE *file = NULL;
  298. if (!(prkey = crypto_new_pk_env(CRYPTO_PK_RSA))) {
  299. log(LOG_ERR, "Error creating crypto environment.");
  300. goto error;
  301. }
  302. switch(file_status(fname)) {
  303. case FN_DIR:
  304. case FN_ERROR:
  305. log(LOG_ERR, "Can't read key from %s", fname);
  306. goto error;
  307. case FN_NOENT:
  308. log(LOG_INFO, "No key found in %s; generating fresh key.", fname);
  309. if (crypto_pk_generate_key(prkey)) {
  310. log(LOG_ERR, "Error generating key: %s", crypto_perror());
  311. goto error;
  312. }
  313. if (crypto_pk_check_key(prkey) <= 0) {
  314. log(LOG_ERR, "Generated key seems invalid");
  315. goto error;
  316. }
  317. log(LOG_INFO, "Generated key seems valid");
  318. if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
  319. log(LOG_ERR, "Couldn't write generated key to %s.", fname);
  320. goto error;
  321. }
  322. return prkey;
  323. case FN_FILE:
  324. if (crypto_pk_read_private_key_from_filename(prkey, fname)) {
  325. log(LOG_ERR, "Error loading private key.");
  326. goto error;
  327. }
  328. return prkey;
  329. default:
  330. assert(0);
  331. }
  332. error:
  333. if (prkey)
  334. crypto_free_pk_env(prkey);
  335. if (fd >= 0 && !file)
  336. close(fd);
  337. if (file)
  338. fclose(file);
  339. return NULL;
  340. }
  341. static int init_keys(void)
  342. {
  343. char keydir[512];
  344. char fingerprint[FINGERPRINT_LEN+MAX_NICKNAME_LEN+3];
  345. char *cp;
  346. const char *tmp, *mydesc;
  347. crypto_pk_env_t *prkey;
  348. /* OP's don't need keys. Just initialize the TLS context.*/
  349. if (!options.OnionRouter) {
  350. assert(!options.DirPort);
  351. if (tor_tls_context_new(NULL, 0, NULL)<0) {
  352. log_fn(LOG_ERR, "Error creating TLS context for OP.");
  353. return -1;
  354. }
  355. return 0;
  356. }
  357. assert(options.DataDirectory);
  358. if (strlen(options.DataDirectory) > (512-128)) {
  359. log_fn(LOG_ERR, "DataDirectory is too long.");
  360. return -1;
  361. }
  362. if (check_private_dir(options.DataDirectory, 1)) {
  363. return -1;
  364. }
  365. sprintf(keydir,"%s/keys",options.DataDirectory);
  366. if (check_private_dir(keydir, 1)) {
  367. return -1;
  368. }
  369. cp = keydir + strlen(keydir); /* End of string. */
  370. /* 1. Read identity key. Make it if none is found. */
  371. strcpy(cp, "/identity.key");
  372. log_fn(LOG_INFO,"Reading/making identity key %s...",keydir);
  373. prkey = init_key_from_file(keydir);
  374. if (!prkey) return -1;
  375. set_identity_key(prkey);
  376. /* 2. Read onion key. Make it if none is found. */
  377. strcpy(cp, "/onion.key");
  378. log_fn(LOG_INFO,"Reading/making onion key %s...",keydir);
  379. prkey = init_key_from_file(keydir);
  380. if (!prkey) return -1;
  381. set_onion_key(prkey);
  382. /* 3. Initialize link key and TLS context. */
  383. strcpy(cp, "/link.key");
  384. log_fn(LOG_INFO,"Reading/making link key %s...",keydir);
  385. prkey = init_key_from_file(keydir);
  386. if (!prkey) return -1;
  387. set_link_key(prkey);
  388. if (tor_tls_context_new(prkey, 1, options.Nickname) < 0) {
  389. log_fn(LOG_ERR, "Error initializing TLS context");
  390. return -1;
  391. }
  392. /* 4. Dump router descriptor to 'router.desc' */
  393. /* Must be called after keys are initialized. */
  394. if (!(router_get_my_descriptor())) {
  395. log_fn(LOG_ERR, "Error initializing descriptor.");
  396. return -1;
  397. }
  398. /* We need to add our own fingerprint so it gets recognized. */
  399. if (dirserv_add_own_fingerprint(options.Nickname, get_identity_key())) {
  400. log_fn(LOG_ERR, "Error adding own fingerprint to approved set");
  401. return -1;
  402. }
  403. tmp = mydesc = router_get_my_descriptor();
  404. if (dirserv_add_descriptor(&tmp)) {
  405. log(LOG_ERR, "Unable to add own descriptor to directory.");
  406. return -1;
  407. }
  408. sprintf(keydir,"%s/router.desc", options.DataDirectory);
  409. log_fn(LOG_INFO,"Dumping descriptor to %s...",keydir);
  410. if (write_str_to_file(keydir, mydesc)) {
  411. return -1;
  412. }
  413. /* 5. Dump fingerprint to 'fingerprint' */
  414. sprintf(keydir,"%s/fingerprint", options.DataDirectory);
  415. log_fn(LOG_INFO,"Dumping fingerprint to %s...",keydir);
  416. assert(strlen(options.Nickname) <= MAX_NICKNAME_LEN);
  417. strcpy(fingerprint, options.Nickname);
  418. strcat(fingerprint, " ");
  419. if (crypto_pk_get_fingerprint(get_identity_key(),
  420. fingerprint+strlen(fingerprint))<0) {
  421. log_fn(LOG_ERR, "Error computing fingerprint");
  422. return -1;
  423. }
  424. strcat(fingerprint, "\n");
  425. if (write_str_to_file(keydir, fingerprint))
  426. return -1;
  427. if(!options.DirPort)
  428. return 0;
  429. /* 6. [dirserver only] load approved-routers file */
  430. sprintf(keydir,"%s/approved-routers", options.DataDirectory);
  431. log_fn(LOG_INFO,"Loading approved fingerprints from %s...",keydir);
  432. if(dirserv_parse_fingerprint_file(keydir) < 0) {
  433. log_fn(LOG_ERR, "Error loading fingerprints");
  434. return -1;
  435. }
  436. /* 7. [dirserver only] load old directory, if it's there */
  437. sprintf(keydir,"%s/cached-directory", options.DataDirectory);
  438. log_fn(LOG_INFO,"Loading cached directory from %s...",keydir);
  439. cp = read_file_to_str(keydir);
  440. if(!cp) {
  441. log_fn(LOG_INFO,"Cached directory %s not present. Ok.",keydir);
  442. } else {
  443. if(dirserv_init_from_directory_string(cp) < 0) {
  444. log_fn(LOG_ERR, "Cached directory %s is corrupt", keydir);
  445. free(cp);
  446. return -1;
  447. }
  448. free(cp);
  449. }
  450. /* success */
  451. return 0;
  452. }
  453. static int do_main_loop(void) {
  454. int i;
  455. int timeout;
  456. int poll_result;
  457. /* load the routers file */
  458. if(router_get_list_from_file(options.RouterFile) < 0) {
  459. log_fn(LOG_ERR,"Error loading router list.");
  460. return -1;
  461. }
  462. /* load the private keys, if we're supposed to have them, and set up the
  463. * TLS context. */
  464. if (init_keys() < 0) {
  465. log_fn(LOG_ERR,"Error initializing keys; exiting");
  466. return -1;
  467. }
  468. if(options.OnionRouter) {
  469. cpu_init(); /* launch cpuworkers. Need to do this *after* we've read the onion key. */
  470. router_upload_desc_to_dirservers(); /* upload our descriptor to all dirservers */
  471. }
  472. /* start up the necessary connections based on which ports are
  473. * non-zero. This is where we try to connect to all the other ORs,
  474. * and start the listeners.
  475. */
  476. retry_all_connections((uint16_t) options.ORPort,
  477. (uint16_t) options.APPort,
  478. (uint16_t) options.DirPort);
  479. for(;;) {
  480. #ifndef MS_WIN32 /* do signal stuff only on unix */
  481. if(please_dumpstats) {
  482. dumpstats();
  483. please_dumpstats = 0;
  484. }
  485. if(please_reset) {
  486. /* fetch a new directory */
  487. if(options.DirPort) {
  488. if(router_get_list_from_file(options.RouterFile) < 0) {
  489. log(LOG_WARNING,"Error reloading router list. Continuing with old list.");
  490. }
  491. } else {
  492. directory_initiate_command(router_pick_directory_server(), DIR_CONN_STATE_CONNECTING_FETCH);
  493. }
  494. /* close and reopen the log files */
  495. reset_logs();
  496. please_reset = 0;
  497. }
  498. if(please_reap_children) {
  499. while(waitpid(-1,NULL,WNOHANG)) ; /* keep reaping until no more zombies */
  500. please_reap_children = 0;
  501. }
  502. #endif /* signal stuff */
  503. timeout = prepare_for_poll();
  504. /* poll until we have an event, or the second ends */
  505. poll_result = poll(poll_array, nfds, timeout);
  506. #if 0 /* let catch() handle things like ^c, and otherwise don't worry about it */
  507. if(poll_result < 0) {
  508. log(LOG_ERR,"do_main_loop(): poll failed.");
  509. if(errno != EINTR) /* let the program survive things like ^z */
  510. return -1;
  511. }
  512. #endif
  513. /* do all the reads and errors first, so we can detect closed sockets */
  514. for(i=0;i<nfds;i++)
  515. conn_read(i); /* this also blows away broken connections */
  516. /* then do the writes */
  517. for(i=0;i<nfds;i++)
  518. conn_write(i);
  519. /* any of the conns need to be closed now? */
  520. for(i=0;i<nfds;i++)
  521. check_conn_marked(i);
  522. /* refilling buckets and sending cells happens at the beginning of the
  523. * next iteration of the loop, inside prepare_for_poll()
  524. */
  525. }
  526. }
  527. static void catch(int the_signal) {
  528. #ifndef MS_WIN32 /* do signal stuff only on unix */
  529. switch(the_signal) {
  530. // case SIGABRT:
  531. case SIGTERM:
  532. case SIGINT:
  533. log(LOG_ERR,"Catching signal %d, exiting cleanly.", the_signal);
  534. exit(0);
  535. case SIGHUP:
  536. please_reset = 1;
  537. break;
  538. case SIGUSR1:
  539. please_dumpstats = 1;
  540. break;
  541. case SIGCHLD:
  542. please_reap_children = 1;
  543. break;
  544. default:
  545. log(LOG_WARNING,"Caught signal %d that we can't handle??", the_signal);
  546. }
  547. #endif /* signal stuff */
  548. }
  549. static void dumpstats(void) { /* dump stats to stdout */
  550. int i;
  551. connection_t *conn;
  552. struct timeval now;
  553. printf("Dumping stats:\n");
  554. my_gettimeofday(&now);
  555. for(i=0;i<nfds;i++) {
  556. conn = connection_array[i];
  557. printf("Conn %d (socket %d) type %d (%s), state %d (%s), created %ld secs ago\n",
  558. i, conn->s, conn->type, conn_type_to_string[conn->type],
  559. conn->state, conn_state_to_string[conn->type][conn->state], now.tv_sec - conn->timestamp_created);
  560. if(!connection_is_listener(conn)) {
  561. printf("Conn %d is to '%s:%d'.\n",i,conn->address, conn->port);
  562. printf("Conn %d: %d bytes waiting on inbuf (last read %ld secs ago)\n",i,
  563. (int)buf_datalen(conn->inbuf),
  564. now.tv_sec - conn->timestamp_lastread);
  565. printf("Conn %d: %d bytes waiting on outbuf (last written %ld secs ago)\n",i,(int)buf_datalen(conn->outbuf),
  566. now.tv_sec - conn->timestamp_lastwritten);
  567. }
  568. circuit_dump_by_conn(conn); /* dump info about all the circuits using this conn */
  569. printf("\n");
  570. }
  571. }
  572. void daemonize(void) {
  573. #ifndef MS_WINDOWS
  574. /* Fork; parent exits. */
  575. if (fork())
  576. exit(0);
  577. /* Create new session; make sure we never get a terminal */
  578. setsid();
  579. if (fork())
  580. exit(0);
  581. chdir("/");
  582. umask(000);
  583. fclose(stdin);
  584. fclose(stdout); /* XXX Nick: this closes our log, right? is it safe to leave this open? */
  585. fclose(stderr);
  586. #endif
  587. }
  588. int tor_main(int argc, char *argv[]) {
  589. if(getconfig(argc,argv,&options)) {
  590. log_fn(LOG_ERR,"Reading config file failed. exiting.");
  591. return -1;
  592. }
  593. log_set_severity(options.loglevel); /* assign logging severity level from options */
  594. global_read_bucket = options.TotalBandwidth; /* start it at 1 second of traffic */
  595. if(options.Daemon)
  596. daemonize();
  597. if(options.OnionRouter) { /* only spawn dns handlers if we're a router */
  598. dns_init(); /* initialize the dns resolve tree, and spawn workers */
  599. }
  600. #ifndef MS_WINDOWS /* do signal stuff only on unix */
  601. signal (SIGINT, catch); /* catch kills so we can exit cleanly */
  602. signal (SIGTERM, catch);
  603. signal (SIGUSR1, catch); /* to dump stats to stdout */
  604. signal (SIGHUP, catch); /* to reload directory */
  605. signal (SIGCHLD, catch); /* for exiting dns/cpu workers */
  606. #endif /* signal stuff */
  607. crypto_global_init();
  608. crypto_seed_rng();
  609. do_main_loop();
  610. crypto_global_cleanup();
  611. return -1;
  612. }
  613. /*
  614. Local Variables:
  615. mode:c
  616. indent-tabs-mode:nil
  617. c-basic-offset:2
  618. End:
  619. */