You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

config.go 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760
  1. // Copyright (c) 2012-2014 Jeremy Latt
  2. // Copyright (c) 2014-2015 Edmund Huber
  3. // Copyright (c) 2016-2017 Daniel Oaks <daniel@danieloaks.net>
  4. // released under the MIT license
  5. package irc
  6. import (
  7. "crypto/tls"
  8. "fmt"
  9. "io/ioutil"
  10. "log"
  11. "net"
  12. "os"
  13. "regexp"
  14. "sort"
  15. "strings"
  16. "time"
  17. "code.cloudfoundry.org/bytefmt"
  18. "github.com/oragono/oragono/irc/cloaks"
  19. "github.com/oragono/oragono/irc/connection_limits"
  20. "github.com/oragono/oragono/irc/custime"
  21. "github.com/oragono/oragono/irc/isupport"
  22. "github.com/oragono/oragono/irc/languages"
  23. "github.com/oragono/oragono/irc/logger"
  24. "github.com/oragono/oragono/irc/modes"
  25. "github.com/oragono/oragono/irc/passwd"
  26. "github.com/oragono/oragono/irc/utils"
  27. "gopkg.in/yaml.v2"
  28. )
  29. // here's how this works: exported (capitalized) members of the config structs
  30. // are defined in the YAML file and deserialized directly from there. They may
  31. // be postprocessed and overwritten by LoadConfig. Unexported (lowercase) members
  32. // are derived from the exported members in LoadConfig.
  33. // TLSListenConfig defines configuration options for listening on TLS.
  34. type TLSListenConfig struct {
  35. Cert string
  36. Key string
  37. }
  38. // Config returns the TLS contiguration assicated with this TLSListenConfig.
  39. func (conf *TLSListenConfig) Config() (*tls.Config, error) {
  40. cert, err := tls.LoadX509KeyPair(conf.Cert, conf.Key)
  41. if err != nil {
  42. return nil, ErrInvalidCertKeyPair
  43. }
  44. return &tls.Config{
  45. Certificates: []tls.Certificate{cert},
  46. }, err
  47. }
  48. type AccountConfig struct {
  49. Registration AccountRegistrationConfig
  50. AuthenticationEnabled bool `yaml:"authentication-enabled"`
  51. RequireSasl struct {
  52. Enabled bool
  53. Exempted []string
  54. exemptedNets []net.IPNet
  55. } `yaml:"require-sasl"`
  56. LoginThrottling struct {
  57. Enabled bool
  58. Duration time.Duration
  59. MaxAttempts int `yaml:"max-attempts"`
  60. } `yaml:"login-throttling"`
  61. SkipServerPassword bool `yaml:"skip-server-password"`
  62. NickReservation NickReservationConfig `yaml:"nick-reservation"`
  63. Bouncer struct {
  64. Enabled bool
  65. AllowedByDefault bool `yaml:"allowed-by-default"`
  66. }
  67. VHosts VHostConfig
  68. }
  69. // AccountRegistrationConfig controls account registration.
  70. type AccountRegistrationConfig struct {
  71. Enabled bool
  72. EnabledCallbacks []string `yaml:"enabled-callbacks"`
  73. EnabledCredentialTypes []string `yaml:"-"`
  74. VerifyTimeout time.Duration `yaml:"verify-timeout"`
  75. Callbacks struct {
  76. Mailto struct {
  77. Server string
  78. Port int
  79. TLS struct {
  80. Enabled bool
  81. InsecureSkipVerify bool `yaml:"insecure_skip_verify"`
  82. ServerName string `yaml:"servername"`
  83. }
  84. Username string
  85. Password string
  86. Sender string
  87. VerifyMessageSubject string `yaml:"verify-message-subject"`
  88. VerifyMessage string `yaml:"verify-message"`
  89. }
  90. }
  91. BcryptCost uint `yaml:"bcrypt-cost"`
  92. }
  93. type VHostConfig struct {
  94. Enabled bool
  95. MaxLength int `yaml:"max-length"`
  96. ValidRegexpRaw string `yaml:"valid-regexp"`
  97. ValidRegexp *regexp.Regexp
  98. UserRequests struct {
  99. Enabled bool
  100. Channel string
  101. Cooldown time.Duration
  102. } `yaml:"user-requests"`
  103. }
  104. type NickEnforcementMethod int
  105. const (
  106. // NickEnforcementOptional is the zero value; it serializes to
  107. // "optional" in the yaml config, and "default" as an arg to `NS ENFORCE`.
  108. // in both cases, it means "defer to the other source of truth", i.e.,
  109. // in the config, defer to the user's custom setting, and as a custom setting,
  110. // defer to the default in the config. if both are NickEnforcementOptional then
  111. // there is no enforcement.
  112. // XXX: these are serialized as numbers in the database, so beware of collisions
  113. // when refactoring (any numbers currently in use must keep their meanings, or
  114. // else be fixed up by a schema change)
  115. NickEnforcementOptional NickEnforcementMethod = iota
  116. NickEnforcementNone
  117. NickEnforcementWithTimeout
  118. NickEnforcementStrict
  119. )
  120. func nickReservationToString(method NickEnforcementMethod) string {
  121. switch method {
  122. case NickEnforcementOptional:
  123. return "default"
  124. case NickEnforcementNone:
  125. return "none"
  126. case NickEnforcementWithTimeout:
  127. return "timeout"
  128. case NickEnforcementStrict:
  129. return "strict"
  130. default:
  131. return ""
  132. }
  133. }
  134. func nickReservationFromString(method string) (NickEnforcementMethod, error) {
  135. switch strings.ToLower(method) {
  136. case "default":
  137. return NickEnforcementOptional, nil
  138. case "optional":
  139. return NickEnforcementOptional, nil
  140. case "none":
  141. return NickEnforcementNone, nil
  142. case "timeout":
  143. return NickEnforcementWithTimeout, nil
  144. case "strict":
  145. return NickEnforcementStrict, nil
  146. default:
  147. return NickEnforcementOptional, fmt.Errorf("invalid nick-reservation.method value: %s", method)
  148. }
  149. }
  150. func (nr *NickEnforcementMethod) UnmarshalYAML(unmarshal func(interface{}) error) error {
  151. var orig string
  152. var err error
  153. if err = unmarshal(&orig); err != nil {
  154. return err
  155. }
  156. method, err := nickReservationFromString(orig)
  157. if err == nil {
  158. *nr = method
  159. }
  160. return err
  161. }
  162. type NickReservationConfig struct {
  163. Enabled bool
  164. AdditionalNickLimit int `yaml:"additional-nick-limit"`
  165. Method NickEnforcementMethod
  166. AllowCustomEnforcement bool `yaml:"allow-custom-enforcement"`
  167. RenameTimeout time.Duration `yaml:"rename-timeout"`
  168. RenamePrefix string `yaml:"rename-prefix"`
  169. }
  170. // ChannelRegistrationConfig controls channel registration.
  171. type ChannelRegistrationConfig struct {
  172. Enabled bool
  173. MaxChannelsPerAccount int `yaml:"max-channels-per-account"`
  174. }
  175. // OperClassConfig defines a specific operator class.
  176. type OperClassConfig struct {
  177. Title string
  178. WhoisLine string
  179. Extends string
  180. Capabilities []string
  181. }
  182. // OperConfig defines a specific operator's configuration.
  183. type OperConfig struct {
  184. Class string
  185. Vhost string
  186. WhoisLine string `yaml:"whois-line"`
  187. Password string
  188. Modes string
  189. }
  190. // LineLenConfig controls line lengths.
  191. type LineLenLimits struct {
  192. Rest int
  193. }
  194. // Various server-enforced limits on data size.
  195. type Limits struct {
  196. AwayLen int `yaml:"awaylen"`
  197. ChanListModes int `yaml:"chan-list-modes"`
  198. ChannelLen int `yaml:"channellen"`
  199. IdentLen int `yaml:"identlen"`
  200. KickLen int `yaml:"kicklen"`
  201. LineLen LineLenLimits `yaml:"linelen"`
  202. MonitorEntries int `yaml:"monitor-entries"`
  203. NickLen int `yaml:"nicklen"`
  204. TopicLen int `yaml:"topiclen"`
  205. WhowasEntries int `yaml:"whowas-entries"`
  206. RegistrationMessages int `yaml:"registration-messages"`
  207. }
  208. // STSConfig controls the STS configuration/
  209. type STSConfig struct {
  210. Enabled bool
  211. Duration time.Duration `yaml:"duration-real"`
  212. DurationString string `yaml:"duration"`
  213. Port int
  214. Preload bool
  215. }
  216. // Value returns the STS value to advertise in CAP
  217. func (sts *STSConfig) Value() string {
  218. val := fmt.Sprintf("duration=%d", int(sts.Duration.Seconds()))
  219. if sts.Enabled && sts.Port > 0 {
  220. val += fmt.Sprintf(",port=%d", sts.Port)
  221. }
  222. if sts.Enabled && sts.Preload {
  223. val += ",preload"
  224. }
  225. return val
  226. }
  227. type FakelagConfig struct {
  228. Enabled bool
  229. Window time.Duration
  230. BurstLimit uint `yaml:"burst-limit"`
  231. MessagesPerWindow uint `yaml:"messages-per-window"`
  232. Cooldown time.Duration
  233. }
  234. type TorListenersConfig struct {
  235. Listeners []string
  236. RequireSasl bool `yaml:"require-sasl"`
  237. Vhost string
  238. MaxConnections int `yaml:"max-connections"`
  239. ThrottleDuration time.Duration `yaml:"throttle-duration"`
  240. MaxConnectionsPerDuration int `yaml:"max-connections-per-duration"`
  241. }
  242. // Config defines the overall configuration.
  243. type Config struct {
  244. Network struct {
  245. Name string
  246. }
  247. Server struct {
  248. Password string
  249. passwordBytes []byte
  250. Name string
  251. nameCasefolded string
  252. Listen []string
  253. UnixBindMode os.FileMode `yaml:"unix-bind-mode"`
  254. TLSListeners map[string]*TLSListenConfig `yaml:"tls-listeners"`
  255. TorListeners TorListenersConfig `yaml:"tor-listeners"`
  256. STS STSConfig
  257. CheckIdent bool `yaml:"check-ident"`
  258. MOTD string
  259. motdLines []string
  260. MOTDFormatting bool `yaml:"motd-formatting"`
  261. ProxyAllowedFrom []string `yaml:"proxy-allowed-from"`
  262. proxyAllowedFromNets []net.IPNet
  263. WebIRC []webircConfig `yaml:"webirc"`
  264. MaxSendQString string `yaml:"max-sendq"`
  265. MaxSendQBytes int
  266. AllowPlaintextResume bool `yaml:"allow-plaintext-resume"`
  267. Compatibility struct {
  268. ForceTrailing *bool `yaml:"force-trailing"`
  269. forceTrailing bool
  270. SendUnprefixedSasl bool `yaml:"send-unprefixed-sasl"`
  271. }
  272. isupport isupport.List
  273. ConnectionLimiter connection_limits.LimiterConfig `yaml:"connection-limits"`
  274. ConnectionThrottler connection_limits.ThrottlerConfig `yaml:"connection-throttling"`
  275. Cloaks cloaks.CloakConfig `yaml:"ip-cloaking"`
  276. }
  277. Languages struct {
  278. Enabled bool
  279. Path string
  280. Default string
  281. }
  282. languageManager *languages.Manager
  283. Datastore struct {
  284. Path string
  285. AutoUpgrade bool
  286. }
  287. Accounts AccountConfig
  288. Channels struct {
  289. DefaultModes *string `yaml:"default-modes"`
  290. defaultModes modes.Modes
  291. MaxChannelsPerClient int `yaml:"max-channels-per-client"`
  292. Registration ChannelRegistrationConfig
  293. }
  294. OperClasses map[string]*OperClassConfig `yaml:"oper-classes"`
  295. Opers map[string]*OperConfig
  296. // parsed operator definitions, unexported so they can't be defined
  297. // directly in YAML:
  298. operators map[string]*Oper
  299. Logging []logger.LoggingConfig
  300. Debug struct {
  301. RecoverFromErrors *bool `yaml:"recover-from-errors"`
  302. recoverFromErrors bool
  303. PprofListener *string `yaml:"pprof-listener"`
  304. }
  305. Limits Limits
  306. Fakelag FakelagConfig
  307. History struct {
  308. Enabled bool
  309. ChannelLength int `yaml:"channel-length"`
  310. ClientLength int `yaml:"client-length"`
  311. AutoreplayOnJoin int `yaml:"autoreplay-on-join"`
  312. ChathistoryMax int `yaml:"chathistory-maxmessages"`
  313. }
  314. Filename string
  315. }
  316. // OperClass defines an assembled operator class.
  317. type OperClass struct {
  318. Title string
  319. WhoisLine string `yaml:"whois-line"`
  320. Capabilities map[string]bool // map to make lookups much easier
  321. }
  322. // OperatorClasses returns a map of assembled operator classes from the given config.
  323. func (conf *Config) OperatorClasses() (map[string]*OperClass, error) {
  324. ocs := make(map[string]*OperClass)
  325. // loop from no extends to most extended, breaking if we can't add any more
  326. lenOfLastOcs := -1
  327. for {
  328. if lenOfLastOcs == len(ocs) {
  329. return nil, ErrOperClassDependencies
  330. }
  331. lenOfLastOcs = len(ocs)
  332. var anyMissing bool
  333. for name, info := range conf.OperClasses {
  334. _, exists := ocs[name]
  335. _, extendsExists := ocs[info.Extends]
  336. if exists {
  337. // class already exists
  338. continue
  339. } else if len(info.Extends) > 0 && !extendsExists {
  340. // class we extend on doesn't exist
  341. _, exists := conf.OperClasses[info.Extends]
  342. if !exists {
  343. return nil, fmt.Errorf("Operclass [%s] extends [%s], which doesn't exist", name, info.Extends)
  344. }
  345. anyMissing = true
  346. continue
  347. }
  348. // create new operclass
  349. var oc OperClass
  350. oc.Capabilities = make(map[string]bool)
  351. // get inhereted info from other operclasses
  352. if len(info.Extends) > 0 {
  353. einfo := ocs[info.Extends]
  354. for capab := range einfo.Capabilities {
  355. oc.Capabilities[capab] = true
  356. }
  357. }
  358. // add our own info
  359. oc.Title = info.Title
  360. for _, capab := range info.Capabilities {
  361. oc.Capabilities[capab] = true
  362. }
  363. if len(info.WhoisLine) > 0 {
  364. oc.WhoisLine = info.WhoisLine
  365. } else {
  366. oc.WhoisLine = "is a"
  367. if strings.Contains(strings.ToLower(string(oc.Title[0])), "aeiou") {
  368. oc.WhoisLine += "n"
  369. }
  370. oc.WhoisLine += " "
  371. oc.WhoisLine += oc.Title
  372. }
  373. ocs[name] = &oc
  374. }
  375. if !anyMissing {
  376. // we've got every operclass!
  377. break
  378. }
  379. }
  380. return ocs, nil
  381. }
  382. // Oper represents a single assembled operator's config.
  383. type Oper struct {
  384. Name string
  385. Class *OperClass
  386. WhoisLine string
  387. Vhost string
  388. Pass []byte
  389. Modes []modes.ModeChange
  390. }
  391. // Operators returns a map of operator configs from the given OperClass and config.
  392. func (conf *Config) Operators(oc map[string]*OperClass) (map[string]*Oper, error) {
  393. operators := make(map[string]*Oper)
  394. for name, opConf := range conf.Opers {
  395. var oper Oper
  396. // oper name
  397. name, err := CasefoldName(name)
  398. if err != nil {
  399. return nil, fmt.Errorf("Could not casefold oper name: %s", err.Error())
  400. }
  401. oper.Name = name
  402. oper.Pass, err = decodeLegacyPasswordHash(opConf.Password)
  403. if err != nil {
  404. return nil, err
  405. }
  406. oper.Vhost = opConf.Vhost
  407. class, exists := oc[opConf.Class]
  408. if !exists {
  409. return nil, fmt.Errorf("Could not load operator [%s] - they use operclass [%s] which does not exist", name, opConf.Class)
  410. }
  411. oper.Class = class
  412. if len(opConf.WhoisLine) > 0 {
  413. oper.WhoisLine = opConf.WhoisLine
  414. } else {
  415. oper.WhoisLine = class.WhoisLine
  416. }
  417. modeStr := strings.TrimSpace(opConf.Modes)
  418. modeChanges, unknownChanges := modes.ParseUserModeChanges(strings.Split(modeStr, " ")...)
  419. if len(unknownChanges) > 0 {
  420. return nil, fmt.Errorf("Could not load operator [%s] due to unknown modes %v", name, unknownChanges)
  421. }
  422. oper.Modes = modeChanges
  423. // successful, attach to list of opers
  424. operators[name] = &oper
  425. }
  426. return operators, nil
  427. }
  428. // TLSListeners returns a list of TLS listeners and their configs.
  429. func (conf *Config) TLSListeners() (map[string]*tls.Config, error) {
  430. tlsListeners := make(map[string]*tls.Config)
  431. for s, tlsListenersConf := range conf.Server.TLSListeners {
  432. config, err := tlsListenersConf.Config()
  433. if err != nil {
  434. return nil, err
  435. }
  436. config.ClientAuth = tls.RequestClientCert
  437. tlsListeners[s] = config
  438. }
  439. return tlsListeners, nil
  440. }
  441. // LoadConfig loads the given YAML configuration file.
  442. func LoadConfig(filename string) (config *Config, err error) {
  443. data, err := ioutil.ReadFile(filename)
  444. if err != nil {
  445. return nil, err
  446. }
  447. err = yaml.Unmarshal(data, &config)
  448. if err != nil {
  449. return nil, err
  450. }
  451. config.Filename = filename
  452. if config.Network.Name == "" {
  453. return nil, ErrNetworkNameMissing
  454. }
  455. if config.Server.Name == "" {
  456. return nil, ErrServerNameMissing
  457. }
  458. if !utils.IsHostname(config.Server.Name) {
  459. return nil, ErrServerNameNotHostname
  460. }
  461. if config.Datastore.Path == "" {
  462. return nil, ErrDatastorePathMissing
  463. }
  464. if len(config.Server.Listen) == 0 {
  465. return nil, ErrNoListenersDefined
  466. }
  467. //dan: automagically fix identlen until a few releases in the future (from now, 0.12.0), being a newly-introduced limit
  468. if config.Limits.IdentLen < 1 {
  469. config.Limits.IdentLen = 20
  470. }
  471. if config.Limits.NickLen < 1 || config.Limits.ChannelLen < 2 || config.Limits.AwayLen < 1 || config.Limits.KickLen < 1 || config.Limits.TopicLen < 1 {
  472. return nil, ErrLimitsAreInsane
  473. }
  474. if config.Limits.RegistrationMessages == 0 {
  475. config.Limits.RegistrationMessages = 1024
  476. }
  477. if config.Server.STS.Enabled {
  478. config.Server.STS.Duration, err = custime.ParseDuration(config.Server.STS.DurationString)
  479. if err != nil {
  480. return nil, fmt.Errorf("Could not parse STS duration: %s", err.Error())
  481. }
  482. if config.Server.STS.Port < 0 || config.Server.STS.Port > 65535 {
  483. return nil, fmt.Errorf("STS port is incorrect, should be 0 if disabled: %d", config.Server.STS.Port)
  484. }
  485. }
  486. if config.Server.ConnectionThrottler.Enabled {
  487. config.Server.ConnectionThrottler.Duration, err = time.ParseDuration(config.Server.ConnectionThrottler.DurationString)
  488. if err != nil {
  489. return nil, fmt.Errorf("Could not parse connection-throttle duration: %s", err.Error())
  490. }
  491. config.Server.ConnectionThrottler.BanDuration, err = time.ParseDuration(config.Server.ConnectionThrottler.BanDurationString)
  492. if err != nil {
  493. return nil, fmt.Errorf("Could not parse connection-throttle ban-duration: %s", err.Error())
  494. }
  495. }
  496. // process webirc blocks
  497. var newWebIRC []webircConfig
  498. for _, webirc := range config.Server.WebIRC {
  499. // skip webirc blocks with no hosts (such as the example one)
  500. if len(webirc.Hosts) == 0 {
  501. continue
  502. }
  503. err = webirc.Populate()
  504. if err != nil {
  505. return nil, fmt.Errorf("Could not parse WebIRC config: %s", err.Error())
  506. }
  507. newWebIRC = append(newWebIRC, webirc)
  508. }
  509. config.Server.WebIRC = newWebIRC
  510. // process limits
  511. if config.Limits.LineLen.Rest < 512 {
  512. config.Limits.LineLen.Rest = 512
  513. }
  514. var newLogConfigs []logger.LoggingConfig
  515. for _, logConfig := range config.Logging {
  516. // methods
  517. methods := make(map[string]bool)
  518. for _, method := range strings.Split(logConfig.Method, " ") {
  519. if len(method) > 0 {
  520. methods[strings.ToLower(method)] = true
  521. }
  522. }
  523. if methods["file"] && logConfig.Filename == "" {
  524. return nil, ErrLoggerFilenameMissing
  525. }
  526. logConfig.MethodFile = methods["file"]
  527. logConfig.MethodStdout = methods["stdout"]
  528. logConfig.MethodStderr = methods["stderr"]
  529. // levels
  530. level, exists := logger.LogLevelNames[strings.ToLower(logConfig.LevelString)]
  531. if !exists {
  532. return nil, fmt.Errorf("Could not translate log leve [%s]", logConfig.LevelString)
  533. }
  534. logConfig.Level = level
  535. // types
  536. for _, typeStr := range strings.Split(logConfig.TypeString, " ") {
  537. if len(typeStr) == 0 {
  538. continue
  539. }
  540. if typeStr == "-" {
  541. return nil, ErrLoggerExcludeEmpty
  542. }
  543. if typeStr[0] == '-' {
  544. typeStr = typeStr[1:]
  545. logConfig.ExcludedTypes = append(logConfig.ExcludedTypes, typeStr)
  546. } else {
  547. logConfig.Types = append(logConfig.Types, typeStr)
  548. }
  549. }
  550. if len(logConfig.Types) < 1 {
  551. return nil, ErrLoggerHasNoTypes
  552. }
  553. newLogConfigs = append(newLogConfigs, logConfig)
  554. }
  555. config.Logging = newLogConfigs
  556. // hardcode this for now
  557. config.Accounts.Registration.EnabledCredentialTypes = []string{"passphrase", "certfp"}
  558. for i, name := range config.Accounts.Registration.EnabledCallbacks {
  559. if name == "none" {
  560. // we store "none" as "*" internally
  561. config.Accounts.Registration.EnabledCallbacks[i] = "*"
  562. }
  563. }
  564. sort.Strings(config.Accounts.Registration.EnabledCallbacks)
  565. config.Accounts.RequireSasl.exemptedNets, err = utils.ParseNetList(config.Accounts.RequireSasl.Exempted)
  566. if err != nil {
  567. return nil, fmt.Errorf("Could not parse require-sasl exempted nets: %v", err.Error())
  568. }
  569. config.Server.proxyAllowedFromNets, err = utils.ParseNetList(config.Server.ProxyAllowedFrom)
  570. if err != nil {
  571. return nil, fmt.Errorf("Could not parse proxy-allowed-from nets: %v", err.Error())
  572. }
  573. rawRegexp := config.Accounts.VHosts.ValidRegexpRaw
  574. if rawRegexp != "" {
  575. regexp, err := regexp.Compile(rawRegexp)
  576. if err == nil {
  577. config.Accounts.VHosts.ValidRegexp = regexp
  578. } else {
  579. log.Printf("invalid vhost regexp: %s\n", err.Error())
  580. }
  581. }
  582. if config.Accounts.VHosts.ValidRegexp == nil {
  583. config.Accounts.VHosts.ValidRegexp = defaultValidVhostRegex
  584. }
  585. if !config.Accounts.LoginThrottling.Enabled {
  586. config.Accounts.LoginThrottling.MaxAttempts = 0 // limit of 0 means disabled
  587. }
  588. maxSendQBytes, err := bytefmt.ToBytes(config.Server.MaxSendQString)
  589. if err != nil {
  590. return nil, fmt.Errorf("Could not parse maximum SendQ size (make sure it only contains whole numbers): %s", err.Error())
  591. }
  592. config.Server.MaxSendQBytes = int(maxSendQBytes)
  593. config.languageManager, err = languages.NewManager(config.Languages.Enabled, config.Languages.Path, config.Languages.Default)
  594. if err != nil {
  595. return nil, fmt.Errorf("Could not load languages: %s", err.Error())
  596. }
  597. // RecoverFromErrors defaults to true
  598. if config.Debug.RecoverFromErrors != nil {
  599. config.Debug.recoverFromErrors = *config.Debug.RecoverFromErrors
  600. } else {
  601. config.Debug.recoverFromErrors = true
  602. }
  603. // casefold/validate server name
  604. config.Server.nameCasefolded, err = Casefold(config.Server.Name)
  605. if err != nil {
  606. return nil, fmt.Errorf("Server name isn't valid [%s]: %s", config.Server.Name, err.Error())
  607. }
  608. // process operator definitions, store them to config.operators
  609. operclasses, err := config.OperatorClasses()
  610. if err != nil {
  611. return nil, err
  612. }
  613. opers, err := config.Operators(operclasses)
  614. if err != nil {
  615. return nil, err
  616. }
  617. config.operators = opers
  618. // parse default channel modes
  619. config.Channels.defaultModes = ParseDefaultChannelModes(config.Channels.DefaultModes)
  620. if config.Server.Password != "" {
  621. config.Server.passwordBytes, err = decodeLegacyPasswordHash(config.Server.Password)
  622. if err != nil {
  623. return nil, err
  624. }
  625. }
  626. if config.Accounts.Registration.BcryptCost == 0 {
  627. config.Accounts.Registration.BcryptCost = passwd.DefaultCost
  628. }
  629. if config.Channels.MaxChannelsPerClient == 0 {
  630. config.Channels.MaxChannelsPerClient = 100
  631. }
  632. if config.Channels.Registration.MaxChannelsPerAccount == 0 {
  633. config.Channels.Registration.MaxChannelsPerAccount = 15
  634. }
  635. forceTrailingPtr := config.Server.Compatibility.ForceTrailing
  636. if forceTrailingPtr != nil {
  637. config.Server.Compatibility.forceTrailing = *forceTrailingPtr
  638. } else {
  639. config.Server.Compatibility.forceTrailing = true
  640. }
  641. config.loadMOTD()
  642. err = config.generateISupport()
  643. if err != nil {
  644. return nil, err
  645. }
  646. // in the current implementation, we disable history by creating a history buffer
  647. // with zero capacity. but the `enabled` config option MUST be respected regardless
  648. // of this detail
  649. if !config.History.Enabled {
  650. config.History.ChannelLength = 0
  651. config.History.ClientLength = 0
  652. }
  653. config.Server.Cloaks.Initialize()
  654. if config.Server.Cloaks.Enabled {
  655. if config.Server.Cloaks.Secret == "" || config.Server.Cloaks.Secret == "siaELnk6Kaeo65K3RCrwJjlWaZ-Bt3WuZ2L8MXLbNb4" {
  656. return nil, fmt.Errorf("You must generate a new value of server.ip-cloaking.secret to enable cloaking")
  657. }
  658. }
  659. for _, listenAddress := range config.Server.TorListeners.Listeners {
  660. found := false
  661. for _, configuredListener := range config.Server.Listen {
  662. if listenAddress == configuredListener {
  663. found = true
  664. break
  665. }
  666. }
  667. if !found {
  668. return nil, fmt.Errorf("%s is configured as a Tor listener, but is not in server.listen", listenAddress)
  669. }
  670. }
  671. return config, nil
  672. }