main.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862
  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. /********* START VARIABLES **********/
  8. or_options_t options; /* command-line and config-file options */
  9. int global_read_bucket; /* max number of bytes I can read this second */
  10. static connection_t *connection_array[MAXCONNECTIONS] =
  11. { NULL };
  12. static struct pollfd poll_array[MAXCONNECTIONS];
  13. static int nfds=0; /* number of connections currently active */
  14. static int please_dumpstats=0; /* whether we should dump stats during the loop */
  15. static int please_fetch_directory=0; /* whether we should fetch a new directory */
  16. /* private key */
  17. static crypto_pk_env_t *privatekey=NULL;
  18. static crypto_pk_env_t *signing_privatekey=NULL;
  19. routerinfo_t *my_routerinfo=NULL;
  20. /********* END VARIABLES ************/
  21. void set_privatekey(crypto_pk_env_t *k) {
  22. privatekey = k;
  23. }
  24. crypto_pk_env_t *get_privatekey(void) {
  25. assert(privatekey);
  26. return privatekey;
  27. }
  28. void set_signing_privatekey(crypto_pk_env_t *k) {
  29. signing_privatekey = k;
  30. }
  31. crypto_pk_env_t *get_signing_privatekey(void) {
  32. assert(signing_privatekey);
  33. return signing_privatekey;
  34. }
  35. /****************************************************************************
  36. *
  37. * This section contains accessors and other methods on the connection_array
  38. * and poll_array variables (which are global within this file and unavailable
  39. * outside it).
  40. *
  41. ****************************************************************************/
  42. int connection_add(connection_t *conn) {
  43. if(nfds >= options.MaxConn-1) {
  44. log(LOG_INFO,"connection_add(): failing because nfds is too high.");
  45. return -1;
  46. }
  47. conn->poll_index = nfds;
  48. connection_set_poll_socket(conn);
  49. connection_array[nfds] = conn;
  50. /* zero these out here, because otherwise we'll inherit values from the previously freed one */
  51. poll_array[nfds].events = 0;
  52. poll_array[nfds].revents = 0;
  53. nfds++;
  54. log(LOG_INFO,"connection_add(): new conn type %d, socket %d, nfds %d.",conn->type, conn->s, nfds);
  55. return 0;
  56. }
  57. void connection_set_poll_socket(connection_t *conn) {
  58. poll_array[conn->poll_index].fd = conn->s;
  59. }
  60. int connection_remove(connection_t *conn) {
  61. int current_index;
  62. assert(conn);
  63. assert(nfds>0);
  64. log(LOG_INFO,"connection_remove(): removing socket %d, nfds now %d",conn->s, nfds-1);
  65. circuit_about_to_close_connection(conn); /* if it's an edge conn, remove it from the list
  66. * of conn's on this circuit. If it's not on an edge,
  67. * flush and send destroys for all circuits on this conn
  68. */
  69. current_index = conn->poll_index;
  70. if(current_index == nfds-1) { /* this is the end */
  71. nfds--;
  72. return 0;
  73. }
  74. /* we replace this one with the one at the end, then free it */
  75. nfds--;
  76. poll_array[current_index].fd = poll_array[nfds].fd;
  77. poll_array[current_index].events = poll_array[nfds].events;
  78. poll_array[current_index].revents = poll_array[nfds].revents;
  79. connection_array[current_index] = connection_array[nfds];
  80. connection_array[current_index]->poll_index = current_index;
  81. return 0;
  82. }
  83. connection_t *connection_twin_get_by_addr_port(uint32_t addr, uint16_t port) {
  84. /* Find a connection to the router described by addr and port,
  85. * or alternately any router which knows its key.
  86. * This connection *must* be in 'open' state.
  87. * If not, return NULL.
  88. */
  89. int i;
  90. connection_t *conn;
  91. routerinfo_t *router;
  92. /* first check if it's there exactly */
  93. conn = connection_exact_get_by_addr_port(addr,port);
  94. if(conn && connection_state_is_open(conn)) {
  95. log(LOG_INFO,"connection_twin_get_by_addr_port(): Found exact match.");
  96. return conn;
  97. }
  98. /* now check if any of the other open connections are a twin for this one */
  99. router = router_get_by_addr_port(addr,port);
  100. if(!router)
  101. return NULL;
  102. for(i=0;i<nfds;i++) {
  103. conn = connection_array[i];
  104. assert(conn);
  105. if(connection_state_is_open(conn) &&
  106. !conn->marked_for_close &&
  107. !crypto_pk_cmp_keys(conn->pkey, router->pkey)) {
  108. log(LOG_INFO,"connection_twin_get_by_addr_port(): Found twin (%s).",conn->address);
  109. return conn;
  110. }
  111. }
  112. /* guess not */
  113. return NULL;
  114. }
  115. connection_t *connection_exact_get_by_addr_port(uint32_t addr, uint16_t port) {
  116. int i;
  117. connection_t *conn;
  118. for(i=0;i<nfds;i++) {
  119. conn = connection_array[i];
  120. if(conn->addr == addr && conn->port == port && !conn->marked_for_close)
  121. return conn;
  122. }
  123. return NULL;
  124. }
  125. connection_t *connection_get_by_type(int type) {
  126. int i;
  127. connection_t *conn;
  128. for(i=0;i<nfds;i++) {
  129. conn = connection_array[i];
  130. if(conn->type == type && !conn->marked_for_close)
  131. return conn;
  132. }
  133. return NULL;
  134. }
  135. connection_t *connection_get_by_type_state(int type, int state) {
  136. int i;
  137. connection_t *conn;
  138. for(i=0;i<nfds;i++) {
  139. conn = connection_array[i];
  140. if(conn->type == type && conn->state == state && !conn->marked_for_close)
  141. return conn;
  142. }
  143. return NULL;
  144. }
  145. connection_t *connection_get_by_type_state_lastwritten(int type, int state) {
  146. int i;
  147. connection_t *conn, *best=NULL;
  148. for(i=0;i<nfds;i++) {
  149. conn = connection_array[i];
  150. if(conn->type == type && conn->state == state && !conn->marked_for_close)
  151. if(!best || conn->timestamp_lastwritten < best->timestamp_lastwritten)
  152. best = conn;
  153. }
  154. return best;
  155. }
  156. void connection_watch_events(connection_t *conn, short events) {
  157. assert(conn && conn->poll_index < nfds);
  158. poll_array[conn->poll_index].events = events;
  159. }
  160. void connection_stop_reading(connection_t *conn) {
  161. assert(conn && conn->poll_index < nfds);
  162. log(LOG_DEBUG,"connection_stop_reading() called.");
  163. if(poll_array[conn->poll_index].events & POLLIN)
  164. poll_array[conn->poll_index].events -= POLLIN;
  165. }
  166. void connection_start_reading(connection_t *conn) {
  167. assert(conn && conn->poll_index < nfds);
  168. poll_array[conn->poll_index].events |= POLLIN;
  169. }
  170. void connection_stop_writing(connection_t *conn) {
  171. assert(conn && conn->poll_index < nfds);
  172. if(poll_array[conn->poll_index].events & POLLOUT)
  173. poll_array[conn->poll_index].events -= POLLOUT;
  174. }
  175. void connection_start_writing(connection_t *conn) {
  176. assert(conn && conn->poll_index < nfds);
  177. poll_array[conn->poll_index].events |= POLLOUT;
  178. }
  179. static void conn_read(int i) {
  180. int retval;
  181. connection_t *conn;
  182. conn = connection_array[i];
  183. assert(conn);
  184. // log_fn(LOG_DEBUG,"socket %d has something to read.",conn->s);
  185. if (conn->type == CONN_TYPE_OR_LISTENER) {
  186. retval = connection_or_handle_listener_read(conn);
  187. } else if (conn->type == CONN_TYPE_AP_LISTENER) {
  188. retval = connection_ap_handle_listener_read(conn);
  189. } else if (conn->type == CONN_TYPE_DIR_LISTENER) {
  190. retval = connection_dir_handle_listener_read(conn);
  191. } else {
  192. retval = connection_read_to_buf(conn);
  193. if (retval < 0 && conn->type == CONN_TYPE_DIR && conn->state == DIR_CONN_STATE_CONNECTING) {
  194. /* it's a directory server and connecting failed: forget about this router */
  195. router_forget_router(conn->addr,conn->port); /* FIXME i don't think this function works. */
  196. }
  197. if (retval >= 0) { /* all still well */
  198. retval = connection_process_inbuf(conn);
  199. // log_fn(LOG_DEBUG,"connection_process_inbuf returned %d.",retval);
  200. if(retval >= 0 && !connection_state_is_open(conn) && conn->receiver_bucket == 0) {
  201. log(LOG_DEBUG,"conn_read(): receiver bucket reached 0 before handshake finished. Closing.");
  202. retval = -1;
  203. }
  204. }
  205. }
  206. if(retval < 0) { /* this connection is broken. remove it */
  207. log_fn(LOG_INFO,"Connection broken, removing.");
  208. connection_remove(conn);
  209. connection_free(conn);
  210. if(i<nfds) { /* we just replaced the one at i with a new one.
  211. process it too. */
  212. if(poll_array[i].revents & POLLIN ||
  213. poll_array[i].revents & POLLHUP ) /* something to read */
  214. conn_read(i);
  215. }
  216. }
  217. }
  218. static void conn_write(int i) {
  219. int retval;
  220. connection_t *conn;
  221. conn = connection_array[i];
  222. // log_fn(LOG_DEBUG,"socket %d wants to write.",conn->s);
  223. if(connection_is_listener(conn)) {
  224. log_fn(LOG_DEBUG,"Got a listener socket. Can't happen!");
  225. retval = -1;
  226. } else {
  227. /* else it's an OP, OR, or exit */
  228. retval = connection_flush_buf(conn); /* conns in CONNECTING state will fall through... */
  229. if(retval == 0) { /* it's done flushing */
  230. retval = connection_finished_flushing(conn); /* ...and get handled here. */
  231. }
  232. }
  233. if(retval < 0) { /* this connection is broken. remove it. */
  234. log_fn(LOG_DEBUG,"Connection broken, removing.");
  235. connection_remove(conn);
  236. connection_free(conn);
  237. if(i<nfds) { /* we just replaced the one at i with a new one.
  238. process it too. */
  239. if(poll_array[i].revents & POLLOUT) /* something to write */
  240. conn_write(i);
  241. }
  242. }
  243. }
  244. static void check_conn_marked(int i) {
  245. connection_t *conn;
  246. conn = connection_array[i];
  247. assert(conn);
  248. if(conn->marked_for_close) {
  249. log(LOG_DEBUG,"check_conn_marked(): Cleaning up connection.");
  250. if(conn->s >= 0) { /* might be an incomplete exit connection */
  251. /* FIXME there's got to be a better way to check for this -- and make other checks? */
  252. connection_flush_buf(conn); /* flush it first */
  253. }
  254. connection_remove(conn);
  255. connection_free(conn);
  256. if(i<nfds) { /* we just replaced the one at i with a new one.
  257. process it too. */
  258. check_conn_marked(i);
  259. }
  260. }
  261. }
  262. static int prepare_for_poll(int *timeout) {
  263. int i;
  264. // connection_t *conn = NULL;
  265. connection_t *tmpconn;
  266. struct timeval now; //soonest;
  267. static long current_second = 0; /* from previous calls to gettimeofday */
  268. static long time_to_fetch_directory = 0;
  269. static long time_to_new_circuit = 0;
  270. // int ms_until_conn;
  271. cell_t cell;
  272. circuit_t *circ;
  273. my_gettimeofday(&now);
  274. if(now.tv_sec > current_second) { /* the second has rolled over. check more stuff. */
  275. if(!options.DirPort) {
  276. if(time_to_fetch_directory < now.tv_sec) {
  277. /* it's time to fetch a new directory */
  278. /* NOTE directory servers do not currently fetch directories.
  279. * Hope this doesn't bite us later.
  280. */
  281. directory_initiate_fetch(router_pick_directory_server());
  282. time_to_fetch_directory = now.tv_sec + options.DirFetchPeriod;
  283. }
  284. }
  285. if(options.APPort && time_to_new_circuit < now.tv_sec) {
  286. circuit_expire_unused_circuits();
  287. circuit_launch_new(-1); /* tell it to forget about previous failures */
  288. circ = circuit_get_newest_ap();
  289. if(!circ || circ->dirty) {
  290. log(LOG_INFO,"prepare_for_poll(): Youngest circuit %s; launching replacement.", circ ? "dirty" : "missing");
  291. circuit_launch_new(0); /* make an onion and lay the circuit */
  292. }
  293. time_to_new_circuit = now.tv_sec + options.NewCircuitPeriod;
  294. }
  295. if(global_read_bucket < 9*options.TotalBandwidth) {
  296. global_read_bucket += options.TotalBandwidth;
  297. log_fn(LOG_DEBUG,"global_read_bucket now %d.", global_read_bucket);
  298. }
  299. /* do housekeeping for each connection */
  300. for(i=0;i<nfds;i++) {
  301. tmpconn = connection_array[i];
  302. if(connection_receiver_bucket_should_increase(tmpconn)) {
  303. tmpconn->receiver_bucket += tmpconn->bandwidth;
  304. // log_fn(LOG_DEBUG,"Receiver bucket %d now %d.", i, tmpconn->receiver_bucket);
  305. }
  306. if(tmpconn->wants_to_read == 1 /* it's marked to turn reading back on now */
  307. && global_read_bucket > 0 /* and we're allowed to read */
  308. && tmpconn->receiver_bucket != 0) { /* and either an edge conn or non-empty bucket */
  309. tmpconn->wants_to_read = 0;
  310. connection_start_reading(tmpconn);
  311. }
  312. /* check connections to see whether we should send a keepalive, expire, or wait */
  313. if(!connection_speaks_cells(tmpconn))
  314. continue; /* this conn type doesn't send cells */
  315. if(now.tv_sec >= tmpconn->timestamp_lastwritten + options.KeepalivePeriod) {
  316. if((!options.OnionRouter && !circuit_get_by_conn(tmpconn)) ||
  317. (!connection_state_is_open(tmpconn))) {
  318. /* we're an onion proxy, with no circuits; or our handshake has expired. kill it. */
  319. log(LOG_DEBUG,"prepare_for_poll(): Expiring connection to %d (%s:%d).",
  320. i,tmpconn->address, tmpconn->port);
  321. tmpconn->marked_for_close = 1;
  322. } else {
  323. /* either a full router, or we've got a circuit. send a padding cell. */
  324. // log(LOG_DEBUG,"prepare_for_poll(): Sending keepalive to (%s:%d)",
  325. // tmpconn->address, tmpconn->port);
  326. memset(&cell,0,sizeof(cell_t));
  327. cell.command = CELL_PADDING;
  328. if(connection_write_cell_to_buf(&cell, tmpconn) < 0)
  329. tmpconn->marked_for_close = 1;
  330. }
  331. }
  332. }
  333. /* blow away any connections that need to die. can't do this later
  334. * because we might open up a circuit and not realize it we're about to cull it.
  335. */
  336. for(i=0;i<nfds;i++)
  337. check_conn_marked(i);
  338. current_second = now.tv_sec; /* remember which second it is, for next time */
  339. }
  340. if(onion_pending_check()) {
  341. /* there's an onion pending. check for new things to do, but don't wait any time */
  342. *timeout = 0;
  343. } else {
  344. *timeout = 1000 - (now.tv_usec / 1000); /* how many milliseconds til the next second? */
  345. }
  346. return 0;
  347. }
  348. /* Link padding stuff left here for fun. Not used now. */
  349. #if 0
  350. if(options.LinkPadding) {
  351. /* now check which conn wants to speak soonest */
  352. for(i=0;i<nfds;i++) {
  353. tmpconn = connection_array[i];
  354. if(!connection_speaks_cells(tmpconn))
  355. continue; /* this conn type doesn't send cells */
  356. if(!connection_state_is_open(tmpconn))
  357. continue; /* only conns in state 'open' have a valid send_timeval */
  358. while(tv_cmp(&tmpconn->send_timeval,&now) <= 0) { /* send_timeval has already passed, let it send a cell */
  359. connection_send_cell(tmpconn);
  360. }
  361. if(!conn || tv_cmp(&tmpconn->send_timeval, &soonest) < 0) { /* this is the best choice so far */
  362. conn = tmpconn;
  363. soonest.tv_sec = conn->send_timeval.tv_sec;
  364. soonest.tv_usec = conn->send_timeval.tv_usec;
  365. }
  366. }
  367. if(conn) { /* we might want to set *timeout sooner */
  368. ms_until_conn = (soonest.tv_sec - now.tv_sec)*1000 +
  369. (soonest.tv_usec - now.tv_usec)/1000;
  370. // log(LOG_DEBUG,"prepare_for_poll(): conn %d times out in %d ms.",conn->s, ms_until_conn);
  371. if(ms_until_conn < *timeout) { /* use the new one */
  372. // log(LOG_DEBUG,"prepare_for_poll(): conn %d soonest, in %d ms.",conn->s,ms_until_conn);
  373. *timeout = ms_until_conn;
  374. }
  375. }
  376. }
  377. #endif
  378. static int do_main_loop(void) {
  379. int i;
  380. int timeout;
  381. int poll_result;
  382. crypto_pk_env_t *prkey;
  383. /* load the routers file */
  384. if(router_get_list_from_file(options.RouterFile) < 0) {
  385. log(LOG_ERR,"Error loading router list.");
  386. return -1;
  387. }
  388. /* load the private key, if we're supposed to have one */
  389. if(options.OnionRouter) {
  390. prkey = crypto_new_pk_env(CRYPTO_PK_RSA);
  391. if (!prkey) {
  392. log(LOG_ERR,"Error creating a crypto environment.");
  393. return -1;
  394. }
  395. if (crypto_pk_read_private_key_from_filename(prkey, options.PrivateKeyFile)) {
  396. log(LOG_ERR,"Error loading private key.");
  397. return -1;
  398. }
  399. set_privatekey(prkey);
  400. }
  401. /* load the private key, if we're supposed to have one */
  402. if(options.DirPort) {
  403. prkey = crypto_new_pk_env(CRYPTO_PK_RSA);
  404. if (!prkey) {
  405. log(LOG_ERR,"Error creating a crypto environment.");
  406. return -1;
  407. }
  408. if (crypto_pk_read_private_key_from_filename(prkey, options.SigningPrivateKeyFile)) {
  409. log(LOG_ERR,"Error loading private key.");
  410. return -1;
  411. }
  412. set_signing_privatekey(prkey);
  413. }
  414. /* start up the necessary connections based on which ports are
  415. * non-zero. This is where we try to connect to all the other ORs,
  416. * and start the listeners
  417. */
  418. retry_all_connections(options.ORPort, options.APPort, options.DirPort);
  419. for(;;) {
  420. if(please_dumpstats) {
  421. dumpstats();
  422. please_dumpstats = 0;
  423. }
  424. if(please_fetch_directory) {
  425. if(options.DirPort) {
  426. if(router_get_list_from_file(options.RouterFile) < 0) {
  427. log(LOG_ERR,"Error reloading router list. Continuing with old list.");
  428. }
  429. } else {
  430. directory_initiate_fetch(router_pick_directory_server());
  431. }
  432. please_fetch_directory = 0;
  433. }
  434. if(prepare_for_poll(&timeout) < 0) {
  435. log(LOG_DEBUG,"do_main_loop(): prepare_for_poll failed, exiting.");
  436. return -1;
  437. }
  438. /* now timeout is the value we'll hand to poll. It's either -1, meaning
  439. * don't timeout, else it indicates the soonest event (either the
  440. * one-second rollover for refilling receiver buckets, or the soonest
  441. * conn that needs to send a cell)
  442. */
  443. /* poll until we have an event, or it's time to do something */
  444. poll_result = poll(poll_array, nfds, timeout);
  445. #if 0 /* let catch() handle things like ^c, and otherwise don't worry about it */
  446. if(poll_result < 0) {
  447. log(LOG_ERR,"do_main_loop(): poll failed.");
  448. if(errno != EINTR) /* let the program survive things like ^z */
  449. return -1;
  450. }
  451. #endif
  452. if(poll_result == 0) {
  453. /* poll timed out without anything to do. process a pending onion, if any. */
  454. onion_pending_process_one();
  455. }
  456. if(poll_result > 0) { /* we have at least one connection to deal with */
  457. /* do all the reads first, so we can detect closed sockets */
  458. for(i=0;i<nfds;i++)
  459. if(poll_array[i].revents & POLLIN ||
  460. poll_array[i].revents & POLLHUP ) /* something to read */
  461. conn_read(i); /* this also blows away broken connections */
  462. /* see http://www.greenend.org.uk/rjk/2001/06/poll.html for discussion
  463. * of POLLIN vs POLLHUP */
  464. /* then do the writes */
  465. for(i=0;i<nfds;i++)
  466. if(poll_array[i].revents & POLLOUT) /* something to write */
  467. conn_write(i);
  468. /* any of the conns need to be closed now? */
  469. for(i=0;i<nfds;i++)
  470. check_conn_marked(i);
  471. }
  472. /* refilling buckets and sending cells happens at the beginning of the
  473. * next iteration of the loop, inside prepare_for_poll()
  474. */
  475. }
  476. }
  477. static void catch(int the_signal) {
  478. switch(the_signal) {
  479. // case SIGABRT:
  480. case SIGTERM:
  481. case SIGINT:
  482. log(LOG_NOTICE,"Catching signal %d, exiting cleanly.", the_signal);
  483. exit(0);
  484. case SIGHUP:
  485. please_fetch_directory = 1;
  486. break;
  487. case SIGUSR1:
  488. please_dumpstats = 1;
  489. break;
  490. default:
  491. log(LOG_ERR,"Caught signal that we can't handle??");
  492. }
  493. }
  494. static void dumpstats(void) { /* dump stats to stdout */
  495. int i;
  496. connection_t *conn;
  497. struct timeval now;
  498. extern char *conn_type_to_string[];
  499. extern char *conn_state_to_string[][15];
  500. printf("Dumping stats:\n");
  501. my_gettimeofday(&now);
  502. for(i=0;i<nfds;i++) {
  503. conn = connection_array[i];
  504. printf("Conn %d (socket %d) type %d (%s), state %d (%s), created %ld secs ago\n",
  505. i, conn->s, conn->type, conn_type_to_string[conn->type],
  506. conn->state, conn_state_to_string[conn->type][conn->state], now.tv_sec - conn->timestamp_created);
  507. if(!connection_is_listener(conn)) {
  508. printf("Conn %d is to '%s:%d'.\n",i,conn->address, conn->port);
  509. printf("Conn %d: %d bytes waiting on inbuf (last read %ld secs ago)\n",i,conn->inbuf_datalen,
  510. now.tv_sec - conn->timestamp_lastread);
  511. printf("Conn %d: %d bytes waiting on outbuf (last written %ld secs ago)\n",i,conn->outbuf_datalen,
  512. now.tv_sec - conn->timestamp_lastwritten);
  513. }
  514. circuit_dump_by_conn(conn); /* dump info about all the circuits using this conn */
  515. printf("\n");
  516. }
  517. }
  518. int dump_router_to_string(char *s, int maxlen, routerinfo_t *router) {
  519. char *pkey;
  520. char *signing_pkey, *signing_pkey_tag;
  521. int pkeylen, signing_pkeylen;
  522. int written;
  523. int result=0;
  524. struct exit_policy_t *tmpe;
  525. if(crypto_pk_write_public_key_to_string(router->pkey,&pkey,&pkeylen)<0) {
  526. log(LOG_ERR,"dump_router_to_string(): write pkey to string failed!");
  527. return 0;
  528. }
  529. signing_pkey = "";
  530. signing_pkey_tag = "";
  531. if (router->signing_pkey) {
  532. if(crypto_pk_write_public_key_to_string(router->signing_pkey,
  533. &signing_pkey,&signing_pkeylen)<0) {
  534. log(LOG_ERR,"dump_router_to_string(): write signing_pkey to string failed!");
  535. return 0;
  536. }
  537. signing_pkey_tag = "signing-key\n";
  538. }
  539. result = snprintf(s, maxlen, "router %s %d %d %d %d %d\n%s%s%s",
  540. router->address,
  541. router->or_port,
  542. router->op_port,
  543. router->ap_port,
  544. router->dir_port,
  545. router->bandwidth,
  546. pkey,
  547. signing_pkey_tag, signing_pkey);
  548. free(pkey);
  549. if (*signing_pkey)
  550. free(signing_pkey);
  551. if(result < 0 || result > maxlen) {
  552. /* apparently different glibcs do different things on snprintf error.. so check both */
  553. return -1;
  554. }
  555. written = result;
  556. for(tmpe=router->exit_policy; tmpe; tmpe=tmpe->next) {
  557. result = snprintf(s+written, maxlen-written, "%s %s:%s\n",
  558. tmpe->policy_type == EXIT_POLICY_ACCEPT ? "accept" : "reject",
  559. tmpe->address, tmpe->port);
  560. if(result < 0 || result+written > maxlen) {
  561. /* apparently different glibcs do different things on snprintf error.. so check both */
  562. return -1;
  563. }
  564. written += result;
  565. }
  566. if(written > maxlen-2) {
  567. return -1; /* not enough space for \n\0 */
  568. }
  569. /* XXX count fenceposts here. They're probably wrong. In general,
  570. * we need a better way to handle overruns in building the directory
  571. * string, and a better way to handle directory string size in general. */
  572. /* include a last '\n' */
  573. s[written] = '\n';
  574. s[written+1] = 0;
  575. return written+1;
  576. }
  577. static int
  578. build_directory(directory_t *dir) {
  579. routerinfo_t **routers = NULL;
  580. connection_t *conn;
  581. routerinfo_t *router;
  582. int i, n = 0;
  583. routers = (routerinfo_t **)tor_malloc(sizeof(routerinfo_t*) * (nfds+1));
  584. if (my_routerinfo) {
  585. log(LOG_INFO, "build_directory(): adding self (%s:%d)",
  586. my_routerinfo->address, my_routerinfo->or_port);
  587. routers[n++] = my_routerinfo;
  588. }
  589. for(i = 0; i<nfds; ++i) {
  590. conn = connection_array[i];
  591. if(conn->type != CONN_TYPE_OR)
  592. continue; /* we only want to list ORs */
  593. if(conn->state != OR_CONN_STATE_OPEN)
  594. continue; /* we only want to list ones that successfully handshaked */
  595. router = router_get_by_addr_port(conn->addr,conn->port);
  596. if(!router) {
  597. log(LOG_ERR,"build_directory(): couldn't find router %d:%d!",
  598. conn->addr,conn->port);
  599. continue;
  600. }
  601. log(LOG_INFO, "build_directory(): adding router (%s:%d)",
  602. router->address, router->or_port);
  603. routers[n++] = router;
  604. }
  605. dir->routers = routers;
  606. dir->n_routers = n;
  607. return 0;
  608. }
  609. int
  610. dump_signed_directory_to_string(char *s, int maxlen,
  611. crypto_pk_env_t *private_key)
  612. {
  613. directory_t dir;
  614. if (build_directory(&dir)) {
  615. log(LOG_ERR,"dump_signed_directory_to_string(): build_directory failed.");
  616. return -1;
  617. }
  618. return dump_signed_directory_to_string_impl(s, maxlen, &dir, private_key);
  619. }
  620. int
  621. dump_signed_directory_to_string_impl(char *s, int maxlen, directory_t *dir,
  622. crypto_pk_env_t *private_key)
  623. {
  624. char *cp, *eos;
  625. char digest[20];
  626. char signature[128];
  627. int i, written;
  628. routerinfo_t *router;
  629. eos = s+maxlen;
  630. strncpy(s,
  631. "signed-directory\n"
  632. "recommended-software 0.0.2pre4,0.0.2pre5,0.0.2pre6\n" /* XXX make this real */
  633. , maxlen);
  634. i = strlen(s);
  635. cp = s+i;
  636. for (i = 0; i < dir->n_routers; ++i) {
  637. router = dir->routers[i];
  638. written = dump_router_to_string(cp, eos-cp, router);
  639. if(written < 0) {
  640. log(LOG_ERR,"dump_signed_directory_to_string(): tried to exceed string length.");
  641. cp[maxlen-1] = 0; /* make sure it's null terminated */
  642. free(dir->routers);
  643. return -1;
  644. }
  645. cp += written;
  646. }
  647. free(dir->routers); /* not needed anymore */
  648. /* These multiple strlen calls are inefficient, but dwarfed by the RSA
  649. signature.
  650. */
  651. i = strlen(s);
  652. strncat(s, "directory-signature\n", maxlen-i);
  653. i = strlen(s);
  654. cp = s + i;
  655. if (crypto_SHA_digest(s, i, digest)) {
  656. log(LOG_ERR,"dump_signed_directory_to_string(): couldn't compute digest");
  657. return -1;
  658. }
  659. if (crypto_pk_private_sign(private_key, digest, 20, signature) < 0) {
  660. log(LOG_ERR,"dump_signed_directory_to_string(): couldn't sign digest");
  661. return -1;
  662. }
  663. strncpy(cp,
  664. "-----BEGIN SIGNATURE-----\n", maxlen-i);
  665. i = strlen(s);
  666. cp = s+i;
  667. if (base64_encode(cp, maxlen-i, signature, 128) < 0) {
  668. log_fn(LOG_ERR," couldn't base64-encode signature");
  669. return -1;
  670. }
  671. i = strlen(s);
  672. cp = s+i;
  673. strncat(cp, "-----END SIGNATURE-----\n", maxlen-i);
  674. i = strlen(s);
  675. if (i == maxlen) {
  676. log(LOG_ERR,"dump_signed_directory_to_string(): tried to exceed string length.");
  677. return -1;
  678. }
  679. return 0;
  680. }
  681. void daemonize(void) {
  682. /* Fork; parent exits. */
  683. if (fork())
  684. exit(0);
  685. /* Create new session; make sure we never get a terminal */
  686. setsid();
  687. if (fork())
  688. exit(0);
  689. chdir("/");
  690. umask(000);
  691. fclose(stdin);
  692. fclose(stdout); /* XXX Nick: this closes our log, right? is it safe to leave this open? */
  693. fclose(stderr);
  694. }
  695. int tor_main(int argc, char *argv[]) {
  696. int retval = 0;
  697. if(getconfig(argc,argv,&options))
  698. exit(1);
  699. log_set_severity(options.loglevel); /* assign logging severity level from options */
  700. global_read_bucket = options.TotalBandwidth; /* start it at 1 second of traffic */
  701. if(options.Daemon)
  702. daemonize();
  703. if(options.OnionRouter) { /* only spawn dns handlers if we're a router */
  704. dns_init(); /* initialize the dns resolve tree, and spawn workers */
  705. }
  706. signal (SIGINT, catch); /* catch kills so we can exit cleanly */
  707. signal (SIGTERM, catch);
  708. signal (SIGUSR1, catch); /* to dump stats to stdout */
  709. signal (SIGHUP, catch); /* to reload directory */
  710. crypto_global_init();
  711. crypto_seed_rng();
  712. retval = do_main_loop();
  713. crypto_global_cleanup();
  714. return retval;
  715. }
  716. /*
  717. Local Variables:
  718. mode:c
  719. indent-tabs-mode:nil
  720. c-basic-offset:2
  721. End:
  722. */