control.c 129 KB

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