main.c 130 KB

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