control.c 133 KB

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