main.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853
  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_reset =0; /* whether we just got a sighup */
  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. assert_connection_ok(conn, time(NULL));
  196. if(
  197. /* XXX does POLLHUP also mean it's definitely broken? */
  198. #ifdef MS_WINDOWS
  199. (poll_array[i].revents & POLLERR) ||
  200. #endif
  201. connection_handle_read(conn) < 0)
  202. {
  203. /* this connection is broken. remove it */
  204. log_fn(LOG_INFO,"%s connection broken, removing.", conn_type_to_string[conn->type]);
  205. connection_remove(conn);
  206. connection_free(conn);
  207. if(i<nfds) { /* we just replaced the one at i with a new one. process it too. */
  208. conn_read(i);
  209. }
  210. } else assert_connection_ok(conn, time(NULL));
  211. }
  212. static void conn_write(int i) {
  213. connection_t *conn;
  214. if(!(poll_array[i].revents & POLLOUT))
  215. return; /* this conn doesn't want to write */
  216. conn = connection_array[i];
  217. log_fn(LOG_DEBUG,"socket %d wants to write.",conn->s);
  218. assert_connection_ok(conn, time(NULL));
  219. if(connection_handle_write(conn) < 0) { /* this connection is broken. remove it. */
  220. log_fn(LOG_DEBUG,"%s connection broken, removing.", conn_type_to_string[conn->type]);
  221. connection_remove(conn);
  222. connection_free(conn);
  223. if(i<nfds) { /* we just replaced the one at i with a new one. process it too. */
  224. conn_write(i);
  225. }
  226. } else assert_connection_ok(conn, time(NULL));
  227. }
  228. static void check_conn_marked(int i) {
  229. connection_t *conn;
  230. conn = connection_array[i];
  231. assert_connection_ok(conn, time(NULL));
  232. if(conn->marked_for_close) {
  233. log_fn(LOG_DEBUG,"Cleaning up connection.");
  234. if(conn->s >= 0) { /* might be an incomplete edge connection */
  235. /* FIXME there's got to be a better way to check for this -- and make other checks? */
  236. if(connection_speaks_cells(conn) && conn->state != OR_CONN_STATE_CONNECTING)
  237. flush_buf_tls(conn->tls, &conn->outbuf, &conn->outbuflen,
  238. &conn->outbuf_flushlen, &conn->outbuf_datalen);
  239. else
  240. flush_buf(conn->s, &conn->outbuf, &conn->outbuflen,
  241. &conn->outbuf_flushlen, &conn->outbuf_datalen);
  242. if(connection_wants_to_flush(conn)) /* not done flushing */
  243. log_fn(LOG_WARNING,"Conn (socket %d) still wants to flush. Losing %d bytes!",conn->s, conn->inbuf_datalen);
  244. }
  245. connection_remove(conn);
  246. connection_free(conn);
  247. if(i<nfds) { /* we just replaced the one at i with a new one.
  248. process it too. */
  249. check_conn_marked(i);
  250. }
  251. }
  252. }
  253. static int prepare_for_poll(void) {
  254. int i;
  255. connection_t *conn;
  256. struct timeval now; //soonest;
  257. static long current_second = 0; /* from previous calls to gettimeofday */
  258. static long time_to_fetch_directory = 0;
  259. static long time_to_new_circuit = 0;
  260. // int ms_until_conn;
  261. cell_t cell;
  262. circuit_t *circ;
  263. my_gettimeofday(&now);
  264. if(now.tv_sec > current_second) { /* the second has rolled over. check more stuff. */
  265. if(!options.DirPort) {
  266. if(time_to_fetch_directory < now.tv_sec) {
  267. /* it's time to fetch a new directory */
  268. /* NOTE directory servers do not currently fetch directories.
  269. * Hope this doesn't bite us later.
  270. */
  271. directory_initiate_command(router_pick_directory_server(),
  272. DIR_CONN_STATE_CONNECTING_FETCH);
  273. time_to_fetch_directory = now.tv_sec + options.DirFetchPeriod;
  274. }
  275. }
  276. if(options.APPort && time_to_new_circuit < now.tv_sec) {
  277. circuit_expire_unused_circuits();
  278. circuit_launch_new(-1); /* tell it to forget about previous failures */
  279. circ = circuit_get_newest_open();
  280. if(!circ || circ->dirty) {
  281. log_fn(LOG_INFO,"Youngest circuit %s; launching replacement.", circ ? "dirty" : "missing");
  282. circuit_launch_new(0); /* make an onion and lay the circuit */
  283. }
  284. time_to_new_circuit = now.tv_sec + options.NewCircuitPeriod;
  285. }
  286. if(global_read_bucket < 9*options.TotalBandwidth) {
  287. global_read_bucket += options.TotalBandwidth;
  288. log_fn(LOG_DEBUG,"global_read_bucket now %d.", global_read_bucket);
  289. }
  290. /* do housekeeping for each connection */
  291. for(i=0;i<nfds;i++) {
  292. conn = connection_array[i];
  293. if(connection_receiver_bucket_should_increase(conn)) {
  294. conn->receiver_bucket += conn->bandwidth;
  295. // log_fn(LOG_DEBUG,"Receiver bucket %d now %d.", i, conn->receiver_bucket);
  296. }
  297. if(conn->wants_to_read == 1 /* it's marked to turn reading back on now */
  298. && global_read_bucket > 0 /* and we're allowed to read */
  299. && conn->receiver_bucket != 0) { /* and either an edge conn or non-empty bucket */
  300. conn->wants_to_read = 0;
  301. connection_start_reading(conn);
  302. if(conn->wants_to_write == 1) {
  303. conn->wants_to_write = 0;
  304. connection_start_writing(conn);
  305. }
  306. }
  307. /* check connections to see whether we should send a keepalive, expire, or wait */
  308. if(!connection_speaks_cells(conn))
  309. continue; /* this conn type doesn't send cells */
  310. if(now.tv_sec >= conn->timestamp_lastwritten + options.KeepalivePeriod) {
  311. if((!options.OnionRouter && !circuit_get_by_conn(conn)) ||
  312. (!connection_state_is_open(conn))) {
  313. /* we're an onion proxy, with no circuits; or our handshake has expired. kill it. */
  314. log_fn(LOG_DEBUG,"Expiring connection to %d (%s:%d).",
  315. i,conn->address, conn->port);
  316. conn->marked_for_close = 1;
  317. } else {
  318. /* either a full router, or we've got a circuit. send a padding cell. */
  319. // log_fn(LOG_DEBUG,"Sending keepalive to (%s:%d)",
  320. // conn->address, conn->port);
  321. memset(&cell,0,sizeof(cell_t));
  322. cell.command = CELL_PADDING;
  323. if(connection_write_cell_to_buf(&cell, conn) < 0)
  324. conn->marked_for_close = 1;
  325. }
  326. }
  327. }
  328. /* blow away any connections that need to die. can't do this later
  329. * because we might open up a circuit and not realize it we're about to cull it.
  330. */
  331. for(i=0;i<nfds;i++)
  332. check_conn_marked(i);
  333. current_second = now.tv_sec; /* remember which second it is, for next time */
  334. }
  335. return (1000 - (now.tv_usec / 1000)); /* how many milliseconds til the next second? */
  336. }
  337. static int do_main_loop(void) {
  338. int i;
  339. int timeout;
  340. int poll_result;
  341. crypto_pk_env_t *prkey;
  342. /* load the routers file */
  343. if(router_get_list_from_file(options.RouterFile) < 0) {
  344. log(LOG_ERR,"Error loading router list.");
  345. return -1;
  346. }
  347. /* load the private key, if we're supposed to have one */
  348. if(options.OnionRouter) {
  349. prkey = crypto_new_pk_env(CRYPTO_PK_RSA);
  350. if (!prkey) {
  351. log(LOG_ERR,"Error creating a crypto environment.");
  352. return -1;
  353. }
  354. if (crypto_pk_read_private_key_from_filename(prkey, options.PrivateKeyFile)) {
  355. log(LOG_ERR,"Error loading private key.");
  356. return -1;
  357. }
  358. set_privatekey(prkey);
  359. cpu_init(); /* launch cpuworkers. Need to do this *after* we've read the private key. */
  360. }
  361. /* load the directory private key, if we're supposed to have one */
  362. if(options.DirPort) {
  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.SigningPrivateKeyFile)) {
  369. log(LOG_ERR,"Error loading private key.");
  370. return -1;
  371. }
  372. set_signing_privatekey(prkey);
  373. }
  374. if(options.OnionRouter) {
  375. struct stat statbuf;
  376. if(stat(options.CertFile, &statbuf) < 0) {
  377. log_fn(LOG_INFO,"CertFile %s is missing. Generating.", options.CertFile);
  378. if(tor_tls_write_certificate(options.CertFile,
  379. get_privatekey(),
  380. options.Nickname) < 0) {
  381. log_fn(LOG_ERR,"Couldn't write CertFile %s. Dying.", options.CertFile);
  382. return -1;
  383. }
  384. }
  385. if(tor_tls_context_new(options.CertFile, get_privatekey(), 1) < 0) {
  386. log_fn(LOG_ERR,"Error creating tls context.");
  387. return -1;
  388. }
  389. } else { /* just a proxy, the context is easy */
  390. if(tor_tls_context_new(NULL, NULL, 0) < 0) {
  391. log_fn(LOG_ERR,"Error creating tls context.");
  392. return -1;
  393. }
  394. }
  395. /* start up the necessary connections based on which ports are
  396. * non-zero. This is where we try to connect to all the other ORs,
  397. * and start the listeners.
  398. */
  399. retry_all_connections((uint16_t) options.ORPort,
  400. (uint16_t) options.APPort,
  401. (uint16_t) options.DirPort);
  402. for(;;) {
  403. #ifndef MS_WIN32 /* do signal stuff only on unix */
  404. if(please_dumpstats) {
  405. dumpstats();
  406. please_dumpstats = 0;
  407. }
  408. if(please_reset) {
  409. /* fetch a new directory */
  410. if(options.DirPort) {
  411. if(router_get_list_from_file(options.RouterFile) < 0) {
  412. log(LOG_ERR,"Error reloading router list. Continuing with old list.");
  413. }
  414. } else {
  415. directory_initiate_command(router_pick_directory_server(), DIR_CONN_STATE_CONNECTING_FETCH);
  416. }
  417. /* close and reopen the log files */
  418. reset_logs();
  419. please_reset = 0;
  420. }
  421. if(please_reap_children) {
  422. while(waitpid(-1,NULL,WNOHANG)) ; /* keep reaping until no more zombies */
  423. please_reap_children = 0;
  424. }
  425. #endif /* signal stuff */
  426. timeout = prepare_for_poll();
  427. /* poll until we have an event, or the second ends */
  428. poll_result = poll(poll_array, nfds, timeout);
  429. #if 0 /* let catch() handle things like ^c, and otherwise don't worry about it */
  430. if(poll_result < 0) {
  431. log(LOG_ERR,"do_main_loop(): poll failed.");
  432. if(errno != EINTR) /* let the program survive things like ^z */
  433. return -1;
  434. }
  435. #endif
  436. if(poll_result > 0) { /* we have at least one connection to deal with */
  437. /* do all the reads and errors first, so we can detect closed sockets */
  438. for(i=0;i<nfds;i++)
  439. conn_read(i); /* this also blows away broken connections */
  440. /* then do the writes */
  441. for(i=0;i<nfds;i++)
  442. conn_write(i);
  443. /* any of the conns need to be closed now? */
  444. for(i=0;i<nfds;i++)
  445. check_conn_marked(i);
  446. }
  447. /* refilling buckets and sending cells happens at the beginning of the
  448. * next iteration of the loop, inside prepare_for_poll()
  449. */
  450. }
  451. }
  452. static void catch(int the_signal) {
  453. #ifndef MS_WIN32 /* do signal stuff only on unix */
  454. switch(the_signal) {
  455. // case SIGABRT:
  456. case SIGTERM:
  457. case SIGINT:
  458. log(LOG_NOTICE,"Catching signal %d, exiting cleanly.", the_signal);
  459. exit(0);
  460. case SIGHUP:
  461. please_reset = 1;
  462. break;
  463. case SIGUSR1:
  464. please_dumpstats = 1;
  465. break;
  466. case SIGCHLD:
  467. please_reap_children = 1;
  468. break;
  469. default:
  470. log(LOG_ERR,"Caught signal %d that we can't handle??", the_signal);
  471. }
  472. #endif /* signal stuff */
  473. }
  474. static void dumpstats(void) { /* dump stats to stdout */
  475. int i;
  476. connection_t *conn;
  477. struct timeval now;
  478. printf("Dumping stats:\n");
  479. my_gettimeofday(&now);
  480. for(i=0;i<nfds;i++) {
  481. conn = connection_array[i];
  482. printf("Conn %d (socket %d) type %d (%s), state %d (%s), created %ld secs ago\n",
  483. i, conn->s, conn->type, conn_type_to_string[conn->type],
  484. conn->state, conn_state_to_string[conn->type][conn->state], now.tv_sec - conn->timestamp_created);
  485. if(!connection_is_listener(conn)) {
  486. printf("Conn %d is to '%s:%d'.\n",i,conn->address, conn->port);
  487. printf("Conn %d: %d bytes waiting on inbuf (last read %ld secs ago)\n",i,conn->inbuf_datalen,
  488. now.tv_sec - conn->timestamp_lastread);
  489. printf("Conn %d: %d bytes waiting on outbuf (last written %ld secs ago)\n",i,conn->outbuf_datalen,
  490. now.tv_sec - conn->timestamp_lastwritten);
  491. }
  492. circuit_dump_by_conn(conn); /* dump info about all the circuits using this conn */
  493. printf("\n");
  494. }
  495. }
  496. int dump_router_to_string(char *s, int maxlen, routerinfo_t *router) {
  497. char *pkey;
  498. char *signing_pkey, *signing_pkey_tag;
  499. int pkeylen, signing_pkeylen;
  500. int written;
  501. int result=0;
  502. struct exit_policy_t *tmpe;
  503. if(crypto_pk_write_public_key_to_string(router->pkey,&pkey,&pkeylen)<0) {
  504. log(LOG_ERR,"dump_router_to_string(): write pkey to string failed!");
  505. return 0;
  506. }
  507. signing_pkey = "";
  508. signing_pkey_tag = "";
  509. if (router->signing_pkey) {
  510. if(crypto_pk_write_public_key_to_string(router->signing_pkey,
  511. &signing_pkey,&signing_pkeylen)<0) {
  512. log(LOG_ERR,"dump_router_to_string(): write signing_pkey to string failed!");
  513. return 0;
  514. }
  515. signing_pkey_tag = "signing-key\n";
  516. }
  517. result = snprintf(s, maxlen, "router %s %d %d %d %d\n%s%s%s",
  518. router->address,
  519. router->or_port,
  520. router->ap_port,
  521. router->dir_port,
  522. router->bandwidth,
  523. pkey,
  524. signing_pkey_tag, signing_pkey);
  525. free(pkey);
  526. if (*signing_pkey)
  527. free(signing_pkey);
  528. if(result < 0 || result > maxlen) {
  529. /* apparently different glibcs do different things on snprintf error.. so check both */
  530. return -1;
  531. }
  532. written = result;
  533. for(tmpe=router->exit_policy; tmpe; tmpe=tmpe->next) {
  534. result = snprintf(s+written, maxlen-written, "%s %s:%s\n",
  535. tmpe->policy_type == EXIT_POLICY_ACCEPT ? "accept" : "reject",
  536. tmpe->address, tmpe->port);
  537. if(result < 0 || result+written > maxlen) {
  538. /* apparently different glibcs do different things on snprintf error.. so check both */
  539. return -1;
  540. }
  541. written += result;
  542. }
  543. if(written > maxlen-2) {
  544. return -1; /* not enough space for \n\0 */
  545. }
  546. /* XXX count fenceposts here. They're probably wrong. In general,
  547. * we need a better way to handle overruns in building the directory
  548. * string, and a better way to handle directory string size in general. */
  549. /* include a last '\n' */
  550. s[written] = '\n';
  551. s[written+1] = 0;
  552. return written+1;
  553. }
  554. static int
  555. build_directory(directory_t *dir) {
  556. routerinfo_t **routers = NULL;
  557. connection_t *conn;
  558. routerinfo_t *router;
  559. int i, n = 0;
  560. routers = (routerinfo_t **)tor_malloc(sizeof(routerinfo_t*) * (nfds+1));
  561. if (my_routerinfo) {
  562. log(LOG_INFO, "build_directory(): adding self (%s:%d)",
  563. my_routerinfo->address, my_routerinfo->or_port);
  564. routers[n++] = my_routerinfo;
  565. }
  566. for(i = 0; i<nfds; ++i) {
  567. conn = connection_array[i];
  568. if(conn->type != CONN_TYPE_OR)
  569. continue; /* we only want to list ORs */
  570. if(conn->state != OR_CONN_STATE_OPEN)
  571. continue; /* we only want to list ones that successfully handshaked */
  572. router = router_get_by_addr_port(conn->addr,conn->port);
  573. if(!router) {
  574. /* XXX this legitimately happens when conn is an OP. How to detect this? */
  575. log(LOG_ERR,"build_directory(): couldn't find router %d:%d!",
  576. conn->addr,conn->port);
  577. continue;
  578. }
  579. log(LOG_INFO, "build_directory(): adding router (%s:%d)",
  580. router->address, router->or_port);
  581. routers[n++] = router;
  582. }
  583. dir->routers = routers;
  584. dir->n_routers = n;
  585. return 0;
  586. }
  587. int
  588. dump_signed_directory_to_string(char *s, int maxlen,
  589. crypto_pk_env_t *private_key)
  590. {
  591. directory_t dir;
  592. if (build_directory(&dir)) {
  593. log(LOG_ERR,"dump_signed_directory_to_string(): build_directory failed.");
  594. return -1;
  595. }
  596. return dump_signed_directory_to_string_impl(s, maxlen, &dir, private_key);
  597. }
  598. int
  599. dump_signed_directory_to_string_impl(char *s, int maxlen, directory_t *dir,
  600. crypto_pk_env_t *private_key)
  601. {
  602. char *cp, *eos;
  603. char digest[20];
  604. char signature[128];
  605. int i, written;
  606. routerinfo_t *router;
  607. eos = s+maxlen;
  608. strncpy(s,
  609. "signed-directory\n"
  610. "recommended-software "
  611. RECOMMENDED_SOFTWARE_VERSIONS
  612. "\n"
  613. , maxlen);
  614. i = strlen(s);
  615. cp = s+i;
  616. for (i = 0; i < dir->n_routers; ++i) {
  617. router = dir->routers[i];
  618. written = dump_router_to_string(cp, eos-cp, router);
  619. if(written < 0) {
  620. log(LOG_ERR,"dump_signed_directory_to_string(): tried to exceed string length.");
  621. cp[maxlen-1] = 0; /* make sure it's null terminated */
  622. free(dir->routers);
  623. return -1;
  624. }
  625. cp += written;
  626. }
  627. free(dir->routers); /* not needed anymore */
  628. /* These multiple strlen calls are inefficient, but dwarfed by the RSA
  629. signature.
  630. */
  631. i = strlen(s);
  632. strncat(s, "directory-signature\n", maxlen-i);
  633. i = strlen(s);
  634. cp = s + i;
  635. if (crypto_SHA_digest(s, i, digest)) {
  636. log(LOG_ERR,"dump_signed_directory_to_string(): couldn't compute digest");
  637. return -1;
  638. }
  639. if (crypto_pk_private_sign(private_key, digest, 20, signature) < 0) {
  640. log(LOG_ERR,"dump_signed_directory_to_string(): couldn't sign digest");
  641. return -1;
  642. }
  643. strncpy(cp,
  644. "-----BEGIN SIGNATURE-----\n", maxlen-i);
  645. i = strlen(s);
  646. cp = s+i;
  647. if (base64_encode(cp, maxlen-i, signature, 128) < 0) {
  648. log_fn(LOG_ERR," couldn't base64-encode signature");
  649. return -1;
  650. }
  651. i = strlen(s);
  652. cp = s+i;
  653. strncat(cp, "-----END SIGNATURE-----\n", maxlen-i);
  654. i = strlen(s);
  655. if (i == maxlen) {
  656. log(LOG_ERR,"dump_signed_directory_to_string(): tried to exceed string length.");
  657. return -1;
  658. }
  659. return 0;
  660. }
  661. char *router_get_my_descriptor(void) {
  662. return "this is bob's descriptor";
  663. }
  664. void daemonize(void) {
  665. #ifndef MS_WINDOWS
  666. /* Fork; parent exits. */
  667. if (fork())
  668. exit(0);
  669. /* Create new session; make sure we never get a terminal */
  670. setsid();
  671. if (fork())
  672. exit(0);
  673. chdir("/");
  674. umask(000);
  675. fclose(stdin);
  676. fclose(stdout); /* XXX Nick: this closes our log, right? is it safe to leave this open? */
  677. fclose(stderr);
  678. #endif
  679. }
  680. int tor_main(int argc, char *argv[]) {
  681. int retval = 0;
  682. if(getconfig(argc,argv,&options))
  683. exit(1);
  684. log_set_severity(options.loglevel); /* assign logging severity level from options */
  685. global_read_bucket = options.TotalBandwidth; /* start it at 1 second of traffic */
  686. if(options.Daemon)
  687. daemonize();
  688. if(options.OnionRouter) { /* only spawn dns handlers if we're a router */
  689. dns_init(); /* initialize the dns resolve tree, and spawn workers */
  690. }
  691. #ifndef MS_WINDOWS /* do signal stuff only on unix */
  692. signal (SIGINT, catch); /* catch kills so we can exit cleanly */
  693. signal (SIGTERM, catch);
  694. signal (SIGUSR1, catch); /* to dump stats to stdout */
  695. signal (SIGHUP, catch); /* to reload directory */
  696. signal (SIGCHLD, catch); /* for exiting dns/cpu workers */
  697. #endif /* signal stuff */
  698. crypto_global_init();
  699. crypto_seed_rng();
  700. retval = do_main_loop();
  701. crypto_global_cleanup();
  702. return retval;
  703. }
  704. /*
  705. Local Variables:
  706. mode:c
  707. indent-tabs-mode:nil
  708. c-basic-offset:2
  709. End:
  710. */