config.c 99 KB

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