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

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