config.c 107 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545
  1. /* Copyright 2001 Matej Pfajfar.
  2. * Copyright 2001-2004 Roger Dingledine.
  3. * Copyright 2004-2005 Roger Dingledine, Nick Mathewson. */
  4. /* See LICENSE for licensing information */
  5. /* $Id$ */
  6. const char config_c_id[] = "$Id$";
  7. /**
  8. * \file config.c
  9. * \brief Code to parse and interpret configuration files.
  10. **/
  11. #include "or.h"
  12. #ifdef MS_WINDOWS
  13. #include <shlobj.h>
  14. #endif
  15. #include "../common/aes.h"
  16. /** Enumeration of types which option values can take */
  17. typedef enum config_type_t {
  18. CONFIG_TYPE_STRING = 0, /**< An arbitrary string. */
  19. CONFIG_TYPE_UINT, /**< A non-negative integer less than MAX_INT */
  20. CONFIG_TYPE_INTERVAL, /**< A number of seconds, with optional units*/
  21. CONFIG_TYPE_MEMUNIT, /**< A number of bytes, with optional units*/
  22. CONFIG_TYPE_DOUBLE, /**< A floating-point value */
  23. CONFIG_TYPE_BOOL, /**< A boolean value, expressed as 0 or 1. */
  24. CONFIG_TYPE_ISOTIME, /**< An ISO-formated time relative to GMT. */
  25. CONFIG_TYPE_CSV, /**< A list of strings, separated by commas and optional
  26. * whitespace. */
  27. CONFIG_TYPE_LINELIST, /**< Uninterpreted config lines */
  28. CONFIG_TYPE_LINELIST_S, /**< Uninterpreted, context-sensitive config lines,
  29. * mixed with other keywords. */
  30. CONFIG_TYPE_LINELIST_V, /**< Catch-all "virtual" option to summarize
  31. * context-sensitive config lines when fetching.
  32. */
  33. CONFIG_TYPE_OBSOLETE, /**< Obsolete (ignored) option. */
  34. } config_type_t;
  35. /* An abbreviation for a configuration option allowed on the command line */
  36. typedef struct config_abbrev_t {
  37. const char *abbreviated;
  38. const char *full;
  39. int commandline_only;
  40. } config_abbrev_t;
  41. /* Handy macro for declaring "In the config file or on the command line,
  42. * you can abbreviate <b>tok</b>s as <b>tok</b>". */
  43. #define PLURAL(tok) { #tok, #tok "s", 0 }
  44. /* A list of command-line abbreviations. */
  45. static config_abbrev_t _option_abbrevs[] = {
  46. PLURAL(ExitNode),
  47. PLURAL(EntryNode),
  48. PLURAL(ExcludeNode),
  49. PLURAL(FirewallPort),
  50. PLURAL(LongLivedPort),
  51. PLURAL(HiddenServiceNode),
  52. PLURAL(HiddenServiceExcludeNode),
  53. PLURAL(NumCpu),
  54. PLURAL(RendNode),
  55. PLURAL(RendExcludeNode),
  56. PLURAL(StrictEntryNode),
  57. PLURAL(StrictExitNode),
  58. { "l", "Log", 1},
  59. { "BandwidthRateBytes", "BandwidthRate", 0},
  60. { "BandwidthBurstBytes", "BandwidthBurst", 0},
  61. { "DirFetchPostPeriod", "StatusFetchPeriod", 0},
  62. { "MaxConn", "ConnLimit", 0},
  63. { NULL, NULL , 0},
  64. };
  65. #undef PLURAL
  66. /** A variable allowed in the configuration file or on the command line. */
  67. typedef struct config_var_t {
  68. const char *name; /**< The full keyword (case insensitive). */
  69. config_type_t type; /**< How to interpret the type and turn it into a value. */
  70. off_t var_offset; /**< Offset of the corresponding member of or_options_t. */
  71. const char *initvalue; /**< String (or null) describing initial value. */
  72. const char *description;
  73. } config_var_t;
  74. /** Return the offset of <b>member</b> within the type <b>tp</b>, in bytes */
  75. #define STRUCT_OFFSET(tp, member) ((off_t) (((char*)&((tp*)0)->member)-(char*)0))
  76. /** An entry for config_vars: "The option <b>name</b> has type
  77. * CONFIG_TYPE_<b>conftype</b>, and corresponds to
  78. * or_options_t.<b>member</b>"
  79. */
  80. #define VAR(name,conftype,member,initvalue) \
  81. { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_options_t, member), initvalue, NULL }
  82. /** An entry for config_vars: "The option <b>name</b> is obsolete." */
  83. #define OBSOLETE(name) { name, CONFIG_TYPE_OBSOLETE, 0, NULL, NULL }
  84. /** Array of configuration options. Until we disallow nonstandard
  85. * abbreviations, order is significant, since the first matching option will
  86. * be chosen first.
  87. */
  88. static config_var_t _option_vars[] = {
  89. VAR("AccountingMax", MEMUNIT, AccountingMax, "0 bytes"),
  90. VAR("AccountingMaxKB", UINT, _AccountingMaxKB, "0"),
  91. VAR("AccountingStart", STRING, AccountingStart, NULL),
  92. VAR("Address", STRING, Address, NULL),
  93. VAR("AllowUnverifiedNodes",CSV, AllowUnverifiedNodes, "middle,rendezvous"),
  94. VAR("AssumeReachable", BOOL, AssumeReachable, "0"),
  95. VAR("AuthDirInvalid", LINELIST, AuthDirInvalid, NULL),
  96. VAR("AuthDirReject", LINELIST, AuthDirReject, NULL),
  97. VAR("AuthoritativeDirectory",BOOL, AuthoritativeDir, "0"),
  98. VAR("BandwidthBurst", MEMUNIT, BandwidthBurst, "5 MB"),
  99. VAR("BandwidthRate", MEMUNIT, BandwidthRate, "2 MB"),
  100. VAR("ClientOnly", BOOL, ClientOnly, "0"),
  101. VAR("ConnLimit", UINT, ConnLimit, "1024"),
  102. VAR("ContactInfo", STRING, ContactInfo, NULL),
  103. VAR("ControlPort", UINT, ControlPort, "0"),
  104. VAR("CookieAuthentication",BOOL, CookieAuthentication, "0"),
  105. VAR("DataDirectory", STRING, DataDirectory, NULL),
  106. VAR("DebugLogFile", STRING, DebugLogFile, NULL),
  107. VAR("DirAllowPrivateAddresses",BOOL, DirAllowPrivateAddresses, NULL),
  108. VAR("DirBindAddress", LINELIST, DirBindAddress, NULL),
  109. VAR("DirFetchPeriod", INTERVAL, DirFetchPeriod, "0 seconds"), /** DOCDOC **/
  110. VAR("DirPolicy", LINELIST, DirPolicy, NULL),
  111. VAR("DirPort", UINT, DirPort, "0"),
  112. OBSOLETE("DirPostPeriod"),
  113. VAR("DirServer", LINELIST, DirServers, NULL),
  114. VAR("EntryNodes", STRING, EntryNodes, NULL),
  115. VAR("ExcludeNodes", STRING, ExcludeNodes, NULL),
  116. VAR("ExitNodes", STRING, ExitNodes, NULL),
  117. VAR("ExitPolicy", LINELIST, ExitPolicy, NULL),
  118. VAR("FascistFirewall", BOOL, FascistFirewall, "0"),
  119. VAR("FirewallPorts", CSV, FirewallPorts, ""),
  120. VAR("Group", STRING, Group, NULL),
  121. VAR("HardwareAccel", BOOL, HardwareAccel, "1"),
  122. VAR("HashedControlPassword",STRING, HashedControlPassword, NULL),
  123. VAR("HiddenServiceDir", LINELIST_S, RendConfigLines, NULL),
  124. VAR("HiddenServiceExcludeNodes", LINELIST_S, RendConfigLines, NULL),
  125. VAR("HiddenServiceNodes", LINELIST_S, RendConfigLines, NULL),
  126. VAR("HiddenServiceOptions",LINELIST_V, RendConfigLines, NULL),
  127. VAR("HiddenServicePort", LINELIST_S, RendConfigLines, NULL),
  128. VAR("HttpProxy", STRING, HttpProxy, NULL),
  129. VAR("HttpProxyAuthenticator",STRING, HttpProxyAuthenticator,NULL),
  130. VAR("HttpsProxy", STRING, HttpsProxy, NULL),
  131. VAR("HttpsProxyAuthenticator",STRING,HttpsProxyAuthenticator,NULL),
  132. OBSOLETE("IgnoreVersion"),
  133. VAR("KeepalivePeriod", INTERVAL, KeepalivePeriod, "5 minutes"),
  134. VAR("Log", LINELIST, Logs, NULL),
  135. OBSOLETE("LinkPadding"),
  136. VAR("LogFile", LINELIST_S, OldLogOptions, NULL),
  137. VAR("LogLevel", LINELIST_S, OldLogOptions, NULL),
  138. VAR("LongLivedPorts", CSV, LongLivedPorts, "21,22,706,1863,5050,5190,5222,5223,6667,8300,8888"),
  139. VAR("MapAddress", LINELIST, AddressMap, NULL),
  140. VAR("MaxAdvertisedBandwidth",MEMUNIT,MaxAdvertisedBandwidth,"128 TB"),
  141. VAR("MaxCircuitDirtiness", INTERVAL, MaxCircuitDirtiness, "10 minutes"),
  142. VAR("MaxOnionsPending", UINT, MaxOnionsPending, "100"),
  143. OBSOLETE("MonthlyAccountingStart"),
  144. VAR("MyFamily", STRING, MyFamily, NULL),
  145. VAR("NewCircuitPeriod", INTERVAL, NewCircuitPeriod, "30 seconds"),
  146. /* XXXX 011 change this default on 0.1.1.x */
  147. VAR("NamingAuthoritativeDirectory",BOOL, NamingAuthoritativeDir, "1"),
  148. VAR("Nickname", STRING, Nickname, NULL),
  149. VAR("NoPublish", BOOL, NoPublish, "0"),
  150. VAR("NodeFamily", LINELIST, NodeFamilies, NULL),
  151. VAR("NumCpus", UINT, NumCpus, "1"),
  152. VAR("NumHelperNodes", UINT, NumHelperNodes, "3"),
  153. VAR("ORBindAddress", LINELIST, ORBindAddress, NULL),
  154. VAR("ORPort", UINT, ORPort, "0"),
  155. VAR("OutboundBindAddress", STRING, OutboundBindAddress, NULL),
  156. VAR("PathlenCoinWeight", DOUBLE, PathlenCoinWeight, "0.3"),
  157. VAR("PidFile", STRING, PidFile, NULL),
  158. VAR("ReachableAddresses", LINELIST, ReachableAddresses, NULL),
  159. VAR("RecommendedVersions", LINELIST, RecommendedVersions, NULL),
  160. VAR("RecommendedClientVersions", LINELIST, RecommendedClientVersions, NULL),
  161. VAR("RecommendedServerVersions", LINELIST, RecommendedServerVersions, NULL),
  162. VAR("RedirectExit", LINELIST, RedirectExit, NULL),
  163. VAR("RendExcludeNodes", STRING, RendExcludeNodes, NULL),
  164. VAR("RendNodes", STRING, RendNodes, NULL),
  165. VAR("RendPostPeriod", INTERVAL, RendPostPeriod, "20 minutes"),
  166. VAR("RephistTrackTime", INTERVAL, RephistTrackTime, "24 hours"),
  167. OBSOLETE("RouterFile"),
  168. VAR("RunAsDaemon", BOOL, RunAsDaemon, "0"),
  169. VAR("RunTesting", BOOL, RunTesting, "0"),
  170. VAR("SafeLogging", BOOL, SafeLogging, "1"),
  171. VAR("ShutdownWaitLength", INTERVAL, ShutdownWaitLength, "30 seconds"),
  172. VAR("SocksBindAddress", LINELIST, SocksBindAddress, NULL),
  173. VAR("SocksPolicy", LINELIST, SocksPolicy, NULL),
  174. VAR("SocksPort", UINT, SocksPort, "9050"),
  175. VAR("StatusFetchPeriod", INTERVAL, StatusFetchPeriod, "0 seconds"), /** DOCDOC */
  176. VAR("StrictEntryNodes", BOOL, StrictEntryNodes, "0"),
  177. VAR("StrictExitNodes", BOOL, StrictExitNodes, "0"),
  178. VAR("SysLog", LINELIST_S, OldLogOptions, NULL),
  179. VAR("TrackHostExits", CSV, TrackHostExits, NULL),
  180. VAR("TrackHostExitsExpire",INTERVAL, TrackHostExitsExpire, "30 minutes"),
  181. OBSOLETE("TrafficShaping"),
  182. VAR("UseHelperNodes", BOOL, UseHelperNodes, "0"),
  183. VAR("User", STRING, User, NULL),
  184. VAR("V1AuthoritativeDirectory",BOOL, V1AuthoritativeDir, "0"),
  185. VAR("__LeaveStreamsUnattached", BOOL,LeaveStreamsUnattached, "0"),
  186. { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL, NULL }
  187. };
  188. #undef VAR
  189. #define VAR(name,conftype,member,initvalue) \
  190. { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_state_t, member), initvalue, NULL }
  191. static config_var_t _state_vars[] = {
  192. VAR("AccountingBytesReadInterval", MEMUNIT, AccountingBytesReadInInterval,NULL),
  193. VAR("AccountingBytesWrittenInInterval", MEMUNIT,
  194. AccountingBytesWrittenInInterval, NULL),
  195. VAR("AccountingExpectedUsage", MEMUNIT, AccountingExpectedUsage, NULL),
  196. VAR("AccountingIntervalStart", ISOTIME, AccountingIntervalStart, NULL),
  197. VAR("AccountingSecondsActive", INTERVAL, AccountingSecondsActive, NULL),
  198. VAR("HelperNode", LINELIST_S, HelperNodes, NULL),
  199. VAR("HelperNodeDownSince", LINELIST_S, HelperNodes, NULL),
  200. VAR("HelperNodeUnlistedSince", LINELIST_S, HelperNodes, NULL),
  201. VAR("HelperNodes", LINELIST_V, HelperNodes, NULL),
  202. VAR("LastWritten", ISOTIME, LastWritten, NULL),
  203. { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL, NULL }
  204. };
  205. #undef VAR
  206. #undef OBSOLETE
  207. /** DOCDOC*/
  208. typedef struct config_var_description_t {
  209. const char *name;
  210. const char *description;
  211. } config_var_description_t;
  212. static config_var_description_t options_description[] = {
  213. { "Address", "The advertised (external) address we should use." },
  214. // { "AccountingStart", ""},
  215. { NULL, NULL },
  216. };
  217. static config_var_description_t state_description[] = {
  218. { "HelperNode", "One of the nodes we have chosen as a fixed entry" },
  219. { "HelperNodeDownSince",
  220. "The last helper node has been down since this time." },
  221. { "HelperNodeUnlistedSince",
  222. "The last helper node has been unlisted since this time." },
  223. { NULL, NULL },
  224. };
  225. typedef int (*validate_fn_t)(void*);
  226. typedef struct {
  227. size_t size;
  228. uint32_t magic;
  229. off_t magic_offset;
  230. config_abbrev_t *abbrevs;
  231. config_var_t *vars;
  232. validate_fn_t validate_fn;
  233. config_var_description_t *descriptions;
  234. } config_format_t;
  235. #define CHECK(fmt, cfg) do { \
  236. tor_assert(fmt && cfg); \
  237. tor_assert((fmt)->magic == *(uint32_t*)(((char*)(cfg))+fmt->magic_offset)); \
  238. } while (0)
  239. /** Largest allowed config line */
  240. #define CONFIG_LINE_T_MAXLEN 4096
  241. static void config_line_append(config_line_t **lst,
  242. const char *key, const char *val);
  243. static void option_clear(config_format_t *fmt, or_options_t *options,
  244. config_var_t *var);
  245. static void option_reset(config_format_t *fmt, or_options_t *options,
  246. config_var_t *var, int use_defaults);
  247. static void config_free(config_format_t *fmt, void *options);
  248. static int option_is_same(config_format_t *fmt,
  249. or_options_t *o1, or_options_t *o2, const char *name);
  250. static or_options_t *options_dup(config_format_t *fmt, or_options_t *old);
  251. static int options_validate(or_options_t *options);
  252. static int options_act_reversible(or_options_t *old_options);
  253. static int options_act(or_options_t *old_options);
  254. static int options_transition_allowed(or_options_t *old, or_options_t *new);
  255. static int options_transition_affects_workers(or_options_t *old_options,
  256. or_options_t *new_options);
  257. static int options_transition_affects_descriptor(or_options_t *old_options,
  258. or_options_t *new_options);
  259. static int check_nickname_list(const char *lst, const char *name);
  260. static void config_register_addressmaps(or_options_t *options);
  261. static int parse_dir_server_line(const char *line, int validate_only);
  262. static int parse_redirect_line(smartlist_t *result,
  263. config_line_t *line);
  264. static int parse_log_severity_range(const char *range, int *min_out,
  265. int *max_out);
  266. static int convert_log_option(or_options_t *options,
  267. config_line_t *level_opt,
  268. config_line_t *file_opt, int isDaemon);
  269. static int add_single_log_option(or_options_t *options, int minSeverity,
  270. int maxSeverity,
  271. const char *type, const char *fname);
  272. static int normalize_log_options(or_options_t *options);
  273. static int validate_data_directory(or_options_t *options);
  274. static int write_configuration_file(const char *fname, or_options_t *options);
  275. static config_line_t *get_assigned_option(config_format_t *fmt,
  276. or_options_t *options, const char *key);
  277. static void config_init(config_format_t *fmt, void *options);
  278. static int or_state_validate(or_state_t *options);
  279. static uint64_t config_parse_memunit(const char *s, int *ok);
  280. static int config_parse_interval(const char *s, int *ok);
  281. static void print_cvs_version(void);
  282. static void parse_reachable_addresses(void);
  283. static int init_libevent(void);
  284. #if defined(HAVE_EVENT_GET_VERSION) && defined(HAVE_EVENT_GET_METHOD)
  285. static void check_libevent_version(const char *m, const char *v, int server);
  286. #endif
  287. /*static*/ or_options_t *options_new(void);
  288. #define OR_OPTIONS_MAGIC 9090909
  289. static config_format_t options_format = {
  290. sizeof(or_options_t),
  291. OR_OPTIONS_MAGIC,
  292. STRUCT_OFFSET(or_options_t, _magic),
  293. _option_abbrevs,
  294. _option_vars,
  295. (validate_fn_t)options_validate,
  296. options_description
  297. };
  298. #define OR_STATE_MAGIC 0x57A73f57
  299. static config_format_t state_format = {
  300. sizeof(or_state_t),
  301. OR_STATE_MAGIC,
  302. STRUCT_OFFSET(or_state_t, _magic),
  303. NULL,
  304. _state_vars,
  305. (validate_fn_t)or_state_validate,
  306. state_description
  307. };
  308. /*
  309. * Functions to read and write the global options pointer.
  310. */
  311. /** Command-line and config-file options. */
  312. static or_options_t *global_options = NULL;
  313. /** Name of most recently read torrc file. */
  314. static char *torrc_fname = NULL;
  315. /** Persistant serialized state. */
  316. static or_state_t *global_state = NULL;
  317. /** DOCDOC */
  318. static addr_policy_t *reachable_addr_policy = NULL;
  319. static void *
  320. config_alloc(config_format_t *fmt)
  321. {
  322. void *opts = opts = tor_malloc_zero(fmt->size);
  323. *(uint32_t*)(((char*)opts)+fmt->magic_offset) = fmt->magic;
  324. CHECK(fmt, opts);
  325. return opts;
  326. }
  327. /** Return the currently configured options. */
  328. or_options_t *
  329. get_options(void)
  330. {
  331. tor_assert(global_options);
  332. return global_options;
  333. }
  334. /** Change the current global options to contain <b>new_val</b> instead of
  335. * their current value; take action based on the new value; free the old value
  336. * as necessary.
  337. */
  338. int
  339. set_options(or_options_t *new_val)
  340. {
  341. or_options_t *old_options = global_options;
  342. global_options = new_val;
  343. /* Note that we pass the *old* options below, for comparison. It
  344. * pulls the new options directly out of global_options. */
  345. if (options_act_reversible(old_options)<0) {
  346. global_options = old_options;
  347. return -1;
  348. }
  349. if (options_act(old_options) < 0) { /* acting on the options failed. die. */
  350. log_fn(LOG_ERR,"Acting on config options left us in a broken state. Dying.");
  351. exit(1);
  352. }
  353. if (old_options)
  354. config_free(&options_format, old_options);
  355. return 0;
  356. }
  357. void
  358. config_free_all(void)
  359. {
  360. config_free(&options_format, global_options);
  361. tor_free(torrc_fname);
  362. addr_policy_free(reachable_addr_policy);
  363. reachable_addr_policy = NULL;
  364. }
  365. /** If options->SafeLogging is on, return a not very useful string,
  366. * else return address.
  367. */
  368. const char *
  369. safe_str(const char *address)
  370. {
  371. if (get_options()->SafeLogging)
  372. return "[scrubbed]";
  373. else
  374. return address;
  375. }
  376. /** Fetch the active option list, and take actions based on it. All of the
  377. * things we do should survive being done repeatedly. If present,
  378. * <b>old_options</b> contains the previous value of the options.
  379. *
  380. * Return 0 if all goes well, return -1 if things went badly.
  381. */
  382. static int
  383. options_act_reversible(or_options_t *old_options)
  384. {
  385. smartlist_t *new_listeners = smartlist_create();
  386. smartlist_t *replaced_listeners = smartlist_create();
  387. static int libevent_initialized = 0;
  388. or_options_t *options = get_options();
  389. int running_tor = options->command == CMD_RUN_TOR;
  390. int set_conn_limit = 0;
  391. int r = -1;
  392. if (running_tor && options->RunAsDaemon) {
  393. /* No need to roll back, since you can't change the value. */
  394. start_daemon();
  395. }
  396. /* Setuid/setgid as appropriate */
  397. if (options->User || options->Group) {
  398. if (switch_id(options->User, options->Group) != 0) {
  399. /* No need to roll back, since you can't change the value. */
  400. goto done;
  401. }
  402. }
  403. /* Set up libevent. */
  404. if (running_tor && !libevent_initialized) {
  405. if (init_libevent())
  406. goto done;
  407. libevent_initialized = 1;
  408. }
  409. /* Ensure data directory is private; create if possible. */
  410. if (check_private_dir(options->DataDirectory, CPD_CREATE)<0) {
  411. log_fn(LOG_ERR, "Couldn't access/create private data directory \"%s\"",
  412. options->DataDirectory);
  413. /* No need to roll back, since you can't change the value. */
  414. goto done;
  415. }
  416. /* Bail out at this point if we're not going to be a client or server:
  417. * we don't run */
  418. if (options->command != CMD_RUN_TOR)
  419. goto commit;
  420. options->_ConnLimit =
  421. set_max_file_descriptors((unsigned)options->ConnLimit, MAXCONNECTIONS);
  422. if (options->_ConnLimit < 0)
  423. goto rollback;
  424. set_conn_limit = 1;
  425. if (retry_all_listeners(0, replaced_listeners, new_listeners) < 0) {
  426. log_fn(LOG_ERR,"Failed to bind one of the listener ports.");
  427. goto rollback;
  428. }
  429. commit:
  430. r = 0;
  431. SMARTLIST_FOREACH(replaced_listeners, connection_t *, conn,
  432. {
  433. log_fn(LOG_NOTICE, "Closing old %s on %s:%d",
  434. conn_type_to_string(conn->type), conn->address, conn->port);
  435. connection_close_immediate(conn);
  436. connection_mark_for_close(conn);
  437. });
  438. goto done;
  439. rollback:
  440. r = -1;
  441. if (set_conn_limit && old_options)
  442. set_max_file_descriptors((unsigned)old_options->ConnLimit,MAXCONNECTIONS);
  443. SMARTLIST_FOREACH(new_listeners, connection_t *, conn,
  444. {
  445. log_fn(LOG_NOTICE, "Closing %s on %s:%d",
  446. conn_type_to_string(conn->type), conn->address, conn->port);
  447. connection_close_immediate(conn);
  448. connection_mark_for_close(conn);
  449. });
  450. done:
  451. smartlist_free(new_listeners);
  452. smartlist_free(replaced_listeners);
  453. return r;
  454. }
  455. /** Fetch the active option list, and take actions based on it. All of the
  456. * things we do should survive being done repeatedly. If present,
  457. * <b>old_options</b> contains the previous value of the options.
  458. *
  459. * Return 0 if all goes well, return -1 if it's time to die.
  460. *
  461. * Note 2: We haven't moved all the "act on new configuration" logic
  462. * here yet. Some is still in do_hup() and other places.
  463. */
  464. static int
  465. options_act(or_options_t *old_options)
  466. {
  467. config_line_t *cl;
  468. char *fn;
  469. size_t len;
  470. or_options_t *options = get_options();
  471. int running_tor = options->command == CMD_RUN_TOR;
  472. clear_trusted_dir_servers();
  473. for (cl = options->DirServers; cl; cl = cl->next) {
  474. if (parse_dir_server_line(cl->value, 0)<0) {
  475. log_fn(LOG_ERR,
  476. "Bug: Previously validated DirServer line could not be added!");
  477. return -1;
  478. }
  479. }
  480. if (running_tor && rend_config_services(options, 0)<0) {
  481. log_fn(LOG_ERR,
  482. "Bug: Previously validated hidden services line could not be added!");
  483. return -1;
  484. }
  485. if (options->EntryNodes && strlen(options->EntryNodes))
  486. options->UseHelperNodes = 0;
  487. if (running_tor) {
  488. len = strlen(options->DataDirectory)+32;
  489. fn = tor_malloc(len);
  490. tor_snprintf(fn, len, "%s/cached-status", options->DataDirectory);
  491. if (check_private_dir(fn, CPD_CREATE) != 0) {
  492. log_fn(LOG_ERR, "Couldn't access/create private data directory \"%s\"",
  493. fn);
  494. tor_free(fn);
  495. return -1;
  496. }
  497. tor_free(fn);
  498. }
  499. /* Bail out at this point if we're not going to be a client or server:
  500. * we want to not fork, and to log stuff to stderr. */
  501. if (options->command != CMD_RUN_TOR)
  502. return 0;
  503. mark_logs_temp(); /* Close current logs once new logs are open. */
  504. if (options_init_logs(options, 0)<0) /* Configure the log(s) */
  505. return -1;
  506. /* Close the temporary log we used while starting up, if it isn't already
  507. * gone. */
  508. close_temp_logs();
  509. add_callback_log(LOG_ERR, LOG_ERR, control_event_logmsg);
  510. control_adjust_event_log_severity();
  511. /* Load state */
  512. if (! global_state)
  513. if (or_state_load())
  514. return -1;
  515. {
  516. smartlist_t *sl = smartlist_create();
  517. for (cl = options->RedirectExit; cl; cl = cl->next) {
  518. if (parse_redirect_line(sl, cl)<0)
  519. return -1;
  520. }
  521. set_exit_redirects(sl);
  522. }
  523. /* Finish backgrounding the process */
  524. if (running_tor && options->RunAsDaemon) {
  525. /* We may be calling this for the n'th time (on SIGHUP), but it's safe. */
  526. finish_daemon(options->DataDirectory);
  527. }
  528. /* Write our pid to the pid file. If we do not have write permissions we
  529. * will log a warning */
  530. if (running_tor && options->PidFile)
  531. write_pidfile(options->PidFile);
  532. /* Register addressmap directives */
  533. config_register_addressmaps(options);
  534. /* Update address policies. */
  535. parse_socks_policy();
  536. parse_dir_policy();
  537. parse_authdir_policy();
  538. parse_reachable_addresses();
  539. init_cookie_authentication(options->CookieAuthentication);
  540. /* reload keys as needed for rendezvous services. */
  541. if (rend_service_load_keys()<0) {
  542. log_fn(LOG_ERR,"Error loading rendezvous service keys");
  543. return -1;
  544. }
  545. /* Set up accounting */
  546. if (accounting_parse_options(options, 0)<0) {
  547. log_fn(LOG_ERR,"Error in accounting options");
  548. return -1;
  549. }
  550. if (accounting_is_enabled(options))
  551. configure_accounting(time(NULL));
  552. if (!running_tor)
  553. return 0;
  554. /* Check for transitions that need action. */
  555. if (old_options) {
  556. if (options_transition_affects_workers(old_options, options)) {
  557. log_fn(LOG_INFO,"Worker-related options changed. Rotating workers.");
  558. cpuworkers_rotate();
  559. dnsworkers_rotate();
  560. }
  561. }
  562. /* Since our options changed, we might need to regenerate and upload our
  563. * server descriptor.
  564. */
  565. if (!old_options || options_transition_affects_descriptor(old_options, options))
  566. mark_my_descriptor_dirty();
  567. return 0;
  568. }
  569. /*
  570. * Functions to parse config options
  571. */
  572. /** If <b>option</b> is an official abbreviation for a longer option,
  573. * return the longer option. Otherwise return <b>option</b>.
  574. * If <b>command_line</b> is set, apply all abbreviations. Otherwise, only
  575. * apply abbreviations that work for the config file and the command line. */
  576. static const char *
  577. expand_abbrev(config_format_t *fmt, const char *option, int command_line)
  578. {
  579. int i;
  580. if (! fmt->abbrevs)
  581. return option;
  582. for (i=0; fmt->abbrevs[i].abbreviated; ++i) {
  583. /* Abbreviations aren't casei. */
  584. if (!strcasecmp(option,fmt->abbrevs[i].abbreviated) &&
  585. (command_line || !fmt->abbrevs[i].commandline_only)) {
  586. return fmt->abbrevs[i].full;
  587. }
  588. }
  589. return option;
  590. }
  591. /** Helper: Read a list of configuration options from the command line.
  592. * If successful, put them in *<b>result</b> and return 0, and return
  593. * -1 and leave *<b>result</b> alone. */
  594. static int
  595. config_get_commandlines(int argc, char **argv, config_line_t **result)
  596. {
  597. config_line_t *front = NULL;
  598. config_line_t **new = &front;
  599. char *s;
  600. int i = 1;
  601. while (i < argc) {
  602. if (!strcmp(argv[i],"-f") ||
  603. !strcmp(argv[i],"--hash-password")) {
  604. i += 2; /* command-line option with argument. ignore them. */
  605. continue;
  606. } else if (!strcmp(argv[i],"--list-fingerprint")) {
  607. i += 1; /* command-line option. ignore it. */
  608. continue;
  609. } else if (!strcmp(argv[i],"--nt-service")) {
  610. i += 1;
  611. continue;
  612. }
  613. if (i == argc-1) {
  614. log_fn(LOG_WARN,"Command-line option '%s' with no value. Failing.",
  615. argv[i]);
  616. config_free_lines(front);
  617. return -1;
  618. }
  619. *new = tor_malloc_zero(sizeof(config_line_t));
  620. s = argv[i];
  621. while (*s == '-')
  622. s++;
  623. (*new)->key = tor_strdup(expand_abbrev(&options_format, s, 1));
  624. (*new)->value = tor_strdup(argv[i+1]);
  625. (*new)->next = NULL;
  626. log(LOG_DEBUG,"Commandline: parsed keyword '%s', value '%s'",
  627. (*new)->key, (*new)->value);
  628. new = &((*new)->next);
  629. i += 2;
  630. }
  631. *result = front;
  632. return 0;
  633. }
  634. /** Helper: allocate a new configuration option mapping 'key' to 'val',
  635. * append it to *<b>lst</b>. */
  636. static void
  637. config_line_append(config_line_t **lst,
  638. const char *key,
  639. const char *val)
  640. {
  641. config_line_t *newline;
  642. newline = tor_malloc(sizeof(config_line_t));
  643. newline->key = tor_strdup(key);
  644. newline->value = tor_strdup(val);
  645. newline->next = NULL;
  646. while (*lst)
  647. lst = &((*lst)->next);
  648. (*lst) = newline;
  649. }
  650. /** Helper: parse the config string and strdup into key/value
  651. * strings. Set *result to the list, or NULL if parsing the string
  652. * failed. Return 0 on success, -1 on failure. Warn and ignore any
  653. * misformatted lines. */
  654. int
  655. config_get_lines(char *string, config_line_t **result)
  656. {
  657. config_line_t *list = NULL, **next;
  658. char *k, *v;
  659. next = &list;
  660. do {
  661. string = parse_line_from_str(string, &k, &v);
  662. if (!string) {
  663. config_free_lines(list);
  664. return -1;
  665. }
  666. if (k && v) {
  667. /* This list can get long, so we keep a pointer to the end of it
  668. * rather than using config_line_append over and over and getting n^2
  669. * performance. This is the only really long list. */
  670. *next = tor_malloc(sizeof(config_line_t));
  671. (*next)->key = tor_strdup(k);
  672. (*next)->value = tor_strdup(v);
  673. (*next)->next = NULL;
  674. next = &((*next)->next);
  675. }
  676. } while (*string);
  677. *result = list;
  678. return 0;
  679. }
  680. /**
  681. * Free all the configuration lines on the linked list <b>front</b>.
  682. */
  683. void
  684. config_free_lines(config_line_t *front)
  685. {
  686. config_line_t *tmp;
  687. while (front) {
  688. tmp = front;
  689. front = tmp->next;
  690. tor_free(tmp->key);
  691. tor_free(tmp->value);
  692. tor_free(tmp);
  693. }
  694. }
  695. /** DOCDOC */
  696. static const char *
  697. config_find_description(config_format_t *fmt, const char *name)
  698. {
  699. int i;
  700. for (i=0; fmt->descriptions[i].name; ++i) {
  701. if (!strcasecmp(name, fmt->descriptions[i].name))
  702. return fmt->descriptions[i].description;
  703. }
  704. return NULL;
  705. }
  706. /** If <b>key</b> is a configuration option, return the corresponding
  707. * config_var_t. Otherwise, if <b>key</b> is a non-standard abbreviation,
  708. * warn, and return the corresponding config_var_t. Otherwise return NULL.
  709. */
  710. static config_var_t *
  711. config_find_option(config_format_t *fmt, const char *key)
  712. {
  713. int i;
  714. size_t keylen = strlen(key);
  715. if (!keylen)
  716. return NULL; /* if they say "--" on the commandline, it's not an option */
  717. /* First, check for an exact (case-insensitive) match */
  718. for (i=0; fmt->vars[i].name; ++i) {
  719. if (!strcasecmp(key, fmt->vars[i].name)) {
  720. return &fmt->vars[i];
  721. }
  722. }
  723. /* If none, check for an abbreviated match */
  724. for (i=0; fmt->vars[i].name; ++i) {
  725. if (!strncasecmp(key, fmt->vars[i].name, keylen)) {
  726. log_fn(LOG_WARN, "The abbreviation '%s' is deprecated. "
  727. "Please use '%s' instead",
  728. key, fmt->vars[i].name);
  729. return &fmt->vars[i];
  730. }
  731. }
  732. /* Okay, unrecognized options */
  733. return NULL;
  734. }
  735. /*
  736. * Functions to assign config options.
  737. */
  738. /** <b>c</b>-\>key is known to be a real key. Update <b>options</b>
  739. * with <b>c</b>-\>value and return 0, or return -1 if bad value.
  740. *
  741. * Called from config_assign_line() and option_reset().
  742. */
  743. static int
  744. config_assign_value(config_format_t *fmt, or_options_t *options,
  745. config_line_t *c)
  746. {
  747. int i, ok;
  748. config_var_t *var;
  749. void *lvalue;
  750. CHECK(fmt, options);
  751. var = config_find_option(fmt, c->key);
  752. tor_assert(var);
  753. lvalue = ((char*)options) + var->var_offset;
  754. switch (var->type) {
  755. case CONFIG_TYPE_UINT:
  756. i = tor_parse_long(c->value, 10, 0, INT_MAX, &ok, NULL);
  757. if (!ok) {
  758. log(LOG_WARN, "Int keyword '%s %s' is malformed or out of bounds.",
  759. c->key,c->value);
  760. return -1;
  761. }
  762. *(int *)lvalue = i;
  763. break;
  764. case CONFIG_TYPE_INTERVAL: {
  765. i = config_parse_interval(c->value, &ok);
  766. if (!ok) {
  767. return -1;
  768. }
  769. *(int *)lvalue = i;
  770. break;
  771. }
  772. case CONFIG_TYPE_MEMUNIT: {
  773. uint64_t u64 = config_parse_memunit(c->value, &ok);
  774. if (!ok) {
  775. return -1;
  776. }
  777. *(uint64_t *)lvalue = u64;
  778. break;
  779. }
  780. case CONFIG_TYPE_BOOL:
  781. i = tor_parse_long(c->value, 10, 0, 1, &ok, NULL);
  782. if (!ok) {
  783. log(LOG_WARN, "Boolean keyword '%s' expects 0 or 1.", c->key);
  784. return -1;
  785. }
  786. *(int *)lvalue = i;
  787. break;
  788. case CONFIG_TYPE_STRING:
  789. tor_free(*(char **)lvalue);
  790. *(char **)lvalue = tor_strdup(c->value);
  791. break;
  792. case CONFIG_TYPE_DOUBLE:
  793. *(double *)lvalue = atof(c->value);
  794. break;
  795. case CONFIG_TYPE_ISOTIME:
  796. if (parse_iso_time(c->value, (time_t *)lvalue)) {
  797. log(LOG_WARN, "Invalid time '%s' for keyword '%s'", c->value, c->key);
  798. return -1;
  799. }
  800. break;
  801. case CONFIG_TYPE_CSV:
  802. if (*(smartlist_t**)lvalue) {
  803. SMARTLIST_FOREACH(*(smartlist_t**)lvalue, char *, cp, tor_free(cp));
  804. smartlist_clear(*(smartlist_t**)lvalue);
  805. } else {
  806. *(smartlist_t**)lvalue = smartlist_create();
  807. }
  808. smartlist_split_string(*(smartlist_t**)lvalue, c->value, ",",
  809. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  810. break;
  811. case CONFIG_TYPE_LINELIST:
  812. case CONFIG_TYPE_LINELIST_S:
  813. config_line_append((config_line_t**)lvalue, c->key, c->value);
  814. break;
  815. case CONFIG_TYPE_OBSOLETE:
  816. log_fn(LOG_WARN, "Skipping obsolete configuration option '%s'", c->key);
  817. break;
  818. case CONFIG_TYPE_LINELIST_V:
  819. log_fn(LOG_WARN, "Can't provide value for virtual option '%s'", c->key);
  820. return -1;
  821. default:
  822. tor_assert(0);
  823. break;
  824. }
  825. return 0;
  826. }
  827. /** If <b>c</b> is a syntactically valid configuration line, update
  828. * <b>options</b> with its value and return 0. Otherwise return -1 for bad key,
  829. * -2 for bad value.
  830. *
  831. * If <b>clear_first</b> is set, clear the value first. Then if
  832. * <b>use_defaults</b> is set, set the value to the default.
  833. *
  834. * Called from config_assign().
  835. */
  836. static int
  837. config_assign_line(config_format_t *fmt, or_options_t *options,
  838. config_line_t *c, int use_defaults, int clear_first)
  839. {
  840. config_var_t *var;
  841. CHECK(fmt, options);
  842. var = config_find_option(fmt, c->key);
  843. if (!var) {
  844. log_fn(LOG_WARN, "Unknown option '%s'. Failing.", c->key);
  845. return -1;
  846. }
  847. /* Put keyword into canonical case. */
  848. if (strcmp(var->name, c->key)) {
  849. tor_free(c->key);
  850. c->key = tor_strdup(var->name);
  851. }
  852. if (!strlen(c->value)) { /* reset or clear it, then return */
  853. if (!clear_first) /* not already cleared */
  854. option_reset(fmt, options, var, use_defaults);
  855. return 0;
  856. }
  857. if (config_assign_value(fmt, options, c) < 0)
  858. return -2;
  859. return 0;
  860. }
  861. /** Restore the option named <b>key</b> in options to its default value.
  862. * Called from config_assign(). */
  863. static void
  864. config_reset_line(config_format_t *fmt, or_options_t *options,
  865. const char *key, int use_defaults)
  866. {
  867. config_var_t *var;
  868. CHECK(fmt, options);
  869. var = config_find_option(fmt, key);
  870. if (!var)
  871. return; /* give error on next pass. */
  872. option_reset(fmt, options, var, use_defaults);
  873. }
  874. /** Return true iff key is a valid configuration option. */
  875. int
  876. option_is_recognized(const char *key)
  877. {
  878. config_var_t *var = config_find_option(&options_format, key);
  879. return (var != NULL);
  880. }
  881. /** Return the canonical name of a configuration option. */
  882. const char *
  883. option_get_canonical_name(const char *key)
  884. {
  885. config_var_t *var = config_find_option(&options_format, key);
  886. return var->name;
  887. }
  888. /** Return a canonicalized list of the options assigned for key.
  889. */
  890. config_line_t *
  891. option_get_assignment(or_options_t *options, const char *key)
  892. {
  893. return get_assigned_option(&options_format, options, key);
  894. }
  895. static config_line_t *
  896. config_lines_dup(const config_line_t *inp)
  897. {
  898. config_line_t *result = NULL;
  899. config_line_t **next_out = &result;
  900. while (inp) {
  901. *next_out = tor_malloc(sizeof(config_line_t));
  902. (*next_out)->key = tor_strdup(inp->key);
  903. (*next_out)->value = tor_strdup(inp->value);
  904. inp = inp->next;
  905. next_out = &((*next_out)->next);
  906. }
  907. (*next_out) = NULL;
  908. return result;
  909. }
  910. static config_line_t *
  911. get_assigned_option(config_format_t *fmt, or_options_t *options, const char *key)
  912. {
  913. config_var_t *var;
  914. const void *value;
  915. char buf[32];
  916. config_line_t *result;
  917. tor_assert(options && key);
  918. CHECK(fmt, options);
  919. var = config_find_option(fmt, key);
  920. if (!var) {
  921. log_fn(LOG_WARN, "Unknown option '%s'. Failing.", key);
  922. return NULL;
  923. } else if (var->type == CONFIG_TYPE_LINELIST_S) {
  924. log_fn(LOG_WARN, "Can't return context-sensitive '%s' on its own", key);
  925. return NULL;
  926. }
  927. value = ((char*)options) + var->var_offset;
  928. if (var->type == CONFIG_TYPE_LINELIST ||
  929. var->type == CONFIG_TYPE_LINELIST_V) {
  930. /* Linelist requires special handling: we just copy and return it. */
  931. return config_lines_dup(*(const config_line_t**)value);
  932. }
  933. result = tor_malloc_zero(sizeof(config_line_t));
  934. result->key = tor_strdup(var->name);
  935. switch (var->type)
  936. {
  937. case CONFIG_TYPE_STRING:
  938. if (*(char**)value) {
  939. result->value = tor_strdup(*(char**)value);
  940. } else {
  941. tor_free(result->key);
  942. tor_free(result);
  943. return NULL;
  944. }
  945. break;
  946. case CONFIG_TYPE_ISOTIME:
  947. if (*(time_t*)value) {
  948. result->value = tor_malloc(ISO_TIME_LEN+1);
  949. format_iso_time(result->value, *(time_t*)value);
  950. } else {
  951. tor_free(result->key);
  952. tor_free(result);
  953. }
  954. break;
  955. case CONFIG_TYPE_INTERVAL:
  956. case CONFIG_TYPE_UINT:
  957. /* This means every or_options_t uint or bool element
  958. * needs to be an int. Not, say, a uint16_t or char. */
  959. tor_snprintf(buf, sizeof(buf), "%d", *(int*)value);
  960. result->value = tor_strdup(buf);
  961. break;
  962. case CONFIG_TYPE_MEMUNIT:
  963. tor_snprintf(buf, sizeof(buf), U64_FORMAT,
  964. U64_PRINTF_ARG(*(uint64_t*)value));
  965. result->value = tor_strdup(buf);
  966. break;
  967. case CONFIG_TYPE_DOUBLE:
  968. tor_snprintf(buf, sizeof(buf), "%f", *(double*)value);
  969. result->value = tor_strdup(buf);
  970. break;
  971. case CONFIG_TYPE_BOOL:
  972. result->value = tor_strdup(*(int*)value ? "1" : "0");
  973. break;
  974. case CONFIG_TYPE_CSV:
  975. if (*(smartlist_t**)value)
  976. result->value = smartlist_join_strings(*(smartlist_t**)value,",",0,NULL);
  977. else
  978. result->value = tor_strdup("");
  979. break;
  980. case CONFIG_TYPE_OBSOLETE:
  981. log_fn(LOG_WARN,"You asked me for the value of an obsolete config option '%s'.", key);
  982. tor_free(result->key);
  983. tor_free(result);
  984. return NULL;
  985. default:
  986. tor_free(result->key);
  987. tor_free(result);
  988. log_fn(LOG_WARN,"Bug: unknown type %d for known key '%s'", var->type, key);
  989. return NULL;
  990. }
  991. return result;
  992. }
  993. /** Iterate through the linked list of requested options <b>list</b>.
  994. * For each item, convert as appropriate and assign to <b>options</b>.
  995. * If an item is unrecognized, return -1 immediately,
  996. * else return 0 for success.
  997. *
  998. * If <b>clear_first</b>, interpret config options as replacing (not
  999. * extending) their previous values. If <b>clear_first</b> is set,
  1000. * then <b>use_defaults</b> to decide if you set to defaults after
  1001. * clearing, or make the value 0 or NULL.
  1002. *
  1003. * Here are the use cases:
  1004. * 1. A non-empty AllowUnverified line in your torrc. Appends to current
  1005. * if linelist, replaces current if csv.
  1006. * 2. An empty AllowUnverified line in your torrc. Should clear it.
  1007. * 3. "RESETCONF AllowUnverified" sets it to default.
  1008. * 4. "SETCONF AllowUnverified" makes it NULL.
  1009. * 5. "SETCONF AllowUnverified=foo" clears it and sets it to "foo".
  1010. *
  1011. * Use_defaults Clear_first
  1012. * 0 0 "append"
  1013. * 1 0 undefined, don't use
  1014. * 0 1 "set to null first"
  1015. * 1 1 "set to defaults first"
  1016. * Return 0 on success, -1 on bad key, -2 on bad value.
  1017. */
  1018. /*
  1019. There are three call cases for config_assign() currently.
  1020. Case one: Torrc entry
  1021. options_init_from_torrc() calls config_assign(0, 0)
  1022. calls config_assign_line(0, 0).
  1023. if value is empty, calls option_reset(0) and returns.
  1024. calls config_assign_value(), appends.
  1025. Case two: setconf
  1026. options_trial_assign() calls config_assign(0, 1)
  1027. calls config_reset_line(0)
  1028. calls option_reset(0)
  1029. calls option_clear().
  1030. calls config_assign_line(0, 1).
  1031. if value is empty, returns.
  1032. calls config_assign_value(), appends.
  1033. Case three: resetconf
  1034. options_trial_assign() calls config_assign(1, 1)
  1035. calls config_reset_line(1)
  1036. calls option_reset(1)
  1037. calls option_clear().
  1038. calls config_assign_value(default)
  1039. calls config_assign_line(1, 1).
  1040. returns.
  1041. */
  1042. static int
  1043. config_assign(config_format_t *fmt, void *options,
  1044. config_line_t *list, int use_defaults, int clear_first)
  1045. {
  1046. config_line_t *p;
  1047. CHECK(fmt, options);
  1048. /* pass 1: normalize keys */
  1049. for (p = list; p; p = p->next) {
  1050. const char *full = expand_abbrev(fmt, p->key, 0);
  1051. if (strcmp(full,p->key)) {
  1052. tor_free(p->key);
  1053. p->key = tor_strdup(full);
  1054. }
  1055. }
  1056. /* pass 2: if we're reading from a resetting source, clear all
  1057. * mentioned config options, and maybe set to their defaults. */
  1058. if (clear_first) {
  1059. for (p = list; p; p = p->next)
  1060. config_reset_line(fmt, options, p->key, use_defaults);
  1061. }
  1062. /* pass 3: assign. */
  1063. while (list) {
  1064. int r;
  1065. if ((r=config_assign_line(fmt, options, list, use_defaults, clear_first)))
  1066. return r;
  1067. list = list->next;
  1068. }
  1069. return 0;
  1070. }
  1071. /** Try assigning <b>list</b> to the global options. You do this by duping
  1072. * options, assigning list to the new one, then validating it. If it's
  1073. * ok, then throw out the old one and stick with the new one. Else,
  1074. * revert to old and return failure. Return 0 on success, -1 on bad
  1075. * keys, -2 on bad values, -3 on bad transition, and -4 on failed-to-set.
  1076. */
  1077. int
  1078. options_trial_assign(config_line_t *list, int use_defaults, int clear_first)
  1079. {
  1080. int r;
  1081. or_options_t *trial_options = options_dup(&options_format, get_options());
  1082. if ((r=config_assign(&options_format, trial_options,
  1083. list, use_defaults, clear_first)) < 0) {
  1084. config_free(&options_format, trial_options);
  1085. return r;
  1086. }
  1087. if (options_validate(trial_options) < 0) {
  1088. config_free(&options_format, trial_options);
  1089. return -2;
  1090. }
  1091. if (options_transition_allowed(get_options(), trial_options) < 0) {
  1092. config_free(&options_format, trial_options);
  1093. return -3;
  1094. }
  1095. if (set_options(trial_options)<0) {
  1096. config_free(&options_format, trial_options);
  1097. return -4;
  1098. }
  1099. /* we liked it. put it in place. */
  1100. return 0;
  1101. }
  1102. /** Reset config option <b>var</b> to 0, 0.0, NULL, or the equivalent.
  1103. * Called from option_reset() and config_free(). */
  1104. static void
  1105. option_clear(config_format_t *fmt, or_options_t *options, config_var_t *var)
  1106. {
  1107. void *lvalue = ((char*)options) + var->var_offset;
  1108. switch (var->type) {
  1109. case CONFIG_TYPE_STRING:
  1110. tor_free(*(char**)lvalue);
  1111. break;
  1112. case CONFIG_TYPE_DOUBLE:
  1113. *(double*)lvalue = 0.0;
  1114. break;
  1115. case CONFIG_TYPE_ISOTIME:
  1116. *(time_t*)lvalue = 0;
  1117. case CONFIG_TYPE_INTERVAL:
  1118. case CONFIG_TYPE_UINT:
  1119. case CONFIG_TYPE_BOOL:
  1120. *(int*)lvalue = 0;
  1121. break;
  1122. case CONFIG_TYPE_MEMUNIT:
  1123. *(uint64_t*)lvalue = 0;
  1124. break;
  1125. case CONFIG_TYPE_CSV:
  1126. if (*(smartlist_t**)lvalue) {
  1127. SMARTLIST_FOREACH(*(smartlist_t **)lvalue, char *, cp, tor_free(cp));
  1128. smartlist_free(*(smartlist_t **)lvalue);
  1129. *(smartlist_t **)lvalue = NULL;
  1130. }
  1131. break;
  1132. case CONFIG_TYPE_LINELIST:
  1133. case CONFIG_TYPE_LINELIST_S:
  1134. config_free_lines(*(config_line_t **)lvalue);
  1135. *(config_line_t **)lvalue = NULL;
  1136. break;
  1137. case CONFIG_TYPE_LINELIST_V:
  1138. /* handled by linelist_s. */
  1139. break;
  1140. case CONFIG_TYPE_OBSOLETE:
  1141. break;
  1142. }
  1143. }
  1144. /** Clear the option indexed by <b>var</b> in <b>options</b>. Then if
  1145. * <b>use_defaults</b>, set it to its default value.
  1146. * Called by config_init() and option_reset_line() and option_assign_line(). */
  1147. static void
  1148. option_reset(config_format_t *fmt, or_options_t *options,
  1149. config_var_t *var, int use_defaults)
  1150. {
  1151. config_line_t *c;
  1152. void *lvalue;
  1153. CHECK(fmt, options);
  1154. option_clear(fmt, options, var); /* clear it first */
  1155. if (!use_defaults)
  1156. return; /* all done */
  1157. lvalue = ((char*)options) + var->var_offset;
  1158. if (var->initvalue) {
  1159. c = tor_malloc_zero(sizeof(config_line_t));
  1160. c->key = tor_strdup(var->name);
  1161. c->value = tor_strdup(var->initvalue);
  1162. config_assign_value(fmt, options, c);
  1163. config_free_lines(c);
  1164. }
  1165. }
  1166. /** Set <b>options</b>-&gt;DirServers to contain the default directory
  1167. * servers. */
  1168. static void
  1169. add_default_trusted_dirservers(or_options_t *options)
  1170. {
  1171. /* moria1 */
  1172. config_line_append(&options->DirServers, "DirServer",
  1173. "v1 18.244.0.188:9031 FFCB 46DB 1339 DA84 674C 70D7 CB58 6434 C437 0441");
  1174. /* moria2 */
  1175. config_line_append(&options->DirServers, "DirServer",
  1176. "v1 18.244.0.114:80 719B E45D E224 B607 C537 07D0 E214 3E2D 423E 74CF");
  1177. /* tor26 */
  1178. config_line_append(&options->DirServers, "DirServer",
  1179. "v1 86.59.5.130:80 847B 1F85 0344 D787 6491 A548 92F9 0493 4E4E B85D");
  1180. // "tor.noreply.org:9030 847B 1F85 0344 D787 6491 A548 92F9 0493 4E4E B85D");
  1181. }
  1182. /** Print a usage message for tor. */
  1183. static void
  1184. print_usage(void)
  1185. {
  1186. printf(
  1187. "Copyright 2001-2005 Roger Dingledine, Nick Mathewson.\n\n"
  1188. "tor -f <torrc> [args]\n"
  1189. "See man page for options, or http://tor.eff.org/ for documentation.\n");
  1190. }
  1191. /**
  1192. * Based on <b>options-\>Address</b>, guess our public IP address and put it
  1193. * (in host order) into *<b>addr_out</b>. If <b>hostname_out</b> is provided, set
  1194. * *<b>hostname_out</b> to a new string holding the hostname we used to get
  1195. * the address. Return 0 if all is well, or -1 if we can't find a suitable
  1196. * public IP address.
  1197. */
  1198. int
  1199. resolve_my_address(or_options_t *options, uint32_t *addr_out, char **hostname_out)
  1200. {
  1201. struct in_addr in;
  1202. struct hostent *rent;
  1203. char hostname[256];
  1204. int explicit_ip=1;
  1205. char tmpbuf[INET_NTOA_BUF_LEN];
  1206. static uint32_t old_addr=0;
  1207. const char *address = options->Address;
  1208. tor_assert(addr_out);
  1209. if (address && *address) {
  1210. strlcpy(hostname, address, sizeof(hostname));
  1211. } else { /* then we need to guess our address */
  1212. explicit_ip = 0; /* it's implicit */
  1213. if (gethostname(hostname, sizeof(hostname)) < 0) {
  1214. log_fn(LOG_WARN,"Error obtaining local hostname");
  1215. return -1;
  1216. }
  1217. log_fn(LOG_DEBUG,"Guessed local host name as '%s'",hostname);
  1218. }
  1219. /* now we know hostname. resolve it and keep only the IP */
  1220. if (tor_inet_aton(hostname, &in) == 0) {
  1221. /* then we have to resolve it */
  1222. explicit_ip = 0;
  1223. rent = (struct hostent *)gethostbyname(hostname);
  1224. if (!rent) {
  1225. log_fn(LOG_WARN,"Could not resolve local Address '%s'. Failing.", hostname);
  1226. return -1;
  1227. }
  1228. tor_assert(rent->h_length == 4);
  1229. memcpy(&in.s_addr, rent->h_addr, rent->h_length);
  1230. }
  1231. tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
  1232. if (is_internal_IP(htonl(in.s_addr)) && !options->NoPublish) {
  1233. /* make sure we're ok with publishing an internal IP */
  1234. if (!options->DirServers) {
  1235. /* if they are using the default dirservers, disallow internal IPs always. */
  1236. log_fn(LOG_WARN,"Address '%s' resolves to private IP '%s'. "
  1237. "Tor servers that use the default DirServers must have public IP addresses.",
  1238. hostname, tmpbuf);
  1239. return -1;
  1240. }
  1241. if (!explicit_ip) {
  1242. /* even if they've set their own dirservers, require an explicit IP if
  1243. * they're using an internal address. */
  1244. log_fn(LOG_WARN,"Address '%s' resolves to private IP '%s'. "
  1245. "Please set the Address config option to be the IP you want to use.",
  1246. hostname, tmpbuf);
  1247. return -1;
  1248. }
  1249. }
  1250. log_fn(LOG_DEBUG, "Resolved Address to '%s'.", tmpbuf);
  1251. *addr_out = ntohl(in.s_addr);
  1252. if (old_addr && old_addr != *addr_out) {
  1253. log_fn(LOG_NOTICE,"Your IP seems to have changed. Updating.");
  1254. server_has_changed_ip();
  1255. }
  1256. old_addr = *addr_out;
  1257. if (hostname_out)
  1258. *hostname_out = tor_strdup(hostname);
  1259. return 0;
  1260. }
  1261. /** Called when we don't have a nickname set. Try to guess a good
  1262. * nickname based on the hostname, and return it in a newly allocated string. */
  1263. static char *
  1264. get_default_nickname(void)
  1265. {
  1266. char localhostname[256];
  1267. char *cp, *out, *outp;
  1268. if (gethostname(localhostname, sizeof(localhostname)) < 0) {
  1269. log_fn(LOG_WARN,"Error obtaining local hostname");
  1270. return NULL;
  1271. }
  1272. /* Put it in lowercase; stop at the first dot. */
  1273. for (cp = localhostname; *cp; ++cp) {
  1274. if (*cp == '.') {
  1275. *cp = '\0';
  1276. break;
  1277. }
  1278. *cp = tolower(*cp);
  1279. }
  1280. /* Strip invalid characters. */
  1281. cp = localhostname;
  1282. out = outp = tor_malloc(strlen(localhostname) + 1);
  1283. while (*cp) {
  1284. if (strchr(LEGAL_NICKNAME_CHARACTERS, *cp))
  1285. *outp++ = *cp++;
  1286. else
  1287. cp++;
  1288. }
  1289. *outp = '\0';
  1290. /* Enforce length. */
  1291. if (strlen(out) > MAX_NICKNAME_LEN)
  1292. out[MAX_NICKNAME_LEN]='\0';
  1293. return out;
  1294. }
  1295. /** Release storage held by <b>options</b> */
  1296. static void
  1297. config_free(config_format_t *fmt, void *options)
  1298. {
  1299. int i;
  1300. tor_assert(options);
  1301. for (i=0; fmt->vars[i].name; ++i)
  1302. option_clear(fmt, options, &(fmt->vars[i]));
  1303. tor_free(options);
  1304. }
  1305. /** Return true iff a and b contain identical keys and values in identical
  1306. * order. */
  1307. static int
  1308. config_lines_eq(config_line_t *a, config_line_t *b)
  1309. {
  1310. while (a && b) {
  1311. if (strcasecmp(a->key, b->key) || strcmp(a->value, b->value))
  1312. return 0;
  1313. a = a->next;
  1314. b = b->next;
  1315. }
  1316. if (a || b)
  1317. return 0;
  1318. return 1;
  1319. }
  1320. /** Return true iff the option <b>var</b> has the same value in <b>o1</b>
  1321. * and <b>o2</b>. Must not be called for LINELIST_S or OBSOLETE options.
  1322. */
  1323. static int
  1324. option_is_same(config_format_t *fmt,
  1325. or_options_t *o1, or_options_t *o2, const char *name)
  1326. {
  1327. config_line_t *c1, *c2;
  1328. int r = 1;
  1329. CHECK(fmt, o1);
  1330. CHECK(fmt, o2);
  1331. c1 = get_assigned_option(fmt, o1, name);
  1332. c2 = get_assigned_option(fmt, o2, name);
  1333. r = config_lines_eq(c1, c2);
  1334. config_free_lines(c1);
  1335. config_free_lines(c2);
  1336. return r;
  1337. }
  1338. /** Copy storage held by <b>old</b> into a new or_options_t and return it. */
  1339. static or_options_t *
  1340. options_dup(config_format_t *fmt, or_options_t *old)
  1341. {
  1342. or_options_t *newopts;
  1343. int i;
  1344. config_line_t *line;
  1345. newopts = config_alloc(fmt);
  1346. for (i=0; fmt->vars[i].name; ++i) {
  1347. if (fmt->vars[i].type == CONFIG_TYPE_LINELIST_S)
  1348. continue;
  1349. if (fmt->vars[i].type == CONFIG_TYPE_OBSOLETE)
  1350. continue;
  1351. line = get_assigned_option(fmt, old, fmt->vars[i].name);
  1352. if (line) {
  1353. if (config_assign(fmt, newopts, line, 0, 0) < 0) {
  1354. log_fn(LOG_WARN,"Bug: config_get_assigned_option() generated "
  1355. "something we couldn't config_assign().");
  1356. tor_assert(0);
  1357. }
  1358. }
  1359. config_free_lines(line);
  1360. }
  1361. return newopts;
  1362. }
  1363. /** Return a new empty or_options_t. Used for testing. */
  1364. or_options_t *
  1365. options_new(void)
  1366. {
  1367. return config_alloc(&options_format);
  1368. }
  1369. /** Set <b>options</b> to hold reasonable defaults for most options.
  1370. * Each option defaults to zero. */
  1371. void
  1372. options_init(or_options_t *options)
  1373. {
  1374. config_init(&options_format, options);
  1375. }
  1376. /* DOCDOC */
  1377. static void
  1378. config_init(config_format_t *fmt, void *options)
  1379. {
  1380. int i;
  1381. config_var_t *var;
  1382. CHECK(fmt, options);
  1383. for (i=0; fmt->vars[i].name; ++i) {
  1384. var = &fmt->vars[i];
  1385. if (!var->initvalue)
  1386. continue; /* defaults to NULL or 0 */
  1387. option_reset(fmt, options, var, 1);
  1388. }
  1389. }
  1390. /* DOCDOC */
  1391. static char *
  1392. config_dump(config_format_t *fmt, void *options, int minimal)
  1393. {
  1394. smartlist_t *elements;
  1395. or_options_t *defaults;
  1396. config_line_t *line;
  1397. char *result;
  1398. int i;
  1399. const char *desc;
  1400. defaults = config_alloc(fmt);
  1401. config_init(fmt, defaults);
  1402. fmt->validate_fn(defaults);
  1403. elements = smartlist_create();
  1404. for (i=0; fmt->vars[i].name; ++i) {
  1405. if (fmt->vars[i].type == CONFIG_TYPE_OBSOLETE ||
  1406. fmt->vars[i].type == CONFIG_TYPE_LINELIST_S)
  1407. continue;
  1408. /* Don't save 'hidden' control variables. */
  1409. if (!strcmpstart(fmt->vars[i].name, "__"))
  1410. continue;
  1411. if (minimal && option_is_same(fmt, options, defaults, fmt->vars[i].name))
  1412. continue;
  1413. desc = config_find_description(fmt, fmt->vars[i].name);
  1414. if (desc) {
  1415. size_t len = strlen(desc)+8;
  1416. char *tmp = tor_malloc(len);
  1417. tor_snprintf(tmp, len, "# %s\n",desc);
  1418. smartlist_add(elements, tmp);
  1419. }
  1420. line = get_assigned_option(fmt, options, fmt->vars[i].name);
  1421. for (; line; line = line->next) {
  1422. size_t len = strlen(line->key) + strlen(line->value) + 3;
  1423. char *tmp;
  1424. tmp = tor_malloc(len);
  1425. if (tor_snprintf(tmp, len, "%s %s\n", line->key, line->value)<0) {
  1426. log_fn(LOG_ERR, "Internal error writing log option");
  1427. tor_assert(0);
  1428. }
  1429. smartlist_add(elements, tmp);
  1430. }
  1431. config_free_lines(line);
  1432. }
  1433. result = smartlist_join_strings(elements, "", 0, NULL);
  1434. SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
  1435. smartlist_free(elements);
  1436. return result;
  1437. }
  1438. /** Return a string containing a possible configuration file that would give
  1439. * the configuration in <b>options</b>. If <b>minimal</b> is true, do not
  1440. * include options that are the same as Tor's defaults.
  1441. */
  1442. char *
  1443. options_dump(or_options_t *options, int minimal)
  1444. {
  1445. return config_dump(&options_format, options, minimal);
  1446. }
  1447. /* Return 0 if every element of sl is a string holding a decimal
  1448. * representation of a port number, or if sl is NULL.
  1449. * Otherwise return -1. */
  1450. static int
  1451. validate_ports_csv(smartlist_t *sl, const char *name)
  1452. {
  1453. int i;
  1454. int result = 0;
  1455. tor_assert(name);
  1456. if (!sl)
  1457. return 0;
  1458. SMARTLIST_FOREACH(sl, const char *, cp,
  1459. {
  1460. i = atoi(cp);
  1461. if (i < 1 || i > 65535) {
  1462. log(LOG_WARN, "Port '%s' out of range in %s", cp, name);
  1463. result=-1;
  1464. }
  1465. });
  1466. return result;
  1467. }
  1468. /** DOCDOC */
  1469. static void
  1470. parse_reachable_addresses(void)
  1471. {
  1472. or_options_t *options = get_options();
  1473. addr_policy_free(reachable_addr_policy);
  1474. reachable_addr_policy = NULL;
  1475. if (config_parse_addr_policy(options->ReachableAddresses,
  1476. &reachable_addr_policy,
  1477. ADDR_POLICY_ACCEPT)) {
  1478. log_fn(LOG_WARN, "Error in ReachableAddresses entry; ignoring.");
  1479. return;
  1480. }
  1481. }
  1482. /** Return true iff the firewall options might block any address:port
  1483. * combination
  1484. */
  1485. int
  1486. firewall_is_fascist(void)
  1487. {
  1488. return reachable_addr_policy ? 1 : 0;
  1489. }
  1490. /** Return true iff we are configured to think that the local fascist
  1491. * firewall (if any) will allow a connection to <b>addr</b>:<b>port</b> */
  1492. int
  1493. fascist_firewall_allows_address(uint32_t addr, uint16_t port)
  1494. {
  1495. addr_policy_result_t p = router_compare_addr_to_addr_policy(
  1496. addr, port, reachable_addr_policy);
  1497. switch (p) {
  1498. case ADDR_POLICY_PROBABLY_ACCEPTED:
  1499. case ADDR_POLICY_ACCEPTED:
  1500. return 1;
  1501. case ADDR_POLICY_PROBABLY_REJECTED:
  1502. case ADDR_POLICY_REJECTED:
  1503. return 0;
  1504. default:
  1505. log_fn(LOG_WARN, "Unexpected result: %d", (int)p);
  1506. return 0;
  1507. }
  1508. }
  1509. /** Return 0 if every setting in <b>options</b> is reasonable. Else
  1510. * warn and return -1. Should have no side effects, except for
  1511. * normalizing the contents of <b>options</b>. */
  1512. static int
  1513. options_validate(or_options_t *options)
  1514. {
  1515. int result = 0;
  1516. config_line_t *cl;
  1517. addr_policy_t *addr_policy=NULL;
  1518. if (options->ORPort < 0 || options->ORPort > 65535) {
  1519. log(LOG_WARN, "ORPort option out of bounds.");
  1520. result = -1;
  1521. }
  1522. if (options->ORPort == 0 && options->ORBindAddress != NULL) {
  1523. log(LOG_WARN, "ORPort must be defined if ORBindAddress is defined.");
  1524. result = -1;
  1525. }
  1526. if (options->DirPort == 0 && options->DirBindAddress != NULL) {
  1527. log(LOG_WARN, "DirPort must be defined if DirBindAddress is defined.");
  1528. result = -1;
  1529. }
  1530. if (options->SocksPort == 0 && options->SocksBindAddress != NULL) {
  1531. log(LOG_WARN, "SocksPort must be defined if SocksBindAddress is defined.");
  1532. result = -1;
  1533. }
  1534. if (validate_data_directory(options)<0) {
  1535. log(LOG_WARN, "Invalid DataDirectory");
  1536. result = -1;
  1537. }
  1538. if (options->Nickname == NULL) {
  1539. if (server_mode(options)) {
  1540. if (!(options->Nickname = get_default_nickname()))
  1541. return -1;
  1542. log_fn(LOG_NOTICE, "Choosing default nickname '%s'", options->Nickname);
  1543. }
  1544. } else {
  1545. if (!is_legal_nickname(options->Nickname)) {
  1546. log_fn(LOG_WARN, "Nickname '%s' is wrong length or contains illegal characters.", options->Nickname);
  1547. result = -1;
  1548. }
  1549. }
  1550. if (server_mode(options) && !options->ContactInfo)
  1551. log_fn(LOG_NOTICE,"Your ContactInfo config option is not set. Please consider setting it, so we can contact you if your server is misconfigured or something else goes wrong.");
  1552. if (normalize_log_options(options))
  1553. return -1;
  1554. /* Special case if no options are given. */
  1555. if (!options->Logs) {
  1556. config_line_append(&options->Logs, "Log", "notice stdout");
  1557. }
  1558. if (options_init_logs(options, 1)<0) /* Validate the log(s) */
  1559. return -1;
  1560. if (server_mode(options)) {
  1561. /* confirm that our address isn't broken, so we can complain now */
  1562. uint32_t tmp;
  1563. if (resolve_my_address(options, &tmp, NULL) < 0)
  1564. result = -1;
  1565. }
  1566. if (options->SocksPort < 0 || options->SocksPort > 65535) {
  1567. log(LOG_WARN, "SocksPort option out of bounds.");
  1568. result = -1;
  1569. }
  1570. if (options->SocksPort == 0 && options->ORPort == 0) {
  1571. log(LOG_WARN, "SocksPort and ORPort are both undefined? Quitting.");
  1572. result = -1;
  1573. }
  1574. if (options->ControlPort < 0 || options->ControlPort > 65535) {
  1575. log(LOG_WARN, "ControlPort option out of bounds.");
  1576. result = -1;
  1577. }
  1578. if (options->DirPort < 0 || options->DirPort > 65535) {
  1579. log(LOG_WARN, "DirPort option out of bounds.");
  1580. result = -1;
  1581. }
  1582. if (options->StrictExitNodes &&
  1583. (!options->ExitNodes || !strlen(options->ExitNodes))) {
  1584. log(LOG_WARN, "StrictExitNodes set, but no ExitNodes listed.");
  1585. }
  1586. if (options->StrictEntryNodes &&
  1587. (!options->EntryNodes || !strlen(options->EntryNodes))) {
  1588. log(LOG_WARN, "StrictEntryNodes set, but no EntryNodes listed.");
  1589. }
  1590. if (options->AuthoritativeDir) {
  1591. if (!options->ContactInfo) {
  1592. log(LOG_WARN, "Authoritative directory servers must set ContactInfo");
  1593. result = -1;
  1594. }
  1595. if (!options->RecommendedVersions) {
  1596. log(LOG_WARN, "Authoritative directory servers must configure RecommendedVersions.");
  1597. result = -1;
  1598. }
  1599. if (!options->RecommendedClientVersions)
  1600. options->RecommendedClientVersions =
  1601. config_lines_dup(options->RecommendedVersions);
  1602. if (!options->RecommendedServerVersions)
  1603. options->RecommendedServerVersions =
  1604. config_lines_dup(options->RecommendedVersions);
  1605. }
  1606. if (options->AuthoritativeDir && !options->DirPort) {
  1607. log(LOG_WARN, "Running as authoritative directory, but no DirPort set.");
  1608. result = -1;
  1609. }
  1610. if (options->AuthoritativeDir && !options->ORPort) {
  1611. log(LOG_WARN, "Running as authoritative directory, but no ORPort set.");
  1612. result = -1;
  1613. }
  1614. if (options->AuthoritativeDir && options->ClientOnly) {
  1615. log(LOG_WARN, "Running as authoritative directory, but ClientOnly also set.");
  1616. result = -1;
  1617. }
  1618. if (options->AuthoritativeDir && options->NoPublish) {
  1619. log(LOG_WARN, "You cannot set both AuthoritativeDir and NoPublish.");
  1620. result = -1;
  1621. }
  1622. if (options->ConnLimit <= 0) {
  1623. log(LOG_WARN, "ConnLimit must be greater than 0, but was set to %d",
  1624. options->ConnLimit);
  1625. result = -1;
  1626. }
  1627. if (options->_AccountingMaxKB) {
  1628. log(LOG_WARN, "AccountingMaxKB is deprecated. Say 'AccountingMax %d KB' instead.", options->_AccountingMaxKB);
  1629. options->AccountingMax = U64_LITERAL(1024)*options->_AccountingMaxKB;
  1630. options->_AccountingMaxKB = 0;
  1631. }
  1632. if (validate_ports_csv(options->FirewallPorts,
  1633. "FirewallPorts") < 0)
  1634. result = -1;
  1635. if (validate_ports_csv(options->LongLivedPorts,
  1636. "LongLivedPorts") < 0)
  1637. result = -1;
  1638. if (options->FascistFirewall) {
  1639. smartlist_t *instead = smartlist_create();
  1640. config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
  1641. new_line->key = tor_strdup("ReachableAddresses");
  1642. /* If we're configured with the old format, we need to prepend some
  1643. * open ports. */
  1644. if (!smartlist_len(options->FirewallPorts)) {
  1645. smartlist_add(options->FirewallPorts, tor_strdup("80"));
  1646. smartlist_add(options->FirewallPorts, tor_strdup("443"));
  1647. }
  1648. SMARTLIST_FOREACH(options->FirewallPorts, const char *, portno,
  1649. {
  1650. int p = atoi(portno);
  1651. char *s;
  1652. if (p<0) continue;
  1653. s = tor_malloc(16);
  1654. tor_snprintf(s, 16, "*:%d", p);
  1655. smartlist_add(instead, s);
  1656. });
  1657. new_line->value = smartlist_join_strings(instead,",",0,NULL);
  1658. /* These have been deprecated since 0.1.1.5-alpha-cvs */
  1659. log_fn(LOG_WARN, "FascistFirewall and FirewallPorts are deprecated. Instead, use \"ReachableAddresses %s\"", new_line->value);
  1660. new_line->next = options->ReachableAddresses;
  1661. options->ReachableAddresses = new_line;
  1662. SMARTLIST_FOREACH(instead, char *, cp, tor_free(cp));
  1663. smartlist_free(instead);
  1664. }
  1665. if (options->FascistFirewall || options->ReachableAddresses) {
  1666. /* We need to end with a reject *:*, not an implicit accept *:* */
  1667. config_line_t **linep = &options->ReachableAddresses;
  1668. while (*linep) {
  1669. linep = &((*linep)->next);
  1670. }
  1671. *linep = tor_malloc_zero(sizeof(config_line_t));
  1672. (*linep)->key = tor_strdup("ReachableAddresses");
  1673. (*linep)->value = tor_strdup("reject *:*");
  1674. }
  1675. options->_AllowUnverified = 0;
  1676. if (options->AllowUnverifiedNodes) {
  1677. SMARTLIST_FOREACH(options->AllowUnverifiedNodes, const char *, cp, {
  1678. if (!strcasecmp(cp, "entry"))
  1679. options->_AllowUnverified |= ALLOW_UNVERIFIED_ENTRY;
  1680. else if (!strcasecmp(cp, "exit"))
  1681. options->_AllowUnverified |= ALLOW_UNVERIFIED_EXIT;
  1682. else if (!strcasecmp(cp, "middle"))
  1683. options->_AllowUnverified |= ALLOW_UNVERIFIED_MIDDLE;
  1684. else if (!strcasecmp(cp, "introduction"))
  1685. options->_AllowUnverified |= ALLOW_UNVERIFIED_INTRODUCTION;
  1686. else if (!strcasecmp(cp, "rendezvous"))
  1687. options->_AllowUnverified |= ALLOW_UNVERIFIED_RENDEZVOUS;
  1688. else {
  1689. log(LOG_WARN, "Unrecognized value '%s' in AllowUnverifiedNodes",
  1690. cp);
  1691. result = -1;
  1692. }
  1693. });
  1694. }
  1695. if (options->SocksPort >= 1 &&
  1696. (options->PathlenCoinWeight < 0.0 || options->PathlenCoinWeight >= 1.0)) {
  1697. log(LOG_WARN, "PathlenCoinWeight option must be >=0.0 and <1.0.");
  1698. result = -1;
  1699. }
  1700. #define MIN_DIR_FETCH_PERIOD 600
  1701. #define MIN_REND_POST_PERIOD 300
  1702. #define MIN_STATUS_FETCH_PERIOD 60
  1703. #define MAX_DIR_PERIOD (MIN_ONION_KEY_LIFETIME/2)
  1704. #define MAX_CACHE_DIR_FETCH_PERIOD 3600
  1705. #define MAX_CACHE_STATUS_FETCH_PERIOD 900
  1706. if (options->DirFetchPeriod &&
  1707. options->DirFetchPeriod < MIN_DIR_FETCH_PERIOD) {
  1708. log(LOG_WARN, "DirFetchPeriod option must be at least %d seconds. Clipping.", MIN_DIR_FETCH_PERIOD);
  1709. options->DirFetchPeriod = MIN_DIR_FETCH_PERIOD;
  1710. }
  1711. if (options->StatusFetchPeriod &&
  1712. options->StatusFetchPeriod < MIN_STATUS_FETCH_PERIOD) {
  1713. log(LOG_WARN, "StatusFetchPeriod option must be at least %d seconds. Clipping.", MIN_STATUS_FETCH_PERIOD);
  1714. options->StatusFetchPeriod = MIN_STATUS_FETCH_PERIOD;
  1715. }
  1716. if (options->RendPostPeriod < MIN_REND_POST_PERIOD) {
  1717. log(LOG_WARN,"RendPostPeriod option must be at least %d seconds. Clipping.",
  1718. MIN_REND_POST_PERIOD);
  1719. options->RendPostPeriod = MIN_REND_POST_PERIOD;
  1720. }
  1721. if (options->DirPort && ! options->AuthoritativeDir) {
  1722. if (options->DirFetchPeriod > MAX_CACHE_DIR_FETCH_PERIOD) {
  1723. log(LOG_WARN, "Caching directory servers must have DirFetchPeriod less than %d seconds. Clipping.", MAX_CACHE_DIR_FETCH_PERIOD);
  1724. options->DirFetchPeriod = MAX_CACHE_DIR_FETCH_PERIOD;
  1725. }
  1726. if (options->StatusFetchPeriod > MAX_CACHE_STATUS_FETCH_PERIOD) {
  1727. log(LOG_WARN, "Caching directory servers must have StatusFetchPeriod less than %d seconds. Clipping.", MAX_CACHE_STATUS_FETCH_PERIOD);
  1728. options->StatusFetchPeriod = MAX_CACHE_STATUS_FETCH_PERIOD;
  1729. }
  1730. }
  1731. if (options->DirFetchPeriod > MAX_DIR_PERIOD) {
  1732. log(LOG_WARN, "DirFetchPeriod is too large; clipping to %ds.", MAX_DIR_PERIOD);
  1733. options->DirFetchPeriod = MAX_DIR_PERIOD;
  1734. }
  1735. if (options->StatusFetchPeriod > MAX_DIR_PERIOD) {
  1736. log(LOG_WARN, "StatusFetchPeriod is too large; clipping to %ds.", MAX_DIR_PERIOD);
  1737. options->StatusFetchPeriod = MAX_DIR_PERIOD;
  1738. }
  1739. if (options->RendPostPeriod > MAX_DIR_PERIOD) {
  1740. log(LOG_WARN, "RendPostPeriod is too large; clipping to %ds.", MAX_DIR_PERIOD);
  1741. options->RendPostPeriod = MAX_DIR_PERIOD;
  1742. }
  1743. if (options->KeepalivePeriod < 1) {
  1744. log(LOG_WARN,"KeepalivePeriod option must be positive.");
  1745. result = -1;
  1746. }
  1747. if (options->BandwidthRate > INT_MAX) {
  1748. log(LOG_WARN,"BandwidthRate must be less than %d",INT_MAX);
  1749. result = -1;
  1750. }
  1751. if (options->BandwidthBurst > INT_MAX) {
  1752. log(LOG_WARN,"BandwidthBurst must be less than %d",INT_MAX);
  1753. result = -1;
  1754. }
  1755. if (server_mode(options) &&
  1756. options->BandwidthRate < ROUTER_REQUIRED_MIN_BANDWIDTH*2) {
  1757. log(LOG_WARN,"BandwidthRate is set to %d bytes/second. For servers, it must be at least %d.", (int)options->BandwidthRate, ROUTER_REQUIRED_MIN_BANDWIDTH*2);
  1758. result = -1;
  1759. }
  1760. if (options->BandwidthRate > options->BandwidthBurst) {
  1761. log(LOG_WARN,"BandwidthBurst must be at least equal to BandwidthRate.");
  1762. result = -1;
  1763. }
  1764. if (accounting_parse_options(options, 1)<0) {
  1765. result = -1;
  1766. }
  1767. if (options->HttpProxy) { /* parse it now */
  1768. if (parse_addr_port(options->HttpProxy, NULL,
  1769. &options->HttpProxyAddr, &options->HttpProxyPort) < 0) {
  1770. log(LOG_WARN,"HttpProxy failed to parse or resolve. Please fix.");
  1771. result = -1;
  1772. }
  1773. if (options->HttpProxyPort == 0) { /* give it a default */
  1774. options->HttpProxyPort = 80;
  1775. }
  1776. }
  1777. if (options->HttpProxyAuthenticator) {
  1778. if (strlen(options->HttpProxyAuthenticator) >= 48) {
  1779. log(LOG_WARN, "HttpProxyAuthenticator is too long (>= 48 chars).");
  1780. result = -1;
  1781. }
  1782. }
  1783. if (options->HttpsProxy) { /* parse it now */
  1784. if (parse_addr_port(options->HttpsProxy, NULL,
  1785. &options->HttpsProxyAddr, &options->HttpsProxyPort) < 0) {
  1786. log(LOG_WARN,"HttpsProxy failed to parse or resolve. Please fix.");
  1787. result = -1;
  1788. }
  1789. if (options->HttpsProxyPort == 0) { /* give it a default */
  1790. options->HttpsProxyPort = 443;
  1791. }
  1792. }
  1793. if (options->HttpsProxyAuthenticator) {
  1794. if (strlen(options->HttpsProxyAuthenticator) >= 48) {
  1795. log(LOG_WARN, "HttpsProxyAuthenticator is too long (>= 48 chars).");
  1796. result = -1;
  1797. }
  1798. }
  1799. if (options->HashedControlPassword) {
  1800. if (decode_hashed_password(NULL, options->HashedControlPassword)<0) {
  1801. log_fn(LOG_WARN,"Bad HashedControlPassword: wrong length or bad encoding");
  1802. result = -1;
  1803. }
  1804. }
  1805. if (options->HashedControlPassword && options->CookieAuthentication) {
  1806. log_fn(LOG_WARN,"Cannot enable both HashedControlPassword and CookieAuthentication");
  1807. result = -1;
  1808. }
  1809. if (options->UseHelperNodes && ! options->NumHelperNodes) {
  1810. log_fn(LOG_WARN, "Cannot enable UseHelperNodes with NumHelperNodes set to 0");
  1811. result = -1;
  1812. }
  1813. if (check_nickname_list(options->ExitNodes, "ExitNodes"))
  1814. result = -1;
  1815. if (check_nickname_list(options->EntryNodes, "EntryNodes"))
  1816. result = -1;
  1817. if (check_nickname_list(options->ExcludeNodes, "ExcludeNodes"))
  1818. result = -1;
  1819. if (check_nickname_list(options->RendNodes, "RendNodes"))
  1820. result = -1;
  1821. if (check_nickname_list(options->RendNodes, "RendExcludeNodes"))
  1822. result = -1;
  1823. if (check_nickname_list(options->MyFamily, "MyFamily"))
  1824. result = -1;
  1825. for (cl = options->NodeFamilies; cl; cl = cl->next) {
  1826. if (check_nickname_list(cl->value, "NodeFamily"))
  1827. result = -1;
  1828. }
  1829. if (config_parse_addr_policy(options->ExitPolicy, &addr_policy, -1)) {
  1830. log_fn(LOG_WARN, "Error in Exit Policy entry.");
  1831. result = -1;
  1832. }
  1833. options_append_default_exit_policy(&addr_policy);
  1834. if (server_mode(options)) {
  1835. exit_policy_implicitly_allows_local_networks(addr_policy, 1);
  1836. }
  1837. /* The rest of these calls *append* to addr_policy. So don't actually
  1838. * use the results for anything other than checking if they parse! */
  1839. if (config_parse_addr_policy(options->DirPolicy, &addr_policy, -1)) {
  1840. log_fn(LOG_WARN, "Error in DirPolicy entry.");
  1841. result = -1;
  1842. }
  1843. if (config_parse_addr_policy(options->SocksPolicy, &addr_policy, -1)) {
  1844. log_fn(LOG_WARN, "Error in SocksPolicy entry.");
  1845. result = -1;
  1846. }
  1847. if (config_parse_addr_policy(options->ReachableAddresses, &addr_policy,
  1848. ADDR_POLICY_ACCEPT)) {
  1849. log_fn(LOG_WARN, "Error in ReachableAddresses entry.");
  1850. result = -1;
  1851. }
  1852. if (config_parse_addr_policy(options->AuthDirReject, &addr_policy,
  1853. ADDR_POLICY_ACCEPT)) {
  1854. log_fn(LOG_WARN, "Error in ReachableAddresses entry.");
  1855. result = -1;
  1856. }
  1857. if (config_parse_addr_policy(options->AuthDirInvalid, &addr_policy,
  1858. ADDR_POLICY_ACCEPT)) {
  1859. log_fn(LOG_WARN, "Error in ReachableAddresses entry.");
  1860. result = -1;
  1861. }
  1862. addr_policy_free(addr_policy);
  1863. for (cl = options->RedirectExit; cl; cl = cl->next) {
  1864. if (parse_redirect_line(NULL, cl)<0)
  1865. result = -1;
  1866. }
  1867. if (!options->DirServers) {
  1868. add_default_trusted_dirservers(options);
  1869. } else {
  1870. for (cl = options->DirServers; cl; cl = cl->next) {
  1871. if (parse_dir_server_line(cl->value, 1)<0)
  1872. result = -1;
  1873. }
  1874. }
  1875. if (rend_config_services(options, 1) < 0)
  1876. result = -1;
  1877. return result;
  1878. }
  1879. /** Helper: return true iff s1 and s2 are both NULL, or both non-NULL
  1880. * equal strings. */
  1881. static int
  1882. opt_streq(const char *s1, const char *s2)
  1883. {
  1884. if (!s1 && !s2)
  1885. return 1;
  1886. else if (s1 && s2 && !strcmp(s1,s2))
  1887. return 1;
  1888. else
  1889. return 0;
  1890. }
  1891. /** Check if any of the previous options have changed but aren't allowed to. */
  1892. static int
  1893. options_transition_allowed(or_options_t *old, or_options_t *new_val)
  1894. {
  1895. if (!old)
  1896. return 0;
  1897. if (!opt_streq(old->PidFile, new_val->PidFile)) {
  1898. log_fn(LOG_WARN,"PidFile is not allowed to change. Failing.");
  1899. return -1;
  1900. }
  1901. if (old->RunAsDaemon != new_val->RunAsDaemon) {
  1902. log_fn(LOG_WARN,"While Tor is running, changing RunAsDaemon is not allowed. Failing.");
  1903. return -1;
  1904. }
  1905. if (strcmp(old->DataDirectory,new_val->DataDirectory)!=0) {
  1906. log_fn(LOG_WARN,"While Tor is running, changing DataDirectory (\"%s\"->\"%s\") is not allowed. Failing.", old->DataDirectory, new_val->DataDirectory);
  1907. return -1;
  1908. }
  1909. if (!opt_streq(old->User, new_val->User)) {
  1910. log_fn(LOG_WARN,"While Tor is running, changing User is not allowed. Failing.");
  1911. return -1;
  1912. }
  1913. if (!opt_streq(old->Group, new_val->Group)) {
  1914. log_fn(LOG_WARN,"While Tor is running, changing Group is not allowed. Failing.");
  1915. return -1;
  1916. }
  1917. if (old->HardwareAccel != new_val->HardwareAccel) {
  1918. log_fn(LOG_WARN,"While Tor is running, changing HardwareAccel is not allowed. Failing.");
  1919. return -1;
  1920. }
  1921. return 0;
  1922. }
  1923. /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
  1924. * will require us to rotate the cpu and dns workers; else return 0. */
  1925. static int
  1926. options_transition_affects_workers(or_options_t *old_options,
  1927. or_options_t *new_options)
  1928. {
  1929. if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
  1930. old_options->NumCpus != new_options->NumCpus ||
  1931. old_options->ORPort != new_options->ORPort ||
  1932. old_options->SafeLogging != new_options->SafeLogging ||
  1933. !config_lines_eq(old_options->Logs, new_options->Logs))
  1934. return 1;
  1935. /* Check whether log options match. */
  1936. /* Nothing that changed matters. */
  1937. return 0;
  1938. }
  1939. /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
  1940. * will require us to generate a new descriptor; else return 0. */
  1941. static int
  1942. options_transition_affects_descriptor(or_options_t *old_options,
  1943. or_options_t *new_options)
  1944. {
  1945. if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
  1946. !opt_streq(old_options->Nickname,new_options->Nickname) ||
  1947. !opt_streq(old_options->Address,new_options->Address) ||
  1948. !config_lines_eq(old_options->ExitPolicy,new_options->ExitPolicy) ||
  1949. old_options->ORPort != new_options->ORPort ||
  1950. old_options->DirPort != new_options->DirPort ||
  1951. old_options->ClientOnly != new_options->ClientOnly ||
  1952. old_options->NoPublish != new_options->NoPublish ||
  1953. old_options->BandwidthRate != new_options->BandwidthRate ||
  1954. old_options->BandwidthBurst != new_options->BandwidthBurst ||
  1955. !opt_streq(old_options->ContactInfo, new_options->ContactInfo) ||
  1956. !opt_streq(old_options->MyFamily, new_options->MyFamily) ||
  1957. !opt_streq(old_options->AccountingStart, new_options->AccountingStart) ||
  1958. old_options->AccountingMax != new_options->AccountingMax)
  1959. return 1;
  1960. return 0;
  1961. }
  1962. #ifdef MS_WINDOWS
  1963. /** Return the directory on windows where we expect to find our application
  1964. * data. */
  1965. static char *
  1966. get_windows_conf_root(void)
  1967. {
  1968. static int is_set = 0;
  1969. static char path[MAX_PATH+1];
  1970. LPITEMIDLIST idl;
  1971. IMalloc *m;
  1972. HRESULT result;
  1973. if (is_set)
  1974. return path;
  1975. /* Find X:\documents and settings\username\application data\ .
  1976. * We would use SHGetSpecialFolder path, but that wasn't added until IE4.
  1977. */
  1978. if (!SUCCEEDED(SHGetSpecialFolderLocation(NULL, CSIDL_APPDATA,
  1979. &idl))) {
  1980. GetCurrentDirectory(MAX_PATH, path);
  1981. is_set = 1;
  1982. log_fn(LOG_WARN, "I couldn't find your application data folder: are you running an ancient version of Windows 95? Defaulting to \"%s\"", path);
  1983. return path;
  1984. }
  1985. /* Convert the path from an "ID List" (whatever that is!) to a path. */
  1986. result = SHGetPathFromIDList(idl, path);
  1987. /* Now we need to free the */
  1988. SHGetMalloc(&m);
  1989. if (m) {
  1990. m->lpVtbl->Free(m, idl);
  1991. m->lpVtbl->Release(m);
  1992. }
  1993. if (!SUCCEEDED(result)) {
  1994. return NULL;
  1995. }
  1996. strlcat(path,"\\tor",MAX_PATH);
  1997. is_set = 1;
  1998. return path;
  1999. }
  2000. #endif
  2001. /** Return the default location for our torrc file. */
  2002. static const char *
  2003. get_default_conf_file(void)
  2004. {
  2005. #ifdef MS_WINDOWS
  2006. static char path[MAX_PATH+1];
  2007. strlcpy(path, get_windows_conf_root(), MAX_PATH);
  2008. strlcat(path,"\\torrc",MAX_PATH);
  2009. return path;
  2010. #else
  2011. return (CONFDIR "/torrc");
  2012. #endif
  2013. }
  2014. /** Verify whether lst is a string containing valid-looking space-separated
  2015. * nicknames, or NULL. Return 0 on success. Warn and return -1 on failure.
  2016. */
  2017. static int
  2018. check_nickname_list(const char *lst, const char *name)
  2019. {
  2020. int r = 0;
  2021. smartlist_t *sl;
  2022. if (!lst)
  2023. return 0;
  2024. sl = smartlist_create();
  2025. smartlist_split_string(sl, lst, ",", SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2026. SMARTLIST_FOREACH(sl, const char *, s,
  2027. {
  2028. if (!is_legal_nickname_or_hexdigest(s)) {
  2029. log_fn(LOG_WARN, "Invalid nickname '%s' in %s line", s, name);
  2030. r = -1;
  2031. }
  2032. });
  2033. SMARTLIST_FOREACH(sl, char *, s, tor_free(s));
  2034. smartlist_free(sl);
  2035. return r;
  2036. }
  2037. /** Read a configuration file into <b>options</b>, finding the configuration
  2038. * file location based on the command line. After loading the options,
  2039. * validate them for consistency, then take actions based on them.
  2040. * Return 0 if success, -1 if failure. */
  2041. int
  2042. options_init_from_torrc(int argc, char **argv)
  2043. {
  2044. or_options_t *oldoptions, *newoptions;
  2045. config_line_t *cl;
  2046. char *cf=NULL, *fname=NULL;
  2047. int i, retval;
  2048. int using_default_torrc;
  2049. static char **backup_argv;
  2050. static int backup_argc;
  2051. if (argv) { /* first time we're called. save commandline args */
  2052. backup_argv = argv;
  2053. backup_argc = argc;
  2054. oldoptions = NULL;
  2055. } else { /* we're reloading. need to clean up old options first. */
  2056. argv = backup_argv;
  2057. argc = backup_argc;
  2058. oldoptions = get_options();
  2059. }
  2060. if (argc > 1 && (!strcmp(argv[1], "-h") || !strcmp(argv[1],"--help"))) {
  2061. print_usage();
  2062. exit(0);
  2063. }
  2064. if (argc > 1 && (!strcmp(argv[1],"--version"))) {
  2065. printf("Tor version %s.\n",VERSION);
  2066. if (argc > 2 && (!strcmp(argv[2],"--version"))) {
  2067. print_cvs_version();
  2068. }
  2069. exit(0);
  2070. }
  2071. newoptions = tor_malloc_zero(sizeof(or_options_t));
  2072. newoptions->_magic = OR_OPTIONS_MAGIC;
  2073. options_init(newoptions);
  2074. /* learn config file name */
  2075. fname = NULL;
  2076. using_default_torrc = 1;
  2077. newoptions->command = CMD_RUN_TOR;
  2078. for (i = 1; i < argc; ++i) {
  2079. if (i < argc-1 && !strcmp(argv[i],"-f")) {
  2080. if (fname) {
  2081. log(LOG_WARN, "Duplicate -f options on command line.");
  2082. tor_free(fname);
  2083. }
  2084. fname = tor_strdup(argv[i+1]);
  2085. using_default_torrc = 0;
  2086. ++i;
  2087. } else if (!strcmp(argv[i],"--list-fingerprint")) {
  2088. newoptions->command = CMD_LIST_FINGERPRINT;
  2089. } else if (!strcmp(argv[i],"--hash-password")) {
  2090. newoptions->command = CMD_HASH_PASSWORD;
  2091. newoptions->command_arg = tor_strdup( (i < argc-1) ? argv[i+1] : "");
  2092. ++i;
  2093. } else if (!strcmp(argv[i],"--verify-config")) {
  2094. newoptions->command = CMD_VERIFY_CONFIG;
  2095. }
  2096. }
  2097. if (using_default_torrc) {
  2098. /* didn't find one, try CONFDIR */
  2099. const char *dflt = get_default_conf_file();
  2100. char *fn = NULL;
  2101. if (dflt && file_status(dflt) == FN_FILE) {
  2102. fname = tor_strdup(dflt);
  2103. } else {
  2104. #ifndef MS_WINDOWS
  2105. fn = expand_filename("~/.torrc");
  2106. if (fn && file_status(fn) == FN_FILE) {
  2107. fname = fn;
  2108. } else {
  2109. tor_free(fn);
  2110. fname = tor_strdup(dflt);
  2111. }
  2112. #else
  2113. fname = tor_strdup(dflt);
  2114. #endif
  2115. }
  2116. }
  2117. tor_assert(fname);
  2118. log(LOG_DEBUG, "Opening config file \"%s\"", fname);
  2119. /* get config lines, assign them */
  2120. if (file_status(fname) != FN_FILE ||
  2121. !(cf = read_file_to_str(fname,0))) {
  2122. if (using_default_torrc == 1) {
  2123. log(LOG_NOTICE, "Configuration file \"%s\" not present, "
  2124. "using reasonable defaults.", fname);
  2125. tor_free(fname); /* sets fname to NULL */
  2126. } else {
  2127. log(LOG_WARN, "Unable to open configuration file \"%s\".", fname);
  2128. tor_free(fname);
  2129. goto err;
  2130. }
  2131. } else { /* it opened successfully. use it. */
  2132. retval = config_get_lines(cf, &cl);
  2133. tor_free(cf);
  2134. if (retval < 0)
  2135. goto err;
  2136. retval = config_assign(&options_format, newoptions, cl, 0, 0);
  2137. config_free_lines(cl);
  2138. if (retval < 0)
  2139. goto err;
  2140. }
  2141. /* Go through command-line variables too */
  2142. if (config_get_commandlines(argc, argv, &cl) < 0)
  2143. goto err;
  2144. retval = config_assign(&options_format, newoptions, cl, 0, 0);
  2145. config_free_lines(cl);
  2146. if (retval < 0)
  2147. goto err;
  2148. /* Validate newoptions */
  2149. if (options_validate(newoptions) < 0)
  2150. goto err;
  2151. if (options_transition_allowed(oldoptions, newoptions) < 0)
  2152. goto err;
  2153. if (set_options(newoptions))
  2154. goto err; /* frees and replaces old options */
  2155. tor_free(torrc_fname);
  2156. torrc_fname = fname;
  2157. return 0;
  2158. err:
  2159. tor_free(fname);
  2160. config_free(&options_format, newoptions);
  2161. return -1;
  2162. }
  2163. /** Return the location for our configuration file.
  2164. */
  2165. const char *
  2166. get_torrc_fname(void)
  2167. {
  2168. if (torrc_fname)
  2169. return torrc_fname;
  2170. else
  2171. return get_default_conf_file();
  2172. }
  2173. /** Adjust the address map mased on the MapAddress elements in the
  2174. * configuration <b>options</b>
  2175. */
  2176. static void
  2177. config_register_addressmaps(or_options_t *options)
  2178. {
  2179. smartlist_t *elts;
  2180. config_line_t *opt;
  2181. char *from, *to;
  2182. addressmap_clear_configured();
  2183. elts = smartlist_create();
  2184. for (opt = options->AddressMap; opt; opt = opt->next) {
  2185. smartlist_split_string(elts, opt->value, NULL,
  2186. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
  2187. if (smartlist_len(elts) >= 2) {
  2188. from = smartlist_get(elts,0);
  2189. to = smartlist_get(elts,1);
  2190. if (!is_plausible_address(from)) {
  2191. log_fn(LOG_WARN,"Skipping invalid argument '%s' to MapAddress",from);
  2192. } else if (!is_plausible_address(to)) {
  2193. log_fn(LOG_WARN,"Skipping invalid argument '%s' to MapAddress",to);
  2194. } else {
  2195. addressmap_register(from, tor_strdup(to), 0);
  2196. if (smartlist_len(elts)>2) {
  2197. log_fn(LOG_WARN,"Ignoring extra arguments to MapAddress.");
  2198. }
  2199. }
  2200. } else {
  2201. log_fn(LOG_WARN,"MapAddress '%s' has too few arguments. Ignoring.", opt->value);
  2202. }
  2203. SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
  2204. smartlist_clear(elts);
  2205. }
  2206. smartlist_free(elts);
  2207. }
  2208. /** If <b>range</b> is of the form MIN-MAX, for MIN and MAX both
  2209. * recognized log severity levels, set *<b>min_out</b> to MIN and
  2210. * *<b>max_out</b> to MAX and return 0. Else, if <b>range</b> is of
  2211. * the form MIN, act as if MIN-err had been specified. Else, warn and
  2212. * return -1.
  2213. */
  2214. static int
  2215. parse_log_severity_range(const char *range, int *min_out, int *max_out)
  2216. {
  2217. int levelMin, levelMax;
  2218. const char *cp;
  2219. cp = strchr(range, '-');
  2220. if (cp) {
  2221. if (cp == range) {
  2222. levelMin = LOG_DEBUG;
  2223. } else {
  2224. char *tmp_sev = tor_strndup(range, cp - range);
  2225. levelMin = parse_log_level(tmp_sev);
  2226. if (levelMin < 0) {
  2227. log_fn(LOG_WARN, "Unrecognized log severity '%s': must be one of "
  2228. "err|warn|notice|info|debug", tmp_sev);
  2229. tor_free(tmp_sev);
  2230. return -1;
  2231. }
  2232. tor_free(tmp_sev);
  2233. }
  2234. if (!*(cp+1)) {
  2235. levelMax = LOG_ERR;
  2236. } else {
  2237. levelMax = parse_log_level(cp+1);
  2238. if (levelMax < 0) {
  2239. log_fn(LOG_WARN, "Unrecognized log severity '%s': must be one of "
  2240. "err|warn|notice|info|debug", cp+1);
  2241. return -1;
  2242. }
  2243. }
  2244. } else {
  2245. levelMin = parse_log_level(range);
  2246. if (levelMin < 0) {
  2247. log_fn(LOG_WARN, "Unrecognized log severity '%s': must be one of "
  2248. "err|warn|notice|info|debug", range);
  2249. return -1;
  2250. }
  2251. levelMax = LOG_ERR;
  2252. }
  2253. *min_out = levelMin;
  2254. *max_out = levelMax;
  2255. return 0;
  2256. }
  2257. /** Try to convert a pair of old-style logging options [LogLevel, and
  2258. * (LogFile/Syslog)] to a new-style option, and add the new option to
  2259. * options->Logs. */
  2260. static int
  2261. convert_log_option(or_options_t *options, config_line_t *level_opt,
  2262. config_line_t *file_opt, int isDaemon)
  2263. {
  2264. int levelMin = -1, levelMax = -1;
  2265. if (level_opt) {
  2266. if (parse_log_severity_range(level_opt->value, &levelMin, &levelMax))
  2267. return -1;
  2268. }
  2269. if (levelMin < 0 && levelMax < 0) {
  2270. levelMin = LOG_NOTICE;
  2271. levelMax = LOG_ERR;
  2272. } else if (levelMin < 0) {
  2273. levelMin = levelMax;
  2274. } else {
  2275. levelMax = LOG_ERR;
  2276. }
  2277. if (file_opt && !strcasecmp(file_opt->key, "LogFile")) {
  2278. if (add_single_log_option(options, levelMin, levelMax, "file", file_opt->value) < 0) {
  2279. log_fn(LOG_WARN, "Cannot write to LogFile \"%s\": %s.", file_opt->value,
  2280. strerror(errno));
  2281. return -1;
  2282. }
  2283. } else if (file_opt && !strcasecmp(file_opt->key, "SysLog")) {
  2284. if (add_single_log_option(options, levelMin, levelMax, "syslog", NULL) < 0)
  2285. return -1;
  2286. } else if (!isDaemon) {
  2287. add_single_log_option(options, levelMin, levelMax, "stdout", NULL);
  2288. }
  2289. return 0;
  2290. }
  2291. /**
  2292. * Initialize the logs based on the configuration file.
  2293. */
  2294. int
  2295. options_init_logs(or_options_t *options, int validate_only)
  2296. {
  2297. config_line_t *opt;
  2298. int ok;
  2299. smartlist_t *elts;
  2300. ok = 1;
  2301. elts = smartlist_create();
  2302. for (opt = options->Logs; opt; opt = opt->next) {
  2303. int levelMin=LOG_DEBUG, levelMax=LOG_ERR;
  2304. smartlist_split_string(elts, opt->value, NULL,
  2305. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 3);
  2306. if (smartlist_len(elts) == 0) {
  2307. log_fn(LOG_WARN, "Bad syntax on Log option 'Log %s'", opt->value);
  2308. ok = 0; goto cleanup;
  2309. }
  2310. if (parse_log_severity_range(smartlist_get(elts,0), &levelMin, &levelMax)) {
  2311. ok = 0; goto cleanup;
  2312. }
  2313. if (smartlist_len(elts) < 2) { /* only loglevels were provided */
  2314. if (!validate_only)
  2315. add_stream_log(levelMin, levelMax, "<stdout>", stdout);
  2316. goto cleanup;
  2317. }
  2318. if (!strcasecmp(smartlist_get(elts,1), "file")) {
  2319. if (smartlist_len(elts) != 3) {
  2320. log_fn(LOG_WARN, "Bad syntax on Log option 'Log %s'", opt->value);
  2321. ok = 0; goto cleanup;
  2322. }
  2323. if (!validate_only)
  2324. add_file_log(levelMin, levelMax, smartlist_get(elts, 2));
  2325. goto cleanup;
  2326. }
  2327. if (smartlist_len(elts) != 2) {
  2328. log_fn(LOG_WARN, "Bad syntax on Log option 'Log %s'", opt->value);
  2329. ok = 0; goto cleanup;
  2330. }
  2331. if (!strcasecmp(smartlist_get(elts,1), "stdout")) {
  2332. if (!validate_only) {
  2333. add_stream_log(levelMin, levelMax, "<stdout>", stdout);
  2334. close_temp_logs();
  2335. }
  2336. } else if (!strcasecmp(smartlist_get(elts,1), "stderr")) {
  2337. if (!validate_only) {
  2338. add_stream_log(levelMin, levelMax, "<stderr>", stderr);
  2339. close_temp_logs();
  2340. }
  2341. } else if (!strcasecmp(smartlist_get(elts,1), "syslog")) {
  2342. #ifdef HAVE_SYSLOG_H
  2343. if (!validate_only)
  2344. add_syslog_log(levelMin, levelMax);
  2345. #else
  2346. log_fn(LOG_WARN, "Syslog is not supported in this compilation.");
  2347. #endif
  2348. } else {
  2349. log_fn(LOG_WARN, "Unrecognized log type %s",
  2350. (const char*)smartlist_get(elts,1));
  2351. if (strchr(smartlist_get(elts,1), '/')) {
  2352. log_fn(LOG_WARN, "Did you mean to say 'Log file %s' ?",
  2353. (const char *)smartlist_get(elts,1));
  2354. }
  2355. ok = 0; goto cleanup;
  2356. }
  2357. cleanup:
  2358. SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
  2359. smartlist_clear(elts);
  2360. }
  2361. smartlist_free(elts);
  2362. if (!validate_only)
  2363. close_temp_logs();
  2364. return ok?0:-1;
  2365. }
  2366. /** Add a single option of the form Log min-max \<type\> [fname] to options. */
  2367. static int
  2368. add_single_log_option(or_options_t *options, int minSeverity, int maxSeverity,
  2369. const char *type, const char *fname)
  2370. {
  2371. char buf[512];
  2372. int n;
  2373. n = tor_snprintf(buf, sizeof(buf), "%s%s%s %s%s%s",
  2374. log_level_to_string(minSeverity),
  2375. maxSeverity == LOG_ERR ? "" : "-",
  2376. maxSeverity == LOG_ERR ? "" : log_level_to_string(maxSeverity),
  2377. type, fname?" ":"", fname?fname:"");
  2378. if (n<0) {
  2379. log_fn(LOG_WARN, "Normalized log option too long.");
  2380. return -1;
  2381. }
  2382. log(LOG_WARN, "The old LogLevel/LogFile/DebugLogFile/SysLog options are deprecated, and will go away soon. Your new torrc line should be: 'Log %s'", buf);
  2383. config_line_append(&options->Logs, "Log", buf);
  2384. return 0;
  2385. }
  2386. /** Convert all old-style logging options to new-style Log options. Return 0
  2387. * on success, -1 on failure. */
  2388. static int
  2389. normalize_log_options(or_options_t *options)
  2390. {
  2391. /* The order of options is: Level? (File Level?)+
  2392. */
  2393. config_line_t *opt = options->OldLogOptions;
  2394. /* Special case for if first option is LogLevel. */
  2395. if (opt && !strcasecmp(opt->key, "LogLevel")) {
  2396. if (opt->next && (!strcasecmp(opt->next->key, "LogFile") ||
  2397. !strcasecmp(opt->next->key, "SysLog"))) {
  2398. if (convert_log_option(options, opt, opt->next, options->RunAsDaemon) < 0)
  2399. return -1;
  2400. opt = opt->next->next;
  2401. } else if (!opt->next) {
  2402. if (convert_log_option(options, opt, NULL, options->RunAsDaemon) < 0)
  2403. return -1;
  2404. opt = opt->next;
  2405. } else {
  2406. ; /* give warning below */
  2407. }
  2408. }
  2409. while (opt) {
  2410. if (!strcasecmp(opt->key, "LogLevel")) {
  2411. log_fn(LOG_WARN, "Two LogLevel options in a row without intervening LogFile or SysLog");
  2412. opt = opt->next;
  2413. } else {
  2414. tor_assert(!strcasecmp(opt->key, "LogFile") ||
  2415. !strcasecmp(opt->key, "SysLog"));
  2416. if (opt->next && !strcasecmp(opt->next->key, "LogLevel")) {
  2417. /* LogFile/SysLog followed by LogLevel */
  2418. if (convert_log_option(options,opt->next,opt, options->RunAsDaemon) < 0)
  2419. return -1;
  2420. opt = opt->next->next;
  2421. } else {
  2422. /* LogFile/SysLog followed by LogFile/SysLog or end of list. */
  2423. if (convert_log_option(options,NULL, opt, options->RunAsDaemon) < 0)
  2424. return -1;
  2425. opt = opt->next;
  2426. }
  2427. }
  2428. }
  2429. if (options->DebugLogFile) {
  2430. if (add_single_log_option(options, LOG_DEBUG, LOG_ERR, "file", options->DebugLogFile) < 0)
  2431. return -1;
  2432. }
  2433. tor_free(options->DebugLogFile);
  2434. config_free_lines(options->OldLogOptions);
  2435. options->OldLogOptions = NULL;
  2436. return 0;
  2437. }
  2438. #define DEFAULT_EXIT_POLICY "reject 0.0.0.0/8,reject 169.254.0.0/16,reject 127.0.0.0/8,reject 192.168.0.0/16,reject 10.0.0.0/8,reject 172.16.0.0/12,reject *:25,reject *:119,reject *:135-139,reject *:445,reject *:465,reject *:587,reject *:1214,reject *:4661-4666,reject *:6346-6429,reject *:6699,reject *:6881-6999,accept *:*"
  2439. /** Add the default exit policy entries to <b>policy</b>
  2440. */
  2441. void
  2442. options_append_default_exit_policy(addr_policy_t **policy)
  2443. {
  2444. config_line_t tmp;
  2445. addr_policy_t *ap;
  2446. tmp.key = NULL;
  2447. tmp.value = (char*)DEFAULT_EXIT_POLICY;
  2448. tmp.next = NULL;
  2449. config_parse_addr_policy(&tmp, policy, -1);
  2450. /* Remove redundant parts, if any. */
  2451. for (ap=*policy; ap; ap=ap->next) {
  2452. if (ap->msk == 0 && ap->prt_min <= 1 && ap->prt_max >= 65535) {
  2453. if (ap->next) {
  2454. addr_policy_free(ap->next);
  2455. ap->next = NULL;
  2456. }
  2457. return;
  2458. }
  2459. }
  2460. }
  2461. /**
  2462. * Given a linked list of config lines containing "allow" and "deny" tokens,
  2463. * parse them and append the result to <b>dest</b>. Return -1 if any tokens
  2464. * are malformed, else return 0.
  2465. */
  2466. int
  2467. config_parse_addr_policy(config_line_t *cfg,
  2468. addr_policy_t **dest,
  2469. int assume_action)
  2470. {
  2471. addr_policy_t **nextp;
  2472. smartlist_t *entries;
  2473. int r = 0;
  2474. if (!cfg)
  2475. return 0;
  2476. nextp = dest;
  2477. while (*nextp)
  2478. nextp = &((*nextp)->next);
  2479. entries = smartlist_create();
  2480. for (; cfg; cfg = cfg->next) {
  2481. smartlist_split_string(entries, cfg->value, ",", SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2482. SMARTLIST_FOREACH(entries, const char *, ent,
  2483. {
  2484. log_fn(LOG_DEBUG,"Adding new entry '%s'",ent);
  2485. *nextp = router_parse_addr_policy_from_string(ent, assume_action);
  2486. if (*nextp) {
  2487. nextp = &((*nextp)->next);
  2488. } else {
  2489. log_fn(LOG_WARN,"Malformed policy '%s'.", ent);
  2490. r = -1;
  2491. }
  2492. });
  2493. SMARTLIST_FOREACH(entries, char *, ent, tor_free(ent));
  2494. smartlist_clear(entries);
  2495. }
  2496. smartlist_free(entries);
  2497. return r;
  2498. }
  2499. /** Release all storage held by <b>p</b> */
  2500. void
  2501. addr_policy_free(addr_policy_t *p)
  2502. {
  2503. addr_policy_t *e;
  2504. while (p) {
  2505. e = p;
  2506. p = p->next;
  2507. tor_free(e->string);
  2508. tor_free(e);
  2509. }
  2510. }
  2511. /** Parse a single RedirectExit line's contents from <b>line</b>. If
  2512. * they are valid, and <b>result</b> is not NULL, add an element to
  2513. * <b>result</b> and return 0. Else if they are valid, return 0.
  2514. * Else return -1. */
  2515. static int
  2516. parse_redirect_line(smartlist_t *result, config_line_t *line)
  2517. {
  2518. smartlist_t *elements = NULL;
  2519. exit_redirect_t *r;
  2520. tor_assert(line);
  2521. r = tor_malloc_zero(sizeof(exit_redirect_t));
  2522. elements = smartlist_create();
  2523. smartlist_split_string(elements, line->value, NULL,
  2524. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2525. if (smartlist_len(elements) != 2) {
  2526. log_fn(LOG_WARN, "Wrong number of elements in RedirectExit line");
  2527. goto err;
  2528. }
  2529. if (parse_addr_and_port_range(smartlist_get(elements,0),&r->addr,&r->mask,
  2530. &r->port_min,&r->port_max)) {
  2531. log_fn(LOG_WARN, "Error parsing source address in RedirectExit line");
  2532. goto err;
  2533. }
  2534. if (0==strcasecmp(smartlist_get(elements,1), "pass")) {
  2535. r->is_redirect = 0;
  2536. } else {
  2537. if (parse_addr_port(smartlist_get(elements,1),NULL,&r->addr_dest,
  2538. &r->port_dest)) {
  2539. log_fn(LOG_WARN, "Error parsing dest address in RedirectExit line");
  2540. goto err;
  2541. }
  2542. r->is_redirect = 1;
  2543. }
  2544. goto done;
  2545. err:
  2546. tor_free(r);
  2547. done:
  2548. SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
  2549. smartlist_free(elements);
  2550. if (r) {
  2551. if (result)
  2552. smartlist_add(result, r);
  2553. else
  2554. tor_free(r);
  2555. return 0;
  2556. } else {
  2557. return -1;
  2558. }
  2559. }
  2560. /** Read the contents of a DirServer line from <b>line</b>. Return 0
  2561. * if the line is well-formed, and -1 if it isn't. If
  2562. * <b>validate_only</b> is 0, and the line is well-formed, then add
  2563. * the dirserver described in the line as a valid server. */
  2564. static int
  2565. parse_dir_server_line(const char *line, int validate_only)
  2566. {
  2567. smartlist_t *items = NULL;
  2568. int r;
  2569. char *addrport, *address=NULL;
  2570. uint16_t port;
  2571. char digest[DIGEST_LEN];
  2572. int supports_v1 = 1; /*XXXX011 change default when clients support v2. */
  2573. while (TOR_ISSPACE(*line))
  2574. ++line;
  2575. if (!strcmpstart(line, "v1 ")) {
  2576. line += 3;
  2577. supports_v1 = 1;
  2578. }
  2579. items = smartlist_create();
  2580. smartlist_split_string(items, line, NULL,
  2581. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
  2582. if (smartlist_len(items) < 2) {
  2583. log_fn(LOG_WARN, "Too few arguments to DirServer line.");
  2584. goto err;
  2585. }
  2586. addrport = smartlist_get(items, 0);
  2587. if (parse_addr_port(addrport, &address, NULL, &port)<0) {
  2588. log_fn(LOG_WARN, "Error parsing DirServer address '%s'", addrport);
  2589. goto err;
  2590. }
  2591. if (!port) {
  2592. log_fn(LOG_WARN, "Missing port in DirServer address '%s'",addrport);
  2593. goto err;
  2594. }
  2595. tor_strstrip(smartlist_get(items, 1), " ");
  2596. if (strlen(smartlist_get(items, 1)) != HEX_DIGEST_LEN) {
  2597. log_fn(LOG_WARN, "Key digest for DirServer is wrong length.");
  2598. goto err;
  2599. }
  2600. if (base16_decode(digest, DIGEST_LEN,
  2601. smartlist_get(items,1), HEX_DIGEST_LEN)<0) {
  2602. log_fn(LOG_WARN, "Unable to decode DirServer key digest.");
  2603. goto err;
  2604. }
  2605. if (!validate_only) {
  2606. log_fn(LOG_DEBUG, "Trusted dirserver at %s:%d (%s)", address, (int)port,
  2607. (char*)smartlist_get(items,1));
  2608. add_trusted_dir_server(address, port, digest, supports_v1);
  2609. }
  2610. r = 0;
  2611. goto done;
  2612. err:
  2613. r = -1;
  2614. done:
  2615. SMARTLIST_FOREACH(items, char*, s, tor_free(s));
  2616. smartlist_free(items);
  2617. tor_free(address);
  2618. return r;
  2619. }
  2620. /** Adjust the value of options->DataDirectory, or fill it in if it's
  2621. * absent. Return 0 on success, -1 on failure. */
  2622. static int
  2623. normalize_data_directory(or_options_t *options)
  2624. {
  2625. #ifdef MS_WINDOWS
  2626. char *p;
  2627. if (options->DataDirectory)
  2628. return 0; /* all set */
  2629. p = tor_malloc(MAX_PATH);
  2630. strlcpy(p,get_windows_conf_root(),MAX_PATH);
  2631. options->DataDirectory = p;
  2632. return 0;
  2633. #else
  2634. const char *d = options->DataDirectory;
  2635. if (!d)
  2636. d = "~/.tor";
  2637. if (strncmp(d,"~/",2) == 0) {
  2638. char *fn = expand_filename(d);
  2639. if (!fn) {
  2640. log_fn(LOG_ERR,"Failed to expand filename \"%s\".", d);
  2641. return -1;
  2642. }
  2643. if (!options->DataDirectory && !strcmp(fn,"/.tor")) {
  2644. /* If our homedir is /, we probably don't want to use it. */
  2645. /* XXXX Default to /var/lib/tor? */
  2646. log_fn(LOG_WARN, "Default DataDirectory is \"~/.tor\". This expands to \"%s\", which is probably not what you want. Using \"%s/tor\" instead", fn, LOCALSTATEDIR);
  2647. tor_free(fn);
  2648. fn = tor_strdup(LOCALSTATEDIR"/tor");
  2649. }
  2650. tor_free(options->DataDirectory);
  2651. options->DataDirectory = fn;
  2652. }
  2653. return 0;
  2654. #endif
  2655. }
  2656. /** Check and normalize the value of options->DataDirectory; return 0 if it
  2657. * sane, -1 otherwise. */
  2658. static int
  2659. validate_data_directory(or_options_t *options)
  2660. {
  2661. if (normalize_data_directory(options) < 0)
  2662. return -1;
  2663. tor_assert(options->DataDirectory);
  2664. if (strlen(options->DataDirectory) > (512-128)) {
  2665. log_fn(LOG_ERR, "DataDirectory is too long.");
  2666. return -1;
  2667. }
  2668. return 0;
  2669. }
  2670. #define GENERATED_FILE_PREFIX "# This file was generated by Tor; if you edit it, comments will not be preserved"
  2671. /** Save a configuration file for the configuration in <b>options</b>
  2672. * into the file <b>fname</b>. If the file already exists, and
  2673. * doesn't begin with GENERATED_FILE_PREFIX, rename it. Otherwise
  2674. * replace it. Return 0 on success, -1 on failure. */
  2675. static int
  2676. write_configuration_file(const char *fname, or_options_t *options)
  2677. {
  2678. char *old_val=NULL, *new_val=NULL, *new_conf=NULL;
  2679. int rename_old = 0, r;
  2680. size_t len;
  2681. if (fname) {
  2682. switch (file_status(fname)) {
  2683. case FN_FILE:
  2684. old_val = read_file_to_str(fname, 0);
  2685. if (strcmpstart(old_val, GENERATED_FILE_PREFIX)) {
  2686. rename_old = 1;
  2687. }
  2688. tor_free(old_val);
  2689. break;
  2690. case FN_NOENT:
  2691. break;
  2692. default:
  2693. log_fn(LOG_WARN,"Config file \"%s\" is not a file? Failing.", fname);
  2694. return -1;
  2695. }
  2696. }
  2697. if (!(new_conf = options_dump(options, 1))) {
  2698. log_fn(LOG_WARN, "Couldn't get configuration string");
  2699. goto err;
  2700. }
  2701. len = strlen(new_conf)+128;
  2702. new_val = tor_malloc(len);
  2703. tor_snprintf(new_val, len, "%s\n\n%s", GENERATED_FILE_PREFIX, new_conf);
  2704. if (rename_old) {
  2705. int i = 1;
  2706. size_t fn_tmp_len = strlen(fname)+32;
  2707. char *fn_tmp;
  2708. tor_assert(fn_tmp_len > strlen(fname)); /*check for overflow*/
  2709. fn_tmp = tor_malloc(fn_tmp_len);
  2710. while (1) {
  2711. if (tor_snprintf(fn_tmp, fn_tmp_len, "%s.orig.%d", fname, i)<0) {
  2712. log_fn(LOG_WARN, "tor_snprintf failed inexplicably");
  2713. tor_free(fn_tmp);
  2714. goto err;
  2715. }
  2716. if (file_status(fn_tmp) == FN_NOENT)
  2717. break;
  2718. ++i;
  2719. }
  2720. log_fn(LOG_NOTICE, "Renaming old configuration file to \"%s\"", fn_tmp);
  2721. rename(fname, fn_tmp);
  2722. tor_free(fn_tmp);
  2723. }
  2724. write_str_to_file(fname, new_val, 0);
  2725. r = 0;
  2726. goto done;
  2727. err:
  2728. r = -1;
  2729. done:
  2730. tor_free(new_val);
  2731. tor_free(new_conf);
  2732. return r;
  2733. }
  2734. /**
  2735. * Save the current configuration file value to disk. Return 0 on
  2736. * success, -1 on failure.
  2737. **/
  2738. int
  2739. options_save_current(void)
  2740. {
  2741. if (torrc_fname) {
  2742. /* XXX This fails if we can't write to our configuration file.
  2743. * Arguably, we should try falling back to datadirectory or something.
  2744. * But just as arguably, we shouldn't. */
  2745. return write_configuration_file(torrc_fname, get_options());
  2746. }
  2747. return write_configuration_file(get_default_conf_file(), get_options());
  2748. }
  2749. struct unit_table_t {
  2750. const char *unit;
  2751. uint64_t multiplier;
  2752. };
  2753. static struct unit_table_t memory_units[] = {
  2754. { "", 1 },
  2755. { "b", 1<< 0 },
  2756. { "byte", 1<< 0 },
  2757. { "bytes", 1<< 0 },
  2758. { "kb", 1<<10 },
  2759. { "kilobyte", 1<<10 },
  2760. { "kilobytes", 1<<10 },
  2761. { "m", 1<<20 },
  2762. { "mb", 1<<20 },
  2763. { "megabyte", 1<<20 },
  2764. { "megabytes", 1<<20 },
  2765. { "gb", 1<<30 },
  2766. { "gigabyte", 1<<30 },
  2767. { "gigabytes", 1<<30 },
  2768. { "tb", U64_LITERAL(1)<<40 },
  2769. { "terabyte", U64_LITERAL(1)<<40 },
  2770. { "terabytes", U64_LITERAL(1)<<40 },
  2771. { NULL, 0 },
  2772. };
  2773. static struct unit_table_t time_units[] = {
  2774. { "", 1 },
  2775. { "second", 1 },
  2776. { "seconds", 1 },
  2777. { "minute", 60 },
  2778. { "minutes", 60 },
  2779. { "hour", 60*60 },
  2780. { "hours", 60*60 },
  2781. { "day", 24*60*60 },
  2782. { "days", 24*60*60 },
  2783. { "week", 7*24*60*60 },
  2784. { "weeks", 7*24*60*60 },
  2785. { NULL, 0 },
  2786. };
  2787. /** Parse a string <b>val</b> containing a number, zero or more
  2788. * spaces, and an optional unit string. If the unit appears in the
  2789. * table <b>u</b>, then multiply the number by the unit multiplier.
  2790. * On success, set *<b>ok</b> to 1 and return this product.
  2791. * Otherwise, set *<b>ok</b> to 0.
  2792. */
  2793. static uint64_t
  2794. config_parse_units(const char *val, struct unit_table_t *u, int *ok)
  2795. {
  2796. uint64_t v;
  2797. char *cp;
  2798. tor_assert(ok);
  2799. v = tor_parse_uint64(val, 10, 0, UINT64_MAX, ok, &cp);
  2800. if (!*ok)
  2801. return 0;
  2802. if (!cp) {
  2803. *ok = 1;
  2804. return v;
  2805. }
  2806. while (TOR_ISSPACE(*cp))
  2807. ++cp;
  2808. for ( ;u->unit;++u) {
  2809. if (!strcasecmp(u->unit, cp)) {
  2810. v *= u->multiplier;
  2811. *ok = 1;
  2812. return v;
  2813. }
  2814. }
  2815. log_fn(LOG_WARN, "Unknown unit '%s'.", cp);
  2816. *ok = 0;
  2817. return 0;
  2818. }
  2819. /** Parse a string in the format "number unit", where unit is a unit of
  2820. * information (byte, KB, M, etc). On success, set *<b>ok</b> to true
  2821. * and return the number of bytes specified. Otherwise, set
  2822. * *<b>ok</b> to false and return 0. */
  2823. static uint64_t
  2824. config_parse_memunit(const char *s, int *ok) {
  2825. return config_parse_units(s, memory_units, ok);
  2826. }
  2827. /** Parse a string in the format "number unit", where unit is a unit of time.
  2828. * On success, set *<b>ok</b> to true and return the number of seconds in
  2829. * the provided interval. Otherwise, set *<b>ok</b> to 0 and return -1.
  2830. */
  2831. static int
  2832. config_parse_interval(const char *s, int *ok) {
  2833. uint64_t r;
  2834. r = config_parse_units(s, time_units, ok);
  2835. if (!ok)
  2836. return -1;
  2837. if (r > INT_MAX) {
  2838. log_fn(LOG_WARN, "Interval '%s' is too long", s);
  2839. *ok = 0;
  2840. return -1;
  2841. }
  2842. return (int)r;
  2843. }
  2844. /**
  2845. * Initialize the libevent library.
  2846. */
  2847. static int
  2848. init_libevent(void)
  2849. {
  2850. configure_libevent_logging();
  2851. /* If the kernel complains that some method (say, epoll) doesn't
  2852. * exist, we don't care about it, since libevent will cope.
  2853. */
  2854. suppress_libevent_log_msg("Function not implemented");
  2855. #ifdef __APPLE__
  2856. setenv("EVENT_NOKQUEUE","1",1);
  2857. #endif
  2858. event_init();
  2859. suppress_libevent_log_msg(NULL);
  2860. #if defined(HAVE_EVENT_GET_VERSION) && defined(HAVE_EVENT_GET_METHOD)
  2861. /* Making this a NOTICE for now so we can link bugs to a libevent versions
  2862. * or methods better. */
  2863. log(LOG_NOTICE, "Initialized libevent version %s using method %s. Good.",
  2864. event_get_version(), event_get_method());
  2865. check_libevent_version(event_get_method(), event_get_version(),
  2866. get_options()->ORPort != 0);
  2867. #else
  2868. log(LOG_NOTICE, "Initialized old libevent (version 1.0b or earlier).");
  2869. log(LOG_WARN, "You have a very old version of libevent. It is likely to be buggy; please consider building Tor with a more recent version.");
  2870. #endif
  2871. return 0;
  2872. }
  2873. #if defined(HAVE_EVENT_GET_VERSION) && defined(HAVE_EVENT_GET_METHOD)
  2874. /**
  2875. * Compare the given libevent method and version to a list of versions
  2876. * which are known not to work. Warn the user as appropriate.
  2877. *
  2878. */
  2879. static void
  2880. check_libevent_version(const char *m, const char *v, int server)
  2881. {
  2882. int buggy = 0, iffy = 0, slow = 0;
  2883. tor_assert(m && v);
  2884. if (!strcmp(m, "kqueue")) {
  2885. if (!strcmp(v, "1.0c") || !strcmp(v, "1.0d") || !strcmp(v, "1.0e") ||
  2886. !strcmp(v, "1.1")) {
  2887. buggy = 1;
  2888. }
  2889. } else if (!strcmp(m, "epoll")) {
  2890. if (!strcmp(v, "1.0c") || !strcmp(v, "1.0d") || !strcmp(v, "1.0e"))
  2891. iffy = 1;
  2892. } else if (!strcmp(m, "poll")) {
  2893. if (!strcmp(v, "1.0c") || !strcmp(v, "1.0d"))
  2894. buggy = 1;
  2895. else if (!strcmp(v, "1.0e"))
  2896. slow = 1;
  2897. } else if (!strcmp(m, "poll")) {
  2898. if (!strcmp(v, "1.0c") || !strcmp(v, "1.0d") || !strcmp(v, "1.0e"))
  2899. slow = 1;
  2900. }
  2901. if (buggy) {
  2902. log(LOG_WARN,
  2903. "There are known bugs in using %s with libevent %s. "
  2904. "Please use the latest version of libevent.", m, v);
  2905. } else if (iffy) {
  2906. log(LOG_WARN,
  2907. "There are minor bugs in using %s with libevent %s. "
  2908. "You may want to use the latest version of libevent.", m, v);
  2909. } else if (slow && server) {
  2910. log(LOG_WARN,
  2911. "libevent %s can be very slow with %s. "
  2912. "When running a server, please use the latest version of libevent.",v,m);
  2913. }
  2914. }
  2915. #endif
  2916. /* Versioning issues and state: we want to be able to understand old state
  2917. * files, and not choke on new ones.
  2918. *
  2919. * We could preserve all unrecognized variables across invocations, but we could
  2920. * screw up order, if their order is significant with respect to existing
  2921. * options.
  2922. *
  2923. * We could just dump unrecognized variables if you downgrade.
  2924. *
  2925. * This needs thought. XXXX NM
  2926. */
  2927. /** DOCDOC */
  2928. or_state_t *
  2929. get_or_state(void)
  2930. {
  2931. return global_state;
  2932. }
  2933. /** DOCDOC */
  2934. static char *
  2935. get_or_state_fname(void)
  2936. {
  2937. char *fname = NULL;
  2938. or_options_t *options = get_options();
  2939. size_t len = strlen(options->DataDirectory) + 16;
  2940. fname = tor_malloc(len);
  2941. tor_snprintf(fname, len, "%s/state", options->DataDirectory);
  2942. return fname;
  2943. }
  2944. /** DOCDOC */
  2945. static int
  2946. or_state_validate(or_state_t *state)
  2947. {
  2948. const char *err;
  2949. if (helper_nodes_parse_state(state, 0, &err)<0) {
  2950. log_fn(LOG_WARN, "Unable to parse helper nodes: %s", err);
  2951. return -1;
  2952. }
  2953. return 0;
  2954. }
  2955. /** DOCDOC */
  2956. static void
  2957. or_state_set(or_state_t *new_state)
  2958. {
  2959. const char *err;
  2960. tor_assert(new_state);
  2961. if (global_state)
  2962. config_free(&state_format, global_state);
  2963. global_state = new_state;
  2964. if (helper_nodes_parse_state(global_state, 1, &err)<0)
  2965. log_fn(LOG_WARN,"Unparseable helper nodes state: %s",err);
  2966. }
  2967. /* DOCDOC */
  2968. int
  2969. or_state_load(void)
  2970. {
  2971. or_state_t *new_state = NULL;
  2972. char *contents = NULL, *fname;
  2973. int r = -1;
  2974. fname = get_or_state_fname();
  2975. switch (file_status(fname)) {
  2976. case FN_FILE:
  2977. if (!(contents = read_file_to_str(fname, 0))) {
  2978. log_fn(LOG_WARN, "Unable to read state file \"%s\"", fname);
  2979. goto done;
  2980. }
  2981. break;
  2982. case FN_NOENT:
  2983. break;
  2984. default:
  2985. log_fn(LOG_WARN,"State file \"%s\" is not a file? Failing.", fname);
  2986. goto done;
  2987. }
  2988. new_state = tor_malloc_zero(sizeof(or_state_t));
  2989. new_state->_magic = OR_STATE_MAGIC;
  2990. config_init(&state_format, new_state);
  2991. if (contents) {
  2992. config_line_t *lines=NULL;
  2993. int assign_retval;
  2994. if (config_get_lines(contents, &lines)<0)
  2995. goto done;
  2996. assign_retval = config_assign(&state_format, new_state, lines, 0, 0);
  2997. config_free_lines(lines);
  2998. if (assign_retval<0)
  2999. goto done;
  3000. }
  3001. if (or_state_validate(new_state) < 0)
  3002. goto done;
  3003. if (contents)
  3004. log_fn(LOG_INFO, "Loaded state from \"%s\"", fname);
  3005. else
  3006. log_fn(LOG_INFO, "Initialized state");
  3007. or_state_set(new_state);
  3008. new_state = NULL;
  3009. if (!contents) {
  3010. global_state->dirty = 1;
  3011. or_state_save();
  3012. }
  3013. r = 0;
  3014. done:
  3015. tor_free(fname);
  3016. tor_free(contents);
  3017. if (new_state)
  3018. config_free(&state_format, new_state);
  3019. return r;
  3020. }
  3021. /** DOCDOC */
  3022. int
  3023. or_state_save(void)
  3024. {
  3025. char *state, *contents;
  3026. char tbuf[ISO_TIME_LEN+1];
  3027. size_t len;
  3028. char *fname;
  3029. helper_nodes_update_state(global_state);
  3030. if (!global_state->dirty)
  3031. return 0;
  3032. global_state->LastWritten = time(NULL);
  3033. state = config_dump(&state_format, global_state, 0);
  3034. len = strlen(state)+128;
  3035. contents = tor_malloc(len);
  3036. format_local_iso_time(tbuf, time(NULL));
  3037. tor_snprintf(contents, len,
  3038. "# Tor state file last generated on %s\n"
  3039. "# You *do not* need to edit this file.\n\n%s",
  3040. tbuf, state);
  3041. tor_free(state);
  3042. fname = get_or_state_fname();
  3043. if (write_str_to_file(fname, contents, 0)<0) {
  3044. log_fn(LOG_WARN, "Unable to write state to file \"%s\"", fname);
  3045. tor_free(fname);
  3046. tor_free(contents);
  3047. return -1;
  3048. }
  3049. log_fn(LOG_INFO, "Saved state to \"%s\"", fname);
  3050. tor_free(fname);
  3051. tor_free(contents);
  3052. global_state->dirty = 0;
  3053. return 0;
  3054. }
  3055. /** DOCDOC */
  3056. int
  3057. config_getinfo_helper(const char *question, char **answer)
  3058. {
  3059. if (!strcmp(question, "config/names")) {
  3060. smartlist_t *sl = smartlist_create();
  3061. int i;
  3062. for (i = 0; _option_vars[i].name; ++i) {
  3063. config_var_t *var = &_option_vars[i];
  3064. const char *type, *desc;
  3065. char *line;
  3066. size_t len;
  3067. desc = config_find_description(&options_format, var->name);
  3068. switch (var->type) {
  3069. case CONFIG_TYPE_STRING: type = "String"; break;
  3070. case CONFIG_TYPE_UINT: type = "Integer"; break;
  3071. case CONFIG_TYPE_INTERVAL: type = "TimeInterval"; break;
  3072. case CONFIG_TYPE_MEMUNIT: type = "DataSize"; break;
  3073. case CONFIG_TYPE_DOUBLE: type = "Float"; break;
  3074. case CONFIG_TYPE_BOOL: type = "Boolean"; break;
  3075. case CONFIG_TYPE_ISOTIME: type = "Time"; break;
  3076. case CONFIG_TYPE_CSV: type = "CommaList"; break;
  3077. case CONFIG_TYPE_LINELIST: type = "LineList"; break;
  3078. case CONFIG_TYPE_LINELIST_S: type = "Dependant"; break;
  3079. case CONFIG_TYPE_LINELIST_V: type = "Virtual"; break;
  3080. default:
  3081. case CONFIG_TYPE_OBSOLETE:
  3082. type = NULL; break;
  3083. }
  3084. if (!type)
  3085. continue;
  3086. len = strlen(var->name)+strlen(type)+16;
  3087. if (desc)
  3088. len += strlen(desc);
  3089. line = tor_malloc(len);
  3090. if (desc)
  3091. tor_snprintf(line, len, "%s %s %s\n",var->name,type,desc);
  3092. else
  3093. tor_snprintf(line, len, "%s %s\n",var->name,type);
  3094. smartlist_add(sl, line);
  3095. }
  3096. *answer = smartlist_join_strings(sl, "", 0, NULL);
  3097. SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  3098. smartlist_free(sl);
  3099. }
  3100. return 0;
  3101. }
  3102. /** Dump the version of every file to the log. */
  3103. static void
  3104. print_cvs_version(void)
  3105. {
  3106. extern const char aes_c_id[];
  3107. extern const char compat_c_id[];
  3108. extern const char container_c_id[];
  3109. extern const char crypto_c_id[];
  3110. extern const char log_c_id[];
  3111. extern const char torgzip_c_id[];
  3112. extern const char tortls_c_id[];
  3113. extern const char util_c_id[];
  3114. extern const char buffers_c_id[];
  3115. extern const char circuitbuild_c_id[];
  3116. extern const char circuitlist_c_id[];
  3117. extern const char circuituse_c_id[];
  3118. extern const char command_c_id[];
  3119. // extern const char config_c_id[];
  3120. extern const char connection_c_id[];
  3121. extern const char connection_edge_c_id[];
  3122. extern const char connection_or_c_id[];
  3123. extern const char control_c_id[];
  3124. extern const char cpuworker_c_id[];
  3125. extern const char directory_c_id[];
  3126. extern const char dirserv_c_id[];
  3127. extern const char dns_c_id[];
  3128. extern const char hibernate_c_id[];
  3129. extern const char main_c_id[];
  3130. extern const char onion_c_id[];
  3131. extern const char relay_c_id[];
  3132. extern const char rendclient_c_id[];
  3133. extern const char rendcommon_c_id[];
  3134. extern const char rendmid_c_id[];
  3135. extern const char rendservice_c_id[];
  3136. extern const char rephist_c_id[];
  3137. extern const char router_c_id[];
  3138. extern const char routerlist_c_id[];
  3139. extern const char routerparse_c_id[];
  3140. puts(AES_H_ID);
  3141. puts(COMPAT_H_ID);
  3142. puts(CONTAINER_H_ID);
  3143. puts(CRYPTO_H_ID);
  3144. puts(LOG_H_ID);
  3145. puts(TORGZIP_H_ID);
  3146. puts(TORINT_H_ID);
  3147. puts(TORTLS_H_ID);
  3148. puts(UTIL_H_ID);
  3149. puts(aes_c_id);
  3150. puts(compat_c_id);
  3151. puts(container_c_id);
  3152. puts(crypto_c_id);
  3153. puts(log_c_id);
  3154. puts(torgzip_c_id);
  3155. puts(tortls_c_id);
  3156. puts(util_c_id);
  3157. puts(OR_H_ID);
  3158. puts(buffers_c_id);
  3159. puts(circuitbuild_c_id);
  3160. puts(circuitlist_c_id);
  3161. puts(circuituse_c_id);
  3162. puts(command_c_id);
  3163. puts(config_c_id);
  3164. puts(connection_c_id);
  3165. puts(connection_edge_c_id);
  3166. puts(connection_or_c_id);
  3167. puts(control_c_id);
  3168. puts(cpuworker_c_id);
  3169. puts(directory_c_id);
  3170. puts(dirserv_c_id);
  3171. puts(dns_c_id);
  3172. puts(hibernate_c_id);
  3173. puts(main_c_id);
  3174. puts(onion_c_id);
  3175. puts(relay_c_id);
  3176. puts(rendclient_c_id);
  3177. puts(rendcommon_c_id);
  3178. puts(rendmid_c_id);
  3179. puts(rendservice_c_id);
  3180. puts(rephist_c_id);
  3181. puts(router_c_id);
  3182. puts(routerlist_c_id);
  3183. puts(routerparse_c_id);
  3184. }