main.c 27 KB

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