main.c 69 KB

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