control.c 130 KB

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