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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251
  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. "errors"
  9. "fmt"
  10. "io/ioutil"
  11. "log"
  12. "net"
  13. "os"
  14. "path/filepath"
  15. "regexp"
  16. "sort"
  17. "strconv"
  18. "strings"
  19. "time"
  20. "code.cloudfoundry.org/bytefmt"
  21. "github.com/oragono/oragono/irc/caps"
  22. "github.com/oragono/oragono/irc/cloaks"
  23. "github.com/oragono/oragono/irc/connection_limits"
  24. "github.com/oragono/oragono/irc/custime"
  25. "github.com/oragono/oragono/irc/email"
  26. "github.com/oragono/oragono/irc/isupport"
  27. "github.com/oragono/oragono/irc/languages"
  28. "github.com/oragono/oragono/irc/ldap"
  29. "github.com/oragono/oragono/irc/logger"
  30. "github.com/oragono/oragono/irc/modes"
  31. "github.com/oragono/oragono/irc/mysql"
  32. "github.com/oragono/oragono/irc/passwd"
  33. "github.com/oragono/oragono/irc/utils"
  34. "gopkg.in/yaml.v2"
  35. )
  36. // here's how this works: exported (capitalized) members of the config structs
  37. // are defined in the YAML file and deserialized directly from there. They may
  38. // be postprocessed and overwritten by LoadConfig. Unexported (lowercase) members
  39. // are derived from the exported members in LoadConfig.
  40. // TLSListenConfig defines configuration options for listening on TLS.
  41. type TLSListenConfig struct {
  42. Cert string
  43. Key string
  44. Proxy bool
  45. }
  46. // This is the YAML-deserializable type of the value of the `Server.Listeners` map
  47. type listenerConfigBlock struct {
  48. TLS TLSListenConfig
  49. Tor bool
  50. STSOnly bool `yaml:"sts-only"`
  51. WebSocket bool
  52. }
  53. type PersistentStatus uint
  54. const (
  55. PersistentUnspecified PersistentStatus = iota
  56. PersistentDisabled
  57. PersistentOptIn
  58. PersistentOptOut
  59. PersistentMandatory
  60. )
  61. func persistentStatusToString(status PersistentStatus) string {
  62. switch status {
  63. case PersistentUnspecified:
  64. return "default"
  65. case PersistentDisabled:
  66. return "disabled"
  67. case PersistentOptIn:
  68. return "opt-in"
  69. case PersistentOptOut:
  70. return "opt-out"
  71. case PersistentMandatory:
  72. return "mandatory"
  73. default:
  74. return ""
  75. }
  76. }
  77. func persistentStatusFromString(status string) (PersistentStatus, error) {
  78. switch strings.ToLower(status) {
  79. case "default":
  80. return PersistentUnspecified, nil
  81. case "":
  82. return PersistentDisabled, nil
  83. case "opt-in":
  84. return PersistentOptIn, nil
  85. case "opt-out":
  86. return PersistentOptOut, nil
  87. case "mandatory":
  88. return PersistentMandatory, nil
  89. default:
  90. b, err := utils.StringToBool(status)
  91. if b {
  92. return PersistentMandatory, err
  93. } else {
  94. return PersistentDisabled, err
  95. }
  96. }
  97. }
  98. func (ps *PersistentStatus) UnmarshalYAML(unmarshal func(interface{}) error) error {
  99. var orig string
  100. var err error
  101. if err = unmarshal(&orig); err != nil {
  102. return err
  103. }
  104. result, err := persistentStatusFromString(orig)
  105. if err == nil {
  106. if result == PersistentUnspecified {
  107. result = PersistentDisabled
  108. }
  109. *ps = result
  110. }
  111. return err
  112. }
  113. func persistenceEnabled(serverSetting, clientSetting PersistentStatus) (enabled bool) {
  114. if serverSetting == PersistentDisabled {
  115. return false
  116. } else if serverSetting == PersistentMandatory {
  117. return true
  118. } else if clientSetting == PersistentDisabled {
  119. return false
  120. } else if clientSetting == PersistentMandatory {
  121. return true
  122. } else if serverSetting == PersistentOptOut {
  123. return true
  124. } else {
  125. return false
  126. }
  127. }
  128. type HistoryStatus uint
  129. const (
  130. HistoryDefault HistoryStatus = iota
  131. HistoryDisabled
  132. HistoryEphemeral
  133. HistoryPersistent
  134. )
  135. func historyStatusFromString(str string) (status HistoryStatus, err error) {
  136. switch strings.ToLower(str) {
  137. case "default":
  138. return HistoryDefault, nil
  139. case "ephemeral":
  140. return HistoryEphemeral, nil
  141. case "persistent":
  142. return HistoryPersistent, nil
  143. default:
  144. b, err := utils.StringToBool(str)
  145. if b {
  146. return HistoryPersistent, err
  147. } else {
  148. return HistoryDisabled, err
  149. }
  150. }
  151. }
  152. func historyStatusToString(status HistoryStatus) string {
  153. switch status {
  154. case HistoryDefault:
  155. return "default"
  156. case HistoryDisabled:
  157. return "disabled"
  158. case HistoryEphemeral:
  159. return "ephemeral"
  160. case HistoryPersistent:
  161. return "persistent"
  162. default:
  163. return ""
  164. }
  165. }
  166. // XXX you must have already checked History.Enabled before calling this
  167. func historyEnabled(serverSetting PersistentStatus, localSetting HistoryStatus) (result HistoryStatus) {
  168. switch serverSetting {
  169. case PersistentMandatory:
  170. return HistoryPersistent
  171. case PersistentOptOut:
  172. if localSetting == HistoryDefault {
  173. return HistoryPersistent
  174. } else {
  175. return localSetting
  176. }
  177. case PersistentOptIn:
  178. switch localSetting {
  179. case HistoryPersistent:
  180. return HistoryPersistent
  181. case HistoryEphemeral, HistoryDefault:
  182. return HistoryEphemeral
  183. default:
  184. return HistoryDisabled
  185. }
  186. case PersistentDisabled:
  187. if localSetting == HistoryDisabled {
  188. return HistoryDisabled
  189. } else {
  190. return HistoryEphemeral
  191. }
  192. default:
  193. // PersistentUnspecified: shouldn't happen because the deserializer converts it
  194. // to PersistentDisabled
  195. if localSetting == HistoryDefault {
  196. return HistoryEphemeral
  197. } else {
  198. return localSetting
  199. }
  200. }
  201. }
  202. type MulticlientConfig struct {
  203. Enabled bool
  204. AllowedByDefault bool `yaml:"allowed-by-default"`
  205. AlwaysOn PersistentStatus `yaml:"always-on"`
  206. }
  207. type throttleConfig struct {
  208. Enabled bool
  209. Duration time.Duration
  210. MaxAttempts int `yaml:"max-attempts"`
  211. }
  212. type ThrottleConfig struct {
  213. throttleConfig
  214. }
  215. func (t *ThrottleConfig) UnmarshalYAML(unmarshal func(interface{}) error) (err error) {
  216. // note that this technique only works if the zero value of the struct
  217. // doesn't need any postprocessing (because if the field is omitted entirely
  218. // from the YAML, then UnmarshalYAML won't be called at all)
  219. if err = unmarshal(&t.throttleConfig); err != nil {
  220. return
  221. }
  222. if !t.Enabled {
  223. t.MaxAttempts = 0 // limit of 0 means disabled
  224. }
  225. return
  226. }
  227. type AccountConfig struct {
  228. Registration AccountRegistrationConfig
  229. AuthenticationEnabled bool `yaml:"authentication-enabled"`
  230. RequireSasl struct {
  231. Enabled bool
  232. Exempted []string
  233. exemptedNets []net.IPNet
  234. } `yaml:"require-sasl"`
  235. DefaultUserModes *string `yaml:"default-user-modes"`
  236. defaultUserModes modes.ModeChanges
  237. LDAP ldap.ServerConfig
  238. LoginThrottling ThrottleConfig `yaml:"login-throttling"`
  239. SkipServerPassword bool `yaml:"skip-server-password"`
  240. NickReservation struct {
  241. Enabled bool
  242. AdditionalNickLimit int `yaml:"additional-nick-limit"`
  243. Method NickEnforcementMethod
  244. AllowCustomEnforcement bool `yaml:"allow-custom-enforcement"`
  245. RenameTimeout time.Duration `yaml:"rename-timeout"`
  246. // RenamePrefix is the legacy field, GuestFormat is the new version
  247. RenamePrefix string `yaml:"rename-prefix"`
  248. GuestFormat string `yaml:"guest-nickname-format"`
  249. guestRegexp *regexp.Regexp
  250. guestRegexpFolded *regexp.Regexp
  251. ForceGuestFormat bool `yaml:"force-guest-format"`
  252. ForceNickEqualsAccount bool `yaml:"force-nick-equals-account"`
  253. } `yaml:"nick-reservation"`
  254. Multiclient MulticlientConfig
  255. Bouncer *MulticlientConfig // # handle old name for 'multiclient'
  256. VHosts VHostConfig
  257. }
  258. // AccountRegistrationConfig controls account registration.
  259. type AccountRegistrationConfig struct {
  260. Enabled bool
  261. Throttling ThrottleConfig
  262. EnabledCallbacks []string `yaml:"enabled-callbacks"`
  263. EnabledCredentialTypes []string `yaml:"-"`
  264. VerifyTimeout custime.Duration `yaml:"verify-timeout"`
  265. Callbacks struct {
  266. Mailto email.MailtoConfig
  267. }
  268. BcryptCost uint `yaml:"bcrypt-cost"`
  269. }
  270. type VHostConfig struct {
  271. Enabled bool
  272. MaxLength int `yaml:"max-length"`
  273. ValidRegexpRaw string `yaml:"valid-regexp"`
  274. ValidRegexp *regexp.Regexp
  275. UserRequests struct {
  276. Enabled bool
  277. Channel string
  278. Cooldown custime.Duration
  279. } `yaml:"user-requests"`
  280. OfferList []string `yaml:"offer-list"`
  281. }
  282. type NickEnforcementMethod int
  283. const (
  284. // NickEnforcementOptional is the zero value; it serializes to
  285. // "optional" in the yaml config, and "default" as an arg to `NS ENFORCE`.
  286. // in both cases, it means "defer to the other source of truth", i.e.,
  287. // in the config, defer to the user's custom setting, and as a custom setting,
  288. // defer to the default in the config. if both are NickEnforcementOptional then
  289. // there is no enforcement.
  290. // XXX: these are serialized as numbers in the database, so beware of collisions
  291. // when refactoring (any numbers currently in use must keep their meanings, or
  292. // else be fixed up by a schema change)
  293. NickEnforcementOptional NickEnforcementMethod = iota
  294. NickEnforcementNone
  295. NickEnforcementWithTimeout
  296. NickEnforcementStrict
  297. )
  298. func nickReservationToString(method NickEnforcementMethod) string {
  299. switch method {
  300. case NickEnforcementOptional:
  301. return "default"
  302. case NickEnforcementNone:
  303. return "none"
  304. case NickEnforcementWithTimeout:
  305. return "timeout"
  306. case NickEnforcementStrict:
  307. return "strict"
  308. default:
  309. return ""
  310. }
  311. }
  312. func nickReservationFromString(method string) (NickEnforcementMethod, error) {
  313. switch strings.ToLower(method) {
  314. case "default":
  315. return NickEnforcementOptional, nil
  316. case "optional":
  317. return NickEnforcementOptional, nil
  318. case "none":
  319. return NickEnforcementNone, nil
  320. case "timeout":
  321. return NickEnforcementWithTimeout, nil
  322. case "strict":
  323. return NickEnforcementStrict, nil
  324. default:
  325. return NickEnforcementOptional, fmt.Errorf("invalid nick-reservation.method value: %s", method)
  326. }
  327. }
  328. func (nr *NickEnforcementMethod) UnmarshalYAML(unmarshal func(interface{}) error) error {
  329. var orig string
  330. var err error
  331. if err = unmarshal(&orig); err != nil {
  332. return err
  333. }
  334. method, err := nickReservationFromString(orig)
  335. if err == nil {
  336. *nr = method
  337. }
  338. return err
  339. }
  340. func (cm *Casemapping) UnmarshalYAML(unmarshal func(interface{}) error) (err error) {
  341. var orig string
  342. if err = unmarshal(&orig); err != nil {
  343. return err
  344. }
  345. var result Casemapping
  346. switch strings.ToLower(orig) {
  347. case "ascii":
  348. result = CasemappingASCII
  349. case "precis", "rfc7613", "rfc8265":
  350. result = CasemappingPRECIS
  351. case "permissive", "fun":
  352. result = CasemappingPermissive
  353. default:
  354. return fmt.Errorf("invalid casemapping value: %s", orig)
  355. }
  356. *cm = result
  357. return nil
  358. }
  359. // OperClassConfig defines a specific operator class.
  360. type OperClassConfig struct {
  361. Title string
  362. WhoisLine string
  363. Extends string
  364. Capabilities []string
  365. }
  366. // OperConfig defines a specific operator's configuration.
  367. type OperConfig struct {
  368. Class string
  369. Vhost string
  370. WhoisLine string `yaml:"whois-line"`
  371. Password string
  372. Fingerprint string
  373. Auto bool
  374. Modes string
  375. }
  376. // Various server-enforced limits on data size.
  377. type Limits struct {
  378. AwayLen int `yaml:"awaylen"`
  379. ChanListModes int `yaml:"chan-list-modes"`
  380. ChannelLen int `yaml:"channellen"`
  381. IdentLen int `yaml:"identlen"`
  382. KickLen int `yaml:"kicklen"`
  383. MonitorEntries int `yaml:"monitor-entries"`
  384. NickLen int `yaml:"nicklen"`
  385. TopicLen int `yaml:"topiclen"`
  386. WhowasEntries int `yaml:"whowas-entries"`
  387. RegistrationMessages int `yaml:"registration-messages"`
  388. Multiline struct {
  389. MaxBytes int `yaml:"max-bytes"`
  390. MaxLines int `yaml:"max-lines"`
  391. }
  392. }
  393. // STSConfig controls the STS configuration/
  394. type STSConfig struct {
  395. Enabled bool
  396. Duration custime.Duration
  397. Port int
  398. Preload bool
  399. STSOnlyBanner string `yaml:"sts-only-banner"`
  400. bannerLines []string
  401. }
  402. // Value returns the STS value to advertise in CAP
  403. func (sts *STSConfig) Value() string {
  404. val := fmt.Sprintf("duration=%d", int(time.Duration(sts.Duration).Seconds()))
  405. if sts.Enabled && sts.Port > 0 {
  406. val += fmt.Sprintf(",port=%d", sts.Port)
  407. }
  408. if sts.Enabled && sts.Preload {
  409. val += ",preload"
  410. }
  411. return val
  412. }
  413. type FakelagConfig struct {
  414. Enabled bool
  415. Window time.Duration
  416. BurstLimit uint `yaml:"burst-limit"`
  417. MessagesPerWindow uint `yaml:"messages-per-window"`
  418. Cooldown time.Duration
  419. }
  420. type TorListenersConfig struct {
  421. Listeners []string // legacy only
  422. RequireSasl bool `yaml:"require-sasl"`
  423. Vhost string
  424. MaxConnections int `yaml:"max-connections"`
  425. ThrottleDuration time.Duration `yaml:"throttle-duration"`
  426. MaxConnectionsPerDuration int `yaml:"max-connections-per-duration"`
  427. }
  428. // Config defines the overall configuration.
  429. type Config struct {
  430. Network struct {
  431. Name string
  432. }
  433. Server struct {
  434. Password string
  435. passwordBytes []byte
  436. Name string
  437. nameCasefolded string
  438. // Listeners is the new style for configuring listeners:
  439. Listeners map[string]listenerConfigBlock
  440. UnixBindMode os.FileMode `yaml:"unix-bind-mode"`
  441. TorListeners TorListenersConfig `yaml:"tor-listeners"`
  442. WebSockets struct {
  443. AllowedOrigins []string `yaml:"allowed-origins"`
  444. allowedOriginRegexps []*regexp.Regexp
  445. }
  446. // they get parsed into this internal representation:
  447. trueListeners map[string]utils.ListenerConfig
  448. STS STSConfig
  449. LookupHostnames *bool `yaml:"lookup-hostnames"`
  450. lookupHostnames bool
  451. ForwardConfirmHostnames bool `yaml:"forward-confirm-hostnames"`
  452. CheckIdent bool `yaml:"check-ident"`
  453. MOTD string
  454. motdLines []string
  455. MOTDFormatting bool `yaml:"motd-formatting"`
  456. ProxyAllowedFrom []string `yaml:"proxy-allowed-from"`
  457. proxyAllowedFromNets []net.IPNet
  458. WebIRC []webircConfig `yaml:"webirc"`
  459. MaxSendQString string `yaml:"max-sendq"`
  460. MaxSendQBytes int
  461. AllowPlaintextResume bool `yaml:"allow-plaintext-resume"`
  462. Compatibility struct {
  463. ForceTrailing *bool `yaml:"force-trailing"`
  464. forceTrailing bool
  465. SendUnprefixedSasl bool `yaml:"send-unprefixed-sasl"`
  466. }
  467. isupport isupport.List
  468. IPLimits connection_limits.LimiterConfig `yaml:"ip-limits"`
  469. Cloaks cloaks.CloakConfig `yaml:"ip-cloaking"`
  470. SecureNetDefs []string `yaml:"secure-nets"`
  471. secureNets []net.IPNet
  472. supportedCaps *caps.Set
  473. capValues caps.Values
  474. Casemapping Casemapping
  475. OutputPath string `yaml:"output-path"`
  476. }
  477. Roleplay struct {
  478. Enabled *bool
  479. enabled bool
  480. RequireChanops bool `yaml:"require-chanops"`
  481. RequireOper bool `yaml:"require-oper"`
  482. AddSuffix *bool `yaml:"add-suffix"`
  483. addSuffix bool
  484. }
  485. Languages struct {
  486. Enabled bool
  487. Path string
  488. Default string
  489. }
  490. languageManager *languages.Manager
  491. Datastore struct {
  492. Path string
  493. AutoUpgrade bool
  494. MySQL mysql.Config
  495. }
  496. Accounts AccountConfig
  497. Channels struct {
  498. DefaultModes *string `yaml:"default-modes"`
  499. defaultModes modes.Modes
  500. MaxChannelsPerClient int `yaml:"max-channels-per-client"`
  501. OpOnlyCreation bool `yaml:"operator-only-creation"`
  502. Registration struct {
  503. Enabled bool
  504. OperatorOnly bool `yaml:"operator-only"`
  505. MaxChannelsPerAccount int `yaml:"max-channels-per-account"`
  506. }
  507. ListDelay time.Duration `yaml:"list-delay"`
  508. }
  509. OperClasses map[string]*OperClassConfig `yaml:"oper-classes"`
  510. Opers map[string]*OperConfig
  511. // parsed operator definitions, unexported so they can't be defined
  512. // directly in YAML:
  513. operators map[string]*Oper
  514. Logging []logger.LoggingConfig
  515. Debug struct {
  516. RecoverFromErrors *bool `yaml:"recover-from-errors"`
  517. recoverFromErrors bool
  518. PprofListener *string `yaml:"pprof-listener"`
  519. }
  520. Limits Limits
  521. Fakelag FakelagConfig
  522. History struct {
  523. Enabled bool
  524. ChannelLength int `yaml:"channel-length"`
  525. ClientLength int `yaml:"client-length"`
  526. AutoresizeWindow time.Duration `yaml:"autoresize-window"`
  527. AutoreplayOnJoin int `yaml:"autoreplay-on-join"`
  528. ChathistoryMax int `yaml:"chathistory-maxmessages"`
  529. ZNCMax int `yaml:"znc-maxmessages"`
  530. Restrictions struct {
  531. ExpireTime custime.Duration `yaml:"expire-time"`
  532. EnforceRegistrationDate bool `yaml:"enforce-registration-date"`
  533. GracePeriod custime.Duration `yaml:"grace-period"`
  534. }
  535. Persistent struct {
  536. Enabled bool
  537. UnregisteredChannels bool `yaml:"unregistered-channels"`
  538. RegisteredChannels PersistentStatus `yaml:"registered-channels"`
  539. DirectMessages PersistentStatus `yaml:"direct-messages"`
  540. }
  541. Retention struct {
  542. AllowIndividualDelete bool `yaml:"allow-individual-delete"`
  543. EnableAccountIndexing bool `yaml:"enable-account-indexing"`
  544. }
  545. }
  546. Filename string
  547. }
  548. // OperClass defines an assembled operator class.
  549. type OperClass struct {
  550. Title string
  551. WhoisLine string `yaml:"whois-line"`
  552. Capabilities StringSet // map to make lookups much easier
  553. }
  554. // OperatorClasses returns a map of assembled operator classes from the given config.
  555. func (conf *Config) OperatorClasses() (map[string]*OperClass, error) {
  556. fixupCapability := func(capab string) string {
  557. return strings.TrimPrefix(capab, "oper:") // #868
  558. }
  559. ocs := make(map[string]*OperClass)
  560. // loop from no extends to most extended, breaking if we can't add any more
  561. lenOfLastOcs := -1
  562. for {
  563. if lenOfLastOcs == len(ocs) {
  564. return nil, ErrOperClassDependencies
  565. }
  566. lenOfLastOcs = len(ocs)
  567. var anyMissing bool
  568. for name, info := range conf.OperClasses {
  569. _, exists := ocs[name]
  570. _, extendsExists := ocs[info.Extends]
  571. if exists {
  572. // class already exists
  573. continue
  574. } else if len(info.Extends) > 0 && !extendsExists {
  575. // class we extend on doesn't exist
  576. _, exists := conf.OperClasses[info.Extends]
  577. if !exists {
  578. return nil, fmt.Errorf("Operclass [%s] extends [%s], which doesn't exist", name, info.Extends)
  579. }
  580. anyMissing = true
  581. continue
  582. }
  583. // create new operclass
  584. var oc OperClass
  585. oc.Capabilities = make(StringSet)
  586. // get inhereted info from other operclasses
  587. if len(info.Extends) > 0 {
  588. einfo := ocs[info.Extends]
  589. for capab := range einfo.Capabilities {
  590. oc.Capabilities.Add(fixupCapability(capab))
  591. }
  592. }
  593. // add our own info
  594. oc.Title = info.Title
  595. for _, capab := range info.Capabilities {
  596. oc.Capabilities.Add(fixupCapability(capab))
  597. }
  598. if len(info.WhoisLine) > 0 {
  599. oc.WhoisLine = info.WhoisLine
  600. } else {
  601. oc.WhoisLine = "is a"
  602. if strings.Contains(strings.ToLower(string(oc.Title[0])), "aeiou") {
  603. oc.WhoisLine += "n"
  604. }
  605. oc.WhoisLine += " "
  606. oc.WhoisLine += oc.Title
  607. }
  608. ocs[name] = &oc
  609. }
  610. if !anyMissing {
  611. // we've got every operclass!
  612. break
  613. }
  614. }
  615. return ocs, nil
  616. }
  617. // Oper represents a single assembled operator's config.
  618. type Oper struct {
  619. Name string
  620. Class *OperClass
  621. WhoisLine string
  622. Vhost string
  623. Pass []byte
  624. Fingerprint string
  625. Auto bool
  626. Modes []modes.ModeChange
  627. }
  628. // Operators returns a map of operator configs from the given OperClass and config.
  629. func (conf *Config) Operators(oc map[string]*OperClass) (map[string]*Oper, error) {
  630. operators := make(map[string]*Oper)
  631. for name, opConf := range conf.Opers {
  632. var oper Oper
  633. // oper name
  634. name, err := CasefoldName(name)
  635. if err != nil {
  636. return nil, fmt.Errorf("Could not casefold oper name: %s", err.Error())
  637. }
  638. oper.Name = name
  639. if opConf.Password != "" {
  640. oper.Pass, err = decodeLegacyPasswordHash(opConf.Password)
  641. if err != nil {
  642. return nil, fmt.Errorf("Oper %s has an invalid password hash: %s", oper.Name, err.Error())
  643. }
  644. }
  645. if opConf.Fingerprint != "" {
  646. oper.Fingerprint, err = utils.NormalizeCertfp(opConf.Fingerprint)
  647. if err != nil {
  648. return nil, fmt.Errorf("Oper %s has an invalid fingerprint: %s", oper.Name, err.Error())
  649. }
  650. }
  651. oper.Auto = opConf.Auto
  652. if oper.Pass == nil && oper.Fingerprint == "" {
  653. return nil, fmt.Errorf("Oper %s has neither a password nor a fingerprint", name)
  654. }
  655. oper.Vhost = opConf.Vhost
  656. class, exists := oc[opConf.Class]
  657. if !exists {
  658. return nil, fmt.Errorf("Could not load operator [%s] - they use operclass [%s] which does not exist", name, opConf.Class)
  659. }
  660. oper.Class = class
  661. if len(opConf.WhoisLine) > 0 {
  662. oper.WhoisLine = opConf.WhoisLine
  663. } else {
  664. oper.WhoisLine = class.WhoisLine
  665. }
  666. modeStr := strings.TrimSpace(opConf.Modes)
  667. modeChanges, unknownChanges := modes.ParseUserModeChanges(strings.Split(modeStr, " ")...)
  668. if len(unknownChanges) > 0 {
  669. return nil, fmt.Errorf("Could not load operator [%s] due to unknown modes %v", name, unknownChanges)
  670. }
  671. oper.Modes = modeChanges
  672. // successful, attach to list of opers
  673. operators[name] = &oper
  674. }
  675. return operators, nil
  676. }
  677. func loadTlsConfig(config TLSListenConfig, webSocket bool) (tlsConfig *tls.Config, err error) {
  678. cert, err := tls.LoadX509KeyPair(config.Cert, config.Key)
  679. if err != nil {
  680. return nil, &CertKeyError{Err: err}
  681. }
  682. clientAuth := tls.RequestClientCert
  683. if webSocket {
  684. // if Chrome receives a server request for a client certificate
  685. // on a websocket connection, it will immediately disconnect:
  686. // https://bugs.chromium.org/p/chromium/issues/detail?id=329884
  687. // work around this behavior:
  688. clientAuth = tls.NoClientCert
  689. }
  690. result := tls.Config{
  691. Certificates: []tls.Certificate{cert},
  692. ClientAuth: clientAuth,
  693. }
  694. return &result, nil
  695. }
  696. // prepareListeners populates Config.Server.trueListeners
  697. func (conf *Config) prepareListeners() (err error) {
  698. if len(conf.Server.Listeners) == 0 {
  699. return fmt.Errorf("No listeners were configured")
  700. }
  701. conf.Server.trueListeners = make(map[string]utils.ListenerConfig)
  702. for addr, block := range conf.Server.Listeners {
  703. var lconf utils.ListenerConfig
  704. lconf.ProxyDeadline = RegisterTimeout
  705. lconf.Tor = block.Tor
  706. lconf.STSOnly = block.STSOnly
  707. if lconf.STSOnly && !conf.Server.STS.Enabled {
  708. return fmt.Errorf("%s is configured as a STS-only listener, but STS is disabled", addr)
  709. }
  710. if block.TLS.Cert != "" {
  711. tlsConfig, err := loadTlsConfig(block.TLS, block.WebSocket)
  712. if err != nil {
  713. return err
  714. }
  715. lconf.TLSConfig = tlsConfig
  716. lconf.RequireProxy = block.TLS.Proxy
  717. }
  718. lconf.WebSocket = block.WebSocket
  719. conf.Server.trueListeners[addr] = lconf
  720. }
  721. return nil
  722. }
  723. // LoadRawConfig loads the config without doing any consistency checks or postprocessing
  724. func LoadRawConfig(filename string) (config *Config, err error) {
  725. data, err := ioutil.ReadFile(filename)
  726. if err != nil {
  727. return nil, err
  728. }
  729. err = yaml.Unmarshal(data, &config)
  730. if err != nil {
  731. return nil, err
  732. }
  733. return
  734. }
  735. // LoadConfig loads the given YAML configuration file.
  736. func LoadConfig(filename string) (config *Config, err error) {
  737. config, err = LoadRawConfig(filename)
  738. if err != nil {
  739. return nil, err
  740. }
  741. config.Filename = filename
  742. if config.Network.Name == "" {
  743. return nil, ErrNetworkNameMissing
  744. }
  745. if config.Server.Name == "" {
  746. return nil, ErrServerNameMissing
  747. }
  748. if !utils.IsServerName(config.Server.Name) {
  749. return nil, ErrServerNameNotHostname
  750. }
  751. config.Server.nameCasefolded = strings.ToLower(config.Server.Name)
  752. if config.Datastore.Path == "" {
  753. return nil, ErrDatastorePathMissing
  754. }
  755. //dan: automagically fix identlen until a few releases in the future (from now, 0.12.0), being a newly-introduced limit
  756. if config.Limits.IdentLen < 1 {
  757. config.Limits.IdentLen = 20
  758. }
  759. if config.Limits.NickLen < 1 || config.Limits.ChannelLen < 2 || config.Limits.AwayLen < 1 || config.Limits.KickLen < 1 || config.Limits.TopicLen < 1 {
  760. return nil, ErrLimitsAreInsane
  761. }
  762. if config.Limits.RegistrationMessages == 0 {
  763. config.Limits.RegistrationMessages = 1024
  764. }
  765. if config.Datastore.MySQL.Enabled {
  766. if config.Limits.NickLen > mysql.MaxTargetLength || config.Limits.ChannelLen > mysql.MaxTargetLength {
  767. return nil, fmt.Errorf("to use MySQL, nick and channel length limits must be %d or lower", mysql.MaxTargetLength)
  768. }
  769. }
  770. config.Server.supportedCaps = caps.NewCompleteSet()
  771. config.Server.capValues = make(caps.Values)
  772. err = config.prepareListeners()
  773. if err != nil {
  774. return nil, fmt.Errorf("failed to prepare listeners: %v", err)
  775. }
  776. for _, glob := range config.Server.WebSockets.AllowedOrigins {
  777. globre, err := utils.CompileGlob(glob, false)
  778. if err != nil {
  779. return nil, fmt.Errorf("invalid websocket allowed-origin expression: %s", glob)
  780. }
  781. config.Server.WebSockets.allowedOriginRegexps = append(config.Server.WebSockets.allowedOriginRegexps, globre)
  782. }
  783. if config.Server.STS.Enabled {
  784. if config.Server.STS.Port < 0 || config.Server.STS.Port > 65535 {
  785. return nil, fmt.Errorf("STS port is incorrect, should be 0 if disabled: %d", config.Server.STS.Port)
  786. }
  787. if config.Server.STS.STSOnlyBanner != "" {
  788. for _, line := range strings.Split(config.Server.STS.STSOnlyBanner, "\n") {
  789. config.Server.STS.bannerLines = append(config.Server.STS.bannerLines, strings.TrimSpace(line))
  790. }
  791. } else {
  792. 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)}
  793. }
  794. } else {
  795. config.Server.supportedCaps.Disable(caps.STS)
  796. config.Server.STS.Duration = 0
  797. }
  798. // set this even if STS is disabled
  799. config.Server.capValues[caps.STS] = config.Server.STS.Value()
  800. config.Server.lookupHostnames = utils.BoolDefaultTrue(config.Server.LookupHostnames)
  801. // process webirc blocks
  802. var newWebIRC []webircConfig
  803. for _, webirc := range config.Server.WebIRC {
  804. // skip webirc blocks with no hosts (such as the example one)
  805. if len(webirc.Hosts) == 0 {
  806. continue
  807. }
  808. err = webirc.Populate()
  809. if err != nil {
  810. return nil, fmt.Errorf("Could not parse WebIRC config: %s", err.Error())
  811. }
  812. newWebIRC = append(newWebIRC, webirc)
  813. }
  814. config.Server.WebIRC = newWebIRC
  815. if config.Limits.Multiline.MaxBytes <= 0 {
  816. config.Server.supportedCaps.Disable(caps.Multiline)
  817. } else {
  818. var multilineCapValue string
  819. if config.Limits.Multiline.MaxLines == 0 {
  820. multilineCapValue = fmt.Sprintf("max-bytes=%d", config.Limits.Multiline.MaxBytes)
  821. } else {
  822. multilineCapValue = fmt.Sprintf("max-bytes=%d,max-lines=%d", config.Limits.Multiline.MaxBytes, config.Limits.Multiline.MaxLines)
  823. }
  824. config.Server.capValues[caps.Multiline] = multilineCapValue
  825. }
  826. // handle legacy name 'bouncer' for 'multiclient' section:
  827. if config.Accounts.Bouncer != nil {
  828. config.Accounts.Multiclient = *config.Accounts.Bouncer
  829. }
  830. if !config.Accounts.Multiclient.Enabled {
  831. config.Accounts.Multiclient.AlwaysOn = PersistentDisabled
  832. } else if config.Accounts.Multiclient.AlwaysOn >= PersistentOptOut {
  833. config.Accounts.Multiclient.AllowedByDefault = true
  834. }
  835. // handle guest format, including the legacy key rename-prefix
  836. if config.Accounts.NickReservation.GuestFormat == "" {
  837. renamePrefix := config.Accounts.NickReservation.RenamePrefix
  838. if renamePrefix == "" {
  839. renamePrefix = "Guest-"
  840. }
  841. config.Accounts.NickReservation.GuestFormat = renamePrefix + "*"
  842. }
  843. config.Accounts.NickReservation.guestRegexp, config.Accounts.NickReservation.guestRegexpFolded, err = compileGuestRegexp(config.Accounts.NickReservation.GuestFormat, config.Server.Casemapping)
  844. if err != nil {
  845. return nil, err
  846. }
  847. var newLogConfigs []logger.LoggingConfig
  848. for _, logConfig := range config.Logging {
  849. // methods
  850. methods := make(map[string]bool)
  851. for _, method := range strings.Split(logConfig.Method, " ") {
  852. if len(method) > 0 {
  853. methods[strings.ToLower(method)] = true
  854. }
  855. }
  856. if methods["file"] && logConfig.Filename == "" {
  857. return nil, ErrLoggerFilenameMissing
  858. }
  859. logConfig.MethodFile = methods["file"]
  860. logConfig.MethodStdout = methods["stdout"]
  861. logConfig.MethodStderr = methods["stderr"]
  862. // levels
  863. level, exists := logger.LogLevelNames[strings.ToLower(logConfig.LevelString)]
  864. if !exists {
  865. return nil, fmt.Errorf("Could not translate log leve [%s]", logConfig.LevelString)
  866. }
  867. logConfig.Level = level
  868. // types
  869. for _, typeStr := range strings.Split(logConfig.TypeString, " ") {
  870. if len(typeStr) == 0 {
  871. continue
  872. }
  873. if typeStr == "-" {
  874. return nil, ErrLoggerExcludeEmpty
  875. }
  876. if typeStr[0] == '-' {
  877. typeStr = typeStr[1:]
  878. logConfig.ExcludedTypes = append(logConfig.ExcludedTypes, typeStr)
  879. } else {
  880. logConfig.Types = append(logConfig.Types, typeStr)
  881. }
  882. }
  883. if len(logConfig.Types) < 1 {
  884. return nil, ErrLoggerHasNoTypes
  885. }
  886. newLogConfigs = append(newLogConfigs, logConfig)
  887. }
  888. config.Logging = newLogConfigs
  889. // hardcode this for now
  890. config.Accounts.Registration.EnabledCredentialTypes = []string{"passphrase", "certfp"}
  891. mailtoEnabled := false
  892. for i, name := range config.Accounts.Registration.EnabledCallbacks {
  893. if name == "none" {
  894. // we store "none" as "*" internally
  895. config.Accounts.Registration.EnabledCallbacks[i] = "*"
  896. } else if name == "mailto" {
  897. mailtoEnabled = true
  898. }
  899. }
  900. sort.Strings(config.Accounts.Registration.EnabledCallbacks)
  901. if mailtoEnabled {
  902. err := config.Accounts.Registration.Callbacks.Mailto.Postprocess(config.Server.Name)
  903. if err != nil {
  904. return nil, err
  905. }
  906. }
  907. config.Accounts.defaultUserModes = ParseDefaultUserModes(config.Accounts.DefaultUserModes)
  908. config.Accounts.RequireSasl.exemptedNets, err = utils.ParseNetList(config.Accounts.RequireSasl.Exempted)
  909. if err != nil {
  910. return nil, fmt.Errorf("Could not parse require-sasl exempted nets: %v", err.Error())
  911. }
  912. config.Server.proxyAllowedFromNets, err = utils.ParseNetList(config.Server.ProxyAllowedFrom)
  913. if err != nil {
  914. return nil, fmt.Errorf("Could not parse proxy-allowed-from nets: %v", err.Error())
  915. }
  916. config.Server.secureNets, err = utils.ParseNetList(config.Server.SecureNetDefs)
  917. if err != nil {
  918. return nil, fmt.Errorf("Could not parse secure-nets: %v\n", err.Error())
  919. }
  920. rawRegexp := config.Accounts.VHosts.ValidRegexpRaw
  921. if rawRegexp != "" {
  922. regexp, err := regexp.Compile(rawRegexp)
  923. if err == nil {
  924. config.Accounts.VHosts.ValidRegexp = regexp
  925. } else {
  926. log.Printf("invalid vhost regexp: %s\n", err.Error())
  927. }
  928. }
  929. if config.Accounts.VHosts.ValidRegexp == nil {
  930. config.Accounts.VHosts.ValidRegexp = defaultValidVhostRegex
  931. }
  932. for _, vhost := range config.Accounts.VHosts.OfferList {
  933. if !config.Accounts.VHosts.ValidRegexp.MatchString(vhost) {
  934. return nil, fmt.Errorf("invalid offered vhost: %s", vhost)
  935. }
  936. }
  937. config.Server.capValues[caps.SASL] = "PLAIN,EXTERNAL"
  938. if !config.Accounts.AuthenticationEnabled {
  939. config.Server.supportedCaps.Disable(caps.SASL)
  940. }
  941. maxSendQBytes, err := bytefmt.ToBytes(config.Server.MaxSendQString)
  942. if err != nil {
  943. return nil, fmt.Errorf("Could not parse maximum SendQ size (make sure it only contains whole numbers): %s", err.Error())
  944. }
  945. config.Server.MaxSendQBytes = int(maxSendQBytes)
  946. config.languageManager, err = languages.NewManager(config.Languages.Enabled, config.Languages.Path, config.Languages.Default)
  947. if err != nil {
  948. return nil, fmt.Errorf("Could not load languages: %s", err.Error())
  949. }
  950. config.Server.capValues[caps.Languages] = config.languageManager.CapValue()
  951. config.Debug.recoverFromErrors = utils.BoolDefaultTrue(config.Debug.RecoverFromErrors)
  952. // process operator definitions, store them to config.operators
  953. operclasses, err := config.OperatorClasses()
  954. if err != nil {
  955. return nil, err
  956. }
  957. opers, err := config.Operators(operclasses)
  958. if err != nil {
  959. return nil, err
  960. }
  961. config.operators = opers
  962. // parse default channel modes
  963. config.Channels.defaultModes = ParseDefaultChannelModes(config.Channels.DefaultModes)
  964. if config.Server.Password != "" {
  965. config.Server.passwordBytes, err = decodeLegacyPasswordHash(config.Server.Password)
  966. if err != nil {
  967. return nil, err
  968. }
  969. }
  970. if config.Accounts.Registration.BcryptCost == 0 {
  971. config.Accounts.Registration.BcryptCost = passwd.DefaultCost
  972. }
  973. if config.Channels.MaxChannelsPerClient == 0 {
  974. config.Channels.MaxChannelsPerClient = 100
  975. }
  976. if config.Channels.Registration.MaxChannelsPerAccount == 0 {
  977. config.Channels.Registration.MaxChannelsPerAccount = 15
  978. }
  979. config.Server.Compatibility.forceTrailing = utils.BoolDefaultTrue(config.Server.Compatibility.ForceTrailing)
  980. config.loadMOTD()
  981. // in the current implementation, we disable history by creating a history buffer
  982. // with zero capacity. but the `enabled` config option MUST be respected regardless
  983. // of this detail
  984. if !config.History.Enabled {
  985. config.History.ChannelLength = 0
  986. config.History.ClientLength = 0
  987. }
  988. if !config.History.Enabled || !config.History.Persistent.Enabled {
  989. config.History.Persistent.UnregisteredChannels = false
  990. config.History.Persistent.RegisteredChannels = PersistentDisabled
  991. config.History.Persistent.DirectMessages = PersistentDisabled
  992. }
  993. if config.History.ZNCMax == 0 {
  994. config.History.ZNCMax = config.History.ChathistoryMax
  995. }
  996. config.Roleplay.enabled = utils.BoolDefaultTrue(config.Roleplay.Enabled)
  997. config.Roleplay.addSuffix = utils.BoolDefaultTrue(config.Roleplay.AddSuffix)
  998. config.Datastore.MySQL.ExpireTime = time.Duration(config.History.Restrictions.ExpireTime)
  999. config.Datastore.MySQL.TrackAccountMessages = config.History.Retention.EnableAccountIndexing
  1000. config.Server.Cloaks.Initialize()
  1001. if config.Server.Cloaks.Enabled {
  1002. if !utils.IsHostname(config.Server.Cloaks.Netname) {
  1003. return nil, fmt.Errorf("Invalid netname for cloaked hostnames: %s", config.Server.Cloaks.Netname)
  1004. }
  1005. }
  1006. // now that all postprocessing is complete, regenerate ISUPPORT:
  1007. err = config.generateISupport()
  1008. if err != nil {
  1009. return nil, err
  1010. }
  1011. err = config.prepareListeners()
  1012. if err != nil {
  1013. return nil, fmt.Errorf("failed to prepare listeners: %v", err)
  1014. }
  1015. return config, nil
  1016. }
  1017. func (config *Config) getOutputPath(filename string) string {
  1018. return filepath.Join(config.Server.OutputPath, filename)
  1019. }
  1020. // setISupport sets up our RPL_ISUPPORT reply.
  1021. func (config *Config) generateISupport() (err error) {
  1022. maxTargetsString := strconv.Itoa(maxTargets)
  1023. // add RPL_ISUPPORT tokens
  1024. isupport := &config.Server.isupport
  1025. isupport.Initialize()
  1026. isupport.Add("AWAYLEN", strconv.Itoa(config.Limits.AwayLen))
  1027. isupport.Add("CASEMAPPING", "ascii")
  1028. isupport.Add("CHANLIMIT", fmt.Sprintf("%s:%d", chanTypes, config.Channels.MaxChannelsPerClient))
  1029. isupport.Add("CHANMODES", strings.Join([]string{modes.Modes{modes.BanMask, modes.ExceptMask, modes.InviteMask}.String(), modes.Modes{modes.Key}.String(), modes.Modes{modes.UserLimit}.String(), modes.Modes{modes.InviteOnly, modes.Moderated, modes.NoOutside, modes.OpOnlyTopic, modes.ChanRoleplaying, modes.Secret, modes.NoCTCP, modes.RegisteredOnly}.String()}, ","))
  1030. if config.History.Enabled && config.History.ChathistoryMax > 0 {
  1031. isupport.Add("draft/CHATHISTORY", strconv.Itoa(config.History.ChathistoryMax))
  1032. }
  1033. isupport.Add("CHANNELLEN", strconv.Itoa(config.Limits.ChannelLen))
  1034. isupport.Add("CHANTYPES", chanTypes)
  1035. isupport.Add("ELIST", "U")
  1036. isupport.Add("EXCEPTS", "")
  1037. isupport.Add("INVEX", "")
  1038. isupport.Add("KICKLEN", strconv.Itoa(config.Limits.KickLen))
  1039. isupport.Add("MAXLIST", fmt.Sprintf("beI:%s", strconv.Itoa(config.Limits.ChanListModes)))
  1040. isupport.Add("MAXTARGETS", maxTargetsString)
  1041. isupport.Add("MODES", "")
  1042. isupport.Add("MONITOR", strconv.Itoa(config.Limits.MonitorEntries))
  1043. isupport.Add("NETWORK", config.Network.Name)
  1044. isupport.Add("NICKLEN", strconv.Itoa(config.Limits.NickLen))
  1045. isupport.Add("PREFIX", "(qaohv)~&@%+")
  1046. if config.Roleplay.enabled {
  1047. isupport.Add("RPCHAN", "E")
  1048. isupport.Add("RPUSER", "E")
  1049. }
  1050. isupport.Add("STATUSMSG", "~&@%+")
  1051. 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))
  1052. isupport.Add("TOPICLEN", strconv.Itoa(config.Limits.TopicLen))
  1053. if config.Server.Casemapping == CasemappingPRECIS {
  1054. isupport.Add("UTF8MAPPING", precisUTF8MappingToken)
  1055. }
  1056. err = isupport.RegenerateCachedReply()
  1057. return
  1058. }
  1059. // Diff returns changes in supported caps across a rehash.
  1060. func (config *Config) Diff(oldConfig *Config) (addedCaps, removedCaps *caps.Set) {
  1061. addedCaps = caps.NewSet()
  1062. removedCaps = caps.NewSet()
  1063. if oldConfig == nil {
  1064. return
  1065. }
  1066. if oldConfig.Server.capValues[caps.Languages] != config.Server.capValues[caps.Languages] {
  1067. // XXX updated caps get a DEL line and then a NEW line with the new value
  1068. addedCaps.Add(caps.Languages)
  1069. removedCaps.Add(caps.Languages)
  1070. }
  1071. if !oldConfig.Accounts.AuthenticationEnabled && config.Accounts.AuthenticationEnabled {
  1072. addedCaps.Add(caps.SASL)
  1073. } else if oldConfig.Accounts.AuthenticationEnabled && !config.Accounts.AuthenticationEnabled {
  1074. removedCaps.Add(caps.SASL)
  1075. }
  1076. if oldConfig.Limits.Multiline.MaxBytes != 0 && config.Limits.Multiline.MaxBytes == 0 {
  1077. removedCaps.Add(caps.Multiline)
  1078. } else if oldConfig.Limits.Multiline.MaxBytes == 0 && config.Limits.Multiline.MaxBytes != 0 {
  1079. addedCaps.Add(caps.Multiline)
  1080. } else if oldConfig.Limits.Multiline != config.Limits.Multiline {
  1081. removedCaps.Add(caps.Multiline)
  1082. addedCaps.Add(caps.Multiline)
  1083. }
  1084. if oldConfig.Server.STS.Enabled != config.Server.STS.Enabled || oldConfig.Server.capValues[caps.STS] != config.Server.capValues[caps.STS] {
  1085. // XXX: STS is always removed by CAP NEW sts=duration=0, not CAP DEL
  1086. // so the appropriate notify is always a CAP NEW; put it in addedCaps for any change
  1087. addedCaps.Add(caps.STS)
  1088. }
  1089. return
  1090. }
  1091. func compileGuestRegexp(guestFormat string, casemapping Casemapping) (standard, folded *regexp.Regexp, err error) {
  1092. if strings.Count(guestFormat, "?") != 0 || strings.Count(guestFormat, "*") != 1 {
  1093. err = errors.New("guest format must contain 1 '*' and no '?'s")
  1094. return
  1095. }
  1096. standard, err = utils.CompileGlob(guestFormat, true)
  1097. if err != nil {
  1098. return
  1099. }
  1100. starIndex := strings.IndexByte(guestFormat, '*')
  1101. initial := guestFormat[:starIndex]
  1102. final := guestFormat[starIndex+1:]
  1103. initialFolded, err := casefoldWithSetting(initial, casemapping)
  1104. if err != nil {
  1105. return
  1106. }
  1107. finalFolded, err := casefoldWithSetting(final, casemapping)
  1108. if err != nil {
  1109. return
  1110. }
  1111. folded, err = utils.CompileGlob(fmt.Sprintf("%s*%s", initialFolded, finalFolded), false)
  1112. return
  1113. }