control.c 86 KB

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