control.c 120 KB

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