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

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