control.c 167 KB

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