main.c 118 KB

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