main.c 124 KB

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