control.c 130 KB

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