main.c 68 KB

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