control.c 95 KB

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