control.c 119 KB

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