main.c 111 KB

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