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

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