control.c 133 KB

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