main.c 25 KB

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