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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761
  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. OpOnlyCreation bool `yaml:"operator-only-creation"`
  293. Registration ChannelRegistrationConfig
  294. }
  295. OperClasses map[string]*OperClassConfig `yaml:"oper-classes"`
  296. Opers map[string]*OperConfig
  297. // parsed operator definitions, unexported so they can't be defined
  298. // directly in YAML:
  299. operators map[string]*Oper
  300. Logging []logger.LoggingConfig
  301. Debug struct {
  302. RecoverFromErrors *bool `yaml:"recover-from-errors"`
  303. recoverFromErrors bool
  304. PprofListener *string `yaml:"pprof-listener"`
  305. }
  306. Limits Limits
  307. Fakelag FakelagConfig
  308. History struct {
  309. Enabled bool
  310. ChannelLength int `yaml:"channel-length"`
  311. ClientLength int `yaml:"client-length"`
  312. AutoreplayOnJoin int `yaml:"autoreplay-on-join"`
  313. ChathistoryMax int `yaml:"chathistory-maxmessages"`
  314. }
  315. Filename string
  316. }
  317. // OperClass defines an assembled operator class.
  318. type OperClass struct {
  319. Title string
  320. WhoisLine string `yaml:"whois-line"`
  321. Capabilities map[string]bool // map to make lookups much easier
  322. }
  323. // OperatorClasses returns a map of assembled operator classes from the given config.
  324. func (conf *Config) OperatorClasses() (map[string]*OperClass, error) {
  325. ocs := make(map[string]*OperClass)
  326. // loop from no extends to most extended, breaking if we can't add any more
  327. lenOfLastOcs := -1
  328. for {
  329. if lenOfLastOcs == len(ocs) {
  330. return nil, ErrOperClassDependencies
  331. }
  332. lenOfLastOcs = len(ocs)
  333. var anyMissing bool
  334. for name, info := range conf.OperClasses {
  335. _, exists := ocs[name]
  336. _, extendsExists := ocs[info.Extends]
  337. if exists {
  338. // class already exists
  339. continue
  340. } else if len(info.Extends) > 0 && !extendsExists {
  341. // class we extend on doesn't exist
  342. _, exists := conf.OperClasses[info.Extends]
  343. if !exists {
  344. return nil, fmt.Errorf("Operclass [%s] extends [%s], which doesn't exist", name, info.Extends)
  345. }
  346. anyMissing = true
  347. continue
  348. }
  349. // create new operclass
  350. var oc OperClass
  351. oc.Capabilities = make(map[string]bool)
  352. // get inhereted info from other operclasses
  353. if len(info.Extends) > 0 {
  354. einfo := ocs[info.Extends]
  355. for capab := range einfo.Capabilities {
  356. oc.Capabilities[capab] = true
  357. }
  358. }
  359. // add our own info
  360. oc.Title = info.Title
  361. for _, capab := range info.Capabilities {
  362. oc.Capabilities[capab] = true
  363. }
  364. if len(info.WhoisLine) > 0 {
  365. oc.WhoisLine = info.WhoisLine
  366. } else {
  367. oc.WhoisLine = "is a"
  368. if strings.Contains(strings.ToLower(string(oc.Title[0])), "aeiou") {
  369. oc.WhoisLine += "n"
  370. }
  371. oc.WhoisLine += " "
  372. oc.WhoisLine += oc.Title
  373. }
  374. ocs[name] = &oc
  375. }
  376. if !anyMissing {
  377. // we've got every operclass!
  378. break
  379. }
  380. }
  381. return ocs, nil
  382. }
  383. // Oper represents a single assembled operator's config.
  384. type Oper struct {
  385. Name string
  386. Class *OperClass
  387. WhoisLine string
  388. Vhost string
  389. Pass []byte
  390. Modes []modes.ModeChange
  391. }
  392. // Operators returns a map of operator configs from the given OperClass and config.
  393. func (conf *Config) Operators(oc map[string]*OperClass) (map[string]*Oper, error) {
  394. operators := make(map[string]*Oper)
  395. for name, opConf := range conf.Opers {
  396. var oper Oper
  397. // oper name
  398. name, err := CasefoldName(name)
  399. if err != nil {
  400. return nil, fmt.Errorf("Could not casefold oper name: %s", err.Error())
  401. }
  402. oper.Name = name
  403. oper.Pass, err = decodeLegacyPasswordHash(opConf.Password)
  404. if err != nil {
  405. return nil, err
  406. }
  407. oper.Vhost = opConf.Vhost
  408. class, exists := oc[opConf.Class]
  409. if !exists {
  410. return nil, fmt.Errorf("Could not load operator [%s] - they use operclass [%s] which does not exist", name, opConf.Class)
  411. }
  412. oper.Class = class
  413. if len(opConf.WhoisLine) > 0 {
  414. oper.WhoisLine = opConf.WhoisLine
  415. } else {
  416. oper.WhoisLine = class.WhoisLine
  417. }
  418. modeStr := strings.TrimSpace(opConf.Modes)
  419. modeChanges, unknownChanges := modes.ParseUserModeChanges(strings.Split(modeStr, " ")...)
  420. if len(unknownChanges) > 0 {
  421. return nil, fmt.Errorf("Could not load operator [%s] due to unknown modes %v", name, unknownChanges)
  422. }
  423. oper.Modes = modeChanges
  424. // successful, attach to list of opers
  425. operators[name] = &oper
  426. }
  427. return operators, nil
  428. }
  429. // TLSListeners returns a list of TLS listeners and their configs.
  430. func (conf *Config) TLSListeners() (map[string]*tls.Config, error) {
  431. tlsListeners := make(map[string]*tls.Config)
  432. for s, tlsListenersConf := range conf.Server.TLSListeners {
  433. config, err := tlsListenersConf.Config()
  434. if err != nil {
  435. return nil, err
  436. }
  437. config.ClientAuth = tls.RequestClientCert
  438. tlsListeners[s] = config
  439. }
  440. return tlsListeners, nil
  441. }
  442. // LoadConfig loads the given YAML configuration file.
  443. func LoadConfig(filename string) (config *Config, err error) {
  444. data, err := ioutil.ReadFile(filename)
  445. if err != nil {
  446. return nil, err
  447. }
  448. err = yaml.Unmarshal(data, &config)
  449. if err != nil {
  450. return nil, err
  451. }
  452. config.Filename = filename
  453. if config.Network.Name == "" {
  454. return nil, ErrNetworkNameMissing
  455. }
  456. if config.Server.Name == "" {
  457. return nil, ErrServerNameMissing
  458. }
  459. if !utils.IsHostname(config.Server.Name) {
  460. return nil, ErrServerNameNotHostname
  461. }
  462. if config.Datastore.Path == "" {
  463. return nil, ErrDatastorePathMissing
  464. }
  465. if len(config.Server.Listen) == 0 {
  466. return nil, ErrNoListenersDefined
  467. }
  468. //dan: automagically fix identlen until a few releases in the future (from now, 0.12.0), being a newly-introduced limit
  469. if config.Limits.IdentLen < 1 {
  470. config.Limits.IdentLen = 20
  471. }
  472. if config.Limits.NickLen < 1 || config.Limits.ChannelLen < 2 || config.Limits.AwayLen < 1 || config.Limits.KickLen < 1 || config.Limits.TopicLen < 1 {
  473. return nil, ErrLimitsAreInsane
  474. }
  475. if config.Limits.RegistrationMessages == 0 {
  476. config.Limits.RegistrationMessages = 1024
  477. }
  478. if config.Server.STS.Enabled {
  479. config.Server.STS.Duration, err = custime.ParseDuration(config.Server.STS.DurationString)
  480. if err != nil {
  481. return nil, fmt.Errorf("Could not parse STS duration: %s", err.Error())
  482. }
  483. if config.Server.STS.Port < 0 || config.Server.STS.Port > 65535 {
  484. return nil, fmt.Errorf("STS port is incorrect, should be 0 if disabled: %d", config.Server.STS.Port)
  485. }
  486. }
  487. if config.Server.ConnectionThrottler.Enabled {
  488. config.Server.ConnectionThrottler.Duration, err = time.ParseDuration(config.Server.ConnectionThrottler.DurationString)
  489. if err != nil {
  490. return nil, fmt.Errorf("Could not parse connection-throttle duration: %s", err.Error())
  491. }
  492. config.Server.ConnectionThrottler.BanDuration, err = time.ParseDuration(config.Server.ConnectionThrottler.BanDurationString)
  493. if err != nil {
  494. return nil, fmt.Errorf("Could not parse connection-throttle ban-duration: %s", err.Error())
  495. }
  496. }
  497. // process webirc blocks
  498. var newWebIRC []webircConfig
  499. for _, webirc := range config.Server.WebIRC {
  500. // skip webirc blocks with no hosts (such as the example one)
  501. if len(webirc.Hosts) == 0 {
  502. continue
  503. }
  504. err = webirc.Populate()
  505. if err != nil {
  506. return nil, fmt.Errorf("Could not parse WebIRC config: %s", err.Error())
  507. }
  508. newWebIRC = append(newWebIRC, webirc)
  509. }
  510. config.Server.WebIRC = newWebIRC
  511. // process limits
  512. if config.Limits.LineLen.Rest < 512 {
  513. config.Limits.LineLen.Rest = 512
  514. }
  515. var newLogConfigs []logger.LoggingConfig
  516. for _, logConfig := range config.Logging {
  517. // methods
  518. methods := make(map[string]bool)
  519. for _, method := range strings.Split(logConfig.Method, " ") {
  520. if len(method) > 0 {
  521. methods[strings.ToLower(method)] = true
  522. }
  523. }
  524. if methods["file"] && logConfig.Filename == "" {
  525. return nil, ErrLoggerFilenameMissing
  526. }
  527. logConfig.MethodFile = methods["file"]
  528. logConfig.MethodStdout = methods["stdout"]
  529. logConfig.MethodStderr = methods["stderr"]
  530. // levels
  531. level, exists := logger.LogLevelNames[strings.ToLower(logConfig.LevelString)]
  532. if !exists {
  533. return nil, fmt.Errorf("Could not translate log leve [%s]", logConfig.LevelString)
  534. }
  535. logConfig.Level = level
  536. // types
  537. for _, typeStr := range strings.Split(logConfig.TypeString, " ") {
  538. if len(typeStr) == 0 {
  539. continue
  540. }
  541. if typeStr == "-" {
  542. return nil, ErrLoggerExcludeEmpty
  543. }
  544. if typeStr[0] == '-' {
  545. typeStr = typeStr[1:]
  546. logConfig.ExcludedTypes = append(logConfig.ExcludedTypes, typeStr)
  547. } else {
  548. logConfig.Types = append(logConfig.Types, typeStr)
  549. }
  550. }
  551. if len(logConfig.Types) < 1 {
  552. return nil, ErrLoggerHasNoTypes
  553. }
  554. newLogConfigs = append(newLogConfigs, logConfig)
  555. }
  556. config.Logging = newLogConfigs
  557. // hardcode this for now
  558. config.Accounts.Registration.EnabledCredentialTypes = []string{"passphrase", "certfp"}
  559. for i, name := range config.Accounts.Registration.EnabledCallbacks {
  560. if name == "none" {
  561. // we store "none" as "*" internally
  562. config.Accounts.Registration.EnabledCallbacks[i] = "*"
  563. }
  564. }
  565. sort.Strings(config.Accounts.Registration.EnabledCallbacks)
  566. config.Accounts.RequireSasl.exemptedNets, err = utils.ParseNetList(config.Accounts.RequireSasl.Exempted)
  567. if err != nil {
  568. return nil, fmt.Errorf("Could not parse require-sasl exempted nets: %v", err.Error())
  569. }
  570. config.Server.proxyAllowedFromNets, err = utils.ParseNetList(config.Server.ProxyAllowedFrom)
  571. if err != nil {
  572. return nil, fmt.Errorf("Could not parse proxy-allowed-from nets: %v", err.Error())
  573. }
  574. rawRegexp := config.Accounts.VHosts.ValidRegexpRaw
  575. if rawRegexp != "" {
  576. regexp, err := regexp.Compile(rawRegexp)
  577. if err == nil {
  578. config.Accounts.VHosts.ValidRegexp = regexp
  579. } else {
  580. log.Printf("invalid vhost regexp: %s\n", err.Error())
  581. }
  582. }
  583. if config.Accounts.VHosts.ValidRegexp == nil {
  584. config.Accounts.VHosts.ValidRegexp = defaultValidVhostRegex
  585. }
  586. if !config.Accounts.LoginThrottling.Enabled {
  587. config.Accounts.LoginThrottling.MaxAttempts = 0 // limit of 0 means disabled
  588. }
  589. maxSendQBytes, err := bytefmt.ToBytes(config.Server.MaxSendQString)
  590. if err != nil {
  591. return nil, fmt.Errorf("Could not parse maximum SendQ size (make sure it only contains whole numbers): %s", err.Error())
  592. }
  593. config.Server.MaxSendQBytes = int(maxSendQBytes)
  594. config.languageManager, err = languages.NewManager(config.Languages.Enabled, config.Languages.Path, config.Languages.Default)
  595. if err != nil {
  596. return nil, fmt.Errorf("Could not load languages: %s", err.Error())
  597. }
  598. // RecoverFromErrors defaults to true
  599. if config.Debug.RecoverFromErrors != nil {
  600. config.Debug.recoverFromErrors = *config.Debug.RecoverFromErrors
  601. } else {
  602. config.Debug.recoverFromErrors = true
  603. }
  604. // casefold/validate server name
  605. config.Server.nameCasefolded, err = Casefold(config.Server.Name)
  606. if err != nil {
  607. return nil, fmt.Errorf("Server name isn't valid [%s]: %s", config.Server.Name, err.Error())
  608. }
  609. // process operator definitions, store them to config.operators
  610. operclasses, err := config.OperatorClasses()
  611. if err != nil {
  612. return nil, err
  613. }
  614. opers, err := config.Operators(operclasses)
  615. if err != nil {
  616. return nil, err
  617. }
  618. config.operators = opers
  619. // parse default channel modes
  620. config.Channels.defaultModes = ParseDefaultChannelModes(config.Channels.DefaultModes)
  621. if config.Server.Password != "" {
  622. config.Server.passwordBytes, err = decodeLegacyPasswordHash(config.Server.Password)
  623. if err != nil {
  624. return nil, err
  625. }
  626. }
  627. if config.Accounts.Registration.BcryptCost == 0 {
  628. config.Accounts.Registration.BcryptCost = passwd.DefaultCost
  629. }
  630. if config.Channels.MaxChannelsPerClient == 0 {
  631. config.Channels.MaxChannelsPerClient = 100
  632. }
  633. if config.Channels.Registration.MaxChannelsPerAccount == 0 {
  634. config.Channels.Registration.MaxChannelsPerAccount = 15
  635. }
  636. forceTrailingPtr := config.Server.Compatibility.ForceTrailing
  637. if forceTrailingPtr != nil {
  638. config.Server.Compatibility.forceTrailing = *forceTrailingPtr
  639. } else {
  640. config.Server.Compatibility.forceTrailing = true
  641. }
  642. config.loadMOTD()
  643. err = config.generateISupport()
  644. if err != nil {
  645. return nil, err
  646. }
  647. // in the current implementation, we disable history by creating a history buffer
  648. // with zero capacity. but the `enabled` config option MUST be respected regardless
  649. // of this detail
  650. if !config.History.Enabled {
  651. config.History.ChannelLength = 0
  652. config.History.ClientLength = 0
  653. }
  654. config.Server.Cloaks.Initialize()
  655. if config.Server.Cloaks.Enabled {
  656. if config.Server.Cloaks.Secret == "" || config.Server.Cloaks.Secret == "siaELnk6Kaeo65K3RCrwJjlWaZ-Bt3WuZ2L8MXLbNb4" {
  657. return nil, fmt.Errorf("You must generate a new value of server.ip-cloaking.secret to enable cloaking")
  658. }
  659. }
  660. for _, listenAddress := range config.Server.TorListeners.Listeners {
  661. found := false
  662. for _, configuredListener := range config.Server.Listen {
  663. if listenAddress == configuredListener {
  664. found = true
  665. break
  666. }
  667. }
  668. if !found {
  669. return nil, fmt.Errorf("%s is configured as a Tor listener, but is not in server.listen", listenAddress)
  670. }
  671. }
  672. return config, nil
  673. }