control.c 143 KB

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