main.c 24 KB

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