main.c 123 KB

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