main.c 128 KB

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