control.c 144 KB

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