Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

config.go 38KB

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