control.c 149 KB

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