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

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