main.c 123 KB

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