control.c 136 KB

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