control.c 131 KB

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