control.c 103 KB

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