main.c 137 KB

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