control.c 133 KB

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