control.c 133 KB

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