config.c 94 KB

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