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 21KB

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