control.c 133 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978
  1. /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  2. * Copyright (c) 2007-2010, The Tor Project, Inc. */
  3. /* See LICENSE for licensing information */
  4. /**
  5. * \file control.c
  6. * \brief Implementation for Tor's control-socket interface.
  7. * See doc/spec/control-spec.txt for full details on protocol.
  8. **/
  9. #define CONTROL_PRIVATE
  10. #include "or.h"
  11. #include "buffers.h"
  12. #include "circuitbuild.h"
  13. #include "circuitlist.h"
  14. #include "circuituse.h"
  15. #include "config.h"
  16. #include "connection.h"
  17. #include "connection_edge.h"
  18. #include "control.h"
  19. #include "directory.h"
  20. #include "dirserv.h"
  21. #include "dnsserv.h"
  22. #include "geoip.h"
  23. #include "hibernate.h"
  24. #include "main.h"
  25. #include "networkstatus.h"
  26. #include "policies.h"
  27. #include "reasons.h"
  28. #include "router.h"
  29. #include "routerlist.h"
  30. #include "routerparse.h"
  31. /** Yield true iff <b>s</b> is the state of a control_connection_t that has
  32. * finished authentication and is accepting commands. */
  33. #define STATE_IS_OPEN(s) ((s) == CONTROL_CONN_STATE_OPEN)
  34. /* Recognized asynchronous event types. It's okay to expand this list
  35. * because it is used both as a list of v0 event types, and as indices
  36. * into the bitfield to determine which controllers want which events.
  37. */
  38. #define _EVENT_MIN 0x0001
  39. #define EVENT_CIRCUIT_STATUS 0x0001
  40. #define EVENT_STREAM_STATUS 0x0002
  41. #define EVENT_OR_CONN_STATUS 0x0003
  42. #define EVENT_BANDWIDTH_USED 0x0004
  43. #define EVENT_LOG_OBSOLETE 0x0005 /* Can reclaim this. */
  44. #define EVENT_NEW_DESC 0x0006
  45. #define EVENT_DEBUG_MSG 0x0007
  46. #define EVENT_INFO_MSG 0x0008
  47. #define EVENT_NOTICE_MSG 0x0009
  48. #define EVENT_WARN_MSG 0x000A
  49. #define EVENT_ERR_MSG 0x000B
  50. #define EVENT_ADDRMAP 0x000C
  51. // #define EVENT_AUTHDIR_NEWDESCS 0x000D
  52. #define EVENT_DESCCHANGED 0x000E
  53. // #define EVENT_NS 0x000F
  54. #define EVENT_STATUS_CLIENT 0x0010
  55. #define EVENT_STATUS_SERVER 0x0011
  56. #define EVENT_STATUS_GENERAL 0x0012
  57. #define EVENT_GUARD 0x0013
  58. #define EVENT_STREAM_BANDWIDTH_USED 0x0014
  59. #define EVENT_CLIENTS_SEEN 0x0015
  60. #define EVENT_NEWCONSENSUS 0x0016
  61. #define EVENT_BUILDTIMEOUT_SET 0x0017
  62. #define _EVENT_MAX 0x0017
  63. /* If _EVENT_MAX ever hits 0x0020, we need to make the mask wider. */
  64. /** Bitfield: The bit 1&lt;&lt;e is set if <b>any</b> open control
  65. * connection is interested in events of type <b>e</b>. We use this
  66. * so that we can decide to skip generating event messages that nobody
  67. * has interest in without having to walk over the global connection
  68. * list to find out.
  69. **/
  70. typedef uint32_t event_mask_t;
  71. /** An event mask of all the events that any controller is interested in
  72. * receiving. */
  73. static event_mask_t global_event_mask = 0;
  74. /** True iff we have disabled log messages from being sent to the controller */
  75. static int disable_log_messages = 0;
  76. /** Macro: true if any control connection is interested in events of type
  77. * <b>e</b>. */
  78. #define EVENT_IS_INTERESTING(e) \
  79. (global_event_mask & (1<<(e)))
  80. /** If we're using cookie-type authentication, how long should our cookies be?
  81. */
  82. #define AUTHENTICATION_COOKIE_LEN 32
  83. /** If true, we've set authentication_cookie to a secret code and
  84. * stored it to disk. */
  85. static int authentication_cookie_is_set = 0;
  86. /** If authentication_cookie_is_set, a secret cookie that we've stored to disk
  87. * and which we're using to authenticate controllers. (If the controller can
  88. * read it off disk, it has permission to connect. */
  89. static char authentication_cookie[AUTHENTICATION_COOKIE_LEN];
  90. /** A sufficiently large size to record the last bootstrap phase string. */
  91. #define BOOTSTRAP_MSG_LEN 1024
  92. /** What was the last bootstrap phase message we sent? We keep track
  93. * of this so we can respond to getinfo status/bootstrap-phase queries. */
  94. static char last_sent_bootstrap_message[BOOTSTRAP_MSG_LEN];
  95. /** Flag for event_format_t. Indicates that we should use the one standard
  96. format.
  97. */
  98. #define ALL_FORMATS 1
  99. /** Bit field of flags to select how to format a controller event. Recognized
  100. * flag is ALL_FORMATS. */
  101. typedef int event_format_t;
  102. static void connection_printf_to_buf(control_connection_t *conn,
  103. const char *format, ...)
  104. CHECK_PRINTF(2,3);
  105. static void send_control_done(control_connection_t *conn);
  106. static void send_control_event(uint16_t event, event_format_t which,
  107. const char *format, ...)
  108. CHECK_PRINTF(3,4);
  109. static int handle_control_setconf(control_connection_t *conn, uint32_t len,
  110. char *body);
  111. static int handle_control_resetconf(control_connection_t *conn, uint32_t len,
  112. char *body);
  113. static int handle_control_getconf(control_connection_t *conn, uint32_t len,
  114. const char *body);
  115. static int handle_control_loadconf(control_connection_t *conn, uint32_t len,
  116. const char *body);
  117. static int handle_control_setevents(control_connection_t *conn, uint32_t len,
  118. const char *body);
  119. static int handle_control_authenticate(control_connection_t *conn,
  120. uint32_t len,
  121. const char *body);
  122. static int handle_control_signal(control_connection_t *conn, uint32_t len,
  123. const char *body);
  124. static int handle_control_mapaddress(control_connection_t *conn, uint32_t len,
  125. const char *body);
  126. static char *list_getinfo_options(void);
  127. static int handle_control_getinfo(control_connection_t *conn, uint32_t len,
  128. const char *body);
  129. static int handle_control_extendcircuit(control_connection_t *conn,
  130. uint32_t len,
  131. const char *body);
  132. static int handle_control_setcircuitpurpose(control_connection_t *conn,
  133. uint32_t len, const char *body);
  134. static int handle_control_attachstream(control_connection_t *conn,
  135. uint32_t len,
  136. const char *body);
  137. static int handle_control_postdescriptor(control_connection_t *conn,
  138. uint32_t len,
  139. const char *body);
  140. static int handle_control_redirectstream(control_connection_t *conn,
  141. uint32_t len,
  142. const char *body);
  143. static int handle_control_closestream(control_connection_t *conn, uint32_t len,
  144. const char *body);
  145. static int handle_control_closecircuit(control_connection_t *conn,
  146. uint32_t len,
  147. const char *body);
  148. static int handle_control_resolve(control_connection_t *conn, uint32_t len,
  149. const char *body);
  150. static int handle_control_usefeature(control_connection_t *conn,
  151. uint32_t len,
  152. const char *body);
  153. static int write_stream_target_to_buf(edge_connection_t *conn, char *buf,
  154. size_t len);
  155. static void orconn_target_get_name(char *buf, size_t len,
  156. or_connection_t *conn);
  157. static char *get_cookie_file(void);
  158. /** Given a control event code for a message event, return the corresponding
  159. * log severity. */
  160. static INLINE int
  161. event_to_log_severity(int event)
  162. {
  163. switch (event) {
  164. case EVENT_DEBUG_MSG: return LOG_DEBUG;
  165. case EVENT_INFO_MSG: return LOG_INFO;
  166. case EVENT_NOTICE_MSG: return LOG_NOTICE;
  167. case EVENT_WARN_MSG: return LOG_WARN;
  168. case EVENT_ERR_MSG: return LOG_ERR;
  169. default: return -1;
  170. }
  171. }
  172. /** Given a log severity, return the corresponding control event code. */
  173. static INLINE int
  174. log_severity_to_event(int severity)
  175. {
  176. switch (severity) {
  177. case LOG_DEBUG: return EVENT_DEBUG_MSG;
  178. case LOG_INFO: return EVENT_INFO_MSG;
  179. case LOG_NOTICE: return EVENT_NOTICE_MSG;
  180. case LOG_WARN: return EVENT_WARN_MSG;
  181. case LOG_ERR: return EVENT_ERR_MSG;
  182. default: return -1;
  183. }
  184. }
  185. /** Set <b>global_event_mask*</b> to the bitwise OR of each live control
  186. * connection's event_mask field. */
  187. void
  188. control_update_global_event_mask(void)
  189. {
  190. smartlist_t *conns = get_connection_array();
  191. event_mask_t old_mask, new_mask;
  192. old_mask = global_event_mask;
  193. global_event_mask = 0;
  194. SMARTLIST_FOREACH(conns, connection_t *, _conn,
  195. {
  196. if (_conn->type == CONN_TYPE_CONTROL &&
  197. STATE_IS_OPEN(_conn->state)) {
  198. control_connection_t *conn = TO_CONTROL_CONN(_conn);
  199. global_event_mask |= conn->event_mask;
  200. }
  201. });
  202. new_mask = global_event_mask;
  203. /* Handle the aftermath. Set up the log callback to tell us only what
  204. * we want to hear...*/
  205. control_adjust_event_log_severity();
  206. /* ...then, if we've started logging stream bw, clear the appropriate
  207. * fields. */
  208. if (! (old_mask & EVENT_STREAM_BANDWIDTH_USED) &&
  209. (new_mask & EVENT_STREAM_BANDWIDTH_USED)) {
  210. SMARTLIST_FOREACH(conns, connection_t *, conn,
  211. {
  212. if (conn->type == CONN_TYPE_AP) {
  213. edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
  214. edge_conn->n_written = edge_conn->n_read = 0;
  215. }
  216. });
  217. }
  218. }
  219. /** Adjust the log severities that result in control_event_logmsg being called
  220. * to match the severity of log messages that any controllers are interested
  221. * in. */
  222. void
  223. control_adjust_event_log_severity(void)
  224. {
  225. int i;
  226. int min_log_event=EVENT_ERR_MSG, max_log_event=EVENT_DEBUG_MSG;
  227. for (i = EVENT_DEBUG_MSG; i <= EVENT_ERR_MSG; ++i) {
  228. if (EVENT_IS_INTERESTING(i)) {
  229. min_log_event = i;
  230. break;
  231. }
  232. }
  233. for (i = EVENT_ERR_MSG; i >= EVENT_DEBUG_MSG; --i) {
  234. if (EVENT_IS_INTERESTING(i)) {
  235. max_log_event = i;
  236. break;
  237. }
  238. }
  239. if (EVENT_IS_INTERESTING(EVENT_LOG_OBSOLETE) ||
  240. EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL)) {
  241. if (min_log_event > EVENT_NOTICE_MSG)
  242. min_log_event = EVENT_NOTICE_MSG;
  243. if (max_log_event < EVENT_ERR_MSG)
  244. max_log_event = EVENT_ERR_MSG;
  245. }
  246. if (min_log_event <= max_log_event)
  247. change_callback_log_severity(event_to_log_severity(min_log_event),
  248. event_to_log_severity(max_log_event),
  249. control_event_logmsg);
  250. else
  251. change_callback_log_severity(LOG_ERR, LOG_ERR,
  252. control_event_logmsg);
  253. }
  254. /** Return true iff the event with code <b>c</b> is being sent to any current
  255. * control connection. This is useful if the amount of work needed to prepare
  256. * to call the appropriate control_event_...() function is high.
  257. */
  258. int
  259. control_event_is_interesting(int event)
  260. {
  261. return EVENT_IS_INTERESTING(event);
  262. }
  263. /** Append a NUL-terminated string <b>s</b> to the end of
  264. * <b>conn</b>-\>outbuf.
  265. */
  266. static INLINE void
  267. connection_write_str_to_buf(const char *s, control_connection_t *conn)
  268. {
  269. size_t len = strlen(s);
  270. connection_write_to_buf(s, len, TO_CONN(conn));
  271. }
  272. /** Given a <b>len</b>-character string in <b>data</b>, made of lines
  273. * terminated by CRLF, allocate a new string in *<b>out</b>, and copy the
  274. * contents of <b>data</b> into *<b>out</b>, adding a period before any period
  275. * that appears at the start of a line, and adding a period-CRLF line at
  276. * the end. Replace all LF characters sequences with CRLF. Return the number
  277. * of bytes in *<b>out</b>.
  278. */
  279. /* static */ size_t
  280. write_escaped_data(const char *data, size_t len, char **out)
  281. {
  282. size_t sz_out = len+8;
  283. char *outp;
  284. const char *start = data, *end;
  285. int i;
  286. int start_of_line;
  287. for (i=0; i<(int)len; ++i) {
  288. if (data[i]== '\n')
  289. sz_out += 2; /* Maybe add a CR; maybe add a dot. */
  290. }
  291. *out = outp = tor_malloc(sz_out+1);
  292. end = data+len;
  293. start_of_line = 1;
  294. while (data < end) {
  295. if (*data == '\n') {
  296. if (data > start && data[-1] != '\r')
  297. *outp++ = '\r';
  298. start_of_line = 1;
  299. } else if (*data == '.') {
  300. if (start_of_line) {
  301. start_of_line = 0;
  302. *outp++ = '.';
  303. }
  304. } else {
  305. start_of_line = 0;
  306. }
  307. *outp++ = *data++;
  308. }
  309. if (outp < *out+2 || memcmp(outp-2, "\r\n", 2)) {
  310. *outp++ = '\r';
  311. *outp++ = '\n';
  312. }
  313. *outp++ = '.';
  314. *outp++ = '\r';
  315. *outp++ = '\n';
  316. *outp = '\0'; /* NUL-terminate just in case. */
  317. tor_assert((outp - *out) <= (int)sz_out);
  318. return outp - *out;
  319. }
  320. /** Given a <b>len</b>-character string in <b>data</b>, made of lines
  321. * terminated by CRLF, allocate a new string in *<b>out</b>, and copy
  322. * the contents of <b>data</b> into *<b>out</b>, removing any period
  323. * that appears at the start of a line, and replacing all CRLF sequences
  324. * with LF. Return the number of
  325. * bytes in *<b>out</b>. */
  326. /* static */ size_t
  327. read_escaped_data(const char *data, size_t len, char **out)
  328. {
  329. char *outp;
  330. const char *next;
  331. const char *end;
  332. *out = outp = tor_malloc(len+1);
  333. end = data+len;
  334. while (data < end) {
  335. /* we're at the start of a line. */
  336. if (*data == '.')
  337. ++data;
  338. next = memchr(data, '\n', end-data);
  339. if (next) {
  340. size_t n_to_copy = next-data;
  341. /* Don't copy a CR that precedes this LF. */
  342. if (n_to_copy && *(next-1) == '\r')
  343. --n_to_copy;
  344. memcpy(outp, data, n_to_copy);
  345. outp += n_to_copy;
  346. data = next+1; /* This will point at the start of the next line,
  347. * or the end of the string, or a period. */
  348. } else {
  349. memcpy(outp, data, end-data);
  350. outp += (end-data);
  351. *outp = '\0';
  352. return outp - *out;
  353. }
  354. *outp++ = '\n';
  355. }
  356. *outp = '\0';
  357. return outp - *out;
  358. }
  359. /** If the first <b>in_len_max</b> characters in <b>start</b> contain a
  360. * double-quoted string with escaped characters, return the length of that
  361. * string (as encoded, including quotes). Otherwise return -1. */
  362. static INLINE int
  363. get_escaped_string_length(const char *start, size_t in_len_max,
  364. int *chars_out)
  365. {
  366. const char *cp, *end;
  367. int chars = 0;
  368. if (*start != '\"')
  369. return -1;
  370. cp = start+1;
  371. end = start+in_len_max;
  372. /* Calculate length. */
  373. while (1) {
  374. if (cp >= end) {
  375. return -1; /* Too long. */
  376. } else if (*cp == '\\') {
  377. if (++cp == end)
  378. return -1; /* Can't escape EOS. */
  379. ++cp;
  380. ++chars;
  381. } else if (*cp == '\"') {
  382. break;
  383. } else {
  384. ++cp;
  385. ++chars;
  386. }
  387. }
  388. if (chars_out)
  389. *chars_out = chars;
  390. return (int)(cp - start+1);
  391. }
  392. /** As decode_escaped_string, but does not decode the string: copies the
  393. * entire thing, including quotation marks. */
  394. static const char *
  395. extract_escaped_string(const char *start, size_t in_len_max,
  396. char **out, size_t *out_len)
  397. {
  398. int length = get_escaped_string_length(start, in_len_max, NULL);
  399. if (length<0)
  400. return NULL;
  401. *out_len = length;
  402. *out = tor_strndup(start, *out_len);
  403. return start+length;
  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 one double
  407. * quote, containing any number of non-quote characters or characters escaped
  408. * with a backslash, and ending with a final double 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. decode_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. int len, n_chars = 0;
  420. len = get_escaped_string_length(start, in_len_max, &n_chars);
  421. if (len<0)
  422. return NULL;
  423. end = start+len-1; /* Index of last quote. */
  424. tor_assert(*end == '\"');
  425. outp = *out = tor_malloc(len+1);
  426. *out_len = n_chars;
  427. cp = start+1;
  428. while (cp < end) {
  429. if (*cp == '\\')
  430. ++cp;
  431. *outp++ = *cp++;
  432. }
  433. *outp = '\0';
  434. tor_assert((outp - *out) == (int)*out_len);
  435. return end+1;
  436. }
  437. /** Acts like sprintf, but writes its formatted string to the end of
  438. * <b>conn</b>-\>outbuf. The message may be truncated if it is too long,
  439. * but it will always end with a CRLF sequence.
  440. *
  441. * Currently the length of the message is limited to 1024 (including the
  442. * ending CR LF NUL ("\\r\\n\\0"). */
  443. static void
  444. connection_printf_to_buf(control_connection_t *conn, const char *format, ...)
  445. {
  446. #define CONNECTION_PRINTF_TO_BUF_BUFFERSIZE 1024
  447. va_list ap;
  448. char buf[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE];
  449. int r;
  450. size_t len;
  451. va_start(ap,format);
  452. r = tor_vsnprintf(buf, sizeof(buf), format, ap);
  453. va_end(ap);
  454. if (r<0) {
  455. log_warn(LD_BUG, "Unable to format string for controller.");
  456. return;
  457. }
  458. len = strlen(buf);
  459. if (memcmp("\r\n\0", buf+len-2, 3)) {
  460. buf[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE-1] = '\0';
  461. buf[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE-2] = '\n';
  462. buf[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE-3] = '\r';
  463. }
  464. connection_write_to_buf(buf, len, TO_CONN(conn));
  465. }
  466. /** Send a "DONE" message down the control connection <b>conn</b>. */
  467. static void
  468. send_control_done(control_connection_t *conn)
  469. {
  470. connection_write_str_to_buf("250 OK\r\n", conn);
  471. }
  472. /** Send an event to all v1 controllers that are listening for code
  473. * <b>event</b>. The event's body is given by <b>msg</b>.
  474. *
  475. * If <b>which</b> & SHORT_NAMES, the event contains short-format names: send
  476. * it to controllers that haven't enabled the VERBOSE_NAMES feature. If
  477. * <b>which</b> & LONG_NAMES, the event contains long-format names: send it
  478. * to controllers that <em>have</em> enabled VERBOSE_NAMES.
  479. *
  480. * The EXTENDED_FORMAT and NONEXTENDED_FORMAT flags behave similarly with
  481. * respect to the EXTENDED_EVENTS feature. */
  482. static void
  483. send_control_event_string(uint16_t event, event_format_t which,
  484. const char *msg)
  485. {
  486. smartlist_t *conns = get_connection_array();
  487. (void)which;
  488. tor_assert(event >= _EVENT_MIN && event <= _EVENT_MAX);
  489. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
  490. if (conn->type == CONN_TYPE_CONTROL &&
  491. !conn->marked_for_close &&
  492. conn->state == CONTROL_CONN_STATE_OPEN) {
  493. control_connection_t *control_conn = TO_CONTROL_CONN(conn);
  494. if (control_conn->event_mask & (1<<event)) {
  495. int is_err = 0;
  496. connection_write_to_buf(msg, strlen(msg), TO_CONN(control_conn));
  497. if (event == EVENT_ERR_MSG)
  498. is_err = 1;
  499. else if (event == EVENT_STATUS_GENERAL)
  500. is_err = !strcmpstart(msg, "STATUS_GENERAL ERR ");
  501. else if (event == EVENT_STATUS_CLIENT)
  502. is_err = !strcmpstart(msg, "STATUS_CLIENT ERR ");
  503. else if (event == EVENT_STATUS_SERVER)
  504. is_err = !strcmpstart(msg, "STATUS_SERVER ERR ");
  505. if (is_err)
  506. connection_handle_write(TO_CONN(control_conn), 1);
  507. }
  508. }
  509. } SMARTLIST_FOREACH_END(conn);
  510. }
  511. /** Helper for send_control1_event and send_control1_event_extended:
  512. * Send an event to all v1 controllers that are listening for code
  513. * <b>event</b>. The event's body is created by the printf-style format in
  514. * <b>format</b>, and other arguments as provided.
  515. *
  516. * Currently the length of the message is limited to 1024 (including the
  517. * ending \\r\\n\\0). */
  518. static void
  519. send_control_event_impl(uint16_t event, event_format_t which,
  520. const char *format, va_list ap)
  521. {
  522. /* This is just a little longer than the longest allowed log message */
  523. #define SEND_CONTROL1_EVENT_BUFFERSIZE 10064
  524. int r;
  525. char buf[SEND_CONTROL1_EVENT_BUFFERSIZE];
  526. size_t len;
  527. r = tor_vsnprintf(buf, sizeof(buf), format, ap);
  528. if (r<0) {
  529. log_warn(LD_BUG, "Unable to format event for controller.");
  530. return;
  531. }
  532. len = strlen(buf);
  533. if (memcmp("\r\n\0", buf+len-2, 3)) {
  534. /* if it is not properly terminated, do it now */
  535. buf[SEND_CONTROL1_EVENT_BUFFERSIZE-1] = '\0';
  536. buf[SEND_CONTROL1_EVENT_BUFFERSIZE-2] = '\n';
  537. buf[SEND_CONTROL1_EVENT_BUFFERSIZE-3] = '\r';
  538. }
  539. send_control_event_string(event, which|ALL_FORMATS, buf);
  540. }
  541. /** Send an event to all v1 controllers that are listening for code
  542. * <b>event</b>. The event's body is created by the printf-style format in
  543. * <b>format</b>, and other arguments as provided.
  544. *
  545. * Currently the length of the message is limited to 1024 (including the
  546. * ending \\n\\r\\0. */
  547. static void
  548. send_control_event(uint16_t event, event_format_t which,
  549. const char *format, ...)
  550. {
  551. va_list ap;
  552. va_start(ap, format);
  553. send_control_event_impl(event, which, format, ap);
  554. va_end(ap);
  555. }
  556. /** Given a text circuit <b>id</b>, return the corresponding circuit. */
  557. static origin_circuit_t *
  558. get_circ(const char *id)
  559. {
  560. uint32_t n_id;
  561. int ok;
  562. n_id = (uint32_t) tor_parse_ulong(id, 10, 0, UINT32_MAX, &ok, NULL);
  563. if (!ok)
  564. return NULL;
  565. return circuit_get_by_global_id(n_id);
  566. }
  567. /** Given a text stream <b>id</b>, return the corresponding AP connection. */
  568. static edge_connection_t *
  569. get_stream(const char *id)
  570. {
  571. uint64_t n_id;
  572. int ok;
  573. connection_t *conn;
  574. n_id = tor_parse_uint64(id, 10, 0, UINT64_MAX, &ok, NULL);
  575. if (!ok)
  576. return NULL;
  577. conn = connection_get_by_global_id(n_id);
  578. if (!conn || conn->type != CONN_TYPE_AP || conn->marked_for_close)
  579. return NULL;
  580. return TO_EDGE_CONN(conn);
  581. }
  582. /** Helper for setconf and resetconf. Acts like setconf, except
  583. * it passes <b>use_defaults</b> on to options_trial_assign(). Modifies the
  584. * contents of body.
  585. */
  586. static int
  587. control_setconf_helper(control_connection_t *conn, uint32_t len, char *body,
  588. int use_defaults)
  589. {
  590. setopt_err_t opt_err;
  591. config_line_t *lines=NULL;
  592. char *start = body;
  593. char *errstring = NULL;
  594. const int clear_first = 1;
  595. char *config;
  596. smartlist_t *entries = smartlist_create();
  597. /* We have a string, "body", of the format '(key(=val|="val")?)' entries
  598. * separated by space. break it into a list of configuration entries. */
  599. while (*body) {
  600. char *eq = body;
  601. char *key;
  602. char *entry;
  603. while (!TOR_ISSPACE(*eq) && *eq != '=')
  604. ++eq;
  605. key = tor_strndup(body, eq-body);
  606. body = eq+1;
  607. if (*eq == '=') {
  608. char *val=NULL;
  609. size_t val_len=0;
  610. size_t ent_len;
  611. if (*body != '\"') {
  612. char *val_start = body;
  613. while (!TOR_ISSPACE(*body))
  614. body++;
  615. val = tor_strndup(val_start, body-val_start);
  616. val_len = strlen(val);
  617. } else {
  618. body = (char*)extract_escaped_string(body, (len - (body-start)),
  619. &val, &val_len);
  620. if (!body) {
  621. connection_write_str_to_buf("551 Couldn't parse string\r\n", conn);
  622. SMARTLIST_FOREACH(entries, char *, cp, tor_free(cp));
  623. smartlist_free(entries);
  624. tor_free(key);
  625. return 0;
  626. }
  627. }
  628. ent_len = strlen(key)+val_len+3;
  629. entry = tor_malloc(ent_len+1);
  630. tor_snprintf(entry, ent_len, "%s %s", key, val);
  631. tor_free(key);
  632. tor_free(val);
  633. } else {
  634. entry = key;
  635. }
  636. smartlist_add(entries, entry);
  637. while (TOR_ISSPACE(*body))
  638. ++body;
  639. }
  640. smartlist_add(entries, tor_strdup(""));
  641. config = smartlist_join_strings(entries, "\n", 0, NULL);
  642. SMARTLIST_FOREACH(entries, char *, cp, tor_free(cp));
  643. smartlist_free(entries);
  644. if (config_get_lines(config, &lines) < 0) {
  645. log_warn(LD_CONTROL,"Controller gave us config lines we can't parse.");
  646. connection_write_str_to_buf("551 Couldn't parse configuration\r\n",
  647. conn);
  648. tor_free(config);
  649. return 0;
  650. }
  651. tor_free(config);
  652. opt_err = options_trial_assign(lines, use_defaults, clear_first, &errstring);
  653. {
  654. const char *msg;
  655. switch (opt_err) {
  656. case SETOPT_ERR_MISC:
  657. msg = "552 Unrecognized option";
  658. break;
  659. case SETOPT_ERR_PARSE:
  660. msg = "513 Unacceptable option value";
  661. break;
  662. case SETOPT_ERR_TRANSITION:
  663. msg = "553 Transition not allowed";
  664. break;
  665. case SETOPT_ERR_SETTING:
  666. default:
  667. msg = "553 Unable to set option";
  668. break;
  669. case SETOPT_OK:
  670. config_free_lines(lines);
  671. send_control_done(conn);
  672. return 0;
  673. }
  674. log_warn(LD_CONTROL,
  675. "Controller gave us config lines that didn't validate: %s",
  676. errstring);
  677. connection_printf_to_buf(conn, "%s: %s\r\n", msg, errstring);
  678. config_free_lines(lines);
  679. tor_free(errstring);
  680. return 0;
  681. }
  682. }
  683. /** Called when we receive a SETCONF message: parse the body and try
  684. * to update our configuration. Reply with a DONE or ERROR message.
  685. * Modifies the contents of body.*/
  686. static int
  687. handle_control_setconf(control_connection_t *conn, uint32_t len, char *body)
  688. {
  689. return control_setconf_helper(conn, len, body, 0);
  690. }
  691. /** Called when we receive a RESETCONF message: parse the body and try
  692. * to update our configuration. Reply with a DONE or ERROR message.
  693. * Modifies the contents of body. */
  694. static int
  695. handle_control_resetconf(control_connection_t *conn, uint32_t len, char *body)
  696. {
  697. return control_setconf_helper(conn, len, body, 1);
  698. }
  699. /** Called when we receive a GETCONF message. Parse the request, and
  700. * reply with a CONFVALUE or an ERROR message */
  701. static int
  702. handle_control_getconf(control_connection_t *conn, uint32_t body_len,
  703. const char *body)
  704. {
  705. smartlist_t *questions = smartlist_create();
  706. smartlist_t *answers = smartlist_create();
  707. smartlist_t *unrecognized = smartlist_create();
  708. char *msg = NULL;
  709. size_t msg_len;
  710. or_options_t *options = get_options();
  711. int i, len;
  712. (void) body_len; /* body is NUL-terminated; so we can ignore len. */
  713. smartlist_split_string(questions, body, " ",
  714. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  715. SMARTLIST_FOREACH(questions, const char *, q,
  716. {
  717. if (!option_is_recognized(q)) {
  718. smartlist_add(unrecognized, (char*) q);
  719. } else {
  720. config_line_t *answer = option_get_assignment(options,q);
  721. if (!answer) {
  722. const char *name = option_get_canonical_name(q);
  723. size_t alen = strlen(name)+8;
  724. char *astr = tor_malloc(alen);
  725. tor_snprintf(astr, alen, "250-%s\r\n", name);
  726. smartlist_add(answers, astr);
  727. }
  728. while (answer) {
  729. config_line_t *next;
  730. size_t alen = strlen(answer->key)+strlen(answer->value)+8;
  731. char *astr = tor_malloc(alen);
  732. tor_snprintf(astr, alen, "250-%s=%s\r\n",
  733. answer->key, answer->value);
  734. smartlist_add(answers, astr);
  735. next = answer->next;
  736. tor_free(answer->key);
  737. tor_free(answer->value);
  738. tor_free(answer);
  739. answer = next;
  740. }
  741. }
  742. });
  743. if ((len = smartlist_len(unrecognized))) {
  744. for (i=0; i < len-1; ++i)
  745. connection_printf_to_buf(conn,
  746. "552-Unrecognized configuration key \"%s\"\r\n",
  747. (char*)smartlist_get(unrecognized, i));
  748. connection_printf_to_buf(conn,
  749. "552 Unrecognized configuration key \"%s\"\r\n",
  750. (char*)smartlist_get(unrecognized, len-1));
  751. } else if ((len = smartlist_len(answers))) {
  752. char *tmp = smartlist_get(answers, len-1);
  753. tor_assert(strlen(tmp)>4);
  754. tmp[3] = ' ';
  755. msg = smartlist_join_strings(answers, "", 0, &msg_len);
  756. connection_write_to_buf(msg, msg_len, TO_CONN(conn));
  757. } else {
  758. connection_write_str_to_buf("250 OK\r\n", conn);
  759. }
  760. SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
  761. smartlist_free(answers);
  762. SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
  763. smartlist_free(questions);
  764. smartlist_free(unrecognized);
  765. tor_free(msg);
  766. return 0;
  767. }
  768. /** Called when we get a +LOADCONF message. */
  769. static int
  770. handle_control_loadconf(control_connection_t *conn, uint32_t len,
  771. const char *body)
  772. {
  773. setopt_err_t retval;
  774. char *errstring = NULL;
  775. const char *msg = NULL;
  776. (void) len;
  777. retval = options_init_from_string(body, CMD_RUN_TOR, NULL, &errstring);
  778. if (retval != SETOPT_OK)
  779. log_warn(LD_CONTROL,
  780. "Controller gave us config file that didn't validate: %s",
  781. errstring);
  782. switch (retval) {
  783. case SETOPT_ERR_PARSE:
  784. msg = "552 Invalid config file";
  785. break;
  786. case SETOPT_ERR_TRANSITION:
  787. msg = "553 Transition not allowed";
  788. break;
  789. case SETOPT_ERR_SETTING:
  790. msg = "553 Unable to set option";
  791. break;
  792. case SETOPT_ERR_MISC:
  793. default:
  794. msg = "550 Unable to load config";
  795. break;
  796. case SETOPT_OK:
  797. break;
  798. }
  799. if (msg) {
  800. if (errstring)
  801. connection_printf_to_buf(conn, "%s: %s\r\n", msg, errstring);
  802. else
  803. connection_printf_to_buf(conn, "%s\r\n", msg);
  804. } else {
  805. send_control_done(conn);
  806. }
  807. tor_free(errstring);
  808. return 0;
  809. }
  810. /** Called when we get a SETEVENTS message: update conn->event_mask,
  811. * and reply with DONE or ERROR. */
  812. static int
  813. handle_control_setevents(control_connection_t *conn, uint32_t len,
  814. const char *body)
  815. {
  816. uint16_t event_code;
  817. uint32_t event_mask = 0;
  818. smartlist_t *events = smartlist_create();
  819. (void) len;
  820. smartlist_split_string(events, body, " ",
  821. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  822. SMARTLIST_FOREACH_BEGIN(events, const char *, ev)
  823. {
  824. if (!strcasecmp(ev, "EXTENDED")) {
  825. continue;
  826. } else if (!strcasecmp(ev, "CIRC"))
  827. event_code = EVENT_CIRCUIT_STATUS;
  828. else if (!strcasecmp(ev, "STREAM"))
  829. event_code = EVENT_STREAM_STATUS;
  830. else if (!strcasecmp(ev, "ORCONN"))
  831. event_code = EVENT_OR_CONN_STATUS;
  832. else if (!strcasecmp(ev, "BW"))
  833. event_code = EVENT_BANDWIDTH_USED;
  834. else if (!strcasecmp(ev, "DEBUG"))
  835. event_code = EVENT_DEBUG_MSG;
  836. else if (!strcasecmp(ev, "INFO"))
  837. event_code = EVENT_INFO_MSG;
  838. else if (!strcasecmp(ev, "NOTICE"))
  839. event_code = EVENT_NOTICE_MSG;
  840. else if (!strcasecmp(ev, "WARN"))
  841. event_code = EVENT_WARN_MSG;
  842. else if (!strcasecmp(ev, "ERR"))
  843. event_code = EVENT_ERR_MSG;
  844. else if (!strcasecmp(ev, "NEWDESC"))
  845. event_code = EVENT_NEW_DESC;
  846. else if (!strcasecmp(ev, "ADDRMAP"))
  847. event_code = EVENT_ADDRMAP;
  848. else if (!strcasecmp(ev, "AUTHDIR_NEWDESCS"))
  849. event_code = EVENT_AUTHDIR_NEWDESCS;
  850. else if (!strcasecmp(ev, "DESCCHANGED"))
  851. event_code = EVENT_DESCCHANGED;
  852. else if (!strcasecmp(ev, "NS"))
  853. event_code = EVENT_NS;
  854. else if (!strcasecmp(ev, "STATUS_GENERAL"))
  855. event_code = EVENT_STATUS_GENERAL;
  856. else if (!strcasecmp(ev, "STATUS_CLIENT"))
  857. event_code = EVENT_STATUS_CLIENT;
  858. else if (!strcasecmp(ev, "STATUS_SERVER"))
  859. event_code = EVENT_STATUS_SERVER;
  860. else if (!strcasecmp(ev, "GUARD"))
  861. event_code = EVENT_GUARD;
  862. else if (!strcasecmp(ev, "STREAM_BW"))
  863. event_code = EVENT_STREAM_BANDWIDTH_USED;
  864. else if (!strcasecmp(ev, "CLIENTS_SEEN"))
  865. event_code = EVENT_CLIENTS_SEEN;
  866. else if (!strcasecmp(ev, "NEWCONSENSUS"))
  867. event_code = EVENT_NEWCONSENSUS;
  868. else if (!strcasecmp(ev, "BUILDTIMEOUT_SET"))
  869. event_code = EVENT_BUILDTIMEOUT_SET;
  870. else {
  871. connection_printf_to_buf(conn, "552 Unrecognized event \"%s\"\r\n",
  872. ev);
  873. SMARTLIST_FOREACH(events, char *, e, tor_free(e));
  874. smartlist_free(events);
  875. return 0;
  876. }
  877. event_mask |= (1 << event_code);
  878. }
  879. SMARTLIST_FOREACH_END(ev);
  880. SMARTLIST_FOREACH(events, char *, e, tor_free(e));
  881. smartlist_free(events);
  882. conn->event_mask = event_mask;
  883. control_update_global_event_mask();
  884. send_control_done(conn);
  885. return 0;
  886. }
  887. /** Decode the hashed, base64'd passwords stored in <b>passwords</b>.
  888. * Return a smartlist of acceptable passwords (unterminated strings of
  889. * length S2K_SPECIFIER_LEN+DIGEST_LEN) on success, or NULL on failure.
  890. */
  891. smartlist_t *
  892. decode_hashed_passwords(config_line_t *passwords)
  893. {
  894. char decoded[64];
  895. config_line_t *cl;
  896. smartlist_t *sl = smartlist_create();
  897. tor_assert(passwords);
  898. for (cl = passwords; cl; cl = cl->next) {
  899. const char *hashed = cl->value;
  900. if (!strcmpstart(hashed, "16:")) {
  901. if (base16_decode(decoded, sizeof(decoded), hashed+3, strlen(hashed+3))<0
  902. || strlen(hashed+3) != (S2K_SPECIFIER_LEN+DIGEST_LEN)*2) {
  903. goto err;
  904. }
  905. } else {
  906. if (base64_decode(decoded, sizeof(decoded), hashed, strlen(hashed))
  907. != S2K_SPECIFIER_LEN+DIGEST_LEN) {
  908. goto err;
  909. }
  910. }
  911. smartlist_add(sl, tor_memdup(decoded, S2K_SPECIFIER_LEN+DIGEST_LEN));
  912. }
  913. return sl;
  914. err:
  915. SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
  916. smartlist_free(sl);
  917. return NULL;
  918. }
  919. /** Called when we get an AUTHENTICATE message. Check whether the
  920. * authentication is valid, and if so, update the connection's state to
  921. * OPEN. Reply with DONE or ERROR.
  922. */
  923. static int
  924. handle_control_authenticate(control_connection_t *conn, uint32_t len,
  925. const char *body)
  926. {
  927. int used_quoted_string = 0;
  928. or_options_t *options = get_options();
  929. const char *errstr = NULL;
  930. char *password;
  931. size_t password_len;
  932. const char *cp;
  933. int i;
  934. int bad_cookie=0, bad_password=0;
  935. smartlist_t *sl = NULL;
  936. if (TOR_ISXDIGIT(body[0])) {
  937. cp = body;
  938. while (TOR_ISXDIGIT(*cp))
  939. ++cp;
  940. i = (int)(cp - body);
  941. tor_assert(i>0);
  942. password_len = i/2;
  943. password = tor_malloc(password_len + 1);
  944. if (base16_decode(password, password_len+1, body, i)<0) {
  945. connection_write_str_to_buf(
  946. "551 Invalid hexadecimal encoding. Maybe you tried a plain text "
  947. "password? If so, the standard requires that you put it in "
  948. "double quotes.\r\n", conn);
  949. connection_mark_for_close(TO_CONN(conn));
  950. tor_free(password);
  951. return 0;
  952. }
  953. } else if (TOR_ISSPACE(body[0])) {
  954. password = tor_strdup("");
  955. password_len = 0;
  956. } else {
  957. if (!decode_escaped_string(body, len, &password, &password_len)) {
  958. connection_write_str_to_buf("551 Invalid quoted string. You need "
  959. "to put the password in double quotes.\r\n", conn);
  960. connection_mark_for_close(TO_CONN(conn));
  961. return 0;
  962. }
  963. used_quoted_string = 1;
  964. }
  965. if (!options->CookieAuthentication && !options->HashedControlPassword &&
  966. !options->HashedControlSessionPassword) {
  967. /* if Tor doesn't demand any stronger authentication, then
  968. * the controller can get in with anything. */
  969. goto ok;
  970. }
  971. if (options->CookieAuthentication) {
  972. int also_password = options->HashedControlPassword != NULL ||
  973. options->HashedControlSessionPassword != NULL;
  974. if (password_len != AUTHENTICATION_COOKIE_LEN) {
  975. if (!also_password) {
  976. log_warn(LD_CONTROL, "Got authentication cookie with wrong length "
  977. "(%d)", (int)password_len);
  978. errstr = "Wrong length on authentication cookie.";
  979. goto err;
  980. }
  981. bad_cookie = 1;
  982. } else if (memcmp(authentication_cookie, password, password_len)) {
  983. if (!also_password) {
  984. log_warn(LD_CONTROL, "Got mismatched authentication cookie");
  985. errstr = "Authentication cookie did not match expected value.";
  986. goto err;
  987. }
  988. bad_cookie = 1;
  989. } else {
  990. goto ok;
  991. }
  992. }
  993. if (options->HashedControlPassword ||
  994. options->HashedControlSessionPassword) {
  995. int bad = 0;
  996. smartlist_t *sl_tmp;
  997. char received[DIGEST_LEN];
  998. int also_cookie = options->CookieAuthentication;
  999. sl = smartlist_create();
  1000. if (options->HashedControlPassword) {
  1001. sl_tmp = decode_hashed_passwords(options->HashedControlPassword);
  1002. if (!sl_tmp)
  1003. bad = 1;
  1004. else {
  1005. smartlist_add_all(sl, sl_tmp);
  1006. smartlist_free(sl_tmp);
  1007. }
  1008. }
  1009. if (options->HashedControlSessionPassword) {
  1010. sl_tmp = decode_hashed_passwords(options->HashedControlSessionPassword);
  1011. if (!sl_tmp)
  1012. bad = 1;
  1013. else {
  1014. smartlist_add_all(sl, sl_tmp);
  1015. smartlist_free(sl_tmp);
  1016. }
  1017. }
  1018. if (bad) {
  1019. if (!also_cookie) {
  1020. log_warn(LD_CONTROL,
  1021. "Couldn't decode HashedControlPassword: invalid base16");
  1022. errstr="Couldn't decode HashedControlPassword value in configuration.";
  1023. }
  1024. bad_password = 1;
  1025. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  1026. smartlist_free(sl);
  1027. } else {
  1028. SMARTLIST_FOREACH(sl, char *, expected,
  1029. {
  1030. secret_to_key(received,DIGEST_LEN,password,password_len,expected);
  1031. if (!memcmp(expected+S2K_SPECIFIER_LEN, received, DIGEST_LEN))
  1032. goto ok;
  1033. });
  1034. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  1035. smartlist_free(sl);
  1036. if (used_quoted_string)
  1037. errstr = "Password did not match HashedControlPassword value from "
  1038. "configuration";
  1039. else
  1040. errstr = "Password did not match HashedControlPassword value from "
  1041. "configuration. Maybe you tried a plain text password? "
  1042. "If so, the standard requires that you put it in double quotes.";
  1043. bad_password = 1;
  1044. if (!also_cookie)
  1045. goto err;
  1046. }
  1047. }
  1048. /** We only get here if both kinds of authentication failed. */
  1049. tor_assert(bad_password && bad_cookie);
  1050. log_warn(LD_CONTROL, "Bad password or authentication cookie on controller.");
  1051. errstr = "Password did not match HashedControlPassword *or* authentication "
  1052. "cookie.";
  1053. err:
  1054. tor_free(password);
  1055. connection_printf_to_buf(conn, "515 Authentication failed: %s\r\n",
  1056. errstr ? errstr : "Unknown reason.");
  1057. connection_mark_for_close(TO_CONN(conn));
  1058. return 0;
  1059. ok:
  1060. log_info(LD_CONTROL, "Authenticated control connection (%d)", conn->_base.s);
  1061. send_control_done(conn);
  1062. conn->_base.state = CONTROL_CONN_STATE_OPEN;
  1063. tor_free(password);
  1064. if (sl) { /* clean up */
  1065. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  1066. smartlist_free(sl);
  1067. }
  1068. return 0;
  1069. }
  1070. /** Called when we get a SAVECONF command. Try to flush the current options to
  1071. * disk, and report success or failure. */
  1072. static int
  1073. handle_control_saveconf(control_connection_t *conn, uint32_t len,
  1074. const char *body)
  1075. {
  1076. (void) len;
  1077. (void) body;
  1078. if (options_save_current()<0) {
  1079. connection_write_str_to_buf(
  1080. "551 Unable to write configuration to disk.\r\n", conn);
  1081. } else {
  1082. send_control_done(conn);
  1083. }
  1084. return 0;
  1085. }
  1086. /** Called when we get a SIGNAL command. React to the provided signal, and
  1087. * report success or failure. (If the signal results in a shutdown, success
  1088. * may not be reported.) */
  1089. static int
  1090. handle_control_signal(control_connection_t *conn, uint32_t len,
  1091. const char *body)
  1092. {
  1093. int sig;
  1094. int n = 0;
  1095. char *s;
  1096. (void) len;
  1097. while (body[n] && ! TOR_ISSPACE(body[n]))
  1098. ++n;
  1099. s = tor_strndup(body, n);
  1100. if (!strcasecmp(s, "RELOAD") || !strcasecmp(s, "HUP"))
  1101. sig = SIGHUP;
  1102. else if (!strcasecmp(s, "SHUTDOWN") || !strcasecmp(s, "INT"))
  1103. sig = SIGINT;
  1104. else if (!strcasecmp(s, "DUMP") || !strcasecmp(s, "USR1"))
  1105. sig = SIGUSR1;
  1106. else if (!strcasecmp(s, "DEBUG") || !strcasecmp(s, "USR2"))
  1107. sig = SIGUSR2;
  1108. else if (!strcasecmp(s, "HALT") || !strcasecmp(s, "TERM"))
  1109. sig = SIGTERM;
  1110. else if (!strcasecmp(s, "NEWNYM"))
  1111. sig = SIGNEWNYM;
  1112. else if (!strcasecmp(s, "CLEARDNSCACHE"))
  1113. sig = SIGCLEARDNSCACHE;
  1114. else {
  1115. connection_printf_to_buf(conn, "552 Unrecognized signal code \"%s\"\r\n",
  1116. s);
  1117. sig = -1;
  1118. }
  1119. tor_free(s);
  1120. if (sig<0)
  1121. return 0;
  1122. send_control_done(conn);
  1123. /* Flush the "done" first if the signal might make us shut down. */
  1124. if (sig == SIGTERM || sig == SIGINT)
  1125. connection_handle_write(TO_CONN(conn), 1);
  1126. control_signal_act(sig);
  1127. return 0;
  1128. }
  1129. /** Called when we get a MAPADDRESS command; try to bind all listed addresses,
  1130. * and report success or failure. */
  1131. static int
  1132. handle_control_mapaddress(control_connection_t *conn, uint32_t len,
  1133. const char *body)
  1134. {
  1135. smartlist_t *elts;
  1136. smartlist_t *lines;
  1137. smartlist_t *reply;
  1138. char *r;
  1139. size_t sz;
  1140. (void) len; /* body is NUL-terminated, so it's safe to ignore the length. */
  1141. lines = smartlist_create();
  1142. elts = smartlist_create();
  1143. reply = smartlist_create();
  1144. smartlist_split_string(lines, body, " ",
  1145. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1146. SMARTLIST_FOREACH(lines, char *, line,
  1147. {
  1148. tor_strlower(line);
  1149. smartlist_split_string(elts, line, "=", 0, 2);
  1150. if (smartlist_len(elts) == 2) {
  1151. const char *from = smartlist_get(elts,0);
  1152. const char *to = smartlist_get(elts,1);
  1153. size_t anslen = strlen(line)+512;
  1154. char *ans = tor_malloc(anslen);
  1155. if (address_is_invalid_destination(to, 1)) {
  1156. tor_snprintf(ans, anslen,
  1157. "512-syntax error: invalid address '%s'", to);
  1158. smartlist_add(reply, ans);
  1159. log_warn(LD_CONTROL,
  1160. "Skipping invalid argument '%s' in MapAddress msg", to);
  1161. } else if (!strcmp(from, ".") || !strcmp(from, "0.0.0.0")) {
  1162. const char *address = addressmap_register_virtual_address(
  1163. !strcmp(from,".") ? RESOLVED_TYPE_HOSTNAME : RESOLVED_TYPE_IPV4,
  1164. tor_strdup(to));
  1165. if (!address) {
  1166. tor_snprintf(ans, anslen,
  1167. "451-resource exhausted: skipping '%s'", line);
  1168. smartlist_add(reply, ans);
  1169. log_warn(LD_CONTROL,
  1170. "Unable to allocate address for '%s' in MapAddress msg",
  1171. safe_str_client(line));
  1172. } else {
  1173. tor_snprintf(ans, anslen, "250-%s=%s", address, to);
  1174. smartlist_add(reply, ans);
  1175. }
  1176. } else {
  1177. addressmap_register(from, tor_strdup(to), 1, ADDRMAPSRC_CONTROLLER);
  1178. tor_snprintf(ans, anslen, "250-%s", line);
  1179. smartlist_add(reply, ans);
  1180. }
  1181. } else {
  1182. size_t anslen = strlen(line)+256;
  1183. char *ans = tor_malloc(anslen);
  1184. tor_snprintf(ans, anslen, "512-syntax error: mapping '%s' is "
  1185. "not of expected form 'foo=bar'.", line);
  1186. smartlist_add(reply, ans);
  1187. log_info(LD_CONTROL, "Skipping MapAddress '%s': wrong "
  1188. "number of items.",
  1189. safe_str_client(line));
  1190. }
  1191. SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
  1192. smartlist_clear(elts);
  1193. });
  1194. SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
  1195. smartlist_free(lines);
  1196. smartlist_free(elts);
  1197. if (smartlist_len(reply)) {
  1198. ((char*)smartlist_get(reply,smartlist_len(reply)-1))[3] = ' ';
  1199. r = smartlist_join_strings(reply, "\r\n", 1, &sz);
  1200. connection_write_to_buf(r, sz, TO_CONN(conn));
  1201. tor_free(r);
  1202. } else {
  1203. const char *response =
  1204. "512 syntax error: not enough arguments to mapaddress.\r\n";
  1205. connection_write_to_buf(response, strlen(response), TO_CONN(conn));
  1206. }
  1207. SMARTLIST_FOREACH(reply, char *, cp, tor_free(cp));
  1208. smartlist_free(reply);
  1209. return 0;
  1210. }
  1211. /** Implementation helper for GETINFO: knows the answers for various
  1212. * trivial-to-implement questions. */
  1213. static int
  1214. getinfo_helper_misc(control_connection_t *conn, const char *question,
  1215. char **answer, const char **errmsg)
  1216. {
  1217. (void) conn;
  1218. if (!strcmp(question, "version")) {
  1219. *answer = tor_strdup(get_version());
  1220. } else if (!strcmp(question, "config-file")) {
  1221. *answer = tor_strdup(get_torrc_fname());
  1222. } else if (!strcmp(question, "config-text")) {
  1223. *answer = options_dump(get_options(), 1);
  1224. } else if (!strcmp(question, "info/names")) {
  1225. *answer = list_getinfo_options();
  1226. } else if (!strcmp(question, "events/names")) {
  1227. *answer = tor_strdup("CIRC STREAM ORCONN BW DEBUG INFO NOTICE WARN ERR "
  1228. "NEWDESC ADDRMAP AUTHDIR_NEWDESCS DESCCHANGED "
  1229. "NS STATUS_GENERAL STATUS_CLIENT STATUS_SERVER "
  1230. "GUARD STREAM_BW CLIENTS_SEEN NEWCONSENSUS");
  1231. } else if (!strcmp(question, "features/names")) {
  1232. *answer = tor_strdup("VERBOSE_NAMES EXTENDED_EVENTS");
  1233. } else if (!strcmp(question, "address")) {
  1234. uint32_t addr;
  1235. if (router_pick_published_address(get_options(), &addr) < 0) {
  1236. *errmsg = "Address unknown";
  1237. return -1;
  1238. }
  1239. *answer = tor_dup_ip(addr);
  1240. } else if (!strcmp(question, "dir-usage")) {
  1241. *answer = directory_dump_request_log();
  1242. } else if (!strcmp(question, "fingerprint")) {
  1243. routerinfo_t *me = router_get_my_routerinfo();
  1244. if (!me) {
  1245. *errmsg = "No routerdesc known; am I really a server?";
  1246. return -1;
  1247. }
  1248. *answer = tor_malloc(HEX_DIGEST_LEN+1);
  1249. base16_encode(*answer, HEX_DIGEST_LEN+1, me->cache_info.identity_digest,
  1250. DIGEST_LEN);
  1251. }
  1252. return 0;
  1253. }
  1254. /** Awful hack: return a newly allocated string based on a routerinfo and
  1255. * (possibly) an extrainfo, sticking the read-history and write-history from
  1256. * <b>ei</b> into the resulting string. The thing you get back won't
  1257. * necessarily have a valid signature.
  1258. *
  1259. * New code should never use this; it's for backward compatibility.
  1260. *
  1261. * NOTE: <b>ri_body</b> is as returned by signed_descriptor_get_body: it might
  1262. * not be NUL-terminated. */
  1263. static char *
  1264. munge_extrainfo_into_routerinfo(const char *ri_body, signed_descriptor_t *ri,
  1265. signed_descriptor_t *ei)
  1266. {
  1267. char *out = NULL, *outp;
  1268. int i;
  1269. const char *router_sig;
  1270. const char *ei_body = signed_descriptor_get_body(ei);
  1271. size_t ri_len = ri->signed_descriptor_len;
  1272. size_t ei_len = ei->signed_descriptor_len;
  1273. if (!ei_body)
  1274. goto bail;
  1275. outp = out = tor_malloc(ri_len+ei_len+1);
  1276. if (!(router_sig = tor_memstr(ri_body, ri_len, "\nrouter-signature")))
  1277. goto bail;
  1278. ++router_sig;
  1279. memcpy(out, ri_body, router_sig-ri_body);
  1280. outp += router_sig-ri_body;
  1281. for (i=0; i < 2; ++i) {
  1282. const char *kwd = i?"\nwrite-history ":"\nread-history ";
  1283. const char *cp, *eol;
  1284. if (!(cp = tor_memstr(ei_body, ei_len, kwd)))
  1285. continue;
  1286. ++cp;
  1287. eol = memchr(cp, '\n', ei_len - (cp-ei_body));
  1288. memcpy(outp, cp, eol-cp+1);
  1289. outp += eol-cp+1;
  1290. }
  1291. memcpy(outp, router_sig, ri_len - (router_sig-ri_body));
  1292. *outp++ = '\0';
  1293. tor_assert(outp-out < (int)(ri_len+ei_len+1));
  1294. return out;
  1295. bail:
  1296. tor_free(out);
  1297. return tor_strndup(ri_body, ri->signed_descriptor_len);
  1298. }
  1299. /** Implementation helper for GETINFO: knows the answers for questions about
  1300. * directory information. */
  1301. static int
  1302. getinfo_helper_dir(control_connection_t *control_conn,
  1303. const char *question, char **answer,
  1304. const char **errmsg)
  1305. {
  1306. (void) control_conn;
  1307. if (!strcmpstart(question, "desc/id/")) {
  1308. routerinfo_t *ri = router_get_by_hexdigest(question+strlen("desc/id/"));
  1309. if (ri) {
  1310. const char *body = signed_descriptor_get_body(&ri->cache_info);
  1311. if (body)
  1312. *answer = tor_strndup(body, ri->cache_info.signed_descriptor_len);
  1313. }
  1314. } else if (!strcmpstart(question, "desc/name/")) {
  1315. routerinfo_t *ri = router_get_by_nickname(question+strlen("desc/name/"),1);
  1316. if (ri) {
  1317. const char *body = signed_descriptor_get_body(&ri->cache_info);
  1318. if (body)
  1319. *answer = tor_strndup(body, ri->cache_info.signed_descriptor_len);
  1320. }
  1321. } else if (!strcmp(question, "desc/all-recent")) {
  1322. routerlist_t *routerlist = router_get_routerlist();
  1323. smartlist_t *sl = smartlist_create();
  1324. if (routerlist && routerlist->routers) {
  1325. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, ri,
  1326. {
  1327. const char *body = signed_descriptor_get_body(&ri->cache_info);
  1328. if (body)
  1329. smartlist_add(sl,
  1330. tor_strndup(body, ri->cache_info.signed_descriptor_len));
  1331. });
  1332. }
  1333. *answer = smartlist_join_strings(sl, "", 0, NULL);
  1334. SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  1335. smartlist_free(sl);
  1336. } else if (!strcmp(question, "desc/all-recent-extrainfo-hack")) {
  1337. /* XXXX Remove this once Torstat asks for extrainfos. */
  1338. routerlist_t *routerlist = router_get_routerlist();
  1339. smartlist_t *sl = smartlist_create();
  1340. if (routerlist && routerlist->routers) {
  1341. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, ri,
  1342. {
  1343. const char *body = signed_descriptor_get_body(&ri->cache_info);
  1344. signed_descriptor_t *ei = extrainfo_get_by_descriptor_digest(
  1345. ri->cache_info.extra_info_digest);
  1346. if (ei && body) {
  1347. smartlist_add(sl, munge_extrainfo_into_routerinfo(body,
  1348. &ri->cache_info, ei));
  1349. } else if (body) {
  1350. smartlist_add(sl,
  1351. tor_strndup(body, ri->cache_info.signed_descriptor_len));
  1352. }
  1353. });
  1354. }
  1355. *answer = smartlist_join_strings(sl, "", 0, NULL);
  1356. SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  1357. smartlist_free(sl);
  1358. } else if (!strcmpstart(question, "desc-annotations/id/")) {
  1359. routerinfo_t *ri = router_get_by_hexdigest(question+
  1360. strlen("desc-annotations/id/"));
  1361. if (ri) {
  1362. const char *annotations =
  1363. signed_descriptor_get_annotations(&ri->cache_info);
  1364. if (annotations)
  1365. *answer = tor_strndup(annotations,
  1366. ri->cache_info.annotations_len);
  1367. }
  1368. } else if (!strcmpstart(question, "dir/server/")) {
  1369. size_t answer_len = 0, url_len = strlen(question)+2;
  1370. char *url = tor_malloc(url_len);
  1371. smartlist_t *descs = smartlist_create();
  1372. const char *msg;
  1373. int res;
  1374. char *cp;
  1375. tor_snprintf(url, url_len, "/tor/%s", question+4);
  1376. res = dirserv_get_routerdescs(descs, url, &msg);
  1377. if (res) {
  1378. log_warn(LD_CONTROL, "getinfo '%s': %s", question, msg);
  1379. smartlist_free(descs);
  1380. tor_free(url);
  1381. *errmsg = msg;
  1382. return -1;
  1383. }
  1384. SMARTLIST_FOREACH(descs, signed_descriptor_t *, sd,
  1385. answer_len += sd->signed_descriptor_len);
  1386. cp = *answer = tor_malloc(answer_len+1);
  1387. SMARTLIST_FOREACH(descs, signed_descriptor_t *, sd,
  1388. {
  1389. memcpy(cp, signed_descriptor_get_body(sd),
  1390. sd->signed_descriptor_len);
  1391. cp += sd->signed_descriptor_len;
  1392. });
  1393. *cp = '\0';
  1394. tor_free(url);
  1395. smartlist_free(descs);
  1396. } else if (!strcmpstart(question, "dir/status/")) {
  1397. if (directory_permits_controller_requests(get_options())) {
  1398. size_t len=0;
  1399. char *cp;
  1400. smartlist_t *status_list = smartlist_create();
  1401. dirserv_get_networkstatus_v2(status_list,
  1402. question+strlen("dir/status/"));
  1403. SMARTLIST_FOREACH(status_list, cached_dir_t *, d, len += d->dir_len);
  1404. cp = *answer = tor_malloc(len+1);
  1405. SMARTLIST_FOREACH(status_list, cached_dir_t *, d, {
  1406. memcpy(cp, d->dir, d->dir_len);
  1407. cp += d->dir_len;
  1408. });
  1409. *cp = '\0';
  1410. smartlist_free(status_list);
  1411. } else {
  1412. smartlist_t *fp_list = smartlist_create();
  1413. smartlist_t *status_list = smartlist_create();
  1414. dirserv_get_networkstatus_v2_fingerprints(
  1415. fp_list, question+strlen("dir/status/"));
  1416. SMARTLIST_FOREACH(fp_list, const char *, fp, {
  1417. char *s;
  1418. char *fname = networkstatus_get_cache_filename(fp);
  1419. s = read_file_to_str(fname, 0, NULL);
  1420. if (s)
  1421. smartlist_add(status_list, s);
  1422. tor_free(fname);
  1423. });
  1424. SMARTLIST_FOREACH(fp_list, char *, fp, tor_free(fp));
  1425. smartlist_free(fp_list);
  1426. *answer = smartlist_join_strings(status_list, "", 0, NULL);
  1427. SMARTLIST_FOREACH(status_list, char *, s, tor_free(s));
  1428. smartlist_free(status_list);
  1429. }
  1430. } else if (!strcmp(question, "dir/status-vote/current/consensus")) { /* v3 */
  1431. if (directory_caches_dir_info(get_options())) {
  1432. const cached_dir_t *consensus = dirserv_get_consensus("ns");
  1433. if (consensus)
  1434. *answer = tor_strdup(consensus->dir);
  1435. }
  1436. if (!*answer) { /* try loading it from disk */
  1437. char *filename = get_datadir_fname("cached-consensus");
  1438. *answer = read_file_to_str(filename, RFTS_IGNORE_MISSING, NULL);
  1439. tor_free(filename);
  1440. }
  1441. } else if (!strcmp(question, "network-status")) { /* v1 */
  1442. routerlist_t *routerlist = router_get_routerlist();
  1443. if (!routerlist || !routerlist->routers ||
  1444. list_server_status_v1(routerlist->routers, answer, 1) < 0) {
  1445. return -1;
  1446. }
  1447. } else if (!strcmpstart(question, "extra-info/digest/")) {
  1448. question += strlen("extra-info/digest/");
  1449. if (strlen(question) == HEX_DIGEST_LEN) {
  1450. char d[DIGEST_LEN];
  1451. signed_descriptor_t *sd = NULL;
  1452. if (base16_decode(d, sizeof(d), question, strlen(question))==0) {
  1453. /* XXXX this test should move into extrainfo_get_by_descriptor_digest,
  1454. * but I don't want to risk affecting other parts of the code,
  1455. * especially since the rules for using our own extrainfo (including
  1456. * when it might be freed) are different from those for using one
  1457. * we have downloaded. */
  1458. if (router_extrainfo_digest_is_me(d))
  1459. sd = &(router_get_my_extrainfo()->cache_info);
  1460. else
  1461. sd = extrainfo_get_by_descriptor_digest(d);
  1462. }
  1463. if (sd) {
  1464. const char *body = signed_descriptor_get_body(sd);
  1465. if (body)
  1466. *answer = tor_strndup(body, sd->signed_descriptor_len);
  1467. }
  1468. }
  1469. }
  1470. return 0;
  1471. }
  1472. /** Implementation helper for GETINFO: knows how to generate summaries of the
  1473. * current states of things we send events about. */
  1474. static int
  1475. getinfo_helper_events(control_connection_t *control_conn,
  1476. const char *question, char **answer,
  1477. const char **errmsg)
  1478. {
  1479. (void) control_conn;
  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. const char *purpose;
  1488. if (! CIRCUIT_IS_ORIGIN(circ) || circ->marked_for_close)
  1489. continue;
  1490. path = circuit_list_path_for_controller(TO_ORIGIN_CIRCUIT(circ));
  1491. if (circ->state == CIRCUIT_STATE_OPEN)
  1492. state = "BUILT";
  1493. else if (strlen(path))
  1494. state = "EXTENDED";
  1495. else
  1496. state = "LAUNCHED";
  1497. purpose = circuit_purpose_to_controller_string(circ->purpose);
  1498. slen = strlen(path)+strlen(state)+strlen(purpose)+30;
  1499. s = tor_malloc(slen+1);
  1500. tor_snprintf(s, slen, "%lu %s%s%s PURPOSE=%s",
  1501. (unsigned long)TO_ORIGIN_CIRCUIT(circ)->global_identifier,
  1502. state, *path ? " " : "", path, purpose);
  1503. smartlist_add(status, s);
  1504. tor_free(path);
  1505. }
  1506. *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
  1507. SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
  1508. smartlist_free(status);
  1509. } else if (!strcmp(question, "stream-status")) {
  1510. smartlist_t *conns = get_connection_array();
  1511. smartlist_t *status = smartlist_create();
  1512. char buf[256];
  1513. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, base_conn) {
  1514. const char *state;
  1515. edge_connection_t *conn;
  1516. char *s;
  1517. size_t slen;
  1518. circuit_t *circ;
  1519. origin_circuit_t *origin_circ = NULL;
  1520. if (base_conn->type != CONN_TYPE_AP ||
  1521. base_conn->marked_for_close ||
  1522. base_conn->state == AP_CONN_STATE_SOCKS_WAIT ||
  1523. base_conn->state == AP_CONN_STATE_NATD_WAIT)
  1524. continue;
  1525. conn = TO_EDGE_CONN(base_conn);
  1526. switch (conn->_base.state)
  1527. {
  1528. case AP_CONN_STATE_CONTROLLER_WAIT:
  1529. case AP_CONN_STATE_CIRCUIT_WAIT:
  1530. if (conn->socks_request &&
  1531. SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command))
  1532. state = "NEWRESOLVE";
  1533. else
  1534. state = "NEW";
  1535. break;
  1536. case AP_CONN_STATE_RENDDESC_WAIT:
  1537. case AP_CONN_STATE_CONNECT_WAIT:
  1538. state = "SENTCONNECT"; break;
  1539. case AP_CONN_STATE_RESOLVE_WAIT:
  1540. state = "SENTRESOLVE"; break;
  1541. case AP_CONN_STATE_OPEN:
  1542. state = "SUCCEEDED"; break;
  1543. default:
  1544. log_warn(LD_BUG, "Asked for stream in unknown state %d",
  1545. conn->_base.state);
  1546. continue;
  1547. }
  1548. circ = circuit_get_by_edge_conn(conn);
  1549. if (circ && CIRCUIT_IS_ORIGIN(circ))
  1550. origin_circ = TO_ORIGIN_CIRCUIT(circ);
  1551. write_stream_target_to_buf(conn, buf, sizeof(buf));
  1552. slen = strlen(buf)+strlen(state)+32;
  1553. s = tor_malloc(slen+1);
  1554. tor_snprintf(s, slen, "%lu %s %lu %s",
  1555. (unsigned long) conn->_base.global_identifier,state,
  1556. origin_circ?
  1557. (unsigned long)origin_circ->global_identifier : 0ul,
  1558. buf);
  1559. smartlist_add(status, s);
  1560. } SMARTLIST_FOREACH_END(base_conn);
  1561. *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
  1562. SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
  1563. smartlist_free(status);
  1564. } else if (!strcmp(question, "orconn-status")) {
  1565. smartlist_t *conns = get_connection_array();
  1566. smartlist_t *status = smartlist_create();
  1567. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, base_conn) {
  1568. const char *state;
  1569. char *s;
  1570. char name[128];
  1571. size_t slen;
  1572. or_connection_t *conn;
  1573. if (base_conn->type != CONN_TYPE_OR || base_conn->marked_for_close)
  1574. continue;
  1575. conn = TO_OR_CONN(base_conn);
  1576. if (conn->_base.state == OR_CONN_STATE_OPEN)
  1577. state = "CONNECTED";
  1578. else if (conn->nickname)
  1579. state = "LAUNCHED";
  1580. else
  1581. state = "NEW";
  1582. orconn_target_get_name(name, sizeof(name), conn);
  1583. slen = strlen(name)+strlen(state)+2;
  1584. s = tor_malloc(slen+1);
  1585. tor_snprintf(s, slen, "%s %s", name, state);
  1586. smartlist_add(status, s);
  1587. } SMARTLIST_FOREACH_END(base_conn);
  1588. *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
  1589. SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
  1590. smartlist_free(status);
  1591. } else if (!strcmpstart(question, "address-mappings/")) {
  1592. time_t min_e, max_e;
  1593. smartlist_t *mappings;
  1594. question += strlen("address-mappings/");
  1595. if (!strcmp(question, "all")) {
  1596. min_e = 0; max_e = TIME_MAX;
  1597. } else if (!strcmp(question, "cache")) {
  1598. min_e = 2; max_e = TIME_MAX;
  1599. } else if (!strcmp(question, "config")) {
  1600. min_e = 0; max_e = 0;
  1601. } else if (!strcmp(question, "control")) {
  1602. min_e = 1; max_e = 1;
  1603. } else {
  1604. return 0;
  1605. }
  1606. mappings = smartlist_create();
  1607. addressmap_get_mappings(mappings, min_e, max_e, 1);
  1608. *answer = smartlist_join_strings(mappings, "\r\n", 0, NULL);
  1609. SMARTLIST_FOREACH(mappings, char *, cp, tor_free(cp));
  1610. smartlist_free(mappings);
  1611. } else if (!strcmpstart(question, "status/")) {
  1612. /* Note that status/ is not a catch-all for events; there's only supposed
  1613. * to be a status GETINFO if there's a corresponding STATUS event. */
  1614. if (!strcmp(question, "status/circuit-established")) {
  1615. *answer = tor_strdup(can_complete_circuit ? "1" : "0");
  1616. } else if (!strcmp(question, "status/enough-dir-info")) {
  1617. *answer = tor_strdup(router_have_minimum_dir_info() ? "1" : "0");
  1618. } else if (!strcmp(question, "status/good-server-descriptor") ||
  1619. !strcmp(question, "status/accepted-server-descriptor")) {
  1620. /* They're equivalent for now, until we can figure out how to make
  1621. * good-server-descriptor be what we want. See comment in
  1622. * control-spec.txt. */
  1623. *answer = tor_strdup(directories_have_accepted_server_descriptor()
  1624. ? "1" : "0");
  1625. } else if (!strcmp(question, "status/reachability-succeeded/or")) {
  1626. *answer = tor_strdup(check_whether_orport_reachable() ? "1" : "0");
  1627. } else if (!strcmp(question, "status/reachability-succeeded/dir")) {
  1628. *answer = tor_strdup(check_whether_dirport_reachable() ? "1" : "0");
  1629. } else if (!strcmp(question, "status/reachability-succeeded")) {
  1630. *answer = tor_malloc(16);
  1631. tor_snprintf(*answer, 16, "OR=%d DIR=%d",
  1632. check_whether_orport_reachable() ? 1 : 0,
  1633. check_whether_dirport_reachable() ? 1 : 0);
  1634. } else if (!strcmp(question, "status/bootstrap-phase")) {
  1635. *answer = tor_strdup(last_sent_bootstrap_message);
  1636. } else if (!strcmpstart(question, "status/version/")) {
  1637. int is_server = server_mode(get_options());
  1638. networkstatus_t *c = networkstatus_get_latest_consensus();
  1639. version_status_t status;
  1640. const char *recommended;
  1641. if (c) {
  1642. recommended = is_server ? c->server_versions : c->client_versions;
  1643. status = tor_version_is_obsolete(VERSION, recommended);
  1644. } else {
  1645. recommended = "?";
  1646. status = VS_UNKNOWN;
  1647. }
  1648. if (!strcmp(question, "status/version/recommended")) {
  1649. *answer = tor_strdup(recommended);
  1650. return 0;
  1651. }
  1652. if (!strcmp(question, "status/version/current")) {
  1653. switch (status)
  1654. {
  1655. case VS_RECOMMENDED: *answer = tor_strdup("recommended"); break;
  1656. case VS_OLD: *answer = tor_strdup("obsolete"); break;
  1657. case VS_NEW: *answer = tor_strdup("new"); break;
  1658. case VS_NEW_IN_SERIES: *answer = tor_strdup("new in series"); break;
  1659. case VS_UNRECOMMENDED: *answer = tor_strdup("unrecommended"); break;
  1660. case VS_EMPTY: *answer = tor_strdup("none recommended"); break;
  1661. case VS_UNKNOWN: *answer = tor_strdup("unknown"); break;
  1662. default: tor_fragile_assert();
  1663. }
  1664. } else if (!strcmp(question, "status/version/num-versioning") ||
  1665. !strcmp(question, "status/version/num-concurring")) {
  1666. char s[33];
  1667. tor_snprintf(s, sizeof(s), "%d", get_n_authorities(V3_AUTHORITY));
  1668. *answer = tor_strdup(s);
  1669. log_warn(LD_GENERAL, "%s is deprecated; it no longer gives useful "
  1670. "information", question);
  1671. }
  1672. } else if (!strcmp(question, "status/clients-seen")) {
  1673. const char *bridge_stats = geoip_get_bridge_stats_controller(time(NULL));
  1674. if (!bridge_stats) {
  1675. *errmsg = "No bridge-client stats available";
  1676. return -1;
  1677. }
  1678. *answer = tor_strdup(bridge_stats);
  1679. } else {
  1680. return 0;
  1681. }
  1682. }
  1683. return 0;
  1684. }
  1685. /** Callback function for GETINFO: on a given control connection, try to
  1686. * answer the question <b>q</b> and store the newly-allocated answer in
  1687. * *<b>a</b>. If an internal error occurs, return -1 and optionally set
  1688. * *<b>error_out</b> to point to an error message to be delivered to the
  1689. * controller. On success, _or if the key is not recognized_, return 0. Do not
  1690. * set <b>a</b> if the key is not recognized.
  1691. */
  1692. typedef int (*getinfo_helper_t)(control_connection_t *,
  1693. const char *q, char **a,
  1694. const char **error_out);
  1695. /** A single item for the GETINFO question-to-answer-function table. */
  1696. typedef struct getinfo_item_t {
  1697. const char *varname; /**< The value (or prefix) of the question. */
  1698. getinfo_helper_t fn; /**< The function that knows the answer: NULL if
  1699. * this entry is documentation-only. */
  1700. const char *desc; /**< Description of the variable. */
  1701. int is_prefix; /** Must varname match exactly, or must it be a prefix? */
  1702. } getinfo_item_t;
  1703. #define ITEM(name, fn, desc) { name, getinfo_helper_##fn, desc, 0 }
  1704. #define PREFIX(name, fn, desc) { name, getinfo_helper_##fn, desc, 1 }
  1705. #define DOC(name, desc) { name, NULL, desc, 0 }
  1706. /** Table mapping questions accepted by GETINFO to the functions that know how
  1707. * to answer them. */
  1708. static const getinfo_item_t getinfo_items[] = {
  1709. ITEM("version", misc, "The current version of Tor."),
  1710. ITEM("config-file", misc, "Current location of the \"torrc\" file."),
  1711. ITEM("config-text", misc,
  1712. "Return the string that would be written by a saveconf command."),
  1713. ITEM("accounting/bytes", accounting,
  1714. "Number of bytes read/written so far in the accounting interval."),
  1715. ITEM("accounting/bytes-left", accounting,
  1716. "Number of bytes left to write/read so far in the accounting interval."),
  1717. ITEM("accounting/enabled", accounting, "Is accounting currently enabled?"),
  1718. ITEM("accounting/hibernating", accounting, "Are we hibernating or awake?"),
  1719. ITEM("accounting/interval-start", accounting,
  1720. "Time when the accounting period starts."),
  1721. ITEM("accounting/interval-end", accounting,
  1722. "Time when the accounting period ends."),
  1723. ITEM("accounting/interval-wake", accounting,
  1724. "Time to wake up in this accounting period."),
  1725. ITEM("helper-nodes", entry_guards, NULL), /* deprecated */
  1726. ITEM("entry-guards", entry_guards,
  1727. "Which nodes are we using as entry guards?"),
  1728. ITEM("fingerprint", misc, NULL),
  1729. PREFIX("config/", config, "Current configuration values."),
  1730. DOC("config/names",
  1731. "List of configuration options, types, and documentation."),
  1732. ITEM("info/names", misc,
  1733. "List of GETINFO options, types, and documentation."),
  1734. ITEM("events/names", misc,
  1735. "Events that the controller can ask for with SETEVENTS."),
  1736. ITEM("features/names", misc, "What arguments can USEFEATURE take?"),
  1737. PREFIX("desc/id/", dir, "Router descriptors by ID."),
  1738. PREFIX("desc/name/", dir, "Router descriptors by nickname."),
  1739. ITEM("desc/all-recent", dir,
  1740. "All non-expired, non-superseded router descriptors."),
  1741. ITEM("desc/all-recent-extrainfo-hack", dir, NULL), /* Hack. */
  1742. PREFIX("extra-info/digest/", dir, "Extra-info documents by digest."),
  1743. ITEM("ns/all", networkstatus,
  1744. "Brief summary of router status (v2 directory format)"),
  1745. PREFIX("ns/id/", networkstatus,
  1746. "Brief summary of router status by ID (v2 directory format)."),
  1747. PREFIX("ns/name/", networkstatus,
  1748. "Brief summary of router status by nickname (v2 directory format)."),
  1749. PREFIX("ns/purpose/", networkstatus,
  1750. "Brief summary of router status by purpose (v2 directory format)."),
  1751. ITEM("network-status", dir,
  1752. "Brief summary of router status (v1 directory format)"),
  1753. ITEM("circuit-status", events, "List of current circuits originating here."),
  1754. ITEM("stream-status", events,"List of current streams."),
  1755. ITEM("orconn-status", events, "A list of current OR connections."),
  1756. PREFIX("address-mappings/", events, NULL),
  1757. DOC("address-mappings/all", "Current address mappings."),
  1758. DOC("address-mappings/cache", "Current cached DNS replies."),
  1759. DOC("address-mappings/config",
  1760. "Current address mappings from configuration."),
  1761. DOC("address-mappings/control", "Current address mappings from controller."),
  1762. PREFIX("status/", events, NULL),
  1763. DOC("status/circuit-established",
  1764. "Whether we think client functionality is working."),
  1765. DOC("status/enough-dir-info",
  1766. "Whether we have enough up-to-date directory information to build "
  1767. "circuits."),
  1768. DOC("status/bootstrap-phase",
  1769. "The last bootstrap phase status event that Tor sent."),
  1770. DOC("status/clients-seen",
  1771. "Breakdown of client countries seen by a bridge."),
  1772. DOC("status/version/recommended", "List of currently recommended versions."),
  1773. DOC("status/version/current", "Status of the current version."),
  1774. DOC("status/version/num-versioning", "Number of versioning authorities."),
  1775. DOC("status/version/num-concurring",
  1776. "Number of versioning authorities agreeing on the status of the "
  1777. "current version"),
  1778. ITEM("address", misc, "IP address of this Tor host, if we can guess it."),
  1779. ITEM("dir-usage", misc, "Breakdown of bytes transferred over DirPort."),
  1780. PREFIX("desc-annotations/id/", dir, "Router annotations by hexdigest."),
  1781. PREFIX("dir/server/", dir,"Router descriptors as retrieved from a DirPort."),
  1782. PREFIX("dir/status/", dir,
  1783. "v2 networkstatus docs as retrieved from a DirPort."),
  1784. ITEM("dir/status-vote/current/consensus", dir,
  1785. "v3 Networkstatus consensus as retrieved from a DirPort."),
  1786. PREFIX("exit-policy/default", policies,
  1787. "The default value appended to the configured exit policy."),
  1788. PREFIX("ip-to-country/", geoip, "Perform a GEOIP lookup"),
  1789. { NULL, NULL, NULL, 0 }
  1790. };
  1791. /** Allocate and return a list of recognized GETINFO options. */
  1792. static char *
  1793. list_getinfo_options(void)
  1794. {
  1795. int i;
  1796. char *buf=NULL;
  1797. smartlist_t *lines = smartlist_create();
  1798. char *ans;
  1799. for (i = 0; getinfo_items[i].varname; ++i) {
  1800. if (!getinfo_items[i].desc)
  1801. continue;
  1802. tor_asprintf(&buf, "%s%s -- %s\n",
  1803. getinfo_items[i].varname,
  1804. getinfo_items[i].is_prefix ? "*" : "",
  1805. getinfo_items[i].desc);
  1806. smartlist_add(lines, buf);
  1807. }
  1808. smartlist_sort_strings(lines);
  1809. ans = smartlist_join_strings(lines, "", 0, NULL);
  1810. SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
  1811. smartlist_free(lines);
  1812. return ans;
  1813. }
  1814. /** Lookup the 'getinfo' entry <b>question</b>, and return
  1815. * the answer in <b>*answer</b> (or NULL if key not recognized).
  1816. * Return 0 if success or unrecognized, or -1 if recognized but
  1817. * internal error. */
  1818. static int
  1819. handle_getinfo_helper(control_connection_t *control_conn,
  1820. const char *question, char **answer,
  1821. const char **err_out)
  1822. {
  1823. int i;
  1824. *answer = NULL; /* unrecognized key by default */
  1825. for (i = 0; getinfo_items[i].varname; ++i) {
  1826. int match;
  1827. if (getinfo_items[i].is_prefix)
  1828. match = !strcmpstart(question, getinfo_items[i].varname);
  1829. else
  1830. match = !strcmp(question, getinfo_items[i].varname);
  1831. if (match) {
  1832. tor_assert(getinfo_items[i].fn);
  1833. return getinfo_items[i].fn(control_conn, question, answer, err_out);
  1834. }
  1835. }
  1836. return 0; /* unrecognized */
  1837. }
  1838. /** Called when we receive a GETINFO command. Try to fetch all requested
  1839. * information, and reply with information or error message. */
  1840. static int
  1841. handle_control_getinfo(control_connection_t *conn, uint32_t len,
  1842. const char *body)
  1843. {
  1844. smartlist_t *questions = smartlist_create();
  1845. smartlist_t *answers = smartlist_create();
  1846. smartlist_t *unrecognized = smartlist_create();
  1847. char *msg = NULL, *ans = NULL;
  1848. int i;
  1849. (void) len; /* body is NUL-terminated, so it's safe to ignore the length. */
  1850. smartlist_split_string(questions, body, " ",
  1851. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1852. SMARTLIST_FOREACH_BEGIN(questions, const char *, q) {
  1853. const char *errmsg = NULL;
  1854. if (handle_getinfo_helper(conn, q, &ans, &errmsg) < 0) {
  1855. if (!errmsg)
  1856. errmsg = "Internal error";
  1857. connection_printf_to_buf(conn, "551 %s\r\n", errmsg);
  1858. goto done;
  1859. }
  1860. if (!ans) {
  1861. smartlist_add(unrecognized, (char*)q);
  1862. } else {
  1863. smartlist_add(answers, tor_strdup(q));
  1864. smartlist_add(answers, ans);
  1865. }
  1866. } SMARTLIST_FOREACH_END(q);
  1867. if (smartlist_len(unrecognized)) {
  1868. for (i=0; i < smartlist_len(unrecognized)-1; ++i)
  1869. connection_printf_to_buf(conn,
  1870. "552-Unrecognized key \"%s\"\r\n",
  1871. (char*)smartlist_get(unrecognized, i));
  1872. connection_printf_to_buf(conn,
  1873. "552 Unrecognized key \"%s\"\r\n",
  1874. (char*)smartlist_get(unrecognized, i));
  1875. goto done;
  1876. }
  1877. for (i = 0; i < smartlist_len(answers); i += 2) {
  1878. char *k = smartlist_get(answers, i);
  1879. char *v = smartlist_get(answers, i+1);
  1880. if (!strchr(v, '\n') && !strchr(v, '\r')) {
  1881. connection_printf_to_buf(conn, "250-%s=", k);
  1882. connection_write_str_to_buf(v, conn);
  1883. connection_write_str_to_buf("\r\n", conn);
  1884. } else {
  1885. char *esc = NULL;
  1886. size_t esc_len;
  1887. esc_len = write_escaped_data(v, strlen(v), &esc);
  1888. connection_printf_to_buf(conn, "250+%s=\r\n", k);
  1889. connection_write_to_buf(esc, esc_len, TO_CONN(conn));
  1890. tor_free(esc);
  1891. }
  1892. }
  1893. connection_write_str_to_buf("250 OK\r\n", conn);
  1894. done:
  1895. SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
  1896. smartlist_free(answers);
  1897. SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
  1898. smartlist_free(questions);
  1899. smartlist_free(unrecognized);
  1900. tor_free(msg);
  1901. return 0;
  1902. }
  1903. /** Given a string, convert it to a circuit purpose. */
  1904. static uint8_t
  1905. circuit_purpose_from_string(const char *string)
  1906. {
  1907. if (!strcasecmpstart(string, "purpose="))
  1908. string += strlen("purpose=");
  1909. if (!strcasecmp(string, "general"))
  1910. return CIRCUIT_PURPOSE_C_GENERAL;
  1911. else if (!strcasecmp(string, "controller"))
  1912. return CIRCUIT_PURPOSE_CONTROLLER;
  1913. else
  1914. return CIRCUIT_PURPOSE_UNKNOWN;
  1915. }
  1916. /** Return a newly allocated smartlist containing the arguments to the command
  1917. * waiting in <b>body</b>. If there are fewer than <b>min_args</b> arguments,
  1918. * or if <b>max_args</b> is nonnegative and there are more than
  1919. * <b>max_args</b> arguments, send a 512 error to the controller, using
  1920. * <b>command</b> as the command name in the error message. */
  1921. static smartlist_t *
  1922. getargs_helper(const char *command, control_connection_t *conn,
  1923. const char *body, int min_args, int max_args)
  1924. {
  1925. smartlist_t *args = smartlist_create();
  1926. smartlist_split_string(args, body, " ",
  1927. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1928. if (smartlist_len(args) < min_args) {
  1929. connection_printf_to_buf(conn, "512 Missing argument to %s\r\n",command);
  1930. goto err;
  1931. } else if (max_args >= 0 && smartlist_len(args) > max_args) {
  1932. connection_printf_to_buf(conn, "512 Too many arguments to %s\r\n",command);
  1933. goto err;
  1934. }
  1935. return args;
  1936. err:
  1937. SMARTLIST_FOREACH(args, char *, s, tor_free(s));
  1938. smartlist_free(args);
  1939. return NULL;
  1940. }
  1941. /** Helper. Return the first element of <b>sl</b> at index <b>start_at</b> or
  1942. * higher that starts with <b>prefix</b>, case-insensitive. Return NULL if no
  1943. * such element exists. */
  1944. static const char *
  1945. find_element_starting_with(smartlist_t *sl, int start_at, const char *prefix)
  1946. {
  1947. int i;
  1948. for (i = start_at; i < smartlist_len(sl); ++i) {
  1949. const char *elt = smartlist_get(sl, i);
  1950. if (!strcasecmpstart(elt, prefix))
  1951. return elt;
  1952. }
  1953. return NULL;
  1954. }
  1955. /** Helper. Return true iff s is an argument that we should treat as a
  1956. * key-value pair. */
  1957. static int
  1958. is_keyval_pair(const char *s)
  1959. {
  1960. /* An argument is a key-value pair if it has an =, and it isn't of the form
  1961. * $fingeprint=name */
  1962. return strchr(s, '=') && s[0] != '$';
  1963. }
  1964. /** Called when we get an EXTENDCIRCUIT message. Try to extend the listed
  1965. * circuit, and report success or failure. */
  1966. static int
  1967. handle_control_extendcircuit(control_connection_t *conn, uint32_t len,
  1968. const char *body)
  1969. {
  1970. smartlist_t *router_nicknames=NULL, *routers=NULL;
  1971. origin_circuit_t *circ = NULL;
  1972. int zero_circ;
  1973. uint8_t intended_purpose = CIRCUIT_PURPOSE_C_GENERAL;
  1974. smartlist_t *args;
  1975. (void) len;
  1976. router_nicknames = smartlist_create();
  1977. args = getargs_helper("EXTENDCIRCUIT", conn, body, 1, -1);
  1978. if (!args)
  1979. goto done;
  1980. zero_circ = !strcmp("0", (char*)smartlist_get(args,0));
  1981. if (zero_circ) {
  1982. const char *purp = find_element_starting_with(args, 1, "PURPOSE=");
  1983. if (purp) {
  1984. intended_purpose = circuit_purpose_from_string(purp);
  1985. if (intended_purpose == CIRCUIT_PURPOSE_UNKNOWN) {
  1986. connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n", purp);
  1987. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1988. smartlist_free(args);
  1989. goto done;
  1990. }
  1991. }
  1992. if ((smartlist_len(args) == 1) ||
  1993. (smartlist_len(args) >= 2 && is_keyval_pair(smartlist_get(args, 1)))) {
  1994. // "EXTENDCIRCUIT 0" || EXTENDCIRCUIT 0 foo=bar"
  1995. circ = circuit_launch_by_router(intended_purpose, NULL,
  1996. CIRCLAUNCH_NEED_CAPACITY);
  1997. if (!circ) {
  1998. connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn);
  1999. } else {
  2000. connection_printf_to_buf(conn, "250 EXTENDED %lu\r\n",
  2001. (unsigned long)circ->global_identifier);
  2002. }
  2003. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2004. smartlist_free(args);
  2005. goto done;
  2006. }
  2007. // "EXTENDCIRCUIT 0 router1,router2" ||
  2008. // "EXTENDCIRCUIT 0 router1,router2 PURPOSE=foo"
  2009. }
  2010. if (!zero_circ && !(circ = get_circ(smartlist_get(args,0)))) {
  2011. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  2012. (char*)smartlist_get(args, 0));
  2013. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2014. smartlist_free(args);
  2015. goto done;
  2016. }
  2017. smartlist_split_string(router_nicknames, smartlist_get(args,1), ",", 0, 0);
  2018. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2019. smartlist_free(args);
  2020. routers = smartlist_create();
  2021. SMARTLIST_FOREACH(router_nicknames, const char *, n,
  2022. {
  2023. routerinfo_t *r = router_get_by_nickname(n, 1);
  2024. if (!r) {
  2025. connection_printf_to_buf(conn, "552 No such router \"%s\"\r\n", n);
  2026. goto done;
  2027. }
  2028. smartlist_add(routers, r);
  2029. });
  2030. if (!smartlist_len(routers)) {
  2031. connection_write_str_to_buf("512 No router names provided\r\n", conn);
  2032. goto done;
  2033. }
  2034. if (zero_circ) {
  2035. /* start a new circuit */
  2036. circ = origin_circuit_init(intended_purpose, 0);
  2037. }
  2038. /* now circ refers to something that is ready to be extended */
  2039. SMARTLIST_FOREACH(routers, routerinfo_t *, r,
  2040. {
  2041. extend_info_t *info = extend_info_from_router(r);
  2042. circuit_append_new_exit(circ, info);
  2043. extend_info_free(info);
  2044. });
  2045. /* now that we've populated the cpath, start extending */
  2046. if (zero_circ) {
  2047. int err_reason = 0;
  2048. if ((err_reason = circuit_handle_first_hop(circ)) < 0) {
  2049. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  2050. connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn);
  2051. goto done;
  2052. }
  2053. } else {
  2054. if (circ->_base.state == CIRCUIT_STATE_OPEN) {
  2055. int err_reason = 0;
  2056. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
  2057. if ((err_reason = circuit_send_next_onion_skin(circ)) < 0) {
  2058. log_info(LD_CONTROL,
  2059. "send_next_onion_skin failed; circuit marked for closing.");
  2060. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  2061. connection_write_str_to_buf("551 Couldn't send onion skin\r\n", conn);
  2062. goto done;
  2063. }
  2064. }
  2065. }
  2066. connection_printf_to_buf(conn, "250 EXTENDED %lu\r\n",
  2067. (unsigned long)circ->global_identifier);
  2068. if (zero_circ) /* send a 'launched' event, for completeness */
  2069. control_event_circuit_status(circ, CIRC_EVENT_LAUNCHED, 0);
  2070. done:
  2071. SMARTLIST_FOREACH(router_nicknames, char *, n, tor_free(n));
  2072. smartlist_free(router_nicknames);
  2073. smartlist_free(routers);
  2074. return 0;
  2075. }
  2076. /** Called when we get a SETCIRCUITPURPOSE message. If we can find the
  2077. * circuit and it's a valid purpose, change it. */
  2078. static int
  2079. handle_control_setcircuitpurpose(control_connection_t *conn,
  2080. uint32_t len, const char *body)
  2081. {
  2082. origin_circuit_t *circ = NULL;
  2083. uint8_t new_purpose;
  2084. smartlist_t *args;
  2085. (void) len; /* body is NUL-terminated, so it's safe to ignore the length. */
  2086. args = getargs_helper("SETCIRCUITPURPOSE", conn, body, 2, -1);
  2087. if (!args)
  2088. goto done;
  2089. if (!(circ = get_circ(smartlist_get(args,0)))) {
  2090. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  2091. (char*)smartlist_get(args, 0));
  2092. goto done;
  2093. }
  2094. {
  2095. const char *purp = find_element_starting_with(args,1,"PURPOSE=");
  2096. new_purpose = circuit_purpose_from_string(purp);
  2097. if (new_purpose == CIRCUIT_PURPOSE_UNKNOWN) {
  2098. connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n", purp);
  2099. goto done;
  2100. }
  2101. }
  2102. circ->_base.purpose = new_purpose;
  2103. connection_write_str_to_buf("250 OK\r\n", conn);
  2104. done:
  2105. if (args) {
  2106. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2107. smartlist_free(args);
  2108. }
  2109. return 0;
  2110. }
  2111. /** Called when we get an ATTACHSTREAM message. Try to attach the requested
  2112. * stream, and report success or failure. */
  2113. static int
  2114. handle_control_attachstream(control_connection_t *conn, uint32_t len,
  2115. const char *body)
  2116. {
  2117. edge_connection_t *ap_conn = NULL;
  2118. origin_circuit_t *circ = NULL;
  2119. int zero_circ;
  2120. smartlist_t *args;
  2121. crypt_path_t *cpath=NULL;
  2122. int hop=0, hop_line_ok=1;
  2123. (void) len;
  2124. args = getargs_helper("ATTACHSTREAM", conn, body, 2, -1);
  2125. if (!args)
  2126. return 0;
  2127. zero_circ = !strcmp("0", (char*)smartlist_get(args,1));
  2128. if (!(ap_conn = get_stream(smartlist_get(args, 0)))) {
  2129. connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
  2130. (char*)smartlist_get(args, 0));
  2131. } else if (!zero_circ && !(circ = get_circ(smartlist_get(args, 1)))) {
  2132. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  2133. (char*)smartlist_get(args, 1));
  2134. } else if (circ) {
  2135. const char *hopstring = find_element_starting_with(args,2,"HOP=");
  2136. if (hopstring) {
  2137. hopstring += strlen("HOP=");
  2138. hop = (int) tor_parse_ulong(hopstring, 10, 0, INT_MAX,
  2139. &hop_line_ok, NULL);
  2140. if (!hop_line_ok) { /* broken hop line */
  2141. connection_printf_to_buf(conn, "552 Bad value hop=%s\r\n", hopstring);
  2142. }
  2143. }
  2144. }
  2145. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2146. smartlist_free(args);
  2147. if (!ap_conn || (!zero_circ && !circ) || !hop_line_ok)
  2148. return 0;
  2149. if (ap_conn->_base.state != AP_CONN_STATE_CONTROLLER_WAIT &&
  2150. ap_conn->_base.state != AP_CONN_STATE_CONNECT_WAIT &&
  2151. ap_conn->_base.state != AP_CONN_STATE_RESOLVE_WAIT) {
  2152. connection_write_str_to_buf(
  2153. "555 Connection is not managed by controller.\r\n",
  2154. conn);
  2155. return 0;
  2156. }
  2157. /* Do we need to detach it first? */
  2158. if (ap_conn->_base.state != AP_CONN_STATE_CONTROLLER_WAIT) {
  2159. circuit_t *tmpcirc = circuit_get_by_edge_conn(ap_conn);
  2160. connection_edge_end(ap_conn, END_STREAM_REASON_TIMEOUT);
  2161. /* Un-mark it as ending, since we're going to reuse it. */
  2162. ap_conn->edge_has_sent_end = 0;
  2163. ap_conn->end_reason = 0;
  2164. if (tmpcirc)
  2165. circuit_detach_stream(tmpcirc,ap_conn);
  2166. ap_conn->_base.state = AP_CONN_STATE_CONTROLLER_WAIT;
  2167. }
  2168. if (circ && (circ->_base.state != CIRCUIT_STATE_OPEN)) {
  2169. connection_write_str_to_buf(
  2170. "551 Can't attach stream to non-open origin circuit\r\n",
  2171. conn);
  2172. return 0;
  2173. }
  2174. /* Is this a single hop circuit? */
  2175. if (circ && (circuit_get_cpath_len(circ)<2 || hop==1)) {
  2176. routerinfo_t *r = NULL;
  2177. char* exit_digest;
  2178. if (circ->build_state &&
  2179. circ->build_state->chosen_exit &&
  2180. !tor_digest_is_zero(circ->build_state->chosen_exit->identity_digest)) {
  2181. exit_digest = circ->build_state->chosen_exit->identity_digest;
  2182. r = router_get_by_digest(exit_digest);
  2183. }
  2184. /* Do both the client and relay allow one-hop exit circuits? */
  2185. if (!r || !r->allow_single_hop_exits ||
  2186. !get_options()->AllowSingleHopCircuits) {
  2187. connection_write_str_to_buf(
  2188. "551 Can't attach stream to this one-hop circuit.\r\n", conn);
  2189. return 0;
  2190. }
  2191. ap_conn->chosen_exit_name = tor_strdup(hex_str(exit_digest, DIGEST_LEN));
  2192. }
  2193. if (circ && hop>0) {
  2194. /* find this hop in the circuit, and set cpath */
  2195. cpath = circuit_get_cpath_hop(circ, hop);
  2196. if (!cpath) {
  2197. connection_printf_to_buf(conn,
  2198. "551 Circuit doesn't have %d hops.\r\n", hop);
  2199. return 0;
  2200. }
  2201. }
  2202. if (connection_ap_handshake_rewrite_and_attach(ap_conn, circ, cpath) < 0) {
  2203. connection_write_str_to_buf("551 Unable to attach stream\r\n", conn);
  2204. return 0;
  2205. }
  2206. send_control_done(conn);
  2207. return 0;
  2208. }
  2209. /** Called when we get a POSTDESCRIPTOR message. Try to learn the provided
  2210. * descriptor, and report success or failure. */
  2211. static int
  2212. handle_control_postdescriptor(control_connection_t *conn, uint32_t len,
  2213. const char *body)
  2214. {
  2215. char *desc;
  2216. const char *msg=NULL;
  2217. uint8_t purpose = ROUTER_PURPOSE_GENERAL;
  2218. int cache = 0; /* eventually, we may switch this to 1 */
  2219. char *cp = memchr(body, '\n', len);
  2220. smartlist_t *args = smartlist_create();
  2221. tor_assert(cp);
  2222. *cp++ = '\0';
  2223. smartlist_split_string(args, body, " ",
  2224. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2225. SMARTLIST_FOREACH(args, char *, option,
  2226. {
  2227. if (!strcasecmpstart(option, "purpose=")) {
  2228. option += strlen("purpose=");
  2229. purpose = router_purpose_from_string(option);
  2230. if (purpose == ROUTER_PURPOSE_UNKNOWN) {
  2231. connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n",
  2232. option);
  2233. goto done;
  2234. }
  2235. } else if (!strcasecmpstart(option, "cache=")) {
  2236. option += strlen("cache=");
  2237. if (!strcasecmp(option, "no"))
  2238. cache = 0;
  2239. else if (!strcasecmp(option, "yes"))
  2240. cache = 1;
  2241. else {
  2242. connection_printf_to_buf(conn, "552 Unknown cache request \"%s\"\r\n",
  2243. option);
  2244. goto done;
  2245. }
  2246. } else { /* unrecognized argument? */
  2247. connection_printf_to_buf(conn,
  2248. "512 Unexpected argument \"%s\" to postdescriptor\r\n", option);
  2249. goto done;
  2250. }
  2251. });
  2252. read_escaped_data(cp, len-(cp-body), &desc);
  2253. switch (router_load_single_router(desc, purpose, cache, &msg)) {
  2254. case -1:
  2255. if (!msg) msg = "Could not parse descriptor";
  2256. connection_printf_to_buf(conn, "554 %s\r\n", msg);
  2257. break;
  2258. case 0:
  2259. if (!msg) msg = "Descriptor not added";
  2260. connection_printf_to_buf(conn, "251 %s\r\n",msg);
  2261. break;
  2262. case 1:
  2263. send_control_done(conn);
  2264. break;
  2265. }
  2266. tor_free(desc);
  2267. done:
  2268. SMARTLIST_FOREACH(args, char *, arg, tor_free(arg));
  2269. smartlist_free(args);
  2270. return 0;
  2271. }
  2272. /** Called when we receive a REDIRECTSTERAM command. Try to change the target
  2273. * address of the named AP stream, and report success or failure. */
  2274. static int
  2275. handle_control_redirectstream(control_connection_t *conn, uint32_t len,
  2276. const char *body)
  2277. {
  2278. edge_connection_t *ap_conn = NULL;
  2279. char *new_addr = NULL;
  2280. uint16_t new_port = 0;
  2281. smartlist_t *args;
  2282. (void) len;
  2283. args = getargs_helper("REDIRECTSTREAM", conn, body, 2, -1);
  2284. if (!args)
  2285. return 0;
  2286. if (!(ap_conn = get_stream(smartlist_get(args, 0)))
  2287. || !ap_conn->socks_request) {
  2288. connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
  2289. (char*)smartlist_get(args, 0));
  2290. } else {
  2291. int ok = 1;
  2292. if (smartlist_len(args) > 2) { /* they included a port too */
  2293. new_port = (uint16_t) tor_parse_ulong(smartlist_get(args, 2),
  2294. 10, 1, 65535, &ok, NULL);
  2295. }
  2296. if (!ok) {
  2297. connection_printf_to_buf(conn, "512 Cannot parse port \"%s\"\r\n",
  2298. (char*)smartlist_get(args, 2));
  2299. } else {
  2300. new_addr = tor_strdup(smartlist_get(args, 1));
  2301. }
  2302. }
  2303. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2304. smartlist_free(args);
  2305. if (!new_addr)
  2306. return 0;
  2307. strlcpy(ap_conn->socks_request->address, new_addr,
  2308. sizeof(ap_conn->socks_request->address));
  2309. if (new_port)
  2310. ap_conn->socks_request->port = new_port;
  2311. tor_free(new_addr);
  2312. send_control_done(conn);
  2313. return 0;
  2314. }
  2315. /** Called when we get a CLOSESTREAM command; try to close the named stream
  2316. * and report success or failure. */
  2317. static int
  2318. handle_control_closestream(control_connection_t *conn, uint32_t len,
  2319. const char *body)
  2320. {
  2321. edge_connection_t *ap_conn=NULL;
  2322. uint8_t reason=0;
  2323. smartlist_t *args;
  2324. int ok;
  2325. (void) len;
  2326. args = getargs_helper("CLOSESTREAM", conn, body, 2, -1);
  2327. if (!args)
  2328. return 0;
  2329. else if (!(ap_conn = get_stream(smartlist_get(args, 0))))
  2330. connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
  2331. (char*)smartlist_get(args, 0));
  2332. else {
  2333. reason = (uint8_t) tor_parse_ulong(smartlist_get(args,1), 10, 0, 255,
  2334. &ok, NULL);
  2335. if (!ok) {
  2336. connection_printf_to_buf(conn, "552 Unrecognized reason \"%s\"\r\n",
  2337. (char*)smartlist_get(args, 1));
  2338. ap_conn = NULL;
  2339. }
  2340. }
  2341. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2342. smartlist_free(args);
  2343. if (!ap_conn)
  2344. return 0;
  2345. connection_mark_unattached_ap(ap_conn, reason);
  2346. send_control_done(conn);
  2347. return 0;
  2348. }
  2349. /** Called when we get a CLOSECIRCUIT command; try to close the named circuit
  2350. * and report success or failure. */
  2351. static int
  2352. handle_control_closecircuit(control_connection_t *conn, uint32_t len,
  2353. const char *body)
  2354. {
  2355. origin_circuit_t *circ = NULL;
  2356. int safe = 0;
  2357. smartlist_t *args;
  2358. (void) len;
  2359. args = getargs_helper("CLOSECIRCUIT", conn, body, 1, -1);
  2360. if (!args)
  2361. return 0;
  2362. if (!(circ=get_circ(smartlist_get(args, 0))))
  2363. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  2364. (char*)smartlist_get(args, 0));
  2365. else {
  2366. int i;
  2367. for (i=1; i < smartlist_len(args); ++i) {
  2368. if (!strcasecmp(smartlist_get(args, i), "IfUnused"))
  2369. safe = 1;
  2370. else
  2371. log_info(LD_CONTROL, "Skipping unknown option %s",
  2372. (char*)smartlist_get(args,i));
  2373. }
  2374. }
  2375. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2376. smartlist_free(args);
  2377. if (!circ)
  2378. return 0;
  2379. if (!safe || !circ->p_streams) {
  2380. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_REQUESTED);
  2381. }
  2382. send_control_done(conn);
  2383. return 0;
  2384. }
  2385. /** Called when we get a RESOLVE command: start trying to resolve
  2386. * the listed addresses. */
  2387. static int
  2388. handle_control_resolve(control_connection_t *conn, uint32_t len,
  2389. const char *body)
  2390. {
  2391. smartlist_t *args, *failed;
  2392. int is_reverse = 0;
  2393. (void) len; /* body is nul-terminated; it's safe to ignore the length */
  2394. if (!(conn->event_mask & ((uint32_t)1L<<EVENT_ADDRMAP))) {
  2395. log_warn(LD_CONTROL, "Controller asked us to resolve an address, but "
  2396. "isn't listening for ADDRMAP events. It probably won't see "
  2397. "the answer.");
  2398. }
  2399. args = smartlist_create();
  2400. smartlist_split_string(args, body, " ",
  2401. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2402. {
  2403. const char *modearg = find_element_starting_with(args, 0, "mode=");
  2404. if (modearg && !strcasecmp(modearg, "mode=reverse"))
  2405. is_reverse = 1;
  2406. }
  2407. failed = smartlist_create();
  2408. SMARTLIST_FOREACH(args, const char *, arg, {
  2409. if (!is_keyval_pair(arg)) {
  2410. if (dnsserv_launch_request(arg, is_reverse)<0)
  2411. smartlist_add(failed, (char*)arg);
  2412. }
  2413. });
  2414. send_control_done(conn);
  2415. SMARTLIST_FOREACH(failed, const char *, arg, {
  2416. control_event_address_mapped(arg, arg, time(NULL),
  2417. "Unable to launch resolve request");
  2418. });
  2419. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2420. smartlist_free(args);
  2421. smartlist_free(failed);
  2422. return 0;
  2423. }
  2424. /** Called when we get a PROTOCOLINFO command: send back a reply. */
  2425. static int
  2426. handle_control_protocolinfo(control_connection_t *conn, uint32_t len,
  2427. const char *body)
  2428. {
  2429. const char *bad_arg = NULL;
  2430. smartlist_t *args;
  2431. (void)len;
  2432. conn->have_sent_protocolinfo = 1;
  2433. args = smartlist_create();
  2434. smartlist_split_string(args, body, " ",
  2435. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2436. SMARTLIST_FOREACH(args, const char *, arg, {
  2437. int ok;
  2438. tor_parse_long(arg, 10, 0, LONG_MAX, &ok, NULL);
  2439. if (!ok) {
  2440. bad_arg = arg;
  2441. break;
  2442. }
  2443. });
  2444. if (bad_arg) {
  2445. connection_printf_to_buf(conn, "513 No such version %s\r\n",
  2446. escaped(bad_arg));
  2447. /* Don't tolerate bad arguments when not authenticated. */
  2448. if (!STATE_IS_OPEN(TO_CONN(conn)->state))
  2449. connection_mark_for_close(TO_CONN(conn));
  2450. goto done;
  2451. } else {
  2452. or_options_t *options = get_options();
  2453. int cookies = options->CookieAuthentication;
  2454. char *cfile = get_cookie_file();
  2455. char *esc_cfile = esc_for_log(cfile);
  2456. char *methods;
  2457. {
  2458. int passwd = (options->HashedControlPassword != NULL ||
  2459. options->HashedControlSessionPassword != NULL);
  2460. smartlist_t *mlist = smartlist_create();
  2461. if (cookies)
  2462. smartlist_add(mlist, (char*)"COOKIE");
  2463. if (passwd)
  2464. smartlist_add(mlist, (char*)"HASHEDPASSWORD");
  2465. if (!cookies && !passwd)
  2466. smartlist_add(mlist, (char*)"NULL");
  2467. methods = smartlist_join_strings(mlist, ",", 0, NULL);
  2468. smartlist_free(mlist);
  2469. }
  2470. connection_printf_to_buf(conn,
  2471. "250-PROTOCOLINFO 1\r\n"
  2472. "250-AUTH METHODS=%s%s%s\r\n"
  2473. "250-VERSION Tor=%s\r\n"
  2474. "250 OK\r\n",
  2475. methods,
  2476. cookies?" COOKIEFILE=":"",
  2477. cookies?esc_cfile:"",
  2478. escaped(VERSION));
  2479. tor_free(methods);
  2480. tor_free(cfile);
  2481. tor_free(esc_cfile);
  2482. }
  2483. done:
  2484. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2485. smartlist_free(args);
  2486. return 0;
  2487. }
  2488. /** Called when we get a USEFEATURE command: parse the feature list, and
  2489. * set up the control_connection's options properly. */
  2490. static int
  2491. handle_control_usefeature(control_connection_t *conn,
  2492. uint32_t len,
  2493. const char *body)
  2494. {
  2495. smartlist_t *args;
  2496. int bad = 0;
  2497. (void) len; /* body is nul-terminated; it's safe to ignore the length */
  2498. args = smartlist_create();
  2499. smartlist_split_string(args, body, " ",
  2500. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2501. SMARTLIST_FOREACH(args, const char *, arg, {
  2502. if (!strcasecmp(arg, "VERBOSE_NAMES"))
  2503. ;
  2504. else if (!strcasecmp(arg, "EXTENDED_EVENTS"))
  2505. ;
  2506. else {
  2507. connection_printf_to_buf(conn, "552 Unrecognized feature \"%s\"\r\n",
  2508. arg);
  2509. bad = 1;
  2510. break;
  2511. }
  2512. });
  2513. if (!bad) {
  2514. send_control_done(conn);
  2515. }
  2516. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2517. smartlist_free(args);
  2518. return 0;
  2519. }
  2520. /** Called when <b>conn</b> has no more bytes left on its outbuf. */
  2521. int
  2522. connection_control_finished_flushing(control_connection_t *conn)
  2523. {
  2524. tor_assert(conn);
  2525. connection_stop_writing(TO_CONN(conn));
  2526. return 0;
  2527. }
  2528. /** Called when <b>conn</b> has gotten its socket closed. */
  2529. int
  2530. connection_control_reached_eof(control_connection_t *conn)
  2531. {
  2532. tor_assert(conn);
  2533. log_info(LD_CONTROL,"Control connection reached EOF. Closing.");
  2534. connection_mark_for_close(TO_CONN(conn));
  2535. return 0;
  2536. }
  2537. /** Return true iff <b>cmd</b> is allowable (or at least forgivable) at this
  2538. * stage of the protocol. */
  2539. static int
  2540. is_valid_initial_command(control_connection_t *conn, const char *cmd)
  2541. {
  2542. if (conn->_base.state == CONTROL_CONN_STATE_OPEN)
  2543. return 1;
  2544. if (!strcasecmp(cmd, "PROTOCOLINFO"))
  2545. return !conn->have_sent_protocolinfo;
  2546. if (!strcasecmp(cmd, "AUTHENTICATE") ||
  2547. !strcasecmp(cmd, "QUIT"))
  2548. return 1;
  2549. return 0;
  2550. }
  2551. /** Do not accept any control command of more than 1MB in length. Anything
  2552. * that needs to be anywhere near this long probably means that one of our
  2553. * interfaces is broken. */
  2554. #define MAX_COMMAND_LINE_LENGTH (1024*1024)
  2555. /** Called when data has arrived on a v1 control connection: Try to fetch
  2556. * commands from conn->inbuf, and execute them.
  2557. */
  2558. int
  2559. connection_control_process_inbuf(control_connection_t *conn)
  2560. {
  2561. size_t data_len;
  2562. uint32_t cmd_data_len;
  2563. int cmd_len;
  2564. char *args;
  2565. tor_assert(conn);
  2566. tor_assert(conn->_base.state == CONTROL_CONN_STATE_OPEN ||
  2567. conn->_base.state == CONTROL_CONN_STATE_NEEDAUTH);
  2568. if (!conn->incoming_cmd) {
  2569. conn->incoming_cmd = tor_malloc(1024);
  2570. conn->incoming_cmd_len = 1024;
  2571. conn->incoming_cmd_cur_len = 0;
  2572. }
  2573. if (conn->_base.state == CONTROL_CONN_STATE_NEEDAUTH &&
  2574. peek_buf_has_control0_command(conn->_base.inbuf)) {
  2575. /* Detect v0 commands and send a "no more v0" message. */
  2576. size_t body_len;
  2577. char buf[128];
  2578. set_uint16(buf+2, htons(0x0000)); /* type == error */
  2579. set_uint16(buf+4, htons(0x0001)); /* code == internal error */
  2580. strlcpy(buf+6, "The v0 control protocol is not supported by Tor 0.1.2.17 "
  2581. "and later; upgrade your controller.",
  2582. sizeof(buf)-6);
  2583. body_len = 2+strlen(buf+6)+2; /* code, msg, nul. */
  2584. set_uint16(buf+0, htons(body_len));
  2585. connection_write_to_buf(buf, 4+body_len, TO_CONN(conn));
  2586. connection_mark_for_close(TO_CONN(conn));
  2587. conn->_base.hold_open_until_flushed = 1;
  2588. return 0;
  2589. }
  2590. again:
  2591. while (1) {
  2592. size_t last_idx;
  2593. int r;
  2594. /* First, fetch a line. */
  2595. do {
  2596. data_len = conn->incoming_cmd_len - conn->incoming_cmd_cur_len;
  2597. r = fetch_from_buf_line(conn->_base.inbuf,
  2598. conn->incoming_cmd+conn->incoming_cmd_cur_len,
  2599. &data_len);
  2600. if (r == 0)
  2601. /* Line not all here yet. Wait. */
  2602. return 0;
  2603. else if (r == -1) {
  2604. if (data_len + conn->incoming_cmd_cur_len > MAX_COMMAND_LINE_LENGTH) {
  2605. connection_write_str_to_buf("500 Line too long.\r\n", conn);
  2606. connection_stop_reading(TO_CONN(conn));
  2607. connection_mark_for_close(TO_CONN(conn));
  2608. conn->_base.hold_open_until_flushed = 1;
  2609. }
  2610. while (conn->incoming_cmd_len < data_len+conn->incoming_cmd_cur_len)
  2611. conn->incoming_cmd_len *= 2;
  2612. conn->incoming_cmd = tor_realloc(conn->incoming_cmd,
  2613. conn->incoming_cmd_len);
  2614. }
  2615. } while (r != 1);
  2616. tor_assert(data_len);
  2617. last_idx = conn->incoming_cmd_cur_len;
  2618. conn->incoming_cmd_cur_len += (int)data_len;
  2619. /* We have appended a line to incoming_cmd. Is the command done? */
  2620. if (last_idx == 0 && *conn->incoming_cmd != '+')
  2621. /* One line command, didn't start with '+'. */
  2622. break;
  2623. /* XXXX this code duplication is kind of dumb. */
  2624. if (last_idx+3 == conn->incoming_cmd_cur_len &&
  2625. !memcmp(conn->incoming_cmd + last_idx, ".\r\n", 3)) {
  2626. /* Just appended ".\r\n"; we're done. Remove it. */
  2627. conn->incoming_cmd[last_idx] = '\0';
  2628. conn->incoming_cmd_cur_len -= 3;
  2629. break;
  2630. } else if (last_idx+2 == conn->incoming_cmd_cur_len &&
  2631. !memcmp(conn->incoming_cmd + last_idx, ".\n", 2)) {
  2632. /* Just appended ".\n"; we're done. Remove it. */
  2633. conn->incoming_cmd[last_idx] = '\0';
  2634. conn->incoming_cmd_cur_len -= 2;
  2635. break;
  2636. }
  2637. /* Otherwise, read another line. */
  2638. }
  2639. data_len = conn->incoming_cmd_cur_len;
  2640. /* Okay, we now have a command sitting on conn->incoming_cmd. See if we
  2641. * recognize it.
  2642. */
  2643. cmd_len = 0;
  2644. while ((size_t)cmd_len < data_len
  2645. && !TOR_ISSPACE(conn->incoming_cmd[cmd_len]))
  2646. ++cmd_len;
  2647. data_len -= cmd_len;
  2648. conn->incoming_cmd[cmd_len]='\0';
  2649. args = conn->incoming_cmd+cmd_len+1;
  2650. while (*args == ' ' || *args == '\t') {
  2651. ++args;
  2652. --data_len;
  2653. }
  2654. /* If the connection is already closing, ignore further commands */
  2655. if (TO_CONN(conn)->marked_for_close) {
  2656. return 0;
  2657. }
  2658. /* Otherwise, Quit is always valid. */
  2659. if (!strcasecmp(conn->incoming_cmd, "QUIT")) {
  2660. connection_write_str_to_buf("250 closing connection\r\n", conn);
  2661. connection_mark_for_close(TO_CONN(conn));
  2662. conn->_base.hold_open_until_flushed = 1;
  2663. return 0;
  2664. }
  2665. if (conn->_base.state == CONTROL_CONN_STATE_NEEDAUTH &&
  2666. !is_valid_initial_command(conn, conn->incoming_cmd)) {
  2667. connection_write_str_to_buf("514 Authentication required.\r\n", conn);
  2668. connection_mark_for_close(TO_CONN(conn));
  2669. return 0;
  2670. }
  2671. if (data_len >= UINT32_MAX) {
  2672. connection_write_str_to_buf("500 A 4GB command? Nice try.\r\n", conn);
  2673. connection_mark_for_close(TO_CONN(conn));
  2674. return 0;
  2675. }
  2676. cmd_data_len = (uint32_t)data_len;
  2677. if (!strcasecmp(conn->incoming_cmd, "SETCONF")) {
  2678. if (handle_control_setconf(conn, cmd_data_len, args))
  2679. return -1;
  2680. } else if (!strcasecmp(conn->incoming_cmd, "RESETCONF")) {
  2681. if (handle_control_resetconf(conn, cmd_data_len, args))
  2682. return -1;
  2683. } else if (!strcasecmp(conn->incoming_cmd, "GETCONF")) {
  2684. if (handle_control_getconf(conn, cmd_data_len, args))
  2685. return -1;
  2686. } else if (!strcasecmp(conn->incoming_cmd, "+LOADCONF")) {
  2687. if (handle_control_loadconf(conn, cmd_data_len, args))
  2688. return -1;
  2689. } else if (!strcasecmp(conn->incoming_cmd, "SETEVENTS")) {
  2690. if (handle_control_setevents(conn, cmd_data_len, args))
  2691. return -1;
  2692. } else if (!strcasecmp(conn->incoming_cmd, "AUTHENTICATE")) {
  2693. if (handle_control_authenticate(conn, cmd_data_len, args))
  2694. return -1;
  2695. } else if (!strcasecmp(conn->incoming_cmd, "SAVECONF")) {
  2696. if (handle_control_saveconf(conn, cmd_data_len, args))
  2697. return -1;
  2698. } else if (!strcasecmp(conn->incoming_cmd, "SIGNAL")) {
  2699. if (handle_control_signal(conn, cmd_data_len, args))
  2700. return -1;
  2701. } else if (!strcasecmp(conn->incoming_cmd, "MAPADDRESS")) {
  2702. if (handle_control_mapaddress(conn, cmd_data_len, args))
  2703. return -1;
  2704. } else if (!strcasecmp(conn->incoming_cmd, "GETINFO")) {
  2705. if (handle_control_getinfo(conn, cmd_data_len, args))
  2706. return -1;
  2707. } else if (!strcasecmp(conn->incoming_cmd, "EXTENDCIRCUIT")) {
  2708. if (handle_control_extendcircuit(conn, cmd_data_len, args))
  2709. return -1;
  2710. } else if (!strcasecmp(conn->incoming_cmd, "SETCIRCUITPURPOSE")) {
  2711. if (handle_control_setcircuitpurpose(conn, cmd_data_len, args))
  2712. return -1;
  2713. } else if (!strcasecmp(conn->incoming_cmd, "SETROUTERPURPOSE")) {
  2714. connection_write_str_to_buf("511 SETROUTERPURPOSE is obsolete.\r\n", conn);
  2715. } else if (!strcasecmp(conn->incoming_cmd, "ATTACHSTREAM")) {
  2716. if (handle_control_attachstream(conn, cmd_data_len, args))
  2717. return -1;
  2718. } else if (!strcasecmp(conn->incoming_cmd, "+POSTDESCRIPTOR")) {
  2719. if (handle_control_postdescriptor(conn, cmd_data_len, args))
  2720. return -1;
  2721. } else if (!strcasecmp(conn->incoming_cmd, "REDIRECTSTREAM")) {
  2722. if (handle_control_redirectstream(conn, cmd_data_len, args))
  2723. return -1;
  2724. } else if (!strcasecmp(conn->incoming_cmd, "CLOSESTREAM")) {
  2725. if (handle_control_closestream(conn, cmd_data_len, args))
  2726. return -1;
  2727. } else if (!strcasecmp(conn->incoming_cmd, "CLOSECIRCUIT")) {
  2728. if (handle_control_closecircuit(conn, cmd_data_len, args))
  2729. return -1;
  2730. } else if (!strcasecmp(conn->incoming_cmd, "USEFEATURE")) {
  2731. if (handle_control_usefeature(conn, cmd_data_len, args))
  2732. return -1;
  2733. } else if (!strcasecmp(conn->incoming_cmd, "RESOLVE")) {
  2734. if (handle_control_resolve(conn, cmd_data_len, args))
  2735. return -1;
  2736. } else if (!strcasecmp(conn->incoming_cmd, "PROTOCOLINFO")) {
  2737. if (handle_control_protocolinfo(conn, cmd_data_len, args))
  2738. return -1;
  2739. } else {
  2740. connection_printf_to_buf(conn, "510 Unrecognized command \"%s\"\r\n",
  2741. conn->incoming_cmd);
  2742. }
  2743. conn->incoming_cmd_cur_len = 0;
  2744. goto again;
  2745. }
  2746. /** Something has happened to circuit <b>circ</b>: tell any interested
  2747. * control connections. */
  2748. int
  2749. control_event_circuit_status(origin_circuit_t *circ, circuit_status_event_t tp,
  2750. int reason_code)
  2751. {
  2752. const char *status;
  2753. char extended_buf[96];
  2754. int providing_reason=0;
  2755. if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS))
  2756. return 0;
  2757. tor_assert(circ);
  2758. switch (tp)
  2759. {
  2760. case CIRC_EVENT_LAUNCHED: status = "LAUNCHED"; break;
  2761. case CIRC_EVENT_BUILT: status = "BUILT"; break;
  2762. case CIRC_EVENT_EXTENDED: status = "EXTENDED"; break;
  2763. case CIRC_EVENT_FAILED: status = "FAILED"; break;
  2764. case CIRC_EVENT_CLOSED: status = "CLOSED"; break;
  2765. default:
  2766. log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
  2767. return 0;
  2768. }
  2769. tor_snprintf(extended_buf, sizeof(extended_buf), "PURPOSE=%s",
  2770. circuit_purpose_to_controller_string(circ->_base.purpose));
  2771. if (tp == CIRC_EVENT_FAILED || tp == CIRC_EVENT_CLOSED) {
  2772. const char *reason_str = circuit_end_reason_to_control_string(reason_code);
  2773. char *reason = NULL;
  2774. size_t n=strlen(extended_buf);
  2775. providing_reason=1;
  2776. if (!reason_str) {
  2777. reason = tor_malloc(16);
  2778. tor_snprintf(reason, 16, "UNKNOWN_%d", reason_code);
  2779. reason_str = reason;
  2780. }
  2781. if (reason_code > 0 && reason_code & END_CIRC_REASON_FLAG_REMOTE) {
  2782. tor_snprintf(extended_buf+n, sizeof(extended_buf)-n,
  2783. " REASON=DESTROYED REMOTE_REASON=%s", reason_str);
  2784. } else {
  2785. tor_snprintf(extended_buf+n, sizeof(extended_buf)-n,
  2786. " REASON=%s", reason_str);
  2787. }
  2788. tor_free(reason);
  2789. }
  2790. {
  2791. char *vpath = circuit_list_path_for_controller(circ);
  2792. const char *sp = strlen(vpath) ? " " : "";
  2793. send_control_event(EVENT_CIRCUIT_STATUS, ALL_FORMATS,
  2794. "650 CIRC %lu %s%s%s %s\r\n",
  2795. (unsigned long)circ->global_identifier,
  2796. status, sp, vpath, extended_buf);
  2797. tor_free(vpath);
  2798. }
  2799. return 0;
  2800. }
  2801. /** Given an AP connection <b>conn</b> and a <b>len</b>-character buffer
  2802. * <b>buf</b>, determine the address:port combination requested on
  2803. * <b>conn</b>, and write it to <b>buf</b>. Return 0 on success, -1 on
  2804. * failure. */
  2805. static int
  2806. write_stream_target_to_buf(edge_connection_t *conn, char *buf, size_t len)
  2807. {
  2808. char buf2[256];
  2809. if (conn->chosen_exit_name)
  2810. if (tor_snprintf(buf2, sizeof(buf2), ".%s.exit", conn->chosen_exit_name)<0)
  2811. return -1;
  2812. if (!conn->socks_request)
  2813. return -1;
  2814. if (tor_snprintf(buf, len, "%s%s%s:%d",
  2815. conn->socks_request->address,
  2816. conn->chosen_exit_name ? buf2 : "",
  2817. !conn->chosen_exit_name &&
  2818. connection_edge_is_rendezvous_stream(conn) ? ".onion" : "",
  2819. conn->socks_request->port)<0)
  2820. return -1;
  2821. return 0;
  2822. }
  2823. /** Something has happened to the stream associated with AP connection
  2824. * <b>conn</b>: tell any interested control connections. */
  2825. int
  2826. control_event_stream_status(edge_connection_t *conn, stream_status_event_t tp,
  2827. int reason_code)
  2828. {
  2829. char reason_buf[64];
  2830. char addrport_buf[64];
  2831. const char *status;
  2832. circuit_t *circ;
  2833. origin_circuit_t *origin_circ = NULL;
  2834. char buf[256];
  2835. const char *purpose = "";
  2836. tor_assert(conn->socks_request);
  2837. if (!EVENT_IS_INTERESTING(EVENT_STREAM_STATUS))
  2838. return 0;
  2839. if (tp == STREAM_EVENT_CLOSED &&
  2840. (reason_code & END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED))
  2841. return 0;
  2842. write_stream_target_to_buf(conn, buf, sizeof(buf));
  2843. reason_buf[0] = '\0';
  2844. switch (tp)
  2845. {
  2846. case STREAM_EVENT_SENT_CONNECT: status = "SENTCONNECT"; break;
  2847. case STREAM_EVENT_SENT_RESOLVE: status = "SENTRESOLVE"; break;
  2848. case STREAM_EVENT_SUCCEEDED: status = "SUCCEEDED"; break;
  2849. case STREAM_EVENT_FAILED: status = "FAILED"; break;
  2850. case STREAM_EVENT_CLOSED: status = "CLOSED"; break;
  2851. case STREAM_EVENT_NEW: status = "NEW"; break;
  2852. case STREAM_EVENT_NEW_RESOLVE: status = "NEWRESOLVE"; break;
  2853. case STREAM_EVENT_FAILED_RETRIABLE: status = "DETACHED"; break;
  2854. case STREAM_EVENT_REMAP: status = "REMAP"; break;
  2855. default:
  2856. log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
  2857. return 0;
  2858. }
  2859. if (reason_code && (tp == STREAM_EVENT_FAILED ||
  2860. tp == STREAM_EVENT_CLOSED ||
  2861. tp == STREAM_EVENT_FAILED_RETRIABLE)) {
  2862. const char *reason_str = stream_end_reason_to_control_string(reason_code);
  2863. char *r = NULL;
  2864. if (!reason_str) {
  2865. r = tor_malloc(16);
  2866. tor_snprintf(r, 16, " UNKNOWN_%d", reason_code);
  2867. reason_str = r;
  2868. }
  2869. if (reason_code & END_STREAM_REASON_FLAG_REMOTE)
  2870. tor_snprintf(reason_buf, sizeof(reason_buf),
  2871. " REASON=END REMOTE_REASON=%s", reason_str);
  2872. else
  2873. tor_snprintf(reason_buf, sizeof(reason_buf),
  2874. " REASON=%s", reason_str);
  2875. tor_free(r);
  2876. } else if (reason_code && tp == STREAM_EVENT_REMAP) {
  2877. switch (reason_code) {
  2878. case REMAP_STREAM_SOURCE_CACHE:
  2879. strlcpy(reason_buf, " SOURCE=CACHE", sizeof(reason_buf));
  2880. break;
  2881. case REMAP_STREAM_SOURCE_EXIT:
  2882. strlcpy(reason_buf, " SOURCE=EXIT", sizeof(reason_buf));
  2883. break;
  2884. default:
  2885. tor_snprintf(reason_buf, sizeof(reason_buf), " REASON=UNKNOWN_%d",
  2886. reason_code);
  2887. /* XXX do we want SOURCE=UNKNOWN_%d above instead? -RD */
  2888. break;
  2889. }
  2890. }
  2891. if (tp == STREAM_EVENT_NEW) {
  2892. tor_snprintf(addrport_buf,sizeof(addrport_buf), " SOURCE_ADDR=%s:%d",
  2893. TO_CONN(conn)->address, TO_CONN(conn)->port );
  2894. } else {
  2895. addrport_buf[0] = '\0';
  2896. }
  2897. if (tp == STREAM_EVENT_NEW_RESOLVE) {
  2898. purpose = " PURPOSE=DNS_REQUEST";
  2899. } else if (tp == STREAM_EVENT_NEW) {
  2900. if (conn->is_dns_request ||
  2901. (conn->socks_request &&
  2902. SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command)))
  2903. purpose = " PURPOSE=DNS_REQUEST";
  2904. else if (conn->use_begindir) {
  2905. connection_t *linked = TO_CONN(conn)->linked_conn;
  2906. int linked_dir_purpose = -1;
  2907. if (linked && linked->type == CONN_TYPE_DIR)
  2908. linked_dir_purpose = linked->purpose;
  2909. if (DIR_PURPOSE_IS_UPLOAD(linked_dir_purpose))
  2910. purpose = " PURPOSE=DIR_UPLOAD";
  2911. else
  2912. purpose = " PURPOSE=DIR_FETCH";
  2913. } else
  2914. purpose = " PURPOSE=USER";
  2915. }
  2916. circ = circuit_get_by_edge_conn(conn);
  2917. if (circ && CIRCUIT_IS_ORIGIN(circ))
  2918. origin_circ = TO_ORIGIN_CIRCUIT(circ);
  2919. send_control_event(EVENT_STREAM_STATUS, ALL_FORMATS,
  2920. "650 STREAM "U64_FORMAT" %s %lu %s%s%s%s\r\n",
  2921. U64_PRINTF_ARG(conn->_base.global_identifier), status,
  2922. origin_circ?
  2923. (unsigned long)origin_circ->global_identifier : 0ul,
  2924. buf, reason_buf, addrport_buf, purpose);
  2925. /* XXX need to specify its intended exit, etc? */
  2926. return 0;
  2927. }
  2928. /** Figure out the best name for the target router of an OR connection
  2929. * <b>conn</b>, and write it into the <b>len</b>-character buffer
  2930. * <b>name</b>. */
  2931. static void
  2932. orconn_target_get_name(char *name, size_t len, or_connection_t *conn)
  2933. {
  2934. routerinfo_t *ri = router_get_by_digest(conn->identity_digest);
  2935. if (ri) {
  2936. tor_assert(len > MAX_VERBOSE_NICKNAME_LEN);
  2937. router_get_verbose_nickname(name, ri);
  2938. } else if (! tor_digest_is_zero(conn->identity_digest)) {
  2939. name[0] = '$';
  2940. base16_encode(name+1, len-1, conn->identity_digest,
  2941. DIGEST_LEN);
  2942. } else {
  2943. tor_snprintf(name, len, "%s:%d",
  2944. conn->_base.address, conn->_base.port);
  2945. }
  2946. }
  2947. /** Called when the status of an OR connection <b>conn</b> changes: tell any
  2948. * interested control connections. <b>tp</b> is the new status for the
  2949. * connection. If <b>conn</b> has just closed or failed, then <b>reason</b>
  2950. * may be the reason why.
  2951. */
  2952. int
  2953. control_event_or_conn_status(or_connection_t *conn, or_conn_status_event_t tp,
  2954. int reason)
  2955. {
  2956. int ncircs = 0;
  2957. const char *status;
  2958. char name[128];
  2959. char ncircs_buf[32] = {0}; /* > 8 + log10(2^32)=10 + 2 */
  2960. if (!EVENT_IS_INTERESTING(EVENT_OR_CONN_STATUS))
  2961. return 0;
  2962. switch (tp)
  2963. {
  2964. case OR_CONN_EVENT_LAUNCHED: status = "LAUNCHED"; break;
  2965. case OR_CONN_EVENT_CONNECTED: status = "CONNECTED"; break;
  2966. case OR_CONN_EVENT_FAILED: status = "FAILED"; break;
  2967. case OR_CONN_EVENT_CLOSED: status = "CLOSED"; break;
  2968. case OR_CONN_EVENT_NEW: status = "NEW"; break;
  2969. default:
  2970. log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
  2971. return 0;
  2972. }
  2973. ncircs = circuit_count_pending_on_or_conn(conn);
  2974. ncircs += conn->n_circuits;
  2975. if (ncircs && (tp == OR_CONN_EVENT_FAILED || tp == OR_CONN_EVENT_CLOSED)) {
  2976. tor_snprintf(ncircs_buf, sizeof(ncircs_buf), "%sNCIRCS=%d",
  2977. reason ? " " : "", ncircs);
  2978. }
  2979. orconn_target_get_name(name, sizeof(name), conn);
  2980. send_control_event(EVENT_OR_CONN_STATUS, ALL_FORMATS,
  2981. "650 ORCONN %s %s %s%s%s\r\n",
  2982. name, status,
  2983. reason ? "REASON=" : "",
  2984. orconn_end_reason_to_control_string(reason),
  2985. ncircs_buf);
  2986. return 0;
  2987. }
  2988. /**
  2989. * Print out STREAM_BW event for a single conn
  2990. */
  2991. int
  2992. control_event_stream_bandwidth(edge_connection_t *edge_conn)
  2993. {
  2994. if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED)) {
  2995. if (!edge_conn->n_read && !edge_conn->n_written)
  2996. return 0;
  2997. send_control_event(EVENT_STREAM_BANDWIDTH_USED, ALL_FORMATS,
  2998. "650 STREAM_BW "U64_FORMAT" %lu %lu\r\n",
  2999. U64_PRINTF_ARG(edge_conn->_base.global_identifier),
  3000. (unsigned long)edge_conn->n_read,
  3001. (unsigned long)edge_conn->n_written);
  3002. edge_conn->n_written = edge_conn->n_read = 0;
  3003. }
  3004. return 0;
  3005. }
  3006. /** A second or more has elapsed: tell any interested control
  3007. * connections how much bandwidth streams have used. */
  3008. int
  3009. control_event_stream_bandwidth_used(void)
  3010. {
  3011. if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED)) {
  3012. smartlist_t *conns = get_connection_array();
  3013. edge_connection_t *edge_conn;
  3014. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn)
  3015. {
  3016. if (conn->type != CONN_TYPE_AP)
  3017. continue;
  3018. edge_conn = TO_EDGE_CONN(conn);
  3019. if (!edge_conn->n_read && !edge_conn->n_written)
  3020. continue;
  3021. send_control_event(EVENT_STREAM_BANDWIDTH_USED, ALL_FORMATS,
  3022. "650 STREAM_BW "U64_FORMAT" %lu %lu\r\n",
  3023. U64_PRINTF_ARG(edge_conn->_base.global_identifier),
  3024. (unsigned long)edge_conn->n_read,
  3025. (unsigned long)edge_conn->n_written);
  3026. edge_conn->n_written = edge_conn->n_read = 0;
  3027. }
  3028. SMARTLIST_FOREACH_END(conn);
  3029. }
  3030. return 0;
  3031. }
  3032. /** A second or more has elapsed: tell any interested control
  3033. * connections how much bandwidth we used. */
  3034. int
  3035. control_event_bandwidth_used(uint32_t n_read, uint32_t n_written)
  3036. {
  3037. if (EVENT_IS_INTERESTING(EVENT_BANDWIDTH_USED)) {
  3038. send_control_event(EVENT_BANDWIDTH_USED, ALL_FORMATS,
  3039. "650 BW %lu %lu\r\n",
  3040. (unsigned long)n_read,
  3041. (unsigned long)n_written);
  3042. }
  3043. return 0;
  3044. }
  3045. /** Called when we are sending a log message to the controllers: suspend
  3046. * sending further log messages to the controllers until we're done. Used by
  3047. * CONN_LOG_PROTECT. */
  3048. void
  3049. disable_control_logging(void)
  3050. {
  3051. ++disable_log_messages;
  3052. }
  3053. /** We're done sending a log message to the controllers: re-enable controller
  3054. * logging. Used by CONN_LOG_PROTECT. */
  3055. void
  3056. enable_control_logging(void)
  3057. {
  3058. if (--disable_log_messages < 0)
  3059. tor_assert(0);
  3060. }
  3061. /** We got a log message: tell any interested control connections. */
  3062. void
  3063. control_event_logmsg(int severity, uint32_t domain, const char *msg)
  3064. {
  3065. int event;
  3066. /* Don't even think of trying to add stuff to a buffer from a cpuworker
  3067. * thread. */
  3068. if (! in_main_thread())
  3069. return;
  3070. if (disable_log_messages)
  3071. return;
  3072. if (domain == LD_BUG && EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL) &&
  3073. severity <= LOG_NOTICE) {
  3074. char *esc = esc_for_log(msg);
  3075. ++disable_log_messages;
  3076. control_event_general_status(severity, "BUG REASON=\"%s\"", esc);
  3077. --disable_log_messages;
  3078. tor_free(esc);
  3079. }
  3080. event = log_severity_to_event(severity);
  3081. if (event >= 0 && EVENT_IS_INTERESTING(event)) {
  3082. char *b = NULL;
  3083. const char *s;
  3084. if (strchr(msg, '\n')) {
  3085. char *cp;
  3086. b = tor_strdup(msg);
  3087. for (cp = b; *cp; ++cp)
  3088. if (*cp == '\r' || *cp == '\n')
  3089. *cp = ' ';
  3090. }
  3091. switch (severity) {
  3092. case LOG_DEBUG: s = "DEBUG"; break;
  3093. case LOG_INFO: s = "INFO"; break;
  3094. case LOG_NOTICE: s = "NOTICE"; break;
  3095. case LOG_WARN: s = "WARN"; break;
  3096. case LOG_ERR: s = "ERR"; break;
  3097. default: s = "UnknownLogSeverity"; break;
  3098. }
  3099. ++disable_log_messages;
  3100. send_control_event(event, ALL_FORMATS, "650 %s %s\r\n", s, b?b:msg);
  3101. --disable_log_messages;
  3102. tor_free(b);
  3103. }
  3104. }
  3105. /** Called whenever we receive new router descriptors: tell any
  3106. * interested control connections. <b>routers</b> is a list of
  3107. * routerinfo_t's.
  3108. */
  3109. int
  3110. control_event_descriptors_changed(smartlist_t *routers)
  3111. {
  3112. char *msg;
  3113. if (!EVENT_IS_INTERESTING(EVENT_NEW_DESC))
  3114. return 0;
  3115. {
  3116. smartlist_t *names = smartlist_create();
  3117. char *ids;
  3118. size_t names_len;
  3119. SMARTLIST_FOREACH(routers, routerinfo_t *, ri, {
  3120. char *b = tor_malloc(MAX_VERBOSE_NICKNAME_LEN+1);
  3121. router_get_verbose_nickname(b, ri);
  3122. smartlist_add(names, b);
  3123. });
  3124. ids = smartlist_join_strings(names, " ", 0, &names_len);
  3125. names_len = strlen(ids)+32;
  3126. msg = tor_malloc(names_len);
  3127. tor_snprintf(msg, names_len, "650 NEWDESC %s\r\n", ids);
  3128. send_control_event_string(EVENT_NEW_DESC, ALL_FORMATS, msg);
  3129. tor_free(ids);
  3130. tor_free(msg);
  3131. SMARTLIST_FOREACH(names, char *, cp, tor_free(cp));
  3132. smartlist_free(names);
  3133. }
  3134. return 0;
  3135. }
  3136. /** Called when an address mapping on <b>from</b> from changes to <b>to</b>.
  3137. * <b>expires</b> values less than 3 are special; see connection_edge.c. If
  3138. * <b>error</b> is non-NULL, it is an error code describing the failure
  3139. * mode of the mapping.
  3140. */
  3141. int
  3142. control_event_address_mapped(const char *from, const char *to, time_t expires,
  3143. const char *error)
  3144. {
  3145. if (!EVENT_IS_INTERESTING(EVENT_ADDRMAP))
  3146. return 0;
  3147. if (expires < 3 || expires == TIME_MAX)
  3148. send_control_event(EVENT_ADDRMAP, ALL_FORMATS,
  3149. "650 ADDRMAP %s %s NEVER %s\r\n", from, to,
  3150. error?error:"");
  3151. else {
  3152. char buf[ISO_TIME_LEN+1];
  3153. char buf2[ISO_TIME_LEN+1];
  3154. format_local_iso_time(buf,expires);
  3155. format_iso_time(buf2,expires);
  3156. send_control_event(EVENT_ADDRMAP, ALL_FORMATS,
  3157. "650 ADDRMAP %s %s \"%s\""
  3158. " %s%sEXPIRES=\"%s\"\r\n",
  3159. from, to, buf,
  3160. error?error:"", error?" ":"",
  3161. buf2);
  3162. }
  3163. return 0;
  3164. }
  3165. /** The authoritative dirserver has received a new descriptor that
  3166. * has passed basic syntax checks and is properly self-signed.
  3167. *
  3168. * Notify any interested party of the new descriptor and what has
  3169. * been done with it, and also optionally give an explanation/reason. */
  3170. int
  3171. control_event_or_authdir_new_descriptor(const char *action,
  3172. const char *desc, size_t desclen,
  3173. const char *msg)
  3174. {
  3175. char firstline[1024];
  3176. char *buf;
  3177. size_t totallen;
  3178. char *esc = NULL;
  3179. size_t esclen;
  3180. if (!EVENT_IS_INTERESTING(EVENT_AUTHDIR_NEWDESCS))
  3181. return 0;
  3182. tor_snprintf(firstline, sizeof(firstline),
  3183. "650+AUTHDIR_NEWDESC=\r\n%s\r\n%s\r\n",
  3184. action,
  3185. msg ? msg : "");
  3186. /* Escape the server descriptor properly */
  3187. esclen = write_escaped_data(desc, desclen, &esc);
  3188. totallen = strlen(firstline) + esclen + 1;
  3189. buf = tor_malloc(totallen);
  3190. strlcpy(buf, firstline, totallen);
  3191. strlcpy(buf+strlen(firstline), esc, totallen);
  3192. send_control_event_string(EVENT_AUTHDIR_NEWDESCS, ALL_FORMATS,
  3193. buf);
  3194. send_control_event_string(EVENT_AUTHDIR_NEWDESCS, ALL_FORMATS,
  3195. "650 OK\r\n");
  3196. tor_free(esc);
  3197. tor_free(buf);
  3198. return 0;
  3199. }
  3200. /** Helper function for NS-style events. Constructs and sends an event
  3201. * of type <b>event</b> with string <b>event_string</b> out of the set of
  3202. * networkstatuses <b>statuses</b>. Currently it is used for NS events
  3203. * and NEWCONSENSUS events. */
  3204. static int
  3205. control_event_networkstatus_changed_helper(smartlist_t *statuses,
  3206. uint16_t event,
  3207. const char *event_string)
  3208. {
  3209. smartlist_t *strs;
  3210. char *s, *esc = NULL;
  3211. if (!EVENT_IS_INTERESTING(event) || !smartlist_len(statuses))
  3212. return 0;
  3213. strs = smartlist_create();
  3214. smartlist_add(strs, tor_strdup("650+"));
  3215. smartlist_add(strs, tor_strdup(event_string));
  3216. smartlist_add(strs, tor_strdup("\r\n"));
  3217. SMARTLIST_FOREACH(statuses, routerstatus_t *, rs,
  3218. {
  3219. s = networkstatus_getinfo_helper_single(rs);
  3220. if (!s) continue;
  3221. smartlist_add(strs, s);
  3222. });
  3223. s = smartlist_join_strings(strs, "", 0, NULL);
  3224. write_escaped_data(s, strlen(s), &esc);
  3225. SMARTLIST_FOREACH(strs, char *, cp, tor_free(cp));
  3226. smartlist_free(strs);
  3227. tor_free(s);
  3228. send_control_event_string(event, ALL_FORMATS, esc);
  3229. send_control_event_string(event, ALL_FORMATS,
  3230. "650 OK\r\n");
  3231. tor_free(esc);
  3232. return 0;
  3233. }
  3234. /** Called when the routerstatus_ts <b>statuses</b> have changed: sends
  3235. * an NS event to any controller that cares. */
  3236. int
  3237. control_event_networkstatus_changed(smartlist_t *statuses)
  3238. {
  3239. return control_event_networkstatus_changed_helper(statuses, EVENT_NS, "NS");
  3240. }
  3241. /** Called when we get a new consensus networkstatus. Sends a NEWCONSENSUS
  3242. * event consisting of an NS-style line for each relay in the consensus. */
  3243. int
  3244. control_event_newconsensus(const networkstatus_t *consensus)
  3245. {
  3246. if (!control_event_is_interesting(EVENT_NEWCONSENSUS))
  3247. return 0;
  3248. return control_event_networkstatus_changed_helper(
  3249. consensus->routerstatus_list, EVENT_NEWCONSENSUS, "NEWCONSENSUS");
  3250. }
  3251. /** Called when we compute a new circuitbuildtimeout */
  3252. int
  3253. control_event_buildtimeout_set(const circuit_build_times_t *cbt,
  3254. buildtimeout_set_event_t type)
  3255. {
  3256. const char *type_string = NULL;
  3257. double qnt = circuit_build_times_quantile_cutoff();
  3258. if (!control_event_is_interesting(EVENT_BUILDTIMEOUT_SET))
  3259. return 0;
  3260. switch (type) {
  3261. case BUILDTIMEOUT_SET_EVENT_COMPUTED:
  3262. type_string = "COMPUTED";
  3263. break;
  3264. case BUILDTIMEOUT_SET_EVENT_RESET:
  3265. type_string = "RESET";
  3266. qnt = 1.0;
  3267. break;
  3268. case BUILDTIMEOUT_SET_EVENT_SUSPENDED:
  3269. type_string = "SUSPENDED";
  3270. qnt = 1.0;
  3271. break;
  3272. case BUILDTIMEOUT_SET_EVENT_DISCARD:
  3273. type_string = "DISCARD";
  3274. qnt = 1.0;
  3275. break;
  3276. case BUILDTIMEOUT_SET_EVENT_RESUME:
  3277. type_string = "RESUME";
  3278. break;
  3279. default:
  3280. type_string = "UNKNOWN";
  3281. break;
  3282. }
  3283. send_control_event(EVENT_BUILDTIMEOUT_SET, ALL_FORMATS,
  3284. "650 BUILDTIMEOUT_SET %s TOTAL_TIMES=%lu "
  3285. "TIMEOUT_MS=%lu XM=%lu ALPHA=%lf CUTOFF_QUANTILE=%lf "
  3286. "TIMEOUT_RATE=%lf CLOSE_MS=%lu CLOSE_RATE=%lf\r\n",
  3287. type_string, (unsigned long)cbt->total_build_times,
  3288. (unsigned long)cbt->timeout_ms,
  3289. (unsigned long)cbt->Xm, cbt->alpha, qnt,
  3290. circuit_build_times_timeout_rate(cbt),
  3291. (unsigned long)cbt->close_ms,
  3292. circuit_build_times_close_rate(cbt));
  3293. return 0;
  3294. }
  3295. /** Called when a single local_routerstatus_t has changed: Sends an NS event
  3296. * to any controller that cares. */
  3297. int
  3298. control_event_networkstatus_changed_single(routerstatus_t *rs)
  3299. {
  3300. smartlist_t *statuses;
  3301. int r;
  3302. if (!EVENT_IS_INTERESTING(EVENT_NS))
  3303. return 0;
  3304. statuses = smartlist_create();
  3305. smartlist_add(statuses, rs);
  3306. r = control_event_networkstatus_changed(statuses);
  3307. smartlist_free(statuses);
  3308. return r;
  3309. }
  3310. /** Our own router descriptor has changed; tell any controllers that care.
  3311. */
  3312. int
  3313. control_event_my_descriptor_changed(void)
  3314. {
  3315. send_control_event(EVENT_DESCCHANGED, ALL_FORMATS, "650 DESCCHANGED\r\n");
  3316. return 0;
  3317. }
  3318. /** Helper: sends a status event where <b>type</b> is one of
  3319. * EVENT_STATUS_{GENERAL,CLIENT,SERVER}, where <b>severity</b> is one of
  3320. * LOG_{NOTICE,WARN,ERR}, and where <b>format</b> is a printf-style format
  3321. * string corresponding to <b>args</b>. */
  3322. static int
  3323. control_event_status(int type, int severity, const char *format, va_list args)
  3324. {
  3325. char format_buf[160];
  3326. const char *status, *sev;
  3327. switch (type) {
  3328. case EVENT_STATUS_GENERAL:
  3329. status = "STATUS_GENERAL";
  3330. break;
  3331. case EVENT_STATUS_CLIENT:
  3332. status = "STATUS_CLIENT";
  3333. break;
  3334. case EVENT_STATUS_SERVER:
  3335. status = "STATUS_SERVER";
  3336. break;
  3337. default:
  3338. log_warn(LD_BUG, "Unrecognized status type %d", type);
  3339. return -1;
  3340. }
  3341. switch (severity) {
  3342. case LOG_NOTICE:
  3343. sev = "NOTICE";
  3344. break;
  3345. case LOG_WARN:
  3346. sev = "WARN";
  3347. break;
  3348. case LOG_ERR:
  3349. sev = "ERR";
  3350. break;
  3351. default:
  3352. log_warn(LD_BUG, "Unrecognized status severity %d", severity);
  3353. return -1;
  3354. }
  3355. if (tor_snprintf(format_buf, sizeof(format_buf), "650 %s %s %s\r\n",
  3356. status, sev, format)<0) {
  3357. log_warn(LD_BUG, "Format string too long.");
  3358. return -1;
  3359. }
  3360. send_control_event_impl(type, ALL_FORMATS, format_buf, args);
  3361. return 0;
  3362. }
  3363. /** Format and send an EVENT_STATUS_GENERAL event whose main text is obtained
  3364. * by formatting the arguments using the printf-style <b>format</b>. */
  3365. int
  3366. control_event_general_status(int severity, const char *format, ...)
  3367. {
  3368. va_list ap;
  3369. int r;
  3370. if (!EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL))
  3371. return 0;
  3372. va_start(ap, format);
  3373. r = control_event_status(EVENT_STATUS_GENERAL, severity, format, ap);
  3374. va_end(ap);
  3375. return r;
  3376. }
  3377. /** Format and send an EVENT_STATUS_CLIENT event whose main text is obtained
  3378. * by formatting the arguments using the printf-style <b>format</b>. */
  3379. int
  3380. control_event_client_status(int severity, const char *format, ...)
  3381. {
  3382. va_list ap;
  3383. int r;
  3384. if (!EVENT_IS_INTERESTING(EVENT_STATUS_CLIENT))
  3385. return 0;
  3386. va_start(ap, format);
  3387. r = control_event_status(EVENT_STATUS_CLIENT, severity, format, ap);
  3388. va_end(ap);
  3389. return r;
  3390. }
  3391. /** Format and send an EVENT_STATUS_SERVER event whose main text is obtained
  3392. * by formatting the arguments using the printf-style <b>format</b>. */
  3393. int
  3394. control_event_server_status(int severity, const char *format, ...)
  3395. {
  3396. va_list ap;
  3397. int r;
  3398. if (!EVENT_IS_INTERESTING(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. /** Called when the status of an entry guard with the given <b>nickname</b>
  3406. * and identity <b>digest</b> has changed to <b>status</b>: tells any
  3407. * controllers that care. */
  3408. int
  3409. control_event_guard(const char *nickname, const char *digest,
  3410. const char *status)
  3411. {
  3412. char hbuf[HEX_DIGEST_LEN+1];
  3413. base16_encode(hbuf, sizeof(hbuf), digest, DIGEST_LEN);
  3414. if (!EVENT_IS_INTERESTING(EVENT_GUARD))
  3415. return 0;
  3416. {
  3417. char buf[MAX_VERBOSE_NICKNAME_LEN+1];
  3418. routerinfo_t *ri = router_get_by_digest(digest);
  3419. if (ri) {
  3420. router_get_verbose_nickname(buf, ri);
  3421. } else {
  3422. tor_snprintf(buf, sizeof(buf), "$%s~%s", hbuf, nickname);
  3423. }
  3424. send_control_event(EVENT_GUARD, ALL_FORMATS,
  3425. "650 GUARD ENTRY %s %s\r\n", buf, status);
  3426. }
  3427. return 0;
  3428. }
  3429. /** Helper: Return a newly allocated string containing a path to the
  3430. * file where we store our authentication cookie. */
  3431. static char *
  3432. get_cookie_file(void)
  3433. {
  3434. or_options_t *options = get_options();
  3435. if (options->CookieAuthFile && strlen(options->CookieAuthFile)) {
  3436. return tor_strdup(options->CookieAuthFile);
  3437. } else {
  3438. return get_datadir_fname("control_auth_cookie");
  3439. }
  3440. }
  3441. /** Choose a random authentication cookie and write it to disk.
  3442. * Anybody who can read the cookie from disk will be considered
  3443. * authorized to use the control connection. Return -1 if we can't
  3444. * write the file, or 0 on success. */
  3445. int
  3446. init_cookie_authentication(int enabled)
  3447. {
  3448. char *fname;
  3449. if (!enabled) {
  3450. authentication_cookie_is_set = 0;
  3451. return 0;
  3452. }
  3453. /* We don't want to generate a new cookie every time we call
  3454. * options_act(). One should be enough. */
  3455. if (authentication_cookie_is_set)
  3456. return 0; /* all set */
  3457. fname = get_cookie_file();
  3458. crypto_rand(authentication_cookie, AUTHENTICATION_COOKIE_LEN);
  3459. authentication_cookie_is_set = 1;
  3460. if (write_bytes_to_file(fname, authentication_cookie,
  3461. AUTHENTICATION_COOKIE_LEN, 1)) {
  3462. log_warn(LD_FS,"Error writing authentication cookie to %s.",
  3463. escaped(fname));
  3464. tor_free(fname);
  3465. return -1;
  3466. }
  3467. #ifndef MS_WINDOWS
  3468. if (get_options()->CookieAuthFileGroupReadable) {
  3469. if (chmod(fname, 0640)) {
  3470. log_warn(LD_FS,"Unable to make %s group-readable.", escaped(fname));
  3471. }
  3472. }
  3473. #endif
  3474. tor_free(fname);
  3475. return 0;
  3476. }
  3477. /** Convert the name of a bootstrapping phase <b>s</b> into strings
  3478. * <b>tag</b> and <b>summary</b> suitable for display by the controller. */
  3479. static int
  3480. bootstrap_status_to_string(bootstrap_status_t s, const char **tag,
  3481. const char **summary)
  3482. {
  3483. switch (s) {
  3484. case BOOTSTRAP_STATUS_UNDEF:
  3485. *tag = "undef";
  3486. *summary = "Undefined";
  3487. break;
  3488. case BOOTSTRAP_STATUS_STARTING:
  3489. *tag = "starting";
  3490. *summary = "Starting";
  3491. break;
  3492. case BOOTSTRAP_STATUS_CONN_DIR:
  3493. *tag = "conn_dir";
  3494. *summary = "Connecting to directory server";
  3495. break;
  3496. case BOOTSTRAP_STATUS_HANDSHAKE:
  3497. *tag = "status_handshake";
  3498. *summary = "Finishing handshake";
  3499. break;
  3500. case BOOTSTRAP_STATUS_HANDSHAKE_DIR:
  3501. *tag = "handshake_dir";
  3502. *summary = "Finishing handshake with directory server";
  3503. break;
  3504. case BOOTSTRAP_STATUS_ONEHOP_CREATE:
  3505. *tag = "onehop_create";
  3506. *summary = "Establishing an encrypted directory connection";
  3507. break;
  3508. case BOOTSTRAP_STATUS_REQUESTING_STATUS:
  3509. *tag = "requesting_status";
  3510. *summary = "Asking for networkstatus consensus";
  3511. break;
  3512. case BOOTSTRAP_STATUS_LOADING_STATUS:
  3513. *tag = "loading_status";
  3514. *summary = "Loading networkstatus consensus";
  3515. break;
  3516. case BOOTSTRAP_STATUS_LOADING_KEYS:
  3517. *tag = "loading_keys";
  3518. *summary = "Loading authority key certs";
  3519. break;
  3520. case BOOTSTRAP_STATUS_REQUESTING_DESCRIPTORS:
  3521. *tag = "requesting_descriptors";
  3522. *summary = "Asking for relay descriptors";
  3523. break;
  3524. case BOOTSTRAP_STATUS_LOADING_DESCRIPTORS:
  3525. *tag = "loading_descriptors";
  3526. *summary = "Loading relay descriptors";
  3527. break;
  3528. case BOOTSTRAP_STATUS_CONN_OR:
  3529. *tag = "conn_or";
  3530. *summary = "Connecting to the Tor network";
  3531. break;
  3532. case BOOTSTRAP_STATUS_HANDSHAKE_OR:
  3533. *tag = "handshake_or";
  3534. *summary = "Finishing handshake with first hop";
  3535. break;
  3536. case BOOTSTRAP_STATUS_CIRCUIT_CREATE:
  3537. *tag = "circuit_create";
  3538. *summary = "Establishing a Tor circuit";
  3539. break;
  3540. case BOOTSTRAP_STATUS_DONE:
  3541. *tag = "done";
  3542. *summary = "Done";
  3543. break;
  3544. default:
  3545. // log_warn(LD_BUG, "Unrecognized bootstrap status code %d", s);
  3546. *tag = *summary = "unknown";
  3547. return -1;
  3548. }
  3549. return 0;
  3550. }
  3551. /** What percentage through the bootstrap process are we? We remember
  3552. * this so we can avoid sending redundant bootstrap status events, and
  3553. * so we can guess context for the bootstrap messages which are
  3554. * ambiguous. It starts at 'undef', but gets set to 'starting' while
  3555. * Tor initializes. */
  3556. static int bootstrap_percent = BOOTSTRAP_STATUS_UNDEF;
  3557. /** How many problems have we had getting to the next bootstrapping phase?
  3558. * These include failure to establish a connection to a Tor relay,
  3559. * failures to finish the TLS handshake, failures to validate the
  3560. * consensus document, etc. */
  3561. static int bootstrap_problems = 0;
  3562. /* We only tell the controller once we've hit a threshold of problems
  3563. * for the current phase. */
  3564. #define BOOTSTRAP_PROBLEM_THRESHOLD 10
  3565. /** Called when Tor has made progress at bootstrapping its directory
  3566. * information and initial circuits.
  3567. *
  3568. * <b>status</b> is the new status, that is, what task we will be doing
  3569. * next. <b>percent</b> is zero if we just started this task, else it
  3570. * represents progress on the task. */
  3571. void
  3572. control_event_bootstrap(bootstrap_status_t status, int progress)
  3573. {
  3574. const char *tag, *summary;
  3575. char buf[BOOTSTRAP_MSG_LEN];
  3576. if (bootstrap_percent == BOOTSTRAP_STATUS_DONE)
  3577. return; /* already bootstrapped; nothing to be done here. */
  3578. /* special case for handshaking status, since our TLS handshaking code
  3579. * can't distinguish what the connection is going to be for. */
  3580. if (status == BOOTSTRAP_STATUS_HANDSHAKE) {
  3581. if (bootstrap_percent < BOOTSTRAP_STATUS_CONN_OR) {
  3582. status = BOOTSTRAP_STATUS_HANDSHAKE_DIR;
  3583. } else {
  3584. status = BOOTSTRAP_STATUS_HANDSHAKE_OR;
  3585. }
  3586. }
  3587. if (status > bootstrap_percent ||
  3588. (progress && progress > bootstrap_percent)) {
  3589. bootstrap_status_to_string(status, &tag, &summary);
  3590. log(status ? LOG_NOTICE : LOG_INFO, LD_CONTROL,
  3591. "Bootstrapped %d%%: %s.", progress ? progress : status, summary);
  3592. tor_snprintf(buf, sizeof(buf),
  3593. "BOOTSTRAP PROGRESS=%d TAG=%s SUMMARY=\"%s\"",
  3594. progress ? progress : status, tag, summary);
  3595. tor_snprintf(last_sent_bootstrap_message,
  3596. sizeof(last_sent_bootstrap_message),
  3597. "NOTICE %s", buf);
  3598. control_event_client_status(LOG_NOTICE, "%s", buf);
  3599. if (status > bootstrap_percent) {
  3600. bootstrap_percent = status; /* new milestone reached */
  3601. }
  3602. if (progress > bootstrap_percent) {
  3603. /* incremental progress within a milestone */
  3604. bootstrap_percent = progress;
  3605. bootstrap_problems = 0; /* Progress! Reset our problem counter. */
  3606. }
  3607. }
  3608. }
  3609. /** Called when Tor has failed to make bootstrapping progress in a way
  3610. * that indicates a problem. <b>warn</b> gives a hint as to why, and
  3611. * <b>reason</b> provides an "or_conn_end_reason" tag.
  3612. */
  3613. void
  3614. control_event_bootstrap_problem(const char *warn, int reason)
  3615. {
  3616. int status = bootstrap_percent;
  3617. const char *tag, *summary;
  3618. char buf[BOOTSTRAP_MSG_LEN];
  3619. const char *recommendation = "ignore";
  3620. if (bootstrap_percent == 100)
  3621. return; /* already bootstrapped; nothing to be done here. */
  3622. bootstrap_problems++;
  3623. if (bootstrap_problems >= BOOTSTRAP_PROBLEM_THRESHOLD)
  3624. recommendation = "warn";
  3625. if (reason == END_OR_CONN_REASON_NO_ROUTE)
  3626. recommendation = "warn";
  3627. if (get_options()->UseBridges &&
  3628. !any_bridge_descriptors_known() &&
  3629. !any_pending_bridge_descriptor_fetches())
  3630. recommendation = "warn";
  3631. while (status>=0 && bootstrap_status_to_string(status, &tag, &summary) < 0)
  3632. status--; /* find a recognized status string based on current progress */
  3633. status = bootstrap_percent; /* set status back to the actual number */
  3634. log_fn(!strcmp(recommendation, "warn") ? LOG_WARN : LOG_INFO,
  3635. LD_CONTROL, "Problem bootstrapping. Stuck at %d%%: %s. (%s; %s; "
  3636. "count %d; recommendation %s)",
  3637. status, summary, warn,
  3638. orconn_end_reason_to_control_string(reason),
  3639. bootstrap_problems, recommendation);
  3640. tor_snprintf(buf, sizeof(buf),
  3641. "BOOTSTRAP PROGRESS=%d TAG=%s SUMMARY=\"%s\" WARNING=\"%s\" REASON=%s "
  3642. "COUNT=%d RECOMMENDATION=%s",
  3643. bootstrap_percent, tag, summary, warn,
  3644. orconn_end_reason_to_control_string(reason), bootstrap_problems,
  3645. recommendation);
  3646. tor_snprintf(last_sent_bootstrap_message,
  3647. sizeof(last_sent_bootstrap_message),
  3648. "WARN %s", buf);
  3649. control_event_client_status(LOG_WARN, "%s", buf);
  3650. }
  3651. /** We just generated a new summary of which countries we've seen clients
  3652. * from recently. Send a copy to the controller in case it wants to
  3653. * display it for the user. */
  3654. void
  3655. control_event_clients_seen(const char *controller_str)
  3656. {
  3657. send_control_event(EVENT_CLIENTS_SEEN, 0,
  3658. "650 CLIENTS_SEEN %s\r\n", controller_str);
  3659. }