main.c 23 KB

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