main.c 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977
  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[][_CONN_TYPE_MAX+1];
  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_WARNING,"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 = connection_array[i];
  200. /* see http://www.greenend.org.uk/rjk/2001/06/poll.html for
  201. * discussion of POLLIN vs POLLHUP */
  202. if(!(poll_array[i].revents & (POLLIN|POLLHUP|POLLERR)))
  203. if(!connection_speaks_cells(conn) ||
  204. conn->state != OR_CONN_STATE_OPEN ||
  205. !connection_is_reading(conn) ||
  206. !tor_tls_get_pending_bytes(conn->tls))
  207. return; /* this conn should not read */
  208. log_fn(LOG_DEBUG,"socket %d wants to read.",conn->s);
  209. assert_connection_ok(conn, time(NULL));
  210. if(
  211. /* XXX does POLLHUP also mean it's definitely broken? */
  212. #ifdef MS_WINDOWS
  213. (poll_array[i].revents & POLLERR) ||
  214. #endif
  215. connection_handle_read(conn) < 0)
  216. {
  217. /* this connection is broken. remove it */
  218. log_fn(LOG_INFO,"%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_read(i);
  223. }
  224. } else assert_connection_ok(conn, time(NULL));
  225. }
  226. static void conn_write(int i) {
  227. connection_t *conn;
  228. if(!(poll_array[i].revents & POLLOUT))
  229. return; /* this conn doesn't want to write */
  230. conn = connection_array[i];
  231. log_fn(LOG_DEBUG,"socket %d wants to write.",conn->s);
  232. assert_connection_ok(conn, time(NULL));
  233. if(connection_handle_write(conn) < 0) { /* this connection is broken. remove it. */
  234. log_fn(LOG_INFO,"%s connection broken, removing.", conn_type_to_string[conn->type]);
  235. connection_remove(conn);
  236. connection_free(conn);
  237. if(i<nfds) { /* we just replaced the one at i with a new one. process it too. */
  238. conn_write(i);
  239. }
  240. } else assert_connection_ok(conn, time(NULL));
  241. }
  242. static void check_conn_marked(int i) {
  243. connection_t *conn;
  244. conn = connection_array[i];
  245. assert_connection_ok(conn, time(NULL));
  246. if(conn->marked_for_close) {
  247. log_fn(LOG_INFO,"Cleaning up connection (fd %d).",conn->s);
  248. if(conn->s >= 0) { /* might be an incomplete edge connection */
  249. /* FIXME there's got to be a better way to check for this -- and make other checks? */
  250. if(connection_speaks_cells(conn)) {
  251. if(conn->state == OR_CONN_STATE_OPEN)
  252. flush_buf_tls(conn->tls, conn->outbuf, &conn->outbuf_flushlen);
  253. } else {
  254. flush_buf(conn->s, conn->outbuf, &conn->outbuf_flushlen);
  255. }
  256. if(connection_wants_to_flush(conn)) /* not done flushing */
  257. log_fn(LOG_WARNING,"Conn (socket %d) still wants to flush. Losing %d bytes!",conn->s, (int)buf_datalen(conn->inbuf));
  258. }
  259. connection_remove(conn);
  260. connection_free(conn);
  261. if(i<nfds) { /* we just replaced the one at i with a new one.
  262. process it too. */
  263. check_conn_marked(i);
  264. }
  265. }
  266. }
  267. static int prepare_for_poll(void) {
  268. int i;
  269. int timeout;
  270. connection_t *conn;
  271. struct timeval now;
  272. static long current_second = 0; /* from previous calls to gettimeofday */
  273. static long time_to_fetch_directory = 0;
  274. static long time_to_new_circuit = 0;
  275. // int ms_until_conn;
  276. cell_t cell;
  277. circuit_t *circ;
  278. my_gettimeofday(&now);
  279. timeout = (1000 - (now.tv_usec / 1000)); /* how many milliseconds til the next second? */
  280. if(now.tv_sec > current_second) { /* the second has rolled over. check more stuff. */
  281. if(!options.DirPort) {
  282. if(time_to_fetch_directory < now.tv_sec) {
  283. /* it's time to fetch a new directory */
  284. /* NOTE directory servers do not currently fetch directories.
  285. * Hope this doesn't bite us later.
  286. */
  287. directory_initiate_command(router_pick_directory_server(),
  288. DIR_CONN_STATE_CONNECTING_FETCH);
  289. time_to_fetch_directory = now.tv_sec + options.DirFetchPeriod;
  290. }
  291. }
  292. if(options.APPort && time_to_new_circuit < now.tv_sec) {
  293. circuit_expire_unused_circuits();
  294. circuit_launch_new(-1); /* tell it to forget about previous failures */
  295. circ = circuit_get_newest_open();
  296. if(!circ || circ->dirty) {
  297. log_fn(LOG_INFO,"Youngest circuit %s; launching replacement.", circ ? "dirty" : "missing");
  298. circuit_launch_new(0); /* make an onion and lay the circuit */
  299. }
  300. time_to_new_circuit = now.tv_sec + options.NewCircuitPeriod;
  301. }
  302. if(global_read_bucket < 9*options.TotalBandwidth) {
  303. global_read_bucket += options.TotalBandwidth;
  304. log_fn(LOG_DEBUG,"global_read_bucket now %d.", global_read_bucket);
  305. }
  306. /* do housekeeping for each connection */
  307. for(i=0;i<nfds;i++) {
  308. conn = connection_array[i];
  309. if(connection_receiver_bucket_should_increase(conn)) {
  310. conn->receiver_bucket += conn->bandwidth;
  311. // log_fn(LOG_DEBUG,"Receiver bucket %d now %d.", i, conn->receiver_bucket);
  312. }
  313. if(conn->wants_to_read == 1 /* it's marked to turn reading back on now */
  314. && global_read_bucket > 0 /* and we're allowed to read */
  315. && (!connection_speaks_cells(conn) || conn->receiver_bucket > 0)) {
  316. /* and either a non-cell conn or a cell conn with non-empty bucket */
  317. conn->wants_to_read = 0;
  318. connection_start_reading(conn);
  319. if(conn->wants_to_write == 1) {
  320. conn->wants_to_write = 0;
  321. connection_start_writing(conn);
  322. }
  323. }
  324. /* check connections to see whether we should send a keepalive, expire, or wait */
  325. if(!connection_speaks_cells(conn))
  326. continue; /* this conn type doesn't send cells */
  327. if(connection_state_is_open(conn) && tor_tls_get_pending_bytes(conn->tls))
  328. timeout = 0; /* has pending bytes to read; don't let poll wait. */
  329. if(now.tv_sec >= conn->timestamp_lastwritten + options.KeepalivePeriod) {
  330. if((!options.OnionRouter && !circuit_get_by_conn(conn)) ||
  331. (!connection_state_is_open(conn))) {
  332. /* we're an onion proxy, with no circuits; or our handshake has expired. kill it. */
  333. log_fn(LOG_INFO,"Expiring connection to %d (%s:%d).",
  334. i,conn->address, conn->port);
  335. conn->marked_for_close = 1;
  336. } else {
  337. /* either a full router, or we've got a circuit. send a padding cell. */
  338. // log_fn(LOG_DEBUG,"Sending keepalive to (%s:%d)",
  339. // conn->address, conn->port);
  340. memset(&cell,0,sizeof(cell_t));
  341. cell.command = CELL_PADDING;
  342. if(connection_write_cell_to_buf(&cell, conn) < 0)
  343. conn->marked_for_close = 1;
  344. }
  345. }
  346. }
  347. /* blow away any connections that need to die. can't do this later
  348. * because we might open up a circuit and not realize we're about to cull
  349. * the connection it's running over.
  350. */
  351. for(i=0;i<nfds;i++)
  352. check_conn_marked(i);
  353. current_second = now.tv_sec; /* remember which second it is, for next time */
  354. }
  355. return timeout;
  356. }
  357. static crypto_pk_env_t *init_key_from_file(const char *fname)
  358. {
  359. crypto_pk_env_t *prkey = NULL;
  360. int fd = -1;
  361. FILE *file = NULL;
  362. if (!(prkey = crypto_new_pk_env(CRYPTO_PK_RSA))) {
  363. log(LOG_ERR, "Error creating crypto environment.");
  364. goto error;
  365. }
  366. switch(file_status(fname)) {
  367. case FN_DIR:
  368. case FN_ERROR:
  369. log(LOG_ERR, "Can't read key from %s", fname);
  370. goto error;
  371. case FN_NOENT:
  372. log(LOG_INFO, "No key found in %s; generating fresh key.", fname);
  373. if (crypto_pk_generate_key(prkey)) {
  374. log(LOG_ERR, "Error generating key: %s", crypto_perror());
  375. goto error;
  376. }
  377. if (crypto_pk_check_key(prkey) <= 0) {
  378. log(LOG_ERR, "Generated key seems invalid");
  379. goto error;
  380. }
  381. log(LOG_INFO, "Generated key seems valid");
  382. if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
  383. log(LOG_ERR, "Couldn't write generated key to %s.", fname);
  384. goto error;
  385. }
  386. return prkey;
  387. case FN_FILE:
  388. if (crypto_pk_read_private_key_from_filename(prkey, fname)) {
  389. log(LOG_ERR, "Error loading private key.");
  390. goto error;
  391. }
  392. return prkey;
  393. default:
  394. assert(0);
  395. }
  396. error:
  397. if (prkey)
  398. crypto_free_pk_env(prkey);
  399. if (fd >= 0 && !file)
  400. close(fd);
  401. if (file)
  402. fclose(file);
  403. return NULL;
  404. }
  405. static int init_keys(void)
  406. {
  407. char keydir[512];
  408. char fingerprint[FINGERPRINT_LEN+MAX_NICKNAME_LEN+3];
  409. char *cp;
  410. crypto_pk_env_t *prkey;
  411. /* OP's don't need keys. Just initialize the TLS context.*/
  412. if (!options.OnionRouter) {
  413. assert(!options.DirPort);
  414. if (tor_tls_context_new(NULL, 0, NULL)<0) {
  415. log_fn(LOG_ERR, "Error creating TLS context for OP.");
  416. return -1;
  417. }
  418. return 0;
  419. }
  420. assert(options.DataDirectory);
  421. if (strlen(options.DataDirectory) > (512-128)) {
  422. log_fn(LOG_ERR, "DataDirectory is too long.");
  423. return -1;
  424. }
  425. if (check_private_dir(options.DataDirectory, 1)) {
  426. return -1;
  427. }
  428. sprintf(keydir,"%s/keys",options.DataDirectory);
  429. if (check_private_dir(keydir, 1)) {
  430. return -1;
  431. }
  432. cp = keydir + strlen(keydir); /* End of string. */
  433. /* 1. Read identity key. Make it if none is found. */
  434. strcpy(cp, "/identity.key");
  435. log_fn(LOG_INFO,"Reading/making identity key %s...",keydir);
  436. prkey = init_key_from_file(keydir);
  437. if (!prkey) return -1;
  438. set_identity_key(prkey);
  439. /* 2. Read onion key. Make it if none is found. */
  440. strcpy(cp, "/onion.key");
  441. log_fn(LOG_INFO,"Reading/making onion key %s...",keydir);
  442. prkey = init_key_from_file(keydir);
  443. if (!prkey) return -1;
  444. set_onion_key(prkey);
  445. /* 3. Initialize link key and TLS context. */
  446. strcpy(cp, "/link.key");
  447. log_fn(LOG_INFO,"Reading/making link key %s...",keydir);
  448. prkey = init_key_from_file(keydir);
  449. if (!prkey) return -1;
  450. set_link_key(prkey);
  451. if (tor_tls_context_new(prkey, 1, options.Nickname) < 0) {
  452. log_fn(LOG_ERR, "Error initializing TLS context");
  453. return -1;
  454. }
  455. /* 4. Dump router descriptor to 'router.desc' */
  456. /* Must be called after keys are initialized. */
  457. if (init_descriptor()<0) {
  458. log_fn(LOG_ERR, "Error initializing descriptor.");
  459. return -1;
  460. }
  461. sprintf(keydir,"%s/router.desc", options.DataDirectory);
  462. log_fn(LOG_INFO,"Dumping descriptor to %s...",keydir);
  463. if (write_str_to_file(keydir, router_get_my_descriptor())) {
  464. return -1;
  465. }
  466. /* 5. Dump fingerprint to 'fingerprint' */
  467. sprintf(keydir,"%s/fingerprint", options.DataDirectory);
  468. log_fn(LOG_INFO,"Dumping fingerprint to %s...",keydir);
  469. assert(strlen(options.Nickname) <= MAX_NICKNAME_LEN);
  470. strcpy(fingerprint, options.Nickname);
  471. strcat(fingerprint, " ");
  472. if (crypto_pk_get_fingerprint(get_identity_key(),
  473. fingerprint+strlen(fingerprint))<0) {
  474. log_fn(LOG_ERR, "Error computing fingerprint");
  475. return -1;
  476. }
  477. strcat(fingerprint, "\n");
  478. if (write_str_to_file(keydir, fingerprint))
  479. return -1;
  480. if(!options.DirPort)
  481. return 0;
  482. /* 6. [dirserver only] load approved-routers file */
  483. sprintf(keydir,"%s/approved-routers", options.DataDirectory);
  484. log_fn(LOG_INFO,"Loading approved fingerprints from %s...",keydir);
  485. if(dirserv_parse_fingerprint_file(keydir) < 0) {
  486. log_fn(LOG_ERR, "Error loading fingerprints");
  487. return -1;
  488. }
  489. /* 7. [dirserver only] load old directory, if it's there */
  490. sprintf(keydir,"%s/cached-directory", options.DataDirectory);
  491. log_fn(LOG_INFO,"Loading cached directory from %s...",keydir);
  492. cp = read_file_to_str(keydir);
  493. if(!cp) {
  494. log_fn(LOG_INFO,"Cached directory %s not present. Ok.",keydir);
  495. } else {
  496. if(dirserv_init_from_directory_string(cp) < 0) {
  497. log_fn(LOG_ERR, "Cached directory %s is corrupt", keydir);
  498. free(cp);
  499. return -1;
  500. }
  501. free(cp);
  502. }
  503. /* success */
  504. return 0;
  505. }
  506. static int do_main_loop(void) {
  507. int i;
  508. int timeout;
  509. int poll_result;
  510. /* load the routers file */
  511. if(router_get_list_from_file(options.RouterFile) < 0) {
  512. log_fn(LOG_ERR,"Error loading router list.");
  513. return -1;
  514. }
  515. /* load the private keys, if we're supposed to have them, and set up the
  516. * TLS context. */
  517. if (init_keys() < 0) {
  518. log_fn(LOG_ERR,"Error initializing keys; exiting");
  519. return -1;
  520. }
  521. if(options.OnionRouter) {
  522. cpu_init(); /* launch cpuworkers. Need to do this *after* we've read the onion key. */
  523. router_upload_desc_to_dirservers(); /* upload our descriptor to all dirservers */
  524. }
  525. /* start up the necessary connections based on which ports are
  526. * non-zero. This is where we try to connect to all the other ORs,
  527. * and start the listeners.
  528. */
  529. retry_all_connections((uint16_t) options.ORPort,
  530. (uint16_t) options.APPort,
  531. (uint16_t) options.DirPort);
  532. for(;;) {
  533. #ifndef MS_WIN32 /* do signal stuff only on unix */
  534. if(please_dumpstats) {
  535. dumpstats();
  536. please_dumpstats = 0;
  537. }
  538. if(please_reset) {
  539. /* fetch a new directory */
  540. if(options.DirPort) {
  541. if(router_get_list_from_file(options.RouterFile) < 0) {
  542. log(LOG_WARNING,"Error reloading router list. Continuing with old list.");
  543. }
  544. } else {
  545. directory_initiate_command(router_pick_directory_server(), DIR_CONN_STATE_CONNECTING_FETCH);
  546. }
  547. /* close and reopen the log files */
  548. reset_logs();
  549. please_reset = 0;
  550. }
  551. if(please_reap_children) {
  552. while(waitpid(-1,NULL,WNOHANG)) ; /* keep reaping until no more zombies */
  553. please_reap_children = 0;
  554. }
  555. #endif /* signal stuff */
  556. timeout = prepare_for_poll();
  557. /* poll until we have an event, or the second ends */
  558. poll_result = poll(poll_array, nfds, timeout);
  559. #if 0 /* let catch() handle things like ^c, and otherwise don't worry about it */
  560. if(poll_result < 0) {
  561. log(LOG_ERR,"do_main_loop(): poll failed.");
  562. if(errno != EINTR) /* let the program survive things like ^z */
  563. return -1;
  564. }
  565. #endif
  566. if(poll_result > 0) { /* we have at least one connection to deal with */
  567. /* do all the reads and errors first, so we can detect closed sockets */
  568. for(i=0;i<nfds;i++)
  569. conn_read(i); /* this also blows away broken connections */
  570. /* then do the writes */
  571. for(i=0;i<nfds;i++)
  572. conn_write(i);
  573. /* any of the conns need to be closed now? */
  574. for(i=0;i<nfds;i++)
  575. check_conn_marked(i);
  576. }
  577. /* refilling buckets and sending cells happens at the beginning of the
  578. * next iteration of the loop, inside prepare_for_poll()
  579. */
  580. }
  581. }
  582. static void catch(int the_signal) {
  583. #ifndef MS_WIN32 /* do signal stuff only on unix */
  584. switch(the_signal) {
  585. // case SIGABRT:
  586. case SIGTERM:
  587. case SIGINT:
  588. log(LOG_ERR,"Catching signal %d, exiting cleanly.", the_signal);
  589. exit(0);
  590. case SIGHUP:
  591. please_reset = 1;
  592. break;
  593. case SIGUSR1:
  594. please_dumpstats = 1;
  595. break;
  596. case SIGCHLD:
  597. please_reap_children = 1;
  598. break;
  599. default:
  600. log(LOG_WARNING,"Caught signal %d that we can't handle??", the_signal);
  601. }
  602. #endif /* signal stuff */
  603. }
  604. static void dumpstats(void) { /* dump stats to stdout */
  605. int i;
  606. connection_t *conn;
  607. struct timeval now;
  608. printf("Dumping stats:\n");
  609. my_gettimeofday(&now);
  610. for(i=0;i<nfds;i++) {
  611. conn = connection_array[i];
  612. printf("Conn %d (socket %d) type %d (%s), state %d (%s), created %ld secs ago\n",
  613. i, conn->s, conn->type, conn_type_to_string[conn->type],
  614. conn->state, conn_state_to_string[conn->type][conn->state], now.tv_sec - conn->timestamp_created);
  615. if(!connection_is_listener(conn)) {
  616. printf("Conn %d is to '%s:%d'.\n",i,conn->address, conn->port);
  617. printf("Conn %d: %d bytes waiting on inbuf (last read %ld secs ago)\n",i,
  618. (int)buf_datalen(conn->inbuf),
  619. now.tv_sec - conn->timestamp_lastread);
  620. printf("Conn %d: %d bytes waiting on outbuf (last written %ld secs ago)\n",i,(int)buf_datalen(conn->outbuf),
  621. now.tv_sec - conn->timestamp_lastwritten);
  622. }
  623. circuit_dump_by_conn(conn); /* dump info about all the circuits using this conn */
  624. printf("\n");
  625. }
  626. }
  627. int dump_router_to_string(char *s, int maxlen, routerinfo_t *router,
  628. crypto_pk_env_t *ident_key) {
  629. char *onion_pkey;
  630. char *link_pkey;
  631. char *identity_pkey;
  632. char digest[20];
  633. char signature[128];
  634. char published[32];
  635. int onion_pkeylen, link_pkeylen, identity_pkeylen;
  636. int written;
  637. int result=0;
  638. struct exit_policy_t *tmpe;
  639. if(crypto_pk_write_public_key_to_string(router->onion_pkey,
  640. &onion_pkey,&onion_pkeylen)<0) {
  641. log_fn(LOG_WARNING,"write onion_pkey to string failed!");
  642. return -1;
  643. }
  644. if(crypto_pk_write_public_key_to_string(router->identity_pkey,
  645. &identity_pkey,&identity_pkeylen)<0) {
  646. log_fn(LOG_WARNING,"write identity_pkey to string failed!");
  647. return -1;
  648. }
  649. if(crypto_pk_write_public_key_to_string(router->link_pkey,
  650. &link_pkey,&link_pkeylen)<0) {
  651. log_fn(LOG_WARNING,"write link_pkey to string failed!");
  652. return -1;
  653. }
  654. strftime(published, 32, "%Y-%m-%d %H:%M:%S", gmtime(&router->published_on));
  655. result = snprintf(s, maxlen,
  656. "router %s %s %d %d %d %d\n"
  657. "published %s\n"
  658. "onion-key\n%s"
  659. "link-key\n%s"
  660. "signing-key\n%s",
  661. router->nickname,
  662. router->address,
  663. router->or_port,
  664. router->ap_port,
  665. router->dir_port,
  666. router->bandwidth,
  667. published,
  668. onion_pkey, link_pkey, identity_pkey);
  669. free(onion_pkey);
  670. free(link_pkey);
  671. free(identity_pkey);
  672. if(result < 0 || result >= maxlen) {
  673. /* apparently different glibcs do different things on snprintf error.. so check both */
  674. return -1;
  675. }
  676. written = result;
  677. for(tmpe=router->exit_policy; tmpe; tmpe=tmpe->next) {
  678. result = snprintf(s+written, maxlen-written, "%s %s:%s\n",
  679. tmpe->policy_type == EXIT_POLICY_ACCEPT ? "accept" : "reject",
  680. tmpe->address, tmpe->port);
  681. if(result < 0 || result+written > maxlen) {
  682. /* apparently different glibcs do different things on snprintf error.. so check both */
  683. return -1;
  684. }
  685. written += result;
  686. }
  687. if (written > maxlen-256) /* Not enough room for signature. */
  688. return -1;
  689. strcat(s+written, "router-signature\n");
  690. written += strlen(s+written);
  691. s[written] = '\0';
  692. if (router_get_router_hash(s, digest) < 0)
  693. return -1;
  694. if (crypto_pk_private_sign(ident_key, digest, 20, signature) < 0) {
  695. log_fn(LOG_WARNING, "Error signing digest");
  696. return -1;
  697. }
  698. strcat(s+written, "-----BEGIN SIGNATURE-----\n");
  699. written += strlen(s+written);
  700. if (base64_encode(s+written, maxlen-written, signature, 128) < 0) {
  701. log_fn(LOG_WARNING, "Couldn't base64-encode signature");
  702. /* XXX Nick: do we really mean to fall through here? */
  703. }
  704. written += strlen(s+written);
  705. strcat(s+written, "-----END SIGNATURE-----\n");
  706. written += strlen(s+written);
  707. if (written > maxlen-2)
  708. return -1;
  709. /* include a last '\n' */
  710. s[written] = '\n';
  711. s[written+1] = 0;
  712. return written+1;
  713. }
  714. int
  715. list_running_servers(char **nicknames_out)
  716. {
  717. char *nickname_lst[MAX_ROUTERS_IN_DIR];
  718. connection_t *conn;
  719. char *cp;
  720. int n = 0, i;
  721. int length;
  722. *nicknames_out = NULL;
  723. if (my_routerinfo)
  724. nickname_lst[n++] = my_routerinfo->nickname;
  725. for (i = 0; i<nfds; ++i) {
  726. conn = connection_array[i];
  727. if (conn->type != CONN_TYPE_OR || conn->state != OR_CONN_STATE_OPEN)
  728. continue; /* only list successfully handshaked OR's. */
  729. if(!conn->nickname) /* it's an OP, don't list it */
  730. continue;
  731. nickname_lst[n++] = conn->nickname;
  732. }
  733. length = n + 1; /* spaces + EOS + 1. */
  734. for (i = 0; i<n; ++i) {
  735. length += strlen(nickname_lst[i]);
  736. }
  737. *nicknames_out = tor_malloc(length);
  738. cp = *nicknames_out;
  739. memset(cp,0,length);
  740. for (i = 0; i<n; ++i) {
  741. if (i)
  742. strcat(cp, " ");
  743. strcat(cp, nickname_lst[i]);
  744. while (*cp)
  745. ++cp;
  746. }
  747. return 0;
  748. }
  749. static char descriptor[8192];
  750. /* XXX should this replace my_routerinfo? */
  751. static routerinfo_t *desc_routerinfo;
  752. const char *router_get_my_descriptor(void) {
  753. log_fn(LOG_DEBUG,"my desc is '%s'",descriptor);
  754. return descriptor;
  755. }
  756. static int init_descriptor(void) {
  757. routerinfo_t *ri;
  758. char localhostname[256];
  759. char *address = options.Address;
  760. if(!address) { /* if not specified in config, we find a default */
  761. if(gethostname(localhostname,sizeof(localhostname)) < 0) {
  762. log_fn(LOG_WARNING,"Error obtaining local hostname");
  763. return -1;
  764. }
  765. address = localhostname;
  766. }
  767. ri = tor_malloc(sizeof(routerinfo_t));
  768. ri->address = strdup(address);
  769. ri->nickname = strdup(options.Nickname);
  770. /* No need to set addr. */
  771. ri->or_port = options.ORPort;
  772. ri->ap_port = options.APPort;
  773. ri->dir_port = options.DirPort;
  774. ri->published_on = time(NULL);
  775. ri->onion_pkey = crypto_pk_dup_key(get_onion_key());
  776. ri->link_pkey = crypto_pk_dup_key(get_link_key());
  777. ri->identity_pkey = crypto_pk_dup_key(get_identity_key());
  778. ri->bandwidth = options.TotalBandwidth;
  779. ri->exit_policy = NULL; /* XXX implement this. */
  780. if (desc_routerinfo)
  781. routerinfo_free(desc_routerinfo);
  782. desc_routerinfo = ri;
  783. if (dump_router_to_string(descriptor, 8192, ri, get_identity_key())<0) {
  784. log_fn(LOG_WARNING, "Couldn't dump router to string.");
  785. return -1;
  786. }
  787. return 0;
  788. }
  789. void daemonize(void) {
  790. #ifndef MS_WINDOWS
  791. /* Fork; parent exits. */
  792. if (fork())
  793. exit(0);
  794. /* Create new session; make sure we never get a terminal */
  795. setsid();
  796. if (fork())
  797. exit(0);
  798. chdir("/");
  799. umask(000);
  800. fclose(stdin);
  801. fclose(stdout); /* XXX Nick: this closes our log, right? is it safe to leave this open? */
  802. fclose(stderr);
  803. #endif
  804. }
  805. int tor_main(int argc, char *argv[]) {
  806. if(getconfig(argc,argv,&options)) {
  807. log_fn(LOG_ERR,"Reading config file failed. exiting.");
  808. return -1;
  809. }
  810. log_set_severity(options.loglevel); /* assign logging severity level from options */
  811. global_read_bucket = options.TotalBandwidth; /* start it at 1 second of traffic */
  812. if(options.Daemon)
  813. daemonize();
  814. if(options.OnionRouter) { /* only spawn dns handlers if we're a router */
  815. dns_init(); /* initialize the dns resolve tree, and spawn workers */
  816. }
  817. #ifndef MS_WINDOWS /* do signal stuff only on unix */
  818. signal (SIGINT, catch); /* catch kills so we can exit cleanly */
  819. signal (SIGTERM, catch);
  820. signal (SIGUSR1, catch); /* to dump stats to stdout */
  821. signal (SIGHUP, catch); /* to reload directory */
  822. signal (SIGCHLD, catch); /* for exiting dns/cpu workers */
  823. #endif /* signal stuff */
  824. crypto_global_init();
  825. crypto_seed_rng();
  826. do_main_loop();
  827. crypto_global_cleanup();
  828. return -1;
  829. }
  830. /*
  831. Local Variables:
  832. mode:c
  833. indent-tabs-mode:nil
  834. c-basic-offset:2
  835. End:
  836. */