control.c 133 KB

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