main.c 130 KB

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