main.c 137 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312
  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 main.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 MAIN_PRIVATE
  48. #include "core/or/or.h"
  49. #include "feature/client/addressmap.h"
  50. #include "lib/err/backtrace.h"
  51. #include "feature/client/bridges.h"
  52. #include "lib/container/buffers.h"
  53. #include "lib/tls/buffers_tls.h"
  54. #include "core/or/channel.h"
  55. #include "core/or/channeltls.h"
  56. #include "core/or/channelpadding.h"
  57. #include "core/or/circuitbuild.h"
  58. #include "core/or/circuitlist.h"
  59. #include "core/or/circuituse.h"
  60. #include "core/or/circuitmux_ewma.h"
  61. #include "core/or/command.h"
  62. #include "lib/compress/compress.h"
  63. #include "app/config/config.h"
  64. #include "app/config/confparse.h"
  65. #include "core/mainloop/connection.h"
  66. #include "core/or/connection_edge.h"
  67. #include "core/or/connection_or.h"
  68. #include "feature/dircache/consdiffmgr.h"
  69. #include "feature/control/control.h"
  70. #include "core/mainloop/cpuworker.h"
  71. #include "lib/crypt_ops/crypto_s2k.h"
  72. #include "lib/crypt_ops/crypto_rand.h"
  73. #include "feature/dircache/directory.h"
  74. #include "feature/dircache/dirserv.h"
  75. #include "feature/relay/dns.h"
  76. #include "feature/client/dnsserv.h"
  77. #include "core/or/dos.h"
  78. #include "feature/client/entrynodes.h"
  79. #include "feature/stats/geoip.h"
  80. #include "feature/hibernate/hibernate.h"
  81. #include "feature/hs/hs_cache.h"
  82. #include "feature/hs/hs_circuitmap.h"
  83. #include "feature/hs/hs_client.h"
  84. #include "feature/dirauth/keypin.h"
  85. #include "core/mainloop/main.h"
  86. #include "feature/nodelist/microdesc.h"
  87. #include "feature/nodelist/networkstatus.h"
  88. #include "feature/nodelist/nodelist.h"
  89. #include "app/main/ntmain.h"
  90. #include "core/crypto/onion.h"
  91. #include "core/mainloop/periodic.h"
  92. #include "core/or/policies.h"
  93. #include "core/or/protover.h"
  94. #include "feature/client/transports.h"
  95. #include "core/or/relay.h"
  96. #include "feature/rend/rendclient.h"
  97. #include "feature/rend/rendcommon.h"
  98. #include "feature/rend/rendservice.h"
  99. #include "feature/stats/rephist.h"
  100. #include "feature/relay/router.h"
  101. #include "feature/relay/routerkeys.h"
  102. #include "feature/nodelist/routerlist.h"
  103. #include "feature/nodelist/routerparse.h"
  104. #include "core/or/scheduler.h"
  105. #include "app/config/statefile.h"
  106. #include "core/or/status.h"
  107. #include "feature/api/tor_api.h"
  108. #include "feature/api/tor_api_internal.h"
  109. #include "lib/process/waitpid.h"
  110. #include "feature/relay/ext_orport.h"
  111. #include "lib/memarea/memarea.h"
  112. #include "lib/meminfo/meminfo.h"
  113. #include "lib/osinfo/uname.h"
  114. #include "lib/sandbox/sandbox.h"
  115. #include "lib/fs/lockfile.h"
  116. #include "lib/net/buffers_net.h"
  117. #include "lib/net/resolve.h"
  118. #include "lib/tls/tortls.h"
  119. #include "lib/evloop/compat_libevent.h"
  120. #include "lib/encoding/confline.h"
  121. #include "lib/evloop/timers.h"
  122. #include <event2/event.h>
  123. #include "feature/dirauth/dirvote.h"
  124. #include "feature/dirauth/mode.h"
  125. #include "feature/dirauth/shared_random.h"
  126. #include "core/or/cell_st.h"
  127. #include "core/or/entry_connection_st.h"
  128. #include "feature/nodelist/networkstatus_st.h"
  129. #include "core/or/or_connection_st.h"
  130. #include "app/config/or_state_st.h"
  131. #include "core/or/port_cfg_st.h"
  132. #include "feature/nodelist/routerinfo_st.h"
  133. #include "core/or/socks_request_st.h"
  134. #ifdef HAVE_UNISTD_H
  135. #include <unistd.h>
  136. #endif
  137. #ifdef HAVE_SYSTEMD
  138. # if defined(__COVERITY__) && !defined(__INCLUDE_LEVEL__)
  139. /* Systemd's use of gcc's __INCLUDE_LEVEL__ extension macro appears to confuse
  140. * Coverity. Here's a kludge to unconfuse it.
  141. */
  142. # define __INCLUDE_LEVEL__ 2
  143. #endif /* defined(__COVERITY__) && !defined(__INCLUDE_LEVEL__) */
  144. #include <systemd/sd-daemon.h>
  145. #endif /* defined(HAVE_SYSTEMD) */
  146. void evdns_shutdown(int);
  147. #ifdef HAVE_RUST
  148. // helper function defined in Rust to output a log message indicating if tor is
  149. // running with Rust enabled. See src/rust/tor_util
  150. void rust_log_welcome_string(void);
  151. #endif
  152. /********* PROTOTYPES **********/
  153. static void dumpmemusage(int severity);
  154. static void dumpstats(int severity); /* log stats */
  155. static void conn_read_callback(evutil_socket_t fd, short event, void *_conn);
  156. static void conn_write_callback(evutil_socket_t fd, short event, void *_conn);
  157. static void second_elapsed_callback(periodic_timer_t *timer, void *args);
  158. static int conn_close_if_marked(int i);
  159. static void connection_start_reading_from_linked_conn(connection_t *conn);
  160. static int connection_should_read_from_linked_conn(connection_t *conn);
  161. static int run_main_loop_until_done(void);
  162. static void process_signal(int sig);
  163. static void shutdown_did_not_work_callback(evutil_socket_t fd, short event,
  164. void *arg) ATTR_NORETURN;
  165. /********* START VARIABLES **********/
  166. /* Token bucket for all traffic. */
  167. token_bucket_rw_t global_bucket;
  168. /* Token bucket for relayed traffic. */
  169. token_bucket_rw_t global_relayed_bucket;
  170. /* XXX we might want to keep stats about global_relayed_*_bucket too. Or not.*/
  171. /** How many bytes have we read since we started the process? */
  172. static uint64_t stats_n_bytes_read = 0;
  173. /** How many bytes have we written since we started the process? */
  174. static uint64_t stats_n_bytes_written = 0;
  175. /** What time did this process start up? */
  176. time_t time_of_process_start = 0;
  177. /** How many seconds have we been running? */
  178. static long stats_n_seconds_working = 0;
  179. /** How many times have we returned from the main loop successfully? */
  180. static uint64_t stats_n_main_loop_successes = 0;
  181. /** How many times have we received an error from the main loop? */
  182. static uint64_t stats_n_main_loop_errors = 0;
  183. /** How many times have we returned from the main loop with no events. */
  184. static uint64_t stats_n_main_loop_idle = 0;
  185. /** How often will we honor SIGNEWNYM requests? */
  186. #define MAX_SIGNEWNYM_RATE 10
  187. /** When did we last process a SIGNEWNYM request? */
  188. static time_t time_of_last_signewnym = 0;
  189. /** Is there a signewnym request we're currently waiting to handle? */
  190. static int signewnym_is_pending = 0;
  191. /** Mainloop event for the deferred signewnym call. */
  192. static mainloop_event_t *handle_deferred_signewnym_ev = NULL;
  193. /** How many times have we called newnym? */
  194. static unsigned newnym_epoch = 0;
  195. /** Smartlist of all open connections. */
  196. STATIC smartlist_t *connection_array = NULL;
  197. /** List of connections that have been marked for close and need to be freed
  198. * and removed from connection_array. */
  199. static smartlist_t *closeable_connection_lst = NULL;
  200. /** List of linked connections that are currently reading data into their
  201. * inbuf from their partner's outbuf. */
  202. static smartlist_t *active_linked_connection_lst = NULL;
  203. /** Flag: Set to true iff we entered the current libevent main loop via
  204. * <b>loop_once</b>. If so, there's no need to trigger a loopexit in order
  205. * to handle linked connections. */
  206. static int called_loop_once = 0;
  207. /** Flag: if true, it's time to shut down, so the main loop should exit as
  208. * soon as possible.
  209. */
  210. static int main_loop_should_exit = 0;
  211. /** The return value that the main loop should yield when it exits, if
  212. * main_loop_should_exit is true.
  213. */
  214. static int main_loop_exit_value = 0;
  215. /** We set this to 1 when we've opened a circuit, so we can print a log
  216. * entry to inform the user that Tor is working. We set it to 0 when
  217. * we think the fact that we once opened a circuit doesn't mean we can do so
  218. * any longer (a big time jump happened, when we notice our directory is
  219. * heinously out-of-date, etc.
  220. */
  221. static int can_complete_circuits = 0;
  222. /** How often do we check for router descriptors that we should download
  223. * when we have too little directory info? */
  224. #define GREEDY_DESCRIPTOR_RETRY_INTERVAL (10)
  225. /** How often do we check for router descriptors that we should download
  226. * when we have enough directory info? */
  227. #define LAZY_DESCRIPTOR_RETRY_INTERVAL (60)
  228. /** Decides our behavior when no logs are configured/before any
  229. * logs have been configured. For 0, we log notice to stdout as normal.
  230. * For 1, we log warnings only. For 2, we log nothing.
  231. */
  232. int quiet_level = 0;
  233. /********* END VARIABLES ************/
  234. /****************************************************************************
  235. *
  236. * This section contains accessors and other methods on the connection_array
  237. * variables (which are global within this file and unavailable outside it).
  238. *
  239. ****************************************************************************/
  240. /** Return 1 if we have successfully built a circuit, and nothing has changed
  241. * to make us think that maybe we can't.
  242. */
  243. int
  244. have_completed_a_circuit(void)
  245. {
  246. return can_complete_circuits;
  247. }
  248. /** Note that we have successfully built a circuit, so that reachability
  249. * testing and introduction points and so on may be attempted. */
  250. void
  251. note_that_we_completed_a_circuit(void)
  252. {
  253. can_complete_circuits = 1;
  254. }
  255. /** Note that something has happened (like a clock jump, or DisableNetwork) to
  256. * make us think that maybe we can't complete circuits. */
  257. void
  258. note_that_we_maybe_cant_complete_circuits(void)
  259. {
  260. can_complete_circuits = 0;
  261. }
  262. /** Add <b>conn</b> to the array of connections that we can poll on. The
  263. * connection's socket must be set; the connection starts out
  264. * non-reading and non-writing.
  265. */
  266. int
  267. connection_add_impl(connection_t *conn, int is_connecting)
  268. {
  269. tor_assert(conn);
  270. tor_assert(SOCKET_OK(conn->s) ||
  271. conn->linked ||
  272. (conn->type == CONN_TYPE_AP &&
  273. TO_EDGE_CONN(conn)->is_dns_request));
  274. tor_assert(conn->conn_array_index == -1); /* can only connection_add once */
  275. conn->conn_array_index = smartlist_len(connection_array);
  276. smartlist_add(connection_array, conn);
  277. (void) is_connecting;
  278. if (SOCKET_OK(conn->s) || conn->linked) {
  279. conn->read_event = tor_event_new(tor_libevent_get_base(),
  280. conn->s, EV_READ|EV_PERSIST, conn_read_callback, conn);
  281. conn->write_event = tor_event_new(tor_libevent_get_base(),
  282. conn->s, EV_WRITE|EV_PERSIST, conn_write_callback, conn);
  283. /* XXXX CHECK FOR NULL RETURN! */
  284. }
  285. log_debug(LD_NET,"new conn type %s, socket %d, address %s, n_conns %d.",
  286. conn_type_to_string(conn->type), (int)conn->s, conn->address,
  287. smartlist_len(connection_array));
  288. return 0;
  289. }
  290. /** Tell libevent that we don't care about <b>conn</b> any more. */
  291. void
  292. connection_unregister_events(connection_t *conn)
  293. {
  294. if (conn->read_event) {
  295. if (event_del(conn->read_event))
  296. log_warn(LD_BUG, "Error removing read event for %d", (int)conn->s);
  297. tor_free(conn->read_event);
  298. }
  299. if (conn->write_event) {
  300. if (event_del(conn->write_event))
  301. log_warn(LD_BUG, "Error removing write event for %d", (int)conn->s);
  302. tor_free(conn->write_event);
  303. }
  304. if (conn->type == CONN_TYPE_AP_DNS_LISTENER) {
  305. dnsserv_close_listener(conn);
  306. }
  307. }
  308. /** Remove the connection from the global list, and remove the
  309. * corresponding poll entry. Calling this function will shift the last
  310. * connection (if any) into the position occupied by conn.
  311. */
  312. int
  313. connection_remove(connection_t *conn)
  314. {
  315. int current_index;
  316. connection_t *tmp;
  317. tor_assert(conn);
  318. log_debug(LD_NET,"removing socket %d (type %s), n_conns now %d",
  319. (int)conn->s, conn_type_to_string(conn->type),
  320. smartlist_len(connection_array));
  321. if (conn->type == CONN_TYPE_AP && conn->socket_family == AF_UNIX) {
  322. log_info(LD_NET, "Closing SOCKS Unix socket connection");
  323. }
  324. control_event_conn_bandwidth(conn);
  325. tor_assert(conn->conn_array_index >= 0);
  326. current_index = conn->conn_array_index;
  327. connection_unregister_events(conn); /* This is redundant, but cheap. */
  328. if (current_index == smartlist_len(connection_array)-1) { /* at the end */
  329. smartlist_del(connection_array, current_index);
  330. return 0;
  331. }
  332. /* replace this one with the one at the end */
  333. smartlist_del(connection_array, current_index);
  334. tmp = smartlist_get(connection_array, current_index);
  335. tmp->conn_array_index = current_index;
  336. return 0;
  337. }
  338. /** If <b>conn</b> is an edge conn, remove it from the list
  339. * of conn's on this circuit. If it's not on an edge,
  340. * flush and send destroys for all circuits on this conn.
  341. *
  342. * Remove it from connection_array (if applicable) and
  343. * from closeable_connection_list.
  344. *
  345. * Then free it.
  346. */
  347. static void
  348. connection_unlink(connection_t *conn)
  349. {
  350. connection_about_to_close_connection(conn);
  351. if (conn->conn_array_index >= 0) {
  352. connection_remove(conn);
  353. }
  354. if (conn->linked_conn) {
  355. conn->linked_conn->linked_conn = NULL;
  356. if (! conn->linked_conn->marked_for_close &&
  357. conn->linked_conn->reading_from_linked_conn)
  358. connection_start_reading(conn->linked_conn);
  359. conn->linked_conn = NULL;
  360. }
  361. smartlist_remove(closeable_connection_lst, conn);
  362. smartlist_remove(active_linked_connection_lst, conn);
  363. if (conn->type == CONN_TYPE_EXIT) {
  364. assert_connection_edge_not_dns_pending(TO_EDGE_CONN(conn));
  365. }
  366. if (conn->type == CONN_TYPE_OR) {
  367. if (!tor_digest_is_zero(TO_OR_CONN(conn)->identity_digest))
  368. connection_or_clear_identity(TO_OR_CONN(conn));
  369. /* connection_unlink() can only get called if the connection
  370. * was already on the closeable list, and it got there by
  371. * connection_mark_for_close(), which was called from
  372. * connection_or_close_normally() or
  373. * connection_or_close_for_error(), so the channel should
  374. * already be in CHANNEL_STATE_CLOSING, and then the
  375. * connection_about_to_close_connection() goes to
  376. * connection_or_about_to_close(), which calls channel_closed()
  377. * to notify the channel_t layer, and closed the channel, so
  378. * nothing more to do here to deal with the channel associated
  379. * with an orconn.
  380. */
  381. }
  382. connection_free(conn);
  383. }
  384. /**
  385. * Callback: used to activate read events for all linked connections, so
  386. * libevent knows to call their read callbacks. This callback run as a
  387. * postloop event, so that the events _it_ activates don't happen until
  388. * Libevent has a chance to check for other events.
  389. */
  390. static void
  391. schedule_active_linked_connections_cb(mainloop_event_t *event, void *arg)
  392. {
  393. (void)event;
  394. (void)arg;
  395. /* All active linked conns should get their read events activated,
  396. * so that libevent knows to run their callbacks. */
  397. SMARTLIST_FOREACH(active_linked_connection_lst, connection_t *, conn,
  398. event_active(conn->read_event, EV_READ, 1));
  399. }
  400. /** Event that invokes schedule_active_linked_connections_cb. */
  401. static mainloop_event_t *schedule_active_linked_connections_event = NULL;
  402. /** Initialize the global connection list, closeable connection list,
  403. * and active connection list. */
  404. STATIC void
  405. init_connection_lists(void)
  406. {
  407. if (!connection_array)
  408. connection_array = smartlist_new();
  409. if (!closeable_connection_lst)
  410. closeable_connection_lst = smartlist_new();
  411. if (!active_linked_connection_lst)
  412. active_linked_connection_lst = smartlist_new();
  413. }
  414. /** Schedule <b>conn</b> to be closed. **/
  415. void
  416. add_connection_to_closeable_list(connection_t *conn)
  417. {
  418. tor_assert(!smartlist_contains(closeable_connection_lst, conn));
  419. tor_assert(conn->marked_for_close);
  420. assert_connection_ok(conn, time(NULL));
  421. smartlist_add(closeable_connection_lst, conn);
  422. mainloop_schedule_postloop_cleanup();
  423. }
  424. /** Return 1 if conn is on the closeable list, else return 0. */
  425. int
  426. connection_is_on_closeable_list(connection_t *conn)
  427. {
  428. return smartlist_contains(closeable_connection_lst, conn);
  429. }
  430. /** Return true iff conn is in the current poll array. */
  431. int
  432. connection_in_array(connection_t *conn)
  433. {
  434. return smartlist_contains(connection_array, conn);
  435. }
  436. /** Set <b>*array</b> to an array of all connections. <b>*array</b> must not
  437. * be modified.
  438. */
  439. MOCK_IMPL(smartlist_t *,
  440. get_connection_array, (void))
  441. {
  442. if (!connection_array)
  443. connection_array = smartlist_new();
  444. return connection_array;
  445. }
  446. /**
  447. * Return the amount of network traffic read, in bytes, over the life of this
  448. * process.
  449. */
  450. MOCK_IMPL(uint64_t,
  451. get_bytes_read,(void))
  452. {
  453. return stats_n_bytes_read;
  454. }
  455. /**
  456. * Return the amount of network traffic read, in bytes, over the life of this
  457. * process.
  458. */
  459. MOCK_IMPL(uint64_t,
  460. get_bytes_written,(void))
  461. {
  462. return stats_n_bytes_written;
  463. }
  464. /**
  465. * Increment the amount of network traffic read and written, over the life of
  466. * this process.
  467. */
  468. void
  469. stats_increment_bytes_read_and_written(uint64_t r, uint64_t w)
  470. {
  471. stats_n_bytes_read += r;
  472. stats_n_bytes_written += w;
  473. }
  474. /** Set the event mask on <b>conn</b> to <b>events</b>. (The event
  475. * mask is a bitmask whose bits are READ_EVENT and WRITE_EVENT)
  476. */
  477. void
  478. connection_watch_events(connection_t *conn, watchable_events_t events)
  479. {
  480. if (events & READ_EVENT)
  481. connection_start_reading(conn);
  482. else
  483. connection_stop_reading(conn);
  484. if (events & WRITE_EVENT)
  485. connection_start_writing(conn);
  486. else
  487. connection_stop_writing(conn);
  488. }
  489. /** Return true iff <b>conn</b> is listening for read events. */
  490. int
  491. connection_is_reading(connection_t *conn)
  492. {
  493. tor_assert(conn);
  494. return conn->reading_from_linked_conn ||
  495. (conn->read_event && event_pending(conn->read_event, EV_READ, NULL));
  496. }
  497. /** Reset our main loop counters. */
  498. void
  499. reset_main_loop_counters(void)
  500. {
  501. stats_n_main_loop_successes = 0;
  502. stats_n_main_loop_errors = 0;
  503. stats_n_main_loop_idle = 0;
  504. }
  505. /** Increment the main loop success counter. */
  506. static void
  507. increment_main_loop_success_count(void)
  508. {
  509. ++stats_n_main_loop_successes;
  510. }
  511. /** Get the main loop success counter. */
  512. uint64_t
  513. get_main_loop_success_count(void)
  514. {
  515. return stats_n_main_loop_successes;
  516. }
  517. /** Increment the main loop error counter. */
  518. static void
  519. increment_main_loop_error_count(void)
  520. {
  521. ++stats_n_main_loop_errors;
  522. }
  523. /** Get the main loop error counter. */
  524. uint64_t
  525. get_main_loop_error_count(void)
  526. {
  527. return stats_n_main_loop_errors;
  528. }
  529. /** Increment the main loop idle counter. */
  530. static void
  531. increment_main_loop_idle_count(void)
  532. {
  533. ++stats_n_main_loop_idle;
  534. }
  535. /** Get the main loop idle counter. */
  536. uint64_t
  537. get_main_loop_idle_count(void)
  538. {
  539. return stats_n_main_loop_idle;
  540. }
  541. /** Check whether <b>conn</b> is correct in having (or not having) a
  542. * read/write event (passed in <b>ev</b>). On success, return 0. On failure,
  543. * log a warning and return -1. */
  544. static int
  545. connection_check_event(connection_t *conn, struct event *ev)
  546. {
  547. int bad;
  548. if (conn->type == CONN_TYPE_AP && TO_EDGE_CONN(conn)->is_dns_request) {
  549. /* DNS requests which we launch through the dnsserv.c module do not have
  550. * any underlying socket or any underlying linked connection, so they
  551. * shouldn't have any attached events either.
  552. */
  553. bad = ev != NULL;
  554. } else {
  555. /* Everything else should have an underlying socket, or a linked
  556. * connection (which is also tracked with a read_event/write_event pair).
  557. */
  558. bad = ev == NULL;
  559. }
  560. if (bad) {
  561. log_warn(LD_BUG, "Event missing on connection %p [%s;%s]. "
  562. "socket=%d. linked=%d. "
  563. "is_dns_request=%d. Marked_for_close=%s:%d",
  564. conn,
  565. conn_type_to_string(conn->type),
  566. conn_state_to_string(conn->type, conn->state),
  567. (int)conn->s, (int)conn->linked,
  568. (conn->type == CONN_TYPE_AP &&
  569. TO_EDGE_CONN(conn)->is_dns_request),
  570. conn->marked_for_close_file ? conn->marked_for_close_file : "-",
  571. conn->marked_for_close
  572. );
  573. log_backtrace(LOG_WARN, LD_BUG, "Backtrace attached.");
  574. return -1;
  575. }
  576. return 0;
  577. }
  578. /** Tell the main loop to stop notifying <b>conn</b> of any read events. */
  579. MOCK_IMPL(void,
  580. connection_stop_reading,(connection_t *conn))
  581. {
  582. tor_assert(conn);
  583. if (connection_check_event(conn, conn->read_event) < 0) {
  584. return;
  585. }
  586. if (conn->linked) {
  587. conn->reading_from_linked_conn = 0;
  588. connection_stop_reading_from_linked_conn(conn);
  589. } else {
  590. if (event_del(conn->read_event))
  591. log_warn(LD_NET, "Error from libevent setting read event state for %d "
  592. "to unwatched: %s",
  593. (int)conn->s,
  594. tor_socket_strerror(tor_socket_errno(conn->s)));
  595. }
  596. }
  597. /** Tell the main loop to start notifying <b>conn</b> of any read events. */
  598. MOCK_IMPL(void,
  599. connection_start_reading,(connection_t *conn))
  600. {
  601. tor_assert(conn);
  602. if (connection_check_event(conn, conn->read_event) < 0) {
  603. return;
  604. }
  605. if (conn->linked) {
  606. conn->reading_from_linked_conn = 1;
  607. if (connection_should_read_from_linked_conn(conn))
  608. connection_start_reading_from_linked_conn(conn);
  609. } else {
  610. if (event_add(conn->read_event, NULL))
  611. log_warn(LD_NET, "Error from libevent setting read event state for %d "
  612. "to watched: %s",
  613. (int)conn->s,
  614. tor_socket_strerror(tor_socket_errno(conn->s)));
  615. }
  616. }
  617. /** Return true iff <b>conn</b> is listening for write events. */
  618. int
  619. connection_is_writing(connection_t *conn)
  620. {
  621. tor_assert(conn);
  622. return conn->writing_to_linked_conn ||
  623. (conn->write_event && event_pending(conn->write_event, EV_WRITE, NULL));
  624. }
  625. /** Tell the main loop to stop notifying <b>conn</b> of any write events. */
  626. MOCK_IMPL(void,
  627. connection_stop_writing,(connection_t *conn))
  628. {
  629. tor_assert(conn);
  630. if (connection_check_event(conn, conn->write_event) < 0) {
  631. return;
  632. }
  633. if (conn->linked) {
  634. conn->writing_to_linked_conn = 0;
  635. if (conn->linked_conn)
  636. connection_stop_reading_from_linked_conn(conn->linked_conn);
  637. } else {
  638. if (event_del(conn->write_event))
  639. log_warn(LD_NET, "Error from libevent setting write event state for %d "
  640. "to unwatched: %s",
  641. (int)conn->s,
  642. tor_socket_strerror(tor_socket_errno(conn->s)));
  643. }
  644. }
  645. /** Tell the main loop to start notifying <b>conn</b> of any write events. */
  646. MOCK_IMPL(void,
  647. connection_start_writing,(connection_t *conn))
  648. {
  649. tor_assert(conn);
  650. if (connection_check_event(conn, conn->write_event) < 0) {
  651. return;
  652. }
  653. if (conn->linked) {
  654. conn->writing_to_linked_conn = 1;
  655. if (conn->linked_conn &&
  656. connection_should_read_from_linked_conn(conn->linked_conn))
  657. connection_start_reading_from_linked_conn(conn->linked_conn);
  658. } else {
  659. if (event_add(conn->write_event, NULL))
  660. log_warn(LD_NET, "Error from libevent setting write event state for %d "
  661. "to watched: %s",
  662. (int)conn->s,
  663. tor_socket_strerror(tor_socket_errno(conn->s)));
  664. }
  665. }
  666. /** Return true iff <b>conn</b> is linked conn, and reading from the conn
  667. * linked to it would be good and feasible. (Reading is "feasible" if the
  668. * other conn exists and has data in its outbuf, and is "good" if we have our
  669. * reading_from_linked_conn flag set and the other conn has its
  670. * writing_to_linked_conn flag set.)*/
  671. static int
  672. connection_should_read_from_linked_conn(connection_t *conn)
  673. {
  674. if (conn->linked && conn->reading_from_linked_conn) {
  675. if (! conn->linked_conn ||
  676. (conn->linked_conn->writing_to_linked_conn &&
  677. buf_datalen(conn->linked_conn->outbuf)))
  678. return 1;
  679. }
  680. return 0;
  681. }
  682. /** Event to run 'shutdown did not work callback'. */
  683. static struct event *shutdown_did_not_work_event = NULL;
  684. /** Failsafe measure that should never actually be necessary: If
  685. * tor_shutdown_event_loop_and_exit() somehow doesn't successfully exit the
  686. * event loop, then this callback will kill Tor with an assertion failure
  687. * seconds later
  688. */
  689. static void
  690. shutdown_did_not_work_callback(evutil_socket_t fd, short event, void *arg)
  691. {
  692. // LCOV_EXCL_START
  693. (void) fd;
  694. (void) event;
  695. (void) arg;
  696. tor_assert_unreached();
  697. // LCOV_EXCL_STOP
  698. }
  699. #ifdef ENABLE_RESTART_DEBUGGING
  700. static struct event *tor_shutdown_event_loop_for_restart_event = NULL;
  701. static void
  702. tor_shutdown_event_loop_for_restart_cb(
  703. evutil_socket_t fd, short event, void *arg)
  704. {
  705. (void)fd;
  706. (void)event;
  707. (void)arg;
  708. tor_event_free(tor_shutdown_event_loop_for_restart_event);
  709. tor_shutdown_event_loop_and_exit(0);
  710. }
  711. #endif
  712. /**
  713. * After finishing the current callback (if any), shut down the main loop,
  714. * clean up the process, and exit with <b>exitcode</b>.
  715. */
  716. void
  717. tor_shutdown_event_loop_and_exit(int exitcode)
  718. {
  719. if (main_loop_should_exit)
  720. return; /* Ignore multiple calls to this function. */
  721. main_loop_should_exit = 1;
  722. main_loop_exit_value = exitcode;
  723. /* Die with an assertion failure in ten seconds, if for some reason we don't
  724. * exit normally. */
  725. /* XXXX We should consider this code if it's never used. */
  726. struct timeval ten_seconds = { 10, 0 };
  727. shutdown_did_not_work_event = tor_evtimer_new(
  728. tor_libevent_get_base(),
  729. shutdown_did_not_work_callback, NULL);
  730. event_add(shutdown_did_not_work_event, &ten_seconds);
  731. /* Unlike exit_loop_after_delay(), exit_loop_after_callback
  732. * prevents other callbacks from running. */
  733. tor_libevent_exit_loop_after_callback(tor_libevent_get_base());
  734. }
  735. /** Return true iff tor_shutdown_event_loop_and_exit() has been called. */
  736. int
  737. tor_event_loop_shutdown_is_pending(void)
  738. {
  739. return main_loop_should_exit;
  740. }
  741. /** Helper: Tell the main loop to begin reading bytes into <b>conn</b> from
  742. * its linked connection, if it is not doing so already. Called by
  743. * connection_start_reading and connection_start_writing as appropriate. */
  744. static void
  745. connection_start_reading_from_linked_conn(connection_t *conn)
  746. {
  747. tor_assert(conn);
  748. tor_assert(conn->linked == 1);
  749. if (!conn->active_on_link) {
  750. conn->active_on_link = 1;
  751. smartlist_add(active_linked_connection_lst, conn);
  752. mainloop_event_activate(schedule_active_linked_connections_event);
  753. } else {
  754. tor_assert(smartlist_contains(active_linked_connection_lst, conn));
  755. }
  756. }
  757. /** Tell the main loop to stop reading bytes into <b>conn</b> from its linked
  758. * connection, if is currently doing so. Called by connection_stop_reading,
  759. * connection_stop_writing, and connection_read. */
  760. void
  761. connection_stop_reading_from_linked_conn(connection_t *conn)
  762. {
  763. tor_assert(conn);
  764. tor_assert(conn->linked == 1);
  765. if (conn->active_on_link) {
  766. conn->active_on_link = 0;
  767. /* FFFF We could keep an index here so we can smartlist_del
  768. * cleanly. On the other hand, this doesn't show up on profiles,
  769. * so let's leave it alone for now. */
  770. smartlist_remove(active_linked_connection_lst, conn);
  771. } else {
  772. tor_assert(!smartlist_contains(active_linked_connection_lst, conn));
  773. }
  774. }
  775. /** Close all connections that have been scheduled to get closed. */
  776. STATIC void
  777. close_closeable_connections(void)
  778. {
  779. int i;
  780. for (i = 0; i < smartlist_len(closeable_connection_lst); ) {
  781. connection_t *conn = smartlist_get(closeable_connection_lst, i);
  782. if (conn->conn_array_index < 0) {
  783. connection_unlink(conn); /* blow it away right now */
  784. } else {
  785. if (!conn_close_if_marked(conn->conn_array_index))
  786. ++i;
  787. }
  788. }
  789. }
  790. /** Count moribund connections for the OOS handler */
  791. MOCK_IMPL(int,
  792. connection_count_moribund, (void))
  793. {
  794. int moribund = 0;
  795. /*
  796. * Count things we'll try to kill when close_closeable_connections()
  797. * runs next.
  798. */
  799. SMARTLIST_FOREACH_BEGIN(closeable_connection_lst, connection_t *, conn) {
  800. if (SOCKET_OK(conn->s) && connection_is_moribund(conn)) ++moribund;
  801. } SMARTLIST_FOREACH_END(conn);
  802. return moribund;
  803. }
  804. /** Libevent callback: this gets invoked when (connection_t*)<b>conn</b> has
  805. * some data to read. */
  806. static void
  807. conn_read_callback(evutil_socket_t fd, short event, void *_conn)
  808. {
  809. connection_t *conn = _conn;
  810. (void)fd;
  811. (void)event;
  812. log_debug(LD_NET,"socket %d wants to read.",(int)conn->s);
  813. /* assert_connection_ok(conn, time(NULL)); */
  814. if (connection_handle_read(conn) < 0) {
  815. if (!conn->marked_for_close) {
  816. #ifndef _WIN32
  817. log_warn(LD_BUG,"Unhandled error on read for %s connection "
  818. "(fd %d); removing",
  819. conn_type_to_string(conn->type), (int)conn->s);
  820. tor_fragile_assert();
  821. #endif /* !defined(_WIN32) */
  822. if (CONN_IS_EDGE(conn))
  823. connection_edge_end_errno(TO_EDGE_CONN(conn));
  824. connection_mark_for_close(conn);
  825. }
  826. }
  827. assert_connection_ok(conn, time(NULL));
  828. if (smartlist_len(closeable_connection_lst))
  829. close_closeable_connections();
  830. }
  831. /** Libevent callback: this gets invoked when (connection_t*)<b>conn</b> has
  832. * some data to write. */
  833. static void
  834. conn_write_callback(evutil_socket_t fd, short events, void *_conn)
  835. {
  836. connection_t *conn = _conn;
  837. (void)fd;
  838. (void)events;
  839. LOG_FN_CONN(conn, (LOG_DEBUG, LD_NET, "socket %d wants to write.",
  840. (int)conn->s));
  841. /* assert_connection_ok(conn, time(NULL)); */
  842. if (connection_handle_write(conn, 0) < 0) {
  843. if (!conn->marked_for_close) {
  844. /* this connection is broken. remove it. */
  845. log_fn(LOG_WARN,LD_BUG,
  846. "unhandled error on write for %s connection (fd %d); removing",
  847. conn_type_to_string(conn->type), (int)conn->s);
  848. tor_fragile_assert();
  849. if (CONN_IS_EDGE(conn)) {
  850. /* otherwise we cry wolf about duplicate close */
  851. edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
  852. if (!edge_conn->end_reason)
  853. edge_conn->end_reason = END_STREAM_REASON_INTERNAL;
  854. edge_conn->edge_has_sent_end = 1;
  855. }
  856. connection_close_immediate(conn); /* So we don't try to flush. */
  857. connection_mark_for_close(conn);
  858. }
  859. }
  860. assert_connection_ok(conn, time(NULL));
  861. if (smartlist_len(closeable_connection_lst))
  862. close_closeable_connections();
  863. }
  864. /** If the connection at connection_array[i] is marked for close, then:
  865. * - If it has data that it wants to flush, try to flush it.
  866. * - If it _still_ has data to flush, and conn->hold_open_until_flushed is
  867. * true, then leave the connection open and return.
  868. * - Otherwise, remove the connection from connection_array and from
  869. * all other lists, close it, and free it.
  870. * Returns 1 if the connection was closed, 0 otherwise.
  871. */
  872. static int
  873. conn_close_if_marked(int i)
  874. {
  875. connection_t *conn;
  876. int retval;
  877. time_t now;
  878. conn = smartlist_get(connection_array, i);
  879. if (!conn->marked_for_close)
  880. return 0; /* nothing to see here, move along */
  881. now = time(NULL);
  882. assert_connection_ok(conn, now);
  883. /* assert_all_pending_dns_resolves_ok(); */
  884. log_debug(LD_NET,"Cleaning up connection (fd "TOR_SOCKET_T_FORMAT").",
  885. conn->s);
  886. /* If the connection we are about to close was trying to connect to
  887. a proxy server and failed, the client won't be able to use that
  888. proxy. We should warn the user about this. */
  889. if (conn->proxy_state == PROXY_INFANT)
  890. log_failed_proxy_connection(conn);
  891. if ((SOCKET_OK(conn->s) || conn->linked_conn) &&
  892. connection_wants_to_flush(conn)) {
  893. /* s == -1 means it's an incomplete edge connection, or that the socket
  894. * has already been closed as unflushable. */
  895. ssize_t sz = connection_bucket_write_limit(conn, now);
  896. if (!conn->hold_open_until_flushed)
  897. log_info(LD_NET,
  898. "Conn (addr %s, fd %d, type %s, state %d) marked, but wants "
  899. "to flush %d bytes. (Marked at %s:%d)",
  900. escaped_safe_str_client(conn->address),
  901. (int)conn->s, conn_type_to_string(conn->type), conn->state,
  902. (int)conn->outbuf_flushlen,
  903. conn->marked_for_close_file, conn->marked_for_close);
  904. if (conn->linked_conn) {
  905. retval = buf_move_to_buf(conn->linked_conn->inbuf, conn->outbuf,
  906. &conn->outbuf_flushlen);
  907. if (retval >= 0) {
  908. /* The linked conn will notice that it has data when it notices that
  909. * we're gone. */
  910. connection_start_reading_from_linked_conn(conn->linked_conn);
  911. }
  912. log_debug(LD_GENERAL, "Flushed last %d bytes from a linked conn; "
  913. "%d left; flushlen %d; wants-to-flush==%d", retval,
  914. (int)connection_get_outbuf_len(conn),
  915. (int)conn->outbuf_flushlen,
  916. connection_wants_to_flush(conn));
  917. } else if (connection_speaks_cells(conn)) {
  918. if (conn->state == OR_CONN_STATE_OPEN) {
  919. retval = buf_flush_to_tls(conn->outbuf, TO_OR_CONN(conn)->tls, sz,
  920. &conn->outbuf_flushlen);
  921. } else
  922. retval = -1; /* never flush non-open broken tls connections */
  923. } else {
  924. retval = buf_flush_to_socket(conn->outbuf, conn->s, sz,
  925. &conn->outbuf_flushlen);
  926. }
  927. if (retval >= 0 && /* Technically, we could survive things like
  928. TLS_WANT_WRITE here. But don't bother for now. */
  929. conn->hold_open_until_flushed && connection_wants_to_flush(conn)) {
  930. if (retval > 0) {
  931. LOG_FN_CONN(conn, (LOG_INFO,LD_NET,
  932. "Holding conn (fd %d) open for more flushing.",
  933. (int)conn->s));
  934. conn->timestamp_last_write_allowed = now; /* reset so we can flush
  935. * more */
  936. } else if (sz == 0) {
  937. /* Also, retval==0. If we get here, we didn't want to write anything
  938. * (because of rate-limiting) and we didn't. */
  939. /* Connection must flush before closing, but it's being rate-limited.
  940. * Let's remove from Libevent, and mark it as blocked on bandwidth
  941. * so it will be re-added on next token bucket refill. Prevents
  942. * busy Libevent loops where we keep ending up here and returning
  943. * 0 until we are no longer blocked on bandwidth.
  944. */
  945. connection_consider_empty_read_buckets(conn);
  946. connection_consider_empty_write_buckets(conn);
  947. /* Make sure that consider_empty_buckets really disabled the
  948. * connection: */
  949. if (BUG(connection_is_writing(conn))) {
  950. connection_write_bw_exhausted(conn, true);
  951. }
  952. if (BUG(connection_is_reading(conn))) {
  953. /* XXXX+ We should make this code unreachable; if a connection is
  954. * marked for close and flushing, there is no point in reading to it
  955. * at all. Further, checking at this point is a bit of a hack: it
  956. * would make much more sense to react in
  957. * connection_handle_read_impl, or to just stop reading in
  958. * mark_and_flush */
  959. connection_read_bw_exhausted(conn, true/* kludge. */);
  960. }
  961. }
  962. return 0;
  963. }
  964. if (connection_wants_to_flush(conn)) {
  965. log_fn(LOG_INFO, LD_NET, "We stalled too much while trying to write %d "
  966. "bytes to address %s. If this happens a lot, either "
  967. "something is wrong with your network connection, or "
  968. "something is wrong with theirs. "
  969. "(fd %d, type %s, state %d, marked at %s:%d).",
  970. (int)connection_get_outbuf_len(conn),
  971. escaped_safe_str_client(conn->address),
  972. (int)conn->s, conn_type_to_string(conn->type), conn->state,
  973. conn->marked_for_close_file,
  974. conn->marked_for_close);
  975. }
  976. }
  977. connection_unlink(conn); /* unlink, remove, free */
  978. return 1;
  979. }
  980. /** Implementation for directory_all_unreachable. This is done in a callback,
  981. * since otherwise it would complicate Tor's control-flow graph beyond all
  982. * reason.
  983. */
  984. static void
  985. directory_all_unreachable_cb(mainloop_event_t *event, void *arg)
  986. {
  987. (void)event;
  988. (void)arg;
  989. connection_t *conn;
  990. while ((conn = connection_get_by_type_state(CONN_TYPE_AP,
  991. AP_CONN_STATE_CIRCUIT_WAIT))) {
  992. entry_connection_t *entry_conn = TO_ENTRY_CONN(conn);
  993. log_notice(LD_NET,
  994. "Is your network connection down? "
  995. "Failing connection to '%s:%d'.",
  996. safe_str_client(entry_conn->socks_request->address),
  997. entry_conn->socks_request->port);
  998. connection_mark_unattached_ap(entry_conn,
  999. END_STREAM_REASON_NET_UNREACHABLE);
  1000. }
  1001. control_event_general_error("DIR_ALL_UNREACHABLE");
  1002. }
  1003. static mainloop_event_t *directory_all_unreachable_cb_event = NULL;
  1004. /** We've just tried every dirserver we know about, and none of
  1005. * them were reachable. Assume the network is down. Change state
  1006. * so next time an application connection arrives we'll delay it
  1007. * and try another directory fetch. Kill off all the circuit_wait
  1008. * streams that are waiting now, since they will all timeout anyway.
  1009. */
  1010. void
  1011. directory_all_unreachable(time_t now)
  1012. {
  1013. (void)now;
  1014. reset_uptime(); /* reset it */
  1015. if (!directory_all_unreachable_cb_event) {
  1016. directory_all_unreachable_cb_event =
  1017. mainloop_event_new(directory_all_unreachable_cb, NULL);
  1018. tor_assert(directory_all_unreachable_cb_event);
  1019. }
  1020. mainloop_event_activate(directory_all_unreachable_cb_event);
  1021. }
  1022. /** This function is called whenever we successfully pull down some new
  1023. * network statuses or server descriptors. */
  1024. void
  1025. directory_info_has_arrived(time_t now, int from_cache, int suppress_logs)
  1026. {
  1027. const or_options_t *options = get_options();
  1028. /* if we have enough dir info, then update our guard status with
  1029. * whatever we just learned. */
  1030. int invalidate_circs = guards_update_all();
  1031. if (invalidate_circs) {
  1032. circuit_mark_all_unused_circs();
  1033. circuit_mark_all_dirty_circs_as_unusable();
  1034. }
  1035. if (!router_have_minimum_dir_info()) {
  1036. int quiet = suppress_logs || from_cache ||
  1037. directory_too_idle_to_fetch_descriptors(options, now);
  1038. tor_log(quiet ? LOG_INFO : LOG_NOTICE, LD_DIR,
  1039. "I learned some more directory information, but not enough to "
  1040. "build a circuit: %s", get_dir_info_status_string());
  1041. update_all_descriptor_downloads(now);
  1042. return;
  1043. } else {
  1044. if (directory_fetches_from_authorities(options)) {
  1045. update_all_descriptor_downloads(now);
  1046. }
  1047. /* Don't even bother trying to get extrainfo until the rest of our
  1048. * directory info is up-to-date */
  1049. if (options->DownloadExtraInfo)
  1050. update_extrainfo_downloads(now);
  1051. }
  1052. if (server_mode(options) && !net_is_disabled() && !from_cache &&
  1053. (have_completed_a_circuit() || !any_predicted_circuits(now)))
  1054. router_do_reachability_checks(1, 1);
  1055. }
  1056. /** Perform regular maintenance tasks for a single connection. This
  1057. * function gets run once per second per connection by run_scheduled_events.
  1058. */
  1059. static void
  1060. run_connection_housekeeping(int i, time_t now)
  1061. {
  1062. cell_t cell;
  1063. connection_t *conn = smartlist_get(connection_array, i);
  1064. const or_options_t *options = get_options();
  1065. or_connection_t *or_conn;
  1066. channel_t *chan = NULL;
  1067. int have_any_circuits;
  1068. int past_keepalive =
  1069. now >= conn->timestamp_last_write_allowed + options->KeepalivePeriod;
  1070. if (conn->outbuf && !connection_get_outbuf_len(conn) &&
  1071. conn->type == CONN_TYPE_OR)
  1072. TO_OR_CONN(conn)->timestamp_lastempty = now;
  1073. if (conn->marked_for_close) {
  1074. /* nothing to do here */
  1075. return;
  1076. }
  1077. /* Expire any directory connections that haven't been active (sent
  1078. * if a server or received if a client) for 5 min */
  1079. if (conn->type == CONN_TYPE_DIR &&
  1080. ((DIR_CONN_IS_SERVER(conn) &&
  1081. conn->timestamp_last_write_allowed
  1082. + options->TestingDirConnectionMaxStall < now) ||
  1083. (!DIR_CONN_IS_SERVER(conn) &&
  1084. conn->timestamp_last_read_allowed
  1085. + options->TestingDirConnectionMaxStall < now))) {
  1086. log_info(LD_DIR,"Expiring wedged directory conn (fd %d, purpose %d)",
  1087. (int)conn->s, conn->purpose);
  1088. /* This check is temporary; it's to let us know whether we should consider
  1089. * parsing partial serverdesc responses. */
  1090. if (conn->purpose == DIR_PURPOSE_FETCH_SERVERDESC &&
  1091. connection_get_inbuf_len(conn) >= 1024) {
  1092. log_info(LD_DIR,"Trying to extract information from wedged server desc "
  1093. "download.");
  1094. connection_dir_reached_eof(TO_DIR_CONN(conn));
  1095. } else {
  1096. connection_mark_for_close(conn);
  1097. }
  1098. return;
  1099. }
  1100. if (!connection_speaks_cells(conn))
  1101. return; /* we're all done here, the rest is just for OR conns */
  1102. /* If we haven't flushed to an OR connection for a while, then either nuke
  1103. the connection or send a keepalive, depending. */
  1104. or_conn = TO_OR_CONN(conn);
  1105. tor_assert(conn->outbuf);
  1106. chan = TLS_CHAN_TO_BASE(or_conn->chan);
  1107. tor_assert(chan);
  1108. if (channel_num_circuits(chan) != 0) {
  1109. have_any_circuits = 1;
  1110. chan->timestamp_last_had_circuits = now;
  1111. } else {
  1112. have_any_circuits = 0;
  1113. }
  1114. if (channel_is_bad_for_new_circs(TLS_CHAN_TO_BASE(or_conn->chan)) &&
  1115. ! have_any_circuits) {
  1116. /* It's bad for new circuits, and has no unmarked circuits on it:
  1117. * mark it now. */
  1118. log_info(LD_OR,
  1119. "Expiring non-used OR connection to fd %d (%s:%d) [Too old].",
  1120. (int)conn->s, conn->address, conn->port);
  1121. if (conn->state == OR_CONN_STATE_CONNECTING)
  1122. connection_or_connect_failed(TO_OR_CONN(conn),
  1123. END_OR_CONN_REASON_TIMEOUT,
  1124. "Tor gave up on the connection");
  1125. connection_or_close_normally(TO_OR_CONN(conn), 1);
  1126. } else if (!connection_state_is_open(conn)) {
  1127. if (past_keepalive) {
  1128. /* We never managed to actually get this connection open and happy. */
  1129. log_info(LD_OR,"Expiring non-open OR connection to fd %d (%s:%d).",
  1130. (int)conn->s,conn->address, conn->port);
  1131. connection_or_close_normally(TO_OR_CONN(conn), 0);
  1132. }
  1133. } else if (we_are_hibernating() &&
  1134. ! have_any_circuits &&
  1135. !connection_get_outbuf_len(conn)) {
  1136. /* We're hibernating or shutting down, there's no circuits, and nothing to
  1137. * flush.*/
  1138. log_info(LD_OR,"Expiring non-used OR connection to fd %d (%s:%d) "
  1139. "[Hibernating or exiting].",
  1140. (int)conn->s,conn->address, conn->port);
  1141. connection_or_close_normally(TO_OR_CONN(conn), 1);
  1142. } else if (!have_any_circuits &&
  1143. now - or_conn->idle_timeout >=
  1144. chan->timestamp_last_had_circuits) {
  1145. log_info(LD_OR,"Expiring non-used OR connection %"PRIu64" to fd %d "
  1146. "(%s:%d) [no circuits for %d; timeout %d; %scanonical].",
  1147. (chan->global_identifier),
  1148. (int)conn->s, conn->address, conn->port,
  1149. (int)(now - chan->timestamp_last_had_circuits),
  1150. or_conn->idle_timeout,
  1151. or_conn->is_canonical ? "" : "non");
  1152. connection_or_close_normally(TO_OR_CONN(conn), 0);
  1153. } else if (
  1154. now >= or_conn->timestamp_lastempty + options->KeepalivePeriod*10 &&
  1155. now >=
  1156. conn->timestamp_last_write_allowed + options->KeepalivePeriod*10) {
  1157. log_fn(LOG_PROTOCOL_WARN,LD_PROTOCOL,
  1158. "Expiring stuck OR connection to fd %d (%s:%d). (%d bytes to "
  1159. "flush; %d seconds since last write)",
  1160. (int)conn->s, conn->address, conn->port,
  1161. (int)connection_get_outbuf_len(conn),
  1162. (int)(now-conn->timestamp_last_write_allowed));
  1163. connection_or_close_normally(TO_OR_CONN(conn), 0);
  1164. } else if (past_keepalive && !connection_get_outbuf_len(conn)) {
  1165. /* send a padding cell */
  1166. log_fn(LOG_DEBUG,LD_OR,"Sending keepalive to (%s:%d)",
  1167. conn->address, conn->port);
  1168. memset(&cell,0,sizeof(cell_t));
  1169. cell.command = CELL_PADDING;
  1170. connection_or_write_cell_to_buf(&cell, or_conn);
  1171. } else {
  1172. channelpadding_decide_to_pad_channel(chan);
  1173. }
  1174. }
  1175. /** Honor a NEWNYM request: make future requests unlinkable to past
  1176. * requests. */
  1177. static void
  1178. signewnym_impl(time_t now)
  1179. {
  1180. const or_options_t *options = get_options();
  1181. if (!proxy_mode(options)) {
  1182. log_info(LD_CONTROL, "Ignoring SIGNAL NEWNYM because client functionality "
  1183. "is disabled.");
  1184. return;
  1185. }
  1186. circuit_mark_all_dirty_circs_as_unusable();
  1187. addressmap_clear_transient();
  1188. hs_client_purge_state();
  1189. time_of_last_signewnym = now;
  1190. signewnym_is_pending = 0;
  1191. ++newnym_epoch;
  1192. control_event_signal(SIGNEWNYM);
  1193. }
  1194. /** Callback: run a deferred signewnym. */
  1195. static void
  1196. handle_deferred_signewnym_cb(mainloop_event_t *event, void *arg)
  1197. {
  1198. (void)event;
  1199. (void)arg;
  1200. log_info(LD_CONTROL, "Honoring delayed NEWNYM request");
  1201. signewnym_impl(time(NULL));
  1202. }
  1203. /** Return the number of times that signewnym has been called. */
  1204. unsigned
  1205. get_signewnym_epoch(void)
  1206. {
  1207. return newnym_epoch;
  1208. }
  1209. /** True iff we have initialized all the members of <b>periodic_events</b>.
  1210. * Used to prevent double-initialization. */
  1211. static int periodic_events_initialized = 0;
  1212. /* Declare all the timer callback functions... */
  1213. #undef CALLBACK
  1214. #define CALLBACK(name) \
  1215. static int name ## _callback(time_t, const or_options_t *)
  1216. CALLBACK(add_entropy);
  1217. CALLBACK(check_authority_cert);
  1218. CALLBACK(check_canonical_channels);
  1219. CALLBACK(check_descriptor);
  1220. CALLBACK(check_dns_honesty);
  1221. CALLBACK(check_ed_keys);
  1222. CALLBACK(check_expired_networkstatus);
  1223. CALLBACK(check_for_reachability_bw);
  1224. CALLBACK(check_onion_keys_expiry_time);
  1225. CALLBACK(clean_caches);
  1226. CALLBACK(clean_consdiffmgr);
  1227. CALLBACK(dirvote);
  1228. CALLBACK(downrate_stability);
  1229. CALLBACK(expire_old_ciruits_serverside);
  1230. CALLBACK(fetch_networkstatus);
  1231. CALLBACK(heartbeat);
  1232. CALLBACK(hs_service);
  1233. CALLBACK(launch_descriptor_fetches);
  1234. CALLBACK(launch_reachability_tests);
  1235. CALLBACK(reachability_warnings);
  1236. CALLBACK(record_bridge_stats);
  1237. CALLBACK(rend_cache_failure_clean);
  1238. CALLBACK(reset_padding_counts);
  1239. CALLBACK(retry_dns);
  1240. CALLBACK(retry_listeners);
  1241. CALLBACK(rotate_onion_key);
  1242. CALLBACK(rotate_x509_certificate);
  1243. CALLBACK(save_stability);
  1244. CALLBACK(save_state);
  1245. CALLBACK(write_bridge_ns);
  1246. CALLBACK(write_stats_file);
  1247. #undef CALLBACK
  1248. /* Now we declare an array of periodic_event_item_t for each periodic event */
  1249. #define CALLBACK(name, r, f) PERIODIC_EVENT(name, r, f)
  1250. STATIC periodic_event_item_t periodic_events[] = {
  1251. /* Everyone needs to run those. */
  1252. CALLBACK(add_entropy, PERIODIC_EVENT_ROLE_ALL, 0),
  1253. CALLBACK(check_expired_networkstatus, PERIODIC_EVENT_ROLE_ALL, 0),
  1254. CALLBACK(clean_caches, PERIODIC_EVENT_ROLE_ALL, 0),
  1255. CALLBACK(fetch_networkstatus, PERIODIC_EVENT_ROLE_ALL,
  1256. PERIODIC_EVENT_FLAG_NEED_NET),
  1257. CALLBACK(heartbeat, PERIODIC_EVENT_ROLE_ALL, 0),
  1258. CALLBACK(launch_descriptor_fetches, PERIODIC_EVENT_ROLE_ALL,
  1259. PERIODIC_EVENT_FLAG_NEED_NET),
  1260. CALLBACK(reset_padding_counts, PERIODIC_EVENT_ROLE_ALL, 0),
  1261. CALLBACK(retry_listeners, PERIODIC_EVENT_ROLE_ALL,
  1262. PERIODIC_EVENT_FLAG_NEED_NET),
  1263. CALLBACK(save_state, PERIODIC_EVENT_ROLE_ALL, 0),
  1264. CALLBACK(rotate_x509_certificate, PERIODIC_EVENT_ROLE_ALL, 0),
  1265. CALLBACK(write_stats_file, PERIODIC_EVENT_ROLE_ALL, 0),
  1266. /* Routers (bridge and relay) only. */
  1267. CALLBACK(check_descriptor, PERIODIC_EVENT_ROLE_ROUTER,
  1268. PERIODIC_EVENT_FLAG_NEED_NET),
  1269. CALLBACK(check_ed_keys, PERIODIC_EVENT_ROLE_ROUTER, 0),
  1270. CALLBACK(check_for_reachability_bw, PERIODIC_EVENT_ROLE_ROUTER,
  1271. PERIODIC_EVENT_FLAG_NEED_NET),
  1272. CALLBACK(check_onion_keys_expiry_time, PERIODIC_EVENT_ROLE_ROUTER, 0),
  1273. CALLBACK(expire_old_ciruits_serverside, PERIODIC_EVENT_ROLE_ROUTER,
  1274. PERIODIC_EVENT_FLAG_NEED_NET),
  1275. CALLBACK(reachability_warnings, PERIODIC_EVENT_ROLE_ROUTER,
  1276. PERIODIC_EVENT_FLAG_NEED_NET),
  1277. CALLBACK(retry_dns, PERIODIC_EVENT_ROLE_ROUTER, 0),
  1278. CALLBACK(rotate_onion_key, PERIODIC_EVENT_ROLE_ROUTER, 0),
  1279. /* Authorities (bridge and directory) only. */
  1280. CALLBACK(downrate_stability, PERIODIC_EVENT_ROLE_AUTHORITIES, 0),
  1281. CALLBACK(launch_reachability_tests, PERIODIC_EVENT_ROLE_AUTHORITIES,
  1282. PERIODIC_EVENT_FLAG_NEED_NET),
  1283. CALLBACK(save_stability, PERIODIC_EVENT_ROLE_AUTHORITIES, 0),
  1284. /* Directory authority only. */
  1285. CALLBACK(check_authority_cert, PERIODIC_EVENT_ROLE_DIRAUTH, 0),
  1286. CALLBACK(dirvote, PERIODIC_EVENT_ROLE_DIRAUTH, PERIODIC_EVENT_FLAG_NEED_NET),
  1287. /* Relay only. */
  1288. CALLBACK(check_canonical_channels, PERIODIC_EVENT_ROLE_RELAY,
  1289. PERIODIC_EVENT_FLAG_NEED_NET),
  1290. CALLBACK(check_dns_honesty, PERIODIC_EVENT_ROLE_RELAY,
  1291. PERIODIC_EVENT_FLAG_NEED_NET),
  1292. /* Hidden Service service only. */
  1293. CALLBACK(hs_service, PERIODIC_EVENT_ROLE_HS_SERVICE,
  1294. PERIODIC_EVENT_FLAG_NEED_NET),
  1295. /* Bridge only. */
  1296. CALLBACK(record_bridge_stats, PERIODIC_EVENT_ROLE_BRIDGE, 0),
  1297. /* Client only. */
  1298. CALLBACK(rend_cache_failure_clean, PERIODIC_EVENT_ROLE_CLIENT, 0),
  1299. /* Bridge Authority only. */
  1300. CALLBACK(write_bridge_ns, PERIODIC_EVENT_ROLE_BRIDGEAUTH, 0),
  1301. /* Directory server only. */
  1302. CALLBACK(clean_consdiffmgr, PERIODIC_EVENT_ROLE_DIRSERVER, 0),
  1303. END_OF_PERIODIC_EVENTS
  1304. };
  1305. #undef CALLBACK
  1306. /* These are pointers to members of periodic_events[] that are used to
  1307. * implement particular callbacks. We keep them separate here so that we
  1308. * can access them by name. We also keep them inside periodic_events[]
  1309. * so that we can implement "reset all timers" in a reasonable way. */
  1310. static periodic_event_item_t *check_descriptor_event=NULL;
  1311. static periodic_event_item_t *dirvote_event=NULL;
  1312. static periodic_event_item_t *fetch_networkstatus_event=NULL;
  1313. static periodic_event_item_t *launch_descriptor_fetches_event=NULL;
  1314. static periodic_event_item_t *check_dns_honesty_event=NULL;
  1315. static periodic_event_item_t *save_state_event=NULL;
  1316. /** Reset all the periodic events so we'll do all our actions again as if we
  1317. * just started up.
  1318. * Useful if our clock just moved back a long time from the future,
  1319. * so we don't wait until that future arrives again before acting.
  1320. */
  1321. void
  1322. reset_all_main_loop_timers(void)
  1323. {
  1324. int i;
  1325. for (i = 0; periodic_events[i].name; ++i) {
  1326. periodic_event_reschedule(&periodic_events[i]);
  1327. }
  1328. }
  1329. /** Return the member of periodic_events[] whose name is <b>name</b>.
  1330. * Return NULL if no such event is found.
  1331. */
  1332. static periodic_event_item_t *
  1333. find_periodic_event(const char *name)
  1334. {
  1335. int i;
  1336. for (i = 0; periodic_events[i].name; ++i) {
  1337. if (strcmp(name, periodic_events[i].name) == 0)
  1338. return &periodic_events[i];
  1339. }
  1340. return NULL;
  1341. }
  1342. /** Return a bitmask of the roles this tor instance is configured for using
  1343. * the given options. */
  1344. STATIC int
  1345. get_my_roles(const or_options_t *options)
  1346. {
  1347. tor_assert(options);
  1348. int roles = 0;
  1349. int is_bridge = options->BridgeRelay;
  1350. int is_client = options_any_client_port_set(options);
  1351. int is_relay = server_mode(options);
  1352. int is_dirauth = authdir_mode_v3(options);
  1353. int is_bridgeauth = authdir_mode_bridge(options);
  1354. int is_hidden_service = !!hs_service_get_num_services() ||
  1355. !!rend_num_services();
  1356. int is_dirserver = dir_server_mode(options);
  1357. if (is_bridge) roles |= PERIODIC_EVENT_ROLE_BRIDGE;
  1358. if (is_client) roles |= PERIODIC_EVENT_ROLE_CLIENT;
  1359. if (is_relay) roles |= PERIODIC_EVENT_ROLE_RELAY;
  1360. if (is_dirauth) roles |= PERIODIC_EVENT_ROLE_DIRAUTH;
  1361. if (is_bridgeauth) roles |= PERIODIC_EVENT_ROLE_BRIDGEAUTH;
  1362. if (is_hidden_service) roles |= PERIODIC_EVENT_ROLE_HS_SERVICE;
  1363. if (is_dirserver) roles |= PERIODIC_EVENT_ROLE_DIRSERVER;
  1364. return roles;
  1365. }
  1366. /** Event to run initialize_periodic_events_cb */
  1367. static struct event *initialize_periodic_events_event = NULL;
  1368. /** Helper, run one second after setup:
  1369. * Initializes all members of periodic_events and starts them running.
  1370. *
  1371. * (We do this one second after setup for backward-compatibility reasons;
  1372. * it might not actually be necessary.) */
  1373. static void
  1374. initialize_periodic_events_cb(evutil_socket_t fd, short events, void *data)
  1375. {
  1376. (void) fd;
  1377. (void) events;
  1378. (void) data;
  1379. tor_event_free(initialize_periodic_events_event);
  1380. rescan_periodic_events(get_options());
  1381. }
  1382. /** Set up all the members of periodic_events[], and configure them all to be
  1383. * launched from a callback. */
  1384. STATIC void
  1385. initialize_periodic_events(void)
  1386. {
  1387. tor_assert(periodic_events_initialized == 0);
  1388. periodic_events_initialized = 1;
  1389. /* Set up all periodic events. We'll launch them by roles. */
  1390. int i;
  1391. for (i = 0; periodic_events[i].name; ++i) {
  1392. periodic_event_setup(&periodic_events[i]);
  1393. }
  1394. #define NAMED_CALLBACK(name) \
  1395. STMT_BEGIN name ## _event = find_periodic_event( #name ); STMT_END
  1396. NAMED_CALLBACK(check_descriptor);
  1397. NAMED_CALLBACK(dirvote);
  1398. NAMED_CALLBACK(fetch_networkstatus);
  1399. NAMED_CALLBACK(launch_descriptor_fetches);
  1400. NAMED_CALLBACK(check_dns_honesty);
  1401. NAMED_CALLBACK(save_state);
  1402. struct timeval one_second = { 1, 0 };
  1403. initialize_periodic_events_event = tor_evtimer_new(
  1404. tor_libevent_get_base(),
  1405. initialize_periodic_events_cb, NULL);
  1406. event_add(initialize_periodic_events_event, &one_second);
  1407. }
  1408. STATIC void
  1409. teardown_periodic_events(void)
  1410. {
  1411. int i;
  1412. for (i = 0; periodic_events[i].name; ++i) {
  1413. periodic_event_destroy(&periodic_events[i]);
  1414. }
  1415. periodic_events_initialized = 0;
  1416. }
  1417. /** Do a pass at all our periodic events, disable those we don't need anymore
  1418. * and enable those we need now using the given options. */
  1419. void
  1420. rescan_periodic_events(const or_options_t *options)
  1421. {
  1422. tor_assert(options);
  1423. /* Avoid scanning the event list if we haven't initialized it yet. This is
  1424. * particularly useful for unit tests in order to avoid initializing main
  1425. * loop events everytime. */
  1426. if (!periodic_events_initialized) {
  1427. return;
  1428. }
  1429. int roles = get_my_roles(options);
  1430. for (int i = 0; periodic_events[i].name; ++i) {
  1431. periodic_event_item_t *item = &periodic_events[i];
  1432. /* Handle the event flags. */
  1433. if (net_is_disabled() &&
  1434. (item->flags & PERIODIC_EVENT_FLAG_NEED_NET)) {
  1435. continue;
  1436. }
  1437. /* Enable the event if needed. It is safe to enable an event that was
  1438. * already enabled. Same goes for disabling it. */
  1439. if (item->roles & roles) {
  1440. log_debug(LD_GENERAL, "Launching periodic event %s", item->name);
  1441. periodic_event_enable(item);
  1442. } else {
  1443. log_debug(LD_GENERAL, "Disabling periodic event %s", item->name);
  1444. periodic_event_disable(item);
  1445. }
  1446. }
  1447. }
  1448. /* We just got new options globally set, see if we need to enabled or disable
  1449. * periodic events. */
  1450. void
  1451. periodic_events_on_new_options(const or_options_t *options)
  1452. {
  1453. /* Only if we've already initialized the events, rescan the list which will
  1454. * enable or disable events depending on our roles. This will be called at
  1455. * bootup and we don't want this function to initialize the events because
  1456. * they aren't set up at this stage. */
  1457. if (periodic_events_initialized) {
  1458. rescan_periodic_events(options);
  1459. }
  1460. }
  1461. /**
  1462. * Update our schedule so that we'll check whether we need to update our
  1463. * descriptor immediately, rather than after up to CHECK_DESCRIPTOR_INTERVAL
  1464. * seconds.
  1465. */
  1466. void
  1467. reschedule_descriptor_update_check(void)
  1468. {
  1469. if (check_descriptor_event) {
  1470. periodic_event_reschedule(check_descriptor_event);
  1471. }
  1472. }
  1473. /**
  1474. * Update our schedule so that we'll check whether we need to fetch directory
  1475. * info immediately.
  1476. */
  1477. void
  1478. reschedule_directory_downloads(void)
  1479. {
  1480. tor_assert(fetch_networkstatus_event);
  1481. tor_assert(launch_descriptor_fetches_event);
  1482. periodic_event_reschedule(fetch_networkstatus_event);
  1483. periodic_event_reschedule(launch_descriptor_fetches_event);
  1484. }
  1485. /** Mainloop callback: clean up circuits, channels, and connections
  1486. * that are pending close. */
  1487. static void
  1488. postloop_cleanup_cb(mainloop_event_t *ev, void *arg)
  1489. {
  1490. (void)ev;
  1491. (void)arg;
  1492. circuit_close_all_marked();
  1493. close_closeable_connections();
  1494. channel_run_cleanup();
  1495. channel_listener_run_cleanup();
  1496. }
  1497. /** Event to run postloop_cleanup_cb */
  1498. static mainloop_event_t *postloop_cleanup_ev=NULL;
  1499. /** Schedule a post-loop event to clean up marked channels, connections, and
  1500. * circuits. */
  1501. void
  1502. mainloop_schedule_postloop_cleanup(void)
  1503. {
  1504. if (PREDICT_UNLIKELY(postloop_cleanup_ev == NULL)) {
  1505. // (It's possible that we can get here if we decide to close a connection
  1506. // in the earliest stages of our configuration, before we create events.)
  1507. return;
  1508. }
  1509. mainloop_event_activate(postloop_cleanup_ev);
  1510. }
  1511. #define LONGEST_TIMER_PERIOD (30 * 86400)
  1512. /** Helper: Return the number of seconds between <b>now</b> and <b>next</b>,
  1513. * clipped to the range [1 second, LONGEST_TIMER_PERIOD]. */
  1514. static inline int
  1515. safe_timer_diff(time_t now, time_t next)
  1516. {
  1517. if (next > now) {
  1518. /* There were no computers at signed TIME_MIN (1902 on 32-bit systems),
  1519. * and nothing that could run Tor. It's a bug if 'next' is around then.
  1520. * On 64-bit systems with signed TIME_MIN, TIME_MIN is before the Big
  1521. * Bang. We cannot extrapolate past a singularity, but there was probably
  1522. * nothing that could run Tor then, either.
  1523. **/
  1524. tor_assert(next > TIME_MIN + LONGEST_TIMER_PERIOD);
  1525. if (next - LONGEST_TIMER_PERIOD > now)
  1526. return LONGEST_TIMER_PERIOD;
  1527. return (int)(next - now);
  1528. } else {
  1529. return 1;
  1530. }
  1531. }
  1532. /** Perform regular maintenance tasks. This function gets run once per
  1533. * second by second_elapsed_callback().
  1534. */
  1535. static void
  1536. run_scheduled_events(time_t now)
  1537. {
  1538. const or_options_t *options = get_options();
  1539. /* 0. See if we've been asked to shut down and our timeout has
  1540. * expired; or if our bandwidth limits are exhausted and we
  1541. * should hibernate; or if it's time to wake up from hibernation.
  1542. */
  1543. consider_hibernation(now);
  1544. /* Maybe enough time elapsed for us to reconsider a circuit. */
  1545. circuit_upgrade_circuits_from_guard_wait();
  1546. if (options->UseBridges && !net_is_disabled()) {
  1547. /* Note: this check uses net_is_disabled(), not should_delay_dir_fetches()
  1548. * -- the latter is only for fetching consensus-derived directory info. */
  1549. fetch_bridge_descriptors(options, now);
  1550. }
  1551. if (accounting_is_enabled(options)) {
  1552. accounting_run_housekeeping(now);
  1553. }
  1554. /* 3a. Every second, we examine pending circuits and prune the
  1555. * ones which have been pending for more than a few seconds.
  1556. * We do this before step 4, so it can try building more if
  1557. * it's not comfortable with the number of available circuits.
  1558. */
  1559. /* (If our circuit build timeout can ever become lower than a second (which
  1560. * it can't, currently), we should do this more often.) */
  1561. circuit_expire_building();
  1562. circuit_expire_waiting_for_better_guard();
  1563. /* 3b. Also look at pending streams and prune the ones that 'began'
  1564. * a long time ago but haven't gotten a 'connected' yet.
  1565. * Do this before step 4, so we can put them back into pending
  1566. * state to be picked up by the new circuit.
  1567. */
  1568. connection_ap_expire_beginning();
  1569. /* 3c. And expire connections that we've held open for too long.
  1570. */
  1571. connection_expire_held_open();
  1572. /* 4. Every second, we try a new circuit if there are no valid
  1573. * circuits. Every NewCircuitPeriod seconds, we expire circuits
  1574. * that became dirty more than MaxCircuitDirtiness seconds ago,
  1575. * and we make a new circ if there are no clean circuits.
  1576. */
  1577. const int have_dir_info = router_have_minimum_dir_info();
  1578. if (have_dir_info && !net_is_disabled()) {
  1579. circuit_build_needed_circs(now);
  1580. } else {
  1581. circuit_expire_old_circs_as_needed(now);
  1582. }
  1583. /* 5. We do housekeeping for each connection... */
  1584. channel_update_bad_for_new_circs(NULL, 0);
  1585. int i;
  1586. for (i=0;i<smartlist_len(connection_array);i++) {
  1587. run_connection_housekeeping(i, now);
  1588. }
  1589. /* 11b. check pending unconfigured managed proxies */
  1590. if (!net_is_disabled() && pt_proxies_configuration_pending())
  1591. pt_configure_remaining_proxies();
  1592. }
  1593. /* Periodic callback: rotate the onion keys after the period defined by the
  1594. * "onion-key-rotation-days" consensus parameter, shut down and restart all
  1595. * cpuworkers, and update our descriptor if necessary.
  1596. */
  1597. static int
  1598. rotate_onion_key_callback(time_t now, const or_options_t *options)
  1599. {
  1600. if (server_mode(options)) {
  1601. int onion_key_lifetime = get_onion_key_lifetime();
  1602. time_t rotation_time = get_onion_key_set_at()+onion_key_lifetime;
  1603. if (rotation_time > now) {
  1604. return ONION_KEY_CONSENSUS_CHECK_INTERVAL;
  1605. }
  1606. log_info(LD_GENERAL,"Rotating onion key.");
  1607. rotate_onion_key();
  1608. cpuworkers_rotate_keyinfo();
  1609. if (router_rebuild_descriptor(1)<0) {
  1610. log_info(LD_CONFIG, "Couldn't rebuild router descriptor");
  1611. }
  1612. if (advertised_server_mode() && !net_is_disabled())
  1613. router_upload_dir_desc_to_dirservers(0);
  1614. return ONION_KEY_CONSENSUS_CHECK_INTERVAL;
  1615. }
  1616. return PERIODIC_EVENT_NO_UPDATE;
  1617. }
  1618. /* Period callback: Check if our old onion keys are still valid after the
  1619. * period of time defined by the consensus parameter
  1620. * "onion-key-grace-period-days", otherwise expire them by setting them to
  1621. * NULL.
  1622. */
  1623. static int
  1624. check_onion_keys_expiry_time_callback(time_t now, const or_options_t *options)
  1625. {
  1626. if (server_mode(options)) {
  1627. int onion_key_grace_period = get_onion_key_grace_period();
  1628. time_t expiry_time = get_onion_key_set_at()+onion_key_grace_period;
  1629. if (expiry_time > now) {
  1630. return ONION_KEY_CONSENSUS_CHECK_INTERVAL;
  1631. }
  1632. log_info(LD_GENERAL, "Expiring old onion keys.");
  1633. expire_old_onion_keys();
  1634. cpuworkers_rotate_keyinfo();
  1635. return ONION_KEY_CONSENSUS_CHECK_INTERVAL;
  1636. }
  1637. return PERIODIC_EVENT_NO_UPDATE;
  1638. }
  1639. /* Periodic callback: Every 30 seconds, check whether it's time to make new
  1640. * Ed25519 subkeys.
  1641. */
  1642. static int
  1643. check_ed_keys_callback(time_t now, const or_options_t *options)
  1644. {
  1645. if (server_mode(options)) {
  1646. if (should_make_new_ed_keys(options, now)) {
  1647. int new_signing_key = load_ed_keys(options, now);
  1648. if (new_signing_key < 0 ||
  1649. generate_ed_link_cert(options, now, new_signing_key > 0)) {
  1650. log_err(LD_OR, "Unable to update Ed25519 keys! Exiting.");
  1651. tor_shutdown_event_loop_and_exit(1);
  1652. }
  1653. }
  1654. return 30;
  1655. }
  1656. return PERIODIC_EVENT_NO_UPDATE;
  1657. }
  1658. /**
  1659. * Periodic callback: Every {LAZY,GREEDY}_DESCRIPTOR_RETRY_INTERVAL,
  1660. * see about fetching descriptors, microdescriptors, and extrainfo
  1661. * documents.
  1662. */
  1663. static int
  1664. launch_descriptor_fetches_callback(time_t now, const or_options_t *options)
  1665. {
  1666. if (should_delay_dir_fetches(options, NULL))
  1667. return PERIODIC_EVENT_NO_UPDATE;
  1668. update_all_descriptor_downloads(now);
  1669. update_extrainfo_downloads(now);
  1670. if (router_have_minimum_dir_info())
  1671. return LAZY_DESCRIPTOR_RETRY_INTERVAL;
  1672. else
  1673. return GREEDY_DESCRIPTOR_RETRY_INTERVAL;
  1674. }
  1675. /**
  1676. * Periodic event: Rotate our X.509 certificates and TLS keys once every
  1677. * MAX_SSL_KEY_LIFETIME_INTERNAL.
  1678. */
  1679. static int
  1680. rotate_x509_certificate_callback(time_t now, const or_options_t *options)
  1681. {
  1682. static int first = 1;
  1683. (void)now;
  1684. (void)options;
  1685. if (first) {
  1686. first = 0;
  1687. return MAX_SSL_KEY_LIFETIME_INTERNAL;
  1688. }
  1689. /* 1b. Every MAX_SSL_KEY_LIFETIME_INTERNAL seconds, we change our
  1690. * TLS context. */
  1691. log_info(LD_GENERAL,"Rotating tls context.");
  1692. if (router_initialize_tls_context() < 0) {
  1693. log_err(LD_BUG, "Error reinitializing TLS context");
  1694. tor_assert_unreached();
  1695. }
  1696. if (generate_ed_link_cert(options, now, 1)) {
  1697. log_err(LD_OR, "Unable to update Ed25519->TLS link certificate for "
  1698. "new TLS context.");
  1699. tor_assert_unreached();
  1700. }
  1701. /* We also make sure to rotate the TLS connections themselves if they've
  1702. * been up for too long -- but that's done via is_bad_for_new_circs in
  1703. * run_connection_housekeeping() above. */
  1704. return MAX_SSL_KEY_LIFETIME_INTERNAL;
  1705. }
  1706. /**
  1707. * Periodic callback: once an hour, grab some more entropy from the
  1708. * kernel and feed it to our CSPRNG.
  1709. **/
  1710. static int
  1711. add_entropy_callback(time_t now, const or_options_t *options)
  1712. {
  1713. (void)now;
  1714. (void)options;
  1715. /* We already seeded once, so don't die on failure. */
  1716. if (crypto_seed_rng() < 0) {
  1717. log_warn(LD_GENERAL, "Tried to re-seed RNG, but failed. We already "
  1718. "seeded once, though, so we won't exit here.");
  1719. }
  1720. /** How often do we add more entropy to OpenSSL's RNG pool? */
  1721. #define ENTROPY_INTERVAL (60*60)
  1722. return ENTROPY_INTERVAL;
  1723. }
  1724. /**
  1725. * Periodic callback: if we're an authority, make sure we test
  1726. * the routers on the network for reachability.
  1727. */
  1728. static int
  1729. launch_reachability_tests_callback(time_t now, const or_options_t *options)
  1730. {
  1731. if (authdir_mode_tests_reachability(options) &&
  1732. !net_is_disabled()) {
  1733. /* try to determine reachability of the other Tor relays */
  1734. dirserv_test_reachability(now);
  1735. }
  1736. return REACHABILITY_TEST_INTERVAL;
  1737. }
  1738. /**
  1739. * Periodic callback: if we're an authority, discount the stability
  1740. * information (and other rephist information) that's older.
  1741. */
  1742. static int
  1743. downrate_stability_callback(time_t now, const or_options_t *options)
  1744. {
  1745. (void)options;
  1746. /* 1d. Periodically, we discount older stability information so that new
  1747. * stability info counts more, and save the stability information to disk as
  1748. * appropriate. */
  1749. time_t next = rep_hist_downrate_old_runs(now);
  1750. return safe_timer_diff(now, next);
  1751. }
  1752. /**
  1753. * Periodic callback: if we're an authority, record our measured stability
  1754. * information from rephist in an mtbf file.
  1755. */
  1756. static int
  1757. save_stability_callback(time_t now, const or_options_t *options)
  1758. {
  1759. if (authdir_mode_tests_reachability(options)) {
  1760. if (rep_hist_record_mtbf_data(now, 1)<0) {
  1761. log_warn(LD_GENERAL, "Couldn't store mtbf data.");
  1762. }
  1763. }
  1764. #define SAVE_STABILITY_INTERVAL (30*60)
  1765. return SAVE_STABILITY_INTERVAL;
  1766. }
  1767. /**
  1768. * Periodic callback: if we're an authority, check on our authority
  1769. * certificate (the one that authenticates our authority signing key).
  1770. */
  1771. static int
  1772. check_authority_cert_callback(time_t now, const or_options_t *options)
  1773. {
  1774. (void)now;
  1775. (void)options;
  1776. /* 1e. Periodically, if we're a v3 authority, we check whether our cert is
  1777. * close to expiring and warn the admin if it is. */
  1778. v3_authority_check_key_expiry();
  1779. #define CHECK_V3_CERTIFICATE_INTERVAL (5*60)
  1780. return CHECK_V3_CERTIFICATE_INTERVAL;
  1781. }
  1782. /**
  1783. * Scheduled callback: Run directory-authority voting functionality.
  1784. *
  1785. * The schedule is a bit complicated here, so dirvote_act() manages the
  1786. * schedule itself.
  1787. **/
  1788. static int
  1789. dirvote_callback(time_t now, const or_options_t *options)
  1790. {
  1791. if (!authdir_mode_v3(options)) {
  1792. tor_assert_nonfatal_unreached();
  1793. return 3600;
  1794. }
  1795. time_t next = dirvote_act(options, now);
  1796. if (BUG(next == TIME_MAX)) {
  1797. /* This shouldn't be returned unless we called dirvote_act() without
  1798. * being an authority. If it happens, maybe our configuration will
  1799. * fix itself in an hour or so? */
  1800. return 3600;
  1801. }
  1802. return safe_timer_diff(now, next);
  1803. }
  1804. /** Reschedule the directory-authority voting event. Run this whenever the
  1805. * schedule has changed. */
  1806. void
  1807. reschedule_dirvote(const or_options_t *options)
  1808. {
  1809. if (periodic_events_initialized && authdir_mode_v3(options)) {
  1810. periodic_event_reschedule(dirvote_event);
  1811. }
  1812. }
  1813. /**
  1814. * Periodic callback: If our consensus is too old, recalculate whether
  1815. * we can actually use it.
  1816. */
  1817. static int
  1818. check_expired_networkstatus_callback(time_t now, const or_options_t *options)
  1819. {
  1820. (void)options;
  1821. /* Check whether our networkstatus has expired. */
  1822. networkstatus_t *ns = networkstatus_get_latest_consensus();
  1823. /*XXXX RD: This value needs to be the same as REASONABLY_LIVE_TIME in
  1824. * networkstatus_get_reasonably_live_consensus(), but that value is way
  1825. * way too high. Arma: is the bridge issue there resolved yet? -NM */
  1826. #define NS_EXPIRY_SLOP (24*60*60)
  1827. if (ns && ns->valid_until < (now - NS_EXPIRY_SLOP) &&
  1828. router_have_minimum_dir_info()) {
  1829. router_dir_info_changed();
  1830. }
  1831. #define CHECK_EXPIRED_NS_INTERVAL (2*60)
  1832. return CHECK_EXPIRED_NS_INTERVAL;
  1833. }
  1834. /**
  1835. * Scheduled callback: Save the state file to disk if appropriate.
  1836. */
  1837. static int
  1838. save_state_callback(time_t now, const or_options_t *options)
  1839. {
  1840. (void) options;
  1841. (void) or_state_save(now); // only saves if appropriate
  1842. const time_t next_write = get_or_state()->next_write;
  1843. if (next_write == TIME_MAX) {
  1844. return 86400;
  1845. }
  1846. return safe_timer_diff(now, next_write);
  1847. }
  1848. /** Reschedule the event for saving the state file.
  1849. *
  1850. * Run this when the state becomes dirty. */
  1851. void
  1852. reschedule_or_state_save(void)
  1853. {
  1854. if (save_state_event == NULL) {
  1855. /* This can happen early on during startup. */
  1856. return;
  1857. }
  1858. periodic_event_reschedule(save_state_event);
  1859. }
  1860. /**
  1861. * Periodic callback: Write statistics to disk if appropriate.
  1862. */
  1863. static int
  1864. write_stats_file_callback(time_t now, const or_options_t *options)
  1865. {
  1866. /* 1g. Check whether we should write statistics to disk.
  1867. */
  1868. #define CHECK_WRITE_STATS_INTERVAL (60*60)
  1869. time_t next_time_to_write_stats_files = now + CHECK_WRITE_STATS_INTERVAL;
  1870. if (options->CellStatistics) {
  1871. time_t next_write =
  1872. rep_hist_buffer_stats_write(now);
  1873. if (next_write && next_write < next_time_to_write_stats_files)
  1874. next_time_to_write_stats_files = next_write;
  1875. }
  1876. if (options->DirReqStatistics) {
  1877. time_t next_write = geoip_dirreq_stats_write(now);
  1878. if (next_write && next_write < next_time_to_write_stats_files)
  1879. next_time_to_write_stats_files = next_write;
  1880. }
  1881. if (options->EntryStatistics) {
  1882. time_t next_write = geoip_entry_stats_write(now);
  1883. if (next_write && next_write < next_time_to_write_stats_files)
  1884. next_time_to_write_stats_files = next_write;
  1885. }
  1886. if (options->HiddenServiceStatistics) {
  1887. time_t next_write = rep_hist_hs_stats_write(now);
  1888. if (next_write && next_write < next_time_to_write_stats_files)
  1889. next_time_to_write_stats_files = next_write;
  1890. }
  1891. if (options->ExitPortStatistics) {
  1892. time_t next_write = rep_hist_exit_stats_write(now);
  1893. if (next_write && next_write < next_time_to_write_stats_files)
  1894. next_time_to_write_stats_files = next_write;
  1895. }
  1896. if (options->ConnDirectionStatistics) {
  1897. time_t next_write = rep_hist_conn_stats_write(now);
  1898. if (next_write && next_write < next_time_to_write_stats_files)
  1899. next_time_to_write_stats_files = next_write;
  1900. }
  1901. if (options->BridgeAuthoritativeDir) {
  1902. time_t next_write = rep_hist_desc_stats_write(now);
  1903. if (next_write && next_write < next_time_to_write_stats_files)
  1904. next_time_to_write_stats_files = next_write;
  1905. }
  1906. return safe_timer_diff(now, next_time_to_write_stats_files);
  1907. }
  1908. #define CHANNEL_CHECK_INTERVAL (60*60)
  1909. static int
  1910. check_canonical_channels_callback(time_t now, const or_options_t *options)
  1911. {
  1912. (void)now;
  1913. if (public_server_mode(options))
  1914. channel_check_for_duplicates();
  1915. return CHANNEL_CHECK_INTERVAL;
  1916. }
  1917. static int
  1918. reset_padding_counts_callback(time_t now, const or_options_t *options)
  1919. {
  1920. if (options->PaddingStatistics) {
  1921. rep_hist_prep_published_padding_counts(now);
  1922. }
  1923. rep_hist_reset_padding_counts();
  1924. return REPHIST_CELL_PADDING_COUNTS_INTERVAL;
  1925. }
  1926. static int should_init_bridge_stats = 1;
  1927. /**
  1928. * Periodic callback: Write bridge statistics to disk if appropriate.
  1929. */
  1930. static int
  1931. record_bridge_stats_callback(time_t now, const or_options_t *options)
  1932. {
  1933. /* 1h. Check whether we should write bridge statistics to disk.
  1934. */
  1935. if (should_record_bridge_info(options)) {
  1936. if (should_init_bridge_stats) {
  1937. /* (Re-)initialize bridge statistics. */
  1938. geoip_bridge_stats_init(now);
  1939. should_init_bridge_stats = 0;
  1940. return WRITE_STATS_INTERVAL;
  1941. } else {
  1942. /* Possibly write bridge statistics to disk and ask when to write
  1943. * them next time. */
  1944. time_t next = geoip_bridge_stats_write(now);
  1945. return safe_timer_diff(now, next);
  1946. }
  1947. } else if (!should_init_bridge_stats) {
  1948. /* Bridge mode was turned off. Ensure that stats are re-initialized
  1949. * next time bridge mode is turned on. */
  1950. should_init_bridge_stats = 1;
  1951. }
  1952. return PERIODIC_EVENT_NO_UPDATE;
  1953. }
  1954. /**
  1955. * Periodic callback: Clean in-memory caches every once in a while
  1956. */
  1957. static int
  1958. clean_caches_callback(time_t now, const or_options_t *options)
  1959. {
  1960. /* Remove old information from rephist and the rend cache. */
  1961. rep_history_clean(now - options->RephistTrackTime);
  1962. rend_cache_clean(now, REND_CACHE_TYPE_SERVICE);
  1963. hs_cache_clean_as_client(now);
  1964. hs_cache_clean_as_dir(now);
  1965. microdesc_cache_rebuild(NULL, 0);
  1966. #define CLEAN_CACHES_INTERVAL (30*60)
  1967. return CLEAN_CACHES_INTERVAL;
  1968. }
  1969. /**
  1970. * Periodic callback: Clean the cache of failed hidden service lookups
  1971. * frequently.
  1972. */
  1973. static int
  1974. rend_cache_failure_clean_callback(time_t now, const or_options_t *options)
  1975. {
  1976. (void)options;
  1977. /* We don't keep entries that are more than five minutes old so we try to
  1978. * clean it as soon as we can since we want to make sure the client waits
  1979. * as little as possible for reachability reasons. */
  1980. rend_cache_failure_clean(now);
  1981. hs_cache_client_intro_state_clean(now);
  1982. return 30;
  1983. }
  1984. /**
  1985. * Periodic callback: If we're a server and initializing dns failed, retry.
  1986. */
  1987. static int
  1988. retry_dns_callback(time_t now, const or_options_t *options)
  1989. {
  1990. (void)now;
  1991. #define RETRY_DNS_INTERVAL (10*60)
  1992. if (server_mode(options) && has_dns_init_failed())
  1993. dns_init();
  1994. return RETRY_DNS_INTERVAL;
  1995. }
  1996. /** Periodic callback: consider rebuilding or and re-uploading our descriptor
  1997. * (if we've passed our internal checks). */
  1998. static int
  1999. check_descriptor_callback(time_t now, const or_options_t *options)
  2000. {
  2001. /** How often do we check whether part of our router info has changed in a
  2002. * way that would require an upload? That includes checking whether our IP
  2003. * address has changed. */
  2004. #define CHECK_DESCRIPTOR_INTERVAL (60)
  2005. (void)options;
  2006. /* 2b. Once per minute, regenerate and upload the descriptor if the old
  2007. * one is inaccurate. */
  2008. if (!net_is_disabled()) {
  2009. check_descriptor_bandwidth_changed(now);
  2010. check_descriptor_ipaddress_changed(now);
  2011. mark_my_descriptor_dirty_if_too_old(now);
  2012. consider_publishable_server(0);
  2013. /* If any networkstatus documents are no longer recent, we need to
  2014. * update all the descriptors' running status. */
  2015. /* Remove dead routers. */
  2016. /* XXXX This doesn't belong here, but it was here in the pre-
  2017. * XXXX refactoring code. */
  2018. routerlist_remove_old_routers();
  2019. }
  2020. return CHECK_DESCRIPTOR_INTERVAL;
  2021. }
  2022. /**
  2023. * Periodic callback: check whether we're reachable (as a relay), and
  2024. * whether our bandwidth has changed enough that we need to
  2025. * publish a new descriptor.
  2026. */
  2027. static int
  2028. check_for_reachability_bw_callback(time_t now, const or_options_t *options)
  2029. {
  2030. /* XXXX This whole thing was stuck in the middle of what is now
  2031. * XXXX check_descriptor_callback. I'm not sure it's right. */
  2032. static int dirport_reachability_count = 0;
  2033. /* also, check religiously for reachability, if it's within the first
  2034. * 20 minutes of our uptime. */
  2035. if (server_mode(options) &&
  2036. (have_completed_a_circuit() || !any_predicted_circuits(now)) &&
  2037. !net_is_disabled()) {
  2038. if (get_uptime() < TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT) {
  2039. router_do_reachability_checks(1, dirport_reachability_count==0);
  2040. if (++dirport_reachability_count > 5)
  2041. dirport_reachability_count = 0;
  2042. return 1;
  2043. } else {
  2044. /* If we haven't checked for 12 hours and our bandwidth estimate is
  2045. * low, do another bandwidth test. This is especially important for
  2046. * bridges, since they might go long periods without much use. */
  2047. const routerinfo_t *me = router_get_my_routerinfo();
  2048. static int first_time = 1;
  2049. if (!first_time && me &&
  2050. me->bandwidthcapacity < me->bandwidthrate &&
  2051. me->bandwidthcapacity < 51200) {
  2052. reset_bandwidth_test();
  2053. }
  2054. first_time = 0;
  2055. #define BANDWIDTH_RECHECK_INTERVAL (12*60*60)
  2056. return BANDWIDTH_RECHECK_INTERVAL;
  2057. }
  2058. }
  2059. return CHECK_DESCRIPTOR_INTERVAL;
  2060. }
  2061. /**
  2062. * Periodic event: once a minute, (or every second if TestingTorNetwork, or
  2063. * during client bootstrap), check whether we want to download any
  2064. * networkstatus documents. */
  2065. static int
  2066. fetch_networkstatus_callback(time_t now, const or_options_t *options)
  2067. {
  2068. /* How often do we check whether we should download network status
  2069. * documents? */
  2070. const int we_are_bootstrapping = networkstatus_consensus_is_bootstrapping(
  2071. now);
  2072. const int prefer_mirrors = !directory_fetches_from_authorities(
  2073. get_options());
  2074. int networkstatus_dl_check_interval = 60;
  2075. /* check more often when testing, or when bootstrapping from mirrors
  2076. * (connection limits prevent too many connections being made) */
  2077. if (options->TestingTorNetwork
  2078. || (we_are_bootstrapping && prefer_mirrors)) {
  2079. networkstatus_dl_check_interval = 1;
  2080. }
  2081. if (should_delay_dir_fetches(options, NULL))
  2082. return PERIODIC_EVENT_NO_UPDATE;
  2083. update_networkstatus_downloads(now);
  2084. return networkstatus_dl_check_interval;
  2085. }
  2086. /**
  2087. * Periodic callback: Every 60 seconds, we relaunch listeners if any died. */
  2088. static int
  2089. retry_listeners_callback(time_t now, const or_options_t *options)
  2090. {
  2091. (void)now;
  2092. (void)options;
  2093. if (!net_is_disabled()) {
  2094. retry_all_listeners(NULL, NULL, 0);
  2095. return 60;
  2096. }
  2097. return PERIODIC_EVENT_NO_UPDATE;
  2098. }
  2099. /**
  2100. * Periodic callback: as a server, see if we have any old unused circuits
  2101. * that should be expired */
  2102. static int
  2103. expire_old_ciruits_serverside_callback(time_t now, const or_options_t *options)
  2104. {
  2105. (void)options;
  2106. /* every 11 seconds, so not usually the same second as other such events */
  2107. circuit_expire_old_circuits_serverside(now);
  2108. return 11;
  2109. }
  2110. /**
  2111. * Callback: Send warnings if Tor doesn't find its ports reachable.
  2112. */
  2113. static int
  2114. reachability_warnings_callback(time_t now, const or_options_t *options)
  2115. {
  2116. (void) now;
  2117. if (get_uptime() < TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT) {
  2118. return (int)(TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT - get_uptime());
  2119. }
  2120. if (server_mode(options) &&
  2121. !net_is_disabled() &&
  2122. have_completed_a_circuit()) {
  2123. /* every 20 minutes, check and complain if necessary */
  2124. const routerinfo_t *me = router_get_my_routerinfo();
  2125. if (me && !check_whether_orport_reachable(options)) {
  2126. char *address = tor_dup_ip(me->addr);
  2127. log_warn(LD_CONFIG,"Your server (%s:%d) has not managed to confirm that "
  2128. "its ORPort is reachable. Relays do not publish descriptors "
  2129. "until their ORPort and DirPort are reachable. Please check "
  2130. "your firewalls, ports, address, /etc/hosts file, etc.",
  2131. address, me->or_port);
  2132. control_event_server_status(LOG_WARN,
  2133. "REACHABILITY_FAILED ORADDRESS=%s:%d",
  2134. address, me->or_port);
  2135. tor_free(address);
  2136. }
  2137. if (me && !check_whether_dirport_reachable(options)) {
  2138. char *address = tor_dup_ip(me->addr);
  2139. log_warn(LD_CONFIG,
  2140. "Your server (%s:%d) has not managed to confirm that its "
  2141. "DirPort is reachable. Relays do not publish descriptors "
  2142. "until their ORPort and DirPort are reachable. Please check "
  2143. "your firewalls, ports, address, /etc/hosts file, etc.",
  2144. address, me->dir_port);
  2145. control_event_server_status(LOG_WARN,
  2146. "REACHABILITY_FAILED DIRADDRESS=%s:%d",
  2147. address, me->dir_port);
  2148. tor_free(address);
  2149. }
  2150. }
  2151. return TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT;
  2152. }
  2153. static int dns_honesty_first_time = 1;
  2154. /**
  2155. * Periodic event: if we're an exit, see if our DNS server is telling us
  2156. * obvious lies.
  2157. */
  2158. static int
  2159. check_dns_honesty_callback(time_t now, const or_options_t *options)
  2160. {
  2161. (void)now;
  2162. /* 9. and if we're an exit node, check whether our DNS is telling stories
  2163. * to us. */
  2164. if (net_is_disabled() ||
  2165. ! public_server_mode(options) ||
  2166. router_my_exit_policy_is_reject_star())
  2167. return PERIODIC_EVENT_NO_UPDATE;
  2168. if (dns_honesty_first_time) {
  2169. /* Don't launch right when we start */
  2170. dns_honesty_first_time = 0;
  2171. return crypto_rand_int_range(60, 180);
  2172. }
  2173. dns_launch_correctness_checks();
  2174. return 12*3600 + crypto_rand_int(12*3600);
  2175. }
  2176. /**
  2177. * Periodic callback: if we're the bridge authority, write a networkstatus
  2178. * file to disk.
  2179. */
  2180. static int
  2181. write_bridge_ns_callback(time_t now, const or_options_t *options)
  2182. {
  2183. /* 10. write bridge networkstatus file to disk */
  2184. if (options->BridgeAuthoritativeDir) {
  2185. networkstatus_dump_bridge_status_to_file(now);
  2186. #define BRIDGE_STATUSFILE_INTERVAL (30*60)
  2187. return BRIDGE_STATUSFILE_INTERVAL;
  2188. }
  2189. return PERIODIC_EVENT_NO_UPDATE;
  2190. }
  2191. static int heartbeat_callback_first_time = 1;
  2192. /**
  2193. * Periodic callback: write the heartbeat message in the logs.
  2194. *
  2195. * If writing the heartbeat message to the logs fails for some reason, retry
  2196. * again after <b>MIN_HEARTBEAT_PERIOD</b> seconds.
  2197. */
  2198. static int
  2199. heartbeat_callback(time_t now, const or_options_t *options)
  2200. {
  2201. /* Check if heartbeat is disabled */
  2202. if (!options->HeartbeatPeriod) {
  2203. return PERIODIC_EVENT_NO_UPDATE;
  2204. }
  2205. /* Skip the first one. */
  2206. if (heartbeat_callback_first_time) {
  2207. heartbeat_callback_first_time = 0;
  2208. return options->HeartbeatPeriod;
  2209. }
  2210. /* Write the heartbeat message */
  2211. if (log_heartbeat(now) == 0) {
  2212. return options->HeartbeatPeriod;
  2213. } else {
  2214. /* If we couldn't write the heartbeat log message, try again in the minimum
  2215. * interval of time. */
  2216. return MIN_HEARTBEAT_PERIOD;
  2217. }
  2218. }
  2219. #define CDM_CLEAN_CALLBACK_INTERVAL 600
  2220. static int
  2221. clean_consdiffmgr_callback(time_t now, const or_options_t *options)
  2222. {
  2223. (void)now;
  2224. if (dir_server_mode(options)) {
  2225. consdiffmgr_cleanup();
  2226. }
  2227. return CDM_CLEAN_CALLBACK_INTERVAL;
  2228. }
  2229. /*
  2230. * Periodic callback: Run scheduled events for HS service. This is called
  2231. * every second.
  2232. */
  2233. static int
  2234. hs_service_callback(time_t now, const or_options_t *options)
  2235. {
  2236. (void) options;
  2237. /* We need to at least be able to build circuits and that we actually have
  2238. * a working network. */
  2239. if (!have_completed_a_circuit() || net_is_disabled() ||
  2240. networkstatus_get_live_consensus(now) == NULL) {
  2241. goto end;
  2242. }
  2243. hs_service_run_scheduled_events(now);
  2244. end:
  2245. /* Every 1 second. */
  2246. return 1;
  2247. }
  2248. /** Timer: used to invoke second_elapsed_callback() once per second. */
  2249. static periodic_timer_t *second_timer = NULL;
  2250. /**
  2251. * Enable or disable the per-second timer as appropriate, creating it if
  2252. * necessary.
  2253. */
  2254. void
  2255. reschedule_per_second_timer(void)
  2256. {
  2257. struct timeval one_second;
  2258. one_second.tv_sec = 1;
  2259. one_second.tv_usec = 0;
  2260. if (! second_timer) {
  2261. second_timer = periodic_timer_new(tor_libevent_get_base(),
  2262. &one_second,
  2263. second_elapsed_callback,
  2264. NULL);
  2265. tor_assert(second_timer);
  2266. }
  2267. const bool run_per_second_events =
  2268. control_any_per_second_event_enabled() || ! net_is_completely_disabled();
  2269. if (run_per_second_events) {
  2270. periodic_timer_launch(second_timer, &one_second);
  2271. } else {
  2272. periodic_timer_disable(second_timer);
  2273. }
  2274. }
  2275. /** Last time that update_current_time was called. */
  2276. static time_t current_second = 0;
  2277. /** Last time that update_current_time updated current_second. */
  2278. static monotime_coarse_t current_second_last_changed;
  2279. /**
  2280. * Set the current time to "now", which should be the value returned by
  2281. * time(). Check for clock jumps and track the total number of seconds we
  2282. * have been running.
  2283. */
  2284. void
  2285. update_current_time(time_t now)
  2286. {
  2287. if (PREDICT_LIKELY(now == current_second)) {
  2288. /* We call this function a lot. Most frequently, the current second
  2289. * will not have changed, so we just return. */
  2290. return;
  2291. }
  2292. const time_t seconds_elapsed = current_second ? (now - current_second) : 0;
  2293. /* Check the wall clock against the monotonic clock, so we can
  2294. * better tell idleness from clock jumps and/or other shenanigans. */
  2295. monotime_coarse_t last_updated;
  2296. memcpy(&last_updated, &current_second_last_changed, sizeof(last_updated));
  2297. monotime_coarse_get(&current_second_last_changed);
  2298. /** How much clock jumping do we tolerate? */
  2299. #define NUM_JUMPED_SECONDS_BEFORE_WARN 100
  2300. /** How much idleness do we tolerate? */
  2301. #define NUM_IDLE_SECONDS_BEFORE_WARN 3600
  2302. if (seconds_elapsed < -NUM_JUMPED_SECONDS_BEFORE_WARN) {
  2303. // moving back in time is always a bad sign.
  2304. circuit_note_clock_jumped(seconds_elapsed, false);
  2305. } else if (seconds_elapsed >= NUM_JUMPED_SECONDS_BEFORE_WARN) {
  2306. /* Compare the monotonic clock to the result of time(). */
  2307. const int32_t monotime_msec_passed =
  2308. monotime_coarse_diff_msec32(&last_updated,
  2309. &current_second_last_changed);
  2310. const int monotime_sec_passed = monotime_msec_passed / 1000;
  2311. const int discrepancy = monotime_sec_passed - (int)seconds_elapsed;
  2312. /* If the monotonic clock deviates from time(NULL), we have a couple of
  2313. * possibilities. On some systems, this means we have been suspended or
  2314. * sleeping. Everywhere, it can mean that the wall-clock time has
  2315. * been changed -- for example, with settimeofday().
  2316. *
  2317. * On the other hand, if the monotonic time matches with the wall-clock
  2318. * time, we've probably just been idle for a while, with no events firing.
  2319. * we tolerate much more of that.
  2320. */
  2321. const bool clock_jumped = abs(discrepancy) > 2;
  2322. if (clock_jumped || seconds_elapsed >= NUM_IDLE_SECONDS_BEFORE_WARN) {
  2323. circuit_note_clock_jumped(seconds_elapsed, ! clock_jumped);
  2324. }
  2325. } else if (seconds_elapsed > 0) {
  2326. stats_n_seconds_working += seconds_elapsed;
  2327. }
  2328. update_approx_time(now);
  2329. current_second = now;
  2330. }
  2331. /** Libevent callback: invoked once every second. */
  2332. static void
  2333. second_elapsed_callback(periodic_timer_t *timer, void *arg)
  2334. {
  2335. /* XXXX This could be sensibly refactored into multiple callbacks, and we
  2336. * could use Libevent's timers for this rather than checking the current
  2337. * time against a bunch of timeouts every second. */
  2338. time_t now;
  2339. (void)timer;
  2340. (void)arg;
  2341. now = time(NULL);
  2342. /* We don't need to do this once-per-second any more: time-updating is
  2343. * only in this callback _because it is a callback_. It should be fine
  2344. * to disable this callback, and the time will still get updated.
  2345. */
  2346. update_current_time(now);
  2347. /* Maybe some controller events are ready to fire */
  2348. control_per_second_events();
  2349. run_scheduled_events(now);
  2350. }
  2351. #ifdef HAVE_SYSTEMD_209
  2352. static periodic_timer_t *systemd_watchdog_timer = NULL;
  2353. /** Libevent callback: invoked to reset systemd watchdog. */
  2354. static void
  2355. systemd_watchdog_callback(periodic_timer_t *timer, void *arg)
  2356. {
  2357. (void)timer;
  2358. (void)arg;
  2359. sd_notify(0, "WATCHDOG=1");
  2360. }
  2361. #endif /* defined(HAVE_SYSTEMD_209) */
  2362. #define UPTIME_CUTOFF_FOR_NEW_BANDWIDTH_TEST (6*60*60)
  2363. /** Called when our IP address seems to have changed. <b>at_interface</b>
  2364. * should be true if we detected a change in our interface, and false if we
  2365. * detected a change in our published address. */
  2366. void
  2367. ip_address_changed(int at_interface)
  2368. {
  2369. const or_options_t *options = get_options();
  2370. int server = server_mode(options);
  2371. int exit_reject_interfaces = (server && options->ExitRelay
  2372. && options->ExitPolicyRejectLocalInterfaces);
  2373. if (at_interface) {
  2374. if (! server) {
  2375. /* Okay, change our keys. */
  2376. if (init_keys_client() < 0)
  2377. log_warn(LD_GENERAL, "Unable to rotate keys after IP change!");
  2378. }
  2379. } else {
  2380. if (server) {
  2381. if (get_uptime() > UPTIME_CUTOFF_FOR_NEW_BANDWIDTH_TEST)
  2382. reset_bandwidth_test();
  2383. reset_uptime();
  2384. router_reset_reachability();
  2385. }
  2386. }
  2387. /* Exit relays incorporate interface addresses in their exit policies when
  2388. * ExitPolicyRejectLocalInterfaces is set */
  2389. if (exit_reject_interfaces || (server && !at_interface)) {
  2390. mark_my_descriptor_dirty("IP address changed");
  2391. }
  2392. dns_servers_relaunch_checks();
  2393. }
  2394. /** Forget what we've learned about the correctness of our DNS servers, and
  2395. * start learning again. */
  2396. void
  2397. dns_servers_relaunch_checks(void)
  2398. {
  2399. if (server_mode(get_options())) {
  2400. dns_reset_correctness_checks();
  2401. if (periodic_events_initialized) {
  2402. tor_assert(check_dns_honesty_event);
  2403. periodic_event_reschedule(check_dns_honesty_event);
  2404. }
  2405. }
  2406. }
  2407. /** Called when we get a SIGHUP: reload configuration files and keys,
  2408. * retry all connections, and so on. */
  2409. static int
  2410. do_hup(void)
  2411. {
  2412. const or_options_t *options = get_options();
  2413. log_notice(LD_GENERAL,"Received reload signal (hup). Reloading config and "
  2414. "resetting internal state.");
  2415. if (accounting_is_enabled(options))
  2416. accounting_record_bandwidth_usage(time(NULL), get_or_state());
  2417. router_reset_warnings();
  2418. routerlist_reset_warnings();
  2419. /* first, reload config variables, in case they've changed */
  2420. if (options->ReloadTorrcOnSIGHUP) {
  2421. /* no need to provide argc/v, they've been cached in init_from_config */
  2422. int init_rv = options_init_from_torrc(0, NULL);
  2423. if (init_rv < 0) {
  2424. log_err(LD_CONFIG,"Reading config failed--see warnings above. "
  2425. "For usage, try -h.");
  2426. return -1;
  2427. } else if (BUG(init_rv > 0)) {
  2428. // LCOV_EXCL_START
  2429. /* This should be impossible: the only "return 1" cases in
  2430. * options_init_from_torrc are ones caused by command-line arguments;
  2431. * but they can't change while Tor is running. */
  2432. return -1;
  2433. // LCOV_EXCL_STOP
  2434. }
  2435. options = get_options(); /* they have changed now */
  2436. /* Logs are only truncated the first time they are opened, but were
  2437. probably intended to be cleaned up on signal. */
  2438. if (options->TruncateLogFile)
  2439. truncate_logs();
  2440. } else {
  2441. char *msg = NULL;
  2442. log_notice(LD_GENERAL, "Not reloading config file: the controller told "
  2443. "us not to.");
  2444. /* Make stuff get rescanned, reloaded, etc. */
  2445. if (set_options((or_options_t*)options, &msg) < 0) {
  2446. if (!msg)
  2447. msg = tor_strdup("Unknown error");
  2448. log_warn(LD_GENERAL, "Unable to re-set previous options: %s", msg);
  2449. tor_free(msg);
  2450. }
  2451. }
  2452. if (authdir_mode(options)) {
  2453. /* reload the approved-routers file */
  2454. if (dirserv_load_fingerprint_file() < 0) {
  2455. /* warnings are logged from dirserv_load_fingerprint_file() directly */
  2456. log_info(LD_GENERAL, "Error reloading fingerprints. "
  2457. "Continuing with old list.");
  2458. }
  2459. }
  2460. /* Rotate away from the old dirty circuits. This has to be done
  2461. * after we've read the new options, but before we start using
  2462. * circuits for directory fetches. */
  2463. circuit_mark_all_dirty_circs_as_unusable();
  2464. /* retry appropriate downloads */
  2465. router_reset_status_download_failures();
  2466. router_reset_descriptor_download_failures();
  2467. if (!net_is_disabled())
  2468. update_networkstatus_downloads(time(NULL));
  2469. /* We'll retry routerstatus downloads in about 10 seconds; no need to
  2470. * force a retry there. */
  2471. if (server_mode(options)) {
  2472. /* Maybe we've been given a new ed25519 key or certificate?
  2473. */
  2474. time_t now = approx_time();
  2475. int new_signing_key = load_ed_keys(options, now);
  2476. if (new_signing_key < 0 ||
  2477. generate_ed_link_cert(options, now, new_signing_key > 0)) {
  2478. log_warn(LD_OR, "Problem reloading Ed25519 keys; still using old keys.");
  2479. }
  2480. /* Update cpuworker and dnsworker processes, so they get up-to-date
  2481. * configuration options. */
  2482. cpuworkers_rotate_keyinfo();
  2483. dns_reset();
  2484. }
  2485. return 0;
  2486. }
  2487. /** Initialize some mainloop_event_t objects that we require. */
  2488. STATIC void
  2489. initialize_mainloop_events(void)
  2490. {
  2491. if (!schedule_active_linked_connections_event) {
  2492. schedule_active_linked_connections_event =
  2493. mainloop_event_postloop_new(schedule_active_linked_connections_cb, NULL);
  2494. }
  2495. if (!postloop_cleanup_ev) {
  2496. postloop_cleanup_ev =
  2497. mainloop_event_postloop_new(postloop_cleanup_cb, NULL);
  2498. }
  2499. }
  2500. /** Tor main loop. */
  2501. int
  2502. do_main_loop(void)
  2503. {
  2504. time_t now;
  2505. /* initialize the periodic events first, so that code that depends on the
  2506. * events being present does not assert.
  2507. */
  2508. if (! periodic_events_initialized) {
  2509. initialize_periodic_events();
  2510. }
  2511. initialize_mainloop_events();
  2512. /* initialize dns resolve map, spawn workers if needed */
  2513. if (dns_init() < 0) {
  2514. if (get_options()->ServerDNSAllowBrokenConfig)
  2515. log_warn(LD_GENERAL, "Couldn't set up any working nameservers. "
  2516. "Network not up yet? Will try again soon.");
  2517. else {
  2518. log_err(LD_GENERAL,"Error initializing dns subsystem; exiting. To "
  2519. "retry instead, set the ServerDNSAllowBrokenResolvConf option.");
  2520. }
  2521. }
  2522. handle_signals();
  2523. monotime_init();
  2524. timers_initialize();
  2525. /* load the private keys, if we're supposed to have them, and set up the
  2526. * TLS context. */
  2527. if (! client_identity_key_is_set()) {
  2528. if (init_keys() < 0) {
  2529. log_err(LD_OR, "Error initializing keys; exiting");
  2530. return -1;
  2531. }
  2532. }
  2533. /* Set up our buckets */
  2534. connection_bucket_init();
  2535. /* initialize the bootstrap status events to know we're starting up */
  2536. control_event_bootstrap(BOOTSTRAP_STATUS_STARTING, 0);
  2537. /* Initialize the keypinning log. */
  2538. if (authdir_mode_v3(get_options())) {
  2539. char *fname = get_datadir_fname("key-pinning-journal");
  2540. int r = 0;
  2541. if (keypin_load_journal(fname)<0) {
  2542. log_err(LD_DIR, "Error loading key-pinning journal: %s",strerror(errno));
  2543. r = -1;
  2544. }
  2545. if (keypin_open_journal(fname)<0) {
  2546. log_err(LD_DIR, "Error opening key-pinning journal: %s",strerror(errno));
  2547. r = -1;
  2548. }
  2549. tor_free(fname);
  2550. if (r)
  2551. return r;
  2552. }
  2553. {
  2554. /* This is the old name for key-pinning-journal. These got corrupted
  2555. * in a couple of cases by #16530, so we started over. See #16580 for
  2556. * the rationale and for other options we didn't take. We can remove
  2557. * this code once all the authorities that ran 0.2.7.1-alpha-dev are
  2558. * upgraded.
  2559. */
  2560. char *fname = get_datadir_fname("key-pinning-entries");
  2561. unlink(fname);
  2562. tor_free(fname);
  2563. }
  2564. if (trusted_dirs_reload_certs()) {
  2565. log_warn(LD_DIR,
  2566. "Couldn't load all cached v3 certificates. Starting anyway.");
  2567. }
  2568. if (router_reload_consensus_networkstatus()) {
  2569. return -1;
  2570. }
  2571. /* load the routers file, or assign the defaults. */
  2572. if (router_reload_router_list()) {
  2573. return -1;
  2574. }
  2575. /* load the networkstatuses. (This launches a download for new routers as
  2576. * appropriate.)
  2577. */
  2578. now = time(NULL);
  2579. directory_info_has_arrived(now, 1, 0);
  2580. if (server_mode(get_options()) || dir_server_mode(get_options())) {
  2581. /* launch cpuworkers. Need to do this *after* we've read the onion key. */
  2582. cpu_init();
  2583. }
  2584. consdiffmgr_enable_background_compression();
  2585. /* Setup shared random protocol subsystem. */
  2586. if (authdir_mode_v3(get_options())) {
  2587. if (sr_init(1) < 0) {
  2588. return -1;
  2589. }
  2590. }
  2591. /* set up once-a-second callback. */
  2592. reschedule_per_second_timer();
  2593. #ifdef HAVE_SYSTEMD_209
  2594. uint64_t watchdog_delay;
  2595. /* set up systemd watchdog notification. */
  2596. if (sd_watchdog_enabled(1, &watchdog_delay) > 0) {
  2597. if (! systemd_watchdog_timer) {
  2598. struct timeval watchdog;
  2599. /* The manager will "act on" us if we don't send them a notification
  2600. * every 'watchdog_delay' microseconds. So, send notifications twice
  2601. * that often. */
  2602. watchdog_delay /= 2;
  2603. watchdog.tv_sec = watchdog_delay / 1000000;
  2604. watchdog.tv_usec = watchdog_delay % 1000000;
  2605. systemd_watchdog_timer = periodic_timer_new(tor_libevent_get_base(),
  2606. &watchdog,
  2607. systemd_watchdog_callback,
  2608. NULL);
  2609. tor_assert(systemd_watchdog_timer);
  2610. }
  2611. }
  2612. #endif /* defined(HAVE_SYSTEMD_209) */
  2613. #ifdef HAVE_SYSTEMD
  2614. {
  2615. const int r = sd_notify(0, "READY=1");
  2616. if (r < 0) {
  2617. log_warn(LD_GENERAL, "Unable to send readiness to systemd: %s",
  2618. strerror(r));
  2619. } else if (r > 0) {
  2620. log_notice(LD_GENERAL, "Signaled readiness to systemd");
  2621. } else {
  2622. log_info(LD_GENERAL, "Systemd NOTIFY_SOCKET not present.");
  2623. }
  2624. }
  2625. #endif /* defined(HAVE_SYSTEMD) */
  2626. main_loop_should_exit = 0;
  2627. main_loop_exit_value = 0;
  2628. #ifdef ENABLE_RESTART_DEBUGGING
  2629. {
  2630. static int first_time = 1;
  2631. if (first_time && getenv("TOR_DEBUG_RESTART")) {
  2632. first_time = 0;
  2633. const char *sec_str = getenv("TOR_DEBUG_RESTART_AFTER_SECONDS");
  2634. long sec;
  2635. int sec_ok=0;
  2636. if (sec_str &&
  2637. (sec = tor_parse_long(sec_str, 10, 0, INT_MAX, &sec_ok, NULL)) &&
  2638. sec_ok) {
  2639. /* Okay, we parsed the seconds. */
  2640. } else {
  2641. sec = 5;
  2642. }
  2643. struct timeval restart_after = { (time_t) sec, 0 };
  2644. tor_shutdown_event_loop_for_restart_event =
  2645. tor_evtimer_new(tor_libevent_get_base(),
  2646. tor_shutdown_event_loop_for_restart_cb, NULL);
  2647. event_add(tor_shutdown_event_loop_for_restart_event, &restart_after);
  2648. }
  2649. }
  2650. #endif
  2651. return run_main_loop_until_done();
  2652. }
  2653. #ifndef _WIN32
  2654. /** Rate-limiter for EINVAL-type libevent warnings. */
  2655. static ratelim_t libevent_error_ratelim = RATELIM_INIT(10);
  2656. #endif
  2657. /**
  2658. * Run the main loop a single time. Return 0 for "exit"; -1 for "exit with
  2659. * error", and 1 for "run this again."
  2660. */
  2661. static int
  2662. run_main_loop_once(void)
  2663. {
  2664. int loop_result;
  2665. if (nt_service_is_stopping())
  2666. return 0;
  2667. if (main_loop_should_exit)
  2668. return 0;
  2669. #ifndef _WIN32
  2670. /* Make it easier to tell whether libevent failure is our fault or not. */
  2671. errno = 0;
  2672. #endif
  2673. if (get_options()->MainloopStats) {
  2674. /* We always enforce that EVLOOP_ONCE is passed to event_base_loop() if we
  2675. * are collecting main loop statistics. */
  2676. called_loop_once = 1;
  2677. } else {
  2678. called_loop_once = 0;
  2679. }
  2680. /* Make sure we know (about) what time it is. */
  2681. update_approx_time(time(NULL));
  2682. /* Here it is: the main loop. Here we tell Libevent to poll until we have
  2683. * an event, or the second ends, or until we have some active linked
  2684. * connections to trigger events for. Libevent will wait till one
  2685. * of these happens, then run all the appropriate callbacks. */
  2686. loop_result = tor_libevent_run_event_loop(tor_libevent_get_base(),
  2687. called_loop_once);
  2688. if (get_options()->MainloopStats) {
  2689. /* Update our main loop counters. */
  2690. if (loop_result == 0) {
  2691. // The call was successful.
  2692. increment_main_loop_success_count();
  2693. } else if (loop_result == -1) {
  2694. // The call was erroneous.
  2695. increment_main_loop_error_count();
  2696. } else if (loop_result == 1) {
  2697. // The call didn't have any active or pending events
  2698. // to handle.
  2699. increment_main_loop_idle_count();
  2700. }
  2701. }
  2702. /* Oh, the loop failed. That might be an error that we need to
  2703. * catch, but more likely, it's just an interrupted poll() call or something,
  2704. * and we should try again. */
  2705. if (loop_result < 0) {
  2706. int e = tor_socket_errno(-1);
  2707. /* let the program survive things like ^z */
  2708. if (e != EINTR && !ERRNO_IS_EINPROGRESS(e)) {
  2709. log_err(LD_NET,"libevent call with %s failed: %s [%d]",
  2710. tor_libevent_get_method(), tor_socket_strerror(e), e);
  2711. return -1;
  2712. #ifndef _WIN32
  2713. } else if (e == EINVAL) {
  2714. log_fn_ratelim(&libevent_error_ratelim, LOG_WARN, LD_NET,
  2715. "EINVAL from libevent: should you upgrade libevent?");
  2716. if (libevent_error_ratelim.n_calls_since_last_time > 8) {
  2717. log_err(LD_NET, "Too many libevent errors, too fast: dying");
  2718. return -1;
  2719. }
  2720. #endif /* !defined(_WIN32) */
  2721. } else {
  2722. tor_assert_nonfatal_once(! ERRNO_IS_EINPROGRESS(e));
  2723. log_debug(LD_NET,"libevent call interrupted.");
  2724. /* You can't trust the results of this poll(). Go back to the
  2725. * top of the big for loop. */
  2726. return 1;
  2727. }
  2728. }
  2729. if (main_loop_should_exit)
  2730. return 0;
  2731. return 1;
  2732. }
  2733. /** Run the run_main_loop_once() function until it declares itself done,
  2734. * and return its final return value.
  2735. *
  2736. * Shadow won't invoke this function, so don't fill it up with things.
  2737. */
  2738. static int
  2739. run_main_loop_until_done(void)
  2740. {
  2741. int loop_result = 1;
  2742. do {
  2743. loop_result = run_main_loop_once();
  2744. } while (loop_result == 1);
  2745. if (main_loop_should_exit)
  2746. return main_loop_exit_value;
  2747. else
  2748. return loop_result;
  2749. }
  2750. /** Libevent callback: invoked when we get a signal.
  2751. */
  2752. static void
  2753. signal_callback(evutil_socket_t fd, short events, void *arg)
  2754. {
  2755. const int *sigptr = arg;
  2756. const int sig = *sigptr;
  2757. (void)fd;
  2758. (void)events;
  2759. update_current_time(time(NULL));
  2760. process_signal(sig);
  2761. }
  2762. /** Do the work of acting on a signal received in <b>sig</b> */
  2763. static void
  2764. process_signal(int sig)
  2765. {
  2766. switch (sig)
  2767. {
  2768. case SIGTERM:
  2769. log_notice(LD_GENERAL,"Catching signal TERM, exiting cleanly.");
  2770. tor_shutdown_event_loop_and_exit(0);
  2771. break;
  2772. case SIGINT:
  2773. if (!server_mode(get_options())) { /* do it now */
  2774. log_notice(LD_GENERAL,"Interrupt: exiting cleanly.");
  2775. tor_shutdown_event_loop_and_exit(0);
  2776. return;
  2777. }
  2778. #ifdef HAVE_SYSTEMD
  2779. sd_notify(0, "STOPPING=1");
  2780. #endif
  2781. hibernate_begin_shutdown();
  2782. break;
  2783. #ifdef SIGPIPE
  2784. case SIGPIPE:
  2785. log_debug(LD_GENERAL,"Caught SIGPIPE. Ignoring.");
  2786. break;
  2787. #endif
  2788. case SIGUSR1:
  2789. /* prefer to log it at INFO, but make sure we always see it */
  2790. dumpstats(get_min_log_level()<LOG_INFO ? get_min_log_level() : LOG_INFO);
  2791. control_event_signal(sig);
  2792. break;
  2793. case SIGUSR2:
  2794. switch_logs_debug();
  2795. log_debug(LD_GENERAL,"Caught USR2, going to loglevel debug. "
  2796. "Send HUP to change back.");
  2797. control_event_signal(sig);
  2798. break;
  2799. case SIGHUP:
  2800. #ifdef HAVE_SYSTEMD
  2801. sd_notify(0, "RELOADING=1");
  2802. #endif
  2803. if (do_hup() < 0) {
  2804. log_warn(LD_CONFIG,"Restart failed (config error?). Exiting.");
  2805. tor_shutdown_event_loop_and_exit(1);
  2806. return;
  2807. }
  2808. #ifdef HAVE_SYSTEMD
  2809. sd_notify(0, "READY=1");
  2810. #endif
  2811. control_event_signal(sig);
  2812. break;
  2813. #ifdef SIGCHLD
  2814. case SIGCHLD:
  2815. notify_pending_waitpid_callbacks();
  2816. break;
  2817. #endif
  2818. case SIGNEWNYM: {
  2819. time_t now = time(NULL);
  2820. if (time_of_last_signewnym + MAX_SIGNEWNYM_RATE > now) {
  2821. const time_t delay_sec =
  2822. time_of_last_signewnym + MAX_SIGNEWNYM_RATE - now;
  2823. if (! signewnym_is_pending) {
  2824. signewnym_is_pending = 1;
  2825. if (!handle_deferred_signewnym_ev) {
  2826. handle_deferred_signewnym_ev =
  2827. mainloop_event_postloop_new(handle_deferred_signewnym_cb, NULL);
  2828. }
  2829. const struct timeval delay_tv = { delay_sec, 0 };
  2830. mainloop_event_schedule(handle_deferred_signewnym_ev, &delay_tv);
  2831. }
  2832. log_notice(LD_CONTROL,
  2833. "Rate limiting NEWNYM request: delaying by %d second(s)",
  2834. (int)(delay_sec));
  2835. } else {
  2836. signewnym_impl(now);
  2837. }
  2838. break;
  2839. }
  2840. case SIGCLEARDNSCACHE:
  2841. addressmap_clear_transient();
  2842. control_event_signal(sig);
  2843. break;
  2844. case SIGHEARTBEAT:
  2845. log_heartbeat(time(NULL));
  2846. control_event_signal(sig);
  2847. break;
  2848. }
  2849. }
  2850. /** Returns Tor's uptime. */
  2851. MOCK_IMPL(long,
  2852. get_uptime,(void))
  2853. {
  2854. return stats_n_seconds_working;
  2855. }
  2856. /** Reset Tor's uptime. */
  2857. MOCK_IMPL(void,
  2858. reset_uptime,(void))
  2859. {
  2860. stats_n_seconds_working = 0;
  2861. }
  2862. /**
  2863. * Write current memory usage information to the log.
  2864. */
  2865. static void
  2866. dumpmemusage(int severity)
  2867. {
  2868. connection_dump_buffer_mem_stats(severity);
  2869. tor_log(severity, LD_GENERAL, "In rephist: %"PRIu64" used by %d Tors.",
  2870. (rephist_total_alloc), rephist_total_num);
  2871. dump_routerlist_mem_usage(severity);
  2872. dump_cell_pool_usage(severity);
  2873. dump_dns_mem_usage(severity);
  2874. tor_log_mallinfo(severity);
  2875. }
  2876. /** Write all statistics to the log, with log level <b>severity</b>. Called
  2877. * in response to a SIGUSR1. */
  2878. static void
  2879. dumpstats(int severity)
  2880. {
  2881. time_t now = time(NULL);
  2882. time_t elapsed;
  2883. size_t rbuf_cap, wbuf_cap, rbuf_len, wbuf_len;
  2884. tor_log(severity, LD_GENERAL, "Dumping stats:");
  2885. SMARTLIST_FOREACH_BEGIN(connection_array, connection_t *, conn) {
  2886. int i = conn_sl_idx;
  2887. tor_log(severity, LD_GENERAL,
  2888. "Conn %d (socket %d) type %d (%s), state %d (%s), created %d secs ago",
  2889. i, (int)conn->s, conn->type, conn_type_to_string(conn->type),
  2890. conn->state, conn_state_to_string(conn->type, conn->state),
  2891. (int)(now - conn->timestamp_created));
  2892. if (!connection_is_listener(conn)) {
  2893. tor_log(severity,LD_GENERAL,
  2894. "Conn %d is to %s:%d.", i,
  2895. safe_str_client(conn->address),
  2896. conn->port);
  2897. tor_log(severity,LD_GENERAL,
  2898. "Conn %d: %d bytes waiting on inbuf (len %d, last read %d secs ago)",
  2899. i,
  2900. (int)connection_get_inbuf_len(conn),
  2901. (int)buf_allocation(conn->inbuf),
  2902. (int)(now - conn->timestamp_last_read_allowed));
  2903. tor_log(severity,LD_GENERAL,
  2904. "Conn %d: %d bytes waiting on outbuf "
  2905. "(len %d, last written %d secs ago)",i,
  2906. (int)connection_get_outbuf_len(conn),
  2907. (int)buf_allocation(conn->outbuf),
  2908. (int)(now - conn->timestamp_last_write_allowed));
  2909. if (conn->type == CONN_TYPE_OR) {
  2910. or_connection_t *or_conn = TO_OR_CONN(conn);
  2911. if (or_conn->tls) {
  2912. if (tor_tls_get_buffer_sizes(or_conn->tls, &rbuf_cap, &rbuf_len,
  2913. &wbuf_cap, &wbuf_len) == 0) {
  2914. tor_log(severity, LD_GENERAL,
  2915. "Conn %d: %d/%d bytes used on OpenSSL read buffer; "
  2916. "%d/%d bytes used on write buffer.",
  2917. i, (int)rbuf_len, (int)rbuf_cap, (int)wbuf_len, (int)wbuf_cap);
  2918. }
  2919. }
  2920. }
  2921. }
  2922. circuit_dump_by_conn(conn, severity); /* dump info about all the circuits
  2923. * using this conn */
  2924. } SMARTLIST_FOREACH_END(conn);
  2925. channel_dumpstats(severity);
  2926. channel_listener_dumpstats(severity);
  2927. tor_log(severity, LD_NET,
  2928. "Cells processed: %"PRIu64" padding\n"
  2929. " %"PRIu64" create\n"
  2930. " %"PRIu64" created\n"
  2931. " %"PRIu64" relay\n"
  2932. " (%"PRIu64" relayed)\n"
  2933. " (%"PRIu64" delivered)\n"
  2934. " %"PRIu64" destroy",
  2935. (stats_n_padding_cells_processed),
  2936. (stats_n_create_cells_processed),
  2937. (stats_n_created_cells_processed),
  2938. (stats_n_relay_cells_processed),
  2939. (stats_n_relay_cells_relayed),
  2940. (stats_n_relay_cells_delivered),
  2941. (stats_n_destroy_cells_processed));
  2942. if (stats_n_data_cells_packaged)
  2943. tor_log(severity,LD_NET,"Average packaged cell fullness: %2.3f%%",
  2944. 100*(((double)stats_n_data_bytes_packaged) /
  2945. ((double)stats_n_data_cells_packaged*RELAY_PAYLOAD_SIZE)) );
  2946. if (stats_n_data_cells_received)
  2947. tor_log(severity,LD_NET,"Average delivered cell fullness: %2.3f%%",
  2948. 100*(((double)stats_n_data_bytes_received) /
  2949. ((double)stats_n_data_cells_received*RELAY_PAYLOAD_SIZE)) );
  2950. cpuworker_log_onionskin_overhead(severity, ONION_HANDSHAKE_TYPE_TAP, "TAP");
  2951. cpuworker_log_onionskin_overhead(severity, ONION_HANDSHAKE_TYPE_NTOR,"ntor");
  2952. if (now - time_of_process_start >= 0)
  2953. elapsed = now - time_of_process_start;
  2954. else
  2955. elapsed = 0;
  2956. if (elapsed) {
  2957. tor_log(severity, LD_NET,
  2958. "Average bandwidth: %"PRIu64"/%d = %d bytes/sec reading",
  2959. (stats_n_bytes_read),
  2960. (int)elapsed,
  2961. (int) (stats_n_bytes_read/elapsed));
  2962. tor_log(severity, LD_NET,
  2963. "Average bandwidth: %"PRIu64"/%d = %d bytes/sec writing",
  2964. (stats_n_bytes_written),
  2965. (int)elapsed,
  2966. (int) (stats_n_bytes_written/elapsed));
  2967. }
  2968. tor_log(severity, LD_NET, "--------------- Dumping memory information:");
  2969. dumpmemusage(severity);
  2970. rep_hist_dump_stats(now,severity);
  2971. rend_service_dump_stats(severity);
  2972. dump_distinct_digest_count(severity);
  2973. }
  2974. /** Called by exit() as we shut down the process.
  2975. */
  2976. static void
  2977. exit_function(void)
  2978. {
  2979. /* NOTE: If we ever daemonize, this gets called immediately. That's
  2980. * okay for now, because we only use this on Windows. */
  2981. #ifdef _WIN32
  2982. WSACleanup();
  2983. #endif
  2984. }
  2985. #ifdef _WIN32
  2986. #define UNIX_ONLY 0
  2987. #else
  2988. #define UNIX_ONLY 1
  2989. #endif
  2990. static struct {
  2991. /** A numeric code for this signal. Must match the signal value if
  2992. * try_to_register is true. */
  2993. int signal_value;
  2994. /** True if we should try to register this signal with libevent and catch
  2995. * corresponding posix signals. False otherwise. */
  2996. int try_to_register;
  2997. /** Pointer to hold the event object constructed for this signal. */
  2998. struct event *signal_event;
  2999. } signal_handlers[] = {
  3000. #ifdef SIGINT
  3001. { SIGINT, UNIX_ONLY, NULL }, /* do a controlled slow shutdown */
  3002. #endif
  3003. #ifdef SIGTERM
  3004. { SIGTERM, UNIX_ONLY, NULL }, /* to terminate now */
  3005. #endif
  3006. #ifdef SIGPIPE
  3007. { SIGPIPE, UNIX_ONLY, NULL }, /* otherwise SIGPIPE kills us */
  3008. #endif
  3009. #ifdef SIGUSR1
  3010. { SIGUSR1, UNIX_ONLY, NULL }, /* dump stats */
  3011. #endif
  3012. #ifdef SIGUSR2
  3013. { SIGUSR2, UNIX_ONLY, NULL }, /* go to loglevel debug */
  3014. #endif
  3015. #ifdef SIGHUP
  3016. { SIGHUP, UNIX_ONLY, NULL }, /* to reload config, retry conns, etc */
  3017. #endif
  3018. #ifdef SIGXFSZ
  3019. { SIGXFSZ, UNIX_ONLY, NULL }, /* handle file-too-big resource exhaustion */
  3020. #endif
  3021. #ifdef SIGCHLD
  3022. { SIGCHLD, UNIX_ONLY, NULL }, /* handle dns/cpu workers that exit */
  3023. #endif
  3024. /* These are controller-only */
  3025. { SIGNEWNYM, 0, NULL },
  3026. { SIGCLEARDNSCACHE, 0, NULL },
  3027. { SIGHEARTBEAT, 0, NULL },
  3028. { -1, -1, NULL }
  3029. };
  3030. /** Set up the signal handler events for this process, and register them
  3031. * with libevent if appropriate. */
  3032. void
  3033. handle_signals(void)
  3034. {
  3035. int i;
  3036. const int enabled = !get_options()->DisableSignalHandlers;
  3037. for (i = 0; signal_handlers[i].signal_value >= 0; ++i) {
  3038. /* Signal handlers are only registered with libevent if they need to catch
  3039. * real POSIX signals. We construct these signal handler events in either
  3040. * case, though, so that controllers can activate them with the SIGNAL
  3041. * command.
  3042. */
  3043. if (enabled && signal_handlers[i].try_to_register) {
  3044. signal_handlers[i].signal_event =
  3045. tor_evsignal_new(tor_libevent_get_base(),
  3046. signal_handlers[i].signal_value,
  3047. signal_callback,
  3048. &signal_handlers[i].signal_value);
  3049. if (event_add(signal_handlers[i].signal_event, NULL))
  3050. log_warn(LD_BUG, "Error from libevent when adding "
  3051. "event for signal %d",
  3052. signal_handlers[i].signal_value);
  3053. } else {
  3054. signal_handlers[i].signal_event =
  3055. tor_event_new(tor_libevent_get_base(), -1,
  3056. EV_SIGNAL, signal_callback,
  3057. &signal_handlers[i].signal_value);
  3058. }
  3059. }
  3060. }
  3061. /* Cause the signal handler for signal_num to be called in the event loop. */
  3062. void
  3063. activate_signal(int signal_num)
  3064. {
  3065. int i;
  3066. for (i = 0; signal_handlers[i].signal_value >= 0; ++i) {
  3067. if (signal_handlers[i].signal_value == signal_num) {
  3068. event_active(signal_handlers[i].signal_event, EV_SIGNAL, 1);
  3069. return;
  3070. }
  3071. }
  3072. }
  3073. /** Main entry point for the Tor command-line client. Return 0 on "success",
  3074. * negative on "failure", and positive on "success and exit".
  3075. */
  3076. int
  3077. tor_init(int argc, char *argv[])
  3078. {
  3079. char progname[256];
  3080. int quiet = 0;
  3081. time_of_process_start = time(NULL);
  3082. init_connection_lists();
  3083. /* Have the log set up with our application name. */
  3084. tor_snprintf(progname, sizeof(progname), "Tor %s", get_version());
  3085. log_set_application_name(progname);
  3086. /* Set up the crypto nice and early */
  3087. if (crypto_early_init() < 0) {
  3088. log_err(LD_GENERAL, "Unable to initialize the crypto subsystem!");
  3089. return -1;
  3090. }
  3091. /* Initialize the history structures. */
  3092. rep_hist_init();
  3093. /* Initialize the service cache. */
  3094. rend_cache_init();
  3095. addressmap_init(); /* Init the client dns cache. Do it always, since it's
  3096. * cheap. */
  3097. /* Initialize the HS subsystem. */
  3098. hs_init();
  3099. {
  3100. /* We search for the "quiet" option first, since it decides whether we
  3101. * will log anything at all to the command line. */
  3102. config_line_t *opts = NULL, *cmdline_opts = NULL;
  3103. const config_line_t *cl;
  3104. (void) config_parse_commandline(argc, argv, 1, &opts, &cmdline_opts);
  3105. for (cl = cmdline_opts; cl; cl = cl->next) {
  3106. if (!strcmp(cl->key, "--hush"))
  3107. quiet = 1;
  3108. if (!strcmp(cl->key, "--quiet") ||
  3109. !strcmp(cl->key, "--dump-config"))
  3110. quiet = 2;
  3111. /* The following options imply --hush */
  3112. if (!strcmp(cl->key, "--version") || !strcmp(cl->key, "--digests") ||
  3113. !strcmp(cl->key, "--list-torrc-options") ||
  3114. !strcmp(cl->key, "--library-versions") ||
  3115. !strcmp(cl->key, "--hash-password") ||
  3116. !strcmp(cl->key, "-h") || !strcmp(cl->key, "--help")) {
  3117. if (quiet < 1)
  3118. quiet = 1;
  3119. }
  3120. }
  3121. config_free_lines(opts);
  3122. config_free_lines(cmdline_opts);
  3123. }
  3124. /* give it somewhere to log to initially */
  3125. switch (quiet) {
  3126. case 2:
  3127. /* no initial logging */
  3128. break;
  3129. case 1:
  3130. add_temp_log(LOG_WARN);
  3131. break;
  3132. default:
  3133. add_temp_log(LOG_NOTICE);
  3134. }
  3135. quiet_level = quiet;
  3136. {
  3137. const char *version = get_version();
  3138. log_notice(LD_GENERAL, "Tor %s running on %s with Libevent %s, "
  3139. "OpenSSL %s, Zlib %s, Liblzma %s, and Libzstd %s.", version,
  3140. get_uname(),
  3141. tor_libevent_get_version_str(),
  3142. crypto_openssl_get_version_str(),
  3143. tor_compress_supports_method(ZLIB_METHOD) ?
  3144. tor_compress_version_str(ZLIB_METHOD) : "N/A",
  3145. tor_compress_supports_method(LZMA_METHOD) ?
  3146. tor_compress_version_str(LZMA_METHOD) : "N/A",
  3147. tor_compress_supports_method(ZSTD_METHOD) ?
  3148. tor_compress_version_str(ZSTD_METHOD) : "N/A");
  3149. log_notice(LD_GENERAL, "Tor can't help you if you use it wrong! "
  3150. "Learn how to be safe at "
  3151. "https://www.torproject.org/download/download#warning");
  3152. if (strstr(version, "alpha") || strstr(version, "beta"))
  3153. log_notice(LD_GENERAL, "This version is not a stable Tor release. "
  3154. "Expect more bugs than usual.");
  3155. tor_compress_log_init_warnings();
  3156. }
  3157. #ifdef HAVE_RUST
  3158. rust_log_welcome_string();
  3159. #endif /* defined(HAVE_RUST) */
  3160. if (network_init()<0) {
  3161. log_err(LD_BUG,"Error initializing network; exiting.");
  3162. return -1;
  3163. }
  3164. atexit(exit_function);
  3165. int init_rv = options_init_from_torrc(argc,argv);
  3166. if (init_rv < 0) {
  3167. log_err(LD_CONFIG,"Reading config failed--see warnings above.");
  3168. return -1;
  3169. } else if (init_rv > 0) {
  3170. // We succeeded, and should exit anyway -- probably the user just said
  3171. // "--version" or something like that.
  3172. return 1;
  3173. }
  3174. /* The options are now initialised */
  3175. const or_options_t *options = get_options();
  3176. /* Initialize channelpadding parameters to defaults until we get
  3177. * a consensus */
  3178. channelpadding_new_consensus_params(NULL);
  3179. /* Initialize predicted ports list after loading options */
  3180. predicted_ports_init();
  3181. #ifndef _WIN32
  3182. if (geteuid()==0)
  3183. log_warn(LD_GENERAL,"You are running Tor as root. You don't need to, "
  3184. "and you probably shouldn't.");
  3185. #endif
  3186. if (crypto_global_init(options->HardwareAccel,
  3187. options->AccelName,
  3188. options->AccelDir)) {
  3189. log_err(LD_BUG, "Unable to initialize OpenSSL. Exiting.");
  3190. return -1;
  3191. }
  3192. stream_choice_seed_weak_rng();
  3193. if (tor_init_libevent_rng() < 0) {
  3194. log_warn(LD_NET, "Problem initializing libevent RNG.");
  3195. }
  3196. /* Scan/clean unparseable descriptors; after reading config */
  3197. routerparse_init();
  3198. return 0;
  3199. }
  3200. /** A lockfile structure, used to prevent two Tors from messing with the
  3201. * data directory at once. If this variable is non-NULL, we're holding
  3202. * the lockfile. */
  3203. static tor_lockfile_t *lockfile = NULL;
  3204. /** Try to grab the lock file described in <b>options</b>, if we do not
  3205. * already have it. If <b>err_if_locked</b> is true, warn if somebody else is
  3206. * holding the lock, and exit if we can't get it after waiting. Otherwise,
  3207. * return -1 if we can't get the lockfile. Return 0 on success.
  3208. */
  3209. int
  3210. try_locking(const or_options_t *options, int err_if_locked)
  3211. {
  3212. if (lockfile)
  3213. return 0;
  3214. else {
  3215. char *fname = options_get_datadir_fname(options, "lock");
  3216. int already_locked = 0;
  3217. tor_lockfile_t *lf = tor_lockfile_lock(fname, 0, &already_locked);
  3218. tor_free(fname);
  3219. if (!lf) {
  3220. if (err_if_locked && already_locked) {
  3221. int r;
  3222. log_warn(LD_GENERAL, "It looks like another Tor process is running "
  3223. "with the same data directory. Waiting 5 seconds to see "
  3224. "if it goes away.");
  3225. #ifndef _WIN32
  3226. sleep(5);
  3227. #else
  3228. Sleep(5000);
  3229. #endif
  3230. r = try_locking(options, 0);
  3231. if (r<0) {
  3232. log_err(LD_GENERAL, "No, it's still there. Exiting.");
  3233. return -1;
  3234. }
  3235. return r;
  3236. }
  3237. return -1;
  3238. }
  3239. lockfile = lf;
  3240. return 0;
  3241. }
  3242. }
  3243. /** Return true iff we've successfully acquired the lock file. */
  3244. int
  3245. have_lockfile(void)
  3246. {
  3247. return lockfile != NULL;
  3248. }
  3249. /** If we have successfully acquired the lock file, release it. */
  3250. void
  3251. release_lockfile(void)
  3252. {
  3253. if (lockfile) {
  3254. tor_lockfile_unlock(lockfile);
  3255. lockfile = NULL;
  3256. }
  3257. }
  3258. /** Free all memory that we might have allocated somewhere.
  3259. * If <b>postfork</b>, we are a worker process and we want to free
  3260. * only the parts of memory that we won't touch. If !<b>postfork</b>,
  3261. * Tor is shutting down and we should free everything.
  3262. *
  3263. * Helps us find the real leaks with sanitizers and the like. Also valgrind
  3264. * should then report 0 reachable in its leak report (in an ideal world --
  3265. * in practice libevent, SSL, libc etc never quite free everything). */
  3266. void
  3267. tor_free_all(int postfork)
  3268. {
  3269. if (!postfork) {
  3270. evdns_shutdown(1);
  3271. }
  3272. geoip_free_all();
  3273. dirvote_free_all();
  3274. routerlist_free_all();
  3275. networkstatus_free_all();
  3276. addressmap_free_all();
  3277. dirserv_free_all();
  3278. rend_cache_free_all();
  3279. rend_service_authorization_free_all();
  3280. rep_hist_free_all();
  3281. dns_free_all();
  3282. clear_pending_onions();
  3283. circuit_free_all();
  3284. entry_guards_free_all();
  3285. pt_free_all();
  3286. channel_tls_free_all();
  3287. channel_free_all();
  3288. connection_free_all();
  3289. connection_edge_free_all();
  3290. scheduler_free_all();
  3291. nodelist_free_all();
  3292. microdesc_free_all();
  3293. routerparse_free_all();
  3294. ext_orport_free_all();
  3295. control_free_all();
  3296. tor_free_getaddrinfo_cache();
  3297. protover_free_all();
  3298. bridges_free_all();
  3299. consdiffmgr_free_all();
  3300. hs_free_all();
  3301. dos_free_all();
  3302. circuitmux_ewma_free_all();
  3303. accounting_free_all();
  3304. if (!postfork) {
  3305. config_free_all();
  3306. or_state_free_all();
  3307. router_free_all();
  3308. routerkeys_free_all();
  3309. policies_free_all();
  3310. }
  3311. if (!postfork) {
  3312. tor_tls_free_all();
  3313. #ifndef _WIN32
  3314. tor_getpwnam(NULL);
  3315. #endif
  3316. }
  3317. /* stuff in main.c */
  3318. smartlist_free(connection_array);
  3319. smartlist_free(closeable_connection_lst);
  3320. smartlist_free(active_linked_connection_lst);
  3321. periodic_timer_free(second_timer);
  3322. teardown_periodic_events();
  3323. tor_event_free(shutdown_did_not_work_event);
  3324. tor_event_free(initialize_periodic_events_event);
  3325. mainloop_event_free(directory_all_unreachable_cb_event);
  3326. mainloop_event_free(schedule_active_linked_connections_event);
  3327. mainloop_event_free(postloop_cleanup_ev);
  3328. mainloop_event_free(handle_deferred_signewnym_ev);
  3329. #ifdef HAVE_SYSTEMD_209
  3330. periodic_timer_free(systemd_watchdog_timer);
  3331. #endif
  3332. memset(&global_bucket, 0, sizeof(global_bucket));
  3333. memset(&global_relayed_bucket, 0, sizeof(global_relayed_bucket));
  3334. stats_n_bytes_read = stats_n_bytes_written = 0;
  3335. time_of_process_start = 0;
  3336. time_of_last_signewnym = 0;
  3337. signewnym_is_pending = 0;
  3338. newnym_epoch = 0;
  3339. called_loop_once = 0;
  3340. main_loop_should_exit = 0;
  3341. main_loop_exit_value = 0;
  3342. can_complete_circuits = 0;
  3343. quiet_level = 0;
  3344. should_init_bridge_stats = 1;
  3345. dns_honesty_first_time = 1;
  3346. heartbeat_callback_first_time = 1;
  3347. current_second = 0;
  3348. memset(&current_second_last_changed, 0,
  3349. sizeof(current_second_last_changed));
  3350. if (!postfork) {
  3351. release_lockfile();
  3352. }
  3353. tor_libevent_free_all();
  3354. /* Stuff in util.c and address.c*/
  3355. if (!postfork) {
  3356. escaped(NULL);
  3357. esc_router_info(NULL);
  3358. clean_up_backtrace_handler();
  3359. logs_free_all(); /* free log strings. do this last so logs keep working. */
  3360. }
  3361. }
  3362. /**
  3363. * Remove the specified file, and log a warning if the operation fails for
  3364. * any reason other than the file not existing. Ignores NULL filenames.
  3365. */
  3366. void
  3367. tor_remove_file(const char *filename)
  3368. {
  3369. if (filename && tor_unlink(filename) != 0 && errno != ENOENT) {
  3370. log_warn(LD_FS, "Couldn't unlink %s: %s",
  3371. filename, strerror(errno));
  3372. }
  3373. }
  3374. /** Do whatever cleanup is necessary before shutting Tor down. */
  3375. void
  3376. tor_cleanup(void)
  3377. {
  3378. const or_options_t *options = get_options();
  3379. if (options->command == CMD_RUN_TOR) {
  3380. time_t now = time(NULL);
  3381. /* Remove our pid file. We don't care if there was an error when we
  3382. * unlink, nothing we could do about it anyways. */
  3383. tor_remove_file(options->PidFile);
  3384. /* Remove control port file */
  3385. tor_remove_file(options->ControlPortWriteToFile);
  3386. /* Remove cookie authentication file */
  3387. {
  3388. char *cookie_fname = get_controller_cookie_file_name();
  3389. tor_remove_file(cookie_fname);
  3390. tor_free(cookie_fname);
  3391. }
  3392. /* Remove Extended ORPort cookie authentication file */
  3393. {
  3394. char *cookie_fname = get_ext_or_auth_cookie_file_name();
  3395. tor_remove_file(cookie_fname);
  3396. tor_free(cookie_fname);
  3397. }
  3398. if (accounting_is_enabled(options))
  3399. accounting_record_bandwidth_usage(now, get_or_state());
  3400. or_state_mark_dirty(get_or_state(), 0); /* force an immediate save. */
  3401. or_state_save(now);
  3402. if (authdir_mode(options)) {
  3403. sr_save_and_cleanup();
  3404. }
  3405. if (authdir_mode_tests_reachability(options))
  3406. rep_hist_record_mtbf_data(now, 0);
  3407. keypin_close_journal();
  3408. }
  3409. timers_shutdown();
  3410. tor_free_all(0); /* We could move tor_free_all back into the ifdef below
  3411. later, if it makes shutdown unacceptably slow. But for
  3412. now, leave it here: it's helped us catch bugs in the
  3413. past. */
  3414. crypto_global_cleanup();
  3415. }
  3416. /** Read/create keys as needed, and echo our fingerprint to stdout. */
  3417. static int
  3418. do_list_fingerprint(void)
  3419. {
  3420. char buf[FINGERPRINT_LEN+1];
  3421. crypto_pk_t *k;
  3422. const char *nickname = get_options()->Nickname;
  3423. sandbox_disable_getaddrinfo_cache();
  3424. if (!server_mode(get_options())) {
  3425. log_err(LD_GENERAL,
  3426. "Clients don't have long-term identity keys. Exiting.");
  3427. return -1;
  3428. }
  3429. tor_assert(nickname);
  3430. if (init_keys() < 0) {
  3431. log_err(LD_GENERAL,"Error initializing keys; exiting.");
  3432. return -1;
  3433. }
  3434. if (!(k = get_server_identity_key())) {
  3435. log_err(LD_GENERAL,"Error: missing identity key.");
  3436. return -1;
  3437. }
  3438. if (crypto_pk_get_fingerprint(k, buf, 1)<0) {
  3439. log_err(LD_BUG, "Error computing fingerprint");
  3440. return -1;
  3441. }
  3442. printf("%s %s\n", nickname, buf);
  3443. return 0;
  3444. }
  3445. /** Entry point for password hashing: take the desired password from
  3446. * the command line, and print its salted hash to stdout. **/
  3447. static void
  3448. do_hash_password(void)
  3449. {
  3450. char output[256];
  3451. char key[S2K_RFC2440_SPECIFIER_LEN+DIGEST_LEN];
  3452. crypto_rand(key, S2K_RFC2440_SPECIFIER_LEN-1);
  3453. key[S2K_RFC2440_SPECIFIER_LEN-1] = (uint8_t)96; /* Hash 64 K of data. */
  3454. secret_to_key_rfc2440(key+S2K_RFC2440_SPECIFIER_LEN, DIGEST_LEN,
  3455. get_options()->command_arg, strlen(get_options()->command_arg),
  3456. key);
  3457. base16_encode(output, sizeof(output), key, sizeof(key));
  3458. printf("16:%s\n",output);
  3459. }
  3460. /** Entry point for configuration dumping: write the configuration to
  3461. * stdout. */
  3462. static int
  3463. do_dump_config(void)
  3464. {
  3465. const or_options_t *options = get_options();
  3466. const char *arg = options->command_arg;
  3467. int how;
  3468. char *opts;
  3469. if (!strcmp(arg, "short")) {
  3470. how = OPTIONS_DUMP_MINIMAL;
  3471. } else if (!strcmp(arg, "non-builtin")) {
  3472. how = OPTIONS_DUMP_DEFAULTS;
  3473. } else if (!strcmp(arg, "full")) {
  3474. how = OPTIONS_DUMP_ALL;
  3475. } else {
  3476. fprintf(stderr, "No valid argument to --dump-config found!\n");
  3477. fprintf(stderr, "Please select 'short', 'non-builtin', or 'full'.\n");
  3478. return -1;
  3479. }
  3480. opts = options_dump(options, how);
  3481. printf("%s", opts);
  3482. tor_free(opts);
  3483. return 0;
  3484. }
  3485. static void
  3486. init_addrinfo(void)
  3487. {
  3488. if (! server_mode(get_options()) ||
  3489. (get_options()->Address && strlen(get_options()->Address) > 0)) {
  3490. /* We don't need to seed our own hostname, because we won't be calling
  3491. * resolve_my_address on it.
  3492. */
  3493. return;
  3494. }
  3495. char hname[256];
  3496. // host name to sandbox
  3497. gethostname(hname, sizeof(hname));
  3498. tor_add_addrinfo(hname);
  3499. }
  3500. static sandbox_cfg_t*
  3501. sandbox_init_filter(void)
  3502. {
  3503. const or_options_t *options = get_options();
  3504. sandbox_cfg_t *cfg = sandbox_cfg_new();
  3505. int i;
  3506. sandbox_cfg_allow_openat_filename(&cfg,
  3507. get_cachedir_fname("cached-status"));
  3508. #define OPEN(name) \
  3509. sandbox_cfg_allow_open_filename(&cfg, tor_strdup(name))
  3510. #define OPEN_DATADIR(name) \
  3511. sandbox_cfg_allow_open_filename(&cfg, get_datadir_fname(name))
  3512. #define OPEN_DATADIR2(name, name2) \
  3513. sandbox_cfg_allow_open_filename(&cfg, get_datadir_fname2((name), (name2)))
  3514. #define OPEN_DATADIR_SUFFIX(name, suffix) do { \
  3515. OPEN_DATADIR(name); \
  3516. OPEN_DATADIR(name suffix); \
  3517. } while (0)
  3518. #define OPEN_DATADIR2_SUFFIX(name, name2, suffix) do { \
  3519. OPEN_DATADIR2(name, name2); \
  3520. OPEN_DATADIR2(name, name2 suffix); \
  3521. } while (0)
  3522. #define OPEN_KEY_DIRECTORY() \
  3523. sandbox_cfg_allow_open_filename(&cfg, tor_strdup(options->KeyDirectory))
  3524. #define OPEN_CACHEDIR(name) \
  3525. sandbox_cfg_allow_open_filename(&cfg, get_cachedir_fname(name))
  3526. #define OPEN_CACHEDIR_SUFFIX(name, suffix) do { \
  3527. OPEN_CACHEDIR(name); \
  3528. OPEN_CACHEDIR(name suffix); \
  3529. } while (0)
  3530. #define OPEN_KEYDIR(name) \
  3531. sandbox_cfg_allow_open_filename(&cfg, get_keydir_fname(name))
  3532. #define OPEN_KEYDIR_SUFFIX(name, suffix) do { \
  3533. OPEN_KEYDIR(name); \
  3534. OPEN_KEYDIR(name suffix); \
  3535. } while (0)
  3536. OPEN(options->DataDirectory);
  3537. OPEN_KEY_DIRECTORY();
  3538. OPEN_CACHEDIR_SUFFIX("cached-certs", ".tmp");
  3539. OPEN_CACHEDIR_SUFFIX("cached-consensus", ".tmp");
  3540. OPEN_CACHEDIR_SUFFIX("unverified-consensus", ".tmp");
  3541. OPEN_CACHEDIR_SUFFIX("unverified-microdesc-consensus", ".tmp");
  3542. OPEN_CACHEDIR_SUFFIX("cached-microdesc-consensus", ".tmp");
  3543. OPEN_CACHEDIR_SUFFIX("cached-microdescs", ".tmp");
  3544. OPEN_CACHEDIR_SUFFIX("cached-microdescs.new", ".tmp");
  3545. OPEN_CACHEDIR_SUFFIX("cached-descriptors", ".tmp");
  3546. OPEN_CACHEDIR_SUFFIX("cached-descriptors.new", ".tmp");
  3547. OPEN_CACHEDIR("cached-descriptors.tmp.tmp");
  3548. OPEN_CACHEDIR_SUFFIX("cached-extrainfo", ".tmp");
  3549. OPEN_CACHEDIR_SUFFIX("cached-extrainfo.new", ".tmp");
  3550. OPEN_CACHEDIR("cached-extrainfo.tmp.tmp");
  3551. OPEN_DATADIR_SUFFIX("state", ".tmp");
  3552. OPEN_DATADIR_SUFFIX("sr-state", ".tmp");
  3553. OPEN_DATADIR_SUFFIX("unparseable-desc", ".tmp");
  3554. OPEN_DATADIR_SUFFIX("v3-status-votes", ".tmp");
  3555. OPEN_DATADIR("key-pinning-journal");
  3556. OPEN("/dev/srandom");
  3557. OPEN("/dev/urandom");
  3558. OPEN("/dev/random");
  3559. OPEN("/etc/hosts");
  3560. OPEN("/proc/meminfo");
  3561. if (options->BridgeAuthoritativeDir)
  3562. OPEN_DATADIR_SUFFIX("networkstatus-bridges", ".tmp");
  3563. if (authdir_mode(options))
  3564. OPEN_DATADIR("approved-routers");
  3565. if (options->ServerDNSResolvConfFile)
  3566. sandbox_cfg_allow_open_filename(&cfg,
  3567. tor_strdup(options->ServerDNSResolvConfFile));
  3568. else
  3569. sandbox_cfg_allow_open_filename(&cfg, tor_strdup("/etc/resolv.conf"));
  3570. for (i = 0; i < 2; ++i) {
  3571. if (get_torrc_fname(i)) {
  3572. sandbox_cfg_allow_open_filename(&cfg, tor_strdup(get_torrc_fname(i)));
  3573. }
  3574. }
  3575. SMARTLIST_FOREACH(options->FilesOpenedByIncludes, char *, f, {
  3576. OPEN(f);
  3577. });
  3578. #define RENAME_SUFFIX(name, suffix) \
  3579. sandbox_cfg_allow_rename(&cfg, \
  3580. get_datadir_fname(name suffix), \
  3581. get_datadir_fname(name))
  3582. #define RENAME_SUFFIX2(prefix, name, suffix) \
  3583. sandbox_cfg_allow_rename(&cfg, \
  3584. get_datadir_fname2(prefix, name suffix), \
  3585. get_datadir_fname2(prefix, name))
  3586. #define RENAME_CACHEDIR_SUFFIX(name, suffix) \
  3587. sandbox_cfg_allow_rename(&cfg, \
  3588. get_cachedir_fname(name suffix), \
  3589. get_cachedir_fname(name))
  3590. #define RENAME_KEYDIR_SUFFIX(name, suffix) \
  3591. sandbox_cfg_allow_rename(&cfg, \
  3592. get_keydir_fname(name suffix), \
  3593. get_keydir_fname(name))
  3594. RENAME_CACHEDIR_SUFFIX("cached-certs", ".tmp");
  3595. RENAME_CACHEDIR_SUFFIX("cached-consensus", ".tmp");
  3596. RENAME_CACHEDIR_SUFFIX("unverified-consensus", ".tmp");
  3597. RENAME_CACHEDIR_SUFFIX("unverified-microdesc-consensus", ".tmp");
  3598. RENAME_CACHEDIR_SUFFIX("cached-microdesc-consensus", ".tmp");
  3599. RENAME_CACHEDIR_SUFFIX("cached-microdescs", ".tmp");
  3600. RENAME_CACHEDIR_SUFFIX("cached-microdescs", ".new");
  3601. RENAME_CACHEDIR_SUFFIX("cached-microdescs.new", ".tmp");
  3602. RENAME_CACHEDIR_SUFFIX("cached-descriptors", ".tmp");
  3603. RENAME_CACHEDIR_SUFFIX("cached-descriptors", ".new");
  3604. RENAME_CACHEDIR_SUFFIX("cached-descriptors.new", ".tmp");
  3605. RENAME_CACHEDIR_SUFFIX("cached-extrainfo", ".tmp");
  3606. RENAME_CACHEDIR_SUFFIX("cached-extrainfo", ".new");
  3607. RENAME_CACHEDIR_SUFFIX("cached-extrainfo.new", ".tmp");
  3608. RENAME_SUFFIX("state", ".tmp");
  3609. RENAME_SUFFIX("sr-state", ".tmp");
  3610. RENAME_SUFFIX("unparseable-desc", ".tmp");
  3611. RENAME_SUFFIX("v3-status-votes", ".tmp");
  3612. if (options->BridgeAuthoritativeDir)
  3613. RENAME_SUFFIX("networkstatus-bridges", ".tmp");
  3614. #define STAT_DATADIR(name) \
  3615. sandbox_cfg_allow_stat_filename(&cfg, get_datadir_fname(name))
  3616. #define STAT_CACHEDIR(name) \
  3617. sandbox_cfg_allow_stat_filename(&cfg, get_cachedir_fname(name))
  3618. #define STAT_DATADIR2(name, name2) \
  3619. sandbox_cfg_allow_stat_filename(&cfg, get_datadir_fname2((name), (name2)))
  3620. #define STAT_KEY_DIRECTORY() \
  3621. sandbox_cfg_allow_stat_filename(&cfg, tor_strdup(options->KeyDirectory))
  3622. STAT_DATADIR(NULL);
  3623. STAT_DATADIR("lock");
  3624. STAT_DATADIR("state");
  3625. STAT_DATADIR("router-stability");
  3626. STAT_CACHEDIR("cached-extrainfo.new");
  3627. {
  3628. smartlist_t *files = smartlist_new();
  3629. tor_log_get_logfile_names(files);
  3630. SMARTLIST_FOREACH(files, char *, file_name, {
  3631. /* steals reference */
  3632. sandbox_cfg_allow_open_filename(&cfg, file_name);
  3633. });
  3634. smartlist_free(files);
  3635. }
  3636. {
  3637. smartlist_t *files = smartlist_new();
  3638. smartlist_t *dirs = smartlist_new();
  3639. hs_service_lists_fnames_for_sandbox(files, dirs);
  3640. SMARTLIST_FOREACH(files, char *, file_name, {
  3641. char *tmp_name = NULL;
  3642. tor_asprintf(&tmp_name, "%s.tmp", file_name);
  3643. sandbox_cfg_allow_rename(&cfg,
  3644. tor_strdup(tmp_name), tor_strdup(file_name));
  3645. /* steals references */
  3646. sandbox_cfg_allow_open_filename(&cfg, file_name);
  3647. sandbox_cfg_allow_open_filename(&cfg, tmp_name);
  3648. });
  3649. SMARTLIST_FOREACH(dirs, char *, dir, {
  3650. /* steals reference */
  3651. sandbox_cfg_allow_stat_filename(&cfg, dir);
  3652. });
  3653. smartlist_free(files);
  3654. smartlist_free(dirs);
  3655. }
  3656. {
  3657. char *fname;
  3658. if ((fname = get_controller_cookie_file_name())) {
  3659. sandbox_cfg_allow_open_filename(&cfg, fname);
  3660. }
  3661. if ((fname = get_ext_or_auth_cookie_file_name())) {
  3662. sandbox_cfg_allow_open_filename(&cfg, fname);
  3663. }
  3664. }
  3665. SMARTLIST_FOREACH_BEGIN(get_configured_ports(), port_cfg_t *, port) {
  3666. if (!port->is_unix_addr)
  3667. continue;
  3668. /* When we open an AF_UNIX address, we want permission to open the
  3669. * directory that holds it. */
  3670. char *dirname = tor_strdup(port->unix_addr);
  3671. if (get_parent_directory(dirname) == 0) {
  3672. OPEN(dirname);
  3673. }
  3674. tor_free(dirname);
  3675. sandbox_cfg_allow_chmod_filename(&cfg, tor_strdup(port->unix_addr));
  3676. sandbox_cfg_allow_chown_filename(&cfg, tor_strdup(port->unix_addr));
  3677. } SMARTLIST_FOREACH_END(port);
  3678. if (options->DirPortFrontPage) {
  3679. sandbox_cfg_allow_open_filename(&cfg,
  3680. tor_strdup(options->DirPortFrontPage));
  3681. }
  3682. // orport
  3683. if (server_mode(get_options())) {
  3684. OPEN_KEYDIR_SUFFIX("secret_id_key", ".tmp");
  3685. OPEN_KEYDIR_SUFFIX("secret_onion_key", ".tmp");
  3686. OPEN_KEYDIR_SUFFIX("secret_onion_key_ntor", ".tmp");
  3687. OPEN_KEYDIR("secret_id_key.old");
  3688. OPEN_KEYDIR("secret_onion_key.old");
  3689. OPEN_KEYDIR("secret_onion_key_ntor.old");
  3690. OPEN_KEYDIR_SUFFIX("ed25519_master_id_secret_key", ".tmp");
  3691. OPEN_KEYDIR_SUFFIX("ed25519_master_id_secret_key_encrypted", ".tmp");
  3692. OPEN_KEYDIR_SUFFIX("ed25519_master_id_public_key", ".tmp");
  3693. OPEN_KEYDIR_SUFFIX("ed25519_signing_secret_key", ".tmp");
  3694. OPEN_KEYDIR_SUFFIX("ed25519_signing_secret_key_encrypted", ".tmp");
  3695. OPEN_KEYDIR_SUFFIX("ed25519_signing_public_key", ".tmp");
  3696. OPEN_KEYDIR_SUFFIX("ed25519_signing_cert", ".tmp");
  3697. OPEN_DATADIR2_SUFFIX("stats", "bridge-stats", ".tmp");
  3698. OPEN_DATADIR2_SUFFIX("stats", "dirreq-stats", ".tmp");
  3699. OPEN_DATADIR2_SUFFIX("stats", "entry-stats", ".tmp");
  3700. OPEN_DATADIR2_SUFFIX("stats", "exit-stats", ".tmp");
  3701. OPEN_DATADIR2_SUFFIX("stats", "buffer-stats", ".tmp");
  3702. OPEN_DATADIR2_SUFFIX("stats", "conn-stats", ".tmp");
  3703. OPEN_DATADIR2_SUFFIX("stats", "hidserv-stats", ".tmp");
  3704. OPEN_DATADIR("approved-routers");
  3705. OPEN_DATADIR_SUFFIX("fingerprint", ".tmp");
  3706. OPEN_DATADIR_SUFFIX("hashed-fingerprint", ".tmp");
  3707. OPEN_DATADIR_SUFFIX("router-stability", ".tmp");
  3708. OPEN("/etc/resolv.conf");
  3709. RENAME_SUFFIX("fingerprint", ".tmp");
  3710. RENAME_KEYDIR_SUFFIX("secret_onion_key_ntor", ".tmp");
  3711. RENAME_KEYDIR_SUFFIX("secret_id_key", ".tmp");
  3712. RENAME_KEYDIR_SUFFIX("secret_id_key.old", ".tmp");
  3713. RENAME_KEYDIR_SUFFIX("secret_onion_key", ".tmp");
  3714. RENAME_KEYDIR_SUFFIX("secret_onion_key.old", ".tmp");
  3715. RENAME_SUFFIX2("stats", "bridge-stats", ".tmp");
  3716. RENAME_SUFFIX2("stats", "dirreq-stats", ".tmp");
  3717. RENAME_SUFFIX2("stats", "entry-stats", ".tmp");
  3718. RENAME_SUFFIX2("stats", "exit-stats", ".tmp");
  3719. RENAME_SUFFIX2("stats", "buffer-stats", ".tmp");
  3720. RENAME_SUFFIX2("stats", "conn-stats", ".tmp");
  3721. RENAME_SUFFIX2("stats", "hidserv-stats", ".tmp");
  3722. RENAME_SUFFIX("hashed-fingerprint", ".tmp");
  3723. RENAME_SUFFIX("router-stability", ".tmp");
  3724. RENAME_KEYDIR_SUFFIX("ed25519_master_id_secret_key", ".tmp");
  3725. RENAME_KEYDIR_SUFFIX("ed25519_master_id_secret_key_encrypted", ".tmp");
  3726. RENAME_KEYDIR_SUFFIX("ed25519_master_id_public_key", ".tmp");
  3727. RENAME_KEYDIR_SUFFIX("ed25519_signing_secret_key", ".tmp");
  3728. RENAME_KEYDIR_SUFFIX("ed25519_signing_cert", ".tmp");
  3729. sandbox_cfg_allow_rename(&cfg,
  3730. get_keydir_fname("secret_onion_key"),
  3731. get_keydir_fname("secret_onion_key.old"));
  3732. sandbox_cfg_allow_rename(&cfg,
  3733. get_keydir_fname("secret_onion_key_ntor"),
  3734. get_keydir_fname("secret_onion_key_ntor.old"));
  3735. STAT_KEY_DIRECTORY();
  3736. OPEN_DATADIR("stats");
  3737. STAT_DATADIR("stats");
  3738. STAT_DATADIR2("stats", "dirreq-stats");
  3739. consdiffmgr_register_with_sandbox(&cfg);
  3740. }
  3741. init_addrinfo();
  3742. return cfg;
  3743. }
  3744. /* Main entry point for the Tor process. Called from tor_main(), and by
  3745. * anybody embedding Tor. */
  3746. int
  3747. tor_run_main(const tor_main_configuration_t *tor_cfg)
  3748. {
  3749. int result = 0;
  3750. int argc = tor_cfg->argc;
  3751. char **argv = tor_cfg->argv;
  3752. #ifdef _WIN32
  3753. #ifndef HeapEnableTerminationOnCorruption
  3754. #define HeapEnableTerminationOnCorruption 1
  3755. #endif
  3756. /* On heap corruption, just give up; don't try to play along. */
  3757. HeapSetInformation(NULL, HeapEnableTerminationOnCorruption, NULL, 0);
  3758. /* Call SetProcessDEPPolicy to permanently enable DEP.
  3759. The function will not resolve on earlier versions of Windows,
  3760. and failure is not dangerous. */
  3761. HMODULE hMod = GetModuleHandleA("Kernel32.dll");
  3762. if (hMod) {
  3763. typedef BOOL (WINAPI *PSETDEP)(DWORD);
  3764. PSETDEP setdeppolicy = (PSETDEP)GetProcAddress(hMod,
  3765. "SetProcessDEPPolicy");
  3766. if (setdeppolicy) {
  3767. /* PROCESS_DEP_ENABLE | PROCESS_DEP_DISABLE_ATL_THUNK_EMULATION */
  3768. setdeppolicy(3);
  3769. }
  3770. }
  3771. #endif /* defined(_WIN32) */
  3772. {
  3773. int bt_err = configure_backtrace_handler(get_version());
  3774. if (bt_err < 0) {
  3775. log_warn(LD_BUG, "Unable to install backtrace handler: %s",
  3776. strerror(-bt_err));
  3777. }
  3778. }
  3779. init_protocol_warning_severity_level();
  3780. update_approx_time(time(NULL));
  3781. tor_threads_init();
  3782. tor_compress_init();
  3783. init_logging(0);
  3784. monotime_init();
  3785. #ifdef NT_SERVICE
  3786. {
  3787. int done = 0;
  3788. result = nt_service_parse_options(argc, argv, &done);
  3789. if (done) return result;
  3790. }
  3791. #endif /* defined(NT_SERVICE) */
  3792. {
  3793. int init_rv = tor_init(argc, argv);
  3794. if (init_rv < 0)
  3795. return -1;
  3796. else if (init_rv > 0)
  3797. return 0;
  3798. }
  3799. if (get_options()->Sandbox && get_options()->command == CMD_RUN_TOR) {
  3800. sandbox_cfg_t* cfg = sandbox_init_filter();
  3801. if (sandbox_init(cfg)) {
  3802. log_err(LD_BUG,"Failed to create syscall sandbox filter");
  3803. return -1;
  3804. }
  3805. // registering libevent rng
  3806. #ifdef HAVE_EVUTIL_SECURE_RNG_SET_URANDOM_DEVICE_FILE
  3807. evutil_secure_rng_set_urandom_device_file(
  3808. (char*) sandbox_intern_string("/dev/urandom"));
  3809. #endif
  3810. }
  3811. switch (get_options()->command) {
  3812. case CMD_RUN_TOR:
  3813. #ifdef NT_SERVICE
  3814. nt_service_set_state(SERVICE_RUNNING);
  3815. #endif
  3816. result = do_main_loop();
  3817. break;
  3818. case CMD_KEYGEN:
  3819. result = load_ed_keys(get_options(), time(NULL)) < 0;
  3820. break;
  3821. case CMD_KEY_EXPIRATION:
  3822. init_keys();
  3823. result = log_cert_expiration();
  3824. break;
  3825. case CMD_LIST_FINGERPRINT:
  3826. result = do_list_fingerprint();
  3827. break;
  3828. case CMD_HASH_PASSWORD:
  3829. do_hash_password();
  3830. result = 0;
  3831. break;
  3832. case CMD_VERIFY_CONFIG:
  3833. if (quiet_level == 0)
  3834. printf("Configuration was valid\n");
  3835. result = 0;
  3836. break;
  3837. case CMD_DUMP_CONFIG:
  3838. result = do_dump_config();
  3839. break;
  3840. case CMD_RUN_UNITTESTS: /* only set by test.c */
  3841. default:
  3842. log_warn(LD_BUG,"Illegal command number %d: internal error.",
  3843. get_options()->command);
  3844. result = -1;
  3845. }
  3846. tor_cleanup();
  3847. return result;
  3848. }