control.c 136 KB

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