main.c 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908
  1. /* Copyright 2001,2002,2003 Roger Dingledine, Matej Pfajfar. */
  2. /* See LICENSE for licensing information */
  3. /* $Id$ */
  4. /**
  5. * \file main.c
  6. * \brief Tor main loop and startup functions.
  7. **/
  8. #include "or.h"
  9. /********* PROTOTYPES **********/
  10. static void dumpstats(int severity); /* log stats */
  11. static int init_from_config(int argc, char **argv);
  12. /********* START VARIABLES **********/
  13. /* declared in connection.c */
  14. extern char *conn_state_to_string[][_CONN_TYPE_MAX+1];
  15. or_options_t options; /**< Command-line and config-file options. */
  16. int global_read_bucket; /**< Max number of bytes I can read this second. */
  17. /** What was the read bucket before the last call to prepare_for_pool?
  18. * (used to determine how many bytes we've read). */
  19. static int stats_prev_global_read_bucket;
  20. /** How many bytes have we read since we started the process? */
  21. static uint64_t stats_n_bytes_read = 0;
  22. /** How many seconds have we been running? */
  23. static long stats_n_seconds_reading = 0;
  24. /** Array of all open connections; each element corresponds to the element of
  25. * poll_array in the same position. The first nfds elements are valid. */
  26. static connection_t *connection_array[MAXCONNECTIONS] =
  27. { NULL };
  28. /** Array of pollfd objects for calls to poll(). */
  29. static struct pollfd poll_array[MAXCONNECTIONS];
  30. static int nfds=0; /**< Number of connections currently active. */
  31. #ifndef MS_WINDOWS /* do signal stuff only on unix */
  32. static int please_dumpstats=0; /**< Whether we should dump stats during the loop. */
  33. static int please_reset=0; /**< Whether we just got a sighup. */
  34. static int please_reap_children=0; /**< Whether we should waitpid for exited children. */
  35. #endif /* signal stuff */
  36. /** We set this to 1 when we've fetched a dir, to know whether to complain
  37. * yet about unrecognized nicknames in entrynodes, exitnodes, etc.
  38. * Also, we don't try building circuits unless this is 1. */
  39. int has_fetched_directory=0;
  40. /** We set this to 1 when we've opened a circuit, so we can print a log
  41. * entry to inform the user that Tor is working. */
  42. int has_completed_circuit=0;
  43. /********* END VARIABLES ************/
  44. /****************************************************************************
  45. *
  46. * This section contains accessors and other methods on the connection_array
  47. * and poll_array variables (which are global within this file and unavailable
  48. * outside it).
  49. *
  50. ****************************************************************************/
  51. /** Add <b>conn</b> to the array of connections that we can poll on. The
  52. * connection's socket must be set; the connection starts out
  53. * non-reading and non-writing.
  54. */
  55. int connection_add(connection_t *conn) {
  56. tor_assert(conn);
  57. tor_assert(conn->s >= 0);
  58. if(nfds >= options.MaxConn-1) {
  59. log_fn(LOG_WARN,"failing because nfds is too high.");
  60. return -1;
  61. }
  62. tor_assert(conn->poll_index == -1); /* can only connection_add once */
  63. conn->poll_index = nfds;
  64. connection_array[nfds] = conn;
  65. poll_array[nfds].fd = conn->s;
  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_fn(LOG_INFO,"new conn type %s, socket %d, nfds %d.",
  71. CONN_TYPE_TO_STRING(conn->type), conn->s, nfds);
  72. return 0;
  73. }
  74. /** Remove the connection from the global list, and remove the
  75. * corresponding poll entry. Calling this function will shift the last
  76. * connection (if any) into the position occupied by conn.
  77. */
  78. int connection_remove(connection_t *conn) {
  79. int current_index;
  80. tor_assert(conn);
  81. tor_assert(nfds>0);
  82. log_fn(LOG_INFO,"removing socket %d (type %s), nfds now %d",
  83. conn->s, CONN_TYPE_TO_STRING(conn->type), nfds-1);
  84. tor_assert(conn->poll_index >= 0);
  85. current_index = conn->poll_index;
  86. if(current_index == nfds-1) { /* this is the end */
  87. nfds--;
  88. return 0;
  89. }
  90. /* replace this one with the one at the end */
  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. /** Set <b>*array</b> to an array of all connections, and <b>*n</b>
  100. * to the length of the array. <b>*array</b> and <b>*n</b> must not
  101. * be modified.
  102. */
  103. void get_connection_array(connection_t ***array, int *n) {
  104. *array = connection_array;
  105. *n = nfds;
  106. }
  107. /** Set the event mask on <b>conn</b> to <b>events</b>. (The form of
  108. * the event mask is as for poll().)
  109. */
  110. void connection_watch_events(connection_t *conn, short events) {
  111. tor_assert(conn && conn->poll_index >= 0 && conn->poll_index < nfds);
  112. poll_array[conn->poll_index].events = events;
  113. }
  114. /** Return true iff <b>conn</b> is listening for read events. */
  115. int connection_is_reading(connection_t *conn) {
  116. tor_assert(conn && conn->poll_index >= 0);
  117. return poll_array[conn->poll_index].events & POLLIN;
  118. }
  119. /** Tell the main loop to stop notifying <b>conn</b> of any read events. */
  120. void connection_stop_reading(connection_t *conn) {
  121. tor_assert(conn && conn->poll_index >= 0 && conn->poll_index < nfds);
  122. log(LOG_DEBUG,"connection_stop_reading() called.");
  123. if(poll_array[conn->poll_index].events & POLLIN)
  124. poll_array[conn->poll_index].events -= POLLIN;
  125. }
  126. /** Tell the main loop to start notifying <b>conn</b> of any read events. */
  127. void connection_start_reading(connection_t *conn) {
  128. tor_assert(conn && conn->poll_index >= 0 && conn->poll_index < nfds);
  129. poll_array[conn->poll_index].events |= POLLIN;
  130. }
  131. /** Return true iff <b>conn</b> is listening for write events. */
  132. int connection_is_writing(connection_t *conn) {
  133. return poll_array[conn->poll_index].events & POLLOUT;
  134. }
  135. /** Tell the main loop to stop notifying <b>conn</b> of any write events. */
  136. void connection_stop_writing(connection_t *conn) {
  137. tor_assert(conn && conn->poll_index >= 0 && conn->poll_index < nfds);
  138. if(poll_array[conn->poll_index].events & POLLOUT)
  139. poll_array[conn->poll_index].events -= POLLOUT;
  140. }
  141. /** Tell the main loop to start notifying <b>conn</b> of any write events. */
  142. void connection_start_writing(connection_t *conn) {
  143. tor_assert(conn && conn->poll_index >= 0 && conn->poll_index < nfds);
  144. poll_array[conn->poll_index].events |= POLLOUT;
  145. }
  146. /** Called when the connection at connection_array[i] has a read event,
  147. * or it has pending tls data waiting to be read: checks for validity,
  148. * catches numerous errors, and dispatches to connection_handle_read.
  149. */
  150. static void conn_read(int i) {
  151. connection_t *conn = connection_array[i];
  152. if (conn->marked_for_close)
  153. return;
  154. /* see http://www.greenend.org.uk/rjk/2001/06/poll.html for
  155. * discussion of POLLIN vs POLLHUP */
  156. if(!(poll_array[i].revents & (POLLIN|POLLHUP|POLLERR)))
  157. if(!connection_is_reading(conn) ||
  158. !connection_has_pending_tls_data(conn))
  159. return; /* this conn should not read */
  160. log_fn(LOG_DEBUG,"socket %d wants to read.",conn->s);
  161. assert_connection_ok(conn, time(NULL));
  162. assert_all_pending_dns_resolves_ok();
  163. if(
  164. /* XXX does POLLHUP also mean it's definitely broken? */
  165. #ifdef MS_WINDOWS
  166. (poll_array[i].revents & POLLERR) ||
  167. #endif
  168. connection_handle_read(conn) < 0) {
  169. if (!conn->marked_for_close) {
  170. /* this connection is broken. remove it */
  171. log_fn(LOG_WARN,"Unhandled error on read for %s connection (fd %d); removing",
  172. CONN_TYPE_TO_STRING(conn->type), conn->s);
  173. connection_mark_for_close(conn);
  174. }
  175. }
  176. assert_connection_ok(conn, time(NULL));
  177. assert_all_pending_dns_resolves_ok();
  178. }
  179. /** Called when the connection at connection_array[i] has a write event:
  180. * checks for validity, catches numerous errors, and dispatches to
  181. * connection_handle_write.
  182. */
  183. static void conn_write(int i) {
  184. connection_t *conn;
  185. if(!(poll_array[i].revents & POLLOUT))
  186. return; /* this conn doesn't want to write */
  187. conn = connection_array[i];
  188. log_fn(LOG_DEBUG,"socket %d wants to write.",conn->s);
  189. if (conn->marked_for_close)
  190. return;
  191. assert_connection_ok(conn, time(NULL));
  192. assert_all_pending_dns_resolves_ok();
  193. if (connection_handle_write(conn) < 0) {
  194. if (!conn->marked_for_close) {
  195. /* this connection is broken. remove it. */
  196. log_fn(LOG_WARN,"Unhandled error on read for %s connection (fd %d); removing",
  197. CONN_TYPE_TO_STRING(conn->type), conn->s);
  198. conn->has_sent_end = 1; /* otherwise we cry wolf about duplicate close */
  199. /* XXX do we need a close-immediate here, so we don't try to flush? */
  200. connection_mark_for_close(conn);
  201. }
  202. }
  203. assert_connection_ok(conn, time(NULL));
  204. assert_all_pending_dns_resolves_ok();
  205. }
  206. /** If the connection at connection_array[i] is marked for close, then:
  207. * - If it has data that it wants to flush, try to flush it.
  208. * - If it _still_ has data to flush, and conn->hold_open_until_flushed is
  209. * true, then leave the connection open and return.
  210. * - Otherwise, remove the connection from connection_array and from
  211. * all other lists, close it, and free it.
  212. * If we remove the connection, then call conn_closed_if_marked at the new
  213. * connection at position i.
  214. */
  215. static void conn_close_if_marked(int i) {
  216. connection_t *conn;
  217. int retval;
  218. conn = connection_array[i];
  219. assert_connection_ok(conn, time(NULL));
  220. assert_all_pending_dns_resolves_ok();
  221. if(!conn->marked_for_close)
  222. return; /* nothing to see here, move along */
  223. log_fn(LOG_INFO,"Cleaning up connection (fd %d).",conn->s);
  224. if(conn->s >= 0 && connection_wants_to_flush(conn)) {
  225. /* -1 means it's an incomplete edge connection, or that the socket
  226. * has already been closed as unflushable. */
  227. if(!conn->hold_open_until_flushed)
  228. log_fn(LOG_WARN,
  229. "Conn (fd %d, type %s, state %d) marked, but wants to flush %d bytes. "
  230. "(Marked at %s:%d)",
  231. conn->s, CONN_TYPE_TO_STRING(conn->type), conn->state,
  232. conn->outbuf_flushlen, conn->marked_for_close_file, conn->marked_for_close);
  233. if(connection_speaks_cells(conn)) {
  234. if(conn->state == OR_CONN_STATE_OPEN) {
  235. retval = flush_buf_tls(conn->tls, conn->outbuf, &conn->outbuf_flushlen);
  236. } else
  237. retval = -1; /* never flush non-open broken tls connections */
  238. } else {
  239. retval = flush_buf(conn->s, conn->outbuf, &conn->outbuf_flushlen);
  240. }
  241. if(retval >= 0 &&
  242. conn->hold_open_until_flushed && connection_wants_to_flush(conn)) {
  243. log_fn(LOG_INFO,"Holding conn (fd %d) open for more flushing.",conn->s);
  244. /* XXX should we reset timestamp_lastwritten here? */
  245. return;
  246. }
  247. if(connection_wants_to_flush(conn)) {
  248. log_fn(LOG_WARN,"Conn (fd %d, type %s, state %d) still wants to flush. Losing %d bytes! (Marked at %s:%d)",
  249. conn->s, CONN_TYPE_TO_STRING(conn->type), conn->state,
  250. (int)buf_datalen(conn->outbuf), conn->marked_for_close_file,
  251. conn->marked_for_close);
  252. }
  253. }
  254. /* if it's an edge conn, remove it from the list
  255. * of conn's on this circuit. If it's not on an edge,
  256. * flush and send destroys for all circuits on this conn
  257. */
  258. circuit_about_to_close_connection(conn);
  259. connection_about_to_close_connection(conn);
  260. connection_remove(conn);
  261. if(conn->type == CONN_TYPE_EXIT) {
  262. assert_connection_edge_not_dns_pending(conn);
  263. }
  264. connection_free(conn);
  265. if(i<nfds) { /* we just replaced the one at i with a new one.
  266. process it too. */
  267. conn_close_if_marked(i);
  268. }
  269. }
  270. /** This function is called whenever we successfully pull down a directory */
  271. void directory_has_arrived(void) {
  272. log_fn(LOG_INFO, "A directory has arrived.");
  273. has_fetched_directory=1;
  274. if(options.ORPort) { /* connect to them all */
  275. router_retry_connections();
  276. }
  277. }
  278. /** Perform regular maintenance tasks for a single connection. This
  279. * function gets run once per second per connection by run_housekeeping.
  280. */
  281. static void run_connection_housekeeping(int i, time_t now) {
  282. cell_t cell;
  283. connection_t *conn = connection_array[i];
  284. /* Expire any directory connections that haven't sent anything for 5 min */
  285. if(conn->type == CONN_TYPE_DIR &&
  286. !conn->marked_for_close &&
  287. conn->timestamp_lastwritten + 5*60 < now) {
  288. log_fn(LOG_WARN,"Expiring wedged directory conn (fd %d, purpose %d)", conn->s, conn->purpose);
  289. /* XXXX This next check may help isolate where the pesky EPIPE bug
  290. * really occurs. */
  291. if (connection_wants_to_flush(conn)) {
  292. if(flush_buf(conn->s, conn->outbuf, &conn->outbuf_flushlen) < 0) {
  293. log_fn(LOG_WARN,"flushing expired directory conn failed.");
  294. connection_close_immediate(conn);
  295. connection_mark_for_close(conn);
  296. /* */
  297. } else {
  298. /* XXXX Does this next part make sense, really? */
  299. connection_mark_for_close(conn);
  300. conn->hold_open_until_flushed = 1; /* give it a last chance */
  301. }
  302. }
  303. return;
  304. }
  305. /* check connections to see whether we should send a keepalive, expire, or wait */
  306. if(!connection_speaks_cells(conn))
  307. return;
  308. /* If we haven't written to an OR connection for a while, then either nuke
  309. the connection or send a keepalive, depending. */
  310. if(now >= conn->timestamp_lastwritten + options.KeepalivePeriod) {
  311. if((!options.ORPort && !circuit_get_by_conn(conn)) ||
  312. (!connection_state_is_open(conn))) {
  313. /* we're an onion proxy, with no circuits; or our handshake has expired. kill it. */
  314. log_fn(LOG_INFO,"Expiring connection to %d (%s:%d).",
  315. i,conn->address, conn->port);
  316. /* flush anything waiting, e.g. a destroy for a just-expired circ */
  317. connection_mark_for_close(conn);
  318. conn->hold_open_until_flushed = 1;
  319. } else {
  320. /* either a full router, or we've got a circuit. send a padding cell. */
  321. log_fn(LOG_DEBUG,"Sending keepalive to (%s:%d)",
  322. conn->address, conn->port);
  323. memset(&cell,0,sizeof(cell_t));
  324. cell.command = CELL_PADDING;
  325. connection_or_write_cell_to_buf(&cell, conn);
  326. }
  327. }
  328. }
  329. /** Perform regular maintenance tasks. This function gets run once per
  330. * second by prepare_for_poll.
  331. */
  332. static void run_scheduled_events(time_t now) {
  333. static long time_to_fetch_directory = 0;
  334. static time_t last_uploaded_services = 0;
  335. static time_t last_rotated_certificate = 0;
  336. int i;
  337. /** 1a. Every MIN_ONION_KEY_LIFETIME seconds, rotate the onion keys,
  338. * shut down and restart all cpuworkers, and update the directory if
  339. * necessary.
  340. */
  341. if (options.ORPort && get_onion_key_set_at()+MIN_ONION_KEY_LIFETIME < now) {
  342. log_fn(LOG_INFO,"Rotating onion key.");
  343. rotate_onion_key();
  344. cpuworkers_rotate();
  345. if (router_rebuild_descriptor()<0) {
  346. log_fn(LOG_WARN, "Couldn't rebuild router descriptor");
  347. }
  348. router_upload_dir_desc_to_dirservers();
  349. }
  350. /** 1b. Every MAX_SSL_KEY_LIFETIME seconds, we change our TLS context. */
  351. if (!last_rotated_certificate)
  352. last_rotated_certificate = now;
  353. if (options.ORPort && last_rotated_certificate+MAX_SSL_KEY_LIFETIME < now) {
  354. log_fn(LOG_INFO,"Rotating tls context.");
  355. if (tor_tls_context_new(get_identity_key(), 1, options.Nickname,
  356. MAX_SSL_KEY_LIFETIME) < 0) {
  357. log_fn(LOG_WARN, "Error reinitializing TLS context");
  358. }
  359. last_rotated_certificate = now;
  360. /* XXXX We should rotate TLS connections as well; this code doesn't change
  361. * XXXX them at all. */
  362. }
  363. /** 1c. Every DirFetchPostPeriod seconds, we get a new directory and upload
  364. * our descriptor (if any). */
  365. if(time_to_fetch_directory < now) {
  366. /* it's time to fetch a new directory and/or post our descriptor */
  367. if(options.ORPort) {
  368. router_rebuild_descriptor();
  369. router_upload_dir_desc_to_dirservers();
  370. }
  371. if(!options.DirPort) {
  372. /* NOTE directory servers do not currently fetch directories.
  373. * Hope this doesn't bite us later. */
  374. directory_get_from_dirserver(DIR_PURPOSE_FETCH_DIR, NULL, 0);
  375. } else {
  376. /* We're a directory; dump any old descriptors. */
  377. dirserv_remove_old_servers();
  378. }
  379. /* Force an upload of our descriptors every DirFetchPostPeriod seconds. */
  380. rend_services_upload(1);
  381. last_uploaded_services = now;
  382. rend_cache_clean(); /* should this go elsewhere? */
  383. time_to_fetch_directory = now + options.DirFetchPostPeriod;
  384. }
  385. /** 2. Every second, we examine pending circuits and prune the
  386. * ones which have been pending for more than a few seconds.
  387. * We do this before step 3, so it can try building more if
  388. * it's not comfortable with the number of available circuits.
  389. */
  390. circuit_expire_building(now);
  391. /** 2b. Also look at pending streams and prune the ones that 'began'
  392. * a long time ago but haven't gotten a 'connected' yet.
  393. * Do this before step 3, so we can put them back into pending
  394. * state to be picked up by the new circuit.
  395. */
  396. connection_ap_expire_beginning();
  397. /** 2c. And expire connections that we've held open for too long.
  398. */
  399. connection_expire_held_open();
  400. /** 3. Every second, we try a new circuit if there are no valid
  401. * circuits. Every NewCircuitPeriod seconds, we expire circuits
  402. * that became dirty more than NewCircuitPeriod seconds ago,
  403. * and we make a new circ if there are no clean circuits.
  404. */
  405. if(has_fetched_directory)
  406. circuit_build_needed_circs(now);
  407. /** 4. We do housekeeping for each connection... */
  408. for(i=0;i<nfds;i++) {
  409. run_connection_housekeeping(i, now);
  410. }
  411. /** 5. And remove any marked circuits... */
  412. circuit_close_all_marked();
  413. /** 6. And upload service descriptors for any services whose intro points
  414. * have changed in the last second. */
  415. if (last_uploaded_services < now-5) {
  416. rend_services_upload(0);
  417. last_uploaded_services = now;
  418. }
  419. /** 7. and blow away any connections that need to die. have to do this now,
  420. * because if we marked a conn for close and left its socket -1, then
  421. * we'll pass it to poll/select and bad things will happen.
  422. */
  423. for(i=0;i<nfds;i++)
  424. conn_close_if_marked(i);
  425. }
  426. /** Called every time we're about to call tor_poll. Increments statistics,
  427. * and adjusts token buckets. Returns the number of milliseconds to use for
  428. * the poll() timeout.
  429. */
  430. static int prepare_for_poll(void) {
  431. static long current_second = 0; /* from previous calls to gettimeofday */
  432. connection_t *conn;
  433. struct timeval now;
  434. int i;
  435. tor_gettimeofday(&now);
  436. /* Check how much bandwidth we've consumed, and increment the token
  437. * buckets. */
  438. stats_n_bytes_read += stats_prev_global_read_bucket-global_read_bucket;
  439. connection_bucket_refill(&now);
  440. stats_prev_global_read_bucket = global_read_bucket;
  441. if(now.tv_sec > current_second) { /* the second has rolled over. check more stuff. */
  442. ++stats_n_seconds_reading;
  443. assert_all_pending_dns_resolves_ok();
  444. run_scheduled_events(now.tv_sec);
  445. assert_all_pending_dns_resolves_ok();
  446. current_second = now.tv_sec; /* remember which second it is, for next time */
  447. }
  448. for(i=0;i<nfds;i++) {
  449. conn = connection_array[i];
  450. if(connection_has_pending_tls_data(conn) &&
  451. connection_is_reading(conn)) {
  452. log_fn(LOG_DEBUG,"sock %d has pending bytes.",conn->s);
  453. return 0; /* has pending bytes to read; don't let poll wait. */
  454. }
  455. }
  456. return (1000 - (now.tv_usec / 1000)); /* how many milliseconds til the next second? */
  457. }
  458. /** Configure the Tor process from the command line arguments and from the
  459. * configuration file.
  460. */
  461. static int init_from_config(int argc, char **argv) {
  462. /* read the configuration file. */
  463. if(getconfig(argc,argv,&options)) {
  464. log_fn(LOG_ERR,"Reading config failed. For usage, try -h.");
  465. return -1;
  466. }
  467. close_logs(); /* we'll close, then open with correct loglevel if necessary */
  468. /* Setuid/setgid as appropriate */
  469. if(options.User || options.Group) {
  470. if(switch_id(options.User, options.Group) != 0) {
  471. return -1;
  472. }
  473. }
  474. /* Start backgrounding the process, if requested. */
  475. if (options.RunAsDaemon) {
  476. start_daemon(options.DataDirectory);
  477. }
  478. /* Configure the log(s) */
  479. config_init_logs(&options);
  480. /* Set up our buckets */
  481. connection_bucket_init();
  482. stats_prev_global_read_bucket = global_read_bucket;
  483. /* Finish backgrounding the process */
  484. if(options.RunAsDaemon) {
  485. /* XXXX Can we delay this any more? */
  486. finish_daemon();
  487. }
  488. /* Write our pid to the pid file. if we do not have write permissions we
  489. * will log a warning */
  490. if(options.PidFile)
  491. write_pidfile(options.PidFile);
  492. return 0;
  493. }
  494. /** Called when we get a SIGHUP: reload configuration files and keys,
  495. * retry all connections, re-upload all descriptors, and so on. */
  496. static int do_hup(void) {
  497. char keydir[512];
  498. log_fn(LOG_NOTICE,"Received sighup. Reloading config.");
  499. has_completed_circuit=0;
  500. /* first, reload config variables, in case they've changed */
  501. /* no need to provide argc/v, they've been cached inside init_from_config */
  502. if (init_from_config(0, NULL) < 0) {
  503. exit(1);
  504. }
  505. /* reload keys as needed for rendezvous services. */
  506. if (rend_service_load_keys()<0) {
  507. log_fn(LOG_ERR,"Error reloading rendezvous service keys");
  508. exit(1);
  509. }
  510. if(retry_all_connections() < 0) {
  511. log_fn(LOG_ERR,"Failed to bind one of the listener ports.");
  512. return -1;
  513. }
  514. if(options.DirPort) {
  515. /* reload the approved-routers file */
  516. sprintf(keydir,"%s/approved-routers", options.DataDirectory);
  517. log_fn(LOG_INFO,"Reloading approved fingerprints from %s...",keydir);
  518. if(dirserv_parse_fingerprint_file(keydir) < 0) {
  519. log_fn(LOG_WARN, "Error reloading fingerprints. Continuing with old list.");
  520. }
  521. /* Since we aren't fetching a directory, we won't retry rendezvous points
  522. * when it gets in. Try again now. */
  523. rend_services_introduce();
  524. } else {
  525. /* fetch a new directory */
  526. directory_get_from_dirserver(DIR_PURPOSE_FETCH_DIR, NULL, 0);
  527. }
  528. if(options.ORPort) {
  529. router_rebuild_descriptor();
  530. sprintf(keydir,"%s/router.desc", options.DataDirectory);
  531. log_fn(LOG_INFO,"Dumping descriptor to %s...",keydir);
  532. if (write_str_to_file(keydir, router_get_my_descriptor())) {
  533. return -1;
  534. }
  535. }
  536. return 0;
  537. }
  538. /** Tor main loop. */
  539. static int do_main_loop(void) {
  540. int i;
  541. int timeout;
  542. int poll_result;
  543. /* Initialize the history structures. */
  544. rep_hist_init();
  545. /* Intialize the service cache. */
  546. rend_cache_init();
  547. /* load the private keys, if we're supposed to have them, and set up the
  548. * TLS context. */
  549. if (init_keys() < 0 || rend_service_load_keys() < 0) {
  550. log_fn(LOG_ERR,"Error initializing keys; exiting");
  551. return -1;
  552. }
  553. /* load the routers file */
  554. if(options.RouterFile) {
  555. routerlist_clear_trusted_directories();
  556. if (router_load_routerlist_from_file(options.RouterFile, 1) < 0) {
  557. log_fn(LOG_ERR,"Error loading router list.");
  558. return -1;
  559. }
  560. }
  561. if(options.DirPort) { /* the directory is already here, run startup things */
  562. has_fetched_directory = 1;
  563. directory_has_arrived();
  564. }
  565. if(options.ORPort) {
  566. cpu_init(); /* launch cpuworkers. Need to do this *after* we've read the onion key. */
  567. }
  568. /* start up the necessary connections based on which ports are
  569. * non-zero. This is where we try to connect to all the other ORs,
  570. * and start the listeners.
  571. */
  572. if(retry_all_connections() < 0) {
  573. log_fn(LOG_ERR,"Failed to bind one of the listener ports.");
  574. return -1;
  575. }
  576. for(;;) {
  577. #ifndef MS_WINDOWS /* do signal stuff only on unix */
  578. if(please_dumpstats) {
  579. /* prefer to log it at INFO, but make sure we always see it */
  580. dumpstats(get_min_log_level()>LOG_INFO ? get_min_log_level() : LOG_INFO);
  581. please_dumpstats = 0;
  582. }
  583. if(please_reset) {
  584. do_hup();
  585. please_reset = 0;
  586. }
  587. if(please_reap_children) {
  588. while(waitpid(-1,NULL,WNOHANG)) ; /* keep reaping until no more zombies */
  589. please_reap_children = 0;
  590. }
  591. #endif /* signal stuff */
  592. timeout = prepare_for_poll();
  593. /* poll until we have an event, or the second ends */
  594. poll_result = tor_poll(poll_array, nfds, timeout);
  595. /* let catch() handle things like ^c, and otherwise don't worry about it */
  596. if(poll_result < 0) {
  597. /* let the program survive things like ^z */
  598. if(tor_socket_errno(-1) != EINTR) {
  599. log_fn(LOG_ERR,"poll failed: %s [%d]",
  600. tor_socket_strerror(tor_socket_errno(-1)),
  601. tor_socket_errno(-1));
  602. return -1;
  603. } else {
  604. log_fn(LOG_DEBUG,"poll interrupted.");
  605. }
  606. }
  607. /* do all the reads and errors first, so we can detect closed sockets */
  608. for(i=0;i<nfds;i++)
  609. conn_read(i); /* this also marks broken connections */
  610. /* then do the writes */
  611. for(i=0;i<nfds;i++)
  612. conn_write(i);
  613. /* any of the conns need to be closed now? */
  614. for(i=0;i<nfds;i++)
  615. conn_close_if_marked(i);
  616. /* refilling buckets and sending cells happens at the beginning of the
  617. * next iteration of the loop, inside prepare_for_poll()
  618. */
  619. }
  620. }
  621. /** Unix signal handler. */
  622. static void catch(int the_signal) {
  623. #ifndef MS_WINDOWS /* do signal stuff only on unix */
  624. switch(the_signal) {
  625. // case SIGABRT:
  626. case SIGTERM:
  627. case SIGINT:
  628. log(LOG_ERR,"Catching signal %d, exiting cleanly.", the_signal);
  629. /* we don't care if there was an error when we unlink, nothing
  630. we could do about it anyways */
  631. if(options.PidFile)
  632. unlink(options.PidFile);
  633. exit(0);
  634. case SIGPIPE:
  635. log(LOG_WARN,"Bug: caught sigpipe. Ignoring.");
  636. break;
  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. /** Write all statistics to the log, with log level 'severity'. Called
  652. * in response to a SIGUSR1. */
  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 %d 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], (int)(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 %d secs ago)",i,
  666. (int)buf_datalen(conn->inbuf),
  667. (int)(now - conn->timestamp_lastread));
  668. log(severity,"Conn %d: %d bytes waiting on outbuf (last written %d secs ago)",i,
  669. (int)buf_datalen(conn->outbuf), (int)(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. " %10lu 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 packaged cell fullness: %2.3f%%",
  690. 100*(((double)stats_n_data_bytes_packaged) /
  691. (stats_n_data_cells_packaged*RELAY_PAYLOAD_SIZE)) );
  692. if (stats_n_data_cells_received)
  693. log(severity,"Average delivered cell fullness: %2.3f%%",
  694. 100*(((double)stats_n_data_bytes_received) /
  695. (stats_n_data_cells_received*RELAY_PAYLOAD_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. rep_hist_dump_stats(now,severity);
  700. rend_service_dump_stats(severity);
  701. }
  702. /** Called before we make any calls to network-related functions.
  703. * (Some operating systems require their network libraries to be
  704. * initialized.) */
  705. int network_init(void)
  706. {
  707. #ifdef MS_WINDOWS
  708. /* This silly exercise is necessary before windows will allow gethostbyname to work.
  709. */
  710. WSADATA WSAData;
  711. int r;
  712. r = WSAStartup(0x101,&WSAData);
  713. if (r) {
  714. log_fn(LOG_WARN,"Error initializing windows network layer: code was %d",r);
  715. return -1;
  716. }
  717. /* XXXX We should call WSACleanup on exit, I think. */
  718. #endif
  719. return 0;
  720. }
  721. /** Called by exit() as we shut down the process.
  722. */
  723. void exit_function(void)
  724. {
  725. #ifdef MS_WINDOWS
  726. WSACleanup();
  727. #endif
  728. }
  729. /** Main entry point for the Tor command-line client.
  730. */
  731. int tor_main(int argc, char *argv[]) {
  732. /* give it somewhere to log to initially */
  733. add_stream_log(LOG_INFO, LOG_ERR, "<stdout>", stdout);
  734. log_fn(LOG_NOTICE,"Tor v%s. This is experimental software. Do not use it if you need anonymity.",VERSION);
  735. if (network_init()<0) {
  736. log_fn(LOG_ERR,"Error initializing network; exiting.");
  737. return 1;
  738. }
  739. atexit(exit_function);
  740. if (init_from_config(argc,argv) < 0)
  741. return -1;
  742. #ifndef MS_WINDOWS
  743. if(geteuid()==0)
  744. log_fn(LOG_WARN,"You are running Tor as root. You don't need to, and you probably shouldn't.");
  745. #endif
  746. if(options.ORPort) { /* only spawn dns handlers if we're a router */
  747. dns_init(); /* initialize the dns resolve tree, and spawn workers */
  748. }
  749. if(options.SocksPort) {
  750. client_dns_init(); /* init the client dns cache */
  751. }
  752. #ifndef MS_WINDOWS /* do signal stuff only on unix */
  753. {
  754. struct sigaction action;
  755. action.sa_flags = 0;
  756. sigemptyset(&action.sa_mask);
  757. action.sa_handler = catch;
  758. sigaction(SIGINT, &action, NULL);
  759. sigaction(SIGTERM, &action, NULL);
  760. sigaction(SIGPIPE, &action, NULL);
  761. sigaction(SIGUSR1, &action, NULL);
  762. sigaction(SIGHUP, &action, NULL); /* to reload config, retry conns, etc */
  763. sigaction(SIGCHLD, &action, NULL); /* handle dns/cpu workers that exit */
  764. }
  765. #endif /* signal stuff */
  766. crypto_global_init();
  767. crypto_seed_rng();
  768. do_main_loop();
  769. crypto_global_cleanup();
  770. return -1;
  771. }
  772. /*
  773. Local Variables:
  774. mode:c
  775. indent-tabs-mode:nil
  776. c-basic-offset:2
  777. End:
  778. */