main.c 131 KB

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