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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303
  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/jwt"
  28. "github.com/oragono/oragono/irc/languages"
  29. "github.com/oragono/oragono/irc/ldap"
  30. "github.com/oragono/oragono/irc/logger"
  31. "github.com/oragono/oragono/irc/modes"
  32. "github.com/oragono/oragono/irc/mysql"
  33. "github.com/oragono/oragono/irc/passwd"
  34. "github.com/oragono/oragono/irc/utils"
  35. "gopkg.in/yaml.v2"
  36. )
  37. // here's how this works: exported (capitalized) members of the config structs
  38. // are defined in the YAML file and deserialized directly from there. They may
  39. // be postprocessed and overwritten by LoadConfig. Unexported (lowercase) members
  40. // are derived from the exported members in LoadConfig.
  41. // TLSListenConfig defines configuration options for listening on TLS.
  42. type TLSListenConfig struct {
  43. Cert string
  44. Key string
  45. Proxy bool
  46. }
  47. // This is the YAML-deserializable type of the value of the `Server.Listeners` map
  48. type listenerConfigBlock struct {
  49. TLS TLSListenConfig
  50. Tor bool
  51. STSOnly bool `yaml:"sts-only"`
  52. WebSocket bool
  53. }
  54. type PersistentStatus uint
  55. const (
  56. PersistentUnspecified PersistentStatus = iota
  57. PersistentDisabled
  58. PersistentOptIn
  59. PersistentOptOut
  60. PersistentMandatory
  61. )
  62. func persistentStatusToString(status PersistentStatus) string {
  63. switch status {
  64. case PersistentUnspecified:
  65. return "default"
  66. case PersistentDisabled:
  67. return "disabled"
  68. case PersistentOptIn:
  69. return "opt-in"
  70. case PersistentOptOut:
  71. return "opt-out"
  72. case PersistentMandatory:
  73. return "mandatory"
  74. default:
  75. return ""
  76. }
  77. }
  78. func persistentStatusFromString(status string) (PersistentStatus, error) {
  79. switch strings.ToLower(status) {
  80. case "default":
  81. return PersistentUnspecified, nil
  82. case "":
  83. return PersistentDisabled, nil
  84. case "opt-in":
  85. return PersistentOptIn, nil
  86. case "opt-out":
  87. return PersistentOptOut, nil
  88. case "mandatory":
  89. return PersistentMandatory, nil
  90. default:
  91. b, err := utils.StringToBool(status)
  92. if b {
  93. return PersistentMandatory, err
  94. } else {
  95. return PersistentDisabled, err
  96. }
  97. }
  98. }
  99. func (ps *PersistentStatus) UnmarshalYAML(unmarshal func(interface{}) error) error {
  100. var orig string
  101. var err error
  102. if err = unmarshal(&orig); err != nil {
  103. return err
  104. }
  105. result, err := persistentStatusFromString(orig)
  106. if err == nil {
  107. if result == PersistentUnspecified {
  108. result = PersistentDisabled
  109. }
  110. *ps = result
  111. }
  112. return err
  113. }
  114. func persistenceEnabled(serverSetting, clientSetting PersistentStatus) (enabled bool) {
  115. if serverSetting == PersistentDisabled {
  116. return false
  117. } else if serverSetting == PersistentMandatory {
  118. return true
  119. } else if clientSetting == PersistentDisabled {
  120. return false
  121. } else if clientSetting == PersistentMandatory {
  122. return true
  123. } else if serverSetting == PersistentOptOut {
  124. return true
  125. } else {
  126. return false
  127. }
  128. }
  129. type HistoryStatus uint
  130. const (
  131. HistoryDefault HistoryStatus = iota
  132. HistoryDisabled
  133. HistoryEphemeral
  134. HistoryPersistent
  135. )
  136. func historyStatusFromString(str string) (status HistoryStatus, err error) {
  137. switch strings.ToLower(str) {
  138. case "default":
  139. return HistoryDefault, nil
  140. case "ephemeral":
  141. return HistoryEphemeral, nil
  142. case "persistent":
  143. return HistoryPersistent, nil
  144. default:
  145. b, err := utils.StringToBool(str)
  146. if b {
  147. return HistoryPersistent, err
  148. } else {
  149. return HistoryDisabled, err
  150. }
  151. }
  152. }
  153. func historyStatusToString(status HistoryStatus) string {
  154. switch status {
  155. case HistoryDefault:
  156. return "default"
  157. case HistoryDisabled:
  158. return "disabled"
  159. case HistoryEphemeral:
  160. return "ephemeral"
  161. case HistoryPersistent:
  162. return "persistent"
  163. default:
  164. return ""
  165. }
  166. }
  167. // XXX you must have already checked History.Enabled before calling this
  168. func historyEnabled(serverSetting PersistentStatus, localSetting HistoryStatus) (result HistoryStatus) {
  169. switch serverSetting {
  170. case PersistentMandatory:
  171. return HistoryPersistent
  172. case PersistentOptOut:
  173. if localSetting == HistoryDefault {
  174. return HistoryPersistent
  175. } else {
  176. return localSetting
  177. }
  178. case PersistentOptIn:
  179. switch localSetting {
  180. case HistoryPersistent:
  181. return HistoryPersistent
  182. case HistoryEphemeral, HistoryDefault:
  183. return HistoryEphemeral
  184. default:
  185. return HistoryDisabled
  186. }
  187. case PersistentDisabled:
  188. if localSetting == HistoryDisabled {
  189. return HistoryDisabled
  190. } else {
  191. return HistoryEphemeral
  192. }
  193. default:
  194. // PersistentUnspecified: shouldn't happen because the deserializer converts it
  195. // to PersistentDisabled
  196. if localSetting == HistoryDefault {
  197. return HistoryEphemeral
  198. } else {
  199. return localSetting
  200. }
  201. }
  202. }
  203. type MulticlientConfig struct {
  204. Enabled bool
  205. AllowedByDefault bool `yaml:"allowed-by-default"`
  206. AlwaysOn PersistentStatus `yaml:"always-on"`
  207. AutoAway PersistentStatus `yaml:"auto-away"`
  208. }
  209. type throttleConfig struct {
  210. Enabled bool
  211. Duration time.Duration
  212. MaxAttempts int `yaml:"max-attempts"`
  213. }
  214. type ThrottleConfig struct {
  215. throttleConfig
  216. }
  217. func (t *ThrottleConfig) UnmarshalYAML(unmarshal func(interface{}) error) (err error) {
  218. // note that this technique only works if the zero value of the struct
  219. // doesn't need any postprocessing (because if the field is omitted entirely
  220. // from the YAML, then UnmarshalYAML won't be called at all)
  221. if err = unmarshal(&t.throttleConfig); err != nil {
  222. return
  223. }
  224. if !t.Enabled {
  225. t.MaxAttempts = 0 // limit of 0 means disabled
  226. }
  227. return
  228. }
  229. type AccountConfig struct {
  230. Registration AccountRegistrationConfig
  231. AuthenticationEnabled bool `yaml:"authentication-enabled"`
  232. RequireSasl struct {
  233. Enabled bool
  234. Exempted []string
  235. exemptedNets []net.IPNet
  236. } `yaml:"require-sasl"`
  237. DefaultUserModes *string `yaml:"default-user-modes"`
  238. defaultUserModes modes.Modes
  239. LDAP ldap.ServerConfig
  240. LoginThrottling ThrottleConfig `yaml:"login-throttling"`
  241. SkipServerPassword bool `yaml:"skip-server-password"`
  242. LoginViaPassCommand bool `yaml:"login-via-pass-command"`
  243. NickReservation struct {
  244. Enabled bool
  245. AdditionalNickLimit int `yaml:"additional-nick-limit"`
  246. Method NickEnforcementMethod
  247. AllowCustomEnforcement bool `yaml:"allow-custom-enforcement"`
  248. RenameTimeout time.Duration `yaml:"rename-timeout"`
  249. // RenamePrefix is the legacy field, GuestFormat is the new version
  250. RenamePrefix string `yaml:"rename-prefix"`
  251. GuestFormat string `yaml:"guest-nickname-format"`
  252. guestRegexp *regexp.Regexp
  253. guestRegexpFolded *regexp.Regexp
  254. ForceGuestFormat bool `yaml:"force-guest-format"`
  255. ForceNickEqualsAccount bool `yaml:"force-nick-equals-account"`
  256. } `yaml:"nick-reservation"`
  257. Multiclient MulticlientConfig
  258. Bouncer *MulticlientConfig // # handle old name for 'multiclient'
  259. VHosts VHostConfig
  260. AuthScript AuthScriptConfig `yaml:"auth-script"`
  261. }
  262. type AuthScriptConfig struct {
  263. Enabled bool
  264. Command string
  265. Args []string
  266. Autocreate bool
  267. Timeout time.Duration
  268. KillTimeout time.Duration `yaml:"kill-timeout"`
  269. }
  270. // AccountRegistrationConfig controls account registration.
  271. type AccountRegistrationConfig struct {
  272. Enabled bool
  273. Throttling ThrottleConfig
  274. EnabledCallbacks []string `yaml:"enabled-callbacks"`
  275. EnabledCredentialTypes []string `yaml:"-"`
  276. VerifyTimeout custime.Duration `yaml:"verify-timeout"`
  277. Callbacks struct {
  278. Mailto email.MailtoConfig
  279. }
  280. BcryptCost uint `yaml:"bcrypt-cost"`
  281. }
  282. type VHostConfig struct {
  283. Enabled bool
  284. MaxLength int `yaml:"max-length"`
  285. ValidRegexpRaw string `yaml:"valid-regexp"`
  286. ValidRegexp *regexp.Regexp
  287. UserRequests struct {
  288. Enabled bool
  289. Channel string
  290. Cooldown custime.Duration
  291. } `yaml:"user-requests"`
  292. OfferList []string `yaml:"offer-list"`
  293. }
  294. type NickEnforcementMethod int
  295. const (
  296. // NickEnforcementOptional is the zero value; it serializes to
  297. // "optional" in the yaml config, and "default" as an arg to `NS ENFORCE`.
  298. // in both cases, it means "defer to the other source of truth", i.e.,
  299. // in the config, defer to the user's custom setting, and as a custom setting,
  300. // defer to the default in the config. if both are NickEnforcementOptional then
  301. // there is no enforcement.
  302. // XXX: these are serialized as numbers in the database, so beware of collisions
  303. // when refactoring (any numbers currently in use must keep their meanings, or
  304. // else be fixed up by a schema change)
  305. NickEnforcementOptional NickEnforcementMethod = iota
  306. NickEnforcementNone
  307. NickEnforcementStrict
  308. )
  309. func nickReservationToString(method NickEnforcementMethod) string {
  310. switch method {
  311. case NickEnforcementOptional:
  312. return "default"
  313. case NickEnforcementNone:
  314. return "none"
  315. case NickEnforcementStrict:
  316. return "strict"
  317. default:
  318. return ""
  319. }
  320. }
  321. func nickReservationFromString(method string) (NickEnforcementMethod, error) {
  322. switch strings.ToLower(method) {
  323. case "default":
  324. return NickEnforcementOptional, nil
  325. case "optional":
  326. return NickEnforcementOptional, nil
  327. case "none":
  328. return NickEnforcementNone, nil
  329. case "strict":
  330. return NickEnforcementStrict, nil
  331. default:
  332. return NickEnforcementOptional, fmt.Errorf("invalid nick-reservation.method value: %s", method)
  333. }
  334. }
  335. func (nr *NickEnforcementMethod) UnmarshalYAML(unmarshal func(interface{}) error) error {
  336. var orig string
  337. var err error
  338. if err = unmarshal(&orig); err != nil {
  339. return err
  340. }
  341. method, err := nickReservationFromString(orig)
  342. if err == nil {
  343. *nr = method
  344. }
  345. return err
  346. }
  347. func (cm *Casemapping) UnmarshalYAML(unmarshal func(interface{}) error) (err error) {
  348. var orig string
  349. if err = unmarshal(&orig); err != nil {
  350. return err
  351. }
  352. var result Casemapping
  353. switch strings.ToLower(orig) {
  354. case "ascii":
  355. result = CasemappingASCII
  356. case "precis", "rfc7613", "rfc8265":
  357. result = CasemappingPRECIS
  358. case "permissive", "fun":
  359. result = CasemappingPermissive
  360. default:
  361. return fmt.Errorf("invalid casemapping value: %s", orig)
  362. }
  363. *cm = result
  364. return nil
  365. }
  366. // OperClassConfig defines a specific operator class.
  367. type OperClassConfig struct {
  368. Title string
  369. WhoisLine string
  370. Extends string
  371. Capabilities []string
  372. }
  373. // OperConfig defines a specific operator's configuration.
  374. type OperConfig struct {
  375. Class string
  376. Vhost string
  377. WhoisLine string `yaml:"whois-line"`
  378. Password string
  379. Fingerprint string
  380. Auto bool
  381. Modes string
  382. }
  383. // Various server-enforced limits on data size.
  384. type Limits struct {
  385. AwayLen int `yaml:"awaylen"`
  386. ChanListModes int `yaml:"chan-list-modes"`
  387. ChannelLen int `yaml:"channellen"`
  388. IdentLen int `yaml:"identlen"`
  389. KickLen int `yaml:"kicklen"`
  390. MonitorEntries int `yaml:"monitor-entries"`
  391. NickLen int `yaml:"nicklen"`
  392. TopicLen int `yaml:"topiclen"`
  393. WhowasEntries int `yaml:"whowas-entries"`
  394. RegistrationMessages int `yaml:"registration-messages"`
  395. Multiline struct {
  396. MaxBytes int `yaml:"max-bytes"`
  397. MaxLines int `yaml:"max-lines"`
  398. }
  399. }
  400. // STSConfig controls the STS configuration/
  401. type STSConfig struct {
  402. Enabled bool
  403. Duration custime.Duration
  404. Port int
  405. Preload bool
  406. STSOnlyBanner string `yaml:"sts-only-banner"`
  407. bannerLines []string
  408. }
  409. // Value returns the STS value to advertise in CAP
  410. func (sts *STSConfig) Value() string {
  411. val := fmt.Sprintf("duration=%d", int(time.Duration(sts.Duration).Seconds()))
  412. if sts.Enabled && sts.Port > 0 {
  413. val += fmt.Sprintf(",port=%d", sts.Port)
  414. }
  415. if sts.Enabled && sts.Preload {
  416. val += ",preload"
  417. }
  418. return val
  419. }
  420. type FakelagConfig struct {
  421. Enabled bool
  422. Window time.Duration
  423. BurstLimit uint `yaml:"burst-limit"`
  424. MessagesPerWindow uint `yaml:"messages-per-window"`
  425. Cooldown time.Duration
  426. }
  427. type TorListenersConfig struct {
  428. Listeners []string // legacy only
  429. RequireSasl bool `yaml:"require-sasl"`
  430. Vhost string
  431. MaxConnections int `yaml:"max-connections"`
  432. ThrottleDuration time.Duration `yaml:"throttle-duration"`
  433. MaxConnectionsPerDuration int `yaml:"max-connections-per-duration"`
  434. }
  435. // Config defines the overall configuration.
  436. type Config struct {
  437. Network struct {
  438. Name string
  439. }
  440. Server struct {
  441. Password string
  442. passwordBytes []byte
  443. Name string
  444. nameCasefolded string
  445. // Listeners is the new style for configuring listeners:
  446. Listeners map[string]listenerConfigBlock
  447. UnixBindMode os.FileMode `yaml:"unix-bind-mode"`
  448. TorListeners TorListenersConfig `yaml:"tor-listeners"`
  449. WebSockets struct {
  450. AllowedOrigins []string `yaml:"allowed-origins"`
  451. allowedOriginRegexps []*regexp.Regexp
  452. }
  453. // they get parsed into this internal representation:
  454. trueListeners map[string]utils.ListenerConfig
  455. STS STSConfig
  456. LookupHostnames *bool `yaml:"lookup-hostnames"`
  457. lookupHostnames bool
  458. ForwardConfirmHostnames bool `yaml:"forward-confirm-hostnames"`
  459. CheckIdent bool `yaml:"check-ident"`
  460. MOTD string
  461. motdLines []string
  462. MOTDFormatting bool `yaml:"motd-formatting"`
  463. ProxyAllowedFrom []string `yaml:"proxy-allowed-from"`
  464. proxyAllowedFromNets []net.IPNet
  465. WebIRC []webircConfig `yaml:"webirc"`
  466. MaxSendQString string `yaml:"max-sendq"`
  467. MaxSendQBytes int
  468. AllowPlaintextResume bool `yaml:"allow-plaintext-resume"`
  469. Compatibility struct {
  470. ForceTrailing *bool `yaml:"force-trailing"`
  471. forceTrailing bool
  472. SendUnprefixedSasl bool `yaml:"send-unprefixed-sasl"`
  473. }
  474. isupport isupport.List
  475. IPLimits connection_limits.LimiterConfig `yaml:"ip-limits"`
  476. Cloaks cloaks.CloakConfig `yaml:"ip-cloaking"`
  477. SecureNetDefs []string `yaml:"secure-nets"`
  478. secureNets []net.IPNet
  479. supportedCaps *caps.Set
  480. capValues caps.Values
  481. Casemapping Casemapping
  482. OutputPath string `yaml:"output-path"`
  483. }
  484. Roleplay struct {
  485. Enabled *bool
  486. enabled bool
  487. RequireChanops bool `yaml:"require-chanops"`
  488. RequireOper bool `yaml:"require-oper"`
  489. AddSuffix *bool `yaml:"add-suffix"`
  490. addSuffix bool
  491. }
  492. Extjwt struct {
  493. Default jwt.JwtServiceConfig `yaml:",inline"`
  494. Services map[string]jwt.JwtServiceConfig `yaml:"services"`
  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. func (config *Config) processExtjwt() (err error) {
  735. // first process the default service, which may be disabled
  736. err = config.Extjwt.Default.Postprocess()
  737. if err != nil {
  738. return
  739. }
  740. // now process the named services. it is an error if any is disabled
  741. // also, normalize the service names to lowercase
  742. services := make(map[string]jwt.JwtServiceConfig, len(config.Extjwt.Services))
  743. for service, sConf := range config.Extjwt.Services {
  744. err := sConf.Postprocess()
  745. if err != nil {
  746. return err
  747. }
  748. if !sConf.Enabled() {
  749. return fmt.Errorf("no keys enabled for extjwt service %s", service)
  750. }
  751. services[strings.ToLower(service)] = sConf
  752. }
  753. config.Extjwt.Services = services
  754. return nil
  755. }
  756. // LoadRawConfig loads the config without doing any consistency checks or postprocessing
  757. func LoadRawConfig(filename string) (config *Config, err error) {
  758. data, err := ioutil.ReadFile(filename)
  759. if err != nil {
  760. return nil, err
  761. }
  762. err = yaml.Unmarshal(data, &config)
  763. if err != nil {
  764. return nil, err
  765. }
  766. return
  767. }
  768. // LoadConfig loads the given YAML configuration file.
  769. func LoadConfig(filename string) (config *Config, err error) {
  770. config, err = LoadRawConfig(filename)
  771. if err != nil {
  772. return nil, err
  773. }
  774. config.Filename = filename
  775. if config.Network.Name == "" {
  776. return nil, ErrNetworkNameMissing
  777. }
  778. if config.Server.Name == "" {
  779. return nil, ErrServerNameMissing
  780. }
  781. if !utils.IsServerName(config.Server.Name) {
  782. return nil, ErrServerNameNotHostname
  783. }
  784. config.Server.nameCasefolded = strings.ToLower(config.Server.Name)
  785. if config.Datastore.Path == "" {
  786. return nil, ErrDatastorePathMissing
  787. }
  788. //dan: automagically fix identlen until a few releases in the future (from now, 0.12.0), being a newly-introduced limit
  789. if config.Limits.IdentLen < 1 {
  790. config.Limits.IdentLen = 20
  791. }
  792. if config.Limits.NickLen < 1 || config.Limits.ChannelLen < 2 || config.Limits.AwayLen < 1 || config.Limits.KickLen < 1 || config.Limits.TopicLen < 1 {
  793. return nil, ErrLimitsAreInsane
  794. }
  795. if config.Limits.RegistrationMessages == 0 {
  796. config.Limits.RegistrationMessages = 1024
  797. }
  798. if config.Datastore.MySQL.Enabled {
  799. if config.Limits.NickLen > mysql.MaxTargetLength || config.Limits.ChannelLen > mysql.MaxTargetLength {
  800. return nil, fmt.Errorf("to use MySQL, nick and channel length limits must be %d or lower", mysql.MaxTargetLength)
  801. }
  802. }
  803. config.Server.supportedCaps = caps.NewCompleteSet()
  804. config.Server.capValues = make(caps.Values)
  805. err = config.prepareListeners()
  806. if err != nil {
  807. return nil, fmt.Errorf("failed to prepare listeners: %v", err)
  808. }
  809. for _, glob := range config.Server.WebSockets.AllowedOrigins {
  810. globre, err := utils.CompileGlob(glob, false)
  811. if err != nil {
  812. return nil, fmt.Errorf("invalid websocket allowed-origin expression: %s", glob)
  813. }
  814. config.Server.WebSockets.allowedOriginRegexps = append(config.Server.WebSockets.allowedOriginRegexps, globre)
  815. }
  816. if config.Server.STS.Enabled {
  817. if config.Server.STS.Port < 0 || config.Server.STS.Port > 65535 {
  818. return nil, fmt.Errorf("STS port is incorrect, should be 0 if disabled: %d", config.Server.STS.Port)
  819. }
  820. if config.Server.STS.STSOnlyBanner != "" {
  821. for _, line := range strings.Split(config.Server.STS.STSOnlyBanner, "\n") {
  822. config.Server.STS.bannerLines = append(config.Server.STS.bannerLines, strings.TrimSpace(line))
  823. }
  824. } else {
  825. 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)}
  826. }
  827. } else {
  828. config.Server.supportedCaps.Disable(caps.STS)
  829. config.Server.STS.Duration = 0
  830. }
  831. // set this even if STS is disabled
  832. config.Server.capValues[caps.STS] = config.Server.STS.Value()
  833. config.Server.lookupHostnames = utils.BoolDefaultTrue(config.Server.LookupHostnames)
  834. // process webirc blocks
  835. var newWebIRC []webircConfig
  836. for _, webirc := range config.Server.WebIRC {
  837. // skip webirc blocks with no hosts (such as the example one)
  838. if len(webirc.Hosts) == 0 {
  839. continue
  840. }
  841. err = webirc.Populate()
  842. if err != nil {
  843. return nil, fmt.Errorf("Could not parse WebIRC config: %s", err.Error())
  844. }
  845. newWebIRC = append(newWebIRC, webirc)
  846. }
  847. config.Server.WebIRC = newWebIRC
  848. if config.Limits.Multiline.MaxBytes <= 0 {
  849. config.Server.supportedCaps.Disable(caps.Multiline)
  850. } else {
  851. var multilineCapValue string
  852. if config.Limits.Multiline.MaxLines == 0 {
  853. multilineCapValue = fmt.Sprintf("max-bytes=%d", config.Limits.Multiline.MaxBytes)
  854. } else {
  855. multilineCapValue = fmt.Sprintf("max-bytes=%d,max-lines=%d", config.Limits.Multiline.MaxBytes, config.Limits.Multiline.MaxLines)
  856. }
  857. config.Server.capValues[caps.Multiline] = multilineCapValue
  858. }
  859. // handle legacy name 'bouncer' for 'multiclient' section:
  860. if config.Accounts.Bouncer != nil {
  861. config.Accounts.Multiclient = *config.Accounts.Bouncer
  862. }
  863. if !config.Accounts.Multiclient.Enabled {
  864. config.Accounts.Multiclient.AlwaysOn = PersistentDisabled
  865. } else if config.Accounts.Multiclient.AlwaysOn >= PersistentOptOut {
  866. config.Accounts.Multiclient.AllowedByDefault = true
  867. }
  868. if config.Accounts.NickReservation.ForceNickEqualsAccount && !config.Accounts.Multiclient.Enabled {
  869. return nil, errors.New("force-nick-equals-account requires enabling multiclient as well")
  870. }
  871. // handle guest format, including the legacy key rename-prefix
  872. if config.Accounts.NickReservation.GuestFormat == "" {
  873. renamePrefix := config.Accounts.NickReservation.RenamePrefix
  874. if renamePrefix == "" {
  875. renamePrefix = "Guest-"
  876. }
  877. config.Accounts.NickReservation.GuestFormat = renamePrefix + "*"
  878. }
  879. config.Accounts.NickReservation.guestRegexp, config.Accounts.NickReservation.guestRegexpFolded, err = compileGuestRegexp(config.Accounts.NickReservation.GuestFormat, config.Server.Casemapping)
  880. if err != nil {
  881. return nil, err
  882. }
  883. var newLogConfigs []logger.LoggingConfig
  884. for _, logConfig := range config.Logging {
  885. // methods
  886. methods := make(map[string]bool)
  887. for _, method := range strings.Split(logConfig.Method, " ") {
  888. if len(method) > 0 {
  889. methods[strings.ToLower(method)] = true
  890. }
  891. }
  892. if methods["file"] && logConfig.Filename == "" {
  893. return nil, ErrLoggerFilenameMissing
  894. }
  895. logConfig.MethodFile = methods["file"]
  896. logConfig.MethodStdout = methods["stdout"]
  897. logConfig.MethodStderr = methods["stderr"]
  898. // levels
  899. level, exists := logger.LogLevelNames[strings.ToLower(logConfig.LevelString)]
  900. if !exists {
  901. return nil, fmt.Errorf("Could not translate log leve [%s]", logConfig.LevelString)
  902. }
  903. logConfig.Level = level
  904. // types
  905. for _, typeStr := range strings.Split(logConfig.TypeString, " ") {
  906. if len(typeStr) == 0 {
  907. continue
  908. }
  909. if typeStr == "-" {
  910. return nil, ErrLoggerExcludeEmpty
  911. }
  912. if typeStr[0] == '-' {
  913. typeStr = typeStr[1:]
  914. logConfig.ExcludedTypes = append(logConfig.ExcludedTypes, typeStr)
  915. } else {
  916. logConfig.Types = append(logConfig.Types, typeStr)
  917. }
  918. }
  919. if len(logConfig.Types) < 1 {
  920. return nil, ErrLoggerHasNoTypes
  921. }
  922. newLogConfigs = append(newLogConfigs, logConfig)
  923. }
  924. config.Logging = newLogConfigs
  925. // hardcode this for now
  926. config.Accounts.Registration.EnabledCredentialTypes = []string{"passphrase", "certfp"}
  927. mailtoEnabled := false
  928. for i, name := range config.Accounts.Registration.EnabledCallbacks {
  929. if name == "none" {
  930. // we store "none" as "*" internally
  931. config.Accounts.Registration.EnabledCallbacks[i] = "*"
  932. } else if name == "mailto" {
  933. mailtoEnabled = true
  934. }
  935. }
  936. sort.Strings(config.Accounts.Registration.EnabledCallbacks)
  937. if mailtoEnabled {
  938. err := config.Accounts.Registration.Callbacks.Mailto.Postprocess(config.Server.Name)
  939. if err != nil {
  940. return nil, err
  941. }
  942. }
  943. config.Accounts.defaultUserModes = ParseDefaultUserModes(config.Accounts.DefaultUserModes)
  944. config.Accounts.RequireSasl.exemptedNets, err = utils.ParseNetList(config.Accounts.RequireSasl.Exempted)
  945. if err != nil {
  946. return nil, fmt.Errorf("Could not parse require-sasl exempted nets: %v", err.Error())
  947. }
  948. config.Server.proxyAllowedFromNets, err = utils.ParseNetList(config.Server.ProxyAllowedFrom)
  949. if err != nil {
  950. return nil, fmt.Errorf("Could not parse proxy-allowed-from nets: %v", err.Error())
  951. }
  952. config.Server.secureNets, err = utils.ParseNetList(config.Server.SecureNetDefs)
  953. if err != nil {
  954. return nil, fmt.Errorf("Could not parse secure-nets: %v\n", err.Error())
  955. }
  956. rawRegexp := config.Accounts.VHosts.ValidRegexpRaw
  957. if rawRegexp != "" {
  958. regexp, err := regexp.Compile(rawRegexp)
  959. if err == nil {
  960. config.Accounts.VHosts.ValidRegexp = regexp
  961. } else {
  962. log.Printf("invalid vhost regexp: %s\n", err.Error())
  963. }
  964. }
  965. if config.Accounts.VHosts.ValidRegexp == nil {
  966. config.Accounts.VHosts.ValidRegexp = defaultValidVhostRegex
  967. }
  968. for _, vhost := range config.Accounts.VHosts.OfferList {
  969. if !config.Accounts.VHosts.ValidRegexp.MatchString(vhost) {
  970. return nil, fmt.Errorf("invalid offered vhost: %s", vhost)
  971. }
  972. }
  973. config.Server.capValues[caps.SASL] = "PLAIN,EXTERNAL"
  974. if !config.Accounts.AuthenticationEnabled {
  975. config.Server.supportedCaps.Disable(caps.SASL)
  976. }
  977. maxSendQBytes, err := bytefmt.ToBytes(config.Server.MaxSendQString)
  978. if err != nil {
  979. return nil, fmt.Errorf("Could not parse maximum SendQ size (make sure it only contains whole numbers): %s", err.Error())
  980. }
  981. config.Server.MaxSendQBytes = int(maxSendQBytes)
  982. config.languageManager, err = languages.NewManager(config.Languages.Enabled, config.Languages.Path, config.Languages.Default)
  983. if err != nil {
  984. return nil, fmt.Errorf("Could not load languages: %s", err.Error())
  985. }
  986. config.Server.capValues[caps.Languages] = config.languageManager.CapValue()
  987. config.Debug.recoverFromErrors = utils.BoolDefaultTrue(config.Debug.RecoverFromErrors)
  988. // process operator definitions, store them to config.operators
  989. operclasses, err := config.OperatorClasses()
  990. if err != nil {
  991. return nil, err
  992. }
  993. opers, err := config.Operators(operclasses)
  994. if err != nil {
  995. return nil, err
  996. }
  997. config.operators = opers
  998. // parse default channel modes
  999. config.Channels.defaultModes = ParseDefaultChannelModes(config.Channels.DefaultModes)
  1000. if config.Server.Password != "" {
  1001. config.Server.passwordBytes, err = decodeLegacyPasswordHash(config.Server.Password)
  1002. if err != nil {
  1003. return nil, err
  1004. }
  1005. if config.Accounts.LoginViaPassCommand && !config.Accounts.SkipServerPassword {
  1006. return nil, errors.New("Using a server password and login-via-pass-command requires skip-server-password as well")
  1007. }
  1008. }
  1009. if config.Accounts.Registration.BcryptCost == 0 {
  1010. config.Accounts.Registration.BcryptCost = passwd.DefaultCost
  1011. }
  1012. if config.Channels.MaxChannelsPerClient == 0 {
  1013. config.Channels.MaxChannelsPerClient = 100
  1014. }
  1015. if config.Channels.Registration.MaxChannelsPerAccount == 0 {
  1016. config.Channels.Registration.MaxChannelsPerAccount = 15
  1017. }
  1018. config.Server.Compatibility.forceTrailing = utils.BoolDefaultTrue(config.Server.Compatibility.ForceTrailing)
  1019. config.loadMOTD()
  1020. // in the current implementation, we disable history by creating a history buffer
  1021. // with zero capacity. but the `enabled` config option MUST be respected regardless
  1022. // of this detail
  1023. if !config.History.Enabled {
  1024. config.History.ChannelLength = 0
  1025. config.History.ClientLength = 0
  1026. }
  1027. if !config.History.Enabled || !config.History.Persistent.Enabled {
  1028. config.History.Persistent.UnregisteredChannels = false
  1029. config.History.Persistent.RegisteredChannels = PersistentDisabled
  1030. config.History.Persistent.DirectMessages = PersistentDisabled
  1031. }
  1032. if config.History.ZNCMax == 0 {
  1033. config.History.ZNCMax = config.History.ChathistoryMax
  1034. }
  1035. config.Roleplay.enabled = utils.BoolDefaultTrue(config.Roleplay.Enabled)
  1036. config.Roleplay.addSuffix = utils.BoolDefaultTrue(config.Roleplay.AddSuffix)
  1037. config.Datastore.MySQL.ExpireTime = time.Duration(config.History.Restrictions.ExpireTime)
  1038. config.Datastore.MySQL.TrackAccountMessages = config.History.Retention.EnableAccountIndexing
  1039. config.Server.Cloaks.Initialize()
  1040. if config.Server.Cloaks.Enabled {
  1041. if !utils.IsHostname(config.Server.Cloaks.Netname) {
  1042. return nil, fmt.Errorf("Invalid netname for cloaked hostnames: %s", config.Server.Cloaks.Netname)
  1043. }
  1044. }
  1045. err = config.processExtjwt()
  1046. if err != nil {
  1047. return nil, err
  1048. }
  1049. // now that all postprocessing is complete, regenerate ISUPPORT:
  1050. err = config.generateISupport()
  1051. if err != nil {
  1052. return nil, err
  1053. }
  1054. err = config.prepareListeners()
  1055. if err != nil {
  1056. return nil, fmt.Errorf("failed to prepare listeners: %v", err)
  1057. }
  1058. return config, nil
  1059. }
  1060. func (config *Config) getOutputPath(filename string) string {
  1061. return filepath.Join(config.Server.OutputPath, filename)
  1062. }
  1063. // setISupport sets up our RPL_ISUPPORT reply.
  1064. func (config *Config) generateISupport() (err error) {
  1065. maxTargetsString := strconv.Itoa(maxTargets)
  1066. // add RPL_ISUPPORT tokens
  1067. isupport := &config.Server.isupport
  1068. isupport.Initialize()
  1069. isupport.Add("AWAYLEN", strconv.Itoa(config.Limits.AwayLen))
  1070. isupport.Add("BOT", "B")
  1071. isupport.Add("CASEMAPPING", "ascii")
  1072. isupport.Add("CHANLIMIT", fmt.Sprintf("%s:%d", chanTypes, config.Channels.MaxChannelsPerClient))
  1073. 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()}, ","))
  1074. if config.History.Enabled && config.History.ChathistoryMax > 0 {
  1075. isupport.Add("draft/CHATHISTORY", strconv.Itoa(config.History.ChathistoryMax))
  1076. }
  1077. isupport.Add("CHANNELLEN", strconv.Itoa(config.Limits.ChannelLen))
  1078. isupport.Add("CHANTYPES", chanTypes)
  1079. isupport.Add("ELIST", "U")
  1080. isupport.Add("EXCEPTS", "")
  1081. if config.Extjwt.Default.Enabled() || len(config.Extjwt.Services) != 0 {
  1082. isupport.Add("EXTJWT", "1")
  1083. }
  1084. isupport.Add("INVEX", "")
  1085. isupport.Add("KICKLEN", strconv.Itoa(config.Limits.KickLen))
  1086. isupport.Add("MAXLIST", fmt.Sprintf("beI:%s", strconv.Itoa(config.Limits.ChanListModes)))
  1087. isupport.Add("MAXTARGETS", maxTargetsString)
  1088. isupport.Add("MODES", "")
  1089. isupport.Add("MONITOR", strconv.Itoa(config.Limits.MonitorEntries))
  1090. isupport.Add("NETWORK", config.Network.Name)
  1091. isupport.Add("NICKLEN", strconv.Itoa(config.Limits.NickLen))
  1092. isupport.Add("PREFIX", "(qaohv)~&@%+")
  1093. if config.Roleplay.enabled {
  1094. isupport.Add("RPCHAN", "E")
  1095. isupport.Add("RPUSER", "E")
  1096. }
  1097. isupport.Add("STATUSMSG", "~&@%+")
  1098. 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))
  1099. isupport.Add("TOPICLEN", strconv.Itoa(config.Limits.TopicLen))
  1100. if config.Server.Casemapping == CasemappingPRECIS {
  1101. isupport.Add("UTF8MAPPING", precisUTF8MappingToken)
  1102. }
  1103. err = isupport.RegenerateCachedReply()
  1104. return
  1105. }
  1106. // Diff returns changes in supported caps across a rehash.
  1107. func (config *Config) Diff(oldConfig *Config) (addedCaps, removedCaps *caps.Set) {
  1108. addedCaps = caps.NewSet()
  1109. removedCaps = caps.NewSet()
  1110. if oldConfig == nil {
  1111. return
  1112. }
  1113. if oldConfig.Server.capValues[caps.Languages] != config.Server.capValues[caps.Languages] {
  1114. // XXX updated caps get a DEL line and then a NEW line with the new value
  1115. addedCaps.Add(caps.Languages)
  1116. removedCaps.Add(caps.Languages)
  1117. }
  1118. if !oldConfig.Accounts.AuthenticationEnabled && config.Accounts.AuthenticationEnabled {
  1119. addedCaps.Add(caps.SASL)
  1120. } else if oldConfig.Accounts.AuthenticationEnabled && !config.Accounts.AuthenticationEnabled {
  1121. removedCaps.Add(caps.SASL)
  1122. }
  1123. if oldConfig.Limits.Multiline.MaxBytes != 0 && config.Limits.Multiline.MaxBytes == 0 {
  1124. removedCaps.Add(caps.Multiline)
  1125. } else if oldConfig.Limits.Multiline.MaxBytes == 0 && config.Limits.Multiline.MaxBytes != 0 {
  1126. addedCaps.Add(caps.Multiline)
  1127. } else if oldConfig.Limits.Multiline != config.Limits.Multiline {
  1128. removedCaps.Add(caps.Multiline)
  1129. addedCaps.Add(caps.Multiline)
  1130. }
  1131. if oldConfig.Server.STS.Enabled != config.Server.STS.Enabled || oldConfig.Server.capValues[caps.STS] != config.Server.capValues[caps.STS] {
  1132. // XXX: STS is always removed by CAP NEW sts=duration=0, not CAP DEL
  1133. // so the appropriate notify is always a CAP NEW; put it in addedCaps for any change
  1134. addedCaps.Add(caps.STS)
  1135. }
  1136. return
  1137. }
  1138. func compileGuestRegexp(guestFormat string, casemapping Casemapping) (standard, folded *regexp.Regexp, err error) {
  1139. if strings.Count(guestFormat, "?") != 0 || strings.Count(guestFormat, "*") != 1 {
  1140. err = errors.New("guest format must contain 1 '*' and no '?'s")
  1141. return
  1142. }
  1143. standard, err = utils.CompileGlob(guestFormat, true)
  1144. if err != nil {
  1145. return
  1146. }
  1147. starIndex := strings.IndexByte(guestFormat, '*')
  1148. initial := guestFormat[:starIndex]
  1149. final := guestFormat[starIndex+1:]
  1150. initialFolded, err := casefoldWithSetting(initial, casemapping)
  1151. if err != nil {
  1152. return
  1153. }
  1154. finalFolded, err := casefoldWithSetting(final, casemapping)
  1155. if err != nil {
  1156. return
  1157. }
  1158. folded, err = utils.CompileGlob(fmt.Sprintf("%s*%s", initialFolded, finalFolded), false)
  1159. return
  1160. }