control.c 133 KB

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