Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

config.go 54KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768
  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. "crypto/x509"
  10. "errors"
  11. "fmt"
  12. "io"
  13. "log"
  14. "net"
  15. "os"
  16. "path/filepath"
  17. "reflect"
  18. "regexp"
  19. "runtime"
  20. "strconv"
  21. "strings"
  22. "time"
  23. "code.cloudfoundry.org/bytefmt"
  24. "github.com/ergochat/irc-go/ircfmt"
  25. "gopkg.in/yaml.v2"
  26. "github.com/ergochat/ergo/irc/caps"
  27. "github.com/ergochat/ergo/irc/cloaks"
  28. "github.com/ergochat/ergo/irc/connection_limits"
  29. "github.com/ergochat/ergo/irc/custime"
  30. "github.com/ergochat/ergo/irc/email"
  31. "github.com/ergochat/ergo/irc/isupport"
  32. "github.com/ergochat/ergo/irc/jwt"
  33. "github.com/ergochat/ergo/irc/languages"
  34. "github.com/ergochat/ergo/irc/logger"
  35. "github.com/ergochat/ergo/irc/modes"
  36. "github.com/ergochat/ergo/irc/mysql"
  37. "github.com/ergochat/ergo/irc/passwd"
  38. "github.com/ergochat/ergo/irc/utils"
  39. )
  40. // here's how this works: exported (capitalized) members of the config structs
  41. // are defined in the YAML file and deserialized directly from there. They may
  42. // be postprocessed and overwritten by LoadConfig. Unexported (lowercase) members
  43. // are derived from the exported members in LoadConfig.
  44. // TLSListenConfig defines configuration options for listening on TLS.
  45. type TLSListenConfig struct {
  46. Cert string
  47. Key string
  48. Proxy bool // XXX: legacy key: it's preferred to specify this directly in listenerConfigBlock
  49. }
  50. // This is the YAML-deserializable type of the value of the `Server.Listeners` map
  51. type listenerConfigBlock struct {
  52. // normal TLS configuration, with a single certificate:
  53. TLS TLSListenConfig
  54. // SNI configuration, with multiple certificates:
  55. TLSCertificates []TLSListenConfig `yaml:"tls-certificates"`
  56. MinTLSVersion string `yaml:"min-tls-version"`
  57. Proxy bool
  58. Tor bool
  59. STSOnly bool `yaml:"sts-only"`
  60. WebSocket bool
  61. HideSTS bool `yaml:"hide-sts"`
  62. }
  63. type HistoryCutoff uint
  64. const (
  65. HistoryCutoffDefault HistoryCutoff = iota
  66. HistoryCutoffNone
  67. HistoryCutoffRegistrationTime
  68. HistoryCutoffJoinTime
  69. )
  70. func historyCutoffToString(restriction HistoryCutoff) string {
  71. switch restriction {
  72. case HistoryCutoffDefault:
  73. return "default"
  74. case HistoryCutoffNone:
  75. return "none"
  76. case HistoryCutoffRegistrationTime:
  77. return "registration-time"
  78. case HistoryCutoffJoinTime:
  79. return "join-time"
  80. default:
  81. return ""
  82. }
  83. }
  84. func historyCutoffFromString(str string) (result HistoryCutoff, err error) {
  85. switch strings.ToLower(str) {
  86. case "default":
  87. return HistoryCutoffDefault, nil
  88. case "none", "disabled", "off", "false":
  89. return HistoryCutoffNone, nil
  90. case "registration-time":
  91. return HistoryCutoffRegistrationTime, nil
  92. case "join-time":
  93. return HistoryCutoffJoinTime, nil
  94. default:
  95. return HistoryCutoffDefault, errInvalidParams
  96. }
  97. }
  98. type PersistentStatus uint
  99. const (
  100. PersistentUnspecified PersistentStatus = iota
  101. PersistentDisabled
  102. PersistentOptIn
  103. PersistentOptOut
  104. PersistentMandatory
  105. )
  106. func persistentStatusToString(status PersistentStatus) string {
  107. switch status {
  108. case PersistentUnspecified:
  109. return "default"
  110. case PersistentDisabled:
  111. return "disabled"
  112. case PersistentOptIn:
  113. return "opt-in"
  114. case PersistentOptOut:
  115. return "opt-out"
  116. case PersistentMandatory:
  117. return "mandatory"
  118. default:
  119. return ""
  120. }
  121. }
  122. func persistentStatusFromString(status string) (PersistentStatus, error) {
  123. switch strings.ToLower(status) {
  124. case "default":
  125. return PersistentUnspecified, nil
  126. case "":
  127. return PersistentDisabled, nil
  128. case "opt-in":
  129. return PersistentOptIn, nil
  130. case "opt-out":
  131. return PersistentOptOut, nil
  132. case "mandatory":
  133. return PersistentMandatory, nil
  134. default:
  135. b, err := utils.StringToBool(status)
  136. if b {
  137. return PersistentMandatory, err
  138. } else {
  139. return PersistentDisabled, err
  140. }
  141. }
  142. }
  143. func (ps *PersistentStatus) UnmarshalYAML(unmarshal func(interface{}) error) error {
  144. var orig string
  145. var err error
  146. if err = unmarshal(&orig); err != nil {
  147. return err
  148. }
  149. result, err := persistentStatusFromString(orig)
  150. if err == nil {
  151. if result == PersistentUnspecified {
  152. result = PersistentDisabled
  153. }
  154. *ps = result
  155. } else {
  156. err = fmt.Errorf("invalid value `%s` for server persistence status: %w", orig, err)
  157. }
  158. return err
  159. }
  160. func persistenceEnabled(serverSetting, clientSetting PersistentStatus) (enabled bool) {
  161. if serverSetting == PersistentDisabled {
  162. return false
  163. } else if serverSetting == PersistentMandatory {
  164. return true
  165. } else if clientSetting == PersistentDisabled {
  166. return false
  167. } else if clientSetting == PersistentMandatory {
  168. return true
  169. } else if serverSetting == PersistentOptOut {
  170. return true
  171. } else {
  172. return false
  173. }
  174. }
  175. type HistoryStatus uint
  176. const (
  177. HistoryDefault HistoryStatus = iota
  178. HistoryDisabled
  179. HistoryEphemeral
  180. HistoryPersistent
  181. )
  182. func historyStatusFromString(str string) (status HistoryStatus, err error) {
  183. switch strings.ToLower(str) {
  184. case "default":
  185. return HistoryDefault, nil
  186. case "ephemeral":
  187. return HistoryEphemeral, nil
  188. case "persistent":
  189. return HistoryPersistent, nil
  190. default:
  191. b, err := utils.StringToBool(str)
  192. if b {
  193. return HistoryPersistent, err
  194. } else {
  195. return HistoryDisabled, err
  196. }
  197. }
  198. }
  199. func historyStatusToString(status HistoryStatus) string {
  200. switch status {
  201. case HistoryDefault:
  202. return "default"
  203. case HistoryDisabled:
  204. return "disabled"
  205. case HistoryEphemeral:
  206. return "ephemeral"
  207. case HistoryPersistent:
  208. return "persistent"
  209. default:
  210. return ""
  211. }
  212. }
  213. // XXX you must have already checked History.Enabled before calling this
  214. func historyEnabled(serverSetting PersistentStatus, localSetting HistoryStatus) (result HistoryStatus) {
  215. switch serverSetting {
  216. case PersistentMandatory:
  217. return HistoryPersistent
  218. case PersistentOptOut:
  219. if localSetting == HistoryDefault {
  220. return HistoryPersistent
  221. } else {
  222. return localSetting
  223. }
  224. case PersistentOptIn:
  225. switch localSetting {
  226. case HistoryPersistent:
  227. return HistoryPersistent
  228. case HistoryEphemeral, HistoryDefault:
  229. return HistoryEphemeral
  230. default:
  231. return HistoryDisabled
  232. }
  233. case PersistentDisabled:
  234. if localSetting == HistoryDisabled {
  235. return HistoryDisabled
  236. } else {
  237. return HistoryEphemeral
  238. }
  239. default:
  240. // PersistentUnspecified: shouldn't happen because the deserializer converts it
  241. // to PersistentDisabled
  242. if localSetting == HistoryDefault {
  243. return HistoryEphemeral
  244. } else {
  245. return localSetting
  246. }
  247. }
  248. }
  249. type MulticlientConfig struct {
  250. Enabled bool
  251. AllowedByDefault bool `yaml:"allowed-by-default"`
  252. AlwaysOn PersistentStatus `yaml:"always-on"`
  253. AutoAway PersistentStatus `yaml:"auto-away"`
  254. AlwaysOnExpiration custime.Duration `yaml:"always-on-expiration"`
  255. }
  256. type throttleConfig struct {
  257. Enabled bool
  258. Duration time.Duration
  259. MaxAttempts int `yaml:"max-attempts"`
  260. }
  261. type ThrottleConfig struct {
  262. throttleConfig
  263. }
  264. func (t *ThrottleConfig) UnmarshalYAML(unmarshal func(interface{}) error) (err error) {
  265. // note that this technique only works if the zero value of the struct
  266. // doesn't need any postprocessing (because if the field is omitted entirely
  267. // from the YAML, then UnmarshalYAML won't be called at all)
  268. if err = unmarshal(&t.throttleConfig); err != nil {
  269. return
  270. }
  271. if !t.Enabled {
  272. t.MaxAttempts = 0 // limit of 0 means disabled
  273. }
  274. return
  275. }
  276. type MetadataKeyConfig struct {
  277. AllowedKeys []string `yaml:"allowed-keys"`
  278. AllowedKeysMatcher *regexp.Regexp
  279. BlockedKeys []string `yaml:"blocked-keys"`
  280. BlockedKeysMatcher *regexp.Regexp
  281. RestrictedKeys []string `yaml:"restricted-keys"`
  282. RestrictedKeysMatcher *regexp.Regexp
  283. }
  284. func (mkc *MetadataKeyConfig) compileMatchers() (err error) {
  285. mkc.AllowedKeysMatcher, err = utils.CompileMasks(mkc.AllowedKeys)
  286. if err != nil {
  287. err = errors.New("allowed-keys")
  288. }
  289. mkc.BlockedKeysMatcher, err = utils.CompileMasks(mkc.BlockedKeys)
  290. if err != nil {
  291. err = errors.New("blocked-keys")
  292. }
  293. mkc.RestrictedKeysMatcher, err = utils.CompileMasks(mkc.RestrictedKeys)
  294. if err != nil {
  295. err = errors.New("restricted-keys")
  296. }
  297. return err
  298. }
  299. type MetadataConfig struct {
  300. MaxKeys int `yaml:"max-keys"`
  301. MaxSubs int `yaml:"max-subs"`
  302. Users MetadataKeyConfig
  303. Channels MetadataKeyConfig
  304. }
  305. type AccountConfig struct {
  306. Registration AccountRegistrationConfig
  307. AuthenticationEnabled bool `yaml:"authentication-enabled"`
  308. AdvertiseSCRAM bool `yaml:"advertise-scram"` // undocumented, see #1782
  309. RequireSasl struct {
  310. Enabled bool
  311. Exempted []string
  312. exemptedNets []net.IPNet
  313. } `yaml:"require-sasl"`
  314. DefaultUserModes *string `yaml:"default-user-modes"`
  315. defaultUserModes modes.Modes
  316. LoginThrottling ThrottleConfig `yaml:"login-throttling"`
  317. SkipServerPassword bool `yaml:"skip-server-password"`
  318. LoginViaPassCommand bool `yaml:"login-via-pass-command"`
  319. NickReservation struct {
  320. Enabled bool
  321. AdditionalNickLimit int `yaml:"additional-nick-limit"`
  322. Method NickEnforcementMethod
  323. AllowCustomEnforcement bool `yaml:"allow-custom-enforcement"`
  324. // RenamePrefix is the legacy field, GuestFormat is the new version
  325. RenamePrefix string `yaml:"rename-prefix"`
  326. GuestFormat string `yaml:"guest-nickname-format"`
  327. guestRegexp *regexp.Regexp
  328. guestRegexpFolded *regexp.Regexp
  329. ForceGuestFormat bool `yaml:"force-guest-format"`
  330. ForceNickEqualsAccount bool `yaml:"force-nick-equals-account"`
  331. ForbidAnonNickChanges bool `yaml:"forbid-anonymous-nick-changes"`
  332. } `yaml:"nick-reservation"`
  333. Multiclient MulticlientConfig
  334. Bouncer *MulticlientConfig // # handle old name for 'multiclient'
  335. VHosts VHostConfig
  336. AuthScript AuthScriptConfig `yaml:"auth-script"`
  337. }
  338. type ScriptConfig struct {
  339. Enabled bool
  340. Command string
  341. Args []string
  342. Timeout time.Duration
  343. KillTimeout time.Duration `yaml:"kill-timeout"`
  344. MaxConcurrency uint `yaml:"max-concurrency"`
  345. }
  346. type AuthScriptConfig struct {
  347. ScriptConfig `yaml:",inline"`
  348. Autocreate bool
  349. }
  350. // AccountRegistrationConfig controls account registration.
  351. type AccountRegistrationConfig struct {
  352. Enabled bool
  353. AllowBeforeConnect bool `yaml:"allow-before-connect"`
  354. Throttling ThrottleConfig
  355. // new-style (v2.4 email verification config):
  356. EmailVerification email.MailtoConfig `yaml:"email-verification"`
  357. // old-style email verification config, with "callbacks":
  358. LegacyEnabledCallbacks []string `yaml:"enabled-callbacks"`
  359. LegacyCallbacks struct {
  360. Mailto email.MailtoConfig
  361. } `yaml:"callbacks"`
  362. VerifyTimeout custime.Duration `yaml:"verify-timeout"`
  363. BcryptCost uint `yaml:"bcrypt-cost"`
  364. }
  365. type VHostConfig struct {
  366. Enabled bool
  367. MaxLength int `yaml:"max-length"`
  368. ValidRegexpRaw string `yaml:"valid-regexp"`
  369. validRegexp *regexp.Regexp
  370. }
  371. type NickEnforcementMethod int
  372. const (
  373. // NickEnforcementOptional is the zero value; it serializes to
  374. // "optional" in the yaml config, and "default" as an arg to `NS ENFORCE`.
  375. // in both cases, it means "defer to the other source of truth", i.e.,
  376. // in the config, defer to the user's custom setting, and as a custom setting,
  377. // defer to the default in the config. if both are NickEnforcementOptional then
  378. // there is no enforcement.
  379. // XXX: these are serialized as numbers in the database, so beware of collisions
  380. // when refactoring (any numbers currently in use must keep their meanings, or
  381. // else be fixed up by a schema change)
  382. NickEnforcementOptional NickEnforcementMethod = iota
  383. NickEnforcementNone
  384. NickEnforcementStrict
  385. )
  386. func nickReservationToString(method NickEnforcementMethod) string {
  387. switch method {
  388. case NickEnforcementOptional:
  389. return "default"
  390. case NickEnforcementNone:
  391. return "none"
  392. case NickEnforcementStrict:
  393. return "strict"
  394. default:
  395. return ""
  396. }
  397. }
  398. func nickReservationFromString(method string) (NickEnforcementMethod, error) {
  399. switch strings.ToLower(method) {
  400. case "default":
  401. return NickEnforcementOptional, nil
  402. case "optional":
  403. return NickEnforcementOptional, nil
  404. case "none":
  405. return NickEnforcementNone, nil
  406. case "strict":
  407. return NickEnforcementStrict, nil
  408. default:
  409. return NickEnforcementOptional, fmt.Errorf("invalid nick-reservation.method value: %s", method)
  410. }
  411. }
  412. func (nr *NickEnforcementMethod) UnmarshalYAML(unmarshal func(interface{}) error) error {
  413. var orig string
  414. var err error
  415. if err = unmarshal(&orig); err != nil {
  416. return err
  417. }
  418. method, err := nickReservationFromString(orig)
  419. if err == nil {
  420. *nr = method
  421. } else {
  422. err = fmt.Errorf("invalid value `%s` for nick enforcement method: %w", orig, err)
  423. }
  424. return err
  425. }
  426. func (cm *Casemapping) UnmarshalYAML(unmarshal func(interface{}) error) (err error) {
  427. var orig string
  428. if err = unmarshal(&orig); err != nil {
  429. return err
  430. }
  431. var result Casemapping
  432. switch strings.ToLower(orig) {
  433. case "ascii":
  434. result = CasemappingASCII
  435. case "precis", "rfc7613", "rfc8265":
  436. result = CasemappingPRECIS
  437. case "permissive", "fun":
  438. result = CasemappingPermissive
  439. default:
  440. return fmt.Errorf("invalid casemapping value: %s", orig)
  441. }
  442. *cm = result
  443. return nil
  444. }
  445. // OperClassConfig defines a specific operator class.
  446. type OperClassConfig struct {
  447. Title string
  448. WhoisLine string
  449. Extends string
  450. Capabilities []string
  451. }
  452. // OperConfig defines a specific operator's configuration.
  453. type OperConfig struct {
  454. Class string
  455. Vhost string
  456. WhoisLine string `yaml:"whois-line"`
  457. Password string
  458. Fingerprint *string // legacy name for certfp, #1050
  459. Certfp string
  460. Auto bool
  461. Hidden bool
  462. Modes string
  463. }
  464. // Various server-enforced limits on data size.
  465. type Limits struct {
  466. AwayLen int `yaml:"awaylen"`
  467. ChanListModes int `yaml:"chan-list-modes"`
  468. ChannelLen int `yaml:"channellen"`
  469. IdentLen int `yaml:"identlen"`
  470. KickLen int `yaml:"kicklen"`
  471. MonitorEntries int `yaml:"monitor-entries"`
  472. NickLen int `yaml:"nicklen"`
  473. TopicLen int `yaml:"topiclen"`
  474. WhowasEntries int `yaml:"whowas-entries"`
  475. RegistrationMessages int `yaml:"registration-messages"`
  476. Multiline struct {
  477. MaxBytes int `yaml:"max-bytes"`
  478. MaxLines int `yaml:"max-lines"`
  479. }
  480. }
  481. // STSConfig controls the STS configuration/
  482. type STSConfig struct {
  483. Enabled bool
  484. Duration custime.Duration
  485. Port int
  486. Preload bool
  487. STSOnlyBanner string `yaml:"sts-only-banner"`
  488. bannerLines []string
  489. }
  490. // Value returns the STS value to advertise in CAP
  491. func (sts *STSConfig) Value() string {
  492. val := fmt.Sprintf("duration=%d", int(time.Duration(sts.Duration).Seconds()))
  493. if sts.Enabled && sts.Port > 0 {
  494. val += fmt.Sprintf(",port=%d", sts.Port)
  495. }
  496. if sts.Enabled && sts.Preload {
  497. val += ",preload"
  498. }
  499. return val
  500. }
  501. type FakelagConfig struct {
  502. Enabled bool
  503. Window time.Duration
  504. BurstLimit uint `yaml:"burst-limit"`
  505. MessagesPerWindow uint `yaml:"messages-per-window"`
  506. Cooldown time.Duration
  507. }
  508. type TorListenersConfig struct {
  509. Listeners []string // legacy only
  510. RequireSasl bool `yaml:"require-sasl"`
  511. Vhost string
  512. MaxConnections int `yaml:"max-connections"`
  513. ThrottleDuration time.Duration `yaml:"throttle-duration"`
  514. MaxConnectionsPerDuration int `yaml:"max-connections-per-duration"`
  515. }
  516. // Config defines the overall configuration.
  517. type Config struct {
  518. AllowEnvironmentOverrides bool `yaml:"allow-environment-overrides"`
  519. Network struct {
  520. Name string
  521. }
  522. Server struct {
  523. Password string
  524. passwordBytes []byte
  525. Name string
  526. nameCasefolded string
  527. Listeners map[string]listenerConfigBlock
  528. UnixBindMode os.FileMode `yaml:"unix-bind-mode"`
  529. TorListeners TorListenersConfig `yaml:"tor-listeners"`
  530. WebSockets struct {
  531. AllowedOrigins []string `yaml:"allowed-origins"`
  532. allowedOriginRegexps []*regexp.Regexp
  533. }
  534. // they get parsed into this internal representation:
  535. trueListeners map[string]utils.ListenerConfig
  536. STS STSConfig
  537. LookupHostnames *bool `yaml:"lookup-hostnames"`
  538. lookupHostnames bool
  539. ForwardConfirmHostnames bool `yaml:"forward-confirm-hostnames"`
  540. CheckIdent bool `yaml:"check-ident"`
  541. CoerceIdent string `yaml:"coerce-ident"`
  542. MOTD string
  543. motdLines []string
  544. MOTDFormatting bool `yaml:"motd-formatting"`
  545. Relaymsg struct {
  546. Enabled bool
  547. Separators string
  548. AvailableToChanops bool `yaml:"available-to-chanops"`
  549. }
  550. ProxyAllowedFrom []string `yaml:"proxy-allowed-from"`
  551. proxyAllowedFromNets []net.IPNet
  552. WebIRC []webircConfig `yaml:"webirc"`
  553. MaxSendQString string `yaml:"max-sendq"`
  554. MaxSendQBytes int
  555. Compatibility struct {
  556. ForceTrailing *bool `yaml:"force-trailing"`
  557. forceTrailing bool
  558. SendUnprefixedSasl bool `yaml:"send-unprefixed-sasl"`
  559. AllowTruncation *bool `yaml:"allow-truncation"`
  560. allowTruncation bool
  561. }
  562. isupport isupport.List
  563. IPLimits connection_limits.LimiterConfig `yaml:"ip-limits"`
  564. Cloaks cloaks.CloakConfig `yaml:"ip-cloaking"`
  565. SecureNetDefs []string `yaml:"secure-nets"`
  566. secureNets []net.IPNet
  567. supportedCaps *caps.Set
  568. supportedCapsWithoutSTS *caps.Set
  569. capValues caps.Values
  570. Casemapping Casemapping
  571. EnforceUtf8 bool `yaml:"enforce-utf8"`
  572. OutputPath string `yaml:"output-path"`
  573. IPCheckScript ScriptConfig `yaml:"ip-check-script"`
  574. OverrideServicesHostname string `yaml:"override-services-hostname"`
  575. MaxLineLen int `yaml:"max-line-len"`
  576. }
  577. Roleplay struct {
  578. Enabled bool
  579. RequireChanops bool `yaml:"require-chanops"`
  580. RequireOper bool `yaml:"require-oper"`
  581. AddSuffix *bool `yaml:"add-suffix"`
  582. addSuffix bool
  583. }
  584. Extjwt struct {
  585. Default jwt.JwtServiceConfig `yaml:",inline"`
  586. Services map[string]jwt.JwtServiceConfig `yaml:"services"`
  587. }
  588. Languages struct {
  589. Enabled bool
  590. Path string
  591. Default string
  592. }
  593. languageManager *languages.Manager
  594. Datastore struct {
  595. Path string
  596. AutoUpgrade bool
  597. MySQL mysql.Config
  598. }
  599. Metadata MetadataConfig
  600. Accounts AccountConfig
  601. Channels struct {
  602. DefaultModes *string `yaml:"default-modes"`
  603. defaultModes modes.Modes
  604. MaxChannelsPerClient int `yaml:"max-channels-per-client"`
  605. OpOnlyCreation bool `yaml:"operator-only-creation"`
  606. Registration struct {
  607. Enabled bool
  608. OperatorOnly bool `yaml:"operator-only"`
  609. MaxChannelsPerAccount int `yaml:"max-channels-per-account"`
  610. }
  611. ListDelay time.Duration `yaml:"list-delay"`
  612. InviteExpiration custime.Duration `yaml:"invite-expiration"`
  613. }
  614. OperClasses map[string]*OperClassConfig `yaml:"oper-classes"`
  615. Opers map[string]*OperConfig
  616. // parsed operator definitions, unexported so they can't be defined
  617. // directly in YAML:
  618. operators map[string]*Oper
  619. Logging []logger.LoggingConfig
  620. Debug struct {
  621. RecoverFromErrors *bool `yaml:"recover-from-errors"`
  622. recoverFromErrors bool
  623. PprofListener *string `yaml:"pprof-listener"`
  624. }
  625. Limits Limits
  626. Fakelag FakelagConfig
  627. History struct {
  628. Enabled bool
  629. ChannelLength int `yaml:"channel-length"`
  630. ClientLength int `yaml:"client-length"`
  631. AutoresizeWindow custime.Duration `yaml:"autoresize-window"`
  632. AutoreplayOnJoin int `yaml:"autoreplay-on-join"`
  633. ChathistoryMax int `yaml:"chathistory-maxmessages"`
  634. ZNCMax int `yaml:"znc-maxmessages"`
  635. Restrictions struct {
  636. ExpireTime custime.Duration `yaml:"expire-time"`
  637. // legacy key, superceded by QueryCutoff:
  638. EnforceRegistrationDate_ bool `yaml:"enforce-registration-date"`
  639. QueryCutoff string `yaml:"query-cutoff"`
  640. queryCutoff HistoryCutoff
  641. GracePeriod custime.Duration `yaml:"grace-period"`
  642. }
  643. Persistent struct {
  644. Enabled bool
  645. UnregisteredChannels bool `yaml:"unregistered-channels"`
  646. RegisteredChannels PersistentStatus `yaml:"registered-channels"`
  647. DirectMessages PersistentStatus `yaml:"direct-messages"`
  648. }
  649. Retention struct {
  650. AllowIndividualDelete bool `yaml:"allow-individual-delete"`
  651. EnableAccountIndexing bool `yaml:"enable-account-indexing"`
  652. }
  653. TagmsgStorage struct {
  654. Default bool
  655. Whitelist []string
  656. Blacklist []string
  657. } `yaml:"tagmsg-storage"`
  658. }
  659. Filename string
  660. }
  661. // OperClass defines an assembled operator class.
  662. type OperClass struct {
  663. Title string
  664. WhoisLine string `yaml:"whois-line"`
  665. Capabilities utils.StringSet // map to make lookups much easier
  666. }
  667. // OperatorClasses returns a map of assembled operator classes from the given config.
  668. func (conf *Config) OperatorClasses() (map[string]*OperClass, error) {
  669. fixupCapability := func(capab string) string {
  670. return strings.TrimPrefix(strings.TrimPrefix(capab, "oper:"), "local_") // #868, #1442
  671. }
  672. ocs := make(map[string]*OperClass)
  673. // loop from no extends to most extended, breaking if we can't add any more
  674. lenOfLastOcs := -1
  675. for {
  676. if lenOfLastOcs == len(ocs) {
  677. return nil, errors.New("OperClasses contains a looping dependency, or a class extends from a class that doesn't exist")
  678. }
  679. lenOfLastOcs = len(ocs)
  680. var anyMissing bool
  681. for name, info := range conf.OperClasses {
  682. _, exists := ocs[name]
  683. _, extendsExists := ocs[info.Extends]
  684. if exists {
  685. // class already exists
  686. continue
  687. } else if len(info.Extends) > 0 && !extendsExists {
  688. // class we extend on doesn't exist
  689. _, exists := conf.OperClasses[info.Extends]
  690. if !exists {
  691. return nil, fmt.Errorf("Operclass [%s] extends [%s], which doesn't exist", name, info.Extends)
  692. }
  693. anyMissing = true
  694. continue
  695. }
  696. // create new operclass
  697. var oc OperClass
  698. oc.Capabilities = make(utils.StringSet)
  699. // get inhereted info from other operclasses
  700. if len(info.Extends) > 0 {
  701. einfo := ocs[info.Extends]
  702. for capab := range einfo.Capabilities {
  703. oc.Capabilities.Add(fixupCapability(capab))
  704. }
  705. }
  706. // add our own info
  707. oc.Title = info.Title
  708. if oc.Title == "" {
  709. oc.Title = "IRC operator"
  710. }
  711. for _, capab := range info.Capabilities {
  712. oc.Capabilities.Add(fixupCapability(capab))
  713. }
  714. if len(info.WhoisLine) > 0 {
  715. oc.WhoisLine = info.WhoisLine
  716. } else {
  717. oc.WhoisLine = "is a"
  718. if strings.Contains(strings.ToLower(string(oc.Title[0])), "aeiou") {
  719. oc.WhoisLine += "n"
  720. }
  721. oc.WhoisLine += " "
  722. oc.WhoisLine += oc.Title
  723. }
  724. ocs[name] = &oc
  725. }
  726. if !anyMissing {
  727. // we've got every operclass!
  728. break
  729. }
  730. }
  731. return ocs, nil
  732. }
  733. // Oper represents a single assembled operator's config.
  734. type Oper struct {
  735. Name string
  736. Class *OperClass
  737. WhoisLine string
  738. Vhost string
  739. Pass []byte
  740. Certfp string
  741. Auto bool
  742. Hidden bool
  743. Modes []modes.ModeChange
  744. }
  745. func (oper *Oper) HasRoleCapab(capab string) bool {
  746. return oper != nil && oper.Class.Capabilities.Has(capab)
  747. }
  748. // Operators returns a map of operator configs from the given OperClass and config.
  749. func (conf *Config) Operators(oc map[string]*OperClass) (map[string]*Oper, error) {
  750. operators := make(map[string]*Oper)
  751. for name, opConf := range conf.Opers {
  752. var oper Oper
  753. // oper name
  754. name, err := CasefoldName(name)
  755. if err != nil {
  756. return nil, fmt.Errorf("Could not casefold oper name: %s", err.Error())
  757. }
  758. oper.Name = name
  759. if opConf.Password != "" {
  760. oper.Pass, err = decodeLegacyPasswordHash(opConf.Password)
  761. if err != nil {
  762. return nil, fmt.Errorf("Oper %s has an invalid password hash: %s", oper.Name, err.Error())
  763. }
  764. }
  765. certfp := opConf.Certfp
  766. if certfp == "" && opConf.Fingerprint != nil {
  767. certfp = *opConf.Fingerprint
  768. }
  769. if certfp != "" {
  770. oper.Certfp, err = utils.NormalizeCertfp(certfp)
  771. if err != nil {
  772. return nil, fmt.Errorf("Oper %s has an invalid fingerprint: %s", oper.Name, err.Error())
  773. }
  774. }
  775. oper.Auto = opConf.Auto
  776. oper.Hidden = opConf.Hidden
  777. if oper.Pass == nil && oper.Certfp == "" {
  778. return nil, fmt.Errorf("Oper %s has neither a password nor a fingerprint", name)
  779. }
  780. oper.Vhost = opConf.Vhost
  781. if oper.Vhost != "" && !conf.Accounts.VHosts.validRegexp.MatchString(oper.Vhost) {
  782. return nil, fmt.Errorf("Oper %s has an invalid vhost: `%s`", name, oper.Vhost)
  783. }
  784. class, exists := oc[opConf.Class]
  785. if !exists {
  786. return nil, fmt.Errorf("Could not load operator [%s] - they use operclass [%s] which does not exist", name, opConf.Class)
  787. }
  788. oper.Class = class
  789. if len(opConf.WhoisLine) > 0 {
  790. oper.WhoisLine = opConf.WhoisLine
  791. } else {
  792. oper.WhoisLine = class.WhoisLine
  793. }
  794. modeStr := strings.TrimSpace(opConf.Modes)
  795. modeChanges, unknownChanges := modes.ParseUserModeChanges(strings.Split(modeStr, " ")...)
  796. if len(unknownChanges) > 0 {
  797. return nil, fmt.Errorf("Could not load operator [%s] due to unknown modes %v", name, unknownChanges)
  798. }
  799. oper.Modes = modeChanges
  800. // successful, attach to list of opers
  801. operators[name] = &oper
  802. }
  803. return operators, nil
  804. }
  805. func loadTlsConfig(config listenerConfigBlock) (tlsConfig *tls.Config, err error) {
  806. var certificates []tls.Certificate
  807. if len(config.TLSCertificates) != 0 {
  808. // SNI configuration with multiple certificates
  809. for _, certPairConf := range config.TLSCertificates {
  810. cert, err := loadCertWithLeaf(certPairConf.Cert, certPairConf.Key)
  811. if err != nil {
  812. return nil, err
  813. }
  814. certificates = append(certificates, cert)
  815. }
  816. } else if config.TLS.Cert != "" {
  817. // normal configuration with one certificate
  818. cert, err := loadCertWithLeaf(config.TLS.Cert, config.TLS.Key)
  819. if err != nil {
  820. return nil, err
  821. }
  822. certificates = append(certificates, cert)
  823. } else {
  824. // plaintext!
  825. return nil, nil
  826. }
  827. clientAuth := tls.RequestClientCert
  828. if config.WebSocket {
  829. // if Chrome receives a server request for a client certificate
  830. // on a websocket connection, it will immediately disconnect:
  831. // https://bugs.chromium.org/p/chromium/issues/detail?id=329884
  832. // work around this behavior:
  833. clientAuth = tls.NoClientCert
  834. }
  835. result := tls.Config{
  836. Certificates: certificates,
  837. ClientAuth: clientAuth,
  838. MinVersion: tlsMinVersionFromString(config.MinTLSVersion),
  839. }
  840. return &result, nil
  841. }
  842. func tlsMinVersionFromString(version string) uint16 {
  843. version = strings.ToLower(version)
  844. version = strings.TrimPrefix(version, "v")
  845. switch version {
  846. case "1", "1.0":
  847. return tls.VersionTLS10
  848. case "1.1":
  849. return tls.VersionTLS11
  850. case "1.2":
  851. return tls.VersionTLS12
  852. case "1.3":
  853. return tls.VersionTLS13
  854. default:
  855. // tls package will fill in a sane value, currently 1.0
  856. return 0
  857. }
  858. }
  859. func loadCertWithLeaf(certFile, keyFile string) (cert tls.Certificate, err error) {
  860. // LoadX509KeyPair: "On successful return, Certificate.Leaf will be nil because
  861. // the parsed form of the certificate is not retained." tls.Config:
  862. // "Note: if there are multiple Certificates, and they don't have the
  863. // optional field Leaf set, certificate selection will incur a significant
  864. // per-handshake performance cost."
  865. cert, err = tls.LoadX509KeyPair(certFile, keyFile)
  866. if err != nil {
  867. return
  868. }
  869. cert.Leaf, err = x509.ParseCertificate(cert.Certificate[0])
  870. return
  871. }
  872. // prepareListeners populates Config.Server.trueListeners
  873. func (conf *Config) prepareListeners() (err error) {
  874. if len(conf.Server.Listeners) == 0 {
  875. return fmt.Errorf("No listeners were configured")
  876. }
  877. conf.Server.trueListeners = make(map[string]utils.ListenerConfig)
  878. for addr, block := range conf.Server.Listeners {
  879. var lconf utils.ListenerConfig
  880. lconf.ProxyDeadline = RegisterTimeout
  881. lconf.Tor = block.Tor
  882. lconf.STSOnly = block.STSOnly
  883. if lconf.STSOnly && !conf.Server.STS.Enabled {
  884. return fmt.Errorf("%s is configured as a STS-only listener, but STS is disabled", addr)
  885. }
  886. lconf.TLSConfig, err = loadTlsConfig(block)
  887. if err != nil {
  888. return &CertKeyError{Err: err}
  889. }
  890. lconf.RequireProxy = block.TLS.Proxy || block.Proxy
  891. lconf.WebSocket = block.WebSocket
  892. if lconf.WebSocket && !conf.Server.EnforceUtf8 {
  893. return fmt.Errorf("enabling a websocket listener requires the use of server.enforce-utf8")
  894. }
  895. lconf.HideSTS = block.HideSTS
  896. conf.Server.trueListeners[addr] = lconf
  897. }
  898. return nil
  899. }
  900. func (config *Config) processExtjwt() (err error) {
  901. // first process the default service, which may be disabled
  902. err = config.Extjwt.Default.Postprocess()
  903. if err != nil {
  904. return
  905. }
  906. // now process the named services. it is an error if any is disabled
  907. // also, normalize the service names to lowercase
  908. services := make(map[string]jwt.JwtServiceConfig, len(config.Extjwt.Services))
  909. for service, sConf := range config.Extjwt.Services {
  910. err := sConf.Postprocess()
  911. if err != nil {
  912. return err
  913. }
  914. if !sConf.Enabled() {
  915. return fmt.Errorf("no keys enabled for extjwt service %s", service)
  916. }
  917. services[strings.ToLower(service)] = sConf
  918. }
  919. config.Extjwt.Services = services
  920. return nil
  921. }
  922. // LoadRawConfig loads the config without doing any consistency checks or postprocessing
  923. func LoadRawConfig(filename string) (config *Config, err error) {
  924. data, err := os.ReadFile(filename)
  925. if err != nil {
  926. return nil, err
  927. }
  928. err = yaml.Unmarshal(data, &config)
  929. if err != nil {
  930. return nil, err
  931. }
  932. return
  933. }
  934. // convert, e.g., "ALLOWED_ORIGINS" to "allowed-origins"
  935. func screamingSnakeToKebab(in string) (out string) {
  936. var buf strings.Builder
  937. for i := 0; i < len(in); i++ {
  938. c := in[i]
  939. switch {
  940. case c == '_':
  941. buf.WriteByte('-')
  942. case 'A' <= c && c <= 'Z':
  943. buf.WriteByte(c + ('a' - 'A'))
  944. default:
  945. buf.WriteByte(c)
  946. }
  947. }
  948. return buf.String()
  949. }
  950. func isExported(field reflect.StructField) bool {
  951. return field.PkgPath == "" // https://golang.org/pkg/reflect/#StructField
  952. }
  953. // errors caused by config overrides
  954. type configPathError struct {
  955. name string
  956. desc string
  957. fatalErr error
  958. }
  959. func (ce *configPathError) Error() string {
  960. if ce.fatalErr != nil {
  961. return fmt.Sprintf("Couldn't apply config override `%s`: %s: %v", ce.name, ce.desc, ce.fatalErr)
  962. }
  963. return fmt.Sprintf("Couldn't apply config override `%s`: %s", ce.name, ce.desc)
  964. }
  965. func mungeFromEnvironment(config *Config, envPair string) (applied bool, err *configPathError) {
  966. equalIdx := strings.IndexByte(envPair, '=')
  967. name, value := envPair[:equalIdx], envPair[equalIdx+1:]
  968. if strings.HasPrefix(name, "ERGO__") {
  969. name = strings.TrimPrefix(name, "ERGO__")
  970. } else if strings.HasPrefix(name, "ORAGONO__") {
  971. name = strings.TrimPrefix(name, "ORAGONO__")
  972. } else {
  973. return false, nil
  974. }
  975. pathComponents := strings.Split(name, "__")
  976. for i, pathComponent := range pathComponents {
  977. pathComponents[i] = screamingSnakeToKebab(pathComponent)
  978. }
  979. v := reflect.Indirect(reflect.ValueOf(config))
  980. t := v.Type()
  981. for _, component := range pathComponents {
  982. if component == "" {
  983. return false, &configPathError{name, "invalid", nil}
  984. }
  985. if v.Kind() != reflect.Struct {
  986. return false, &configPathError{name, "index into non-struct", nil}
  987. }
  988. var nextField reflect.StructField
  989. success := false
  990. n := t.NumField()
  991. // preferentially get a field with an exact yaml tag match,
  992. // then fall back to case-insensitive comparison of field names
  993. for i := 0; i < n; i++ {
  994. field := t.Field(i)
  995. if isExported(field) && field.Tag.Get("yaml") == component {
  996. nextField = field
  997. success = true
  998. break
  999. }
  1000. }
  1001. if !success {
  1002. for i := 0; i < n; i++ {
  1003. field := t.Field(i)
  1004. if isExported(field) && strings.ToLower(field.Name) == component {
  1005. nextField = field
  1006. success = true
  1007. break
  1008. }
  1009. }
  1010. }
  1011. if !success {
  1012. return false, &configPathError{name, fmt.Sprintf("couldn't resolve path component: `%s`", component), nil}
  1013. }
  1014. v = v.FieldByName(nextField.Name)
  1015. // dereference pointer field if necessary, initialize new value if necessary
  1016. if v.Kind() == reflect.Ptr {
  1017. if v.IsNil() {
  1018. v.Set(reflect.New(v.Type().Elem()))
  1019. }
  1020. v = reflect.Indirect(v)
  1021. }
  1022. t = v.Type()
  1023. }
  1024. yamlErr := yaml.Unmarshal([]byte(value), v.Addr().Interface())
  1025. if yamlErr != nil {
  1026. return false, &configPathError{name, "couldn't deserialize YAML", yamlErr}
  1027. }
  1028. return true, nil
  1029. }
  1030. // LoadConfig loads the given YAML configuration file.
  1031. func LoadConfig(filename string) (config *Config, err error) {
  1032. config, err = LoadRawConfig(filename)
  1033. if err != nil {
  1034. return nil, err
  1035. }
  1036. if config.AllowEnvironmentOverrides {
  1037. for _, envPair := range os.Environ() {
  1038. applied, envErr := mungeFromEnvironment(config, envPair)
  1039. if envErr != nil {
  1040. if envErr.fatalErr != nil {
  1041. return nil, envErr
  1042. } else {
  1043. log.Println(envErr.Error())
  1044. }
  1045. } else if applied {
  1046. log.Printf("applied environment override: %s\n", envPair)
  1047. }
  1048. }
  1049. }
  1050. config.Filename = filename
  1051. if config.Network.Name == "" {
  1052. return nil, errors.New("Network name missing")
  1053. }
  1054. if config.Server.Name == "" {
  1055. return nil, errors.New("Server name missing")
  1056. }
  1057. if !utils.IsServerName(config.Server.Name) {
  1058. return nil, errors.New("Server name must match the format of a hostname")
  1059. }
  1060. config.Server.nameCasefolded = strings.ToLower(config.Server.Name)
  1061. if config.Datastore.Path == "" {
  1062. return nil, errors.New("Datastore path missing")
  1063. }
  1064. //dan: automagically fix identlen until a few releases in the future (from now, 0.12.0), being a newly-introduced limit
  1065. if config.Limits.IdentLen < 1 {
  1066. config.Limits.IdentLen = 20
  1067. }
  1068. if config.Limits.NickLen < 1 || config.Limits.ChannelLen < 2 || config.Limits.AwayLen < 1 || config.Limits.KickLen < 1 || config.Limits.TopicLen < 1 {
  1069. return nil, errors.New("One or more limits values are too low")
  1070. }
  1071. if config.Limits.RegistrationMessages == 0 {
  1072. config.Limits.RegistrationMessages = 1024
  1073. }
  1074. if config.Server.MaxLineLen < DefaultMaxLineLen {
  1075. config.Server.MaxLineLen = DefaultMaxLineLen
  1076. }
  1077. if config.Datastore.MySQL.Enabled {
  1078. if config.Limits.NickLen > mysql.MaxTargetLength || config.Limits.ChannelLen > mysql.MaxTargetLength {
  1079. return nil, fmt.Errorf("to use MySQL, nick and channel length limits must be %d or lower", mysql.MaxTargetLength)
  1080. }
  1081. }
  1082. if config.Server.CoerceIdent != "" {
  1083. if config.Server.CheckIdent {
  1084. return nil, errors.New("Can't configure both check-ident and coerce-ident")
  1085. }
  1086. if config.Server.CoerceIdent[0] != '~' {
  1087. return nil, errors.New("coerce-ident value must start with a ~")
  1088. }
  1089. if !isIdent(config.Server.CoerceIdent[1:]) {
  1090. return nil, errors.New("coerce-ident must be valid as an IRC user/ident field")
  1091. }
  1092. }
  1093. config.Server.supportedCaps = caps.NewCompleteSet()
  1094. config.Server.capValues = make(caps.Values)
  1095. err = config.prepareListeners()
  1096. if err != nil {
  1097. return nil, fmt.Errorf("failed to prepare listeners: %v", err)
  1098. }
  1099. for _, glob := range config.Server.WebSockets.AllowedOrigins {
  1100. globre, err := utils.CompileGlob(glob, false)
  1101. if err != nil {
  1102. return nil, fmt.Errorf("invalid websocket allowed-origin expression: %s", glob)
  1103. }
  1104. config.Server.WebSockets.allowedOriginRegexps = append(config.Server.WebSockets.allowedOriginRegexps, globre)
  1105. }
  1106. if config.Server.STS.Enabled {
  1107. if config.Server.STS.Port < 0 || config.Server.STS.Port > 65535 {
  1108. return nil, fmt.Errorf("STS port is incorrect, should be 0 if disabled: %d", config.Server.STS.Port)
  1109. }
  1110. if config.Server.STS.STSOnlyBanner != "" {
  1111. for _, line := range strings.Split(config.Server.STS.STSOnlyBanner, "\n") {
  1112. config.Server.STS.bannerLines = append(config.Server.STS.bannerLines, strings.TrimSpace(line))
  1113. }
  1114. } else {
  1115. 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)}
  1116. }
  1117. } else {
  1118. config.Server.supportedCaps.Disable(caps.STS)
  1119. config.Server.STS.Duration = 0
  1120. }
  1121. // set this even if STS is disabled
  1122. config.Server.capValues[caps.STS] = config.Server.STS.Value()
  1123. config.Server.lookupHostnames = utils.BoolDefaultTrue(config.Server.LookupHostnames)
  1124. // process webirc blocks
  1125. var newWebIRC []webircConfig
  1126. for _, webirc := range config.Server.WebIRC {
  1127. // skip webirc blocks with no hosts (such as the example one)
  1128. if len(webirc.Hosts) == 0 {
  1129. continue
  1130. }
  1131. err = webirc.Populate()
  1132. if err != nil {
  1133. return nil, fmt.Errorf("Could not parse WebIRC config: %s", err.Error())
  1134. }
  1135. newWebIRC = append(newWebIRC, webirc)
  1136. }
  1137. config.Server.WebIRC = newWebIRC
  1138. if config.Limits.Multiline.MaxBytes <= 0 {
  1139. config.Server.supportedCaps.Disable(caps.Multiline)
  1140. } else {
  1141. var multilineCapValue string
  1142. if config.Limits.Multiline.MaxLines == 0 {
  1143. multilineCapValue = fmt.Sprintf("max-bytes=%d", config.Limits.Multiline.MaxBytes)
  1144. } else {
  1145. multilineCapValue = fmt.Sprintf("max-bytes=%d,max-lines=%d", config.Limits.Multiline.MaxBytes, config.Limits.Multiline.MaxLines)
  1146. }
  1147. config.Server.capValues[caps.Multiline] = multilineCapValue
  1148. }
  1149. // confirm that we don't have both allowed and blocked metadata keys set
  1150. config.Server.capValues[caps.Metadata] = fmt.Sprintf("maxsub=%d,maxkey=%d", config.Metadata.MaxSubs, config.Metadata.MaxKeys)
  1151. if len(config.Metadata.Users.AllowedKeys) > 0 && len(config.Metadata.Users.BlockedKeys) > 0 {
  1152. return nil, errors.New("You can only set either allowed-keys or blocked-keys in metadata.users, not both")
  1153. }
  1154. if len(config.Metadata.Channels.AllowedKeys) > 0 && len(config.Metadata.Channels.BlockedKeys) > 0 {
  1155. return nil, errors.New("You can only set either allowed-keys or blocked-keys in metadata.channels, not both")
  1156. }
  1157. err = config.Metadata.Users.compileMatchers()
  1158. if err != nil {
  1159. return nil, fmt.Errorf("Could not compile metadata.users.%s", err.Error())
  1160. }
  1161. err = config.Metadata.Channels.compileMatchers()
  1162. if err != nil {
  1163. return nil, fmt.Errorf("Could not compile metadata.channels.%s", err.Error())
  1164. }
  1165. // handle legacy name 'bouncer' for 'multiclient' section:
  1166. if config.Accounts.Bouncer != nil {
  1167. config.Accounts.Multiclient = *config.Accounts.Bouncer
  1168. }
  1169. if !config.Accounts.Multiclient.Enabled {
  1170. config.Accounts.Multiclient.AlwaysOn = PersistentDisabled
  1171. } else if config.Accounts.Multiclient.AlwaysOn >= PersistentOptOut {
  1172. config.Accounts.Multiclient.AllowedByDefault = true
  1173. }
  1174. if !config.Accounts.NickReservation.Enabled {
  1175. config.Accounts.NickReservation.ForceNickEqualsAccount = false
  1176. }
  1177. if config.Accounts.NickReservation.ForceNickEqualsAccount && !config.Accounts.Multiclient.Enabled {
  1178. return nil, errors.New("force-nick-equals-account requires enabling multiclient as well")
  1179. }
  1180. // handle guest format, including the legacy key rename-prefix
  1181. if config.Accounts.NickReservation.GuestFormat == "" {
  1182. renamePrefix := config.Accounts.NickReservation.RenamePrefix
  1183. if renamePrefix == "" {
  1184. renamePrefix = "Guest-"
  1185. }
  1186. config.Accounts.NickReservation.GuestFormat = renamePrefix + "*"
  1187. }
  1188. config.Accounts.NickReservation.guestRegexp, config.Accounts.NickReservation.guestRegexpFolded, err = compileGuestRegexp(config.Accounts.NickReservation.GuestFormat, config.Server.Casemapping)
  1189. if err != nil {
  1190. return nil, err
  1191. }
  1192. var newLogConfigs []logger.LoggingConfig
  1193. for _, logConfig := range config.Logging {
  1194. // methods
  1195. methods := make(map[string]bool)
  1196. for _, method := range strings.Split(logConfig.Method, " ") {
  1197. if len(method) > 0 {
  1198. methods[strings.ToLower(method)] = true
  1199. }
  1200. }
  1201. if methods["file"] && logConfig.Filename == "" {
  1202. return nil, errors.New("Logging configuration specifies 'file' method but 'filename' is empty")
  1203. }
  1204. logConfig.MethodFile = methods["file"]
  1205. logConfig.MethodStdout = methods["stdout"]
  1206. logConfig.MethodStderr = methods["stderr"]
  1207. // levels
  1208. level, exists := logger.LogLevelNames[strings.ToLower(logConfig.LevelString)]
  1209. if !exists {
  1210. return nil, fmt.Errorf("Could not translate log leve [%s]", logConfig.LevelString)
  1211. }
  1212. logConfig.Level = level
  1213. // types
  1214. for _, typeStr := range strings.Split(logConfig.TypeString, " ") {
  1215. if len(typeStr) == 0 {
  1216. continue
  1217. }
  1218. if typeStr == "-" {
  1219. return nil, errors.New("Encountered logging type '-' with no type to exclude")
  1220. }
  1221. if typeStr[0] == '-' {
  1222. typeStr = typeStr[1:]
  1223. logConfig.ExcludedTypes = append(logConfig.ExcludedTypes, typeStr)
  1224. } else {
  1225. logConfig.Types = append(logConfig.Types, typeStr)
  1226. }
  1227. }
  1228. if len(logConfig.Types) < 1 {
  1229. return nil, errors.New("Logger has no types to log")
  1230. }
  1231. newLogConfigs = append(newLogConfigs, logConfig)
  1232. }
  1233. config.Logging = newLogConfigs
  1234. if config.Accounts.Registration.EmailVerification.Enabled {
  1235. err := config.Accounts.Registration.EmailVerification.Postprocess(config.Server.Name)
  1236. if err != nil {
  1237. return nil, err
  1238. }
  1239. } else {
  1240. // TODO: this processes the legacy "callback" config, clean this up in 2.5 or later
  1241. // TODO: also clean up the legacy "inline" MTA config format (from ee05a4324dfde)
  1242. mailtoEnabled := false
  1243. for _, name := range config.Accounts.Registration.LegacyEnabledCallbacks {
  1244. if name == "mailto" {
  1245. mailtoEnabled = true
  1246. break
  1247. }
  1248. }
  1249. if mailtoEnabled {
  1250. config.Accounts.Registration.EmailVerification = config.Accounts.Registration.LegacyCallbacks.Mailto
  1251. config.Accounts.Registration.EmailVerification.Enabled = true
  1252. err := config.Accounts.Registration.EmailVerification.Postprocess(config.Server.Name)
  1253. if err != nil {
  1254. return nil, err
  1255. }
  1256. }
  1257. }
  1258. config.Accounts.defaultUserModes = ParseDefaultUserModes(config.Accounts.DefaultUserModes)
  1259. if config.Server.Password != "" {
  1260. config.Server.passwordBytes, err = decodeLegacyPasswordHash(config.Server.Password)
  1261. if err != nil {
  1262. return nil, err
  1263. }
  1264. if config.Accounts.LoginViaPassCommand && !config.Accounts.SkipServerPassword {
  1265. return nil, errors.New("Using a server password and login-via-pass-command requires skip-server-password as well")
  1266. }
  1267. // #1634: accounts.registration.allow-before-connect is an auth bypass
  1268. // for configurations that start from default and then enable server.password
  1269. config.Accounts.Registration.AllowBeforeConnect = false
  1270. }
  1271. if config.Accounts.RequireSasl.Enabled {
  1272. // minor gotcha: Tor listeners will typically be loopback and
  1273. // therefore exempted from require-sasl. if require-sasl is enabled
  1274. // for non-Tor (non-local) connections, enable it for Tor as well:
  1275. config.Server.TorListeners.RequireSasl = true
  1276. }
  1277. config.Accounts.RequireSasl.exemptedNets, err = utils.ParseNetList(config.Accounts.RequireSasl.Exempted)
  1278. if err != nil {
  1279. return nil, fmt.Errorf("Could not parse require-sasl exempted nets: %v", err.Error())
  1280. }
  1281. config.Server.proxyAllowedFromNets, err = utils.ParseNetList(config.Server.ProxyAllowedFrom)
  1282. if err != nil {
  1283. return nil, fmt.Errorf("Could not parse proxy-allowed-from nets: %v", err.Error())
  1284. }
  1285. config.Server.secureNets, err = utils.ParseNetList(config.Server.SecureNetDefs)
  1286. if err != nil {
  1287. return nil, fmt.Errorf("Could not parse secure-nets: %v\n", err.Error())
  1288. }
  1289. rawRegexp := config.Accounts.VHosts.ValidRegexpRaw
  1290. if rawRegexp != "" {
  1291. regexp, err := regexp.Compile(rawRegexp)
  1292. if err == nil {
  1293. config.Accounts.VHosts.validRegexp = regexp
  1294. } else {
  1295. log.Printf("invalid vhost regexp: %s\n", err.Error())
  1296. }
  1297. }
  1298. if config.Accounts.VHosts.validRegexp == nil {
  1299. config.Accounts.VHosts.validRegexp = defaultValidVhostRegex
  1300. }
  1301. saslCapValue := "PLAIN,EXTERNAL,SCRAM-SHA-256"
  1302. // TODO(#1782) clean this up:
  1303. if !config.Accounts.AdvertiseSCRAM {
  1304. saslCapValue = "PLAIN,EXTERNAL"
  1305. }
  1306. config.Server.capValues[caps.SASL] = saslCapValue
  1307. if !config.Accounts.AuthenticationEnabled {
  1308. config.Server.supportedCaps.Disable(caps.SASL)
  1309. }
  1310. if !config.Accounts.Registration.Enabled {
  1311. config.Server.supportedCaps.Disable(caps.AccountRegistration)
  1312. } else {
  1313. var registerValues []string
  1314. if config.Accounts.Registration.AllowBeforeConnect {
  1315. registerValues = append(registerValues, "before-connect")
  1316. }
  1317. if config.Accounts.Registration.EmailVerification.Enabled {
  1318. registerValues = append(registerValues, "email-required")
  1319. }
  1320. if config.Accounts.RequireSasl.Enabled {
  1321. registerValues = append(registerValues, "account-required")
  1322. }
  1323. if len(registerValues) != 0 {
  1324. config.Server.capValues[caps.AccountRegistration] = strings.Join(registerValues, ",")
  1325. }
  1326. }
  1327. maxSendQBytes, err := bytefmt.ToBytes(config.Server.MaxSendQString)
  1328. if err != nil {
  1329. return nil, fmt.Errorf("Could not parse maximum SendQ size (make sure it only contains whole numbers): %s", err.Error())
  1330. }
  1331. config.Server.MaxSendQBytes = int(maxSendQBytes)
  1332. config.languageManager, err = languages.NewManager(config.Languages.Enabled, config.Languages.Path, config.Languages.Default)
  1333. if err != nil {
  1334. return nil, fmt.Errorf("Could not load languages: %s", err.Error())
  1335. }
  1336. config.Server.capValues[caps.Languages] = config.languageManager.CapValue()
  1337. if config.Server.Relaymsg.Enabled {
  1338. for _, char := range protocolBreakingNameCharacters {
  1339. if strings.ContainsRune(config.Server.Relaymsg.Separators, char) {
  1340. return nil, fmt.Errorf("RELAYMSG separators cannot include the characters %s", protocolBreakingNameCharacters)
  1341. }
  1342. }
  1343. config.Server.capValues[caps.Relaymsg] = config.Server.Relaymsg.Separators
  1344. } else {
  1345. config.Server.supportedCaps.Disable(caps.Relaymsg)
  1346. }
  1347. config.Debug.recoverFromErrors = utils.BoolDefaultTrue(config.Debug.RecoverFromErrors)
  1348. // process operator definitions, store them to config.operators
  1349. operclasses, err := config.OperatorClasses()
  1350. if err != nil {
  1351. return nil, err
  1352. }
  1353. opers, err := config.Operators(operclasses)
  1354. if err != nil {
  1355. return nil, err
  1356. }
  1357. config.operators = opers
  1358. // parse default channel modes
  1359. config.Channels.defaultModes = ParseDefaultChannelModes(config.Channels.DefaultModes)
  1360. if config.Accounts.Registration.BcryptCost == 0 {
  1361. config.Accounts.Registration.BcryptCost = passwd.DefaultCost
  1362. }
  1363. if config.Channels.MaxChannelsPerClient == 0 {
  1364. config.Channels.MaxChannelsPerClient = 100
  1365. }
  1366. if config.Channels.Registration.MaxChannelsPerAccount == 0 {
  1367. config.Channels.Registration.MaxChannelsPerAccount = 15
  1368. }
  1369. config.Server.Compatibility.forceTrailing = utils.BoolDefaultTrue(config.Server.Compatibility.ForceTrailing)
  1370. config.Server.Compatibility.allowTruncation = utils.BoolDefaultTrue(config.Server.Compatibility.AllowTruncation)
  1371. config.loadMOTD()
  1372. // in the current implementation, we disable history by creating a history buffer
  1373. // with zero capacity. but the `enabled` config option MUST be respected regardless
  1374. // of this detail
  1375. if !config.History.Enabled {
  1376. config.History.ChannelLength = 0
  1377. config.History.ClientLength = 0
  1378. config.Server.supportedCaps.Disable(caps.Chathistory)
  1379. config.Server.supportedCaps.Disable(caps.EventPlayback)
  1380. config.Server.supportedCaps.Disable(caps.ZNCPlayback)
  1381. }
  1382. if !config.History.Enabled || !config.History.Persistent.Enabled {
  1383. config.History.Persistent.Enabled = false
  1384. config.History.Persistent.UnregisteredChannels = false
  1385. config.History.Persistent.RegisteredChannels = PersistentDisabled
  1386. config.History.Persistent.DirectMessages = PersistentDisabled
  1387. }
  1388. if config.History.Persistent.Enabled && !config.Datastore.MySQL.Enabled {
  1389. return nil, fmt.Errorf("You must configure a MySQL server in order to enable persistent history")
  1390. }
  1391. if config.History.ZNCMax == 0 {
  1392. config.History.ZNCMax = config.History.ChathistoryMax
  1393. }
  1394. if config.History.Restrictions.QueryCutoff != "" {
  1395. config.History.Restrictions.queryCutoff, err = historyCutoffFromString(config.History.Restrictions.QueryCutoff)
  1396. if err != nil {
  1397. return nil, fmt.Errorf("invalid value of history.query-restrictions: %w", err)
  1398. }
  1399. } else {
  1400. if config.History.Restrictions.EnforceRegistrationDate_ {
  1401. config.History.Restrictions.queryCutoff = HistoryCutoffRegistrationTime
  1402. } else {
  1403. config.History.Restrictions.queryCutoff = HistoryCutoffNone
  1404. }
  1405. }
  1406. config.Roleplay.addSuffix = utils.BoolDefaultTrue(config.Roleplay.AddSuffix)
  1407. config.Datastore.MySQL.ExpireTime = time.Duration(config.History.Restrictions.ExpireTime)
  1408. config.Datastore.MySQL.TrackAccountMessages = config.History.Retention.EnableAccountIndexing
  1409. if config.Datastore.MySQL.MaxConns == 0 {
  1410. // #1622: not putting an upper limit on the number of MySQL connections is
  1411. // potentially dangerous. as a naive heuristic, assume they're running on the
  1412. // same machine:
  1413. config.Datastore.MySQL.MaxConns = runtime.NumCPU()
  1414. }
  1415. config.Server.Cloaks.Initialize()
  1416. if config.Server.Cloaks.Enabled {
  1417. if !utils.IsHostname(config.Server.Cloaks.Netname) {
  1418. return nil, fmt.Errorf("Invalid netname for cloaked hostnames: %s", config.Server.Cloaks.Netname)
  1419. }
  1420. }
  1421. err = config.processExtjwt()
  1422. if err != nil {
  1423. return nil, err
  1424. }
  1425. // now that all postprocessing is complete, regenerate ISUPPORT:
  1426. err = config.generateISupport()
  1427. if err != nil {
  1428. return nil, err
  1429. }
  1430. // #1428: Tor listeners should never see STS
  1431. config.Server.supportedCapsWithoutSTS = caps.NewSet()
  1432. config.Server.supportedCapsWithoutSTS.Union(config.Server.supportedCaps)
  1433. config.Server.supportedCapsWithoutSTS.Disable(caps.STS)
  1434. return config, nil
  1435. }
  1436. func (config *Config) getOutputPath(filename string) string {
  1437. return filepath.Join(config.Server.OutputPath, filename)
  1438. }
  1439. func (config *Config) isRelaymsgIdentifier(nick string) bool {
  1440. if !config.Server.Relaymsg.Enabled {
  1441. return false
  1442. }
  1443. for _, char := range config.Server.Relaymsg.Separators {
  1444. if strings.ContainsRune(nick, char) {
  1445. return true
  1446. }
  1447. }
  1448. return false
  1449. }
  1450. // setISupport sets up our RPL_ISUPPORT reply.
  1451. func (config *Config) generateISupport() (err error) {
  1452. maxTargetsString := strconv.Itoa(maxTargets)
  1453. // add RPL_ISUPPORT tokens
  1454. isupport := &config.Server.isupport
  1455. isupport.Initialize()
  1456. isupport.Add("AWAYLEN", strconv.Itoa(config.Limits.AwayLen))
  1457. isupport.Add("BOT", "B")
  1458. isupport.Add("CASEMAPPING", "ascii")
  1459. isupport.Add("CHANLIMIT", fmt.Sprintf("%s:%d", chanTypes, config.Channels.MaxChannelsPerClient))
  1460. isupport.Add("CHANMODES", chanmodesToken)
  1461. if config.History.Enabled && config.History.ChathistoryMax > 0 {
  1462. isupport.Add("draft/CHATHISTORY", strconv.Itoa(config.History.ChathistoryMax))
  1463. }
  1464. isupport.Add("CHANNELLEN", strconv.Itoa(config.Limits.ChannelLen))
  1465. isupport.Add("CHANTYPES", chanTypes)
  1466. isupport.Add("ELIST", "U")
  1467. isupport.Add("EXCEPTS", "")
  1468. if config.Extjwt.Default.Enabled() || len(config.Extjwt.Services) != 0 {
  1469. isupport.Add("EXTJWT", "1")
  1470. }
  1471. isupport.Add("EXTBAN", ",m")
  1472. isupport.Add("FORWARD", "f")
  1473. isupport.Add("INVEX", "")
  1474. isupport.Add("KICKLEN", strconv.Itoa(config.Limits.KickLen))
  1475. isupport.Add("MAXLIST", fmt.Sprintf("beI:%s", strconv.Itoa(config.Limits.ChanListModes)))
  1476. isupport.Add("MAXTARGETS", maxTargetsString)
  1477. isupport.Add("MODES", "")
  1478. isupport.Add("MONITOR", strconv.Itoa(config.Limits.MonitorEntries))
  1479. isupport.Add("NETWORK", config.Network.Name)
  1480. isupport.Add("NICKLEN", strconv.Itoa(config.Limits.NickLen))
  1481. isupport.Add("PREFIX", "(qaohv)~&@%+")
  1482. if config.Roleplay.Enabled {
  1483. isupport.Add("RPCHAN", "E")
  1484. isupport.Add("RPUSER", "E")
  1485. }
  1486. isupport.Add("STATUSMSG", "~&@%+")
  1487. isupport.Add("TARGMAX", fmt.Sprintf("NAMES:1,LIST:1,KICK:,WHOIS:1,USERHOST:10,PRIVMSG:%s,TAGMSG:%s,NOTICE:%s,MONITOR:%d", maxTargetsString, maxTargetsString, maxTargetsString, config.Limits.MonitorEntries))
  1488. isupport.Add("TOPICLEN", strconv.Itoa(config.Limits.TopicLen))
  1489. if config.Server.Casemapping == CasemappingPRECIS {
  1490. isupport.Add("UTF8MAPPING", precisUTF8MappingToken)
  1491. }
  1492. if config.Server.EnforceUtf8 {
  1493. isupport.Add("UTF8ONLY", "")
  1494. }
  1495. isupport.Add("WHOX", "")
  1496. err = isupport.RegenerateCachedReply()
  1497. return
  1498. }
  1499. // Diff returns changes in supported caps across a rehash.
  1500. func (config *Config) Diff(oldConfig *Config) (addedCaps, removedCaps *caps.Set) {
  1501. addedCaps = caps.NewSet()
  1502. removedCaps = caps.NewSet()
  1503. if oldConfig == nil {
  1504. return
  1505. }
  1506. if oldConfig.Server.capValues[caps.Languages] != config.Server.capValues[caps.Languages] {
  1507. // XXX updated caps get a DEL line and then a NEW line with the new value
  1508. addedCaps.Add(caps.Languages)
  1509. removedCaps.Add(caps.Languages)
  1510. }
  1511. if !oldConfig.Accounts.AuthenticationEnabled && config.Accounts.AuthenticationEnabled {
  1512. addedCaps.Add(caps.SASL)
  1513. } else if oldConfig.Accounts.AuthenticationEnabled && !config.Accounts.AuthenticationEnabled {
  1514. removedCaps.Add(caps.SASL)
  1515. }
  1516. if oldConfig.Limits.Multiline.MaxBytes != 0 && config.Limits.Multiline.MaxBytes == 0 {
  1517. removedCaps.Add(caps.Multiline)
  1518. } else if oldConfig.Limits.Multiline.MaxBytes == 0 && config.Limits.Multiline.MaxBytes != 0 {
  1519. addedCaps.Add(caps.Multiline)
  1520. } else if oldConfig.Limits.Multiline != config.Limits.Multiline {
  1521. removedCaps.Add(caps.Multiline)
  1522. addedCaps.Add(caps.Multiline)
  1523. }
  1524. if oldConfig.Server.STS.Enabled != config.Server.STS.Enabled || oldConfig.Server.capValues[caps.STS] != config.Server.capValues[caps.STS] {
  1525. // XXX: STS is always removed by CAP NEW sts=duration=0, not CAP DEL
  1526. // so the appropriate notify is always a CAP NEW; put it in addedCaps for any change
  1527. addedCaps.Add(caps.STS)
  1528. }
  1529. return
  1530. }
  1531. // determine whether we need to resize / create / destroy
  1532. // the in-memory history buffers:
  1533. func (config *Config) historyChangedFrom(oldConfig *Config) bool {
  1534. return config.History.Enabled != oldConfig.History.Enabled ||
  1535. config.History.ChannelLength != oldConfig.History.ChannelLength ||
  1536. config.History.ClientLength != oldConfig.History.ClientLength ||
  1537. config.History.AutoresizeWindow != oldConfig.History.AutoresizeWindow ||
  1538. config.History.Persistent != oldConfig.History.Persistent
  1539. }
  1540. func compileGuestRegexp(guestFormat string, casemapping Casemapping) (standard, folded *regexp.Regexp, err error) {
  1541. if strings.Count(guestFormat, "?") != 0 || strings.Count(guestFormat, "*") != 1 {
  1542. err = errors.New("guest format must contain 1 '*' and no '?'s")
  1543. return
  1544. }
  1545. standard, err = utils.CompileGlob(guestFormat, true)
  1546. if err != nil {
  1547. return
  1548. }
  1549. starIndex := strings.IndexByte(guestFormat, '*')
  1550. initial := guestFormat[:starIndex]
  1551. final := guestFormat[starIndex+1:]
  1552. initialFolded, err := casefoldWithSetting(initial, casemapping)
  1553. if err != nil {
  1554. return
  1555. }
  1556. finalFolded, err := casefoldWithSetting(final, casemapping)
  1557. if err != nil {
  1558. return
  1559. }
  1560. folded, err = utils.CompileGlob(fmt.Sprintf("%s*%s", initialFolded, finalFolded), false)
  1561. return
  1562. }
  1563. func (config *Config) loadMOTD() error {
  1564. if config.Server.MOTD != "" {
  1565. file, err := os.Open(config.Server.MOTD)
  1566. if err != nil {
  1567. return err
  1568. }
  1569. defer file.Close()
  1570. contents, err := io.ReadAll(file)
  1571. if err != nil {
  1572. return err
  1573. }
  1574. lines := bytes.Split(contents, []byte{'\n'})
  1575. for i, line := range lines {
  1576. lineToSend := string(bytes.TrimRight(line, "\r\n"))
  1577. if len(lineToSend) == 0 && i == len(lines)-1 {
  1578. // if the last line of the MOTD was properly terminated with \n,
  1579. // there's no need to send a blank line to clients
  1580. continue
  1581. }
  1582. if config.Server.MOTDFormatting {
  1583. lineToSend = ircfmt.Unescape(lineToSend)
  1584. }
  1585. // "- " is the required prefix for MOTD
  1586. lineToSend = fmt.Sprintf("- %s", lineToSend)
  1587. config.Server.motdLines = append(config.Server.motdLines, lineToSend)
  1588. }
  1589. }
  1590. return nil
  1591. }