control.c 95 KB

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