control.c 98 KB

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