Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

config.go 25KB

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