control.c 126 KB

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