control.c 108 KB

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