main.c 121 KB

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