control.c 147 KB

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