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 41KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354
  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. "bytes"
  8. "crypto/tls"
  9. "errors"
  10. "fmt"
  11. "io/ioutil"
  12. "log"
  13. "net"
  14. "os"
  15. "path/filepath"
  16. "regexp"
  17. "sort"
  18. "strconv"
  19. "strings"
  20. "time"
  21. "code.cloudfoundry.org/bytefmt"
  22. "github.com/goshuirc/irc-go/ircfmt"
  23. "gopkg.in/yaml.v2"
  24. "github.com/oragono/oragono/irc/caps"
  25. "github.com/oragono/oragono/irc/cloaks"
  26. "github.com/oragono/oragono/irc/connection_limits"
  27. "github.com/oragono/oragono/irc/custime"
  28. "github.com/oragono/oragono/irc/email"
  29. "github.com/oragono/oragono/irc/isupport"
  30. "github.com/oragono/oragono/irc/jwt"
  31. "github.com/oragono/oragono/irc/languages"
  32. "github.com/oragono/oragono/irc/logger"
  33. "github.com/oragono/oragono/irc/modes"
  34. "github.com/oragono/oragono/irc/mysql"
  35. "github.com/oragono/oragono/irc/passwd"
  36. "github.com/oragono/oragono/irc/utils"
  37. )
  38. // here's how this works: exported (capitalized) members of the config structs
  39. // are defined in the YAML file and deserialized directly from there. They may
  40. // be postprocessed and overwritten by LoadConfig. Unexported (lowercase) members
  41. // are derived from the exported members in LoadConfig.
  42. // TLSListenConfig defines configuration options for listening on TLS.
  43. type TLSListenConfig struct {
  44. Cert string
  45. Key string
  46. Proxy bool
  47. }
  48. // This is the YAML-deserializable type of the value of the `Server.Listeners` map
  49. type listenerConfigBlock struct {
  50. TLS TLSListenConfig
  51. Tor bool
  52. STSOnly bool `yaml:"sts-only"`
  53. WebSocket bool
  54. }
  55. type PersistentStatus uint
  56. const (
  57. PersistentUnspecified PersistentStatus = iota
  58. PersistentDisabled
  59. PersistentOptIn
  60. PersistentOptOut
  61. PersistentMandatory
  62. )
  63. func persistentStatusToString(status PersistentStatus) string {
  64. switch status {
  65. case PersistentUnspecified:
  66. return "default"
  67. case PersistentDisabled:
  68. return "disabled"
  69. case PersistentOptIn:
  70. return "opt-in"
  71. case PersistentOptOut:
  72. return "opt-out"
  73. case PersistentMandatory:
  74. return "mandatory"
  75. default:
  76. return ""
  77. }
  78. }
  79. func persistentStatusFromString(status string) (PersistentStatus, error) {
  80. switch strings.ToLower(status) {
  81. case "default":
  82. return PersistentUnspecified, nil
  83. case "":
  84. return PersistentDisabled, nil
  85. case "opt-in":
  86. return PersistentOptIn, nil
  87. case "opt-out":
  88. return PersistentOptOut, nil
  89. case "mandatory":
  90. return PersistentMandatory, nil
  91. default:
  92. b, err := utils.StringToBool(status)
  93. if b {
  94. return PersistentMandatory, err
  95. } else {
  96. return PersistentDisabled, err
  97. }
  98. }
  99. }
  100. func (ps *PersistentStatus) UnmarshalYAML(unmarshal func(interface{}) error) error {
  101. var orig string
  102. var err error
  103. if err = unmarshal(&orig); err != nil {
  104. return err
  105. }
  106. result, err := persistentStatusFromString(orig)
  107. if err == nil {
  108. if result == PersistentUnspecified {
  109. result = PersistentDisabled
  110. }
  111. *ps = result
  112. }
  113. return err
  114. }
  115. func persistenceEnabled(serverSetting, clientSetting PersistentStatus) (enabled bool) {
  116. if serverSetting == PersistentDisabled {
  117. return false
  118. } else if serverSetting == PersistentMandatory {
  119. return true
  120. } else if clientSetting == PersistentDisabled {
  121. return false
  122. } else if clientSetting == PersistentMandatory {
  123. return true
  124. } else if serverSetting == PersistentOptOut {
  125. return true
  126. } else {
  127. return false
  128. }
  129. }
  130. type HistoryStatus uint
  131. const (
  132. HistoryDefault HistoryStatus = iota
  133. HistoryDisabled
  134. HistoryEphemeral
  135. HistoryPersistent
  136. )
  137. func historyStatusFromString(str string) (status HistoryStatus, err error) {
  138. switch strings.ToLower(str) {
  139. case "default":
  140. return HistoryDefault, nil
  141. case "ephemeral":
  142. return HistoryEphemeral, nil
  143. case "persistent":
  144. return HistoryPersistent, nil
  145. default:
  146. b, err := utils.StringToBool(str)
  147. if b {
  148. return HistoryPersistent, err
  149. } else {
  150. return HistoryDisabled, err
  151. }
  152. }
  153. }
  154. func historyStatusToString(status HistoryStatus) string {
  155. switch status {
  156. case HistoryDefault:
  157. return "default"
  158. case HistoryDisabled:
  159. return "disabled"
  160. case HistoryEphemeral:
  161. return "ephemeral"
  162. case HistoryPersistent:
  163. return "persistent"
  164. default:
  165. return ""
  166. }
  167. }
  168. // XXX you must have already checked History.Enabled before calling this
  169. func historyEnabled(serverSetting PersistentStatus, localSetting HistoryStatus) (result HistoryStatus) {
  170. switch serverSetting {
  171. case PersistentMandatory:
  172. return HistoryPersistent
  173. case PersistentOptOut:
  174. if localSetting == HistoryDefault {
  175. return HistoryPersistent
  176. } else {
  177. return localSetting
  178. }
  179. case PersistentOptIn:
  180. switch localSetting {
  181. case HistoryPersistent:
  182. return HistoryPersistent
  183. case HistoryEphemeral, HistoryDefault:
  184. return HistoryEphemeral
  185. default:
  186. return HistoryDisabled
  187. }
  188. case PersistentDisabled:
  189. if localSetting == HistoryDisabled {
  190. return HistoryDisabled
  191. } else {
  192. return HistoryEphemeral
  193. }
  194. default:
  195. // PersistentUnspecified: shouldn't happen because the deserializer converts it
  196. // to PersistentDisabled
  197. if localSetting == HistoryDefault {
  198. return HistoryEphemeral
  199. } else {
  200. return localSetting
  201. }
  202. }
  203. }
  204. type MulticlientConfig struct {
  205. Enabled bool
  206. AllowedByDefault bool `yaml:"allowed-by-default"`
  207. AlwaysOn PersistentStatus `yaml:"always-on"`
  208. AutoAway PersistentStatus `yaml:"auto-away"`
  209. }
  210. type throttleConfig struct {
  211. Enabled bool
  212. Duration time.Duration
  213. MaxAttempts int `yaml:"max-attempts"`
  214. }
  215. type ThrottleConfig struct {
  216. throttleConfig
  217. }
  218. func (t *ThrottleConfig) UnmarshalYAML(unmarshal func(interface{}) error) (err error) {
  219. // note that this technique only works if the zero value of the struct
  220. // doesn't need any postprocessing (because if the field is omitted entirely
  221. // from the YAML, then UnmarshalYAML won't be called at all)
  222. if err = unmarshal(&t.throttleConfig); err != nil {
  223. return
  224. }
  225. if !t.Enabled {
  226. t.MaxAttempts = 0 // limit of 0 means disabled
  227. }
  228. return
  229. }
  230. type AccountConfig struct {
  231. Registration AccountRegistrationConfig
  232. AuthenticationEnabled bool `yaml:"authentication-enabled"`
  233. RequireSasl struct {
  234. Enabled bool
  235. Exempted []string
  236. exemptedNets []net.IPNet
  237. } `yaml:"require-sasl"`
  238. DefaultUserModes *string `yaml:"default-user-modes"`
  239. defaultUserModes modes.Modes
  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. // RenamePrefix is the legacy field, GuestFormat is the new version
  249. RenamePrefix string `yaml:"rename-prefix"`
  250. GuestFormat string `yaml:"guest-nickname-format"`
  251. guestRegexp *regexp.Regexp
  252. guestRegexpFolded *regexp.Regexp
  253. ForceGuestFormat bool `yaml:"force-guest-format"`
  254. ForceNickEqualsAccount bool `yaml:"force-nick-equals-account"`
  255. } `yaml:"nick-reservation"`
  256. Multiclient MulticlientConfig
  257. Bouncer *MulticlientConfig // # handle old name for 'multiclient'
  258. VHosts VHostConfig
  259. AuthScript AuthScriptConfig `yaml:"auth-script"`
  260. }
  261. type AuthScriptConfig struct {
  262. Enabled bool
  263. Command string
  264. Args []string
  265. Autocreate bool
  266. Timeout time.Duration
  267. KillTimeout time.Duration `yaml:"kill-timeout"`
  268. }
  269. // AccountRegistrationConfig controls account registration.
  270. type AccountRegistrationConfig struct {
  271. Enabled bool
  272. Throttling ThrottleConfig
  273. EnabledCallbacks []string `yaml:"enabled-callbacks"`
  274. EnabledCredentialTypes []string `yaml:"-"`
  275. VerifyTimeout custime.Duration `yaml:"verify-timeout"`
  276. Callbacks struct {
  277. Mailto email.MailtoConfig
  278. }
  279. BcryptCost uint `yaml:"bcrypt-cost"`
  280. }
  281. type VHostConfig struct {
  282. Enabled bool
  283. MaxLength int `yaml:"max-length"`
  284. ValidRegexpRaw string `yaml:"valid-regexp"`
  285. ValidRegexp *regexp.Regexp
  286. UserRequests struct {
  287. Enabled bool
  288. Channel string
  289. Cooldown custime.Duration
  290. } `yaml:"user-requests"`
  291. }
  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. EnforceUtf8 bool `yaml:"enforce-utf8"`
  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. TagmsgStorage struct {
  557. Default bool
  558. Whitelist []string
  559. Blacklist []string
  560. } `yaml:"tagmsg-storage"`
  561. }
  562. Filename string
  563. }
  564. // OperClass defines an assembled operator class.
  565. type OperClass struct {
  566. Title string
  567. WhoisLine string `yaml:"whois-line"`
  568. Capabilities utils.StringSet // map to make lookups much easier
  569. }
  570. // OperatorClasses returns a map of assembled operator classes from the given config.
  571. func (conf *Config) OperatorClasses() (map[string]*OperClass, error) {
  572. fixupCapability := func(capab string) string {
  573. return strings.TrimPrefix(capab, "oper:") // #868
  574. }
  575. ocs := make(map[string]*OperClass)
  576. // loop from no extends to most extended, breaking if we can't add any more
  577. lenOfLastOcs := -1
  578. for {
  579. if lenOfLastOcs == len(ocs) {
  580. return nil, errors.New("OperClasses contains a looping dependency, or a class extends from a class that doesn't exist")
  581. }
  582. lenOfLastOcs = len(ocs)
  583. var anyMissing bool
  584. for name, info := range conf.OperClasses {
  585. _, exists := ocs[name]
  586. _, extendsExists := ocs[info.Extends]
  587. if exists {
  588. // class already exists
  589. continue
  590. } else if len(info.Extends) > 0 && !extendsExists {
  591. // class we extend on doesn't exist
  592. _, exists := conf.OperClasses[info.Extends]
  593. if !exists {
  594. return nil, fmt.Errorf("Operclass [%s] extends [%s], which doesn't exist", name, info.Extends)
  595. }
  596. anyMissing = true
  597. continue
  598. }
  599. // create new operclass
  600. var oc OperClass
  601. oc.Capabilities = make(utils.StringSet)
  602. // get inhereted info from other operclasses
  603. if len(info.Extends) > 0 {
  604. einfo := ocs[info.Extends]
  605. for capab := range einfo.Capabilities {
  606. oc.Capabilities.Add(fixupCapability(capab))
  607. }
  608. }
  609. // add our own info
  610. oc.Title = info.Title
  611. for _, capab := range info.Capabilities {
  612. oc.Capabilities.Add(fixupCapability(capab))
  613. }
  614. if len(info.WhoisLine) > 0 {
  615. oc.WhoisLine = info.WhoisLine
  616. } else {
  617. oc.WhoisLine = "is a"
  618. if strings.Contains(strings.ToLower(string(oc.Title[0])), "aeiou") {
  619. oc.WhoisLine += "n"
  620. }
  621. oc.WhoisLine += " "
  622. oc.WhoisLine += oc.Title
  623. }
  624. ocs[name] = &oc
  625. }
  626. if !anyMissing {
  627. // we've got every operclass!
  628. break
  629. }
  630. }
  631. return ocs, nil
  632. }
  633. // Oper represents a single assembled operator's config.
  634. type Oper struct {
  635. Name string
  636. Class *OperClass
  637. WhoisLine string
  638. Vhost string
  639. Pass []byte
  640. Certfp string
  641. Auto bool
  642. Modes []modes.ModeChange
  643. }
  644. // Operators returns a map of operator configs from the given OperClass and config.
  645. func (conf *Config) Operators(oc map[string]*OperClass) (map[string]*Oper, error) {
  646. operators := make(map[string]*Oper)
  647. for name, opConf := range conf.Opers {
  648. var oper Oper
  649. // oper name
  650. name, err := CasefoldName(name)
  651. if err != nil {
  652. return nil, fmt.Errorf("Could not casefold oper name: %s", err.Error())
  653. }
  654. oper.Name = name
  655. if opConf.Password != "" {
  656. oper.Pass, err = decodeLegacyPasswordHash(opConf.Password)
  657. if err != nil {
  658. return nil, fmt.Errorf("Oper %s has an invalid password hash: %s", oper.Name, err.Error())
  659. }
  660. }
  661. certfp := opConf.Certfp
  662. if certfp == "" && opConf.Fingerprint != nil {
  663. certfp = *opConf.Fingerprint
  664. }
  665. if certfp != "" {
  666. oper.Certfp, err = utils.NormalizeCertfp(certfp)
  667. if err != nil {
  668. return nil, fmt.Errorf("Oper %s has an invalid fingerprint: %s", oper.Name, err.Error())
  669. }
  670. }
  671. oper.Auto = opConf.Auto
  672. if oper.Pass == nil && oper.Certfp == "" {
  673. return nil, fmt.Errorf("Oper %s has neither a password nor a fingerprint", name)
  674. }
  675. oper.Vhost = opConf.Vhost
  676. class, exists := oc[opConf.Class]
  677. if !exists {
  678. return nil, fmt.Errorf("Could not load operator [%s] - they use operclass [%s] which does not exist", name, opConf.Class)
  679. }
  680. oper.Class = class
  681. if len(opConf.WhoisLine) > 0 {
  682. oper.WhoisLine = opConf.WhoisLine
  683. } else {
  684. oper.WhoisLine = class.WhoisLine
  685. }
  686. modeStr := strings.TrimSpace(opConf.Modes)
  687. modeChanges, unknownChanges := modes.ParseUserModeChanges(strings.Split(modeStr, " ")...)
  688. if len(unknownChanges) > 0 {
  689. return nil, fmt.Errorf("Could not load operator [%s] due to unknown modes %v", name, unknownChanges)
  690. }
  691. oper.Modes = modeChanges
  692. // successful, attach to list of opers
  693. operators[name] = &oper
  694. }
  695. return operators, nil
  696. }
  697. func loadTlsConfig(config TLSListenConfig, webSocket bool) (tlsConfig *tls.Config, err error) {
  698. cert, err := tls.LoadX509KeyPair(config.Cert, config.Key)
  699. if err != nil {
  700. return nil, &CertKeyError{Err: err}
  701. }
  702. clientAuth := tls.RequestClientCert
  703. if webSocket {
  704. // if Chrome receives a server request for a client certificate
  705. // on a websocket connection, it will immediately disconnect:
  706. // https://bugs.chromium.org/p/chromium/issues/detail?id=329884
  707. // work around this behavior:
  708. clientAuth = tls.NoClientCert
  709. }
  710. result := tls.Config{
  711. Certificates: []tls.Certificate{cert},
  712. ClientAuth: clientAuth,
  713. }
  714. return &result, nil
  715. }
  716. // prepareListeners populates Config.Server.trueListeners
  717. func (conf *Config) prepareListeners() (err error) {
  718. if len(conf.Server.Listeners) == 0 {
  719. return fmt.Errorf("No listeners were configured")
  720. }
  721. conf.Server.trueListeners = make(map[string]utils.ListenerConfig)
  722. for addr, block := range conf.Server.Listeners {
  723. var lconf utils.ListenerConfig
  724. lconf.ProxyDeadline = RegisterTimeout
  725. lconf.Tor = block.Tor
  726. lconf.STSOnly = block.STSOnly
  727. if lconf.STSOnly && !conf.Server.STS.Enabled {
  728. return fmt.Errorf("%s is configured as a STS-only listener, but STS is disabled", addr)
  729. }
  730. if block.TLS.Cert != "" {
  731. tlsConfig, err := loadTlsConfig(block.TLS, block.WebSocket)
  732. if err != nil {
  733. return err
  734. }
  735. lconf.TLSConfig = tlsConfig
  736. lconf.RequireProxy = block.TLS.Proxy
  737. }
  738. lconf.WebSocket = block.WebSocket
  739. conf.Server.trueListeners[addr] = lconf
  740. }
  741. return nil
  742. }
  743. func (config *Config) processExtjwt() (err error) {
  744. // first process the default service, which may be disabled
  745. err = config.Extjwt.Default.Postprocess()
  746. if err != nil {
  747. return
  748. }
  749. // now process the named services. it is an error if any is disabled
  750. // also, normalize the service names to lowercase
  751. services := make(map[string]jwt.JwtServiceConfig, len(config.Extjwt.Services))
  752. for service, sConf := range config.Extjwt.Services {
  753. err := sConf.Postprocess()
  754. if err != nil {
  755. return err
  756. }
  757. if !sConf.Enabled() {
  758. return fmt.Errorf("no keys enabled for extjwt service %s", service)
  759. }
  760. services[strings.ToLower(service)] = sConf
  761. }
  762. config.Extjwt.Services = services
  763. return nil
  764. }
  765. // LoadRawConfig loads the config without doing any consistency checks or postprocessing
  766. func LoadRawConfig(filename string) (config *Config, err error) {
  767. data, err := ioutil.ReadFile(filename)
  768. if err != nil {
  769. return nil, err
  770. }
  771. err = yaml.Unmarshal(data, &config)
  772. if err != nil {
  773. return nil, err
  774. }
  775. return
  776. }
  777. // LoadConfig loads the given YAML configuration file.
  778. func LoadConfig(filename string) (config *Config, err error) {
  779. config, err = LoadRawConfig(filename)
  780. if err != nil {
  781. return nil, err
  782. }
  783. config.Filename = filename
  784. if config.Network.Name == "" {
  785. return nil, errors.New("Network name missing")
  786. }
  787. if config.Server.Name == "" {
  788. return nil, errors.New("Server name missing")
  789. }
  790. if !utils.IsServerName(config.Server.Name) {
  791. return nil, errors.New("Server name must match the format of a hostname")
  792. }
  793. config.Server.nameCasefolded = strings.ToLower(config.Server.Name)
  794. if config.Datastore.Path == "" {
  795. return nil, errors.New("Datastore path missing")
  796. }
  797. //dan: automagically fix identlen until a few releases in the future (from now, 0.12.0), being a newly-introduced limit
  798. if config.Limits.IdentLen < 1 {
  799. config.Limits.IdentLen = 20
  800. }
  801. if config.Limits.NickLen < 1 || config.Limits.ChannelLen < 2 || config.Limits.AwayLen < 1 || config.Limits.KickLen < 1 || config.Limits.TopicLen < 1 {
  802. return nil, errors.New("One or more limits values are too low")
  803. }
  804. if config.Limits.RegistrationMessages == 0 {
  805. config.Limits.RegistrationMessages = 1024
  806. }
  807. if config.Datastore.MySQL.Enabled {
  808. if config.Limits.NickLen > mysql.MaxTargetLength || config.Limits.ChannelLen > mysql.MaxTargetLength {
  809. return nil, fmt.Errorf("to use MySQL, nick and channel length limits must be %d or lower", mysql.MaxTargetLength)
  810. }
  811. }
  812. config.Server.supportedCaps = caps.NewCompleteSet()
  813. config.Server.capValues = make(caps.Values)
  814. err = config.prepareListeners()
  815. if err != nil {
  816. return nil, fmt.Errorf("failed to prepare listeners: %v", err)
  817. }
  818. for _, glob := range config.Server.WebSockets.AllowedOrigins {
  819. globre, err := utils.CompileGlob(glob, false)
  820. if err != nil {
  821. return nil, fmt.Errorf("invalid websocket allowed-origin expression: %s", glob)
  822. }
  823. config.Server.WebSockets.allowedOriginRegexps = append(config.Server.WebSockets.allowedOriginRegexps, globre)
  824. }
  825. if config.Server.STS.Enabled {
  826. if config.Server.STS.Port < 0 || config.Server.STS.Port > 65535 {
  827. return nil, fmt.Errorf("STS port is incorrect, should be 0 if disabled: %d", config.Server.STS.Port)
  828. }
  829. if config.Server.STS.STSOnlyBanner != "" {
  830. for _, line := range strings.Split(config.Server.STS.STSOnlyBanner, "\n") {
  831. config.Server.STS.bannerLines = append(config.Server.STS.bannerLines, strings.TrimSpace(line))
  832. }
  833. } else {
  834. 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)}
  835. }
  836. } else {
  837. config.Server.supportedCaps.Disable(caps.STS)
  838. config.Server.STS.Duration = 0
  839. }
  840. // set this even if STS is disabled
  841. config.Server.capValues[caps.STS] = config.Server.STS.Value()
  842. config.Server.lookupHostnames = utils.BoolDefaultTrue(config.Server.LookupHostnames)
  843. // process webirc blocks
  844. var newWebIRC []webircConfig
  845. for _, webirc := range config.Server.WebIRC {
  846. // skip webirc blocks with no hosts (such as the example one)
  847. if len(webirc.Hosts) == 0 {
  848. continue
  849. }
  850. err = webirc.Populate()
  851. if err != nil {
  852. return nil, fmt.Errorf("Could not parse WebIRC config: %s", err.Error())
  853. }
  854. newWebIRC = append(newWebIRC, webirc)
  855. }
  856. config.Server.WebIRC = newWebIRC
  857. if config.Limits.Multiline.MaxBytes <= 0 {
  858. config.Server.supportedCaps.Disable(caps.Multiline)
  859. } else {
  860. var multilineCapValue string
  861. if config.Limits.Multiline.MaxLines == 0 {
  862. multilineCapValue = fmt.Sprintf("max-bytes=%d", config.Limits.Multiline.MaxBytes)
  863. } else {
  864. multilineCapValue = fmt.Sprintf("max-bytes=%d,max-lines=%d", config.Limits.Multiline.MaxBytes, config.Limits.Multiline.MaxLines)
  865. }
  866. config.Server.capValues[caps.Multiline] = multilineCapValue
  867. }
  868. // handle legacy name 'bouncer' for 'multiclient' section:
  869. if config.Accounts.Bouncer != nil {
  870. config.Accounts.Multiclient = *config.Accounts.Bouncer
  871. }
  872. if !config.Accounts.Multiclient.Enabled {
  873. config.Accounts.Multiclient.AlwaysOn = PersistentDisabled
  874. } else if config.Accounts.Multiclient.AlwaysOn >= PersistentOptOut {
  875. config.Accounts.Multiclient.AllowedByDefault = true
  876. }
  877. if config.Accounts.NickReservation.ForceNickEqualsAccount && !config.Accounts.Multiclient.Enabled {
  878. return nil, errors.New("force-nick-equals-account requires enabling multiclient as well")
  879. }
  880. // handle guest format, including the legacy key rename-prefix
  881. if config.Accounts.NickReservation.GuestFormat == "" {
  882. renamePrefix := config.Accounts.NickReservation.RenamePrefix
  883. if renamePrefix == "" {
  884. renamePrefix = "Guest-"
  885. }
  886. config.Accounts.NickReservation.GuestFormat = renamePrefix + "*"
  887. }
  888. config.Accounts.NickReservation.guestRegexp, config.Accounts.NickReservation.guestRegexpFolded, err = compileGuestRegexp(config.Accounts.NickReservation.GuestFormat, config.Server.Casemapping)
  889. if err != nil {
  890. return nil, err
  891. }
  892. var newLogConfigs []logger.LoggingConfig
  893. for _, logConfig := range config.Logging {
  894. // methods
  895. methods := make(map[string]bool)
  896. for _, method := range strings.Split(logConfig.Method, " ") {
  897. if len(method) > 0 {
  898. methods[strings.ToLower(method)] = true
  899. }
  900. }
  901. if methods["file"] && logConfig.Filename == "" {
  902. return nil, errors.New("Logging configuration specifies 'file' method but 'filename' is empty")
  903. }
  904. logConfig.MethodFile = methods["file"]
  905. logConfig.MethodStdout = methods["stdout"]
  906. logConfig.MethodStderr = methods["stderr"]
  907. // levels
  908. level, exists := logger.LogLevelNames[strings.ToLower(logConfig.LevelString)]
  909. if !exists {
  910. return nil, fmt.Errorf("Could not translate log leve [%s]", logConfig.LevelString)
  911. }
  912. logConfig.Level = level
  913. // types
  914. for _, typeStr := range strings.Split(logConfig.TypeString, " ") {
  915. if len(typeStr) == 0 {
  916. continue
  917. }
  918. if typeStr == "-" {
  919. return nil, errors.New("Encountered logging type '-' with no type to exclude")
  920. }
  921. if typeStr[0] == '-' {
  922. typeStr = typeStr[1:]
  923. logConfig.ExcludedTypes = append(logConfig.ExcludedTypes, typeStr)
  924. } else {
  925. logConfig.Types = append(logConfig.Types, typeStr)
  926. }
  927. }
  928. if len(logConfig.Types) < 1 {
  929. return nil, errors.New("Logger has no types to log")
  930. }
  931. newLogConfigs = append(newLogConfigs, logConfig)
  932. }
  933. config.Logging = newLogConfigs
  934. // hardcode this for now
  935. config.Accounts.Registration.EnabledCredentialTypes = []string{"passphrase", "certfp"}
  936. mailtoEnabled := false
  937. for i, name := range config.Accounts.Registration.EnabledCallbacks {
  938. if name == "none" {
  939. // we store "none" as "*" internally
  940. config.Accounts.Registration.EnabledCallbacks[i] = "*"
  941. } else if name == "mailto" {
  942. mailtoEnabled = true
  943. }
  944. }
  945. sort.Strings(config.Accounts.Registration.EnabledCallbacks)
  946. if mailtoEnabled {
  947. err := config.Accounts.Registration.Callbacks.Mailto.Postprocess(config.Server.Name)
  948. if err != nil {
  949. return nil, err
  950. }
  951. }
  952. config.Accounts.defaultUserModes = ParseDefaultUserModes(config.Accounts.DefaultUserModes)
  953. config.Accounts.RequireSasl.exemptedNets, err = utils.ParseNetList(config.Accounts.RequireSasl.Exempted)
  954. if err != nil {
  955. return nil, fmt.Errorf("Could not parse require-sasl exempted nets: %v", err.Error())
  956. }
  957. config.Server.proxyAllowedFromNets, err = utils.ParseNetList(config.Server.ProxyAllowedFrom)
  958. if err != nil {
  959. return nil, fmt.Errorf("Could not parse proxy-allowed-from nets: %v", err.Error())
  960. }
  961. config.Server.secureNets, err = utils.ParseNetList(config.Server.SecureNetDefs)
  962. if err != nil {
  963. return nil, fmt.Errorf("Could not parse secure-nets: %v\n", err.Error())
  964. }
  965. rawRegexp := config.Accounts.VHosts.ValidRegexpRaw
  966. if rawRegexp != "" {
  967. regexp, err := regexp.Compile(rawRegexp)
  968. if err == nil {
  969. config.Accounts.VHosts.ValidRegexp = regexp
  970. } else {
  971. log.Printf("invalid vhost regexp: %s\n", err.Error())
  972. }
  973. }
  974. if config.Accounts.VHosts.ValidRegexp == nil {
  975. config.Accounts.VHosts.ValidRegexp = defaultValidVhostRegex
  976. }
  977. config.Server.capValues[caps.SASL] = "PLAIN,EXTERNAL"
  978. if !config.Accounts.AuthenticationEnabled {
  979. config.Server.supportedCaps.Disable(caps.SASL)
  980. }
  981. maxSendQBytes, err := bytefmt.ToBytes(config.Server.MaxSendQString)
  982. if err != nil {
  983. return nil, fmt.Errorf("Could not parse maximum SendQ size (make sure it only contains whole numbers): %s", err.Error())
  984. }
  985. config.Server.MaxSendQBytes = int(maxSendQBytes)
  986. config.languageManager, err = languages.NewManager(config.Languages.Enabled, config.Languages.Path, config.Languages.Default)
  987. if err != nil {
  988. return nil, fmt.Errorf("Could not load languages: %s", err.Error())
  989. }
  990. config.Server.capValues[caps.Languages] = config.languageManager.CapValue()
  991. config.Debug.recoverFromErrors = utils.BoolDefaultTrue(config.Debug.RecoverFromErrors)
  992. // process operator definitions, store them to config.operators
  993. operclasses, err := config.OperatorClasses()
  994. if err != nil {
  995. return nil, err
  996. }
  997. opers, err := config.Operators(operclasses)
  998. if err != nil {
  999. return nil, err
  1000. }
  1001. config.operators = opers
  1002. // parse default channel modes
  1003. config.Channels.defaultModes = ParseDefaultChannelModes(config.Channels.DefaultModes)
  1004. if config.Server.Password != "" {
  1005. config.Server.passwordBytes, err = decodeLegacyPasswordHash(config.Server.Password)
  1006. if err != nil {
  1007. return nil, err
  1008. }
  1009. if config.Accounts.LoginViaPassCommand && !config.Accounts.SkipServerPassword {
  1010. return nil, errors.New("Using a server password and login-via-pass-command requires skip-server-password as well")
  1011. }
  1012. }
  1013. if config.Accounts.Registration.BcryptCost == 0 {
  1014. config.Accounts.Registration.BcryptCost = passwd.DefaultCost
  1015. }
  1016. if config.Channels.MaxChannelsPerClient == 0 {
  1017. config.Channels.MaxChannelsPerClient = 100
  1018. }
  1019. if config.Channels.Registration.MaxChannelsPerAccount == 0 {
  1020. config.Channels.Registration.MaxChannelsPerAccount = 15
  1021. }
  1022. config.Server.Compatibility.forceTrailing = utils.BoolDefaultTrue(config.Server.Compatibility.ForceTrailing)
  1023. config.loadMOTD()
  1024. // in the current implementation, we disable history by creating a history buffer
  1025. // with zero capacity. but the `enabled` config option MUST be respected regardless
  1026. // of this detail
  1027. if !config.History.Enabled {
  1028. config.History.ChannelLength = 0
  1029. config.History.ClientLength = 0
  1030. }
  1031. if !config.History.Enabled || !config.History.Persistent.Enabled {
  1032. config.History.Persistent.Enabled = false
  1033. config.History.Persistent.UnregisteredChannels = false
  1034. config.History.Persistent.RegisteredChannels = PersistentDisabled
  1035. config.History.Persistent.DirectMessages = PersistentDisabled
  1036. }
  1037. if config.History.Persistent.Enabled && !config.Datastore.MySQL.Enabled {
  1038. return nil, fmt.Errorf("You must configure a MySQL server in order to enable persistent history")
  1039. }
  1040. if config.History.ZNCMax == 0 {
  1041. config.History.ZNCMax = config.History.ChathistoryMax
  1042. }
  1043. config.Roleplay.enabled = utils.BoolDefaultTrue(config.Roleplay.Enabled)
  1044. config.Roleplay.addSuffix = utils.BoolDefaultTrue(config.Roleplay.AddSuffix)
  1045. config.Datastore.MySQL.ExpireTime = time.Duration(config.History.Restrictions.ExpireTime)
  1046. config.Datastore.MySQL.TrackAccountMessages = config.History.Retention.EnableAccountIndexing
  1047. config.Server.Cloaks.Initialize()
  1048. if config.Server.Cloaks.Enabled {
  1049. if !utils.IsHostname(config.Server.Cloaks.Netname) {
  1050. return nil, fmt.Errorf("Invalid netname for cloaked hostnames: %s", config.Server.Cloaks.Netname)
  1051. }
  1052. }
  1053. err = config.processExtjwt()
  1054. if err != nil {
  1055. return nil, err
  1056. }
  1057. // now that all postprocessing is complete, regenerate ISUPPORT:
  1058. err = config.generateISupport()
  1059. if err != nil {
  1060. return nil, err
  1061. }
  1062. err = config.prepareListeners()
  1063. if err != nil {
  1064. return nil, fmt.Errorf("failed to prepare listeners: %v", err)
  1065. }
  1066. return config, nil
  1067. }
  1068. func (config *Config) getOutputPath(filename string) string {
  1069. return filepath.Join(config.Server.OutputPath, filename)
  1070. }
  1071. // setISupport sets up our RPL_ISUPPORT reply.
  1072. func (config *Config) generateISupport() (err error) {
  1073. maxTargetsString := strconv.Itoa(maxTargets)
  1074. // add RPL_ISUPPORT tokens
  1075. isupport := &config.Server.isupport
  1076. isupport.Initialize()
  1077. isupport.Add("AWAYLEN", strconv.Itoa(config.Limits.AwayLen))
  1078. isupport.Add("BOT", "B")
  1079. isupport.Add("CASEMAPPING", "ascii")
  1080. isupport.Add("CHANLIMIT", fmt.Sprintf("%s:%d", chanTypes, config.Channels.MaxChannelsPerClient))
  1081. 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()}, ","))
  1082. if config.History.Enabled && config.History.ChathistoryMax > 0 {
  1083. isupport.Add("draft/CHATHISTORY", strconv.Itoa(config.History.ChathistoryMax))
  1084. }
  1085. isupport.Add("CHANNELLEN", strconv.Itoa(config.Limits.ChannelLen))
  1086. isupport.Add("CHANTYPES", chanTypes)
  1087. isupport.Add("ELIST", "U")
  1088. isupport.Add("EXCEPTS", "")
  1089. if config.Extjwt.Default.Enabled() || len(config.Extjwt.Services) != 0 {
  1090. isupport.Add("EXTJWT", "1")
  1091. }
  1092. isupport.Add("INVEX", "")
  1093. isupport.Add("KICKLEN", strconv.Itoa(config.Limits.KickLen))
  1094. isupport.Add("MAXLIST", fmt.Sprintf("beI:%s", strconv.Itoa(config.Limits.ChanListModes)))
  1095. isupport.Add("MAXTARGETS", maxTargetsString)
  1096. isupport.Add("MODES", "")
  1097. isupport.Add("MONITOR", strconv.Itoa(config.Limits.MonitorEntries))
  1098. isupport.Add("NETWORK", config.Network.Name)
  1099. isupport.Add("NICKLEN", strconv.Itoa(config.Limits.NickLen))
  1100. isupport.Add("PREFIX", "(qaohv)~&@%+")
  1101. if config.Roleplay.enabled {
  1102. isupport.Add("RPCHAN", "E")
  1103. isupport.Add("RPUSER", "E")
  1104. }
  1105. isupport.Add("STATUSMSG", "~&@%+")
  1106. 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))
  1107. isupport.Add("TOPICLEN", strconv.Itoa(config.Limits.TopicLen))
  1108. if config.Server.Casemapping == CasemappingPRECIS {
  1109. isupport.Add("UTF8MAPPING", precisUTF8MappingToken)
  1110. }
  1111. isupport.Add("WHOX", "")
  1112. err = isupport.RegenerateCachedReply()
  1113. return
  1114. }
  1115. // Diff returns changes in supported caps across a rehash.
  1116. func (config *Config) Diff(oldConfig *Config) (addedCaps, removedCaps *caps.Set) {
  1117. addedCaps = caps.NewSet()
  1118. removedCaps = caps.NewSet()
  1119. if oldConfig == nil {
  1120. return
  1121. }
  1122. if oldConfig.Server.capValues[caps.Languages] != config.Server.capValues[caps.Languages] {
  1123. // XXX updated caps get a DEL line and then a NEW line with the new value
  1124. addedCaps.Add(caps.Languages)
  1125. removedCaps.Add(caps.Languages)
  1126. }
  1127. if !oldConfig.Accounts.AuthenticationEnabled && config.Accounts.AuthenticationEnabled {
  1128. addedCaps.Add(caps.SASL)
  1129. } else if oldConfig.Accounts.AuthenticationEnabled && !config.Accounts.AuthenticationEnabled {
  1130. removedCaps.Add(caps.SASL)
  1131. }
  1132. if oldConfig.Limits.Multiline.MaxBytes != 0 && config.Limits.Multiline.MaxBytes == 0 {
  1133. removedCaps.Add(caps.Multiline)
  1134. } else if oldConfig.Limits.Multiline.MaxBytes == 0 && config.Limits.Multiline.MaxBytes != 0 {
  1135. addedCaps.Add(caps.Multiline)
  1136. } else if oldConfig.Limits.Multiline != config.Limits.Multiline {
  1137. removedCaps.Add(caps.Multiline)
  1138. addedCaps.Add(caps.Multiline)
  1139. }
  1140. if oldConfig.Server.STS.Enabled != config.Server.STS.Enabled || oldConfig.Server.capValues[caps.STS] != config.Server.capValues[caps.STS] {
  1141. // XXX: STS is always removed by CAP NEW sts=duration=0, not CAP DEL
  1142. // so the appropriate notify is always a CAP NEW; put it in addedCaps for any change
  1143. addedCaps.Add(caps.STS)
  1144. }
  1145. return
  1146. }
  1147. // determine whether we need to resize / create / destroy
  1148. // the in-memory history buffers:
  1149. func (config *Config) historyChangedFrom(oldConfig *Config) bool {
  1150. return config.History.Enabled != oldConfig.History.Enabled ||
  1151. config.History.ChannelLength != oldConfig.History.ChannelLength ||
  1152. config.History.ClientLength != oldConfig.History.ClientLength ||
  1153. config.History.AutoresizeWindow != oldConfig.History.AutoresizeWindow ||
  1154. config.History.Persistent != oldConfig.History.Persistent
  1155. }
  1156. func compileGuestRegexp(guestFormat string, casemapping Casemapping) (standard, folded *regexp.Regexp, err error) {
  1157. if strings.Count(guestFormat, "?") != 0 || strings.Count(guestFormat, "*") != 1 {
  1158. err = errors.New("guest format must contain 1 '*' and no '?'s")
  1159. return
  1160. }
  1161. standard, err = utils.CompileGlob(guestFormat, true)
  1162. if err != nil {
  1163. return
  1164. }
  1165. starIndex := strings.IndexByte(guestFormat, '*')
  1166. initial := guestFormat[:starIndex]
  1167. final := guestFormat[starIndex+1:]
  1168. initialFolded, err := casefoldWithSetting(initial, casemapping)
  1169. if err != nil {
  1170. return
  1171. }
  1172. finalFolded, err := casefoldWithSetting(final, casemapping)
  1173. if err != nil {
  1174. return
  1175. }
  1176. folded, err = utils.CompileGlob(fmt.Sprintf("%s*%s", initialFolded, finalFolded), false)
  1177. return
  1178. }
  1179. func (config *Config) loadMOTD() error {
  1180. if config.Server.MOTD != "" {
  1181. file, err := os.Open(config.Server.MOTD)
  1182. if err != nil {
  1183. return err
  1184. }
  1185. defer file.Close()
  1186. contents, err := ioutil.ReadAll(file)
  1187. if err != nil {
  1188. return err
  1189. }
  1190. lines := bytes.Split(contents, []byte{'\n'})
  1191. for i, line := range lines {
  1192. lineToSend := string(bytes.TrimRight(line, "\r\n"))
  1193. if len(lineToSend) == 0 && i == len(lines)-1 {
  1194. // if the last line of the MOTD was properly terminated with \n,
  1195. // there's no need to send a blank line to clients
  1196. continue
  1197. }
  1198. if config.Server.MOTDFormatting {
  1199. lineToSend = ircfmt.Unescape(lineToSend)
  1200. }
  1201. // "- " is the required prefix for MOTD
  1202. lineToSend = fmt.Sprintf("- %s", lineToSend)
  1203. config.Server.motdLines = append(config.Server.motdLines, lineToSend)
  1204. }
  1205. }
  1206. return nil
  1207. }