control.c 137 KB

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