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

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