control.c 134 KB

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