config.c 115 KB

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