control.c 133 KB

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