您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

config.go 38KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266
  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("BOT", "B")
  1040. isupport.Add("CASEMAPPING", "ascii")
  1041. isupport.Add("CHANLIMIT", fmt.Sprintf("%s:%d", chanTypes, config.Channels.MaxChannelsPerClient))
  1042. 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()}, ","))
  1043. if config.History.Enabled && config.History.ChathistoryMax > 0 {
  1044. isupport.Add("draft/CHATHISTORY", strconv.Itoa(config.History.ChathistoryMax))
  1045. }
  1046. isupport.Add("CHANNELLEN", strconv.Itoa(config.Limits.ChannelLen))
  1047. isupport.Add("CHANTYPES", chanTypes)
  1048. isupport.Add("ELIST", "U")
  1049. isupport.Add("EXCEPTS", "")
  1050. isupport.Add("INVEX", "")
  1051. isupport.Add("KICKLEN", strconv.Itoa(config.Limits.KickLen))
  1052. isupport.Add("MAXLIST", fmt.Sprintf("beI:%s", strconv.Itoa(config.Limits.ChanListModes)))
  1053. isupport.Add("MAXTARGETS", maxTargetsString)
  1054. isupport.Add("MODES", "")
  1055. isupport.Add("MONITOR", strconv.Itoa(config.Limits.MonitorEntries))
  1056. isupport.Add("NETWORK", config.Network.Name)
  1057. isupport.Add("NICKLEN", strconv.Itoa(config.Limits.NickLen))
  1058. isupport.Add("PREFIX", "(qaohv)~&@%+")
  1059. if config.Roleplay.enabled {
  1060. isupport.Add("RPCHAN", "E")
  1061. isupport.Add("RPUSER", "E")
  1062. }
  1063. isupport.Add("STATUSMSG", "~&@%+")
  1064. 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))
  1065. isupport.Add("TOPICLEN", strconv.Itoa(config.Limits.TopicLen))
  1066. if config.Server.Casemapping == CasemappingPRECIS {
  1067. isupport.Add("UTF8MAPPING", precisUTF8MappingToken)
  1068. }
  1069. err = isupport.RegenerateCachedReply()
  1070. return
  1071. }
  1072. // Diff returns changes in supported caps across a rehash.
  1073. func (config *Config) Diff(oldConfig *Config) (addedCaps, removedCaps *caps.Set) {
  1074. addedCaps = caps.NewSet()
  1075. removedCaps = caps.NewSet()
  1076. if oldConfig == nil {
  1077. return
  1078. }
  1079. if oldConfig.Server.capValues[caps.Languages] != config.Server.capValues[caps.Languages] {
  1080. // XXX updated caps get a DEL line and then a NEW line with the new value
  1081. addedCaps.Add(caps.Languages)
  1082. removedCaps.Add(caps.Languages)
  1083. }
  1084. if !oldConfig.Accounts.AuthenticationEnabled && config.Accounts.AuthenticationEnabled {
  1085. addedCaps.Add(caps.SASL)
  1086. } else if oldConfig.Accounts.AuthenticationEnabled && !config.Accounts.AuthenticationEnabled {
  1087. removedCaps.Add(caps.SASL)
  1088. }
  1089. if oldConfig.Limits.Multiline.MaxBytes != 0 && config.Limits.Multiline.MaxBytes == 0 {
  1090. removedCaps.Add(caps.Multiline)
  1091. } else if oldConfig.Limits.Multiline.MaxBytes == 0 && config.Limits.Multiline.MaxBytes != 0 {
  1092. addedCaps.Add(caps.Multiline)
  1093. } else if oldConfig.Limits.Multiline != config.Limits.Multiline {
  1094. removedCaps.Add(caps.Multiline)
  1095. addedCaps.Add(caps.Multiline)
  1096. }
  1097. if oldConfig.Server.STS.Enabled != config.Server.STS.Enabled || oldConfig.Server.capValues[caps.STS] != config.Server.capValues[caps.STS] {
  1098. // XXX: STS is always removed by CAP NEW sts=duration=0, not CAP DEL
  1099. // so the appropriate notify is always a CAP NEW; put it in addedCaps for any change
  1100. addedCaps.Add(caps.STS)
  1101. }
  1102. return
  1103. }
  1104. func compileGuestRegexp(guestFormat string, casemapping Casemapping) (standard, folded *regexp.Regexp, err error) {
  1105. if strings.Count(guestFormat, "?") != 0 || strings.Count(guestFormat, "*") != 1 {
  1106. err = errors.New("guest format must contain 1 '*' and no '?'s")
  1107. return
  1108. }
  1109. standard, err = utils.CompileGlob(guestFormat, true)
  1110. if err != nil {
  1111. return
  1112. }
  1113. starIndex := strings.IndexByte(guestFormat, '*')
  1114. initial := guestFormat[:starIndex]
  1115. final := guestFormat[starIndex+1:]
  1116. initialFolded, err := casefoldWithSetting(initial, casemapping)
  1117. if err != nil {
  1118. return
  1119. }
  1120. finalFolded, err := casefoldWithSetting(final, casemapping)
  1121. if err != nil {
  1122. return
  1123. }
  1124. folded, err = utils.CompileGlob(fmt.Sprintf("%s*%s", initialFolded, finalFolded), false)
  1125. return
  1126. }