control.c 137 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099
  1. /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  2. * Copyright (c) 2007-2011, The Tor Project, Inc. */
  3. /* See LICENSE for licensing information */
  4. /**
  5. * \file control.c
  6. * \brief Implementation for Tor's control-socket interface.
  7. * See doc/spec/control-spec.txt for full details on protocol.
  8. **/
  9. #define CONTROL_PRIVATE
  10. #include "or.h"
  11. #include "buffers.h"
  12. #include "circuitbuild.h"
  13. #include "circuitlist.h"
  14. #include "circuituse.h"
  15. #include "config.h"
  16. #include "connection.h"
  17. #include "connection_edge.h"
  18. #include "control.h"
  19. #include "directory.h"
  20. #include "dirserv.h"
  21. #include "dnsserv.h"
  22. #include "geoip.h"
  23. #include "hibernate.h"
  24. #include "main.h"
  25. #include "networkstatus.h"
  26. #include "nodelist.h"
  27. #include "policies.h"
  28. #include "reasons.h"
  29. #include "router.h"
  30. #include "routerlist.h"
  31. #include "routerparse.h"
  32. #ifndef MS_WINDOWS
  33. #include <pwd.h>
  34. #include <sys/resource.h>
  35. #endif
  36. /** Yield true iff <b>s</b> is the state of a control_connection_t that has
  37. * finished authentication and is accepting commands. */
  38. #define STATE_IS_OPEN(s) ((s) == CONTROL_CONN_STATE_OPEN)
  39. /* Recognized asynchronous event types. It's okay to expand this list
  40. * because it is used both as a list of v0 event types, and as indices
  41. * into the bitfield to determine which controllers want which events.
  42. */
  43. #define _EVENT_MIN 0x0001
  44. #define EVENT_CIRCUIT_STATUS 0x0001
  45. #define EVENT_STREAM_STATUS 0x0002
  46. #define EVENT_OR_CONN_STATUS 0x0003
  47. #define EVENT_BANDWIDTH_USED 0x0004
  48. #define EVENT_LOG_OBSOLETE 0x0005 /* Can reclaim this. */
  49. #define EVENT_NEW_DESC 0x0006
  50. #define EVENT_DEBUG_MSG 0x0007
  51. #define EVENT_INFO_MSG 0x0008
  52. #define EVENT_NOTICE_MSG 0x0009
  53. #define EVENT_WARN_MSG 0x000A
  54. #define EVENT_ERR_MSG 0x000B
  55. #define EVENT_ADDRMAP 0x000C
  56. // #define EVENT_AUTHDIR_NEWDESCS 0x000D
  57. #define EVENT_DESCCHANGED 0x000E
  58. // #define EVENT_NS 0x000F
  59. #define EVENT_STATUS_CLIENT 0x0010
  60. #define EVENT_STATUS_SERVER 0x0011
  61. #define EVENT_STATUS_GENERAL 0x0012
  62. #define EVENT_GUARD 0x0013
  63. #define EVENT_STREAM_BANDWIDTH_USED 0x0014
  64. #define EVENT_CLIENTS_SEEN 0x0015
  65. #define EVENT_NEWCONSENSUS 0x0016
  66. #define EVENT_BUILDTIMEOUT_SET 0x0017
  67. #define EVENT_SIGNAL 0x0018
  68. #define _EVENT_MAX 0x0018
  69. /* If _EVENT_MAX ever hits 0x0020, we need to make the mask wider. */
  70. /** Bitfield: The bit 1&lt;&lt;e is set if <b>any</b> open control
  71. * connection is interested in events of type <b>e</b>. We use this
  72. * so that we can decide to skip generating event messages that nobody
  73. * has interest in without having to walk over the global connection
  74. * list to find out.
  75. **/
  76. typedef uint32_t event_mask_t;
  77. /** An event mask of all the events that any controller is interested in
  78. * receiving. */
  79. static event_mask_t global_event_mask = 0;
  80. /** True iff we have disabled log messages from being sent to the controller */
  81. static int disable_log_messages = 0;
  82. /** Macro: true if any control connection is interested in events of type
  83. * <b>e</b>. */
  84. #define EVENT_IS_INTERESTING(e) \
  85. (global_event_mask & (1<<(e)))
  86. /** If we're using cookie-type authentication, how long should our cookies be?
  87. */
  88. #define AUTHENTICATION_COOKIE_LEN 32
  89. /** If true, we've set authentication_cookie to a secret code and
  90. * stored it to disk. */
  91. static int authentication_cookie_is_set = 0;
  92. /** If authentication_cookie_is_set, a secret cookie that we've stored to disk
  93. * and which we're using to authenticate controllers. (If the controller can
  94. * read it off disk, it has permission to connect. */
  95. static char authentication_cookie[AUTHENTICATION_COOKIE_LEN];
  96. /** A sufficiently large size to record the last bootstrap phase string. */
  97. #define BOOTSTRAP_MSG_LEN 1024
  98. /** What was the last bootstrap phase message we sent? We keep track
  99. * of this so we can respond to getinfo status/bootstrap-phase queries. */
  100. static char last_sent_bootstrap_message[BOOTSTRAP_MSG_LEN];
  101. /** Flag for event_format_t. Indicates that we should use the one standard
  102. format.
  103. */
  104. #define ALL_FORMATS 1
  105. /** Bit field of flags to select how to format a controller event. Recognized
  106. * flag is ALL_FORMATS. */
  107. typedef int event_format_t;
  108. static void connection_printf_to_buf(control_connection_t *conn,
  109. const char *format, ...)
  110. CHECK_PRINTF(2,3);
  111. static void send_control_done(control_connection_t *conn);
  112. static void send_control_event(uint16_t event, event_format_t which,
  113. const char *format, ...)
  114. CHECK_PRINTF(3,4);
  115. static int handle_control_setconf(control_connection_t *conn, uint32_t len,
  116. char *body);
  117. static int handle_control_resetconf(control_connection_t *conn, uint32_t len,
  118. char *body);
  119. static int handle_control_getconf(control_connection_t *conn, uint32_t len,
  120. const char *body);
  121. static int handle_control_loadconf(control_connection_t *conn, uint32_t len,
  122. const char *body);
  123. static int handle_control_setevents(control_connection_t *conn, uint32_t len,
  124. const char *body);
  125. static int handle_control_authenticate(control_connection_t *conn,
  126. uint32_t len,
  127. const char *body);
  128. static int handle_control_signal(control_connection_t *conn, uint32_t len,
  129. const char *body);
  130. static int handle_control_mapaddress(control_connection_t *conn, uint32_t len,
  131. const char *body);
  132. static char *list_getinfo_options(void);
  133. static int handle_control_getinfo(control_connection_t *conn, uint32_t len,
  134. const char *body);
  135. static int handle_control_extendcircuit(control_connection_t *conn,
  136. uint32_t len,
  137. const char *body);
  138. static int handle_control_setcircuitpurpose(control_connection_t *conn,
  139. uint32_t len, const char *body);
  140. static int handle_control_attachstream(control_connection_t *conn,
  141. uint32_t len,
  142. const char *body);
  143. static int handle_control_postdescriptor(control_connection_t *conn,
  144. uint32_t len,
  145. const char *body);
  146. static int handle_control_redirectstream(control_connection_t *conn,
  147. uint32_t len,
  148. const char *body);
  149. static int handle_control_closestream(control_connection_t *conn, uint32_t len,
  150. const char *body);
  151. static int handle_control_closecircuit(control_connection_t *conn,
  152. uint32_t len,
  153. const char *body);
  154. static int handle_control_resolve(control_connection_t *conn, uint32_t len,
  155. const char *body);
  156. static int handle_control_usefeature(control_connection_t *conn,
  157. uint32_t len,
  158. const char *body);
  159. static int write_stream_target_to_buf(edge_connection_t *conn, char *buf,
  160. size_t len);
  161. static void orconn_target_get_name(char *buf, size_t len,
  162. or_connection_t *conn);
  163. static char *get_cookie_file(void);
  164. /** Given a control event code for a message event, return the corresponding
  165. * log severity. */
  166. static INLINE int
  167. event_to_log_severity(int event)
  168. {
  169. switch (event) {
  170. case EVENT_DEBUG_MSG: return LOG_DEBUG;
  171. case EVENT_INFO_MSG: return LOG_INFO;
  172. case EVENT_NOTICE_MSG: return LOG_NOTICE;
  173. case EVENT_WARN_MSG: return LOG_WARN;
  174. case EVENT_ERR_MSG: return LOG_ERR;
  175. default: return -1;
  176. }
  177. }
  178. /** Given a log severity, return the corresponding control event code. */
  179. static INLINE int
  180. log_severity_to_event(int severity)
  181. {
  182. switch (severity) {
  183. case LOG_DEBUG: return EVENT_DEBUG_MSG;
  184. case LOG_INFO: return EVENT_INFO_MSG;
  185. case LOG_NOTICE: return EVENT_NOTICE_MSG;
  186. case LOG_WARN: return EVENT_WARN_MSG;
  187. case LOG_ERR: return EVENT_ERR_MSG;
  188. default: return -1;
  189. }
  190. }
  191. /** Set <b>global_event_mask*</b> to the bitwise OR of each live control
  192. * connection's event_mask field. */
  193. void
  194. control_update_global_event_mask(void)
  195. {
  196. smartlist_t *conns = get_connection_array();
  197. event_mask_t old_mask, new_mask;
  198. old_mask = global_event_mask;
  199. global_event_mask = 0;
  200. SMARTLIST_FOREACH(conns, connection_t *, _conn,
  201. {
  202. if (_conn->type == CONN_TYPE_CONTROL &&
  203. STATE_IS_OPEN(_conn->state)) {
  204. control_connection_t *conn = TO_CONTROL_CONN(_conn);
  205. global_event_mask |= conn->event_mask;
  206. }
  207. });
  208. new_mask = global_event_mask;
  209. /* Handle the aftermath. Set up the log callback to tell us only what
  210. * we want to hear...*/
  211. control_adjust_event_log_severity();
  212. /* ...then, if we've started logging stream bw, clear the appropriate
  213. * fields. */
  214. if (! (old_mask & EVENT_STREAM_BANDWIDTH_USED) &&
  215. (new_mask & EVENT_STREAM_BANDWIDTH_USED)) {
  216. SMARTLIST_FOREACH(conns, connection_t *, conn,
  217. {
  218. if (conn->type == CONN_TYPE_AP) {
  219. edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
  220. edge_conn->n_written = edge_conn->n_read = 0;
  221. }
  222. });
  223. }
  224. }
  225. /** Adjust the log severities that result in control_event_logmsg being called
  226. * to match the severity of log messages that any controllers are interested
  227. * in. */
  228. void
  229. control_adjust_event_log_severity(void)
  230. {
  231. int i;
  232. int min_log_event=EVENT_ERR_MSG, max_log_event=EVENT_DEBUG_MSG;
  233. for (i = EVENT_DEBUG_MSG; i <= EVENT_ERR_MSG; ++i) {
  234. if (EVENT_IS_INTERESTING(i)) {
  235. min_log_event = i;
  236. break;
  237. }
  238. }
  239. for (i = EVENT_ERR_MSG; i >= EVENT_DEBUG_MSG; --i) {
  240. if (EVENT_IS_INTERESTING(i)) {
  241. max_log_event = i;
  242. break;
  243. }
  244. }
  245. if (EVENT_IS_INTERESTING(EVENT_LOG_OBSOLETE) ||
  246. EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL)) {
  247. if (min_log_event > EVENT_NOTICE_MSG)
  248. min_log_event = EVENT_NOTICE_MSG;
  249. if (max_log_event < EVENT_ERR_MSG)
  250. max_log_event = EVENT_ERR_MSG;
  251. }
  252. if (min_log_event <= max_log_event)
  253. change_callback_log_severity(event_to_log_severity(min_log_event),
  254. event_to_log_severity(max_log_event),
  255. control_event_logmsg);
  256. else
  257. change_callback_log_severity(LOG_ERR, LOG_ERR,
  258. control_event_logmsg);
  259. }
  260. /** Return true iff the event with code <b>c</b> is being sent to any current
  261. * control connection. This is useful if the amount of work needed to prepare
  262. * to call the appropriate control_event_...() function is high.
  263. */
  264. int
  265. control_event_is_interesting(int event)
  266. {
  267. return EVENT_IS_INTERESTING(event);
  268. }
  269. /** Append a NUL-terminated string <b>s</b> to the end of
  270. * <b>conn</b>-\>outbuf.
  271. */
  272. static INLINE void
  273. connection_write_str_to_buf(const char *s, control_connection_t *conn)
  274. {
  275. size_t len = strlen(s);
  276. connection_write_to_buf(s, len, TO_CONN(conn));
  277. }
  278. /** Given a <b>len</b>-character string in <b>data</b>, made of lines
  279. * terminated by CRLF, allocate a new string in *<b>out</b>, and copy the
  280. * contents of <b>data</b> into *<b>out</b>, adding a period before any period
  281. * that appears at the start of a line, and adding a period-CRLF line at
  282. * the end. Replace all LF characters sequences with CRLF. Return the number
  283. * of bytes in *<b>out</b>.
  284. */
  285. /* static */ size_t
  286. write_escaped_data(const char *data, size_t len, char **out)
  287. {
  288. size_t sz_out = len+8;
  289. char *outp;
  290. const char *start = data, *end;
  291. int i;
  292. int start_of_line;
  293. for (i=0; i<(int)len; ++i) {
  294. if (data[i]== '\n')
  295. sz_out += 2; /* Maybe add a CR; maybe add a dot. */
  296. }
  297. *out = outp = tor_malloc(sz_out+1);
  298. end = data+len;
  299. start_of_line = 1;
  300. while (data < end) {
  301. if (*data == '\n') {
  302. if (data > start && data[-1] != '\r')
  303. *outp++ = '\r';
  304. start_of_line = 1;
  305. } else if (*data == '.') {
  306. if (start_of_line) {
  307. start_of_line = 0;
  308. *outp++ = '.';
  309. }
  310. } else {
  311. start_of_line = 0;
  312. }
  313. *outp++ = *data++;
  314. }
  315. if (outp < *out+2 || memcmp(outp-2, "\r\n", 2)) {
  316. *outp++ = '\r';
  317. *outp++ = '\n';
  318. }
  319. *outp++ = '.';
  320. *outp++ = '\r';
  321. *outp++ = '\n';
  322. *outp = '\0'; /* NUL-terminate just in case. */
  323. tor_assert((outp - *out) <= (int)sz_out);
  324. return outp - *out;
  325. }
  326. /** Given a <b>len</b>-character string in <b>data</b>, made of lines
  327. * terminated by CRLF, allocate a new string in *<b>out</b>, and copy
  328. * the contents of <b>data</b> into *<b>out</b>, removing any period
  329. * that appears at the start of a line, and replacing all CRLF sequences
  330. * with LF. Return the number of
  331. * bytes in *<b>out</b>. */
  332. /* static */ size_t
  333. read_escaped_data(const char *data, size_t len, char **out)
  334. {
  335. char *outp;
  336. const char *next;
  337. const char *end;
  338. *out = outp = tor_malloc(len+1);
  339. end = data+len;
  340. while (data < end) {
  341. /* we're at the start of a line. */
  342. if (*data == '.')
  343. ++data;
  344. next = memchr(data, '\n', end-data);
  345. if (next) {
  346. size_t n_to_copy = next-data;
  347. /* Don't copy a CR that precedes this LF. */
  348. if (n_to_copy && *(next-1) == '\r')
  349. --n_to_copy;
  350. memcpy(outp, data, n_to_copy);
  351. outp += n_to_copy;
  352. data = next+1; /* This will point at the start of the next line,
  353. * or the end of the string, or a period. */
  354. } else {
  355. memcpy(outp, data, end-data);
  356. outp += (end-data);
  357. *outp = '\0';
  358. return outp - *out;
  359. }
  360. *outp++ = '\n';
  361. }
  362. *outp = '\0';
  363. return outp - *out;
  364. }
  365. /** If the first <b>in_len_max</b> characters in <b>start</b> contain a
  366. * double-quoted string with escaped characters, return the length of that
  367. * string (as encoded, including quotes). Otherwise return -1. */
  368. static INLINE int
  369. get_escaped_string_length(const char *start, size_t in_len_max,
  370. int *chars_out)
  371. {
  372. const char *cp, *end;
  373. int chars = 0;
  374. if (*start != '\"')
  375. return -1;
  376. cp = start+1;
  377. end = start+in_len_max;
  378. /* Calculate length. */
  379. while (1) {
  380. if (cp >= end) {
  381. return -1; /* Too long. */
  382. } else if (*cp == '\\') {
  383. if (++cp == end)
  384. return -1; /* Can't escape EOS. */
  385. ++cp;
  386. ++chars;
  387. } else if (*cp == '\"') {
  388. break;
  389. } else {
  390. ++cp;
  391. ++chars;
  392. }
  393. }
  394. if (chars_out)
  395. *chars_out = chars;
  396. return (int)(cp - start+1);
  397. }
  398. /** As decode_escaped_string, but does not decode the string: copies the
  399. * entire thing, including quotation marks. */
  400. static const char *
  401. extract_escaped_string(const char *start, size_t in_len_max,
  402. char **out, size_t *out_len)
  403. {
  404. int length = get_escaped_string_length(start, in_len_max, NULL);
  405. if (length<0)
  406. return NULL;
  407. *out_len = length;
  408. *out = tor_strndup(start, *out_len);
  409. return start+length;
  410. }
  411. /** Given a pointer to a string starting at <b>start</b> containing
  412. * <b>in_len_max</b> characters, decode a string beginning with one double
  413. * quote, containing any number of non-quote characters or characters escaped
  414. * with a backslash, and ending with a final double quote. Place the resulting
  415. * string (unquoted, unescaped) into a newly allocated string in *<b>out</b>;
  416. * store its length in <b>out_len</b>. On success, return a pointer to the
  417. * character immediately following the escaped string. On failure, return
  418. * NULL. */
  419. static const char *
  420. decode_escaped_string(const char *start, size_t in_len_max,
  421. char **out, size_t *out_len)
  422. {
  423. const char *cp, *end;
  424. char *outp;
  425. int len, n_chars = 0;
  426. len = get_escaped_string_length(start, in_len_max, &n_chars);
  427. if (len<0)
  428. return NULL;
  429. end = start+len-1; /* Index of last quote. */
  430. tor_assert(*end == '\"');
  431. outp = *out = tor_malloc(len+1);
  432. *out_len = n_chars;
  433. cp = start+1;
  434. while (cp < end) {
  435. if (*cp == '\\')
  436. ++cp;
  437. *outp++ = *cp++;
  438. }
  439. *outp = '\0';
  440. tor_assert((outp - *out) == (int)*out_len);
  441. return end+1;
  442. }
  443. /** Acts like sprintf, but writes its formatted string to the end of
  444. * <b>conn</b>-\>outbuf. The message may be truncated if it is too long,
  445. * but it will always end with a CRLF sequence.
  446. *
  447. * Currently the length of the message is limited to 1024 (including the
  448. * ending CR LF NUL ("\\r\\n\\0"). */
  449. static void
  450. connection_printf_to_buf(control_connection_t *conn, const char *format, ...)
  451. {
  452. #define CONNECTION_PRINTF_TO_BUF_BUFFERSIZE 1024
  453. va_list ap;
  454. char buf[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE];
  455. int r;
  456. size_t len;
  457. va_start(ap,format);
  458. r = tor_vsnprintf(buf, sizeof(buf), format, ap);
  459. va_end(ap);
  460. if (r<0) {
  461. log_warn(LD_BUG, "Unable to format string for controller.");
  462. return;
  463. }
  464. len = strlen(buf);
  465. if (memcmp("\r\n\0", buf+len-2, 3)) {
  466. buf[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE-1] = '\0';
  467. buf[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE-2] = '\n';
  468. buf[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE-3] = '\r';
  469. }
  470. connection_write_to_buf(buf, len, TO_CONN(conn));
  471. }
  472. /** Send a "DONE" message down the control connection <b>conn</b>. */
  473. static void
  474. send_control_done(control_connection_t *conn)
  475. {
  476. connection_write_str_to_buf("250 OK\r\n", conn);
  477. }
  478. /** Send an event to all v1 controllers that are listening for code
  479. * <b>event</b>. The event's body is given by <b>msg</b>.
  480. *
  481. * If <b>which</b> & SHORT_NAMES, the event contains short-format names: send
  482. * it to controllers that haven't enabled the VERBOSE_NAMES feature. If
  483. * <b>which</b> & LONG_NAMES, the event contains long-format names: send it
  484. * to controllers that <em>have</em> enabled VERBOSE_NAMES.
  485. *
  486. * The EXTENDED_FORMAT and NONEXTENDED_FORMAT flags behave similarly with
  487. * respect to the EXTENDED_EVENTS feature. */
  488. static void
  489. send_control_event_string(uint16_t event, event_format_t which,
  490. const char *msg)
  491. {
  492. smartlist_t *conns = get_connection_array();
  493. (void)which;
  494. tor_assert(event >= _EVENT_MIN && event <= _EVENT_MAX);
  495. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
  496. if (conn->type == CONN_TYPE_CONTROL &&
  497. !conn->marked_for_close &&
  498. conn->state == CONTROL_CONN_STATE_OPEN) {
  499. control_connection_t *control_conn = TO_CONTROL_CONN(conn);
  500. if (control_conn->event_mask & (1<<event)) {
  501. int is_err = 0;
  502. connection_write_to_buf(msg, strlen(msg), TO_CONN(control_conn));
  503. if (event == EVENT_ERR_MSG)
  504. is_err = 1;
  505. else if (event == EVENT_STATUS_GENERAL)
  506. is_err = !strcmpstart(msg, "STATUS_GENERAL ERR ");
  507. else if (event == EVENT_STATUS_CLIENT)
  508. is_err = !strcmpstart(msg, "STATUS_CLIENT ERR ");
  509. else if (event == EVENT_STATUS_SERVER)
  510. is_err = !strcmpstart(msg, "STATUS_SERVER ERR ");
  511. if (is_err)
  512. connection_handle_write(TO_CONN(control_conn), 1);
  513. }
  514. }
  515. } SMARTLIST_FOREACH_END(conn);
  516. }
  517. /** Helper for send_control1_event and send_control1_event_extended:
  518. * Send an event to all v1 controllers that are listening for code
  519. * <b>event</b>. The event's body is created by the printf-style format in
  520. * <b>format</b>, and other arguments as provided.
  521. *
  522. * Currently the length of the message is limited to 1024 (including the
  523. * ending \\r\\n\\0). */
  524. static void
  525. send_control_event_impl(uint16_t event, event_format_t which,
  526. const char *format, va_list ap)
  527. {
  528. /* This is just a little longer than the longest allowed log message */
  529. #define SEND_CONTROL1_EVENT_BUFFERSIZE 10064
  530. int r;
  531. char buf[SEND_CONTROL1_EVENT_BUFFERSIZE];
  532. size_t len;
  533. r = tor_vsnprintf(buf, sizeof(buf), format, ap);
  534. if (r<0) {
  535. log_warn(LD_BUG, "Unable to format event for controller.");
  536. return;
  537. }
  538. len = strlen(buf);
  539. if (memcmp("\r\n\0", buf+len-2, 3)) {
  540. /* if it is not properly terminated, do it now */
  541. buf[SEND_CONTROL1_EVENT_BUFFERSIZE-1] = '\0';
  542. buf[SEND_CONTROL1_EVENT_BUFFERSIZE-2] = '\n';
  543. buf[SEND_CONTROL1_EVENT_BUFFERSIZE-3] = '\r';
  544. }
  545. send_control_event_string(event, which|ALL_FORMATS, buf);
  546. }
  547. /** Send an event to all v1 controllers that are listening for code
  548. * <b>event</b>. The event's body is created by the printf-style format in
  549. * <b>format</b>, and other arguments as provided.
  550. *
  551. * Currently the length of the message is limited to 1024 (including the
  552. * ending \\n\\r\\0. */
  553. static void
  554. send_control_event(uint16_t event, event_format_t which,
  555. const char *format, ...)
  556. {
  557. va_list ap;
  558. va_start(ap, format);
  559. send_control_event_impl(event, which, format, ap);
  560. va_end(ap);
  561. }
  562. /** Given a text circuit <b>id</b>, return the corresponding circuit. */
  563. static origin_circuit_t *
  564. get_circ(const char *id)
  565. {
  566. uint32_t n_id;
  567. int ok;
  568. n_id = (uint32_t) tor_parse_ulong(id, 10, 0, UINT32_MAX, &ok, NULL);
  569. if (!ok)
  570. return NULL;
  571. return circuit_get_by_global_id(n_id);
  572. }
  573. /** Given a text stream <b>id</b>, return the corresponding AP connection. */
  574. static edge_connection_t *
  575. get_stream(const char *id)
  576. {
  577. uint64_t n_id;
  578. int ok;
  579. connection_t *conn;
  580. n_id = tor_parse_uint64(id, 10, 0, UINT64_MAX, &ok, NULL);
  581. if (!ok)
  582. return NULL;
  583. conn = connection_get_by_global_id(n_id);
  584. if (!conn || conn->type != CONN_TYPE_AP || conn->marked_for_close)
  585. return NULL;
  586. return TO_EDGE_CONN(conn);
  587. }
  588. /** Helper for setconf and resetconf. Acts like setconf, except
  589. * it passes <b>use_defaults</b> on to options_trial_assign(). Modifies the
  590. * contents of body.
  591. */
  592. static int
  593. control_setconf_helper(control_connection_t *conn, uint32_t len, char *body,
  594. int use_defaults)
  595. {
  596. setopt_err_t opt_err;
  597. config_line_t *lines=NULL;
  598. char *start = body;
  599. char *errstring = NULL;
  600. const int clear_first = 1;
  601. char *config;
  602. smartlist_t *entries = smartlist_create();
  603. /* We have a string, "body", of the format '(key(=val|="val")?)' entries
  604. * separated by space. break it into a list of configuration entries. */
  605. while (*body) {
  606. char *eq = body;
  607. char *key;
  608. char *entry;
  609. while (!TOR_ISSPACE(*eq) && *eq != '=')
  610. ++eq;
  611. key = tor_strndup(body, eq-body);
  612. body = eq+1;
  613. if (*eq == '=') {
  614. char *val=NULL;
  615. size_t val_len=0;
  616. size_t ent_len;
  617. if (*body != '\"') {
  618. char *val_start = body;
  619. while (!TOR_ISSPACE(*body))
  620. body++;
  621. val = tor_strndup(val_start, body-val_start);
  622. val_len = strlen(val);
  623. } else {
  624. body = (char*)extract_escaped_string(body, (len - (body-start)),
  625. &val, &val_len);
  626. if (!body) {
  627. connection_write_str_to_buf("551 Couldn't parse string\r\n", conn);
  628. SMARTLIST_FOREACH(entries, char *, cp, tor_free(cp));
  629. smartlist_free(entries);
  630. tor_free(key);
  631. return 0;
  632. }
  633. }
  634. ent_len = strlen(key)+val_len+3;
  635. entry = tor_malloc(ent_len+1);
  636. tor_snprintf(entry, ent_len, "%s %s", key, val);
  637. tor_free(key);
  638. tor_free(val);
  639. } else {
  640. entry = key;
  641. }
  642. smartlist_add(entries, entry);
  643. while (TOR_ISSPACE(*body))
  644. ++body;
  645. }
  646. smartlist_add(entries, tor_strdup(""));
  647. config = smartlist_join_strings(entries, "\n", 0, NULL);
  648. SMARTLIST_FOREACH(entries, char *, cp, tor_free(cp));
  649. smartlist_free(entries);
  650. if (config_get_lines(config, &lines) < 0) {
  651. log_warn(LD_CONTROL,"Controller gave us config lines we can't parse.");
  652. connection_write_str_to_buf("551 Couldn't parse configuration\r\n",
  653. conn);
  654. tor_free(config);
  655. return 0;
  656. }
  657. tor_free(config);
  658. opt_err = options_trial_assign(lines, use_defaults, clear_first, &errstring);
  659. {
  660. const char *msg;
  661. switch (opt_err) {
  662. case SETOPT_ERR_MISC:
  663. msg = "552 Unrecognized option";
  664. break;
  665. case SETOPT_ERR_PARSE:
  666. msg = "513 Unacceptable option value";
  667. break;
  668. case SETOPT_ERR_TRANSITION:
  669. msg = "553 Transition not allowed";
  670. break;
  671. case SETOPT_ERR_SETTING:
  672. default:
  673. msg = "553 Unable to set option";
  674. break;
  675. case SETOPT_OK:
  676. config_free_lines(lines);
  677. send_control_done(conn);
  678. return 0;
  679. }
  680. log_warn(LD_CONTROL,
  681. "Controller gave us config lines that didn't validate: %s",
  682. errstring);
  683. connection_printf_to_buf(conn, "%s: %s\r\n", msg, errstring);
  684. config_free_lines(lines);
  685. tor_free(errstring);
  686. return 0;
  687. }
  688. }
  689. /** Called when we receive a SETCONF message: parse the body and try
  690. * to update our configuration. Reply with a DONE or ERROR message.
  691. * Modifies the contents of body.*/
  692. static int
  693. handle_control_setconf(control_connection_t *conn, uint32_t len, char *body)
  694. {
  695. return control_setconf_helper(conn, len, body, 0);
  696. }
  697. /** Called when we receive a RESETCONF message: parse the body and try
  698. * to update our configuration. Reply with a DONE or ERROR message.
  699. * Modifies the contents of body. */
  700. static int
  701. handle_control_resetconf(control_connection_t *conn, uint32_t len, char *body)
  702. {
  703. return control_setconf_helper(conn, len, body, 1);
  704. }
  705. /** Called when we receive a GETCONF message. Parse the request, and
  706. * reply with a CONFVALUE or an ERROR message */
  707. static int
  708. handle_control_getconf(control_connection_t *conn, uint32_t body_len,
  709. const char *body)
  710. {
  711. smartlist_t *questions = smartlist_create();
  712. smartlist_t *answers = smartlist_create();
  713. smartlist_t *unrecognized = smartlist_create();
  714. char *msg = NULL;
  715. size_t msg_len;
  716. or_options_t *options = get_options();
  717. int i, len;
  718. (void) body_len; /* body is NUL-terminated; so we can ignore len. */
  719. smartlist_split_string(questions, body, " ",
  720. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  721. SMARTLIST_FOREACH(questions, const char *, q,
  722. {
  723. if (!option_is_recognized(q)) {
  724. smartlist_add(unrecognized, (char*) q);
  725. } else {
  726. config_line_t *answer = option_get_assignment(options,q);
  727. if (!answer) {
  728. const char *name = option_get_canonical_name(q);
  729. size_t alen = strlen(name)+8;
  730. char *astr = tor_malloc(alen);
  731. tor_snprintf(astr, alen, "250-%s\r\n", name);
  732. smartlist_add(answers, astr);
  733. }
  734. while (answer) {
  735. config_line_t *next;
  736. size_t alen = strlen(answer->key)+strlen(answer->value)+8;
  737. char *astr = tor_malloc(alen);
  738. tor_snprintf(astr, alen, "250-%s=%s\r\n",
  739. answer->key, answer->value);
  740. smartlist_add(answers, astr);
  741. next = answer->next;
  742. tor_free(answer->key);
  743. tor_free(answer->value);
  744. tor_free(answer);
  745. answer = next;
  746. }
  747. }
  748. });
  749. if ((len = smartlist_len(unrecognized))) {
  750. for (i=0; i < len-1; ++i)
  751. connection_printf_to_buf(conn,
  752. "552-Unrecognized configuration key \"%s\"\r\n",
  753. (char*)smartlist_get(unrecognized, i));
  754. connection_printf_to_buf(conn,
  755. "552 Unrecognized configuration key \"%s\"\r\n",
  756. (char*)smartlist_get(unrecognized, len-1));
  757. } else if ((len = smartlist_len(answers))) {
  758. char *tmp = smartlist_get(answers, len-1);
  759. tor_assert(strlen(tmp)>4);
  760. tmp[3] = ' ';
  761. msg = smartlist_join_strings(answers, "", 0, &msg_len);
  762. connection_write_to_buf(msg, msg_len, TO_CONN(conn));
  763. } else {
  764. connection_write_str_to_buf("250 OK\r\n", conn);
  765. }
  766. SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
  767. smartlist_free(answers);
  768. SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
  769. smartlist_free(questions);
  770. smartlist_free(unrecognized);
  771. tor_free(msg);
  772. return 0;
  773. }
  774. /** Called when we get a +LOADCONF message. */
  775. static int
  776. handle_control_loadconf(control_connection_t *conn, uint32_t len,
  777. const char *body)
  778. {
  779. setopt_err_t retval;
  780. char *errstring = NULL;
  781. const char *msg = NULL;
  782. (void) len;
  783. retval = options_init_from_string(body, CMD_RUN_TOR, NULL, &errstring);
  784. if (retval != SETOPT_OK)
  785. log_warn(LD_CONTROL,
  786. "Controller gave us config file that didn't validate: %s",
  787. errstring);
  788. switch (retval) {
  789. case SETOPT_ERR_PARSE:
  790. msg = "552 Invalid config file";
  791. break;
  792. case SETOPT_ERR_TRANSITION:
  793. msg = "553 Transition not allowed";
  794. break;
  795. case SETOPT_ERR_SETTING:
  796. msg = "553 Unable to set option";
  797. break;
  798. case SETOPT_ERR_MISC:
  799. default:
  800. msg = "550 Unable to load config";
  801. break;
  802. case SETOPT_OK:
  803. break;
  804. }
  805. if (msg) {
  806. if (errstring)
  807. connection_printf_to_buf(conn, "%s: %s\r\n", msg, errstring);
  808. else
  809. connection_printf_to_buf(conn, "%s\r\n", msg);
  810. } else {
  811. send_control_done(conn);
  812. }
  813. tor_free(errstring);
  814. return 0;
  815. }
  816. /** Called when we get a SETEVENTS message: update conn->event_mask,
  817. * and reply with DONE or ERROR. */
  818. static int
  819. handle_control_setevents(control_connection_t *conn, uint32_t len,
  820. const char *body)
  821. {
  822. uint16_t event_code;
  823. uint32_t event_mask = 0;
  824. smartlist_t *events = smartlist_create();
  825. (void) len;
  826. smartlist_split_string(events, body, " ",
  827. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  828. SMARTLIST_FOREACH_BEGIN(events, const char *, ev)
  829. {
  830. if (!strcasecmp(ev, "EXTENDED")) {
  831. continue;
  832. } else if (!strcasecmp(ev, "CIRC"))
  833. event_code = EVENT_CIRCUIT_STATUS;
  834. else if (!strcasecmp(ev, "STREAM"))
  835. event_code = EVENT_STREAM_STATUS;
  836. else if (!strcasecmp(ev, "ORCONN"))
  837. event_code = EVENT_OR_CONN_STATUS;
  838. else if (!strcasecmp(ev, "BW"))
  839. event_code = EVENT_BANDWIDTH_USED;
  840. else if (!strcasecmp(ev, "DEBUG"))
  841. event_code = EVENT_DEBUG_MSG;
  842. else if (!strcasecmp(ev, "INFO"))
  843. event_code = EVENT_INFO_MSG;
  844. else if (!strcasecmp(ev, "NOTICE"))
  845. event_code = EVENT_NOTICE_MSG;
  846. else if (!strcasecmp(ev, "WARN"))
  847. event_code = EVENT_WARN_MSG;
  848. else if (!strcasecmp(ev, "ERR"))
  849. event_code = EVENT_ERR_MSG;
  850. else if (!strcasecmp(ev, "NEWDESC"))
  851. event_code = EVENT_NEW_DESC;
  852. else if (!strcasecmp(ev, "ADDRMAP"))
  853. event_code = EVENT_ADDRMAP;
  854. else if (!strcasecmp(ev, "AUTHDIR_NEWDESCS"))
  855. event_code = EVENT_AUTHDIR_NEWDESCS;
  856. else if (!strcasecmp(ev, "DESCCHANGED"))
  857. event_code = EVENT_DESCCHANGED;
  858. else if (!strcasecmp(ev, "NS"))
  859. event_code = EVENT_NS;
  860. else if (!strcasecmp(ev, "STATUS_GENERAL"))
  861. event_code = EVENT_STATUS_GENERAL;
  862. else if (!strcasecmp(ev, "STATUS_CLIENT"))
  863. event_code = EVENT_STATUS_CLIENT;
  864. else if (!strcasecmp(ev, "STATUS_SERVER"))
  865. event_code = EVENT_STATUS_SERVER;
  866. else if (!strcasecmp(ev, "GUARD"))
  867. event_code = EVENT_GUARD;
  868. else if (!strcasecmp(ev, "STREAM_BW"))
  869. event_code = EVENT_STREAM_BANDWIDTH_USED;
  870. else if (!strcasecmp(ev, "CLIENTS_SEEN"))
  871. event_code = EVENT_CLIENTS_SEEN;
  872. else if (!strcasecmp(ev, "NEWCONSENSUS"))
  873. event_code = EVENT_NEWCONSENSUS;
  874. else if (!strcasecmp(ev, "BUILDTIMEOUT_SET"))
  875. event_code = EVENT_BUILDTIMEOUT_SET;
  876. else if (!strcasecmp(ev, "SIGNAL"))
  877. event_code = EVENT_SIGNAL;
  878. else {
  879. connection_printf_to_buf(conn, "552 Unrecognized event \"%s\"\r\n",
  880. ev);
  881. SMARTLIST_FOREACH(events, char *, e, tor_free(e));
  882. smartlist_free(events);
  883. return 0;
  884. }
  885. event_mask |= (1 << event_code);
  886. }
  887. SMARTLIST_FOREACH_END(ev);
  888. SMARTLIST_FOREACH(events, char *, e, tor_free(e));
  889. smartlist_free(events);
  890. conn->event_mask = event_mask;
  891. control_update_global_event_mask();
  892. send_control_done(conn);
  893. return 0;
  894. }
  895. /** Decode the hashed, base64'd passwords stored in <b>passwords</b>.
  896. * Return a smartlist of acceptable passwords (unterminated strings of
  897. * length S2K_SPECIFIER_LEN+DIGEST_LEN) on success, or NULL on failure.
  898. */
  899. smartlist_t *
  900. decode_hashed_passwords(config_line_t *passwords)
  901. {
  902. char decoded[64];
  903. config_line_t *cl;
  904. smartlist_t *sl = smartlist_create();
  905. tor_assert(passwords);
  906. for (cl = passwords; cl; cl = cl->next) {
  907. const char *hashed = cl->value;
  908. if (!strcmpstart(hashed, "16:")) {
  909. if (base16_decode(decoded, sizeof(decoded), hashed+3, strlen(hashed+3))<0
  910. || strlen(hashed+3) != (S2K_SPECIFIER_LEN+DIGEST_LEN)*2) {
  911. goto err;
  912. }
  913. } else {
  914. if (base64_decode(decoded, sizeof(decoded), hashed, strlen(hashed))
  915. != S2K_SPECIFIER_LEN+DIGEST_LEN) {
  916. goto err;
  917. }
  918. }
  919. smartlist_add(sl, tor_memdup(decoded, S2K_SPECIFIER_LEN+DIGEST_LEN));
  920. }
  921. return sl;
  922. err:
  923. SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
  924. smartlist_free(sl);
  925. return NULL;
  926. }
  927. /** Called when we get an AUTHENTICATE message. Check whether the
  928. * authentication is valid, and if so, update the connection's state to
  929. * OPEN. Reply with DONE or ERROR.
  930. */
  931. static int
  932. handle_control_authenticate(control_connection_t *conn, uint32_t len,
  933. const char *body)
  934. {
  935. int used_quoted_string = 0;
  936. or_options_t *options = get_options();
  937. const char *errstr = NULL;
  938. char *password;
  939. size_t password_len;
  940. const char *cp;
  941. int i;
  942. int bad_cookie=0, bad_password=0;
  943. smartlist_t *sl = NULL;
  944. if (TOR_ISXDIGIT(body[0])) {
  945. cp = body;
  946. while (TOR_ISXDIGIT(*cp))
  947. ++cp;
  948. i = (int)(cp - body);
  949. tor_assert(i>0);
  950. password_len = i/2;
  951. password = tor_malloc(password_len + 1);
  952. if (base16_decode(password, password_len+1, body, i)<0) {
  953. connection_write_str_to_buf(
  954. "551 Invalid hexadecimal encoding. Maybe you tried a plain text "
  955. "password? If so, the standard requires that you put it in "
  956. "double quotes.\r\n", conn);
  957. connection_mark_for_close(TO_CONN(conn));
  958. tor_free(password);
  959. return 0;
  960. }
  961. } else if (TOR_ISSPACE(body[0])) {
  962. password = tor_strdup("");
  963. password_len = 0;
  964. } else {
  965. if (!decode_escaped_string(body, len, &password, &password_len)) {
  966. connection_write_str_to_buf("551 Invalid quoted string. You need "
  967. "to put the password in double quotes.\r\n", conn);
  968. connection_mark_for_close(TO_CONN(conn));
  969. return 0;
  970. }
  971. used_quoted_string = 1;
  972. }
  973. if (!options->CookieAuthentication && !options->HashedControlPassword &&
  974. !options->HashedControlSessionPassword) {
  975. /* if Tor doesn't demand any stronger authentication, then
  976. * the controller can get in with anything. */
  977. goto ok;
  978. }
  979. if (options->CookieAuthentication) {
  980. int also_password = options->HashedControlPassword != NULL ||
  981. options->HashedControlSessionPassword != NULL;
  982. if (password_len != AUTHENTICATION_COOKIE_LEN) {
  983. if (!also_password) {
  984. log_warn(LD_CONTROL, "Got authentication cookie with wrong length "
  985. "(%d)", (int)password_len);
  986. errstr = "Wrong length on authentication cookie.";
  987. goto err;
  988. }
  989. bad_cookie = 1;
  990. } else if (memcmp(authentication_cookie, password, password_len)) {
  991. if (!also_password) {
  992. log_warn(LD_CONTROL, "Got mismatched authentication cookie");
  993. errstr = "Authentication cookie did not match expected value.";
  994. goto err;
  995. }
  996. bad_cookie = 1;
  997. } else {
  998. goto ok;
  999. }
  1000. }
  1001. if (options->HashedControlPassword ||
  1002. options->HashedControlSessionPassword) {
  1003. int bad = 0;
  1004. smartlist_t *sl_tmp;
  1005. char received[DIGEST_LEN];
  1006. int also_cookie = options->CookieAuthentication;
  1007. sl = smartlist_create();
  1008. if (options->HashedControlPassword) {
  1009. sl_tmp = decode_hashed_passwords(options->HashedControlPassword);
  1010. if (!sl_tmp)
  1011. bad = 1;
  1012. else {
  1013. smartlist_add_all(sl, sl_tmp);
  1014. smartlist_free(sl_tmp);
  1015. }
  1016. }
  1017. if (options->HashedControlSessionPassword) {
  1018. sl_tmp = decode_hashed_passwords(options->HashedControlSessionPassword);
  1019. if (!sl_tmp)
  1020. bad = 1;
  1021. else {
  1022. smartlist_add_all(sl, sl_tmp);
  1023. smartlist_free(sl_tmp);
  1024. }
  1025. }
  1026. if (bad) {
  1027. if (!also_cookie) {
  1028. log_warn(LD_CONTROL,
  1029. "Couldn't decode HashedControlPassword: invalid base16");
  1030. errstr="Couldn't decode HashedControlPassword value in configuration.";
  1031. }
  1032. bad_password = 1;
  1033. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  1034. smartlist_free(sl);
  1035. } else {
  1036. SMARTLIST_FOREACH(sl, char *, expected,
  1037. {
  1038. secret_to_key(received,DIGEST_LEN,password,password_len,expected);
  1039. if (!memcmp(expected+S2K_SPECIFIER_LEN, received, DIGEST_LEN))
  1040. goto ok;
  1041. });
  1042. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  1043. smartlist_free(sl);
  1044. if (used_quoted_string)
  1045. errstr = "Password did not match HashedControlPassword value from "
  1046. "configuration";
  1047. else
  1048. errstr = "Password did not match HashedControlPassword value from "
  1049. "configuration. Maybe you tried a plain text password? "
  1050. "If so, the standard requires that you put it in double quotes.";
  1051. bad_password = 1;
  1052. if (!also_cookie)
  1053. goto err;
  1054. }
  1055. }
  1056. /** We only get here if both kinds of authentication failed. */
  1057. tor_assert(bad_password && bad_cookie);
  1058. log_warn(LD_CONTROL, "Bad password or authentication cookie on controller.");
  1059. errstr = "Password did not match HashedControlPassword *or* authentication "
  1060. "cookie.";
  1061. err:
  1062. tor_free(password);
  1063. connection_printf_to_buf(conn, "515 Authentication failed: %s\r\n",
  1064. errstr ? errstr : "Unknown reason.");
  1065. connection_mark_for_close(TO_CONN(conn));
  1066. return 0;
  1067. ok:
  1068. log_info(LD_CONTROL, "Authenticated control connection (%d)", conn->_base.s);
  1069. send_control_done(conn);
  1070. conn->_base.state = CONTROL_CONN_STATE_OPEN;
  1071. tor_free(password);
  1072. if (sl) { /* clean up */
  1073. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  1074. smartlist_free(sl);
  1075. }
  1076. return 0;
  1077. }
  1078. /** Called when we get a SAVECONF command. Try to flush the current options to
  1079. * disk, and report success or failure. */
  1080. static int
  1081. handle_control_saveconf(control_connection_t *conn, uint32_t len,
  1082. const char *body)
  1083. {
  1084. (void) len;
  1085. (void) body;
  1086. if (options_save_current()<0) {
  1087. connection_write_str_to_buf(
  1088. "551 Unable to write configuration to disk.\r\n", conn);
  1089. } else {
  1090. send_control_done(conn);
  1091. }
  1092. return 0;
  1093. }
  1094. /** Called when we get a SIGNAL command. React to the provided signal, and
  1095. * report success or failure. (If the signal results in a shutdown, success
  1096. * may not be reported.) */
  1097. static int
  1098. handle_control_signal(control_connection_t *conn, uint32_t len,
  1099. const char *body)
  1100. {
  1101. int sig;
  1102. int n = 0;
  1103. char *s;
  1104. (void) len;
  1105. while (body[n] && ! TOR_ISSPACE(body[n]))
  1106. ++n;
  1107. s = tor_strndup(body, n);
  1108. if (!strcasecmp(s, "RELOAD") || !strcasecmp(s, "HUP"))
  1109. sig = SIGHUP;
  1110. else if (!strcasecmp(s, "SHUTDOWN") || !strcasecmp(s, "INT"))
  1111. sig = SIGINT;
  1112. else if (!strcasecmp(s, "DUMP") || !strcasecmp(s, "USR1"))
  1113. sig = SIGUSR1;
  1114. else if (!strcasecmp(s, "DEBUG") || !strcasecmp(s, "USR2"))
  1115. sig = SIGUSR2;
  1116. else if (!strcasecmp(s, "HALT") || !strcasecmp(s, "TERM"))
  1117. sig = SIGTERM;
  1118. else if (!strcasecmp(s, "NEWNYM"))
  1119. sig = SIGNEWNYM;
  1120. else if (!strcasecmp(s, "CLEARDNSCACHE"))
  1121. sig = SIGCLEARDNSCACHE;
  1122. else {
  1123. connection_printf_to_buf(conn, "552 Unrecognized signal code \"%s\"\r\n",
  1124. s);
  1125. sig = -1;
  1126. }
  1127. tor_free(s);
  1128. if (sig<0)
  1129. return 0;
  1130. send_control_done(conn);
  1131. /* Flush the "done" first if the signal might make us shut down. */
  1132. if (sig == SIGTERM || sig == SIGINT)
  1133. connection_handle_write(TO_CONN(conn), 1);
  1134. control_signal_act(sig);
  1135. return 0;
  1136. }
  1137. /** Called when we get a MAPADDRESS command; try to bind all listed addresses,
  1138. * and report success or failure. */
  1139. static int
  1140. handle_control_mapaddress(control_connection_t *conn, uint32_t len,
  1141. const char *body)
  1142. {
  1143. smartlist_t *elts;
  1144. smartlist_t *lines;
  1145. smartlist_t *reply;
  1146. char *r;
  1147. size_t sz;
  1148. (void) len; /* body is NUL-terminated, so it's safe to ignore the length. */
  1149. lines = smartlist_create();
  1150. elts = smartlist_create();
  1151. reply = smartlist_create();
  1152. smartlist_split_string(lines, body, " ",
  1153. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1154. SMARTLIST_FOREACH(lines, char *, line,
  1155. {
  1156. tor_strlower(line);
  1157. smartlist_split_string(elts, line, "=", 0, 2);
  1158. if (smartlist_len(elts) == 2) {
  1159. const char *from = smartlist_get(elts,0);
  1160. const char *to = smartlist_get(elts,1);
  1161. size_t anslen = strlen(line)+512;
  1162. char *ans = tor_malloc(anslen);
  1163. if (address_is_invalid_destination(to, 1)) {
  1164. tor_snprintf(ans, anslen,
  1165. "512-syntax error: invalid address '%s'", to);
  1166. smartlist_add(reply, ans);
  1167. log_warn(LD_CONTROL,
  1168. "Skipping invalid argument '%s' in MapAddress msg", to);
  1169. } else if (!strcmp(from, ".") || !strcmp(from, "0.0.0.0")) {
  1170. const char *address = addressmap_register_virtual_address(
  1171. !strcmp(from,".") ? RESOLVED_TYPE_HOSTNAME : RESOLVED_TYPE_IPV4,
  1172. tor_strdup(to));
  1173. if (!address) {
  1174. tor_snprintf(ans, anslen,
  1175. "451-resource exhausted: skipping '%s'", line);
  1176. smartlist_add(reply, ans);
  1177. log_warn(LD_CONTROL,
  1178. "Unable to allocate address for '%s' in MapAddress msg",
  1179. safe_str_client(line));
  1180. } else {
  1181. tor_snprintf(ans, anslen, "250-%s=%s", address, to);
  1182. smartlist_add(reply, ans);
  1183. }
  1184. } else {
  1185. addressmap_register(from, tor_strdup(to), 1, ADDRMAPSRC_CONTROLLER);
  1186. tor_snprintf(ans, anslen, "250-%s", line);
  1187. smartlist_add(reply, ans);
  1188. }
  1189. } else {
  1190. size_t anslen = strlen(line)+256;
  1191. char *ans = tor_malloc(anslen);
  1192. tor_snprintf(ans, anslen, "512-syntax error: mapping '%s' is "
  1193. "not of expected form 'foo=bar'.", line);
  1194. smartlist_add(reply, ans);
  1195. log_info(LD_CONTROL, "Skipping MapAddress '%s': wrong "
  1196. "number of items.",
  1197. safe_str_client(line));
  1198. }
  1199. SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
  1200. smartlist_clear(elts);
  1201. });
  1202. SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
  1203. smartlist_free(lines);
  1204. smartlist_free(elts);
  1205. if (smartlist_len(reply)) {
  1206. ((char*)smartlist_get(reply,smartlist_len(reply)-1))[3] = ' ';
  1207. r = smartlist_join_strings(reply, "\r\n", 1, &sz);
  1208. connection_write_to_buf(r, sz, TO_CONN(conn));
  1209. tor_free(r);
  1210. } else {
  1211. const char *response =
  1212. "512 syntax error: not enough arguments to mapaddress.\r\n";
  1213. connection_write_to_buf(response, strlen(response), TO_CONN(conn));
  1214. }
  1215. SMARTLIST_FOREACH(reply, char *, cp, tor_free(cp));
  1216. smartlist_free(reply);
  1217. return 0;
  1218. }
  1219. /** Implementation helper for GETINFO: knows the answers for various
  1220. * trivial-to-implement questions. */
  1221. static int
  1222. getinfo_helper_misc(control_connection_t *conn, const char *question,
  1223. char **answer, const char **errmsg)
  1224. {
  1225. (void) conn;
  1226. if (!strcmp(question, "version")) {
  1227. *answer = tor_strdup(get_version());
  1228. } else if (!strcmp(question, "config-file")) {
  1229. *answer = tor_strdup(get_torrc_fname());
  1230. } else if (!strcmp(question, "config-text")) {
  1231. *answer = options_dump(get_options(), 1);
  1232. } else if (!strcmp(question, "info/names")) {
  1233. *answer = list_getinfo_options();
  1234. } else if (!strcmp(question, "events/names")) {
  1235. *answer = tor_strdup("CIRC STREAM ORCONN BW DEBUG INFO NOTICE WARN ERR "
  1236. "NEWDESC ADDRMAP AUTHDIR_NEWDESCS DESCCHANGED "
  1237. "NS STATUS_GENERAL STATUS_CLIENT STATUS_SERVER "
  1238. "GUARD STREAM_BW CLIENTS_SEEN NEWCONSENSUS");
  1239. } else if (!strcmp(question, "features/names")) {
  1240. *answer = tor_strdup("VERBOSE_NAMES EXTENDED_EVENTS");
  1241. } else if (!strcmp(question, "address")) {
  1242. uint32_t addr;
  1243. if (router_pick_published_address(get_options(), &addr) < 0) {
  1244. *errmsg = "Address unknown";
  1245. return -1;
  1246. }
  1247. *answer = tor_dup_ip(addr);
  1248. } else if (!strcmp(question, "traffic/read")) {
  1249. tor_asprintf(answer, U64_FORMAT, U64_PRINTF_ARG(get_bytes_read()));
  1250. } else if (!strcmp(question, "traffic/written")) {
  1251. tor_asprintf(answer, U64_FORMAT, U64_PRINTF_ARG(get_bytes_written()));
  1252. } else if (!strcmp(question, "process/pid")) {
  1253. int myPid = -1;
  1254. #ifdef MS_WINDOWS
  1255. myPid = _getpid();
  1256. #else
  1257. myPid = getpid();
  1258. #endif
  1259. tor_asprintf(answer, "%d", myPid);
  1260. } else if (!strcmp(question, "process/uid")) {
  1261. #ifdef MS_WINDOWS
  1262. *answer = tor_strdup("-1");
  1263. #else
  1264. int myUid = geteuid();
  1265. tor_asprintf(answer, "%d", myUid);
  1266. #endif
  1267. } else if (!strcmp(question, "process/user")) {
  1268. #ifdef MS_WINDOWS
  1269. *answer = tor_strdup("");
  1270. #else
  1271. int myUid = geteuid();
  1272. struct passwd *myPwEntry = getpwuid(myUid);
  1273. if (myPwEntry) {
  1274. *answer = tor_strdup(myPwEntry->pw_name);
  1275. } else {
  1276. *answer = tor_strdup("");
  1277. }
  1278. #endif
  1279. } else if (!strcmp(question, "process/descriptor-limit")) {
  1280. /** platform specifc limits are from the set_max_file_descriptors function
  1281. * of src/common/compat.c */
  1282. /* XXXX023 This is duplicated code from compat.c; it should turn into a
  1283. * function. */
  1284. #ifdef HAVE_GETRLIMIT
  1285. struct rlimit descriptorLimit;
  1286. if (getrlimit(RLIMIT_NOFILE, &descriptorLimit) == 0) {
  1287. tor_asprintf(answer, U64_FORMAT,
  1288. U64_PRINTF_ARG(descriptorLimit.rlim_max));
  1289. } else {
  1290. *answer = tor_strdup("-1");
  1291. }
  1292. #elif defined(CYGWIN) || defined(__CYGWIN__)
  1293. *answer = tor_strdup("3200");
  1294. #elif defined(MS_WINDOWS)
  1295. *answer = tor_strdup("15000");
  1296. #else
  1297. *answer = tor_strdup("15000");
  1298. #endif
  1299. } else if (!strcmp(question, "dir-usage")) {
  1300. *answer = directory_dump_request_log();
  1301. } else if (!strcmp(question, "fingerprint")) {
  1302. const routerinfo_t *me = router_get_my_routerinfo();
  1303. if (!me) {
  1304. *errmsg = "No routerdesc known; am I really a server?";
  1305. return -1;
  1306. }
  1307. *answer = tor_malloc(HEX_DIGEST_LEN+1);
  1308. base16_encode(*answer, HEX_DIGEST_LEN+1, me->cache_info.identity_digest,
  1309. DIGEST_LEN);
  1310. }
  1311. return 0;
  1312. }
  1313. /** Awful hack: return a newly allocated string based on a routerinfo and
  1314. * (possibly) an extrainfo, sticking the read-history and write-history from
  1315. * <b>ei</b> into the resulting string. The thing you get back won't
  1316. * necessarily have a valid signature.
  1317. *
  1318. * New code should never use this; it's for backward compatibility.
  1319. *
  1320. * NOTE: <b>ri_body</b> is as returned by signed_descriptor_get_body: it might
  1321. * not be NUL-terminated. */
  1322. static char *
  1323. munge_extrainfo_into_routerinfo(const char *ri_body,
  1324. const signed_descriptor_t *ri,
  1325. const signed_descriptor_t *ei)
  1326. {
  1327. char *out = NULL, *outp;
  1328. int i;
  1329. const char *router_sig;
  1330. const char *ei_body = signed_descriptor_get_body(ei);
  1331. size_t ri_len = ri->signed_descriptor_len;
  1332. size_t ei_len = ei->signed_descriptor_len;
  1333. if (!ei_body)
  1334. goto bail;
  1335. outp = out = tor_malloc(ri_len+ei_len+1);
  1336. if (!(router_sig = tor_memstr(ri_body, ri_len, "\nrouter-signature")))
  1337. goto bail;
  1338. ++router_sig;
  1339. memcpy(out, ri_body, router_sig-ri_body);
  1340. outp += router_sig-ri_body;
  1341. for (i=0; i < 2; ++i) {
  1342. const char *kwd = i?"\nwrite-history ":"\nread-history ";
  1343. const char *cp, *eol;
  1344. if (!(cp = tor_memstr(ei_body, ei_len, kwd)))
  1345. continue;
  1346. ++cp;
  1347. eol = memchr(cp, '\n', ei_len - (cp-ei_body));
  1348. memcpy(outp, cp, eol-cp+1);
  1349. outp += eol-cp+1;
  1350. }
  1351. memcpy(outp, router_sig, ri_len - (router_sig-ri_body));
  1352. *outp++ = '\0';
  1353. tor_assert(outp-out < (int)(ri_len+ei_len+1));
  1354. return out;
  1355. bail:
  1356. tor_free(out);
  1357. return tor_strndup(ri_body, ri->signed_descriptor_len);
  1358. }
  1359. /** Implementation helper for GETINFO: knows the answers for questions about
  1360. * directory information. */
  1361. static int
  1362. getinfo_helper_dir(control_connection_t *control_conn,
  1363. const char *question, char **answer,
  1364. const char **errmsg)
  1365. {
  1366. const routerinfo_t *ri;
  1367. (void) control_conn;
  1368. if (!strcmpstart(question, "desc/id/")) {
  1369. ri = router_get_by_hexdigest(question+strlen("desc/id/"));
  1370. if (ri) {
  1371. const char *body = signed_descriptor_get_body(&ri->cache_info);
  1372. if (body)
  1373. *answer = tor_strndup(body, ri->cache_info.signed_descriptor_len);
  1374. }
  1375. } else if (!strcmpstart(question, "desc/name/")) {
  1376. ri = router_get_by_nickname(question+strlen("desc/name/"),1);
  1377. if (ri) {
  1378. const char *body = signed_descriptor_get_body(&ri->cache_info);
  1379. if (body)
  1380. *answer = tor_strndup(body, ri->cache_info.signed_descriptor_len);
  1381. }
  1382. } else if (!strcmp(question, "desc/all-recent")) {
  1383. routerlist_t *routerlist = router_get_routerlist();
  1384. smartlist_t *sl = smartlist_create();
  1385. if (routerlist && routerlist->routers) {
  1386. SMARTLIST_FOREACH(routerlist->routers, const routerinfo_t *, ri,
  1387. {
  1388. const char *body = signed_descriptor_get_body(&ri->cache_info);
  1389. if (body)
  1390. smartlist_add(sl,
  1391. tor_strndup(body, ri->cache_info.signed_descriptor_len));
  1392. });
  1393. }
  1394. *answer = smartlist_join_strings(sl, "", 0, NULL);
  1395. SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  1396. smartlist_free(sl);
  1397. } else if (!strcmp(question, "desc/all-recent-extrainfo-hack")) {
  1398. /* XXXX Remove this once Torstat asks for extrainfos. */
  1399. routerlist_t *routerlist = router_get_routerlist();
  1400. smartlist_t *sl = smartlist_create();
  1401. if (routerlist && routerlist->routers) {
  1402. SMARTLIST_FOREACH(routerlist->routers, const routerinfo_t *, ri,
  1403. {
  1404. const char *body = signed_descriptor_get_body(&ri->cache_info);
  1405. signed_descriptor_t *ei = extrainfo_get_by_descriptor_digest(
  1406. ri->cache_info.extra_info_digest);
  1407. if (ei && body) {
  1408. smartlist_add(sl, munge_extrainfo_into_routerinfo(body,
  1409. &ri->cache_info, ei));
  1410. } else if (body) {
  1411. smartlist_add(sl,
  1412. tor_strndup(body, ri->cache_info.signed_descriptor_len));
  1413. }
  1414. });
  1415. }
  1416. *answer = smartlist_join_strings(sl, "", 0, NULL);
  1417. SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  1418. smartlist_free(sl);
  1419. } else if (!strcmpstart(question, "desc-annotations/id/")) {
  1420. ri = router_get_by_hexdigest(question+
  1421. strlen("desc-annotations/id/"));
  1422. if (ri) {
  1423. const char *annotations =
  1424. signed_descriptor_get_annotations(&ri->cache_info);
  1425. if (annotations)
  1426. *answer = tor_strndup(annotations,
  1427. ri->cache_info.annotations_len);
  1428. }
  1429. } else if (!strcmpstart(question, "dir/server/")) {
  1430. size_t answer_len = 0, url_len = strlen(question)+2;
  1431. char *url = tor_malloc(url_len);
  1432. smartlist_t *descs = smartlist_create();
  1433. const char *msg;
  1434. int res;
  1435. char *cp;
  1436. tor_snprintf(url, url_len, "/tor/%s", question+4);
  1437. res = dirserv_get_routerdescs(descs, url, &msg);
  1438. if (res) {
  1439. log_warn(LD_CONTROL, "getinfo '%s': %s", question, msg);
  1440. smartlist_free(descs);
  1441. tor_free(url);
  1442. *errmsg = msg;
  1443. return -1;
  1444. }
  1445. SMARTLIST_FOREACH(descs, signed_descriptor_t *, sd,
  1446. answer_len += sd->signed_descriptor_len);
  1447. cp = *answer = tor_malloc(answer_len+1);
  1448. SMARTLIST_FOREACH(descs, signed_descriptor_t *, sd,
  1449. {
  1450. memcpy(cp, signed_descriptor_get_body(sd),
  1451. sd->signed_descriptor_len);
  1452. cp += sd->signed_descriptor_len;
  1453. });
  1454. *cp = '\0';
  1455. tor_free(url);
  1456. smartlist_free(descs);
  1457. } else if (!strcmpstart(question, "dir/status/")) {
  1458. if (directory_permits_controller_requests(get_options())) {
  1459. size_t len=0;
  1460. char *cp;
  1461. smartlist_t *status_list = smartlist_create();
  1462. dirserv_get_networkstatus_v2(status_list,
  1463. question+strlen("dir/status/"));
  1464. SMARTLIST_FOREACH(status_list, cached_dir_t *, d, len += d->dir_len);
  1465. cp = *answer = tor_malloc(len+1);
  1466. SMARTLIST_FOREACH(status_list, cached_dir_t *, d, {
  1467. memcpy(cp, d->dir, d->dir_len);
  1468. cp += d->dir_len;
  1469. });
  1470. *cp = '\0';
  1471. smartlist_free(status_list);
  1472. } else {
  1473. smartlist_t *fp_list = smartlist_create();
  1474. smartlist_t *status_list = smartlist_create();
  1475. dirserv_get_networkstatus_v2_fingerprints(
  1476. fp_list, question+strlen("dir/status/"));
  1477. SMARTLIST_FOREACH(fp_list, const char *, fp, {
  1478. char *s;
  1479. char *fname = networkstatus_get_cache_filename(fp);
  1480. s = read_file_to_str(fname, 0, NULL);
  1481. if (s)
  1482. smartlist_add(status_list, s);
  1483. tor_free(fname);
  1484. });
  1485. SMARTLIST_FOREACH(fp_list, char *, fp, tor_free(fp));
  1486. smartlist_free(fp_list);
  1487. *answer = smartlist_join_strings(status_list, "", 0, NULL);
  1488. SMARTLIST_FOREACH(status_list, char *, s, tor_free(s));
  1489. smartlist_free(status_list);
  1490. }
  1491. } else if (!strcmp(question, "dir/status-vote/current/consensus")) { /* v3 */
  1492. if (directory_caches_dir_info(get_options())) {
  1493. const cached_dir_t *consensus = dirserv_get_consensus("ns");
  1494. if (consensus)
  1495. *answer = tor_strdup(consensus->dir);
  1496. }
  1497. if (!*answer) { /* try loading it from disk */
  1498. char *filename = get_datadir_fname("cached-consensus");
  1499. *answer = read_file_to_str(filename, RFTS_IGNORE_MISSING, NULL);
  1500. tor_free(filename);
  1501. }
  1502. } else if (!strcmp(question, "network-status")) { /* v1 */
  1503. routerlist_t *routerlist = router_get_routerlist();
  1504. if (!routerlist || !routerlist->routers ||
  1505. list_server_status_v1(routerlist->routers, answer, 1) < 0) {
  1506. return -1;
  1507. }
  1508. } else if (!strcmpstart(question, "extra-info/digest/")) {
  1509. question += strlen("extra-info/digest/");
  1510. if (strlen(question) == HEX_DIGEST_LEN) {
  1511. char d[DIGEST_LEN];
  1512. signed_descriptor_t *sd = NULL;
  1513. if (base16_decode(d, sizeof(d), question, strlen(question))==0) {
  1514. /* XXXX this test should move into extrainfo_get_by_descriptor_digest,
  1515. * but I don't want to risk affecting other parts of the code,
  1516. * especially since the rules for using our own extrainfo (including
  1517. * when it might be freed) are different from those for using one
  1518. * we have downloaded. */
  1519. if (router_extrainfo_digest_is_me(d))
  1520. sd = &(router_get_my_extrainfo()->cache_info);
  1521. else
  1522. sd = extrainfo_get_by_descriptor_digest(d);
  1523. }
  1524. if (sd) {
  1525. const char *body = signed_descriptor_get_body(sd);
  1526. if (body)
  1527. *answer = tor_strndup(body, sd->signed_descriptor_len);
  1528. }
  1529. }
  1530. }
  1531. return 0;
  1532. }
  1533. /** Implementation helper for GETINFO: knows how to generate summaries of the
  1534. * current states of things we send events about. */
  1535. static int
  1536. getinfo_helper_events(control_connection_t *control_conn,
  1537. const char *question, char **answer,
  1538. const char **errmsg)
  1539. {
  1540. (void) control_conn;
  1541. if (!strcmp(question, "circuit-status")) {
  1542. circuit_t *circ;
  1543. smartlist_t *status = smartlist_create();
  1544. for (circ = _circuit_get_global_list(); circ; circ = circ->next) {
  1545. char *s, *path;
  1546. size_t slen;
  1547. const char *state;
  1548. const char *purpose;
  1549. if (! CIRCUIT_IS_ORIGIN(circ) || circ->marked_for_close)
  1550. continue;
  1551. path = circuit_list_path_for_controller(TO_ORIGIN_CIRCUIT(circ));
  1552. if (circ->state == CIRCUIT_STATE_OPEN)
  1553. state = "BUILT";
  1554. else if (strlen(path))
  1555. state = "EXTENDED";
  1556. else
  1557. state = "LAUNCHED";
  1558. purpose = circuit_purpose_to_controller_string(circ->purpose);
  1559. slen = strlen(path)+strlen(state)+strlen(purpose)+30;
  1560. s = tor_malloc(slen+1);
  1561. tor_snprintf(s, slen, "%lu %s%s%s PURPOSE=%s",
  1562. (unsigned long)TO_ORIGIN_CIRCUIT(circ)->global_identifier,
  1563. state, *path ? " " : "", path, purpose);
  1564. smartlist_add(status, s);
  1565. tor_free(path);
  1566. }
  1567. *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
  1568. SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
  1569. smartlist_free(status);
  1570. } else if (!strcmp(question, "stream-status")) {
  1571. smartlist_t *conns = get_connection_array();
  1572. smartlist_t *status = smartlist_create();
  1573. char buf[256];
  1574. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, base_conn) {
  1575. const char *state;
  1576. edge_connection_t *conn;
  1577. char *s;
  1578. size_t slen;
  1579. circuit_t *circ;
  1580. origin_circuit_t *origin_circ = NULL;
  1581. if (base_conn->type != CONN_TYPE_AP ||
  1582. base_conn->marked_for_close ||
  1583. base_conn->state == AP_CONN_STATE_SOCKS_WAIT ||
  1584. base_conn->state == AP_CONN_STATE_NATD_WAIT)
  1585. continue;
  1586. conn = TO_EDGE_CONN(base_conn);
  1587. switch (conn->_base.state)
  1588. {
  1589. case AP_CONN_STATE_CONTROLLER_WAIT:
  1590. case AP_CONN_STATE_CIRCUIT_WAIT:
  1591. if (conn->socks_request &&
  1592. SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command))
  1593. state = "NEWRESOLVE";
  1594. else
  1595. state = "NEW";
  1596. break;
  1597. case AP_CONN_STATE_RENDDESC_WAIT:
  1598. case AP_CONN_STATE_CONNECT_WAIT:
  1599. state = "SENTCONNECT"; break;
  1600. case AP_CONN_STATE_RESOLVE_WAIT:
  1601. state = "SENTRESOLVE"; break;
  1602. case AP_CONN_STATE_OPEN:
  1603. state = "SUCCEEDED"; break;
  1604. default:
  1605. log_warn(LD_BUG, "Asked for stream in unknown state %d",
  1606. conn->_base.state);
  1607. continue;
  1608. }
  1609. circ = circuit_get_by_edge_conn(conn);
  1610. if (circ && CIRCUIT_IS_ORIGIN(circ))
  1611. origin_circ = TO_ORIGIN_CIRCUIT(circ);
  1612. write_stream_target_to_buf(conn, buf, sizeof(buf));
  1613. slen = strlen(buf)+strlen(state)+32;
  1614. s = tor_malloc(slen+1);
  1615. tor_snprintf(s, slen, "%lu %s %lu %s",
  1616. (unsigned long) conn->_base.global_identifier,state,
  1617. origin_circ?
  1618. (unsigned long)origin_circ->global_identifier : 0ul,
  1619. buf);
  1620. smartlist_add(status, s);
  1621. } SMARTLIST_FOREACH_END(base_conn);
  1622. *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
  1623. SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
  1624. smartlist_free(status);
  1625. } else if (!strcmp(question, "orconn-status")) {
  1626. smartlist_t *conns = get_connection_array();
  1627. smartlist_t *status = smartlist_create();
  1628. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, base_conn) {
  1629. const char *state;
  1630. char *s;
  1631. char name[128];
  1632. size_t slen;
  1633. or_connection_t *conn;
  1634. if (base_conn->type != CONN_TYPE_OR || base_conn->marked_for_close)
  1635. continue;
  1636. conn = TO_OR_CONN(base_conn);
  1637. if (conn->_base.state == OR_CONN_STATE_OPEN)
  1638. state = "CONNECTED";
  1639. else if (conn->nickname)
  1640. state = "LAUNCHED";
  1641. else
  1642. state = "NEW";
  1643. orconn_target_get_name(name, sizeof(name), conn);
  1644. slen = strlen(name)+strlen(state)+2;
  1645. s = tor_malloc(slen+1);
  1646. tor_snprintf(s, slen, "%s %s", name, state);
  1647. smartlist_add(status, s);
  1648. } SMARTLIST_FOREACH_END(base_conn);
  1649. *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
  1650. SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
  1651. smartlist_free(status);
  1652. } else if (!strcmpstart(question, "address-mappings/")) {
  1653. time_t min_e, max_e;
  1654. smartlist_t *mappings;
  1655. question += strlen("address-mappings/");
  1656. if (!strcmp(question, "all")) {
  1657. min_e = 0; max_e = TIME_MAX;
  1658. } else if (!strcmp(question, "cache")) {
  1659. min_e = 2; max_e = TIME_MAX;
  1660. } else if (!strcmp(question, "config")) {
  1661. min_e = 0; max_e = 0;
  1662. } else if (!strcmp(question, "control")) {
  1663. min_e = 1; max_e = 1;
  1664. } else {
  1665. return 0;
  1666. }
  1667. mappings = smartlist_create();
  1668. addressmap_get_mappings(mappings, min_e, max_e, 1);
  1669. *answer = smartlist_join_strings(mappings, "\r\n", 0, NULL);
  1670. SMARTLIST_FOREACH(mappings, char *, cp, tor_free(cp));
  1671. smartlist_free(mappings);
  1672. } else if (!strcmpstart(question, "status/")) {
  1673. /* Note that status/ is not a catch-all for events; there's only supposed
  1674. * to be a status GETINFO if there's a corresponding STATUS event. */
  1675. if (!strcmp(question, "status/circuit-established")) {
  1676. *answer = tor_strdup(can_complete_circuit ? "1" : "0");
  1677. } else if (!strcmp(question, "status/enough-dir-info")) {
  1678. *answer = tor_strdup(router_have_minimum_dir_info() ? "1" : "0");
  1679. } else if (!strcmp(question, "status/good-server-descriptor") ||
  1680. !strcmp(question, "status/accepted-server-descriptor")) {
  1681. /* They're equivalent for now, until we can figure out how to make
  1682. * good-server-descriptor be what we want. See comment in
  1683. * control-spec.txt. */
  1684. *answer = tor_strdup(directories_have_accepted_server_descriptor()
  1685. ? "1" : "0");
  1686. } else if (!strcmp(question, "status/reachability-succeeded/or")) {
  1687. *answer = tor_strdup(check_whether_orport_reachable() ? "1" : "0");
  1688. } else if (!strcmp(question, "status/reachability-succeeded/dir")) {
  1689. *answer = tor_strdup(check_whether_dirport_reachable() ? "1" : "0");
  1690. } else if (!strcmp(question, "status/reachability-succeeded")) {
  1691. *answer = tor_malloc(16);
  1692. tor_snprintf(*answer, 16, "OR=%d DIR=%d",
  1693. check_whether_orport_reachable() ? 1 : 0,
  1694. check_whether_dirport_reachable() ? 1 : 0);
  1695. } else if (!strcmp(question, "status/bootstrap-phase")) {
  1696. *answer = tor_strdup(last_sent_bootstrap_message);
  1697. } else if (!strcmpstart(question, "status/version/")) {
  1698. int is_server = server_mode(get_options());
  1699. networkstatus_t *c = networkstatus_get_latest_consensus();
  1700. version_status_t status;
  1701. const char *recommended;
  1702. if (c) {
  1703. recommended = is_server ? c->server_versions : c->client_versions;
  1704. status = tor_version_is_obsolete(VERSION, recommended);
  1705. } else {
  1706. recommended = "?";
  1707. status = VS_UNKNOWN;
  1708. }
  1709. if (!strcmp(question, "status/version/recommended")) {
  1710. *answer = tor_strdup(recommended);
  1711. return 0;
  1712. }
  1713. if (!strcmp(question, "status/version/current")) {
  1714. switch (status)
  1715. {
  1716. case VS_RECOMMENDED: *answer = tor_strdup("recommended"); break;
  1717. case VS_OLD: *answer = tor_strdup("obsolete"); break;
  1718. case VS_NEW: *answer = tor_strdup("new"); break;
  1719. case VS_NEW_IN_SERIES: *answer = tor_strdup("new in series"); break;
  1720. case VS_UNRECOMMENDED: *answer = tor_strdup("unrecommended"); break;
  1721. case VS_EMPTY: *answer = tor_strdup("none recommended"); break;
  1722. case VS_UNKNOWN: *answer = tor_strdup("unknown"); break;
  1723. default: tor_fragile_assert();
  1724. }
  1725. } else if (!strcmp(question, "status/version/num-versioning") ||
  1726. !strcmp(question, "status/version/num-concurring")) {
  1727. char s[33];
  1728. tor_snprintf(s, sizeof(s), "%d", get_n_authorities(V3_AUTHORITY));
  1729. *answer = tor_strdup(s);
  1730. log_warn(LD_GENERAL, "%s is deprecated; it no longer gives useful "
  1731. "information", question);
  1732. }
  1733. } else if (!strcmp(question, "status/clients-seen")) {
  1734. const char *bridge_stats = geoip_get_bridge_stats_controller(time(NULL));
  1735. if (!bridge_stats) {
  1736. *errmsg = "No bridge-client stats available";
  1737. return -1;
  1738. }
  1739. *answer = tor_strdup(bridge_stats);
  1740. } else {
  1741. return 0;
  1742. }
  1743. }
  1744. return 0;
  1745. }
  1746. /** Callback function for GETINFO: on a given control connection, try to
  1747. * answer the question <b>q</b> and store the newly-allocated answer in
  1748. * *<b>a</b>. If an internal error occurs, return -1 and optionally set
  1749. * *<b>error_out</b> to point to an error message to be delivered to the
  1750. * controller. On success, _or if the key is not recognized_, return 0. Do not
  1751. * set <b>a</b> if the key is not recognized.
  1752. */
  1753. typedef int (*getinfo_helper_t)(control_connection_t *,
  1754. const char *q, char **a,
  1755. const char **error_out);
  1756. /** A single item for the GETINFO question-to-answer-function table. */
  1757. typedef struct getinfo_item_t {
  1758. const char *varname; /**< The value (or prefix) of the question. */
  1759. getinfo_helper_t fn; /**< The function that knows the answer: NULL if
  1760. * this entry is documentation-only. */
  1761. const char *desc; /**< Description of the variable. */
  1762. int is_prefix; /** Must varname match exactly, or must it be a prefix? */
  1763. } getinfo_item_t;
  1764. #define ITEM(name, fn, desc) { name, getinfo_helper_##fn, desc, 0 }
  1765. #define PREFIX(name, fn, desc) { name, getinfo_helper_##fn, desc, 1 }
  1766. #define DOC(name, desc) { name, NULL, desc, 0 }
  1767. /** Table mapping questions accepted by GETINFO to the functions that know how
  1768. * to answer them. */
  1769. static const getinfo_item_t getinfo_items[] = {
  1770. ITEM("version", misc, "The current version of Tor."),
  1771. ITEM("config-file", misc, "Current location of the \"torrc\" file."),
  1772. ITEM("config-text", misc,
  1773. "Return the string that would be written by a saveconf command."),
  1774. ITEM("accounting/bytes", accounting,
  1775. "Number of bytes read/written so far in the accounting interval."),
  1776. ITEM("accounting/bytes-left", accounting,
  1777. "Number of bytes left to write/read so far in the accounting interval."),
  1778. ITEM("accounting/enabled", accounting, "Is accounting currently enabled?"),
  1779. ITEM("accounting/hibernating", accounting, "Are we hibernating or awake?"),
  1780. ITEM("accounting/interval-start", accounting,
  1781. "Time when the accounting period starts."),
  1782. ITEM("accounting/interval-end", accounting,
  1783. "Time when the accounting period ends."),
  1784. ITEM("accounting/interval-wake", accounting,
  1785. "Time to wake up in this accounting period."),
  1786. ITEM("helper-nodes", entry_guards, NULL), /* deprecated */
  1787. ITEM("entry-guards", entry_guards,
  1788. "Which nodes are we using as entry guards?"),
  1789. ITEM("fingerprint", misc, NULL),
  1790. PREFIX("config/", config, "Current configuration values."),
  1791. DOC("config/names",
  1792. "List of configuration options, types, and documentation."),
  1793. ITEM("info/names", misc,
  1794. "List of GETINFO options, types, and documentation."),
  1795. ITEM("events/names", misc,
  1796. "Events that the controller can ask for with SETEVENTS."),
  1797. ITEM("features/names", misc, "What arguments can USEFEATURE take?"),
  1798. PREFIX("desc/id/", dir, "Router descriptors by ID."),
  1799. PREFIX("desc/name/", dir, "Router descriptors by nickname."),
  1800. ITEM("desc/all-recent", dir,
  1801. "All non-expired, non-superseded router descriptors."),
  1802. ITEM("desc/all-recent-extrainfo-hack", dir, NULL), /* Hack. */
  1803. PREFIX("extra-info/digest/", dir, "Extra-info documents by digest."),
  1804. ITEM("ns/all", networkstatus,
  1805. "Brief summary of router status (v2 directory format)"),
  1806. PREFIX("ns/id/", networkstatus,
  1807. "Brief summary of router status by ID (v2 directory format)."),
  1808. PREFIX("ns/name/", networkstatus,
  1809. "Brief summary of router status by nickname (v2 directory format)."),
  1810. PREFIX("ns/purpose/", networkstatus,
  1811. "Brief summary of router status by purpose (v2 directory format)."),
  1812. ITEM("network-status", dir,
  1813. "Brief summary of router status (v1 directory format)"),
  1814. ITEM("circuit-status", events, "List of current circuits originating here."),
  1815. ITEM("stream-status", events,"List of current streams."),
  1816. ITEM("orconn-status", events, "A list of current OR connections."),
  1817. PREFIX("address-mappings/", events, NULL),
  1818. DOC("address-mappings/all", "Current address mappings."),
  1819. DOC("address-mappings/cache", "Current cached DNS replies."),
  1820. DOC("address-mappings/config",
  1821. "Current address mappings from configuration."),
  1822. DOC("address-mappings/control", "Current address mappings from controller."),
  1823. PREFIX("status/", events, NULL),
  1824. DOC("status/circuit-established",
  1825. "Whether we think client functionality is working."),
  1826. DOC("status/enough-dir-info",
  1827. "Whether we have enough up-to-date directory information to build "
  1828. "circuits."),
  1829. DOC("status/bootstrap-phase",
  1830. "The last bootstrap phase status event that Tor sent."),
  1831. DOC("status/clients-seen",
  1832. "Breakdown of client countries seen by a bridge."),
  1833. DOC("status/version/recommended", "List of currently recommended versions."),
  1834. DOC("status/version/current", "Status of the current version."),
  1835. DOC("status/version/num-versioning", "Number of versioning authorities."),
  1836. DOC("status/version/num-concurring",
  1837. "Number of versioning authorities agreeing on the status of the "
  1838. "current version"),
  1839. ITEM("address", misc, "IP address of this Tor host, if we can guess it."),
  1840. ITEM("traffic/read", misc, "Bytes read since the process was started."),
  1841. ITEM("traffic/written", misc, "Bytes written since the process was started."),
  1842. ITEM("process/pid", misc, "Process id belonging to the main tor process."),
  1843. ITEM("process/uid", misc, "User id running the tor process."),
  1844. ITEM("process/user", misc,"Username under which the tor process is running."),
  1845. ITEM("process/descriptor-limit", misc, "File descriptor limit."),
  1846. ITEM("dir-usage", misc, "Breakdown of bytes transferred over DirPort."),
  1847. PREFIX("desc-annotations/id/", dir, "Router annotations by hexdigest."),
  1848. PREFIX("dir/server/", dir,"Router descriptors as retrieved from a DirPort."),
  1849. PREFIX("dir/status/", dir,
  1850. "v2 networkstatus docs as retrieved from a DirPort."),
  1851. ITEM("dir/status-vote/current/consensus", dir,
  1852. "v3 Networkstatus consensus as retrieved from a DirPort."),
  1853. PREFIX("exit-policy/default", policies,
  1854. "The default value appended to the configured exit policy."),
  1855. PREFIX("ip-to-country/", geoip, "Perform a GEOIP lookup"),
  1856. { NULL, NULL, NULL, 0 }
  1857. };
  1858. /** Allocate and return a list of recognized GETINFO options. */
  1859. static char *
  1860. list_getinfo_options(void)
  1861. {
  1862. int i;
  1863. char *buf=NULL;
  1864. smartlist_t *lines = smartlist_create();
  1865. char *ans;
  1866. for (i = 0; getinfo_items[i].varname; ++i) {
  1867. if (!getinfo_items[i].desc)
  1868. continue;
  1869. tor_asprintf(&buf, "%s%s -- %s\n",
  1870. getinfo_items[i].varname,
  1871. getinfo_items[i].is_prefix ? "*" : "",
  1872. getinfo_items[i].desc);
  1873. smartlist_add(lines, buf);
  1874. }
  1875. smartlist_sort_strings(lines);
  1876. ans = smartlist_join_strings(lines, "", 0, NULL);
  1877. SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
  1878. smartlist_free(lines);
  1879. return ans;
  1880. }
  1881. /** Lookup the 'getinfo' entry <b>question</b>, and return
  1882. * the answer in <b>*answer</b> (or NULL if key not recognized).
  1883. * Return 0 if success or unrecognized, or -1 if recognized but
  1884. * internal error. */
  1885. static int
  1886. handle_getinfo_helper(control_connection_t *control_conn,
  1887. const char *question, char **answer,
  1888. const char **err_out)
  1889. {
  1890. int i;
  1891. *answer = NULL; /* unrecognized key by default */
  1892. for (i = 0; getinfo_items[i].varname; ++i) {
  1893. int match;
  1894. if (getinfo_items[i].is_prefix)
  1895. match = !strcmpstart(question, getinfo_items[i].varname);
  1896. else
  1897. match = !strcmp(question, getinfo_items[i].varname);
  1898. if (match) {
  1899. tor_assert(getinfo_items[i].fn);
  1900. return getinfo_items[i].fn(control_conn, question, answer, err_out);
  1901. }
  1902. }
  1903. return 0; /* unrecognized */
  1904. }
  1905. /** Called when we receive a GETINFO command. Try to fetch all requested
  1906. * information, and reply with information or error message. */
  1907. static int
  1908. handle_control_getinfo(control_connection_t *conn, uint32_t len,
  1909. const char *body)
  1910. {
  1911. smartlist_t *questions = smartlist_create();
  1912. smartlist_t *answers = smartlist_create();
  1913. smartlist_t *unrecognized = smartlist_create();
  1914. char *msg = NULL, *ans = NULL;
  1915. int i;
  1916. (void) len; /* body is NUL-terminated, so it's safe to ignore the length. */
  1917. smartlist_split_string(questions, body, " ",
  1918. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1919. SMARTLIST_FOREACH_BEGIN(questions, const char *, q) {
  1920. const char *errmsg = NULL;
  1921. if (handle_getinfo_helper(conn, q, &ans, &errmsg) < 0) {
  1922. if (!errmsg)
  1923. errmsg = "Internal error";
  1924. connection_printf_to_buf(conn, "551 %s\r\n", errmsg);
  1925. goto done;
  1926. }
  1927. if (!ans) {
  1928. smartlist_add(unrecognized, (char*)q);
  1929. } else {
  1930. smartlist_add(answers, tor_strdup(q));
  1931. smartlist_add(answers, ans);
  1932. }
  1933. } SMARTLIST_FOREACH_END(q);
  1934. if (smartlist_len(unrecognized)) {
  1935. for (i=0; i < smartlist_len(unrecognized)-1; ++i)
  1936. connection_printf_to_buf(conn,
  1937. "552-Unrecognized key \"%s\"\r\n",
  1938. (char*)smartlist_get(unrecognized, i));
  1939. connection_printf_to_buf(conn,
  1940. "552 Unrecognized key \"%s\"\r\n",
  1941. (char*)smartlist_get(unrecognized, i));
  1942. goto done;
  1943. }
  1944. for (i = 0; i < smartlist_len(answers); i += 2) {
  1945. char *k = smartlist_get(answers, i);
  1946. char *v = smartlist_get(answers, i+1);
  1947. if (!strchr(v, '\n') && !strchr(v, '\r')) {
  1948. connection_printf_to_buf(conn, "250-%s=", k);
  1949. connection_write_str_to_buf(v, conn);
  1950. connection_write_str_to_buf("\r\n", conn);
  1951. } else {
  1952. char *esc = NULL;
  1953. size_t esc_len;
  1954. esc_len = write_escaped_data(v, strlen(v), &esc);
  1955. connection_printf_to_buf(conn, "250+%s=\r\n", k);
  1956. connection_write_to_buf(esc, esc_len, TO_CONN(conn));
  1957. tor_free(esc);
  1958. }
  1959. }
  1960. connection_write_str_to_buf("250 OK\r\n", conn);
  1961. done:
  1962. SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
  1963. smartlist_free(answers);
  1964. SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
  1965. smartlist_free(questions);
  1966. smartlist_free(unrecognized);
  1967. tor_free(msg);
  1968. return 0;
  1969. }
  1970. /** Given a string, convert it to a circuit purpose. */
  1971. static uint8_t
  1972. circuit_purpose_from_string(const char *string)
  1973. {
  1974. if (!strcasecmpstart(string, "purpose="))
  1975. string += strlen("purpose=");
  1976. if (!strcasecmp(string, "general"))
  1977. return CIRCUIT_PURPOSE_C_GENERAL;
  1978. else if (!strcasecmp(string, "controller"))
  1979. return CIRCUIT_PURPOSE_CONTROLLER;
  1980. else
  1981. return CIRCUIT_PURPOSE_UNKNOWN;
  1982. }
  1983. /** Return a newly allocated smartlist containing the arguments to the command
  1984. * waiting in <b>body</b>. If there are fewer than <b>min_args</b> arguments,
  1985. * or if <b>max_args</b> is nonnegative and there are more than
  1986. * <b>max_args</b> arguments, send a 512 error to the controller, using
  1987. * <b>command</b> as the command name in the error message. */
  1988. static smartlist_t *
  1989. getargs_helper(const char *command, control_connection_t *conn,
  1990. const char *body, int min_args, int max_args)
  1991. {
  1992. smartlist_t *args = smartlist_create();
  1993. smartlist_split_string(args, body, " ",
  1994. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1995. if (smartlist_len(args) < min_args) {
  1996. connection_printf_to_buf(conn, "512 Missing argument to %s\r\n",command);
  1997. goto err;
  1998. } else if (max_args >= 0 && smartlist_len(args) > max_args) {
  1999. connection_printf_to_buf(conn, "512 Too many arguments to %s\r\n",command);
  2000. goto err;
  2001. }
  2002. return args;
  2003. err:
  2004. SMARTLIST_FOREACH(args, char *, s, tor_free(s));
  2005. smartlist_free(args);
  2006. return NULL;
  2007. }
  2008. /** Helper. Return the first element of <b>sl</b> at index <b>start_at</b> or
  2009. * higher that starts with <b>prefix</b>, case-insensitive. Return NULL if no
  2010. * such element exists. */
  2011. static const char *
  2012. find_element_starting_with(smartlist_t *sl, int start_at, const char *prefix)
  2013. {
  2014. int i;
  2015. for (i = start_at; i < smartlist_len(sl); ++i) {
  2016. const char *elt = smartlist_get(sl, i);
  2017. if (!strcasecmpstart(elt, prefix))
  2018. return elt;
  2019. }
  2020. return NULL;
  2021. }
  2022. /** Helper. Return true iff s is an argument that we should treat as a
  2023. * key-value pair. */
  2024. static int
  2025. is_keyval_pair(const char *s)
  2026. {
  2027. /* An argument is a key-value pair if it has an =, and it isn't of the form
  2028. * $fingeprint=name */
  2029. return strchr(s, '=') && s[0] != '$';
  2030. }
  2031. /** Called when we get an EXTENDCIRCUIT message. Try to extend the listed
  2032. * circuit, and report success or failure. */
  2033. static int
  2034. handle_control_extendcircuit(control_connection_t *conn, uint32_t len,
  2035. const char *body)
  2036. {
  2037. smartlist_t *router_nicknames=NULL, *nodes=NULL;
  2038. origin_circuit_t *circ = NULL;
  2039. int zero_circ;
  2040. uint8_t intended_purpose = CIRCUIT_PURPOSE_C_GENERAL;
  2041. smartlist_t *args;
  2042. (void) len;
  2043. router_nicknames = smartlist_create();
  2044. args = getargs_helper("EXTENDCIRCUIT", conn, body, 1, -1);
  2045. if (!args)
  2046. goto done;
  2047. zero_circ = !strcmp("0", (char*)smartlist_get(args,0));
  2048. if (zero_circ) {
  2049. const char *purp = find_element_starting_with(args, 1, "PURPOSE=");
  2050. if (purp) {
  2051. intended_purpose = circuit_purpose_from_string(purp);
  2052. if (intended_purpose == CIRCUIT_PURPOSE_UNKNOWN) {
  2053. connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n", purp);
  2054. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2055. smartlist_free(args);
  2056. goto done;
  2057. }
  2058. }
  2059. if ((smartlist_len(args) == 1) ||
  2060. (smartlist_len(args) >= 2 && is_keyval_pair(smartlist_get(args, 1)))) {
  2061. // "EXTENDCIRCUIT 0" || EXTENDCIRCUIT 0 foo=bar"
  2062. circ = circuit_launch(intended_purpose, CIRCLAUNCH_NEED_CAPACITY);
  2063. if (!circ) {
  2064. connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn);
  2065. } else {
  2066. connection_printf_to_buf(conn, "250 EXTENDED %lu\r\n",
  2067. (unsigned long)circ->global_identifier);
  2068. }
  2069. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2070. smartlist_free(args);
  2071. goto done;
  2072. }
  2073. // "EXTENDCIRCUIT 0 router1,router2" ||
  2074. // "EXTENDCIRCUIT 0 router1,router2 PURPOSE=foo"
  2075. }
  2076. if (!zero_circ && !(circ = get_circ(smartlist_get(args,0)))) {
  2077. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  2078. (char*)smartlist_get(args, 0));
  2079. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2080. smartlist_free(args);
  2081. goto done;
  2082. }
  2083. smartlist_split_string(router_nicknames, smartlist_get(args,1), ",", 0, 0);
  2084. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2085. smartlist_free(args);
  2086. nodes = smartlist_create();
  2087. SMARTLIST_FOREACH(router_nicknames, const char *, n,
  2088. {
  2089. const node_t *node = node_get_by_nickname(n, 1);
  2090. if (!node) {
  2091. connection_printf_to_buf(conn, "552 No such router \"%s\"\r\n", n);
  2092. goto done;
  2093. }
  2094. if (!node_has_descriptor(node)) {
  2095. connection_printf_to_buf(conn, "552 descriptor for \"%s\"\r\n", n);
  2096. goto done;
  2097. }
  2098. smartlist_add(nodes, (void*)node);
  2099. });
  2100. if (!smartlist_len(nodes)) {
  2101. connection_write_str_to_buf("512 No router names provided\r\n", conn);
  2102. goto done;
  2103. }
  2104. if (zero_circ) {
  2105. /* start a new circuit */
  2106. circ = origin_circuit_init(intended_purpose, 0);
  2107. }
  2108. /* now circ refers to something that is ready to be extended */
  2109. SMARTLIST_FOREACH(nodes, const node_t *, node,
  2110. {
  2111. extend_info_t *info = extend_info_from_node(node);
  2112. tor_assert(info); /* True, since node_has_descriptor(node) == true */
  2113. circuit_append_new_exit(circ, info);
  2114. extend_info_free(info);
  2115. });
  2116. /* now that we've populated the cpath, start extending */
  2117. if (zero_circ) {
  2118. int err_reason = 0;
  2119. if ((err_reason = circuit_handle_first_hop(circ)) < 0) {
  2120. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  2121. connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn);
  2122. goto done;
  2123. }
  2124. } else {
  2125. if (circ->_base.state == CIRCUIT_STATE_OPEN) {
  2126. int err_reason = 0;
  2127. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
  2128. if ((err_reason = circuit_send_next_onion_skin(circ)) < 0) {
  2129. log_info(LD_CONTROL,
  2130. "send_next_onion_skin failed; circuit marked for closing.");
  2131. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  2132. connection_write_str_to_buf("551 Couldn't send onion skin\r\n", conn);
  2133. goto done;
  2134. }
  2135. }
  2136. }
  2137. connection_printf_to_buf(conn, "250 EXTENDED %lu\r\n",
  2138. (unsigned long)circ->global_identifier);
  2139. if (zero_circ) /* send a 'launched' event, for completeness */
  2140. control_event_circuit_status(circ, CIRC_EVENT_LAUNCHED, 0);
  2141. done:
  2142. SMARTLIST_FOREACH(router_nicknames, char *, n, tor_free(n));
  2143. smartlist_free(router_nicknames);
  2144. smartlist_free(nodes);
  2145. return 0;
  2146. }
  2147. /** Called when we get a SETCIRCUITPURPOSE message. If we can find the
  2148. * circuit and it's a valid purpose, change it. */
  2149. static int
  2150. handle_control_setcircuitpurpose(control_connection_t *conn,
  2151. uint32_t len, const char *body)
  2152. {
  2153. origin_circuit_t *circ = NULL;
  2154. uint8_t new_purpose;
  2155. smartlist_t *args;
  2156. (void) len; /* body is NUL-terminated, so it's safe to ignore the length. */
  2157. args = getargs_helper("SETCIRCUITPURPOSE", conn, body, 2, -1);
  2158. if (!args)
  2159. goto done;
  2160. if (!(circ = get_circ(smartlist_get(args,0)))) {
  2161. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  2162. (char*)smartlist_get(args, 0));
  2163. goto done;
  2164. }
  2165. {
  2166. const char *purp = find_element_starting_with(args,1,"PURPOSE=");
  2167. new_purpose = circuit_purpose_from_string(purp);
  2168. if (new_purpose == CIRCUIT_PURPOSE_UNKNOWN) {
  2169. connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n", purp);
  2170. goto done;
  2171. }
  2172. }
  2173. circ->_base.purpose = new_purpose;
  2174. connection_write_str_to_buf("250 OK\r\n", conn);
  2175. done:
  2176. if (args) {
  2177. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2178. smartlist_free(args);
  2179. }
  2180. return 0;
  2181. }
  2182. /** Called when we get an ATTACHSTREAM message. Try to attach the requested
  2183. * stream, and report success or failure. */
  2184. static int
  2185. handle_control_attachstream(control_connection_t *conn, uint32_t len,
  2186. const char *body)
  2187. {
  2188. edge_connection_t *ap_conn = NULL;
  2189. origin_circuit_t *circ = NULL;
  2190. int zero_circ;
  2191. smartlist_t *args;
  2192. crypt_path_t *cpath=NULL;
  2193. int hop=0, hop_line_ok=1;
  2194. (void) len;
  2195. args = getargs_helper("ATTACHSTREAM", conn, body, 2, -1);
  2196. if (!args)
  2197. return 0;
  2198. zero_circ = !strcmp("0", (char*)smartlist_get(args,1));
  2199. if (!(ap_conn = get_stream(smartlist_get(args, 0)))) {
  2200. connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
  2201. (char*)smartlist_get(args, 0));
  2202. } else if (!zero_circ && !(circ = get_circ(smartlist_get(args, 1)))) {
  2203. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  2204. (char*)smartlist_get(args, 1));
  2205. } else if (circ) {
  2206. const char *hopstring = find_element_starting_with(args,2,"HOP=");
  2207. if (hopstring) {
  2208. hopstring += strlen("HOP=");
  2209. hop = (int) tor_parse_ulong(hopstring, 10, 0, INT_MAX,
  2210. &hop_line_ok, NULL);
  2211. if (!hop_line_ok) { /* broken hop line */
  2212. connection_printf_to_buf(conn, "552 Bad value hop=%s\r\n", hopstring);
  2213. }
  2214. }
  2215. }
  2216. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2217. smartlist_free(args);
  2218. if (!ap_conn || (!zero_circ && !circ) || !hop_line_ok)
  2219. return 0;
  2220. if (ap_conn->_base.state != AP_CONN_STATE_CONTROLLER_WAIT &&
  2221. ap_conn->_base.state != AP_CONN_STATE_CONNECT_WAIT &&
  2222. ap_conn->_base.state != AP_CONN_STATE_RESOLVE_WAIT) {
  2223. connection_write_str_to_buf(
  2224. "555 Connection is not managed by controller.\r\n",
  2225. conn);
  2226. return 0;
  2227. }
  2228. /* Do we need to detach it first? */
  2229. if (ap_conn->_base.state != AP_CONN_STATE_CONTROLLER_WAIT) {
  2230. circuit_t *tmpcirc = circuit_get_by_edge_conn(ap_conn);
  2231. connection_edge_end(ap_conn, END_STREAM_REASON_TIMEOUT);
  2232. /* Un-mark it as ending, since we're going to reuse it. */
  2233. ap_conn->edge_has_sent_end = 0;
  2234. ap_conn->end_reason = 0;
  2235. if (tmpcirc)
  2236. circuit_detach_stream(tmpcirc,ap_conn);
  2237. ap_conn->_base.state = AP_CONN_STATE_CONTROLLER_WAIT;
  2238. }
  2239. if (circ && (circ->_base.state != CIRCUIT_STATE_OPEN)) {
  2240. connection_write_str_to_buf(
  2241. "551 Can't attach stream to non-open origin circuit\r\n",
  2242. conn);
  2243. return 0;
  2244. }
  2245. /* Is this a single hop circuit? */
  2246. if (circ && (circuit_get_cpath_len(circ)<2 || hop==1)) {
  2247. const node_t *node = NULL;
  2248. char *exit_digest;
  2249. if (circ->build_state &&
  2250. circ->build_state->chosen_exit &&
  2251. !tor_digest_is_zero(circ->build_state->chosen_exit->identity_digest)) {
  2252. exit_digest = circ->build_state->chosen_exit->identity_digest;
  2253. node = node_get_by_id(exit_digest);
  2254. }
  2255. /* Do both the client and relay allow one-hop exit circuits? */
  2256. if (!node ||
  2257. !node_allows_single_hop_exits(node) ||
  2258. !get_options()->AllowSingleHopCircuits) {
  2259. connection_write_str_to_buf(
  2260. "551 Can't attach stream to this one-hop circuit.\r\n", conn);
  2261. return 0;
  2262. }
  2263. ap_conn->chosen_exit_name = tor_strdup(hex_str(exit_digest, DIGEST_LEN));
  2264. }
  2265. if (circ && hop>0) {
  2266. /* find this hop in the circuit, and set cpath */
  2267. cpath = circuit_get_cpath_hop(circ, hop);
  2268. if (!cpath) {
  2269. connection_printf_to_buf(conn,
  2270. "551 Circuit doesn't have %d hops.\r\n", hop);
  2271. return 0;
  2272. }
  2273. }
  2274. if (connection_ap_handshake_rewrite_and_attach(ap_conn, circ, cpath) < 0) {
  2275. connection_write_str_to_buf("551 Unable to attach stream\r\n", conn);
  2276. return 0;
  2277. }
  2278. send_control_done(conn);
  2279. return 0;
  2280. }
  2281. /** Called when we get a POSTDESCRIPTOR message. Try to learn the provided
  2282. * descriptor, and report success or failure. */
  2283. static int
  2284. handle_control_postdescriptor(control_connection_t *conn, uint32_t len,
  2285. const char *body)
  2286. {
  2287. char *desc;
  2288. const char *msg=NULL;
  2289. uint8_t purpose = ROUTER_PURPOSE_GENERAL;
  2290. int cache = 0; /* eventually, we may switch this to 1 */
  2291. char *cp = memchr(body, '\n', len);
  2292. smartlist_t *args = smartlist_create();
  2293. tor_assert(cp);
  2294. *cp++ = '\0';
  2295. smartlist_split_string(args, body, " ",
  2296. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2297. SMARTLIST_FOREACH(args, char *, option,
  2298. {
  2299. if (!strcasecmpstart(option, "purpose=")) {
  2300. option += strlen("purpose=");
  2301. purpose = router_purpose_from_string(option);
  2302. if (purpose == ROUTER_PURPOSE_UNKNOWN) {
  2303. connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n",
  2304. option);
  2305. goto done;
  2306. }
  2307. } else if (!strcasecmpstart(option, "cache=")) {
  2308. option += strlen("cache=");
  2309. if (!strcasecmp(option, "no"))
  2310. cache = 0;
  2311. else if (!strcasecmp(option, "yes"))
  2312. cache = 1;
  2313. else {
  2314. connection_printf_to_buf(conn, "552 Unknown cache request \"%s\"\r\n",
  2315. option);
  2316. goto done;
  2317. }
  2318. } else { /* unrecognized argument? */
  2319. connection_printf_to_buf(conn,
  2320. "512 Unexpected argument \"%s\" to postdescriptor\r\n", option);
  2321. goto done;
  2322. }
  2323. });
  2324. read_escaped_data(cp, len-(cp-body), &desc);
  2325. switch (router_load_single_router(desc, purpose, cache, &msg)) {
  2326. case -1:
  2327. if (!msg) msg = "Could not parse descriptor";
  2328. connection_printf_to_buf(conn, "554 %s\r\n", msg);
  2329. break;
  2330. case 0:
  2331. if (!msg) msg = "Descriptor not added";
  2332. connection_printf_to_buf(conn, "251 %s\r\n",msg);
  2333. break;
  2334. case 1:
  2335. send_control_done(conn);
  2336. break;
  2337. }
  2338. tor_free(desc);
  2339. done:
  2340. SMARTLIST_FOREACH(args, char *, arg, tor_free(arg));
  2341. smartlist_free(args);
  2342. return 0;
  2343. }
  2344. /** Called when we receive a REDIRECTSTERAM command. Try to change the target
  2345. * address of the named AP stream, and report success or failure. */
  2346. static int
  2347. handle_control_redirectstream(control_connection_t *conn, uint32_t len,
  2348. const char *body)
  2349. {
  2350. edge_connection_t *ap_conn = NULL;
  2351. char *new_addr = NULL;
  2352. uint16_t new_port = 0;
  2353. smartlist_t *args;
  2354. (void) len;
  2355. args = getargs_helper("REDIRECTSTREAM", conn, body, 2, -1);
  2356. if (!args)
  2357. return 0;
  2358. if (!(ap_conn = get_stream(smartlist_get(args, 0)))
  2359. || !ap_conn->socks_request) {
  2360. connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
  2361. (char*)smartlist_get(args, 0));
  2362. } else {
  2363. int ok = 1;
  2364. if (smartlist_len(args) > 2) { /* they included a port too */
  2365. new_port = (uint16_t) tor_parse_ulong(smartlist_get(args, 2),
  2366. 10, 1, 65535, &ok, NULL);
  2367. }
  2368. if (!ok) {
  2369. connection_printf_to_buf(conn, "512 Cannot parse port \"%s\"\r\n",
  2370. (char*)smartlist_get(args, 2));
  2371. } else {
  2372. new_addr = tor_strdup(smartlist_get(args, 1));
  2373. }
  2374. }
  2375. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2376. smartlist_free(args);
  2377. if (!new_addr)
  2378. return 0;
  2379. strlcpy(ap_conn->socks_request->address, new_addr,
  2380. sizeof(ap_conn->socks_request->address));
  2381. if (new_port)
  2382. ap_conn->socks_request->port = new_port;
  2383. tor_free(new_addr);
  2384. send_control_done(conn);
  2385. return 0;
  2386. }
  2387. /** Called when we get a CLOSESTREAM command; try to close the named stream
  2388. * and report success or failure. */
  2389. static int
  2390. handle_control_closestream(control_connection_t *conn, uint32_t len,
  2391. const char *body)
  2392. {
  2393. edge_connection_t *ap_conn=NULL;
  2394. uint8_t reason=0;
  2395. smartlist_t *args;
  2396. int ok;
  2397. (void) len;
  2398. args = getargs_helper("CLOSESTREAM", conn, body, 2, -1);
  2399. if (!args)
  2400. return 0;
  2401. else if (!(ap_conn = get_stream(smartlist_get(args, 0))))
  2402. connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
  2403. (char*)smartlist_get(args, 0));
  2404. else {
  2405. reason = (uint8_t) tor_parse_ulong(smartlist_get(args,1), 10, 0, 255,
  2406. &ok, NULL);
  2407. if (!ok) {
  2408. connection_printf_to_buf(conn, "552 Unrecognized reason \"%s\"\r\n",
  2409. (char*)smartlist_get(args, 1));
  2410. ap_conn = NULL;
  2411. }
  2412. }
  2413. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2414. smartlist_free(args);
  2415. if (!ap_conn)
  2416. return 0;
  2417. connection_mark_unattached_ap(ap_conn, reason);
  2418. send_control_done(conn);
  2419. return 0;
  2420. }
  2421. /** Called when we get a CLOSECIRCUIT command; try to close the named circuit
  2422. * and report success or failure. */
  2423. static int
  2424. handle_control_closecircuit(control_connection_t *conn, uint32_t len,
  2425. const char *body)
  2426. {
  2427. origin_circuit_t *circ = NULL;
  2428. int safe = 0;
  2429. smartlist_t *args;
  2430. (void) len;
  2431. args = getargs_helper("CLOSECIRCUIT", conn, body, 1, -1);
  2432. if (!args)
  2433. return 0;
  2434. if (!(circ=get_circ(smartlist_get(args, 0))))
  2435. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  2436. (char*)smartlist_get(args, 0));
  2437. else {
  2438. int i;
  2439. for (i=1; i < smartlist_len(args); ++i) {
  2440. if (!strcasecmp(smartlist_get(args, i), "IfUnused"))
  2441. safe = 1;
  2442. else
  2443. log_info(LD_CONTROL, "Skipping unknown option %s",
  2444. (char*)smartlist_get(args,i));
  2445. }
  2446. }
  2447. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2448. smartlist_free(args);
  2449. if (!circ)
  2450. return 0;
  2451. if (!safe || !circ->p_streams) {
  2452. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_REQUESTED);
  2453. }
  2454. send_control_done(conn);
  2455. return 0;
  2456. }
  2457. /** Called when we get a RESOLVE command: start trying to resolve
  2458. * the listed addresses. */
  2459. static int
  2460. handle_control_resolve(control_connection_t *conn, uint32_t len,
  2461. const char *body)
  2462. {
  2463. smartlist_t *args, *failed;
  2464. int is_reverse = 0;
  2465. (void) len; /* body is nul-terminated; it's safe to ignore the length */
  2466. if (!(conn->event_mask & ((uint32_t)1L<<EVENT_ADDRMAP))) {
  2467. log_warn(LD_CONTROL, "Controller asked us to resolve an address, but "
  2468. "isn't listening for ADDRMAP events. It probably won't see "
  2469. "the answer.");
  2470. }
  2471. args = smartlist_create();
  2472. smartlist_split_string(args, body, " ",
  2473. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2474. {
  2475. const char *modearg = find_element_starting_with(args, 0, "mode=");
  2476. if (modearg && !strcasecmp(modearg, "mode=reverse"))
  2477. is_reverse = 1;
  2478. }
  2479. failed = smartlist_create();
  2480. SMARTLIST_FOREACH(args, const char *, arg, {
  2481. if (!is_keyval_pair(arg)) {
  2482. if (dnsserv_launch_request(arg, is_reverse)<0)
  2483. smartlist_add(failed, (char*)arg);
  2484. }
  2485. });
  2486. send_control_done(conn);
  2487. SMARTLIST_FOREACH(failed, const char *, arg, {
  2488. control_event_address_mapped(arg, arg, time(NULL),
  2489. "Unable to launch resolve request");
  2490. });
  2491. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2492. smartlist_free(args);
  2493. smartlist_free(failed);
  2494. return 0;
  2495. }
  2496. /** Called when we get a PROTOCOLINFO command: send back a reply. */
  2497. static int
  2498. handle_control_protocolinfo(control_connection_t *conn, uint32_t len,
  2499. const char *body)
  2500. {
  2501. const char *bad_arg = NULL;
  2502. smartlist_t *args;
  2503. (void)len;
  2504. conn->have_sent_protocolinfo = 1;
  2505. args = smartlist_create();
  2506. smartlist_split_string(args, body, " ",
  2507. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2508. SMARTLIST_FOREACH(args, const char *, arg, {
  2509. int ok;
  2510. tor_parse_long(arg, 10, 0, LONG_MAX, &ok, NULL);
  2511. if (!ok) {
  2512. bad_arg = arg;
  2513. break;
  2514. }
  2515. });
  2516. if (bad_arg) {
  2517. connection_printf_to_buf(conn, "513 No such version %s\r\n",
  2518. escaped(bad_arg));
  2519. /* Don't tolerate bad arguments when not authenticated. */
  2520. if (!STATE_IS_OPEN(TO_CONN(conn)->state))
  2521. connection_mark_for_close(TO_CONN(conn));
  2522. goto done;
  2523. } else {
  2524. or_options_t *options = get_options();
  2525. int cookies = options->CookieAuthentication;
  2526. char *cfile = get_cookie_file();
  2527. char *esc_cfile = esc_for_log(cfile);
  2528. char *methods;
  2529. {
  2530. int passwd = (options->HashedControlPassword != NULL ||
  2531. options->HashedControlSessionPassword != NULL);
  2532. smartlist_t *mlist = smartlist_create();
  2533. if (cookies)
  2534. smartlist_add(mlist, (char*)"COOKIE");
  2535. if (passwd)
  2536. smartlist_add(mlist, (char*)"HASHEDPASSWORD");
  2537. if (!cookies && !passwd)
  2538. smartlist_add(mlist, (char*)"NULL");
  2539. methods = smartlist_join_strings(mlist, ",", 0, NULL);
  2540. smartlist_free(mlist);
  2541. }
  2542. connection_printf_to_buf(conn,
  2543. "250-PROTOCOLINFO 1\r\n"
  2544. "250-AUTH METHODS=%s%s%s\r\n"
  2545. "250-VERSION Tor=%s\r\n"
  2546. "250 OK\r\n",
  2547. methods,
  2548. cookies?" COOKIEFILE=":"",
  2549. cookies?esc_cfile:"",
  2550. escaped(VERSION));
  2551. tor_free(methods);
  2552. tor_free(cfile);
  2553. tor_free(esc_cfile);
  2554. }
  2555. done:
  2556. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2557. smartlist_free(args);
  2558. return 0;
  2559. }
  2560. /** Called when we get a USEFEATURE command: parse the feature list, and
  2561. * set up the control_connection's options properly. */
  2562. static int
  2563. handle_control_usefeature(control_connection_t *conn,
  2564. uint32_t len,
  2565. const char *body)
  2566. {
  2567. smartlist_t *args;
  2568. int bad = 0;
  2569. (void) len; /* body is nul-terminated; it's safe to ignore the length */
  2570. args = smartlist_create();
  2571. smartlist_split_string(args, body, " ",
  2572. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2573. SMARTLIST_FOREACH(args, const char *, arg, {
  2574. if (!strcasecmp(arg, "VERBOSE_NAMES"))
  2575. ;
  2576. else if (!strcasecmp(arg, "EXTENDED_EVENTS"))
  2577. ;
  2578. else {
  2579. connection_printf_to_buf(conn, "552 Unrecognized feature \"%s\"\r\n",
  2580. arg);
  2581. bad = 1;
  2582. break;
  2583. }
  2584. });
  2585. if (!bad) {
  2586. send_control_done(conn);
  2587. }
  2588. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2589. smartlist_free(args);
  2590. return 0;
  2591. }
  2592. /** Called when <b>conn</b> has no more bytes left on its outbuf. */
  2593. int
  2594. connection_control_finished_flushing(control_connection_t *conn)
  2595. {
  2596. tor_assert(conn);
  2597. return 0;
  2598. }
  2599. /** Called when <b>conn</b> has gotten its socket closed. */
  2600. int
  2601. connection_control_reached_eof(control_connection_t *conn)
  2602. {
  2603. tor_assert(conn);
  2604. log_info(LD_CONTROL,"Control connection reached EOF. Closing.");
  2605. connection_mark_for_close(TO_CONN(conn));
  2606. return 0;
  2607. }
  2608. /** Return true iff <b>cmd</b> is allowable (or at least forgivable) at this
  2609. * stage of the protocol. */
  2610. static int
  2611. is_valid_initial_command(control_connection_t *conn, const char *cmd)
  2612. {
  2613. if (conn->_base.state == CONTROL_CONN_STATE_OPEN)
  2614. return 1;
  2615. if (!strcasecmp(cmd, "PROTOCOLINFO"))
  2616. return !conn->have_sent_protocolinfo;
  2617. if (!strcasecmp(cmd, "AUTHENTICATE") ||
  2618. !strcasecmp(cmd, "QUIT"))
  2619. return 1;
  2620. return 0;
  2621. }
  2622. /** Do not accept any control command of more than 1MB in length. Anything
  2623. * that needs to be anywhere near this long probably means that one of our
  2624. * interfaces is broken. */
  2625. #define MAX_COMMAND_LINE_LENGTH (1024*1024)
  2626. static int
  2627. peek_connection_has_control0_command(connection_t *conn)
  2628. {
  2629. IF_HAS_BUFFEREVENT(conn, {
  2630. struct evbuffer *input = bufferevent_get_input(conn->bufev);
  2631. return peek_evbuffer_has_control0_command(input);
  2632. }) ELSE_IF_NO_BUFFEREVENT {
  2633. return peek_buf_has_control0_command(conn->inbuf);
  2634. }
  2635. }
  2636. /** Called when data has arrived on a v1 control connection: Try to fetch
  2637. * commands from conn->inbuf, and execute them.
  2638. */
  2639. int
  2640. connection_control_process_inbuf(control_connection_t *conn)
  2641. {
  2642. size_t data_len;
  2643. uint32_t cmd_data_len;
  2644. int cmd_len;
  2645. char *args;
  2646. tor_assert(conn);
  2647. tor_assert(conn->_base.state == CONTROL_CONN_STATE_OPEN ||
  2648. conn->_base.state == CONTROL_CONN_STATE_NEEDAUTH);
  2649. if (!conn->incoming_cmd) {
  2650. conn->incoming_cmd = tor_malloc(1024);
  2651. conn->incoming_cmd_len = 1024;
  2652. conn->incoming_cmd_cur_len = 0;
  2653. }
  2654. if (conn->_base.state == CONTROL_CONN_STATE_NEEDAUTH &&
  2655. peek_connection_has_control0_command(TO_CONN(conn))) {
  2656. /* Detect v0 commands and send a "no more v0" message. */
  2657. size_t body_len;
  2658. char buf[128];
  2659. set_uint16(buf+2, htons(0x0000)); /* type == error */
  2660. set_uint16(buf+4, htons(0x0001)); /* code == internal error */
  2661. strlcpy(buf+6, "The v0 control protocol is not supported by Tor 0.1.2.17 "
  2662. "and later; upgrade your controller.",
  2663. sizeof(buf)-6);
  2664. body_len = 2+strlen(buf+6)+2; /* code, msg, nul. */
  2665. set_uint16(buf+0, htons(body_len));
  2666. connection_write_to_buf(buf, 4+body_len, TO_CONN(conn));
  2667. connection_mark_and_flush(TO_CONN(conn));
  2668. return 0;
  2669. }
  2670. again:
  2671. while (1) {
  2672. size_t last_idx;
  2673. int r;
  2674. /* First, fetch a line. */
  2675. do {
  2676. data_len = conn->incoming_cmd_len - conn->incoming_cmd_cur_len;
  2677. r = connection_fetch_from_buf_line(TO_CONN(conn),
  2678. conn->incoming_cmd+conn->incoming_cmd_cur_len,
  2679. &data_len);
  2680. if (r == 0)
  2681. /* Line not all here yet. Wait. */
  2682. return 0;
  2683. else if (r == -1) {
  2684. if (data_len + conn->incoming_cmd_cur_len > MAX_COMMAND_LINE_LENGTH) {
  2685. connection_write_str_to_buf("500 Line too long.\r\n", conn);
  2686. connection_stop_reading(TO_CONN(conn));
  2687. connection_mark_and_flush(TO_CONN(conn));
  2688. }
  2689. while (conn->incoming_cmd_len < data_len+conn->incoming_cmd_cur_len)
  2690. conn->incoming_cmd_len *= 2;
  2691. conn->incoming_cmd = tor_realloc(conn->incoming_cmd,
  2692. conn->incoming_cmd_len);
  2693. }
  2694. } while (r != 1);
  2695. tor_assert(data_len);
  2696. last_idx = conn->incoming_cmd_cur_len;
  2697. conn->incoming_cmd_cur_len += (int)data_len;
  2698. /* We have appended a line to incoming_cmd. Is the command done? */
  2699. if (last_idx == 0 && *conn->incoming_cmd != '+')
  2700. /* One line command, didn't start with '+'. */
  2701. break;
  2702. /* XXXX this code duplication is kind of dumb. */
  2703. if (last_idx+3 == conn->incoming_cmd_cur_len &&
  2704. !memcmp(conn->incoming_cmd + last_idx, ".\r\n", 3)) {
  2705. /* Just appended ".\r\n"; we're done. Remove it. */
  2706. conn->incoming_cmd[last_idx] = '\0';
  2707. conn->incoming_cmd_cur_len -= 3;
  2708. break;
  2709. } else if (last_idx+2 == conn->incoming_cmd_cur_len &&
  2710. !memcmp(conn->incoming_cmd + last_idx, ".\n", 2)) {
  2711. /* Just appended ".\n"; we're done. Remove it. */
  2712. conn->incoming_cmd[last_idx] = '\0';
  2713. conn->incoming_cmd_cur_len -= 2;
  2714. break;
  2715. }
  2716. /* Otherwise, read another line. */
  2717. }
  2718. data_len = conn->incoming_cmd_cur_len;
  2719. /* Okay, we now have a command sitting on conn->incoming_cmd. See if we
  2720. * recognize it.
  2721. */
  2722. cmd_len = 0;
  2723. while ((size_t)cmd_len < data_len
  2724. && !TOR_ISSPACE(conn->incoming_cmd[cmd_len]))
  2725. ++cmd_len;
  2726. conn->incoming_cmd[cmd_len]='\0';
  2727. args = conn->incoming_cmd+cmd_len+1;
  2728. tor_assert(data_len>(size_t)cmd_len);
  2729. data_len -= (cmd_len+1); /* skip the command and NUL we added after it */
  2730. while (*args == ' ' || *args == '\t') {
  2731. ++args;
  2732. --data_len;
  2733. }
  2734. /* If the connection is already closing, ignore further commands */
  2735. if (TO_CONN(conn)->marked_for_close) {
  2736. return 0;
  2737. }
  2738. /* Otherwise, Quit is always valid. */
  2739. if (!strcasecmp(conn->incoming_cmd, "QUIT")) {
  2740. connection_write_str_to_buf("250 closing connection\r\n", conn);
  2741. connection_mark_and_flush(TO_CONN(conn));
  2742. return 0;
  2743. }
  2744. if (conn->_base.state == CONTROL_CONN_STATE_NEEDAUTH &&
  2745. !is_valid_initial_command(conn, conn->incoming_cmd)) {
  2746. connection_write_str_to_buf("514 Authentication required.\r\n", conn);
  2747. connection_mark_for_close(TO_CONN(conn));
  2748. return 0;
  2749. }
  2750. if (data_len >= UINT32_MAX) {
  2751. connection_write_str_to_buf("500 A 4GB command? Nice try.\r\n", conn);
  2752. connection_mark_for_close(TO_CONN(conn));
  2753. return 0;
  2754. }
  2755. cmd_data_len = (uint32_t)data_len;
  2756. if (!strcasecmp(conn->incoming_cmd, "SETCONF")) {
  2757. if (handle_control_setconf(conn, cmd_data_len, args))
  2758. return -1;
  2759. } else if (!strcasecmp(conn->incoming_cmd, "RESETCONF")) {
  2760. if (handle_control_resetconf(conn, cmd_data_len, args))
  2761. return -1;
  2762. } else if (!strcasecmp(conn->incoming_cmd, "GETCONF")) {
  2763. if (handle_control_getconf(conn, cmd_data_len, args))
  2764. return -1;
  2765. } else if (!strcasecmp(conn->incoming_cmd, "+LOADCONF")) {
  2766. if (handle_control_loadconf(conn, cmd_data_len, args))
  2767. return -1;
  2768. } else if (!strcasecmp(conn->incoming_cmd, "SETEVENTS")) {
  2769. if (handle_control_setevents(conn, cmd_data_len, args))
  2770. return -1;
  2771. } else if (!strcasecmp(conn->incoming_cmd, "AUTHENTICATE")) {
  2772. if (handle_control_authenticate(conn, cmd_data_len, args))
  2773. return -1;
  2774. } else if (!strcasecmp(conn->incoming_cmd, "SAVECONF")) {
  2775. if (handle_control_saveconf(conn, cmd_data_len, args))
  2776. return -1;
  2777. } else if (!strcasecmp(conn->incoming_cmd, "SIGNAL")) {
  2778. if (handle_control_signal(conn, cmd_data_len, args))
  2779. return -1;
  2780. } else if (!strcasecmp(conn->incoming_cmd, "MAPADDRESS")) {
  2781. if (handle_control_mapaddress(conn, cmd_data_len, args))
  2782. return -1;
  2783. } else if (!strcasecmp(conn->incoming_cmd, "GETINFO")) {
  2784. if (handle_control_getinfo(conn, cmd_data_len, args))
  2785. return -1;
  2786. } else if (!strcasecmp(conn->incoming_cmd, "EXTENDCIRCUIT")) {
  2787. if (handle_control_extendcircuit(conn, cmd_data_len, args))
  2788. return -1;
  2789. } else if (!strcasecmp(conn->incoming_cmd, "SETCIRCUITPURPOSE")) {
  2790. if (handle_control_setcircuitpurpose(conn, cmd_data_len, args))
  2791. return -1;
  2792. } else if (!strcasecmp(conn->incoming_cmd, "SETROUTERPURPOSE")) {
  2793. connection_write_str_to_buf("511 SETROUTERPURPOSE is obsolete.\r\n", conn);
  2794. } else if (!strcasecmp(conn->incoming_cmd, "ATTACHSTREAM")) {
  2795. if (handle_control_attachstream(conn, cmd_data_len, args))
  2796. return -1;
  2797. } else if (!strcasecmp(conn->incoming_cmd, "+POSTDESCRIPTOR")) {
  2798. if (handle_control_postdescriptor(conn, cmd_data_len, args))
  2799. return -1;
  2800. } else if (!strcasecmp(conn->incoming_cmd, "REDIRECTSTREAM")) {
  2801. if (handle_control_redirectstream(conn, cmd_data_len, args))
  2802. return -1;
  2803. } else if (!strcasecmp(conn->incoming_cmd, "CLOSESTREAM")) {
  2804. if (handle_control_closestream(conn, cmd_data_len, args))
  2805. return -1;
  2806. } else if (!strcasecmp(conn->incoming_cmd, "CLOSECIRCUIT")) {
  2807. if (handle_control_closecircuit(conn, cmd_data_len, args))
  2808. return -1;
  2809. } else if (!strcasecmp(conn->incoming_cmd, "USEFEATURE")) {
  2810. if (handle_control_usefeature(conn, cmd_data_len, args))
  2811. return -1;
  2812. } else if (!strcasecmp(conn->incoming_cmd, "RESOLVE")) {
  2813. if (handle_control_resolve(conn, cmd_data_len, args))
  2814. return -1;
  2815. } else if (!strcasecmp(conn->incoming_cmd, "PROTOCOLINFO")) {
  2816. if (handle_control_protocolinfo(conn, cmd_data_len, args))
  2817. return -1;
  2818. } else {
  2819. connection_printf_to_buf(conn, "510 Unrecognized command \"%s\"\r\n",
  2820. conn->incoming_cmd);
  2821. }
  2822. conn->incoming_cmd_cur_len = 0;
  2823. goto again;
  2824. }
  2825. /** Something has happened to circuit <b>circ</b>: tell any interested
  2826. * control connections. */
  2827. int
  2828. control_event_circuit_status(origin_circuit_t *circ, circuit_status_event_t tp,
  2829. int reason_code)
  2830. {
  2831. const char *status;
  2832. char extended_buf[96];
  2833. int providing_reason=0;
  2834. if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS))
  2835. return 0;
  2836. tor_assert(circ);
  2837. switch (tp)
  2838. {
  2839. case CIRC_EVENT_LAUNCHED: status = "LAUNCHED"; break;
  2840. case CIRC_EVENT_BUILT: status = "BUILT"; break;
  2841. case CIRC_EVENT_EXTENDED: status = "EXTENDED"; break;
  2842. case CIRC_EVENT_FAILED: status = "FAILED"; break;
  2843. case CIRC_EVENT_CLOSED: status = "CLOSED"; break;
  2844. default:
  2845. log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
  2846. return 0;
  2847. }
  2848. tor_snprintf(extended_buf, sizeof(extended_buf), "PURPOSE=%s",
  2849. circuit_purpose_to_controller_string(circ->_base.purpose));
  2850. if (tp == CIRC_EVENT_FAILED || tp == CIRC_EVENT_CLOSED) {
  2851. const char *reason_str = circuit_end_reason_to_control_string(reason_code);
  2852. char *reason = NULL;
  2853. size_t n=strlen(extended_buf);
  2854. providing_reason=1;
  2855. if (!reason_str) {
  2856. reason = tor_malloc(16);
  2857. tor_snprintf(reason, 16, "UNKNOWN_%d", reason_code);
  2858. reason_str = reason;
  2859. }
  2860. if (reason_code > 0 && reason_code & END_CIRC_REASON_FLAG_REMOTE) {
  2861. tor_snprintf(extended_buf+n, sizeof(extended_buf)-n,
  2862. " REASON=DESTROYED REMOTE_REASON=%s", reason_str);
  2863. } else {
  2864. tor_snprintf(extended_buf+n, sizeof(extended_buf)-n,
  2865. " REASON=%s", reason_str);
  2866. }
  2867. tor_free(reason);
  2868. }
  2869. {
  2870. char *vpath = circuit_list_path_for_controller(circ);
  2871. const char *sp = strlen(vpath) ? " " : "";
  2872. send_control_event(EVENT_CIRCUIT_STATUS, ALL_FORMATS,
  2873. "650 CIRC %lu %s%s%s %s\r\n",
  2874. (unsigned long)circ->global_identifier,
  2875. status, sp, vpath, extended_buf);
  2876. tor_free(vpath);
  2877. }
  2878. return 0;
  2879. }
  2880. /** Given an AP connection <b>conn</b> and a <b>len</b>-character buffer
  2881. * <b>buf</b>, determine the address:port combination requested on
  2882. * <b>conn</b>, and write it to <b>buf</b>. Return 0 on success, -1 on
  2883. * failure. */
  2884. static int
  2885. write_stream_target_to_buf(edge_connection_t *conn, char *buf, size_t len)
  2886. {
  2887. char buf2[256];
  2888. if (conn->chosen_exit_name)
  2889. if (tor_snprintf(buf2, sizeof(buf2), ".%s.exit", conn->chosen_exit_name)<0)
  2890. return -1;
  2891. if (!conn->socks_request)
  2892. return -1;
  2893. if (tor_snprintf(buf, len, "%s%s%s:%d",
  2894. conn->socks_request->address,
  2895. conn->chosen_exit_name ? buf2 : "",
  2896. !conn->chosen_exit_name &&
  2897. connection_edge_is_rendezvous_stream(conn) ? ".onion" : "",
  2898. conn->socks_request->port)<0)
  2899. return -1;
  2900. return 0;
  2901. }
  2902. /** Something has happened to the stream associated with AP connection
  2903. * <b>conn</b>: tell any interested control connections. */
  2904. int
  2905. control_event_stream_status(edge_connection_t *conn, stream_status_event_t tp,
  2906. int reason_code)
  2907. {
  2908. char reason_buf[64];
  2909. char addrport_buf[64];
  2910. const char *status;
  2911. circuit_t *circ;
  2912. origin_circuit_t *origin_circ = NULL;
  2913. char buf[256];
  2914. const char *purpose = "";
  2915. tor_assert(conn->socks_request);
  2916. if (!EVENT_IS_INTERESTING(EVENT_STREAM_STATUS))
  2917. return 0;
  2918. if (tp == STREAM_EVENT_CLOSED &&
  2919. (reason_code & END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED))
  2920. return 0;
  2921. write_stream_target_to_buf(conn, buf, sizeof(buf));
  2922. reason_buf[0] = '\0';
  2923. switch (tp)
  2924. {
  2925. case STREAM_EVENT_SENT_CONNECT: status = "SENTCONNECT"; break;
  2926. case STREAM_EVENT_SENT_RESOLVE: status = "SENTRESOLVE"; break;
  2927. case STREAM_EVENT_SUCCEEDED: status = "SUCCEEDED"; break;
  2928. case STREAM_EVENT_FAILED: status = "FAILED"; break;
  2929. case STREAM_EVENT_CLOSED: status = "CLOSED"; break;
  2930. case STREAM_EVENT_NEW: status = "NEW"; break;
  2931. case STREAM_EVENT_NEW_RESOLVE: status = "NEWRESOLVE"; break;
  2932. case STREAM_EVENT_FAILED_RETRIABLE: status = "DETACHED"; break;
  2933. case STREAM_EVENT_REMAP: status = "REMAP"; break;
  2934. default:
  2935. log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
  2936. return 0;
  2937. }
  2938. if (reason_code && (tp == STREAM_EVENT_FAILED ||
  2939. tp == STREAM_EVENT_CLOSED ||
  2940. tp == STREAM_EVENT_FAILED_RETRIABLE)) {
  2941. const char *reason_str = stream_end_reason_to_control_string(reason_code);
  2942. char *r = NULL;
  2943. if (!reason_str) {
  2944. r = tor_malloc(16);
  2945. tor_snprintf(r, 16, " UNKNOWN_%d", reason_code);
  2946. reason_str = r;
  2947. }
  2948. if (reason_code & END_STREAM_REASON_FLAG_REMOTE)
  2949. tor_snprintf(reason_buf, sizeof(reason_buf),
  2950. " REASON=END REMOTE_REASON=%s", reason_str);
  2951. else
  2952. tor_snprintf(reason_buf, sizeof(reason_buf),
  2953. " REASON=%s", reason_str);
  2954. tor_free(r);
  2955. } else if (reason_code && tp == STREAM_EVENT_REMAP) {
  2956. switch (reason_code) {
  2957. case REMAP_STREAM_SOURCE_CACHE:
  2958. strlcpy(reason_buf, " SOURCE=CACHE", sizeof(reason_buf));
  2959. break;
  2960. case REMAP_STREAM_SOURCE_EXIT:
  2961. strlcpy(reason_buf, " SOURCE=EXIT", sizeof(reason_buf));
  2962. break;
  2963. default:
  2964. tor_snprintf(reason_buf, sizeof(reason_buf), " REASON=UNKNOWN_%d",
  2965. reason_code);
  2966. /* XXX do we want SOURCE=UNKNOWN_%d above instead? -RD */
  2967. break;
  2968. }
  2969. }
  2970. if (tp == STREAM_EVENT_NEW) {
  2971. tor_snprintf(addrport_buf,sizeof(addrport_buf), " SOURCE_ADDR=%s:%d",
  2972. TO_CONN(conn)->address, TO_CONN(conn)->port );
  2973. } else {
  2974. addrport_buf[0] = '\0';
  2975. }
  2976. if (tp == STREAM_EVENT_NEW_RESOLVE) {
  2977. purpose = " PURPOSE=DNS_REQUEST";
  2978. } else if (tp == STREAM_EVENT_NEW) {
  2979. if (conn->is_dns_request ||
  2980. (conn->socks_request &&
  2981. SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command)))
  2982. purpose = " PURPOSE=DNS_REQUEST";
  2983. else if (conn->use_begindir) {
  2984. connection_t *linked = TO_CONN(conn)->linked_conn;
  2985. int linked_dir_purpose = -1;
  2986. if (linked && linked->type == CONN_TYPE_DIR)
  2987. linked_dir_purpose = linked->purpose;
  2988. if (DIR_PURPOSE_IS_UPLOAD(linked_dir_purpose))
  2989. purpose = " PURPOSE=DIR_UPLOAD";
  2990. else
  2991. purpose = " PURPOSE=DIR_FETCH";
  2992. } else
  2993. purpose = " PURPOSE=USER";
  2994. }
  2995. circ = circuit_get_by_edge_conn(conn);
  2996. if (circ && CIRCUIT_IS_ORIGIN(circ))
  2997. origin_circ = TO_ORIGIN_CIRCUIT(circ);
  2998. send_control_event(EVENT_STREAM_STATUS, ALL_FORMATS,
  2999. "650 STREAM "U64_FORMAT" %s %lu %s%s%s%s\r\n",
  3000. U64_PRINTF_ARG(conn->_base.global_identifier), status,
  3001. origin_circ?
  3002. (unsigned long)origin_circ->global_identifier : 0ul,
  3003. buf, reason_buf, addrport_buf, purpose);
  3004. /* XXX need to specify its intended exit, etc? */
  3005. return 0;
  3006. }
  3007. /** Figure out the best name for the target router of an OR connection
  3008. * <b>conn</b>, and write it into the <b>len</b>-character buffer
  3009. * <b>name</b>. */
  3010. static void
  3011. orconn_target_get_name(char *name, size_t len, or_connection_t *conn)
  3012. {
  3013. const node_t *node = node_get_by_id(conn->identity_digest);
  3014. if (node) {
  3015. tor_assert(len > MAX_VERBOSE_NICKNAME_LEN);
  3016. node_get_verbose_nickname(node, name);
  3017. } else if (! tor_digest_is_zero(conn->identity_digest)) {
  3018. name[0] = '$';
  3019. base16_encode(name+1, len-1, conn->identity_digest,
  3020. DIGEST_LEN);
  3021. } else {
  3022. tor_snprintf(name, len, "%s:%d",
  3023. conn->_base.address, conn->_base.port);
  3024. }
  3025. }
  3026. /** Called when the status of an OR connection <b>conn</b> changes: tell any
  3027. * interested control connections. <b>tp</b> is the new status for the
  3028. * connection. If <b>conn</b> has just closed or failed, then <b>reason</b>
  3029. * may be the reason why.
  3030. */
  3031. int
  3032. control_event_or_conn_status(or_connection_t *conn, or_conn_status_event_t tp,
  3033. int reason)
  3034. {
  3035. int ncircs = 0;
  3036. const char *status;
  3037. char name[128];
  3038. char ncircs_buf[32] = {0}; /* > 8 + log10(2^32)=10 + 2 */
  3039. if (!EVENT_IS_INTERESTING(EVENT_OR_CONN_STATUS))
  3040. return 0;
  3041. switch (tp)
  3042. {
  3043. case OR_CONN_EVENT_LAUNCHED: status = "LAUNCHED"; break;
  3044. case OR_CONN_EVENT_CONNECTED: status = "CONNECTED"; break;
  3045. case OR_CONN_EVENT_FAILED: status = "FAILED"; break;
  3046. case OR_CONN_EVENT_CLOSED: status = "CLOSED"; break;
  3047. case OR_CONN_EVENT_NEW: status = "NEW"; break;
  3048. default:
  3049. log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
  3050. return 0;
  3051. }
  3052. ncircs = circuit_count_pending_on_or_conn(conn);
  3053. ncircs += conn->n_circuits;
  3054. if (ncircs && (tp == OR_CONN_EVENT_FAILED || tp == OR_CONN_EVENT_CLOSED)) {
  3055. tor_snprintf(ncircs_buf, sizeof(ncircs_buf), "%sNCIRCS=%d",
  3056. reason ? " " : "", ncircs);
  3057. }
  3058. orconn_target_get_name(name, sizeof(name), conn);
  3059. send_control_event(EVENT_OR_CONN_STATUS, ALL_FORMATS,
  3060. "650 ORCONN %s %s %s%s%s\r\n",
  3061. name, status,
  3062. reason ? "REASON=" : "",
  3063. orconn_end_reason_to_control_string(reason),
  3064. ncircs_buf);
  3065. return 0;
  3066. }
  3067. /**
  3068. * Print out STREAM_BW event for a single conn
  3069. */
  3070. int
  3071. control_event_stream_bandwidth(edge_connection_t *edge_conn)
  3072. {
  3073. if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED)) {
  3074. if (!edge_conn->n_read && !edge_conn->n_written)
  3075. return 0;
  3076. send_control_event(EVENT_STREAM_BANDWIDTH_USED, ALL_FORMATS,
  3077. "650 STREAM_BW "U64_FORMAT" %lu %lu\r\n",
  3078. U64_PRINTF_ARG(edge_conn->_base.global_identifier),
  3079. (unsigned long)edge_conn->n_read,
  3080. (unsigned long)edge_conn->n_written);
  3081. edge_conn->n_written = edge_conn->n_read = 0;
  3082. }
  3083. return 0;
  3084. }
  3085. /** A second or more has elapsed: tell any interested control
  3086. * connections how much bandwidth streams have used. */
  3087. int
  3088. control_event_stream_bandwidth_used(void)
  3089. {
  3090. if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED)) {
  3091. smartlist_t *conns = get_connection_array();
  3092. edge_connection_t *edge_conn;
  3093. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn)
  3094. {
  3095. if (conn->type != CONN_TYPE_AP)
  3096. continue;
  3097. edge_conn = TO_EDGE_CONN(conn);
  3098. if (!edge_conn->n_read && !edge_conn->n_written)
  3099. continue;
  3100. send_control_event(EVENT_STREAM_BANDWIDTH_USED, ALL_FORMATS,
  3101. "650 STREAM_BW "U64_FORMAT" %lu %lu\r\n",
  3102. U64_PRINTF_ARG(edge_conn->_base.global_identifier),
  3103. (unsigned long)edge_conn->n_read,
  3104. (unsigned long)edge_conn->n_written);
  3105. edge_conn->n_written = edge_conn->n_read = 0;
  3106. }
  3107. SMARTLIST_FOREACH_END(conn);
  3108. }
  3109. return 0;
  3110. }
  3111. /** A second or more has elapsed: tell any interested control
  3112. * connections how much bandwidth we used. */
  3113. int
  3114. control_event_bandwidth_used(uint32_t n_read, uint32_t n_written)
  3115. {
  3116. if (EVENT_IS_INTERESTING(EVENT_BANDWIDTH_USED)) {
  3117. send_control_event(EVENT_BANDWIDTH_USED, ALL_FORMATS,
  3118. "650 BW %lu %lu\r\n",
  3119. (unsigned long)n_read,
  3120. (unsigned long)n_written);
  3121. }
  3122. return 0;
  3123. }
  3124. /** Called when we are sending a log message to the controllers: suspend
  3125. * sending further log messages to the controllers until we're done. Used by
  3126. * CONN_LOG_PROTECT. */
  3127. void
  3128. disable_control_logging(void)
  3129. {
  3130. ++disable_log_messages;
  3131. }
  3132. /** We're done sending a log message to the controllers: re-enable controller
  3133. * logging. Used by CONN_LOG_PROTECT. */
  3134. void
  3135. enable_control_logging(void)
  3136. {
  3137. if (--disable_log_messages < 0)
  3138. tor_assert(0);
  3139. }
  3140. /** We got a log message: tell any interested control connections. */
  3141. void
  3142. control_event_logmsg(int severity, uint32_t domain, const char *msg)
  3143. {
  3144. int event;
  3145. /* Don't even think of trying to add stuff to a buffer from a cpuworker
  3146. * thread. */
  3147. if (! in_main_thread())
  3148. return;
  3149. if (disable_log_messages)
  3150. return;
  3151. if (domain == LD_BUG && EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL) &&
  3152. severity <= LOG_NOTICE) {
  3153. char *esc = esc_for_log(msg);
  3154. ++disable_log_messages;
  3155. control_event_general_status(severity, "BUG REASON=\"%s\"", esc);
  3156. --disable_log_messages;
  3157. tor_free(esc);
  3158. }
  3159. event = log_severity_to_event(severity);
  3160. if (event >= 0 && EVENT_IS_INTERESTING(event)) {
  3161. char *b = NULL;
  3162. const char *s;
  3163. if (strchr(msg, '\n')) {
  3164. char *cp;
  3165. b = tor_strdup(msg);
  3166. for (cp = b; *cp; ++cp)
  3167. if (*cp == '\r' || *cp == '\n')
  3168. *cp = ' ';
  3169. }
  3170. switch (severity) {
  3171. case LOG_DEBUG: s = "DEBUG"; break;
  3172. case LOG_INFO: s = "INFO"; break;
  3173. case LOG_NOTICE: s = "NOTICE"; break;
  3174. case LOG_WARN: s = "WARN"; break;
  3175. case LOG_ERR: s = "ERR"; break;
  3176. default: s = "UnknownLogSeverity"; break;
  3177. }
  3178. ++disable_log_messages;
  3179. send_control_event(event, ALL_FORMATS, "650 %s %s\r\n", s, b?b:msg);
  3180. --disable_log_messages;
  3181. tor_free(b);
  3182. }
  3183. }
  3184. /** Called whenever we receive new router descriptors: tell any
  3185. * interested control connections. <b>routers</b> is a list of
  3186. * routerinfo_t's.
  3187. */
  3188. int
  3189. control_event_descriptors_changed(smartlist_t *routers)
  3190. {
  3191. char *msg;
  3192. if (!EVENT_IS_INTERESTING(EVENT_NEW_DESC))
  3193. return 0;
  3194. {
  3195. smartlist_t *names = smartlist_create();
  3196. char *ids;
  3197. size_t names_len;
  3198. SMARTLIST_FOREACH(routers, routerinfo_t *, ri, {
  3199. char *b = tor_malloc(MAX_VERBOSE_NICKNAME_LEN+1);
  3200. router_get_verbose_nickname(b, ri);
  3201. smartlist_add(names, b);
  3202. });
  3203. ids = smartlist_join_strings(names, " ", 0, &names_len);
  3204. names_len = strlen(ids)+32;
  3205. msg = tor_malloc(names_len);
  3206. tor_snprintf(msg, names_len, "650 NEWDESC %s\r\n", ids);
  3207. send_control_event_string(EVENT_NEW_DESC, ALL_FORMATS, msg);
  3208. tor_free(ids);
  3209. tor_free(msg);
  3210. SMARTLIST_FOREACH(names, char *, cp, tor_free(cp));
  3211. smartlist_free(names);
  3212. }
  3213. return 0;
  3214. }
  3215. /** Called when an address mapping on <b>from</b> from changes to <b>to</b>.
  3216. * <b>expires</b> values less than 3 are special; see connection_edge.c. If
  3217. * <b>error</b> is non-NULL, it is an error code describing the failure
  3218. * mode of the mapping.
  3219. */
  3220. int
  3221. control_event_address_mapped(const char *from, const char *to, time_t expires,
  3222. const char *error)
  3223. {
  3224. if (!EVENT_IS_INTERESTING(EVENT_ADDRMAP))
  3225. return 0;
  3226. if (expires < 3 || expires == TIME_MAX)
  3227. send_control_event(EVENT_ADDRMAP, ALL_FORMATS,
  3228. "650 ADDRMAP %s %s NEVER %s\r\n", from, to,
  3229. error?error:"");
  3230. else {
  3231. char buf[ISO_TIME_LEN+1];
  3232. char buf2[ISO_TIME_LEN+1];
  3233. format_local_iso_time(buf,expires);
  3234. format_iso_time(buf2,expires);
  3235. send_control_event(EVENT_ADDRMAP, ALL_FORMATS,
  3236. "650 ADDRMAP %s %s \"%s\""
  3237. " %s%sEXPIRES=\"%s\"\r\n",
  3238. from, to, buf,
  3239. error?error:"", error?" ":"",
  3240. buf2);
  3241. }
  3242. return 0;
  3243. }
  3244. /** The authoritative dirserver has received a new descriptor that
  3245. * has passed basic syntax checks and is properly self-signed.
  3246. *
  3247. * Notify any interested party of the new descriptor and what has
  3248. * been done with it, and also optionally give an explanation/reason. */
  3249. int
  3250. control_event_or_authdir_new_descriptor(const char *action,
  3251. const char *desc, size_t desclen,
  3252. const char *msg)
  3253. {
  3254. char firstline[1024];
  3255. char *buf;
  3256. size_t totallen;
  3257. char *esc = NULL;
  3258. size_t esclen;
  3259. if (!EVENT_IS_INTERESTING(EVENT_AUTHDIR_NEWDESCS))
  3260. return 0;
  3261. tor_snprintf(firstline, sizeof(firstline),
  3262. "650+AUTHDIR_NEWDESC=\r\n%s\r\n%s\r\n",
  3263. action,
  3264. msg ? msg : "");
  3265. /* Escape the server descriptor properly */
  3266. esclen = write_escaped_data(desc, desclen, &esc);
  3267. totallen = strlen(firstline) + esclen + 1;
  3268. buf = tor_malloc(totallen);
  3269. strlcpy(buf, firstline, totallen);
  3270. strlcpy(buf+strlen(firstline), esc, totallen);
  3271. send_control_event_string(EVENT_AUTHDIR_NEWDESCS, ALL_FORMATS,
  3272. buf);
  3273. send_control_event_string(EVENT_AUTHDIR_NEWDESCS, ALL_FORMATS,
  3274. "650 OK\r\n");
  3275. tor_free(esc);
  3276. tor_free(buf);
  3277. return 0;
  3278. }
  3279. /** Helper function for NS-style events. Constructs and sends an event
  3280. * of type <b>event</b> with string <b>event_string</b> out of the set of
  3281. * networkstatuses <b>statuses</b>. Currently it is used for NS events
  3282. * and NEWCONSENSUS events. */
  3283. static int
  3284. control_event_networkstatus_changed_helper(smartlist_t *statuses,
  3285. uint16_t event,
  3286. const char *event_string)
  3287. {
  3288. smartlist_t *strs;
  3289. char *s, *esc = NULL;
  3290. if (!EVENT_IS_INTERESTING(event) || !smartlist_len(statuses))
  3291. return 0;
  3292. strs = smartlist_create();
  3293. smartlist_add(strs, tor_strdup("650+"));
  3294. smartlist_add(strs, tor_strdup(event_string));
  3295. smartlist_add(strs, tor_strdup("\r\n"));
  3296. SMARTLIST_FOREACH(statuses, const routerstatus_t *, rs,
  3297. {
  3298. s = networkstatus_getinfo_helper_single(rs);
  3299. if (!s) continue;
  3300. smartlist_add(strs, s);
  3301. });
  3302. s = smartlist_join_strings(strs, "", 0, NULL);
  3303. write_escaped_data(s, strlen(s), &esc);
  3304. SMARTLIST_FOREACH(strs, char *, cp, tor_free(cp));
  3305. smartlist_free(strs);
  3306. tor_free(s);
  3307. send_control_event_string(event, ALL_FORMATS, esc);
  3308. send_control_event_string(event, ALL_FORMATS,
  3309. "650 OK\r\n");
  3310. tor_free(esc);
  3311. return 0;
  3312. }
  3313. /** Called when the routerstatus_ts <b>statuses</b> have changed: sends
  3314. * an NS event to any controller that cares. */
  3315. int
  3316. control_event_networkstatus_changed(smartlist_t *statuses)
  3317. {
  3318. return control_event_networkstatus_changed_helper(statuses, EVENT_NS, "NS");
  3319. }
  3320. /** Called when we get a new consensus networkstatus. Sends a NEWCONSENSUS
  3321. * event consisting of an NS-style line for each relay in the consensus. */
  3322. int
  3323. control_event_newconsensus(const networkstatus_t *consensus)
  3324. {
  3325. if (!control_event_is_interesting(EVENT_NEWCONSENSUS))
  3326. return 0;
  3327. return control_event_networkstatus_changed_helper(
  3328. consensus->routerstatus_list, EVENT_NEWCONSENSUS, "NEWCONSENSUS");
  3329. }
  3330. /** Called when we compute a new circuitbuildtimeout */
  3331. int
  3332. control_event_buildtimeout_set(const circuit_build_times_t *cbt,
  3333. buildtimeout_set_event_t type)
  3334. {
  3335. const char *type_string = NULL;
  3336. double qnt = circuit_build_times_quantile_cutoff();
  3337. if (!control_event_is_interesting(EVENT_BUILDTIMEOUT_SET))
  3338. return 0;
  3339. switch (type) {
  3340. case BUILDTIMEOUT_SET_EVENT_COMPUTED:
  3341. type_string = "COMPUTED";
  3342. break;
  3343. case BUILDTIMEOUT_SET_EVENT_RESET:
  3344. type_string = "RESET";
  3345. qnt = 1.0;
  3346. break;
  3347. case BUILDTIMEOUT_SET_EVENT_SUSPENDED:
  3348. type_string = "SUSPENDED";
  3349. qnt = 1.0;
  3350. break;
  3351. case BUILDTIMEOUT_SET_EVENT_DISCARD:
  3352. type_string = "DISCARD";
  3353. qnt = 1.0;
  3354. break;
  3355. case BUILDTIMEOUT_SET_EVENT_RESUME:
  3356. type_string = "RESUME";
  3357. break;
  3358. default:
  3359. type_string = "UNKNOWN";
  3360. break;
  3361. }
  3362. send_control_event(EVENT_BUILDTIMEOUT_SET, ALL_FORMATS,
  3363. "650 BUILDTIMEOUT_SET %s TOTAL_TIMES=%lu "
  3364. "TIMEOUT_MS=%lu XM=%lu ALPHA=%lf CUTOFF_QUANTILE=%lf "
  3365. "TIMEOUT_RATE=%lf CLOSE_MS=%lu CLOSE_RATE=%lf\r\n",
  3366. type_string, (unsigned long)cbt->total_build_times,
  3367. (unsigned long)cbt->timeout_ms,
  3368. (unsigned long)cbt->Xm, cbt->alpha, qnt,
  3369. circuit_build_times_timeout_rate(cbt),
  3370. (unsigned long)cbt->close_ms,
  3371. circuit_build_times_close_rate(cbt));
  3372. return 0;
  3373. }
  3374. /** Called when a signal has been processed from signal_callback */
  3375. int
  3376. control_event_signal(uintptr_t signal)
  3377. {
  3378. const char *signal_string = NULL;
  3379. if (!control_event_is_interesting(EVENT_SIGNAL))
  3380. return 0;
  3381. switch (signal) {
  3382. case SIGHUP:
  3383. signal_string = "RELOAD";
  3384. break;
  3385. case SIGUSR1:
  3386. signal_string = "DUMP";
  3387. break;
  3388. case SIGUSR2:
  3389. signal_string = "DEBUG";
  3390. break;
  3391. case SIGNEWNYM:
  3392. signal_string = "NEWNYM";
  3393. break;
  3394. case SIGCLEARDNSCACHE:
  3395. signal_string = "CLEARDNSCACHE";
  3396. break;
  3397. default:
  3398. log_warn(LD_BUG, "Unrecognized signal %lu in control_event_signal",
  3399. (unsigned long)signal);
  3400. return -1;
  3401. }
  3402. send_control_event(EVENT_SIGNAL, ALL_FORMATS, "650 SIGNAL %s\r\n",
  3403. signal_string);
  3404. return 0;
  3405. }
  3406. /** Called when a single local_routerstatus_t has changed: Sends an NS event
  3407. * to any controller that cares. */
  3408. int
  3409. control_event_networkstatus_changed_single(const routerstatus_t *rs)
  3410. {
  3411. smartlist_t *statuses;
  3412. int r;
  3413. if (!EVENT_IS_INTERESTING(EVENT_NS))
  3414. return 0;
  3415. statuses = smartlist_create();
  3416. smartlist_add(statuses, (void*)rs);
  3417. r = control_event_networkstatus_changed(statuses);
  3418. smartlist_free(statuses);
  3419. return r;
  3420. }
  3421. /** Our own router descriptor has changed; tell any controllers that care.
  3422. */
  3423. int
  3424. control_event_my_descriptor_changed(void)
  3425. {
  3426. send_control_event(EVENT_DESCCHANGED, ALL_FORMATS, "650 DESCCHANGED\r\n");
  3427. return 0;
  3428. }
  3429. /** Helper: sends a status event where <b>type</b> is one of
  3430. * EVENT_STATUS_{GENERAL,CLIENT,SERVER}, where <b>severity</b> is one of
  3431. * LOG_{NOTICE,WARN,ERR}, and where <b>format</b> is a printf-style format
  3432. * string corresponding to <b>args</b>. */
  3433. static int
  3434. control_event_status(int type, int severity, const char *format, va_list args)
  3435. {
  3436. char format_buf[160];
  3437. const char *status, *sev;
  3438. switch (type) {
  3439. case EVENT_STATUS_GENERAL:
  3440. status = "STATUS_GENERAL";
  3441. break;
  3442. case EVENT_STATUS_CLIENT:
  3443. status = "STATUS_CLIENT";
  3444. break;
  3445. case EVENT_STATUS_SERVER:
  3446. status = "STATUS_SERVER";
  3447. break;
  3448. default:
  3449. log_warn(LD_BUG, "Unrecognized status type %d", type);
  3450. return -1;
  3451. }
  3452. switch (severity) {
  3453. case LOG_NOTICE:
  3454. sev = "NOTICE";
  3455. break;
  3456. case LOG_WARN:
  3457. sev = "WARN";
  3458. break;
  3459. case LOG_ERR:
  3460. sev = "ERR";
  3461. break;
  3462. default:
  3463. log_warn(LD_BUG, "Unrecognized status severity %d", severity);
  3464. return -1;
  3465. }
  3466. if (tor_snprintf(format_buf, sizeof(format_buf), "650 %s %s %s\r\n",
  3467. status, sev, format)<0) {
  3468. log_warn(LD_BUG, "Format string too long.");
  3469. return -1;
  3470. }
  3471. send_control_event_impl(type, ALL_FORMATS, format_buf, args);
  3472. return 0;
  3473. }
  3474. /** Format and send an EVENT_STATUS_GENERAL event whose main text is obtained
  3475. * by formatting the arguments using the printf-style <b>format</b>. */
  3476. int
  3477. control_event_general_status(int severity, const char *format, ...)
  3478. {
  3479. va_list ap;
  3480. int r;
  3481. if (!EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL))
  3482. return 0;
  3483. va_start(ap, format);
  3484. r = control_event_status(EVENT_STATUS_GENERAL, severity, format, ap);
  3485. va_end(ap);
  3486. return r;
  3487. }
  3488. /** Format and send an EVENT_STATUS_CLIENT event whose main text is obtained
  3489. * by formatting the arguments using the printf-style <b>format</b>. */
  3490. int
  3491. control_event_client_status(int severity, const char *format, ...)
  3492. {
  3493. va_list ap;
  3494. int r;
  3495. if (!EVENT_IS_INTERESTING(EVENT_STATUS_CLIENT))
  3496. return 0;
  3497. va_start(ap, format);
  3498. r = control_event_status(EVENT_STATUS_CLIENT, severity, format, ap);
  3499. va_end(ap);
  3500. return r;
  3501. }
  3502. /** Format and send an EVENT_STATUS_SERVER event whose main text is obtained
  3503. * by formatting the arguments using the printf-style <b>format</b>. */
  3504. int
  3505. control_event_server_status(int severity, const char *format, ...)
  3506. {
  3507. va_list ap;
  3508. int r;
  3509. if (!EVENT_IS_INTERESTING(EVENT_STATUS_SERVER))
  3510. return 0;
  3511. va_start(ap, format);
  3512. r = control_event_status(EVENT_STATUS_SERVER, severity, format, ap);
  3513. va_end(ap);
  3514. return r;
  3515. }
  3516. /** Called when the status of an entry guard with the given <b>nickname</b>
  3517. * and identity <b>digest</b> has changed to <b>status</b>: tells any
  3518. * controllers that care. */
  3519. int
  3520. control_event_guard(const char *nickname, const char *digest,
  3521. const char *status)
  3522. {
  3523. char hbuf[HEX_DIGEST_LEN+1];
  3524. base16_encode(hbuf, sizeof(hbuf), digest, DIGEST_LEN);
  3525. if (!EVENT_IS_INTERESTING(EVENT_GUARD))
  3526. return 0;
  3527. {
  3528. char buf[MAX_VERBOSE_NICKNAME_LEN+1];
  3529. const node_t *node = node_get_by_id(digest);
  3530. if (node) {
  3531. node_get_verbose_nickname(node, buf);
  3532. } else {
  3533. tor_snprintf(buf, sizeof(buf), "$%s~%s", hbuf, nickname);
  3534. }
  3535. send_control_event(EVENT_GUARD, ALL_FORMATS,
  3536. "650 GUARD ENTRY %s %s\r\n", buf, status);
  3537. }
  3538. return 0;
  3539. }
  3540. /** Helper: Return a newly allocated string containing a path to the
  3541. * file where we store our authentication cookie. */
  3542. static char *
  3543. get_cookie_file(void)
  3544. {
  3545. or_options_t *options = get_options();
  3546. if (options->CookieAuthFile && strlen(options->CookieAuthFile)) {
  3547. return tor_strdup(options->CookieAuthFile);
  3548. } else {
  3549. return get_datadir_fname("control_auth_cookie");
  3550. }
  3551. }
  3552. /** Choose a random authentication cookie and write it to disk.
  3553. * Anybody who can read the cookie from disk will be considered
  3554. * authorized to use the control connection. Return -1 if we can't
  3555. * write the file, or 0 on success. */
  3556. int
  3557. init_cookie_authentication(int enabled)
  3558. {
  3559. char *fname;
  3560. if (!enabled) {
  3561. authentication_cookie_is_set = 0;
  3562. return 0;
  3563. }
  3564. /* We don't want to generate a new cookie every time we call
  3565. * options_act(). One should be enough. */
  3566. if (authentication_cookie_is_set)
  3567. return 0; /* all set */
  3568. fname = get_cookie_file();
  3569. crypto_rand(authentication_cookie, AUTHENTICATION_COOKIE_LEN);
  3570. authentication_cookie_is_set = 1;
  3571. if (write_bytes_to_file(fname, authentication_cookie,
  3572. AUTHENTICATION_COOKIE_LEN, 1)) {
  3573. log_warn(LD_FS,"Error writing authentication cookie to %s.",
  3574. escaped(fname));
  3575. tor_free(fname);
  3576. return -1;
  3577. }
  3578. #ifndef MS_WINDOWS
  3579. if (get_options()->CookieAuthFileGroupReadable) {
  3580. if (chmod(fname, 0640)) {
  3581. log_warn(LD_FS,"Unable to make %s group-readable.", escaped(fname));
  3582. }
  3583. }
  3584. #endif
  3585. tor_free(fname);
  3586. return 0;
  3587. }
  3588. /** Convert the name of a bootstrapping phase <b>s</b> into strings
  3589. * <b>tag</b> and <b>summary</b> suitable for display by the controller. */
  3590. static int
  3591. bootstrap_status_to_string(bootstrap_status_t s, const char **tag,
  3592. const char **summary)
  3593. {
  3594. switch (s) {
  3595. case BOOTSTRAP_STATUS_UNDEF:
  3596. *tag = "undef";
  3597. *summary = "Undefined";
  3598. break;
  3599. case BOOTSTRAP_STATUS_STARTING:
  3600. *tag = "starting";
  3601. *summary = "Starting";
  3602. break;
  3603. case BOOTSTRAP_STATUS_CONN_DIR:
  3604. *tag = "conn_dir";
  3605. *summary = "Connecting to directory server";
  3606. break;
  3607. case BOOTSTRAP_STATUS_HANDSHAKE:
  3608. *tag = "status_handshake";
  3609. *summary = "Finishing handshake";
  3610. break;
  3611. case BOOTSTRAP_STATUS_HANDSHAKE_DIR:
  3612. *tag = "handshake_dir";
  3613. *summary = "Finishing handshake with directory server";
  3614. break;
  3615. case BOOTSTRAP_STATUS_ONEHOP_CREATE:
  3616. *tag = "onehop_create";
  3617. *summary = "Establishing an encrypted directory connection";
  3618. break;
  3619. case BOOTSTRAP_STATUS_REQUESTING_STATUS:
  3620. *tag = "requesting_status";
  3621. *summary = "Asking for networkstatus consensus";
  3622. break;
  3623. case BOOTSTRAP_STATUS_LOADING_STATUS:
  3624. *tag = "loading_status";
  3625. *summary = "Loading networkstatus consensus";
  3626. break;
  3627. case BOOTSTRAP_STATUS_LOADING_KEYS:
  3628. *tag = "loading_keys";
  3629. *summary = "Loading authority key certs";
  3630. break;
  3631. case BOOTSTRAP_STATUS_REQUESTING_DESCRIPTORS:
  3632. *tag = "requesting_descriptors";
  3633. *summary = "Asking for relay descriptors";
  3634. break;
  3635. case BOOTSTRAP_STATUS_LOADING_DESCRIPTORS:
  3636. *tag = "loading_descriptors";
  3637. *summary = "Loading relay descriptors";
  3638. break;
  3639. case BOOTSTRAP_STATUS_CONN_OR:
  3640. *tag = "conn_or";
  3641. *summary = "Connecting to the Tor network";
  3642. break;
  3643. case BOOTSTRAP_STATUS_HANDSHAKE_OR:
  3644. *tag = "handshake_or";
  3645. *summary = "Finishing handshake with first hop";
  3646. break;
  3647. case BOOTSTRAP_STATUS_CIRCUIT_CREATE:
  3648. *tag = "circuit_create";
  3649. *summary = "Establishing a Tor circuit";
  3650. break;
  3651. case BOOTSTRAP_STATUS_DONE:
  3652. *tag = "done";
  3653. *summary = "Done";
  3654. break;
  3655. default:
  3656. // log_warn(LD_BUG, "Unrecognized bootstrap status code %d", s);
  3657. *tag = *summary = "unknown";
  3658. return -1;
  3659. }
  3660. return 0;
  3661. }
  3662. /** What percentage through the bootstrap process are we? We remember
  3663. * this so we can avoid sending redundant bootstrap status events, and
  3664. * so we can guess context for the bootstrap messages which are
  3665. * ambiguous. It starts at 'undef', but gets set to 'starting' while
  3666. * Tor initializes. */
  3667. static int bootstrap_percent = BOOTSTRAP_STATUS_UNDEF;
  3668. /** How many problems have we had getting to the next bootstrapping phase?
  3669. * These include failure to establish a connection to a Tor relay,
  3670. * failures to finish the TLS handshake, failures to validate the
  3671. * consensus document, etc. */
  3672. static int bootstrap_problems = 0;
  3673. /* We only tell the controller once we've hit a threshold of problems
  3674. * for the current phase. */
  3675. #define BOOTSTRAP_PROBLEM_THRESHOLD 10
  3676. /** Called when Tor has made progress at bootstrapping its directory
  3677. * information and initial circuits.
  3678. *
  3679. * <b>status</b> is the new status, that is, what task we will be doing
  3680. * next. <b>percent</b> is zero if we just started this task, else it
  3681. * represents progress on the task. */
  3682. void
  3683. control_event_bootstrap(bootstrap_status_t status, int progress)
  3684. {
  3685. const char *tag, *summary;
  3686. char buf[BOOTSTRAP_MSG_LEN];
  3687. if (bootstrap_percent == BOOTSTRAP_STATUS_DONE)
  3688. return; /* already bootstrapped; nothing to be done here. */
  3689. /* special case for handshaking status, since our TLS handshaking code
  3690. * can't distinguish what the connection is going to be for. */
  3691. if (status == BOOTSTRAP_STATUS_HANDSHAKE) {
  3692. if (bootstrap_percent < BOOTSTRAP_STATUS_CONN_OR) {
  3693. status = BOOTSTRAP_STATUS_HANDSHAKE_DIR;
  3694. } else {
  3695. status = BOOTSTRAP_STATUS_HANDSHAKE_OR;
  3696. }
  3697. }
  3698. if (status > bootstrap_percent ||
  3699. (progress && progress > bootstrap_percent)) {
  3700. bootstrap_status_to_string(status, &tag, &summary);
  3701. log(status ? LOG_NOTICE : LOG_INFO, LD_CONTROL,
  3702. "Bootstrapped %d%%: %s.", progress ? progress : status, summary);
  3703. tor_snprintf(buf, sizeof(buf),
  3704. "BOOTSTRAP PROGRESS=%d TAG=%s SUMMARY=\"%s\"",
  3705. progress ? progress : status, tag, summary);
  3706. tor_snprintf(last_sent_bootstrap_message,
  3707. sizeof(last_sent_bootstrap_message),
  3708. "NOTICE %s", buf);
  3709. control_event_client_status(LOG_NOTICE, "%s", buf);
  3710. if (status > bootstrap_percent) {
  3711. bootstrap_percent = status; /* new milestone reached */
  3712. }
  3713. if (progress > bootstrap_percent) {
  3714. /* incremental progress within a milestone */
  3715. bootstrap_percent = progress;
  3716. bootstrap_problems = 0; /* Progress! Reset our problem counter. */
  3717. }
  3718. }
  3719. }
  3720. /** Called when Tor has failed to make bootstrapping progress in a way
  3721. * that indicates a problem. <b>warn</b> gives a hint as to why, and
  3722. * <b>reason</b> provides an "or_conn_end_reason" tag.
  3723. */
  3724. void
  3725. control_event_bootstrap_problem(const char *warn, int reason)
  3726. {
  3727. int status = bootstrap_percent;
  3728. const char *tag, *summary;
  3729. char buf[BOOTSTRAP_MSG_LEN];
  3730. const char *recommendation = "ignore";
  3731. if (bootstrap_percent == 100)
  3732. return; /* already bootstrapped; nothing to be done here. */
  3733. bootstrap_problems++;
  3734. if (bootstrap_problems >= BOOTSTRAP_PROBLEM_THRESHOLD)
  3735. recommendation = "warn";
  3736. if (reason == END_OR_CONN_REASON_NO_ROUTE)
  3737. recommendation = "warn";
  3738. if (get_options()->UseBridges &&
  3739. !any_bridge_descriptors_known() &&
  3740. !any_pending_bridge_descriptor_fetches())
  3741. recommendation = "warn";
  3742. while (status>=0 && bootstrap_status_to_string(status, &tag, &summary) < 0)
  3743. status--; /* find a recognized status string based on current progress */
  3744. status = bootstrap_percent; /* set status back to the actual number */
  3745. log_fn(!strcmp(recommendation, "warn") ? LOG_WARN : LOG_INFO,
  3746. LD_CONTROL, "Problem bootstrapping. Stuck at %d%%: %s. (%s; %s; "
  3747. "count %d; recommendation %s)",
  3748. status, summary, warn,
  3749. orconn_end_reason_to_control_string(reason),
  3750. bootstrap_problems, recommendation);
  3751. tor_snprintf(buf, sizeof(buf),
  3752. "BOOTSTRAP PROGRESS=%d TAG=%s SUMMARY=\"%s\" WARNING=\"%s\" REASON=%s "
  3753. "COUNT=%d RECOMMENDATION=%s",
  3754. bootstrap_percent, tag, summary, warn,
  3755. orconn_end_reason_to_control_string(reason), bootstrap_problems,
  3756. recommendation);
  3757. tor_snprintf(last_sent_bootstrap_message,
  3758. sizeof(last_sent_bootstrap_message),
  3759. "WARN %s", buf);
  3760. control_event_client_status(LOG_WARN, "%s", buf);
  3761. }
  3762. /** We just generated a new summary of which countries we've seen clients
  3763. * from recently. Send a copy to the controller in case it wants to
  3764. * display it for the user. */
  3765. void
  3766. control_event_clients_seen(const char *controller_str)
  3767. {
  3768. send_control_event(EVENT_CLIENTS_SEEN, 0,
  3769. "650 CLIENTS_SEEN %s\r\n", controller_str);
  3770. }