control.c 106 KB

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