main.c 36 KB

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