Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

config.go 38KB

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