main.c 136 KB

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