control.c 124 KB

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