main.c 136 KB

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