control.c 133 KB

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