main.c 130 KB

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