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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871
  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. Fingerprint string
  196. Auto bool
  197. Modes string
  198. }
  199. // LineLenConfig controls line lengths.
  200. type LineLenLimits struct {
  201. Rest int
  202. }
  203. // Various server-enforced limits on data size.
  204. type Limits struct {
  205. AwayLen int `yaml:"awaylen"`
  206. ChanListModes int `yaml:"chan-list-modes"`
  207. ChannelLen int `yaml:"channellen"`
  208. IdentLen int `yaml:"identlen"`
  209. KickLen int `yaml:"kicklen"`
  210. LineLen LineLenLimits `yaml:"linelen"`
  211. MonitorEntries int `yaml:"monitor-entries"`
  212. NickLen int `yaml:"nicklen"`
  213. TopicLen int `yaml:"topiclen"`
  214. WhowasEntries int `yaml:"whowas-entries"`
  215. RegistrationMessages int `yaml:"registration-messages"`
  216. }
  217. // STSConfig controls the STS configuration/
  218. type STSConfig struct {
  219. Enabled bool
  220. Duration time.Duration `yaml:"duration-real"`
  221. DurationString string `yaml:"duration"`
  222. Port int
  223. Preload bool
  224. STSOnlyBanner string `yaml:"sts-only-banner"`
  225. bannerLines []string
  226. }
  227. // Value returns the STS value to advertise in CAP
  228. func (sts *STSConfig) Value() string {
  229. val := fmt.Sprintf("duration=%d", int(sts.Duration.Seconds()))
  230. if sts.Enabled && sts.Port > 0 {
  231. val += fmt.Sprintf(",port=%d", sts.Port)
  232. }
  233. if sts.Enabled && sts.Preload {
  234. val += ",preload"
  235. }
  236. return val
  237. }
  238. type FakelagConfig struct {
  239. Enabled bool
  240. Window time.Duration
  241. BurstLimit uint `yaml:"burst-limit"`
  242. MessagesPerWindow uint `yaml:"messages-per-window"`
  243. Cooldown time.Duration
  244. }
  245. type TorListenersConfig struct {
  246. Listeners []string // legacy only
  247. RequireSasl bool `yaml:"require-sasl"`
  248. Vhost string
  249. MaxConnections int `yaml:"max-connections"`
  250. ThrottleDuration time.Duration `yaml:"throttle-duration"`
  251. MaxConnectionsPerDuration int `yaml:"max-connections-per-duration"`
  252. }
  253. // Config defines the overall configuration.
  254. type Config struct {
  255. Network struct {
  256. Name string
  257. }
  258. Server struct {
  259. Password string
  260. passwordBytes []byte
  261. Name string
  262. nameCasefolded string
  263. // Listeners is the new style for configuring listeners:
  264. Listeners map[string]listenerConfigBlock
  265. UnixBindMode os.FileMode `yaml:"unix-bind-mode"`
  266. TorListeners TorListenersConfig `yaml:"tor-listeners"`
  267. // Listen and TLSListeners are the legacy style:
  268. Listen []string
  269. TLSListeners map[string]TLSListenConfig `yaml:"tls-listeners"`
  270. // either way, the result is this:
  271. trueListeners map[string]listenerConfig
  272. STS STSConfig
  273. LookupHostnames *bool `yaml:"lookup-hostnames"`
  274. lookupHostnames bool
  275. ForwardConfirmHostnames bool `yaml:"forward-confirm-hostnames"`
  276. CheckIdent bool `yaml:"check-ident"`
  277. MOTD string
  278. motdLines []string
  279. MOTDFormatting bool `yaml:"motd-formatting"`
  280. ProxyAllowedFrom []string `yaml:"proxy-allowed-from"`
  281. proxyAllowedFromNets []net.IPNet
  282. WebIRC []webircConfig `yaml:"webirc"`
  283. MaxSendQString string `yaml:"max-sendq"`
  284. MaxSendQBytes int
  285. AllowPlaintextResume bool `yaml:"allow-plaintext-resume"`
  286. Compatibility struct {
  287. ForceTrailing *bool `yaml:"force-trailing"`
  288. forceTrailing bool
  289. SendUnprefixedSasl bool `yaml:"send-unprefixed-sasl"`
  290. }
  291. isupport isupport.List
  292. IPLimits connection_limits.LimiterConfig `yaml:"ip-limits"`
  293. Cloaks cloaks.CloakConfig `yaml:"ip-cloaking"`
  294. supportedCaps *caps.Set
  295. capValues caps.Values
  296. }
  297. Languages struct {
  298. Enabled bool
  299. Path string
  300. Default string
  301. }
  302. languageManager *languages.Manager
  303. Datastore struct {
  304. Path string
  305. AutoUpgrade bool
  306. }
  307. Accounts AccountConfig
  308. Channels struct {
  309. DefaultModes *string `yaml:"default-modes"`
  310. defaultModes modes.Modes
  311. MaxChannelsPerClient int `yaml:"max-channels-per-client"`
  312. OpOnlyCreation bool `yaml:"operator-only-creation"`
  313. Registration ChannelRegistrationConfig
  314. }
  315. OperClasses map[string]*OperClassConfig `yaml:"oper-classes"`
  316. Opers map[string]*OperConfig
  317. // parsed operator definitions, unexported so they can't be defined
  318. // directly in YAML:
  319. operators map[string]*Oper
  320. Logging []logger.LoggingConfig
  321. Debug struct {
  322. RecoverFromErrors *bool `yaml:"recover-from-errors"`
  323. recoverFromErrors bool
  324. PprofListener *string `yaml:"pprof-listener"`
  325. }
  326. Limits Limits
  327. Fakelag FakelagConfig
  328. History struct {
  329. Enabled bool
  330. ChannelLength int `yaml:"channel-length"`
  331. ClientLength int `yaml:"client-length"`
  332. AutoresizeWindow time.Duration `yaml:"autoresize-window"`
  333. AutoreplayOnJoin int `yaml:"autoreplay-on-join"`
  334. ChathistoryMax int `yaml:"chathistory-maxmessages"`
  335. }
  336. Filename string
  337. }
  338. // OperClass defines an assembled operator class.
  339. type OperClass struct {
  340. Title string
  341. WhoisLine string `yaml:"whois-line"`
  342. Capabilities map[string]bool // map to make lookups much easier
  343. }
  344. // OperatorClasses returns a map of assembled operator classes from the given config.
  345. func (conf *Config) OperatorClasses() (map[string]*OperClass, error) {
  346. ocs := make(map[string]*OperClass)
  347. // loop from no extends to most extended, breaking if we can't add any more
  348. lenOfLastOcs := -1
  349. for {
  350. if lenOfLastOcs == len(ocs) {
  351. return nil, ErrOperClassDependencies
  352. }
  353. lenOfLastOcs = len(ocs)
  354. var anyMissing bool
  355. for name, info := range conf.OperClasses {
  356. _, exists := ocs[name]
  357. _, extendsExists := ocs[info.Extends]
  358. if exists {
  359. // class already exists
  360. continue
  361. } else if len(info.Extends) > 0 && !extendsExists {
  362. // class we extend on doesn't exist
  363. _, exists := conf.OperClasses[info.Extends]
  364. if !exists {
  365. return nil, fmt.Errorf("Operclass [%s] extends [%s], which doesn't exist", name, info.Extends)
  366. }
  367. anyMissing = true
  368. continue
  369. }
  370. // create new operclass
  371. var oc OperClass
  372. oc.Capabilities = make(map[string]bool)
  373. // get inhereted info from other operclasses
  374. if len(info.Extends) > 0 {
  375. einfo := ocs[info.Extends]
  376. for capab := range einfo.Capabilities {
  377. oc.Capabilities[capab] = true
  378. }
  379. }
  380. // add our own info
  381. oc.Title = info.Title
  382. for _, capab := range info.Capabilities {
  383. oc.Capabilities[capab] = true
  384. }
  385. if len(info.WhoisLine) > 0 {
  386. oc.WhoisLine = info.WhoisLine
  387. } else {
  388. oc.WhoisLine = "is a"
  389. if strings.Contains(strings.ToLower(string(oc.Title[0])), "aeiou") {
  390. oc.WhoisLine += "n"
  391. }
  392. oc.WhoisLine += " "
  393. oc.WhoisLine += oc.Title
  394. }
  395. ocs[name] = &oc
  396. }
  397. if !anyMissing {
  398. // we've got every operclass!
  399. break
  400. }
  401. }
  402. return ocs, nil
  403. }
  404. // Oper represents a single assembled operator's config.
  405. type Oper struct {
  406. Name string
  407. Class *OperClass
  408. WhoisLine string
  409. Vhost string
  410. Pass []byte
  411. Fingerprint string
  412. Auto bool
  413. Modes []modes.ModeChange
  414. }
  415. // Operators returns a map of operator configs from the given OperClass and config.
  416. func (conf *Config) Operators(oc map[string]*OperClass) (map[string]*Oper, error) {
  417. operators := make(map[string]*Oper)
  418. for name, opConf := range conf.Opers {
  419. var oper Oper
  420. // oper name
  421. name, err := CasefoldName(name)
  422. if err != nil {
  423. return nil, fmt.Errorf("Could not casefold oper name: %s", err.Error())
  424. }
  425. oper.Name = name
  426. if opConf.Password != "" {
  427. oper.Pass, err = decodeLegacyPasswordHash(opConf.Password)
  428. if err != nil {
  429. return nil, err
  430. }
  431. }
  432. oper.Fingerprint = opConf.Fingerprint
  433. oper.Auto = opConf.Auto
  434. if oper.Pass == nil && oper.Fingerprint == "" {
  435. return nil, fmt.Errorf("Oper %s has neither a password nor a fingerprint", name)
  436. }
  437. oper.Vhost = opConf.Vhost
  438. class, exists := oc[opConf.Class]
  439. if !exists {
  440. return nil, fmt.Errorf("Could not load operator [%s] - they use operclass [%s] which does not exist", name, opConf.Class)
  441. }
  442. oper.Class = class
  443. if len(opConf.WhoisLine) > 0 {
  444. oper.WhoisLine = opConf.WhoisLine
  445. } else {
  446. oper.WhoisLine = class.WhoisLine
  447. }
  448. modeStr := strings.TrimSpace(opConf.Modes)
  449. modeChanges, unknownChanges := modes.ParseUserModeChanges(strings.Split(modeStr, " ")...)
  450. if len(unknownChanges) > 0 {
  451. return nil, fmt.Errorf("Could not load operator [%s] due to unknown modes %v", name, unknownChanges)
  452. }
  453. oper.Modes = modeChanges
  454. // successful, attach to list of opers
  455. operators[name] = &oper
  456. }
  457. return operators, nil
  458. }
  459. func loadTlsConfig(config TLSListenConfig) (tlsConfig *tls.Config, err error) {
  460. cert, err := tls.LoadX509KeyPair(config.Cert, config.Key)
  461. if err != nil {
  462. return nil, ErrInvalidCertKeyPair
  463. }
  464. result := tls.Config{
  465. Certificates: []tls.Certificate{cert},
  466. ClientAuth: tls.RequestClientCert,
  467. }
  468. return &result, nil
  469. }
  470. // prepareListeners populates Config.Server.trueListeners
  471. func (conf *Config) prepareListeners() (err error) {
  472. listeners := make(map[string]listenerConfig)
  473. if 0 < len(conf.Server.Listeners) {
  474. for addr, block := range conf.Server.Listeners {
  475. var lconf listenerConfig
  476. lconf.Tor = block.Tor
  477. lconf.STSOnly = block.STSOnly
  478. if lconf.STSOnly && !conf.Server.STS.Enabled {
  479. return fmt.Errorf("%s is configured as a STS-only listener, but STS is disabled", addr)
  480. }
  481. if block.TLS.Cert != "" {
  482. tlsConfig, err := loadTlsConfig(block.TLS)
  483. if err != nil {
  484. return err
  485. }
  486. lconf.TLSConfig = tlsConfig
  487. lconf.ProxyBeforeTLS = block.TLS.Proxy
  488. }
  489. listeners[addr] = lconf
  490. }
  491. } else if 0 < len(conf.Server.Listen) {
  492. log.Printf("WARNING: configuring listeners via the legacy `server.listen` config option")
  493. log.Printf("This will be removed in a later release: you should update to use `server.listeners`")
  494. torListeners := make(map[string]bool, len(conf.Server.TorListeners.Listeners))
  495. for _, addr := range conf.Server.TorListeners.Listeners {
  496. torListeners[addr] = true
  497. }
  498. for _, addr := range conf.Server.Listen {
  499. var lconf listenerConfig
  500. lconf.Tor = torListeners[addr]
  501. tlsListenConf, ok := conf.Server.TLSListeners[addr]
  502. if ok {
  503. tlsConfig, err := loadTlsConfig(tlsListenConf)
  504. if err != nil {
  505. return err
  506. }
  507. lconf.TLSConfig = tlsConfig
  508. }
  509. listeners[addr] = lconf
  510. }
  511. } else {
  512. return fmt.Errorf("No listeners were configured")
  513. }
  514. conf.Server.trueListeners = listeners
  515. return nil
  516. }
  517. // LoadRawConfig loads the config without doing any consistency checks or postprocessing
  518. func LoadRawConfig(filename string) (config *Config, err error) {
  519. data, err := ioutil.ReadFile(filename)
  520. if err != nil {
  521. return nil, err
  522. }
  523. err = yaml.Unmarshal(data, &config)
  524. if err != nil {
  525. return nil, err
  526. }
  527. return
  528. }
  529. // LoadConfig loads the given YAML configuration file.
  530. func LoadConfig(filename string) (config *Config, err error) {
  531. config, err = LoadRawConfig(filename)
  532. if err != nil {
  533. return nil, err
  534. }
  535. config.Filename = filename
  536. if config.Network.Name == "" {
  537. return nil, ErrNetworkNameMissing
  538. }
  539. if config.Server.Name == "" {
  540. return nil, ErrServerNameMissing
  541. }
  542. if !utils.IsServerName(config.Server.Name) {
  543. return nil, ErrServerNameNotHostname
  544. }
  545. if config.Datastore.Path == "" {
  546. return nil, ErrDatastorePathMissing
  547. }
  548. //dan: automagically fix identlen until a few releases in the future (from now, 0.12.0), being a newly-introduced limit
  549. if config.Limits.IdentLen < 1 {
  550. config.Limits.IdentLen = 20
  551. }
  552. if config.Limits.NickLen < 1 || config.Limits.ChannelLen < 2 || config.Limits.AwayLen < 1 || config.Limits.KickLen < 1 || config.Limits.TopicLen < 1 {
  553. return nil, ErrLimitsAreInsane
  554. }
  555. if config.Limits.RegistrationMessages == 0 {
  556. config.Limits.RegistrationMessages = 1024
  557. }
  558. config.Server.supportedCaps = caps.NewCompleteSet()
  559. config.Server.capValues = make(caps.Values)
  560. err = config.prepareListeners()
  561. if err != nil {
  562. return nil, fmt.Errorf("failed to prepare listeners: %v", err)
  563. }
  564. if config.Server.STS.Enabled {
  565. config.Server.STS.Duration, err = custime.ParseDuration(config.Server.STS.DurationString)
  566. if err != nil {
  567. return nil, fmt.Errorf("Could not parse STS duration: %s", err.Error())
  568. }
  569. if config.Server.STS.Port < 0 || config.Server.STS.Port > 65535 {
  570. return nil, fmt.Errorf("STS port is incorrect, should be 0 if disabled: %d", config.Server.STS.Port)
  571. }
  572. if config.Server.STS.STSOnlyBanner != "" {
  573. config.Server.STS.bannerLines = utils.WordWrap(config.Server.STS.STSOnlyBanner, 400)
  574. } else {
  575. 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)}
  576. }
  577. } else {
  578. config.Server.supportedCaps.Disable(caps.STS)
  579. config.Server.STS.Duration = 0
  580. }
  581. // set this even if STS is disabled
  582. config.Server.capValues[caps.STS] = config.Server.STS.Value()
  583. // lookup-hostnames defaults to true if unset
  584. if config.Server.LookupHostnames != nil {
  585. config.Server.lookupHostnames = *config.Server.LookupHostnames
  586. } else {
  587. config.Server.lookupHostnames = true
  588. }
  589. // process webirc blocks
  590. var newWebIRC []webircConfig
  591. for _, webirc := range config.Server.WebIRC {
  592. // skip webirc blocks with no hosts (such as the example one)
  593. if len(webirc.Hosts) == 0 {
  594. continue
  595. }
  596. err = webirc.Populate()
  597. if err != nil {
  598. return nil, fmt.Errorf("Could not parse WebIRC config: %s", err.Error())
  599. }
  600. newWebIRC = append(newWebIRC, webirc)
  601. }
  602. config.Server.WebIRC = newWebIRC
  603. // process limits
  604. if config.Limits.LineLen.Rest < 512 {
  605. config.Limits.LineLen.Rest = 512
  606. }
  607. if config.Limits.LineLen.Rest == 512 {
  608. config.Server.supportedCaps.Disable(caps.MaxLine)
  609. } else {
  610. config.Server.capValues[caps.MaxLine] = strconv.Itoa(config.Limits.LineLen.Rest)
  611. }
  612. if !config.Accounts.Bouncer.Enabled {
  613. config.Server.supportedCaps.Disable(caps.Bouncer)
  614. }
  615. var newLogConfigs []logger.LoggingConfig
  616. for _, logConfig := range config.Logging {
  617. // methods
  618. methods := make(map[string]bool)
  619. for _, method := range strings.Split(logConfig.Method, " ") {
  620. if len(method) > 0 {
  621. methods[strings.ToLower(method)] = true
  622. }
  623. }
  624. if methods["file"] && logConfig.Filename == "" {
  625. return nil, ErrLoggerFilenameMissing
  626. }
  627. logConfig.MethodFile = methods["file"]
  628. logConfig.MethodStdout = methods["stdout"]
  629. logConfig.MethodStderr = methods["stderr"]
  630. // levels
  631. level, exists := logger.LogLevelNames[strings.ToLower(logConfig.LevelString)]
  632. if !exists {
  633. return nil, fmt.Errorf("Could not translate log leve [%s]", logConfig.LevelString)
  634. }
  635. logConfig.Level = level
  636. // types
  637. for _, typeStr := range strings.Split(logConfig.TypeString, " ") {
  638. if len(typeStr) == 0 {
  639. continue
  640. }
  641. if typeStr == "-" {
  642. return nil, ErrLoggerExcludeEmpty
  643. }
  644. if typeStr[0] == '-' {
  645. typeStr = typeStr[1:]
  646. logConfig.ExcludedTypes = append(logConfig.ExcludedTypes, typeStr)
  647. } else {
  648. logConfig.Types = append(logConfig.Types, typeStr)
  649. }
  650. }
  651. if len(logConfig.Types) < 1 {
  652. return nil, ErrLoggerHasNoTypes
  653. }
  654. newLogConfigs = append(newLogConfigs, logConfig)
  655. }
  656. config.Logging = newLogConfigs
  657. // hardcode this for now
  658. config.Accounts.Registration.EnabledCredentialTypes = []string{"passphrase", "certfp"}
  659. for i, name := range config.Accounts.Registration.EnabledCallbacks {
  660. if name == "none" {
  661. // we store "none" as "*" internally
  662. config.Accounts.Registration.EnabledCallbacks[i] = "*"
  663. }
  664. }
  665. sort.Strings(config.Accounts.Registration.EnabledCallbacks)
  666. config.Accounts.RequireSasl.exemptedNets, err = utils.ParseNetList(config.Accounts.RequireSasl.Exempted)
  667. if err != nil {
  668. return nil, fmt.Errorf("Could not parse require-sasl exempted nets: %v", err.Error())
  669. }
  670. config.Server.proxyAllowedFromNets, err = utils.ParseNetList(config.Server.ProxyAllowedFrom)
  671. if err != nil {
  672. return nil, fmt.Errorf("Could not parse proxy-allowed-from nets: %v", err.Error())
  673. }
  674. rawRegexp := config.Accounts.VHosts.ValidRegexpRaw
  675. if rawRegexp != "" {
  676. regexp, err := regexp.Compile(rawRegexp)
  677. if err == nil {
  678. config.Accounts.VHosts.ValidRegexp = regexp
  679. } else {
  680. log.Printf("invalid vhost regexp: %s\n", err.Error())
  681. }
  682. }
  683. if config.Accounts.VHosts.ValidRegexp == nil {
  684. config.Accounts.VHosts.ValidRegexp = defaultValidVhostRegex
  685. }
  686. if !config.Accounts.LoginThrottling.Enabled {
  687. config.Accounts.LoginThrottling.MaxAttempts = 0 // limit of 0 means disabled
  688. }
  689. config.Server.capValues[caps.SASL] = "PLAIN,EXTERNAL"
  690. if !config.Accounts.AuthenticationEnabled {
  691. config.Server.supportedCaps.Disable(caps.SASL)
  692. }
  693. maxSendQBytes, err := bytefmt.ToBytes(config.Server.MaxSendQString)
  694. if err != nil {
  695. return nil, fmt.Errorf("Could not parse maximum SendQ size (make sure it only contains whole numbers): %s", err.Error())
  696. }
  697. config.Server.MaxSendQBytes = int(maxSendQBytes)
  698. config.languageManager, err = languages.NewManager(config.Languages.Enabled, config.Languages.Path, config.Languages.Default)
  699. if err != nil {
  700. return nil, fmt.Errorf("Could not load languages: %s", err.Error())
  701. }
  702. config.Server.capValues[caps.Languages] = config.languageManager.CapValue()
  703. // RecoverFromErrors defaults to true
  704. if config.Debug.RecoverFromErrors != nil {
  705. config.Debug.recoverFromErrors = *config.Debug.RecoverFromErrors
  706. } else {
  707. config.Debug.recoverFromErrors = true
  708. }
  709. // casefold/validate server name
  710. config.Server.nameCasefolded, err = Casefold(config.Server.Name)
  711. if err != nil {
  712. return nil, fmt.Errorf("Server name isn't valid [%s]: %s", config.Server.Name, err.Error())
  713. }
  714. // process operator definitions, store them to config.operators
  715. operclasses, err := config.OperatorClasses()
  716. if err != nil {
  717. return nil, err
  718. }
  719. opers, err := config.Operators(operclasses)
  720. if err != nil {
  721. return nil, err
  722. }
  723. config.operators = opers
  724. // parse default channel modes
  725. config.Channels.defaultModes = ParseDefaultChannelModes(config.Channels.DefaultModes)
  726. if config.Server.Password != "" {
  727. config.Server.passwordBytes, err = decodeLegacyPasswordHash(config.Server.Password)
  728. if err != nil {
  729. return nil, err
  730. }
  731. }
  732. if config.Accounts.Registration.BcryptCost == 0 {
  733. config.Accounts.Registration.BcryptCost = passwd.DefaultCost
  734. }
  735. if config.Channels.MaxChannelsPerClient == 0 {
  736. config.Channels.MaxChannelsPerClient = 100
  737. }
  738. if config.Channels.Registration.MaxChannelsPerAccount == 0 {
  739. config.Channels.Registration.MaxChannelsPerAccount = 15
  740. }
  741. forceTrailingPtr := config.Server.Compatibility.ForceTrailing
  742. if forceTrailingPtr != nil {
  743. config.Server.Compatibility.forceTrailing = *forceTrailingPtr
  744. } else {
  745. config.Server.Compatibility.forceTrailing = true
  746. }
  747. config.loadMOTD()
  748. // in the current implementation, we disable history by creating a history buffer
  749. // with zero capacity. but the `enabled` config option MUST be respected regardless
  750. // of this detail
  751. if !config.History.Enabled {
  752. config.History.ChannelLength = 0
  753. config.History.ClientLength = 0
  754. }
  755. config.Server.Cloaks.Initialize()
  756. if config.Server.Cloaks.Enabled {
  757. if config.Server.Cloaks.Secret == "" || config.Server.Cloaks.Secret == "siaELnk6Kaeo65K3RCrwJjlWaZ-Bt3WuZ2L8MXLbNb4" {
  758. return nil, fmt.Errorf("You must generate a new value of server.ip-cloaking.secret to enable cloaking")
  759. }
  760. }
  761. // now that all postprocessing is complete, regenerate ISUPPORT:
  762. err = config.generateISupport()
  763. if err != nil {
  764. return nil, err
  765. }
  766. err = config.prepareListeners()
  767. if err != nil {
  768. return nil, fmt.Errorf("failed to prepare listeners: %v", err)
  769. }
  770. return config, nil
  771. }