config.c 121 KB

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