control.c 129 KB

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