control.c 134 KB

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