main.c 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977
  1. /* Copyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  4. * Copyright (c) 2007, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /* $Id$ */
  7. const char main_c_id[] =
  8. "$Id$";
  9. /**
  10. * \file main.c
  11. * \brief Toplevel module. Handles signals, multiplexes between
  12. * connections, implements main loop, and drives scheduled events.
  13. **/
  14. #define MAIN_PRIVATE
  15. #include "or.h"
  16. #ifdef USE_DMALLOC
  17. #include <dmalloc.h>
  18. #endif
  19. void evdns_shutdown(int);
  20. /********* PROTOTYPES **********/
  21. static void dumpmemusage(int severity);
  22. static void dumpstats(int severity); /* log stats */
  23. static void conn_read_callback(int fd, short event, void *_conn);
  24. static void conn_write_callback(int fd, short event, void *_conn);
  25. static void signal_callback(int fd, short events, void *arg);
  26. static void second_elapsed_callback(int fd, short event, void *args);
  27. static int conn_close_if_marked(int i);
  28. static void connection_start_reading_from_linked_conn(connection_t *conn);
  29. static int connection_should_read_from_linked_conn(connection_t *conn);
  30. /********* START VARIABLES **********/
  31. int global_read_bucket; /**< Max number of bytes I can read this second. */
  32. int global_write_bucket; /**< Max number of bytes I can write this second. */
  33. /** Max number of relayed (bandwidth class 1) bytes I can read this second. */
  34. int global_relayed_read_bucket;
  35. /** Max number of relayed (bandwidth class 1) bytes I can write this second. */
  36. int global_relayed_write_bucket;
  37. /** What was the read bucket before the last call to prepare_for_pool?
  38. * (used to determine how many bytes we've read). */
  39. static int stats_prev_global_read_bucket;
  40. /** What was the write bucket before the last call to prepare_for_pool?
  41. * (used to determine how many bytes we've written). */
  42. static int stats_prev_global_write_bucket;
  43. /* XXX we might want to keep stats about global_relayed_*_bucket too. Or not.*/
  44. /** How many bytes have we read/written since we started the process? */
  45. static uint64_t stats_n_bytes_read = 0;
  46. static uint64_t stats_n_bytes_written = 0;
  47. /** What time did this process start up? */
  48. time_t time_of_process_start = 0;
  49. /** How many seconds have we been running? */
  50. long stats_n_seconds_working = 0;
  51. /** When do we next download a directory? */
  52. static time_t time_to_fetch_directory = 0;
  53. /** When do we next download a running-routers summary? */
  54. static time_t time_to_fetch_running_routers = 0;
  55. /** When do we next launch DNS wildcarding checks? */
  56. static time_t time_to_check_for_correct_dns = 0;
  57. /** How often will we honor SIGNEWNYM requests? */
  58. #define MAX_SIGNEWNYM_RATE 10
  59. /** When did we last process a SIGNEWNYM request? */
  60. static time_t time_of_last_signewnym = 0;
  61. /** Is there a signewnym request we're currently waiting to handle? */
  62. static int signewnym_is_pending = 0;
  63. /** Smartlist of all open connections. */
  64. static smartlist_t *connection_array = NULL;
  65. /** List of connections that have been marked for close and need to be freed
  66. * and removed from connection_array. */
  67. static smartlist_t *closeable_connection_lst = NULL;
  68. /** List of linked connections that are currently reading data into their
  69. * inbuf from their partner's outbuf. */
  70. static smartlist_t *active_linked_connection_lst = NULL;
  71. /** Flag: Set to true iff we entered the current libevent main loop via
  72. * <b>loop_once</b>. If so, there's no need to trigger a loopexit in order
  73. * to handle linked connections. */
  74. static int called_loop_once = 0;
  75. /** We set this to 1 when we've opened a circuit, so we can print a log
  76. * entry to inform the user that Tor is working. */
  77. int has_completed_circuit=0;
  78. /** If our router descriptor ever goes this long without being regenerated
  79. * because something changed, we force an immediate regenerate-and-upload. */
  80. #define FORCE_REGENERATE_DESCRIPTOR_INTERVAL (18*60*60)
  81. /** How often do we check whether part of our router info has changed in a way
  82. * that would require an upload? */
  83. #define CHECK_DESCRIPTOR_INTERVAL (60)
  84. /** How often do we (as a router) check whether our IP address has changed? */
  85. #define CHECK_IPADDRESS_INTERVAL (15*60)
  86. /** How often do we check buffers and pools for empty space that can be
  87. * deallocated? */
  88. #define MEM_SHRINK_INTERVAL (60)
  89. /** How often do we check for router descriptors that we should download
  90. * when we have too little directory info? */
  91. #define GREEDY_DESCRIPTOR_RETRY_INTERVAL (10)
  92. /** How often do we check for router descriptors that we should download
  93. * when we have enough directory info? */
  94. #define LAZY_DESCRIPTOR_RETRY_INTERVAL (60)
  95. /** How often do we 'forgive' undownloadable router descriptors and attempt
  96. * to download them again? */
  97. #define DESCRIPTOR_FAILURE_RESET_INTERVAL (60*60)
  98. /** How often do we add more entropy to OpenSSL's RNG pool? */
  99. #define ENTROPY_INTERVAL (60*60)
  100. /** How long do we let a directory connection stall before expiring it? */
  101. #define DIR_CONN_MAX_STALL (5*60)
  102. /** How old do we let a connection to an OR get before deciding it's
  103. * obsolete? */
  104. #define TIME_BEFORE_OR_CONN_IS_OBSOLETE (60*60*24*7)
  105. /** How long do we let OR connections handshake before we decide that
  106. * they are obsolete? */
  107. #define TLS_HANDSHAKE_TIMEOUT (60)
  108. /** How often do we write hidden service usage statistics to disk? */
  109. #define WRITE_HSUSAGE_INTERVAL (900)
  110. /********* END VARIABLES ************/
  111. /****************************************************************************
  112. *
  113. * This section contains accessors and other methods on the connection_array
  114. * variables (which are global within this file and unavailable outside it).
  115. *
  116. ****************************************************************************/
  117. /** Add <b>conn</b> to the array of connections that we can poll on. The
  118. * connection's socket must be set; the connection starts out
  119. * non-reading and non-writing.
  120. */
  121. int
  122. connection_add(connection_t *conn)
  123. {
  124. tor_assert(conn);
  125. tor_assert(conn->s >= 0 ||
  126. conn->linked ||
  127. (conn->type == CONN_TYPE_AP &&
  128. TO_EDGE_CONN(conn)->is_dns_request));
  129. tor_assert(conn->conn_array_index == -1); /* can only connection_add once */
  130. conn->conn_array_index = smartlist_len(connection_array);
  131. smartlist_add(connection_array, conn);
  132. if (conn->s >= 0 || conn->linked) {
  133. conn->read_event = tor_malloc_zero(sizeof(struct event));
  134. conn->write_event = tor_malloc_zero(sizeof(struct event));
  135. event_set(conn->read_event, conn->s, EV_READ|EV_PERSIST,
  136. conn_read_callback, conn);
  137. event_set(conn->write_event, conn->s, EV_WRITE|EV_PERSIST,
  138. conn_write_callback, conn);
  139. }
  140. log_debug(LD_NET,"new conn type %s, socket %d, n_conns %d.",
  141. conn_type_to_string(conn->type), conn->s,
  142. smartlist_len(connection_array));
  143. return 0;
  144. }
  145. /** Remove the connection from the global list, and remove the
  146. * corresponding poll entry. Calling this function will shift the last
  147. * connection (if any) into the position occupied by conn.
  148. */
  149. int
  150. connection_remove(connection_t *conn)
  151. {
  152. int current_index;
  153. connection_t *tmp;
  154. tor_assert(conn);
  155. log_debug(LD_NET,"removing socket %d (type %s), n_conns now %d",
  156. conn->s, conn_type_to_string(conn->type),
  157. smartlist_len(connection_array));
  158. tor_assert(conn->conn_array_index >= 0);
  159. current_index = conn->conn_array_index;
  160. connection_unregister_events(conn); /* This is redundant, but cheap. */
  161. if (current_index == smartlist_len(connection_array)-1) { /* at the end */
  162. smartlist_del(connection_array, current_index);
  163. return 0;
  164. }
  165. /* replace this one with the one at the end */
  166. smartlist_del(connection_array, current_index);
  167. tmp = smartlist_get(connection_array, current_index);
  168. tmp->conn_array_index = current_index;
  169. return 0;
  170. }
  171. /** If <b>conn</b> is an edge conn, remove it from the list
  172. * of conn's on this circuit. If it's not on an edge,
  173. * flush and send destroys for all circuits on this conn.
  174. *
  175. * Remove it from connection_array (if applicable) and
  176. * from closeable_connection_list.
  177. *
  178. * Then free it.
  179. */
  180. static void
  181. connection_unlink(connection_t *conn)
  182. {
  183. connection_about_to_close_connection(conn);
  184. if (conn->conn_array_index >= 0) {
  185. connection_remove(conn);
  186. }
  187. if (conn->linked_conn) {
  188. conn->linked_conn->linked_conn = NULL;
  189. if (! conn->linked_conn->marked_for_close &&
  190. conn->linked_conn->reading_from_linked_conn)
  191. connection_start_reading(conn->linked_conn);
  192. conn->linked_conn = NULL;
  193. }
  194. smartlist_remove(closeable_connection_lst, conn);
  195. smartlist_remove(active_linked_connection_lst, conn);
  196. if (conn->type == CONN_TYPE_EXIT) {
  197. assert_connection_edge_not_dns_pending(TO_EDGE_CONN(conn));
  198. }
  199. if (conn->type == CONN_TYPE_OR) {
  200. if (!tor_digest_is_zero(TO_OR_CONN(conn)->identity_digest))
  201. connection_or_remove_from_identity_map(TO_OR_CONN(conn));
  202. }
  203. connection_free(conn);
  204. }
  205. /** Schedule <b>conn</b> to be closed. **/
  206. void
  207. add_connection_to_closeable_list(connection_t *conn)
  208. {
  209. tor_assert(!smartlist_isin(closeable_connection_lst, conn));
  210. tor_assert(conn->marked_for_close);
  211. assert_connection_ok(conn, time(NULL));
  212. smartlist_add(closeable_connection_lst, conn);
  213. }
  214. /** Return 1 if conn is on the closeable list, else return 0. */
  215. int
  216. connection_is_on_closeable_list(connection_t *conn)
  217. {
  218. return smartlist_isin(closeable_connection_lst, conn);
  219. }
  220. /** Return true iff conn is in the current poll array. */
  221. int
  222. connection_in_array(connection_t *conn)
  223. {
  224. return smartlist_isin(connection_array, conn);
  225. }
  226. /** Set <b>*array</b> to an array of all connections, and <b>*n</b>
  227. * to the length of the array. <b>*array</b> and <b>*n</b> must not
  228. * be modified.
  229. */
  230. smartlist_t *
  231. get_connection_array(void)
  232. {
  233. return connection_array;
  234. }
  235. /** Set the event mask on <b>conn</b> to <b>events</b>. (The event
  236. * mask is a bitmask whose bits are EV_READ and EV_WRITE.)
  237. */
  238. void
  239. connection_watch_events(connection_t *conn, short events)
  240. {
  241. if (events & EV_READ)
  242. connection_start_reading(conn);
  243. else
  244. connection_stop_reading(conn);
  245. if (events & EV_WRITE)
  246. connection_start_writing(conn);
  247. else
  248. connection_stop_writing(conn);
  249. }
  250. /** Return true iff <b>conn</b> is listening for read events. */
  251. int
  252. connection_is_reading(connection_t *conn)
  253. {
  254. tor_assert(conn);
  255. return conn->reading_from_linked_conn ||
  256. (conn->read_event && event_pending(conn->read_event, EV_READ, NULL));
  257. }
  258. /** Tell the main loop to stop notifying <b>conn</b> of any read events. */
  259. void
  260. connection_stop_reading(connection_t *conn)
  261. {
  262. tor_assert(conn);
  263. tor_assert(conn->read_event);
  264. if (conn->linked) {
  265. conn->reading_from_linked_conn = 0;
  266. connection_stop_reading_from_linked_conn(conn);
  267. } else {
  268. if (event_del(conn->read_event))
  269. log_warn(LD_NET, "Error from libevent setting read event state for %d "
  270. "to unwatched: %s",
  271. conn->s,
  272. tor_socket_strerror(tor_socket_errno(conn->s)));
  273. }
  274. }
  275. /** Tell the main loop to start notifying <b>conn</b> of any read events. */
  276. void
  277. connection_start_reading(connection_t *conn)
  278. {
  279. tor_assert(conn);
  280. tor_assert(conn->read_event);
  281. if (conn->linked) {
  282. conn->reading_from_linked_conn = 1;
  283. if (connection_should_read_from_linked_conn(conn))
  284. connection_start_reading_from_linked_conn(conn);
  285. } else {
  286. if (event_add(conn->read_event, NULL))
  287. log_warn(LD_NET, "Error from libevent setting read event state for %d "
  288. "to watched: %s",
  289. conn->s,
  290. tor_socket_strerror(tor_socket_errno(conn->s)));
  291. }
  292. }
  293. /** Return true iff <b>conn</b> is listening for write events. */
  294. int
  295. connection_is_writing(connection_t *conn)
  296. {
  297. tor_assert(conn);
  298. return conn->writing_to_linked_conn ||
  299. (conn->write_event && event_pending(conn->write_event, EV_WRITE, NULL));
  300. }
  301. /** Tell the main loop to stop notifying <b>conn</b> of any write events. */
  302. void
  303. connection_stop_writing(connection_t *conn)
  304. {
  305. tor_assert(conn);
  306. tor_assert(conn->write_event);
  307. if (conn->linked) {
  308. conn->writing_to_linked_conn = 0;
  309. if (conn->linked_conn)
  310. connection_stop_reading_from_linked_conn(conn->linked_conn);
  311. } else {
  312. if (event_del(conn->write_event))
  313. log_warn(LD_NET, "Error from libevent setting write event state for %d "
  314. "to unwatched: %s",
  315. conn->s,
  316. tor_socket_strerror(tor_socket_errno(conn->s)));
  317. }
  318. }
  319. /** Tell the main loop to start notifying <b>conn</b> of any write events. */
  320. void
  321. connection_start_writing(connection_t *conn)
  322. {
  323. tor_assert(conn);
  324. tor_assert(conn->write_event);
  325. if (conn->linked) {
  326. conn->writing_to_linked_conn = 1;
  327. if (conn->linked_conn &&
  328. connection_should_read_from_linked_conn(conn->linked_conn))
  329. connection_start_reading_from_linked_conn(conn->linked_conn);
  330. } else {
  331. if (event_add(conn->write_event, NULL))
  332. log_warn(LD_NET, "Error from libevent setting write event state for %d "
  333. "to watched: %s",
  334. conn->s,
  335. tor_socket_strerror(tor_socket_errno(conn->s)));
  336. }
  337. }
  338. /** Return true iff <b>conn</b> is linked conn, and reading from the conn
  339. * linked to it would be good and feasible. (Reading is "feasible" if the
  340. * other conn exists and has data in its outbuf, and is "good" if we have our
  341. * reading_from_linked_conn flag set and the other conn has its
  342. * writing_to_linked_conn flag set.)*/
  343. static int
  344. connection_should_read_from_linked_conn(connection_t *conn)
  345. {
  346. if (conn->linked && conn->reading_from_linked_conn) {
  347. if (! conn->linked_conn ||
  348. (conn->linked_conn->writing_to_linked_conn &&
  349. buf_datalen(conn->linked_conn->outbuf)))
  350. return 1;
  351. }
  352. return 0;
  353. }
  354. /** Helper: Tell the main loop to begin reading bytes into <b>conn</b> from
  355. * its linked connection, if it is not doing so already. Called by
  356. * connection_start_reading and connection_start_writing as appropriate. */
  357. static void
  358. connection_start_reading_from_linked_conn(connection_t *conn)
  359. {
  360. tor_assert(conn);
  361. tor_assert(conn->linked == 1);
  362. if (!conn->active_on_link) {
  363. conn->active_on_link = 1;
  364. smartlist_add(active_linked_connection_lst, conn);
  365. if (!called_loop_once) {
  366. /* This is the first event on the list; we won't be in LOOP_ONCE mode,
  367. * so we need to make sure that the event_loop() actually exits at the
  368. * end of its run through the current connections and
  369. * lets us activate read events for linked connections. */
  370. struct timeval tv = { 0, 0 };
  371. event_loopexit(&tv);
  372. }
  373. } else {
  374. tor_assert(smartlist_isin(active_linked_connection_lst, conn));
  375. }
  376. }
  377. /** Tell the main loop to stop reading bytes into <b>conn</b> from its linked
  378. * connection, if is currently doing so. Called by connection_stop_reading,
  379. * connection_stop_writing, and connection_read. */
  380. void
  381. connection_stop_reading_from_linked_conn(connection_t *conn)
  382. {
  383. tor_assert(conn);
  384. tor_assert(conn->linked == 1);
  385. if (conn->active_on_link) {
  386. conn->active_on_link = 0;
  387. /* XXXX020 maybe we should keep an index here so we can smartlist_del
  388. * cleanly. */
  389. smartlist_remove(active_linked_connection_lst, conn);
  390. } else {
  391. tor_assert(!smartlist_isin(active_linked_connection_lst, conn));
  392. }
  393. }
  394. /** Close all connections that have been scheduled to get closed. */
  395. static void
  396. close_closeable_connections(void)
  397. {
  398. int i;
  399. for (i = 0; i < smartlist_len(closeable_connection_lst); ) {
  400. connection_t *conn = smartlist_get(closeable_connection_lst, i);
  401. if (conn->conn_array_index < 0) {
  402. connection_unlink(conn); /* blow it away right now */
  403. } else {
  404. if (!conn_close_if_marked(conn->conn_array_index))
  405. ++i;
  406. }
  407. }
  408. }
  409. /** Libevent callback: this gets invoked when (connection_t*)<b>conn</b> has
  410. * some data to read. */
  411. static void
  412. conn_read_callback(int fd, short event, void *_conn)
  413. {
  414. connection_t *conn = _conn;
  415. (void)fd;
  416. (void)event;
  417. log_debug(LD_NET,"socket %d wants to read.",conn->s);
  418. assert_connection_ok(conn, time(NULL));
  419. if (connection_handle_read(conn) < 0) {
  420. if (!conn->marked_for_close) {
  421. #ifndef MS_WINDOWS
  422. log_warn(LD_BUG,"Unhandled error on read for %s connection "
  423. "(fd %d); removing",
  424. conn_type_to_string(conn->type), conn->s);
  425. tor_fragile_assert();
  426. #endif
  427. if (CONN_IS_EDGE(conn))
  428. connection_edge_end_errno(TO_EDGE_CONN(conn));
  429. connection_mark_for_close(conn);
  430. }
  431. }
  432. assert_connection_ok(conn, time(NULL));
  433. if (smartlist_len(closeable_connection_lst))
  434. close_closeable_connections();
  435. }
  436. /** Libevent callback: this gets invoked when (connection_t*)<b>conn</b> has
  437. * some data to write. */
  438. static void
  439. conn_write_callback(int fd, short events, void *_conn)
  440. {
  441. connection_t *conn = _conn;
  442. (void)fd;
  443. (void)events;
  444. LOG_FN_CONN(conn, (LOG_DEBUG, LD_NET, "socket %d wants to write.",conn->s));
  445. assert_connection_ok(conn, time(NULL));
  446. if (connection_handle_write(conn, 0) < 0) {
  447. if (!conn->marked_for_close) {
  448. /* this connection is broken. remove it. */
  449. log_fn(LOG_WARN,LD_BUG,
  450. "unhandled error on write for %s connection (fd %d); removing",
  451. conn_type_to_string(conn->type), conn->s);
  452. tor_fragile_assert();
  453. if (CONN_IS_EDGE(conn)) {
  454. /* otherwise we cry wolf about duplicate close */
  455. edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
  456. if (!edge_conn->end_reason)
  457. edge_conn->end_reason = END_STREAM_REASON_INTERNAL;
  458. conn->edge_has_sent_end = 1;
  459. }
  460. /* XXX020 do we need a close-immediate here, so we don't try to flush? */
  461. connection_mark_for_close(conn);
  462. }
  463. }
  464. assert_connection_ok(conn, time(NULL));
  465. if (smartlist_len(closeable_connection_lst))
  466. close_closeable_connections();
  467. }
  468. /** If the connection at connection_array[i] is marked for close, then:
  469. * - If it has data that it wants to flush, try to flush it.
  470. * - If it _still_ has data to flush, and conn->hold_open_until_flushed is
  471. * true, then leave the connection open and return.
  472. * - Otherwise, remove the connection from connection_array and from
  473. * all other lists, close it, and free it.
  474. * Returns 1 if the connection was closed, 0 otherwise.
  475. */
  476. static int
  477. conn_close_if_marked(int i)
  478. {
  479. connection_t *conn;
  480. int retval;
  481. time_t now;
  482. conn = smartlist_get(connection_array, i);
  483. if (!conn->marked_for_close)
  484. return 0; /* nothing to see here, move along */
  485. now = time(NULL);
  486. assert_connection_ok(conn, now);
  487. assert_all_pending_dns_resolves_ok();
  488. log_debug(LD_NET,"Cleaning up connection (fd %d).",conn->s);
  489. if ((conn->s >= 0 || conn->linked_conn) && connection_wants_to_flush(conn)) {
  490. /* s == -1 means it's an incomplete edge connection, or that the socket
  491. * has already been closed as unflushable. */
  492. int sz = connection_bucket_write_limit(conn, now);
  493. if (!conn->hold_open_until_flushed)
  494. log_info(LD_NET,
  495. "Conn (addr %s, fd %d, type %s, state %d) marked, but wants "
  496. "to flush %d bytes. (Marked at %s:%d)",
  497. escaped_safe_str(conn->address),
  498. conn->s, conn_type_to_string(conn->type), conn->state,
  499. (int)conn->outbuf_flushlen,
  500. conn->marked_for_close_file, conn->marked_for_close);
  501. if (conn->linked_conn) {
  502. retval = move_buf_to_buf(conn->linked_conn->inbuf, conn->outbuf,
  503. &conn->outbuf_flushlen);
  504. if (retval >= 0) {
  505. /* The linked conn will notice that it has data when it notices that
  506. * we're gone. */
  507. connection_start_reading_from_linked_conn(conn->linked_conn);
  508. }
  509. /* XXXX020 Downgrade to debug. */
  510. log_info(LD_GENERAL, "Flushed last %d bytes from a linked conn; "
  511. "%d left; flushlen %d; wants-to-flush==%d", retval,
  512. (int)buf_datalen(conn->outbuf),
  513. (int)conn->outbuf_flushlen,
  514. connection_wants_to_flush(conn));
  515. } else if (connection_speaks_cells(conn)) {
  516. if (conn->state == OR_CONN_STATE_OPEN) {
  517. retval = flush_buf_tls(TO_OR_CONN(conn)->tls, conn->outbuf, sz,
  518. &conn->outbuf_flushlen);
  519. } else
  520. retval = -1; /* never flush non-open broken tls connections */
  521. } else {
  522. retval = flush_buf(conn->s, conn->outbuf, sz, &conn->outbuf_flushlen);
  523. }
  524. if (retval >= 0 && /* Technically, we could survive things like
  525. TLS_WANT_WRITE here. But don't bother for now. */
  526. conn->hold_open_until_flushed && connection_wants_to_flush(conn)) {
  527. if (retval > 0)
  528. LOG_FN_CONN(conn, (LOG_INFO,LD_NET,
  529. "Holding conn (fd %d) open for more flushing.",
  530. conn->s));
  531. /* XXX020 should we reset timestamp_lastwritten here? */
  532. return 0;
  533. }
  534. if (connection_wants_to_flush(conn)) {
  535. int severity;
  536. if (conn->type == CONN_TYPE_EXIT ||
  537. (conn->type == CONN_TYPE_OR && server_mode(get_options())) ||
  538. (conn->type == CONN_TYPE_DIR && conn->purpose == DIR_PURPOSE_SERVER))
  539. severity = LOG_INFO;
  540. else
  541. severity = LOG_NOTICE;
  542. /* XXXX Maybe allow this to happen a certain amount per hour; it usually
  543. * is meaningless. */
  544. log_fn(severity, LD_NET, "We stalled too much while trying to write %d "
  545. "bytes to address %s. If this happens a lot, either "
  546. "something is wrong with your network connection, or "
  547. "something is wrong with theirs. "
  548. "(fd %d, type %s, state %d, marked at %s:%d).",
  549. (int)buf_datalen(conn->outbuf),
  550. escaped_safe_str(conn->address), conn->s,
  551. conn_type_to_string(conn->type), conn->state,
  552. conn->marked_for_close_file,
  553. conn->marked_for_close);
  554. }
  555. }
  556. connection_unlink(conn); /* unlink, remove, free */
  557. return 1;
  558. }
  559. /** We've just tried every dirserver we know about, and none of
  560. * them were reachable. Assume the network is down. Change state
  561. * so next time an application connection arrives we'll delay it
  562. * and try another directory fetch. Kill off all the circuit_wait
  563. * streams that are waiting now, since they will all timeout anyway.
  564. */
  565. void
  566. directory_all_unreachable(time_t now)
  567. {
  568. connection_t *conn;
  569. (void)now;
  570. stats_n_seconds_working=0; /* reset it */
  571. while ((conn = connection_get_by_type_state(CONN_TYPE_AP,
  572. AP_CONN_STATE_CIRCUIT_WAIT))) {
  573. edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
  574. log_notice(LD_NET,
  575. "Is your network connection down? "
  576. "Failing connection to '%s:%d'.",
  577. safe_str(edge_conn->socks_request->address),
  578. edge_conn->socks_request->port);
  579. connection_mark_unattached_ap(edge_conn,
  580. END_STREAM_REASON_NET_UNREACHABLE);
  581. }
  582. control_event_general_status(LOG_ERR, "DIR_ALL_UNREACHABLE");
  583. }
  584. /** This function is called whenever we successfully pull down some new
  585. * network statuses or server descriptors. */
  586. void
  587. directory_info_has_arrived(time_t now, int from_cache)
  588. {
  589. or_options_t *options = get_options();
  590. if (!router_have_minimum_dir_info()) {
  591. log(LOG_NOTICE, LD_DIR,
  592. "I learned some more directory information, but not enough to "
  593. "build a circuit: %s", get_dir_info_status_string());
  594. update_router_descriptor_downloads(now);
  595. return;
  596. } else {
  597. /* if we have enough dir info, then update our guard status with
  598. * whatever we just learned. */
  599. entry_guards_compute_status();
  600. /* Don't even bother trying to get extrainfo until the rest of our
  601. * directory info is up-to-date */
  602. if (options->DownloadExtraInfo)
  603. update_extrainfo_downloads(now);
  604. }
  605. if (server_mode(options) && !we_are_hibernating() && !from_cache &&
  606. (has_completed_circuit || !any_predicted_circuits(now)))
  607. consider_testing_reachability(1, 1);
  608. }
  609. /** Perform regular maintenance tasks for a single connection. This
  610. * function gets run once per second per connection by run_scheduled_events.
  611. */
  612. static void
  613. run_connection_housekeeping(int i, time_t now)
  614. {
  615. cell_t cell;
  616. connection_t *conn = smartlist_get(connection_array, i);
  617. or_options_t *options = get_options();
  618. or_connection_t *or_conn;
  619. if (conn->outbuf && !buf_datalen(conn->outbuf) && conn->type == CONN_TYPE_OR)
  620. TO_OR_CONN(conn)->timestamp_lastempty = now;
  621. if (conn->marked_for_close) {
  622. /* nothing to do here */
  623. return;
  624. }
  625. /* Expire any directory connections that haven't been active (sent
  626. * if a server or received if a client) for 5 min */
  627. if (conn->type == CONN_TYPE_DIR &&
  628. ((DIR_CONN_IS_SERVER(conn) &&
  629. conn->timestamp_lastwritten + DIR_CONN_MAX_STALL < now) ||
  630. (!DIR_CONN_IS_SERVER(conn) &&
  631. conn->timestamp_lastread + DIR_CONN_MAX_STALL < now))) {
  632. log_info(LD_DIR,"Expiring wedged directory conn (fd %d, purpose %d)",
  633. conn->s, conn->purpose);
  634. /* This check is temporary; it's to let us know whether we should consider
  635. * parsing partial serverdesc responses. */
  636. if (conn->purpose == DIR_PURPOSE_FETCH_SERVERDESC &&
  637. buf_datalen(conn->inbuf)>=1024) {
  638. log_info(LD_DIR,"Trying to extract information from wedged server desc "
  639. "download.");
  640. connection_dir_reached_eof(TO_DIR_CONN(conn));
  641. } else {
  642. connection_mark_for_close(conn);
  643. }
  644. return;
  645. }
  646. if (!connection_speaks_cells(conn))
  647. return; /* we're all done here, the rest is just for OR conns */
  648. or_conn = TO_OR_CONN(conn);
  649. if (!conn->or_is_obsolete) {
  650. if (conn->timestamp_created + TIME_BEFORE_OR_CONN_IS_OBSOLETE < now) {
  651. log_info(LD_OR,
  652. "Marking OR conn to %s:%d obsolete (fd %d, %d secs old).",
  653. conn->address, conn->port, conn->s,
  654. (int)(now - conn->timestamp_created));
  655. conn->or_is_obsolete = 1;
  656. } else {
  657. or_connection_t *best =
  658. connection_or_get_by_identity_digest(or_conn->identity_digest);
  659. if (best && best != or_conn &&
  660. (conn->state == OR_CONN_STATE_OPEN ||
  661. now > conn->timestamp_created + TLS_HANDSHAKE_TIMEOUT)) {
  662. /* We only mark as obsolete connections that already are in
  663. * OR_CONN_STATE_OPEN, i.e. that have finished their TLS handshaking.
  664. * This is necessary because authorities judge whether a router is
  665. * reachable based on whether they were able to TLS handshake with it
  666. * recently. Without this check we would expire connections too
  667. * early for router->last_reachable to be updated.
  668. */
  669. log_info(LD_OR,
  670. "Marking duplicate conn to %s:%d obsolete "
  671. "(fd %d, %d secs old).",
  672. conn->address, conn->port, conn->s,
  673. (int)(now - conn->timestamp_created));
  674. conn->or_is_obsolete = 1;
  675. }
  676. }
  677. }
  678. if (conn->or_is_obsolete && !or_conn->n_circuits) {
  679. /* no unmarked circs -- mark it now */
  680. log_info(LD_OR,
  681. "Expiring non-used OR connection to fd %d (%s:%d) [Obsolete].",
  682. conn->s, conn->address, conn->port);
  683. connection_mark_for_close(conn);
  684. conn->hold_open_until_flushed = 1;
  685. return;
  686. }
  687. /* If we haven't written to an OR connection for a while, then either nuke
  688. the connection or send a keepalive, depending. */
  689. if (now >= conn->timestamp_lastwritten + options->KeepalivePeriod) {
  690. routerinfo_t *router = router_get_by_digest(or_conn->identity_digest);
  691. int maxCircuitlessPeriod = options->MaxCircuitDirtiness*3/2;
  692. if (!connection_state_is_open(conn)) {
  693. /* We never managed to actually get this connection open and happy. */
  694. log_info(LD_OR,"Expiring non-open OR connection to fd %d (%s:%d).",
  695. conn->s,conn->address, conn->port);
  696. connection_mark_for_close(conn);
  697. conn->hold_open_until_flushed = 1;
  698. } else if (we_are_hibernating() && !or_conn->n_circuits &&
  699. !buf_datalen(conn->outbuf)) {
  700. /* We're hibernating, there's no circuits, and nothing to flush.*/
  701. log_info(LD_OR,"Expiring non-used OR connection to fd %d (%s:%d) "
  702. "[Hibernating or exiting].",
  703. conn->s,conn->address, conn->port);
  704. connection_mark_for_close(conn);
  705. conn->hold_open_until_flushed = 1;
  706. } else if (!clique_mode(options) && !or_conn->n_circuits &&
  707. now >= or_conn->timestamp_last_added_nonpadding +
  708. maxCircuitlessPeriod &&
  709. (!router || !server_mode(options) ||
  710. !router_is_clique_mode(router))) {
  711. log_info(LD_OR,"Expiring non-used OR connection to fd %d (%s:%d) "
  712. "[Not in clique mode].",
  713. conn->s,conn->address, conn->port);
  714. connection_mark_for_close(conn);
  715. conn->hold_open_until_flushed = 1;
  716. } else if (
  717. now >= or_conn->timestamp_lastempty + options->KeepalivePeriod*10 &&
  718. now >= conn->timestamp_lastwritten + options->KeepalivePeriod*10) {
  719. log_fn(LOG_PROTOCOL_WARN,LD_PROTOCOL,
  720. "Expiring stuck OR connection to fd %d (%s:%d). (%d bytes to "
  721. "flush; %d seconds since last write)",
  722. conn->s, conn->address, conn->port,
  723. (int)buf_datalen(conn->outbuf),
  724. (int)(now-conn->timestamp_lastwritten));
  725. connection_mark_for_close(conn);
  726. } else if (!buf_datalen(conn->outbuf)) {
  727. /* either in clique mode, or we've got a circuit. send a padding cell. */
  728. log_fn(LOG_DEBUG,LD_OR,"Sending keepalive to (%s:%d)",
  729. conn->address, conn->port);
  730. memset(&cell,0,sizeof(cell_t));
  731. cell.command = CELL_PADDING;
  732. connection_or_write_cell_to_buf(&cell, or_conn);
  733. }
  734. }
  735. }
  736. /** Perform regular maintenance tasks. This function gets run once per
  737. * second by prepare_for_poll.
  738. */
  739. static void
  740. run_scheduled_events(time_t now)
  741. {
  742. static time_t last_rotated_x509_certificate = 0;
  743. static time_t time_to_check_v3_certificate = 0;
  744. #define CHECK_V3_CERTIFICATE_INTERVAL (5*60)
  745. static time_t time_to_check_listeners = 0;
  746. static time_t time_to_check_descriptor = 0;
  747. static time_t time_to_check_ipaddress = 0;
  748. static time_t time_to_shrink_memory = 0;
  749. static time_t time_to_try_getting_descriptors = 0;
  750. static time_t time_to_reset_descriptor_failures = 0;
  751. static time_t time_to_add_entropy = 0;
  752. static time_t time_to_write_hs_statistics = 0;
  753. static time_t time_to_downrate_stability = 0;
  754. #define SAVE_STABILITY_INTERVAL (30*60)
  755. static time_t time_to_save_stability = 0;
  756. #define CLEAN_CACHES_INTERVAL (30*60)
  757. static time_t time_to_clean_caches = 0;
  758. or_options_t *options = get_options();
  759. int i;
  760. int have_dir_info;
  761. /** 0. See if we've been asked to shut down and our timeout has
  762. * expired; or if our bandwidth limits are exhausted and we
  763. * should hibernate; or if it's time to wake up from hibernation.
  764. */
  765. consider_hibernation(now);
  766. /* 0b. If we've deferred a signewnym, make sure it gets handled
  767. * eventually */
  768. if (signewnym_is_pending &&
  769. time_of_last_signewnym + MAX_SIGNEWNYM_RATE <= now) {
  770. log(LOG_INFO, LD_CONTROL, "Honoring delayed NEWNYM request");
  771. circuit_expire_all_dirty_circs();
  772. addressmap_clear_transient();
  773. time_of_last_signewnym = now;
  774. signewnym_is_pending = 0;
  775. }
  776. /** 1a. Every MIN_ONION_KEY_LIFETIME seconds, rotate the onion keys,
  777. * shut down and restart all cpuworkers, and update the directory if
  778. * necessary.
  779. */
  780. if (server_mode(options) &&
  781. get_onion_key_set_at()+MIN_ONION_KEY_LIFETIME < now) {
  782. log_info(LD_GENERAL,"Rotating onion key.");
  783. rotate_onion_key();
  784. cpuworkers_rotate();
  785. if (router_rebuild_descriptor(1)<0) {
  786. log_info(LD_CONFIG, "Couldn't rebuild router descriptor");
  787. }
  788. if (advertised_server_mode())
  789. router_upload_dir_desc_to_dirservers(0);
  790. }
  791. if (time_to_try_getting_descriptors < now) {
  792. update_router_descriptor_downloads(now);
  793. update_extrainfo_downloads(now);
  794. if (options->UseBridges)
  795. fetch_bridge_descriptors(now);
  796. if (router_have_minimum_dir_info())
  797. time_to_try_getting_descriptors = now + LAZY_DESCRIPTOR_RETRY_INTERVAL;
  798. else
  799. time_to_try_getting_descriptors = now + GREEDY_DESCRIPTOR_RETRY_INTERVAL;
  800. }
  801. if (time_to_reset_descriptor_failures < now) {
  802. router_reset_descriptor_download_failures();
  803. time_to_reset_descriptor_failures =
  804. now + DESCRIPTOR_FAILURE_RESET_INTERVAL;
  805. }
  806. /** 1b. Every MAX_SSL_KEY_LIFETIME seconds, we change our TLS context. */
  807. if (!last_rotated_x509_certificate)
  808. last_rotated_x509_certificate = now;
  809. if (last_rotated_x509_certificate+MAX_SSL_KEY_LIFETIME < now) {
  810. log_info(LD_GENERAL,"Rotating tls context.");
  811. if (tor_tls_context_new(get_identity_key(), options->Nickname,
  812. MAX_SSL_KEY_LIFETIME) < 0) {
  813. log_warn(LD_BUG, "Error reinitializing TLS context");
  814. /* XXX is it a bug here, that we just keep going? */
  815. }
  816. last_rotated_x509_certificate = now;
  817. /* XXXX We should rotate TLS connections as well; this code doesn't change
  818. * them at all. */
  819. }
  820. if (time_to_add_entropy == 0)
  821. time_to_add_entropy = now + ENTROPY_INTERVAL;
  822. if (time_to_add_entropy < now) {
  823. /* We already seeded once, so don't die on failure. */
  824. crypto_seed_rng();
  825. time_to_add_entropy = now + ENTROPY_INTERVAL;
  826. }
  827. /** 1c. If we have to change the accounting interval or record
  828. * bandwidth used in this accounting interval, do so. */
  829. if (accounting_is_enabled(options))
  830. accounting_run_housekeeping(now);
  831. if (now % 10 == 0 && (authdir_mode_tests_reachability(options)) &&
  832. !we_are_hibernating()) {
  833. /* try to determine reachability of the other Tor servers */
  834. dirserv_test_reachability(now, 0);
  835. }
  836. /** 1d. Periodically, we discount older stability information so that new
  837. * stability info counts more, and save the stability information to disk as
  838. * appropriate. */
  839. if (time_to_downrate_stability < now)
  840. time_to_downrate_stability = rep_hist_downrate_old_runs(now);
  841. if (authdir_mode_tests_reachability(options)) {
  842. if (!time_to_save_stability)
  843. time_to_save_stability = now + SAVE_STABILITY_INTERVAL;
  844. if (time_to_save_stability < now) {
  845. if (rep_hist_record_mtbf_data()<0) {
  846. log_warn(LD_GENERAL, "Couldn't store mtbf data.");
  847. }
  848. time_to_save_stability = now + SAVE_STABILITY_INTERVAL;
  849. }
  850. }
  851. /* 1e. Periodicaly, if we're a v3 authority, we check whether our cert is
  852. * close to expiring and warn the admin if it is. */
  853. if (time_to_check_v3_certificate < now) {
  854. v3_authority_check_key_expiry();
  855. time_to_check_v3_certificate = now + CHECK_V3_CERTIFICATE_INTERVAL;
  856. }
  857. /** 2. Periodically, we consider getting a new directory, getting a
  858. * new running-routers list, and/or force-uploading our descriptor
  859. * (if we've passed our internal checks). */
  860. if (time_to_fetch_directory < now) {
  861. /* Only caches actually need to fetch directories now. */
  862. if (directory_fetches_dir_info_like_mirror(options) &&
  863. !authdir_mode_v1(options)) {
  864. if (any_trusted_dir_is_v1_authority() &&
  865. !should_delay_dir_fetches(options))
  866. directory_get_from_dirserver(DIR_PURPOSE_FETCH_DIR,
  867. ROUTER_PURPOSE_GENERAL, NULL, 1);
  868. }
  869. /** How often do we (as a cache) fetch a new V1 directory? */
  870. #define V1_DIR_FETCH_PERIOD (12*60*60)
  871. time_to_fetch_directory = now + V1_DIR_FETCH_PERIOD;
  872. }
  873. /* Caches need to fetch running_routers; directory clients don't. */
  874. if (directory_fetches_dir_info_like_mirror(options) &&
  875. time_to_fetch_running_routers < now) {
  876. if (!authdir_mode_v1(options) && !should_delay_dir_fetches(options)) {
  877. directory_get_from_dirserver(DIR_PURPOSE_FETCH_RUNNING_LIST,
  878. ROUTER_PURPOSE_GENERAL, NULL, 1);
  879. }
  880. /** How often do we (as a cache) fetch a new V1 runningrouters document? */
  881. #define V1_RUNNINGROUTERS_FETCH_PERIOD (12*60*60)
  882. time_to_fetch_running_routers = now + V1_RUNNINGROUTERS_FETCH_PERIOD;
  883. }
  884. /* Remove old information from rephist and the rend cache. */
  885. if (time_to_clean_caches < now) {
  886. rep_history_clean(now - options->RephistTrackTime);
  887. rend_cache_clean();
  888. rend_cache_clean_v2_descs_as_dir();
  889. time_to_clean_caches = now + CLEAN_CACHES_INTERVAL;
  890. }
  891. /* 2b. Once per minute, regenerate and upload the descriptor if the old
  892. * one is inaccurate. */
  893. if (time_to_check_descriptor < now) {
  894. static int dirport_reachability_count = 0;
  895. time_to_check_descriptor = now + CHECK_DESCRIPTOR_INTERVAL;
  896. check_descriptor_bandwidth_changed(now);
  897. if (time_to_check_ipaddress < now) {
  898. time_to_check_ipaddress = now + CHECK_IPADDRESS_INTERVAL;
  899. check_descriptor_ipaddress_changed(now);
  900. }
  901. mark_my_descriptor_dirty_if_older_than(
  902. now - FORCE_REGENERATE_DESCRIPTOR_INTERVAL);
  903. consider_publishable_server(0);
  904. /* also, check religiously for reachability, if it's within the first
  905. * 20 minutes of our uptime. */
  906. if (server_mode(options) &&
  907. (has_completed_circuit || !any_predicted_circuits(now)) &&
  908. stats_n_seconds_working < TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT &&
  909. !we_are_hibernating()) {
  910. consider_testing_reachability(1, dirport_reachability_count==0);
  911. if (++dirport_reachability_count > 5)
  912. dirport_reachability_count = 0;
  913. }
  914. /* If any networkstatus documents are no longer recent, we need to
  915. * update all the descriptors' running status. */
  916. /* purge obsolete entries */
  917. networkstatus_v2_list_clean(now);
  918. /* Remove dead routers. */
  919. routerlist_remove_old_routers();
  920. /* Also, once per minute, check whether we want to download any
  921. * networkstatus documents.
  922. */
  923. update_networkstatus_downloads(now);
  924. }
  925. /** 2c. Let directory voting happen. */
  926. if (authdir_mode_v3(options))
  927. dirvote_act(options, now);
  928. /** 3a. Every second, we examine pending circuits and prune the
  929. * ones which have been pending for more than a few seconds.
  930. * We do this before step 4, so it can try building more if
  931. * it's not comfortable with the number of available circuits.
  932. */
  933. circuit_expire_building(now);
  934. /** 3b. Also look at pending streams and prune the ones that 'began'
  935. * a long time ago but haven't gotten a 'connected' yet.
  936. * Do this before step 4, so we can put them back into pending
  937. * state to be picked up by the new circuit.
  938. */
  939. connection_ap_expire_beginning();
  940. /** 3c. And expire connections that we've held open for too long.
  941. */
  942. connection_expire_held_open();
  943. /** 3d. And every 60 seconds, we relaunch listeners if any died. */
  944. if (!we_are_hibernating() && time_to_check_listeners < now) {
  945. /* 0 means "only launch the ones that died." */
  946. retry_all_listeners(NULL, NULL);
  947. time_to_check_listeners = now+60;
  948. }
  949. /** 4. Every second, we try a new circuit if there are no valid
  950. * circuits. Every NewCircuitPeriod seconds, we expire circuits
  951. * that became dirty more than MaxCircuitDirtiness seconds ago,
  952. * and we make a new circ if there are no clean circuits.
  953. */
  954. have_dir_info = router_have_minimum_dir_info();
  955. if (have_dir_info && !we_are_hibernating())
  956. circuit_build_needed_circs(now);
  957. /** 5. We do housekeeping for each connection... */
  958. for (i=0;i<smartlist_len(connection_array);i++) {
  959. run_connection_housekeeping(i, now);
  960. }
  961. if (time_to_shrink_memory < now) {
  962. SMARTLIST_FOREACH(connection_array, connection_t *, conn, {
  963. if (conn->outbuf)
  964. buf_shrink(conn->outbuf);
  965. if (conn->inbuf)
  966. buf_shrink(conn->inbuf);
  967. });
  968. clean_cell_pool();
  969. buf_shrink_freelists(0);
  970. time_to_shrink_memory = now + MEM_SHRINK_INTERVAL;
  971. }
  972. /** 6. And remove any marked circuits... */
  973. circuit_close_all_marked();
  974. /** 7. And upload service descriptors if necessary. */
  975. if (has_completed_circuit && !we_are_hibernating())
  976. rend_consider_services_upload(now);
  977. /** 8. and blow away any connections that need to die. have to do this now,
  978. * because if we marked a conn for close and left its socket -1, then
  979. * we'll pass it to poll/select and bad things will happen.
  980. */
  981. close_closeable_connections();
  982. /** 8b. And if anything in our state is ready to get flushed to disk, we
  983. * flush it. */
  984. or_state_save(now);
  985. /** 9. and if we're a server, check whether our DNS is telling stories to
  986. * us. */
  987. if (server_mode(options) && time_to_check_for_correct_dns < now) {
  988. if (!time_to_check_for_correct_dns) {
  989. time_to_check_for_correct_dns = now + 60 + crypto_rand_int(120);
  990. } else {
  991. dns_launch_correctness_checks();
  992. time_to_check_for_correct_dns = now + 12*3600 +
  993. crypto_rand_int(12*3600);
  994. }
  995. }
  996. /** 10. write hidden service usage statistic to disk */
  997. if (options->HSAuthorityRecordStats && time_to_write_hs_statistics < now) {
  998. hs_usage_write_statistics_to_file(now);
  999. time_to_write_hs_statistics = now+WRITE_HSUSAGE_INTERVAL;
  1000. }
  1001. }
  1002. /** Libevent timer: used to invoke second_elapsed_callback() once per
  1003. * second. */
  1004. static struct event *timeout_event = NULL;
  1005. /** Number of libevent errors in the last second: we die if we get too many. */
  1006. static int n_libevent_errors = 0;
  1007. /** Libevent callback: invoked once every second. */
  1008. static void
  1009. second_elapsed_callback(int fd, short event, void *args)
  1010. {
  1011. /* XXXX This could be sensibly refactored into multiple callbacks, and we
  1012. * could use libevent's timers for this rather than checking the current
  1013. * time against a bunch of timeouts every second. */
  1014. static struct timeval one_second;
  1015. static long current_second = 0;
  1016. struct timeval now;
  1017. size_t bytes_written;
  1018. size_t bytes_read;
  1019. int seconds_elapsed;
  1020. or_options_t *options = get_options();
  1021. (void)fd;
  1022. (void)event;
  1023. (void)args;
  1024. if (!timeout_event) {
  1025. timeout_event = tor_malloc_zero(sizeof(struct event));
  1026. evtimer_set(timeout_event, second_elapsed_callback, NULL);
  1027. one_second.tv_sec = 1;
  1028. one_second.tv_usec = 0;
  1029. }
  1030. n_libevent_errors = 0;
  1031. /* log_fn(LOG_NOTICE, "Tick."); */
  1032. tor_gettimeofday(&now);
  1033. /* the second has rolled over. check more stuff. */
  1034. bytes_written = stats_prev_global_write_bucket - global_write_bucket;
  1035. bytes_read = stats_prev_global_read_bucket - global_read_bucket;
  1036. seconds_elapsed = current_second ? (now.tv_sec - current_second) : 0;
  1037. stats_n_bytes_read += bytes_read;
  1038. stats_n_bytes_written += bytes_written;
  1039. if (accounting_is_enabled(options) && seconds_elapsed >= 0)
  1040. accounting_add_bytes(bytes_read, bytes_written, seconds_elapsed);
  1041. control_event_bandwidth_used((uint32_t)bytes_read,(uint32_t)bytes_written);
  1042. control_event_stream_bandwidth_used();
  1043. if (seconds_elapsed > 0)
  1044. connection_bucket_refill(seconds_elapsed, now.tv_sec);
  1045. stats_prev_global_read_bucket = global_read_bucket;
  1046. stats_prev_global_write_bucket = global_write_bucket;
  1047. if (server_mode(options) &&
  1048. !we_are_hibernating() &&
  1049. seconds_elapsed > 0 &&
  1050. has_completed_circuit &&
  1051. stats_n_seconds_working / TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT !=
  1052. (stats_n_seconds_working+seconds_elapsed) /
  1053. TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT) {
  1054. /* every 20 minutes, check and complain if necessary */
  1055. routerinfo_t *me = router_get_my_routerinfo();
  1056. if (me && !check_whether_orport_reachable())
  1057. log_warn(LD_CONFIG,"Your server (%s:%d) has not managed to confirm that "
  1058. "its ORPort is reachable. Please check your firewalls, ports, "
  1059. "address, /etc/hosts file, etc.",
  1060. me->address, me->or_port);
  1061. if (me && !check_whether_dirport_reachable())
  1062. log_warn(LD_CONFIG,
  1063. "Your server (%s:%d) has not managed to confirm that its "
  1064. "DirPort is reachable. Please check your firewalls, ports, "
  1065. "address, /etc/hosts file, etc.",
  1066. me->address, me->dir_port);
  1067. }
  1068. /** If more than this many seconds have elapsed, probably the clock
  1069. * jumped: doesn't count. */
  1070. #define NUM_JUMPED_SECONDS_BEFORE_WARN 100
  1071. if (seconds_elapsed < -NUM_JUMPED_SECONDS_BEFORE_WARN ||
  1072. seconds_elapsed >= NUM_JUMPED_SECONDS_BEFORE_WARN) {
  1073. circuit_note_clock_jumped(seconds_elapsed);
  1074. /* XXX if the time jumps *back* many months, do our events in
  1075. * run_scheduled_events() recover? I don't think they do. -RD */
  1076. } else if (seconds_elapsed > 0)
  1077. stats_n_seconds_working += seconds_elapsed;
  1078. run_scheduled_events(now.tv_sec);
  1079. current_second = now.tv_sec; /* remember which second it is, for next time */
  1080. #if 0
  1081. if (current_second % 300 == 0) {
  1082. rep_history_clean(current_second - options->RephistTrackTime);
  1083. dumpmemusage(get_min_log_level()<LOG_INFO ?
  1084. get_min_log_level() : LOG_INFO);
  1085. }
  1086. #endif
  1087. if (evtimer_add(timeout_event, &one_second))
  1088. log_err(LD_NET,
  1089. "Error from libevent when setting one-second timeout event");
  1090. }
  1091. #ifndef MS_WINDOWS
  1092. /** Called when a possibly ignorable libevent error occurs; ensures that we
  1093. * don't get into an infinite loop by ignoring too many errors from
  1094. * libevent. */
  1095. static int
  1096. got_libevent_error(void)
  1097. {
  1098. if (++n_libevent_errors > 8) {
  1099. log_err(LD_NET, "Too many libevent errors in one second; dying");
  1100. return -1;
  1101. }
  1102. return 0;
  1103. }
  1104. #endif
  1105. #define UPTIME_CUTOFF_FOR_NEW_BANDWIDTH_TEST (6*60*60)
  1106. /** Called when our IP address seems to have changed. <b>at_interface</b>
  1107. * should be true if we detected a change in our interface, and false if we
  1108. * detected a change in our published address. */
  1109. void
  1110. ip_address_changed(int at_interface)
  1111. {
  1112. int server = server_mode(get_options());
  1113. if (at_interface) {
  1114. if (! server) {
  1115. /* Okay, change our keys. */
  1116. init_keys();
  1117. }
  1118. } else {
  1119. if (server) {
  1120. if (stats_n_seconds_working > UPTIME_CUTOFF_FOR_NEW_BANDWIDTH_TEST)
  1121. reset_bandwidth_test();
  1122. stats_n_seconds_working = 0;
  1123. router_reset_reachability();
  1124. mark_my_descriptor_dirty();
  1125. }
  1126. }
  1127. dns_servers_relaunch_checks();
  1128. }
  1129. /** Forget what we've learned about the correctness of our DNS servers, and
  1130. * start learning again. */
  1131. void
  1132. dns_servers_relaunch_checks(void)
  1133. {
  1134. if (server_mode(get_options())) {
  1135. dns_reset_correctness_checks();
  1136. time_to_check_for_correct_dns = 0;
  1137. }
  1138. }
  1139. /** Called when we get a SIGHUP: reload configuration files and keys,
  1140. * retry all connections, and so on. */
  1141. static int
  1142. do_hup(void)
  1143. {
  1144. or_options_t *options = get_options();
  1145. #ifdef USE_DMALLOC
  1146. dmalloc_log_stats();
  1147. dmalloc_log_changed(0, 1, 0, 0);
  1148. #endif
  1149. log_notice(LD_GENERAL,"Received reload signal (hup). Reloading config.");
  1150. if (accounting_is_enabled(options))
  1151. accounting_record_bandwidth_usage(time(NULL), get_or_state());
  1152. router_reset_warnings();
  1153. routerlist_reset_warnings();
  1154. addressmap_clear_transient();
  1155. /* first, reload config variables, in case they've changed */
  1156. /* no need to provide argc/v, they've been cached inside init_from_config */
  1157. if (options_init_from_torrc(0, NULL) < 0) {
  1158. log_err(LD_CONFIG,"Reading config failed--see warnings above. "
  1159. "For usage, try -h.");
  1160. return -1;
  1161. }
  1162. options = get_options(); /* they have changed now */
  1163. if (authdir_mode_handles_descs(options)) {
  1164. /* reload the approved-routers file */
  1165. if (dirserv_load_fingerprint_file() < 0) {
  1166. /* warnings are logged from dirserv_load_fingerprint_file() directly */
  1167. log_info(LD_GENERAL, "Error reloading fingerprints. "
  1168. "Continuing with old list.");
  1169. }
  1170. }
  1171. /* Rotate away from the old dirty circuits. This has to be done
  1172. * after we've read the new options, but before we start using
  1173. * circuits for directory fetches. */
  1174. circuit_expire_all_dirty_circs();
  1175. /* retry appropriate downloads */
  1176. router_reset_status_download_failures();
  1177. router_reset_descriptor_download_failures();
  1178. update_networkstatus_downloads(time(NULL));
  1179. /* We'll retry routerstatus downloads in about 10 seconds; no need to
  1180. * force a retry there. */
  1181. if (server_mode(options)) {
  1182. /* Restart cpuworker and dnsworker processes, so they get up-to-date
  1183. * configuration options. */
  1184. cpuworkers_rotate();
  1185. dns_reset();
  1186. }
  1187. return 0;
  1188. }
  1189. /** Tor main loop. */
  1190. /* static */ int
  1191. do_main_loop(void)
  1192. {
  1193. int loop_result;
  1194. time_t now;
  1195. /* initialize dns resolve map, spawn workers if needed */
  1196. if (dns_init() < 0) {
  1197. log_err(LD_GENERAL,"Error initializing dns subsystem; exiting");
  1198. return -1;
  1199. }
  1200. handle_signals(1);
  1201. /* load the private keys, if we're supposed to have them, and set up the
  1202. * TLS context. */
  1203. if (! identity_key_is_set()) {
  1204. if (init_keys() < 0) {
  1205. log_err(LD_BUG,"Error initializing keys; exiting");
  1206. return -1;
  1207. }
  1208. }
  1209. /* Set up the packed_cell_t memory pool. */
  1210. init_cell_pool();
  1211. /* Set up our buckets */
  1212. connection_bucket_init();
  1213. stats_prev_global_read_bucket = global_read_bucket;
  1214. stats_prev_global_write_bucket = global_write_bucket;
  1215. if (trusted_dirs_reload_certs())
  1216. return -1;
  1217. if (router_reload_v2_networkstatus()) {
  1218. return -1;
  1219. }
  1220. if (router_reload_consensus_networkstatus()) {
  1221. return -1;
  1222. }
  1223. /* load the routers file, or assign the defaults. */
  1224. if (router_reload_router_list()) {
  1225. return -1;
  1226. }
  1227. /* load the networkstatuses. (This launches a download for new routers as
  1228. * appropriate.)
  1229. */
  1230. now = time(NULL);
  1231. directory_info_has_arrived(now, 1);
  1232. if (authdir_mode_tests_reachability(get_options())) {
  1233. /* the directory is already here, run startup things */
  1234. dirserv_test_reachability(now, 1);
  1235. }
  1236. if (server_mode(get_options())) {
  1237. /* launch cpuworkers. Need to do this *after* we've read the onion key. */
  1238. cpu_init();
  1239. }
  1240. /* set up once-a-second callback. */
  1241. second_elapsed_callback(0,0,NULL);
  1242. for (;;) {
  1243. if (nt_service_is_stopping())
  1244. return 0;
  1245. #ifndef MS_WINDOWS
  1246. /* Make it easier to tell whether libevent failure is our fault or not. */
  1247. errno = 0;
  1248. #endif
  1249. /* All active linked conns should get their read events activated. */
  1250. SMARTLIST_FOREACH(active_linked_connection_lst, connection_t *, conn,
  1251. event_active(conn->read_event, EV_READ, 1));
  1252. called_loop_once = smartlist_len(active_linked_connection_lst) ? 1 : 0;
  1253. /* poll until we have an event, or the second ends, or until we have
  1254. * some active linked connections to trigger events for. */
  1255. loop_result = event_loop(called_loop_once ? EVLOOP_ONCE : 0);
  1256. /* let catch() handle things like ^c, and otherwise don't worry about it */
  1257. if (loop_result < 0) {
  1258. int e = tor_socket_errno(-1);
  1259. /* let the program survive things like ^z */
  1260. if (e != EINTR && !ERRNO_IS_EINPROGRESS(e)) {
  1261. #ifdef HAVE_EVENT_GET_METHOD
  1262. log_err(LD_NET,"libevent call with %s failed: %s [%d]",
  1263. event_get_method(), tor_socket_strerror(e), e);
  1264. #else
  1265. log_err(LD_NET,"libevent call failed: %s [%d]",
  1266. tor_socket_strerror(e), e);
  1267. #endif
  1268. return -1;
  1269. #ifndef MS_WINDOWS
  1270. } else if (e == EINVAL) {
  1271. log_warn(LD_NET, "EINVAL from libevent: should you upgrade libevent?");
  1272. if (got_libevent_error())
  1273. return -1;
  1274. #endif
  1275. } else {
  1276. if (ERRNO_IS_EINPROGRESS(e))
  1277. log_warn(LD_BUG,
  1278. "libevent call returned EINPROGRESS? Please report.");
  1279. log_debug(LD_NET,"libevent call interrupted.");
  1280. /* You can't trust the results of this poll(). Go back to the
  1281. * top of the big for loop. */
  1282. continue;
  1283. }
  1284. }
  1285. /* refilling buckets and sending cells happens at the beginning of the
  1286. * next iteration of the loop, inside prepare_for_poll()
  1287. * XXXX020 No longer so; fix comment.
  1288. */
  1289. }
  1290. }
  1291. /** Used to implement the SIGNAL control command: if we accept
  1292. * <b>the_signal</b> as a remote pseudo-signal, act on it. */
  1293. /* We don't re-use catch() here because:
  1294. * 1. We handle a different set of signals than those allowed in catch.
  1295. * 2. Platforms without signal() are unlikely to define SIGfoo.
  1296. * 3. The control spec is defined to use fixed numeric signal values
  1297. * which just happen to match the unix values.
  1298. */
  1299. void
  1300. control_signal_act(int the_signal)
  1301. {
  1302. switch (the_signal)
  1303. {
  1304. case 1:
  1305. signal_callback(0,0,(void*)(uintptr_t)SIGHUP);
  1306. break;
  1307. case 2:
  1308. signal_callback(0,0,(void*)(uintptr_t)SIGINT);
  1309. break;
  1310. case 10:
  1311. signal_callback(0,0,(void*)(uintptr_t)SIGUSR1);
  1312. break;
  1313. case 12:
  1314. signal_callback(0,0,(void*)(uintptr_t)SIGUSR2);
  1315. break;
  1316. case 15:
  1317. signal_callback(0,0,(void*)(uintptr_t)SIGTERM);
  1318. break;
  1319. case SIGNEWNYM:
  1320. signal_callback(0,0,(void*)(uintptr_t)SIGNEWNYM);
  1321. break;
  1322. case SIGCLEARDNSCACHE:
  1323. signal_callback(0,0,(void*)(uintptr_t)SIGCLEARDNSCACHE);
  1324. break;
  1325. default:
  1326. log_warn(LD_BUG, "Unrecognized signal number %d.", the_signal);
  1327. break;
  1328. }
  1329. }
  1330. /** Libevent callback: invoked when we get a signal.
  1331. */
  1332. static void
  1333. signal_callback(int fd, short events, void *arg)
  1334. {
  1335. uintptr_t sig = (uintptr_t)arg;
  1336. (void)fd;
  1337. (void)events;
  1338. switch (sig)
  1339. {
  1340. case SIGTERM:
  1341. log_notice(LD_GENERAL,"Catching signal TERM, exiting cleanly.");
  1342. tor_cleanup();
  1343. exit(0);
  1344. break;
  1345. case SIGINT:
  1346. if (!server_mode(get_options())) { /* do it now */
  1347. log_notice(LD_GENERAL,"Interrupt: exiting cleanly.");
  1348. tor_cleanup();
  1349. exit(0);
  1350. }
  1351. hibernate_begin_shutdown();
  1352. break;
  1353. #ifdef SIGPIPE
  1354. case SIGPIPE:
  1355. log_debug(LD_GENERAL,"Caught sigpipe. Ignoring.");
  1356. break;
  1357. #endif
  1358. case SIGUSR1:
  1359. /* prefer to log it at INFO, but make sure we always see it */
  1360. dumpstats(get_min_log_level()<LOG_INFO ? get_min_log_level() : LOG_INFO);
  1361. break;
  1362. case SIGUSR2:
  1363. switch_logs_debug();
  1364. log_debug(LD_GENERAL,"Caught USR2, going to loglevel debug. "
  1365. "Send HUP to change back.");
  1366. break;
  1367. case SIGHUP:
  1368. if (do_hup() < 0) {
  1369. log_warn(LD_CONFIG,"Restart failed (config error?). Exiting.");
  1370. tor_cleanup();
  1371. exit(1);
  1372. }
  1373. break;
  1374. #ifdef SIGCHLD
  1375. case SIGCHLD:
  1376. while (waitpid(-1,NULL,WNOHANG) > 0) ; /* keep reaping until no more
  1377. zombies */
  1378. break;
  1379. #endif
  1380. case SIGNEWNYM: {
  1381. time_t now = time(NULL);
  1382. if (time_of_last_signewnym + MAX_SIGNEWNYM_RATE > now) {
  1383. signewnym_is_pending = 1;
  1384. log(LOG_NOTICE, LD_CONTROL,
  1385. "Rate limiting NEWNYM request: delaying by %d second(s)",
  1386. (int)(MAX_SIGNEWNYM_RATE+time_of_last_signewnym-now));
  1387. } else {
  1388. /* XXX020 refactor someday: these two calls are in
  1389. * run_scheduled_events() above too, and they should be in just
  1390. * one place. */
  1391. circuit_expire_all_dirty_circs();
  1392. addressmap_clear_transient();
  1393. time_of_last_signewnym = now;
  1394. }
  1395. break;
  1396. }
  1397. case SIGCLEARDNSCACHE:
  1398. addressmap_clear_transient();
  1399. break;
  1400. }
  1401. }
  1402. extern uint64_t rephist_total_alloc;
  1403. extern uint32_t rephist_total_num;
  1404. /**
  1405. * Write current memory usage information to the log.
  1406. */
  1407. static void
  1408. dumpmemusage(int severity)
  1409. {
  1410. connection_dump_buffer_mem_stats(severity);
  1411. log(severity, LD_GENERAL, "In rephist: "U64_FORMAT" used by %d Tors.",
  1412. U64_PRINTF_ARG(rephist_total_alloc), rephist_total_num);
  1413. dump_routerlist_mem_usage(severity);
  1414. dump_cell_pool_usage(severity);
  1415. buf_dump_freelist_sizes(severity);
  1416. tor_log_mallinfo(severity);
  1417. }
  1418. /** Write all statistics to the log, with log level 'severity'. Called
  1419. * in response to a SIGUSR1. */
  1420. static void
  1421. dumpstats(int severity)
  1422. {
  1423. time_t now = time(NULL);
  1424. time_t elapsed;
  1425. log(severity, LD_GENERAL, "Dumping stats:");
  1426. SMARTLIST_FOREACH(connection_array, connection_t *, conn,
  1427. {
  1428. int i = conn_sl_idx;
  1429. log(severity, LD_GENERAL,
  1430. "Conn %d (socket %d) type %d (%s), state %d (%s), created %d secs ago",
  1431. i, conn->s, conn->type, conn_type_to_string(conn->type),
  1432. conn->state, conn_state_to_string(conn->type, conn->state),
  1433. (int)(now - conn->timestamp_created));
  1434. if (!connection_is_listener(conn)) {
  1435. log(severity,LD_GENERAL,
  1436. "Conn %d is to %s:%d.", i,
  1437. safe_str(conn->address), conn->port);
  1438. log(severity,LD_GENERAL,
  1439. "Conn %d: %d bytes waiting on inbuf (len %d, last read %d secs ago)",
  1440. i,
  1441. (int)buf_datalen(conn->inbuf),
  1442. (int)buf_capacity(conn->inbuf),
  1443. (int)(now - conn->timestamp_lastread));
  1444. log(severity,LD_GENERAL,
  1445. "Conn %d: %d bytes waiting on outbuf "
  1446. "(len %d, last written %d secs ago)",i,
  1447. (int)buf_datalen(conn->outbuf),
  1448. (int)buf_capacity(conn->outbuf),
  1449. (int)(now - conn->timestamp_lastwritten));
  1450. }
  1451. circuit_dump_by_conn(conn, severity); /* dump info about all the circuits
  1452. * using this conn */
  1453. });
  1454. log(severity, LD_NET,
  1455. "Cells processed: "U64_FORMAT" padding\n"
  1456. " "U64_FORMAT" create\n"
  1457. " "U64_FORMAT" created\n"
  1458. " "U64_FORMAT" relay\n"
  1459. " ("U64_FORMAT" relayed)\n"
  1460. " ("U64_FORMAT" delivered)\n"
  1461. " "U64_FORMAT" destroy",
  1462. U64_PRINTF_ARG(stats_n_padding_cells_processed),
  1463. U64_PRINTF_ARG(stats_n_create_cells_processed),
  1464. U64_PRINTF_ARG(stats_n_created_cells_processed),
  1465. U64_PRINTF_ARG(stats_n_relay_cells_processed),
  1466. U64_PRINTF_ARG(stats_n_relay_cells_relayed),
  1467. U64_PRINTF_ARG(stats_n_relay_cells_delivered),
  1468. U64_PRINTF_ARG(stats_n_destroy_cells_processed));
  1469. if (stats_n_data_cells_packaged)
  1470. log(severity,LD_NET,"Average packaged cell fullness: %2.3f%%",
  1471. 100*(U64_TO_DBL(stats_n_data_bytes_packaged) /
  1472. U64_TO_DBL(stats_n_data_cells_packaged*RELAY_PAYLOAD_SIZE)) );
  1473. if (stats_n_data_cells_received)
  1474. log(severity,LD_NET,"Average delivered cell fullness: %2.3f%%",
  1475. 100*(U64_TO_DBL(stats_n_data_bytes_received) /
  1476. U64_TO_DBL(stats_n_data_cells_received*RELAY_PAYLOAD_SIZE)) );
  1477. if (now - time_of_process_start >= 0)
  1478. elapsed = now - time_of_process_start;
  1479. else
  1480. elapsed = 0;
  1481. if (elapsed) {
  1482. log(severity, LD_NET,
  1483. "Average bandwidth: "U64_FORMAT"/%d = %d bytes/sec reading",
  1484. U64_PRINTF_ARG(stats_n_bytes_read),
  1485. (int)elapsed,
  1486. (int) (stats_n_bytes_read/elapsed));
  1487. log(severity, LD_NET,
  1488. "Average bandwidth: "U64_FORMAT"/%d = %d bytes/sec writing",
  1489. U64_PRINTF_ARG(stats_n_bytes_written),
  1490. (int)elapsed,
  1491. (int) (stats_n_bytes_written/elapsed));
  1492. }
  1493. log(severity, LD_NET, "--------------- Dumping memory information:");
  1494. dumpmemusage(severity);
  1495. rep_hist_dump_stats(now,severity);
  1496. rend_service_dump_stats(severity);
  1497. dump_pk_ops(severity);
  1498. dump_distinct_digest_count(severity);
  1499. }
  1500. /** Called by exit() as we shut down the process.
  1501. */
  1502. static void
  1503. exit_function(void)
  1504. {
  1505. /* NOTE: If we ever daemonize, this gets called immediately. That's
  1506. * okay for now, because we only use this on Windows. */
  1507. #ifdef MS_WINDOWS
  1508. WSACleanup();
  1509. #endif
  1510. }
  1511. /** Set up the signal handlers for either parent or child. */
  1512. void
  1513. handle_signals(int is_parent)
  1514. {
  1515. #ifndef MS_WINDOWS /* do signal stuff only on unix */
  1516. int i;
  1517. static int signals[] = {
  1518. SIGINT, /* do a controlled slow shutdown */
  1519. SIGTERM, /* to terminate now */
  1520. SIGPIPE, /* otherwise sigpipe kills us */
  1521. SIGUSR1, /* dump stats */
  1522. SIGUSR2, /* go to loglevel debug */
  1523. SIGHUP, /* to reload config, retry conns, etc */
  1524. #ifdef SIGXFSZ
  1525. SIGXFSZ, /* handle file-too-big resource exhaustion */
  1526. #endif
  1527. SIGCHLD, /* handle dns/cpu workers that exit */
  1528. -1 };
  1529. static struct event signal_events[16]; /* bigger than it has to be. */
  1530. if (is_parent) {
  1531. for (i = 0; signals[i] >= 0; ++i) {
  1532. signal_set(&signal_events[i], signals[i], signal_callback,
  1533. (void*)(uintptr_t)signals[i]);
  1534. if (signal_add(&signal_events[i], NULL))
  1535. log_warn(LD_BUG, "Error from libevent when adding event for signal %d",
  1536. signals[i]);
  1537. }
  1538. } else {
  1539. struct sigaction action;
  1540. action.sa_flags = 0;
  1541. sigemptyset(&action.sa_mask);
  1542. action.sa_handler = SIG_IGN;
  1543. sigaction(SIGINT, &action, NULL);
  1544. sigaction(SIGTERM, &action, NULL);
  1545. sigaction(SIGPIPE, &action, NULL);
  1546. sigaction(SIGUSR1, &action, NULL);
  1547. sigaction(SIGUSR2, &action, NULL);
  1548. sigaction(SIGHUP, &action, NULL);
  1549. #ifdef SIGXFSZ
  1550. sigaction(SIGXFSZ, &action, NULL);
  1551. #endif
  1552. }
  1553. #else /* MS windows */
  1554. (void)is_parent;
  1555. #endif /* signal stuff */
  1556. }
  1557. /** Main entry point for the Tor command-line client.
  1558. */
  1559. /* static */ int
  1560. tor_init(int argc, char *argv[])
  1561. {
  1562. char buf[256];
  1563. int i, quiet = 0;
  1564. time_of_process_start = time(NULL);
  1565. if (!connection_array)
  1566. connection_array = smartlist_create();
  1567. if (!closeable_connection_lst)
  1568. closeable_connection_lst = smartlist_create();
  1569. if (!active_linked_connection_lst)
  1570. active_linked_connection_lst = smartlist_create();
  1571. /* Have the log set up with our application name. */
  1572. tor_snprintf(buf, sizeof(buf), "Tor %s", get_version());
  1573. log_set_application_name(buf);
  1574. /* Initialize threading. */
  1575. tor_threads_init();
  1576. /* Initialize the history structures. */
  1577. rep_hist_init();
  1578. /* Initialize the service cache. */
  1579. rend_cache_init();
  1580. addressmap_init(); /* Init the client dns cache. Do it always, since it's
  1581. * cheap. */
  1582. /* We search for the "quiet" option first, since it decides whether we
  1583. * will log anything at all to the command line. */
  1584. for (i=1;i<argc;++i) {
  1585. if (!strcmp(argv[i], "--quiet")) /*DOCDOC in mangpage.*/
  1586. quiet = 1;
  1587. }
  1588. if (!quiet) {
  1589. /* give it somewhere to log to initially */
  1590. add_temp_log();
  1591. }
  1592. log(LOG_NOTICE, LD_GENERAL, "Tor v%s. This is experimental software. "
  1593. "Do not rely on it for strong anonymity. (Running on %s)",get_version(),
  1594. get_uname());
  1595. if (network_init()<0) {
  1596. log_err(LD_BUG,"Error initializing network; exiting.");
  1597. return -1;
  1598. }
  1599. atexit(exit_function);
  1600. if (options_init_from_torrc(argc,argv) < 0) {
  1601. log_err(LD_CONFIG,"Reading config failed--see warnings above.");
  1602. return -1;
  1603. }
  1604. #ifndef MS_WINDOWS
  1605. if (geteuid()==0)
  1606. log_warn(LD_GENERAL,"You are running Tor as root. You don't need to, "
  1607. "and you probably shouldn't.");
  1608. #endif
  1609. crypto_global_init(get_options()->HardwareAccel);
  1610. if (crypto_seed_rng()) {
  1611. log_err(LD_BUG, "Unable to seed random number generator. Exiting.");
  1612. return -1;
  1613. }
  1614. return 0;
  1615. }
  1616. /** Free all memory that we might have allocated somewhere.
  1617. * If <b>postfork</b>, we are a worker process and we want to free
  1618. * only the parts of memory that we won't touch. If !<b>postfork</b>,
  1619. * Tor is shutting down and we should free everything.
  1620. *
  1621. * Helps us find the real leaks with dmalloc and the like. Also valgrind
  1622. * should then report 0 reachable in its leak report (in an ideal world --
  1623. * in practice libevent, ssl, libc etc never quite free everything). */
  1624. void
  1625. tor_free_all(int postfork)
  1626. {
  1627. if (!postfork) {
  1628. evdns_shutdown(1);
  1629. }
  1630. dirvote_free_all();
  1631. routerlist_free_all();
  1632. networkstatus_free_all();
  1633. addressmap_free_all();
  1634. set_exit_redirects(NULL); /* free the registered exit redirects */
  1635. dirserv_free_all();
  1636. rend_service_free_all();
  1637. rend_cache_free_all();
  1638. rep_hist_free_all();
  1639. hs_usage_free_all();
  1640. dns_free_all();
  1641. clear_pending_onions();
  1642. circuit_free_all();
  1643. entry_guards_free_all();
  1644. connection_free_all();
  1645. buf_shrink_freelists(1);
  1646. policies_free_all();
  1647. if (!postfork) {
  1648. config_free_all();
  1649. router_free_all();
  1650. }
  1651. free_cell_pool();
  1652. tor_tls_free_all();
  1653. /* stuff in main.c */
  1654. smartlist_free(connection_array);
  1655. smartlist_free(closeable_connection_lst);
  1656. smartlist_free(active_linked_connection_lst);
  1657. tor_free(timeout_event);
  1658. /* Stuff in util.c */
  1659. if (!postfork) {
  1660. escaped(NULL);
  1661. esc_router_info(NULL);
  1662. logs_free_all(); /* free log strings. do this last so logs keep working. */
  1663. }
  1664. }
  1665. /** Do whatever cleanup is necessary before shutting Tor down. */
  1666. void
  1667. tor_cleanup(void)
  1668. {
  1669. or_options_t *options = get_options();
  1670. /* Remove our pid file. We don't care if there was an error when we
  1671. * unlink, nothing we could do about it anyways. */
  1672. if (options->command == CMD_RUN_TOR) {
  1673. if (options->PidFile)
  1674. unlink(options->PidFile);
  1675. if (accounting_is_enabled(options))
  1676. accounting_record_bandwidth_usage(time(NULL), get_or_state());
  1677. or_state_mark_dirty(get_or_state(), 0); /* force an immediate save. */
  1678. or_state_save(time(NULL));
  1679. if (authdir_mode_tests_reachability(options))
  1680. rep_hist_record_mtbf_data();
  1681. }
  1682. #ifdef USE_DMALLOC
  1683. dmalloc_log_stats();
  1684. #endif
  1685. tor_free_all(0); /* We could move tor_free_all back into the ifdef below
  1686. later, if it makes shutdown unacceptably slow. But for
  1687. now, leave it here: it's helped us catch bugs in the
  1688. past. */
  1689. crypto_global_cleanup();
  1690. #ifdef USE_DMALLOC
  1691. dmalloc_log_unfreed();
  1692. dmalloc_shutdown();
  1693. #endif
  1694. }
  1695. /** Read/create keys as needed, and echo our fingerprint to stdout. */
  1696. /* static */ int
  1697. do_list_fingerprint(void)
  1698. {
  1699. char buf[FINGERPRINT_LEN+1];
  1700. crypto_pk_env_t *k;
  1701. const char *nickname = get_options()->Nickname;
  1702. if (!server_mode(get_options())) {
  1703. log_err(LD_GENERAL,
  1704. "Clients don't have long-term identity keys. Exiting.\n");
  1705. return -1;
  1706. }
  1707. tor_assert(nickname);
  1708. if (init_keys() < 0) {
  1709. log_err(LD_BUG,"Error initializing keys; can't display fingerprint");
  1710. return -1;
  1711. }
  1712. if (!(k = get_identity_key())) {
  1713. log_err(LD_GENERAL,"Error: missing identity key.");
  1714. return -1;
  1715. }
  1716. if (crypto_pk_get_fingerprint(k, buf, 1)<0) {
  1717. log_err(LD_BUG, "Error computing fingerprint");
  1718. return -1;
  1719. }
  1720. printf("%s %s\n", nickname, buf);
  1721. return 0;
  1722. }
  1723. /** Entry point for password hashing: take the desired password from
  1724. * the command line, and print its salted hash to stdout. **/
  1725. /* static */ void
  1726. do_hash_password(void)
  1727. {
  1728. char output[256];
  1729. char key[S2K_SPECIFIER_LEN+DIGEST_LEN];
  1730. crypto_rand(key, S2K_SPECIFIER_LEN-1);
  1731. key[S2K_SPECIFIER_LEN-1] = (uint8_t)96; /* Hash 64 K of data. */
  1732. secret_to_key(key+S2K_SPECIFIER_LEN, DIGEST_LEN,
  1733. get_options()->command_arg, strlen(get_options()->command_arg),
  1734. key);
  1735. base16_encode(output, sizeof(output), key, sizeof(key));
  1736. printf("16:%s\n",output);
  1737. }
  1738. #ifdef USE_DMALLOC
  1739. #include <openssl/crypto.h>
  1740. static void
  1741. _tor_dmalloc_free(void *p)
  1742. {
  1743. tor_free(p);
  1744. }
  1745. #endif
  1746. /** Main entry point for the Tor process. Called from main(). */
  1747. /* This function is distinct from main() only so we can link main.c into
  1748. * the unittest binary without conflicting with the unittests' main. */
  1749. int
  1750. tor_main(int argc, char *argv[])
  1751. {
  1752. int result = 0;
  1753. #ifdef USE_DMALLOC
  1754. int r = CRYPTO_set_mem_ex_functions(_tor_malloc, _tor_realloc,
  1755. _tor_dmalloc_free);
  1756. log_notice(LD_CONFIG, "Set up dmalloc; returned %d", r);
  1757. #endif
  1758. #ifdef NT_SERVICE
  1759. {
  1760. int done = 0;
  1761. result = nt_service_parse_options(argc, argv, &done);
  1762. if (done) return result;
  1763. }
  1764. #endif
  1765. if (tor_init(argc, argv)<0)
  1766. return -1;
  1767. switch (get_options()->command) {
  1768. case CMD_RUN_TOR:
  1769. #ifdef NT_SERVICE
  1770. nt_service_set_state(SERVICE_RUNNING);
  1771. #endif
  1772. result = do_main_loop();
  1773. break;
  1774. case CMD_LIST_FINGERPRINT:
  1775. result = do_list_fingerprint();
  1776. break;
  1777. case CMD_HASH_PASSWORD:
  1778. do_hash_password();
  1779. result = 0;
  1780. break;
  1781. case CMD_VERIFY_CONFIG:
  1782. printf("Configuration was valid\n");
  1783. result = 0;
  1784. break;
  1785. case CMD_RUN_UNITTESTS: /* only set by test.c */
  1786. default:
  1787. log_warn(LD_BUG,"Illegal command number %d: internal error.",
  1788. get_options()->command);
  1789. result = -1;
  1790. }
  1791. tor_cleanup();
  1792. return result;
  1793. }