Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

config.go 38KB

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