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

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