config.c 108 KB

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