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

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