main.c 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023
  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. #ifdef MS_WINDOWS
  44. SERVICE_STATUS service_status;
  45. SERVICE_STATUS_HANDLE hStatus;
  46. #endif
  47. /********* END VARIABLES ************/
  48. /****************************************************************************
  49. *
  50. * This section contains accessors and other methods on the connection_array
  51. * and poll_array variables (which are global within this file and unavailable
  52. * outside it).
  53. *
  54. ****************************************************************************/
  55. /** Add <b>conn</b> to the array of connections that we can poll on. The
  56. * connection's socket must be set; the connection starts out
  57. * non-reading and non-writing.
  58. */
  59. int connection_add(connection_t *conn) {
  60. tor_assert(conn);
  61. tor_assert(conn->s >= 0);
  62. if(nfds >= options.MaxConn-1) {
  63. log_fn(LOG_WARN,"failing because nfds is too high.");
  64. return -1;
  65. }
  66. tor_assert(conn->poll_index == -1); /* can only connection_add once */
  67. conn->poll_index = nfds;
  68. connection_array[nfds] = conn;
  69. poll_array[nfds].fd = conn->s;
  70. /* zero these out here, because otherwise we'll inherit values from the previously freed one */
  71. poll_array[nfds].events = 0;
  72. poll_array[nfds].revents = 0;
  73. nfds++;
  74. log_fn(LOG_INFO,"new conn type %s, socket %d, nfds %d.",
  75. CONN_TYPE_TO_STRING(conn->type), conn->s, nfds);
  76. return 0;
  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. tor_assert(conn);
  85. tor_assert(nfds>0);
  86. log_fn(LOG_INFO,"removing socket %d (type %s), nfds now %d",
  87. conn->s, CONN_TYPE_TO_STRING(conn->type), nfds-1);
  88. tor_assert(conn->poll_index >= 0);
  89. current_index = conn->poll_index;
  90. if(current_index == nfds-1) { /* this is the end */
  91. nfds--;
  92. return 0;
  93. }
  94. /* replace this one with the one at the end */
  95. nfds--;
  96. poll_array[current_index].fd = poll_array[nfds].fd;
  97. poll_array[current_index].events = poll_array[nfds].events;
  98. poll_array[current_index].revents = poll_array[nfds].revents;
  99. connection_array[current_index] = connection_array[nfds];
  100. connection_array[current_index]->poll_index = current_index;
  101. return 0;
  102. }
  103. /** Return true iff conn is in the current poll array. */
  104. int connection_in_array(connection_t *conn) {
  105. int i;
  106. for (i=0; i<nfds; ++i) {
  107. if (conn==connection_array[i])
  108. return 1;
  109. }
  110. return 0;
  111. }
  112. /** Set <b>*array</b> to an array of all connections, and <b>*n</b>
  113. * to the length of the array. <b>*array</b> and <b>*n</b> must not
  114. * be modified.
  115. */
  116. void get_connection_array(connection_t ***array, int *n) {
  117. *array = connection_array;
  118. *n = nfds;
  119. }
  120. /** Set the event mask on <b>conn</b> to <b>events</b>. (The form of
  121. * the event mask is as for poll().)
  122. */
  123. void connection_watch_events(connection_t *conn, short events) {
  124. tor_assert(conn && conn->poll_index >= 0 && conn->poll_index < nfds);
  125. poll_array[conn->poll_index].events = events;
  126. }
  127. /** Return true iff <b>conn</b> is listening for read events. */
  128. int connection_is_reading(connection_t *conn) {
  129. tor_assert(conn && conn->poll_index >= 0);
  130. return poll_array[conn->poll_index].events & POLLIN;
  131. }
  132. /** Tell the main loop to stop notifying <b>conn</b> of any read events. */
  133. void connection_stop_reading(connection_t *conn) {
  134. tor_assert(conn && conn->poll_index >= 0 && conn->poll_index < nfds);
  135. log(LOG_DEBUG,"connection_stop_reading() called.");
  136. if(poll_array[conn->poll_index].events & POLLIN)
  137. poll_array[conn->poll_index].events -= POLLIN;
  138. }
  139. /** Tell the main loop to start notifying <b>conn</b> of any read events. */
  140. void connection_start_reading(connection_t *conn) {
  141. tor_assert(conn && conn->poll_index >= 0 && conn->poll_index < nfds);
  142. poll_array[conn->poll_index].events |= POLLIN;
  143. }
  144. /** Return true iff <b>conn</b> is listening for write events. */
  145. int connection_is_writing(connection_t *conn) {
  146. return poll_array[conn->poll_index].events & POLLOUT;
  147. }
  148. /** Tell the main loop to stop notifying <b>conn</b> of any write events. */
  149. void connection_stop_writing(connection_t *conn) {
  150. tor_assert(conn && conn->poll_index >= 0 && conn->poll_index < nfds);
  151. if(poll_array[conn->poll_index].events & POLLOUT)
  152. poll_array[conn->poll_index].events -= POLLOUT;
  153. }
  154. /** Tell the main loop to start notifying <b>conn</b> of any write events. */
  155. void connection_start_writing(connection_t *conn) {
  156. tor_assert(conn && conn->poll_index >= 0 && conn->poll_index < nfds);
  157. poll_array[conn->poll_index].events |= POLLOUT;
  158. }
  159. /** Called when the connection at connection_array[i] has a read event,
  160. * or it has pending tls data waiting to be read: checks for validity,
  161. * catches numerous errors, and dispatches to connection_handle_read.
  162. */
  163. static void conn_read(int i) {
  164. connection_t *conn = connection_array[i];
  165. if (conn->marked_for_close)
  166. return;
  167. /* see http://www.greenend.org.uk/rjk/2001/06/poll.html for
  168. * discussion of POLLIN vs POLLHUP */
  169. if(!(poll_array[i].revents & (POLLIN|POLLHUP|POLLERR)))
  170. if(!connection_is_reading(conn) ||
  171. !connection_has_pending_tls_data(conn))
  172. return; /* this conn should not read */
  173. log_fn(LOG_DEBUG,"socket %d wants to read.",conn->s);
  174. assert_connection_ok(conn, time(NULL));
  175. assert_all_pending_dns_resolves_ok();
  176. if(
  177. /* XXX does POLLHUP also mean it's definitely broken? */
  178. #ifdef MS_WINDOWS
  179. (poll_array[i].revents & POLLERR) ||
  180. #endif
  181. connection_handle_read(conn) < 0) {
  182. if (!conn->marked_for_close) {
  183. /* this connection is broken. remove it */
  184. log_fn(LOG_WARN,"Unhandled error on read for %s connection (fd %d); removing",
  185. CONN_TYPE_TO_STRING(conn->type), conn->s);
  186. connection_mark_for_close(conn);
  187. }
  188. }
  189. assert_connection_ok(conn, time(NULL));
  190. assert_all_pending_dns_resolves_ok();
  191. }
  192. /** Called when the connection at connection_array[i] has a write event:
  193. * checks for validity, catches numerous errors, and dispatches to
  194. * connection_handle_write.
  195. */
  196. static void conn_write(int i) {
  197. connection_t *conn;
  198. if(!(poll_array[i].revents & POLLOUT))
  199. return; /* this conn doesn't want to write */
  200. conn = connection_array[i];
  201. log_fn(LOG_DEBUG,"socket %d wants to write.",conn->s);
  202. if (conn->marked_for_close)
  203. return;
  204. assert_connection_ok(conn, time(NULL));
  205. assert_all_pending_dns_resolves_ok();
  206. if (connection_handle_write(conn) < 0) {
  207. if (!conn->marked_for_close) {
  208. /* this connection is broken. remove it. */
  209. log_fn(LOG_WARN,"Unhandled error on read for %s connection (fd %d); removing",
  210. CONN_TYPE_TO_STRING(conn->type), conn->s);
  211. conn->has_sent_end = 1; /* otherwise we cry wolf about duplicate close */
  212. /* XXX do we need a close-immediate here, so we don't try to flush? */
  213. connection_mark_for_close(conn);
  214. }
  215. }
  216. assert_connection_ok(conn, time(NULL));
  217. assert_all_pending_dns_resolves_ok();
  218. }
  219. /** If the connection at connection_array[i] is marked for close, then:
  220. * - If it has data that it wants to flush, try to flush it.
  221. * - If it _still_ has data to flush, and conn->hold_open_until_flushed is
  222. * true, then leave the connection open and return.
  223. * - Otherwise, remove the connection from connection_array and from
  224. * all other lists, close it, and free it.
  225. * If we remove the connection, then call conn_closed_if_marked at the new
  226. * connection at position i.
  227. */
  228. static void conn_close_if_marked(int i) {
  229. connection_t *conn;
  230. int retval;
  231. conn = connection_array[i];
  232. assert_connection_ok(conn, time(NULL));
  233. assert_all_pending_dns_resolves_ok();
  234. if(!conn->marked_for_close)
  235. return; /* nothing to see here, move along */
  236. log_fn(LOG_INFO,"Cleaning up connection (fd %d).",conn->s);
  237. if(conn->s >= 0 && connection_wants_to_flush(conn)) {
  238. /* -1 means it's an incomplete edge connection, or that the socket
  239. * has already been closed as unflushable. */
  240. if(!conn->hold_open_until_flushed)
  241. log_fn(LOG_WARN,
  242. "Conn (fd %d, type %s, state %d) marked, but wants to flush %d bytes. "
  243. "(Marked at %s:%d)",
  244. conn->s, CONN_TYPE_TO_STRING(conn->type), conn->state,
  245. conn->outbuf_flushlen, conn->marked_for_close_file, conn->marked_for_close);
  246. if(connection_speaks_cells(conn)) {
  247. if(conn->state == OR_CONN_STATE_OPEN) {
  248. retval = flush_buf_tls(conn->tls, conn->outbuf, &conn->outbuf_flushlen);
  249. } else
  250. retval = -1; /* never flush non-open broken tls connections */
  251. } else {
  252. retval = flush_buf(conn->s, conn->outbuf, &conn->outbuf_flushlen);
  253. }
  254. if(retval >= 0 &&
  255. conn->hold_open_until_flushed && connection_wants_to_flush(conn)) {
  256. log_fn(LOG_INFO,"Holding conn (fd %d) open for more flushing.",conn->s);
  257. /* XXX should we reset timestamp_lastwritten here? */
  258. return;
  259. }
  260. if(connection_wants_to_flush(conn)) {
  261. log_fn(LOG_WARN,"Conn (fd %d, type %s, state %d) still wants to flush. Losing %d bytes! (Marked at %s:%d)",
  262. conn->s, CONN_TYPE_TO_STRING(conn->type), conn->state,
  263. (int)buf_datalen(conn->outbuf), conn->marked_for_close_file,
  264. conn->marked_for_close);
  265. }
  266. }
  267. /* if it's an edge conn, remove it from the list
  268. * of conn's on this circuit. If it's not on an edge,
  269. * flush and send destroys for all circuits on this conn
  270. */
  271. circuit_about_to_close_connection(conn);
  272. connection_about_to_close_connection(conn);
  273. connection_remove(conn);
  274. if(conn->type == CONN_TYPE_EXIT) {
  275. assert_connection_edge_not_dns_pending(conn);
  276. }
  277. connection_free(conn);
  278. if(i<nfds) { /* we just replaced the one at i with a new one.
  279. process it too. */
  280. conn_close_if_marked(i);
  281. }
  282. }
  283. /** This function is called whenever we successfully pull down a directory */
  284. void directory_has_arrived(void) {
  285. log_fn(LOG_INFO, "A directory has arrived.");
  286. has_fetched_directory=1;
  287. if(options.ORPort) { /* connect to them all */
  288. router_retry_connections();
  289. }
  290. }
  291. /** Perform regular maintenance tasks for a single connection. This
  292. * function gets run once per second per connection by run_housekeeping.
  293. */
  294. static void run_connection_housekeeping(int i, time_t now) {
  295. cell_t cell;
  296. connection_t *conn = connection_array[i];
  297. /* Expire any directory connections that haven't sent anything for 5 min */
  298. if(conn->type == CONN_TYPE_DIR &&
  299. !conn->marked_for_close &&
  300. conn->timestamp_lastwritten + 5*60 < now) {
  301. log_fn(LOG_WARN,"Expiring wedged directory conn (fd %d, purpose %d)", conn->s, conn->purpose);
  302. if (connection_wants_to_flush(conn)) {
  303. if(flush_buf(conn->s, conn->outbuf, &conn->outbuf_flushlen) < 0) {
  304. log_fn(LOG_WARN,"flushing expired directory conn failed.");
  305. connection_close_immediate(conn);
  306. connection_mark_for_close(conn);
  307. /* */
  308. } else {
  309. /* XXXX Does this next part make sense, really? */
  310. connection_mark_for_close(conn);
  311. conn->hold_open_until_flushed = 1; /* give it a last chance */
  312. }
  313. } else {
  314. connection_mark_for_close(conn);
  315. }
  316. return;
  317. }
  318. /* check connections to see whether we should send a keepalive, expire, or wait */
  319. if(!connection_speaks_cells(conn))
  320. return;
  321. /* If we haven't written to an OR connection for a while, then either nuke
  322. the connection or send a keepalive, depending. */
  323. if(now >= conn->timestamp_lastwritten + options.KeepalivePeriod) {
  324. if((!options.ORPort && !circuit_get_by_conn(conn)) ||
  325. (!connection_state_is_open(conn))) {
  326. /* we're an onion proxy, with no circuits; or our handshake has expired. kill it. */
  327. log_fn(LOG_INFO,"Expiring connection to %d (%s:%d).",
  328. i,conn->address, conn->port);
  329. /* flush anything waiting, e.g. a destroy for a just-expired circ */
  330. connection_mark_for_close(conn);
  331. conn->hold_open_until_flushed = 1;
  332. } else {
  333. /* either a full router, or we've got a circuit. send a padding cell. */
  334. log_fn(LOG_DEBUG,"Sending keepalive to (%s:%d)",
  335. conn->address, conn->port);
  336. memset(&cell,0,sizeof(cell_t));
  337. cell.command = CELL_PADDING;
  338. connection_or_write_cell_to_buf(&cell, conn);
  339. }
  340. }
  341. }
  342. /** Perform regular maintenance tasks. This function gets run once per
  343. * second by prepare_for_poll.
  344. */
  345. static void run_scheduled_events(time_t now) {
  346. static long time_to_fetch_directory = 0;
  347. static time_t last_uploaded_services = 0;
  348. static time_t last_rotated_certificate = 0;
  349. int i;
  350. /** 1a. Every MIN_ONION_KEY_LIFETIME seconds, rotate the onion keys,
  351. * shut down and restart all cpuworkers, and update the directory if
  352. * necessary.
  353. */
  354. if (options.ORPort && get_onion_key_set_at()+MIN_ONION_KEY_LIFETIME < now) {
  355. log_fn(LOG_INFO,"Rotating onion key.");
  356. rotate_onion_key();
  357. cpuworkers_rotate();
  358. if (router_rebuild_descriptor()<0) {
  359. log_fn(LOG_WARN, "Couldn't rebuild router descriptor");
  360. }
  361. router_upload_dir_desc_to_dirservers();
  362. }
  363. /** 1b. Every MAX_SSL_KEY_LIFETIME seconds, we change our TLS context. */
  364. if (!last_rotated_certificate)
  365. last_rotated_certificate = now;
  366. if (options.ORPort && last_rotated_certificate+MAX_SSL_KEY_LIFETIME < now) {
  367. log_fn(LOG_INFO,"Rotating tls context.");
  368. if (tor_tls_context_new(get_identity_key(), 1, options.Nickname,
  369. MAX_SSL_KEY_LIFETIME) < 0) {
  370. log_fn(LOG_WARN, "Error reinitializing TLS context");
  371. }
  372. last_rotated_certificate = now;
  373. /* XXXX We should rotate TLS connections as well; this code doesn't change
  374. * XXXX them at all. */
  375. }
  376. /** 1c. Every DirFetchPostPeriod seconds, we get a new directory and upload
  377. * our descriptor (if any). */
  378. if(time_to_fetch_directory < now) {
  379. /* it's time to fetch a new directory and/or post our descriptor */
  380. if(options.ORPort) {
  381. router_rebuild_descriptor();
  382. router_upload_dir_desc_to_dirservers();
  383. }
  384. if(!options.DirPort || !options.AuthoritativeDir) {
  385. /* XXXX should directories do this next part too? */
  386. routerlist_remove_old_routers(); /* purge obsolete entries */
  387. directory_get_from_dirserver(DIR_PURPOSE_FETCH_DIR, NULL, 0);
  388. } else {
  389. /* We're a directory; dump any old descriptors. */
  390. dirserv_remove_old_servers();
  391. /* dirservers try to reconnect too, in case connections have failed */
  392. router_retry_connections();
  393. /* fetch another directory, in case it knows something we don't */
  394. directory_get_from_dirserver(DIR_PURPOSE_FETCH_DIR, NULL, 0);
  395. }
  396. /* Force an upload of our descriptors every DirFetchPostPeriod seconds. */
  397. rend_services_upload(1);
  398. last_uploaded_services = now;
  399. rend_cache_clean(); /* should this go elsewhere? */
  400. time_to_fetch_directory = now + options.DirFetchPostPeriod;
  401. }
  402. /** 2. Every second, we examine pending circuits and prune the
  403. * ones which have been pending for more than a few seconds.
  404. * We do this before step 3, so it can try building more if
  405. * it's not comfortable with the number of available circuits.
  406. */
  407. circuit_expire_building(now);
  408. /** 2b. Also look at pending streams and prune the ones that 'began'
  409. * a long time ago but haven't gotten a 'connected' yet.
  410. * Do this before step 3, so we can put them back into pending
  411. * state to be picked up by the new circuit.
  412. */
  413. connection_ap_expire_beginning();
  414. /** 2c. And expire connections that we've held open for too long.
  415. */
  416. connection_expire_held_open();
  417. /** 3. Every second, we try a new circuit if there are no valid
  418. * circuits. Every NewCircuitPeriod seconds, we expire circuits
  419. * that became dirty more than NewCircuitPeriod seconds ago,
  420. * and we make a new circ if there are no clean circuits.
  421. */
  422. if(has_fetched_directory)
  423. circuit_build_needed_circs(now);
  424. /** 4. We do housekeeping for each connection... */
  425. for(i=0;i<nfds;i++) {
  426. run_connection_housekeeping(i, now);
  427. }
  428. /** 5. And remove any marked circuits... */
  429. circuit_close_all_marked();
  430. /** 6. And upload service descriptors for any services whose intro points
  431. * have changed in the last second. */
  432. if (last_uploaded_services < now-5) {
  433. rend_services_upload(0);
  434. last_uploaded_services = now;
  435. }
  436. /** 7. and blow away any connections that need to die. have to do this now,
  437. * because if we marked a conn for close and left its socket -1, then
  438. * we'll pass it to poll/select and bad things will happen.
  439. */
  440. for(i=0;i<nfds;i++)
  441. conn_close_if_marked(i);
  442. }
  443. /** Called every time we're about to call tor_poll. Increments statistics,
  444. * and adjusts token buckets. Returns the number of milliseconds to use for
  445. * the poll() timeout.
  446. */
  447. static int prepare_for_poll(void) {
  448. static long current_second = 0; /* from previous calls to gettimeofday */
  449. connection_t *conn;
  450. struct timeval now;
  451. int i;
  452. tor_gettimeofday(&now);
  453. /* Check how much bandwidth we've consumed, and increment the token
  454. * buckets. */
  455. stats_n_bytes_read += stats_prev_global_read_bucket-global_read_bucket;
  456. connection_bucket_refill(&now);
  457. stats_prev_global_read_bucket = global_read_bucket;
  458. if(now.tv_sec > current_second) { /* the second has rolled over. check more stuff. */
  459. ++stats_n_seconds_reading;
  460. assert_all_pending_dns_resolves_ok();
  461. run_scheduled_events(now.tv_sec);
  462. assert_all_pending_dns_resolves_ok();
  463. current_second = now.tv_sec; /* remember which second it is, for next time */
  464. }
  465. for(i=0;i<nfds;i++) {
  466. conn = connection_array[i];
  467. if(connection_has_pending_tls_data(conn) &&
  468. connection_is_reading(conn)) {
  469. log_fn(LOG_DEBUG,"sock %d has pending bytes.",conn->s);
  470. return 0; /* has pending bytes to read; don't let poll wait. */
  471. }
  472. }
  473. return (1000 - (now.tv_usec / 1000)); /* how many milliseconds til the next second? */
  474. }
  475. /** Configure the Tor process from the command line arguments and from the
  476. * configuration file.
  477. */
  478. static int init_from_config(int argc, char **argv) {
  479. /* read the configuration file. */
  480. if(getconfig(argc,argv,&options)) {
  481. log_fn(LOG_ERR,"Reading config failed. For usage, try -h.");
  482. return -1;
  483. }
  484. /* Setuid/setgid as appropriate */
  485. if(options.User || options.Group) {
  486. if(switch_id(options.User, options.Group) != 0) {
  487. return -1;
  488. }
  489. }
  490. /* Ensure data directory is private; create if possible. */
  491. if (check_private_dir(get_data_directory(&options), 1) != 0) {
  492. log_fn(LOG_ERR, "Couldn't access/create private data directory %s",
  493. get_data_directory(&options));
  494. return -1;
  495. }
  496. /* Start backgrounding the process, if requested. */
  497. if (options.RunAsDaemon) {
  498. start_daemon(options.DataDirectory);
  499. }
  500. /* Configure the log(s) */
  501. if (config_init_logs(&options)<0)
  502. return -1;
  503. /* Close the temporary log we used while starting up, if it isn't already
  504. * gone. */
  505. close_temp_logs();
  506. /* Set up our buckets */
  507. connection_bucket_init();
  508. stats_prev_global_read_bucket = global_read_bucket;
  509. /* Finish backgrounding the process */
  510. if(options.RunAsDaemon) {
  511. /* XXXX Can we delay this any more? */
  512. finish_daemon();
  513. }
  514. /* Write our pid to the pid file. If we do not have write permissions we
  515. * will log a warning */
  516. if(options.PidFile)
  517. write_pidfile(options.PidFile);
  518. return 0;
  519. }
  520. /** Called when we get a SIGHUP: reload configuration files and keys,
  521. * retry all connections, re-upload all descriptors, and so on. */
  522. static int do_hup(void) {
  523. char keydir[512];
  524. log_fn(LOG_NOTICE,"Received sighup. Reloading config.");
  525. has_completed_circuit=0;
  526. mark_logs_temp(); /* Close current logs once new logs are open. */
  527. /* first, reload config variables, in case they've changed */
  528. /* no need to provide argc/v, they've been cached inside init_from_config */
  529. if (init_from_config(0, NULL) < 0) {
  530. exit(1);
  531. }
  532. /* reload keys as needed for rendezvous services. */
  533. if (rend_service_load_keys()<0) {
  534. log_fn(LOG_ERR,"Error reloading rendezvous service keys");
  535. exit(1);
  536. }
  537. if(retry_all_connections() < 0) {
  538. log_fn(LOG_ERR,"Failed to bind one of the listener ports.");
  539. return -1;
  540. }
  541. if(options.DirPort) {
  542. /* reload the approved-routers file */
  543. sprintf(keydir,"%s/approved-routers", options.DataDirectory);
  544. log_fn(LOG_INFO,"Reloading approved fingerprints from %s...",keydir);
  545. if(dirserv_parse_fingerprint_file(keydir) < 0) {
  546. log_fn(LOG_WARN, "Error reloading fingerprints. Continuing with old list.");
  547. }
  548. /* Since we aren't fetching a directory, we won't retry rendezvous points
  549. * when it gets in. Try again now. */
  550. rend_services_introduce();
  551. } else {
  552. /* fetch a new directory */
  553. directory_get_from_dirserver(DIR_PURPOSE_FETCH_DIR, NULL, 0);
  554. }
  555. if(options.ORPort) {
  556. /* Restart cpuworker and dnsworker processes, so they get up-to-date
  557. * configuration options. */
  558. cpuworkers_rotate();
  559. dnsworkers_rotate();
  560. /* Rebuild fresh descriptor as needed. */
  561. router_rebuild_descriptor();
  562. sprintf(keydir,"%s/router.desc", options.DataDirectory);
  563. log_fn(LOG_INFO,"Dumping descriptor to %s...",keydir);
  564. if (write_str_to_file(keydir, router_get_my_descriptor())) {
  565. return -1;
  566. }
  567. }
  568. return 0;
  569. }
  570. /** Tor main loop. */
  571. static int do_main_loop(void) {
  572. int i;
  573. int timeout;
  574. int poll_result;
  575. /* Initialize the history structures. */
  576. rep_hist_init();
  577. /* Intialize the service cache. */
  578. rend_cache_init();
  579. /* load the private keys, if we're supposed to have them, and set up the
  580. * TLS context. */
  581. if (init_keys() < 0 || rend_service_load_keys() < 0) {
  582. log_fn(LOG_ERR,"Error initializing keys; exiting");
  583. return -1;
  584. }
  585. /* load the routers file */
  586. if(options.RouterFile) {
  587. routerlist_clear_trusted_directories();
  588. if (router_load_routerlist_from_file(options.RouterFile, 1) < 0) {
  589. log_fn(LOG_ERR,"Error loading router list.");
  590. return -1;
  591. }
  592. }
  593. if(options.DirPort) { /* the directory is already here, run startup things */
  594. has_fetched_directory = 1;
  595. directory_has_arrived();
  596. }
  597. if(options.ORPort) {
  598. cpu_init(); /* launch cpuworkers. Need to do this *after* we've read the onion key. */
  599. }
  600. /* start up the necessary connections based on which ports are
  601. * non-zero. This is where we try to connect to all the other ORs,
  602. * and start the listeners.
  603. */
  604. if(retry_all_connections() < 0) {
  605. log_fn(LOG_ERR,"Failed to bind one of the listener ports.");
  606. return -1;
  607. }
  608. for(;;) {
  609. #ifdef MS_WINDOWS /* Do service stuff only on windows. */
  610. if (service_status.dwCurrentState != SERVICE_RUNNING) {
  611. return 0;
  612. }
  613. #else /* do signal stuff only on unix */
  614. if(please_dumpstats) {
  615. /* prefer to log it at INFO, but make sure we always see it */
  616. dumpstats(get_min_log_level()>LOG_INFO ? get_min_log_level() : LOG_INFO);
  617. please_dumpstats = 0;
  618. }
  619. if(please_reset) {
  620. do_hup();
  621. please_reset = 0;
  622. }
  623. if(please_reap_children) {
  624. while(waitpid(-1,NULL,WNOHANG)) ; /* keep reaping until no more zombies */
  625. please_reap_children = 0;
  626. }
  627. #endif /* signal stuff */
  628. timeout = prepare_for_poll();
  629. /* poll until we have an event, or the second ends */
  630. poll_result = tor_poll(poll_array, nfds, timeout);
  631. /* let catch() handle things like ^c, and otherwise don't worry about it */
  632. if(poll_result < 0) {
  633. /* let the program survive things like ^z */
  634. if(tor_socket_errno(-1) != EINTR) {
  635. log_fn(LOG_ERR,"poll failed: %s [%d]",
  636. tor_socket_strerror(tor_socket_errno(-1)),
  637. tor_socket_errno(-1));
  638. return -1;
  639. } else {
  640. log_fn(LOG_DEBUG,"poll interrupted.");
  641. }
  642. }
  643. /* do all the reads and errors first, so we can detect closed sockets */
  644. for(i=0;i<nfds;i++)
  645. conn_read(i); /* this also marks broken connections */
  646. /* then do the writes */
  647. for(i=0;i<nfds;i++)
  648. conn_write(i);
  649. /* any of the conns need to be closed now? */
  650. for(i=0;i<nfds;i++)
  651. conn_close_if_marked(i);
  652. /* refilling buckets and sending cells happens at the beginning of the
  653. * next iteration of the loop, inside prepare_for_poll()
  654. */
  655. }
  656. }
  657. /** Unix signal handler. */
  658. static void catch(int the_signal) {
  659. #ifndef MS_WINDOWS /* do signal stuff only on unix */
  660. switch(the_signal) {
  661. // case SIGABRT:
  662. case SIGTERM:
  663. case SIGINT:
  664. log(LOG_ERR,"Catching signal %d, exiting cleanly.", the_signal);
  665. /* we don't care if there was an error when we unlink, nothing
  666. we could do about it anyways */
  667. if(options.PidFile)
  668. unlink(options.PidFile);
  669. exit(0);
  670. case SIGPIPE:
  671. log(LOG_INFO,"Caught sigpipe. Ignoring.");
  672. break;
  673. case SIGHUP:
  674. please_reset = 1;
  675. break;
  676. case SIGUSR1:
  677. please_dumpstats = 1;
  678. break;
  679. case SIGCHLD:
  680. please_reap_children = 1;
  681. break;
  682. default:
  683. log(LOG_WARN,"Caught signal %d that we can't handle??", the_signal);
  684. }
  685. #endif /* signal stuff */
  686. }
  687. /** Write all statistics to the log, with log level 'severity'. Called
  688. * in response to a SIGUSR1. */
  689. static void dumpstats(int severity) {
  690. int i;
  691. connection_t *conn;
  692. time_t now = time(NULL);
  693. log(severity, "Dumping stats:");
  694. for(i=0;i<nfds;i++) {
  695. conn = connection_array[i];
  696. log(severity, "Conn %d (socket %d) type %d (%s), state %d (%s), created %d secs ago",
  697. i, conn->s, conn->type, CONN_TYPE_TO_STRING(conn->type),
  698. conn->state, conn_state_to_string[conn->type][conn->state], (int)(now - conn->timestamp_created));
  699. if(!connection_is_listener(conn)) {
  700. log(severity,"Conn %d is to '%s:%d'.",i,conn->address, conn->port);
  701. log(severity,"Conn %d: %d bytes waiting on inbuf (last read %d secs ago)",i,
  702. (int)buf_datalen(conn->inbuf),
  703. (int)(now - conn->timestamp_lastread));
  704. log(severity,"Conn %d: %d bytes waiting on outbuf (last written %d secs ago)",i,
  705. (int)buf_datalen(conn->outbuf), (int)(now - conn->timestamp_lastwritten));
  706. }
  707. circuit_dump_by_conn(conn, severity); /* dump info about all the circuits using this conn */
  708. }
  709. log(severity,
  710. "Cells processed: %10lu padding\n"
  711. " %10lu create\n"
  712. " %10lu created\n"
  713. " %10lu relay\n"
  714. " (%10lu relayed)\n"
  715. " (%10lu delivered)\n"
  716. " %10lu destroy",
  717. stats_n_padding_cells_processed,
  718. stats_n_create_cells_processed,
  719. stats_n_created_cells_processed,
  720. stats_n_relay_cells_processed,
  721. stats_n_relay_cells_relayed,
  722. stats_n_relay_cells_delivered,
  723. stats_n_destroy_cells_processed);
  724. if (stats_n_data_cells_packaged)
  725. log(severity,"Average packaged cell fullness: %2.3f%%",
  726. 100*(((double)stats_n_data_bytes_packaged) /
  727. (stats_n_data_cells_packaged*RELAY_PAYLOAD_SIZE)) );
  728. if (stats_n_data_cells_received)
  729. log(severity,"Average delivered cell fullness: %2.3f%%",
  730. 100*(((double)stats_n_data_bytes_received) /
  731. (stats_n_data_cells_received*RELAY_PAYLOAD_SIZE)) );
  732. if (stats_n_seconds_reading)
  733. log(severity,"Average bandwidth used: %d bytes/sec",
  734. (int) (stats_n_bytes_read/stats_n_seconds_reading));
  735. rep_hist_dump_stats(now,severity);
  736. rend_service_dump_stats(severity);
  737. }
  738. /** Called before we make any calls to network-related functions.
  739. * (Some operating systems require their network libraries to be
  740. * initialized.) */
  741. int network_init(void)
  742. {
  743. #ifdef MS_WINDOWS
  744. /* This silly exercise is necessary before windows will allow gethostbyname to work.
  745. */
  746. WSADATA WSAData;
  747. int r;
  748. r = WSAStartup(0x101,&WSAData);
  749. if (r) {
  750. log_fn(LOG_WARN,"Error initializing windows network layer: code was %d",r);
  751. return -1;
  752. }
  753. /* XXXX We should call WSACleanup on exit, I think. */
  754. #endif
  755. return 0;
  756. }
  757. /** Called by exit() as we shut down the process.
  758. */
  759. void exit_function(void)
  760. {
  761. #ifdef MS_WINDOWS
  762. WSACleanup();
  763. #endif
  764. }
  765. /** Main entry point for the Tor command-line client.
  766. */
  767. int tor_init(int argc, char *argv[]) {
  768. /* give it somewhere to log to initially */
  769. add_temp_log();
  770. log_fn(LOG_NOTICE,"Tor v%s. This is experimental software. Do not use it if you need anonymity.",VERSION);
  771. if (network_init()<0) {
  772. log_fn(LOG_ERR,"Error initializing network; exiting.");
  773. return -1;
  774. }
  775. atexit(exit_function);
  776. if (init_from_config(argc,argv) < 0)
  777. return -1;
  778. #ifndef MS_WINDOWS
  779. if(geteuid()==0)
  780. log_fn(LOG_WARN,"You are running Tor as root. You don't need to, and you probably shouldn't.");
  781. #endif
  782. if(options.ORPort) { /* only spawn dns handlers if we're a router */
  783. dns_init(); /* initialize the dns resolve tree, and spawn workers */
  784. }
  785. if(options.SocksPort) {
  786. client_dns_init(); /* init the client dns cache */
  787. }
  788. #ifndef MS_WINDOWS /* do signal stuff only on unix */
  789. {
  790. struct sigaction action;
  791. action.sa_flags = 0;
  792. sigemptyset(&action.sa_mask);
  793. action.sa_handler = catch;
  794. sigaction(SIGINT, &action, NULL);
  795. sigaction(SIGTERM, &action, NULL);
  796. sigaction(SIGPIPE, &action, NULL);
  797. sigaction(SIGUSR1, &action, NULL);
  798. sigaction(SIGHUP, &action, NULL); /* to reload config, retry conns, etc */
  799. sigaction(SIGCHLD, &action, NULL); /* handle dns/cpu workers that exit */
  800. }
  801. #endif /* signal stuff */
  802. crypto_global_init();
  803. crypto_seed_rng();
  804. return 0;
  805. }
  806. void tor_cleanup(void) {
  807. crypto_global_cleanup();
  808. }
  809. #ifdef MS_WINDOWS
  810. void nt_service_control(DWORD request)
  811. {
  812. switch (request) {
  813. case SERVICE_CONTROL_STOP:
  814. case SERVICE_CONTROL_SHUTDOWN:
  815. log(LOG_ERR, "Got stop/shutdown request; shutting down cleanly.");
  816. service_status.dwWin32ExitCode = 0;
  817. service_status.dwCurrentState = SERVICE_STOPPED;
  818. return;
  819. }
  820. SetServiceStatus(hStatus, &service_status);
  821. }
  822. void nt_service_body(int argc, char **argv)
  823. {
  824. int err;
  825. FILE *f;
  826. f = fopen("d:\\foo.txt", "w");
  827. fprintf(f, "POINT 1\n");
  828. fclose(f);
  829. service_status.dwServiceType = SERVICE_WIN32;
  830. service_status.dwCurrentState = SERVICE_START_PENDING;
  831. service_status.dwControlsAccepted =
  832. SERVICE_ACCEPT_STOP |
  833. SERVICE_ACCEPT_SHUTDOWN;
  834. service_status.dwWin32ExitCode = 0;
  835. service_status.dwServiceSpecificExitCode = 0;
  836. service_status.dwCheckPoint = 0;
  837. service_status.dwWaitHint = 0;
  838. hStatus = RegisterServiceCtrlHandler("Tor", (LPHANDLER_FUNCTION) nt_service_control);
  839. if (hStatus == 0) {
  840. // failed;
  841. return;
  842. }
  843. err = tor_init(argc, argv); // refactor this part out of tor_main and do_main_loop
  844. if (err) {
  845. // failed.
  846. service_status.dwCurrentState = SERVICE_STOPPED;
  847. service_status.dwWin32ExitCode = -1;
  848. SetServiceStatus(hStatus, &service_status);
  849. return;
  850. }
  851. service_status.dwCurrentState = SERVICE_RUNNING;
  852. SetServiceStatus(hStatus, &service_status);
  853. do_main_loop();
  854. tor_cleanup();
  855. return;
  856. }
  857. void nt_service_main(void)
  858. {
  859. SERVICE_TABLE_ENTRY table[2];
  860. table[0].lpServiceName = "Tor";
  861. table[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTION)nt_service_body;
  862. table[1].lpServiceName = NULL;
  863. table[1].lpServiceProc = NULL;
  864. if (!StartServiceCtrlDispatcher(table))
  865. printf("Error was %d\n",GetLastError());
  866. }
  867. #endif
  868. int tor_main(int argc, char *argv[]) {
  869. #ifdef MS_WINDOWS_SERVICE
  870. nt_service_main();
  871. return 0;
  872. #else
  873. if (tor_init(argc, argv)<0)
  874. return -1;
  875. do_main_loop();
  876. tor_cleanup();
  877. return -1;
  878. #endif
  879. }
  880. /*
  881. Local Variables:
  882. mode:c
  883. indent-tabs-mode:nil
  884. c-basic-offset:2
  885. End:
  886. */