mainloop.c 97 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041
  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-2018, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file mainloop.c
  8. * \brief Toplevel module. Handles signals, multiplexes between
  9. * connections, implements main loop, and drives scheduled events.
  10. *
  11. * For the main loop itself; see run_main_loop_once(). It invokes the rest of
  12. * Tor mostly through Libevent callbacks. Libevent callbacks can happen when
  13. * a timer elapses, a signal is received, a socket is ready to read or write,
  14. * or an event is manually activated.
  15. *
  16. * Most events in Tor are driven from these callbacks:
  17. * <ul>
  18. * <li>conn_read_callback() and conn_write_callback() here, which are
  19. * invoked when a socket is ready to read or write respectively.
  20. * <li>signal_callback(), which handles incoming signals.
  21. * </ul>
  22. * Other events are used for specific purposes, or for building more complex
  23. * control structures. If you search for usage of tor_libevent_new(), you
  24. * will find all the events that we construct in Tor.
  25. *
  26. * Tor has numerous housekeeping operations that need to happen
  27. * regularly. They are handled in different ways:
  28. * <ul>
  29. * <li>The most frequent operations are handled after every read or write
  30. * event, at the end of connection_handle_read() and
  31. * connection_handle_write().
  32. *
  33. * <li>The next most frequent operations happen after each invocation of the
  34. * main loop, in run_main_loop_once().
  35. *
  36. * <li>Once per second, we run all of the operations listed in
  37. * second_elapsed_callback(), and in its child, run_scheduled_events().
  38. *
  39. * <li>Once-a-second operations are handled in second_elapsed_callback().
  40. *
  41. * <li>More infrequent operations take place based on the periodic event
  42. * driver in periodic.c . These are stored in the periodic_events[]
  43. * table.
  44. * </ul>
  45. *
  46. **/
  47. #define MAINLOOP_PRIVATE
  48. #include "core/or/or.h"
  49. #include "app/config/config.h"
  50. #include "app/config/statefile.h"
  51. #include "app/main/ntmain.h"
  52. #include "core/mainloop/connection.h"
  53. #include "core/mainloop/cpuworker.h"
  54. #include "core/mainloop/mainloop.h"
  55. #include "core/mainloop/netstatus.h"
  56. #include "core/mainloop/periodic.h"
  57. #include "core/or/channel.h"
  58. #include "core/or/channelpadding.h"
  59. #include "core/or/channeltls.h"
  60. #include "core/or/circuitbuild.h"
  61. #include "core/or/circuitlist.h"
  62. #include "core/or/circuituse.h"
  63. #include "core/or/connection_edge.h"
  64. #include "core/or/connection_or.h"
  65. #include "core/or/dos.h"
  66. #include "core/or/status.h"
  67. #include "feature/client/addressmap.h"
  68. #include "feature/client/bridges.h"
  69. #include "feature/client/dnsserv.h"
  70. #include "feature/client/entrynodes.h"
  71. #include "feature/client/transports.h"
  72. #include "feature/control/control.h"
  73. #include "feature/dirauth/authmode.h"
  74. #include "feature/dirauth/reachability.h"
  75. #include "feature/dircache/consdiffmgr.h"
  76. #include "feature/dircache/dirserv.h"
  77. #include "feature/dircommon/directory.h"
  78. #include "feature/hibernate/hibernate.h"
  79. #include "feature/hs/hs_cache.h"
  80. #include "feature/hs/hs_client.h"
  81. #include "feature/hs/hs_service.h"
  82. #include "feature/nodelist/microdesc.h"
  83. #include "feature/nodelist/networkstatus.h"
  84. #include "feature/nodelist/nodelist.h"
  85. #include "feature/nodelist/routerlist.h"
  86. #include "feature/relay/dns.h"
  87. #include "feature/relay/routerkeys.h"
  88. #include "feature/relay/routermode.h"
  89. #include "feature/relay/selftest.h"
  90. #include "feature/rend/rendcache.h"
  91. #include "feature/rend/rendservice.h"
  92. #include "feature/stats/geoip_stats.h"
  93. #include "feature/stats/predict_ports.h"
  94. #include "feature/stats/rephist.h"
  95. #include "lib/buf/buffers.h"
  96. #include "lib/crypt_ops/crypto_rand.h"
  97. #include "lib/err/backtrace.h"
  98. #include "lib/tls/buffers_tls.h"
  99. #include "lib/net/buffers_net.h"
  100. #include "lib/evloop/compat_libevent.h"
  101. #include <event2/event.h>
  102. #include "feature/dirauth/dirvote.h"
  103. #include "feature/dirauth/authmode.h"
  104. #include "core/or/cell_st.h"
  105. #include "core/or/entry_connection_st.h"
  106. #include "feature/nodelist/networkstatus_st.h"
  107. #include "core/or/or_connection_st.h"
  108. #include "app/config/or_state_st.h"
  109. #include "feature/nodelist/routerinfo_st.h"
  110. #include "core/or/socks_request_st.h"
  111. #ifdef HAVE_UNISTD_H
  112. #include <unistd.h>
  113. #endif
  114. #ifdef HAVE_SYSTEMD
  115. # if defined(__COVERITY__) && !defined(__INCLUDE_LEVEL__)
  116. /* Systemd's use of gcc's __INCLUDE_LEVEL__ extension macro appears to confuse
  117. * Coverity. Here's a kludge to unconfuse it.
  118. */
  119. # define __INCLUDE_LEVEL__ 2
  120. #endif /* defined(__COVERITY__) && !defined(__INCLUDE_LEVEL__) */
  121. #include <systemd/sd-daemon.h>
  122. #endif /* defined(HAVE_SYSTEMD) */
  123. /* Token bucket for all traffic. */
  124. token_bucket_rw_t global_bucket;
  125. /* Token bucket for relayed traffic. */
  126. token_bucket_rw_t global_relayed_bucket;
  127. /* XXX we might want to keep stats about global_relayed_*_bucket too. Or not.*/
  128. /** How many bytes have we read since we started the process? */
  129. static uint64_t stats_n_bytes_read = 0;
  130. /** How many bytes have we written since we started the process? */
  131. static uint64_t stats_n_bytes_written = 0;
  132. /** What time did this process start up? */
  133. time_t time_of_process_start = 0;
  134. /** How many seconds have we been running? */
  135. static long stats_n_seconds_working = 0;
  136. /** How many times have we returned from the main loop successfully? */
  137. static uint64_t stats_n_main_loop_successes = 0;
  138. /** How many times have we received an error from the main loop? */
  139. static uint64_t stats_n_main_loop_errors = 0;
  140. /** How many times have we returned from the main loop with no events. */
  141. static uint64_t stats_n_main_loop_idle = 0;
  142. /** How often will we honor SIGNEWNYM requests? */
  143. #define MAX_SIGNEWNYM_RATE 10
  144. /** When did we last process a SIGNEWNYM request? */
  145. static time_t time_of_last_signewnym = 0;
  146. /** Is there a signewnym request we're currently waiting to handle? */
  147. static int signewnym_is_pending = 0;
  148. /** Mainloop event for the deferred signewnym call. */
  149. static mainloop_event_t *handle_deferred_signewnym_ev = NULL;
  150. /** How many times have we called newnym? */
  151. static unsigned newnym_epoch = 0;
  152. /** Smartlist of all open connections. */
  153. STATIC smartlist_t *connection_array = NULL;
  154. /** List of connections that have been marked for close and need to be freed
  155. * and removed from connection_array. */
  156. static smartlist_t *closeable_connection_lst = NULL;
  157. /** List of linked connections that are currently reading data into their
  158. * inbuf from their partner's outbuf. */
  159. static smartlist_t *active_linked_connection_lst = NULL;
  160. /** Flag: Set to true iff we entered the current libevent main loop via
  161. * <b>loop_once</b>. If so, there's no need to trigger a loopexit in order
  162. * to handle linked connections. */
  163. static int called_loop_once = 0;
  164. /** Flag: if true, it's time to shut down, so the main loop should exit as
  165. * soon as possible.
  166. */
  167. static int main_loop_should_exit = 0;
  168. /** The return value that the main loop should yield when it exits, if
  169. * main_loop_should_exit is true.
  170. */
  171. static int main_loop_exit_value = 0;
  172. /** We set this to 1 when we've opened a circuit, so we can print a log
  173. * entry to inform the user that Tor is working. We set it to 0 when
  174. * we think the fact that we once opened a circuit doesn't mean we can do so
  175. * any longer (a big time jump happened, when we notice our directory is
  176. * heinously out-of-date, etc.
  177. */
  178. static int can_complete_circuits = 0;
  179. /** How often do we check for router descriptors that we should download
  180. * when we have too little directory info? */
  181. #define GREEDY_DESCRIPTOR_RETRY_INTERVAL (10)
  182. /** How often do we check for router descriptors that we should download
  183. * when we have enough directory info? */
  184. #define LAZY_DESCRIPTOR_RETRY_INTERVAL (60)
  185. static int conn_close_if_marked(int i);
  186. static void connection_start_reading_from_linked_conn(connection_t *conn);
  187. static int connection_should_read_from_linked_conn(connection_t *conn);
  188. static void conn_read_callback(evutil_socket_t fd, short event, void *_conn);
  189. static void conn_write_callback(evutil_socket_t fd, short event, void *_conn);
  190. static void shutdown_did_not_work_callback(evutil_socket_t fd, short event,
  191. void *arg) ATTR_NORETURN;
  192. /****************************************************************************
  193. *
  194. * This section contains accessors and other methods on the connection_array
  195. * variables (which are global within this file and unavailable outside it).
  196. *
  197. ****************************************************************************/
  198. /** Return 1 if we have successfully built a circuit, and nothing has changed
  199. * to make us think that maybe we can't.
  200. */
  201. int
  202. have_completed_a_circuit(void)
  203. {
  204. return can_complete_circuits;
  205. }
  206. /** Note that we have successfully built a circuit, so that reachability
  207. * testing and introduction points and so on may be attempted. */
  208. void
  209. note_that_we_completed_a_circuit(void)
  210. {
  211. can_complete_circuits = 1;
  212. }
  213. /** Note that something has happened (like a clock jump, or DisableNetwork) to
  214. * make us think that maybe we can't complete circuits. */
  215. void
  216. note_that_we_maybe_cant_complete_circuits(void)
  217. {
  218. can_complete_circuits = 0;
  219. }
  220. /** Add <b>conn</b> to the array of connections that we can poll on. The
  221. * connection's socket must be set; the connection starts out
  222. * non-reading and non-writing.
  223. */
  224. int
  225. connection_add_impl(connection_t *conn, int is_connecting)
  226. {
  227. tor_assert(conn);
  228. tor_assert(SOCKET_OK(conn->s) ||
  229. conn->linked ||
  230. (conn->type == CONN_TYPE_AP &&
  231. TO_EDGE_CONN(conn)->is_dns_request));
  232. tor_assert(conn->conn_array_index == -1); /* can only connection_add once */
  233. conn->conn_array_index = smartlist_len(connection_array);
  234. smartlist_add(connection_array, conn);
  235. (void) is_connecting;
  236. if (SOCKET_OK(conn->s) || conn->linked) {
  237. conn->read_event = tor_event_new(tor_libevent_get_base(),
  238. conn->s, EV_READ|EV_PERSIST, conn_read_callback, conn);
  239. conn->write_event = tor_event_new(tor_libevent_get_base(),
  240. conn->s, EV_WRITE|EV_PERSIST, conn_write_callback, conn);
  241. /* XXXX CHECK FOR NULL RETURN! */
  242. }
  243. log_debug(LD_NET,"new conn type %s, socket %d, address %s, n_conns %d.",
  244. conn_type_to_string(conn->type), (int)conn->s, conn->address,
  245. smartlist_len(connection_array));
  246. return 0;
  247. }
  248. /** Tell libevent that we don't care about <b>conn</b> any more. */
  249. void
  250. connection_unregister_events(connection_t *conn)
  251. {
  252. if (conn->read_event) {
  253. if (event_del(conn->read_event))
  254. log_warn(LD_BUG, "Error removing read event for %d", (int)conn->s);
  255. tor_free(conn->read_event);
  256. }
  257. if (conn->write_event) {
  258. if (event_del(conn->write_event))
  259. log_warn(LD_BUG, "Error removing write event for %d", (int)conn->s);
  260. tor_free(conn->write_event);
  261. }
  262. if (conn->type == CONN_TYPE_AP_DNS_LISTENER) {
  263. dnsserv_close_listener(conn);
  264. }
  265. }
  266. /** Remove the connection from the global list, and remove the
  267. * corresponding poll entry. Calling this function will shift the last
  268. * connection (if any) into the position occupied by conn.
  269. */
  270. int
  271. connection_remove(connection_t *conn)
  272. {
  273. int current_index;
  274. connection_t *tmp;
  275. tor_assert(conn);
  276. log_debug(LD_NET,"removing socket %d (type %s), n_conns now %d",
  277. (int)conn->s, conn_type_to_string(conn->type),
  278. smartlist_len(connection_array));
  279. if (conn->type == CONN_TYPE_AP && conn->socket_family == AF_UNIX) {
  280. log_info(LD_NET, "Closing SOCKS Unix socket connection");
  281. }
  282. control_event_conn_bandwidth(conn);
  283. tor_assert(conn->conn_array_index >= 0);
  284. current_index = conn->conn_array_index;
  285. connection_unregister_events(conn); /* This is redundant, but cheap. */
  286. if (current_index == smartlist_len(connection_array)-1) { /* at the end */
  287. smartlist_del(connection_array, current_index);
  288. return 0;
  289. }
  290. /* replace this one with the one at the end */
  291. smartlist_del(connection_array, current_index);
  292. tmp = smartlist_get(connection_array, current_index);
  293. tmp->conn_array_index = current_index;
  294. return 0;
  295. }
  296. /** If <b>conn</b> is an edge conn, remove it from the list
  297. * of conn's on this circuit. If it's not on an edge,
  298. * flush and send destroys for all circuits on this conn.
  299. *
  300. * Remove it from connection_array (if applicable) and
  301. * from closeable_connection_list.
  302. *
  303. * Then free it.
  304. */
  305. static void
  306. connection_unlink(connection_t *conn)
  307. {
  308. connection_about_to_close_connection(conn);
  309. if (conn->conn_array_index >= 0) {
  310. connection_remove(conn);
  311. }
  312. if (conn->linked_conn) {
  313. conn->linked_conn->linked_conn = NULL;
  314. if (! conn->linked_conn->marked_for_close &&
  315. conn->linked_conn->reading_from_linked_conn)
  316. connection_start_reading(conn->linked_conn);
  317. conn->linked_conn = NULL;
  318. }
  319. smartlist_remove(closeable_connection_lst, conn);
  320. smartlist_remove(active_linked_connection_lst, conn);
  321. if (conn->type == CONN_TYPE_EXIT) {
  322. assert_connection_edge_not_dns_pending(TO_EDGE_CONN(conn));
  323. }
  324. if (conn->type == CONN_TYPE_OR) {
  325. if (!tor_digest_is_zero(TO_OR_CONN(conn)->identity_digest))
  326. connection_or_clear_identity(TO_OR_CONN(conn));
  327. /* connection_unlink() can only get called if the connection
  328. * was already on the closeable list, and it got there by
  329. * connection_mark_for_close(), which was called from
  330. * connection_or_close_normally() or
  331. * connection_or_close_for_error(), so the channel should
  332. * already be in CHANNEL_STATE_CLOSING, and then the
  333. * connection_about_to_close_connection() goes to
  334. * connection_or_about_to_close(), which calls channel_closed()
  335. * to notify the channel_t layer, and closed the channel, so
  336. * nothing more to do here to deal with the channel associated
  337. * with an orconn.
  338. */
  339. }
  340. connection_free(conn);
  341. }
  342. /**
  343. * Callback: used to activate read events for all linked connections, so
  344. * libevent knows to call their read callbacks. This callback run as a
  345. * postloop event, so that the events _it_ activates don't happen until
  346. * Libevent has a chance to check for other events.
  347. */
  348. static void
  349. schedule_active_linked_connections_cb(mainloop_event_t *event, void *arg)
  350. {
  351. (void)event;
  352. (void)arg;
  353. /* All active linked conns should get their read events activated,
  354. * so that libevent knows to run their callbacks. */
  355. SMARTLIST_FOREACH(active_linked_connection_lst, connection_t *, conn,
  356. event_active(conn->read_event, EV_READ, 1));
  357. }
  358. /** Event that invokes schedule_active_linked_connections_cb. */
  359. static mainloop_event_t *schedule_active_linked_connections_event = NULL;
  360. /** Initialize the global connection list, closeable connection list,
  361. * and active connection list. */
  362. void
  363. tor_init_connection_lists(void)
  364. {
  365. if (!connection_array)
  366. connection_array = smartlist_new();
  367. if (!closeable_connection_lst)
  368. closeable_connection_lst = smartlist_new();
  369. if (!active_linked_connection_lst)
  370. active_linked_connection_lst = smartlist_new();
  371. }
  372. /** Schedule <b>conn</b> to be closed. **/
  373. void
  374. add_connection_to_closeable_list(connection_t *conn)
  375. {
  376. tor_assert(!smartlist_contains(closeable_connection_lst, conn));
  377. tor_assert(conn->marked_for_close);
  378. assert_connection_ok(conn, time(NULL));
  379. smartlist_add(closeable_connection_lst, conn);
  380. mainloop_schedule_postloop_cleanup();
  381. }
  382. /** Return 1 if conn is on the closeable list, else return 0. */
  383. int
  384. connection_is_on_closeable_list(connection_t *conn)
  385. {
  386. return smartlist_contains(closeable_connection_lst, conn);
  387. }
  388. /** Return true iff conn is in the current poll array. */
  389. int
  390. connection_in_array(connection_t *conn)
  391. {
  392. return smartlist_contains(connection_array, conn);
  393. }
  394. /** Set <b>*array</b> to an array of all connections. <b>*array</b> must not
  395. * be modified.
  396. */
  397. MOCK_IMPL(smartlist_t *,
  398. get_connection_array, (void))
  399. {
  400. if (!connection_array)
  401. connection_array = smartlist_new();
  402. return connection_array;
  403. }
  404. /**
  405. * Return the amount of network traffic read, in bytes, over the life of this
  406. * process.
  407. */
  408. MOCK_IMPL(uint64_t,
  409. get_bytes_read,(void))
  410. {
  411. return stats_n_bytes_read;
  412. }
  413. /**
  414. * Return the amount of network traffic read, in bytes, over the life of this
  415. * process.
  416. */
  417. MOCK_IMPL(uint64_t,
  418. get_bytes_written,(void))
  419. {
  420. return stats_n_bytes_written;
  421. }
  422. /**
  423. * Increment the amount of network traffic read and written, over the life of
  424. * this process.
  425. */
  426. void
  427. stats_increment_bytes_read_and_written(uint64_t r, uint64_t w)
  428. {
  429. stats_n_bytes_read += r;
  430. stats_n_bytes_written += w;
  431. }
  432. /** Set the event mask on <b>conn</b> to <b>events</b>. (The event
  433. * mask is a bitmask whose bits are READ_EVENT and WRITE_EVENT)
  434. */
  435. void
  436. connection_watch_events(connection_t *conn, watchable_events_t events)
  437. {
  438. if (events & READ_EVENT)
  439. connection_start_reading(conn);
  440. else
  441. connection_stop_reading(conn);
  442. if (events & WRITE_EVENT)
  443. connection_start_writing(conn);
  444. else
  445. connection_stop_writing(conn);
  446. }
  447. /** Return true iff <b>conn</b> is listening for read events. */
  448. int
  449. connection_is_reading(connection_t *conn)
  450. {
  451. tor_assert(conn);
  452. return conn->reading_from_linked_conn ||
  453. (conn->read_event && event_pending(conn->read_event, EV_READ, NULL));
  454. }
  455. /** Reset our main loop counters. */
  456. void
  457. reset_main_loop_counters(void)
  458. {
  459. stats_n_main_loop_successes = 0;
  460. stats_n_main_loop_errors = 0;
  461. stats_n_main_loop_idle = 0;
  462. }
  463. /** Increment the main loop success counter. */
  464. static void
  465. increment_main_loop_success_count(void)
  466. {
  467. ++stats_n_main_loop_successes;
  468. }
  469. /** Get the main loop success counter. */
  470. uint64_t
  471. get_main_loop_success_count(void)
  472. {
  473. return stats_n_main_loop_successes;
  474. }
  475. /** Increment the main loop error counter. */
  476. static void
  477. increment_main_loop_error_count(void)
  478. {
  479. ++stats_n_main_loop_errors;
  480. }
  481. /** Get the main loop error counter. */
  482. uint64_t
  483. get_main_loop_error_count(void)
  484. {
  485. return stats_n_main_loop_errors;
  486. }
  487. /** Increment the main loop idle counter. */
  488. static void
  489. increment_main_loop_idle_count(void)
  490. {
  491. ++stats_n_main_loop_idle;
  492. }
  493. /** Get the main loop idle counter. */
  494. uint64_t
  495. get_main_loop_idle_count(void)
  496. {
  497. return stats_n_main_loop_idle;
  498. }
  499. /** Check whether <b>conn</b> is correct in having (or not having) a
  500. * read/write event (passed in <b>ev</b>). On success, return 0. On failure,
  501. * log a warning and return -1. */
  502. static int
  503. connection_check_event(connection_t *conn, struct event *ev)
  504. {
  505. int bad;
  506. if (conn->type == CONN_TYPE_AP && TO_EDGE_CONN(conn)->is_dns_request) {
  507. /* DNS requests which we launch through the dnsserv.c module do not have
  508. * any underlying socket or any underlying linked connection, so they
  509. * shouldn't have any attached events either.
  510. */
  511. bad = ev != NULL;
  512. } else {
  513. /* Everything else should have an underlying socket, or a linked
  514. * connection (which is also tracked with a read_event/write_event pair).
  515. */
  516. bad = ev == NULL;
  517. }
  518. if (bad) {
  519. log_warn(LD_BUG, "Event missing on connection %p [%s;%s]. "
  520. "socket=%d. linked=%d. "
  521. "is_dns_request=%d. Marked_for_close=%s:%d",
  522. conn,
  523. conn_type_to_string(conn->type),
  524. conn_state_to_string(conn->type, conn->state),
  525. (int)conn->s, (int)conn->linked,
  526. (conn->type == CONN_TYPE_AP &&
  527. TO_EDGE_CONN(conn)->is_dns_request),
  528. conn->marked_for_close_file ? conn->marked_for_close_file : "-",
  529. conn->marked_for_close
  530. );
  531. log_backtrace(LOG_WARN, LD_BUG, "Backtrace attached.");
  532. return -1;
  533. }
  534. return 0;
  535. }
  536. /** Tell the main loop to stop notifying <b>conn</b> of any read events. */
  537. MOCK_IMPL(void,
  538. connection_stop_reading,(connection_t *conn))
  539. {
  540. tor_assert(conn);
  541. if (connection_check_event(conn, conn->read_event) < 0) {
  542. return;
  543. }
  544. if (conn->linked) {
  545. conn->reading_from_linked_conn = 0;
  546. connection_stop_reading_from_linked_conn(conn);
  547. } else {
  548. if (event_del(conn->read_event))
  549. log_warn(LD_NET, "Error from libevent setting read event state for %d "
  550. "to unwatched: %s",
  551. (int)conn->s,
  552. tor_socket_strerror(tor_socket_errno(conn->s)));
  553. }
  554. }
  555. /** Tell the main loop to start notifying <b>conn</b> of any read events. */
  556. MOCK_IMPL(void,
  557. connection_start_reading,(connection_t *conn))
  558. {
  559. tor_assert(conn);
  560. if (connection_check_event(conn, conn->read_event) < 0) {
  561. return;
  562. }
  563. if (conn->linked) {
  564. conn->reading_from_linked_conn = 1;
  565. if (connection_should_read_from_linked_conn(conn))
  566. connection_start_reading_from_linked_conn(conn);
  567. } else {
  568. if (event_add(conn->read_event, NULL))
  569. log_warn(LD_NET, "Error from libevent setting read event state for %d "
  570. "to watched: %s",
  571. (int)conn->s,
  572. tor_socket_strerror(tor_socket_errno(conn->s)));
  573. }
  574. }
  575. /** Return true iff <b>conn</b> is listening for write events. */
  576. int
  577. connection_is_writing(connection_t *conn)
  578. {
  579. tor_assert(conn);
  580. return conn->writing_to_linked_conn ||
  581. (conn->write_event && event_pending(conn->write_event, EV_WRITE, NULL));
  582. }
  583. /** Tell the main loop to stop notifying <b>conn</b> of any write events. */
  584. MOCK_IMPL(void,
  585. connection_stop_writing,(connection_t *conn))
  586. {
  587. tor_assert(conn);
  588. if (connection_check_event(conn, conn->write_event) < 0) {
  589. return;
  590. }
  591. if (conn->linked) {
  592. conn->writing_to_linked_conn = 0;
  593. if (conn->linked_conn)
  594. connection_stop_reading_from_linked_conn(conn->linked_conn);
  595. } else {
  596. if (event_del(conn->write_event))
  597. log_warn(LD_NET, "Error from libevent setting write event state for %d "
  598. "to unwatched: %s",
  599. (int)conn->s,
  600. tor_socket_strerror(tor_socket_errno(conn->s)));
  601. }
  602. }
  603. /** Tell the main loop to start notifying <b>conn</b> of any write events. */
  604. MOCK_IMPL(void,
  605. connection_start_writing,(connection_t *conn))
  606. {
  607. tor_assert(conn);
  608. if (connection_check_event(conn, conn->write_event) < 0) {
  609. return;
  610. }
  611. if (conn->linked) {
  612. conn->writing_to_linked_conn = 1;
  613. if (conn->linked_conn &&
  614. connection_should_read_from_linked_conn(conn->linked_conn))
  615. connection_start_reading_from_linked_conn(conn->linked_conn);
  616. } else {
  617. if (event_add(conn->write_event, NULL))
  618. log_warn(LD_NET, "Error from libevent setting write event state for %d "
  619. "to watched: %s",
  620. (int)conn->s,
  621. tor_socket_strerror(tor_socket_errno(conn->s)));
  622. }
  623. }
  624. /** Return true iff <b>conn</b> is linked conn, and reading from the conn
  625. * linked to it would be good and feasible. (Reading is "feasible" if the
  626. * other conn exists and has data in its outbuf, and is "good" if we have our
  627. * reading_from_linked_conn flag set and the other conn has its
  628. * writing_to_linked_conn flag set.)*/
  629. static int
  630. connection_should_read_from_linked_conn(connection_t *conn)
  631. {
  632. if (conn->linked && conn->reading_from_linked_conn) {
  633. if (! conn->linked_conn ||
  634. (conn->linked_conn->writing_to_linked_conn &&
  635. buf_datalen(conn->linked_conn->outbuf)))
  636. return 1;
  637. }
  638. return 0;
  639. }
  640. /** Event to run 'shutdown did not work callback'. */
  641. static struct event *shutdown_did_not_work_event = NULL;
  642. /** Failsafe measure that should never actually be necessary: If
  643. * tor_shutdown_event_loop_and_exit() somehow doesn't successfully exit the
  644. * event loop, then this callback will kill Tor with an assertion failure
  645. * seconds later
  646. */
  647. static void
  648. shutdown_did_not_work_callback(evutil_socket_t fd, short event, void *arg)
  649. {
  650. // LCOV_EXCL_START
  651. (void) fd;
  652. (void) event;
  653. (void) arg;
  654. tor_assert_unreached();
  655. // LCOV_EXCL_STOP
  656. }
  657. #ifdef ENABLE_RESTART_DEBUGGING
  658. static struct event *tor_shutdown_event_loop_for_restart_event = NULL;
  659. static void
  660. tor_shutdown_event_loop_for_restart_cb(
  661. evutil_socket_t fd, short event, void *arg)
  662. {
  663. (void)fd;
  664. (void)event;
  665. (void)arg;
  666. tor_event_free(tor_shutdown_event_loop_for_restart_event);
  667. tor_shutdown_event_loop_and_exit(0);
  668. }
  669. #endif
  670. /**
  671. * After finishing the current callback (if any), shut down the main loop,
  672. * clean up the process, and exit with <b>exitcode</b>.
  673. */
  674. void
  675. tor_shutdown_event_loop_and_exit(int exitcode)
  676. {
  677. if (main_loop_should_exit)
  678. return; /* Ignore multiple calls to this function. */
  679. main_loop_should_exit = 1;
  680. main_loop_exit_value = exitcode;
  681. /* Die with an assertion failure in ten seconds, if for some reason we don't
  682. * exit normally. */
  683. /* XXXX We should consider this code if it's never used. */
  684. struct timeval ten_seconds = { 10, 0 };
  685. shutdown_did_not_work_event = tor_evtimer_new(
  686. tor_libevent_get_base(),
  687. shutdown_did_not_work_callback, NULL);
  688. event_add(shutdown_did_not_work_event, &ten_seconds);
  689. /* Unlike exit_loop_after_delay(), exit_loop_after_callback
  690. * prevents other callbacks from running. */
  691. tor_libevent_exit_loop_after_callback(tor_libevent_get_base());
  692. }
  693. /** Return true iff tor_shutdown_event_loop_and_exit() has been called. */
  694. int
  695. tor_event_loop_shutdown_is_pending(void)
  696. {
  697. return main_loop_should_exit;
  698. }
  699. /** Helper: Tell the main loop to begin reading bytes into <b>conn</b> from
  700. * its linked connection, if it is not doing so already. Called by
  701. * connection_start_reading and connection_start_writing as appropriate. */
  702. static void
  703. connection_start_reading_from_linked_conn(connection_t *conn)
  704. {
  705. tor_assert(conn);
  706. tor_assert(conn->linked == 1);
  707. if (!conn->active_on_link) {
  708. conn->active_on_link = 1;
  709. smartlist_add(active_linked_connection_lst, conn);
  710. mainloop_event_activate(schedule_active_linked_connections_event);
  711. } else {
  712. tor_assert(smartlist_contains(active_linked_connection_lst, conn));
  713. }
  714. }
  715. /** Tell the main loop to stop reading bytes into <b>conn</b> from its linked
  716. * connection, if is currently doing so. Called by connection_stop_reading,
  717. * connection_stop_writing, and connection_read. */
  718. void
  719. connection_stop_reading_from_linked_conn(connection_t *conn)
  720. {
  721. tor_assert(conn);
  722. tor_assert(conn->linked == 1);
  723. if (conn->active_on_link) {
  724. conn->active_on_link = 0;
  725. /* FFFF We could keep an index here so we can smartlist_del
  726. * cleanly. On the other hand, this doesn't show up on profiles,
  727. * so let's leave it alone for now. */
  728. smartlist_remove(active_linked_connection_lst, conn);
  729. } else {
  730. tor_assert(!smartlist_contains(active_linked_connection_lst, conn));
  731. }
  732. }
  733. /** Close all connections that have been scheduled to get closed. */
  734. STATIC void
  735. close_closeable_connections(void)
  736. {
  737. int i;
  738. for (i = 0; i < smartlist_len(closeable_connection_lst); ) {
  739. connection_t *conn = smartlist_get(closeable_connection_lst, i);
  740. if (conn->conn_array_index < 0) {
  741. connection_unlink(conn); /* blow it away right now */
  742. } else {
  743. if (!conn_close_if_marked(conn->conn_array_index))
  744. ++i;
  745. }
  746. }
  747. }
  748. /** Count moribund connections for the OOS handler */
  749. MOCK_IMPL(int,
  750. connection_count_moribund, (void))
  751. {
  752. int moribund = 0;
  753. /*
  754. * Count things we'll try to kill when close_closeable_connections()
  755. * runs next.
  756. */
  757. SMARTLIST_FOREACH_BEGIN(closeable_connection_lst, connection_t *, conn) {
  758. if (SOCKET_OK(conn->s) && connection_is_moribund(conn)) ++moribund;
  759. } SMARTLIST_FOREACH_END(conn);
  760. return moribund;
  761. }
  762. /** Libevent callback: this gets invoked when (connection_t*)<b>conn</b> has
  763. * some data to read. */
  764. static void
  765. conn_read_callback(evutil_socket_t fd, short event, void *_conn)
  766. {
  767. connection_t *conn = _conn;
  768. (void)fd;
  769. (void)event;
  770. log_debug(LD_NET,"socket %d wants to read.",(int)conn->s);
  771. /* assert_connection_ok(conn, time(NULL)); */
  772. if (connection_handle_read(conn) < 0) {
  773. if (!conn->marked_for_close) {
  774. #ifndef _WIN32
  775. log_warn(LD_BUG,"Unhandled error on read for %s connection "
  776. "(fd %d); removing",
  777. conn_type_to_string(conn->type), (int)conn->s);
  778. tor_fragile_assert();
  779. #endif /* !defined(_WIN32) */
  780. if (CONN_IS_EDGE(conn))
  781. connection_edge_end_errno(TO_EDGE_CONN(conn));
  782. connection_mark_for_close(conn);
  783. }
  784. }
  785. assert_connection_ok(conn, time(NULL));
  786. if (smartlist_len(closeable_connection_lst))
  787. close_closeable_connections();
  788. }
  789. /** Libevent callback: this gets invoked when (connection_t*)<b>conn</b> has
  790. * some data to write. */
  791. static void
  792. conn_write_callback(evutil_socket_t fd, short events, void *_conn)
  793. {
  794. connection_t *conn = _conn;
  795. (void)fd;
  796. (void)events;
  797. LOG_FN_CONN(conn, (LOG_DEBUG, LD_NET, "socket %d wants to write.",
  798. (int)conn->s));
  799. /* assert_connection_ok(conn, time(NULL)); */
  800. if (connection_handle_write(conn, 0) < 0) {
  801. if (!conn->marked_for_close) {
  802. /* this connection is broken. remove it. */
  803. log_fn(LOG_WARN,LD_BUG,
  804. "unhandled error on write for %s connection (fd %d); removing",
  805. conn_type_to_string(conn->type), (int)conn->s);
  806. tor_fragile_assert();
  807. if (CONN_IS_EDGE(conn)) {
  808. /* otherwise we cry wolf about duplicate close */
  809. edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
  810. if (!edge_conn->end_reason)
  811. edge_conn->end_reason = END_STREAM_REASON_INTERNAL;
  812. edge_conn->edge_has_sent_end = 1;
  813. }
  814. connection_close_immediate(conn); /* So we don't try to flush. */
  815. connection_mark_for_close(conn);
  816. }
  817. }
  818. assert_connection_ok(conn, time(NULL));
  819. if (smartlist_len(closeable_connection_lst))
  820. close_closeable_connections();
  821. }
  822. /** If the connection at connection_array[i] is marked for close, then:
  823. * - If it has data that it wants to flush, try to flush it.
  824. * - If it _still_ has data to flush, and conn->hold_open_until_flushed is
  825. * true, then leave the connection open and return.
  826. * - Otherwise, remove the connection from connection_array and from
  827. * all other lists, close it, and free it.
  828. * Returns 1 if the connection was closed, 0 otherwise.
  829. */
  830. static int
  831. conn_close_if_marked(int i)
  832. {
  833. connection_t *conn;
  834. int retval;
  835. time_t now;
  836. conn = smartlist_get(connection_array, i);
  837. if (!conn->marked_for_close)
  838. return 0; /* nothing to see here, move along */
  839. now = time(NULL);
  840. assert_connection_ok(conn, now);
  841. /* assert_all_pending_dns_resolves_ok(); */
  842. log_debug(LD_NET,"Cleaning up connection (fd "TOR_SOCKET_T_FORMAT").",
  843. conn->s);
  844. /* If the connection we are about to close was trying to connect to
  845. a proxy server and failed, the client won't be able to use that
  846. proxy. We should warn the user about this. */
  847. if (conn->proxy_state == PROXY_INFANT)
  848. log_failed_proxy_connection(conn);
  849. if ((SOCKET_OK(conn->s) || conn->linked_conn) &&
  850. connection_wants_to_flush(conn)) {
  851. /* s == -1 means it's an incomplete edge connection, or that the socket
  852. * has already been closed as unflushable. */
  853. ssize_t sz = connection_bucket_write_limit(conn, now);
  854. if (!conn->hold_open_until_flushed)
  855. log_info(LD_NET,
  856. "Conn (addr %s, fd %d, type %s, state %d) marked, but wants "
  857. "to flush %d bytes. (Marked at %s:%d)",
  858. escaped_safe_str_client(conn->address),
  859. (int)conn->s, conn_type_to_string(conn->type), conn->state,
  860. (int)conn->outbuf_flushlen,
  861. conn->marked_for_close_file, conn->marked_for_close);
  862. if (conn->linked_conn) {
  863. retval = buf_move_to_buf(conn->linked_conn->inbuf, conn->outbuf,
  864. &conn->outbuf_flushlen);
  865. if (retval >= 0) {
  866. /* The linked conn will notice that it has data when it notices that
  867. * we're gone. */
  868. connection_start_reading_from_linked_conn(conn->linked_conn);
  869. }
  870. log_debug(LD_GENERAL, "Flushed last %d bytes from a linked conn; "
  871. "%d left; flushlen %d; wants-to-flush==%d", retval,
  872. (int)connection_get_outbuf_len(conn),
  873. (int)conn->outbuf_flushlen,
  874. connection_wants_to_flush(conn));
  875. } else if (connection_speaks_cells(conn)) {
  876. if (conn->state == OR_CONN_STATE_OPEN) {
  877. retval = buf_flush_to_tls(conn->outbuf, TO_OR_CONN(conn)->tls, sz,
  878. &conn->outbuf_flushlen);
  879. } else
  880. retval = -1; /* never flush non-open broken tls connections */
  881. } else {
  882. retval = buf_flush_to_socket(conn->outbuf, conn->s, sz,
  883. &conn->outbuf_flushlen);
  884. }
  885. if (retval >= 0 && /* Technically, we could survive things like
  886. TLS_WANT_WRITE here. But don't bother for now. */
  887. conn->hold_open_until_flushed && connection_wants_to_flush(conn)) {
  888. if (retval > 0) {
  889. LOG_FN_CONN(conn, (LOG_INFO,LD_NET,
  890. "Holding conn (fd %d) open for more flushing.",
  891. (int)conn->s));
  892. conn->timestamp_last_write_allowed = now; /* reset so we can flush
  893. * more */
  894. } else if (sz == 0) {
  895. /* Also, retval==0. If we get here, we didn't want to write anything
  896. * (because of rate-limiting) and we didn't. */
  897. /* Connection must flush before closing, but it's being rate-limited.
  898. * Let's remove from Libevent, and mark it as blocked on bandwidth
  899. * so it will be re-added on next token bucket refill. Prevents
  900. * busy Libevent loops where we keep ending up here and returning
  901. * 0 until we are no longer blocked on bandwidth.
  902. */
  903. connection_consider_empty_write_buckets(conn);
  904. /* Make sure that consider_empty_buckets really disabled the
  905. * connection: */
  906. if (BUG(connection_is_writing(conn))) {
  907. connection_write_bw_exhausted(conn, true);
  908. }
  909. /* The connection is being held due to write rate limit and thus will
  910. * flush its data later. We need to stop reading because this
  911. * connection is about to be closed once flushed. It should not
  912. * process anything more coming in at this stage. */
  913. connection_stop_reading(conn);
  914. }
  915. return 0;
  916. }
  917. if (connection_wants_to_flush(conn)) {
  918. log_fn(LOG_INFO, LD_NET, "We stalled too much while trying to write %d "
  919. "bytes to address %s. If this happens a lot, either "
  920. "something is wrong with your network connection, or "
  921. "something is wrong with theirs. "
  922. "(fd %d, type %s, state %d, marked at %s:%d).",
  923. (int)connection_get_outbuf_len(conn),
  924. escaped_safe_str_client(conn->address),
  925. (int)conn->s, conn_type_to_string(conn->type), conn->state,
  926. conn->marked_for_close_file,
  927. conn->marked_for_close);
  928. }
  929. }
  930. connection_unlink(conn); /* unlink, remove, free */
  931. return 1;
  932. }
  933. /** Implementation for directory_all_unreachable. This is done in a callback,
  934. * since otherwise it would complicate Tor's control-flow graph beyond all
  935. * reason.
  936. */
  937. static void
  938. directory_all_unreachable_cb(mainloop_event_t *event, void *arg)
  939. {
  940. (void)event;
  941. (void)arg;
  942. connection_t *conn;
  943. while ((conn = connection_get_by_type_state(CONN_TYPE_AP,
  944. AP_CONN_STATE_CIRCUIT_WAIT))) {
  945. entry_connection_t *entry_conn = TO_ENTRY_CONN(conn);
  946. log_notice(LD_NET,
  947. "Is your network connection down? "
  948. "Failing connection to '%s:%d'.",
  949. safe_str_client(entry_conn->socks_request->address),
  950. entry_conn->socks_request->port);
  951. connection_mark_unattached_ap(entry_conn,
  952. END_STREAM_REASON_NET_UNREACHABLE);
  953. }
  954. control_event_general_error("DIR_ALL_UNREACHABLE");
  955. }
  956. static mainloop_event_t *directory_all_unreachable_cb_event = NULL;
  957. /** We've just tried every dirserver we know about, and none of
  958. * them were reachable. Assume the network is down. Change state
  959. * so next time an application connection arrives we'll delay it
  960. * and try another directory fetch. Kill off all the circuit_wait
  961. * streams that are waiting now, since they will all timeout anyway.
  962. */
  963. void
  964. directory_all_unreachable(time_t now)
  965. {
  966. (void)now;
  967. reset_uptime(); /* reset it */
  968. if (!directory_all_unreachable_cb_event) {
  969. directory_all_unreachable_cb_event =
  970. mainloop_event_new(directory_all_unreachable_cb, NULL);
  971. tor_assert(directory_all_unreachable_cb_event);
  972. }
  973. mainloop_event_activate(directory_all_unreachable_cb_event);
  974. }
  975. /** This function is called whenever we successfully pull down some new
  976. * network statuses or server descriptors. */
  977. void
  978. directory_info_has_arrived(time_t now, int from_cache, int suppress_logs)
  979. {
  980. const or_options_t *options = get_options();
  981. /* if we have enough dir info, then update our guard status with
  982. * whatever we just learned. */
  983. int invalidate_circs = guards_update_all();
  984. if (invalidate_circs) {
  985. circuit_mark_all_unused_circs();
  986. circuit_mark_all_dirty_circs_as_unusable();
  987. }
  988. if (!router_have_minimum_dir_info()) {
  989. int quiet = suppress_logs || from_cache ||
  990. directory_too_idle_to_fetch_descriptors(options, now);
  991. tor_log(quiet ? LOG_INFO : LOG_NOTICE, LD_DIR,
  992. "I learned some more directory information, but not enough to "
  993. "build a circuit: %s", get_dir_info_status_string());
  994. update_all_descriptor_downloads(now);
  995. return;
  996. } else {
  997. if (directory_fetches_from_authorities(options)) {
  998. update_all_descriptor_downloads(now);
  999. }
  1000. /* Don't even bother trying to get extrainfo until the rest of our
  1001. * directory info is up-to-date */
  1002. if (options->DownloadExtraInfo)
  1003. update_extrainfo_downloads(now);
  1004. }
  1005. if (server_mode(options) && !net_is_disabled() && !from_cache &&
  1006. (have_completed_a_circuit() || !any_predicted_circuits(now)))
  1007. router_do_reachability_checks(1, 1);
  1008. }
  1009. /** Perform regular maintenance tasks for a single connection. This
  1010. * function gets run once per second per connection by run_scheduled_events.
  1011. */
  1012. static void
  1013. run_connection_housekeeping(int i, time_t now)
  1014. {
  1015. cell_t cell;
  1016. connection_t *conn = smartlist_get(connection_array, i);
  1017. const or_options_t *options = get_options();
  1018. or_connection_t *or_conn;
  1019. channel_t *chan = NULL;
  1020. int have_any_circuits;
  1021. int past_keepalive =
  1022. now >= conn->timestamp_last_write_allowed + options->KeepalivePeriod;
  1023. if (conn->outbuf && !connection_get_outbuf_len(conn) &&
  1024. conn->type == CONN_TYPE_OR)
  1025. TO_OR_CONN(conn)->timestamp_lastempty = now;
  1026. if (conn->marked_for_close) {
  1027. /* nothing to do here */
  1028. return;
  1029. }
  1030. /* Expire any directory connections that haven't been active (sent
  1031. * if a server or received if a client) for 5 min */
  1032. if (conn->type == CONN_TYPE_DIR &&
  1033. ((DIR_CONN_IS_SERVER(conn) &&
  1034. conn->timestamp_last_write_allowed
  1035. + options->TestingDirConnectionMaxStall < now) ||
  1036. (!DIR_CONN_IS_SERVER(conn) &&
  1037. conn->timestamp_last_read_allowed
  1038. + options->TestingDirConnectionMaxStall < now))) {
  1039. log_info(LD_DIR,"Expiring wedged directory conn (fd %d, purpose %d)",
  1040. (int)conn->s, conn->purpose);
  1041. /* This check is temporary; it's to let us know whether we should consider
  1042. * parsing partial serverdesc responses. */
  1043. if (conn->purpose == DIR_PURPOSE_FETCH_SERVERDESC &&
  1044. connection_get_inbuf_len(conn) >= 1024) {
  1045. log_info(LD_DIR,"Trying to extract information from wedged server desc "
  1046. "download.");
  1047. connection_dir_reached_eof(TO_DIR_CONN(conn));
  1048. } else {
  1049. connection_mark_for_close(conn);
  1050. }
  1051. return;
  1052. }
  1053. if (!connection_speaks_cells(conn))
  1054. return; /* we're all done here, the rest is just for OR conns */
  1055. /* If we haven't flushed to an OR connection for a while, then either nuke
  1056. the connection or send a keepalive, depending. */
  1057. or_conn = TO_OR_CONN(conn);
  1058. tor_assert(conn->outbuf);
  1059. chan = TLS_CHAN_TO_BASE(or_conn->chan);
  1060. tor_assert(chan);
  1061. if (channel_num_circuits(chan) != 0) {
  1062. have_any_circuits = 1;
  1063. chan->timestamp_last_had_circuits = now;
  1064. } else {
  1065. have_any_circuits = 0;
  1066. }
  1067. if (channel_is_bad_for_new_circs(TLS_CHAN_TO_BASE(or_conn->chan)) &&
  1068. ! have_any_circuits) {
  1069. /* It's bad for new circuits, and has no unmarked circuits on it:
  1070. * mark it now. */
  1071. log_info(LD_OR,
  1072. "Expiring non-used OR connection to fd %d (%s:%d) [Too old].",
  1073. (int)conn->s, conn->address, conn->port);
  1074. if (conn->state == OR_CONN_STATE_CONNECTING)
  1075. connection_or_connect_failed(TO_OR_CONN(conn),
  1076. END_OR_CONN_REASON_TIMEOUT,
  1077. "Tor gave up on the connection");
  1078. connection_or_close_normally(TO_OR_CONN(conn), 1);
  1079. } else if (!connection_state_is_open(conn)) {
  1080. if (past_keepalive) {
  1081. /* We never managed to actually get this connection open and happy. */
  1082. log_info(LD_OR,"Expiring non-open OR connection to fd %d (%s:%d).",
  1083. (int)conn->s,conn->address, conn->port);
  1084. connection_or_close_normally(TO_OR_CONN(conn), 0);
  1085. }
  1086. } else if (we_are_hibernating() &&
  1087. ! have_any_circuits &&
  1088. !connection_get_outbuf_len(conn)) {
  1089. /* We're hibernating or shutting down, there's no circuits, and nothing to
  1090. * flush.*/
  1091. log_info(LD_OR,"Expiring non-used OR connection to fd %d (%s:%d) "
  1092. "[Hibernating or exiting].",
  1093. (int)conn->s,conn->address, conn->port);
  1094. connection_or_close_normally(TO_OR_CONN(conn), 1);
  1095. } else if (!have_any_circuits &&
  1096. now - or_conn->idle_timeout >=
  1097. chan->timestamp_last_had_circuits) {
  1098. log_info(LD_OR,"Expiring non-used OR connection %"PRIu64" to fd %d "
  1099. "(%s:%d) [no circuits for %d; timeout %d; %scanonical].",
  1100. (chan->global_identifier),
  1101. (int)conn->s, conn->address, conn->port,
  1102. (int)(now - chan->timestamp_last_had_circuits),
  1103. or_conn->idle_timeout,
  1104. or_conn->is_canonical ? "" : "non");
  1105. connection_or_close_normally(TO_OR_CONN(conn), 0);
  1106. } else if (
  1107. now >= or_conn->timestamp_lastempty + options->KeepalivePeriod*10 &&
  1108. now >=
  1109. conn->timestamp_last_write_allowed + options->KeepalivePeriod*10) {
  1110. log_fn(LOG_PROTOCOL_WARN,LD_PROTOCOL,
  1111. "Expiring stuck OR connection to fd %d (%s:%d). (%d bytes to "
  1112. "flush; %d seconds since last write)",
  1113. (int)conn->s, conn->address, conn->port,
  1114. (int)connection_get_outbuf_len(conn),
  1115. (int)(now-conn->timestamp_last_write_allowed));
  1116. connection_or_close_normally(TO_OR_CONN(conn), 0);
  1117. } else if (past_keepalive && !connection_get_outbuf_len(conn)) {
  1118. /* send a padding cell */
  1119. log_fn(LOG_DEBUG,LD_OR,"Sending keepalive to (%s:%d)",
  1120. conn->address, conn->port);
  1121. memset(&cell,0,sizeof(cell_t));
  1122. cell.command = CELL_PADDING;
  1123. connection_or_write_cell_to_buf(&cell, or_conn);
  1124. } else {
  1125. channelpadding_decide_to_pad_channel(chan);
  1126. }
  1127. }
  1128. /** Honor a NEWNYM request: make future requests unlinkable to past
  1129. * requests. */
  1130. static void
  1131. signewnym_impl(time_t now)
  1132. {
  1133. const or_options_t *options = get_options();
  1134. if (!proxy_mode(options)) {
  1135. log_info(LD_CONTROL, "Ignoring SIGNAL NEWNYM because client functionality "
  1136. "is disabled.");
  1137. return;
  1138. }
  1139. circuit_mark_all_dirty_circs_as_unusable();
  1140. addressmap_clear_transient();
  1141. hs_client_purge_state();
  1142. time_of_last_signewnym = now;
  1143. signewnym_is_pending = 0;
  1144. ++newnym_epoch;
  1145. control_event_signal(SIGNEWNYM);
  1146. }
  1147. /** Callback: run a deferred signewnym. */
  1148. static void
  1149. handle_deferred_signewnym_cb(mainloop_event_t *event, void *arg)
  1150. {
  1151. (void)event;
  1152. (void)arg;
  1153. log_info(LD_CONTROL, "Honoring delayed NEWNYM request");
  1154. do_signewnym(time(NULL));
  1155. }
  1156. /** Either perform a signewnym or schedule one, depending on rate limiting. */
  1157. void
  1158. do_signewnym(time_t now)
  1159. {
  1160. if (time_of_last_signewnym + MAX_SIGNEWNYM_RATE > now) {
  1161. const time_t delay_sec =
  1162. time_of_last_signewnym + MAX_SIGNEWNYM_RATE - now;
  1163. if (! signewnym_is_pending) {
  1164. signewnym_is_pending = 1;
  1165. if (!handle_deferred_signewnym_ev) {
  1166. handle_deferred_signewnym_ev =
  1167. mainloop_event_postloop_new(handle_deferred_signewnym_cb, NULL);
  1168. }
  1169. const struct timeval delay_tv = { delay_sec, 0 };
  1170. mainloop_event_schedule(handle_deferred_signewnym_ev, &delay_tv);
  1171. }
  1172. log_notice(LD_CONTROL,
  1173. "Rate limiting NEWNYM request: delaying by %d second(s)",
  1174. (int)(delay_sec));
  1175. } else {
  1176. signewnym_impl(now);
  1177. }
  1178. }
  1179. /** Return the number of times that signewnym has been called. */
  1180. unsigned
  1181. get_signewnym_epoch(void)
  1182. {
  1183. return newnym_epoch;
  1184. }
  1185. /** True iff we have initialized all the members of <b>periodic_events</b>.
  1186. * Used to prevent double-initialization. */
  1187. static int periodic_events_initialized = 0;
  1188. /* Declare all the timer callback functions... */
  1189. #undef CALLBACK
  1190. #define CALLBACK(name) \
  1191. static int name ## _callback(time_t, const or_options_t *)
  1192. CALLBACK(add_entropy);
  1193. CALLBACK(check_authority_cert);
  1194. CALLBACK(check_canonical_channels);
  1195. CALLBACK(check_descriptor);
  1196. CALLBACK(check_dns_honesty);
  1197. CALLBACK(check_ed_keys);
  1198. CALLBACK(check_expired_networkstatus);
  1199. CALLBACK(check_for_reachability_bw);
  1200. CALLBACK(check_onion_keys_expiry_time);
  1201. CALLBACK(clean_caches);
  1202. CALLBACK(clean_consdiffmgr);
  1203. CALLBACK(dirvote);
  1204. CALLBACK(downrate_stability);
  1205. CALLBACK(expire_old_ciruits_serverside);
  1206. CALLBACK(fetch_networkstatus);
  1207. CALLBACK(heartbeat);
  1208. CALLBACK(hs_service);
  1209. CALLBACK(launch_descriptor_fetches);
  1210. CALLBACK(launch_reachability_tests);
  1211. CALLBACK(prune_old_routers);
  1212. CALLBACK(reachability_warnings);
  1213. CALLBACK(record_bridge_stats);
  1214. CALLBACK(rend_cache_failure_clean);
  1215. CALLBACK(reset_padding_counts);
  1216. CALLBACK(retry_dns);
  1217. CALLBACK(retry_listeners);
  1218. CALLBACK(rotate_onion_key);
  1219. CALLBACK(rotate_x509_certificate);
  1220. CALLBACK(save_stability);
  1221. CALLBACK(save_state);
  1222. CALLBACK(write_bridge_ns);
  1223. CALLBACK(write_stats_file);
  1224. CALLBACK(control_per_second_events);
  1225. CALLBACK(second_elapsed);
  1226. #undef CALLBACK
  1227. /* Now we declare an array of periodic_event_item_t for each periodic event */
  1228. #define CALLBACK(name, r, f) \
  1229. PERIODIC_EVENT(name, PERIODIC_EVENT_ROLE_ ## r, f)
  1230. #define FL(name) (PERIODIC_EVENT_FLAG_ ## name)
  1231. STATIC periodic_event_item_t periodic_events[] = {
  1232. /* Everyone needs to run these. They need to have very long timeouts for
  1233. * that to be safe. */
  1234. CALLBACK(add_entropy, ALL, 0),
  1235. CALLBACK(heartbeat, ALL, 0),
  1236. CALLBACK(reset_padding_counts, ALL, 0),
  1237. /* This is a legacy catch-all callback that runs once per second if
  1238. * we are online and active. */
  1239. CALLBACK(second_elapsed, NET_PARTICIPANT,
  1240. FL(NEED_NET)|FL(RUN_ON_DISABLE)),
  1241. /* XXXX Do we have a reason to do this on a callback? Does it do any good at
  1242. * all? For now, if we're dormant, we can let our listeners decay. */
  1243. CALLBACK(retry_listeners, NET_PARTICIPANT, FL(NEED_NET)),
  1244. /* We need to do these if we're participating in the Tor network. */
  1245. CALLBACK(check_expired_networkstatus, NET_PARTICIPANT, 0),
  1246. CALLBACK(fetch_networkstatus, NET_PARTICIPANT, 0),
  1247. CALLBACK(launch_descriptor_fetches, NET_PARTICIPANT, FL(NEED_NET)),
  1248. CALLBACK(rotate_x509_certificate, NET_PARTICIPANT, 0),
  1249. CALLBACK(check_network_participation, NET_PARTICIPANT, 0),
  1250. /* We need to do these if we're participating in the Tor network, and
  1251. * immediately before we stop. */
  1252. CALLBACK(clean_caches, NET_PARTICIPANT, FL(RUN_ON_DISABLE)),
  1253. CALLBACK(save_state, NET_PARTICIPANT, FL(RUN_ON_DISABLE)),
  1254. CALLBACK(write_stats_file, NET_PARTICIPANT, FL(RUN_ON_DISABLE)),
  1255. CALLBACK(prune_old_routers, NET_PARTICIPANT, FL(RUN_ON_DISABLE)),
  1256. /* Routers (bridge and relay) only. */
  1257. CALLBACK(check_descriptor, ROUTER, FL(NEED_NET)),
  1258. CALLBACK(check_ed_keys, ROUTER, 0),
  1259. CALLBACK(check_for_reachability_bw, ROUTER, FL(NEED_NET)),
  1260. CALLBACK(check_onion_keys_expiry_time, ROUTER, 0),
  1261. CALLBACK(expire_old_ciruits_serverside, ROUTER, FL(NEED_NET)),
  1262. CALLBACK(reachability_warnings, ROUTER, FL(NEED_NET)),
  1263. CALLBACK(retry_dns, ROUTER, 0),
  1264. CALLBACK(rotate_onion_key, ROUTER, 0),
  1265. /* Authorities (bridge and directory) only. */
  1266. CALLBACK(downrate_stability, AUTHORITIES, 0),
  1267. CALLBACK(launch_reachability_tests, AUTHORITIES, FL(NEED_NET)),
  1268. CALLBACK(save_stability, AUTHORITIES, 0),
  1269. /* Directory authority only. */
  1270. CALLBACK(check_authority_cert, DIRAUTH, 0),
  1271. CALLBACK(dirvote, DIRAUTH, FL(NEED_NET)),
  1272. /* Relay only. */
  1273. CALLBACK(check_canonical_channels, RELAY, FL(NEED_NET)),
  1274. CALLBACK(check_dns_honesty, RELAY, FL(NEED_NET)),
  1275. /* Hidden Service service only. */
  1276. CALLBACK(hs_service, HS_SERVICE, FL(NEED_NET)), // XXXX break this down more
  1277. /* Bridge only. */
  1278. CALLBACK(record_bridge_stats, BRIDGE, 0),
  1279. /* Client only. */
  1280. /* XXXX this could be restricted to CLIENT+NET_PARTICIPANT */
  1281. CALLBACK(rend_cache_failure_clean, NET_PARTICIPANT, FL(RUN_ON_DISABLE)),
  1282. /* Bridge Authority only. */
  1283. CALLBACK(write_bridge_ns, BRIDGEAUTH, 0),
  1284. /* Directory server only. */
  1285. CALLBACK(clean_consdiffmgr, DIRSERVER, 0),
  1286. /* Controller with per-second events only. */
  1287. CALLBACK(control_per_second_events, CONTROLEV, 0),
  1288. END_OF_PERIODIC_EVENTS
  1289. };
  1290. #undef CALLBACK
  1291. #undef FL
  1292. /* These are pointers to members of periodic_events[] that are used to
  1293. * implement particular callbacks. We keep them separate here so that we
  1294. * can access them by name. We also keep them inside periodic_events[]
  1295. * so that we can implement "reset all timers" in a reasonable way. */
  1296. static periodic_event_item_t *check_descriptor_event=NULL;
  1297. static periodic_event_item_t *dirvote_event=NULL;
  1298. static periodic_event_item_t *fetch_networkstatus_event=NULL;
  1299. static periodic_event_item_t *launch_descriptor_fetches_event=NULL;
  1300. static periodic_event_item_t *check_dns_honesty_event=NULL;
  1301. static periodic_event_item_t *save_state_event=NULL;
  1302. static periodic_event_item_t *prune_old_routers_event=NULL;
  1303. /** Reset all the periodic events so we'll do all our actions again as if we
  1304. * just started up.
  1305. * Useful if our clock just moved back a long time from the future,
  1306. * so we don't wait until that future arrives again before acting.
  1307. */
  1308. void
  1309. reset_all_main_loop_timers(void)
  1310. {
  1311. int i;
  1312. for (i = 0; periodic_events[i].name; ++i) {
  1313. periodic_event_reschedule(&periodic_events[i]);
  1314. }
  1315. }
  1316. /** Return the member of periodic_events[] whose name is <b>name</b>.
  1317. * Return NULL if no such event is found.
  1318. */
  1319. static periodic_event_item_t *
  1320. find_periodic_event(const char *name)
  1321. {
  1322. int i;
  1323. for (i = 0; periodic_events[i].name; ++i) {
  1324. if (strcmp(name, periodic_events[i].name) == 0)
  1325. return &periodic_events[i];
  1326. }
  1327. return NULL;
  1328. }
  1329. /** Return a bitmask of the roles this tor instance is configured for using
  1330. * the given options. */
  1331. STATIC int
  1332. get_my_roles(const or_options_t *options)
  1333. {
  1334. tor_assert(options);
  1335. int roles = PERIODIC_EVENT_ROLE_ALL;
  1336. int is_bridge = options->BridgeRelay;
  1337. int is_relay = server_mode(options);
  1338. int is_dirauth = authdir_mode_v3(options);
  1339. int is_bridgeauth = authdir_mode_bridge(options);
  1340. int is_hidden_service = !!hs_service_get_num_services() ||
  1341. !!rend_num_services();
  1342. int is_dirserver = dir_server_mode(options);
  1343. int sending_control_events = control_any_per_second_event_enabled();
  1344. /* We also consider tor to have the role of a client if the ControlPort is
  1345. * set because a lot of things can be done over the control port which
  1346. * requires tor to have basic functionnalities. */
  1347. int is_client = options_any_client_port_set(options) ||
  1348. options->ControlPort_set ||
  1349. options->OwningControllerFD != UINT64_MAX;
  1350. int is_net_participant = is_participating_on_network() ||
  1351. is_relay || is_hidden_service;
  1352. if (is_bridge) roles |= PERIODIC_EVENT_ROLE_BRIDGE;
  1353. if (is_client) roles |= PERIODIC_EVENT_ROLE_CLIENT;
  1354. if (is_relay) roles |= PERIODIC_EVENT_ROLE_RELAY;
  1355. if (is_dirauth) roles |= PERIODIC_EVENT_ROLE_DIRAUTH;
  1356. if (is_bridgeauth) roles |= PERIODIC_EVENT_ROLE_BRIDGEAUTH;
  1357. if (is_hidden_service) roles |= PERIODIC_EVENT_ROLE_HS_SERVICE;
  1358. if (is_dirserver) roles |= PERIODIC_EVENT_ROLE_DIRSERVER;
  1359. if (is_net_participant) roles |= PERIODIC_EVENT_ROLE_NET_PARTICIPANT;
  1360. if (sending_control_events) roles |= PERIODIC_EVENT_ROLE_CONTROLEV;
  1361. return roles;
  1362. }
  1363. /** Event to run initialize_periodic_events_cb */
  1364. static struct event *initialize_periodic_events_event = NULL;
  1365. /** Helper, run one second after setup:
  1366. * Initializes all members of periodic_events and starts them running.
  1367. *
  1368. * (We do this one second after setup for backward-compatibility reasons;
  1369. * it might not actually be necessary.) */
  1370. static void
  1371. initialize_periodic_events_cb(evutil_socket_t fd, short events, void *data)
  1372. {
  1373. (void) fd;
  1374. (void) events;
  1375. (void) data;
  1376. tor_event_free(initialize_periodic_events_event);
  1377. rescan_periodic_events(get_options());
  1378. }
  1379. /** Set up all the members of periodic_events[], and configure them all to be
  1380. * launched from a callback. */
  1381. STATIC void
  1382. initialize_periodic_events(void)
  1383. {
  1384. if (periodic_events_initialized)
  1385. return;
  1386. periodic_events_initialized = 1;
  1387. /* Set up all periodic events. We'll launch them by roles. */
  1388. int i;
  1389. for (i = 0; periodic_events[i].name; ++i) {
  1390. periodic_event_setup(&periodic_events[i]);
  1391. }
  1392. #define NAMED_CALLBACK(name) \
  1393. STMT_BEGIN name ## _event = find_periodic_event( #name ); STMT_END
  1394. NAMED_CALLBACK(check_descriptor);
  1395. NAMED_CALLBACK(prune_old_routers);
  1396. NAMED_CALLBACK(dirvote);
  1397. NAMED_CALLBACK(fetch_networkstatus);
  1398. NAMED_CALLBACK(launch_descriptor_fetches);
  1399. NAMED_CALLBACK(check_dns_honesty);
  1400. NAMED_CALLBACK(save_state);
  1401. struct timeval one_second = { 1, 0 };
  1402. initialize_periodic_events_event = tor_evtimer_new(
  1403. tor_libevent_get_base(),
  1404. initialize_periodic_events_cb, NULL);
  1405. event_add(initialize_periodic_events_event, &one_second);
  1406. }
  1407. STATIC void
  1408. teardown_periodic_events(void)
  1409. {
  1410. int i;
  1411. for (i = 0; periodic_events[i].name; ++i) {
  1412. periodic_event_destroy(&periodic_events[i]);
  1413. }
  1414. periodic_events_initialized = 0;
  1415. }
  1416. static mainloop_event_t *rescan_periodic_events_ev = NULL;
  1417. /** Callback: rescan the periodic event list. */
  1418. static void
  1419. rescan_periodic_events_cb(mainloop_event_t *event, void *arg)
  1420. {
  1421. (void)event;
  1422. (void)arg;
  1423. rescan_periodic_events(get_options());
  1424. }
  1425. /**
  1426. * Schedule an event that will rescan which periodic events should run.
  1427. **/
  1428. MOCK_IMPL(void,
  1429. schedule_rescan_periodic_events,(void))
  1430. {
  1431. if (!rescan_periodic_events_ev) {
  1432. rescan_periodic_events_ev =
  1433. mainloop_event_new(rescan_periodic_events_cb, NULL);
  1434. }
  1435. mainloop_event_activate(rescan_periodic_events_ev);
  1436. }
  1437. /** Do a pass at all our periodic events, disable those we don't need anymore
  1438. * and enable those we need now using the given options. */
  1439. void
  1440. rescan_periodic_events(const or_options_t *options)
  1441. {
  1442. tor_assert(options);
  1443. /* Avoid scanning the event list if we haven't initialized it yet. This is
  1444. * particularly useful for unit tests in order to avoid initializing main
  1445. * loop events everytime. */
  1446. if (!periodic_events_initialized) {
  1447. return;
  1448. }
  1449. int roles = get_my_roles(options);
  1450. for (int i = 0; periodic_events[i].name; ++i) {
  1451. periodic_event_item_t *item = &periodic_events[i];
  1452. int enable = !!(item->roles & roles);
  1453. /* Handle the event flags. */
  1454. if (net_is_disabled() &&
  1455. (item->flags & PERIODIC_EVENT_FLAG_NEED_NET)) {
  1456. enable = 0;
  1457. }
  1458. /* Enable the event if needed. It is safe to enable an event that was
  1459. * already enabled. Same goes for disabling it. */
  1460. if (enable) {
  1461. log_debug(LD_GENERAL, "Launching periodic event %s", item->name);
  1462. periodic_event_enable(item);
  1463. } else {
  1464. log_debug(LD_GENERAL, "Disabling periodic event %s", item->name);
  1465. if (item->flags & PERIODIC_EVENT_FLAG_RUN_ON_DISABLE) {
  1466. periodic_event_schedule_and_disable(item);
  1467. } else {
  1468. periodic_event_disable(item);
  1469. }
  1470. }
  1471. }
  1472. }
  1473. /* We just got new options globally set, see if we need to enabled or disable
  1474. * periodic events. */
  1475. void
  1476. periodic_events_on_new_options(const or_options_t *options)
  1477. {
  1478. /* Only if we've already initialized the events, rescan the list which will
  1479. * enable or disable events depending on our roles. This will be called at
  1480. * bootup and we don't want this function to initialize the events because
  1481. * they aren't set up at this stage. */
  1482. if (periodic_events_initialized) {
  1483. rescan_periodic_events(options);
  1484. }
  1485. }
  1486. /**
  1487. * Update our schedule so that we'll check whether we need to update our
  1488. * descriptor immediately, rather than after up to CHECK_DESCRIPTOR_INTERVAL
  1489. * seconds.
  1490. */
  1491. void
  1492. reschedule_descriptor_update_check(void)
  1493. {
  1494. if (check_descriptor_event) {
  1495. periodic_event_reschedule(check_descriptor_event);
  1496. }
  1497. }
  1498. /**
  1499. * Update our schedule so that we'll check whether we need to fetch directory
  1500. * info immediately.
  1501. */
  1502. void
  1503. reschedule_directory_downloads(void)
  1504. {
  1505. tor_assert(fetch_networkstatus_event);
  1506. tor_assert(launch_descriptor_fetches_event);
  1507. periodic_event_reschedule(fetch_networkstatus_event);
  1508. periodic_event_reschedule(launch_descriptor_fetches_event);
  1509. }
  1510. /** Mainloop callback: clean up circuits, channels, and connections
  1511. * that are pending close. */
  1512. static void
  1513. postloop_cleanup_cb(mainloop_event_t *ev, void *arg)
  1514. {
  1515. (void)ev;
  1516. (void)arg;
  1517. circuit_close_all_marked();
  1518. close_closeable_connections();
  1519. channel_run_cleanup();
  1520. channel_listener_run_cleanup();
  1521. }
  1522. /** Event to run postloop_cleanup_cb */
  1523. static mainloop_event_t *postloop_cleanup_ev=NULL;
  1524. /** Schedule a post-loop event to clean up marked channels, connections, and
  1525. * circuits. */
  1526. void
  1527. mainloop_schedule_postloop_cleanup(void)
  1528. {
  1529. if (PREDICT_UNLIKELY(postloop_cleanup_ev == NULL)) {
  1530. // (It's possible that we can get here if we decide to close a connection
  1531. // in the earliest stages of our configuration, before we create events.)
  1532. return;
  1533. }
  1534. mainloop_event_activate(postloop_cleanup_ev);
  1535. }
  1536. /** Event to run 'scheduled_shutdown_cb' */
  1537. static mainloop_event_t *scheduled_shutdown_ev=NULL;
  1538. /** Callback: run a scheduled shutdown */
  1539. static void
  1540. scheduled_shutdown_cb(mainloop_event_t *ev, void *arg)
  1541. {
  1542. (void)ev;
  1543. (void)arg;
  1544. log_notice(LD_GENERAL, "Clean shutdown finished. Exiting.");
  1545. tor_shutdown_event_loop_and_exit(0);
  1546. }
  1547. /** Schedule the mainloop to exit after <b>delay_sec</b> seconds. */
  1548. void
  1549. mainloop_schedule_shutdown(int delay_sec)
  1550. {
  1551. const struct timeval delay_tv = { delay_sec, 0 };
  1552. if (! scheduled_shutdown_ev) {
  1553. scheduled_shutdown_ev = mainloop_event_new(scheduled_shutdown_cb, NULL);
  1554. }
  1555. mainloop_event_schedule(scheduled_shutdown_ev, &delay_tv);
  1556. }
  1557. #define LONGEST_TIMER_PERIOD (30 * 86400)
  1558. /** Helper: Return the number of seconds between <b>now</b> and <b>next</b>,
  1559. * clipped to the range [1 second, LONGEST_TIMER_PERIOD]. */
  1560. static inline int
  1561. safe_timer_diff(time_t now, time_t next)
  1562. {
  1563. if (next > now) {
  1564. /* There were no computers at signed TIME_MIN (1902 on 32-bit systems),
  1565. * and nothing that could run Tor. It's a bug if 'next' is around then.
  1566. * On 64-bit systems with signed TIME_MIN, TIME_MIN is before the Big
  1567. * Bang. We cannot extrapolate past a singularity, but there was probably
  1568. * nothing that could run Tor then, either.
  1569. **/
  1570. tor_assert(next > TIME_MIN + LONGEST_TIMER_PERIOD);
  1571. if (next - LONGEST_TIMER_PERIOD > now)
  1572. return LONGEST_TIMER_PERIOD;
  1573. return (int)(next - now);
  1574. } else {
  1575. return 1;
  1576. }
  1577. }
  1578. /** Perform regular maintenance tasks. This function gets run once per
  1579. * second.
  1580. */
  1581. static int
  1582. second_elapsed_callback(time_t now, const or_options_t *options)
  1583. {
  1584. /* 0. See if our bandwidth limits are exhausted and we should hibernate
  1585. *
  1586. * Note: we have redundant mechanisms to handle the case where it's
  1587. * time to wake up from hibernation; or where we have a scheduled
  1588. * shutdown and it's time to run it, but this will also handle those.
  1589. */
  1590. consider_hibernation(now);
  1591. /* Maybe enough time elapsed for us to reconsider a circuit. */
  1592. circuit_upgrade_circuits_from_guard_wait();
  1593. if (options->UseBridges && !net_is_disabled()) {
  1594. /* Note: this check uses net_is_disabled(), not should_delay_dir_fetches()
  1595. * -- the latter is only for fetching consensus-derived directory info. */
  1596. // TODO: client
  1597. // Also, schedule this rather than probing 1x / sec
  1598. fetch_bridge_descriptors(options, now);
  1599. }
  1600. if (accounting_is_enabled(options)) {
  1601. // TODO: refactor or rewrite?
  1602. accounting_run_housekeeping(now);
  1603. }
  1604. /* 3a. Every second, we examine pending circuits and prune the
  1605. * ones which have been pending for more than a few seconds.
  1606. * We do this before step 4, so it can try building more if
  1607. * it's not comfortable with the number of available circuits.
  1608. */
  1609. /* (If our circuit build timeout can ever become lower than a second (which
  1610. * it can't, currently), we should do this more often.) */
  1611. // TODO: All expire stuff can become NET_PARTICIPANT, RUN_ON_DISABLE
  1612. circuit_expire_building();
  1613. circuit_expire_waiting_for_better_guard();
  1614. /* 3b. Also look at pending streams and prune the ones that 'began'
  1615. * a long time ago but haven't gotten a 'connected' yet.
  1616. * Do this before step 4, so we can put them back into pending
  1617. * state to be picked up by the new circuit.
  1618. */
  1619. connection_ap_expire_beginning();
  1620. /* 3c. And expire connections that we've held open for too long.
  1621. */
  1622. connection_expire_held_open();
  1623. /* 4. Every second, we try a new circuit if there are no valid
  1624. * circuits. Every NewCircuitPeriod seconds, we expire circuits
  1625. * that became dirty more than MaxCircuitDirtiness seconds ago,
  1626. * and we make a new circ if there are no clean circuits.
  1627. */
  1628. const int have_dir_info = router_have_minimum_dir_info();
  1629. if (have_dir_info && !net_is_disabled()) {
  1630. circuit_build_needed_circs(now);
  1631. } else {
  1632. circuit_expire_old_circs_as_needed(now);
  1633. }
  1634. /* 5. We do housekeeping for each connection... */
  1635. channel_update_bad_for_new_circs(NULL, 0);
  1636. int i;
  1637. for (i=0;i<smartlist_len(connection_array);i++) {
  1638. run_connection_housekeeping(i, now);
  1639. }
  1640. /* Run again in a second. */
  1641. return 1;
  1642. }
  1643. /* Periodic callback: rotate the onion keys after the period defined by the
  1644. * "onion-key-rotation-days" consensus parameter, shut down and restart all
  1645. * cpuworkers, and update our descriptor if necessary.
  1646. */
  1647. static int
  1648. rotate_onion_key_callback(time_t now, const or_options_t *options)
  1649. {
  1650. if (server_mode(options)) {
  1651. int onion_key_lifetime = get_onion_key_lifetime();
  1652. time_t rotation_time = get_onion_key_set_at()+onion_key_lifetime;
  1653. if (rotation_time > now) {
  1654. return ONION_KEY_CONSENSUS_CHECK_INTERVAL;
  1655. }
  1656. log_info(LD_GENERAL,"Rotating onion key.");
  1657. rotate_onion_key();
  1658. cpuworkers_rotate_keyinfo();
  1659. if (router_rebuild_descriptor(1)<0) {
  1660. log_info(LD_CONFIG, "Couldn't rebuild router descriptor");
  1661. }
  1662. if (advertised_server_mode() && !net_is_disabled())
  1663. router_upload_dir_desc_to_dirservers(0);
  1664. return ONION_KEY_CONSENSUS_CHECK_INTERVAL;
  1665. }
  1666. return PERIODIC_EVENT_NO_UPDATE;
  1667. }
  1668. /* Period callback: Check if our old onion keys are still valid after the
  1669. * period of time defined by the consensus parameter
  1670. * "onion-key-grace-period-days", otherwise expire them by setting them to
  1671. * NULL.
  1672. */
  1673. static int
  1674. check_onion_keys_expiry_time_callback(time_t now, const or_options_t *options)
  1675. {
  1676. if (server_mode(options)) {
  1677. int onion_key_grace_period = get_onion_key_grace_period();
  1678. time_t expiry_time = get_onion_key_set_at()+onion_key_grace_period;
  1679. if (expiry_time > now) {
  1680. return ONION_KEY_CONSENSUS_CHECK_INTERVAL;
  1681. }
  1682. log_info(LD_GENERAL, "Expiring old onion keys.");
  1683. expire_old_onion_keys();
  1684. cpuworkers_rotate_keyinfo();
  1685. return ONION_KEY_CONSENSUS_CHECK_INTERVAL;
  1686. }
  1687. return PERIODIC_EVENT_NO_UPDATE;
  1688. }
  1689. /* Periodic callback: Every 30 seconds, check whether it's time to make new
  1690. * Ed25519 subkeys.
  1691. */
  1692. static int
  1693. check_ed_keys_callback(time_t now, const or_options_t *options)
  1694. {
  1695. if (server_mode(options)) {
  1696. if (should_make_new_ed_keys(options, now)) {
  1697. int new_signing_key = load_ed_keys(options, now);
  1698. if (new_signing_key < 0 ||
  1699. generate_ed_link_cert(options, now, new_signing_key > 0)) {
  1700. log_err(LD_OR, "Unable to update Ed25519 keys! Exiting.");
  1701. tor_shutdown_event_loop_and_exit(1);
  1702. }
  1703. }
  1704. return 30;
  1705. }
  1706. return PERIODIC_EVENT_NO_UPDATE;
  1707. }
  1708. /**
  1709. * Periodic callback: Every {LAZY,GREEDY}_DESCRIPTOR_RETRY_INTERVAL,
  1710. * see about fetching descriptors, microdescriptors, and extrainfo
  1711. * documents.
  1712. */
  1713. static int
  1714. launch_descriptor_fetches_callback(time_t now, const or_options_t *options)
  1715. {
  1716. if (should_delay_dir_fetches(options, NULL))
  1717. return PERIODIC_EVENT_NO_UPDATE;
  1718. update_all_descriptor_downloads(now);
  1719. update_extrainfo_downloads(now);
  1720. if (router_have_minimum_dir_info())
  1721. return LAZY_DESCRIPTOR_RETRY_INTERVAL;
  1722. else
  1723. return GREEDY_DESCRIPTOR_RETRY_INTERVAL;
  1724. }
  1725. /**
  1726. * Periodic event: Rotate our X.509 certificates and TLS keys once every
  1727. * MAX_SSL_KEY_LIFETIME_INTERNAL.
  1728. */
  1729. static int
  1730. rotate_x509_certificate_callback(time_t now, const or_options_t *options)
  1731. {
  1732. static int first = 1;
  1733. (void)now;
  1734. (void)options;
  1735. if (first) {
  1736. first = 0;
  1737. return MAX_SSL_KEY_LIFETIME_INTERNAL;
  1738. }
  1739. /* 1b. Every MAX_SSL_KEY_LIFETIME_INTERNAL seconds, we change our
  1740. * TLS context. */
  1741. log_info(LD_GENERAL,"Rotating tls context.");
  1742. if (router_initialize_tls_context() < 0) {
  1743. log_err(LD_BUG, "Error reinitializing TLS context");
  1744. tor_assert_unreached();
  1745. }
  1746. if (generate_ed_link_cert(options, now, 1)) {
  1747. log_err(LD_OR, "Unable to update Ed25519->TLS link certificate for "
  1748. "new TLS context.");
  1749. tor_assert_unreached();
  1750. }
  1751. /* We also make sure to rotate the TLS connections themselves if they've
  1752. * been up for too long -- but that's done via is_bad_for_new_circs in
  1753. * run_connection_housekeeping() above. */
  1754. return MAX_SSL_KEY_LIFETIME_INTERNAL;
  1755. }
  1756. /**
  1757. * Periodic callback: once an hour, grab some more entropy from the
  1758. * kernel and feed it to our CSPRNG.
  1759. **/
  1760. static int
  1761. add_entropy_callback(time_t now, const or_options_t *options)
  1762. {
  1763. (void)now;
  1764. (void)options;
  1765. /* We already seeded once, so don't die on failure. */
  1766. if (crypto_seed_rng() < 0) {
  1767. log_warn(LD_GENERAL, "Tried to re-seed RNG, but failed. We already "
  1768. "seeded once, though, so we won't exit here.");
  1769. }
  1770. /** How often do we add more entropy to OpenSSL's RNG pool? */
  1771. #define ENTROPY_INTERVAL (60*60)
  1772. return ENTROPY_INTERVAL;
  1773. }
  1774. /** Periodic callback: if there has been no network usage in a while,
  1775. * enter a dormant state. */
  1776. STATIC int
  1777. check_network_participation_callback(time_t now, const or_options_t *options)
  1778. {
  1779. /* If we're a server, we can't become dormant. */
  1780. if (server_mode(options)) {
  1781. goto found_activity;
  1782. }
  1783. /* If we're running an onion service, we can't become dormant. */
  1784. /* XXXX this would be nice to change, so that we can be dormant with a
  1785. * service. */
  1786. if (hs_service_get_num_services() || rend_num_services()) {
  1787. goto found_activity;
  1788. }
  1789. /* If we have any currently open entry streams other than "linked"
  1790. * connections used for directory requests, those count as user activity.
  1791. */
  1792. if (options->DormantTimeoutDisabledByIdleStreams) {
  1793. if (connection_get_by_type_nonlinked(CONN_TYPE_AP) != NULL) {
  1794. goto found_activity;
  1795. }
  1796. }
  1797. /* XXXX Make this configurable? */
  1798. /** How often do we check whether we have had network activity? */
  1799. #define CHECK_PARTICIPATION_INTERVAL (5*60)
  1800. /* Become dormant if there has been no user activity in a long time.
  1801. * (The funny checks below are in order to prevent overflow.) */
  1802. time_t time_since_last_activity = 0;
  1803. if (get_last_user_activity_time() < now)
  1804. time_since_last_activity = now - get_last_user_activity_time();
  1805. if (time_since_last_activity >= options->DormantClientTimeout) {
  1806. log_notice(LD_GENERAL, "No user activity in a long time: becoming"
  1807. " dormant.");
  1808. set_network_participation(false);
  1809. rescan_periodic_events(options);
  1810. }
  1811. return CHECK_PARTICIPATION_INTERVAL;
  1812. found_activity:
  1813. note_user_activity(now);
  1814. return CHECK_PARTICIPATION_INTERVAL;
  1815. }
  1816. /**
  1817. * Periodic callback: if we're an authority, make sure we test
  1818. * the routers on the network for reachability.
  1819. */
  1820. static int
  1821. launch_reachability_tests_callback(time_t now, const or_options_t *options)
  1822. {
  1823. if (authdir_mode_tests_reachability(options) &&
  1824. !net_is_disabled()) {
  1825. /* try to determine reachability of the other Tor relays */
  1826. dirserv_test_reachability(now);
  1827. }
  1828. return REACHABILITY_TEST_INTERVAL;
  1829. }
  1830. /**
  1831. * Periodic callback: if we're an authority, discount the stability
  1832. * information (and other rephist information) that's older.
  1833. */
  1834. static int
  1835. downrate_stability_callback(time_t now, const or_options_t *options)
  1836. {
  1837. (void)options;
  1838. /* 1d. Periodically, we discount older stability information so that new
  1839. * stability info counts more, and save the stability information to disk as
  1840. * appropriate. */
  1841. time_t next = rep_hist_downrate_old_runs(now);
  1842. return safe_timer_diff(now, next);
  1843. }
  1844. /**
  1845. * Periodic callback: if we're an authority, record our measured stability
  1846. * information from rephist in an mtbf file.
  1847. */
  1848. static int
  1849. save_stability_callback(time_t now, const or_options_t *options)
  1850. {
  1851. if (authdir_mode_tests_reachability(options)) {
  1852. if (rep_hist_record_mtbf_data(now, 1)<0) {
  1853. log_warn(LD_GENERAL, "Couldn't store mtbf data.");
  1854. }
  1855. }
  1856. #define SAVE_STABILITY_INTERVAL (30*60)
  1857. return SAVE_STABILITY_INTERVAL;
  1858. }
  1859. /**
  1860. * Periodic callback: if we're an authority, check on our authority
  1861. * certificate (the one that authenticates our authority signing key).
  1862. */
  1863. static int
  1864. check_authority_cert_callback(time_t now, const or_options_t *options)
  1865. {
  1866. (void)now;
  1867. (void)options;
  1868. /* 1e. Periodically, if we're a v3 authority, we check whether our cert is
  1869. * close to expiring and warn the admin if it is. */
  1870. v3_authority_check_key_expiry();
  1871. #define CHECK_V3_CERTIFICATE_INTERVAL (5*60)
  1872. return CHECK_V3_CERTIFICATE_INTERVAL;
  1873. }
  1874. /**
  1875. * Scheduled callback: Run directory-authority voting functionality.
  1876. *
  1877. * The schedule is a bit complicated here, so dirvote_act() manages the
  1878. * schedule itself.
  1879. **/
  1880. static int
  1881. dirvote_callback(time_t now, const or_options_t *options)
  1882. {
  1883. if (!authdir_mode_v3(options)) {
  1884. tor_assert_nonfatal_unreached();
  1885. return 3600;
  1886. }
  1887. time_t next = dirvote_act(options, now);
  1888. if (BUG(next == TIME_MAX)) {
  1889. /* This shouldn't be returned unless we called dirvote_act() without
  1890. * being an authority. If it happens, maybe our configuration will
  1891. * fix itself in an hour or so? */
  1892. return 3600;
  1893. }
  1894. return safe_timer_diff(now, next);
  1895. }
  1896. /** Reschedule the directory-authority voting event. Run this whenever the
  1897. * schedule has changed. */
  1898. void
  1899. reschedule_dirvote(const or_options_t *options)
  1900. {
  1901. if (periodic_events_initialized && authdir_mode_v3(options)) {
  1902. periodic_event_reschedule(dirvote_event);
  1903. }
  1904. }
  1905. /**
  1906. * Periodic callback: If our consensus is too old, recalculate whether
  1907. * we can actually use it.
  1908. */
  1909. static int
  1910. check_expired_networkstatus_callback(time_t now, const or_options_t *options)
  1911. {
  1912. (void)options;
  1913. /* Check whether our networkstatus has expired. */
  1914. networkstatus_t *ns = networkstatus_get_latest_consensus();
  1915. /*XXXX RD: This value needs to be the same as REASONABLY_LIVE_TIME in
  1916. * networkstatus_get_reasonably_live_consensus(), but that value is way
  1917. * way too high. Arma: is the bridge issue there resolved yet? -NM */
  1918. #define NS_EXPIRY_SLOP (24*60*60)
  1919. if (ns && ns->valid_until < (now - NS_EXPIRY_SLOP) &&
  1920. router_have_minimum_dir_info()) {
  1921. router_dir_info_changed();
  1922. }
  1923. #define CHECK_EXPIRED_NS_INTERVAL (2*60)
  1924. return CHECK_EXPIRED_NS_INTERVAL;
  1925. }
  1926. /**
  1927. * Scheduled callback: Save the state file to disk if appropriate.
  1928. */
  1929. static int
  1930. save_state_callback(time_t now, const or_options_t *options)
  1931. {
  1932. (void) options;
  1933. (void) or_state_save(now); // only saves if appropriate
  1934. const time_t next_write = get_or_state()->next_write;
  1935. if (next_write == TIME_MAX) {
  1936. return 86400;
  1937. }
  1938. return safe_timer_diff(now, next_write);
  1939. }
  1940. /** Reschedule the event for saving the state file.
  1941. *
  1942. * Run this when the state becomes dirty. */
  1943. void
  1944. reschedule_or_state_save(void)
  1945. {
  1946. if (save_state_event == NULL) {
  1947. /* This can happen early on during startup. */
  1948. return;
  1949. }
  1950. periodic_event_reschedule(save_state_event);
  1951. }
  1952. /**
  1953. * Periodic callback: Write statistics to disk if appropriate.
  1954. */
  1955. static int
  1956. write_stats_file_callback(time_t now, const or_options_t *options)
  1957. {
  1958. /* 1g. Check whether we should write statistics to disk.
  1959. */
  1960. #define CHECK_WRITE_STATS_INTERVAL (60*60)
  1961. time_t next_time_to_write_stats_files = now + CHECK_WRITE_STATS_INTERVAL;
  1962. if (options->CellStatistics) {
  1963. time_t next_write =
  1964. rep_hist_buffer_stats_write(now);
  1965. if (next_write && next_write < next_time_to_write_stats_files)
  1966. next_time_to_write_stats_files = next_write;
  1967. }
  1968. if (options->DirReqStatistics) {
  1969. time_t next_write = geoip_dirreq_stats_write(now);
  1970. if (next_write && next_write < next_time_to_write_stats_files)
  1971. next_time_to_write_stats_files = next_write;
  1972. }
  1973. if (options->EntryStatistics) {
  1974. time_t next_write = geoip_entry_stats_write(now);
  1975. if (next_write && next_write < next_time_to_write_stats_files)
  1976. next_time_to_write_stats_files = next_write;
  1977. }
  1978. if (options->HiddenServiceStatistics) {
  1979. time_t next_write = rep_hist_hs_stats_write(now);
  1980. if (next_write && next_write < next_time_to_write_stats_files)
  1981. next_time_to_write_stats_files = next_write;
  1982. }
  1983. if (options->ExitPortStatistics) {
  1984. time_t next_write = rep_hist_exit_stats_write(now);
  1985. if (next_write && next_write < next_time_to_write_stats_files)
  1986. next_time_to_write_stats_files = next_write;
  1987. }
  1988. if (options->ConnDirectionStatistics) {
  1989. time_t next_write = rep_hist_conn_stats_write(now);
  1990. if (next_write && next_write < next_time_to_write_stats_files)
  1991. next_time_to_write_stats_files = next_write;
  1992. }
  1993. if (options->BridgeAuthoritativeDir) {
  1994. time_t next_write = rep_hist_desc_stats_write(now);
  1995. if (next_write && next_write < next_time_to_write_stats_files)
  1996. next_time_to_write_stats_files = next_write;
  1997. }
  1998. return safe_timer_diff(now, next_time_to_write_stats_files);
  1999. }
  2000. #define CHANNEL_CHECK_INTERVAL (60*60)
  2001. static int
  2002. check_canonical_channels_callback(time_t now, const or_options_t *options)
  2003. {
  2004. (void)now;
  2005. if (public_server_mode(options))
  2006. channel_check_for_duplicates();
  2007. return CHANNEL_CHECK_INTERVAL;
  2008. }
  2009. static int
  2010. reset_padding_counts_callback(time_t now, const or_options_t *options)
  2011. {
  2012. if (options->PaddingStatistics) {
  2013. rep_hist_prep_published_padding_counts(now);
  2014. }
  2015. rep_hist_reset_padding_counts();
  2016. return REPHIST_CELL_PADDING_COUNTS_INTERVAL;
  2017. }
  2018. static int should_init_bridge_stats = 1;
  2019. /**
  2020. * Periodic callback: Write bridge statistics to disk if appropriate.
  2021. */
  2022. static int
  2023. record_bridge_stats_callback(time_t now, const or_options_t *options)
  2024. {
  2025. /* 1h. Check whether we should write bridge statistics to disk.
  2026. */
  2027. if (should_record_bridge_info(options)) {
  2028. if (should_init_bridge_stats) {
  2029. /* (Re-)initialize bridge statistics. */
  2030. geoip_bridge_stats_init(now);
  2031. should_init_bridge_stats = 0;
  2032. return WRITE_STATS_INTERVAL;
  2033. } else {
  2034. /* Possibly write bridge statistics to disk and ask when to write
  2035. * them next time. */
  2036. time_t next = geoip_bridge_stats_write(now);
  2037. return safe_timer_diff(now, next);
  2038. }
  2039. } else if (!should_init_bridge_stats) {
  2040. /* Bridge mode was turned off. Ensure that stats are re-initialized
  2041. * next time bridge mode is turned on. */
  2042. should_init_bridge_stats = 1;
  2043. }
  2044. return PERIODIC_EVENT_NO_UPDATE;
  2045. }
  2046. /**
  2047. * Periodic callback: Clean in-memory caches every once in a while
  2048. */
  2049. static int
  2050. clean_caches_callback(time_t now, const or_options_t *options)
  2051. {
  2052. /* Remove old information from rephist and the rend cache. */
  2053. rep_history_clean(now - options->RephistTrackTime);
  2054. rend_cache_clean(now, REND_CACHE_TYPE_SERVICE);
  2055. hs_cache_clean_as_client(now);
  2056. hs_cache_clean_as_dir(now);
  2057. microdesc_cache_rebuild(NULL, 0);
  2058. #define CLEAN_CACHES_INTERVAL (30*60)
  2059. return CLEAN_CACHES_INTERVAL;
  2060. }
  2061. /**
  2062. * Periodic callback: Clean the cache of failed hidden service lookups
  2063. * frequently.
  2064. */
  2065. static int
  2066. rend_cache_failure_clean_callback(time_t now, const or_options_t *options)
  2067. {
  2068. (void)options;
  2069. /* We don't keep entries that are more than five minutes old so we try to
  2070. * clean it as soon as we can since we want to make sure the client waits
  2071. * as little as possible for reachability reasons. */
  2072. rend_cache_failure_clean(now);
  2073. hs_cache_client_intro_state_clean(now);
  2074. return 30;
  2075. }
  2076. /**
  2077. * Periodic callback: If we're a server and initializing dns failed, retry.
  2078. */
  2079. static int
  2080. retry_dns_callback(time_t now, const or_options_t *options)
  2081. {
  2082. (void)now;
  2083. #define RETRY_DNS_INTERVAL (10*60)
  2084. if (server_mode(options) && has_dns_init_failed())
  2085. dns_init();
  2086. return RETRY_DNS_INTERVAL;
  2087. }
  2088. /**
  2089. * Periodic callback: prune routerlist of old information about Tor network.
  2090. */
  2091. static int
  2092. prune_old_routers_callback(time_t now, const or_options_t *options)
  2093. {
  2094. #define ROUTERLIST_PRUNING_INTERVAL (60*60) // 1 hour.
  2095. (void)now;
  2096. (void)options;
  2097. if (!net_is_disabled()) {
  2098. /* If any networkstatus documents are no longer recent, we need to
  2099. * update all the descriptors' running status. */
  2100. /* Remove dead routers. */
  2101. log_debug(LD_GENERAL, "Pruning routerlist...");
  2102. routerlist_remove_old_routers();
  2103. }
  2104. return ROUTERLIST_PRUNING_INTERVAL;
  2105. }
  2106. /** Periodic callback: consider rebuilding or and re-uploading our descriptor
  2107. * (if we've passed our internal checks). */
  2108. static int
  2109. check_descriptor_callback(time_t now, const or_options_t *options)
  2110. {
  2111. /** How often do we check whether part of our router info has changed in a
  2112. * way that would require an upload? That includes checking whether our IP
  2113. * address has changed. */
  2114. #define CHECK_DESCRIPTOR_INTERVAL (60)
  2115. (void)options;
  2116. /* 2b. Once per minute, regenerate and upload the descriptor if the old
  2117. * one is inaccurate. */
  2118. if (!net_is_disabled()) {
  2119. check_descriptor_bandwidth_changed(now);
  2120. check_descriptor_ipaddress_changed(now);
  2121. mark_my_descriptor_dirty_if_too_old(now);
  2122. consider_publishable_server(0);
  2123. }
  2124. return CHECK_DESCRIPTOR_INTERVAL;
  2125. }
  2126. /**
  2127. * Periodic callback: check whether we're reachable (as a relay), and
  2128. * whether our bandwidth has changed enough that we need to
  2129. * publish a new descriptor.
  2130. */
  2131. static int
  2132. check_for_reachability_bw_callback(time_t now, const or_options_t *options)
  2133. {
  2134. /* XXXX This whole thing was stuck in the middle of what is now
  2135. * XXXX check_descriptor_callback. I'm not sure it's right. */
  2136. static int dirport_reachability_count = 0;
  2137. /* also, check religiously for reachability, if it's within the first
  2138. * 20 minutes of our uptime. */
  2139. if (server_mode(options) &&
  2140. (have_completed_a_circuit() || !any_predicted_circuits(now)) &&
  2141. !net_is_disabled()) {
  2142. if (get_uptime() < TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT) {
  2143. router_do_reachability_checks(1, dirport_reachability_count==0);
  2144. if (++dirport_reachability_count > 5)
  2145. dirport_reachability_count = 0;
  2146. return 1;
  2147. } else {
  2148. /* If we haven't checked for 12 hours and our bandwidth estimate is
  2149. * low, do another bandwidth test. This is especially important for
  2150. * bridges, since they might go long periods without much use. */
  2151. const routerinfo_t *me = router_get_my_routerinfo();
  2152. static int first_time = 1;
  2153. if (!first_time && me &&
  2154. me->bandwidthcapacity < me->bandwidthrate &&
  2155. me->bandwidthcapacity < 51200) {
  2156. reset_bandwidth_test();
  2157. }
  2158. first_time = 0;
  2159. #define BANDWIDTH_RECHECK_INTERVAL (12*60*60)
  2160. return BANDWIDTH_RECHECK_INTERVAL;
  2161. }
  2162. }
  2163. return CHECK_DESCRIPTOR_INTERVAL;
  2164. }
  2165. /**
  2166. * Periodic event: once a minute, (or every second if TestingTorNetwork, or
  2167. * during client bootstrap), check whether we want to download any
  2168. * networkstatus documents. */
  2169. static int
  2170. fetch_networkstatus_callback(time_t now, const or_options_t *options)
  2171. {
  2172. /* How often do we check whether we should download network status
  2173. * documents? */
  2174. const int we_are_bootstrapping = networkstatus_consensus_is_bootstrapping(
  2175. now);
  2176. const int prefer_mirrors = !directory_fetches_from_authorities(
  2177. get_options());
  2178. int networkstatus_dl_check_interval = 60;
  2179. /* check more often when testing, or when bootstrapping from mirrors
  2180. * (connection limits prevent too many connections being made) */
  2181. if (options->TestingTorNetwork
  2182. || (we_are_bootstrapping && prefer_mirrors)) {
  2183. networkstatus_dl_check_interval = 1;
  2184. }
  2185. if (should_delay_dir_fetches(options, NULL))
  2186. return PERIODIC_EVENT_NO_UPDATE;
  2187. update_networkstatus_downloads(now);
  2188. return networkstatus_dl_check_interval;
  2189. }
  2190. /**
  2191. * Periodic callback: Every 60 seconds, we relaunch listeners if any died. */
  2192. static int
  2193. retry_listeners_callback(time_t now, const or_options_t *options)
  2194. {
  2195. (void)now;
  2196. (void)options;
  2197. if (!net_is_disabled()) {
  2198. retry_all_listeners(NULL, 0);
  2199. return 60;
  2200. }
  2201. return PERIODIC_EVENT_NO_UPDATE;
  2202. }
  2203. /**
  2204. * Periodic callback: as a server, see if we have any old unused circuits
  2205. * that should be expired */
  2206. static int
  2207. expire_old_ciruits_serverside_callback(time_t now, const or_options_t *options)
  2208. {
  2209. (void)options;
  2210. /* every 11 seconds, so not usually the same second as other such events */
  2211. circuit_expire_old_circuits_serverside(now);
  2212. return 11;
  2213. }
  2214. /**
  2215. * Callback: Send warnings if Tor doesn't find its ports reachable.
  2216. */
  2217. static int
  2218. reachability_warnings_callback(time_t now, const or_options_t *options)
  2219. {
  2220. (void) now;
  2221. if (get_uptime() < TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT) {
  2222. return (int)(TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT - get_uptime());
  2223. }
  2224. if (server_mode(options) &&
  2225. !net_is_disabled() &&
  2226. have_completed_a_circuit()) {
  2227. /* every 20 minutes, check and complain if necessary */
  2228. const routerinfo_t *me = router_get_my_routerinfo();
  2229. if (me && !check_whether_orport_reachable(options)) {
  2230. char *address = tor_dup_ip(me->addr);
  2231. log_warn(LD_CONFIG,"Your server (%s:%d) has not managed to confirm that "
  2232. "its ORPort is reachable. Relays do not publish descriptors "
  2233. "until their ORPort and DirPort are reachable. Please check "
  2234. "your firewalls, ports, address, /etc/hosts file, etc.",
  2235. address, me->or_port);
  2236. control_event_server_status(LOG_WARN,
  2237. "REACHABILITY_FAILED ORADDRESS=%s:%d",
  2238. address, me->or_port);
  2239. tor_free(address);
  2240. }
  2241. if (me && !check_whether_dirport_reachable(options)) {
  2242. char *address = tor_dup_ip(me->addr);
  2243. log_warn(LD_CONFIG,
  2244. "Your server (%s:%d) has not managed to confirm that its "
  2245. "DirPort is reachable. Relays do not publish descriptors "
  2246. "until their ORPort and DirPort are reachable. Please check "
  2247. "your firewalls, ports, address, /etc/hosts file, etc.",
  2248. address, me->dir_port);
  2249. control_event_server_status(LOG_WARN,
  2250. "REACHABILITY_FAILED DIRADDRESS=%s:%d",
  2251. address, me->dir_port);
  2252. tor_free(address);
  2253. }
  2254. }
  2255. return TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT;
  2256. }
  2257. static int dns_honesty_first_time = 1;
  2258. /**
  2259. * Periodic event: if we're an exit, see if our DNS server is telling us
  2260. * obvious lies.
  2261. */
  2262. static int
  2263. check_dns_honesty_callback(time_t now, const or_options_t *options)
  2264. {
  2265. (void)now;
  2266. /* 9. and if we're an exit node, check whether our DNS is telling stories
  2267. * to us. */
  2268. if (net_is_disabled() ||
  2269. ! public_server_mode(options) ||
  2270. router_my_exit_policy_is_reject_star())
  2271. return PERIODIC_EVENT_NO_UPDATE;
  2272. if (dns_honesty_first_time) {
  2273. /* Don't launch right when we start */
  2274. dns_honesty_first_time = 0;
  2275. return crypto_rand_int_range(60, 180);
  2276. }
  2277. dns_launch_correctness_checks();
  2278. return 12*3600 + crypto_rand_int(12*3600);
  2279. }
  2280. /**
  2281. * Periodic callback: if we're the bridge authority, write a networkstatus
  2282. * file to disk.
  2283. */
  2284. static int
  2285. write_bridge_ns_callback(time_t now, const or_options_t *options)
  2286. {
  2287. /* 10. write bridge networkstatus file to disk */
  2288. if (options->BridgeAuthoritativeDir) {
  2289. networkstatus_dump_bridge_status_to_file(now);
  2290. #define BRIDGE_STATUSFILE_INTERVAL (30*60)
  2291. return BRIDGE_STATUSFILE_INTERVAL;
  2292. }
  2293. return PERIODIC_EVENT_NO_UPDATE;
  2294. }
  2295. static int heartbeat_callback_first_time = 1;
  2296. /**
  2297. * Periodic callback: write the heartbeat message in the logs.
  2298. *
  2299. * If writing the heartbeat message to the logs fails for some reason, retry
  2300. * again after <b>MIN_HEARTBEAT_PERIOD</b> seconds.
  2301. */
  2302. static int
  2303. heartbeat_callback(time_t now, const or_options_t *options)
  2304. {
  2305. /* Check if heartbeat is disabled */
  2306. if (!options->HeartbeatPeriod) {
  2307. return PERIODIC_EVENT_NO_UPDATE;
  2308. }
  2309. /* Skip the first one. */
  2310. if (heartbeat_callback_first_time) {
  2311. heartbeat_callback_first_time = 0;
  2312. return options->HeartbeatPeriod;
  2313. }
  2314. /* Write the heartbeat message */
  2315. if (log_heartbeat(now) == 0) {
  2316. return options->HeartbeatPeriod;
  2317. } else {
  2318. /* If we couldn't write the heartbeat log message, try again in the minimum
  2319. * interval of time. */
  2320. return MIN_HEARTBEAT_PERIOD;
  2321. }
  2322. }
  2323. #define CDM_CLEAN_CALLBACK_INTERVAL 600
  2324. static int
  2325. clean_consdiffmgr_callback(time_t now, const or_options_t *options)
  2326. {
  2327. (void)now;
  2328. if (dir_server_mode(options)) {
  2329. consdiffmgr_cleanup();
  2330. }
  2331. return CDM_CLEAN_CALLBACK_INTERVAL;
  2332. }
  2333. /*
  2334. * Periodic callback: Run scheduled events for HS service. This is called
  2335. * every second.
  2336. */
  2337. static int
  2338. hs_service_callback(time_t now, const or_options_t *options)
  2339. {
  2340. (void) options;
  2341. /* We need to at least be able to build circuits and that we actually have
  2342. * a working network. */
  2343. if (!have_completed_a_circuit() || net_is_disabled() ||
  2344. networkstatus_get_live_consensus(now) == NULL) {
  2345. goto end;
  2346. }
  2347. hs_service_run_scheduled_events(now);
  2348. end:
  2349. /* Every 1 second. */
  2350. return 1;
  2351. }
  2352. /*
  2353. * Periodic callback: Send once-per-second events to the controller(s).
  2354. * This is called every second.
  2355. */
  2356. static int
  2357. control_per_second_events_callback(time_t now, const or_options_t *options)
  2358. {
  2359. (void) options;
  2360. (void) now;
  2361. control_per_second_events();
  2362. return 1;
  2363. }
  2364. /** Last time that update_current_time was called. */
  2365. static time_t current_second = 0;
  2366. /** Last time that update_current_time updated current_second. */
  2367. static monotime_coarse_t current_second_last_changed;
  2368. /**
  2369. * Set the current time to "now", which should be the value returned by
  2370. * time(). Check for clock jumps and track the total number of seconds we
  2371. * have been running.
  2372. */
  2373. void
  2374. update_current_time(time_t now)
  2375. {
  2376. if (PREDICT_LIKELY(now == current_second)) {
  2377. /* We call this function a lot. Most frequently, the current second
  2378. * will not have changed, so we just return. */
  2379. return;
  2380. }
  2381. const time_t seconds_elapsed = current_second ? (now - current_second) : 0;
  2382. /* Check the wall clock against the monotonic clock, so we can
  2383. * better tell idleness from clock jumps and/or other shenanigans. */
  2384. monotime_coarse_t last_updated;
  2385. memcpy(&last_updated, &current_second_last_changed, sizeof(last_updated));
  2386. monotime_coarse_get(&current_second_last_changed);
  2387. /** How much clock jumping means that we should adjust our idea of when
  2388. * to go dormant? */
  2389. #define NUM_JUMPED_SECONDS_BEFORE_NETSTATUS_UPDATE 20
  2390. /* Don't go dormant early or late just because we jumped in time. */
  2391. if (ABS(seconds_elapsed) >= NUM_JUMPED_SECONDS_BEFORE_NETSTATUS_UPDATE) {
  2392. if (is_participating_on_network()) {
  2393. netstatus_note_clock_jumped(seconds_elapsed);
  2394. }
  2395. }
  2396. /** How much clock jumping do we tolerate? */
  2397. #define NUM_JUMPED_SECONDS_BEFORE_WARN 100
  2398. /** How much idleness do we tolerate? */
  2399. #define NUM_IDLE_SECONDS_BEFORE_WARN 3600
  2400. if (seconds_elapsed < -NUM_JUMPED_SECONDS_BEFORE_WARN) {
  2401. // moving back in time is always a bad sign.
  2402. circuit_note_clock_jumped(seconds_elapsed, false);
  2403. } else if (seconds_elapsed >= NUM_JUMPED_SECONDS_BEFORE_WARN) {
  2404. /* Compare the monotonic clock to the result of time(). */
  2405. const int32_t monotime_msec_passed =
  2406. monotime_coarse_diff_msec32(&last_updated,
  2407. &current_second_last_changed);
  2408. const int monotime_sec_passed = monotime_msec_passed / 1000;
  2409. const int discrepancy = monotime_sec_passed - (int)seconds_elapsed;
  2410. /* If the monotonic clock deviates from time(NULL), we have a couple of
  2411. * possibilities. On some systems, this means we have been suspended or
  2412. * sleeping. Everywhere, it can mean that the wall-clock time has
  2413. * been changed -- for example, with settimeofday().
  2414. *
  2415. * On the other hand, if the monotonic time matches with the wall-clock
  2416. * time, we've probably just been idle for a while, with no events firing.
  2417. * we tolerate much more of that.
  2418. */
  2419. const bool clock_jumped = abs(discrepancy) > 2;
  2420. if (clock_jumped || seconds_elapsed >= NUM_IDLE_SECONDS_BEFORE_WARN) {
  2421. circuit_note_clock_jumped(seconds_elapsed, ! clock_jumped);
  2422. }
  2423. } else if (seconds_elapsed > 0) {
  2424. stats_n_seconds_working += seconds_elapsed;
  2425. }
  2426. update_approx_time(now);
  2427. current_second = now;
  2428. }
  2429. #ifdef HAVE_SYSTEMD_209
  2430. static periodic_timer_t *systemd_watchdog_timer = NULL;
  2431. /** Libevent callback: invoked to reset systemd watchdog. */
  2432. static void
  2433. systemd_watchdog_callback(periodic_timer_t *timer, void *arg)
  2434. {
  2435. (void)timer;
  2436. (void)arg;
  2437. sd_notify(0, "WATCHDOG=1");
  2438. }
  2439. #endif /* defined(HAVE_SYSTEMD_209) */
  2440. #define UPTIME_CUTOFF_FOR_NEW_BANDWIDTH_TEST (6*60*60)
  2441. /** Called when our IP address seems to have changed. <b>at_interface</b>
  2442. * should be true if we detected a change in our interface, and false if we
  2443. * detected a change in our published address. */
  2444. void
  2445. ip_address_changed(int at_interface)
  2446. {
  2447. const or_options_t *options = get_options();
  2448. int server = server_mode(options);
  2449. int exit_reject_interfaces = (server && options->ExitRelay
  2450. && options->ExitPolicyRejectLocalInterfaces);
  2451. if (at_interface) {
  2452. if (! server) {
  2453. /* Okay, change our keys. */
  2454. if (init_keys_client() < 0)
  2455. log_warn(LD_GENERAL, "Unable to rotate keys after IP change!");
  2456. }
  2457. } else {
  2458. if (server) {
  2459. if (get_uptime() > UPTIME_CUTOFF_FOR_NEW_BANDWIDTH_TEST)
  2460. reset_bandwidth_test();
  2461. reset_uptime();
  2462. router_reset_reachability();
  2463. }
  2464. }
  2465. /* Exit relays incorporate interface addresses in their exit policies when
  2466. * ExitPolicyRejectLocalInterfaces is set */
  2467. if (exit_reject_interfaces || (server && !at_interface)) {
  2468. mark_my_descriptor_dirty("IP address changed");
  2469. }
  2470. dns_servers_relaunch_checks();
  2471. }
  2472. /** Forget what we've learned about the correctness of our DNS servers, and
  2473. * start learning again. */
  2474. void
  2475. dns_servers_relaunch_checks(void)
  2476. {
  2477. if (server_mode(get_options())) {
  2478. dns_reset_correctness_checks();
  2479. if (periodic_events_initialized) {
  2480. tor_assert(check_dns_honesty_event);
  2481. periodic_event_reschedule(check_dns_honesty_event);
  2482. }
  2483. }
  2484. }
  2485. /** Initialize some mainloop_event_t objects that we require. */
  2486. void
  2487. initialize_mainloop_events(void)
  2488. {
  2489. initialize_periodic_events();
  2490. if (!schedule_active_linked_connections_event) {
  2491. schedule_active_linked_connections_event =
  2492. mainloop_event_postloop_new(schedule_active_linked_connections_cb, NULL);
  2493. }
  2494. if (!postloop_cleanup_ev) {
  2495. postloop_cleanup_ev =
  2496. mainloop_event_postloop_new(postloop_cleanup_cb, NULL);
  2497. }
  2498. }
  2499. /** Tor main loop. */
  2500. int
  2501. do_main_loop(void)
  2502. {
  2503. /* initialize the periodic events first, so that code that depends on the
  2504. * events being present does not assert.
  2505. */
  2506. initialize_periodic_events();
  2507. initialize_mainloop_events();
  2508. #ifdef HAVE_SYSTEMD_209
  2509. uint64_t watchdog_delay;
  2510. /* set up systemd watchdog notification. */
  2511. if (sd_watchdog_enabled(1, &watchdog_delay) > 0) {
  2512. if (! systemd_watchdog_timer) {
  2513. struct timeval watchdog;
  2514. /* The manager will "act on" us if we don't send them a notification
  2515. * every 'watchdog_delay' microseconds. So, send notifications twice
  2516. * that often. */
  2517. watchdog_delay /= 2;
  2518. watchdog.tv_sec = watchdog_delay / 1000000;
  2519. watchdog.tv_usec = watchdog_delay % 1000000;
  2520. systemd_watchdog_timer = periodic_timer_new(tor_libevent_get_base(),
  2521. &watchdog,
  2522. systemd_watchdog_callback,
  2523. NULL);
  2524. tor_assert(systemd_watchdog_timer);
  2525. }
  2526. }
  2527. #endif /* defined(HAVE_SYSTEMD_209) */
  2528. #ifdef ENABLE_RESTART_DEBUGGING
  2529. {
  2530. static int first_time = 1;
  2531. if (first_time && getenv("TOR_DEBUG_RESTART")) {
  2532. first_time = 0;
  2533. const char *sec_str = getenv("TOR_DEBUG_RESTART_AFTER_SECONDS");
  2534. long sec;
  2535. int sec_ok=0;
  2536. if (sec_str &&
  2537. (sec = tor_parse_long(sec_str, 10, 0, INT_MAX, &sec_ok, NULL)) &&
  2538. sec_ok) {
  2539. /* Okay, we parsed the seconds. */
  2540. } else {
  2541. sec = 5;
  2542. }
  2543. struct timeval restart_after = { (time_t) sec, 0 };
  2544. tor_shutdown_event_loop_for_restart_event =
  2545. tor_evtimer_new(tor_libevent_get_base(),
  2546. tor_shutdown_event_loop_for_restart_cb, NULL);
  2547. event_add(tor_shutdown_event_loop_for_restart_event, &restart_after);
  2548. }
  2549. }
  2550. #endif
  2551. return run_main_loop_until_done();
  2552. }
  2553. #ifndef _WIN32
  2554. /** Rate-limiter for EINVAL-type libevent warnings. */
  2555. static ratelim_t libevent_error_ratelim = RATELIM_INIT(10);
  2556. #endif
  2557. /**
  2558. * Run the main loop a single time. Return 0 for "exit"; -1 for "exit with
  2559. * error", and 1 for "run this again."
  2560. */
  2561. static int
  2562. run_main_loop_once(void)
  2563. {
  2564. int loop_result;
  2565. if (nt_service_is_stopping())
  2566. return 0;
  2567. if (main_loop_should_exit)
  2568. return 0;
  2569. #ifndef _WIN32
  2570. /* Make it easier to tell whether libevent failure is our fault or not. */
  2571. errno = 0;
  2572. #endif
  2573. if (get_options()->MainloopStats) {
  2574. /* We always enforce that EVLOOP_ONCE is passed to event_base_loop() if we
  2575. * are collecting main loop statistics. */
  2576. called_loop_once = 1;
  2577. } else {
  2578. called_loop_once = 0;
  2579. }
  2580. /* Make sure we know (about) what time it is. */
  2581. update_approx_time(time(NULL));
  2582. /* Here it is: the main loop. Here we tell Libevent to poll until we have
  2583. * an event, or the second ends, or until we have some active linked
  2584. * connections to trigger events for. Libevent will wait till one
  2585. * of these happens, then run all the appropriate callbacks. */
  2586. loop_result = tor_libevent_run_event_loop(tor_libevent_get_base(),
  2587. called_loop_once);
  2588. if (get_options()->MainloopStats) {
  2589. /* Update our main loop counters. */
  2590. if (loop_result == 0) {
  2591. // The call was successful.
  2592. increment_main_loop_success_count();
  2593. } else if (loop_result == -1) {
  2594. // The call was erroneous.
  2595. increment_main_loop_error_count();
  2596. } else if (loop_result == 1) {
  2597. // The call didn't have any active or pending events
  2598. // to handle.
  2599. increment_main_loop_idle_count();
  2600. }
  2601. }
  2602. /* Oh, the loop failed. That might be an error that we need to
  2603. * catch, but more likely, it's just an interrupted poll() call or something,
  2604. * and we should try again. */
  2605. if (loop_result < 0) {
  2606. int e = tor_socket_errno(-1);
  2607. /* let the program survive things like ^z */
  2608. if (e != EINTR && !ERRNO_IS_EINPROGRESS(e)) {
  2609. log_err(LD_NET,"libevent call with %s failed: %s [%d]",
  2610. tor_libevent_get_method(), tor_socket_strerror(e), e);
  2611. return -1;
  2612. #ifndef _WIN32
  2613. } else if (e == EINVAL) {
  2614. log_fn_ratelim(&libevent_error_ratelim, LOG_WARN, LD_NET,
  2615. "EINVAL from libevent: should you upgrade libevent?");
  2616. if (libevent_error_ratelim.n_calls_since_last_time > 8) {
  2617. log_err(LD_NET, "Too many libevent errors, too fast: dying");
  2618. return -1;
  2619. }
  2620. #endif /* !defined(_WIN32) */
  2621. } else {
  2622. tor_assert_nonfatal_once(! ERRNO_IS_EINPROGRESS(e));
  2623. log_debug(LD_NET,"libevent call interrupted.");
  2624. /* You can't trust the results of this poll(). Go back to the
  2625. * top of the big for loop. */
  2626. return 1;
  2627. }
  2628. }
  2629. if (main_loop_should_exit)
  2630. return 0;
  2631. return 1;
  2632. }
  2633. /** Run the run_main_loop_once() function until it declares itself done,
  2634. * and return its final return value.
  2635. *
  2636. * Shadow won't invoke this function, so don't fill it up with things.
  2637. */
  2638. STATIC int
  2639. run_main_loop_until_done(void)
  2640. {
  2641. int loop_result = 1;
  2642. main_loop_should_exit = 0;
  2643. main_loop_exit_value = 0;
  2644. do {
  2645. loop_result = run_main_loop_once();
  2646. } while (loop_result == 1);
  2647. if (main_loop_should_exit)
  2648. return main_loop_exit_value;
  2649. else
  2650. return loop_result;
  2651. }
  2652. /** Returns Tor's uptime. */
  2653. MOCK_IMPL(long,
  2654. get_uptime,(void))
  2655. {
  2656. return stats_n_seconds_working;
  2657. }
  2658. /** Reset Tor's uptime. */
  2659. MOCK_IMPL(void,
  2660. reset_uptime,(void))
  2661. {
  2662. stats_n_seconds_working = 0;
  2663. }
  2664. void
  2665. tor_mainloop_free_all(void)
  2666. {
  2667. smartlist_free(connection_array);
  2668. smartlist_free(closeable_connection_lst);
  2669. smartlist_free(active_linked_connection_lst);
  2670. teardown_periodic_events();
  2671. tor_event_free(shutdown_did_not_work_event);
  2672. tor_event_free(initialize_periodic_events_event);
  2673. mainloop_event_free(directory_all_unreachable_cb_event);
  2674. mainloop_event_free(schedule_active_linked_connections_event);
  2675. mainloop_event_free(postloop_cleanup_ev);
  2676. mainloop_event_free(handle_deferred_signewnym_ev);
  2677. mainloop_event_free(scheduled_shutdown_ev);
  2678. mainloop_event_free(rescan_periodic_events_ev);
  2679. #ifdef HAVE_SYSTEMD_209
  2680. periodic_timer_free(systemd_watchdog_timer);
  2681. #endif
  2682. stats_n_bytes_read = stats_n_bytes_written = 0;
  2683. memset(&global_bucket, 0, sizeof(global_bucket));
  2684. memset(&global_relayed_bucket, 0, sizeof(global_relayed_bucket));
  2685. time_of_process_start = 0;
  2686. time_of_last_signewnym = 0;
  2687. signewnym_is_pending = 0;
  2688. newnym_epoch = 0;
  2689. called_loop_once = 0;
  2690. main_loop_should_exit = 0;
  2691. main_loop_exit_value = 0;
  2692. can_complete_circuits = 0;
  2693. quiet_level = 0;
  2694. should_init_bridge_stats = 1;
  2695. dns_honesty_first_time = 1;
  2696. heartbeat_callback_first_time = 1;
  2697. current_second = 0;
  2698. memset(&current_second_last_changed, 0,
  2699. sizeof(current_second_last_changed));
  2700. }