control.c 122 KB

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