control.c 140 KB

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