control.c 133 KB

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