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

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