control.c 97 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992
  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 message type codes. */
  21. #define CONTROL0_CMD_ERROR 0x0000
  22. #define CONTROL0_CMD_DONE 0x0001
  23. #define CONTROL0_CMD_SETCONF 0x0002
  24. #define CONTROL0_CMD_GETCONF 0x0003
  25. #define CONTROL0_CMD_CONFVALUE 0x0004
  26. #define CONTROL0_CMD_SETEVENTS 0x0005
  27. #define CONTROL0_CMD_EVENT 0x0006
  28. #define CONTROL0_CMD_AUTHENTICATE 0x0007
  29. #define CONTROL0_CMD_SAVECONF 0x0008
  30. #define CONTROL0_CMD_SIGNAL 0x0009
  31. #define CONTROL0_CMD_MAPADDRESS 0x000A
  32. #define CONTROL0_CMD_GETINFO 0x000B
  33. #define CONTROL0_CMD_INFOVALUE 0x000C
  34. #define CONTROL0_CMD_EXTENDCIRCUIT 0x000D
  35. #define CONTROL0_CMD_ATTACHSTREAM 0x000E
  36. #define CONTROL0_CMD_POSTDESCRIPTOR 0x000F
  37. #define CONTROL0_CMD_FRAGMENTHEADER 0x0010
  38. #define CONTROL0_CMD_FRAGMENT 0x0011
  39. #define CONTROL0_CMD_REDIRECTSTREAM 0x0012
  40. #define CONTROL0_CMD_CLOSESTREAM 0x0013
  41. #define CONTROL0_CMD_CLOSECIRCUIT 0x0014
  42. #define _CONTROL0_CMD_MAX_RECOGNIZED 0x0014
  43. /* Recognized error codes. */
  44. #define ERR_UNSPECIFIED 0x0000
  45. #define ERR_INTERNAL 0x0001
  46. #define ERR_UNRECOGNIZED_TYPE 0x0002
  47. #define ERR_SYNTAX 0x0003
  48. #define ERR_UNRECOGNIZED_CONFIG_KEY 0x0004
  49. #define ERR_INVALID_CONFIG_VALUE 0x0005
  50. #define ERR_UNRECOGNIZED_EVENT_CODE 0x0006
  51. #define ERR_UNAUTHORIZED 0x0007
  52. #define ERR_REJECTED_AUTHENTICATION 0x0008
  53. #define ERR_RESOURCE_EXHAUSETED 0x0009
  54. #define ERR_NO_STREAM 0x000A
  55. #define ERR_NO_CIRC 0x000B
  56. #define ERR_NO_ROUTER 0x000C
  57. /* Recognized asynchronous event types. */
  58. #define _EVENT_MIN 0x0001
  59. #define EVENT_CIRCUIT_STATUS 0x0001
  60. #define EVENT_STREAM_STATUS 0x0002
  61. #define EVENT_OR_CONN_STATUS 0x0003
  62. #define EVENT_BANDWIDTH_USED 0x0004
  63. #define EVENT_LOG_OBSOLETE 0x0005
  64. #define EVENT_NEW_DESC 0x0006
  65. #define EVENT_DEBUG_MSG 0x0007
  66. #define EVENT_INFO_MSG 0x0008
  67. #define EVENT_NOTICE_MSG 0x0009
  68. #define EVENT_WARN_MSG 0x000A
  69. #define EVENT_ERR_MSG 0x000B
  70. #define LAST_V0_EVENT 0x000B
  71. #define EVENT_ADDRMAP 0x000C
  72. #define EVENT_AUTHDIR_NEWDESCS 0x000D
  73. #define _EVENT_MAX 0x000D
  74. /** Array mapping from message type codes to human-readable message
  75. * type names. Used for compatibility with version 0 of the control
  76. * protocol. */
  77. static const char * CONTROL0_COMMANDS[_CONTROL0_CMD_MAX_RECOGNIZED+1] = {
  78. "error",
  79. "done",
  80. "setconf",
  81. "getconf",
  82. "confvalue",
  83. "setevents",
  84. "events",
  85. "authenticate",
  86. "saveconf",
  87. "signal",
  88. "mapaddress",
  89. "getinfo",
  90. "infovalue",
  91. "extendcircuit",
  92. "attachstream",
  93. "postdescriptor",
  94. "fragmentheader",
  95. "fragment",
  96. };
  97. /** Bitfield: The bit 1&lt;&lt;e is set if <b>any</b> open control
  98. * connection is interested in events of type <b>e</b>. We use this
  99. * so that we can decide to skip generating event messages that nobody
  100. * has interest in without having to walk over the global connection
  101. * list to find out.
  102. **/
  103. static uint32_t global_event_mask0 = 0;
  104. static uint32_t global_event_mask1 = 0;
  105. /** True iff we have disabled log messages from being sent to the controller */
  106. static int disable_log_messages = 0;
  107. /** Macro: true if any control connection is interested in events of type
  108. * <b>e</b>. */
  109. #define EVENT_IS_INTERESTING0(e) (global_event_mask0 & (1<<(e)))
  110. #define EVENT_IS_INTERESTING1(e) (global_event_mask1 & (1<<(e)))
  111. #define EVENT_IS_INTERESTING(e) \
  112. ((global_event_mask0|global_event_mask1) & (1<<(e)))
  113. /** If we're using cookie-type authentication, how long should our cookies be?
  114. */
  115. #define AUTHENTICATION_COOKIE_LEN 32
  116. /** If true, we've set authentication_cookie to a secret code and
  117. * stored it to disk. */
  118. static int authentication_cookie_is_set = 0;
  119. static char authentication_cookie[AUTHENTICATION_COOKIE_LEN];
  120. static void connection_printf_to_buf(control_connection_t *conn,
  121. const char *format, ...)
  122. CHECK_PRINTF(2,3);
  123. /*static*/ size_t write_escaped_data(const char *data, size_t len,
  124. int translate_newlines, char **out);
  125. /*static*/ size_t read_escaped_data(const char *data, size_t len,
  126. int translate_newlines, char **out);
  127. static void send_control0_message(control_connection_t *conn, uint16_t type,
  128. uint32_t len, const char *body);
  129. static void send_control_done(control_connection_t *conn);
  130. static void send_control_done2(control_connection_t *conn, const char *msg,
  131. size_t len);
  132. static void send_control0_error(control_connection_t *conn, uint16_t error,
  133. const char *message);
  134. static void send_control0_event(uint16_t event, uint32_t len,
  135. const char *body);
  136. static void send_control1_event(uint16_t event, const char *format, ...)
  137. CHECK_PRINTF(2,3);
  138. static int handle_control_setconf(control_connection_t *conn, uint32_t len,
  139. char *body);
  140. static int handle_control_resetconf(control_connection_t *conn, uint32_t len,
  141. char *body);
  142. static int handle_control_getconf(control_connection_t *conn, uint32_t len,
  143. const char *body);
  144. static int handle_control_setevents(control_connection_t *conn, uint32_t len,
  145. const char *body);
  146. static int handle_control_authenticate(control_connection_t *conn,
  147. uint32_t len,
  148. const char *body);
  149. static int handle_control_saveconf(control_connection_t *conn, uint32_t len,
  150. const char *body);
  151. static int handle_control_signal(control_connection_t *conn, uint32_t len,
  152. const char *body);
  153. static int handle_control_mapaddress(control_connection_t *conn, uint32_t len,
  154. const char *body);
  155. static int handle_control_getinfo(control_connection_t *conn, uint32_t len,
  156. const char *body);
  157. static int handle_control_extendcircuit(control_connection_t *conn,
  158. uint32_t len,
  159. const char *body);
  160. static int handle_control_setpurpose(control_connection_t *conn,
  161. int for_circuits,
  162. uint32_t len, const char *body);
  163. static int handle_control_attachstream(control_connection_t *conn,
  164. uint32_t len,
  165. const char *body);
  166. static int handle_control_postdescriptor(control_connection_t *conn,
  167. uint32_t len,
  168. const char *body);
  169. static int handle_control_redirectstream(control_connection_t *conn,
  170. uint32_t len,
  171. const char *body);
  172. static int handle_control_closestream(control_connection_t *conn, uint32_t len,
  173. const char *body);
  174. static int handle_control_closecircuit(control_connection_t *conn,
  175. uint32_t len,
  176. const char *body);
  177. static int write_stream_target_to_buf(edge_connection_t *conn, char *buf,
  178. size_t len);
  179. /** Given a possibly invalid message type code <b>cmd</b>, return a
  180. * human-readable string equivalent. */
  181. static INLINE const char *
  182. control_cmd_to_string(uint16_t cmd)
  183. {
  184. return (cmd<=_CONTROL0_CMD_MAX_RECOGNIZED) ?
  185. CONTROL0_COMMANDS[cmd] : "Unknown";
  186. }
  187. /** Given a control event code for a message event, return the corresponding
  188. * log severity. */
  189. static INLINE int
  190. event_to_log_severity(int event)
  191. {
  192. switch (event) {
  193. case EVENT_DEBUG_MSG: return LOG_DEBUG;
  194. case EVENT_INFO_MSG: return LOG_INFO;
  195. case EVENT_NOTICE_MSG: return LOG_NOTICE;
  196. case EVENT_WARN_MSG: return LOG_WARN;
  197. case EVENT_ERR_MSG: return LOG_ERR;
  198. default: return -1;
  199. }
  200. }
  201. /** Given a log severity, return the corresponding control event code. */
  202. static INLINE int
  203. log_severity_to_event(int severity)
  204. {
  205. switch (severity) {
  206. case LOG_DEBUG: return EVENT_DEBUG_MSG;
  207. case LOG_INFO: return EVENT_INFO_MSG;
  208. case LOG_NOTICE: return EVENT_NOTICE_MSG;
  209. case LOG_WARN: return EVENT_WARN_MSG;
  210. case LOG_ERR: return EVENT_ERR_MSG;
  211. default: return -1;
  212. }
  213. }
  214. /** Set <b>global_event_maskX</b> (where X is 0 or 1) to the bitwise OR
  215. * of each live control connection's event_mask field. */
  216. void
  217. control_update_global_event_mask(void)
  218. {
  219. connection_t **conns;
  220. int n_conns, i;
  221. global_event_mask0 = 0;
  222. global_event_mask1 = 0;
  223. get_connection_array(&conns, &n_conns);
  224. for (i = 0; i < n_conns; ++i) {
  225. if (conns[i]->type == CONN_TYPE_CONTROL &&
  226. STATE_IS_OPEN(conns[i]->state)) {
  227. control_connection_t *conn = TO_CONTROL_CONN(conns[i]);
  228. if (STATE_IS_V0(conn->_base.state))
  229. global_event_mask0 |= conn->event_mask;
  230. else
  231. global_event_mask1 |= conn->event_mask;
  232. }
  233. }
  234. control_adjust_event_log_severity();
  235. }
  236. /** Adjust the log severities that result in control_event_logmsg being called
  237. * to match the severity of log messages that any controllers are interested
  238. * in. */
  239. void
  240. control_adjust_event_log_severity(void)
  241. {
  242. int i;
  243. int min_log_event=EVENT_ERR_MSG, max_log_event=EVENT_DEBUG_MSG;
  244. for (i = EVENT_DEBUG_MSG; i <= EVENT_ERR_MSG; ++i) {
  245. if (EVENT_IS_INTERESTING(i)) {
  246. min_log_event = i;
  247. break;
  248. }
  249. }
  250. for (i = EVENT_ERR_MSG; i >= EVENT_DEBUG_MSG; --i) {
  251. if (EVENT_IS_INTERESTING(i)) {
  252. max_log_event = i;
  253. break;
  254. }
  255. }
  256. if (EVENT_IS_INTERESTING(EVENT_LOG_OBSOLETE)) {
  257. if (min_log_event > EVENT_NOTICE_MSG)
  258. min_log_event = EVENT_NOTICE_MSG;
  259. if (max_log_event < EVENT_ERR_MSG)
  260. max_log_event = EVENT_ERR_MSG;
  261. }
  262. change_callback_log_severity(event_to_log_severity(min_log_event),
  263. event_to_log_severity(max_log_event),
  264. control_event_logmsg);
  265. }
  266. /** Append a NUL-terminated string <b>s</b> to the end of
  267. * <b>conn</b>-\>outbuf
  268. */
  269. static INLINE void
  270. connection_write_str_to_buf(const char *s, control_connection_t *conn)
  271. {
  272. size_t len = strlen(s);
  273. connection_write_to_buf(s, len, TO_CONN(conn));
  274. }
  275. /** Given a <b>len</b>-character string in <b>data</b>, made of lines
  276. * terminated by CRLF, allocate a new string in *<b>out</b>, and copy
  277. * the contents of <b>data</b> into *<b>out</b>, adding a period
  278. * before any period that that appears at the start of a line, and
  279. * adding a period-CRLF line at the end. If <b>translate_newlines</b>
  280. * is true, replace all LF characters sequences with CRLF. Return the
  281. * number of bytes in *<b>out</b>.
  282. */
  283. /* static */ size_t
  284. write_escaped_data(const char *data, size_t len, int translate_newlines,
  285. char **out)
  286. {
  287. size_t sz_out = len+8;
  288. char *outp;
  289. const char *end;
  290. int i;
  291. int start_of_line;
  292. for (i=0; i<(int)len; ++i) {
  293. if (data[i]== '\n')
  294. sz_out += 2; /* Maybe add a CR; maybe add a dot. */
  295. }
  296. *out = outp = tor_malloc(sz_out+1);
  297. end = data+len;
  298. start_of_line = 1;
  299. while (data < end) {
  300. if (*data == '\n') {
  301. if (translate_newlines)
  302. *outp++ = '\r';
  303. start_of_line = 1;
  304. } else if (*data == '.') {
  305. if (start_of_line) {
  306. start_of_line = 0;
  307. *outp++ = '.';
  308. }
  309. } else {
  310. start_of_line = 0;
  311. }
  312. *outp++ = *data++;
  313. }
  314. if (outp < *out+2 || memcmp(outp-2, "\r\n", 2)) {
  315. *outp++ = '\r';
  316. *outp++ = '\n';
  317. }
  318. *outp++ = '.';
  319. *outp++ = '\r';
  320. *outp++ = '\n';
  321. *outp = '\0'; /* NUL-terminate just in case. */
  322. tor_assert((outp - *out) <= (int)sz_out);
  323. return outp - *out;
  324. }
  325. /** Given a <b>len</b>-character string in <b>data</b>, made of lines
  326. * terminated by CRLF, allocate a new string in *<b>out</b>, and copy
  327. * the contents of <b>data</b> into *<b>out</b>, removing any period
  328. * that appears at the start of a line. If <b>translate_newlines</b>
  329. * is true, replace all CRLF sequences with LF. Return the number of
  330. * bytes in *<b>out</b>. */
  331. /*static*/ size_t
  332. read_escaped_data(const char *data, size_t len, int translate_newlines,
  333. char **out)
  334. {
  335. char *outp;
  336. const char *next;
  337. const char *end;
  338. *out = outp = tor_malloc(len+1);
  339. end = data+len;
  340. while (data < end) {
  341. if (*data == '.')
  342. ++data;
  343. if (translate_newlines)
  344. next = tor_memmem(data, end-data, "\r\n", 2);
  345. else
  346. next = tor_memmem(data, end-data, "\r\n.", 3);
  347. if (next) {
  348. memcpy(outp, data, next-data);
  349. outp += (next-data);
  350. data = next+2;
  351. } else {
  352. memcpy(outp, data, end-data);
  353. outp += (end-data);
  354. *outp = '\0';
  355. return outp - *out;
  356. }
  357. if (translate_newlines) {
  358. *outp++ = '\n';
  359. } else {
  360. *outp++ = '\r';
  361. *outp++ = '\n';
  362. }
  363. }
  364. *outp = '\0';
  365. return outp - *out;
  366. }
  367. /** Given a pointer to a string starting at <b>start</b> containing
  368. * <b>in_len_max</b> characters, decode a string beginning with a single
  369. * quote, containing any number of non-quote characters or characters escaped
  370. * with a backslash, and ending with a final quote. Place the resulting
  371. * string (unquoted, unescaped) into a newly allocated string in *<b>out</b>;
  372. * store its length in <b>out_len</b>. On success, return a pointer to the
  373. * character immediately following the escaped string. On failure, return
  374. * NULL. */
  375. static const char *
  376. get_escaped_string(const char *start, size_t in_len_max,
  377. char **out, size_t *out_len)
  378. {
  379. const char *cp, *end;
  380. char *outp;
  381. size_t len=0;
  382. if (*start != '\"')
  383. return NULL;
  384. cp = start+1;
  385. end = start+in_len_max;
  386. /* Calculate length. */
  387. while (1) {
  388. if (cp >= end)
  389. return NULL;
  390. else if (*cp == '\\') {
  391. if (++cp == end)
  392. return NULL; /* Can't escape EOS. */
  393. ++cp;
  394. ++len;
  395. } else if (*cp == '\"') {
  396. break;
  397. } else {
  398. ++cp;
  399. ++len;
  400. }
  401. }
  402. end = cp;
  403. outp = *out = tor_malloc(len+1);
  404. *out_len = len;
  405. cp = start+1;
  406. while (cp < end) {
  407. if (*cp == '\\')
  408. ++cp;
  409. *outp++ = *cp++;
  410. }
  411. *outp = '\0';
  412. tor_assert((outp - *out) == (int)*out_len);
  413. return end+1;
  414. }
  415. /** Acts like sprintf, but writes its formatted string to the end of
  416. * <b>conn</b>-\>outbuf. The message may be truncated if it is too long,
  417. * but it will always end with a CRLF sequence.
  418. *
  419. * Currently the length of the message is limited to 1024 (including the
  420. * ending \n\r\0. */
  421. static void
  422. connection_printf_to_buf(control_connection_t *conn, const char *format, ...)
  423. {
  424. #define CONNECTION_PRINTF_TO_BUF_BUFFERSIZE 1024
  425. va_list ap;
  426. char buf[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE];
  427. int r;
  428. size_t len;
  429. va_start(ap,format);
  430. r = tor_vsnprintf(buf, sizeof(buf), format, ap);
  431. va_end(ap);
  432. len = strlen(buf);
  433. if (memcmp("\r\n\0", buf+len-2, 3)) {
  434. buf[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE-1] = '\0';
  435. buf[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE-2] = '\n';
  436. buf[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE-3] = '\r';
  437. }
  438. connection_write_to_buf(buf, len, TO_CONN(conn));
  439. }
  440. /** Send a message of type <b>type</b> containing <b>len</b> bytes
  441. * from <b>body</b> along the control connection <b>conn</b> */
  442. static void
  443. send_control0_message(control_connection_t *conn, uint16_t type, uint32_t len,
  444. const char *body)
  445. {
  446. char buf[10];
  447. tor_assert(conn);
  448. tor_assert(STATE_IS_V0(conn->_base.state));
  449. tor_assert(len || !body);
  450. tor_assert(type <= _CONTROL0_CMD_MAX_RECOGNIZED);
  451. if (len < 65536) {
  452. set_uint16(buf, htons(len));
  453. set_uint16(buf+2, htons(type));
  454. connection_write_to_buf(buf, 4, TO_CONN(conn));
  455. if (len)
  456. connection_write_to_buf(body, len, TO_CONN(conn));
  457. } else {
  458. set_uint16(buf, htons(65535));
  459. set_uint16(buf+2, htons(CONTROL0_CMD_FRAGMENTHEADER));
  460. set_uint16(buf+4, htons(type));
  461. set_uint32(buf+6, htonl(len));
  462. connection_write_to_buf(buf, 10, TO_CONN(conn));
  463. connection_write_to_buf(body, 65535-6, TO_CONN(conn));
  464. len -= (65535-6);
  465. body += (65535-6);
  466. while (len) {
  467. size_t chunklen = (len<65535)?len:65535;
  468. set_uint16(buf, htons((uint16_t)chunklen));
  469. set_uint16(buf+2, htons(CONTROL0_CMD_FRAGMENT));
  470. connection_write_to_buf(buf, 4, TO_CONN(conn));
  471. connection_write_to_buf(body, chunklen, TO_CONN(conn));
  472. len -= chunklen;
  473. body += chunklen;
  474. }
  475. }
  476. }
  477. /** Send a "DONE" message down the control connection <b>conn</b> */
  478. static void
  479. send_control_done(control_connection_t *conn)
  480. {
  481. if (STATE_IS_V0(conn->_base.state)) {
  482. send_control0_message(conn, CONTROL0_CMD_DONE, 0, NULL);
  483. } else {
  484. connection_write_str_to_buf("250 OK\r\n", conn);
  485. }
  486. }
  487. /** Send a "DONE" message down the v0 control message <b>conn</b>, with body
  488. * as provided in the <b>len</b> bytes at <b>msg</b>.
  489. */
  490. static void
  491. send_control_done2(control_connection_t *conn, const char *msg, size_t len)
  492. {
  493. if (len==0)
  494. len = strlen(msg);
  495. send_control0_message(conn, CONTROL0_CMD_DONE, len, msg);
  496. }
  497. /** Send an error message with error code <b>error</b> and body
  498. * <b>message</b> down the connection <b>conn</b> */
  499. static void
  500. send_control0_error(control_connection_t *conn, uint16_t error,
  501. const char *message)
  502. {
  503. char buf[256];
  504. size_t len;
  505. set_uint16(buf, htons(error));
  506. len = strlen(message);
  507. tor_assert(len < (256-2));
  508. memcpy(buf+2, message, len);
  509. send_control0_message(conn, CONTROL0_CMD_ERROR, (uint16_t)(len+2), buf);
  510. }
  511. /** Send an 'event' message of event type <b>event</b>, containing
  512. * <b>len</b> bytes in <b>body</b> to every control connection that
  513. * is interested in it. */
  514. static void
  515. send_control0_event(uint16_t event, uint32_t len, const char *body)
  516. {
  517. connection_t **conns;
  518. int n_conns, i;
  519. size_t buflen;
  520. char *buf;
  521. tor_assert(event >= _EVENT_MIN && event <= LAST_V0_EVENT);
  522. buflen = len + 2;
  523. buf = tor_malloc_zero(buflen);
  524. set_uint16(buf, htons(event));
  525. memcpy(buf+2, body, len);
  526. get_connection_array(&conns, &n_conns);
  527. for (i = 0; i < n_conns; ++i) {
  528. if (conns[i]->type == CONN_TYPE_CONTROL &&
  529. !conns[i]->marked_for_close &&
  530. conns[i]->state == CONTROL_CONN_STATE_OPEN_V0) {
  531. control_connection_t *control_conn = TO_CONTROL_CONN(conns[i]);
  532. if (control_conn->event_mask & (1<<event)) {
  533. send_control0_message(control_conn, CONTROL0_CMD_EVENT, buflen, buf);
  534. if (event == EVENT_ERR_MSG)
  535. _connection_controller_force_write(control_conn);
  536. }
  537. }
  538. }
  539. tor_free(buf);
  540. }
  541. /* Send an event to all v1 controllers that are listening for code
  542. * <b>event</b>. The event's body is given by <b>msg</b>. */
  543. static void
  544. send_control1_event_string(uint16_t event, const char *msg)
  545. {
  546. connection_t **conns;
  547. int n_conns, i;
  548. tor_assert(event >= _EVENT_MIN && event <= _EVENT_MAX);
  549. get_connection_array(&conns, &n_conns);
  550. for (i = 0; i < n_conns; ++i) {
  551. if (conns[i]->type == CONN_TYPE_CONTROL &&
  552. !conns[i]->marked_for_close &&
  553. conns[i]->state == CONTROL_CONN_STATE_OPEN_V1) {
  554. control_connection_t *control_conn = TO_CONTROL_CONN(conns[i]);
  555. if (control_conn->event_mask & (1<<event)) {
  556. connection_write_to_buf(msg, strlen(msg), TO_CONN(control_conn));
  557. if (event == EVENT_ERR_MSG)
  558. _connection_controller_force_write(control_conn);
  559. }
  560. }
  561. }
  562. }
  563. /* Send an event to all v1 controllers that are listening for code
  564. * <b>event</b>. The event's body is created by the printf-style format in
  565. * <b>format</b>, and other arguments as provided.
  566. *
  567. * Currently the length of the message is limited to 1024 (including the
  568. * ending \n\r\0. */
  569. static void
  570. send_control1_event(uint16_t event, const char *format, ...)
  571. {
  572. #define SEND_CONTROL1_EVENT_BUFFERSIZE 1024
  573. int r;
  574. char buf[SEND_CONTROL1_EVENT_BUFFERSIZE]; /* XXXX Length */
  575. va_list ap;
  576. size_t len;
  577. va_start(ap, format);
  578. r = tor_vsnprintf(buf, sizeof(buf), format, ap);
  579. va_end(ap);
  580. len = strlen(buf);
  581. if (memcmp("\r\n\0", buf+len-2, 3)) {
  582. /* if it is not properly terminated, do it now */
  583. buf[SEND_CONTROL1_EVENT_BUFFERSIZE-1] = '\0';
  584. buf[SEND_CONTROL1_EVENT_BUFFERSIZE-2] = '\n';
  585. buf[SEND_CONTROL1_EVENT_BUFFERSIZE-3] = '\r';
  586. }
  587. send_control1_event_string(event, buf);
  588. }
  589. /** Given a text circuit <b>id</b>, return the corresponding circuit. */
  590. static origin_circuit_t *
  591. get_circ(const char *id)
  592. {
  593. unsigned long n_id;
  594. int ok;
  595. n_id = tor_parse_ulong(id, 10, 0, ULONG_MAX, &ok, NULL);
  596. if (!ok)
  597. return NULL;
  598. return circuit_get_by_global_id(n_id);
  599. }
  600. /** Given a text stream <b>id</b>, return the corresponding AP connection. */
  601. static edge_connection_t *
  602. get_stream(const char *id)
  603. {
  604. unsigned long n_id;
  605. int ok;
  606. edge_connection_t *conn;
  607. n_id = tor_parse_ulong(id, 10, 0, ULONG_MAX, &ok, NULL);
  608. if (!ok)
  609. return NULL;
  610. conn = connection_get_by_global_id(n_id);
  611. if (!conn || conn->_base.type != CONN_TYPE_AP)
  612. return NULL;
  613. return conn;
  614. }
  615. /** Helper for setconf and resetconf. Acts like setconf, except
  616. * it passes <b>use_defaults</b> on to options_trial_assign().
  617. */
  618. static int
  619. control_setconf_helper(control_connection_t *conn, uint32_t len, char *body,
  620. int use_defaults, int clear_first)
  621. {
  622. int r;
  623. config_line_t *lines=NULL;
  624. char *start = body;
  625. char *errstring = NULL;
  626. int v0 = STATE_IS_V0(conn->_base.state);
  627. if (!v0) {
  628. char *config = tor_malloc(len+1);
  629. char *outp = config;
  630. while (*body) {
  631. char *eq = body;
  632. while (!TOR_ISSPACE(*eq) && *eq != '=')
  633. ++eq;
  634. memcpy(outp, body, eq-body);
  635. outp += (eq-body);
  636. *outp++ = ' ';
  637. body = eq+1;
  638. if (*eq == '=') {
  639. if (*body != '\"') {
  640. while (!TOR_ISSPACE(*body))
  641. *outp++ = *body++;
  642. } else {
  643. char *val;
  644. size_t val_len;
  645. body = (char*)get_escaped_string(body, (len - (body-start)),
  646. &val, &val_len);
  647. if (!body) {
  648. connection_write_str_to_buf("551 Couldn't parse string\r\n", conn);
  649. tor_free(config);
  650. return 0;
  651. }
  652. memcpy(outp, val, val_len);
  653. outp += val_len;
  654. tor_free(val);
  655. }
  656. }
  657. while (TOR_ISSPACE(*body))
  658. ++body;
  659. *outp++ = '\n';
  660. }
  661. *outp = '\0';
  662. if (config_get_lines(config, &lines) < 0) {
  663. log_warn(LD_CONTROL,"Controller gave us config lines we can't parse.");
  664. connection_write_str_to_buf("551 Couldn't parse configuration\r\n",
  665. conn);
  666. tor_free(config);
  667. return 0;
  668. }
  669. tor_free(config);
  670. } else {
  671. if (config_get_lines(body, &lines) < 0) {
  672. log_warn(LD_CONTROL,"Controller gave us config lines we can't parse.");
  673. send_control0_error(conn, ERR_SYNTAX, "Couldn't parse configuration");
  674. return 0;
  675. }
  676. }
  677. if ((r=options_trial_assign(lines, use_defaults,
  678. clear_first, &errstring)) < 0) {
  679. int v0_err;
  680. const char *msg;
  681. log_warn(LD_CONTROL,
  682. "Controller gave us config lines that didn't validate: %s.",
  683. errstring);
  684. switch (r) {
  685. case -1:
  686. v0_err = ERR_UNRECOGNIZED_CONFIG_KEY;
  687. msg = "552 Unrecognized option";
  688. break;
  689. case -2:
  690. v0_err = ERR_INVALID_CONFIG_VALUE;
  691. msg = "513 Unacceptable option value";
  692. break;
  693. case -3:
  694. v0_err = ERR_INVALID_CONFIG_VALUE;
  695. msg = "553 Transition not allowed";
  696. break;
  697. case -4:
  698. default:
  699. v0_err = ERR_INVALID_CONFIG_VALUE;
  700. msg = "553 Unable to set option";
  701. break;
  702. }
  703. if (v0) {
  704. send_control0_error(conn, v0_err, msg);
  705. } else {
  706. connection_printf_to_buf(conn, "%s: %s\r\n", msg, errstring);
  707. }
  708. config_free_lines(lines);
  709. tor_free(errstring);
  710. return 0;
  711. }
  712. config_free_lines(lines);
  713. send_control_done(conn);
  714. return 0;
  715. }
  716. /** Called when we receive a SETCONF message: parse the body and try
  717. * to update our configuration. Reply with a DONE or ERROR message. */
  718. static int
  719. handle_control_setconf(control_connection_t *conn, uint32_t len, char *body)
  720. {
  721. return control_setconf_helper(conn, len, body, 0, 1);
  722. }
  723. /** Called when we receive a RESETCONF message: parse the body and try
  724. * to update our configuration. Reply with a DONE or ERROR message. */
  725. static int
  726. handle_control_resetconf(control_connection_t *conn, uint32_t len, char *body)
  727. {
  728. int v0 = STATE_IS_V0(conn->_base.state);
  729. tor_assert(!v0);
  730. return control_setconf_helper(conn, len, body, 1, 1);
  731. }
  732. /** Called when we receive a GETCONF message. Parse the request, and
  733. * reply with a CONFVALUE or an ERROR message */
  734. static int
  735. handle_control_getconf(control_connection_t *conn, uint32_t body_len,
  736. const char *body)
  737. {
  738. smartlist_t *questions = NULL;
  739. smartlist_t *answers = NULL;
  740. smartlist_t *unrecognized = NULL;
  741. char *msg = NULL;
  742. size_t msg_len;
  743. or_options_t *options = get_options();
  744. int v0 = STATE_IS_V0(conn->_base.state);
  745. questions = smartlist_create();
  746. (void) body_len; /* body is nul-terminated; so we can ignore len. */
  747. if (v0) {
  748. smartlist_split_string(questions, body, "\n",
  749. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  750. } else {
  751. smartlist_split_string(questions, body, " ",
  752. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  753. }
  754. answers = smartlist_create();
  755. unrecognized = smartlist_create();
  756. SMARTLIST_FOREACH(questions, char *, q,
  757. {
  758. if (!option_is_recognized(q)) {
  759. if (v0) {
  760. send_control0_error(conn, ERR_UNRECOGNIZED_CONFIG_KEY, q);
  761. goto done;
  762. } else {
  763. smartlist_add(unrecognized, q);
  764. }
  765. } else {
  766. config_line_t *answer = option_get_assignment(options,q);
  767. if (!v0 && !answer) {
  768. const char *name = option_get_canonical_name(q);
  769. size_t alen = strlen(name)+8;
  770. char *astr = tor_malloc(alen);
  771. tor_snprintf(astr, alen, "250-%s\r\n", name);
  772. smartlist_add(answers, astr);
  773. }
  774. while (answer) {
  775. config_line_t *next;
  776. size_t alen = strlen(answer->key)+strlen(answer->value)+8;
  777. char *astr = tor_malloc(alen);
  778. if (v0)
  779. tor_snprintf(astr, alen, "%s %s\n", answer->key, answer->value);
  780. else
  781. tor_snprintf(astr, alen, "250-%s=%s\r\n",
  782. answer->key, answer->value);
  783. smartlist_add(answers, astr);
  784. next = answer->next;
  785. tor_free(answer->key);
  786. tor_free(answer->value);
  787. tor_free(answer);
  788. answer = next;
  789. }
  790. }
  791. });
  792. if (v0) {
  793. msg = smartlist_join_strings(answers, "", 0, &msg_len);
  794. send_control0_message(conn, CONTROL0_CMD_CONFVALUE,
  795. (uint16_t)msg_len, msg_len?msg:NULL);
  796. } else {
  797. int i,len;
  798. if ((len = smartlist_len(unrecognized))) {
  799. for (i=0; i < len-1; ++i)
  800. connection_printf_to_buf(conn,
  801. "552-Unrecognized configuration key \"%s\"\r\n",
  802. (char*)smartlist_get(unrecognized, i));
  803. connection_printf_to_buf(conn,
  804. "552 Unrecognized configuration key \"%s\"\r\n",
  805. (char*)smartlist_get(unrecognized, len-1));
  806. } else if ((len = smartlist_len(answers))) {
  807. char *tmp = smartlist_get(answers, len-1);
  808. tor_assert(strlen(tmp)>4);
  809. tmp[3] = ' ';
  810. msg = smartlist_join_strings(answers, "", 0, &msg_len);
  811. connection_write_to_buf(msg, msg_len, TO_CONN(conn));
  812. } else {
  813. connection_write_str_to_buf("250 OK\r\n", conn);
  814. }
  815. }
  816. done:
  817. if (answers) {
  818. SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
  819. smartlist_free(answers);
  820. }
  821. if (questions) {
  822. SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
  823. smartlist_free(questions);
  824. }
  825. smartlist_free(unrecognized);
  826. tor_free(msg);
  827. return 0;
  828. }
  829. /** Called when we get a SETEVENTS message: update conn->event_mask,
  830. * and reply with DONE or ERROR. */
  831. static int
  832. handle_control_setevents(control_connection_t *conn, uint32_t len,
  833. const char *body)
  834. {
  835. uint16_t event_code;
  836. uint32_t event_mask = 0;
  837. unsigned int extended = 0;
  838. if (STATE_IS_V0(conn->_base.state)) {
  839. if (len % 2) {
  840. send_control0_error(conn, ERR_SYNTAX,
  841. "Odd number of bytes in setevents message");
  842. return 0;
  843. }
  844. for (; len; len -= 2, body += 2) {
  845. event_code = ntohs(get_uint16(body));
  846. if (event_code < _EVENT_MIN || event_code > LAST_V0_EVENT) {
  847. send_control0_error(conn, ERR_UNRECOGNIZED_EVENT_CODE,
  848. "Unrecognized event code");
  849. return 0;
  850. }
  851. event_mask |= (1 << event_code);
  852. }
  853. } else {
  854. smartlist_t *events = smartlist_create();
  855. smartlist_split_string(events, body, " ",
  856. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  857. SMARTLIST_FOREACH(events, const char *, ev,
  858. {
  859. if (!strcasecmp(ev, "EXTENDED")) {
  860. extended = 1;
  861. continue;
  862. } else if (!strcasecmp(ev, "CIRC"))
  863. event_code = EVENT_CIRCUIT_STATUS;
  864. else if (!strcasecmp(ev, "STREAM"))
  865. event_code = EVENT_STREAM_STATUS;
  866. else if (!strcasecmp(ev, "ORCONN"))
  867. event_code = EVENT_OR_CONN_STATUS;
  868. else if (!strcasecmp(ev, "BW"))
  869. event_code = EVENT_BANDWIDTH_USED;
  870. else if (!strcasecmp(ev, "DEBUG"))
  871. event_code = EVENT_DEBUG_MSG;
  872. else if (!strcasecmp(ev, "INFO"))
  873. event_code = EVENT_INFO_MSG;
  874. else if (!strcasecmp(ev, "NOTICE"))
  875. event_code = EVENT_NOTICE_MSG;
  876. else if (!strcasecmp(ev, "WARN"))
  877. event_code = EVENT_WARN_MSG;
  878. else if (!strcasecmp(ev, "ERR"))
  879. event_code = EVENT_ERR_MSG;
  880. else if (!strcasecmp(ev, "NEWDESC"))
  881. event_code = EVENT_NEW_DESC;
  882. else if (!strcasecmp(ev, "ADDRMAP"))
  883. event_code = EVENT_ADDRMAP;
  884. else if (!strcasecmp(ev, "AUTHDIR_NEWDESCS"))
  885. event_code = EVENT_AUTHDIR_NEWDESCS;
  886. else {
  887. connection_printf_to_buf(conn, "552 Unrecognized event \"%s\"\r\n",
  888. ev);
  889. SMARTLIST_FOREACH(events, char *, e, tor_free(e));
  890. smartlist_free(events);
  891. return 0;
  892. }
  893. event_mask |= (1 << event_code);
  894. });
  895. SMARTLIST_FOREACH(events, char *, e, tor_free(e));
  896. smartlist_free(events);
  897. }
  898. conn->event_mask = event_mask;
  899. conn->_base.control_events_are_extended = extended;
  900. control_update_global_event_mask();
  901. send_control_done(conn);
  902. return 0;
  903. }
  904. /** Decode the hashed, base64'd password stored in <b>hashed</b>. If
  905. * <b>buf</b> is provided, store the hashed password in the first
  906. * S2K_SPECIFIER_LEN+DIGEST_LEN bytes of <b>buf</b>. Return 0 on
  907. * success, -1 on failure.
  908. */
  909. int
  910. decode_hashed_password(char *buf, const char *hashed)
  911. {
  912. char decoded[64];
  913. if (!strcmpstart(hashed, "16:")) {
  914. if (base16_decode(decoded, sizeof(decoded), hashed+3, strlen(hashed+3))<0
  915. || strlen(hashed+3) != (S2K_SPECIFIER_LEN+DIGEST_LEN)*2) {
  916. return -1;
  917. }
  918. } else {
  919. if (base64_decode(decoded, sizeof(decoded), hashed, strlen(hashed))
  920. != S2K_SPECIFIER_LEN+DIGEST_LEN) {
  921. return -1;
  922. }
  923. }
  924. if (buf)
  925. memcpy(buf, decoded, S2K_SPECIFIER_LEN+DIGEST_LEN);
  926. return 0;
  927. }
  928. /** Called when we get an AUTHENTICATE message. Check whether the
  929. * authentication is valid, and if so, update the connection's state to
  930. * OPEN. Reply with DONE or ERROR.
  931. */
  932. static int
  933. handle_control_authenticate(control_connection_t *conn, uint32_t len,
  934. const char *body)
  935. {
  936. int used_quoted_string = 0;
  937. or_options_t *options = get_options();
  938. char *password;
  939. size_t password_len;
  940. if (STATE_IS_V0(conn->_base.state)) {
  941. password = (char*)body;
  942. password_len = len;
  943. } else {
  944. if (TOR_ISXDIGIT(body[0])) {
  945. int i = 0;
  946. while (TOR_ISXDIGIT(body[i]))
  947. ++i;
  948. password = tor_malloc(i/2 + 1);
  949. if (base16_decode(password, i/2+1, body, i)<0) {
  950. connection_write_str_to_buf(
  951. "551 Invalid hexadecimal encoding. Maybe you tried a plain text "
  952. "password? If so, the standard requires you put it in double "
  953. "quotes.\r\n", conn);
  954. tor_free(password);
  955. return 0;
  956. }
  957. password_len = i/2;
  958. } else if (TOR_ISSPACE(body[0])) {
  959. password = tor_strdup("");
  960. password_len = 0;
  961. } else {
  962. if (!get_escaped_string(body, len, &password, &password_len)) {
  963. connection_write_str_to_buf("551 Invalid quoted string. You need "
  964. "to put the password in double quotes.\r\n", conn);
  965. return 0;
  966. }
  967. used_quoted_string = 1;
  968. }
  969. }
  970. if (options->CookieAuthentication) {
  971. if (password_len == AUTHENTICATION_COOKIE_LEN &&
  972. !memcmp(authentication_cookie, password, password_len)) {
  973. goto ok;
  974. }
  975. } else if (options->HashedControlPassword) {
  976. char expected[S2K_SPECIFIER_LEN+DIGEST_LEN];
  977. char received[DIGEST_LEN];
  978. if (decode_hashed_password(expected, options->HashedControlPassword)<0) {
  979. log_warn(LD_CONTROL,
  980. "Couldn't decode HashedControlPassword: invalid base16");
  981. goto err;
  982. }
  983. secret_to_key(received,DIGEST_LEN,password,password_len,expected);
  984. if (!memcmp(expected+S2K_SPECIFIER_LEN, received, DIGEST_LEN))
  985. goto ok;
  986. goto err;
  987. } else {
  988. /* if Tor doesn't demand any stronger authentication, then
  989. * the controller can get in with anything. */
  990. goto ok;
  991. }
  992. err:
  993. if (STATE_IS_V0(conn->_base.state))
  994. send_control0_error(conn,ERR_REJECTED_AUTHENTICATION,
  995. "Authentication failed");
  996. else {
  997. tor_free(password);
  998. if (used_quoted_string)
  999. connection_write_str_to_buf("515 Authentication failed\r\n", conn);
  1000. else
  1001. connection_write_str_to_buf(
  1002. "515 Authentication failed. Maybe you tried a plain text password? "
  1003. "If so, the standard requires you put it in double quotes.\r\n",conn);
  1004. }
  1005. return 0;
  1006. ok:
  1007. log_info(LD_CONTROL, "Authenticated control connection (%d)", conn->_base.s);
  1008. send_control_done(conn);
  1009. if (STATE_IS_V0(conn->_base.state))
  1010. conn->_base.state = CONTROL_CONN_STATE_OPEN_V0;
  1011. else {
  1012. conn->_base.state = CONTROL_CONN_STATE_OPEN_V1;
  1013. tor_free(password);
  1014. }
  1015. return 0;
  1016. }
  1017. /** Called when we get a SAVECONF command. Try to flush the current options to
  1018. * disk, and report success or failure. */
  1019. static int
  1020. handle_control_saveconf(control_connection_t *conn, uint32_t len,
  1021. const char *body)
  1022. {
  1023. (void) len;
  1024. (void) body;
  1025. if (options_save_current()<0) {
  1026. if (STATE_IS_V0(conn->_base.state))
  1027. send_control0_error(conn, ERR_INTERNAL,
  1028. "Unable to write configuration to disk.");
  1029. else
  1030. connection_write_str_to_buf(
  1031. "551 Unable to write configuration to disk.\r\n", conn);
  1032. } else {
  1033. send_control_done(conn);
  1034. }
  1035. return 0;
  1036. }
  1037. /** Called when we get a SIGNAL command. React to the provided signal, and
  1038. * report success or failure. (If the signal results in a shutdown, success
  1039. * may not be reported.) */
  1040. static int
  1041. handle_control_signal(control_connection_t *conn, uint32_t len,
  1042. const char *body)
  1043. {
  1044. int sig;
  1045. if (STATE_IS_V0(conn->_base.state)) {
  1046. if (len != 1) {
  1047. send_control0_error(conn, ERR_SYNTAX,
  1048. "Body of SIGNAL command too long or too short.");
  1049. return 0;
  1050. } else {
  1051. sig = (uint8_t)body[0];
  1052. }
  1053. } else {
  1054. int n = 0;
  1055. char *s;
  1056. while (body[n] && ! TOR_ISSPACE(body[n]))
  1057. ++n;
  1058. s = tor_strndup(body, n);
  1059. if (!strcasecmp(s, "RELOAD") || !strcasecmp(s, "HUP"))
  1060. sig = SIGHUP;
  1061. else if (!strcasecmp(s, "SHUTDOWN") || !strcasecmp(s, "INT"))
  1062. sig = SIGINT;
  1063. else if (!strcasecmp(s, "DUMP") || !strcasecmp(s, "USR1"))
  1064. sig = SIGUSR1;
  1065. else if (!strcasecmp(s, "DEBUG") || !strcasecmp(s, "USR2"))
  1066. sig = SIGUSR2;
  1067. else if (!strcasecmp(s, "HALT") || !strcasecmp(s, "TERM"))
  1068. sig = SIGTERM;
  1069. else if (!strcasecmp(s, "NEWNYM"))
  1070. sig = SIGNEWNYM;
  1071. else {
  1072. connection_printf_to_buf(conn, "552 Unrecognized signal code \"%s\"\r\n",
  1073. s);
  1074. sig = -1;
  1075. }
  1076. tor_free(s);
  1077. if (sig<0)
  1078. return 0;
  1079. }
  1080. if (control_signal_act(sig) < 0) {
  1081. if (STATE_IS_V0(conn->_base.state))
  1082. send_control0_error(conn, ERR_SYNTAX, "Unrecognized signal number.");
  1083. else
  1084. connection_write_str_to_buf("551 Internal error acting on signal\r\n",
  1085. conn);
  1086. } else {
  1087. send_control_done(conn);
  1088. }
  1089. return 0;
  1090. }
  1091. /** Called when we get a MAPADDRESS command; try to bind all listed addresses,
  1092. * and report success or failrue. */
  1093. static int
  1094. handle_control_mapaddress(control_connection_t *conn, uint32_t len,
  1095. const char *body)
  1096. {
  1097. smartlist_t *elts;
  1098. smartlist_t *lines;
  1099. smartlist_t *reply;
  1100. char *r;
  1101. size_t sz;
  1102. int v0 = STATE_IS_V0(conn->_base.state);
  1103. (void) len; /* body is nul-terminated, so it's safe to ignore the length. */
  1104. lines = smartlist_create();
  1105. elts = smartlist_create();
  1106. reply = smartlist_create();
  1107. if (v0)
  1108. smartlist_split_string(lines, body, "\n",
  1109. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1110. else
  1111. smartlist_split_string(lines, body, " ",
  1112. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1113. SMARTLIST_FOREACH(lines, char *, line,
  1114. {
  1115. tor_strlower(line);
  1116. if (v0)
  1117. smartlist_split_string(elts, line, " ", 0, 2);
  1118. else
  1119. smartlist_split_string(elts, line, "=", 0, 2);
  1120. if (smartlist_len(elts) == 2) {
  1121. const char *from = smartlist_get(elts,0);
  1122. const char *to = smartlist_get(elts,1);
  1123. size_t anslen = strlen(line)+512;
  1124. char *ans = tor_malloc(anslen);
  1125. if (!is_plausible_address(from)) {
  1126. if (!v0) {
  1127. tor_snprintf(ans, anslen,
  1128. "512-syntax error: invalid address '%s'", from);
  1129. smartlist_add(reply, ans);
  1130. } else
  1131. tor_free(ans); /* don't respond if v0 */
  1132. log_warn(LD_CONTROL,
  1133. "Skipping invalid argument '%s' in MapAddress msg",
  1134. from);
  1135. } else if (!is_plausible_address(to)) {
  1136. if (!v0) {
  1137. tor_snprintf(ans, anslen,
  1138. "512-syntax error: invalid address '%s'", to);
  1139. smartlist_add(reply, ans);
  1140. } else
  1141. tor_free(ans); /* don't respond if v0 */
  1142. log_warn(LD_CONTROL,
  1143. "Skipping invalid argument '%s' in MapAddress msg", to);
  1144. } else if (!strcmp(from, ".") || !strcmp(from, "0.0.0.0")) {
  1145. const char *address = addressmap_register_virtual_address(
  1146. !strcmp(from,".") ? RESOLVED_TYPE_HOSTNAME : RESOLVED_TYPE_IPV4,
  1147. tor_strdup(to));
  1148. if (!address) {
  1149. if (!v0) {
  1150. tor_snprintf(ans, anslen,
  1151. "451-resource exhausted: skipping '%s'", line);
  1152. smartlist_add(reply, ans);
  1153. } else
  1154. tor_free(ans); /* don't respond if v0 */
  1155. log_warn(LD_CONTROL,
  1156. "Unable to allocate address for '%s' in MapAddress msg",
  1157. safe_str(line));
  1158. } else {
  1159. if (v0)
  1160. tor_snprintf(ans, anslen, "%s %s", address, to);
  1161. else
  1162. tor_snprintf(ans, anslen, "250-%s=%s", address, to);
  1163. smartlist_add(reply, ans);
  1164. }
  1165. } else {
  1166. addressmap_register(from, tor_strdup(to), 1);
  1167. if (v0)
  1168. tor_snprintf(ans, anslen, "%s", line);
  1169. else
  1170. tor_snprintf(ans, anslen, "250-%s", line);
  1171. smartlist_add(reply, ans);
  1172. }
  1173. } else {
  1174. if (!v0) {
  1175. size_t anslen = strlen(line)+256;
  1176. char *ans = tor_malloc(anslen);
  1177. tor_snprintf(ans, anslen, "512-syntax error: mapping '%s' is "
  1178. "not of expected form 'foo=bar'.", line);
  1179. smartlist_add(reply, ans);
  1180. }
  1181. log_info(LD_CONTROL, "Skipping MapAddress '%s': wrong "
  1182. "number of items.", safe_str(line));
  1183. }
  1184. SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
  1185. smartlist_clear(elts);
  1186. });
  1187. SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
  1188. smartlist_free(lines);
  1189. smartlist_free(elts);
  1190. if (v0) {
  1191. r = smartlist_join_strings(reply, "\n", 1, &sz);
  1192. send_control_done2(conn,r,sz);
  1193. tor_free(r);
  1194. } else {
  1195. if (smartlist_len(reply)) {
  1196. ((char*)smartlist_get(reply,smartlist_len(reply)-1))[3] = ' ';
  1197. r = smartlist_join_strings(reply, "\r\n", 1, &sz);
  1198. connection_write_to_buf(r, sz, TO_CONN(conn));
  1199. tor_free(r);
  1200. } else {
  1201. const char *response =
  1202. "512 syntax error: not enough arguments to mapaddress.\r\n";
  1203. connection_write_to_buf(response, strlen(response), TO_CONN(conn));
  1204. }
  1205. }
  1206. SMARTLIST_FOREACH(reply, char *, cp, tor_free(cp));
  1207. smartlist_free(reply);
  1208. return 0;
  1209. }
  1210. /** Return a newly allocated string listing all valid GETINFO fields as
  1211. * required by GETINFO info/names. */
  1212. static char *
  1213. list_getinfo_options(void)
  1214. {
  1215. return tor_strdup(
  1216. "accounting/bytes Number of bytes read/written so far in interval.\n"
  1217. "accounting/bytes-left Number of bytes left to read/write in interval.\n"
  1218. "accounting/enabled Is accounting currently enabled?\n"
  1219. "accounting/hibernating Are we hibernating or awake?\n"
  1220. "accounting/interval-end Time when interval ends.\n"
  1221. "accounting/interval-start Time when interval starts.\n"
  1222. "accounting/interval-wake Time to wake up in this interval.\n"
  1223. "addr-mappings/all All current remapped addresses.\n"
  1224. "addr-mappings/cache Addresses remapped by DNS cache.\n"
  1225. "addr-mappings/configl Addresses remapped from configuration options.\n"
  1226. "addr-mappings/control Addresses remapped by a controller.\n"
  1227. "circuit-status Status of each current circuit.\n"
  1228. "config-file Current location of the \"torrc\" file.\n"
  1229. "config/names List of configuration options, types, and documentation.\n"
  1230. "desc/id/* Server descriptor by hex ID\n"
  1231. "desc/name/* Server descriptor by nickname.\n"
  1232. "desc/all-recent Latest server descriptor for every router\n"
  1233. "dir/server/* Fetch server descriptors -- see dir-spec.txt\n"
  1234. "entry-guards Which nodes will we use as entry guards?\n"
  1235. "exit-policy/default Default lines appended to config->ExitPolicy\n"
  1236. "info/names List of GETINFO options, types, and documentation.\n"
  1237. "network-status List of hex IDs, nicknames, server statuses.\n"
  1238. "orconn-status Status of each current OR connection.\n"
  1239. "stream-status Status of each current application stream.\n"
  1240. "version The current version of Tor.\n");
  1241. }
  1242. /** Lookup the 'getinfo' entry <b>question</b>, and return
  1243. * the answer in <b>*answer</b> (or NULL if key not recognized).
  1244. * Return 0 if success, or -1 if internal error. */
  1245. static int
  1246. handle_getinfo_helper(const char *question, char **answer)
  1247. {
  1248. *answer = NULL; /* unrecognized key by default */
  1249. if (!strcmp(question, "version")) {
  1250. *answer = tor_strdup(VERSION);
  1251. } else if (!strcmp(question, "config-file")) {
  1252. *answer = tor_strdup(get_torrc_fname());
  1253. } else if (!strcmpstart(question, "accounting/")) {
  1254. return accounting_getinfo_helper(question, answer);
  1255. } else if (!strcmpstart(question, "helper-nodes")) { /* deprecated */
  1256. return entry_guards_getinfo(question, answer);
  1257. } else if (!strcmpstart(question, "entry-guards")) {
  1258. return entry_guards_getinfo(question, answer);
  1259. } else if (!strcmpstart(question, "config/")) {
  1260. return config_getinfo_helper(question, answer);
  1261. } else if (!strcmp(question, "info/names")) {
  1262. *answer = list_getinfo_options();
  1263. } else if (!strcmpstart(question, "desc/id/")) {
  1264. routerinfo_t *ri = router_get_by_hexdigest(question+strlen("desc/id/"));
  1265. if (ri) {
  1266. const char *body = signed_descriptor_get_body(&ri->cache_info);
  1267. if (body)
  1268. *answer = tor_strndup(body, ri->cache_info.signed_descriptor_len);
  1269. }
  1270. } else if (!strcmpstart(question, "desc/name/")) {
  1271. routerinfo_t *ri = router_get_by_nickname(question+strlen("desc/name/"),1);
  1272. if (ri) {
  1273. const char *body = signed_descriptor_get_body(&ri->cache_info);
  1274. if (body)
  1275. *answer = tor_strndup(body, ri->cache_info.signed_descriptor_len);
  1276. }
  1277. } else if (!strcmp(question, "desc/all-recent")) {
  1278. routerlist_t *routerlist = router_get_routerlist();
  1279. smartlist_t *sl = smartlist_create();
  1280. if (routerlist && routerlist->routers) {
  1281. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, ri,
  1282. {
  1283. const char *body = signed_descriptor_get_body(&ri->cache_info);
  1284. if (body)
  1285. smartlist_add(sl,
  1286. tor_strndup(body, ri->cache_info.signed_descriptor_len));
  1287. });
  1288. }
  1289. *answer = smartlist_join_strings(sl, "", 0, NULL);
  1290. SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  1291. smartlist_free(sl);
  1292. } else if (!strcmpstart(question, "unregistered-servers-")) {
  1293. *answer = dirserver_getinfo_unregistered(question +
  1294. strlen("unregistered-servers-"));
  1295. } else if (!strcmp(question, "network-status")) {
  1296. routerlist_t *routerlist = router_get_routerlist();
  1297. if (!routerlist || !routerlist->routers ||
  1298. list_server_status(routerlist->routers, answer) < 0) {
  1299. return -1;
  1300. }
  1301. } else if (!strcmp(question, "circuit-status")) {
  1302. circuit_t *circ;
  1303. smartlist_t *status = smartlist_create();
  1304. for (circ = _circuit_get_global_list(); circ; circ = circ->next) {
  1305. char *s, *path;
  1306. size_t slen;
  1307. const char *state;
  1308. if (! CIRCUIT_IS_ORIGIN(circ) || circ->marked_for_close)
  1309. continue;
  1310. path = circuit_list_path(TO_ORIGIN_CIRCUIT(circ),0);
  1311. if (circ->state == CIRCUIT_STATE_OPEN)
  1312. state = "BUILT";
  1313. else if (strlen(path))
  1314. state = "EXTENDED";
  1315. else
  1316. state = "LAUNCHED";
  1317. slen = strlen(path)+strlen(state)+20;
  1318. s = tor_malloc(slen+1);
  1319. tor_snprintf(s, slen, "%lu %s %s",
  1320. (unsigned long)TO_ORIGIN_CIRCUIT(circ)->global_identifier,
  1321. state, path);
  1322. smartlist_add(status, s);
  1323. tor_free(path);
  1324. }
  1325. *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
  1326. SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
  1327. smartlist_free(status);
  1328. } else if (!strcmp(question, "stream-status")) {
  1329. connection_t **conns;
  1330. int n_conns, i;
  1331. char buf[256];
  1332. smartlist_t *status = smartlist_create();
  1333. get_connection_array(&conns, &n_conns);
  1334. for (i=0; i < n_conns; ++i) {
  1335. const char *state;
  1336. edge_connection_t *conn;
  1337. char *s;
  1338. size_t slen;
  1339. circuit_t *circ;
  1340. origin_circuit_t *origin_circ = NULL;
  1341. if (conns[i]->type != CONN_TYPE_AP ||
  1342. conns[i]->marked_for_close ||
  1343. conns[i]->state == AP_CONN_STATE_SOCKS_WAIT ||
  1344. conns[i]->state == AP_CONN_STATE_ORIGDST_WAIT)
  1345. continue;
  1346. conn = TO_EDGE_CONN(conns[i]);
  1347. switch (conn->_base.state)
  1348. {
  1349. case AP_CONN_STATE_CONTROLLER_WAIT:
  1350. case AP_CONN_STATE_CIRCUIT_WAIT:
  1351. if (conn->socks_request &&
  1352. conn->socks_request->command == SOCKS_COMMAND_RESOLVE)
  1353. state = "NEWRESOLVE";
  1354. else
  1355. state = "NEW";
  1356. break;
  1357. case AP_CONN_STATE_RENDDESC_WAIT:
  1358. case AP_CONN_STATE_CONNECT_WAIT:
  1359. state = "SENTCONNECT"; break;
  1360. case AP_CONN_STATE_RESOLVE_WAIT:
  1361. state = "SENTRESOLVE"; break;
  1362. case AP_CONN_STATE_OPEN:
  1363. state = "SUCCEEDED"; break;
  1364. default:
  1365. log_warn(LD_BUG, "Asked for stream in unknown state %d",
  1366. conn->_base.state);
  1367. continue;
  1368. }
  1369. circ = circuit_get_by_edge_conn(conn);
  1370. if (CIRCUIT_IS_ORIGIN(circ))
  1371. origin_circ = TO_ORIGIN_CIRCUIT(circ);
  1372. write_stream_target_to_buf(conn, buf, sizeof(buf));
  1373. slen = strlen(buf)+strlen(state)+32;
  1374. s = tor_malloc(slen+1);
  1375. tor_snprintf(s, slen, "%lu %s %lu %s",
  1376. (unsigned long) conn->global_identifier,state,
  1377. origin_circ?
  1378. (unsigned long)origin_circ->global_identifier : 0ul,
  1379. buf);
  1380. smartlist_add(status, s);
  1381. }
  1382. *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
  1383. SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
  1384. smartlist_free(status);
  1385. } else if (!strcmp(question, "orconn-status")) {
  1386. connection_t **conns;
  1387. int n_conns, i;
  1388. smartlist_t *status = smartlist_create();
  1389. get_connection_array(&conns, &n_conns);
  1390. for (i=0; i < n_conns; ++i) {
  1391. const char *state;
  1392. char *s;
  1393. char name[128];
  1394. size_t slen;
  1395. or_connection_t *conn;
  1396. if (conns[i]->type != CONN_TYPE_OR || conns[i]->marked_for_close)
  1397. continue;
  1398. conn = TO_OR_CONN(conns[i]);
  1399. if (conn->_base.state == OR_CONN_STATE_OPEN)
  1400. state = "CONNECTED";
  1401. else if (conn->nickname)
  1402. state = "LAUNCHED";
  1403. else
  1404. state = "NEW";
  1405. if (conn->nickname)
  1406. strlcpy(name, conn->nickname, sizeof(name));
  1407. else
  1408. tor_snprintf(name, sizeof(name), "%s:%d",
  1409. conn->_base.address, conn->_base.port);
  1410. slen = strlen(name)+strlen(state)+2;
  1411. s = tor_malloc(slen+1);
  1412. tor_snprintf(s, slen, "%s %s", name, state);
  1413. smartlist_add(status, s);
  1414. }
  1415. *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
  1416. SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
  1417. smartlist_free(status);
  1418. } else if (!strcmpstart(question, "addr-mappings/")) {
  1419. time_t min_e, max_e;
  1420. smartlist_t *mappings;
  1421. if (!strcmp(question, "addr-mappings/all")) {
  1422. min_e = 0; max_e = TIME_MAX;
  1423. } else if (!strcmp(question, "addr-mappings/cache")) {
  1424. min_e = 2; max_e = TIME_MAX;
  1425. } else if (!strcmp(question, "addr-mappings/config")) {
  1426. min_e = 0; max_e = 0;
  1427. } else if (!strcmp(question, "addr-mappings/control")) {
  1428. min_e = 1; max_e = 1;
  1429. } else {
  1430. return 0;
  1431. }
  1432. mappings = smartlist_create();
  1433. addressmap_get_mappings(mappings, min_e, max_e);
  1434. *answer = smartlist_join_strings(mappings, "\n", 0, NULL);
  1435. SMARTLIST_FOREACH(mappings, char *, cp, tor_free(cp));
  1436. smartlist_free(mappings);
  1437. } else if (!strcmp(question, "dir-usage")) {
  1438. *answer = directory_dump_request_log();
  1439. } else if (!strcmpstart(question, "dir/server/")) {
  1440. size_t answer_len = 0, url_len = strlen(question)+2;
  1441. char *url = tor_malloc(url_len);
  1442. int res;
  1443. smartlist_t *descs = smartlist_create();
  1444. const char *msg;
  1445. char *cp;
  1446. tor_snprintf(url, url_len, "/tor/%s", question+4);
  1447. res = dirserv_get_routerdescs(descs, url, &msg);
  1448. SMARTLIST_FOREACH(descs, signed_descriptor_t *, sd,
  1449. answer_len += sd->signed_descriptor_len);
  1450. cp = *answer = tor_malloc(answer_len+1);
  1451. SMARTLIST_FOREACH(descs, signed_descriptor_t *, sd,
  1452. {
  1453. memcpy(cp, signed_descriptor_get_body(sd),
  1454. sd->signed_descriptor_len);
  1455. cp += sd->signed_descriptor_len;
  1456. });
  1457. *cp = '\0';
  1458. tor_free(url);
  1459. smartlist_free(descs);
  1460. } else if (!strcmpstart(question, "dir/status/")) {
  1461. smartlist_t *status_list;
  1462. size_t len;
  1463. char *cp;
  1464. if (!get_options()->DirPort) {
  1465. log_warn(LD_CONTROL, "getinfo dir/status/ requires an open dirport.");
  1466. return 0;
  1467. }
  1468. status_list = smartlist_create();
  1469. dirserv_get_networkstatus_v2(status_list,
  1470. question+strlen("dir/status/"));
  1471. len = 0;
  1472. SMARTLIST_FOREACH(status_list, cached_dir_t *, d, len += d->dir_len);
  1473. cp = *answer = tor_malloc(len+1);
  1474. SMARTLIST_FOREACH(status_list, cached_dir_t *, d, {
  1475. memcpy(cp, d->dir, d->dir_len);
  1476. cp += d->dir_len;
  1477. });
  1478. *cp = '\0';
  1479. } else if (!strcmpstart(question, "exit-policy/")) {
  1480. return policies_getinfo_helper(question, answer);
  1481. }
  1482. return 0;
  1483. }
  1484. /** Called when we receive a GETINFO command. Try to fetch all requested
  1485. * information, and reply with information or error message. */
  1486. static int
  1487. handle_control_getinfo(control_connection_t *conn, uint32_t len,
  1488. const char *body)
  1489. {
  1490. smartlist_t *questions = NULL;
  1491. smartlist_t *answers = NULL;
  1492. smartlist_t *unrecognized = NULL;
  1493. char *msg = NULL, *ans = NULL;
  1494. size_t msg_len;
  1495. int v0 = STATE_IS_V0(conn->_base.state);
  1496. (void) len; /* body is nul-terminated, so it's safe to ignore the length. */
  1497. questions = smartlist_create();
  1498. if (v0)
  1499. smartlist_split_string(questions, body, "\n",
  1500. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1501. else
  1502. smartlist_split_string(questions, body, " ",
  1503. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1504. answers = smartlist_create();
  1505. unrecognized = smartlist_create();
  1506. SMARTLIST_FOREACH(questions, const char *, q,
  1507. {
  1508. if (handle_getinfo_helper(q, &ans) < 0) {
  1509. if (v0)
  1510. send_control0_error(conn, ERR_INTERNAL, body);
  1511. else
  1512. connection_write_str_to_buf("551 Internal error\r\n", conn);
  1513. goto done;
  1514. }
  1515. if (!ans) {
  1516. if (v0) {
  1517. send_control0_error(conn, ERR_UNRECOGNIZED_CONFIG_KEY, body);
  1518. goto done;
  1519. } else
  1520. smartlist_add(unrecognized, (char*)q);
  1521. } else {
  1522. smartlist_add(answers, tor_strdup(q));
  1523. smartlist_add(answers, ans);
  1524. }
  1525. });
  1526. if (smartlist_len(unrecognized)) {
  1527. int i;
  1528. tor_assert(!v0);
  1529. for (i=0; i < smartlist_len(unrecognized)-1; ++i)
  1530. connection_printf_to_buf(conn,
  1531. "552-Unrecognized key \"%s\"\r\n",
  1532. (char*)smartlist_get(unrecognized, i));
  1533. connection_printf_to_buf(conn,
  1534. "552 Unrecognized key \"%s\"\r\n",
  1535. (char*)smartlist_get(unrecognized, i));
  1536. goto done;
  1537. }
  1538. if (v0) {
  1539. msg = smartlist_join_strings2(answers, "\0", 1, 1, &msg_len);
  1540. tor_assert(msg_len > 0); /* it will at least be terminated */
  1541. send_control0_message(conn, CONTROL0_CMD_INFOVALUE,
  1542. msg_len, msg);
  1543. } else {
  1544. int i;
  1545. for (i = 0; i < smartlist_len(answers); i += 2) {
  1546. char *k = smartlist_get(answers, i);
  1547. char *v = smartlist_get(answers, i+1);
  1548. if (!strchr(v, '\n') && !strchr(v, '\r')) {
  1549. connection_printf_to_buf(conn, "250-%s=", k);
  1550. connection_write_str_to_buf(v, conn);
  1551. connection_write_str_to_buf("\r\n", conn);
  1552. } else {
  1553. char *esc = NULL;
  1554. size_t len;
  1555. len = write_escaped_data(v, strlen(v), 1, &esc);
  1556. connection_printf_to_buf(conn, "250+%s=\r\n", k);
  1557. connection_write_to_buf(esc, len, TO_CONN(conn));
  1558. tor_free(esc);
  1559. }
  1560. }
  1561. connection_write_str_to_buf("250 OK\r\n", conn);
  1562. }
  1563. done:
  1564. if (answers) {
  1565. SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
  1566. smartlist_free(answers);
  1567. }
  1568. if (questions) {
  1569. SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
  1570. smartlist_free(questions);
  1571. }
  1572. smartlist_free(unrecognized);
  1573. tor_free(msg);
  1574. return 0;
  1575. }
  1576. /** If <b>string</b> contains a recognized purpose (for
  1577. * circuits if <b>for_circuits</b> is 1, else for routers),
  1578. * possibly prefaced with the string "purpose=", then assign it
  1579. * and return 0. Otherwise return -1. */
  1580. static int
  1581. get_purpose(char *string, int for_circuits, uint8_t *purpose)
  1582. {
  1583. if (!strcmpstart(string, "purpose="))
  1584. string += strlen("purpose=");
  1585. if (!strcmp(string, "general"))
  1586. *purpose = for_circuits ? CIRCUIT_PURPOSE_C_GENERAL :
  1587. ROUTER_PURPOSE_GENERAL;
  1588. else if (!strcmp(string, "controller"))
  1589. *purpose = for_circuits ? CIRCUIT_PURPOSE_CONTROLLER :
  1590. ROUTER_PURPOSE_GENERAL;
  1591. else { /* not a recognized purpose */
  1592. return -1;
  1593. }
  1594. return 0;
  1595. }
  1596. /** Called when we get an EXTENDCIRCUIT message. Try to extend the listed
  1597. * circuit, and report success or failure. */
  1598. static int
  1599. handle_control_extendcircuit(control_connection_t *conn, uint32_t len,
  1600. const char *body)
  1601. {
  1602. smartlist_t *router_nicknames=NULL, *routers=NULL;
  1603. uint32_t circ_id;
  1604. origin_circuit_t *circ = NULL;
  1605. int zero_circ, v0;
  1606. char reply[4];
  1607. uint8_t intended_purpose = CIRCUIT_PURPOSE_C_GENERAL;
  1608. v0 = STATE_IS_V0(conn->_base.state);
  1609. router_nicknames = smartlist_create();
  1610. if (v0) {
  1611. if (len<5) {
  1612. send_control0_error(conn, ERR_SYNTAX, "extendcircuit message too short");
  1613. goto done;
  1614. }
  1615. smartlist_split_string(router_nicknames, body+4, ",", 0, 0);
  1616. circ_id = ntohl(get_uint32(body));
  1617. if (!circ_id) {
  1618. /* start a new circuit */
  1619. zero_circ = 1;
  1620. } else {
  1621. circ = circuit_get_by_global_id(circ_id);
  1622. zero_circ = 0;
  1623. if (!circ) {
  1624. send_control0_error(conn, ERR_NO_CIRC,
  1625. "No circuit found with given ID");
  1626. goto done;
  1627. }
  1628. }
  1629. } else { /* v1 */
  1630. smartlist_t *args;
  1631. args = smartlist_create();
  1632. smartlist_split_string(args, body, " ",
  1633. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1634. if (smartlist_len(args)<2) {
  1635. connection_printf_to_buf(conn,
  1636. "512 Missing argument to EXTENDCIRCUIT\r\n");
  1637. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1638. smartlist_free(args);
  1639. goto done;
  1640. }
  1641. zero_circ = !strcmp("0", (char*)smartlist_get(args,0));
  1642. if (!zero_circ && !(circ = get_circ(smartlist_get(args,0)))) {
  1643. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  1644. (char*)smartlist_get(args, 0));
  1645. }
  1646. smartlist_split_string(router_nicknames, smartlist_get(args,1), ",", 0, 0);
  1647. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1648. smartlist_free(args);
  1649. if (!zero_circ && !circ) {
  1650. goto done;
  1651. }
  1652. if (zero_circ && smartlist_len(args)>2) {
  1653. if (get_purpose(smartlist_get(args,2), 1, &intended_purpose) < 0) {
  1654. connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n",
  1655. (char *)smartlist_get(args,2));
  1656. goto done;
  1657. }
  1658. }
  1659. }
  1660. routers = smartlist_create();
  1661. SMARTLIST_FOREACH(router_nicknames, const char *, n,
  1662. {
  1663. routerinfo_t *r = router_get_by_nickname(n, 1);
  1664. if (!r) {
  1665. if (v0)
  1666. send_control0_error(conn, ERR_NO_ROUTER, n);
  1667. else
  1668. connection_printf_to_buf(conn, "552 No such router \"%s\"\r\n", n);
  1669. goto done;
  1670. }
  1671. smartlist_add(routers, r);
  1672. });
  1673. if (!smartlist_len(routers)) {
  1674. if (v0)
  1675. send_control0_error(conn, ERR_SYNTAX, "No router names provided");
  1676. else
  1677. connection_write_str_to_buf("512 No router names provided\r\n", conn);
  1678. goto done;
  1679. }
  1680. if (zero_circ) {
  1681. /* start a new circuit */
  1682. circ = origin_circuit_init(intended_purpose, 0, 0, 0);
  1683. }
  1684. /* now circ refers to something that is ready to be extended */
  1685. SMARTLIST_FOREACH(routers, routerinfo_t *, r,
  1686. {
  1687. extend_info_t *info = extend_info_from_router(r);
  1688. circuit_append_new_exit(circ, info);
  1689. extend_info_free(info);
  1690. });
  1691. /* now that we've populated the cpath, start extending */
  1692. if (zero_circ) {
  1693. if (circuit_handle_first_hop(circ) < 0) {
  1694. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_AT_ORIGIN);
  1695. if (v0)
  1696. send_control0_error(conn, ERR_INTERNAL, "couldn't start circuit");
  1697. else
  1698. connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn);
  1699. goto done;
  1700. }
  1701. } else {
  1702. if (circ->_base.state == CIRCUIT_STATE_OPEN) {
  1703. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
  1704. if (circuit_send_next_onion_skin(circ) < 0) {
  1705. log_info(LD_CONTROL,
  1706. "send_next_onion_skin failed; circuit marked for closing.");
  1707. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_AT_ORIGIN);
  1708. if (v0)
  1709. send_control0_error(conn, ERR_INTERNAL, "couldn't send onion skin");
  1710. else
  1711. connection_write_str_to_buf("551 Couldn't send onion skinr\n", conn);
  1712. goto done;
  1713. }
  1714. }
  1715. }
  1716. if (v0) {
  1717. set_uint32(reply, htonl(circ->global_identifier));
  1718. send_control_done2(conn, reply, sizeof(reply));
  1719. } else {
  1720. connection_printf_to_buf(conn, "250 EXTENDED %lu\r\n",
  1721. (unsigned long)circ->global_identifier);
  1722. }
  1723. done:
  1724. SMARTLIST_FOREACH(router_nicknames, char *, n, tor_free(n));
  1725. smartlist_free(router_nicknames);
  1726. if (routers)
  1727. smartlist_free(routers);
  1728. return 0;
  1729. }
  1730. /** Called when we get a SETCIRCUITPURPOSE (if <b>for_circuits</b>
  1731. * is 1) or SETROUTERPURPOSE message. If we can find
  1732. * the circuit/router and it's a valid purpose, change it. */
  1733. static int
  1734. handle_control_setpurpose(control_connection_t *conn, int for_circuits,
  1735. uint32_t len, const char *body)
  1736. {
  1737. origin_circuit_t *circ = NULL;
  1738. routerinfo_t *ri = NULL;
  1739. uint8_t new_purpose;
  1740. smartlist_t *args = smartlist_create();
  1741. (void) len; /* body is nul-terminated, so it's safe to ignore the length. */
  1742. smartlist_split_string(args, body, " ",
  1743. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1744. if (smartlist_len(args)<2) {
  1745. connection_printf_to_buf(conn,
  1746. "512 Missing argument to SET%sPURPOSE\r\n",
  1747. for_circuits ? "CIRCUIT" : "ROUTER");
  1748. goto done;
  1749. }
  1750. if (for_circuits) {
  1751. if (!(circ = get_circ(smartlist_get(args,0)))) {
  1752. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  1753. (char*)smartlist_get(args, 0));
  1754. goto done;
  1755. }
  1756. } else {
  1757. if (!(ri = router_get_by_nickname(smartlist_get(args,0), 0))) {
  1758. connection_printf_to_buf(conn, "552 Unknown router \"%s\"\r\n",
  1759. (char*)smartlist_get(args, 0));
  1760. goto done;
  1761. }
  1762. }
  1763. if (get_purpose(smartlist_get(args,1), for_circuits, &new_purpose) < 0) {
  1764. connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n",
  1765. (char *)smartlist_get(args,1));
  1766. goto done;
  1767. }
  1768. if (for_circuits)
  1769. circ->_base.purpose = new_purpose;
  1770. else
  1771. ri->purpose = new_purpose;
  1772. connection_write_str_to_buf("250 OK\r\n", conn);
  1773. done:
  1774. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1775. smartlist_free(args);
  1776. return 0;
  1777. }
  1778. /** Called when we get an ATTACHSTREAM message. Try to attach the requested
  1779. * stream, and report success or failure. */
  1780. static int
  1781. handle_control_attachstream(control_connection_t *conn, uint32_t len,
  1782. const char *body)
  1783. {
  1784. edge_connection_t *ap_conn = NULL;
  1785. origin_circuit_t *circ = NULL;
  1786. int zero_circ;
  1787. if (STATE_IS_V0(conn->_base.state)) {
  1788. uint32_t conn_id;
  1789. uint32_t circ_id;
  1790. if (len < 8) {
  1791. send_control0_error(conn, ERR_SYNTAX, "attachstream message too short");
  1792. return 0;
  1793. }
  1794. conn_id = ntohl(get_uint32(body));
  1795. circ_id = ntohl(get_uint32(body+4));
  1796. zero_circ = circ_id == 0;
  1797. if (!(ap_conn = connection_get_by_global_id(conn_id))) {
  1798. send_control0_error(conn, ERR_NO_STREAM,
  1799. "No connection found with given ID");
  1800. return 0;
  1801. }
  1802. if (circ_id && !(circ = circuit_get_by_global_id(circ_id))) {
  1803. send_control0_error(conn, ERR_NO_CIRC, "No circuit found with given ID");
  1804. return 0;
  1805. }
  1806. } else {
  1807. smartlist_t *args;
  1808. args = smartlist_create();
  1809. smartlist_split_string(args, body, " ",
  1810. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1811. if (smartlist_len(args)<2) {
  1812. connection_printf_to_buf(conn,
  1813. "512 Missing argument to ATTACHSTREAM\r\n");
  1814. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1815. smartlist_free(args);
  1816. return 0;
  1817. }
  1818. zero_circ = !strcmp("0", (char*)smartlist_get(args,1));
  1819. if (!(ap_conn = get_stream(smartlist_get(args, 0)))) {
  1820. connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
  1821. (char*)smartlist_get(args, 0));
  1822. } else if (!zero_circ && !(circ = get_circ(smartlist_get(args, 1)))) {
  1823. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  1824. (char*)smartlist_get(args, 1));
  1825. }
  1826. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1827. smartlist_free(args);
  1828. if (!ap_conn || (!zero_circ && !circ))
  1829. return 0;
  1830. }
  1831. if (ap_conn->_base.state != AP_CONN_STATE_CONTROLLER_WAIT &&
  1832. ap_conn->_base.state != AP_CONN_STATE_CONNECT_WAIT &&
  1833. ap_conn->_base.state != AP_CONN_STATE_RESOLVE_WAIT) {
  1834. if (STATE_IS_V0(conn->_base.state)) {
  1835. send_control0_error(conn, ERR_NO_STREAM,
  1836. "Connection is not managed by controller.");
  1837. } else {
  1838. connection_write_str_to_buf(
  1839. "555 Connection is not managed by controller.\r\n",
  1840. conn);
  1841. }
  1842. return 0;
  1843. }
  1844. /* Do we need to detach it first? */
  1845. if (ap_conn->_base.state != AP_CONN_STATE_CONTROLLER_WAIT) {
  1846. circuit_t *tmpcirc = circuit_get_by_edge_conn(ap_conn);
  1847. connection_edge_end(ap_conn, END_STREAM_REASON_TIMEOUT,
  1848. ap_conn->cpath_layer);
  1849. /* Un-mark it as ending, since we're going to reuse it. */
  1850. ap_conn->_base.edge_has_sent_end = 0;
  1851. if (tmpcirc)
  1852. circuit_detach_stream(tmpcirc,ap_conn);
  1853. ap_conn->_base.state = AP_CONN_STATE_CONTROLLER_WAIT;
  1854. }
  1855. if (circ && (circ->_base.state != CIRCUIT_STATE_OPEN)) {
  1856. if (STATE_IS_V0(conn->_base.state))
  1857. send_control0_error(conn, ERR_INTERNAL,
  1858. "Refuse to attach stream to non-open, origin circ.");
  1859. else
  1860. connection_write_str_to_buf(
  1861. "551 Can't attach stream to non-open, origin circuit\r\n",
  1862. conn);
  1863. return 0;
  1864. }
  1865. if (connection_ap_handshake_rewrite_and_attach(ap_conn, circ) < 0) {
  1866. if (STATE_IS_V0(conn->_base.state))
  1867. send_control0_error(conn, ERR_INTERNAL, "Unable to attach stream.");
  1868. else
  1869. connection_write_str_to_buf("551 Unable to attach stream\r\n", conn);
  1870. return 0;
  1871. }
  1872. send_control_done(conn);
  1873. return 0;
  1874. }
  1875. /** Called when we get a POSTDESCRIPTOR message. Try to learn the provided
  1876. * descriptor, and report success or failure. */
  1877. static int
  1878. handle_control_postdescriptor(control_connection_t *conn, uint32_t len,
  1879. const char *body)
  1880. {
  1881. char *desc;
  1882. int v0 = STATE_IS_V0(conn->_base.state);
  1883. const char *msg=NULL;
  1884. uint8_t purpose = ROUTER_PURPOSE_GENERAL;
  1885. if (v0)
  1886. desc = (char*)body;
  1887. else {
  1888. char *cp = memchr(body, '\n', len);
  1889. smartlist_t *args = smartlist_create();
  1890. tor_assert(cp);
  1891. *cp++ = '\0';
  1892. smartlist_split_string(args, body, " ",
  1893. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1894. if (smartlist_len(args)) {
  1895. if (get_purpose(smartlist_get(args,0), 0, &purpose) < 0) {
  1896. connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n",
  1897. (char *)smartlist_get(args,0));
  1898. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1899. smartlist_free(args);
  1900. return 0;
  1901. }
  1902. }
  1903. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1904. smartlist_free(args);
  1905. read_escaped_data(cp, len-(cp-body), 1, &desc);
  1906. }
  1907. switch (router_load_single_router(desc, purpose, &msg)) {
  1908. case -1:
  1909. if (!msg) msg = "Could not parse descriptor";
  1910. if (v0)
  1911. send_control0_error(conn,ERR_SYNTAX,msg);
  1912. else
  1913. connection_printf_to_buf(conn, "554 %s\r\n", msg);
  1914. break;
  1915. case 0:
  1916. if (!msg) msg = "Descriptor not added";
  1917. if (v0)
  1918. send_control_done2(conn,msg,0);
  1919. else
  1920. connection_printf_to_buf(conn, "251 %s\r\n",msg);
  1921. break;
  1922. case 1:
  1923. send_control_done(conn);
  1924. break;
  1925. }
  1926. if (!v0)
  1927. tor_free(desc);
  1928. return 0;
  1929. }
  1930. /** Called when we receive a REDIRECTSTERAM command. Try to change the target
  1931. * address of the named AP stream, and report success or failure. */
  1932. static int
  1933. handle_control_redirectstream(control_connection_t *conn, uint32_t len,
  1934. const char *body)
  1935. {
  1936. edge_connection_t *ap_conn = NULL;
  1937. uint32_t conn_id;
  1938. char *new_addr = NULL;
  1939. uint16_t new_port = 0;
  1940. if (STATE_IS_V0(conn->_base.state)) {
  1941. if (len < 6) {
  1942. send_control0_error(conn, ERR_SYNTAX,
  1943. "redirectstream message too short");
  1944. return 0;
  1945. }
  1946. conn_id = ntohl(get_uint32(body));
  1947. if (!(ap_conn = connection_get_by_global_id(conn_id))
  1948. || ap_conn->_base.state != CONN_TYPE_AP
  1949. || ap_conn->socks_request) {
  1950. send_control0_error(conn, ERR_NO_STREAM,
  1951. "No AP connection found with given ID");
  1952. return 0;
  1953. }
  1954. new_addr = tor_strdup(body+4);
  1955. } else {
  1956. smartlist_t *args;
  1957. args = smartlist_create();
  1958. smartlist_split_string(args, body, " ",
  1959. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1960. if (smartlist_len(args) < 2)
  1961. connection_printf_to_buf(conn,
  1962. "512 Missing argument to REDIRECTSTREAM\r\n");
  1963. else if (!(ap_conn = get_stream(smartlist_get(args, 0)))
  1964. || !ap_conn->socks_request) {
  1965. connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
  1966. (char*)smartlist_get(args, 0));
  1967. } else {
  1968. int ok;
  1969. if (smartlist_len(args) > 2) { /* they included a port too */
  1970. new_port = (uint16_t) tor_parse_ulong(smartlist_get(args, 2),
  1971. 10, 1, 65535, &ok, NULL);
  1972. }
  1973. if (!ok) {
  1974. connection_printf_to_buf(conn, "512 Cannot parse port \"%s\"\r\n",
  1975. (char*)smartlist_get(args, 2));
  1976. } else {
  1977. new_addr = tor_strdup(smartlist_get(args, 1));
  1978. }
  1979. }
  1980. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1981. smartlist_free(args);
  1982. if (!new_addr)
  1983. return 0;
  1984. }
  1985. strlcpy(ap_conn->socks_request->address, new_addr,
  1986. sizeof(ap_conn->socks_request->address));
  1987. if (new_port)
  1988. ap_conn->socks_request->port = new_port;
  1989. tor_free(new_addr);
  1990. send_control_done(conn);
  1991. return 0;
  1992. }
  1993. /** Called when we get a CLOSESTREAM command; try to close the named stream
  1994. * and report success or failure. */
  1995. static int
  1996. handle_control_closestream(control_connection_t *conn, uint32_t len,
  1997. const char *body)
  1998. {
  1999. edge_connection_t *ap_conn=NULL;
  2000. uint8_t reason=0;
  2001. if (STATE_IS_V0(conn->_base.state)) {
  2002. uint32_t conn_id;
  2003. if (len < 6) {
  2004. send_control0_error(conn, ERR_SYNTAX, "closestream message too short");
  2005. return 0;
  2006. }
  2007. conn_id = ntohl(get_uint32(body));
  2008. reason = *(uint8_t*)(body+4);
  2009. if (!(ap_conn = connection_get_by_global_id(conn_id))
  2010. || ap_conn->_base.state != CONN_TYPE_AP
  2011. || ap_conn->socks_request) {
  2012. send_control0_error(conn, ERR_NO_STREAM,
  2013. "No AP connection found with given ID");
  2014. return 0;
  2015. }
  2016. } else {
  2017. smartlist_t *args;
  2018. int ok;
  2019. args = smartlist_create();
  2020. smartlist_split_string(args, body, " ",
  2021. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2022. if (smartlist_len(args)<2)
  2023. connection_printf_to_buf(conn,
  2024. "512 Missing argument to CLOSESTREAM\r\n");
  2025. else if (!(ap_conn = get_stream(smartlist_get(args, 0))))
  2026. connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
  2027. (char*)smartlist_get(args, 0));
  2028. else {
  2029. reason = (uint8_t) tor_parse_ulong(smartlist_get(args,1), 10, 0, 255,
  2030. &ok, NULL);
  2031. if (!ok) {
  2032. connection_printf_to_buf(conn, "552 Unrecognized reason \"%s\"\r\n",
  2033. (char*)smartlist_get(args, 1));
  2034. ap_conn = NULL;
  2035. }
  2036. }
  2037. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2038. smartlist_free(args);
  2039. if (!ap_conn)
  2040. return 0;
  2041. }
  2042. connection_mark_unattached_ap(ap_conn, reason);
  2043. send_control_done(conn);
  2044. return 0;
  2045. }
  2046. /** Called when we get a CLOSECIRCUIT command; try to close the named circuit
  2047. * and report success or failure. */
  2048. static int
  2049. handle_control_closecircuit(control_connection_t *conn, uint32_t len,
  2050. const char *body)
  2051. {
  2052. origin_circuit_t *circ = NULL;
  2053. int safe = 0;
  2054. if (STATE_IS_V0(conn->_base.state)) {
  2055. uint32_t circ_id;
  2056. if (len < 5) {
  2057. send_control0_error(conn, ERR_SYNTAX, "closecircuit message too short");
  2058. return 0;
  2059. }
  2060. circ_id = ntohl(get_uint32(body));
  2061. safe = (*(uint8_t*)(body+4)) & 1;
  2062. if (!(circ = circuit_get_by_global_id(circ_id))) {
  2063. send_control0_error(conn, ERR_NO_CIRC,
  2064. "No circuit found with given ID");
  2065. return 0;
  2066. }
  2067. } else {
  2068. smartlist_t *args;
  2069. args = smartlist_create();
  2070. smartlist_split_string(args, body, " ",
  2071. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2072. if (smartlist_len(args)<1)
  2073. connection_printf_to_buf(conn,
  2074. "512 Missing argument to CLOSECIRCUIT\r\n");
  2075. else if (!(circ=get_circ(smartlist_get(args, 0))))
  2076. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  2077. (char*)smartlist_get(args, 0));
  2078. else {
  2079. int i;
  2080. for (i=1; i < smartlist_len(args); ++i) {
  2081. if (!strcasecmp(smartlist_get(args, i), "IfUnused"))
  2082. safe = 1;
  2083. else
  2084. log_info(LD_CONTROL, "Skipping unknown option %s",
  2085. (char*)smartlist_get(args,i));
  2086. }
  2087. }
  2088. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2089. smartlist_free(args);
  2090. if (!circ)
  2091. return 0;
  2092. }
  2093. if (!safe || !circ->p_streams) {
  2094. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_NONE);
  2095. }
  2096. send_control_done(conn);
  2097. return 0;
  2098. }
  2099. /** Called when we get a v0 FRAGMENTHEADER or FRAGMENT command; try to append
  2100. * the data to conn->incoming_cmd, setting conn->incoming_(type|len|cur_len)
  2101. * as appropriate. If the command is malformed, drop it and all pending
  2102. * fragments and report failure.
  2103. */
  2104. static int
  2105. handle_control_fragments(control_connection_t *conn, uint16_t command_type,
  2106. uint32_t body_len, char *body)
  2107. {
  2108. if (command_type == CONTROL0_CMD_FRAGMENTHEADER) {
  2109. if (conn->incoming_cmd) {
  2110. log_warn(LD_CONTROL, "Dropping incomplete fragmented command");
  2111. tor_free(conn->incoming_cmd);
  2112. }
  2113. if (body_len < 6) {
  2114. send_control0_error(conn, ERR_SYNTAX, "FRAGMENTHEADER too short.");
  2115. return 0;
  2116. }
  2117. conn->incoming_cmd_type = ntohs(get_uint16(body));
  2118. conn->incoming_cmd_len = ntohl(get_uint32(body+2));
  2119. conn->incoming_cmd_cur_len = 0;
  2120. conn->incoming_cmd = tor_malloc(conn->incoming_cmd_len);
  2121. body += 6;
  2122. body_len -= 6;
  2123. } else if (command_type == CONTROL0_CMD_FRAGMENT) {
  2124. if (!conn->incoming_cmd) {
  2125. send_control0_error(conn, ERR_SYNTAX, "Out-of-place FRAGMENT");
  2126. return 0;
  2127. }
  2128. } else {
  2129. tor_assert(0);
  2130. }
  2131. if (conn->incoming_cmd_cur_len + body_len > conn->incoming_cmd_len) {
  2132. tor_free(conn->incoming_cmd);
  2133. send_control0_error(conn, ERR_SYNTAX,
  2134. "Fragmented data exceeds declared length");
  2135. return 0;
  2136. }
  2137. memcpy(conn->incoming_cmd + conn->incoming_cmd_cur_len,
  2138. body, body_len);
  2139. conn->incoming_cmd_cur_len += body_len;
  2140. return 0;
  2141. }
  2142. /** Called when <b>conn</b> has no more bytes left on its outbuf. */
  2143. int
  2144. connection_control_finished_flushing(control_connection_t *conn)
  2145. {
  2146. tor_assert(conn);
  2147. connection_stop_writing(TO_CONN(conn));
  2148. return 0;
  2149. }
  2150. /** Called when <b>conn</b> has gotten its socket closed. */
  2151. int
  2152. connection_control_reached_eof(control_connection_t *conn)
  2153. {
  2154. tor_assert(conn);
  2155. log_info(LD_CONTROL,"Control connection reached EOF. Closing.");
  2156. connection_mark_for_close(TO_CONN(conn));
  2157. return 0;
  2158. }
  2159. /** Called when data has arrived on a v1 control connection: Try to fetch
  2160. * commands from conn->inbuf, and execute them.
  2161. */
  2162. static int
  2163. connection_control_process_inbuf_v1(control_connection_t *conn)
  2164. {
  2165. size_t data_len;
  2166. int cmd_len;
  2167. char *args;
  2168. tor_assert(conn);
  2169. tor_assert(conn->_base.state == CONTROL_CONN_STATE_OPEN_V1 ||
  2170. conn->_base.state == CONTROL_CONN_STATE_NEEDAUTH_V1);
  2171. if (!conn->incoming_cmd) {
  2172. conn->incoming_cmd = tor_malloc(1024);
  2173. conn->incoming_cmd_len = 1024;
  2174. conn->incoming_cmd_cur_len = 0;
  2175. }
  2176. again:
  2177. while (1) {
  2178. size_t last_idx;
  2179. int r;
  2180. /* First, fetch a line. */
  2181. do {
  2182. data_len = conn->incoming_cmd_len - conn->incoming_cmd_cur_len;
  2183. r = fetch_from_buf_line(conn->_base.inbuf,
  2184. conn->incoming_cmd+conn->incoming_cmd_cur_len,
  2185. &data_len);
  2186. if (r == 0)
  2187. /* Line not all here yet. Wait. */
  2188. return 0;
  2189. else if (r == -1) {
  2190. while (conn->incoming_cmd_len < data_len+conn->incoming_cmd_cur_len)
  2191. conn->incoming_cmd_len *= 2;
  2192. conn->incoming_cmd = tor_realloc(conn->incoming_cmd,
  2193. conn->incoming_cmd_len);
  2194. }
  2195. } while (r != 1);
  2196. tor_assert(data_len);
  2197. last_idx = conn->incoming_cmd_cur_len;
  2198. conn->incoming_cmd_cur_len += data_len;
  2199. /* We have appended a line to incoming_cmd. Is the command done? */
  2200. if (last_idx == 0 && *conn->incoming_cmd != '+')
  2201. /* One line command, didn't start with '+'. */
  2202. break;
  2203. if (last_idx+3 == conn->incoming_cmd_cur_len &&
  2204. !memcmp(conn->incoming_cmd + last_idx, ".\r\n", 3)) {
  2205. /* Just appended ".\r\n"; we're done. Remove it. */
  2206. conn->incoming_cmd_cur_len -= 3;
  2207. break;
  2208. }
  2209. /* Otherwise, read another line. */
  2210. }
  2211. data_len = conn->incoming_cmd_cur_len;
  2212. /* Okay, we now have a command sitting on conn->incoming_cmd. See if we
  2213. * recognize it.
  2214. */
  2215. cmd_len = 0;
  2216. while ((size_t)cmd_len < data_len
  2217. && !TOR_ISSPACE(conn->incoming_cmd[cmd_len]))
  2218. ++cmd_len;
  2219. data_len -= cmd_len;
  2220. conn->incoming_cmd[cmd_len]='\0';
  2221. args = conn->incoming_cmd+cmd_len+1;
  2222. while (*args == ' ' || *args == '\t') {
  2223. ++args;
  2224. --data_len;
  2225. }
  2226. if (!strcasecmp(conn->incoming_cmd, "QUIT")) {
  2227. connection_write_str_to_buf("250 closing connection\r\n", conn);
  2228. connection_mark_for_close(TO_CONN(conn));
  2229. return 0;
  2230. }
  2231. if (conn->_base.state == CONTROL_CONN_STATE_NEEDAUTH_V1 &&
  2232. strcasecmp(conn->incoming_cmd, "AUTHENTICATE")) {
  2233. connection_write_str_to_buf("514 Authentication required.\r\n", conn);
  2234. conn->incoming_cmd_cur_len = 0;
  2235. goto again;
  2236. }
  2237. if (!strcasecmp(conn->incoming_cmd, "SETCONF")) {
  2238. if (handle_control_setconf(conn, data_len, args))
  2239. return -1;
  2240. } else if (!strcasecmp(conn->incoming_cmd, "RESETCONF")) {
  2241. if (handle_control_resetconf(conn, data_len, args))
  2242. return -1;
  2243. } else if (!strcasecmp(conn->incoming_cmd, "GETCONF")) {
  2244. if (handle_control_getconf(conn, data_len, args))
  2245. return -1;
  2246. } else if (!strcasecmp(conn->incoming_cmd, "SETEVENTS")) {
  2247. if (handle_control_setevents(conn, data_len, args))
  2248. return -1;
  2249. } else if (!strcasecmp(conn->incoming_cmd, "AUTHENTICATE")) {
  2250. if (handle_control_authenticate(conn, data_len, args))
  2251. return -1;
  2252. } else if (!strcasecmp(conn->incoming_cmd, "SAVECONF")) {
  2253. if (handle_control_saveconf(conn, data_len, args))
  2254. return -1;
  2255. } else if (!strcasecmp(conn->incoming_cmd, "SIGNAL")) {
  2256. if (handle_control_signal(conn, data_len, args))
  2257. return -1;
  2258. } else if (!strcasecmp(conn->incoming_cmd, "MAPADDRESS")) {
  2259. if (handle_control_mapaddress(conn, data_len, args))
  2260. return -1;
  2261. } else if (!strcasecmp(conn->incoming_cmd, "GETINFO")) {
  2262. if (handle_control_getinfo(conn, data_len, args))
  2263. return -1;
  2264. } else if (!strcasecmp(conn->incoming_cmd, "EXTENDCIRCUIT")) {
  2265. if (handle_control_extendcircuit(conn, data_len, args))
  2266. return -1;
  2267. } else if (!strcasecmp(conn->incoming_cmd, "SETCIRCUITPURPOSE")) {
  2268. if (handle_control_setpurpose(conn, 1, data_len, args))
  2269. return -1;
  2270. } else if (!strcasecmp(conn->incoming_cmd, "SETROUTERPURPOSE")) {
  2271. if (handle_control_setpurpose(conn, 0, data_len, args))
  2272. return -1;
  2273. } else if (!strcasecmp(conn->incoming_cmd, "ATTACHSTREAM")) {
  2274. if (handle_control_attachstream(conn, data_len, args))
  2275. return -1;
  2276. } else if (!strcasecmp(conn->incoming_cmd, "+POSTDESCRIPTOR")) {
  2277. if (handle_control_postdescriptor(conn, data_len, args))
  2278. return -1;
  2279. } else if (!strcasecmp(conn->incoming_cmd, "REDIRECTSTREAM")) {
  2280. if (handle_control_redirectstream(conn, data_len, args))
  2281. return -1;
  2282. } else if (!strcasecmp(conn->incoming_cmd, "CLOSESTREAM")) {
  2283. if (handle_control_closestream(conn, data_len, args))
  2284. return -1;
  2285. } else if (!strcasecmp(conn->incoming_cmd, "CLOSECIRCUIT")) {
  2286. if (handle_control_closecircuit(conn, data_len, args))
  2287. return -1;
  2288. } else {
  2289. connection_printf_to_buf(conn, "510 Unrecognized command \"%s\"\r\n",
  2290. conn->incoming_cmd);
  2291. }
  2292. conn->incoming_cmd_cur_len = 0;
  2293. goto again;
  2294. }
  2295. /** Called when data has arrived on a v0 control connection: Try to fetch
  2296. * commands from conn->inbuf, and execute them.
  2297. */
  2298. static int
  2299. connection_control_process_inbuf_v0(control_connection_t *conn)
  2300. {
  2301. uint32_t body_len;
  2302. uint16_t command_type;
  2303. char *body=NULL;
  2304. again:
  2305. /* Try to suck a control message from the buffer. */
  2306. switch (fetch_from_buf_control0(conn->_base.inbuf, &body_len, &command_type,
  2307. &body,
  2308. conn->_base.state == CONTROL_CONN_STATE_NEEDAUTH_V0))
  2309. {
  2310. case -2:
  2311. tor_free(body);
  2312. log_info(LD_CONTROL,
  2313. "Detected v1 control protocol on connection (fd %d)",
  2314. conn->_base.s);
  2315. conn->_base.state = CONTROL_CONN_STATE_NEEDAUTH_V1;
  2316. return connection_control_process_inbuf_v1(conn);
  2317. case -1:
  2318. tor_free(body);
  2319. log_warn(LD_CONTROL, "Error in control command. Failing.");
  2320. return -1;
  2321. case 0:
  2322. /* Control command not all here yet. Wait. */
  2323. return 0;
  2324. case 1:
  2325. /* We got a command. Process it. */
  2326. break;
  2327. default:
  2328. tor_assert(0);
  2329. }
  2330. /* We got a command. If we need authentication, only authentication
  2331. * commands will be considered. */
  2332. if (conn->_base.state == CONTROL_CONN_STATE_NEEDAUTH_V0 &&
  2333. command_type != CONTROL0_CMD_AUTHENTICATE) {
  2334. log_info(LD_CONTROL, "Rejecting '%s' command; authentication needed.",
  2335. control_cmd_to_string(command_type));
  2336. send_control0_error(conn, ERR_UNAUTHORIZED, "Authentication required");
  2337. tor_free(body);
  2338. goto again;
  2339. }
  2340. if (command_type == CONTROL0_CMD_FRAGMENTHEADER ||
  2341. command_type == CONTROL0_CMD_FRAGMENT) {
  2342. if (handle_control_fragments(conn, command_type, body_len, body))
  2343. return -1;
  2344. tor_free(body);
  2345. if (conn->incoming_cmd_cur_len != conn->incoming_cmd_len)
  2346. goto again;
  2347. command_type = conn->incoming_cmd_type;
  2348. body_len = conn->incoming_cmd_len;
  2349. body = conn->incoming_cmd;
  2350. conn->incoming_cmd = NULL;
  2351. } else if (conn->incoming_cmd) {
  2352. log_warn(LD_CONTROL, "Dropping incomplete fragmented command");
  2353. tor_free(conn->incoming_cmd);
  2354. }
  2355. /* Okay, we're willing to process the command. */
  2356. switch (command_type)
  2357. {
  2358. case CONTROL0_CMD_SETCONF:
  2359. if (handle_control_setconf(conn, body_len, body))
  2360. return -1;
  2361. break;
  2362. case CONTROL0_CMD_GETCONF:
  2363. if (handle_control_getconf(conn, body_len, body))
  2364. return -1;
  2365. break;
  2366. case CONTROL0_CMD_SETEVENTS:
  2367. if (handle_control_setevents(conn, body_len, body))
  2368. return -1;
  2369. break;
  2370. case CONTROL0_CMD_AUTHENTICATE:
  2371. if (handle_control_authenticate(conn, body_len, body))
  2372. return -1;
  2373. break;
  2374. case CONTROL0_CMD_SAVECONF:
  2375. if (handle_control_saveconf(conn, body_len, body))
  2376. return -1;
  2377. break;
  2378. case CONTROL0_CMD_SIGNAL:
  2379. if (handle_control_signal(conn, body_len, body))
  2380. return -1;
  2381. break;
  2382. case CONTROL0_CMD_MAPADDRESS:
  2383. if (handle_control_mapaddress(conn, body_len, body))
  2384. return -1;
  2385. break;
  2386. case CONTROL0_CMD_GETINFO:
  2387. if (handle_control_getinfo(conn, body_len, body))
  2388. return -1;
  2389. break;
  2390. case CONTROL0_CMD_EXTENDCIRCUIT:
  2391. if (handle_control_extendcircuit(conn, body_len, body))
  2392. return -1;
  2393. break;
  2394. case CONTROL0_CMD_ATTACHSTREAM:
  2395. if (handle_control_attachstream(conn, body_len, body))
  2396. return -1;
  2397. break;
  2398. case CONTROL0_CMD_POSTDESCRIPTOR:
  2399. if (handle_control_postdescriptor(conn, body_len, body))
  2400. return -1;
  2401. break;
  2402. case CONTROL0_CMD_REDIRECTSTREAM:
  2403. if (handle_control_redirectstream(conn, body_len, body))
  2404. return -1;
  2405. break;
  2406. case CONTROL0_CMD_CLOSESTREAM:
  2407. if (handle_control_closestream(conn, body_len, body))
  2408. return -1;
  2409. break;
  2410. case CONTROL0_CMD_CLOSECIRCUIT:
  2411. if (handle_control_closecircuit(conn, body_len, body))
  2412. return -1;
  2413. break;
  2414. case CONTROL0_CMD_ERROR:
  2415. case CONTROL0_CMD_DONE:
  2416. case CONTROL0_CMD_CONFVALUE:
  2417. case CONTROL0_CMD_EVENT:
  2418. case CONTROL0_CMD_INFOVALUE:
  2419. log_warn(LD_CONTROL, "Received client-only '%s' command; ignoring.",
  2420. control_cmd_to_string(command_type));
  2421. send_control0_error(conn, ERR_UNRECOGNIZED_TYPE,
  2422. "Command type only valid from server to tor client");
  2423. break;
  2424. case CONTROL0_CMD_FRAGMENTHEADER:
  2425. case CONTROL0_CMD_FRAGMENT:
  2426. log_warn(LD_CONTROL,
  2427. "Recieved command fragment out of order; ignoring.");
  2428. send_control0_error(conn, ERR_SYNTAX, "Bad fragmentation on command.");
  2429. default:
  2430. log_warn(LD_CONTROL, "Received unrecognized command type %d; ignoring.",
  2431. (int)command_type);
  2432. send_control0_error(conn, ERR_UNRECOGNIZED_TYPE,
  2433. "Unrecognized command type");
  2434. break;
  2435. }
  2436. tor_free(body);
  2437. goto again; /* There might be more data. */
  2438. }
  2439. /** Called when <b>conn</b> has received more bytes on its inbuf.
  2440. */
  2441. int
  2442. connection_control_process_inbuf(control_connection_t *conn)
  2443. {
  2444. tor_assert(conn);
  2445. if (STATE_IS_V0(conn->_base.state))
  2446. return connection_control_process_inbuf_v0(conn);
  2447. else
  2448. return connection_control_process_inbuf_v1(conn);
  2449. }
  2450. /** Something has happened to circuit <b>circ</b>: tell any interested
  2451. * control connections. */
  2452. int
  2453. control_event_circuit_status(origin_circuit_t *circ, circuit_status_event_t tp)
  2454. {
  2455. char *path, *msg;
  2456. if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS))
  2457. return 0;
  2458. tor_assert(circ);
  2459. path = circuit_list_path(circ,0);
  2460. if (EVENT_IS_INTERESTING0(EVENT_CIRCUIT_STATUS)) {
  2461. size_t path_len = strlen(path);
  2462. msg = tor_malloc(1+4+path_len+1); /* event, circid, path, NUL. */
  2463. msg[0] = (uint8_t) tp;
  2464. set_uint32(msg+1, htonl(circ->global_identifier));
  2465. strlcpy(msg+5,path,path_len+1);
  2466. send_control0_event(EVENT_CIRCUIT_STATUS, (uint32_t)(path_len+6), msg);
  2467. tor_free(msg);
  2468. }
  2469. if (EVENT_IS_INTERESTING1(EVENT_CIRCUIT_STATUS)) {
  2470. const char *status;
  2471. switch (tp)
  2472. {
  2473. case CIRC_EVENT_LAUNCHED: status = "LAUNCHED"; break;
  2474. case CIRC_EVENT_BUILT: status = "BUILT"; break;
  2475. case CIRC_EVENT_EXTENDED: status = "EXTENDED"; break;
  2476. case CIRC_EVENT_FAILED: status = "FAILED"; break;
  2477. case CIRC_EVENT_CLOSED: status = "CLOSED"; break;
  2478. default:
  2479. log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
  2480. return 0;
  2481. }
  2482. send_control1_event(EVENT_CIRCUIT_STATUS,
  2483. "650 CIRC %lu %s %s\r\n",
  2484. (unsigned long)circ->global_identifier,
  2485. status, path);
  2486. }
  2487. tor_free(path);
  2488. return 0;
  2489. }
  2490. /** Given an AP connection <b>conn</b> and a <b>len</b>-character buffer
  2491. * <b>buf</b>, determine the address:port combination requested on
  2492. * <b>conn</b>, and write it to <b>buf</b>. Return 0 on success, -1 on
  2493. * failure. */
  2494. static int
  2495. write_stream_target_to_buf(edge_connection_t *conn, char *buf, size_t len)
  2496. {
  2497. char buf2[256];
  2498. if (conn->chosen_exit_name)
  2499. if (tor_snprintf(buf2, sizeof(buf2), ".%s.exit", conn->chosen_exit_name)<0)
  2500. return -1;
  2501. if (tor_snprintf(buf, len, "%s%s%s:%d",
  2502. conn->socks_request->address,
  2503. conn->chosen_exit_name ? buf2 : "",
  2504. !conn->chosen_exit_name &&
  2505. connection_edge_is_rendezvous_stream(conn) ? ".onion" : "",
  2506. conn->socks_request->port)<0)
  2507. return -1;
  2508. return 0;
  2509. }
  2510. /** Something has happened to the stream associated with AP connection
  2511. * <b>conn</b>: tell any interested control connections. */
  2512. int
  2513. control_event_stream_status(edge_connection_t *conn, stream_status_event_t tp)
  2514. {
  2515. char *msg;
  2516. size_t len;
  2517. char buf[256];
  2518. tor_assert(conn->socks_request);
  2519. if (!EVENT_IS_INTERESTING(EVENT_STREAM_STATUS))
  2520. return 0;
  2521. write_stream_target_to_buf(conn, buf, sizeof(buf));
  2522. if (EVENT_IS_INTERESTING0(EVENT_STREAM_STATUS)) {
  2523. len = strlen(buf);
  2524. msg = tor_malloc(5+len+1);
  2525. msg[0] = (uint8_t) tp;
  2526. set_uint32(msg+1, htonl(conn->global_identifier));
  2527. strlcpy(msg+5, buf, len+1);
  2528. send_control0_event(EVENT_STREAM_STATUS, (uint32_t)(5+len+1), msg);
  2529. tor_free(msg);
  2530. }
  2531. if (EVENT_IS_INTERESTING1(EVENT_STREAM_STATUS)) {
  2532. const char *status;
  2533. circuit_t *circ;
  2534. origin_circuit_t *origin_circ = NULL;
  2535. switch (tp)
  2536. {
  2537. case STREAM_EVENT_SENT_CONNECT: status = "SENTCONNECT"; break;
  2538. case STREAM_EVENT_SENT_RESOLVE: status = "SENTRESOLVE"; break;
  2539. case STREAM_EVENT_SUCCEEDED: status = "SUCCEEDED"; break;
  2540. case STREAM_EVENT_FAILED: status = "FAILED"; break;
  2541. case STREAM_EVENT_CLOSED: status = "CLOSED"; break;
  2542. case STREAM_EVENT_NEW: status = "NEW"; break;
  2543. case STREAM_EVENT_NEW_RESOLVE: status = "NEWRESOLVE"; break;
  2544. case STREAM_EVENT_FAILED_RETRIABLE: status = "DETACHED"; break;
  2545. default:
  2546. log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
  2547. return 0;
  2548. }
  2549. circ = circuit_get_by_edge_conn(conn);
  2550. if (circ && CIRCUIT_IS_ORIGIN(circ))
  2551. origin_circ = TO_ORIGIN_CIRCUIT(circ);
  2552. send_control1_event(EVENT_STREAM_STATUS,
  2553. "650 STREAM %lu %s %lu %s\r\n",
  2554. (unsigned long)conn->global_identifier, status,
  2555. origin_circ?
  2556. (unsigned long)origin_circ->global_identifier : 0ul,
  2557. buf);
  2558. /* XXX need to specify its intended exit, etc? */
  2559. }
  2560. return 0;
  2561. }
  2562. /** Something has happened to the OR connection <b>conn</b>: tell any
  2563. * interested control connections. */
  2564. int
  2565. control_event_or_conn_status(or_connection_t *conn,or_conn_status_event_t tp)
  2566. {
  2567. char buf[HEX_DIGEST_LEN+3]; /* status, dollar, identity, NUL */
  2568. size_t len;
  2569. if (!EVENT_IS_INTERESTING(EVENT_OR_CONN_STATUS))
  2570. return 0;
  2571. if (EVENT_IS_INTERESTING0(EVENT_OR_CONN_STATUS)) {
  2572. buf[0] = (uint8_t)tp;
  2573. strlcpy(buf+1,conn->nickname ? conn->nickname : "",sizeof(buf)-1);
  2574. len = strlen(buf+1);
  2575. send_control0_event(EVENT_OR_CONN_STATUS, (uint32_t)(len+1), buf);
  2576. }
  2577. if (EVENT_IS_INTERESTING1(EVENT_OR_CONN_STATUS)) {
  2578. const char *status;
  2579. char name[128];
  2580. if (conn->nickname)
  2581. strlcpy(name, conn->nickname, sizeof(name));
  2582. else
  2583. tor_snprintf(name, sizeof(name), "%s:%d",
  2584. conn->_base.address, conn->_base.port);
  2585. switch (tp)
  2586. {
  2587. case OR_CONN_EVENT_LAUNCHED: status = "LAUNCHED"; break;
  2588. case OR_CONN_EVENT_CONNECTED: status = "CONNECTED"; break;
  2589. case OR_CONN_EVENT_FAILED: status = "FAILED"; break;
  2590. case OR_CONN_EVENT_CLOSED: status = "CLOSED"; break;
  2591. case OR_CONN_EVENT_NEW: status = "NEW"; break;
  2592. default:
  2593. log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
  2594. return 0;
  2595. }
  2596. send_control1_event(EVENT_OR_CONN_STATUS,
  2597. "650 ORCONN %s %s\r\n",
  2598. name, status);
  2599. }
  2600. return 0;
  2601. }
  2602. /** A second or more has elapsed: tell any interested control
  2603. * connections how much bandwidth we used. */
  2604. int
  2605. control_event_bandwidth_used(uint32_t n_read, uint32_t n_written)
  2606. {
  2607. char buf[8];
  2608. if (EVENT_IS_INTERESTING0(EVENT_BANDWIDTH_USED)) {
  2609. set_uint32(buf, htonl(n_read));
  2610. set_uint32(buf+4, htonl(n_written));
  2611. send_control0_event(EVENT_BANDWIDTH_USED, 8, buf);
  2612. }
  2613. if (EVENT_IS_INTERESTING1(EVENT_BANDWIDTH_USED)) {
  2614. send_control1_event(EVENT_BANDWIDTH_USED,
  2615. "650 BW %lu %lu\r\n",
  2616. (unsigned long)n_read,
  2617. (unsigned long)n_written);
  2618. }
  2619. return 0;
  2620. }
  2621. /** Called when we are sending a log message to the controllers: suspend
  2622. * sending further log messages to the controllers until we're done. Used by
  2623. * CONN_LOG_PROTECT. */
  2624. void
  2625. disable_control_logging(void)
  2626. {
  2627. ++disable_log_messages;
  2628. }
  2629. /** We're done sending a log message to the controllers: re-enable controller
  2630. * logging. Used by CONN_LOG_PROTECT. */
  2631. void
  2632. enable_control_logging(void)
  2633. {
  2634. if (--disable_log_messages < 0)
  2635. tor_assert(0);
  2636. }
  2637. /** We got a log message: tell any interested control connections. */
  2638. void
  2639. control_event_logmsg(int severity, unsigned int domain, const char *msg)
  2640. {
  2641. int oldlog, event;
  2642. (void) domain;
  2643. if (disable_log_messages)
  2644. return;
  2645. oldlog = EVENT_IS_INTERESTING0(EVENT_LOG_OBSOLETE) &&
  2646. (severity == LOG_NOTICE || severity == LOG_WARN || severity == LOG_ERR);
  2647. event = log_severity_to_event(severity);
  2648. if (event<0 || !EVENT_IS_INTERESTING0(event))
  2649. event = 0;
  2650. if (oldlog || event) {
  2651. size_t len = strlen(msg);
  2652. ++disable_log_messages;
  2653. if (event)
  2654. send_control0_event(event, (uint32_t)(len+1), msg);
  2655. if (oldlog)
  2656. send_control0_event(EVENT_LOG_OBSOLETE, (uint32_t)(len+1), msg);
  2657. --disable_log_messages;
  2658. }
  2659. event = log_severity_to_event(severity);
  2660. if (event >= 0 && EVENT_IS_INTERESTING1(event)) {
  2661. char *b = NULL;
  2662. const char *s;
  2663. if (strchr(msg, '\n')) {
  2664. char *cp;
  2665. b = tor_strdup(msg);
  2666. for (cp = b; *cp; ++cp)
  2667. if (*cp == '\r' || *cp == '\n')
  2668. *cp = ' ';
  2669. }
  2670. switch (severity) {
  2671. case LOG_DEBUG: s = "DEBUG"; break;
  2672. case LOG_INFO: s = "INFO"; break;
  2673. case LOG_NOTICE: s = "NOTICE"; break;
  2674. case LOG_WARN: s = "WARN"; break;
  2675. case LOG_ERR: s = "ERR"; break;
  2676. default: s = "UnknownLogSeverity"; break;
  2677. }
  2678. ++disable_log_messages;
  2679. send_control1_event(event, "650 %s %s\r\n", s, b?b:msg);
  2680. --disable_log_messages;
  2681. tor_free(b);
  2682. }
  2683. }
  2684. /** Called whenever we receive new router descriptors: tell any
  2685. * interested control connections. <b>routers</b> is a list of
  2686. * DIGEST_LEN-byte identity digests.
  2687. */
  2688. int
  2689. control_event_descriptors_changed(smartlist_t *routers)
  2690. {
  2691. size_t len;
  2692. char *msg;
  2693. smartlist_t *identities;
  2694. char buf[HEX_DIGEST_LEN+1];
  2695. if (!EVENT_IS_INTERESTING(EVENT_NEW_DESC))
  2696. return 0;
  2697. identities = smartlist_create();
  2698. SMARTLIST_FOREACH(routers, routerinfo_t *, r,
  2699. {
  2700. base16_encode(buf,sizeof(buf),r->cache_info.identity_digest,DIGEST_LEN);
  2701. smartlist_add(identities, tor_strdup(buf));
  2702. });
  2703. if (EVENT_IS_INTERESTING0(EVENT_NEW_DESC)) {
  2704. msg = smartlist_join_strings(identities, ",", 0, &len);
  2705. send_control0_event(EVENT_NEW_DESC, len+1, msg);
  2706. tor_free(msg);
  2707. }
  2708. if (EVENT_IS_INTERESTING1(EVENT_NEW_DESC)) {
  2709. char *ids = smartlist_join_strings(identities, " ", 0, &len);
  2710. size_t len = strlen(ids)+32;
  2711. msg = tor_malloc(len);
  2712. tor_snprintf(msg, len, "650 NEWDESC %s\r\n", ids);
  2713. send_control1_event_string(EVENT_NEW_DESC, msg);
  2714. tor_free(ids);
  2715. tor_free(msg);
  2716. }
  2717. SMARTLIST_FOREACH(identities, char *, cp, tor_free(cp));
  2718. smartlist_free(identities);
  2719. return 0;
  2720. }
  2721. /** Called whenever an address mapping on <b>from<b> from changes to <b>to</b>.
  2722. * <b>expires</b> values less than 3 are special; see connection_edge.c. */
  2723. int
  2724. control_event_address_mapped(const char *from, const char *to, time_t expires)
  2725. {
  2726. if (!EVENT_IS_INTERESTING1(EVENT_ADDRMAP))
  2727. return 0;
  2728. if (expires < 3)
  2729. send_control1_event(EVENT_ADDRMAP,
  2730. "650 ADDRMAP %s %s NEVER\r\n", from, to);
  2731. else {
  2732. char buf[ISO_TIME_LEN+1];
  2733. format_local_iso_time(buf,expires);
  2734. send_control1_event(EVENT_ADDRMAP, "650 ADDRMAP %s %s \"%s\"\r\n",
  2735. from, to, buf);
  2736. }
  2737. return 0;
  2738. }
  2739. /** The authoritative dirserver has received a new descriptor that
  2740. * has passed basic syntax checks and is properly self-signed.
  2741. *
  2742. * Notify any interested party of the new descriptor and what has
  2743. * been done with it, and also optionally give an explanation/reason. */
  2744. int
  2745. control_event_or_authdir_new_descriptor(const char *action,
  2746. const char *descriptor,
  2747. const char *msg)
  2748. {
  2749. char firstline[1024];
  2750. char *buf;
  2751. int totallen;
  2752. char *esc = NULL;
  2753. size_t esclen;
  2754. if (!EVENT_IS_INTERESTING(EVENT_AUTHDIR_NEWDESCS))
  2755. return 0;
  2756. tor_snprintf(firstline, sizeof(firstline),
  2757. "650+AUTHDIR_NEWDESC=\r\n%s\r\n%s\r\n",
  2758. action,
  2759. msg ? msg : "");
  2760. /* Escape the server descriptor properly */
  2761. esclen = write_escaped_data(descriptor, strlen(descriptor), 1, &esc);
  2762. totallen = strlen(firstline) + esclen + 1;
  2763. buf = tor_malloc(totallen);
  2764. strlcpy(buf, firstline, totallen);
  2765. strlcpy(buf+strlen(firstline), esc, totallen);
  2766. send_control1_event_string(EVENT_AUTHDIR_NEWDESCS, buf);
  2767. tor_free(esc);
  2768. tor_free(buf);
  2769. return 0;
  2770. }
  2771. /** Choose a random authentication cookie and write it to disk.
  2772. * Anybody who can read the cookie from disk will be considered
  2773. * authorized to use the control connection. */
  2774. int
  2775. init_cookie_authentication(int enabled)
  2776. {
  2777. char fname[512];
  2778. if (!enabled) {
  2779. authentication_cookie_is_set = 0;
  2780. return 0;
  2781. }
  2782. tor_snprintf(fname, sizeof(fname), "%s/control_auth_cookie",
  2783. get_options()->DataDirectory);
  2784. crypto_rand(authentication_cookie, AUTHENTICATION_COOKIE_LEN);
  2785. authentication_cookie_is_set = 1;
  2786. if (write_bytes_to_file(fname, authentication_cookie,
  2787. AUTHENTICATION_COOKIE_LEN, 1)) {
  2788. log_warn(LD_FS,"Error writing authentication cookie.");
  2789. return -1;
  2790. }
  2791. return 0;
  2792. }