main.c 136 KB

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