main.c 130 KB

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