control.c 113 KB

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