control.c 176 KB

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