control.c 184 KB

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