main.c 68 KB

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