main.c 137 KB

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