main.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857
  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.OnionRouter && !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.OnionRouter) {
  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_launch_new(-1); /* tell it to forget about previous failures */
  287. if(circ && circ->timestamp_dirty) {
  288. log_fn(LOG_INFO,"Youngest circuit dirty; launching replacement.");
  289. circuit_launch_new(0); /* 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(1);
  299. }
  300. /* 4. Every second, we check how much bandwidth we've consumed and
  301. * increment global_read_bucket.
  302. */
  303. stats_n_bytes_read += stats_prev_global_read_bucket-global_read_bucket;
  304. if(global_read_bucket < 9*options.TotalBandwidth) {
  305. global_read_bucket += options.TotalBandwidth;
  306. log_fn(LOG_DEBUG,"global_read_bucket now %d.", global_read_bucket);
  307. }
  308. stats_prev_global_read_bucket = global_read_bucket;
  309. /* 5. We do housekeeping for each connection... */
  310. for(i=0;i<nfds;i++) {
  311. run_connection_housekeeping(i, now);
  312. }
  313. /* 6. and blow away any connections that need to die. can't do this later
  314. * because we might open up a circuit and not realize we're about to cull
  315. * the connection it's running over.
  316. * XXX we can remove this step once we audit circuit-building to make sure
  317. * it doesn't pick a marked-for-close conn. -RD
  318. */
  319. for(i=0;i<nfds;i++)
  320. conn_close_if_marked(i);
  321. }
  322. static int prepare_for_poll(void) {
  323. static long current_second = 0; /* from previous calls to gettimeofday */
  324. connection_t *conn;
  325. struct timeval now;
  326. int i;
  327. tor_gettimeofday(&now);
  328. if(now.tv_sec > current_second) { /* the second has rolled over. check more stuff. */
  329. ++stats_n_seconds_reading;
  330. run_scheduled_events(now.tv_sec);
  331. current_second = now.tv_sec; /* remember which second it is, for next time */
  332. }
  333. for(i=0;i<nfds;i++) {
  334. conn = connection_array[i];
  335. if(connection_has_pending_tls_data(conn)) {
  336. log_fn(LOG_DEBUG,"sock %d has pending bytes.",conn->s);
  337. return 0; /* has pending bytes to read; don't let poll wait. */
  338. }
  339. }
  340. return (1000 - (now.tv_usec / 1000)); /* how many milliseconds til the next second? */
  341. }
  342. static crypto_pk_env_t *init_key_from_file(const char *fname)
  343. {
  344. crypto_pk_env_t *prkey = NULL;
  345. int fd = -1;
  346. FILE *file = NULL;
  347. if (!(prkey = crypto_new_pk_env(CRYPTO_PK_RSA))) {
  348. log(LOG_ERR, "Error creating crypto environment.");
  349. goto error;
  350. }
  351. switch(file_status(fname)) {
  352. case FN_DIR:
  353. case FN_ERROR:
  354. log(LOG_ERR, "Can't read key from %s", fname);
  355. goto error;
  356. case FN_NOENT:
  357. log(LOG_INFO, "No key found in %s; generating fresh key.", fname);
  358. if (crypto_pk_generate_key(prkey)) {
  359. log(LOG_ERR, "Error generating key: %s", crypto_perror());
  360. goto error;
  361. }
  362. if (crypto_pk_check_key(prkey) <= 0) {
  363. log(LOG_ERR, "Generated key seems invalid");
  364. goto error;
  365. }
  366. log(LOG_INFO, "Generated key seems valid");
  367. if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
  368. log(LOG_ERR, "Couldn't write generated key to %s.", fname);
  369. goto error;
  370. }
  371. return prkey;
  372. case FN_FILE:
  373. if (crypto_pk_read_private_key_from_filename(prkey, fname)) {
  374. log(LOG_ERR, "Error loading private key.");
  375. goto error;
  376. }
  377. return prkey;
  378. default:
  379. assert(0);
  380. }
  381. error:
  382. if (prkey)
  383. crypto_free_pk_env(prkey);
  384. if (fd >= 0 && !file)
  385. close(fd);
  386. if (file)
  387. fclose(file);
  388. return NULL;
  389. }
  390. static int init_keys(void)
  391. {
  392. char keydir[512];
  393. char fingerprint[FINGERPRINT_LEN+MAX_NICKNAME_LEN+3];
  394. char *cp;
  395. const char *tmp, *mydesc;
  396. crypto_pk_env_t *prkey;
  397. /* OP's don't need keys. Just initialize the TLS context.*/
  398. if (!options.OnionRouter) {
  399. assert(!options.DirPort);
  400. if (tor_tls_context_new(NULL, 0, NULL)<0) {
  401. log_fn(LOG_ERR, "Error creating TLS context for OP.");
  402. return -1;
  403. }
  404. return 0;
  405. }
  406. assert(options.DataDirectory);
  407. if (strlen(options.DataDirectory) > (512-128)) {
  408. log_fn(LOG_ERR, "DataDirectory is too long.");
  409. return -1;
  410. }
  411. if (check_private_dir(options.DataDirectory, 1)) {
  412. return -1;
  413. }
  414. sprintf(keydir,"%s/keys",options.DataDirectory);
  415. if (check_private_dir(keydir, 1)) {
  416. return -1;
  417. }
  418. cp = keydir + strlen(keydir); /* End of string. */
  419. /* 1. Read identity key. Make it if none is found. */
  420. strcpy(cp, "/identity.key");
  421. log_fn(LOG_INFO,"Reading/making identity key %s...",keydir);
  422. prkey = init_key_from_file(keydir);
  423. if (!prkey) return -1;
  424. set_identity_key(prkey);
  425. /* 2. Read onion key. Make it if none is found. */
  426. strcpy(cp, "/onion.key");
  427. log_fn(LOG_INFO,"Reading/making onion key %s...",keydir);
  428. prkey = init_key_from_file(keydir);
  429. if (!prkey) return -1;
  430. set_onion_key(prkey);
  431. /* 3. Initialize link key and TLS context. */
  432. strcpy(cp, "/link.key");
  433. log_fn(LOG_INFO,"Reading/making link key %s...",keydir);
  434. prkey = init_key_from_file(keydir);
  435. if (!prkey) return -1;
  436. set_link_key(prkey);
  437. if (tor_tls_context_new(prkey, 1, options.Nickname) < 0) {
  438. log_fn(LOG_ERR, "Error initializing TLS context");
  439. return -1;
  440. }
  441. /* 4. Dump router descriptor to 'router.desc' */
  442. /* Must be called after keys are initialized. */
  443. if (!(router_get_my_descriptor())) {
  444. log_fn(LOG_ERR, "Error initializing descriptor.");
  445. return -1;
  446. }
  447. /* We need to add our own fingerprint so it gets recognized. */
  448. if (dirserv_add_own_fingerprint(options.Nickname, get_identity_key())) {
  449. log_fn(LOG_ERR, "Error adding own fingerprint to approved set");
  450. return -1;
  451. }
  452. tmp = mydesc = router_get_my_descriptor();
  453. if (dirserv_add_descriptor(&tmp)) {
  454. log(LOG_ERR, "Unable to add own descriptor to directory.");
  455. return -1;
  456. }
  457. sprintf(keydir,"%s/router.desc", options.DataDirectory);
  458. log_fn(LOG_INFO,"Dumping descriptor to %s...",keydir);
  459. if (write_str_to_file(keydir, mydesc)) {
  460. return -1;
  461. }
  462. /* 5. Dump fingerprint to 'fingerprint' */
  463. sprintf(keydir,"%s/fingerprint", options.DataDirectory);
  464. log_fn(LOG_INFO,"Dumping fingerprint to %s...",keydir);
  465. assert(strlen(options.Nickname) <= MAX_NICKNAME_LEN);
  466. strcpy(fingerprint, options.Nickname);
  467. strcat(fingerprint, " ");
  468. if (crypto_pk_get_fingerprint(get_identity_key(),
  469. fingerprint+strlen(fingerprint))<0) {
  470. log_fn(LOG_ERR, "Error computing fingerprint");
  471. return -1;
  472. }
  473. strcat(fingerprint, "\n");
  474. if (write_str_to_file(keydir, fingerprint))
  475. return -1;
  476. if(!options.DirPort)
  477. return 0;
  478. /* 6. [dirserver only] load approved-routers file */
  479. sprintf(keydir,"%s/approved-routers", options.DataDirectory);
  480. log_fn(LOG_INFO,"Loading approved fingerprints from %s...",keydir);
  481. if(dirserv_parse_fingerprint_file(keydir) < 0) {
  482. log_fn(LOG_ERR, "Error loading fingerprints");
  483. return -1;
  484. }
  485. /* 7. [dirserver only] load old directory, if it's there */
  486. sprintf(keydir,"%s/cached-directory", options.DataDirectory);
  487. log_fn(LOG_INFO,"Loading cached directory from %s...",keydir);
  488. cp = read_file_to_str(keydir);
  489. if(!cp) {
  490. log_fn(LOG_INFO,"Cached directory %s not present. Ok.",keydir);
  491. } else {
  492. if(dirserv_init_from_directory_string(cp) < 0) {
  493. log_fn(LOG_ERR, "Cached directory %s is corrupt", keydir);
  494. free(cp);
  495. return -1;
  496. }
  497. free(cp);
  498. }
  499. /* success */
  500. return 0;
  501. }
  502. static int init_from_config(int argc, char **argv) {
  503. static int have_daemonized=0;
  504. if(getconfig(argc,argv,&options)) {
  505. log_fn(LOG_ERR,"Reading config failed. For usage, try -h.");
  506. return -1;
  507. }
  508. log_set_severity(options.loglevel); /* assign logging severity level from options */
  509. close_logs(); /* we'll close, then open with correct loglevel if necessary */
  510. if(!options.LogFile && !options.RunAsDaemon)
  511. add_stream_log(options.loglevel, "<stdout>", stdout);
  512. if(options.LogFile)
  513. if (add_file_log(options.loglevel, options.LogFile) != 0) {
  514. /* opening the log file failed! Use stderr and log a warning */
  515. add_stream_log(options.loglevel, "<stderr>", stderr);
  516. log_fn(LOG_WARN, "Cannot write to LogFile '%s': %s.", options.LogFile, strerror(errno));
  517. }
  518. if(options.DebugLogFile)
  519. if (add_file_log(LOG_DEBUG, options.DebugLogFile) != 0)
  520. log_fn(LOG_WARN, "Cannot write to DebugLogFile '%s': %s.", options.LogFile, strerror(errno));
  521. global_read_bucket = options.TotalBandwidth; /* start it at 1 second of traffic */
  522. stats_prev_global_read_bucket = global_read_bucket;
  523. if(options.User || options.Group) {
  524. if(switch_id(options.User, options.Group) != 0) {
  525. return -1;
  526. }
  527. }
  528. if(options.RunAsDaemon && !have_daemonized) {
  529. daemonize();
  530. have_daemonized = 1;
  531. }
  532. /* write our pid to the pid file, if we do not have write permissions we will log a warning */
  533. write_pidfile(options.PidFile);
  534. /* XXX Is overwriting the pidfile ok? I think it is. -RD */
  535. return 0;
  536. }
  537. static int do_main_loop(void) {
  538. int i;
  539. int timeout;
  540. int poll_result;
  541. /* load the routers file */
  542. if(router_get_list_from_file(options.RouterFile) < 0) {
  543. log_fn(LOG_ERR,"Error loading router list.");
  544. return -1;
  545. }
  546. /* load the private keys, if we're supposed to have them, and set up the
  547. * TLS context. */
  548. if (init_keys() < 0) {
  549. log_fn(LOG_ERR,"Error initializing keys; exiting");
  550. return -1;
  551. }
  552. if(options.OnionRouter) {
  553. cpu_init(); /* launch cpuworkers. Need to do this *after* we've read the onion key. */
  554. router_upload_desc_to_dirservers(); /* upload our descriptor to all dirservers */
  555. }
  556. /* start up the necessary connections based on which ports are
  557. * non-zero. This is where we try to connect to all the other ORs,
  558. * and start the listeners.
  559. */
  560. if(retry_all_connections() < 0) {
  561. log_fn(LOG_ERR,"Failed to bind one of the listener ports.");
  562. return -1;
  563. }
  564. for(;;) {
  565. #ifndef MS_WINDOWS /* do signal stuff only on unix */
  566. if(please_dumpstats) {
  567. /* prefer to log it at INFO, but make sure we always see it */
  568. dumpstats(options.loglevel>LOG_INFO ? options.loglevel : LOG_INFO);
  569. please_dumpstats = 0;
  570. }
  571. if(please_reset) {
  572. log_fn(LOG_INFO,"Hupped. Reloading config.");
  573. /* first, reload config variables, in case they've changed */
  574. if (init_from_config(0, NULL) < 0) {
  575. /* no need to provide argc/v, they've been cached inside init_from_config */
  576. exit(1);
  577. }
  578. /* fetch a new directory */
  579. if(options.DirPort) {
  580. /* reload the fingerprint file */
  581. char keydir[512];
  582. sprintf(keydir,"%s/approved-routers", options.DataDirectory);
  583. log_fn(LOG_INFO,"Reloading approved fingerprints from %s...",keydir);
  584. if(dirserv_parse_fingerprint_file(keydir) < 0) {
  585. log_fn(LOG_WARN, "Error reloading fingerprints. Continuing with old list.");
  586. }
  587. if(router_get_list_from_file(options.RouterFile) < 0) {
  588. log(LOG_WARN,"Error reloading router list. Continuing with old list.");
  589. }
  590. } else {
  591. directory_initiate_command(router_pick_directory_server(), DIR_CONN_STATE_CONNECTING_FETCH);
  592. }
  593. please_reset = 0;
  594. }
  595. if(please_reap_children) {
  596. while(waitpid(-1,NULL,WNOHANG)) ; /* keep reaping until no more zombies */
  597. please_reap_children = 0;
  598. }
  599. #endif /* signal stuff */
  600. timeout = prepare_for_poll();
  601. /* poll until we have an event, or the second ends */
  602. poll_result = poll(poll_array, nfds, timeout);
  603. /* let catch() handle things like ^c, and otherwise don't worry about it */
  604. if(poll_result < 0) {
  605. if(errno != EINTR) { /* let the program survive things like ^z */
  606. log_fn(LOG_ERR,"poll failed.");
  607. return -1;
  608. } else {
  609. log_fn(LOG_DEBUG,"poll interrupted.");
  610. }
  611. }
  612. /* do all the reads and errors first, so we can detect closed sockets */
  613. for(i=0;i<nfds;i++)
  614. conn_read(i); /* this also blows away broken connections */
  615. /* then do the writes */
  616. for(i=0;i<nfds;i++)
  617. conn_write(i);
  618. /* any of the conns need to be closed now? */
  619. for(i=0;i<nfds;i++)
  620. conn_close_if_marked(i);
  621. /* refilling buckets and sending cells happens at the beginning of the
  622. * next iteration of the loop, inside prepare_for_poll()
  623. */
  624. }
  625. }
  626. static void catch(int the_signal) {
  627. #ifndef MS_WINDOWS /* do signal stuff only on unix */
  628. switch(the_signal) {
  629. // case SIGABRT:
  630. case SIGTERM:
  631. case SIGINT:
  632. log(LOG_ERR,"Catching signal %d, exiting cleanly.", the_signal);
  633. /* we don't care if there was an error when we unlink, nothing
  634. we could do about it anyways */
  635. unlink(options.PidFile);
  636. exit(0);
  637. case SIGHUP:
  638. please_reset = 1;
  639. break;
  640. case SIGUSR1:
  641. please_dumpstats = 1;
  642. break;
  643. case SIGCHLD:
  644. please_reap_children = 1;
  645. break;
  646. default:
  647. log(LOG_WARN,"Caught signal %d that we can't handle??", the_signal);
  648. }
  649. #endif /* signal stuff */
  650. }
  651. static void dumpstats(int severity) {
  652. int i;
  653. connection_t *conn;
  654. time_t now = time(NULL);
  655. log(severity, "Dumping stats:");
  656. for(i=0;i<nfds;i++) {
  657. conn = connection_array[i];
  658. log(severity, "Conn %d (socket %d) type %d (%s), state %d (%s), created %ld secs ago",
  659. i, conn->s, conn->type, conn_type_to_string[conn->type],
  660. conn->state, conn_state_to_string[conn->type][conn->state], now - conn->timestamp_created);
  661. if(!connection_is_listener(conn)) {
  662. log(severity,"Conn %d is to '%s:%d'.",i,conn->address, conn->port);
  663. log(severity,"Conn %d: %d bytes waiting on inbuf (last read %ld secs ago)",i,
  664. (int)buf_datalen(conn->inbuf),
  665. now - conn->timestamp_lastread);
  666. log(severity,"Conn %d: %d bytes waiting on outbuf (last written %ld secs ago)",i,
  667. (int)buf_datalen(conn->outbuf), now - conn->timestamp_lastwritten);
  668. }
  669. circuit_dump_by_conn(conn, severity); /* dump info about all the circuits using this conn */
  670. }
  671. log(severity,
  672. "Cells processed: %10lu padding\n"
  673. " %10lu create\n"
  674. " %10lu created\n"
  675. " %10lu relay\n"
  676. " (%10lu relayed)\n"
  677. " (%10lu delivered)\n"
  678. " %10lud destroy",
  679. stats_n_padding_cells_processed,
  680. stats_n_create_cells_processed,
  681. stats_n_created_cells_processed,
  682. stats_n_relay_cells_processed,
  683. stats_n_relay_cells_relayed,
  684. stats_n_relay_cells_delivered,
  685. stats_n_destroy_cells_processed);
  686. if (stats_n_data_cells_packaged)
  687. log(severity,"Average outgoing cell fullness: %2.3f%%",
  688. 100*(((double)stats_n_data_bytes_packaged) /
  689. (stats_n_data_cells_packaged*(CELL_PAYLOAD_SIZE-RELAY_HEADER_SIZE))) );
  690. if (stats_n_data_cells_received)
  691. log(severity,"Average incoming cell fullness: %2.3f%%",
  692. 100*(((double)stats_n_data_bytes_received) /
  693. (stats_n_data_cells_received*(CELL_PAYLOAD_SIZE-RELAY_HEADER_SIZE))) );
  694. if (stats_n_seconds_reading)
  695. log(severity,"Average bandwidth used: %d bytes/sec",
  696. (int) (stats_n_bytes_read/stats_n_seconds_reading));
  697. }
  698. int tor_main(int argc, char *argv[]) {
  699. /* give it somewhere to log to initially */
  700. add_stream_log(LOG_INFO, "<stdout>", stdout);
  701. log_fn(LOG_WARN,"Tor v%s. This is experimental software. Do not use it if you need anonymity.",VERSION);
  702. if (init_from_config(argc,argv) < 0)
  703. return -1;
  704. if(options.OnionRouter) { /* only spawn dns handlers if we're a router */
  705. dns_init(); /* initialize the dns resolve tree, and spawn workers */
  706. }
  707. if(options.SocksPort) {
  708. client_dns_init(); /* init the client dns cache */
  709. }
  710. #ifndef MS_WINDOWS /* do signal stuff only on unix */
  711. signal (SIGINT, catch); /* catch kills so we can exit cleanly */
  712. signal (SIGTERM, catch);
  713. signal (SIGUSR1, catch); /* to dump stats */
  714. signal (SIGHUP, catch); /* to reload directory */
  715. signal (SIGCHLD, catch); /* for exiting dns/cpu workers */
  716. #endif /* signal stuff */
  717. crypto_global_init();
  718. crypto_seed_rng();
  719. do_main_loop();
  720. crypto_global_cleanup();
  721. return -1;
  722. }
  723. /*
  724. Local Variables:
  725. mode:c
  726. indent-tabs-mode:nil
  727. c-basic-offset:2
  728. End:
  729. */