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

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