control.c 106 KB

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