main.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859
  1. /* Copyright 2001,2002,2003 Roger Dingledine, Matej Pfajfar. */
  2. /* See LICENSE for licensing information */
  3. /* $Id$ */
  4. #include "or.h"
  5. /********* START PROTOTYPES **********/
  6. static void dumpstats(int severity); /* log stats */
  7. static int init_from_config(int argc, char **argv);
  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 int stats_prev_global_read_bucket;
  14. static uint64_t stats_n_bytes_read = 0;
  15. static long stats_n_seconds_reading = 0;
  16. static connection_t *connection_array[MAXCONNECTIONS] =
  17. { NULL };
  18. static struct pollfd poll_array[MAXCONNECTIONS];
  19. static int nfds=0; /* number of connections currently active */
  20. #ifndef MS_WINDOWS /* do signal stuff only on unix */
  21. static int please_dumpstats=0; /* whether we should dump stats during the loop */
  22. static int please_reset=0; /* whether we just got a sighup */
  23. static int please_reap_children=0; /* whether we should waitpid for exited children */
  24. #endif /* signal stuff */
  25. /* private keys */
  26. static crypto_pk_env_t *onionkey=NULL;
  27. static crypto_pk_env_t *linkkey=NULL;
  28. static crypto_pk_env_t *identitykey=NULL;
  29. /********* END VARIABLES ************/
  30. void set_onion_key(crypto_pk_env_t *k) {
  31. onionkey = k;
  32. }
  33. crypto_pk_env_t *get_onion_key(void) {
  34. assert(onionkey);
  35. return onionkey;
  36. }
  37. void set_link_key(crypto_pk_env_t *k)
  38. {
  39. linkkey = k;
  40. }
  41. crypto_pk_env_t *get_link_key(void)
  42. {
  43. assert(linkkey);
  44. return linkkey;
  45. }
  46. void set_identity_key(crypto_pk_env_t *k) {
  47. identitykey = k;
  48. }
  49. crypto_pk_env_t *get_identity_key(void) {
  50. assert(identitykey);
  51. return identitykey;
  52. }
  53. /****************************************************************************
  54. *
  55. * This section contains accessors and other methods on the connection_array
  56. * and poll_array variables (which are global within this file and unavailable
  57. * outside it).
  58. *
  59. ****************************************************************************/
  60. int connection_add(connection_t *conn) {
  61. if(nfds >= options.MaxConn-1) {
  62. log(LOG_WARN,"connection_add(): failing because nfds is too high.");
  63. return -1;
  64. }
  65. conn->poll_index = nfds;
  66. connection_set_poll_socket(conn);
  67. connection_array[nfds] = conn;
  68. /* zero these out here, because otherwise we'll inherit values from the previously freed one */
  69. poll_array[nfds].events = 0;
  70. poll_array[nfds].revents = 0;
  71. nfds++;
  72. log(LOG_INFO,"connection_add(): new conn type %d, socket %d, nfds %d.",conn->type, conn->s, nfds);
  73. return 0;
  74. }
  75. void connection_set_poll_socket(connection_t *conn) {
  76. poll_array[conn->poll_index].fd = conn->s;
  77. }
  78. /* Remove the connection from the global list, and remove the
  79. * corresponding poll entry. Calling this function will shift the last
  80. * connection (if any) into the position occupied by conn.
  81. */
  82. int connection_remove(connection_t *conn) {
  83. int current_index;
  84. assert(conn);
  85. assert(nfds>0);
  86. log(LOG_INFO,"connection_remove(): removing socket %d, nfds now %d",conn->s, nfds-1);
  87. /* if it's an edge conn, remove it from the list
  88. * of conn's on this circuit. If it's not on an edge,
  89. * flush and send destroys for all circuits on this conn
  90. */
  91. circuit_about_to_close_connection(conn);
  92. current_index = conn->poll_index;
  93. if(current_index == nfds-1) { /* this is the end */
  94. nfds--;
  95. return 0;
  96. }
  97. /* we replace this one with the one at the end, then free it */
  98. nfds--;
  99. poll_array[current_index].fd = poll_array[nfds].fd;
  100. poll_array[current_index].events = poll_array[nfds].events;
  101. poll_array[current_index].revents = poll_array[nfds].revents;
  102. connection_array[current_index] = connection_array[nfds];
  103. connection_array[current_index]->poll_index = current_index;
  104. return 0;
  105. }
  106. void get_connection_array(connection_t ***array, int *n) {
  107. *array = connection_array;
  108. *n = nfds;
  109. }
  110. void connection_watch_events(connection_t *conn, short events) {
  111. assert(conn && conn->poll_index < nfds);
  112. poll_array[conn->poll_index].events = events;
  113. }
  114. int connection_is_reading(connection_t *conn) {
  115. return poll_array[conn->poll_index].events & POLLIN;
  116. }
  117. void connection_stop_reading(connection_t *conn) {
  118. assert(conn && conn->poll_index < nfds);
  119. log(LOG_DEBUG,"connection_stop_reading() called.");
  120. if(poll_array[conn->poll_index].events & POLLIN)
  121. poll_array[conn->poll_index].events -= POLLIN;
  122. }
  123. void connection_start_reading(connection_t *conn) {
  124. assert(conn && conn->poll_index < nfds);
  125. poll_array[conn->poll_index].events |= POLLIN;
  126. }
  127. void connection_stop_writing(connection_t *conn) {
  128. assert(conn && conn->poll_index < nfds);
  129. if(poll_array[conn->poll_index].events & POLLOUT)
  130. poll_array[conn->poll_index].events -= POLLOUT;
  131. }
  132. void connection_start_writing(connection_t *conn) {
  133. assert(conn && conn->poll_index < nfds);
  134. poll_array[conn->poll_index].events |= POLLOUT;
  135. }
  136. static void conn_read(int i) {
  137. connection_t *conn = connection_array[i];
  138. /* see http://www.greenend.org.uk/rjk/2001/06/poll.html for
  139. * discussion of POLLIN vs POLLHUP */
  140. if(!(poll_array[i].revents & (POLLIN|POLLHUP|POLLERR)))
  141. if(!connection_is_reading(conn) ||
  142. !connection_has_pending_tls_data(conn))
  143. return; /* this conn should not read */
  144. log_fn(LOG_DEBUG,"socket %d wants to read.",conn->s);
  145. assert_connection_ok(conn, time(NULL));
  146. if(
  147. /* XXX does POLLHUP also mean it's definitely broken? */
  148. #ifdef MS_WINDOWS
  149. (poll_array[i].revents & POLLERR) ||
  150. #endif
  151. connection_handle_read(conn) < 0)
  152. {
  153. /* this connection is broken. remove it */
  154. log_fn(LOG_INFO,"%s connection broken, removing.", conn_type_to_string[conn->type]);
  155. connection_remove(conn);
  156. connection_free(conn);
  157. if(i<nfds) { /* we just replaced the one at i with a new one. process it too. */
  158. conn_read(i);
  159. }
  160. } else assert_connection_ok(conn, time(NULL));
  161. }
  162. static void conn_write(int i) {
  163. connection_t *conn;
  164. if(!(poll_array[i].revents & POLLOUT))
  165. return; /* this conn doesn't want to write */
  166. conn = connection_array[i];
  167. log_fn(LOG_DEBUG,"socket %d wants to write.",conn->s);
  168. assert_connection_ok(conn, time(NULL));
  169. if(connection_handle_write(conn) < 0) { /* this connection is broken. remove it. */
  170. log_fn(LOG_INFO,"%s connection broken, removing.", conn_type_to_string[conn->type]);
  171. connection_remove(conn);
  172. connection_free(conn);
  173. if(i<nfds) { /* we just replaced the one at i with a new one. process it too. */
  174. conn_write(i);
  175. }
  176. } else assert_connection_ok(conn, time(NULL));
  177. }
  178. static void conn_close_if_marked(int i) {
  179. connection_t *conn;
  180. conn = connection_array[i];
  181. assert_connection_ok(conn, time(NULL));
  182. if(conn->marked_for_close) {
  183. log_fn(LOG_INFO,"Cleaning up connection (fd %d).",conn->s);
  184. if(conn->s >= 0) { /* might be an incomplete edge connection */
  185. /* FIXME there's got to be a better way to check for this -- and make other checks? */
  186. if(connection_speaks_cells(conn)) {
  187. if(conn->state == OR_CONN_STATE_OPEN)
  188. flush_buf_tls(conn->tls, conn->outbuf, &conn->outbuf_flushlen);
  189. } else {
  190. flush_buf(conn->s, conn->outbuf, &conn->outbuf_flushlen);
  191. }
  192. if(connection_wants_to_flush(conn)) /* not done flushing */
  193. log_fn(LOG_WARN,"Conn (socket %d) still wants to flush. Losing %d bytes!",conn->s, (int)buf_datalen(conn->inbuf));
  194. }
  195. connection_remove(conn);
  196. connection_free(conn);
  197. if(i<nfds) { /* we just replaced the one at i with a new one.
  198. process it too. */
  199. conn_close_if_marked(i);
  200. }
  201. }
  202. }
  203. /* Perform regular maintenance tasks for a single connection. This
  204. * function gets run once per second per connection by run_housekeeping.
  205. */
  206. static void run_connection_housekeeping(int i, time_t now) {
  207. cell_t cell;
  208. connection_t *conn = connection_array[i];
  209. if(connection_receiver_bucket_should_increase(conn)) {
  210. conn->receiver_bucket += conn->bandwidth;
  211. // log_fn(LOG_DEBUG,"Receiver bucket %d now %d.", i, conn->receiver_bucket);
  212. }
  213. if(conn->wants_to_read == 1 /* it's marked to turn reading back on now */
  214. && global_read_bucket > 0 /* and we're allowed to read */
  215. && (!connection_speaks_cells(conn) || conn->receiver_bucket > 0)) {
  216. /* and either a non-cell conn or a cell conn with non-empty bucket */
  217. conn->wants_to_read = 0;
  218. connection_start_reading(conn);
  219. if(conn->wants_to_write == 1) {
  220. conn->wants_to_write = 0;
  221. connection_start_writing(conn);
  222. }
  223. }
  224. /* check connections to see whether we should send a keepalive, expire, or wait */
  225. if(!connection_speaks_cells(conn))
  226. return;
  227. if(now >= conn->timestamp_lastwritten + options.KeepalivePeriod) {
  228. if((!options.ORPort && !circuit_get_by_conn(conn)) ||
  229. (!connection_state_is_open(conn))) {
  230. /* we're an onion proxy, with no circuits; or our handshake has expired. kill it. */
  231. log_fn(LOG_INFO,"Expiring connection to %d (%s:%d).",
  232. i,conn->address, conn->port);
  233. conn->marked_for_close = 1;
  234. } else {
  235. /* either a full router, or we've got a circuit. send a padding cell. */
  236. log_fn(LOG_DEBUG,"Sending keepalive to (%s:%d)",
  237. conn->address, conn->port);
  238. memset(&cell,0,sizeof(cell_t));
  239. cell.command = CELL_PADDING;
  240. connection_or_write_cell_to_buf(&cell, conn);
  241. }
  242. }
  243. }
  244. /* Perform regular maintenance tasks. This function gets run once per
  245. * second by prepare_for_poll.
  246. */
  247. static void run_scheduled_events(time_t now) {
  248. static long time_to_fetch_directory = 0;
  249. static long time_to_new_circuit = 0;
  250. circuit_t *circ;
  251. int i;
  252. /* 1. Every DirFetchPostPeriod seconds, we get a new directory and upload
  253. * our descriptor (if any). */
  254. if(time_to_fetch_directory < now) {
  255. /* it's time to fetch a new directory and/or post our descriptor */
  256. if(options.ORPort) {
  257. router_rebuild_descriptor();
  258. router_upload_desc_to_dirservers();
  259. }
  260. if(!options.DirPort) {
  261. /* NOTE directory servers do not currently fetch directories.
  262. * Hope this doesn't bite us later. */
  263. directory_initiate_command(router_pick_directory_server(),
  264. DIR_CONN_STATE_CONNECTING_FETCH);
  265. }
  266. time_to_fetch_directory = now + options.DirFetchPostPeriod;
  267. }
  268. /* 2. Every second, we examine pending circuits and prune the
  269. * ones which have been pending for more than 2 seconds.
  270. * We do this before step 3, so it can try building more if
  271. * it's not comfortable with the number of available circuits.
  272. */
  273. circuit_expire_building();
  274. /* 3. Every second, we try a new circuit if there are no valid
  275. * circuits. Every NewCircuitPeriod seconds, we expire circuits
  276. * that became dirty more than NewCircuitPeriod seconds ago,
  277. * and we make a new circ if there are no clean circuits.
  278. */
  279. if(options.SocksPort) {
  280. /* launch a new circ for any pending streams that need one */
  281. connection_ap_attach_pending();
  282. circ = circuit_get_newest(NULL, 1);
  283. if(time_to_new_circuit < now) {
  284. client_dns_clean();
  285. circuit_expire_unused_circuits();
  286. circuit_reset_failure_count();
  287. if(circ && circ->timestamp_dirty) {
  288. log_fn(LOG_INFO,"Youngest circuit dirty; launching replacement.");
  289. circuit_launch_new(); /* make a new circuit */
  290. }
  291. time_to_new_circuit = now + options.NewCircuitPeriod;
  292. }
  293. #define CIRCUIT_MIN_BUILDING 2
  294. if(!circ && circuit_count_building() < CIRCUIT_MIN_BUILDING) {
  295. /* if there's no open circ, and less than 2 are on the way,
  296. * go ahead and try another.
  297. */
  298. circuit_launch_new();
  299. }
  300. }
  301. /* 4. Every second, we check how much bandwidth we've consumed and
  302. * increment global_read_bucket.
  303. */
  304. stats_n_bytes_read += stats_prev_global_read_bucket-global_read_bucket;
  305. if(global_read_bucket < 9*options.TotalBandwidth) {
  306. global_read_bucket += options.TotalBandwidth;
  307. log_fn(LOG_DEBUG,"global_read_bucket now %d.", global_read_bucket);
  308. }
  309. stats_prev_global_read_bucket = global_read_bucket;
  310. /* 5. We do housekeeping for each connection... */
  311. for(i=0;i<nfds;i++) {
  312. run_connection_housekeeping(i, now);
  313. }
  314. /* 6. and blow away any connections that need to die. can't do this later
  315. * because we might open up a circuit and not realize we're about to cull
  316. * the connection it's running over.
  317. * XXX we can remove this step once we audit circuit-building to make sure
  318. * it doesn't pick a marked-for-close conn. -RD
  319. */
  320. for(i=0;i<nfds;i++)
  321. conn_close_if_marked(i);
  322. }
  323. static int prepare_for_poll(void) {
  324. static long current_second = 0; /* from previous calls to gettimeofday */
  325. connection_t *conn;
  326. struct timeval now;
  327. int i;
  328. tor_gettimeofday(&now);
  329. if(now.tv_sec > current_second) { /* the second has rolled over. check more stuff. */
  330. ++stats_n_seconds_reading;
  331. run_scheduled_events(now.tv_sec);
  332. current_second = now.tv_sec; /* remember which second it is, for next time */
  333. }
  334. for(i=0;i<nfds;i++) {
  335. conn = connection_array[i];
  336. if(connection_has_pending_tls_data(conn)) {
  337. log_fn(LOG_DEBUG,"sock %d has pending bytes.",conn->s);
  338. return 0; /* has pending bytes to read; don't let poll wait. */
  339. }
  340. }
  341. return (1000 - (now.tv_usec / 1000)); /* how many milliseconds til the next second? */
  342. }
  343. static crypto_pk_env_t *init_key_from_file(const char *fname)
  344. {
  345. crypto_pk_env_t *prkey = NULL;
  346. int fd = -1;
  347. FILE *file = NULL;
  348. if (!(prkey = crypto_new_pk_env(CRYPTO_PK_RSA))) {
  349. log(LOG_ERR, "Error creating crypto environment.");
  350. goto error;
  351. }
  352. switch(file_status(fname)) {
  353. case FN_DIR:
  354. case FN_ERROR:
  355. log(LOG_ERR, "Can't read key from %s", fname);
  356. goto error;
  357. case FN_NOENT:
  358. log(LOG_INFO, "No key found in %s; generating fresh key.", fname);
  359. if (crypto_pk_generate_key(prkey)) {
  360. log(LOG_ERR, "Error generating key: %s", crypto_perror());
  361. goto error;
  362. }
  363. if (crypto_pk_check_key(prkey) <= 0) {
  364. log(LOG_ERR, "Generated key seems invalid");
  365. goto error;
  366. }
  367. log(LOG_INFO, "Generated key seems valid");
  368. if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
  369. log(LOG_ERR, "Couldn't write generated key to %s.", fname);
  370. goto error;
  371. }
  372. return prkey;
  373. case FN_FILE:
  374. if (crypto_pk_read_private_key_from_filename(prkey, fname)) {
  375. log(LOG_ERR, "Error loading private key.");
  376. goto error;
  377. }
  378. return prkey;
  379. default:
  380. assert(0);
  381. }
  382. error:
  383. if (prkey)
  384. crypto_free_pk_env(prkey);
  385. if (fd >= 0 && !file)
  386. close(fd);
  387. if (file)
  388. fclose(file);
  389. return NULL;
  390. }
  391. static int init_keys(void)
  392. {
  393. char keydir[512];
  394. char fingerprint[FINGERPRINT_LEN+MAX_NICKNAME_LEN+3];
  395. char *cp;
  396. const char *tmp, *mydesc;
  397. crypto_pk_env_t *prkey;
  398. /* OP's don't need keys. Just initialize the TLS context.*/
  399. if (!options.ORPort) {
  400. assert(!options.DirPort);
  401. if (tor_tls_context_new(NULL, 0, NULL)<0) {
  402. log_fn(LOG_ERR, "Error creating TLS context for OP.");
  403. return -1;
  404. }
  405. return 0;
  406. }
  407. assert(options.DataDirectory);
  408. if (strlen(options.DataDirectory) > (512-128)) {
  409. log_fn(LOG_ERR, "DataDirectory is too long.");
  410. return -1;
  411. }
  412. if (check_private_dir(options.DataDirectory, 1)) {
  413. return -1;
  414. }
  415. sprintf(keydir,"%s/keys",options.DataDirectory);
  416. if (check_private_dir(keydir, 1)) {
  417. return -1;
  418. }
  419. cp = keydir + strlen(keydir); /* End of string. */
  420. /* 1. Read identity key. Make it if none is found. */
  421. strcpy(cp, "/identity.key");
  422. log_fn(LOG_INFO,"Reading/making identity key %s...",keydir);
  423. prkey = init_key_from_file(keydir);
  424. if (!prkey) return -1;
  425. set_identity_key(prkey);
  426. /* 2. Read onion key. Make it if none is found. */
  427. strcpy(cp, "/onion.key");
  428. log_fn(LOG_INFO,"Reading/making onion key %s...",keydir);
  429. prkey = init_key_from_file(keydir);
  430. if (!prkey) return -1;
  431. set_onion_key(prkey);
  432. /* 3. Initialize link key and TLS context. */
  433. strcpy(cp, "/link.key");
  434. log_fn(LOG_INFO,"Reading/making link key %s...",keydir);
  435. prkey = init_key_from_file(keydir);
  436. if (!prkey) return -1;
  437. set_link_key(prkey);
  438. if (tor_tls_context_new(prkey, 1, options.Nickname) < 0) {
  439. log_fn(LOG_ERR, "Error initializing TLS context");
  440. return -1;
  441. }
  442. /* 4. Dump router descriptor to 'router.desc' */
  443. /* Must be called after keys are initialized. */
  444. if (!(router_get_my_descriptor())) {
  445. log_fn(LOG_ERR, "Error initializing descriptor.");
  446. return -1;
  447. }
  448. /* We need to add our own fingerprint so it gets recognized. */
  449. if (dirserv_add_own_fingerprint(options.Nickname, get_identity_key())) {
  450. log_fn(LOG_ERR, "Error adding own fingerprint to approved set");
  451. return -1;
  452. }
  453. tmp = mydesc = router_get_my_descriptor();
  454. if (dirserv_add_descriptor(&tmp)) {
  455. log(LOG_ERR, "Unable to add own descriptor to directory.");
  456. return -1;
  457. }
  458. sprintf(keydir,"%s/router.desc", options.DataDirectory);
  459. log_fn(LOG_INFO,"Dumping descriptor to %s...",keydir);
  460. if (write_str_to_file(keydir, mydesc)) {
  461. return -1;
  462. }
  463. /* 5. Dump fingerprint to 'fingerprint' */
  464. sprintf(keydir,"%s/fingerprint", options.DataDirectory);
  465. log_fn(LOG_INFO,"Dumping fingerprint to %s...",keydir);
  466. assert(strlen(options.Nickname) <= MAX_NICKNAME_LEN);
  467. strcpy(fingerprint, options.Nickname);
  468. strcat(fingerprint, " ");
  469. if (crypto_pk_get_fingerprint(get_identity_key(),
  470. fingerprint+strlen(fingerprint))<0) {
  471. log_fn(LOG_ERR, "Error computing fingerprint");
  472. return -1;
  473. }
  474. strcat(fingerprint, "\n");
  475. if (write_str_to_file(keydir, fingerprint))
  476. return -1;
  477. if(!options.DirPort)
  478. return 0;
  479. /* 6. [dirserver only] load approved-routers file */
  480. sprintf(keydir,"%s/approved-routers", options.DataDirectory);
  481. log_fn(LOG_INFO,"Loading approved fingerprints from %s...",keydir);
  482. if(dirserv_parse_fingerprint_file(keydir) < 0) {
  483. log_fn(LOG_ERR, "Error loading fingerprints");
  484. return -1;
  485. }
  486. /* 7. [dirserver only] load old directory, if it's there */
  487. sprintf(keydir,"%s/cached-directory", options.DataDirectory);
  488. log_fn(LOG_INFO,"Loading cached directory from %s...",keydir);
  489. cp = read_file_to_str(keydir);
  490. if(!cp) {
  491. log_fn(LOG_INFO,"Cached directory %s not present. Ok.",keydir);
  492. } else {
  493. if(dirserv_init_from_directory_string(cp) < 0) {
  494. log_fn(LOG_ERR, "Cached directory %s is corrupt", keydir);
  495. free(cp);
  496. return -1;
  497. }
  498. free(cp);
  499. }
  500. /* success */
  501. return 0;
  502. }
  503. static int init_from_config(int argc, char **argv) {
  504. static int have_daemonized=0;
  505. if(getconfig(argc,argv,&options)) {
  506. log_fn(LOG_ERR,"Reading config failed. For usage, try -h.");
  507. return -1;
  508. }
  509. log_set_severity(options.loglevel); /* assign logging severity level from options */
  510. close_logs(); /* we'll close, then open with correct loglevel if necessary */
  511. if(!options.LogFile && !options.RunAsDaemon)
  512. add_stream_log(options.loglevel, "<stdout>", stdout);
  513. if(options.LogFile)
  514. if (add_file_log(options.loglevel, options.LogFile) != 0) {
  515. /* opening the log file failed! Use stderr and log a warning */
  516. add_stream_log(options.loglevel, "<stderr>", stderr);
  517. log_fn(LOG_WARN, "Cannot write to LogFile '%s': %s.", options.LogFile, strerror(errno));
  518. }
  519. if(options.DebugLogFile)
  520. if (add_file_log(LOG_DEBUG, options.DebugLogFile) != 0)
  521. log_fn(LOG_WARN, "Cannot write to DebugLogFile '%s': %s.", options.LogFile, strerror(errno));
  522. global_read_bucket = options.TotalBandwidth; /* start it at 1 second of traffic */
  523. stats_prev_global_read_bucket = global_read_bucket;
  524. if(options.User || options.Group) {
  525. if(switch_id(options.User, options.Group) != 0) {
  526. return -1;
  527. }
  528. }
  529. if(options.RunAsDaemon && !have_daemonized) {
  530. daemonize();
  531. have_daemonized = 1;
  532. }
  533. /* write our pid to the pid file, if we do not have write permissions we will log a warning */
  534. if(options.PidFile)
  535. write_pidfile(options.PidFile);
  536. return 0;
  537. }
  538. static int do_main_loop(void) {
  539. int i;
  540. int timeout;
  541. int poll_result;
  542. /* load the routers file */
  543. if(router_get_list_from_file(options.RouterFile) < 0) {
  544. log_fn(LOG_ERR,"Error loading router list.");
  545. return -1;
  546. }
  547. /* load the private keys, if we're supposed to have them, and set up the
  548. * TLS context. */
  549. if (init_keys() < 0) {
  550. log_fn(LOG_ERR,"Error initializing keys; exiting");
  551. return -1;
  552. }
  553. if(options.ORPort) {
  554. cpu_init(); /* launch cpuworkers. Need to do this *after* we've read the onion key. */
  555. router_upload_desc_to_dirservers(); /* upload our descriptor to all dirservers */
  556. }
  557. /* start up the necessary connections based on which ports are
  558. * non-zero. This is where we try to connect to all the other ORs,
  559. * and start the listeners.
  560. */
  561. if(retry_all_connections() < 0) {
  562. log_fn(LOG_ERR,"Failed to bind one of the listener ports.");
  563. return -1;
  564. }
  565. for(;;) {
  566. #ifndef MS_WINDOWS /* do signal stuff only on unix */
  567. if(please_dumpstats) {
  568. /* prefer to log it at INFO, but make sure we always see it */
  569. dumpstats(options.loglevel>LOG_INFO ? options.loglevel : LOG_INFO);
  570. please_dumpstats = 0;
  571. }
  572. if(please_reset) {
  573. log_fn(LOG_WARN,"Received sighup. Reloading config.");
  574. /* first, reload config variables, in case they've changed */
  575. if (init_from_config(0, NULL) < 0) {
  576. /* no need to provide argc/v, they've been cached inside init_from_config */
  577. exit(1);
  578. }
  579. /* fetch a new directory */
  580. if(options.DirPort) {
  581. /* reload the fingerprint file */
  582. char keydir[512];
  583. sprintf(keydir,"%s/approved-routers", options.DataDirectory);
  584. log_fn(LOG_INFO,"Reloading approved fingerprints from %s...",keydir);
  585. if(dirserv_parse_fingerprint_file(keydir) < 0) {
  586. log_fn(LOG_WARN, "Error reloading fingerprints. Continuing with old list.");
  587. }
  588. if(router_get_list_from_file(options.RouterFile) < 0) {
  589. log(LOG_WARN,"Error reloading router list. Continuing with old list.");
  590. }
  591. } else {
  592. directory_initiate_command(router_pick_directory_server(), DIR_CONN_STATE_CONNECTING_FETCH);
  593. }
  594. please_reset = 0;
  595. }
  596. if(please_reap_children) {
  597. while(waitpid(-1,NULL,WNOHANG)) ; /* keep reaping until no more zombies */
  598. please_reap_children = 0;
  599. }
  600. #endif /* signal stuff */
  601. timeout = prepare_for_poll();
  602. /* poll until we have an event, or the second ends */
  603. poll_result = poll(poll_array, nfds, timeout);
  604. /* let catch() handle things like ^c, and otherwise don't worry about it */
  605. if(poll_result < 0) {
  606. if(errno != EINTR) { /* let the program survive things like ^z */
  607. log_fn(LOG_ERR,"poll failed.");
  608. return -1;
  609. } else {
  610. log_fn(LOG_DEBUG,"poll interrupted.");
  611. }
  612. }
  613. /* do all the reads and errors first, so we can detect closed sockets */
  614. for(i=0;i<nfds;i++)
  615. conn_read(i); /* this also blows away broken connections */
  616. /* then do the writes */
  617. for(i=0;i<nfds;i++)
  618. conn_write(i);
  619. /* any of the conns need to be closed now? */
  620. for(i=0;i<nfds;i++)
  621. conn_close_if_marked(i);
  622. /* refilling buckets and sending cells happens at the beginning of the
  623. * next iteration of the loop, inside prepare_for_poll()
  624. */
  625. }
  626. }
  627. static void catch(int the_signal) {
  628. #ifndef MS_WINDOWS /* do signal stuff only on unix */
  629. switch(the_signal) {
  630. // case SIGABRT:
  631. case SIGTERM:
  632. case SIGINT:
  633. log(LOG_ERR,"Catching signal %d, exiting cleanly.", the_signal);
  634. /* we don't care if there was an error when we unlink, nothing
  635. we could do about it anyways */
  636. if(options.PidFile)
  637. unlink(options.PidFile);
  638. exit(0);
  639. case SIGHUP:
  640. please_reset = 1;
  641. break;
  642. case SIGUSR1:
  643. please_dumpstats = 1;
  644. break;
  645. case SIGCHLD:
  646. please_reap_children = 1;
  647. break;
  648. default:
  649. log(LOG_WARN,"Caught signal %d that we can't handle??", the_signal);
  650. }
  651. #endif /* signal stuff */
  652. }
  653. static void dumpstats(int severity) {
  654. int i;
  655. connection_t *conn;
  656. time_t now = time(NULL);
  657. log(severity, "Dumping stats:");
  658. for(i=0;i<nfds;i++) {
  659. conn = connection_array[i];
  660. log(severity, "Conn %d (socket %d) type %d (%s), state %d (%s), created %ld secs ago",
  661. i, conn->s, conn->type, conn_type_to_string[conn->type],
  662. conn->state, conn_state_to_string[conn->type][conn->state], now - conn->timestamp_created);
  663. if(!connection_is_listener(conn)) {
  664. log(severity,"Conn %d is to '%s:%d'.",i,conn->address, conn->port);
  665. log(severity,"Conn %d: %d bytes waiting on inbuf (last read %ld secs ago)",i,
  666. (int)buf_datalen(conn->inbuf),
  667. now - conn->timestamp_lastread);
  668. log(severity,"Conn %d: %d bytes waiting on outbuf (last written %ld secs ago)",i,
  669. (int)buf_datalen(conn->outbuf), now - conn->timestamp_lastwritten);
  670. }
  671. circuit_dump_by_conn(conn, severity); /* dump info about all the circuits using this conn */
  672. }
  673. log(severity,
  674. "Cells processed: %10lu padding\n"
  675. " %10lu create\n"
  676. " %10lu created\n"
  677. " %10lu relay\n"
  678. " (%10lu relayed)\n"
  679. " (%10lu delivered)\n"
  680. " %10lud destroy",
  681. stats_n_padding_cells_processed,
  682. stats_n_create_cells_processed,
  683. stats_n_created_cells_processed,
  684. stats_n_relay_cells_processed,
  685. stats_n_relay_cells_relayed,
  686. stats_n_relay_cells_delivered,
  687. stats_n_destroy_cells_processed);
  688. if (stats_n_data_cells_packaged)
  689. log(severity,"Average outgoing cell fullness: %2.3f%%",
  690. 100*(((double)stats_n_data_bytes_packaged) /
  691. (stats_n_data_cells_packaged*(CELL_PAYLOAD_SIZE-RELAY_HEADER_SIZE))) );
  692. if (stats_n_data_cells_received)
  693. log(severity,"Average incoming cell fullness: %2.3f%%",
  694. 100*(((double)stats_n_data_bytes_received) /
  695. (stats_n_data_cells_received*(CELL_PAYLOAD_SIZE-RELAY_HEADER_SIZE))) );
  696. if (stats_n_seconds_reading)
  697. log(severity,"Average bandwidth used: %d bytes/sec",
  698. (int) (stats_n_bytes_read/stats_n_seconds_reading));
  699. }
  700. int tor_main(int argc, char *argv[]) {
  701. /* give it somewhere to log to initially */
  702. add_stream_log(LOG_INFO, "<stdout>", stdout);
  703. log_fn(LOG_WARN,"Tor v%s. This is experimental software. Do not use it if you need anonymity.",VERSION);
  704. if (init_from_config(argc,argv) < 0)
  705. return -1;
  706. if(options.ORPort) { /* only spawn dns handlers if we're a router */
  707. dns_init(); /* initialize the dns resolve tree, and spawn workers */
  708. }
  709. if(options.SocksPort) {
  710. client_dns_init(); /* init the client dns cache */
  711. }
  712. #ifndef MS_WINDOWS /* do signal stuff only on unix */
  713. signal (SIGINT, catch); /* catch kills so we can exit cleanly */
  714. signal (SIGTERM, catch);
  715. signal (SIGUSR1, catch); /* to dump stats */
  716. signal (SIGHUP, catch); /* to reload directory */
  717. signal (SIGCHLD, catch); /* for exiting dns/cpu workers */
  718. #endif /* signal stuff */
  719. crypto_global_init();
  720. crypto_seed_rng();
  721. do_main_loop();
  722. crypto_global_cleanup();
  723. return -1;
  724. }
  725. /*
  726. Local Variables:
  727. mode:c
  728. indent-tabs-mode:nil
  729. c-basic-offset:2
  730. End:
  731. */