control.c 123 KB

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