You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

config.go 39KB

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