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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236
  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) (tlsConfig *tls.Config, err error) {
  672. cert, err := tls.LoadX509KeyPair(config.Cert, config.Key)
  673. if err != nil {
  674. return nil, ErrInvalidCertKeyPair
  675. }
  676. result := tls.Config{
  677. Certificates: []tls.Certificate{cert},
  678. ClientAuth: tls.RequestClientCert,
  679. }
  680. return &result, nil
  681. }
  682. // prepareListeners populates Config.Server.trueListeners
  683. func (conf *Config) prepareListeners() (err error) {
  684. if len(conf.Server.Listeners) == 0 {
  685. return fmt.Errorf("No listeners were configured")
  686. }
  687. conf.Server.trueListeners = make(map[string]utils.ListenerConfig)
  688. for addr, block := range conf.Server.Listeners {
  689. var lconf utils.ListenerConfig
  690. lconf.ProxyDeadline = time.Minute
  691. lconf.Tor = block.Tor
  692. lconf.STSOnly = block.STSOnly
  693. if lconf.STSOnly && !conf.Server.STS.Enabled {
  694. return fmt.Errorf("%s is configured as a STS-only listener, but STS is disabled", addr)
  695. }
  696. if block.TLS.Cert != "" {
  697. tlsConfig, err := loadTlsConfig(block.TLS)
  698. if err != nil {
  699. return err
  700. }
  701. lconf.TLSConfig = tlsConfig
  702. lconf.RequireProxy = block.TLS.Proxy
  703. }
  704. lconf.WebSocket = block.WebSocket
  705. conf.Server.trueListeners[addr] = lconf
  706. }
  707. return nil
  708. }
  709. // LoadRawConfig loads the config without doing any consistency checks or postprocessing
  710. func LoadRawConfig(filename string) (config *Config, err error) {
  711. data, err := ioutil.ReadFile(filename)
  712. if err != nil {
  713. return nil, err
  714. }
  715. err = yaml.Unmarshal(data, &config)
  716. if err != nil {
  717. return nil, err
  718. }
  719. return
  720. }
  721. // LoadConfig loads the given YAML configuration file.
  722. func LoadConfig(filename string) (config *Config, err error) {
  723. config, err = LoadRawConfig(filename)
  724. if err != nil {
  725. return nil, err
  726. }
  727. config.Filename = filename
  728. if config.Network.Name == "" {
  729. return nil, ErrNetworkNameMissing
  730. }
  731. if config.Server.Name == "" {
  732. return nil, ErrServerNameMissing
  733. }
  734. if !utils.IsServerName(config.Server.Name) {
  735. return nil, ErrServerNameNotHostname
  736. }
  737. config.Server.nameCasefolded = strings.ToLower(config.Server.Name)
  738. if config.Datastore.Path == "" {
  739. return nil, ErrDatastorePathMissing
  740. }
  741. //dan: automagically fix identlen until a few releases in the future (from now, 0.12.0), being a newly-introduced limit
  742. if config.Limits.IdentLen < 1 {
  743. config.Limits.IdentLen = 20
  744. }
  745. if config.Limits.NickLen < 1 || config.Limits.ChannelLen < 2 || config.Limits.AwayLen < 1 || config.Limits.KickLen < 1 || config.Limits.TopicLen < 1 {
  746. return nil, ErrLimitsAreInsane
  747. }
  748. if config.Limits.RegistrationMessages == 0 {
  749. config.Limits.RegistrationMessages = 1024
  750. }
  751. if config.Datastore.MySQL.Enabled {
  752. if config.Limits.NickLen > mysql.MaxTargetLength || config.Limits.ChannelLen > mysql.MaxTargetLength {
  753. return nil, fmt.Errorf("to use MySQL, nick and channel length limits must be %d or lower", mysql.MaxTargetLength)
  754. }
  755. }
  756. config.Server.supportedCaps = caps.NewCompleteSet()
  757. config.Server.capValues = make(caps.Values)
  758. err = config.prepareListeners()
  759. if err != nil {
  760. return nil, fmt.Errorf("failed to prepare listeners: %v", err)
  761. }
  762. for _, glob := range config.Server.WebSockets.AllowedOrigins {
  763. globre, err := utils.CompileGlob(glob)
  764. if err != nil {
  765. return nil, fmt.Errorf("invalid websocket allowed-origin expression: %s", glob)
  766. }
  767. config.Server.WebSockets.allowedOriginRegexps = append(config.Server.WebSockets.allowedOriginRegexps, globre)
  768. }
  769. if config.Server.STS.Enabled {
  770. if config.Server.STS.Port < 0 || config.Server.STS.Port > 65535 {
  771. return nil, fmt.Errorf("STS port is incorrect, should be 0 if disabled: %d", config.Server.STS.Port)
  772. }
  773. if config.Server.STS.STSOnlyBanner != "" {
  774. for _, line := range strings.Split(config.Server.STS.STSOnlyBanner, "\n") {
  775. config.Server.STS.bannerLines = append(config.Server.STS.bannerLines, strings.TrimSpace(line))
  776. }
  777. } else {
  778. 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)}
  779. }
  780. } else {
  781. config.Server.supportedCaps.Disable(caps.STS)
  782. config.Server.STS.Duration = 0
  783. }
  784. // set this even if STS is disabled
  785. config.Server.capValues[caps.STS] = config.Server.STS.Value()
  786. config.Server.lookupHostnames = utils.BoolDefaultTrue(config.Server.LookupHostnames)
  787. // process webirc blocks
  788. var newWebIRC []webircConfig
  789. for _, webirc := range config.Server.WebIRC {
  790. // skip webirc blocks with no hosts (such as the example one)
  791. if len(webirc.Hosts) == 0 {
  792. continue
  793. }
  794. err = webirc.Populate()
  795. if err != nil {
  796. return nil, fmt.Errorf("Could not parse WebIRC config: %s", err.Error())
  797. }
  798. newWebIRC = append(newWebIRC, webirc)
  799. }
  800. config.Server.WebIRC = newWebIRC
  801. if config.Limits.Multiline.MaxBytes <= 0 {
  802. config.Server.supportedCaps.Disable(caps.Multiline)
  803. } else {
  804. var multilineCapValue string
  805. if config.Limits.Multiline.MaxLines == 0 {
  806. multilineCapValue = fmt.Sprintf("max-bytes=%d", config.Limits.Multiline.MaxBytes)
  807. } else {
  808. multilineCapValue = fmt.Sprintf("max-bytes=%d,max-lines=%d", config.Limits.Multiline.MaxBytes, config.Limits.Multiline.MaxLines)
  809. }
  810. config.Server.capValues[caps.Multiline] = multilineCapValue
  811. }
  812. // handle legacy name 'bouncer' for 'multiclient' section:
  813. if config.Accounts.Bouncer != nil {
  814. config.Accounts.Multiclient = *config.Accounts.Bouncer
  815. }
  816. if !config.Accounts.Multiclient.Enabled {
  817. config.Accounts.Multiclient.AlwaysOn = PersistentDisabled
  818. } else if config.Accounts.Multiclient.AlwaysOn >= PersistentOptOut {
  819. config.Accounts.Multiclient.AllowedByDefault = true
  820. }
  821. // handle guest format, including the legacy key rename-prefix
  822. if config.Accounts.NickReservation.GuestFormat == "" {
  823. renamePrefix := config.Accounts.NickReservation.RenamePrefix
  824. if renamePrefix == "" {
  825. renamePrefix = "Guest-"
  826. }
  827. config.Accounts.NickReservation.GuestFormat = renamePrefix + "*"
  828. }
  829. config.Accounts.NickReservation.guestRegexp, config.Accounts.NickReservation.guestRegexpFolded, err = compileGuestRegexp(config.Accounts.NickReservation.GuestFormat, config.Server.Casemapping)
  830. if err != nil {
  831. return nil, err
  832. }
  833. var newLogConfigs []logger.LoggingConfig
  834. for _, logConfig := range config.Logging {
  835. // methods
  836. methods := make(map[string]bool)
  837. for _, method := range strings.Split(logConfig.Method, " ") {
  838. if len(method) > 0 {
  839. methods[strings.ToLower(method)] = true
  840. }
  841. }
  842. if methods["file"] && logConfig.Filename == "" {
  843. return nil, ErrLoggerFilenameMissing
  844. }
  845. logConfig.MethodFile = methods["file"]
  846. logConfig.MethodStdout = methods["stdout"]
  847. logConfig.MethodStderr = methods["stderr"]
  848. // levels
  849. level, exists := logger.LogLevelNames[strings.ToLower(logConfig.LevelString)]
  850. if !exists {
  851. return nil, fmt.Errorf("Could not translate log leve [%s]", logConfig.LevelString)
  852. }
  853. logConfig.Level = level
  854. // types
  855. for _, typeStr := range strings.Split(logConfig.TypeString, " ") {
  856. if len(typeStr) == 0 {
  857. continue
  858. }
  859. if typeStr == "-" {
  860. return nil, ErrLoggerExcludeEmpty
  861. }
  862. if typeStr[0] == '-' {
  863. typeStr = typeStr[1:]
  864. logConfig.ExcludedTypes = append(logConfig.ExcludedTypes, typeStr)
  865. } else {
  866. logConfig.Types = append(logConfig.Types, typeStr)
  867. }
  868. }
  869. if len(logConfig.Types) < 1 {
  870. return nil, ErrLoggerHasNoTypes
  871. }
  872. newLogConfigs = append(newLogConfigs, logConfig)
  873. }
  874. config.Logging = newLogConfigs
  875. // hardcode this for now
  876. config.Accounts.Registration.EnabledCredentialTypes = []string{"passphrase", "certfp"}
  877. mailtoEnabled := false
  878. for i, name := range config.Accounts.Registration.EnabledCallbacks {
  879. if name == "none" {
  880. // we store "none" as "*" internally
  881. config.Accounts.Registration.EnabledCallbacks[i] = "*"
  882. } else if name == "mailto" {
  883. mailtoEnabled = true
  884. }
  885. }
  886. sort.Strings(config.Accounts.Registration.EnabledCallbacks)
  887. if mailtoEnabled {
  888. err := config.Accounts.Registration.Callbacks.Mailto.Postprocess(config.Server.Name)
  889. if err != nil {
  890. return nil, err
  891. }
  892. }
  893. config.Accounts.defaultUserModes = ParseDefaultUserModes(config.Accounts.DefaultUserModes)
  894. config.Accounts.RequireSasl.exemptedNets, err = utils.ParseNetList(config.Accounts.RequireSasl.Exempted)
  895. if err != nil {
  896. return nil, fmt.Errorf("Could not parse require-sasl exempted nets: %v", err.Error())
  897. }
  898. config.Server.proxyAllowedFromNets, err = utils.ParseNetList(config.Server.ProxyAllowedFrom)
  899. if err != nil {
  900. return nil, fmt.Errorf("Could not parse proxy-allowed-from nets: %v", err.Error())
  901. }
  902. config.Server.secureNets, err = utils.ParseNetList(config.Server.SecureNetDefs)
  903. if err != nil {
  904. return nil, fmt.Errorf("Could not parse secure-nets: %v\n", err.Error())
  905. }
  906. rawRegexp := config.Accounts.VHosts.ValidRegexpRaw
  907. if rawRegexp != "" {
  908. regexp, err := regexp.Compile(rawRegexp)
  909. if err == nil {
  910. config.Accounts.VHosts.ValidRegexp = regexp
  911. } else {
  912. log.Printf("invalid vhost regexp: %s\n", err.Error())
  913. }
  914. }
  915. if config.Accounts.VHosts.ValidRegexp == nil {
  916. config.Accounts.VHosts.ValidRegexp = defaultValidVhostRegex
  917. }
  918. for _, vhost := range config.Accounts.VHosts.OfferList {
  919. if !config.Accounts.VHosts.ValidRegexp.MatchString(vhost) {
  920. return nil, fmt.Errorf("invalid offered vhost: %s", vhost)
  921. }
  922. }
  923. config.Server.capValues[caps.SASL] = "PLAIN,EXTERNAL"
  924. if !config.Accounts.AuthenticationEnabled {
  925. config.Server.supportedCaps.Disable(caps.SASL)
  926. }
  927. maxSendQBytes, err := bytefmt.ToBytes(config.Server.MaxSendQString)
  928. if err != nil {
  929. return nil, fmt.Errorf("Could not parse maximum SendQ size (make sure it only contains whole numbers): %s", err.Error())
  930. }
  931. config.Server.MaxSendQBytes = int(maxSendQBytes)
  932. config.languageManager, err = languages.NewManager(config.Languages.Enabled, config.Languages.Path, config.Languages.Default)
  933. if err != nil {
  934. return nil, fmt.Errorf("Could not load languages: %s", err.Error())
  935. }
  936. config.Server.capValues[caps.Languages] = config.languageManager.CapValue()
  937. config.Debug.recoverFromErrors = utils.BoolDefaultTrue(config.Debug.RecoverFromErrors)
  938. // process operator definitions, store them to config.operators
  939. operclasses, err := config.OperatorClasses()
  940. if err != nil {
  941. return nil, err
  942. }
  943. opers, err := config.Operators(operclasses)
  944. if err != nil {
  945. return nil, err
  946. }
  947. config.operators = opers
  948. // parse default channel modes
  949. config.Channels.defaultModes = ParseDefaultChannelModes(config.Channels.DefaultModes)
  950. if config.Server.Password != "" {
  951. config.Server.passwordBytes, err = decodeLegacyPasswordHash(config.Server.Password)
  952. if err != nil {
  953. return nil, err
  954. }
  955. }
  956. if config.Accounts.Registration.BcryptCost == 0 {
  957. config.Accounts.Registration.BcryptCost = passwd.DefaultCost
  958. }
  959. if config.Channels.MaxChannelsPerClient == 0 {
  960. config.Channels.MaxChannelsPerClient = 100
  961. }
  962. if config.Channels.Registration.MaxChannelsPerAccount == 0 {
  963. config.Channels.Registration.MaxChannelsPerAccount = 15
  964. }
  965. config.Server.Compatibility.forceTrailing = utils.BoolDefaultTrue(config.Server.Compatibility.ForceTrailing)
  966. config.loadMOTD()
  967. // in the current implementation, we disable history by creating a history buffer
  968. // with zero capacity. but the `enabled` config option MUST be respected regardless
  969. // of this detail
  970. if !config.History.Enabled {
  971. config.History.ChannelLength = 0
  972. config.History.ClientLength = 0
  973. }
  974. if !config.History.Enabled || !config.History.Persistent.Enabled {
  975. config.History.Persistent.UnregisteredChannels = false
  976. config.History.Persistent.RegisteredChannels = PersistentDisabled
  977. config.History.Persistent.DirectMessages = PersistentDisabled
  978. }
  979. if config.History.ZNCMax == 0 {
  980. config.History.ZNCMax = config.History.ChathistoryMax
  981. }
  982. config.Roleplay.enabled = utils.BoolDefaultTrue(config.Roleplay.Enabled)
  983. config.Roleplay.addSuffix = utils.BoolDefaultTrue(config.Roleplay.AddSuffix)
  984. config.Datastore.MySQL.ExpireTime = time.Duration(config.History.Restrictions.ExpireTime)
  985. config.Server.Cloaks.Initialize()
  986. if config.Server.Cloaks.Enabled {
  987. if config.Server.Cloaks.Secret == "" || config.Server.Cloaks.Secret == "siaELnk6Kaeo65K3RCrwJjlWaZ-Bt3WuZ2L8MXLbNb4" {
  988. return nil, fmt.Errorf("You must generate a new value of server.ip-cloaking.secret to enable cloaking")
  989. }
  990. if !utils.IsHostname(config.Server.Cloaks.Netname) {
  991. return nil, fmt.Errorf("Invalid netname for cloaked hostnames: %s", config.Server.Cloaks.Netname)
  992. }
  993. }
  994. // now that all postprocessing is complete, regenerate ISUPPORT:
  995. err = config.generateISupport()
  996. if err != nil {
  997. return nil, err
  998. }
  999. err = config.prepareListeners()
  1000. if err != nil {
  1001. return nil, fmt.Errorf("failed to prepare listeners: %v", err)
  1002. }
  1003. return config, nil
  1004. }
  1005. // setISupport sets up our RPL_ISUPPORT reply.
  1006. func (config *Config) generateISupport() (err error) {
  1007. maxTargetsString := strconv.Itoa(maxTargets)
  1008. // add RPL_ISUPPORT tokens
  1009. isupport := &config.Server.isupport
  1010. isupport.Initialize()
  1011. isupport.Add("AWAYLEN", strconv.Itoa(config.Limits.AwayLen))
  1012. isupport.Add("CASEMAPPING", "ascii")
  1013. isupport.Add("CHANLIMIT", fmt.Sprintf("%s:%d", chanTypes, config.Channels.MaxChannelsPerClient))
  1014. 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()}, ","))
  1015. if config.History.Enabled && config.History.ChathistoryMax > 0 {
  1016. isupport.Add("draft/CHATHISTORY", strconv.Itoa(config.History.ChathistoryMax))
  1017. }
  1018. isupport.Add("CHANNELLEN", strconv.Itoa(config.Limits.ChannelLen))
  1019. isupport.Add("CHANTYPES", chanTypes)
  1020. isupport.Add("ELIST", "U")
  1021. isupport.Add("EXCEPTS", "")
  1022. isupport.Add("INVEX", "")
  1023. isupport.Add("KICKLEN", strconv.Itoa(config.Limits.KickLen))
  1024. isupport.Add("MAXLIST", fmt.Sprintf("beI:%s", strconv.Itoa(config.Limits.ChanListModes)))
  1025. isupport.Add("MAXTARGETS", maxTargetsString)
  1026. isupport.Add("MODES", "")
  1027. isupport.Add("MONITOR", strconv.Itoa(config.Limits.MonitorEntries))
  1028. isupport.Add("NETWORK", config.Network.Name)
  1029. isupport.Add("NICKLEN", strconv.Itoa(config.Limits.NickLen))
  1030. isupport.Add("PREFIX", "(qaohv)~&@%+")
  1031. if config.Roleplay.enabled {
  1032. isupport.Add("RPCHAN", "E")
  1033. isupport.Add("RPUSER", "E")
  1034. }
  1035. isupport.Add("STATUSMSG", "~&@%+")
  1036. 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))
  1037. isupport.Add("TOPICLEN", strconv.Itoa(config.Limits.TopicLen))
  1038. if config.Server.Casemapping == CasemappingPRECIS {
  1039. isupport.Add("UTF8MAPPING", precisUTF8MappingToken)
  1040. }
  1041. err = isupport.RegenerateCachedReply()
  1042. return
  1043. }
  1044. // Diff returns changes in supported caps across a rehash.
  1045. func (config *Config) Diff(oldConfig *Config) (addedCaps, removedCaps *caps.Set) {
  1046. addedCaps = caps.NewSet()
  1047. removedCaps = caps.NewSet()
  1048. if oldConfig == nil {
  1049. return
  1050. }
  1051. if oldConfig.Server.capValues[caps.Languages] != config.Server.capValues[caps.Languages] {
  1052. // XXX updated caps get a DEL line and then a NEW line with the new value
  1053. addedCaps.Add(caps.Languages)
  1054. removedCaps.Add(caps.Languages)
  1055. }
  1056. if !oldConfig.Accounts.AuthenticationEnabled && config.Accounts.AuthenticationEnabled {
  1057. addedCaps.Add(caps.SASL)
  1058. } else if oldConfig.Accounts.AuthenticationEnabled && !config.Accounts.AuthenticationEnabled {
  1059. removedCaps.Add(caps.SASL)
  1060. }
  1061. if oldConfig.Limits.Multiline.MaxBytes != 0 && config.Limits.Multiline.MaxBytes == 0 {
  1062. removedCaps.Add(caps.Multiline)
  1063. } else if oldConfig.Limits.Multiline.MaxBytes == 0 && config.Limits.Multiline.MaxBytes != 0 {
  1064. addedCaps.Add(caps.Multiline)
  1065. } else if oldConfig.Limits.Multiline != config.Limits.Multiline {
  1066. removedCaps.Add(caps.Multiline)
  1067. addedCaps.Add(caps.Multiline)
  1068. }
  1069. if oldConfig.Server.STS.Enabled != config.Server.STS.Enabled || oldConfig.Server.capValues[caps.STS] != config.Server.capValues[caps.STS] {
  1070. // XXX: STS is always removed by CAP NEW sts=duration=0, not CAP DEL
  1071. // so the appropriate notify is always a CAP NEW; put it in addedCaps for any change
  1072. addedCaps.Add(caps.STS)
  1073. }
  1074. return
  1075. }
  1076. func compileGuestRegexp(guestFormat string, casemapping Casemapping) (standard, folded *regexp.Regexp, err error) {
  1077. standard, err = utils.CompileGlob(guestFormat)
  1078. if err != nil {
  1079. return
  1080. }
  1081. starIndex := strings.IndexByte(guestFormat, '*')
  1082. if starIndex == -1 {
  1083. return nil, nil, errors.New("guest format must contain exactly one *")
  1084. }
  1085. initial := guestFormat[:starIndex]
  1086. final := guestFormat[starIndex+1:]
  1087. if strings.IndexByte(final, '*') != -1 {
  1088. return nil, nil, errors.New("guest format must contain exactly one *")
  1089. }
  1090. initialFolded, err := casefoldWithSetting(initial, casemapping)
  1091. if err != nil {
  1092. return
  1093. }
  1094. finalFolded, err := casefoldWithSetting(final, casemapping)
  1095. if err != nil {
  1096. return
  1097. }
  1098. folded, err = utils.CompileGlob(fmt.Sprintf("%s*%s", initialFolded, finalFolded))
  1099. return
  1100. }