main.c 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068
  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. static int init_descriptor(void);
  8. /********* START VARIABLES **********/
  9. extern char *conn_type_to_string[];
  10. extern char *conn_state_to_string[][15];
  11. or_options_t options; /* command-line and config-file options */
  12. int global_read_bucket; /* max number of bytes I can read this second */
  13. static connection_t *connection_array[MAXCONNECTIONS] =
  14. { NULL };
  15. static struct pollfd poll_array[MAXCONNECTIONS];
  16. static int nfds=0; /* number of connections currently active */
  17. #ifndef MS_WINDOWS /* do signal stuff only on unix */
  18. static int please_dumpstats=0; /* whether we should dump stats during the loop */
  19. static int please_reset =0; /* whether we just got a sighup */
  20. static int please_reap_children=0; /* whether we should waitpid for exited children*/
  21. #endif /* signal stuff */
  22. /* private keys */
  23. static crypto_pk_env_t *onionkey=NULL;
  24. static crypto_pk_env_t *linkkey=NULL;
  25. static crypto_pk_env_t *identitykey=NULL;
  26. routerinfo_t *my_routerinfo=NULL;
  27. /********* END VARIABLES ************/
  28. void set_onion_key(crypto_pk_env_t *k) {
  29. onionkey = k;
  30. }
  31. crypto_pk_env_t *get_onion_key(void) {
  32. assert(onionkey);
  33. return onionkey;
  34. }
  35. void set_link_key(crypto_pk_env_t *k)
  36. {
  37. linkkey = k;
  38. }
  39. crypto_pk_env_t *get_link_key(void)
  40. {
  41. assert(linkkey);
  42. return linkkey;
  43. }
  44. void set_identity_key(crypto_pk_env_t *k) {
  45. identitykey = k;
  46. }
  47. crypto_pk_env_t *get_identity_key(void) {
  48. assert(identitykey);
  49. return identitykey;
  50. }
  51. /****************************************************************************
  52. *
  53. * This section contains accessors and other methods on the connection_array
  54. * and poll_array variables (which are global within this file and unavailable
  55. * outside it).
  56. *
  57. ****************************************************************************/
  58. int connection_add(connection_t *conn) {
  59. if(nfds >= options.MaxConn-1) {
  60. log(LOG_INFO,"connection_add(): failing because nfds is too high.");
  61. return -1;
  62. }
  63. conn->poll_index = nfds;
  64. connection_set_poll_socket(conn);
  65. connection_array[nfds] = conn;
  66. /* zero these out here, because otherwise we'll inherit values from the previously freed one */
  67. poll_array[nfds].events = 0;
  68. poll_array[nfds].revents = 0;
  69. nfds++;
  70. log(LOG_INFO,"connection_add(): new conn type %d, socket %d, nfds %d.",conn->type, conn->s, nfds);
  71. return 0;
  72. }
  73. void connection_set_poll_socket(connection_t *conn) {
  74. poll_array[conn->poll_index].fd = conn->s;
  75. }
  76. int connection_remove(connection_t *conn) {
  77. int current_index;
  78. assert(conn);
  79. assert(nfds>0);
  80. log(LOG_INFO,"connection_remove(): removing socket %d, nfds now %d",conn->s, nfds-1);
  81. circuit_about_to_close_connection(conn); /* if it's an edge conn, remove it from the list
  82. * of conn's on this circuit. If it's not on an edge,
  83. * flush and send destroys for all circuits on this conn
  84. */
  85. current_index = conn->poll_index;
  86. if(current_index == nfds-1) { /* this is the end */
  87. nfds--;
  88. return 0;
  89. }
  90. /* we replace this one with the one at the end, then free it */
  91. nfds--;
  92. poll_array[current_index].fd = poll_array[nfds].fd;
  93. poll_array[current_index].events = poll_array[nfds].events;
  94. poll_array[current_index].revents = poll_array[nfds].revents;
  95. connection_array[current_index] = connection_array[nfds];
  96. connection_array[current_index]->poll_index = current_index;
  97. return 0;
  98. }
  99. connection_t *connection_twin_get_by_addr_port(uint32_t addr, uint16_t port) {
  100. /* Find a connection to the router described by addr and port,
  101. * or alternately any router which knows its key.
  102. * This connection *must* be in 'open' state.
  103. * If not, return NULL.
  104. */
  105. int i;
  106. connection_t *conn;
  107. routerinfo_t *router;
  108. /* first check if it's there exactly */
  109. conn = connection_exact_get_by_addr_port(addr,port);
  110. if(conn && connection_state_is_open(conn)) {
  111. log(LOG_INFO,"connection_twin_get_by_addr_port(): Found exact match.");
  112. return conn;
  113. }
  114. /* now check if any of the other open connections are a twin for this one */
  115. router = router_get_by_addr_port(addr,port);
  116. if(!router)
  117. return NULL;
  118. for(i=0;i<nfds;i++) {
  119. conn = connection_array[i];
  120. assert(conn);
  121. if(connection_state_is_open(conn) &&
  122. !conn->marked_for_close &&
  123. !crypto_pk_cmp_keys(conn->onion_pkey, router->onion_pkey)) {
  124. log(LOG_INFO,"connection_twin_get_by_addr_port(): Found twin (%s).",conn->address);
  125. return conn;
  126. }
  127. }
  128. /* guess not */
  129. return NULL;
  130. }
  131. connection_t *connection_exact_get_by_addr_port(uint32_t addr, uint16_t port) {
  132. int i;
  133. connection_t *conn;
  134. for(i=0;i<nfds;i++) {
  135. conn = connection_array[i];
  136. if(conn->addr == addr && conn->port == port && !conn->marked_for_close)
  137. return conn;
  138. }
  139. return NULL;
  140. }
  141. connection_t *connection_get_by_type(int type) {
  142. int i;
  143. connection_t *conn;
  144. for(i=0;i<nfds;i++) {
  145. conn = connection_array[i];
  146. if(conn->type == type && !conn->marked_for_close)
  147. return conn;
  148. }
  149. return NULL;
  150. }
  151. connection_t *connection_get_by_type_state(int type, int state) {
  152. int i;
  153. connection_t *conn;
  154. for(i=0;i<nfds;i++) {
  155. conn = connection_array[i];
  156. if(conn->type == type && conn->state == state && !conn->marked_for_close)
  157. return conn;
  158. }
  159. return NULL;
  160. }
  161. connection_t *connection_get_by_type_state_lastwritten(int type, int state) {
  162. int i;
  163. connection_t *conn, *best=NULL;
  164. for(i=0;i<nfds;i++) {
  165. conn = connection_array[i];
  166. if(conn->type == type && conn->state == state && !conn->marked_for_close)
  167. if(!best || conn->timestamp_lastwritten < best->timestamp_lastwritten)
  168. best = conn;
  169. }
  170. return best;
  171. }
  172. void connection_watch_events(connection_t *conn, short events) {
  173. assert(conn && conn->poll_index < nfds);
  174. poll_array[conn->poll_index].events = events;
  175. }
  176. int connection_is_reading(connection_t *conn) {
  177. return poll_array[conn->poll_index].events & POLLIN;
  178. }
  179. void connection_stop_reading(connection_t *conn) {
  180. assert(conn && conn->poll_index < nfds);
  181. log(LOG_DEBUG,"connection_stop_reading() called.");
  182. if(poll_array[conn->poll_index].events & POLLIN)
  183. poll_array[conn->poll_index].events -= POLLIN;
  184. }
  185. void connection_start_reading(connection_t *conn) {
  186. assert(conn && conn->poll_index < nfds);
  187. poll_array[conn->poll_index].events |= POLLIN;
  188. }
  189. void connection_stop_writing(connection_t *conn) {
  190. assert(conn && conn->poll_index < nfds);
  191. if(poll_array[conn->poll_index].events & POLLOUT)
  192. poll_array[conn->poll_index].events -= POLLOUT;
  193. }
  194. void connection_start_writing(connection_t *conn) {
  195. assert(conn && conn->poll_index < nfds);
  196. poll_array[conn->poll_index].events |= POLLOUT;
  197. }
  198. static void conn_read(int i) {
  199. connection_t *conn;
  200. if(!(poll_array[i].revents & (POLLIN|POLLHUP|POLLERR)))
  201. return; /* this conn doesn't want to read */
  202. /* see http://www.greenend.org.uk/rjk/2001/06/poll.html for
  203. * discussion of POLLIN vs POLLHUP */
  204. conn = connection_array[i];
  205. log_fn(LOG_DEBUG,"socket %d wants to read.",conn->s);
  206. assert_connection_ok(conn, time(NULL));
  207. if(
  208. /* XXX does POLLHUP also mean it's definitely broken? */
  209. #ifdef MS_WINDOWS
  210. (poll_array[i].revents & POLLERR) ||
  211. #endif
  212. connection_handle_read(conn) < 0)
  213. {
  214. /* this connection is broken. remove it */
  215. log_fn(LOG_INFO,"%s connection broken, removing.", conn_type_to_string[conn->type]);
  216. connection_remove(conn);
  217. connection_free(conn);
  218. if(i<nfds) { /* we just replaced the one at i with a new one. process it too. */
  219. conn_read(i);
  220. }
  221. } else assert_connection_ok(conn, time(NULL));
  222. }
  223. static void conn_write(int i) {
  224. connection_t *conn;
  225. if(!(poll_array[i].revents & POLLOUT))
  226. return; /* this conn doesn't want to write */
  227. conn = connection_array[i];
  228. log_fn(LOG_DEBUG,"socket %d wants to write.",conn->s);
  229. assert_connection_ok(conn, time(NULL));
  230. if(connection_handle_write(conn) < 0) { /* this connection is broken. remove it. */
  231. log_fn(LOG_DEBUG,"%s connection broken, removing.", conn_type_to_string[conn->type]);
  232. connection_remove(conn);
  233. connection_free(conn);
  234. if(i<nfds) { /* we just replaced the one at i with a new one. process it too. */
  235. conn_write(i);
  236. }
  237. } else assert_connection_ok(conn, time(NULL));
  238. }
  239. static void check_conn_marked(int i) {
  240. connection_t *conn;
  241. conn = connection_array[i];
  242. assert_connection_ok(conn, time(NULL));
  243. if(conn->marked_for_close) {
  244. log_fn(LOG_DEBUG,"Cleaning up connection.");
  245. if(conn->s >= 0) { /* might be an incomplete edge connection */
  246. /* FIXME there's got to be a better way to check for this -- and make other checks? */
  247. if(connection_speaks_cells(conn) && conn->state != OR_CONN_STATE_CONNECTING)
  248. flush_buf_tls(conn->tls, conn->outbuf, &conn->outbuf_flushlen);
  249. else
  250. flush_buf(conn->s, conn->outbuf, &conn->outbuf_flushlen);
  251. if(connection_wants_to_flush(conn)) /* not done flushing */
  252. log_fn(LOG_WARNING,"Conn (socket %d) still wants to flush. Losing %d bytes!",conn->s, (int)buf_datalen(conn->inbuf));
  253. }
  254. connection_remove(conn);
  255. connection_free(conn);
  256. if(i<nfds) { /* we just replaced the one at i with a new one.
  257. process it too. */
  258. check_conn_marked(i);
  259. }
  260. }
  261. }
  262. static int prepare_for_poll(void) {
  263. int i;
  264. connection_t *conn;
  265. struct timeval now; //soonest;
  266. static long current_second = 0; /* from previous calls to gettimeofday */
  267. static long time_to_fetch_directory = 0;
  268. static long time_to_new_circuit = 0;
  269. // int ms_until_conn;
  270. cell_t cell;
  271. circuit_t *circ;
  272. my_gettimeofday(&now);
  273. if(now.tv_sec > current_second) { /* the second has rolled over. check more stuff. */
  274. if(!options.DirPort) {
  275. if(time_to_fetch_directory < now.tv_sec) {
  276. /* it's time to fetch a new directory */
  277. /* NOTE directory servers do not currently fetch directories.
  278. * Hope this doesn't bite us later.
  279. */
  280. directory_initiate_command(router_pick_directory_server(),
  281. DIR_CONN_STATE_CONNECTING_FETCH);
  282. time_to_fetch_directory = now.tv_sec + options.DirFetchPeriod;
  283. }
  284. }
  285. if(options.APPort && time_to_new_circuit < now.tv_sec) {
  286. circuit_expire_unused_circuits();
  287. circuit_launch_new(-1); /* tell it to forget about previous failures */
  288. circ = circuit_get_newest_open();
  289. if(!circ || circ->dirty) {
  290. log_fn(LOG_INFO,"Youngest circuit %s; launching replacement.", circ ? "dirty" : "missing");
  291. circuit_launch_new(0); /* make an onion and lay the circuit */
  292. }
  293. time_to_new_circuit = now.tv_sec + options.NewCircuitPeriod;
  294. }
  295. if(global_read_bucket < 9*options.TotalBandwidth) {
  296. global_read_bucket += options.TotalBandwidth;
  297. log_fn(LOG_DEBUG,"global_read_bucket now %d.", global_read_bucket);
  298. }
  299. /* do housekeeping for each connection */
  300. for(i=0;i<nfds;i++) {
  301. conn = connection_array[i];
  302. if(connection_receiver_bucket_should_increase(conn)) {
  303. conn->receiver_bucket += conn->bandwidth;
  304. // log_fn(LOG_DEBUG,"Receiver bucket %d now %d.", i, conn->receiver_bucket);
  305. }
  306. if(conn->wants_to_read == 1 /* it's marked to turn reading back on now */
  307. && global_read_bucket > 0 /* and we're allowed to read */
  308. && conn->receiver_bucket != 0) { /* and either an edge conn or non-empty bucket */
  309. conn->wants_to_read = 0;
  310. connection_start_reading(conn);
  311. if(conn->wants_to_write == 1) {
  312. conn->wants_to_write = 0;
  313. connection_start_writing(conn);
  314. }
  315. }
  316. /* check connections to see whether we should send a keepalive, expire, or wait */
  317. if(!connection_speaks_cells(conn))
  318. continue; /* this conn type doesn't send cells */
  319. if(now.tv_sec >= conn->timestamp_lastwritten + options.KeepalivePeriod) {
  320. if((!options.OnionRouter && !circuit_get_by_conn(conn)) ||
  321. (!connection_state_is_open(conn))) {
  322. /* we're an onion proxy, with no circuits; or our handshake has expired. kill it. */
  323. log_fn(LOG_DEBUG,"Expiring connection to %d (%s:%d).",
  324. i,conn->address, conn->port);
  325. conn->marked_for_close = 1;
  326. } else {
  327. /* either a full router, or we've got a circuit. send a padding cell. */
  328. // log_fn(LOG_DEBUG,"Sending keepalive to (%s:%d)",
  329. // conn->address, conn->port);
  330. memset(&cell,0,sizeof(cell_t));
  331. cell.command = CELL_PADDING;
  332. if(connection_write_cell_to_buf(&cell, conn) < 0)
  333. conn->marked_for_close = 1;
  334. }
  335. }
  336. }
  337. /* blow away any connections that need to die. can't do this later
  338. * because we might open up a circuit and not realize it we're about to cull it.
  339. */
  340. for(i=0;i<nfds;i++)
  341. check_conn_marked(i);
  342. current_second = now.tv_sec; /* remember which second it is, for next time */
  343. }
  344. return (1000 - (now.tv_usec / 1000)); /* how many milliseconds til the next second? */
  345. }
  346. #define FN_ERROR -1
  347. #define FN_NOENT 0
  348. #define FN_FILE 1
  349. #define FN_DIR 2
  350. static int fn_exists(const char *fname)
  351. {
  352. struct stat st;
  353. if (stat(fname, &st)) {
  354. if (errno == ENOENT) {
  355. return FN_NOENT;
  356. }
  357. return FN_ERROR;
  358. }
  359. if (st.st_mode & S_IFDIR)
  360. return FN_DIR;
  361. else
  362. return FN_FILE;
  363. }
  364. static crypto_pk_env_t *init_key_from_file(const char *fname)
  365. {
  366. crypto_pk_env_t *prkey = NULL;
  367. int fd = -1;
  368. FILE *file = NULL;
  369. if (!(prkey = crypto_new_pk_env(CRYPTO_PK_RSA))) {
  370. log(LOG_ERR, "Error creating crypto environment.");
  371. goto error;
  372. }
  373. switch(fn_exists(fname)) {
  374. case FN_DIR:
  375. case FN_ERROR:
  376. log(LOG_ERR, "Can't read key from %s", fname);
  377. goto error;
  378. case FN_NOENT:
  379. log(LOG_INFO, "No key found in %s; generating fresh key.", fname);
  380. if (crypto_pk_generate_key(prkey)) {
  381. log(LOG_ERR, "Error generating key: %s", crypto_perror());
  382. goto error;
  383. }
  384. if (crypto_pk_check_key(prkey) <= 0) {
  385. log(LOG_ERR, "Generated key seems invalid");
  386. goto error;
  387. }
  388. log(LOG_INFO, "Generated key seems valid");
  389. fd = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0400);
  390. if (fd == -1) {
  391. log(LOG_ERR, "Can't open %s for writing", fname);
  392. goto error;
  393. }
  394. file = fdopen(fd, "w");
  395. if (!file) {
  396. log(LOG_ERR, "Can't fdopen %s for writing", fname);
  397. goto error;
  398. }
  399. if (crypto_pk_write_private_key_to_file(prkey, file) < 0) {
  400. log(LOG_ERR, "Can't write private key to %s", fname);
  401. goto error;
  402. }
  403. fclose(file);
  404. /* XXX fingerprint */
  405. return prkey;
  406. case FN_FILE:
  407. if (crypto_pk_read_private_key_from_filename(prkey, fname)) {
  408. log(LOG_ERR, "Error loading private key.");
  409. goto error;
  410. }
  411. return prkey;
  412. default:
  413. assert(0);
  414. }
  415. error:
  416. if (prkey)
  417. crypto_free_pk_env(prkey);
  418. if (fd >= 0 && !file)
  419. close(fd);
  420. if (file)
  421. fclose(file);
  422. return NULL;
  423. }
  424. static int init_keys(void)
  425. {
  426. char keydir[512];
  427. char fingerprint[FINGERPRINT_LEN+1];
  428. char *cp;
  429. crypto_pk_env_t *prkey;
  430. FILE *file;
  431. /* OP's don't need keys. Just initialize the TLS context.*/
  432. if (!options.OnionRouter && !options.DirPort) {
  433. if (tor_tls_context_new(NULL, 0, NULL)<0) {
  434. log_fn(LOG_ERR, "Error creating TLS context for OP.");
  435. return -1;
  436. }
  437. return 0;
  438. }
  439. assert(options.DataDirectory);
  440. if (strlen(options.DataDirectory) > (512-128)) {
  441. log_fn(LOG_ERR, "DataDirectory is too long.");
  442. return -1;
  443. }
  444. strcpy(keydir, options.DataDirectory);
  445. switch (fn_exists(keydir)) {
  446. case FN_NOENT:
  447. log_fn(LOG_ERR, "DataDirectory does not exist");
  448. return -1;
  449. case FN_ERROR:
  450. log_fn(LOG_ERR, "DataDirectory can't be read");
  451. return -1;
  452. case FN_FILE:
  453. log_fn(LOG_ERR, "DataDirectory is not a directory.");
  454. return -1;
  455. }
  456. strcat(keydir, "/keys");
  457. switch (fn_exists(keydir)) {
  458. case FN_NOENT:
  459. if (mkdir(keydir, 0700)) {
  460. log_fn(LOG_ERR, "Error making key directory.");
  461. return -1;
  462. }
  463. break;
  464. case FN_ERROR:
  465. log_fn(LOG_ERR, "Error reading key directory.");
  466. return -1;
  467. case FN_FILE:
  468. log_fn(LOG_ERR, "Key directory is not a directory.");
  469. return -1;
  470. case FN_DIR:
  471. chmod(keydir, 0700);
  472. break;
  473. }
  474. cp = keydir + strlen(keydir); /* End of string. */
  475. assert(!*cp);
  476. /* 1. Read identity key. Make it if none is found. */
  477. strcat(keydir, "/identity.key");
  478. prkey = init_key_from_file(keydir);
  479. if (!prkey) return -1;
  480. set_identity_key(prkey);
  481. /* 2. Read onion key. Make it if none is found. */
  482. *cp = '\0';
  483. strcat(keydir, "/onion.key");
  484. prkey = init_key_from_file(keydir);
  485. if (!prkey) return -1;
  486. set_onion_key(prkey);
  487. /* 3. Initialize link key and TLS context. */
  488. *cp = '\0';
  489. strcat(keydir, "/link.key");
  490. prkey = init_key_from_file(keydir);
  491. if (!prkey) return -1;
  492. set_link_key(prkey);
  493. if (tor_tls_context_new(prkey, 1, options.Nickname) < 0) {
  494. log_fn(LOG_ERR, "Error initializing TLS context");
  495. return -1;
  496. }
  497. /* 4. Dump router descriptor to 'router.desc' */
  498. /* Must be called after keys are initialized. */
  499. if (init_descriptor()<0) {
  500. log_fn(LOG_ERR, "Error initializing descriptor.");
  501. return -1;
  502. }
  503. strcpy(keydir, options.DataDirectory);
  504. strcat(keydir, "/router.desc");
  505. file = fopen(keydir, "w");
  506. if (!file) {
  507. log_fn(LOG_ERR, "Error opening %s for writing", keydir);
  508. return -1;
  509. }
  510. fputs(router_get_my_descriptor(), file);
  511. fclose(file);
  512. /* 5. Dump fingerprint to 'fingerprint' */
  513. strcpy(keydir, options.DataDirectory);
  514. strcat(keydir, "/fingerprint");
  515. file = fopen(keydir, "w");
  516. if (!file) {
  517. log_fn(LOG_ERR, "Error opening %s for writing", keydir);
  518. return -1;
  519. }
  520. if (crypto_pk_get_fingerprint(get_identity_key(), fingerprint)<0) {
  521. log_fn(LOG_ERR, "Error computing fingerprint");
  522. return -1;
  523. }
  524. fprintf(file, "%s %s\n", options.Nickname, fingerprint);
  525. fclose(file);
  526. return 0;
  527. }
  528. static int do_main_loop(void) {
  529. int i;
  530. int timeout;
  531. int poll_result;
  532. /* load the routers file */
  533. if(router_get_list_from_file(options.RouterFile) < 0) {
  534. log_fn(LOG_ERR,"Error loading router list.");
  535. return -1;
  536. }
  537. /* load the private keys, if we're supposed to have them, and set up the
  538. * TLS context. */
  539. if (init_keys() < 0) {
  540. log_fn(LOG_ERR,"Error initializing keys; exiting");
  541. return -1;
  542. }
  543. if(options.OnionRouter) {
  544. cpu_init(); /* launch cpuworkers. Need to do this *after* we've read the private key. */
  545. }
  546. /* start up the necessary connections based on which ports are
  547. * non-zero. This is where we try to connect to all the other ORs,
  548. * and start the listeners.
  549. */
  550. retry_all_connections((uint16_t) options.ORPort,
  551. (uint16_t) options.APPort,
  552. (uint16_t) options.DirPort);
  553. for(;;) {
  554. #ifndef MS_WIN32 /* do signal stuff only on unix */
  555. if(please_dumpstats) {
  556. dumpstats();
  557. please_dumpstats = 0;
  558. }
  559. if(please_reset) {
  560. /* fetch a new directory */
  561. if(options.DirPort) {
  562. if(router_get_list_from_file(options.RouterFile) < 0) {
  563. log(LOG_ERR,"Error reloading router list. Continuing with old list.");
  564. }
  565. } else {
  566. directory_initiate_command(router_pick_directory_server(), DIR_CONN_STATE_CONNECTING_FETCH);
  567. }
  568. /* close and reopen the log files */
  569. reset_logs();
  570. please_reset = 0;
  571. }
  572. if(please_reap_children) {
  573. while(waitpid(-1,NULL,WNOHANG)) ; /* keep reaping until no more zombies */
  574. please_reap_children = 0;
  575. }
  576. #endif /* signal stuff */
  577. timeout = prepare_for_poll();
  578. /* poll until we have an event, or the second ends */
  579. poll_result = poll(poll_array, nfds, timeout);
  580. #if 0 /* let catch() handle things like ^c, and otherwise don't worry about it */
  581. if(poll_result < 0) {
  582. log(LOG_ERR,"do_main_loop(): poll failed.");
  583. if(errno != EINTR) /* let the program survive things like ^z */
  584. return -1;
  585. }
  586. #endif
  587. if(poll_result > 0) { /* we have at least one connection to deal with */
  588. /* do all the reads and errors first, so we can detect closed sockets */
  589. for(i=0;i<nfds;i++)
  590. conn_read(i); /* this also blows away broken connections */
  591. /* then do the writes */
  592. for(i=0;i<nfds;i++)
  593. conn_write(i);
  594. /* any of the conns need to be closed now? */
  595. for(i=0;i<nfds;i++)
  596. check_conn_marked(i);
  597. }
  598. /* refilling buckets and sending cells happens at the beginning of the
  599. * next iteration of the loop, inside prepare_for_poll()
  600. */
  601. }
  602. }
  603. static void catch(int the_signal) {
  604. #ifndef MS_WIN32 /* do signal stuff only on unix */
  605. switch(the_signal) {
  606. // case SIGABRT:
  607. case SIGTERM:
  608. case SIGINT:
  609. log(LOG_NOTICE,"Catching signal %d, exiting cleanly.", the_signal);
  610. exit(0);
  611. case SIGHUP:
  612. please_reset = 1;
  613. break;
  614. case SIGUSR1:
  615. please_dumpstats = 1;
  616. break;
  617. case SIGCHLD:
  618. please_reap_children = 1;
  619. break;
  620. default:
  621. log(LOG_ERR,"Caught signal %d that we can't handle??", the_signal);
  622. }
  623. #endif /* signal stuff */
  624. }
  625. static void dumpstats(void) { /* dump stats to stdout */
  626. int i;
  627. connection_t *conn;
  628. struct timeval now;
  629. printf("Dumping stats:\n");
  630. my_gettimeofday(&now);
  631. for(i=0;i<nfds;i++) {
  632. conn = connection_array[i];
  633. printf("Conn %d (socket %d) type %d (%s), state %d (%s), created %ld secs ago\n",
  634. i, conn->s, conn->type, conn_type_to_string[conn->type],
  635. conn->state, conn_state_to_string[conn->type][conn->state], now.tv_sec - conn->timestamp_created);
  636. if(!connection_is_listener(conn)) {
  637. printf("Conn %d is to '%s:%d'.\n",i,conn->address, conn->port);
  638. printf("Conn %d: %d bytes waiting on inbuf (last read %ld secs ago)\n",i,
  639. (int)buf_datalen(conn->inbuf),
  640. now.tv_sec - conn->timestamp_lastread);
  641. printf("Conn %d: %d bytes waiting on outbuf (last written %ld secs ago)\n",i,(int)buf_datalen(conn->outbuf),
  642. now.tv_sec - conn->timestamp_lastwritten);
  643. }
  644. circuit_dump_by_conn(conn); /* dump info about all the circuits using this conn */
  645. printf("\n");
  646. }
  647. }
  648. int dump_router_to_string(char *s, int maxlen, routerinfo_t *router,
  649. crypto_pk_env_t *ident_key) {
  650. char *onion_pkey;
  651. char *link_pkey;
  652. char *identity_pkey;
  653. char digest[20];
  654. char signature[128];
  655. int onion_pkeylen, link_pkeylen, identity_pkeylen;
  656. int written;
  657. int result=0;
  658. struct exit_policy_t *tmpe;
  659. if(crypto_pk_write_public_key_to_string(router->onion_pkey,
  660. &onion_pkey,&onion_pkeylen)<0) {
  661. log_fn(LOG_ERR,"write onion_pkey to string failed!");
  662. return -1;
  663. }
  664. if(crypto_pk_write_public_key_to_string(router->identity_pkey,
  665. &identity_pkey,&identity_pkeylen)<0) {
  666. log_fn(LOG_ERR,"write identity_pkey to string failed!");
  667. return -1;
  668. }
  669. if(crypto_pk_write_public_key_to_string(router->link_pkey,
  670. &link_pkey,&link_pkeylen)<0) {
  671. log_fn(LOG_ERR,"write link_pkey to string failed!");
  672. return -1;
  673. }
  674. result = snprintf(s, maxlen,
  675. "router %s %d %d %d %d\nonion-key\n%s"
  676. "link-key\n%s"
  677. "signing-key\n%s",
  678. router->address,
  679. router->or_port,
  680. router->ap_port,
  681. router->dir_port,
  682. router->bandwidth,
  683. onion_pkey, link_pkey, identity_pkey);
  684. free(onion_pkey);
  685. free(link_pkey);
  686. free(identity_pkey);
  687. if(result < 0 || result > maxlen) {
  688. /* apparently different glibcs do different things on snprintf error.. so check both */
  689. return -1;
  690. }
  691. written = result;
  692. for(tmpe=router->exit_policy; tmpe; tmpe=tmpe->next) {
  693. result = snprintf(s+written, maxlen-written, "%s %s:%s\n",
  694. tmpe->policy_type == EXIT_POLICY_ACCEPT ? "accept" : "reject",
  695. tmpe->address, tmpe->port);
  696. if(result < 0 || result+written > maxlen) {
  697. /* apparently different glibcs do different things on snprintf error.. so check both */
  698. return -1;
  699. }
  700. written += result;
  701. }
  702. if (written > maxlen-256) /* Not enough room for signature. */
  703. return -1;
  704. strcat(s+written, "router-signature\n");
  705. written += strlen(s+written);
  706. s[written] = '\0';
  707. if (router_get_router_hash(s, digest) < 0)
  708. return -1;
  709. if (crypto_pk_private_sign(ident_key, digest, 20, signature) < 0) {
  710. log_fn(LOG_ERR, "Error signing digest");
  711. return -1;
  712. }
  713. strcat(s+written, "-----BEGIN SIGNATURE-----\n");
  714. written += strlen(s+written);
  715. if (base64_encode(s+written, maxlen-written, signature, 128) < 0) {
  716. log_fn(LOG_ERR, "Couldn't base64-encode signature");
  717. }
  718. written += strlen(s+written);
  719. strcat(s+written, "-----END SIGNATURE-----\n");
  720. written += strlen(s+written);
  721. if (written > maxlen-2)
  722. return -1;
  723. /* include a last '\n' */
  724. s[written] = '\n';
  725. s[written+1] = 0;
  726. return written+1;
  727. }
  728. static int
  729. build_directory(directory_t *dir) {
  730. routerinfo_t **routers = NULL;
  731. connection_t *conn;
  732. routerinfo_t *router;
  733. int i, n = 0;
  734. routers = (routerinfo_t **)tor_malloc(sizeof(routerinfo_t*) * (nfds+1));
  735. if (my_routerinfo) {
  736. log(LOG_INFO, "build_directory(): adding self (%s:%d)",
  737. my_routerinfo->address, my_routerinfo->or_port);
  738. routers[n++] = my_routerinfo;
  739. }
  740. for(i = 0; i<nfds; ++i) {
  741. conn = connection_array[i];
  742. if(conn->type != CONN_TYPE_OR)
  743. continue; /* we only want to list ORs */
  744. if(conn->state != OR_CONN_STATE_OPEN)
  745. continue; /* we only want to list ones that successfully handshaked */
  746. router = router_get_by_addr_port(conn->addr,conn->port);
  747. if(!router) {
  748. /* XXX this legitimately happens when conn is an OP. How to detect this? */
  749. log(LOG_ERR,"build_directory(): couldn't find router %d:%d!",
  750. conn->addr,conn->port);
  751. continue;
  752. }
  753. log(LOG_INFO, "build_directory(): adding router (%s:%d)",
  754. router->address, router->or_port);
  755. routers[n++] = router;
  756. }
  757. dir->routers = routers;
  758. dir->n_routers = n;
  759. return 0;
  760. }
  761. int
  762. dump_signed_directory_to_string(char *s, int maxlen,
  763. crypto_pk_env_t *private_key)
  764. {
  765. directory_t dir;
  766. if (build_directory(&dir)) {
  767. log(LOG_ERR,"dump_signed_directory_to_string(): build_directory failed.");
  768. return -1;
  769. }
  770. return dump_signed_directory_to_string_impl(s, maxlen, &dir, private_key);
  771. }
  772. int
  773. dump_signed_directory_to_string_impl(char *s, int maxlen, directory_t *dir,
  774. crypto_pk_env_t *private_key)
  775. {
  776. char *cp, *eos;
  777. char digest[20];
  778. char signature[128];
  779. int i, written;
  780. routerinfo_t *router;
  781. eos = s+maxlen;
  782. strncpy(s,
  783. "signed-directory\n"
  784. "recommended-software "
  785. RECOMMENDED_SOFTWARE_VERSIONS
  786. "\n"
  787. , maxlen);
  788. i = strlen(s);
  789. cp = s+i;
  790. for (i = 0; i < dir->n_routers; ++i) {
  791. router = dir->routers[i];
  792. /* XXX This is wrong; we shouldn't sign routers, but rather propagate
  793. * XXX the original router blocks, unaltered.
  794. */
  795. written = dump_router_to_string(cp, eos-cp, router, private_key);
  796. if(written < 0) {
  797. log(LOG_ERR,"dump_signed_directory_to_string(): tried to exceed string length.");
  798. cp[maxlen-1] = 0; /* make sure it's null terminated */
  799. free(dir->routers);
  800. return -1;
  801. }
  802. cp += written;
  803. }
  804. free(dir->routers); /* not needed anymore */
  805. /* These multiple strlen calls are inefficient, but dwarfed by the RSA
  806. signature.
  807. */
  808. i = strlen(s);
  809. strncat(s, "directory-signature\n", maxlen-i);
  810. i = strlen(s);
  811. cp = s + i;
  812. if (crypto_SHA_digest(s, i, digest)) {
  813. log(LOG_ERR,"dump_signed_directory_to_string(): couldn't compute digest");
  814. return -1;
  815. }
  816. if (crypto_pk_private_sign(private_key, digest, 20, signature) < 0) {
  817. log(LOG_ERR,"dump_signed_directory_to_string(): couldn't sign digest");
  818. return -1;
  819. }
  820. strncpy(cp,
  821. "-----BEGIN SIGNATURE-----\n", maxlen-i);
  822. i = strlen(s);
  823. cp = s+i;
  824. if (base64_encode(cp, maxlen-i, signature, 128) < 0) {
  825. log_fn(LOG_ERR," couldn't base64-encode signature");
  826. return -1;
  827. }
  828. i = strlen(s);
  829. cp = s+i;
  830. strncat(cp, "-----END SIGNATURE-----\n", maxlen-i);
  831. i = strlen(s);
  832. if (i == maxlen) {
  833. log(LOG_ERR,"dump_signed_directory_to_string(): tried to exceed string length.");
  834. return -1;
  835. }
  836. return 0;
  837. }
  838. static char descriptor[8192];
  839. /* XXX should this replace my_routerinfo? */
  840. static routerinfo_t *desc_routerinfo;
  841. const char *router_get_my_descriptor(void) {
  842. return descriptor;
  843. }
  844. static int init_descriptor(void) {
  845. routerinfo_t *ri;
  846. ri = tor_malloc(sizeof(routerinfo_t));
  847. ri->address = strdup("XXXXXXX"); /*XXX*/
  848. ri->nickname = strdup(options.Nickname);
  849. /* No need to set addr. ???? */
  850. ri->or_port = options.ORPort;
  851. ri->ap_port = options.APPort;
  852. ri->dir_port = options.DirPort;
  853. ri->onion_pkey = crypto_pk_dup_key(get_onion_key());
  854. ri->link_pkey = crypto_pk_dup_key(get_link_key());
  855. ri->identity_pkey = crypto_pk_dup_key(get_identity_key());
  856. ri->bandwidth = options.TotalBandwidth;
  857. ri->exit_policy = NULL; /* XXX implement this. */
  858. if (desc_routerinfo)
  859. routerinfo_free(desc_routerinfo);
  860. desc_routerinfo = ri;
  861. if (dump_router_to_string(descriptor, 8192, ri, get_identity_key())<0) {
  862. log_fn(LOG_ERR, "Couldn't dump router to string.");
  863. return -1;
  864. }
  865. return 0;
  866. }
  867. void daemonize(void) {
  868. #ifndef MS_WINDOWS
  869. /* Fork; parent exits. */
  870. if (fork())
  871. exit(0);
  872. /* Create new session; make sure we never get a terminal */
  873. setsid();
  874. if (fork())
  875. exit(0);
  876. chdir("/");
  877. umask(000);
  878. fclose(stdin);
  879. fclose(stdout); /* XXX Nick: this closes our log, right? is it safe to leave this open? */
  880. fclose(stderr);
  881. #endif
  882. }
  883. int tor_main(int argc, char *argv[]) {
  884. int retval = 0;
  885. if(getconfig(argc,argv,&options))
  886. exit(1);
  887. log_set_severity(options.loglevel); /* assign logging severity level from options */
  888. global_read_bucket = options.TotalBandwidth; /* start it at 1 second of traffic */
  889. if(options.Daemon)
  890. daemonize();
  891. if(options.OnionRouter) { /* only spawn dns handlers if we're a router */
  892. dns_init(); /* initialize the dns resolve tree, and spawn workers */
  893. }
  894. #ifndef MS_WINDOWS /* do signal stuff only on unix */
  895. signal (SIGINT, catch); /* catch kills so we can exit cleanly */
  896. signal (SIGTERM, catch);
  897. signal (SIGUSR1, catch); /* to dump stats to stdout */
  898. signal (SIGHUP, catch); /* to reload directory */
  899. signal (SIGCHLD, catch); /* for exiting dns/cpu workers */
  900. #endif /* signal stuff */
  901. crypto_global_init();
  902. crypto_seed_rng();
  903. retval = do_main_loop();
  904. crypto_global_cleanup();
  905. return retval;
  906. }
  907. /*
  908. Local Variables:
  909. mode:c
  910. indent-tabs-mode:nil
  911. c-basic-offset:2
  912. End:
  913. */