control.c 98 KB

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