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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717
  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. Rest int
  186. }
  187. // Various server-enforced limits on data size.
  188. type Limits struct {
  189. AwayLen int `yaml:"awaylen"`
  190. ChanListModes int `yaml:"chan-list-modes"`
  191. ChannelLen int `yaml:"channellen"`
  192. IdentLen int `yaml:"identlen"`
  193. KickLen int `yaml:"kicklen"`
  194. LineLen LineLenLimits `yaml:"linelen"`
  195. MonitorEntries int `yaml:"monitor-entries"`
  196. NickLen int `yaml:"nicklen"`
  197. TopicLen int `yaml:"topiclen"`
  198. WhowasEntries int `yaml:"whowas-entries"`
  199. }
  200. // STSConfig controls the STS configuration/
  201. type STSConfig struct {
  202. Enabled bool
  203. Duration time.Duration `yaml:"duration-real"`
  204. DurationString string `yaml:"duration"`
  205. Port int
  206. Preload bool
  207. }
  208. // Value returns the STS value to advertise in CAP
  209. func (sts *STSConfig) Value() string {
  210. val := fmt.Sprintf("duration=%d", int(sts.Duration.Seconds()))
  211. if sts.Enabled && sts.Port > 0 {
  212. val += fmt.Sprintf(",port=%d", sts.Port)
  213. }
  214. if sts.Enabled && sts.Preload {
  215. val += ",preload"
  216. }
  217. return val
  218. }
  219. type FakelagConfig struct {
  220. Enabled bool
  221. Window time.Duration
  222. BurstLimit uint `yaml:"burst-limit"`
  223. MessagesPerWindow uint `yaml:"messages-per-window"`
  224. Cooldown time.Duration
  225. }
  226. type TorListenersConfig struct {
  227. Listeners []string
  228. RequireSasl bool `yaml:"require-sasl"`
  229. Vhost string
  230. MaxConnections int `yaml:"max-connections"`
  231. ThrottleDuration time.Duration `yaml:"throttle-duration"`
  232. MaxConnectionsPerDuration int `yaml:"max-connections-per-duration"`
  233. }
  234. // Config defines the overall configuration.
  235. type Config struct {
  236. Network struct {
  237. Name string
  238. }
  239. Server struct {
  240. Password string
  241. passwordBytes []byte
  242. Name string
  243. nameCasefolded string
  244. Listen []string
  245. UnixBindMode os.FileMode `yaml:"unix-bind-mode"`
  246. TLSListeners map[string]*TLSListenConfig `yaml:"tls-listeners"`
  247. TorListeners TorListenersConfig `yaml:"tor-listeners"`
  248. STS STSConfig
  249. CheckIdent bool `yaml:"check-ident"`
  250. MOTD string
  251. MOTDFormatting bool `yaml:"motd-formatting"`
  252. ProxyAllowedFrom []string `yaml:"proxy-allowed-from"`
  253. proxyAllowedFromNets []net.IPNet
  254. WebIRC []webircConfig `yaml:"webirc"`
  255. MaxSendQString string `yaml:"max-sendq"`
  256. MaxSendQBytes int
  257. AllowPlaintextResume bool `yaml:"allow-plaintext-resume"`
  258. ConnectionLimiter connection_limits.LimiterConfig `yaml:"connection-limits"`
  259. ConnectionThrottler connection_limits.ThrottlerConfig `yaml:"connection-throttling"`
  260. }
  261. Languages struct {
  262. Enabled bool
  263. Path string
  264. Default string
  265. }
  266. languageManager *languages.Manager
  267. Datastore struct {
  268. Path string
  269. AutoUpgrade bool
  270. }
  271. Accounts AccountConfig
  272. Channels struct {
  273. DefaultModes *string `yaml:"default-modes"`
  274. defaultModes modes.Modes
  275. MaxChannelsPerClient int `yaml:"max-channels-per-client"`
  276. Registration ChannelRegistrationConfig
  277. }
  278. OperClasses map[string]*OperClassConfig `yaml:"oper-classes"`
  279. Opers map[string]*OperConfig
  280. // parsed operator definitions, unexported so they can't be defined
  281. // directly in YAML:
  282. operators map[string]*Oper
  283. Logging []logger.LoggingConfig
  284. Debug struct {
  285. RecoverFromErrors *bool `yaml:"recover-from-errors"`
  286. PprofListener *string `yaml:"pprof-listener"`
  287. }
  288. Limits Limits
  289. Fakelag FakelagConfig
  290. History struct {
  291. Enabled bool
  292. ChannelLength int `yaml:"channel-length"`
  293. ClientLength int `yaml:"client-length"`
  294. AutoreplayOnJoin int `yaml:"autoreplay-on-join"`
  295. ChathistoryMax int `yaml:"chathistory-maxmessages"`
  296. }
  297. Filename string
  298. }
  299. // OperClass defines an assembled operator class.
  300. type OperClass struct {
  301. Title string
  302. WhoisLine string `yaml:"whois-line"`
  303. Capabilities map[string]bool // map to make lookups much easier
  304. }
  305. // OperatorClasses returns a map of assembled operator classes from the given config.
  306. func (conf *Config) OperatorClasses() (map[string]*OperClass, error) {
  307. ocs := make(map[string]*OperClass)
  308. // loop from no extends to most extended, breaking if we can't add any more
  309. lenOfLastOcs := -1
  310. for {
  311. if lenOfLastOcs == len(ocs) {
  312. return nil, ErrOperClassDependencies
  313. }
  314. lenOfLastOcs = len(ocs)
  315. var anyMissing bool
  316. for name, info := range conf.OperClasses {
  317. _, exists := ocs[name]
  318. _, extendsExists := ocs[info.Extends]
  319. if exists {
  320. // class already exists
  321. continue
  322. } else if len(info.Extends) > 0 && !extendsExists {
  323. // class we extend on doesn't exist
  324. _, exists := conf.OperClasses[info.Extends]
  325. if !exists {
  326. return nil, fmt.Errorf("Operclass [%s] extends [%s], which doesn't exist", name, info.Extends)
  327. }
  328. anyMissing = true
  329. continue
  330. }
  331. // create new operclass
  332. var oc OperClass
  333. oc.Capabilities = make(map[string]bool)
  334. // get inhereted info from other operclasses
  335. if len(info.Extends) > 0 {
  336. einfo, _ := ocs[info.Extends]
  337. for capab := range einfo.Capabilities {
  338. oc.Capabilities[capab] = true
  339. }
  340. }
  341. // add our own info
  342. oc.Title = info.Title
  343. for _, capab := range info.Capabilities {
  344. oc.Capabilities[capab] = true
  345. }
  346. if len(info.WhoisLine) > 0 {
  347. oc.WhoisLine = info.WhoisLine
  348. } else {
  349. oc.WhoisLine = "is a"
  350. if strings.Contains(strings.ToLower(string(oc.Title[0])), "aeiou") {
  351. oc.WhoisLine += "n"
  352. }
  353. oc.WhoisLine += " "
  354. oc.WhoisLine += oc.Title
  355. }
  356. ocs[name] = &oc
  357. }
  358. if !anyMissing {
  359. // we've got every operclass!
  360. break
  361. }
  362. }
  363. return ocs, nil
  364. }
  365. // Oper represents a single assembled operator's config.
  366. type Oper struct {
  367. Name string
  368. Class *OperClass
  369. WhoisLine string
  370. Vhost string
  371. Pass []byte
  372. Modes []modes.ModeChange
  373. }
  374. // Operators returns a map of operator configs from the given OperClass and config.
  375. func (conf *Config) Operators(oc map[string]*OperClass) (map[string]*Oper, error) {
  376. operators := make(map[string]*Oper)
  377. for name, opConf := range conf.Opers {
  378. var oper Oper
  379. // oper name
  380. name, err := CasefoldName(name)
  381. if err != nil {
  382. return nil, fmt.Errorf("Could not casefold oper name: %s", err.Error())
  383. }
  384. oper.Name = name
  385. oper.Pass, err = decodeLegacyPasswordHash(opConf.Password)
  386. if err != nil {
  387. return nil, err
  388. }
  389. oper.Vhost = opConf.Vhost
  390. class, exists := oc[opConf.Class]
  391. if !exists {
  392. return nil, fmt.Errorf("Could not load operator [%s] - they use operclass [%s] which does not exist", name, opConf.Class)
  393. }
  394. oper.Class = class
  395. if len(opConf.WhoisLine) > 0 {
  396. oper.WhoisLine = opConf.WhoisLine
  397. } else {
  398. oper.WhoisLine = class.WhoisLine
  399. }
  400. modeStr := strings.TrimSpace(opConf.Modes)
  401. modeChanges, unknownChanges := modes.ParseUserModeChanges(strings.Split(modeStr, " ")...)
  402. if len(unknownChanges) > 0 {
  403. return nil, fmt.Errorf("Could not load operator [%s] due to unknown modes %v", name, unknownChanges)
  404. }
  405. oper.Modes = modeChanges
  406. // successful, attach to list of opers
  407. operators[name] = &oper
  408. }
  409. return operators, nil
  410. }
  411. // TLSListeners returns a list of TLS listeners and their configs.
  412. func (conf *Config) TLSListeners() (map[string]*tls.Config, error) {
  413. tlsListeners := make(map[string]*tls.Config)
  414. for s, tlsListenersConf := range conf.Server.TLSListeners {
  415. config, err := tlsListenersConf.Config()
  416. if err != nil {
  417. return nil, err
  418. }
  419. config.ClientAuth = tls.RequestClientCert
  420. tlsListeners[s] = config
  421. }
  422. return tlsListeners, nil
  423. }
  424. // LoadConfig loads the given YAML configuration file.
  425. func LoadConfig(filename string) (config *Config, err error) {
  426. data, err := ioutil.ReadFile(filename)
  427. if err != nil {
  428. return nil, err
  429. }
  430. err = yaml.Unmarshal(data, &config)
  431. if err != nil {
  432. return nil, err
  433. }
  434. config.Filename = filename
  435. if config.Network.Name == "" {
  436. return nil, ErrNetworkNameMissing
  437. }
  438. if config.Server.Name == "" {
  439. return nil, ErrServerNameMissing
  440. }
  441. if !utils.IsHostname(config.Server.Name) {
  442. return nil, ErrServerNameNotHostname
  443. }
  444. if config.Datastore.Path == "" {
  445. return nil, ErrDatastorePathMissing
  446. }
  447. if len(config.Server.Listen) == 0 {
  448. return nil, ErrNoListenersDefined
  449. }
  450. //dan: automagically fix identlen until a few releases in the future (from now, 0.12.0), being a newly-introduced limit
  451. if config.Limits.IdentLen < 1 {
  452. config.Limits.IdentLen = 20
  453. }
  454. if config.Limits.NickLen < 1 || config.Limits.ChannelLen < 2 || config.Limits.AwayLen < 1 || config.Limits.KickLen < 1 || config.Limits.TopicLen < 1 {
  455. return nil, ErrLimitsAreInsane
  456. }
  457. if config.Server.STS.Enabled {
  458. config.Server.STS.Duration, err = custime.ParseDuration(config.Server.STS.DurationString)
  459. if err != nil {
  460. return nil, fmt.Errorf("Could not parse STS duration: %s", err.Error())
  461. }
  462. if config.Server.STS.Port < 0 || config.Server.STS.Port > 65535 {
  463. return nil, fmt.Errorf("STS port is incorrect, should be 0 if disabled: %d", config.Server.STS.Port)
  464. }
  465. }
  466. if config.Server.ConnectionThrottler.Enabled {
  467. config.Server.ConnectionThrottler.Duration, err = time.ParseDuration(config.Server.ConnectionThrottler.DurationString)
  468. if err != nil {
  469. return nil, fmt.Errorf("Could not parse connection-throttle duration: %s", err.Error())
  470. }
  471. config.Server.ConnectionThrottler.BanDuration, err = time.ParseDuration(config.Server.ConnectionThrottler.BanDurationString)
  472. if err != nil {
  473. return nil, fmt.Errorf("Could not parse connection-throttle ban-duration: %s", err.Error())
  474. }
  475. }
  476. // process webirc blocks
  477. var newWebIRC []webircConfig
  478. for _, webirc := range config.Server.WebIRC {
  479. // skip webirc blocks with no hosts (such as the example one)
  480. if len(webirc.Hosts) == 0 {
  481. continue
  482. }
  483. err = webirc.Populate()
  484. if err != nil {
  485. return nil, fmt.Errorf("Could not parse WebIRC config: %s", err.Error())
  486. }
  487. newWebIRC = append(newWebIRC, webirc)
  488. }
  489. config.Server.WebIRC = newWebIRC
  490. // process limits
  491. if config.Limits.LineLen.Rest < 512 {
  492. config.Limits.LineLen.Rest = 512
  493. }
  494. var newLogConfigs []logger.LoggingConfig
  495. for _, logConfig := range config.Logging {
  496. // methods
  497. methods := make(map[string]bool)
  498. for _, method := range strings.Split(logConfig.Method, " ") {
  499. if len(method) > 0 {
  500. methods[strings.ToLower(method)] = true
  501. }
  502. }
  503. if methods["file"] && logConfig.Filename == "" {
  504. return nil, ErrLoggerFilenameMissing
  505. }
  506. logConfig.MethodFile = methods["file"]
  507. logConfig.MethodStdout = methods["stdout"]
  508. logConfig.MethodStderr = methods["stderr"]
  509. // levels
  510. level, exists := logger.LogLevelNames[strings.ToLower(logConfig.LevelString)]
  511. if !exists {
  512. return nil, fmt.Errorf("Could not translate log leve [%s]", logConfig.LevelString)
  513. }
  514. logConfig.Level = level
  515. // types
  516. for _, typeStr := range strings.Split(logConfig.TypeString, " ") {
  517. if len(typeStr) == 0 {
  518. continue
  519. }
  520. if typeStr == "-" {
  521. return nil, ErrLoggerExcludeEmpty
  522. }
  523. if typeStr[0] == '-' {
  524. typeStr = typeStr[1:]
  525. logConfig.ExcludedTypes = append(logConfig.ExcludedTypes, typeStr)
  526. } else {
  527. logConfig.Types = append(logConfig.Types, typeStr)
  528. }
  529. }
  530. if len(logConfig.Types) < 1 {
  531. return nil, ErrLoggerHasNoTypes
  532. }
  533. newLogConfigs = append(newLogConfigs, logConfig)
  534. }
  535. config.Logging = newLogConfigs
  536. // hardcode this for now
  537. config.Accounts.Registration.EnabledCredentialTypes = []string{"passphrase", "certfp"}
  538. for i, name := range config.Accounts.Registration.EnabledCallbacks {
  539. if name == "none" {
  540. // we store "none" as "*" internally
  541. config.Accounts.Registration.EnabledCallbacks[i] = "*"
  542. }
  543. }
  544. config.Accounts.RequireSasl.exemptedNets, err = utils.ParseNetList(config.Accounts.RequireSasl.Exempted)
  545. if err != nil {
  546. return nil, fmt.Errorf("Could not parse require-sasl exempted nets: %v", err.Error())
  547. }
  548. config.Server.proxyAllowedFromNets, err = utils.ParseNetList(config.Server.ProxyAllowedFrom)
  549. if err != nil {
  550. return nil, fmt.Errorf("Could not parse proxy-allowed-from nets: %v", err.Error())
  551. }
  552. rawRegexp := config.Accounts.VHosts.ValidRegexpRaw
  553. if rawRegexp != "" {
  554. regexp, err := regexp.Compile(rawRegexp)
  555. if err == nil {
  556. config.Accounts.VHosts.ValidRegexp = regexp
  557. } else {
  558. log.Printf("invalid vhost regexp: %s\n", err.Error())
  559. }
  560. }
  561. if config.Accounts.VHosts.ValidRegexp == nil {
  562. config.Accounts.VHosts.ValidRegexp = defaultValidVhostRegex
  563. }
  564. if !config.Accounts.LoginThrottling.Enabled {
  565. config.Accounts.LoginThrottling.MaxAttempts = 0 // limit of 0 means disabled
  566. }
  567. maxSendQBytes, err := bytefmt.ToBytes(config.Server.MaxSendQString)
  568. if err != nil {
  569. return nil, fmt.Errorf("Could not parse maximum SendQ size (make sure it only contains whole numbers): %s", err.Error())
  570. }
  571. config.Server.MaxSendQBytes = int(maxSendQBytes)
  572. config.languageManager, err = languages.NewManager(config.Languages.Enabled, config.Languages.Path, config.Languages.Default)
  573. if err != nil {
  574. return nil, fmt.Errorf("Could not load languages: %s", err.Error())
  575. }
  576. // RecoverFromErrors defaults to true
  577. if config.Debug.RecoverFromErrors == nil {
  578. config.Debug.RecoverFromErrors = new(bool)
  579. *config.Debug.RecoverFromErrors = true
  580. }
  581. // casefold/validate server name
  582. config.Server.nameCasefolded, err = Casefold(config.Server.Name)
  583. if err != nil {
  584. return nil, fmt.Errorf("Server name isn't valid [%s]: %s", config.Server.Name, err.Error())
  585. }
  586. // process operator definitions, store them to config.operators
  587. operclasses, err := config.OperatorClasses()
  588. if err != nil {
  589. return nil, err
  590. }
  591. opers, err := config.Operators(operclasses)
  592. if err != nil {
  593. return nil, err
  594. }
  595. config.operators = opers
  596. // parse default channel modes
  597. config.Channels.defaultModes = ParseDefaultChannelModes(config.Channels.DefaultModes)
  598. if config.Server.Password != "" {
  599. config.Server.passwordBytes, err = decodeLegacyPasswordHash(config.Server.Password)
  600. if err != nil {
  601. return nil, err
  602. }
  603. }
  604. if config.Accounts.Registration.BcryptCost == 0 {
  605. config.Accounts.Registration.BcryptCost = passwd.DefaultCost
  606. }
  607. if config.Channels.MaxChannelsPerClient == 0 {
  608. config.Channels.MaxChannelsPerClient = 100
  609. }
  610. if config.Channels.Registration.MaxChannelsPerAccount == 0 {
  611. config.Channels.Registration.MaxChannelsPerAccount = 15
  612. }
  613. // in the current implementation, we disable history by creating a history buffer
  614. // with zero capacity. but the `enabled` config option MUST be respected regardless
  615. // of this detail
  616. if !config.History.Enabled {
  617. config.History.ChannelLength = 0
  618. config.History.ClientLength = 0
  619. }
  620. for _, listenAddress := range config.Server.TorListeners.Listeners {
  621. found := false
  622. for _, configuredListener := range config.Server.Listen {
  623. if listenAddress == configuredListener {
  624. found = true
  625. break
  626. }
  627. }
  628. if !found {
  629. return nil, fmt.Errorf("%s is configured as a Tor listener, but is not in server.listen", listenAddress)
  630. }
  631. }
  632. return config, nil
  633. }