control.c 133 KB

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