control.c 98 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010
  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_check(sig)) {
  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 Unable to act on signal\r\n",
  1085. conn);
  1086. } else {
  1087. /* Send DONE first, in case the signal makes us shut down. */
  1088. send_control_done(conn);
  1089. control_signal_act(sig);
  1090. }
  1091. return 0;
  1092. }
  1093. /** Called when we get a MAPADDRESS command; try to bind all listed addresses,
  1094. * and report success or failrue. */
  1095. static int
  1096. handle_control_mapaddress(control_connection_t *conn, uint32_t len,
  1097. const char *body)
  1098. {
  1099. smartlist_t *elts;
  1100. smartlist_t *lines;
  1101. smartlist_t *reply;
  1102. char *r;
  1103. size_t sz;
  1104. int v0 = STATE_IS_V0(conn->_base.state);
  1105. (void) len; /* body is nul-terminated, so it's safe to ignore the length. */
  1106. lines = smartlist_create();
  1107. elts = smartlist_create();
  1108. reply = smartlist_create();
  1109. if (v0)
  1110. smartlist_split_string(lines, body, "\n",
  1111. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1112. else
  1113. smartlist_split_string(lines, body, " ",
  1114. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1115. SMARTLIST_FOREACH(lines, char *, line,
  1116. {
  1117. tor_strlower(line);
  1118. if (v0)
  1119. smartlist_split_string(elts, line, " ", 0, 2);
  1120. else
  1121. smartlist_split_string(elts, line, "=", 0, 2);
  1122. if (smartlist_len(elts) == 2) {
  1123. const char *from = smartlist_get(elts,0);
  1124. const char *to = smartlist_get(elts,1);
  1125. size_t anslen = strlen(line)+512;
  1126. char *ans = tor_malloc(anslen);
  1127. if (!is_plausible_address(from)) {
  1128. if (!v0) {
  1129. tor_snprintf(ans, anslen,
  1130. "512-syntax error: invalid address '%s'", from);
  1131. smartlist_add(reply, ans);
  1132. } else
  1133. tor_free(ans); /* don't respond if v0 */
  1134. log_warn(LD_CONTROL,
  1135. "Skipping invalid argument '%s' in MapAddress msg",
  1136. from);
  1137. } else if (!is_plausible_address(to)) {
  1138. if (!v0) {
  1139. tor_snprintf(ans, anslen,
  1140. "512-syntax error: invalid address '%s'", to);
  1141. smartlist_add(reply, ans);
  1142. } else
  1143. tor_free(ans); /* don't respond if v0 */
  1144. log_warn(LD_CONTROL,
  1145. "Skipping invalid argument '%s' in MapAddress msg", to);
  1146. } else if (!strcmp(from, ".") || !strcmp(from, "0.0.0.0")) {
  1147. const char *address = addressmap_register_virtual_address(
  1148. !strcmp(from,".") ? RESOLVED_TYPE_HOSTNAME : RESOLVED_TYPE_IPV4,
  1149. tor_strdup(to));
  1150. if (!address) {
  1151. if (!v0) {
  1152. tor_snprintf(ans, anslen,
  1153. "451-resource exhausted: skipping '%s'", line);
  1154. smartlist_add(reply, ans);
  1155. } else
  1156. tor_free(ans); /* don't respond if v0 */
  1157. log_warn(LD_CONTROL,
  1158. "Unable to allocate address for '%s' in MapAddress msg",
  1159. safe_str(line));
  1160. } else {
  1161. if (v0)
  1162. tor_snprintf(ans, anslen, "%s %s", address, to);
  1163. else
  1164. tor_snprintf(ans, anslen, "250-%s=%s", address, to);
  1165. smartlist_add(reply, ans);
  1166. }
  1167. } else {
  1168. addressmap_register(from, tor_strdup(to), 1);
  1169. if (v0)
  1170. tor_snprintf(ans, anslen, "%s", line);
  1171. else
  1172. tor_snprintf(ans, anslen, "250-%s", line);
  1173. smartlist_add(reply, ans);
  1174. }
  1175. } else {
  1176. if (!v0) {
  1177. size_t anslen = strlen(line)+256;
  1178. char *ans = tor_malloc(anslen);
  1179. tor_snprintf(ans, anslen, "512-syntax error: mapping '%s' is "
  1180. "not of expected form 'foo=bar'.", line);
  1181. smartlist_add(reply, ans);
  1182. }
  1183. log_info(LD_CONTROL, "Skipping MapAddress '%s': wrong "
  1184. "number of items.", safe_str(line));
  1185. }
  1186. SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
  1187. smartlist_clear(elts);
  1188. });
  1189. SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
  1190. smartlist_free(lines);
  1191. smartlist_free(elts);
  1192. if (v0) {
  1193. r = smartlist_join_strings(reply, "\n", 1, &sz);
  1194. send_control_done2(conn,r,sz);
  1195. tor_free(r);
  1196. } else {
  1197. if (smartlist_len(reply)) {
  1198. ((char*)smartlist_get(reply,smartlist_len(reply)-1))[3] = ' ';
  1199. r = smartlist_join_strings(reply, "\r\n", 1, &sz);
  1200. connection_write_to_buf(r, sz, TO_CONN(conn));
  1201. tor_free(r);
  1202. } else {
  1203. const char *response =
  1204. "512 syntax error: not enough arguments to mapaddress.\r\n";
  1205. connection_write_to_buf(response, strlen(response), TO_CONN(conn));
  1206. }
  1207. }
  1208. SMARTLIST_FOREACH(reply, char *, cp, tor_free(cp));
  1209. smartlist_free(reply);
  1210. return 0;
  1211. }
  1212. /** Return a newly allocated string listing all valid GETINFO fields as
  1213. * required by GETINFO info/names. */
  1214. static char *
  1215. list_getinfo_options(void)
  1216. {
  1217. return tor_strdup(
  1218. "accounting/bytes Number of bytes read/written so far in interval.\n"
  1219. "accounting/bytes-left Number of bytes left to read/write in interval.\n"
  1220. "accounting/enabled Is accounting currently enabled?\n"
  1221. "accounting/hibernating Are we hibernating or awake?\n"
  1222. "accounting/interval-end Time when interval ends.\n"
  1223. "accounting/interval-start Time when interval starts.\n"
  1224. "accounting/interval-wake Time to wake up in this interval.\n"
  1225. "addr-mappings/all All current remapped addresses.\n"
  1226. "addr-mappings/cache Addresses remapped by DNS cache.\n"
  1227. "addr-mappings/configl Addresses remapped from configuration options.\n"
  1228. "addr-mappings/control Addresses remapped by a controller.\n"
  1229. "address The best guess at our external IP address.\n"
  1230. "circuit-status Status of each current circuit.\n"
  1231. "config-file Current location of the \"torrc\" file.\n"
  1232. "config/names List of configuration options, types, and documentation.\n"
  1233. "desc/id/* Server descriptor by hex ID\n"
  1234. "desc/name/* Server descriptor by nickname.\n"
  1235. "desc/all-recent Latest server descriptor for every router\n"
  1236. "dir/server/* Fetch server descriptors -- see dir-spec.txt\n"
  1237. "entry-guards Which nodes will we use as entry guards?\n"
  1238. "exit-policy/default Default lines appended to config->ExitPolicy\n"
  1239. "info/names List of GETINFO options, types, and documentation.\n"
  1240. "network-status List of hex IDs, nicknames, server statuses.\n"
  1241. "orconn-status Status of each current OR connection.\n"
  1242. "stream-status Status of each current application stream.\n"
  1243. "version The current version of Tor.\n");
  1244. }
  1245. /** Lookup the 'getinfo' entry <b>question</b>, and return
  1246. * the answer in <b>*answer</b> (or NULL if key not recognized).
  1247. * Return 0 if success or unrecognized, or -1 if recognized but
  1248. * internal error. */
  1249. static int
  1250. handle_getinfo_helper(const char *question, char **answer)
  1251. {
  1252. *answer = NULL; /* unrecognized key by default */
  1253. if (!strcmp(question, "version")) {
  1254. *answer = tor_strdup(VERSION);
  1255. } else if (!strcmp(question, "config-file")) {
  1256. *answer = tor_strdup(get_torrc_fname());
  1257. } else if (!strcmpstart(question, "accounting/")) {
  1258. return accounting_getinfo_helper(question, answer);
  1259. } else if (!strcmpstart(question, "helper-nodes")) { /* deprecated */
  1260. return entry_guards_getinfo(question, answer);
  1261. } else if (!strcmpstart(question, "entry-guards")) {
  1262. return entry_guards_getinfo(question, answer);
  1263. } else if (!strcmpstart(question, "config/")) {
  1264. return config_getinfo_helper(question, answer);
  1265. } else if (!strcmp(question, "info/names")) {
  1266. *answer = list_getinfo_options();
  1267. } else if (!strcmpstart(question, "desc/id/")) {
  1268. routerinfo_t *ri = router_get_by_hexdigest(question+strlen("desc/id/"));
  1269. if (ri) {
  1270. const char *body = signed_descriptor_get_body(&ri->cache_info);
  1271. if (body)
  1272. *answer = tor_strndup(body, ri->cache_info.signed_descriptor_len);
  1273. }
  1274. } else if (!strcmpstart(question, "desc/name/")) {
  1275. routerinfo_t *ri = router_get_by_nickname(question+strlen("desc/name/"),1);
  1276. if (ri) {
  1277. const char *body = signed_descriptor_get_body(&ri->cache_info);
  1278. if (body)
  1279. *answer = tor_strndup(body, ri->cache_info.signed_descriptor_len);
  1280. }
  1281. } else if (!strcmp(question, "desc/all-recent")) {
  1282. routerlist_t *routerlist = router_get_routerlist();
  1283. smartlist_t *sl = smartlist_create();
  1284. if (routerlist && routerlist->routers) {
  1285. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, ri,
  1286. {
  1287. const char *body = signed_descriptor_get_body(&ri->cache_info);
  1288. if (body)
  1289. smartlist_add(sl,
  1290. tor_strndup(body, ri->cache_info.signed_descriptor_len));
  1291. });
  1292. }
  1293. *answer = smartlist_join_strings(sl, "", 0, NULL);
  1294. SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  1295. smartlist_free(sl);
  1296. } else if (!strcmpstart(question, "unregistered-servers-")) {
  1297. *answer = dirserver_getinfo_unregistered(question +
  1298. strlen("unregistered-servers-"));
  1299. } else if (!strcmp(question, "network-status")) {
  1300. routerlist_t *routerlist = router_get_routerlist();
  1301. if (!routerlist || !routerlist->routers ||
  1302. list_server_status(routerlist->routers, answer) < 0) {
  1303. return -1;
  1304. }
  1305. } else if (!strcmp(question, "circuit-status")) {
  1306. circuit_t *circ;
  1307. smartlist_t *status = smartlist_create();
  1308. for (circ = _circuit_get_global_list(); circ; circ = circ->next) {
  1309. char *s, *path;
  1310. size_t slen;
  1311. const char *state;
  1312. if (! CIRCUIT_IS_ORIGIN(circ) || circ->marked_for_close)
  1313. continue;
  1314. path = circuit_list_path(TO_ORIGIN_CIRCUIT(circ),0);
  1315. if (circ->state == CIRCUIT_STATE_OPEN)
  1316. state = "BUILT";
  1317. else if (strlen(path))
  1318. state = "EXTENDED";
  1319. else
  1320. state = "LAUNCHED";
  1321. slen = strlen(path)+strlen(state)+20;
  1322. s = tor_malloc(slen+1);
  1323. tor_snprintf(s, slen, "%lu %s %s",
  1324. (unsigned long)TO_ORIGIN_CIRCUIT(circ)->global_identifier,
  1325. state, path);
  1326. smartlist_add(status, s);
  1327. tor_free(path);
  1328. }
  1329. *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
  1330. SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
  1331. smartlist_free(status);
  1332. } else if (!strcmp(question, "stream-status")) {
  1333. connection_t **conns;
  1334. int n_conns, i;
  1335. char buf[256];
  1336. smartlist_t *status = smartlist_create();
  1337. get_connection_array(&conns, &n_conns);
  1338. for (i=0; i < n_conns; ++i) {
  1339. const char *state;
  1340. edge_connection_t *conn;
  1341. char *s;
  1342. size_t slen;
  1343. circuit_t *circ;
  1344. origin_circuit_t *origin_circ = NULL;
  1345. if (conns[i]->type != CONN_TYPE_AP ||
  1346. conns[i]->marked_for_close ||
  1347. conns[i]->state == AP_CONN_STATE_SOCKS_WAIT ||
  1348. conns[i]->state == AP_CONN_STATE_ORIGDST_WAIT)
  1349. continue;
  1350. conn = TO_EDGE_CONN(conns[i]);
  1351. switch (conn->_base.state)
  1352. {
  1353. case AP_CONN_STATE_CONTROLLER_WAIT:
  1354. case AP_CONN_STATE_CIRCUIT_WAIT:
  1355. if (conn->socks_request &&
  1356. (conn->socks_request->command == SOCKS_COMMAND_RESOLVE ||
  1357. conn->socks_request->command == SOCKS_COMMAND_RESOLVE_PTR))
  1358. state = "NEWRESOLVE";
  1359. else
  1360. state = "NEW";
  1361. break;
  1362. case AP_CONN_STATE_RENDDESC_WAIT:
  1363. case AP_CONN_STATE_CONNECT_WAIT:
  1364. state = "SENTCONNECT"; break;
  1365. case AP_CONN_STATE_RESOLVE_WAIT:
  1366. state = "SENTRESOLVE"; break;
  1367. case AP_CONN_STATE_OPEN:
  1368. state = "SUCCEEDED"; break;
  1369. default:
  1370. log_warn(LD_BUG, "Asked for stream in unknown state %d",
  1371. conn->_base.state);
  1372. continue;
  1373. }
  1374. circ = circuit_get_by_edge_conn(conn);
  1375. if (circ && CIRCUIT_IS_ORIGIN(circ))
  1376. origin_circ = TO_ORIGIN_CIRCUIT(circ);
  1377. write_stream_target_to_buf(conn, buf, sizeof(buf));
  1378. slen = strlen(buf)+strlen(state)+32;
  1379. s = tor_malloc(slen+1);
  1380. tor_snprintf(s, slen, "%lu %s %lu %s",
  1381. (unsigned long) conn->global_identifier,state,
  1382. origin_circ?
  1383. (unsigned long)origin_circ->global_identifier : 0ul,
  1384. buf);
  1385. smartlist_add(status, s);
  1386. }
  1387. *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
  1388. SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
  1389. smartlist_free(status);
  1390. } else if (!strcmp(question, "orconn-status")) {
  1391. connection_t **conns;
  1392. int n_conns, i;
  1393. smartlist_t *status = smartlist_create();
  1394. get_connection_array(&conns, &n_conns);
  1395. for (i=0; i < n_conns; ++i) {
  1396. const char *state;
  1397. char *s;
  1398. char name[128];
  1399. size_t slen;
  1400. or_connection_t *conn;
  1401. if (conns[i]->type != CONN_TYPE_OR || conns[i]->marked_for_close)
  1402. continue;
  1403. conn = TO_OR_CONN(conns[i]);
  1404. if (conn->_base.state == OR_CONN_STATE_OPEN)
  1405. state = "CONNECTED";
  1406. else if (conn->nickname)
  1407. state = "LAUNCHED";
  1408. else
  1409. state = "NEW";
  1410. if (conn->nickname)
  1411. strlcpy(name, conn->nickname, sizeof(name));
  1412. else
  1413. tor_snprintf(name, sizeof(name), "%s:%d",
  1414. conn->_base.address, conn->_base.port);
  1415. slen = strlen(name)+strlen(state)+2;
  1416. s = tor_malloc(slen+1);
  1417. tor_snprintf(s, slen, "%s %s", name, state);
  1418. smartlist_add(status, s);
  1419. }
  1420. *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
  1421. SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
  1422. smartlist_free(status);
  1423. } else if (!strcmpstart(question, "addr-mappings/")) {
  1424. time_t min_e, max_e;
  1425. smartlist_t *mappings;
  1426. if (!strcmp(question, "addr-mappings/all")) {
  1427. min_e = 0; max_e = TIME_MAX;
  1428. } else if (!strcmp(question, "addr-mappings/cache")) {
  1429. min_e = 2; max_e = TIME_MAX;
  1430. } else if (!strcmp(question, "addr-mappings/config")) {
  1431. min_e = 0; max_e = 0;
  1432. } else if (!strcmp(question, "addr-mappings/control")) {
  1433. min_e = 1; max_e = 1;
  1434. } else {
  1435. return 0;
  1436. }
  1437. mappings = smartlist_create();
  1438. addressmap_get_mappings(mappings, min_e, max_e);
  1439. *answer = smartlist_join_strings(mappings, "\r\n", 0, NULL);
  1440. SMARTLIST_FOREACH(mappings, char *, cp, tor_free(cp));
  1441. smartlist_free(mappings);
  1442. } else if (!strcmp(question, "address")) {
  1443. uint32_t addr;
  1444. if (router_pick_published_address(get_options(), &addr) < 0)
  1445. return -1;
  1446. *answer = tor_dup_addr(addr);
  1447. } else if (!strcmp(question, "dir-usage")) {
  1448. *answer = directory_dump_request_log();
  1449. } else if (!strcmpstart(question, "dir/server/")) {
  1450. size_t answer_len = 0, url_len = strlen(question)+2;
  1451. char *url = tor_malloc(url_len);
  1452. int res;
  1453. smartlist_t *descs = smartlist_create();
  1454. const char *msg;
  1455. char *cp;
  1456. tor_snprintf(url, url_len, "/tor/%s", question+4);
  1457. res = dirserv_get_routerdescs(descs, url, &msg);
  1458. SMARTLIST_FOREACH(descs, signed_descriptor_t *, sd,
  1459. answer_len += sd->signed_descriptor_len);
  1460. cp = *answer = tor_malloc(answer_len+1);
  1461. SMARTLIST_FOREACH(descs, signed_descriptor_t *, sd,
  1462. {
  1463. memcpy(cp, signed_descriptor_get_body(sd),
  1464. sd->signed_descriptor_len);
  1465. cp += sd->signed_descriptor_len;
  1466. });
  1467. *cp = '\0';
  1468. tor_free(url);
  1469. smartlist_free(descs);
  1470. } else if (!strcmpstart(question, "dir/status/")) {
  1471. smartlist_t *status_list;
  1472. size_t len;
  1473. char *cp;
  1474. if (!get_options()->DirPort) {
  1475. log_warn(LD_CONTROL, "getinfo dir/status/ requires an open dirport.");
  1476. return -1;
  1477. }
  1478. status_list = smartlist_create();
  1479. dirserv_get_networkstatus_v2(status_list,
  1480. question+strlen("dir/status/"));
  1481. len = 0;
  1482. SMARTLIST_FOREACH(status_list, cached_dir_t *, d, len += d->dir_len);
  1483. cp = *answer = tor_malloc(len+1);
  1484. SMARTLIST_FOREACH(status_list, cached_dir_t *, d, {
  1485. memcpy(cp, d->dir, d->dir_len);
  1486. cp += d->dir_len;
  1487. });
  1488. *cp = '\0';
  1489. } else if (!strcmpstart(question, "exit-policy/")) {
  1490. return policies_getinfo_helper(question, answer);
  1491. }
  1492. return 0; /* unrecognized */
  1493. }
  1494. /** Called when we receive a GETINFO command. Try to fetch all requested
  1495. * information, and reply with information or error message. */
  1496. static int
  1497. handle_control_getinfo(control_connection_t *conn, uint32_t len,
  1498. const char *body)
  1499. {
  1500. smartlist_t *questions = NULL;
  1501. smartlist_t *answers = NULL;
  1502. smartlist_t *unrecognized = NULL;
  1503. char *msg = NULL, *ans = NULL;
  1504. size_t msg_len;
  1505. int v0 = STATE_IS_V0(conn->_base.state);
  1506. (void) len; /* body is nul-terminated, so it's safe to ignore the length. */
  1507. questions = smartlist_create();
  1508. if (v0)
  1509. smartlist_split_string(questions, body, "\n",
  1510. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1511. else
  1512. smartlist_split_string(questions, body, " ",
  1513. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1514. answers = smartlist_create();
  1515. unrecognized = smartlist_create();
  1516. SMARTLIST_FOREACH(questions, const char *, q,
  1517. {
  1518. if (handle_getinfo_helper(q, &ans) < 0) {
  1519. if (v0)
  1520. send_control0_error(conn, ERR_INTERNAL, body);
  1521. else
  1522. connection_write_str_to_buf("551 Internal error\r\n", conn);
  1523. goto done;
  1524. }
  1525. if (!ans) {
  1526. if (v0) {
  1527. send_control0_error(conn, ERR_UNRECOGNIZED_CONFIG_KEY, body);
  1528. goto done;
  1529. } else
  1530. smartlist_add(unrecognized, (char*)q);
  1531. } else {
  1532. smartlist_add(answers, tor_strdup(q));
  1533. smartlist_add(answers, ans);
  1534. }
  1535. });
  1536. if (smartlist_len(unrecognized)) {
  1537. int i;
  1538. tor_assert(!v0);
  1539. for (i=0; i < smartlist_len(unrecognized)-1; ++i)
  1540. connection_printf_to_buf(conn,
  1541. "552-Unrecognized key \"%s\"\r\n",
  1542. (char*)smartlist_get(unrecognized, i));
  1543. connection_printf_to_buf(conn,
  1544. "552 Unrecognized key \"%s\"\r\n",
  1545. (char*)smartlist_get(unrecognized, i));
  1546. goto done;
  1547. }
  1548. if (v0) {
  1549. msg = smartlist_join_strings2(answers, "\0", 1, 1, &msg_len);
  1550. tor_assert(msg_len > 0); /* it will at least be terminated */
  1551. send_control0_message(conn, CONTROL0_CMD_INFOVALUE,
  1552. msg_len, msg);
  1553. } else {
  1554. int i;
  1555. for (i = 0; i < smartlist_len(answers); i += 2) {
  1556. char *k = smartlist_get(answers, i);
  1557. char *v = smartlist_get(answers, i+1);
  1558. if (!strchr(v, '\n') && !strchr(v, '\r')) {
  1559. connection_printf_to_buf(conn, "250-%s=", k);
  1560. connection_write_str_to_buf(v, conn);
  1561. connection_write_str_to_buf("\r\n", conn);
  1562. } else {
  1563. char *esc = NULL;
  1564. size_t len;
  1565. len = write_escaped_data(v, strlen(v), 1, &esc);
  1566. connection_printf_to_buf(conn, "250+%s=\r\n", k);
  1567. connection_write_to_buf(esc, len, TO_CONN(conn));
  1568. tor_free(esc);
  1569. }
  1570. }
  1571. connection_write_str_to_buf("250 OK\r\n", conn);
  1572. }
  1573. done:
  1574. if (answers) {
  1575. SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
  1576. smartlist_free(answers);
  1577. }
  1578. if (questions) {
  1579. SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
  1580. smartlist_free(questions);
  1581. }
  1582. smartlist_free(unrecognized);
  1583. tor_free(msg);
  1584. return 0;
  1585. }
  1586. /** If *<b>string</b> contains a recognized purpose (for
  1587. * circuits if <b>for_circuits</b> is 1, else for routers),
  1588. * possibly prefaced with the string "purpose=", then assign it
  1589. * and return 0. Otherwise return -1.
  1590. *
  1591. * If it's prefaced with "purpose=", then set *<b>string</b> to
  1592. * the remainder of the string. */
  1593. static int
  1594. get_purpose(char **string, int for_circuits, uint8_t *purpose)
  1595. {
  1596. if (!strcmpstart(*string, "purpose="))
  1597. *string += strlen("purpose=");
  1598. if (!strcmp(*string, "general"))
  1599. *purpose = for_circuits ? CIRCUIT_PURPOSE_C_GENERAL :
  1600. ROUTER_PURPOSE_GENERAL;
  1601. else if (!strcmp(*string, "controller"))
  1602. *purpose = for_circuits ? CIRCUIT_PURPOSE_CONTROLLER :
  1603. ROUTER_PURPOSE_GENERAL;
  1604. else { /* not a recognized purpose */
  1605. return -1;
  1606. }
  1607. return 0;
  1608. }
  1609. /** Called when we get an EXTENDCIRCUIT message. Try to extend the listed
  1610. * circuit, and report success or failure. */
  1611. static int
  1612. handle_control_extendcircuit(control_connection_t *conn, uint32_t len,
  1613. const char *body)
  1614. {
  1615. smartlist_t *router_nicknames=NULL, *routers=NULL;
  1616. uint32_t circ_id;
  1617. origin_circuit_t *circ = NULL;
  1618. int zero_circ, v0;
  1619. char reply[4];
  1620. uint8_t intended_purpose = CIRCUIT_PURPOSE_C_GENERAL;
  1621. v0 = STATE_IS_V0(conn->_base.state);
  1622. router_nicknames = smartlist_create();
  1623. if (v0) {
  1624. if (len<5) {
  1625. send_control0_error(conn, ERR_SYNTAX, "extendcircuit message too short");
  1626. goto done;
  1627. }
  1628. smartlist_split_string(router_nicknames, body+4, ",", 0, 0);
  1629. circ_id = ntohl(get_uint32(body));
  1630. if (!circ_id) {
  1631. /* start a new circuit */
  1632. zero_circ = 1;
  1633. } else {
  1634. circ = circuit_get_by_global_id(circ_id);
  1635. zero_circ = 0;
  1636. if (!circ) {
  1637. send_control0_error(conn, ERR_NO_CIRC,
  1638. "No circuit found with given ID");
  1639. goto done;
  1640. }
  1641. }
  1642. } else { /* v1 */
  1643. smartlist_t *args;
  1644. args = smartlist_create();
  1645. smartlist_split_string(args, body, " ",
  1646. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1647. if (smartlist_len(args)<2) {
  1648. connection_printf_to_buf(conn,
  1649. "512 Missing argument to EXTENDCIRCUIT\r\n");
  1650. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1651. smartlist_free(args);
  1652. goto done;
  1653. }
  1654. zero_circ = !strcmp("0", (char*)smartlist_get(args,0));
  1655. if (!zero_circ && !(circ = get_circ(smartlist_get(args,0)))) {
  1656. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  1657. (char*)smartlist_get(args, 0));
  1658. }
  1659. smartlist_split_string(router_nicknames, smartlist_get(args,1), ",", 0, 0);
  1660. if (zero_circ && smartlist_len(args)>2) {
  1661. char *purp = smartlist_get(args,2);
  1662. if (get_purpose(&purp, 1, &intended_purpose) < 0) {
  1663. connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n", purp);
  1664. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1665. smartlist_free(args);
  1666. goto done;
  1667. }
  1668. }
  1669. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1670. smartlist_free(args);
  1671. if (!zero_circ && !circ) {
  1672. goto done;
  1673. }
  1674. }
  1675. routers = smartlist_create();
  1676. SMARTLIST_FOREACH(router_nicknames, const char *, n,
  1677. {
  1678. routerinfo_t *r = router_get_by_nickname(n, 1);
  1679. if (!r) {
  1680. if (v0)
  1681. send_control0_error(conn, ERR_NO_ROUTER, n);
  1682. else
  1683. connection_printf_to_buf(conn, "552 No such router \"%s\"\r\n", n);
  1684. goto done;
  1685. }
  1686. smartlist_add(routers, r);
  1687. });
  1688. if (!smartlist_len(routers)) {
  1689. if (v0)
  1690. send_control0_error(conn, ERR_SYNTAX, "No router names provided");
  1691. else
  1692. connection_write_str_to_buf("512 No router names provided\r\n", conn);
  1693. goto done;
  1694. }
  1695. if (zero_circ) {
  1696. /* start a new circuit */
  1697. circ = origin_circuit_init(intended_purpose, 0, 0, 0);
  1698. }
  1699. /* now circ refers to something that is ready to be extended */
  1700. SMARTLIST_FOREACH(routers, routerinfo_t *, r,
  1701. {
  1702. extend_info_t *info = extend_info_from_router(r);
  1703. circuit_append_new_exit(circ, info);
  1704. extend_info_free(info);
  1705. });
  1706. /* now that we've populated the cpath, start extending */
  1707. if (zero_circ) {
  1708. if (circuit_handle_first_hop(circ) < 0) {
  1709. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_AT_ORIGIN);
  1710. if (v0)
  1711. send_control0_error(conn, ERR_INTERNAL, "couldn't start circuit");
  1712. else
  1713. connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn);
  1714. goto done;
  1715. }
  1716. } else {
  1717. if (circ->_base.state == CIRCUIT_STATE_OPEN) {
  1718. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
  1719. if (circuit_send_next_onion_skin(circ) < 0) {
  1720. log_info(LD_CONTROL,
  1721. "send_next_onion_skin failed; circuit marked for closing.");
  1722. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_AT_ORIGIN);
  1723. if (v0)
  1724. send_control0_error(conn, ERR_INTERNAL, "couldn't send onion skin");
  1725. else
  1726. connection_write_str_to_buf("551 Couldn't send onion skinr\n", conn);
  1727. goto done;
  1728. }
  1729. }
  1730. }
  1731. if (v0) {
  1732. set_uint32(reply, htonl(circ->global_identifier));
  1733. send_control_done2(conn, reply, sizeof(reply));
  1734. } else {
  1735. connection_printf_to_buf(conn, "250 EXTENDED %lu\r\n",
  1736. (unsigned long)circ->global_identifier);
  1737. }
  1738. done:
  1739. SMARTLIST_FOREACH(router_nicknames, char *, n, tor_free(n));
  1740. smartlist_free(router_nicknames);
  1741. if (routers)
  1742. smartlist_free(routers);
  1743. return 0;
  1744. }
  1745. /** Called when we get a SETCIRCUITPURPOSE (if <b>for_circuits</b>
  1746. * is 1) or SETROUTERPURPOSE message. If we can find
  1747. * the circuit/router and it's a valid purpose, change it. */
  1748. static int
  1749. handle_control_setpurpose(control_connection_t *conn, int for_circuits,
  1750. uint32_t len, const char *body)
  1751. {
  1752. origin_circuit_t *circ = NULL;
  1753. routerinfo_t *ri = NULL;
  1754. uint8_t new_purpose;
  1755. smartlist_t *args = smartlist_create();
  1756. (void) len; /* body is nul-terminated, so it's safe to ignore the length. */
  1757. smartlist_split_string(args, body, " ",
  1758. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1759. if (smartlist_len(args)<2) {
  1760. connection_printf_to_buf(conn,
  1761. "512 Missing argument to SET%sPURPOSE\r\n",
  1762. for_circuits ? "CIRCUIT" : "ROUTER");
  1763. goto done;
  1764. }
  1765. if (for_circuits) {
  1766. if (!(circ = get_circ(smartlist_get(args,0)))) {
  1767. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  1768. (char*)smartlist_get(args, 0));
  1769. goto done;
  1770. }
  1771. } else {
  1772. if (!(ri = router_get_by_nickname(smartlist_get(args,0), 0))) {
  1773. connection_printf_to_buf(conn, "552 Unknown router \"%s\"\r\n",
  1774. (char*)smartlist_get(args, 0));
  1775. goto done;
  1776. }
  1777. }
  1778. {
  1779. char *purp = smartlist_get(args,1);
  1780. if (get_purpose(&purp, for_circuits, &new_purpose) < 0) {
  1781. connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n", purp);
  1782. goto done;
  1783. }
  1784. }
  1785. if (for_circuits)
  1786. circ->_base.purpose = new_purpose;
  1787. else
  1788. ri->purpose = new_purpose;
  1789. connection_write_str_to_buf("250 OK\r\n", conn);
  1790. done:
  1791. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1792. smartlist_free(args);
  1793. return 0;
  1794. }
  1795. /** Called when we get an ATTACHSTREAM message. Try to attach the requested
  1796. * stream, and report success or failure. */
  1797. static int
  1798. handle_control_attachstream(control_connection_t *conn, uint32_t len,
  1799. const char *body)
  1800. {
  1801. edge_connection_t *ap_conn = NULL;
  1802. origin_circuit_t *circ = NULL;
  1803. int zero_circ;
  1804. if (STATE_IS_V0(conn->_base.state)) {
  1805. uint32_t conn_id;
  1806. uint32_t circ_id;
  1807. if (len < 8) {
  1808. send_control0_error(conn, ERR_SYNTAX, "attachstream message too short");
  1809. return 0;
  1810. }
  1811. conn_id = ntohl(get_uint32(body));
  1812. circ_id = ntohl(get_uint32(body+4));
  1813. zero_circ = circ_id == 0;
  1814. if (!(ap_conn = connection_get_by_global_id(conn_id))) {
  1815. send_control0_error(conn, ERR_NO_STREAM,
  1816. "No connection found with given ID");
  1817. return 0;
  1818. }
  1819. if (circ_id && !(circ = circuit_get_by_global_id(circ_id))) {
  1820. send_control0_error(conn, ERR_NO_CIRC, "No circuit found with given ID");
  1821. return 0;
  1822. }
  1823. } else {
  1824. smartlist_t *args;
  1825. args = smartlist_create();
  1826. smartlist_split_string(args, body, " ",
  1827. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1828. if (smartlist_len(args)<2) {
  1829. connection_printf_to_buf(conn,
  1830. "512 Missing argument to ATTACHSTREAM\r\n");
  1831. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1832. smartlist_free(args);
  1833. return 0;
  1834. }
  1835. zero_circ = !strcmp("0", (char*)smartlist_get(args,1));
  1836. if (!(ap_conn = get_stream(smartlist_get(args, 0)))) {
  1837. connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
  1838. (char*)smartlist_get(args, 0));
  1839. } else if (!zero_circ && !(circ = get_circ(smartlist_get(args, 1)))) {
  1840. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  1841. (char*)smartlist_get(args, 1));
  1842. }
  1843. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1844. smartlist_free(args);
  1845. if (!ap_conn || (!zero_circ && !circ))
  1846. return 0;
  1847. }
  1848. if (ap_conn->_base.state != AP_CONN_STATE_CONTROLLER_WAIT &&
  1849. ap_conn->_base.state != AP_CONN_STATE_CONNECT_WAIT &&
  1850. ap_conn->_base.state != AP_CONN_STATE_RESOLVE_WAIT) {
  1851. if (STATE_IS_V0(conn->_base.state)) {
  1852. send_control0_error(conn, ERR_NO_STREAM,
  1853. "Connection is not managed by controller.");
  1854. } else {
  1855. connection_write_str_to_buf(
  1856. "555 Connection is not managed by controller.\r\n",
  1857. conn);
  1858. }
  1859. return 0;
  1860. }
  1861. /* Do we need to detach it first? */
  1862. if (ap_conn->_base.state != AP_CONN_STATE_CONTROLLER_WAIT) {
  1863. circuit_t *tmpcirc = circuit_get_by_edge_conn(ap_conn);
  1864. connection_edge_end(ap_conn, END_STREAM_REASON_TIMEOUT,
  1865. ap_conn->cpath_layer);
  1866. /* Un-mark it as ending, since we're going to reuse it. */
  1867. ap_conn->_base.edge_has_sent_end = 0;
  1868. if (tmpcirc)
  1869. circuit_detach_stream(tmpcirc,ap_conn);
  1870. ap_conn->_base.state = AP_CONN_STATE_CONTROLLER_WAIT;
  1871. }
  1872. if (circ && (circ->_base.state != CIRCUIT_STATE_OPEN)) {
  1873. if (STATE_IS_V0(conn->_base.state))
  1874. send_control0_error(conn, ERR_INTERNAL,
  1875. "Refuse to attach stream to non-open, origin circ.");
  1876. else
  1877. connection_write_str_to_buf(
  1878. "551 Can't attach stream to non-open, origin circuit\r\n",
  1879. conn);
  1880. return 0;
  1881. }
  1882. if (connection_ap_handshake_rewrite_and_attach(ap_conn, circ) < 0) {
  1883. if (STATE_IS_V0(conn->_base.state))
  1884. send_control0_error(conn, ERR_INTERNAL, "Unable to attach stream.");
  1885. else
  1886. connection_write_str_to_buf("551 Unable to attach stream\r\n", conn);
  1887. return 0;
  1888. }
  1889. send_control_done(conn);
  1890. return 0;
  1891. }
  1892. /** Called when we get a POSTDESCRIPTOR message. Try to learn the provided
  1893. * descriptor, and report success or failure. */
  1894. static int
  1895. handle_control_postdescriptor(control_connection_t *conn, uint32_t len,
  1896. const char *body)
  1897. {
  1898. char *desc;
  1899. int v0 = STATE_IS_V0(conn->_base.state);
  1900. const char *msg=NULL;
  1901. uint8_t purpose = ROUTER_PURPOSE_GENERAL;
  1902. if (v0)
  1903. desc = (char*)body;
  1904. else {
  1905. char *cp = memchr(body, '\n', len);
  1906. smartlist_t *args = smartlist_create();
  1907. tor_assert(cp);
  1908. *cp++ = '\0';
  1909. smartlist_split_string(args, body, " ",
  1910. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1911. if (smartlist_len(args)) {
  1912. char *purp = smartlist_get(args,0);
  1913. if (get_purpose(&purp, 0, &purpose) < 0) {
  1914. connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n",
  1915. purp);
  1916. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1917. smartlist_free(args);
  1918. return 0;
  1919. }
  1920. }
  1921. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1922. smartlist_free(args);
  1923. read_escaped_data(cp, len-(cp-body), 1, &desc);
  1924. }
  1925. switch (router_load_single_router(desc, purpose, &msg)) {
  1926. case -1:
  1927. if (!msg) msg = "Could not parse descriptor";
  1928. if (v0)
  1929. send_control0_error(conn,ERR_SYNTAX,msg);
  1930. else
  1931. connection_printf_to_buf(conn, "554 %s\r\n", msg);
  1932. break;
  1933. case 0:
  1934. if (!msg) msg = "Descriptor not added";
  1935. if (v0)
  1936. send_control_done2(conn,msg,0);
  1937. else
  1938. connection_printf_to_buf(conn, "251 %s\r\n",msg);
  1939. break;
  1940. case 1:
  1941. send_control_done(conn);
  1942. break;
  1943. }
  1944. if (!v0)
  1945. tor_free(desc);
  1946. return 0;
  1947. }
  1948. /** Called when we receive a REDIRECTSTERAM command. Try to change the target
  1949. * address of the named AP stream, and report success or failure. */
  1950. static int
  1951. handle_control_redirectstream(control_connection_t *conn, uint32_t len,
  1952. const char *body)
  1953. {
  1954. edge_connection_t *ap_conn = NULL;
  1955. uint32_t conn_id;
  1956. char *new_addr = NULL;
  1957. uint16_t new_port = 0;
  1958. if (STATE_IS_V0(conn->_base.state)) {
  1959. if (len < 6) {
  1960. send_control0_error(conn, ERR_SYNTAX,
  1961. "redirectstream message too short");
  1962. return 0;
  1963. }
  1964. conn_id = ntohl(get_uint32(body));
  1965. if (!(ap_conn = connection_get_by_global_id(conn_id))
  1966. || ap_conn->_base.state != CONN_TYPE_AP
  1967. || ap_conn->socks_request) {
  1968. send_control0_error(conn, ERR_NO_STREAM,
  1969. "No AP connection found with given ID");
  1970. return 0;
  1971. }
  1972. new_addr = tor_strdup(body+4);
  1973. } else {
  1974. smartlist_t *args;
  1975. args = smartlist_create();
  1976. smartlist_split_string(args, body, " ",
  1977. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1978. if (smartlist_len(args) < 2)
  1979. connection_printf_to_buf(conn,
  1980. "512 Missing argument to REDIRECTSTREAM\r\n");
  1981. else if (!(ap_conn = get_stream(smartlist_get(args, 0)))
  1982. || !ap_conn->socks_request) {
  1983. connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
  1984. (char*)smartlist_get(args, 0));
  1985. } else {
  1986. int ok;
  1987. if (smartlist_len(args) > 2) { /* they included a port too */
  1988. new_port = (uint16_t) tor_parse_ulong(smartlist_get(args, 2),
  1989. 10, 1, 65535, &ok, NULL);
  1990. }
  1991. if (!ok) {
  1992. connection_printf_to_buf(conn, "512 Cannot parse port \"%s\"\r\n",
  1993. (char*)smartlist_get(args, 2));
  1994. } else {
  1995. new_addr = tor_strdup(smartlist_get(args, 1));
  1996. }
  1997. }
  1998. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1999. smartlist_free(args);
  2000. if (!new_addr)
  2001. return 0;
  2002. }
  2003. strlcpy(ap_conn->socks_request->address, new_addr,
  2004. sizeof(ap_conn->socks_request->address));
  2005. if (new_port)
  2006. ap_conn->socks_request->port = new_port;
  2007. tor_free(new_addr);
  2008. send_control_done(conn);
  2009. return 0;
  2010. }
  2011. /** Called when we get a CLOSESTREAM command; try to close the named stream
  2012. * and report success or failure. */
  2013. static int
  2014. handle_control_closestream(control_connection_t *conn, uint32_t len,
  2015. const char *body)
  2016. {
  2017. edge_connection_t *ap_conn=NULL;
  2018. uint8_t reason=0;
  2019. if (STATE_IS_V0(conn->_base.state)) {
  2020. uint32_t conn_id;
  2021. if (len < 6) {
  2022. send_control0_error(conn, ERR_SYNTAX, "closestream message too short");
  2023. return 0;
  2024. }
  2025. conn_id = ntohl(get_uint32(body));
  2026. reason = *(uint8_t*)(body+4);
  2027. if (!(ap_conn = connection_get_by_global_id(conn_id))
  2028. || ap_conn->_base.state != CONN_TYPE_AP
  2029. || ap_conn->socks_request) {
  2030. send_control0_error(conn, ERR_NO_STREAM,
  2031. "No AP connection found with given ID");
  2032. return 0;
  2033. }
  2034. } else {
  2035. smartlist_t *args;
  2036. int ok;
  2037. args = smartlist_create();
  2038. smartlist_split_string(args, body, " ",
  2039. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2040. if (smartlist_len(args)<2)
  2041. connection_printf_to_buf(conn,
  2042. "512 Missing argument to CLOSESTREAM\r\n");
  2043. else if (!(ap_conn = get_stream(smartlist_get(args, 0))))
  2044. connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
  2045. (char*)smartlist_get(args, 0));
  2046. else {
  2047. reason = (uint8_t) tor_parse_ulong(smartlist_get(args,1), 10, 0, 255,
  2048. &ok, NULL);
  2049. if (!ok) {
  2050. connection_printf_to_buf(conn, "552 Unrecognized reason \"%s\"\r\n",
  2051. (char*)smartlist_get(args, 1));
  2052. ap_conn = NULL;
  2053. }
  2054. }
  2055. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2056. smartlist_free(args);
  2057. if (!ap_conn)
  2058. return 0;
  2059. }
  2060. connection_mark_unattached_ap(ap_conn, reason);
  2061. send_control_done(conn);
  2062. return 0;
  2063. }
  2064. /** Called when we get a CLOSECIRCUIT command; try to close the named circuit
  2065. * and report success or failure. */
  2066. static int
  2067. handle_control_closecircuit(control_connection_t *conn, uint32_t len,
  2068. const char *body)
  2069. {
  2070. origin_circuit_t *circ = NULL;
  2071. int safe = 0;
  2072. if (STATE_IS_V0(conn->_base.state)) {
  2073. uint32_t circ_id;
  2074. if (len < 5) {
  2075. send_control0_error(conn, ERR_SYNTAX, "closecircuit message too short");
  2076. return 0;
  2077. }
  2078. circ_id = ntohl(get_uint32(body));
  2079. safe = (*(uint8_t*)(body+4)) & 1;
  2080. if (!(circ = circuit_get_by_global_id(circ_id))) {
  2081. send_control0_error(conn, ERR_NO_CIRC,
  2082. "No circuit found with given ID");
  2083. return 0;
  2084. }
  2085. } else {
  2086. smartlist_t *args;
  2087. args = smartlist_create();
  2088. smartlist_split_string(args, body, " ",
  2089. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2090. if (smartlist_len(args)<1)
  2091. connection_printf_to_buf(conn,
  2092. "512 Missing argument to CLOSECIRCUIT\r\n");
  2093. else if (!(circ=get_circ(smartlist_get(args, 0))))
  2094. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  2095. (char*)smartlist_get(args, 0));
  2096. else {
  2097. int i;
  2098. for (i=1; i < smartlist_len(args); ++i) {
  2099. if (!strcasecmp(smartlist_get(args, i), "IfUnused"))
  2100. safe = 1;
  2101. else
  2102. log_info(LD_CONTROL, "Skipping unknown option %s",
  2103. (char*)smartlist_get(args,i));
  2104. }
  2105. }
  2106. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2107. smartlist_free(args);
  2108. if (!circ)
  2109. return 0;
  2110. }
  2111. if (!safe || !circ->p_streams) {
  2112. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_NONE);
  2113. }
  2114. send_control_done(conn);
  2115. return 0;
  2116. }
  2117. /** Called when we get a v0 FRAGMENTHEADER or FRAGMENT command; try to append
  2118. * the data to conn->incoming_cmd, setting conn->incoming_(type|len|cur_len)
  2119. * as appropriate. If the command is malformed, drop it and all pending
  2120. * fragments and report failure.
  2121. */
  2122. static int
  2123. handle_control_fragments(control_connection_t *conn, uint16_t command_type,
  2124. uint32_t body_len, char *body)
  2125. {
  2126. if (command_type == CONTROL0_CMD_FRAGMENTHEADER) {
  2127. if (conn->incoming_cmd) {
  2128. log_warn(LD_CONTROL, "Dropping incomplete fragmented command");
  2129. tor_free(conn->incoming_cmd);
  2130. }
  2131. if (body_len < 6) {
  2132. send_control0_error(conn, ERR_SYNTAX, "FRAGMENTHEADER too short.");
  2133. return 0;
  2134. }
  2135. conn->incoming_cmd_type = ntohs(get_uint16(body));
  2136. conn->incoming_cmd_len = ntohl(get_uint32(body+2));
  2137. conn->incoming_cmd_cur_len = 0;
  2138. conn->incoming_cmd = tor_malloc(conn->incoming_cmd_len);
  2139. body += 6;
  2140. body_len -= 6;
  2141. } else if (command_type == CONTROL0_CMD_FRAGMENT) {
  2142. if (!conn->incoming_cmd) {
  2143. send_control0_error(conn, ERR_SYNTAX, "Out-of-place FRAGMENT");
  2144. return 0;
  2145. }
  2146. } else {
  2147. tor_assert(0);
  2148. }
  2149. if (conn->incoming_cmd_cur_len + body_len > conn->incoming_cmd_len) {
  2150. tor_free(conn->incoming_cmd);
  2151. send_control0_error(conn, ERR_SYNTAX,
  2152. "Fragmented data exceeds declared length");
  2153. return 0;
  2154. }
  2155. memcpy(conn->incoming_cmd + conn->incoming_cmd_cur_len,
  2156. body, body_len);
  2157. conn->incoming_cmd_cur_len += body_len;
  2158. return 0;
  2159. }
  2160. /** Called when <b>conn</b> has no more bytes left on its outbuf. */
  2161. int
  2162. connection_control_finished_flushing(control_connection_t *conn)
  2163. {
  2164. tor_assert(conn);
  2165. connection_stop_writing(TO_CONN(conn));
  2166. return 0;
  2167. }
  2168. /** Called when <b>conn</b> has gotten its socket closed. */
  2169. int
  2170. connection_control_reached_eof(control_connection_t *conn)
  2171. {
  2172. tor_assert(conn);
  2173. log_info(LD_CONTROL,"Control connection reached EOF. Closing.");
  2174. connection_mark_for_close(TO_CONN(conn));
  2175. return 0;
  2176. }
  2177. /** Called when data has arrived on a v1 control connection: Try to fetch
  2178. * commands from conn->inbuf, and execute them.
  2179. */
  2180. static int
  2181. connection_control_process_inbuf_v1(control_connection_t *conn)
  2182. {
  2183. size_t data_len;
  2184. int cmd_len;
  2185. char *args;
  2186. tor_assert(conn);
  2187. tor_assert(conn->_base.state == CONTROL_CONN_STATE_OPEN_V1 ||
  2188. conn->_base.state == CONTROL_CONN_STATE_NEEDAUTH_V1);
  2189. if (!conn->incoming_cmd) {
  2190. conn->incoming_cmd = tor_malloc(1024);
  2191. conn->incoming_cmd_len = 1024;
  2192. conn->incoming_cmd_cur_len = 0;
  2193. }
  2194. again:
  2195. while (1) {
  2196. size_t last_idx;
  2197. int r;
  2198. /* First, fetch a line. */
  2199. do {
  2200. data_len = conn->incoming_cmd_len - conn->incoming_cmd_cur_len;
  2201. r = fetch_from_buf_line(conn->_base.inbuf,
  2202. conn->incoming_cmd+conn->incoming_cmd_cur_len,
  2203. &data_len);
  2204. if (r == 0)
  2205. /* Line not all here yet. Wait. */
  2206. return 0;
  2207. else if (r == -1) {
  2208. while (conn->incoming_cmd_len < data_len+conn->incoming_cmd_cur_len)
  2209. conn->incoming_cmd_len *= 2;
  2210. conn->incoming_cmd = tor_realloc(conn->incoming_cmd,
  2211. conn->incoming_cmd_len);
  2212. }
  2213. } while (r != 1);
  2214. tor_assert(data_len);
  2215. last_idx = conn->incoming_cmd_cur_len;
  2216. conn->incoming_cmd_cur_len += data_len;
  2217. /* We have appended a line to incoming_cmd. Is the command done? */
  2218. if (last_idx == 0 && *conn->incoming_cmd != '+')
  2219. /* One line command, didn't start with '+'. */
  2220. break;
  2221. if (last_idx+3 == conn->incoming_cmd_cur_len &&
  2222. !memcmp(conn->incoming_cmd + last_idx, ".\r\n", 3)) {
  2223. /* Just appended ".\r\n"; we're done. Remove it. */
  2224. conn->incoming_cmd_cur_len -= 3;
  2225. break;
  2226. }
  2227. /* Otherwise, read another line. */
  2228. }
  2229. data_len = conn->incoming_cmd_cur_len;
  2230. /* Okay, we now have a command sitting on conn->incoming_cmd. See if we
  2231. * recognize it.
  2232. */
  2233. cmd_len = 0;
  2234. while ((size_t)cmd_len < data_len
  2235. && !TOR_ISSPACE(conn->incoming_cmd[cmd_len]))
  2236. ++cmd_len;
  2237. data_len -= cmd_len;
  2238. conn->incoming_cmd[cmd_len]='\0';
  2239. args = conn->incoming_cmd+cmd_len+1;
  2240. while (*args == ' ' || *args == '\t') {
  2241. ++args;
  2242. --data_len;
  2243. }
  2244. if (!strcasecmp(conn->incoming_cmd, "QUIT")) {
  2245. connection_write_str_to_buf("250 closing connection\r\n", conn);
  2246. connection_mark_for_close(TO_CONN(conn));
  2247. return 0;
  2248. }
  2249. if (conn->_base.state == CONTROL_CONN_STATE_NEEDAUTH_V1 &&
  2250. strcasecmp(conn->incoming_cmd, "AUTHENTICATE")) {
  2251. connection_write_str_to_buf("514 Authentication required.\r\n", conn);
  2252. conn->incoming_cmd_cur_len = 0;
  2253. goto again;
  2254. }
  2255. if (!strcasecmp(conn->incoming_cmd, "SETCONF")) {
  2256. if (handle_control_setconf(conn, data_len, args))
  2257. return -1;
  2258. } else if (!strcasecmp(conn->incoming_cmd, "RESETCONF")) {
  2259. if (handle_control_resetconf(conn, data_len, args))
  2260. return -1;
  2261. } else if (!strcasecmp(conn->incoming_cmd, "GETCONF")) {
  2262. if (handle_control_getconf(conn, data_len, args))
  2263. return -1;
  2264. } else if (!strcasecmp(conn->incoming_cmd, "SETEVENTS")) {
  2265. if (handle_control_setevents(conn, data_len, args))
  2266. return -1;
  2267. } else if (!strcasecmp(conn->incoming_cmd, "AUTHENTICATE")) {
  2268. if (handle_control_authenticate(conn, data_len, args))
  2269. return -1;
  2270. } else if (!strcasecmp(conn->incoming_cmd, "SAVECONF")) {
  2271. if (handle_control_saveconf(conn, data_len, args))
  2272. return -1;
  2273. } else if (!strcasecmp(conn->incoming_cmd, "SIGNAL")) {
  2274. if (handle_control_signal(conn, data_len, args))
  2275. return -1;
  2276. } else if (!strcasecmp(conn->incoming_cmd, "MAPADDRESS")) {
  2277. if (handle_control_mapaddress(conn, data_len, args))
  2278. return -1;
  2279. } else if (!strcasecmp(conn->incoming_cmd, "GETINFO")) {
  2280. if (handle_control_getinfo(conn, data_len, args))
  2281. return -1;
  2282. } else if (!strcasecmp(conn->incoming_cmd, "EXTENDCIRCUIT")) {
  2283. if (handle_control_extendcircuit(conn, data_len, args))
  2284. return -1;
  2285. } else if (!strcasecmp(conn->incoming_cmd, "SETCIRCUITPURPOSE")) {
  2286. if (handle_control_setpurpose(conn, 1, data_len, args))
  2287. return -1;
  2288. } else if (!strcasecmp(conn->incoming_cmd, "SETROUTERPURPOSE")) {
  2289. if (handle_control_setpurpose(conn, 0, data_len, args))
  2290. return -1;
  2291. } else if (!strcasecmp(conn->incoming_cmd, "ATTACHSTREAM")) {
  2292. if (handle_control_attachstream(conn, data_len, args))
  2293. return -1;
  2294. } else if (!strcasecmp(conn->incoming_cmd, "+POSTDESCRIPTOR")) {
  2295. if (handle_control_postdescriptor(conn, data_len, args))
  2296. return -1;
  2297. } else if (!strcasecmp(conn->incoming_cmd, "REDIRECTSTREAM")) {
  2298. if (handle_control_redirectstream(conn, data_len, args))
  2299. return -1;
  2300. } else if (!strcasecmp(conn->incoming_cmd, "CLOSESTREAM")) {
  2301. if (handle_control_closestream(conn, data_len, args))
  2302. return -1;
  2303. } else if (!strcasecmp(conn->incoming_cmd, "CLOSECIRCUIT")) {
  2304. if (handle_control_closecircuit(conn, data_len, args))
  2305. return -1;
  2306. } else {
  2307. connection_printf_to_buf(conn, "510 Unrecognized command \"%s\"\r\n",
  2308. conn->incoming_cmd);
  2309. }
  2310. conn->incoming_cmd_cur_len = 0;
  2311. goto again;
  2312. }
  2313. /** Called when data has arrived on a v0 control connection: Try to fetch
  2314. * commands from conn->inbuf, and execute them.
  2315. */
  2316. static int
  2317. connection_control_process_inbuf_v0(control_connection_t *conn)
  2318. {
  2319. uint32_t body_len;
  2320. uint16_t command_type;
  2321. char *body=NULL;
  2322. again:
  2323. /* Try to suck a control message from the buffer. */
  2324. switch (fetch_from_buf_control0(conn->_base.inbuf, &body_len, &command_type,
  2325. &body,
  2326. conn->_base.state == CONTROL_CONN_STATE_NEEDAUTH_V0))
  2327. {
  2328. case -2:
  2329. tor_free(body);
  2330. log_info(LD_CONTROL,
  2331. "Detected v1 control protocol on connection (fd %d)",
  2332. conn->_base.s);
  2333. conn->_base.state = CONTROL_CONN_STATE_NEEDAUTH_V1;
  2334. return connection_control_process_inbuf_v1(conn);
  2335. case -1:
  2336. tor_free(body);
  2337. log_warn(LD_CONTROL, "Error in control command. Failing.");
  2338. return -1;
  2339. case 0:
  2340. /* Control command not all here yet. Wait. */
  2341. return 0;
  2342. case 1:
  2343. /* We got a command. Process it. */
  2344. break;
  2345. default:
  2346. tor_assert(0);
  2347. }
  2348. /* We got a command. If we need authentication, only authentication
  2349. * commands will be considered. */
  2350. if (conn->_base.state == CONTROL_CONN_STATE_NEEDAUTH_V0 &&
  2351. command_type != CONTROL0_CMD_AUTHENTICATE) {
  2352. log_info(LD_CONTROL, "Rejecting '%s' command; authentication needed.",
  2353. control_cmd_to_string(command_type));
  2354. send_control0_error(conn, ERR_UNAUTHORIZED, "Authentication required");
  2355. tor_free(body);
  2356. goto again;
  2357. }
  2358. if (command_type == CONTROL0_CMD_FRAGMENTHEADER ||
  2359. command_type == CONTROL0_CMD_FRAGMENT) {
  2360. if (handle_control_fragments(conn, command_type, body_len, body))
  2361. return -1;
  2362. tor_free(body);
  2363. if (conn->incoming_cmd_cur_len != conn->incoming_cmd_len)
  2364. goto again;
  2365. command_type = conn->incoming_cmd_type;
  2366. body_len = conn->incoming_cmd_len;
  2367. body = conn->incoming_cmd;
  2368. conn->incoming_cmd = NULL;
  2369. } else if (conn->incoming_cmd) {
  2370. log_warn(LD_CONTROL, "Dropping incomplete fragmented command");
  2371. tor_free(conn->incoming_cmd);
  2372. }
  2373. /* Okay, we're willing to process the command. */
  2374. switch (command_type)
  2375. {
  2376. case CONTROL0_CMD_SETCONF:
  2377. if (handle_control_setconf(conn, body_len, body))
  2378. return -1;
  2379. break;
  2380. case CONTROL0_CMD_GETCONF:
  2381. if (handle_control_getconf(conn, body_len, body))
  2382. return -1;
  2383. break;
  2384. case CONTROL0_CMD_SETEVENTS:
  2385. if (handle_control_setevents(conn, body_len, body))
  2386. return -1;
  2387. break;
  2388. case CONTROL0_CMD_AUTHENTICATE:
  2389. if (handle_control_authenticate(conn, body_len, body))
  2390. return -1;
  2391. break;
  2392. case CONTROL0_CMD_SAVECONF:
  2393. if (handle_control_saveconf(conn, body_len, body))
  2394. return -1;
  2395. break;
  2396. case CONTROL0_CMD_SIGNAL:
  2397. if (handle_control_signal(conn, body_len, body))
  2398. return -1;
  2399. break;
  2400. case CONTROL0_CMD_MAPADDRESS:
  2401. if (handle_control_mapaddress(conn, body_len, body))
  2402. return -1;
  2403. break;
  2404. case CONTROL0_CMD_GETINFO:
  2405. if (handle_control_getinfo(conn, body_len, body))
  2406. return -1;
  2407. break;
  2408. case CONTROL0_CMD_EXTENDCIRCUIT:
  2409. if (handle_control_extendcircuit(conn, body_len, body))
  2410. return -1;
  2411. break;
  2412. case CONTROL0_CMD_ATTACHSTREAM:
  2413. if (handle_control_attachstream(conn, body_len, body))
  2414. return -1;
  2415. break;
  2416. case CONTROL0_CMD_POSTDESCRIPTOR:
  2417. if (handle_control_postdescriptor(conn, body_len, body))
  2418. return -1;
  2419. break;
  2420. case CONTROL0_CMD_REDIRECTSTREAM:
  2421. if (handle_control_redirectstream(conn, body_len, body))
  2422. return -1;
  2423. break;
  2424. case CONTROL0_CMD_CLOSESTREAM:
  2425. if (handle_control_closestream(conn, body_len, body))
  2426. return -1;
  2427. break;
  2428. case CONTROL0_CMD_CLOSECIRCUIT:
  2429. if (handle_control_closecircuit(conn, body_len, body))
  2430. return -1;
  2431. break;
  2432. case CONTROL0_CMD_ERROR:
  2433. case CONTROL0_CMD_DONE:
  2434. case CONTROL0_CMD_CONFVALUE:
  2435. case CONTROL0_CMD_EVENT:
  2436. case CONTROL0_CMD_INFOVALUE:
  2437. log_warn(LD_CONTROL, "Received client-only '%s' command; ignoring.",
  2438. control_cmd_to_string(command_type));
  2439. send_control0_error(conn, ERR_UNRECOGNIZED_TYPE,
  2440. "Command type only valid from server to tor client");
  2441. break;
  2442. case CONTROL0_CMD_FRAGMENTHEADER:
  2443. case CONTROL0_CMD_FRAGMENT:
  2444. log_warn(LD_CONTROL,
  2445. "Recieved command fragment out of order; ignoring.");
  2446. send_control0_error(conn, ERR_SYNTAX, "Bad fragmentation on command.");
  2447. default:
  2448. log_warn(LD_CONTROL, "Received unrecognized command type %d; ignoring.",
  2449. (int)command_type);
  2450. send_control0_error(conn, ERR_UNRECOGNIZED_TYPE,
  2451. "Unrecognized command type");
  2452. break;
  2453. }
  2454. tor_free(body);
  2455. goto again; /* There might be more data. */
  2456. }
  2457. /** Called when <b>conn</b> has received more bytes on its inbuf.
  2458. */
  2459. int
  2460. connection_control_process_inbuf(control_connection_t *conn)
  2461. {
  2462. tor_assert(conn);
  2463. if (STATE_IS_V0(conn->_base.state))
  2464. return connection_control_process_inbuf_v0(conn);
  2465. else
  2466. return connection_control_process_inbuf_v1(conn);
  2467. }
  2468. /** Something has happened to circuit <b>circ</b>: tell any interested
  2469. * control connections. */
  2470. int
  2471. control_event_circuit_status(origin_circuit_t *circ, circuit_status_event_t tp)
  2472. {
  2473. char *path, *msg;
  2474. if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS))
  2475. return 0;
  2476. tor_assert(circ);
  2477. path = circuit_list_path(circ,0);
  2478. if (EVENT_IS_INTERESTING0(EVENT_CIRCUIT_STATUS)) {
  2479. size_t path_len = strlen(path);
  2480. msg = tor_malloc(1+4+path_len+1); /* event, circid, path, NUL. */
  2481. msg[0] = (uint8_t) tp;
  2482. set_uint32(msg+1, htonl(circ->global_identifier));
  2483. strlcpy(msg+5,path,path_len+1);
  2484. send_control0_event(EVENT_CIRCUIT_STATUS, (uint32_t)(path_len+6), msg);
  2485. tor_free(msg);
  2486. }
  2487. if (EVENT_IS_INTERESTING1(EVENT_CIRCUIT_STATUS)) {
  2488. const char *status;
  2489. switch (tp)
  2490. {
  2491. case CIRC_EVENT_LAUNCHED: status = "LAUNCHED"; break;
  2492. case CIRC_EVENT_BUILT: status = "BUILT"; break;
  2493. case CIRC_EVENT_EXTENDED: status = "EXTENDED"; break;
  2494. case CIRC_EVENT_FAILED: status = "FAILED"; break;
  2495. case CIRC_EVENT_CLOSED: status = "CLOSED"; break;
  2496. default:
  2497. log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
  2498. return 0;
  2499. }
  2500. send_control1_event(EVENT_CIRCUIT_STATUS,
  2501. "650 CIRC %lu %s %s\r\n",
  2502. (unsigned long)circ->global_identifier,
  2503. status, path);
  2504. }
  2505. tor_free(path);
  2506. return 0;
  2507. }
  2508. /** Given an AP connection <b>conn</b> and a <b>len</b>-character buffer
  2509. * <b>buf</b>, determine the address:port combination requested on
  2510. * <b>conn</b>, and write it to <b>buf</b>. Return 0 on success, -1 on
  2511. * failure. */
  2512. static int
  2513. write_stream_target_to_buf(edge_connection_t *conn, char *buf, size_t len)
  2514. {
  2515. char buf2[256];
  2516. if (conn->chosen_exit_name)
  2517. if (tor_snprintf(buf2, sizeof(buf2), ".%s.exit", conn->chosen_exit_name)<0)
  2518. return -1;
  2519. if (tor_snprintf(buf, len, "%s%s%s:%d",
  2520. conn->socks_request->address,
  2521. conn->chosen_exit_name ? buf2 : "",
  2522. !conn->chosen_exit_name &&
  2523. connection_edge_is_rendezvous_stream(conn) ? ".onion" : "",
  2524. conn->socks_request->port)<0)
  2525. return -1;
  2526. return 0;
  2527. }
  2528. /** Something has happened to the stream associated with AP connection
  2529. * <b>conn</b>: tell any interested control connections. */
  2530. int
  2531. control_event_stream_status(edge_connection_t *conn, stream_status_event_t tp)
  2532. {
  2533. char *msg;
  2534. size_t len;
  2535. char buf[256];
  2536. tor_assert(conn->socks_request);
  2537. if (!EVENT_IS_INTERESTING(EVENT_STREAM_STATUS))
  2538. return 0;
  2539. write_stream_target_to_buf(conn, buf, sizeof(buf));
  2540. if (EVENT_IS_INTERESTING0(EVENT_STREAM_STATUS)) {
  2541. len = strlen(buf);
  2542. msg = tor_malloc(5+len+1);
  2543. msg[0] = (uint8_t) tp;
  2544. set_uint32(msg+1, htonl(conn->global_identifier));
  2545. strlcpy(msg+5, buf, len+1);
  2546. send_control0_event(EVENT_STREAM_STATUS, (uint32_t)(5+len+1), msg);
  2547. tor_free(msg);
  2548. }
  2549. if (EVENT_IS_INTERESTING1(EVENT_STREAM_STATUS)) {
  2550. const char *status;
  2551. circuit_t *circ;
  2552. origin_circuit_t *origin_circ = NULL;
  2553. switch (tp)
  2554. {
  2555. case STREAM_EVENT_SENT_CONNECT: status = "SENTCONNECT"; break;
  2556. case STREAM_EVENT_SENT_RESOLVE: status = "SENTRESOLVE"; break;
  2557. case STREAM_EVENT_SUCCEEDED: status = "SUCCEEDED"; break;
  2558. case STREAM_EVENT_FAILED: status = "FAILED"; break;
  2559. case STREAM_EVENT_CLOSED: status = "CLOSED"; break;
  2560. case STREAM_EVENT_NEW: status = "NEW"; break;
  2561. case STREAM_EVENT_NEW_RESOLVE: status = "NEWRESOLVE"; break;
  2562. case STREAM_EVENT_FAILED_RETRIABLE: status = "DETACHED"; break;
  2563. default:
  2564. log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
  2565. return 0;
  2566. }
  2567. circ = circuit_get_by_edge_conn(conn);
  2568. if (circ && CIRCUIT_IS_ORIGIN(circ))
  2569. origin_circ = TO_ORIGIN_CIRCUIT(circ);
  2570. send_control1_event(EVENT_STREAM_STATUS,
  2571. "650 STREAM %lu %s %lu %s\r\n",
  2572. (unsigned long)conn->global_identifier, status,
  2573. origin_circ?
  2574. (unsigned long)origin_circ->global_identifier : 0ul,
  2575. buf);
  2576. /* XXX need to specify its intended exit, etc? */
  2577. }
  2578. return 0;
  2579. }
  2580. /** Something has happened to the OR connection <b>conn</b>: tell any
  2581. * interested control connections. */
  2582. int
  2583. control_event_or_conn_status(or_connection_t *conn,or_conn_status_event_t tp)
  2584. {
  2585. char buf[HEX_DIGEST_LEN+3]; /* status, dollar, identity, NUL */
  2586. size_t len;
  2587. if (!EVENT_IS_INTERESTING(EVENT_OR_CONN_STATUS))
  2588. return 0;
  2589. if (EVENT_IS_INTERESTING0(EVENT_OR_CONN_STATUS)) {
  2590. buf[0] = (uint8_t)tp;
  2591. strlcpy(buf+1,conn->nickname ? conn->nickname : "",sizeof(buf)-1);
  2592. len = strlen(buf+1);
  2593. send_control0_event(EVENT_OR_CONN_STATUS, (uint32_t)(len+1), buf);
  2594. }
  2595. if (EVENT_IS_INTERESTING1(EVENT_OR_CONN_STATUS)) {
  2596. const char *status;
  2597. char name[128];
  2598. if (conn->nickname)
  2599. strlcpy(name, conn->nickname, sizeof(name));
  2600. else
  2601. tor_snprintf(name, sizeof(name), "%s:%d",
  2602. conn->_base.address, conn->_base.port);
  2603. switch (tp)
  2604. {
  2605. case OR_CONN_EVENT_LAUNCHED: status = "LAUNCHED"; break;
  2606. case OR_CONN_EVENT_CONNECTED: status = "CONNECTED"; break;
  2607. case OR_CONN_EVENT_FAILED: status = "FAILED"; break;
  2608. case OR_CONN_EVENT_CLOSED: status = "CLOSED"; break;
  2609. case OR_CONN_EVENT_NEW: status = "NEW"; break;
  2610. default:
  2611. log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
  2612. return 0;
  2613. }
  2614. send_control1_event(EVENT_OR_CONN_STATUS,
  2615. "650 ORCONN %s %s\r\n",
  2616. name, status);
  2617. }
  2618. return 0;
  2619. }
  2620. /** A second or more has elapsed: tell any interested control
  2621. * connections how much bandwidth we used. */
  2622. int
  2623. control_event_bandwidth_used(uint32_t n_read, uint32_t n_written)
  2624. {
  2625. char buf[8];
  2626. if (EVENT_IS_INTERESTING0(EVENT_BANDWIDTH_USED)) {
  2627. set_uint32(buf, htonl(n_read));
  2628. set_uint32(buf+4, htonl(n_written));
  2629. send_control0_event(EVENT_BANDWIDTH_USED, 8, buf);
  2630. }
  2631. if (EVENT_IS_INTERESTING1(EVENT_BANDWIDTH_USED)) {
  2632. send_control1_event(EVENT_BANDWIDTH_USED,
  2633. "650 BW %lu %lu\r\n",
  2634. (unsigned long)n_read,
  2635. (unsigned long)n_written);
  2636. }
  2637. return 0;
  2638. }
  2639. /** Called when we are sending a log message to the controllers: suspend
  2640. * sending further log messages to the controllers until we're done. Used by
  2641. * CONN_LOG_PROTECT. */
  2642. void
  2643. disable_control_logging(void)
  2644. {
  2645. ++disable_log_messages;
  2646. }
  2647. /** We're done sending a log message to the controllers: re-enable controller
  2648. * logging. Used by CONN_LOG_PROTECT. */
  2649. void
  2650. enable_control_logging(void)
  2651. {
  2652. if (--disable_log_messages < 0)
  2653. tor_assert(0);
  2654. }
  2655. /** We got a log message: tell any interested control connections. */
  2656. void
  2657. control_event_logmsg(int severity, unsigned int domain, const char *msg)
  2658. {
  2659. int oldlog, event;
  2660. (void) domain;
  2661. if (disable_log_messages)
  2662. return;
  2663. oldlog = EVENT_IS_INTERESTING0(EVENT_LOG_OBSOLETE) &&
  2664. (severity == LOG_NOTICE || severity == LOG_WARN || severity == LOG_ERR);
  2665. event = log_severity_to_event(severity);
  2666. if (event<0 || !EVENT_IS_INTERESTING0(event))
  2667. event = 0;
  2668. if (oldlog || event) {
  2669. size_t len = strlen(msg);
  2670. ++disable_log_messages;
  2671. if (event)
  2672. send_control0_event(event, (uint32_t)(len+1), msg);
  2673. if (oldlog)
  2674. send_control0_event(EVENT_LOG_OBSOLETE, (uint32_t)(len+1), msg);
  2675. --disable_log_messages;
  2676. }
  2677. event = log_severity_to_event(severity);
  2678. if (event >= 0 && EVENT_IS_INTERESTING1(event)) {
  2679. char *b = NULL;
  2680. const char *s;
  2681. if (strchr(msg, '\n')) {
  2682. char *cp;
  2683. b = tor_strdup(msg);
  2684. for (cp = b; *cp; ++cp)
  2685. if (*cp == '\r' || *cp == '\n')
  2686. *cp = ' ';
  2687. }
  2688. switch (severity) {
  2689. case LOG_DEBUG: s = "DEBUG"; break;
  2690. case LOG_INFO: s = "INFO"; break;
  2691. case LOG_NOTICE: s = "NOTICE"; break;
  2692. case LOG_WARN: s = "WARN"; break;
  2693. case LOG_ERR: s = "ERR"; break;
  2694. default: s = "UnknownLogSeverity"; break;
  2695. }
  2696. ++disable_log_messages;
  2697. send_control1_event(event, "650 %s %s\r\n", s, b?b:msg);
  2698. --disable_log_messages;
  2699. tor_free(b);
  2700. }
  2701. }
  2702. /** Called whenever we receive new router descriptors: tell any
  2703. * interested control connections. <b>routers</b> is a list of
  2704. * DIGEST_LEN-byte identity digests.
  2705. */
  2706. int
  2707. control_event_descriptors_changed(smartlist_t *routers)
  2708. {
  2709. size_t len;
  2710. char *msg;
  2711. smartlist_t *identities;
  2712. char buf[HEX_DIGEST_LEN+1];
  2713. if (!EVENT_IS_INTERESTING(EVENT_NEW_DESC))
  2714. return 0;
  2715. identities = smartlist_create();
  2716. SMARTLIST_FOREACH(routers, routerinfo_t *, r,
  2717. {
  2718. base16_encode(buf,sizeof(buf),r->cache_info.identity_digest,DIGEST_LEN);
  2719. smartlist_add(identities, tor_strdup(buf));
  2720. });
  2721. if (EVENT_IS_INTERESTING0(EVENT_NEW_DESC)) {
  2722. msg = smartlist_join_strings(identities, ",", 0, &len);
  2723. send_control0_event(EVENT_NEW_DESC, len+1, msg);
  2724. tor_free(msg);
  2725. }
  2726. if (EVENT_IS_INTERESTING1(EVENT_NEW_DESC)) {
  2727. char *ids = smartlist_join_strings(identities, " ", 0, &len);
  2728. size_t len = strlen(ids)+32;
  2729. msg = tor_malloc(len);
  2730. tor_snprintf(msg, len, "650 NEWDESC %s\r\n", ids);
  2731. send_control1_event_string(EVENT_NEW_DESC, msg);
  2732. tor_free(ids);
  2733. tor_free(msg);
  2734. }
  2735. SMARTLIST_FOREACH(identities, char *, cp, tor_free(cp));
  2736. smartlist_free(identities);
  2737. return 0;
  2738. }
  2739. /** Called whenever an address mapping on <b>from<b> from changes to <b>to</b>.
  2740. * <b>expires</b> values less than 3 are special; see connection_edge.c. */
  2741. int
  2742. control_event_address_mapped(const char *from, const char *to, time_t expires)
  2743. {
  2744. if (!EVENT_IS_INTERESTING1(EVENT_ADDRMAP))
  2745. return 0;
  2746. if (expires < 3)
  2747. send_control1_event(EVENT_ADDRMAP,
  2748. "650 ADDRMAP %s %s NEVER\r\n", from, to);
  2749. else {
  2750. char buf[ISO_TIME_LEN+1];
  2751. format_local_iso_time(buf,expires);
  2752. send_control1_event(EVENT_ADDRMAP, "650 ADDRMAP %s %s \"%s\"\r\n",
  2753. from, to, buf);
  2754. }
  2755. return 0;
  2756. }
  2757. /** The authoritative dirserver has received a new descriptor that
  2758. * has passed basic syntax checks and is properly self-signed.
  2759. *
  2760. * Notify any interested party of the new descriptor and what has
  2761. * been done with it, and also optionally give an explanation/reason. */
  2762. int
  2763. control_event_or_authdir_new_descriptor(const char *action,
  2764. const char *descriptor,
  2765. const char *msg)
  2766. {
  2767. char firstline[1024];
  2768. char *buf;
  2769. int totallen;
  2770. char *esc = NULL;
  2771. size_t esclen;
  2772. if (!EVENT_IS_INTERESTING(EVENT_AUTHDIR_NEWDESCS))
  2773. return 0;
  2774. tor_snprintf(firstline, sizeof(firstline),
  2775. "650+AUTHDIR_NEWDESC=\r\n%s\r\n%s\r\n",
  2776. action,
  2777. msg ? msg : "");
  2778. /* Escape the server descriptor properly */
  2779. esclen = write_escaped_data(descriptor, strlen(descriptor), 1, &esc);
  2780. totallen = strlen(firstline) + esclen + 1;
  2781. buf = tor_malloc(totallen);
  2782. strlcpy(buf, firstline, totallen);
  2783. strlcpy(buf+strlen(firstline), esc, totallen);
  2784. send_control1_event_string(EVENT_AUTHDIR_NEWDESCS, buf);
  2785. tor_free(esc);
  2786. tor_free(buf);
  2787. return 0;
  2788. }
  2789. /** Choose a random authentication cookie and write it to disk.
  2790. * Anybody who can read the cookie from disk will be considered
  2791. * authorized to use the control connection. */
  2792. int
  2793. init_cookie_authentication(int enabled)
  2794. {
  2795. char fname[512];
  2796. if (!enabled) {
  2797. authentication_cookie_is_set = 0;
  2798. return 0;
  2799. }
  2800. tor_snprintf(fname, sizeof(fname), "%s/control_auth_cookie",
  2801. get_options()->DataDirectory);
  2802. crypto_rand(authentication_cookie, AUTHENTICATION_COOKIE_LEN);
  2803. authentication_cookie_is_set = 1;
  2804. if (write_bytes_to_file(fname, authentication_cookie,
  2805. AUTHENTICATION_COOKIE_LEN, 1)) {
  2806. log_warn(LD_FS,"Error writing authentication cookie.");
  2807. return -1;
  2808. }
  2809. return 0;
  2810. }