control.c 107 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221
  1. /* Copyright 2004-2007 Roger Dingledine, Nick Mathewson. */
  2. /* See LICENSE for licensing information */
  3. /* $Id$ */
  4. const char control_c_id[] =
  5. "$Id$";
  6. /**
  7. * \file control.c
  8. * \brief Implementation for Tor's control-socket interface.
  9. * See control-spec.txt for full details on protocol.
  10. **/
  11. #include "or.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_MAX 0x0014
  41. /* If _EVENT_MAX ever hits 0x0020, we need to make the mask wider. */
  42. /** Bitfield: The bit 1&lt;&lt;e is set if <b>any</b> open control
  43. * connection is interested in events of type <b>e</b>. We use this
  44. * so that we can decide to skip generating event messages that nobody
  45. * has interest in without having to walk over the global connection
  46. * list to find out.
  47. **/
  48. typedef uint32_t event_mask_t;
  49. static event_mask_t global_event_mask1long = 0;
  50. static event_mask_t global_event_mask1short = 0;
  51. /** True iff we have disabled log messages from being sent to the controller */
  52. static int disable_log_messages = 0;
  53. /** Macro: true if any control connection is interested in events of type
  54. * <b>e</b>. */
  55. #define EVENT_IS_INTERESTING(e) \
  56. ((global_event_mask1long|global_event_mask1short) & (1<<(e)))
  57. #define EVENT_IS_INTERESTING1L(e) (global_event_mask1long & (1<<(e)))
  58. #define EVENT_IS_INTERESTING1S(e) (global_event_mask1short & (1<<(e)))
  59. /** If we're using cookie-type authentication, how long should our cookies be?
  60. */
  61. #define AUTHENTICATION_COOKIE_LEN 32
  62. /** If true, we've set authentication_cookie to a secret code and
  63. * stored it to disk. */
  64. static int authentication_cookie_is_set = 0;
  65. static char authentication_cookie[AUTHENTICATION_COOKIE_LEN];
  66. #define SHORT_NAMES 1
  67. #define LONG_NAMES 2
  68. #define ALL_NAMES (SHORT_NAMES|LONG_NAMES)
  69. #define EXTENDED_FORMAT 4
  70. #define NONEXTENDED_FORMAT 8
  71. #define ALL_FORMATS (EXTENDED_FORMAT|NONEXTENDED_FORMAT)
  72. typedef int event_format_t;
  73. static void connection_printf_to_buf(control_connection_t *conn,
  74. const char *format, ...)
  75. CHECK_PRINTF(2,3);
  76. /*static*/ size_t write_escaped_data(const char *data, size_t len,
  77. int translate_newlines, char **out);
  78. /*static*/ size_t read_escaped_data(const char *data, size_t len,
  79. int translate_newlines, char **out);
  80. static void send_control_done(control_connection_t *conn);
  81. static void send_control_event(uint16_t event, event_format_t which,
  82. const char *format, ...)
  83. CHECK_PRINTF(3,4);
  84. static void send_control_event_extended(uint16_t event, event_format_t which,
  85. const char *format, ...)
  86. CHECK_PRINTF(3,4);
  87. static int handle_control_setconf(control_connection_t *conn, uint32_t len,
  88. char *body);
  89. static int handle_control_resetconf(control_connection_t *conn, uint32_t len,
  90. char *body);
  91. static int handle_control_getconf(control_connection_t *conn, uint32_t len,
  92. const char *body);
  93. static int handle_control_setevents(control_connection_t *conn, uint32_t len,
  94. const char *body);
  95. static int handle_control_authenticate(control_connection_t *conn,
  96. uint32_t len,
  97. const char *body);
  98. static int handle_control_saveconf(control_connection_t *conn, uint32_t len,
  99. const char *body);
  100. static int handle_control_signal(control_connection_t *conn, uint32_t len,
  101. const char *body);
  102. static int handle_control_mapaddress(control_connection_t *conn, uint32_t len,
  103. const char *body);
  104. static char *list_getinfo_options(void);
  105. static int handle_control_getinfo(control_connection_t *conn, uint32_t len,
  106. const char *body);
  107. static int handle_control_extendcircuit(control_connection_t *conn,
  108. uint32_t len,
  109. const char *body);
  110. static int handle_control_setpurpose(control_connection_t *conn,
  111. int for_circuits,
  112. uint32_t len, const char *body);
  113. static int handle_control_attachstream(control_connection_t *conn,
  114. uint32_t len,
  115. const char *body);
  116. static int handle_control_postdescriptor(control_connection_t *conn,
  117. uint32_t len,
  118. const char *body);
  119. static int handle_control_redirectstream(control_connection_t *conn,
  120. uint32_t len,
  121. const char *body);
  122. static int handle_control_closestream(control_connection_t *conn, uint32_t len,
  123. const char *body);
  124. static int handle_control_closecircuit(control_connection_t *conn,
  125. uint32_t len,
  126. const char *body);
  127. static int handle_control_usefeature(control_connection_t *conn,
  128. uint32_t len,
  129. const char *body);
  130. static int write_stream_target_to_buf(edge_connection_t *conn, char *buf,
  131. size_t len);
  132. static void orconn_target_get_name(int long_names, char *buf, size_t len,
  133. or_connection_t *conn);
  134. /** Given a control event code for a message event, return the corresponding
  135. * log severity. */
  136. static INLINE int
  137. event_to_log_severity(int event)
  138. {
  139. switch (event) {
  140. case EVENT_DEBUG_MSG: return LOG_DEBUG;
  141. case EVENT_INFO_MSG: return LOG_INFO;
  142. case EVENT_NOTICE_MSG: return LOG_NOTICE;
  143. case EVENT_WARN_MSG: return LOG_WARN;
  144. case EVENT_ERR_MSG: return LOG_ERR;
  145. default: return -1;
  146. }
  147. }
  148. /** Given a log severity, return the corresponding control event code. */
  149. static INLINE int
  150. log_severity_to_event(int severity)
  151. {
  152. switch (severity) {
  153. case LOG_DEBUG: return EVENT_DEBUG_MSG;
  154. case LOG_INFO: return EVENT_INFO_MSG;
  155. case LOG_NOTICE: return EVENT_NOTICE_MSG;
  156. case LOG_WARN: return EVENT_WARN_MSG;
  157. case LOG_ERR: return EVENT_ERR_MSG;
  158. default: return -1;
  159. }
  160. }
  161. /** Set <b>global_event_mask*</b> to the bitwise OR of each live control
  162. * connection's event_mask field. */
  163. void
  164. control_update_global_event_mask(void)
  165. {
  166. connection_t **conns;
  167. int n_conns, i;
  168. event_mask_t old_mask, new_mask;
  169. old_mask = global_event_mask1short;
  170. old_mask |= global_event_mask1long;
  171. global_event_mask1short = 0;
  172. global_event_mask1long = 0;
  173. get_connection_array(&conns, &n_conns);
  174. for (i = 0; i < n_conns; ++i) {
  175. if (conns[i]->type == CONN_TYPE_CONTROL &&
  176. STATE_IS_OPEN(conns[i]->state)) {
  177. control_connection_t *conn = TO_CONTROL_CONN(conns[i]);
  178. if (conn->use_long_names)
  179. global_event_mask1long |= conn->event_mask;
  180. else
  181. global_event_mask1short |= conn->event_mask;
  182. }
  183. }
  184. new_mask = global_event_mask1short;
  185. new_mask |= global_event_mask1long;
  186. /* Handle the aftermath. Set up the log callback to tell us only what
  187. * we want to hear...*/
  188. control_adjust_event_log_severity();
  189. /* ...then, if we've started logging stream bw, clear the appropriate
  190. * fields. */
  191. if (! (old_mask & EVENT_STREAM_BANDWIDTH_USED) &&
  192. (new_mask & EVENT_STREAM_BANDWIDTH_USED)) {
  193. for (i = 0; i < n_conns; ++i) {
  194. if (conns[i]->type == CONN_TYPE_AP) {
  195. edge_connection_t *conn = TO_EDGE_CONN(conns[i]);
  196. conn->n_written = conn->n_read = 0;
  197. }
  198. }
  199. }
  200. }
  201. /** Adjust the log severities that result in control_event_logmsg being called
  202. * to match the severity of log messages that any controllers are interested
  203. * in. */
  204. void
  205. control_adjust_event_log_severity(void)
  206. {
  207. int i;
  208. int min_log_event=EVENT_ERR_MSG, max_log_event=EVENT_DEBUG_MSG;
  209. for (i = EVENT_DEBUG_MSG; i <= EVENT_ERR_MSG; ++i) {
  210. if (EVENT_IS_INTERESTING(i)) {
  211. min_log_event = i;
  212. break;
  213. }
  214. }
  215. for (i = EVENT_ERR_MSG; i >= EVENT_DEBUG_MSG; --i) {
  216. if (EVENT_IS_INTERESTING(i)) {
  217. max_log_event = i;
  218. break;
  219. }
  220. }
  221. if (EVENT_IS_INTERESTING(EVENT_LOG_OBSOLETE) ||
  222. EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL)) {
  223. if (min_log_event > EVENT_NOTICE_MSG)
  224. min_log_event = EVENT_NOTICE_MSG;
  225. if (max_log_event < EVENT_ERR_MSG)
  226. max_log_event = EVENT_ERR_MSG;
  227. }
  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. }
  232. /** Append a NUL-terminated string <b>s</b> to the end of
  233. * <b>conn</b>-\>outbuf
  234. */
  235. static INLINE void
  236. connection_write_str_to_buf(const char *s, control_connection_t *conn)
  237. {
  238. size_t len = strlen(s);
  239. connection_write_to_buf(s, len, TO_CONN(conn));
  240. }
  241. /** Given a <b>len</b>-character string in <b>data</b>, made of lines
  242. * terminated by CRLF, allocate a new string in *<b>out</b>, and copy
  243. * the contents of <b>data</b> into *<b>out</b>, adding a period
  244. * before any period that that appears at the start of a line, and
  245. * adding a period-CRLF line at the end. If <b>translate_newlines</b>
  246. * is true, replace all LF characters sequences with CRLF. Return the
  247. * number of bytes in *<b>out</b>.
  248. */
  249. /* static */ size_t
  250. write_escaped_data(const char *data, size_t len, int translate_newlines,
  251. char **out)
  252. {
  253. size_t sz_out = len+8;
  254. char *outp;
  255. const char *end;
  256. int i;
  257. int start_of_line;
  258. for (i=0; i<(int)len; ++i) {
  259. if (data[i]== '\n')
  260. sz_out += 2; /* Maybe add a CR; maybe add a dot. */
  261. }
  262. *out = outp = tor_malloc(sz_out+1);
  263. end = data+len;
  264. start_of_line = 1;
  265. while (data < end) {
  266. if (*data == '\n') {
  267. if (translate_newlines)
  268. *outp++ = '\r';
  269. start_of_line = 1;
  270. } else if (*data == '.') {
  271. if (start_of_line) {
  272. start_of_line = 0;
  273. *outp++ = '.';
  274. }
  275. } else {
  276. start_of_line = 0;
  277. }
  278. *outp++ = *data++;
  279. }
  280. if (outp < *out+2 || memcmp(outp-2, "\r\n", 2)) {
  281. *outp++ = '\r';
  282. *outp++ = '\n';
  283. }
  284. *outp++ = '.';
  285. *outp++ = '\r';
  286. *outp++ = '\n';
  287. *outp = '\0'; /* NUL-terminate just in case. */
  288. tor_assert((outp - *out) <= (int)sz_out);
  289. return outp - *out;
  290. }
  291. /** Given a <b>len</b>-character string in <b>data</b>, made of lines
  292. * terminated by CRLF, allocate a new string in *<b>out</b>, and copy
  293. * the contents of <b>data</b> into *<b>out</b>, removing any period
  294. * that appears at the start of a line. If <b>translate_newlines</b>
  295. * is true, replace all CRLF sequences with LF. Return the number of
  296. * bytes in *<b>out</b>. */
  297. /*static*/ size_t
  298. read_escaped_data(const char *data, size_t len, int translate_newlines,
  299. char **out)
  300. {
  301. char *outp;
  302. const char *next;
  303. const char *end;
  304. *out = outp = tor_malloc(len+1);
  305. end = data+len;
  306. while (data < end) {
  307. if (*data == '.')
  308. ++data;
  309. if (translate_newlines)
  310. next = tor_memmem(data, end-data, "\r\n", 2);
  311. else
  312. next = tor_memmem(data, end-data, "\r\n.", 3);
  313. if (next) {
  314. memcpy(outp, data, next-data);
  315. outp += (next-data);
  316. data = next+2;
  317. } else {
  318. memcpy(outp, data, end-data);
  319. outp += (end-data);
  320. *outp = '\0';
  321. return outp - *out;
  322. }
  323. if (translate_newlines) {
  324. *outp++ = '\n';
  325. } else {
  326. *outp++ = '\r';
  327. *outp++ = '\n';
  328. }
  329. }
  330. *outp = '\0';
  331. return outp - *out;
  332. }
  333. /** Given a pointer to a string starting at <b>start</b> containing
  334. * <b>in_len_max</b> characters, decode a string beginning with a single
  335. * quote, containing any number of non-quote characters or characters escaped
  336. * with a backslash, and ending with a final quote. Place the resulting
  337. * string (unquoted, unescaped) into a newly allocated string in *<b>out</b>;
  338. * store its length in <b>out_len</b>. On success, return a pointer to the
  339. * character immediately following the escaped string. On failure, return
  340. * NULL. */
  341. static const char *
  342. get_escaped_string(const char *start, size_t in_len_max,
  343. char **out, size_t *out_len)
  344. {
  345. const char *cp, *end;
  346. char *outp;
  347. size_t len=0;
  348. if (*start != '\"')
  349. return NULL;
  350. cp = start+1;
  351. end = start+in_len_max;
  352. /* Calculate length. */
  353. while (1) {
  354. if (cp >= end)
  355. return NULL;
  356. else if (*cp == '\\') {
  357. if (++cp == end)
  358. return NULL; /* Can't escape EOS. */
  359. ++cp;
  360. ++len;
  361. } else if (*cp == '\"') {
  362. break;
  363. } else {
  364. ++cp;
  365. ++len;
  366. }
  367. }
  368. end = cp;
  369. outp = *out = tor_malloc(len+1);
  370. *out_len = len;
  371. cp = start+1;
  372. while (cp < end) {
  373. if (*cp == '\\')
  374. ++cp;
  375. *outp++ = *cp++;
  376. }
  377. *outp = '\0';
  378. tor_assert((outp - *out) == (int)*out_len);
  379. return end+1;
  380. }
  381. /** Acts like sprintf, but writes its formatted string to the end of
  382. * <b>conn</b>-\>outbuf. The message may be truncated if it is too long,
  383. * but it will always end with a CRLF sequence.
  384. *
  385. * Currently the length of the message is limited to 1024 (including the
  386. * ending \n\r\0. */
  387. static void
  388. connection_printf_to_buf(control_connection_t *conn, const char *format, ...)
  389. {
  390. #define CONNECTION_PRINTF_TO_BUF_BUFFERSIZE 1024
  391. va_list ap;
  392. char buf[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE];
  393. int r;
  394. size_t len;
  395. va_start(ap,format);
  396. r = tor_vsnprintf(buf, sizeof(buf), format, ap);
  397. va_end(ap);
  398. if (r<0) {
  399. log_warn(LD_BUG, "Unable to format string for controller.");
  400. return;
  401. }
  402. len = strlen(buf);
  403. if (memcmp("\r\n\0", buf+len-2, 3)) {
  404. buf[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE-1] = '\0';
  405. buf[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE-2] = '\n';
  406. buf[CONNECTION_PRINTF_TO_BUF_BUFFERSIZE-3] = '\r';
  407. }
  408. connection_write_to_buf(buf, len, TO_CONN(conn));
  409. }
  410. /** Send a "DONE" message down the control connection <b>conn</b> */
  411. static void
  412. send_control_done(control_connection_t *conn)
  413. {
  414. connection_write_str_to_buf("250 OK\r\n", conn);
  415. }
  416. /* Send an event to all v1 controllers that are listening for code
  417. * <b>event</b>. The event's body is given by <b>msg</b>.
  418. *
  419. * If <b>which</b> & SHORT_NAMES, the event contains short-format names: send
  420. * it to controllers that haven't enabled the VERBOSE_NAMES feature. If
  421. * <b>which</b> & LONG_NAMES, the event contains long-format names: send it
  422. * to contollers that <em>have</em> enabled VERBOSE_NAMES.
  423. *
  424. * The EXTENDED_FORMAT and NONEXTENDED_FORMAT flags behave similarly with
  425. * respect to the EXTENDED_EVENTS feature. */
  426. static void
  427. send_control_event_string(uint16_t event, event_format_t which,
  428. const char *msg)
  429. {
  430. connection_t **conns;
  431. int n_conns, i;
  432. tor_assert(event >= _EVENT_MIN && event <= _EVENT_MAX);
  433. get_connection_array(&conns, &n_conns);
  434. for (i = 0; i < n_conns; ++i) {
  435. if (conns[i]->type == CONN_TYPE_CONTROL &&
  436. !conns[i]->marked_for_close &&
  437. conns[i]->state == CONTROL_CONN_STATE_OPEN) {
  438. control_connection_t *control_conn = TO_CONTROL_CONN(conns[i]);
  439. if (control_conn->use_long_names) {
  440. if (!(which & LONG_NAMES))
  441. continue;
  442. } else {
  443. if (!(which & SHORT_NAMES))
  444. continue;
  445. }
  446. if (control_conn->use_extended_events) {
  447. if (!(which & EXTENDED_FORMAT))
  448. continue;
  449. } else {
  450. if (!(which & NONEXTENDED_FORMAT))
  451. continue;
  452. }
  453. if (control_conn->event_mask & (1<<event)) {
  454. int is_err = 0;
  455. connection_write_to_buf(msg, strlen(msg), TO_CONN(control_conn));
  456. if (event == EVENT_ERR_MSG)
  457. is_err = 1;
  458. else if (event == EVENT_STATUS_GENERAL)
  459. is_err = !strcmpstart(msg, "STATUS_GENERAL ERR ");
  460. else if (event == EVENT_STATUS_CLIENT)
  461. is_err = !strcmpstart(msg, "STATUS_CLIENT ERR ");
  462. else if (event == EVENT_STATUS_SERVER)
  463. is_err = !strcmpstart(msg, "STATUS_SERVER ERR ");
  464. if (is_err)
  465. connection_handle_write(TO_CONN(control_conn), 1);
  466. }
  467. }
  468. }
  469. }
  470. /** Helper for send_control1_event and send_control1_event_extended:
  471. * Send an event to all v1 controllers that are listening for code
  472. * <b>event</b>. The event's body is created by the printf-style format in
  473. * <b>format</b>, and other arguments as provided.
  474. *
  475. * If <b>extended</b> is true, and the format contains a single '@' character,
  476. * it will be replaced with a space and all text after that character will be
  477. * sent only to controllers that have enabled extended events.
  478. *
  479. * Currently the length of the message is limited to 1024 (including the
  480. * ending \n\r\0). */
  481. static void
  482. send_control_event_impl(uint16_t event, event_format_t which, int extended,
  483. const char *format, va_list ap)
  484. {
  485. /* This is just a little longer than the longest allowed log message */
  486. #define SEND_CONTROL1_EVENT_BUFFERSIZE 10064
  487. int r;
  488. char buf[SEND_CONTROL1_EVENT_BUFFERSIZE];
  489. size_t len;
  490. char *cp;
  491. r = tor_vsnprintf(buf, sizeof(buf), format, ap);
  492. if (r<0) {
  493. log_warn(LD_BUG, "Unable to format event for controller.");
  494. return;
  495. }
  496. len = strlen(buf);
  497. if (memcmp("\r\n\0", buf+len-2, 3)) {
  498. /* if it is not properly terminated, do it now */
  499. buf[SEND_CONTROL1_EVENT_BUFFERSIZE-1] = '\0';
  500. buf[SEND_CONTROL1_EVENT_BUFFERSIZE-2] = '\n';
  501. buf[SEND_CONTROL1_EVENT_BUFFERSIZE-3] = '\r';
  502. }
  503. if (extended && (cp = strchr(buf, '@'))) {
  504. which &= ~ALL_FORMATS;
  505. *cp = ' ';
  506. send_control_event_string(event, which|EXTENDED_FORMAT, buf);
  507. memcpy(cp, "\r\n\0", 3);
  508. send_control_event_string(event, which|NONEXTENDED_FORMAT, buf);
  509. } else {
  510. send_control_event_string(event, which|ALL_FORMATS, buf);
  511. }
  512. }
  513. /* Send an event to all v1 controllers that are listening for code
  514. * <b>event</b>. The event's body is created by the printf-style format in
  515. * <b>format</b>, and other arguments as provided.
  516. *
  517. * Currently the length of the message is limited to 1024 (including the
  518. * ending \n\r\0. */
  519. static void
  520. send_control_event(uint16_t event, event_format_t which,
  521. const char *format, ...)
  522. {
  523. va_list ap;
  524. va_start(ap, format);
  525. send_control_event_impl(event, which, 0, format, ap);
  526. va_end(ap);
  527. }
  528. /* Send an event to all v1 controllers that are listening for code
  529. * <b>event</b>. The event's body is created by the printf-style format in
  530. * <b>format</b>, and other arguments as provided.
  531. *
  532. * If the format contains a single '@' character, it will be replaced with a
  533. * space and all text after that character will be sent only to controllers
  534. * that have enabled extended events.
  535. *
  536. * Currently the length of the message is limited to 1024 (including the
  537. * ending \n\r\0. */
  538. static void
  539. send_control_event_extended(uint16_t event, event_format_t which,
  540. const char *format, ...)
  541. {
  542. va_list ap;
  543. va_start(ap, format);
  544. send_control_event_impl(event, which, 1, format, ap);
  545. va_end(ap);
  546. }
  547. /** Given a text circuit <b>id</b>, return the corresponding circuit. */
  548. static origin_circuit_t *
  549. get_circ(const char *id)
  550. {
  551. unsigned long n_id;
  552. int ok;
  553. n_id = tor_parse_ulong(id, 10, 0, ULONG_MAX, &ok, NULL);
  554. if (!ok)
  555. return NULL;
  556. return circuit_get_by_global_id(n_id);
  557. }
  558. /** Given a text stream <b>id</b>, return the corresponding AP connection. */
  559. static edge_connection_t *
  560. get_stream(const char *id)
  561. {
  562. unsigned long n_id;
  563. int ok;
  564. edge_connection_t *conn;
  565. n_id = tor_parse_ulong(id, 10, 0, ULONG_MAX, &ok, NULL);
  566. if (!ok)
  567. return NULL;
  568. conn = connection_get_by_global_id(n_id);
  569. if (!conn || conn->_base.type != CONN_TYPE_AP)
  570. return NULL;
  571. return conn;
  572. }
  573. /** Helper for setconf and resetconf. Acts like setconf, except
  574. * it passes <b>use_defaults</b> on to options_trial_assign(). Modifies the
  575. * contents of body.
  576. */
  577. static int
  578. control_setconf_helper(control_connection_t *conn, uint32_t len, char *body,
  579. int use_defaults)
  580. {
  581. int r;
  582. config_line_t *lines=NULL;
  583. char *start = body;
  584. char *errstring = NULL;
  585. const int clear_first = 1;
  586. if (1) {
  587. char *config;
  588. smartlist_t *entries = smartlist_create();
  589. /* We have a string, "body", of the format '(key(=val|="val")?)' entries
  590. * separated by space. break it into a list of configuration entries. */
  591. while (*body) {
  592. char *eq = body;
  593. char *key;
  594. char *entry;
  595. while (!TOR_ISSPACE(*eq) && *eq != '=')
  596. ++eq;
  597. key = tor_strndup(body, eq-body);
  598. body = eq+1;
  599. if (*eq == '=') {
  600. char *val;
  601. size_t val_len;
  602. size_t ent_len;
  603. if (*body != '\"') {
  604. char *val_start = body;
  605. while (!TOR_ISSPACE(*body))
  606. body++;
  607. val = tor_strndup(val_start, body-val_start);
  608. val_len = strlen(val);
  609. } else {
  610. body = (char*)get_escaped_string(body, (len - (body-start)),
  611. &val, &val_len);
  612. if (!body) {
  613. connection_write_str_to_buf("551 Couldn't parse string\r\n", conn);
  614. SMARTLIST_FOREACH(entries, char *, cp, tor_free(cp));
  615. smartlist_free(entries);
  616. return 0;
  617. }
  618. }
  619. ent_len = strlen(key)+val_len+3;
  620. entry = tor_malloc(ent_len+1);
  621. tor_snprintf(entry, ent_len, "%s %s", key, val);
  622. tor_free(key);
  623. tor_free(val);
  624. } else {
  625. entry = key;
  626. }
  627. smartlist_add(entries, entry);
  628. while (TOR_ISSPACE(*body))
  629. ++body;
  630. }
  631. smartlist_add(entries, tor_strdup(""));
  632. config = smartlist_join_strings(entries, "\n", 0, NULL);
  633. SMARTLIST_FOREACH(entries, char *, cp, tor_free(cp));
  634. smartlist_free(entries);
  635. if (config_get_lines(config, &lines) < 0) {
  636. log_warn(LD_CONTROL,"Controller gave us config lines we can't parse.");
  637. connection_write_str_to_buf("551 Couldn't parse configuration\r\n",
  638. conn);
  639. tor_free(config);
  640. return 0;
  641. }
  642. tor_free(config);
  643. }
  644. if ((r=options_trial_assign(lines, use_defaults,
  645. clear_first, &errstring)) < 0) {
  646. const char *msg;
  647. log_warn(LD_CONTROL,
  648. "Controller gave us config lines that didn't validate: %s.",
  649. errstring);
  650. switch (r) {
  651. case -1:
  652. msg = "552 Unrecognized option";
  653. break;
  654. case -2:
  655. msg = "513 Unacceptable option value";
  656. break;
  657. case -3:
  658. msg = "553 Transition not allowed";
  659. break;
  660. case -4:
  661. default:
  662. msg = "553 Unable to set option";
  663. break;
  664. }
  665. connection_printf_to_buf(conn, "%s: %s\r\n", msg, errstring);
  666. config_free_lines(lines);
  667. tor_free(errstring);
  668. return 0;
  669. }
  670. config_free_lines(lines);
  671. send_control_done(conn);
  672. return 0;
  673. }
  674. /** Called when we receive a SETCONF message: parse the body and try
  675. * to update our configuration. Reply with a DONE or ERROR message.
  676. * Modifies the contents of body.*/
  677. static int
  678. handle_control_setconf(control_connection_t *conn, uint32_t len, char *body)
  679. {
  680. return control_setconf_helper(conn, len, body, 0);
  681. }
  682. /** Called when we receive a RESETCONF message: parse the body and try
  683. * to update our configuration. Reply with a DONE or ERROR message.
  684. * Modifies the contents of body. */
  685. static int
  686. handle_control_resetconf(control_connection_t *conn, uint32_t len, char *body)
  687. {
  688. return control_setconf_helper(conn, len, body, 1);
  689. }
  690. /** Called when we receive a GETCONF message. Parse the request, and
  691. * reply with a CONFVALUE or an ERROR message */
  692. static int
  693. handle_control_getconf(control_connection_t *conn, uint32_t body_len,
  694. const char *body)
  695. {
  696. smartlist_t *questions = NULL;
  697. smartlist_t *answers = NULL;
  698. smartlist_t *unrecognized = NULL;
  699. char *msg = NULL;
  700. size_t msg_len;
  701. or_options_t *options = get_options();
  702. questions = smartlist_create();
  703. (void) body_len; /* body is nul-terminated; so we can ignore len. */
  704. smartlist_split_string(questions, body, " ",
  705. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  706. answers = smartlist_create();
  707. unrecognized = smartlist_create();
  708. SMARTLIST_FOREACH(questions, char *, q,
  709. {
  710. if (!option_is_recognized(q)) {
  711. smartlist_add(unrecognized, q);
  712. } else {
  713. config_line_t *answer = option_get_assignment(options,q);
  714. if (!answer) {
  715. const char *name = option_get_canonical_name(q);
  716. size_t alen = strlen(name)+8;
  717. char *astr = tor_malloc(alen);
  718. tor_snprintf(astr, alen, "250-%s\r\n", name);
  719. smartlist_add(answers, astr);
  720. }
  721. while (answer) {
  722. config_line_t *next;
  723. size_t alen = strlen(answer->key)+strlen(answer->value)+8;
  724. char *astr = tor_malloc(alen);
  725. tor_snprintf(astr, alen, "250-%s=%s\r\n",
  726. answer->key, answer->value);
  727. smartlist_add(answers, astr);
  728. next = answer->next;
  729. tor_free(answer->key);
  730. tor_free(answer->value);
  731. tor_free(answer);
  732. answer = next;
  733. }
  734. }
  735. });
  736. if (1) {
  737. int i,len;
  738. if ((len = smartlist_len(unrecognized))) {
  739. for (i=0; i < len-1; ++i)
  740. connection_printf_to_buf(conn,
  741. "552-Unrecognized configuration key \"%s\"\r\n",
  742. (char*)smartlist_get(unrecognized, i));
  743. connection_printf_to_buf(conn,
  744. "552 Unrecognized configuration key \"%s\"\r\n",
  745. (char*)smartlist_get(unrecognized, len-1));
  746. } else if ((len = smartlist_len(answers))) {
  747. char *tmp = smartlist_get(answers, len-1);
  748. tor_assert(strlen(tmp)>4);
  749. tmp[3] = ' ';
  750. msg = smartlist_join_strings(answers, "", 0, &msg_len);
  751. connection_write_to_buf(msg, msg_len, TO_CONN(conn));
  752. } else {
  753. connection_write_str_to_buf("250 OK\r\n", conn);
  754. }
  755. }
  756. if (answers) {
  757. SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
  758. smartlist_free(answers);
  759. }
  760. if (questions) {
  761. SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
  762. smartlist_free(questions);
  763. }
  764. smartlist_free(unrecognized);
  765. tor_free(msg);
  766. return 0;
  767. }
  768. /** Called when we get a SETEVENTS message: update conn->event_mask,
  769. * and reply with DONE or ERROR. */
  770. static int
  771. handle_control_setevents(control_connection_t *conn, uint32_t len,
  772. const char *body)
  773. {
  774. uint16_t event_code;
  775. uint32_t event_mask = 0;
  776. unsigned int extended = 0;
  777. (void) len;
  778. if (1) {
  779. smartlist_t *events = smartlist_create();
  780. smartlist_split_string(events, body, " ",
  781. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  782. SMARTLIST_FOREACH(events, const char *, ev,
  783. {
  784. if (!strcasecmp(ev, "EXTENDED")) {
  785. extended = 1;
  786. continue;
  787. } else if (!strcasecmp(ev, "CIRC"))
  788. event_code = EVENT_CIRCUIT_STATUS;
  789. else if (!strcasecmp(ev, "STREAM"))
  790. event_code = EVENT_STREAM_STATUS;
  791. else if (!strcasecmp(ev, "ORCONN"))
  792. event_code = EVENT_OR_CONN_STATUS;
  793. else if (!strcasecmp(ev, "BW"))
  794. event_code = EVENT_BANDWIDTH_USED;
  795. else if (!strcasecmp(ev, "DEBUG"))
  796. event_code = EVENT_DEBUG_MSG;
  797. else if (!strcasecmp(ev, "INFO"))
  798. event_code = EVENT_INFO_MSG;
  799. else if (!strcasecmp(ev, "NOTICE"))
  800. event_code = EVENT_NOTICE_MSG;
  801. else if (!strcasecmp(ev, "WARN"))
  802. event_code = EVENT_WARN_MSG;
  803. else if (!strcasecmp(ev, "ERR"))
  804. event_code = EVENT_ERR_MSG;
  805. else if (!strcasecmp(ev, "NEWDESC"))
  806. event_code = EVENT_NEW_DESC;
  807. else if (!strcasecmp(ev, "ADDRMAP"))
  808. event_code = EVENT_ADDRMAP;
  809. else if (!strcasecmp(ev, "AUTHDIR_NEWDESCS"))
  810. event_code = EVENT_AUTHDIR_NEWDESCS;
  811. else if (!strcasecmp(ev, "DESCCHANGED"))
  812. event_code = EVENT_DESCCHANGED;
  813. else if (!strcasecmp(ev, "NS"))
  814. event_code = EVENT_NS;
  815. else if (!strcasecmp(ev, "STATUS_GENERAL"))
  816. event_code = EVENT_STATUS_GENERAL;
  817. else if (!strcasecmp(ev, "STATUS_CLIENT"))
  818. event_code = EVENT_STATUS_CLIENT;
  819. else if (!strcasecmp(ev, "STATUS_SERVER"))
  820. event_code = EVENT_STATUS_SERVER;
  821. else if (!strcasecmp(ev, "GUARD"))
  822. event_code = EVENT_GUARD;
  823. else if (!strcasecmp(ev, "GUARDS")) {
  824. /* XXX tolerate buggy spec in 0.1.2.5-alpha through 0.1.2.10-rc */
  825. event_code = EVENT_GUARD;
  826. } else if (!strcasecmp(ev, "STREAM_BW"))
  827. event_code = EVENT_STREAM_BANDWIDTH_USED;
  828. else {
  829. connection_printf_to_buf(conn, "552 Unrecognized event \"%s\"\r\n",
  830. ev);
  831. SMARTLIST_FOREACH(events, char *, e, tor_free(e));
  832. smartlist_free(events);
  833. return 0;
  834. }
  835. event_mask |= (1 << event_code);
  836. });
  837. SMARTLIST_FOREACH(events, char *, e, tor_free(e));
  838. smartlist_free(events);
  839. }
  840. conn->event_mask = event_mask;
  841. if (extended)
  842. conn->use_extended_events = 1;
  843. control_update_global_event_mask();
  844. send_control_done(conn);
  845. return 0;
  846. }
  847. /** Decode the hashed, base64'd password stored in <b>hashed</b>. If
  848. * <b>buf</b> is provided, store the hashed password in the first
  849. * S2K_SPECIFIER_LEN+DIGEST_LEN bytes of <b>buf</b>. Return 0 on
  850. * success, -1 on failure.
  851. */
  852. int
  853. decode_hashed_password(char *buf, const char *hashed)
  854. {
  855. char decoded[64];
  856. if (!strcmpstart(hashed, "16:")) {
  857. if (base16_decode(decoded, sizeof(decoded), hashed+3, strlen(hashed+3))<0
  858. || strlen(hashed+3) != (S2K_SPECIFIER_LEN+DIGEST_LEN)*2) {
  859. return -1;
  860. }
  861. } else {
  862. if (base64_decode(decoded, sizeof(decoded), hashed, strlen(hashed))
  863. != S2K_SPECIFIER_LEN+DIGEST_LEN) {
  864. return -1;
  865. }
  866. }
  867. if (buf)
  868. memcpy(buf, decoded, S2K_SPECIFIER_LEN+DIGEST_LEN);
  869. return 0;
  870. }
  871. /** Called when we get an AUTHENTICATE message. Check whether the
  872. * authentication is valid, and if so, update the connection's state to
  873. * OPEN. Reply with DONE or ERROR.
  874. */
  875. static int
  876. handle_control_authenticate(control_connection_t *conn, uint32_t len,
  877. const char *body)
  878. {
  879. int used_quoted_string = 0;
  880. or_options_t *options = get_options();
  881. const char *errstr = NULL;
  882. char *password;
  883. size_t password_len;
  884. if (1) {
  885. if (TOR_ISXDIGIT(body[0])) {
  886. int i = 0;
  887. while (TOR_ISXDIGIT(body[i]))
  888. ++i;
  889. password = tor_malloc(i/2 + 1);
  890. if (base16_decode(password, i/2+1, body, i)<0) {
  891. connection_write_str_to_buf(
  892. "551 Invalid hexadecimal encoding. Maybe you tried a plain text "
  893. "password? If so, the standard requires that you put it in "
  894. "double quotes.\r\n", conn);
  895. tor_free(password);
  896. return 0;
  897. }
  898. password_len = i/2;
  899. } else if (TOR_ISSPACE(body[0])) {
  900. password = tor_strdup("");
  901. password_len = 0;
  902. } else {
  903. if (!get_escaped_string(body, len, &password, &password_len)) {
  904. connection_write_str_to_buf("551 Invalid quoted string. You need "
  905. "to put the password in double quotes.\r\n", conn);
  906. return 0;
  907. }
  908. used_quoted_string = 1;
  909. }
  910. }
  911. if (options->CookieAuthentication && authentication_cookie_is_set) {
  912. if (password_len != AUTHENTICATION_COOKIE_LEN) {
  913. log_warn(LD_CONTROL, "Got authentication cookie with wrong length (%d)",
  914. (int)password_len);
  915. errstr = "Wrong length on authentication cookie.";
  916. goto err;
  917. } else if (memcmp(authentication_cookie, password, password_len)) {
  918. log_warn(LD_CONTROL, "Got mismatched authentication cookie");
  919. errstr = "Authentication cookie did not match expected value.";
  920. goto err;
  921. } else {
  922. goto ok;
  923. }
  924. } else if (options->HashedControlPassword) {
  925. char expected[S2K_SPECIFIER_LEN+DIGEST_LEN];
  926. char received[DIGEST_LEN];
  927. if (decode_hashed_password(expected, options->HashedControlPassword)<0) {
  928. log_warn(LD_CONTROL,
  929. "Couldn't decode HashedControlPassword: invalid base16");
  930. errstr = "Couldn't decode HashedControlPassword value in configuration.";
  931. goto err;
  932. }
  933. secret_to_key(received,DIGEST_LEN,password,password_len,expected);
  934. if (!memcmp(expected+S2K_SPECIFIER_LEN, received, DIGEST_LEN))
  935. goto ok;
  936. if (used_quoted_string)
  937. errstr = "Password did not match HashedControlPassword value from "
  938. "configuration";
  939. else
  940. errstr = "Password did not match HashedControlPassword value from "
  941. "configuration. Maybe you tried a plain text password? "
  942. "If so, the standard requires that you put it in double quotes.";
  943. goto err;
  944. } else {
  945. /* if Tor doesn't demand any stronger authentication, then
  946. * the controller can get in with anything. */
  947. goto ok;
  948. }
  949. err:
  950. tor_free(password);
  951. if (!errstr)
  952. errstr = "Unknown reason.";
  953. connection_printf_to_buf(conn, "515 Authentication failed: %s\r\n",
  954. errstr);
  955. return 0;
  956. ok:
  957. log_info(LD_CONTROL, "Authenticated control connection (%d)", conn->_base.s);
  958. send_control_done(conn);
  959. conn->_base.state = CONTROL_CONN_STATE_OPEN;
  960. tor_free(password);
  961. return 0;
  962. }
  963. /** Called when we get a SAVECONF command. Try to flush the current options to
  964. * disk, and report success or failure. */
  965. static int
  966. handle_control_saveconf(control_connection_t *conn, uint32_t len,
  967. const char *body)
  968. {
  969. (void) len;
  970. (void) body;
  971. if (options_save_current()<0) {
  972. connection_write_str_to_buf(
  973. "551 Unable to write configuration to disk.\r\n", conn);
  974. } else {
  975. send_control_done(conn);
  976. }
  977. return 0;
  978. }
  979. /** Called when we get a SIGNAL command. React to the provided signal, and
  980. * report success or failure. (If the signal results in a shutdown, success
  981. * may not be reported.) */
  982. static int
  983. handle_control_signal(control_connection_t *conn, uint32_t len,
  984. const char *body)
  985. {
  986. int sig;
  987. (void) len;
  988. if (1) {
  989. int n = 0;
  990. char *s;
  991. while (body[n] && ! TOR_ISSPACE(body[n]))
  992. ++n;
  993. s = tor_strndup(body, n);
  994. if (!strcasecmp(s, "RELOAD") || !strcasecmp(s, "HUP"))
  995. sig = SIGHUP;
  996. else if (!strcasecmp(s, "SHUTDOWN") || !strcasecmp(s, "INT"))
  997. sig = SIGINT;
  998. else if (!strcasecmp(s, "DUMP") || !strcasecmp(s, "USR1"))
  999. sig = SIGUSR1;
  1000. else if (!strcasecmp(s, "DEBUG") || !strcasecmp(s, "USR2"))
  1001. sig = SIGUSR2;
  1002. else if (!strcasecmp(s, "HALT") || !strcasecmp(s, "TERM"))
  1003. sig = SIGTERM;
  1004. else if (!strcasecmp(s, "NEWNYM"))
  1005. sig = SIGNEWNYM;
  1006. else if (!strcasecmp(s, "CLEARDNSCACHE"))
  1007. sig = SIGCLEARDNSCACHE;
  1008. else {
  1009. connection_printf_to_buf(conn, "552 Unrecognized signal code \"%s\"\r\n",
  1010. s);
  1011. sig = -1;
  1012. }
  1013. tor_free(s);
  1014. if (sig<0)
  1015. return 0;
  1016. }
  1017. /* Send DONE first, in case the signal makes us shut down. */
  1018. send_control_done(conn);
  1019. control_signal_act(sig);
  1020. return 0;
  1021. }
  1022. /** Called when we get a MAPADDRESS command; try to bind all listed addresses,
  1023. * and report success or failrue. */
  1024. static int
  1025. handle_control_mapaddress(control_connection_t *conn, uint32_t len,
  1026. const char *body)
  1027. {
  1028. smartlist_t *elts;
  1029. smartlist_t *lines;
  1030. smartlist_t *reply;
  1031. char *r;
  1032. size_t sz;
  1033. (void) len; /* body is nul-terminated, so it's safe to ignore the length. */
  1034. lines = smartlist_create();
  1035. elts = smartlist_create();
  1036. reply = smartlist_create();
  1037. smartlist_split_string(lines, body, " ",
  1038. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1039. SMARTLIST_FOREACH(lines, char *, line,
  1040. {
  1041. tor_strlower(line);
  1042. smartlist_split_string(elts, line, "=", 0, 2);
  1043. if (smartlist_len(elts) == 2) {
  1044. const char *from = smartlist_get(elts,0);
  1045. const char *to = smartlist_get(elts,1);
  1046. size_t anslen = strlen(line)+512;
  1047. char *ans = tor_malloc(anslen);
  1048. if (address_is_invalid_destination(to, 1)) {
  1049. tor_snprintf(ans, anslen,
  1050. "512-syntax error: invalid address '%s'", to);
  1051. smartlist_add(reply, ans);
  1052. log_warn(LD_CONTROL,
  1053. "Skipping invalid argument '%s' in MapAddress msg", to);
  1054. } else if (!strcmp(from, ".") || !strcmp(from, "0.0.0.0")) {
  1055. const char *address = addressmap_register_virtual_address(
  1056. !strcmp(from,".") ? RESOLVED_TYPE_HOSTNAME : RESOLVED_TYPE_IPV4,
  1057. tor_strdup(to));
  1058. if (!address) {
  1059. tor_snprintf(ans, anslen,
  1060. "451-resource exhausted: skipping '%s'", line);
  1061. smartlist_add(reply, ans);
  1062. log_warn(LD_CONTROL,
  1063. "Unable to allocate address for '%s' in MapAddress msg",
  1064. safe_str(line));
  1065. } else {
  1066. tor_snprintf(ans, anslen, "250-%s=%s", address, to);
  1067. smartlist_add(reply, ans);
  1068. }
  1069. } else {
  1070. addressmap_register(from, tor_strdup(to), 1);
  1071. tor_snprintf(ans, anslen, "250-%s", line);
  1072. smartlist_add(reply, ans);
  1073. }
  1074. } else {
  1075. size_t anslen = strlen(line)+256;
  1076. char *ans = tor_malloc(anslen);
  1077. tor_snprintf(ans, anslen, "512-syntax error: mapping '%s' is "
  1078. "not of expected form 'foo=bar'.", line);
  1079. smartlist_add(reply, ans);
  1080. log_info(LD_CONTROL, "Skipping MapAddress '%s': wrong "
  1081. "number of items.", safe_str(line));
  1082. }
  1083. SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
  1084. smartlist_clear(elts);
  1085. });
  1086. SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
  1087. smartlist_free(lines);
  1088. smartlist_free(elts);
  1089. if (1) {
  1090. if (smartlist_len(reply)) {
  1091. ((char*)smartlist_get(reply,smartlist_len(reply)-1))[3] = ' ';
  1092. r = smartlist_join_strings(reply, "\r\n", 1, &sz);
  1093. connection_write_to_buf(r, sz, TO_CONN(conn));
  1094. tor_free(r);
  1095. } else {
  1096. const char *response =
  1097. "512 syntax error: not enough arguments to mapaddress.\r\n";
  1098. connection_write_to_buf(response, strlen(response), TO_CONN(conn));
  1099. }
  1100. }
  1101. SMARTLIST_FOREACH(reply, char *, cp, tor_free(cp));
  1102. smartlist_free(reply);
  1103. return 0;
  1104. }
  1105. /** Implementation helper for GETINFO: knows the answers for various
  1106. * trivial-to-implement questions. */
  1107. static int
  1108. getinfo_helper_misc(control_connection_t *conn, const char *question,
  1109. char **answer)
  1110. {
  1111. (void) conn;
  1112. if (!strcmp(question, "version")) {
  1113. *answer = tor_strdup(VERSION);
  1114. } else if (!strcmp(question, "config-file")) {
  1115. *answer = tor_strdup(get_torrc_fname());
  1116. } else if (!strcmp(question, "info/names")) {
  1117. *answer = list_getinfo_options();
  1118. } else if (!strcmp(question, "events/names")) {
  1119. *answer = tor_strdup("CIRC STREAM ORCONN BW DEBUG INFO NOTICE WARN ERR "
  1120. "NEWDESC ADDRMAP AUTHDIR_NEWDESCS DESCCHANGED "
  1121. "NS STATUS_GENERAL STATUS_CLIENT STATUS_SERVER "
  1122. "GUARD STREAM_BW");
  1123. } else if (!strcmp(question, "features/names")) {
  1124. *answer = tor_strdup("VERBOSE_NAMES EXTENDED_EVENTS");
  1125. } else if (!strcmp(question, "address")) {
  1126. uint32_t addr;
  1127. if (router_pick_published_address(get_options(), &addr) < 0)
  1128. return -1;
  1129. *answer = tor_dup_addr(addr);
  1130. } else if (!strcmp(question, "dir-usage")) {
  1131. *answer = directory_dump_request_log();
  1132. } else if (!strcmp(question, "fingerprint")) {
  1133. routerinfo_t *me = router_get_my_routerinfo();
  1134. if (!me)
  1135. return -1;
  1136. *answer = tor_malloc(HEX_DIGEST_LEN+1);
  1137. base16_encode(*answer, HEX_DIGEST_LEN+1, me->cache_info.identity_digest,
  1138. DIGEST_LEN);
  1139. }
  1140. return 0;
  1141. }
  1142. /** Implementation helper for GETINFO: knows the answers for questions about
  1143. * directory information. */
  1144. static int
  1145. getinfo_helper_dir(control_connection_t *control_conn,
  1146. const char *question, char **answer)
  1147. {
  1148. if (!strcmpstart(question, "desc/id/")) {
  1149. routerinfo_t *ri = router_get_by_hexdigest(question+strlen("desc/id/"));
  1150. if (ri) {
  1151. const char *body = signed_descriptor_get_body(&ri->cache_info);
  1152. if (body)
  1153. *answer = tor_strndup(body, ri->cache_info.signed_descriptor_len);
  1154. }
  1155. } else if (!strcmpstart(question, "desc/name/")) {
  1156. routerinfo_t *ri = router_get_by_nickname(question+strlen("desc/name/"),1);
  1157. if (ri) {
  1158. const char *body = signed_descriptor_get_body(&ri->cache_info);
  1159. if (body)
  1160. *answer = tor_strndup(body, ri->cache_info.signed_descriptor_len);
  1161. }
  1162. } else if (!strcmp(question, "desc/all-recent")) {
  1163. routerlist_t *routerlist = router_get_routerlist();
  1164. smartlist_t *sl = smartlist_create();
  1165. if (routerlist && routerlist->routers) {
  1166. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, ri,
  1167. {
  1168. const char *body = signed_descriptor_get_body(&ri->cache_info);
  1169. if (body)
  1170. smartlist_add(sl,
  1171. tor_strndup(body, ri->cache_info.signed_descriptor_len));
  1172. });
  1173. }
  1174. *answer = smartlist_join_strings(sl, "", 0, NULL);
  1175. SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  1176. smartlist_free(sl);
  1177. } else if (!strcmpstart(question, "dir/server/")) {
  1178. size_t answer_len = 0, url_len = strlen(question)+2;
  1179. char *url = tor_malloc(url_len);
  1180. smartlist_t *descs = smartlist_create();
  1181. const char *msg;
  1182. int res;
  1183. char *cp;
  1184. tor_snprintf(url, url_len, "/tor/%s", question+4);
  1185. res = dirserv_get_routerdescs(descs, url, &msg);
  1186. if (res) {
  1187. log_warn(LD_CONTROL, "getinfo '%s': %s", question, msg);
  1188. return -1;
  1189. }
  1190. SMARTLIST_FOREACH(descs, signed_descriptor_t *, sd,
  1191. answer_len += sd->signed_descriptor_len);
  1192. cp = *answer = tor_malloc(answer_len+1);
  1193. SMARTLIST_FOREACH(descs, signed_descriptor_t *, sd,
  1194. {
  1195. memcpy(cp, signed_descriptor_get_body(sd),
  1196. sd->signed_descriptor_len);
  1197. cp += sd->signed_descriptor_len;
  1198. });
  1199. *cp = '\0';
  1200. tor_free(url);
  1201. smartlist_free(descs);
  1202. } else if (!strcmpstart(question, "dir/status/")) {
  1203. if (get_options()->DirPort) {
  1204. size_t len=0;
  1205. char *cp;
  1206. smartlist_t *status_list = smartlist_create();
  1207. dirserv_get_networkstatus_v2(status_list,
  1208. question+strlen("dir/status/"));
  1209. SMARTLIST_FOREACH(status_list, cached_dir_t *, d, len += d->dir_len);
  1210. cp = *answer = tor_malloc(len+1);
  1211. SMARTLIST_FOREACH(status_list, cached_dir_t *, d, {
  1212. memcpy(cp, d->dir, d->dir_len);
  1213. cp += d->dir_len;
  1214. });
  1215. *cp = '\0';
  1216. smartlist_free(status_list);
  1217. } else {
  1218. smartlist_t *fp_list = smartlist_create();
  1219. smartlist_t *status_list = smartlist_create();
  1220. size_t fn_len = strlen(get_options()->DataDirectory)+HEX_DIGEST_LEN+32;
  1221. char *fn = tor_malloc(fn_len+1);
  1222. char hex_id[HEX_DIGEST_LEN+1];
  1223. dirserv_get_networkstatus_v2_fingerprints(
  1224. fp_list, question+strlen("dir/status/"));
  1225. SMARTLIST_FOREACH(fp_list, const char *, fp, {
  1226. char *s;
  1227. base16_encode(hex_id, sizeof(hex_id), fp, DIGEST_LEN);
  1228. tor_snprintf(fn, fn_len, "%s/cached-status/%s",
  1229. get_options()->DataDirectory, hex_id);
  1230. s = read_file_to_str(fn, 0, NULL);
  1231. if (s)
  1232. smartlist_add(status_list, s);
  1233. });
  1234. SMARTLIST_FOREACH(fp_list, char *, fp, tor_free(fp));
  1235. smartlist_free(fp_list);
  1236. *answer = smartlist_join_strings(status_list, "", 0, NULL);
  1237. SMARTLIST_FOREACH(status_list, char *, s, tor_free(s));
  1238. smartlist_free(status_list);
  1239. }
  1240. } else if (!strcmp(question, "network-status")) {
  1241. routerlist_t *routerlist = router_get_routerlist();
  1242. int verbose = control_conn->use_long_names;
  1243. if (!routerlist || !routerlist->routers ||
  1244. list_server_status(routerlist->routers, answer, verbose ? 2 : 1) < 0) {
  1245. return -1;
  1246. }
  1247. }
  1248. return 0;
  1249. }
  1250. /** Implementation helper for GETINFO: knows how to generate summaries of the
  1251. * current states of things we send events about. */
  1252. static int
  1253. getinfo_helper_events(control_connection_t *control_conn,
  1254. const char *question, char **answer)
  1255. {
  1256. if (!strcmp(question, "circuit-status")) {
  1257. circuit_t *circ;
  1258. smartlist_t *status = smartlist_create();
  1259. for (circ = _circuit_get_global_list(); circ; circ = circ->next) {
  1260. char *s, *path;
  1261. size_t slen;
  1262. const char *state;
  1263. if (! CIRCUIT_IS_ORIGIN(circ) || circ->marked_for_close)
  1264. continue;
  1265. if (control_conn->use_long_names)
  1266. path = circuit_list_path_for_controller(TO_ORIGIN_CIRCUIT(circ));
  1267. else
  1268. path = circuit_list_path(TO_ORIGIN_CIRCUIT(circ),0);
  1269. if (circ->state == CIRCUIT_STATE_OPEN)
  1270. state = "BUILT";
  1271. else if (strlen(path))
  1272. state = "EXTENDED";
  1273. else
  1274. state = "LAUNCHED";
  1275. slen = strlen(path)+strlen(state)+20;
  1276. s = tor_malloc(slen+1);
  1277. tor_snprintf(s, slen, "%lu %s %s",
  1278. (unsigned long)TO_ORIGIN_CIRCUIT(circ)->global_identifier,
  1279. state, path);
  1280. smartlist_add(status, s);
  1281. tor_free(path);
  1282. }
  1283. *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
  1284. SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
  1285. smartlist_free(status);
  1286. } else if (!strcmp(question, "stream-status")) {
  1287. connection_t **conns;
  1288. int n_conns, i;
  1289. char buf[256];
  1290. smartlist_t *status = smartlist_create();
  1291. get_connection_array(&conns, &n_conns);
  1292. for (i=0; i < n_conns; ++i) {
  1293. const char *state;
  1294. edge_connection_t *conn;
  1295. char *s;
  1296. size_t slen;
  1297. circuit_t *circ;
  1298. origin_circuit_t *origin_circ = NULL;
  1299. if (conns[i]->type != CONN_TYPE_AP ||
  1300. conns[i]->marked_for_close ||
  1301. conns[i]->state == AP_CONN_STATE_SOCKS_WAIT ||
  1302. conns[i]->state == AP_CONN_STATE_NATD_WAIT)
  1303. continue;
  1304. conn = TO_EDGE_CONN(conns[i]);
  1305. switch (conn->_base.state)
  1306. {
  1307. case AP_CONN_STATE_CONTROLLER_WAIT:
  1308. case AP_CONN_STATE_CIRCUIT_WAIT:
  1309. if (conn->socks_request &&
  1310. SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command))
  1311. state = "NEWRESOLVE";
  1312. else
  1313. state = "NEW";
  1314. break;
  1315. case AP_CONN_STATE_RENDDESC_WAIT:
  1316. case AP_CONN_STATE_CONNECT_WAIT:
  1317. state = "SENTCONNECT"; break;
  1318. case AP_CONN_STATE_RESOLVE_WAIT:
  1319. state = "SENTRESOLVE"; break;
  1320. case AP_CONN_STATE_OPEN:
  1321. state = "SUCCEEDED"; break;
  1322. default:
  1323. log_warn(LD_BUG, "Asked for stream in unknown state %d",
  1324. conn->_base.state);
  1325. continue;
  1326. }
  1327. circ = circuit_get_by_edge_conn(conn);
  1328. if (circ && CIRCUIT_IS_ORIGIN(circ))
  1329. origin_circ = TO_ORIGIN_CIRCUIT(circ);
  1330. write_stream_target_to_buf(conn, buf, sizeof(buf));
  1331. slen = strlen(buf)+strlen(state)+32;
  1332. s = tor_malloc(slen+1);
  1333. tor_snprintf(s, slen, "%lu %s %lu %s",
  1334. (unsigned long) conn->global_identifier,state,
  1335. origin_circ?
  1336. (unsigned long)origin_circ->global_identifier : 0ul,
  1337. buf);
  1338. smartlist_add(status, s);
  1339. }
  1340. *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
  1341. SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
  1342. smartlist_free(status);
  1343. } else if (!strcmp(question, "orconn-status")) {
  1344. connection_t **conns;
  1345. int n_conns, i;
  1346. smartlist_t *status = smartlist_create();
  1347. get_connection_array(&conns, &n_conns);
  1348. for (i=0; i < n_conns; ++i) {
  1349. const char *state;
  1350. char *s;
  1351. char name[128];
  1352. size_t slen;
  1353. or_connection_t *conn;
  1354. if (conns[i]->type != CONN_TYPE_OR || conns[i]->marked_for_close)
  1355. continue;
  1356. conn = TO_OR_CONN(conns[i]);
  1357. if (conn->_base.state == OR_CONN_STATE_OPEN)
  1358. state = "CONNECTED";
  1359. else if (conn->nickname)
  1360. state = "LAUNCHED";
  1361. else
  1362. state = "NEW";
  1363. orconn_target_get_name(control_conn->use_long_names, name, sizeof(name),
  1364. conn);
  1365. slen = strlen(name)+strlen(state)+2;
  1366. s = tor_malloc(slen+1);
  1367. tor_snprintf(s, slen, "%s %s", name, state);
  1368. smartlist_add(status, s);
  1369. }
  1370. *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
  1371. SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
  1372. smartlist_free(status);
  1373. } else if (!strcmpstart(question, "addr-mappings/")) {
  1374. time_t min_e, max_e;
  1375. smartlist_t *mappings;
  1376. if (!strcmp(question, "addr-mappings/all")) {
  1377. min_e = 0; max_e = TIME_MAX;
  1378. } else if (!strcmp(question, "addr-mappings/cache")) {
  1379. min_e = 2; max_e = TIME_MAX;
  1380. } else if (!strcmp(question, "addr-mappings/config")) {
  1381. min_e = 0; max_e = 0;
  1382. } else if (!strcmp(question, "addr-mappings/control")) {
  1383. min_e = 1; max_e = 1;
  1384. } else {
  1385. return 0;
  1386. }
  1387. mappings = smartlist_create();
  1388. addressmap_get_mappings(mappings, min_e, max_e);
  1389. *answer = smartlist_join_strings(mappings, "\r\n", 0, NULL);
  1390. SMARTLIST_FOREACH(mappings, char *, cp, tor_free(cp));
  1391. smartlist_free(mappings);
  1392. }
  1393. return 0;
  1394. }
  1395. /** Callback function for GETINFO: on a given control connection, try to
  1396. * answer the question <b>q</b> and store the newly-allocated answer in
  1397. * *<b>a</b>. If there's no answer, or an error occurs, just don't set
  1398. * <b>a</b>. Return 0.
  1399. */
  1400. typedef int (*getinfo_helper_t)(control_connection_t *,
  1401. const char *q, char **a);
  1402. /** A single item for the GETINFO question-to-answer-function table. */
  1403. typedef struct getinfo_item_t {
  1404. const char *varname; /**< The value (or prefix) of the question. */
  1405. getinfo_helper_t fn; /**< The function that knows the answer: NULL if
  1406. * this entry is documentation-only. */
  1407. const char *desc; /**< Description of the variable. */
  1408. int is_prefix; /** Must varname match exactly, or must it be a prefix? */
  1409. } getinfo_item_t;
  1410. #define ITEM(name, fn, desc) { name, getinfo_helper_##fn, desc, 0 }
  1411. #define PREFIX(name, fn, desc) { name, getinfo_helper_##fn, desc, 1 }
  1412. #define DOC(name, desc) { name, NULL, desc, 0 }
  1413. /** Table mapping questions accepted by GETINFO to the functions that know how
  1414. * to answer them. */
  1415. static const getinfo_item_t getinfo_items[] = {
  1416. ITEM("version", misc, "The current version of Tor."),
  1417. ITEM("config-file", misc, "Current location of the \"torrc\" file."),
  1418. ITEM("accounting/bytes", accounting,
  1419. "Number of bytes read/written so far in the accounting interval."),
  1420. ITEM("accounting/bytes-left", accounting,
  1421. "Number of bytes left to write/read so far in the accounting interval."),
  1422. ITEM("accounting/enabled", accounting, "Is accounting currently enabled?"),
  1423. ITEM("accounting/hibernating", accounting, "Are we hibernating or awake?"),
  1424. ITEM("accounting/interval-start", accounting,
  1425. "Time when the accounting period starts."),
  1426. ITEM("accounting/interval-end", accounting,
  1427. "Time when the accounting period ends."),
  1428. ITEM("accounting/interval-wake", accounting,
  1429. "Time to wake up in this accounting period."),
  1430. ITEM("helper-nodes", entry_guards, NULL), /* deprecated */
  1431. ITEM("entry-guards", entry_guards,
  1432. "Which nodes are we using as entry guards?"),
  1433. ITEM("fingerprint", misc, NULL),
  1434. PREFIX("config/", config, "Current configuration values."),
  1435. DOC("config/names",
  1436. "List of configuration options, types, and documentation."),
  1437. ITEM("info/names", misc,
  1438. "List of GETINFO options, types, and documentation."),
  1439. ITEM("events/names", misc,
  1440. "Events that the controller can ask for with SETEVENTS."),
  1441. ITEM("features/names", misc, "What arguments can USEFEATURE take?"),
  1442. PREFIX("desc/id/", dir, "Router descriptors by ID."),
  1443. PREFIX("desc/name/", dir, "Router descriptors by nickname."),
  1444. ITEM("desc/all-recent", dir,
  1445. "All non-expired, non-superseded router descriptors."),
  1446. ITEM("ns/all", networkstatus,
  1447. "Brief summary of router status (v2 directory format)"),
  1448. PREFIX("ns/id/", networkstatus,
  1449. "Brief summary of router status by ID (v2 directory format)."),
  1450. PREFIX("ns/name/", networkstatus,
  1451. "Brief summary of router status by nickname (v2 directory format)."),
  1452. PREFIX("unregisterd-servers-", dirserv_unregistered, NULL),
  1453. ITEM("network-status", dir,
  1454. "Brief summary of router status (v1 directory format)"),
  1455. ITEM("circuit-status", events, "List of current circuits originating here."),
  1456. ITEM("stream-status", events,"List of current streams."),
  1457. ITEM("orconn-status", events, "A list of current OR connections."),
  1458. PREFIX("addr-mappings/", events, NULL),
  1459. DOC("addr-mappings/all", "Current address mappings."),
  1460. DOC("addr-mappings/cache", "Current cached DNS replies."),
  1461. DOC("addr-mappings/config", "Current address mappings from configuration."),
  1462. DOC("addr-mappings/control", "Current address mappings from controller."),
  1463. ITEM("address", misc, "IP address of this Tor host, if we can guess it."),
  1464. ITEM("dir-usage", misc, "Breakdown of bytes transferred over DirPort."),
  1465. PREFIX("dir/server/", dir,"Router descriptors as retrieved from a DirPort."),
  1466. PREFIX("dir/status/", dir,"Networkstatus docs as retrieved from a DirPort."),
  1467. PREFIX("exit-policy/default", policies,
  1468. "The default value appended to the configured exit policy."),
  1469. { NULL, NULL, NULL, 0 }
  1470. };
  1471. /** Allocate and return a list of recognized GETINFO options. */
  1472. static char *
  1473. list_getinfo_options(void)
  1474. {
  1475. int i;
  1476. char buf[300];
  1477. smartlist_t *lines = smartlist_create();
  1478. char *ans;
  1479. for (i = 0; getinfo_items[i].varname; ++i) {
  1480. if (!getinfo_items[i].desc)
  1481. continue;
  1482. tor_snprintf(buf, sizeof(buf), "%s%s -- %s\n",
  1483. getinfo_items[i].varname,
  1484. getinfo_items[i].is_prefix ? "*" : "",
  1485. getinfo_items[i].desc);
  1486. smartlist_add(lines, tor_strdup(buf));
  1487. }
  1488. smartlist_sort_strings(lines);
  1489. ans = smartlist_join_strings(lines, "", 0, NULL);
  1490. SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
  1491. smartlist_free(lines);
  1492. return ans;
  1493. }
  1494. /** Lookup the 'getinfo' entry <b>question</b>, and return
  1495. * the answer in <b>*answer</b> (or NULL if key not recognized).
  1496. * Return 0 if success or unrecognized, or -1 if recognized but
  1497. * internal error. */
  1498. static int
  1499. handle_getinfo_helper(control_connection_t *control_conn,
  1500. const char *question, char **answer)
  1501. {
  1502. int i;
  1503. *answer = NULL; /* unrecognized key by default */
  1504. for (i = 0; getinfo_items[i].varname; ++i) {
  1505. int match;
  1506. if (getinfo_items[i].is_prefix)
  1507. match = !strcmpstart(question, getinfo_items[i].varname);
  1508. else
  1509. match = !strcmp(question, getinfo_items[i].varname);
  1510. if (match) {
  1511. tor_assert(getinfo_items[i].fn);
  1512. return getinfo_items[i].fn(control_conn, question, answer);
  1513. }
  1514. }
  1515. return 0; /* unrecognized */
  1516. }
  1517. /** Called when we receive a GETINFO command. Try to fetch all requested
  1518. * information, and reply with information or error message. */
  1519. static int
  1520. handle_control_getinfo(control_connection_t *conn, uint32_t len,
  1521. const char *body)
  1522. {
  1523. smartlist_t *questions = NULL;
  1524. smartlist_t *answers = NULL;
  1525. smartlist_t *unrecognized = NULL;
  1526. char *msg = NULL, *ans = NULL;
  1527. (void) len; /* body is nul-terminated, so it's safe to ignore the length. */
  1528. questions = smartlist_create();
  1529. smartlist_split_string(questions, body, " ",
  1530. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1531. answers = smartlist_create();
  1532. unrecognized = smartlist_create();
  1533. SMARTLIST_FOREACH(questions, const char *, q,
  1534. {
  1535. if (handle_getinfo_helper(conn, q, &ans) < 0) {
  1536. connection_write_str_to_buf("551 Internal error\r\n", conn);
  1537. goto done;
  1538. }
  1539. if (!ans) {
  1540. smartlist_add(unrecognized, (char*)q);
  1541. } else {
  1542. smartlist_add(answers, tor_strdup(q));
  1543. smartlist_add(answers, ans);
  1544. }
  1545. });
  1546. if (smartlist_len(unrecognized)) {
  1547. int i;
  1548. for (i=0; i < smartlist_len(unrecognized)-1; ++i)
  1549. connection_printf_to_buf(conn,
  1550. "552-Unrecognized key \"%s\"\r\n",
  1551. (char*)smartlist_get(unrecognized, i));
  1552. connection_printf_to_buf(conn,
  1553. "552 Unrecognized key \"%s\"\r\n",
  1554. (char*)smartlist_get(unrecognized, i));
  1555. goto done;
  1556. }
  1557. if (1) {
  1558. int i;
  1559. for (i = 0; i < smartlist_len(answers); i += 2) {
  1560. char *k = smartlist_get(answers, i);
  1561. char *v = smartlist_get(answers, i+1);
  1562. if (!strchr(v, '\n') && !strchr(v, '\r')) {
  1563. connection_printf_to_buf(conn, "250-%s=", k);
  1564. connection_write_str_to_buf(v, conn);
  1565. connection_write_str_to_buf("\r\n", conn);
  1566. } else {
  1567. char *esc = NULL;
  1568. size_t len;
  1569. len = write_escaped_data(v, strlen(v), 1, &esc);
  1570. connection_printf_to_buf(conn, "250+%s=\r\n", k);
  1571. connection_write_to_buf(esc, len, TO_CONN(conn));
  1572. tor_free(esc);
  1573. }
  1574. }
  1575. connection_write_str_to_buf("250 OK\r\n", conn);
  1576. }
  1577. done:
  1578. if (answers) {
  1579. SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
  1580. smartlist_free(answers);
  1581. }
  1582. if (questions) {
  1583. SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
  1584. smartlist_free(questions);
  1585. }
  1586. smartlist_free(unrecognized);
  1587. tor_free(msg);
  1588. return 0;
  1589. }
  1590. /** If *<b>string</b> contains a recognized purpose (for
  1591. * circuits if <b>for_circuits</b> is 1, else for routers),
  1592. * possibly prefaced with the string "purpose=", then assign it
  1593. * and return 0. Otherwise return -1.
  1594. *
  1595. * If it's prefaced with "purpose=", then set *<b>string</b> to
  1596. * the remainder of the string. */
  1597. static int
  1598. get_purpose(char **string, int for_circuits, uint8_t *purpose)
  1599. {
  1600. if (!strcmpstart(*string, "purpose="))
  1601. *string += strlen("purpose=");
  1602. if (!strcmp(*string, "general"))
  1603. *purpose = for_circuits ? CIRCUIT_PURPOSE_C_GENERAL :
  1604. ROUTER_PURPOSE_GENERAL;
  1605. else if (!strcmp(*string, "controller"))
  1606. *purpose = for_circuits ? CIRCUIT_PURPOSE_CONTROLLER :
  1607. ROUTER_PURPOSE_GENERAL;
  1608. else { /* not a recognized purpose */
  1609. return -1;
  1610. }
  1611. return 0;
  1612. }
  1613. /** Called when we get an EXTENDCIRCUIT message. Try to extend the listed
  1614. * circuit, and report success or failure. */
  1615. static int
  1616. handle_control_extendcircuit(control_connection_t *conn, uint32_t len,
  1617. const char *body)
  1618. {
  1619. smartlist_t *router_nicknames=NULL, *routers=NULL;
  1620. origin_circuit_t *circ = NULL;
  1621. int zero_circ;
  1622. uint8_t intended_purpose = CIRCUIT_PURPOSE_C_GENERAL;
  1623. (void) len;
  1624. router_nicknames = smartlist_create();
  1625. if (1) {
  1626. smartlist_t *args;
  1627. args = smartlist_create();
  1628. smartlist_split_string(args, body, " ",
  1629. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1630. if (smartlist_len(args)<2) {
  1631. connection_printf_to_buf(conn,
  1632. "512 Missing argument to EXTENDCIRCUIT\r\n");
  1633. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1634. smartlist_free(args);
  1635. goto done;
  1636. }
  1637. zero_circ = !strcmp("0", (char*)smartlist_get(args,0));
  1638. if (!zero_circ && !(circ = get_circ(smartlist_get(args,0)))) {
  1639. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  1640. (char*)smartlist_get(args, 0));
  1641. }
  1642. smartlist_split_string(router_nicknames, smartlist_get(args,1), ",", 0, 0);
  1643. if (zero_circ && smartlist_len(args)>2) {
  1644. char *purp = smartlist_get(args,2);
  1645. if (get_purpose(&purp, 1, &intended_purpose) < 0) {
  1646. connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n", purp);
  1647. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1648. smartlist_free(args);
  1649. goto done;
  1650. }
  1651. }
  1652. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1653. smartlist_free(args);
  1654. if (!zero_circ && !circ) {
  1655. goto done;
  1656. }
  1657. }
  1658. routers = smartlist_create();
  1659. SMARTLIST_FOREACH(router_nicknames, const char *, n,
  1660. {
  1661. routerinfo_t *r = router_get_by_nickname(n, 1);
  1662. if (!r) {
  1663. connection_printf_to_buf(conn, "552 No such router \"%s\"\r\n", n);
  1664. goto done;
  1665. }
  1666. smartlist_add(routers, r);
  1667. });
  1668. if (!smartlist_len(routers)) {
  1669. connection_write_str_to_buf("512 No router names provided\r\n", conn);
  1670. goto done;
  1671. }
  1672. if (zero_circ) {
  1673. /* start a new circuit */
  1674. circ = origin_circuit_init(intended_purpose, 0, 0, 0, 0);
  1675. }
  1676. /* now circ refers to something that is ready to be extended */
  1677. SMARTLIST_FOREACH(routers, routerinfo_t *, r,
  1678. {
  1679. extend_info_t *info = extend_info_from_router(r);
  1680. circuit_append_new_exit(circ, info);
  1681. extend_info_free(info);
  1682. });
  1683. /* now that we've populated the cpath, start extending */
  1684. if (zero_circ) {
  1685. int err_reason = 0;
  1686. if ((err_reason = circuit_handle_first_hop(circ)) < 0) {
  1687. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  1688. connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn);
  1689. goto done;
  1690. }
  1691. } else {
  1692. if (circ->_base.state == CIRCUIT_STATE_OPEN) {
  1693. int err_reason = 0;
  1694. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
  1695. if ((err_reason = circuit_send_next_onion_skin(circ)) < 0) {
  1696. log_info(LD_CONTROL,
  1697. "send_next_onion_skin failed; circuit marked for closing.");
  1698. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  1699. connection_write_str_to_buf("551 Couldn't send onion skinr\n", conn);
  1700. goto done;
  1701. }
  1702. }
  1703. }
  1704. connection_printf_to_buf(conn, "250 EXTENDED %lu\r\n",
  1705. (unsigned long)circ->global_identifier);
  1706. done:
  1707. SMARTLIST_FOREACH(router_nicknames, char *, n, tor_free(n));
  1708. smartlist_free(router_nicknames);
  1709. if (routers)
  1710. smartlist_free(routers);
  1711. return 0;
  1712. }
  1713. /** Called when we get a SETCIRCUITPURPOSE (if <b>for_circuits</b>
  1714. * is 1) or SETROUTERPURPOSE message. If we can find
  1715. * the circuit/router and it's a valid purpose, change it. */
  1716. static int
  1717. handle_control_setpurpose(control_connection_t *conn, int for_circuits,
  1718. uint32_t len, const char *body)
  1719. {
  1720. origin_circuit_t *circ = NULL;
  1721. routerinfo_t *ri = NULL;
  1722. uint8_t new_purpose;
  1723. smartlist_t *args = smartlist_create();
  1724. (void) len; /* body is nul-terminated, so it's safe to ignore the length. */
  1725. smartlist_split_string(args, body, " ",
  1726. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1727. if (smartlist_len(args)<2) {
  1728. connection_printf_to_buf(conn,
  1729. "512 Missing argument to SET%sPURPOSE\r\n",
  1730. for_circuits ? "CIRCUIT" : "ROUTER");
  1731. goto done;
  1732. }
  1733. if (for_circuits) {
  1734. if (!(circ = get_circ(smartlist_get(args,0)))) {
  1735. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  1736. (char*)smartlist_get(args, 0));
  1737. goto done;
  1738. }
  1739. } else {
  1740. if (!(ri = router_get_by_nickname(smartlist_get(args,0), 0))) {
  1741. connection_printf_to_buf(conn, "552 Unknown router \"%s\"\r\n",
  1742. (char*)smartlist_get(args, 0));
  1743. goto done;
  1744. }
  1745. }
  1746. {
  1747. char *purp = smartlist_get(args,1);
  1748. if (get_purpose(&purp, for_circuits, &new_purpose) < 0) {
  1749. connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n", purp);
  1750. goto done;
  1751. }
  1752. }
  1753. if (for_circuits)
  1754. circ->_base.purpose = new_purpose;
  1755. else
  1756. ri->purpose = new_purpose;
  1757. connection_write_str_to_buf("250 OK\r\n", conn);
  1758. done:
  1759. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1760. smartlist_free(args);
  1761. return 0;
  1762. }
  1763. /** Called when we get an ATTACHSTREAM message. Try to attach the requested
  1764. * stream, and report success or failure. */
  1765. static int
  1766. handle_control_attachstream(control_connection_t *conn, uint32_t len,
  1767. const char *body)
  1768. {
  1769. edge_connection_t *ap_conn = NULL;
  1770. origin_circuit_t *circ = NULL;
  1771. int zero_circ;
  1772. (void) len;
  1773. if (1) {
  1774. smartlist_t *args;
  1775. args = smartlist_create();
  1776. smartlist_split_string(args, body, " ",
  1777. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1778. if (smartlist_len(args)<2) {
  1779. connection_printf_to_buf(conn,
  1780. "512 Missing argument to ATTACHSTREAM\r\n");
  1781. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1782. smartlist_free(args);
  1783. return 0;
  1784. }
  1785. zero_circ = !strcmp("0", (char*)smartlist_get(args,1));
  1786. if (!(ap_conn = get_stream(smartlist_get(args, 0)))) {
  1787. connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
  1788. (char*)smartlist_get(args, 0));
  1789. } else if (!zero_circ && !(circ = get_circ(smartlist_get(args, 1)))) {
  1790. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  1791. (char*)smartlist_get(args, 1));
  1792. }
  1793. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1794. smartlist_free(args);
  1795. if (!ap_conn || (!zero_circ && !circ))
  1796. return 0;
  1797. }
  1798. if (ap_conn->_base.state != AP_CONN_STATE_CONTROLLER_WAIT &&
  1799. ap_conn->_base.state != AP_CONN_STATE_CONNECT_WAIT &&
  1800. ap_conn->_base.state != AP_CONN_STATE_RESOLVE_WAIT) {
  1801. connection_write_str_to_buf(
  1802. "555 Connection is not managed by controller.\r\n",
  1803. conn);
  1804. return 0;
  1805. }
  1806. /* Do we need to detach it first? */
  1807. if (ap_conn->_base.state != AP_CONN_STATE_CONTROLLER_WAIT) {
  1808. circuit_t *tmpcirc = circuit_get_by_edge_conn(ap_conn);
  1809. connection_edge_end(ap_conn, END_STREAM_REASON_TIMEOUT,
  1810. ap_conn->cpath_layer);
  1811. /* Un-mark it as ending, since we're going to reuse it. */
  1812. ap_conn->_base.edge_has_sent_end = 0;
  1813. ap_conn->end_reason = 0;
  1814. if (tmpcirc)
  1815. circuit_detach_stream(tmpcirc,ap_conn);
  1816. ap_conn->_base.state = AP_CONN_STATE_CONTROLLER_WAIT;
  1817. }
  1818. if (circ && (circ->_base.state != CIRCUIT_STATE_OPEN)) {
  1819. connection_write_str_to_buf(
  1820. "551 Can't attach stream to non-open, origin circuit\r\n",
  1821. conn);
  1822. return 0;
  1823. }
  1824. if (circ && circuit_get_cpath_len(circ) < 2) {
  1825. connection_write_str_to_buf(
  1826. "551 Can't attach stream to one-hop circuit.\r\n", conn);
  1827. return 0;
  1828. }
  1829. if (connection_ap_handshake_rewrite_and_attach(ap_conn, circ) < 0) {
  1830. connection_write_str_to_buf("551 Unable to attach stream\r\n", conn);
  1831. return 0;
  1832. }
  1833. send_control_done(conn);
  1834. return 0;
  1835. }
  1836. /** Called when we get a POSTDESCRIPTOR message. Try to learn the provided
  1837. * descriptor, and report success or failure. */
  1838. static int
  1839. handle_control_postdescriptor(control_connection_t *conn, uint32_t len,
  1840. const char *body)
  1841. {
  1842. char *desc;
  1843. const char *msg=NULL;
  1844. uint8_t purpose = ROUTER_PURPOSE_GENERAL;
  1845. if (1) {
  1846. char *cp = memchr(body, '\n', len);
  1847. smartlist_t *args = smartlist_create();
  1848. tor_assert(cp);
  1849. *cp++ = '\0';
  1850. smartlist_split_string(args, body, " ",
  1851. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1852. if (smartlist_len(args)) {
  1853. char *purp = smartlist_get(args,0);
  1854. if (get_purpose(&purp, 0, &purpose) < 0) {
  1855. connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n",
  1856. purp);
  1857. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1858. smartlist_free(args);
  1859. return 0;
  1860. }
  1861. }
  1862. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1863. smartlist_free(args);
  1864. read_escaped_data(cp, len-(cp-body), 1, &desc);
  1865. }
  1866. switch (router_load_single_router(desc, purpose, &msg)) {
  1867. case -1:
  1868. if (!msg) msg = "Could not parse descriptor";
  1869. connection_printf_to_buf(conn, "554 %s\r\n", msg);
  1870. break;
  1871. case 0:
  1872. if (!msg) msg = "Descriptor not added";
  1873. connection_printf_to_buf(conn, "251 %s\r\n",msg);
  1874. break;
  1875. case 1:
  1876. send_control_done(conn);
  1877. break;
  1878. }
  1879. tor_free(desc);
  1880. return 0;
  1881. }
  1882. /** Called when we receive a REDIRECTSTERAM command. Try to change the target
  1883. * address of the named AP stream, and report success or failure. */
  1884. static int
  1885. handle_control_redirectstream(control_connection_t *conn, uint32_t len,
  1886. const char *body)
  1887. {
  1888. edge_connection_t *ap_conn = NULL;
  1889. char *new_addr = NULL;
  1890. uint16_t new_port = 0;
  1891. (void) len;
  1892. if (1) {
  1893. smartlist_t *args;
  1894. args = smartlist_create();
  1895. smartlist_split_string(args, body, " ",
  1896. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1897. if (smartlist_len(args) < 2)
  1898. connection_printf_to_buf(conn,
  1899. "512 Missing argument to REDIRECTSTREAM\r\n");
  1900. else if (!(ap_conn = get_stream(smartlist_get(args, 0)))
  1901. || !ap_conn->socks_request) {
  1902. connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
  1903. (char*)smartlist_get(args, 0));
  1904. } else {
  1905. int ok;
  1906. if (smartlist_len(args) > 2) { /* they included a port too */
  1907. new_port = (uint16_t) tor_parse_ulong(smartlist_get(args, 2),
  1908. 10, 1, 65535, &ok, NULL);
  1909. }
  1910. if (!ok) {
  1911. connection_printf_to_buf(conn, "512 Cannot parse port \"%s\"\r\n",
  1912. (char*)smartlist_get(args, 2));
  1913. } else {
  1914. new_addr = tor_strdup(smartlist_get(args, 1));
  1915. }
  1916. }
  1917. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1918. smartlist_free(args);
  1919. if (!new_addr)
  1920. return 0;
  1921. }
  1922. strlcpy(ap_conn->socks_request->address, new_addr,
  1923. sizeof(ap_conn->socks_request->address));
  1924. if (new_port)
  1925. ap_conn->socks_request->port = new_port;
  1926. tor_free(new_addr);
  1927. send_control_done(conn);
  1928. return 0;
  1929. }
  1930. /** Called when we get a CLOSESTREAM command; try to close the named stream
  1931. * and report success or failure. */
  1932. static int
  1933. handle_control_closestream(control_connection_t *conn, uint32_t len,
  1934. const char *body)
  1935. {
  1936. edge_connection_t *ap_conn=NULL;
  1937. uint8_t reason=0;
  1938. (void) len;
  1939. if (1) {
  1940. smartlist_t *args;
  1941. int ok;
  1942. args = smartlist_create();
  1943. smartlist_split_string(args, body, " ",
  1944. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1945. if (smartlist_len(args)<2)
  1946. connection_printf_to_buf(conn,
  1947. "512 Missing argument to CLOSESTREAM\r\n");
  1948. else if (!(ap_conn = get_stream(smartlist_get(args, 0))))
  1949. connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
  1950. (char*)smartlist_get(args, 0));
  1951. else {
  1952. reason = (uint8_t) tor_parse_ulong(smartlist_get(args,1), 10, 0, 255,
  1953. &ok, NULL);
  1954. if (!ok) {
  1955. connection_printf_to_buf(conn, "552 Unrecognized reason \"%s\"\r\n",
  1956. (char*)smartlist_get(args, 1));
  1957. ap_conn = NULL;
  1958. }
  1959. }
  1960. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  1961. smartlist_free(args);
  1962. if (!ap_conn)
  1963. return 0;
  1964. }
  1965. connection_mark_unattached_ap(ap_conn, reason);
  1966. send_control_done(conn);
  1967. return 0;
  1968. }
  1969. /** Called when we get a CLOSECIRCUIT command; try to close the named circuit
  1970. * and report success or failure. */
  1971. static int
  1972. handle_control_closecircuit(control_connection_t *conn, uint32_t len,
  1973. const char *body)
  1974. {
  1975. origin_circuit_t *circ = NULL;
  1976. int safe = 0;
  1977. (void) len;
  1978. if (1) {
  1979. smartlist_t *args;
  1980. args = smartlist_create();
  1981. smartlist_split_string(args, body, " ",
  1982. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1983. if (smartlist_len(args)<1)
  1984. connection_printf_to_buf(conn,
  1985. "512 Missing argument to CLOSECIRCUIT\r\n");
  1986. else if (!(circ=get_circ(smartlist_get(args, 0))))
  1987. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  1988. (char*)smartlist_get(args, 0));
  1989. else {
  1990. int i;
  1991. for (i=1; i < smartlist_len(args); ++i) {
  1992. if (!strcasecmp(smartlist_get(args, i), "IfUnused"))
  1993. safe = 1;
  1994. else
  1995. log_info(LD_CONTROL, "Skipping unknown option %s",
  1996. (char*)smartlist_get(args,i));
  1997. }
  1998. }
  1999. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2000. smartlist_free(args);
  2001. if (!circ)
  2002. return 0;
  2003. }
  2004. if (!safe || !circ->p_streams) {
  2005. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_REQUESTED);
  2006. }
  2007. send_control_done(conn);
  2008. return 0;
  2009. }
  2010. /** Called when we get a USEFEATURE command: parse the feature list, and
  2011. * set up the control_connection's options properly. */
  2012. static int
  2013. handle_control_usefeature(control_connection_t *conn,
  2014. uint32_t len,
  2015. const char *body)
  2016. {
  2017. smartlist_t *args;
  2018. int verbose_names = 0, extended_events = 0;
  2019. int bad = 0;
  2020. (void) len; /* body is nul-terminated; it's safe to ignore the length */
  2021. args = smartlist_create();
  2022. smartlist_split_string(args, body, " ",
  2023. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2024. SMARTLIST_FOREACH(args, const char *, arg, {
  2025. if (!strcasecmp(arg, "VERBOSE_NAMES"))
  2026. verbose_names = 1;
  2027. else if (!strcasecmp(arg, "EXTENDED_EVENTS")) /* <- documented */
  2028. extended_events = 1;
  2029. else if (!strcasecmp(arg, "EXTENDED_FORMAT")) {
  2030. /* remove this in 0.1.2.4; EXTENDED_FORMAT only ever worked for a
  2031. * little while during 0.1.2.2-alpha-dev. */
  2032. log_warn(LD_GENERAL,
  2033. "EXTENDED_FORMAT is deprecated; use EXTENDED_EVENTS "
  2034. "instead.");
  2035. extended_events = 1;
  2036. } else {
  2037. connection_printf_to_buf(conn, "552 Unrecognized feature \"%s\"\r\n",
  2038. arg);
  2039. bad = 1;
  2040. break;
  2041. }
  2042. });
  2043. if (!bad) {
  2044. if (verbose_names) {
  2045. conn->use_long_names = 1;
  2046. control_update_global_event_mask();
  2047. }
  2048. if (extended_events)
  2049. conn->use_extended_events = 1;
  2050. send_control_done(conn);
  2051. }
  2052. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2053. smartlist_free(args);
  2054. return 0;
  2055. }
  2056. /** Called when <b>conn</b> has no more bytes left on its outbuf. */
  2057. int
  2058. connection_control_finished_flushing(control_connection_t *conn)
  2059. {
  2060. tor_assert(conn);
  2061. connection_stop_writing(TO_CONN(conn));
  2062. return 0;
  2063. }
  2064. /** Called when <b>conn</b> has gotten its socket closed. */
  2065. int
  2066. connection_control_reached_eof(control_connection_t *conn)
  2067. {
  2068. tor_assert(conn);
  2069. log_info(LD_CONTROL,"Control connection reached EOF. Closing.");
  2070. connection_mark_for_close(TO_CONN(conn));
  2071. return 0;
  2072. }
  2073. /** Called when data has arrived on a v1 control connection: Try to fetch
  2074. * commands from conn->inbuf, and execute them.
  2075. */
  2076. int
  2077. connection_control_process_inbuf(control_connection_t *conn)
  2078. {
  2079. size_t data_len;
  2080. int cmd_len;
  2081. char *args;
  2082. tor_assert(conn);
  2083. tor_assert(conn->_base.state == CONTROL_CONN_STATE_OPEN ||
  2084. conn->_base.state == CONTROL_CONN_STATE_NEEDAUTH);
  2085. if (!conn->incoming_cmd) {
  2086. conn->incoming_cmd = tor_malloc(1024);
  2087. conn->incoming_cmd_len = 1024;
  2088. conn->incoming_cmd_cur_len = 0;
  2089. }
  2090. if (conn->_base.state == CONTROL_CONN_STATE_NEEDAUTH &&
  2091. peek_buf_has_control0_command(conn->_base.inbuf)) {
  2092. /* Detect v0 commands and send a "no more v0" message. */
  2093. size_t body_len;
  2094. char buf[128];
  2095. set_uint16(buf+2, htons(0x0000)); /* type == error */
  2096. set_uint16(buf+4, htons(0x0001)); /* code == internal error */
  2097. strlcpy(buf+6, "The v0 control protocol no longer supported in "VERSION"; "
  2098. "use Tor 0.1.2.x or upgrade your controller", sizeof(buf)-6);
  2099. body_len = 2+strlen(buf+6)+2; /* code, msg, nul. */
  2100. set_uint16(buf+0, htons(body_len));
  2101. connection_write_to_buf(buf, 4+body_len, TO_CONN(conn));
  2102. connection_mark_for_close(TO_CONN(conn));
  2103. conn->_base.hold_open_until_flushed = 1;
  2104. return 0;
  2105. }
  2106. again:
  2107. while (1) {
  2108. size_t last_idx;
  2109. int r;
  2110. /* First, fetch a line. */
  2111. do {
  2112. data_len = conn->incoming_cmd_len - conn->incoming_cmd_cur_len;
  2113. r = fetch_from_buf_line(conn->_base.inbuf,
  2114. conn->incoming_cmd+conn->incoming_cmd_cur_len,
  2115. &data_len);
  2116. if (r == 0)
  2117. /* Line not all here yet. Wait. */
  2118. return 0;
  2119. else if (r == -1) {
  2120. while (conn->incoming_cmd_len < data_len+conn->incoming_cmd_cur_len)
  2121. conn->incoming_cmd_len *= 2;
  2122. conn->incoming_cmd = tor_realloc(conn->incoming_cmd,
  2123. conn->incoming_cmd_len);
  2124. }
  2125. } while (r != 1);
  2126. tor_assert(data_len);
  2127. last_idx = conn->incoming_cmd_cur_len;
  2128. conn->incoming_cmd_cur_len += data_len;
  2129. /* We have appended a line to incoming_cmd. Is the command done? */
  2130. if (last_idx == 0 && *conn->incoming_cmd != '+')
  2131. /* One line command, didn't start with '+'. */
  2132. break;
  2133. if (last_idx+3 == conn->incoming_cmd_cur_len &&
  2134. !memcmp(conn->incoming_cmd + last_idx, ".\r\n", 3)) {
  2135. /* Just appended ".\r\n"; we're done. Remove it. */
  2136. conn->incoming_cmd_cur_len -= 3;
  2137. break;
  2138. }
  2139. /* Otherwise, read another line. */
  2140. }
  2141. data_len = conn->incoming_cmd_cur_len;
  2142. /* Okay, we now have a command sitting on conn->incoming_cmd. See if we
  2143. * recognize it.
  2144. */
  2145. cmd_len = 0;
  2146. while ((size_t)cmd_len < data_len
  2147. && !TOR_ISSPACE(conn->incoming_cmd[cmd_len]))
  2148. ++cmd_len;
  2149. data_len -= cmd_len;
  2150. conn->incoming_cmd[cmd_len]='\0';
  2151. args = conn->incoming_cmd+cmd_len+1;
  2152. while (*args == ' ' || *args == '\t') {
  2153. ++args;
  2154. --data_len;
  2155. }
  2156. if (!strcasecmp(conn->incoming_cmd, "QUIT")) {
  2157. connection_write_str_to_buf("250 closing connection\r\n", conn);
  2158. connection_mark_for_close(TO_CONN(conn));
  2159. return 0;
  2160. }
  2161. if (conn->_base.state == CONTROL_CONN_STATE_NEEDAUTH &&
  2162. strcasecmp(conn->incoming_cmd, "AUTHENTICATE")) {
  2163. connection_write_str_to_buf("514 Authentication required.\r\n", conn);
  2164. conn->incoming_cmd_cur_len = 0;
  2165. goto again;
  2166. }
  2167. if (!strcasecmp(conn->incoming_cmd, "SETCONF")) {
  2168. if (handle_control_setconf(conn, data_len, args))
  2169. return -1;
  2170. } else if (!strcasecmp(conn->incoming_cmd, "RESETCONF")) {
  2171. if (handle_control_resetconf(conn, data_len, args))
  2172. return -1;
  2173. } else if (!strcasecmp(conn->incoming_cmd, "GETCONF")) {
  2174. if (handle_control_getconf(conn, data_len, args))
  2175. return -1;
  2176. } else if (!strcasecmp(conn->incoming_cmd, "SETEVENTS")) {
  2177. if (handle_control_setevents(conn, data_len, args))
  2178. return -1;
  2179. } else if (!strcasecmp(conn->incoming_cmd, "AUTHENTICATE")) {
  2180. if (handle_control_authenticate(conn, data_len, args))
  2181. return -1;
  2182. } else if (!strcasecmp(conn->incoming_cmd, "SAVECONF")) {
  2183. if (handle_control_saveconf(conn, data_len, args))
  2184. return -1;
  2185. } else if (!strcasecmp(conn->incoming_cmd, "SIGNAL")) {
  2186. if (handle_control_signal(conn, data_len, args))
  2187. return -1;
  2188. } else if (!strcasecmp(conn->incoming_cmd, "MAPADDRESS")) {
  2189. if (handle_control_mapaddress(conn, data_len, args))
  2190. return -1;
  2191. } else if (!strcasecmp(conn->incoming_cmd, "GETINFO")) {
  2192. if (handle_control_getinfo(conn, data_len, args))
  2193. return -1;
  2194. } else if (!strcasecmp(conn->incoming_cmd, "EXTENDCIRCUIT")) {
  2195. if (handle_control_extendcircuit(conn, data_len, args))
  2196. return -1;
  2197. } else if (!strcasecmp(conn->incoming_cmd, "SETCIRCUITPURPOSE")) {
  2198. if (handle_control_setpurpose(conn, 1, data_len, args))
  2199. return -1;
  2200. } else if (!strcasecmp(conn->incoming_cmd, "SETROUTERPURPOSE")) {
  2201. if (handle_control_setpurpose(conn, 0, data_len, args))
  2202. return -1;
  2203. } else if (!strcasecmp(conn->incoming_cmd, "ATTACHSTREAM")) {
  2204. if (handle_control_attachstream(conn, data_len, args))
  2205. return -1;
  2206. } else if (!strcasecmp(conn->incoming_cmd, "+POSTDESCRIPTOR")) {
  2207. if (handle_control_postdescriptor(conn, data_len, args))
  2208. return -1;
  2209. } else if (!strcasecmp(conn->incoming_cmd, "REDIRECTSTREAM")) {
  2210. if (handle_control_redirectstream(conn, data_len, args))
  2211. return -1;
  2212. } else if (!strcasecmp(conn->incoming_cmd, "CLOSESTREAM")) {
  2213. if (handle_control_closestream(conn, data_len, args))
  2214. return -1;
  2215. } else if (!strcasecmp(conn->incoming_cmd, "CLOSECIRCUIT")) {
  2216. if (handle_control_closecircuit(conn, data_len, args))
  2217. return -1;
  2218. } else if (!strcasecmp(conn->incoming_cmd, "USEFEATURE")) {
  2219. if (handle_control_usefeature(conn, data_len, args))
  2220. return -1;
  2221. } else {
  2222. connection_printf_to_buf(conn, "510 Unrecognized command \"%s\"\r\n",
  2223. conn->incoming_cmd);
  2224. }
  2225. conn->incoming_cmd_cur_len = 0;
  2226. goto again;
  2227. }
  2228. /** Convert a numeric reason for destroying a circuit into a string for a
  2229. * CIRCUIT event. */
  2230. static const char *
  2231. circuit_end_reason_to_string(int reason)
  2232. {
  2233. if (reason >= 0 && reason & END_CIRC_REASON_FLAG_REMOTE)
  2234. reason &= ~END_CIRC_REASON_FLAG_REMOTE;
  2235. switch (reason) {
  2236. case END_CIRC_AT_ORIGIN:
  2237. /* This shouldn't get passed here; it's a catch-all reason. */
  2238. return "ORIGIN";
  2239. case END_CIRC_REASON_NONE:
  2240. /* This shouldn't get passed here; it's a catch-all reason. */
  2241. return "NONE";
  2242. case END_CIRC_REASON_TORPROTOCOL:
  2243. return "TORPROTOCOL";
  2244. case END_CIRC_REASON_INTERNAL:
  2245. return "INTERNAL";
  2246. case END_CIRC_REASON_REQUESTED:
  2247. return "REQUESTED";
  2248. case END_CIRC_REASON_HIBERNATING:
  2249. return "HIBERNATING";
  2250. case END_CIRC_REASON_RESOURCELIMIT:
  2251. return "RESOURCELIMIT";
  2252. case END_CIRC_REASON_CONNECTFAILED:
  2253. return "CONNECTFAILED";
  2254. case END_CIRC_REASON_OR_IDENTITY:
  2255. return "OR_IDENTITY";
  2256. case END_CIRC_REASON_OR_CONN_CLOSED:
  2257. return "OR_CONN_CLOSED";
  2258. case END_CIRC_REASON_FINISHED:
  2259. return "FINISHED";
  2260. case END_CIRC_REASON_TIMEOUT:
  2261. return "TIMEOUT";
  2262. case END_CIRC_REASON_DESTROYED:
  2263. return "DESTROYED";
  2264. case END_CIRC_REASON_NOPATH:
  2265. return "NOPATH";
  2266. case END_CIRC_REASON_NOSUCHSERVICE:
  2267. return "NOSUCHSERVICE";
  2268. default:
  2269. log_warn(LD_BUG, "Unrecognized reason code %d", (int)reason);
  2270. return NULL;
  2271. }
  2272. }
  2273. /** Something has happened to circuit <b>circ</b>: tell any interested
  2274. * control connections. */
  2275. int
  2276. control_event_circuit_status(origin_circuit_t *circ, circuit_status_event_t tp,
  2277. int reason_code)
  2278. {
  2279. char *path=NULL;
  2280. if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS))
  2281. return 0;
  2282. tor_assert(circ);
  2283. if (EVENT_IS_INTERESTING1S(EVENT_CIRCUIT_STATUS))
  2284. path = circuit_list_path(circ,0);
  2285. if (1) {
  2286. const char *status;
  2287. char reason_buf[64];
  2288. int providing_reason=0;
  2289. switch (tp)
  2290. {
  2291. case CIRC_EVENT_LAUNCHED: status = "LAUNCHED"; break;
  2292. case CIRC_EVENT_BUILT: status = "BUILT"; break;
  2293. case CIRC_EVENT_EXTENDED: status = "EXTENDED"; break;
  2294. case CIRC_EVENT_FAILED: status = "FAILED"; break;
  2295. case CIRC_EVENT_CLOSED: status = "CLOSED"; break;
  2296. default:
  2297. log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
  2298. return 0;
  2299. }
  2300. if (tp == CIRC_EVENT_FAILED || tp == CIRC_EVENT_CLOSED) {
  2301. const char *reason_str = circuit_end_reason_to_string(reason_code);
  2302. char *reason = NULL;
  2303. providing_reason=1;
  2304. if (!reason_str) {
  2305. reason = tor_malloc(16);
  2306. tor_snprintf(reason, 16, "UNKNOWN_%d", reason_code);
  2307. reason_str = reason;
  2308. }
  2309. if (reason_code > 0 && reason_code & END_CIRC_REASON_FLAG_REMOTE) {
  2310. tor_snprintf(reason_buf, sizeof(reason_buf),
  2311. "REASON=DESTROYED REMOTE_REASON=%s", reason_str);
  2312. } else {
  2313. tor_snprintf(reason_buf, sizeof(reason_buf),
  2314. "REASON=%s", reason_str);
  2315. }
  2316. tor_free(reason);
  2317. }
  2318. if (EVENT_IS_INTERESTING1S(EVENT_CIRCUIT_STATUS)) {
  2319. const char *sp = strlen(path) ? " " : "";
  2320. if (providing_reason)
  2321. send_control_event_extended(EVENT_CIRCUIT_STATUS, SHORT_NAMES,
  2322. "650 CIRC %lu %s%s%s@%s\r\n",
  2323. (unsigned long)circ->global_identifier,
  2324. status, sp, path, reason_buf);
  2325. else
  2326. send_control_event_extended(EVENT_CIRCUIT_STATUS, SHORT_NAMES,
  2327. "650 CIRC %lu %s%s%s\r\n",
  2328. (unsigned long)circ->global_identifier,
  2329. status, sp, path);
  2330. }
  2331. if (EVENT_IS_INTERESTING1L(EVENT_CIRCUIT_STATUS)) {
  2332. char *vpath = circuit_list_path_for_controller(circ);
  2333. const char *sp = strlen(vpath) ? " " : "";
  2334. if (providing_reason)
  2335. send_control_event_extended(EVENT_CIRCUIT_STATUS, LONG_NAMES,
  2336. "650 CIRC %lu %s%s%s@%s\r\n",
  2337. (unsigned long)circ->global_identifier,
  2338. status, sp, vpath, reason_buf);
  2339. else
  2340. send_control_event_extended(EVENT_CIRCUIT_STATUS, LONG_NAMES,
  2341. "650 CIRC %lu %s%s%s\r\n",
  2342. (unsigned long)circ->global_identifier,
  2343. status, sp, vpath);
  2344. tor_free(vpath);
  2345. }
  2346. }
  2347. tor_free(path);
  2348. return 0;
  2349. }
  2350. /** Given an AP connection <b>conn</b> and a <b>len</b>-character buffer
  2351. * <b>buf</b>, determine the address:port combination requested on
  2352. * <b>conn</b>, and write it to <b>buf</b>. Return 0 on success, -1 on
  2353. * failure. */
  2354. static int
  2355. write_stream_target_to_buf(edge_connection_t *conn, char *buf, size_t len)
  2356. {
  2357. char buf2[256];
  2358. if (conn->chosen_exit_name)
  2359. if (tor_snprintf(buf2, sizeof(buf2), ".%s.exit", conn->chosen_exit_name)<0)
  2360. return -1;
  2361. if (tor_snprintf(buf, len, "%s%s%s:%d",
  2362. conn->socks_request->address,
  2363. conn->chosen_exit_name ? buf2 : "",
  2364. !conn->chosen_exit_name &&
  2365. connection_edge_is_rendezvous_stream(conn) ? ".onion" : "",
  2366. conn->socks_request->port)<0)
  2367. return -1;
  2368. return 0;
  2369. }
  2370. /** Convert the reason for ending a stream <b>reason</b> into the format used
  2371. * in STREAM events. Return NULL if the reason is unrecognized. */
  2372. static const char *
  2373. stream_end_reason_to_string(int reason)
  2374. {
  2375. reason &= END_STREAM_REASON_MASK;
  2376. switch (reason) {
  2377. case END_STREAM_REASON_MISC: return "MISC";
  2378. case END_STREAM_REASON_RESOLVEFAILED: return "RESOLVEFAILED";
  2379. case END_STREAM_REASON_CONNECTREFUSED: return "CONNECTREFUSED";
  2380. case END_STREAM_REASON_EXITPOLICY: return "EXITPOLICY";
  2381. case END_STREAM_REASON_DESTROY: return "DESTROY";
  2382. case END_STREAM_REASON_DONE: return "DONE";
  2383. case END_STREAM_REASON_TIMEOUT: return "TIMEOUT";
  2384. case END_STREAM_REASON_HIBERNATING: return "HIBERNATING";
  2385. case END_STREAM_REASON_INTERNAL: return "INTERNAL";
  2386. case END_STREAM_REASON_RESOURCELIMIT: return "RESOURCELIMIT";
  2387. case END_STREAM_REASON_CONNRESET: return "CONNRESET";
  2388. case END_STREAM_REASON_TORPROTOCOL: return "TORPROTOCOL";
  2389. case END_STREAM_REASON_NOTDIRECTORY: return "NOTDIRECTORY";
  2390. case END_STREAM_REASON_CANT_ATTACH: return "CANT_ATTACH";
  2391. case END_STREAM_REASON_NET_UNREACHABLE: return "NET_UNREACHABLE";
  2392. case END_STREAM_REASON_SOCKSPROTOCOL: return "SOCKS_PROTOCOL";
  2393. default: return NULL;
  2394. }
  2395. }
  2396. /** Something has happened to the stream associated with AP connection
  2397. * <b>conn</b>: tell any interested control connections. */
  2398. int
  2399. control_event_stream_status(edge_connection_t *conn, stream_status_event_t tp,
  2400. int reason_code)
  2401. {
  2402. char buf[256];
  2403. tor_assert(conn->socks_request);
  2404. if (!EVENT_IS_INTERESTING(EVENT_STREAM_STATUS))
  2405. return 0;
  2406. if (tp == STREAM_EVENT_CLOSED &&
  2407. (reason_code & END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED))
  2408. return 0;
  2409. write_stream_target_to_buf(conn, buf, sizeof(buf));
  2410. if (1) {
  2411. char reason_buf[64];
  2412. const char *status;
  2413. circuit_t *circ;
  2414. origin_circuit_t *origin_circ = NULL;
  2415. reason_buf[0] = '\0';
  2416. switch (tp)
  2417. {
  2418. case STREAM_EVENT_SENT_CONNECT: status = "SENTCONNECT"; break;
  2419. case STREAM_EVENT_SENT_RESOLVE: status = "SENTRESOLVE"; break;
  2420. case STREAM_EVENT_SUCCEEDED: status = "SUCCEEDED"; break;
  2421. case STREAM_EVENT_FAILED: status = "FAILED"; break;
  2422. case STREAM_EVENT_CLOSED: status = "CLOSED"; break;
  2423. case STREAM_EVENT_NEW: status = "NEW"; break;
  2424. case STREAM_EVENT_NEW_RESOLVE: status = "NEWRESOLVE"; break;
  2425. case STREAM_EVENT_FAILED_RETRIABLE: status = "DETACHED"; break;
  2426. case STREAM_EVENT_REMAP: status = "REMAP"; break;
  2427. default:
  2428. log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
  2429. return 0;
  2430. }
  2431. if (reason_code && (tp == STREAM_EVENT_FAILED ||
  2432. tp == STREAM_EVENT_CLOSED ||
  2433. tp == STREAM_EVENT_FAILED_RETRIABLE)) {
  2434. const char *reason_str = stream_end_reason_to_string(reason_code);
  2435. char *r = NULL;
  2436. if (!reason_str) {
  2437. r = tor_malloc(16);
  2438. tor_snprintf(r, 16, "UNKNOWN_%d", reason_code);
  2439. reason_str = r;
  2440. }
  2441. if (reason_code & END_STREAM_REASON_FLAG_REMOTE)
  2442. tor_snprintf(reason_buf, sizeof(reason_buf),
  2443. "REASON=END REMOTE_REASON=%s", reason_str);
  2444. else
  2445. tor_snprintf(reason_buf, sizeof(reason_buf),
  2446. "REASON=%s", reason_str);
  2447. tor_free(r);
  2448. } else if (reason_code && tp == STREAM_EVENT_REMAP) {
  2449. switch (reason_code) {
  2450. case REMAP_STREAM_SOURCE_CACHE:
  2451. strlcpy(reason_buf, "SOURCE=CACHE", sizeof(reason_buf));
  2452. break;
  2453. case REMAP_STREAM_SOURCE_EXIT:
  2454. strlcpy(reason_buf, "SOURCE=EXIT", sizeof(reason_buf));
  2455. break;
  2456. default:
  2457. tor_snprintf(reason_buf, sizeof(reason_buf), "REASON=UNKNOWN_%d",
  2458. reason_code);
  2459. break;
  2460. }
  2461. }
  2462. circ = circuit_get_by_edge_conn(conn);
  2463. if (circ && CIRCUIT_IS_ORIGIN(circ))
  2464. origin_circ = TO_ORIGIN_CIRCUIT(circ);
  2465. send_control_event_extended(EVENT_STREAM_STATUS, ALL_NAMES,
  2466. "650 STREAM %lu %s %lu %s@%s\r\n",
  2467. (unsigned long)conn->global_identifier, status,
  2468. origin_circ?
  2469. (unsigned long)origin_circ->global_identifier : 0ul,
  2470. buf, reason_buf);
  2471. /* XXX need to specify its intended exit, etc? */
  2472. }
  2473. return 0;
  2474. }
  2475. /** Figure out the best name for the target router of an OR connection
  2476. * <b>conn</b>, and write it into the <b>len</b>-character buffer
  2477. * <b>name</b>. Use verbose names if <b>long_names</b> is set. */
  2478. static void
  2479. orconn_target_get_name(int long_names,
  2480. char *name, size_t len, or_connection_t *conn)
  2481. {
  2482. if (! long_names) {
  2483. if (conn->nickname)
  2484. strlcpy(name, conn->nickname, len);
  2485. else
  2486. tor_snprintf(name, len, "%s:%d",
  2487. conn->_base.address, conn->_base.port);
  2488. } else {
  2489. routerinfo_t *ri = router_get_by_digest(conn->identity_digest);
  2490. if (ri) {
  2491. tor_assert(len > MAX_VERBOSE_NICKNAME_LEN);
  2492. router_get_verbose_nickname(name, ri);
  2493. } else if (! tor_digest_is_zero(conn->identity_digest)) {
  2494. name[0] = '$';
  2495. base16_encode(name+1, len-1, conn->identity_digest,
  2496. DIGEST_LEN);
  2497. } else {
  2498. tor_snprintf(name, len, "%s:%d",
  2499. conn->_base.address, conn->_base.port);
  2500. }
  2501. }
  2502. }
  2503. /** Convert a TOR_TLS_* error code into an END_OR_CONN_* reason. */
  2504. int
  2505. control_tls_error_to_reason(int e)
  2506. {
  2507. switch (e) {
  2508. case TOR_TLS_ERROR_IO:
  2509. return END_OR_CONN_REASON_TLS_IO_ERROR;
  2510. case TOR_TLS_ERROR_CONNREFUSED:
  2511. return END_OR_CONN_REASON_TCP_REFUSED;
  2512. case TOR_TLS_ERROR_CONNRESET:
  2513. return END_OR_CONN_REASON_TLS_CONNRESET;
  2514. case TOR_TLS_ERROR_NO_ROUTE:
  2515. return END_OR_CONN_REASON_TLS_NO_ROUTE;
  2516. case TOR_TLS_ERROR_TIMEOUT:
  2517. return END_OR_CONN_REASON_TLS_TIMEOUT;
  2518. case TOR_TLS_WANTREAD:
  2519. case TOR_TLS_WANTWRITE:
  2520. case TOR_TLS_CLOSE:
  2521. case TOR_TLS_DONE:
  2522. return END_OR_CONN_REASON_DONE;
  2523. default:
  2524. return END_OR_CONN_REASON_TLS_MISC;
  2525. }
  2526. }
  2527. /** Convert the reason for ending an OR connection <b>r</b> into the format
  2528. * used in ORCONN events. Return NULL if the reason is unrecognized. */
  2529. static const char *
  2530. or_conn_end_reason_to_string(int r)
  2531. {
  2532. switch (r) {
  2533. case END_OR_CONN_REASON_DONE:
  2534. return "REASON=DONE";
  2535. case END_OR_CONN_REASON_TCP_REFUSED:
  2536. return "REASON=CONNECTREFUSED";
  2537. case END_OR_CONN_REASON_OR_IDENTITY:
  2538. return "REASON=IDENTITY";
  2539. case END_OR_CONN_REASON_TLS_CONNRESET:
  2540. return "REASON=CONNECTRESET";
  2541. case END_OR_CONN_REASON_TLS_TIMEOUT:
  2542. return "REASON=TIMEOUT";
  2543. case END_OR_CONN_REASON_TLS_NO_ROUTE:
  2544. return "REASON=NOROUTE";
  2545. case END_OR_CONN_REASON_TLS_IO_ERROR:
  2546. return "REASON=IOERROR";
  2547. case END_OR_CONN_REASON_TLS_MISC:
  2548. return "REASON=MISC";
  2549. case 0:
  2550. return "";
  2551. default:
  2552. log_warn(LD_BUG, "Unrecognized or_conn reason code %d", r);
  2553. return "REASON=BOGUS";
  2554. }
  2555. }
  2556. /** Called when the status of an OR connection <b>conn</b> changes: tell any
  2557. * interested control connections. <b>tp</b> is the new status for the
  2558. * connection. If <b>conn</b> has just closed or failed, then <b>reason</b>
  2559. * may be the reason why.
  2560. */
  2561. int
  2562. control_event_or_conn_status(or_connection_t *conn, or_conn_status_event_t tp,
  2563. int reason)
  2564. {
  2565. int ncircs = 0;
  2566. if (!EVENT_IS_INTERESTING(EVENT_OR_CONN_STATUS))
  2567. return 0;
  2568. if (1) {
  2569. const char *status;
  2570. char name[128];
  2571. char ncircs_buf[32] = {0}; /* > 8 + log10(2^32)=10 + 2 */
  2572. switch (tp)
  2573. {
  2574. case OR_CONN_EVENT_LAUNCHED: status = "LAUNCHED"; break;
  2575. case OR_CONN_EVENT_CONNECTED: status = "CONNECTED"; break;
  2576. case OR_CONN_EVENT_FAILED: status = "FAILED"; break;
  2577. case OR_CONN_EVENT_CLOSED: status = "CLOSED"; break;
  2578. case OR_CONN_EVENT_NEW: status = "NEW"; break;
  2579. default:
  2580. log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
  2581. return 0;
  2582. }
  2583. ncircs = circuit_count_pending_on_or_conn(conn);
  2584. ncircs += conn->n_circuits;
  2585. if (ncircs && (tp == OR_CONN_EVENT_FAILED || tp == OR_CONN_EVENT_CLOSED)) {
  2586. tor_snprintf(ncircs_buf, sizeof(ncircs_buf), "%sNCIRCS=%d",
  2587. reason ? " " : "", ncircs);
  2588. }
  2589. if (EVENT_IS_INTERESTING1S(EVENT_OR_CONN_STATUS)) {
  2590. orconn_target_get_name(0, name, sizeof(name), conn);
  2591. send_control_event_extended(EVENT_OR_CONN_STATUS, SHORT_NAMES,
  2592. "650 ORCONN %s %s@%s%s\r\n",
  2593. name, status,
  2594. or_conn_end_reason_to_string(reason), ncircs_buf);
  2595. }
  2596. if (EVENT_IS_INTERESTING1L(EVENT_OR_CONN_STATUS)) {
  2597. orconn_target_get_name(1, name, sizeof(name), conn);
  2598. send_control_event_extended(EVENT_OR_CONN_STATUS, LONG_NAMES,
  2599. "650 ORCONN %s %s@%s%s\r\n",
  2600. name, status,
  2601. or_conn_end_reason_to_string(reason), ncircs_buf);
  2602. }
  2603. }
  2604. return 0;
  2605. }
  2606. /** A second or more has elapsed: tell any interested control
  2607. * connections how much bandwidth streams have used. */
  2608. int
  2609. control_event_stream_bandwidth_used(void)
  2610. {
  2611. connection_t **carray;
  2612. edge_connection_t *conn;
  2613. int n, i;
  2614. if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED)) {
  2615. get_connection_array(&carray, &n);
  2616. for (i = 0; i < n; ++i) {
  2617. if (carray[i]->type != CONN_TYPE_AP)
  2618. continue;
  2619. conn = TO_EDGE_CONN(carray[i]);
  2620. if (!conn->n_read && !conn->n_written)
  2621. continue;
  2622. send_control_event(EVENT_STREAM_BANDWIDTH_USED, ALL_NAMES,
  2623. "650 STREAM_BW %lu %lu %lu\r\n",
  2624. (unsigned long)conn->global_identifier,
  2625. (unsigned long)conn->n_read,
  2626. (unsigned long)conn->n_written);
  2627. conn->n_written = conn->n_read = 0;
  2628. }
  2629. }
  2630. return 0;
  2631. }
  2632. /** A second or more has elapsed: tell any interested control
  2633. * connections how much bandwidth we used. */
  2634. int
  2635. control_event_bandwidth_used(uint32_t n_read, uint32_t n_written)
  2636. {
  2637. if (EVENT_IS_INTERESTING(EVENT_BANDWIDTH_USED)) {
  2638. send_control_event(EVENT_BANDWIDTH_USED, ALL_NAMES,
  2639. "650 BW %lu %lu\r\n",
  2640. (unsigned long)n_read,
  2641. (unsigned long)n_written);
  2642. }
  2643. return 0;
  2644. }
  2645. /** Called when we are sending a log message to the controllers: suspend
  2646. * sending further log messages to the controllers until we're done. Used by
  2647. * CONN_LOG_PROTECT. */
  2648. void
  2649. disable_control_logging(void)
  2650. {
  2651. ++disable_log_messages;
  2652. }
  2653. /** We're done sending a log message to the controllers: re-enable controller
  2654. * logging. Used by CONN_LOG_PROTECT. */
  2655. void
  2656. enable_control_logging(void)
  2657. {
  2658. if (--disable_log_messages < 0)
  2659. tor_assert(0);
  2660. }
  2661. /** We got a log message: tell any interested control connections. */
  2662. void
  2663. control_event_logmsg(int severity, uint32_t domain, const char *msg)
  2664. {
  2665. int event;
  2666. if (disable_log_messages)
  2667. return;
  2668. if (domain == LD_BUG && EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL) &&
  2669. severity <= LOG_NOTICE) {
  2670. char *esc = esc_for_log(msg);
  2671. ++disable_log_messages;
  2672. control_event_general_status(severity, "BUG REASON=\"%s\"", esc);
  2673. --disable_log_messages;
  2674. tor_free(esc);
  2675. }
  2676. event = log_severity_to_event(severity);
  2677. if (event >= 0 && EVENT_IS_INTERESTING(event)) {
  2678. char *b = NULL;
  2679. const char *s;
  2680. if (strchr(msg, '\n')) {
  2681. char *cp;
  2682. b = tor_strdup(msg);
  2683. for (cp = b; *cp; ++cp)
  2684. if (*cp == '\r' || *cp == '\n')
  2685. *cp = ' ';
  2686. }
  2687. switch (severity) {
  2688. case LOG_DEBUG: s = "DEBUG"; break;
  2689. case LOG_INFO: s = "INFO"; break;
  2690. case LOG_NOTICE: s = "NOTICE"; break;
  2691. case LOG_WARN: s = "WARN"; break;
  2692. case LOG_ERR: s = "ERR"; break;
  2693. default: s = "UnknownLogSeverity"; break;
  2694. }
  2695. ++disable_log_messages;
  2696. send_control_event(event, ALL_NAMES, "650 %s %s\r\n", s, b?b:msg);
  2697. --disable_log_messages;
  2698. tor_free(b);
  2699. }
  2700. }
  2701. /** Called whenever we receive new router descriptors: tell any
  2702. * interested control connections. <b>routers</b> is a list of
  2703. * DIGEST_LEN-byte identity digests.
  2704. */
  2705. int
  2706. control_event_descriptors_changed(smartlist_t *routers)
  2707. {
  2708. size_t len;
  2709. char *msg;
  2710. smartlist_t *identities = NULL;
  2711. char buf[HEX_DIGEST_LEN+1];
  2712. if (!EVENT_IS_INTERESTING(EVENT_NEW_DESC))
  2713. return 0;
  2714. if (EVENT_IS_INTERESTING1S(EVENT_NEW_DESC)) {
  2715. identities = smartlist_create();
  2716. SMARTLIST_FOREACH(routers, routerinfo_t *, r,
  2717. {
  2718. base16_encode(buf,sizeof(buf),r->cache_info.identity_digest,DIGEST_LEN);
  2719. smartlist_add(identities, tor_strdup(buf));
  2720. });
  2721. }
  2722. if (EVENT_IS_INTERESTING1S(EVENT_NEW_DESC)) {
  2723. char *ids = smartlist_join_strings(identities, " ", 0, &len);
  2724. size_t len = strlen(ids)+32;
  2725. msg = tor_malloc(len);
  2726. tor_snprintf(msg, len, "650 NEWDESC %s\r\n", ids);
  2727. send_control_event_string(EVENT_NEW_DESC, SHORT_NAMES|ALL_FORMATS, msg);
  2728. tor_free(ids);
  2729. tor_free(msg);
  2730. }
  2731. if (EVENT_IS_INTERESTING1L(EVENT_NEW_DESC)) {
  2732. smartlist_t *names = smartlist_create();
  2733. char *ids;
  2734. size_t len;
  2735. SMARTLIST_FOREACH(routers, routerinfo_t *, ri, {
  2736. char *b = tor_malloc(MAX_VERBOSE_NICKNAME_LEN+1);
  2737. router_get_verbose_nickname(b, ri);
  2738. smartlist_add(names, b);
  2739. });
  2740. ids = smartlist_join_strings(names, " ", 0, &len);
  2741. len = strlen(ids)+32;
  2742. msg = tor_malloc(len);
  2743. tor_snprintf(msg, len, "650 NEWDESC %s\r\n", ids);
  2744. send_control_event_string(EVENT_NEW_DESC, LONG_NAMES|ALL_FORMATS, msg);
  2745. tor_free(ids);
  2746. tor_free(msg);
  2747. SMARTLIST_FOREACH(names, char *, cp, tor_free(cp));
  2748. smartlist_free(names);
  2749. }
  2750. if (identities) {
  2751. SMARTLIST_FOREACH(identities, char *, cp, tor_free(cp));
  2752. smartlist_free(identities);
  2753. }
  2754. return 0;
  2755. }
  2756. /** Called whenever an address mapping on <b>from<b> from changes to <b>to</b>.
  2757. * <b>expires</b> values less than 3 are special; see connection_edge.c. */
  2758. int
  2759. control_event_address_mapped(const char *from, const char *to, time_t expires)
  2760. {
  2761. if (!EVENT_IS_INTERESTING(EVENT_ADDRMAP))
  2762. return 0;
  2763. if (expires < 3)
  2764. send_control_event(EVENT_ADDRMAP, ALL_NAMES,
  2765. "650 ADDRMAP %s %s NEVER\r\n", from, to);
  2766. else {
  2767. char buf[ISO_TIME_LEN+1];
  2768. format_local_iso_time(buf,expires);
  2769. send_control_event(EVENT_ADDRMAP, ALL_NAMES,
  2770. "650 ADDRMAP %s %s \"%s\"\r\n",
  2771. from, to, buf);
  2772. }
  2773. return 0;
  2774. }
  2775. /** The authoritative dirserver has received a new descriptor that
  2776. * has passed basic syntax checks and is properly self-signed.
  2777. *
  2778. * Notify any interested party of the new descriptor and what has
  2779. * been done with it, and also optionally give an explanation/reason. */
  2780. int
  2781. control_event_or_authdir_new_descriptor(const char *action,
  2782. const char *descriptor,
  2783. const char *msg)
  2784. {
  2785. char firstline[1024];
  2786. char *buf;
  2787. int totallen;
  2788. char *esc = NULL;
  2789. size_t esclen;
  2790. if (!EVENT_IS_INTERESTING(EVENT_AUTHDIR_NEWDESCS))
  2791. return 0;
  2792. tor_snprintf(firstline, sizeof(firstline),
  2793. "650+AUTHDIR_NEWDESC=\r\n%s\r\n%s\r\n",
  2794. action,
  2795. msg ? msg : "");
  2796. /* Escape the server descriptor properly */
  2797. esclen = write_escaped_data(descriptor, strlen(descriptor), 1, &esc);
  2798. totallen = strlen(firstline) + esclen + 1;
  2799. buf = tor_malloc(totallen);
  2800. strlcpy(buf, firstline, totallen);
  2801. strlcpy(buf+strlen(firstline), esc, totallen);
  2802. send_control_event_string(EVENT_AUTHDIR_NEWDESCS, ALL_NAMES|ALL_FORMATS,
  2803. buf);
  2804. tor_free(esc);
  2805. tor_free(buf);
  2806. return 0;
  2807. }
  2808. /** Called when the local_routerstatus_ts <b>statuses</b> have changed: sends
  2809. * an NS event to any controller that cares. */
  2810. int
  2811. control_event_networkstatus_changed(smartlist_t *statuses)
  2812. {
  2813. smartlist_t *strs;
  2814. char *s;
  2815. if (!EVENT_IS_INTERESTING(EVENT_NS) || !smartlist_len(statuses))
  2816. return 0;
  2817. strs = smartlist_create();
  2818. smartlist_add(strs, tor_strdup("650+NS\r\n"));
  2819. SMARTLIST_FOREACH(statuses, local_routerstatus_t *, rs,
  2820. {
  2821. s = networkstatus_getinfo_helper_single(&rs->status);
  2822. if (!s) continue;
  2823. smartlist_add(strs, s);
  2824. });
  2825. smartlist_add(strs, tor_strdup("\r\n.\r\n"));
  2826. s = smartlist_join_strings(strs, "", 0, NULL);
  2827. SMARTLIST_FOREACH(strs, char *, cp, tor_free(cp));
  2828. smartlist_free(strs);
  2829. send_control_event_string(EVENT_NS, ALL_NAMES|ALL_FORMATS, s);
  2830. tor_free(s);
  2831. return 0;
  2832. }
  2833. /** Called when a single local_routerstatus_t has changed: Sends an NS event
  2834. * to any countroller that cares. */
  2835. int
  2836. control_event_networkstatus_changed_single(local_routerstatus_t *rs)
  2837. {
  2838. smartlist_t *statuses;
  2839. int r;
  2840. if (!EVENT_IS_INTERESTING(EVENT_NS))
  2841. return 0;
  2842. statuses = smartlist_create();
  2843. smartlist_add(statuses, rs);
  2844. r = control_event_networkstatus_changed(statuses);
  2845. smartlist_free(statuses);
  2846. return r;
  2847. }
  2848. /** Our own router descriptor has changed; tell any controllers that care.
  2849. */
  2850. int
  2851. control_event_my_descriptor_changed(void)
  2852. {
  2853. send_control_event(EVENT_DESCCHANGED, ALL_NAMES, "650 DESCCHANGED\r\n");
  2854. return 0;
  2855. }
  2856. /** Helper: sends a status event where <b>type</b> is one of
  2857. * EVENT_STATUS_{GENERAL,CLIENT,SERVER}, where <b>severity</b> is one of
  2858. * LOG_{NOTICE,WARN,ERR}, and where <b>format</b> is a printf-style format
  2859. * string corresponding to <b>args</b>. */
  2860. static int
  2861. control_event_status(int type, int severity, const char *format, va_list args)
  2862. {
  2863. char format_buf[160];
  2864. const char *status, *sev;
  2865. switch (type) {
  2866. case EVENT_STATUS_GENERAL:
  2867. status = "STATUS_GENERAL";
  2868. break;
  2869. case EVENT_STATUS_CLIENT:
  2870. status = "STATUS_CLIENT";
  2871. break;
  2872. case EVENT_STATUS_SERVER:
  2873. status = "STATUS_SEVER";
  2874. break;
  2875. default:
  2876. log_warn(LD_BUG, "Unrecognized status type %d", type);
  2877. return -1;
  2878. }
  2879. switch (severity) {
  2880. case LOG_NOTICE:
  2881. sev = "NOTICE";
  2882. break;
  2883. case LOG_WARN:
  2884. sev = "WARN";
  2885. break;
  2886. case LOG_ERR:
  2887. sev = "ERR";
  2888. break;
  2889. default:
  2890. log_warn(LD_BUG, "Unrecognized status severity %d", severity);
  2891. return -1;
  2892. }
  2893. if (tor_snprintf(format_buf, sizeof(format_buf), "650 %s %s %s\r\n",
  2894. status, sev, format)<0) {
  2895. log_warn(LD_BUG, "Format string too long.");
  2896. return -1;
  2897. }
  2898. send_control_event_impl(type, ALL_NAMES|ALL_FORMATS, 0, format_buf, args);
  2899. return 0;
  2900. }
  2901. /** Format and send an EVENT_STATUS_GENERAL event whose main text is obtained
  2902. * by formatting the arguments using the printf-style <b>format</b>. */
  2903. int
  2904. control_event_general_status(int severity, const char *format, ...)
  2905. {
  2906. va_list ap;
  2907. int r;
  2908. if (!EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL))
  2909. return 0;
  2910. va_start(ap, format);
  2911. r = control_event_status(EVENT_STATUS_GENERAL, severity, format, ap);
  2912. va_end(ap);
  2913. return r;
  2914. }
  2915. /** Format and send an EVENT_STATUS_CLIENT event whose main text is obtained
  2916. * by formatting the arguments using the printf-style <b>format</b>. */
  2917. int
  2918. control_event_client_status(int severity, const char *format, ...)
  2919. {
  2920. va_list ap;
  2921. int r;
  2922. if (!EVENT_IS_INTERESTING(EVENT_STATUS_CLIENT))
  2923. return 0;
  2924. va_start(ap, format);
  2925. r = control_event_status(EVENT_STATUS_CLIENT, severity, format, ap);
  2926. va_end(ap);
  2927. return r;
  2928. }
  2929. /** Format and send an EVENT_STATUS_SERVER event whose main text is obtained
  2930. * by formatting the arguments using the printf-style <b>format</b>. */
  2931. int
  2932. control_event_server_status(int severity, const char *format, ...)
  2933. {
  2934. va_list ap;
  2935. int r;
  2936. if (!EVENT_IS_INTERESTING(EVENT_STATUS_SERVER))
  2937. return 0;
  2938. va_start(ap, format);
  2939. r = control_event_status(EVENT_STATUS_SERVER, severity, format, ap);
  2940. va_end(ap);
  2941. return r;
  2942. }
  2943. /** Called when the status of an entry guard with the given <b>nickname</b>
  2944. * and identity <b>digest</b> has changed to <b>status</b>: tells any
  2945. * controllers that care. */
  2946. int
  2947. control_event_guard(const char *nickname, const char *digest,
  2948. const char *status)
  2949. {
  2950. char hbuf[HEX_DIGEST_LEN+1];
  2951. base16_encode(hbuf, sizeof(hbuf), digest, DIGEST_LEN);
  2952. if (!EVENT_IS_INTERESTING(EVENT_GUARD))
  2953. return 0;
  2954. if (EVENT_IS_INTERESTING1L(EVENT_GUARD)) {
  2955. char buf[MAX_VERBOSE_NICKNAME_LEN+1];
  2956. routerinfo_t *ri = router_get_by_digest(digest);
  2957. if (ri) {
  2958. router_get_verbose_nickname(buf, ri);
  2959. } else {
  2960. tor_snprintf(buf, sizeof(buf), "$%s~%s", hbuf, nickname);
  2961. }
  2962. send_control_event(EVENT_GUARD, LONG_NAMES,
  2963. "650 GUARD ENTRY %s %s\r\n", buf, status);
  2964. }
  2965. if (EVENT_IS_INTERESTING1S(EVENT_GUARD)) {
  2966. send_control_event(EVENT_GUARD, SHORT_NAMES,
  2967. "650 GUARD ENTRY $%s %s\r\n", hbuf, status);
  2968. }
  2969. return 0;
  2970. }
  2971. /** Choose a random authentication cookie and write it to disk.
  2972. * Anybody who can read the cookie from disk will be considered
  2973. * authorized to use the control connection. */
  2974. int
  2975. init_cookie_authentication(int enabled)
  2976. {
  2977. char fname[512];
  2978. if (!enabled) {
  2979. authentication_cookie_is_set = 0;
  2980. return 0;
  2981. }
  2982. tor_snprintf(fname, sizeof(fname), "%s"PATH_SEPARATOR"control_auth_cookie",
  2983. get_options()->DataDirectory);
  2984. crypto_rand(authentication_cookie, AUTHENTICATION_COOKIE_LEN);
  2985. authentication_cookie_is_set = 1;
  2986. if (write_bytes_to_file(fname, authentication_cookie,
  2987. AUTHENTICATION_COOKIE_LEN, 1)) {
  2988. log_warn(LD_FS,"Error writing authentication cookie.");
  2989. return -1;
  2990. }
  2991. return 0;
  2992. }