control.c 129 KB

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