main.c 137 KB

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