main.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863
  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. extern char *conn_type_to_string[];
  9. extern char *conn_state_to_string[][15];
  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 connection_t *connection_array[MAXCONNECTIONS] =
  13. { NULL };
  14. static struct pollfd poll_array[MAXCONNECTIONS];
  15. static int nfds=0; /* number of connections currently active */
  16. static int please_dumpstats=0; /* whether we should dump stats during the loop */
  17. static int please_fetch_directory=0; /* whether we should fetch a new directory */
  18. /* private key */
  19. static crypto_pk_env_t *privatekey=NULL;
  20. static crypto_pk_env_t *signing_privatekey=NULL;
  21. routerinfo_t *my_routerinfo=NULL;
  22. /********* END VARIABLES ************/
  23. void set_privatekey(crypto_pk_env_t *k) {
  24. privatekey = k;
  25. }
  26. crypto_pk_env_t *get_privatekey(void) {
  27. assert(privatekey);
  28. return privatekey;
  29. }
  30. void set_signing_privatekey(crypto_pk_env_t *k) {
  31. signing_privatekey = k;
  32. }
  33. crypto_pk_env_t *get_signing_privatekey(void) {
  34. assert(signing_privatekey);
  35. return signing_privatekey;
  36. }
  37. /****************************************************************************
  38. *
  39. * This section contains accessors and other methods on the connection_array
  40. * and poll_array variables (which are global within this file and unavailable
  41. * outside it).
  42. *
  43. ****************************************************************************/
  44. int connection_add(connection_t *conn) {
  45. if(nfds >= options.MaxConn-1) {
  46. log(LOG_INFO,"connection_add(): failing because nfds is too high.");
  47. return -1;
  48. }
  49. conn->poll_index = nfds;
  50. connection_set_poll_socket(conn);
  51. connection_array[nfds] = conn;
  52. /* zero these out here, because otherwise we'll inherit values from the previously freed one */
  53. poll_array[nfds].events = 0;
  54. poll_array[nfds].revents = 0;
  55. nfds++;
  56. log(LOG_INFO,"connection_add(): new conn type %d, socket %d, nfds %d.",conn->type, conn->s, nfds);
  57. return 0;
  58. }
  59. void connection_set_poll_socket(connection_t *conn) {
  60. poll_array[conn->poll_index].fd = conn->s;
  61. }
  62. int connection_remove(connection_t *conn) {
  63. int current_index;
  64. assert(conn);
  65. assert(nfds>0);
  66. log(LOG_INFO,"connection_remove(): removing socket %d, nfds now %d",conn->s, nfds-1);
  67. circuit_about_to_close_connection(conn); /* if it's an edge conn, remove it from the list
  68. * of conn's on this circuit. If it's not on an edge,
  69. * flush and send destroys for all circuits on this conn
  70. */
  71. current_index = conn->poll_index;
  72. if(current_index == nfds-1) { /* this is the end */
  73. nfds--;
  74. return 0;
  75. }
  76. /* we replace this one with the one at the end, then free it */
  77. nfds--;
  78. poll_array[current_index].fd = poll_array[nfds].fd;
  79. poll_array[current_index].events = poll_array[nfds].events;
  80. poll_array[current_index].revents = poll_array[nfds].revents;
  81. connection_array[current_index] = connection_array[nfds];
  82. connection_array[current_index]->poll_index = current_index;
  83. return 0;
  84. }
  85. connection_t *connection_twin_get_by_addr_port(uint32_t addr, uint16_t port) {
  86. /* Find a connection to the router described by addr and port,
  87. * or alternately any router which knows its key.
  88. * This connection *must* be in 'open' state.
  89. * If not, return NULL.
  90. */
  91. int i;
  92. connection_t *conn;
  93. routerinfo_t *router;
  94. /* first check if it's there exactly */
  95. conn = connection_exact_get_by_addr_port(addr,port);
  96. if(conn && connection_state_is_open(conn)) {
  97. log(LOG_INFO,"connection_twin_get_by_addr_port(): Found exact match.");
  98. return conn;
  99. }
  100. /* now check if any of the other open connections are a twin for this one */
  101. router = router_get_by_addr_port(addr,port);
  102. if(!router)
  103. return NULL;
  104. for(i=0;i<nfds;i++) {
  105. conn = connection_array[i];
  106. assert(conn);
  107. if(connection_state_is_open(conn) &&
  108. !conn->marked_for_close &&
  109. !crypto_pk_cmp_keys(conn->pkey, router->pkey)) {
  110. log(LOG_INFO,"connection_twin_get_by_addr_port(): Found twin (%s).",conn->address);
  111. return conn;
  112. }
  113. }
  114. /* guess not */
  115. return NULL;
  116. }
  117. connection_t *connection_exact_get_by_addr_port(uint32_t addr, uint16_t port) {
  118. int i;
  119. connection_t *conn;
  120. for(i=0;i<nfds;i++) {
  121. conn = connection_array[i];
  122. if(conn->addr == addr && conn->port == port && !conn->marked_for_close)
  123. return conn;
  124. }
  125. return NULL;
  126. }
  127. connection_t *connection_get_by_type(int type) {
  128. int i;
  129. connection_t *conn;
  130. for(i=0;i<nfds;i++) {
  131. conn = connection_array[i];
  132. if(conn->type == type && !conn->marked_for_close)
  133. return conn;
  134. }
  135. return NULL;
  136. }
  137. connection_t *connection_get_by_type_state(int type, int state) {
  138. int i;
  139. connection_t *conn;
  140. for(i=0;i<nfds;i++) {
  141. conn = connection_array[i];
  142. if(conn->type == type && conn->state == state && !conn->marked_for_close)
  143. return conn;
  144. }
  145. return NULL;
  146. }
  147. connection_t *connection_get_by_type_state_lastwritten(int type, int state) {
  148. int i;
  149. connection_t *conn, *best=NULL;
  150. for(i=0;i<nfds;i++) {
  151. conn = connection_array[i];
  152. if(conn->type == type && conn->state == state && !conn->marked_for_close)
  153. if(!best || conn->timestamp_lastwritten < best->timestamp_lastwritten)
  154. best = conn;
  155. }
  156. return best;
  157. }
  158. void connection_watch_events(connection_t *conn, short events) {
  159. assert(conn && conn->poll_index < nfds);
  160. poll_array[conn->poll_index].events = events;
  161. }
  162. void connection_stop_reading(connection_t *conn) {
  163. assert(conn && conn->poll_index < nfds);
  164. log(LOG_DEBUG,"connection_stop_reading() called.");
  165. if(poll_array[conn->poll_index].events & POLLIN)
  166. poll_array[conn->poll_index].events -= POLLIN;
  167. }
  168. void connection_start_reading(connection_t *conn) {
  169. assert(conn && conn->poll_index < nfds);
  170. poll_array[conn->poll_index].events |= POLLIN;
  171. }
  172. void connection_stop_writing(connection_t *conn) {
  173. assert(conn && conn->poll_index < nfds);
  174. if(poll_array[conn->poll_index].events & POLLOUT)
  175. poll_array[conn->poll_index].events -= POLLOUT;
  176. }
  177. void connection_start_writing(connection_t *conn) {
  178. assert(conn && conn->poll_index < nfds);
  179. poll_array[conn->poll_index].events |= POLLOUT;
  180. }
  181. static void conn_read(int i) {
  182. int retval;
  183. connection_t *conn;
  184. conn = connection_array[i];
  185. assert(conn);
  186. // log_fn(LOG_DEBUG,"socket %d has something to read.",conn->s);
  187. if (conn->type == CONN_TYPE_OR_LISTENER) {
  188. retval = connection_or_handle_listener_read(conn);
  189. } else if (conn->type == CONN_TYPE_AP_LISTENER) {
  190. retval = connection_ap_handle_listener_read(conn);
  191. } else if (conn->type == CONN_TYPE_DIR_LISTENER) {
  192. retval = connection_dir_handle_listener_read(conn);
  193. } else {
  194. retval = connection_read_to_buf(conn);
  195. if (retval < 0 && conn->type == CONN_TYPE_DIR && conn->state == DIR_CONN_STATE_CONNECTING) {
  196. /* it's a directory server and connecting failed: forget about this router */
  197. router_forget_router(conn->addr,conn->port); /* FIXME i don't think this function works. */
  198. }
  199. if (retval >= 0) { /* all still well */
  200. retval = connection_process_inbuf(conn);
  201. // log_fn(LOG_DEBUG,"connection_process_inbuf returned %d.",retval);
  202. if(retval >= 0 && !connection_state_is_open(conn) && conn->receiver_bucket == 0) {
  203. log(LOG_DEBUG,"conn_read(): receiver bucket reached 0 before handshake finished. Closing.");
  204. retval = -1;
  205. }
  206. }
  207. }
  208. if(retval < 0) { /* this connection is broken. remove it */
  209. log_fn(LOG_INFO,"%s connection broken, removing.", conn_type_to_string[conn->type]);
  210. connection_remove(conn);
  211. connection_free(conn);
  212. if(i<nfds) { /* we just replaced the one at i with a new one.
  213. process it too. */
  214. if(poll_array[i].revents & POLLIN ||
  215. poll_array[i].revents & POLLHUP ) /* something to read */
  216. conn_read(i);
  217. }
  218. }
  219. }
  220. static void conn_write(int i) {
  221. int retval;
  222. connection_t *conn;
  223. conn = connection_array[i];
  224. // log_fn(LOG_DEBUG,"socket %d wants to write.",conn->s);
  225. if(connection_is_listener(conn)) {
  226. log_fn(LOG_DEBUG,"Got a listener socket. Can't happen!");
  227. retval = -1;
  228. } else {
  229. /* else it's an OP, OR, or exit */
  230. retval = connection_flush_buf(conn); /* conns in CONNECTING state will fall through... */
  231. if(retval == 0) { /* it's done flushing */
  232. retval = connection_finished_flushing(conn); /* ...and get handled here. */
  233. }
  234. }
  235. if(retval < 0) { /* this connection is broken. remove it. */
  236. log_fn(LOG_DEBUG,"%s connection broken, removing.", conn_type_to_string[conn->type]);
  237. connection_remove(conn);
  238. connection_free(conn);
  239. if(i<nfds) { /* we just replaced the one at i with a new one.
  240. process it too. */
  241. if(poll_array[i].revents & POLLOUT) /* something to write */
  242. conn_write(i);
  243. }
  244. }
  245. }
  246. static void check_conn_marked(int i) {
  247. connection_t *conn;
  248. conn = connection_array[i];
  249. assert(conn);
  250. if(conn->marked_for_close) {
  251. log(LOG_DEBUG,"check_conn_marked(): Cleaning up connection.");
  252. if(conn->s >= 0) { /* might be an incomplete exit connection */
  253. /* FIXME there's got to be a better way to check for this -- and make other checks? */
  254. connection_flush_buf(conn); /* flush it first */
  255. }
  256. connection_remove(conn);
  257. connection_free(conn);
  258. if(i<nfds) { /* we just replaced the one at i with a new one.
  259. process it too. */
  260. check_conn_marked(i);
  261. }
  262. }
  263. }
  264. static int prepare_for_poll(int *timeout) {
  265. int i;
  266. // connection_t *conn = NULL;
  267. connection_t *tmpconn;
  268. struct timeval now; //soonest;
  269. static long current_second = 0; /* from previous calls to gettimeofday */
  270. static long time_to_fetch_directory = 0;
  271. static long time_to_new_circuit = 0;
  272. // int ms_until_conn;
  273. cell_t cell;
  274. circuit_t *circ;
  275. my_gettimeofday(&now);
  276. if(now.tv_sec > current_second) { /* the second has rolled over. check more stuff. */
  277. if(!options.DirPort) {
  278. if(time_to_fetch_directory < now.tv_sec) {
  279. /* it's time to fetch a new directory */
  280. /* NOTE directory servers do not currently fetch directories.
  281. * Hope this doesn't bite us later.
  282. */
  283. directory_initiate_fetch(router_pick_directory_server());
  284. time_to_fetch_directory = now.tv_sec + options.DirFetchPeriod;
  285. }
  286. }
  287. if(options.APPort && time_to_new_circuit < now.tv_sec) {
  288. circuit_expire_unused_circuits();
  289. circuit_launch_new(-1); /* tell it to forget about previous failures */
  290. circ = circuit_get_newest_ap();
  291. if(!circ || circ->dirty) {
  292. log(LOG_INFO,"prepare_for_poll(): Youngest circuit %s; launching replacement.", circ ? "dirty" : "missing");
  293. circuit_launch_new(0); /* make an onion and lay the circuit */
  294. }
  295. time_to_new_circuit = now.tv_sec + options.NewCircuitPeriod;
  296. }
  297. if(global_read_bucket < 9*options.TotalBandwidth) {
  298. global_read_bucket += options.TotalBandwidth;
  299. log_fn(LOG_DEBUG,"global_read_bucket now %d.", global_read_bucket);
  300. }
  301. /* do housekeeping for each connection */
  302. for(i=0;i<nfds;i++) {
  303. tmpconn = connection_array[i];
  304. if(connection_receiver_bucket_should_increase(tmpconn)) {
  305. tmpconn->receiver_bucket += tmpconn->bandwidth;
  306. // log_fn(LOG_DEBUG,"Receiver bucket %d now %d.", i, tmpconn->receiver_bucket);
  307. }
  308. if(tmpconn->wants_to_read == 1 /* it's marked to turn reading back on now */
  309. && global_read_bucket > 0 /* and we're allowed to read */
  310. && tmpconn->receiver_bucket != 0) { /* and either an edge conn or non-empty bucket */
  311. tmpconn->wants_to_read = 0;
  312. connection_start_reading(tmpconn);
  313. }
  314. /* check connections to see whether we should send a keepalive, expire, or wait */
  315. if(!connection_speaks_cells(tmpconn))
  316. continue; /* this conn type doesn't send cells */
  317. if(now.tv_sec >= tmpconn->timestamp_lastwritten + options.KeepalivePeriod) {
  318. if((!options.OnionRouter && !circuit_get_by_conn(tmpconn)) ||
  319. (!connection_state_is_open(tmpconn))) {
  320. /* we're an onion proxy, with no circuits; or our handshake has expired. kill it. */
  321. log(LOG_DEBUG,"prepare_for_poll(): Expiring connection to %d (%s:%d).",
  322. i,tmpconn->address, tmpconn->port);
  323. tmpconn->marked_for_close = 1;
  324. } else {
  325. /* either a full router, or we've got a circuit. send a padding cell. */
  326. // log(LOG_DEBUG,"prepare_for_poll(): Sending keepalive to (%s:%d)",
  327. // tmpconn->address, tmpconn->port);
  328. memset(&cell,0,sizeof(cell_t));
  329. cell.command = CELL_PADDING;
  330. if(connection_write_cell_to_buf(&cell, tmpconn) < 0)
  331. tmpconn->marked_for_close = 1;
  332. }
  333. }
  334. }
  335. /* blow away any connections that need to die. can't do this later
  336. * because we might open up a circuit and not realize it we're about to cull it.
  337. */
  338. for(i=0;i<nfds;i++)
  339. check_conn_marked(i);
  340. current_second = now.tv_sec; /* remember which second it is, for next time */
  341. }
  342. if(onion_pending_check()) {
  343. /* there's an onion pending. check for new things to do, but don't wait any time */
  344. *timeout = 0;
  345. } else {
  346. *timeout = 1000 - (now.tv_usec / 1000); /* how many milliseconds til the next second? */
  347. }
  348. return 0;
  349. }
  350. /* Link padding stuff left here for fun. Not used now. */
  351. #if 0
  352. if(options.LinkPadding) {
  353. /* now check which conn wants to speak soonest */
  354. for(i=0;i<nfds;i++) {
  355. tmpconn = connection_array[i];
  356. if(!connection_speaks_cells(tmpconn))
  357. continue; /* this conn type doesn't send cells */
  358. if(!connection_state_is_open(tmpconn))
  359. continue; /* only conns in state 'open' have a valid send_timeval */
  360. while(tv_cmp(&tmpconn->send_timeval,&now) <= 0) { /* send_timeval has already passed, let it send a cell */
  361. connection_send_cell(tmpconn);
  362. }
  363. if(!conn || tv_cmp(&tmpconn->send_timeval, &soonest) < 0) { /* this is the best choice so far */
  364. conn = tmpconn;
  365. soonest.tv_sec = conn->send_timeval.tv_sec;
  366. soonest.tv_usec = conn->send_timeval.tv_usec;
  367. }
  368. }
  369. if(conn) { /* we might want to set *timeout sooner */
  370. ms_until_conn = (soonest.tv_sec - now.tv_sec)*1000 +
  371. (soonest.tv_usec - now.tv_usec)/1000;
  372. // log(LOG_DEBUG,"prepare_for_poll(): conn %d times out in %d ms.",conn->s, ms_until_conn);
  373. if(ms_until_conn < *timeout) { /* use the new one */
  374. // log(LOG_DEBUG,"prepare_for_poll(): conn %d soonest, in %d ms.",conn->s,ms_until_conn);
  375. *timeout = ms_until_conn;
  376. }
  377. }
  378. }
  379. #endif
  380. static int do_main_loop(void) {
  381. int i;
  382. int timeout;
  383. int poll_result;
  384. crypto_pk_env_t *prkey;
  385. /* load the routers file */
  386. if(router_get_list_from_file(options.RouterFile) < 0) {
  387. log(LOG_ERR,"Error loading router list.");
  388. return -1;
  389. }
  390. /* load the private key, if we're supposed to have one */
  391. if(options.OnionRouter) {
  392. prkey = crypto_new_pk_env(CRYPTO_PK_RSA);
  393. if (!prkey) {
  394. log(LOG_ERR,"Error creating a crypto environment.");
  395. return -1;
  396. }
  397. if (crypto_pk_read_private_key_from_filename(prkey, options.PrivateKeyFile)) {
  398. log(LOG_ERR,"Error loading private key.");
  399. return -1;
  400. }
  401. set_privatekey(prkey);
  402. }
  403. /* load the private key, if we're supposed to have one */
  404. if(options.DirPort) {
  405. prkey = crypto_new_pk_env(CRYPTO_PK_RSA);
  406. if (!prkey) {
  407. log(LOG_ERR,"Error creating a crypto environment.");
  408. return -1;
  409. }
  410. if (crypto_pk_read_private_key_from_filename(prkey, options.SigningPrivateKeyFile)) {
  411. log(LOG_ERR,"Error loading private key.");
  412. return -1;
  413. }
  414. set_signing_privatekey(prkey);
  415. }
  416. /* start up the necessary connections based on which ports are
  417. * non-zero. This is where we try to connect to all the other ORs,
  418. * and start the listeners
  419. */
  420. retry_all_connections(options.ORPort, options.APPort, options.DirPort);
  421. for(;;) {
  422. if(please_dumpstats) {
  423. dumpstats();
  424. please_dumpstats = 0;
  425. }
  426. if(please_fetch_directory) {
  427. if(options.DirPort) {
  428. if(router_get_list_from_file(options.RouterFile) < 0) {
  429. log(LOG_ERR,"Error reloading router list. Continuing with old list.");
  430. }
  431. } else {
  432. directory_initiate_fetch(router_pick_directory_server());
  433. }
  434. please_fetch_directory = 0;
  435. }
  436. if(prepare_for_poll(&timeout) < 0) {
  437. log(LOG_DEBUG,"do_main_loop(): prepare_for_poll failed, exiting.");
  438. return -1;
  439. }
  440. /* now timeout is the value we'll hand to poll. It's either -1, meaning
  441. * don't timeout, else it indicates the soonest event (either the
  442. * one-second rollover for refilling receiver buckets, or the soonest
  443. * conn that needs to send a cell)
  444. */
  445. /* poll until we have an event, or it's time to do something */
  446. poll_result = poll(poll_array, nfds, timeout);
  447. #if 0 /* let catch() handle things like ^c, and otherwise don't worry about it */
  448. if(poll_result < 0) {
  449. log(LOG_ERR,"do_main_loop(): poll failed.");
  450. if(errno != EINTR) /* let the program survive things like ^z */
  451. return -1;
  452. }
  453. #endif
  454. if(poll_result == 0) {
  455. /* poll timed out without anything to do. process a pending onion, if any. */
  456. onion_pending_process_one();
  457. }
  458. if(poll_result > 0) { /* we have at least one connection to deal with */
  459. /* do all the reads first, so we can detect closed sockets */
  460. for(i=0;i<nfds;i++)
  461. if(poll_array[i].revents & POLLIN ||
  462. poll_array[i].revents & POLLHUP ) /* something to read */
  463. conn_read(i); /* this also blows away broken connections */
  464. /* see http://www.greenend.org.uk/rjk/2001/06/poll.html for discussion
  465. * of POLLIN vs POLLHUP */
  466. /* then do the writes */
  467. for(i=0;i<nfds;i++)
  468. if(poll_array[i].revents & POLLOUT) /* something to write */
  469. conn_write(i);
  470. /* any of the conns need to be closed now? */
  471. for(i=0;i<nfds;i++)
  472. check_conn_marked(i);
  473. }
  474. /* refilling buckets and sending cells happens at the beginning of the
  475. * next iteration of the loop, inside prepare_for_poll()
  476. */
  477. }
  478. }
  479. static void catch(int the_signal) {
  480. switch(the_signal) {
  481. // case SIGABRT:
  482. case SIGTERM:
  483. case SIGINT:
  484. log(LOG_NOTICE,"Catching signal %d, exiting cleanly.", the_signal);
  485. exit(0);
  486. case SIGHUP:
  487. please_fetch_directory = 1;
  488. break;
  489. case SIGUSR1:
  490. please_dumpstats = 1;
  491. break;
  492. default:
  493. log(LOG_ERR,"Caught signal that we can't handle??");
  494. }
  495. }
  496. static void dumpstats(void) { /* dump stats to stdout */
  497. int i;
  498. connection_t *conn;
  499. struct timeval now;
  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. */