main.c 71 KB

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