main.c 24 KB

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