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

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