control.c 132 KB

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