control.c 134 KB

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