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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773
  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. KickLen int `yaml:"kicklen"`
  449. MonitorEntries int `yaml:"monitor-entries"`
  450. NickLen int `yaml:"nicklen"`
  451. TopicLen int `yaml:"topiclen"`
  452. WhowasEntries int `yaml:"whowas-entries"`
  453. RegistrationMessages int `yaml:"registration-messages"`
  454. Multiline struct {
  455. MaxBytes int `yaml:"max-bytes"`
  456. MaxLines int `yaml:"max-lines"`
  457. }
  458. }
  459. // STSConfig controls the STS configuration/
  460. type STSConfig struct {
  461. Enabled bool
  462. Duration custime.Duration
  463. Port int
  464. Preload bool
  465. STSOnlyBanner string `yaml:"sts-only-banner"`
  466. bannerLines []string
  467. }
  468. // Value returns the STS value to advertise in CAP
  469. func (sts *STSConfig) Value() string {
  470. val := fmt.Sprintf("duration=%d", int(time.Duration(sts.Duration).Seconds()))
  471. if sts.Enabled && sts.Port > 0 {
  472. val += fmt.Sprintf(",port=%d", sts.Port)
  473. }
  474. if sts.Enabled && sts.Preload {
  475. val += ",preload"
  476. }
  477. return val
  478. }
  479. type FakelagConfig struct {
  480. Enabled bool
  481. Window time.Duration
  482. BurstLimit uint `yaml:"burst-limit"`
  483. MessagesPerWindow uint `yaml:"messages-per-window"`
  484. Cooldown time.Duration
  485. CommandBudgets map[string]int `yaml:"command-budgets"`
  486. }
  487. type TorListenersConfig struct {
  488. Listeners []string // legacy only
  489. RequireSasl bool `yaml:"require-sasl"`
  490. Vhost string
  491. MaxConnections int `yaml:"max-connections"`
  492. ThrottleDuration time.Duration `yaml:"throttle-duration"`
  493. MaxConnectionsPerDuration int `yaml:"max-connections-per-duration"`
  494. }
  495. // Config defines the overall configuration.
  496. type Config struct {
  497. AllowEnvironmentOverrides bool `yaml:"allow-environment-overrides"`
  498. Network struct {
  499. Name string
  500. }
  501. Server struct {
  502. Password string
  503. passwordBytes []byte
  504. Name string
  505. nameCasefolded string
  506. Listeners map[string]listenerConfigBlock
  507. UnixBindMode os.FileMode `yaml:"unix-bind-mode"`
  508. TorListeners TorListenersConfig `yaml:"tor-listeners"`
  509. WebSockets struct {
  510. AllowedOrigins []string `yaml:"allowed-origins"`
  511. allowedOriginRegexps []*regexp.Regexp
  512. }
  513. // they get parsed into this internal representation:
  514. trueListeners map[string]utils.ListenerConfig
  515. STS STSConfig
  516. LookupHostnames *bool `yaml:"lookup-hostnames"`
  517. lookupHostnames bool
  518. ForwardConfirmHostnames bool `yaml:"forward-confirm-hostnames"`
  519. CheckIdent bool `yaml:"check-ident"`
  520. CoerceIdent string `yaml:"coerce-ident"`
  521. MOTD string
  522. motdLines []string
  523. MOTDFormatting bool `yaml:"motd-formatting"`
  524. Relaymsg struct {
  525. Enabled bool
  526. Separators string
  527. AvailableToChanops bool `yaml:"available-to-chanops"`
  528. }
  529. ProxyAllowedFrom []string `yaml:"proxy-allowed-from"`
  530. proxyAllowedFromNets []net.IPNet
  531. WebIRC []webircConfig `yaml:"webirc"`
  532. MaxSendQString string `yaml:"max-sendq"`
  533. MaxSendQBytes int
  534. Compatibility struct {
  535. ForceTrailing *bool `yaml:"force-trailing"`
  536. forceTrailing bool
  537. SendUnprefixedSasl bool `yaml:"send-unprefixed-sasl"`
  538. AllowTruncation *bool `yaml:"allow-truncation"`
  539. allowTruncation bool
  540. }
  541. isupport isupport.List
  542. IPLimits connection_limits.LimiterConfig `yaml:"ip-limits"`
  543. Cloaks cloaks.CloakConfig `yaml:"ip-cloaking"`
  544. SecureNetDefs []string `yaml:"secure-nets"`
  545. secureNets []net.IPNet
  546. supportedCaps *caps.Set
  547. supportedCapsWithoutSTS *caps.Set
  548. capValues caps.Values
  549. Casemapping Casemapping
  550. EnforceUtf8 bool `yaml:"enforce-utf8"`
  551. OutputPath string `yaml:"output-path"`
  552. IPCheckScript IPCheckScriptConfig `yaml:"ip-check-script"`
  553. OverrideServicesHostname string `yaml:"override-services-hostname"`
  554. MaxLineLen int `yaml:"max-line-len"`
  555. SuppressLusers bool `yaml:"suppress-lusers"`
  556. }
  557. Roleplay struct {
  558. Enabled bool
  559. RequireChanops bool `yaml:"require-chanops"`
  560. RequireOper bool `yaml:"require-oper"`
  561. AddSuffix *bool `yaml:"add-suffix"`
  562. addSuffix bool
  563. }
  564. Extjwt struct {
  565. Default jwt.JwtServiceConfig `yaml:",inline"`
  566. Services map[string]jwt.JwtServiceConfig `yaml:"services"`
  567. }
  568. Languages struct {
  569. Enabled bool
  570. Path string
  571. Default string
  572. }
  573. languageManager *languages.Manager
  574. LockFile string `yaml:"lock-file"`
  575. Datastore struct {
  576. Path string
  577. AutoUpgrade bool
  578. MySQL mysql.Config
  579. }
  580. Accounts AccountConfig
  581. Channels struct {
  582. DefaultModes *string `yaml:"default-modes"`
  583. defaultModes modes.Modes
  584. MaxChannelsPerClient int `yaml:"max-channels-per-client"`
  585. OpOnlyCreation bool `yaml:"operator-only-creation"`
  586. Registration struct {
  587. Enabled bool
  588. OperatorOnly bool `yaml:"operator-only"`
  589. MaxChannelsPerAccount int `yaml:"max-channels-per-account"`
  590. }
  591. ListDelay time.Duration `yaml:"list-delay"`
  592. InviteExpiration custime.Duration `yaml:"invite-expiration"`
  593. AutoJoin []string `yaml:"auto-join"`
  594. }
  595. OperClasses map[string]*OperClassConfig `yaml:"oper-classes"`
  596. Opers map[string]*OperConfig
  597. // parsed operator definitions, unexported so they can't be defined
  598. // directly in YAML:
  599. operators map[string]*Oper
  600. Logging []logger.LoggingConfig
  601. Debug struct {
  602. RecoverFromErrors *bool `yaml:"recover-from-errors"`
  603. recoverFromErrors bool
  604. PprofListener string `yaml:"pprof-listener"`
  605. }
  606. Limits Limits
  607. Fakelag FakelagConfig
  608. History struct {
  609. Enabled bool
  610. ChannelLength int `yaml:"channel-length"`
  611. ClientLength int `yaml:"client-length"`
  612. AutoresizeWindow custime.Duration `yaml:"autoresize-window"`
  613. AutoreplayOnJoin int `yaml:"autoreplay-on-join"`
  614. ChathistoryMax int `yaml:"chathistory-maxmessages"`
  615. ZNCMax int `yaml:"znc-maxmessages"`
  616. Restrictions struct {
  617. ExpireTime custime.Duration `yaml:"expire-time"`
  618. // legacy key, superceded by QueryCutoff:
  619. EnforceRegistrationDate_ bool `yaml:"enforce-registration-date"`
  620. QueryCutoff string `yaml:"query-cutoff"`
  621. queryCutoff HistoryCutoff
  622. GracePeriod custime.Duration `yaml:"grace-period"`
  623. }
  624. Persistent struct {
  625. Enabled bool
  626. UnregisteredChannels bool `yaml:"unregistered-channels"`
  627. RegisteredChannels PersistentStatus `yaml:"registered-channels"`
  628. DirectMessages PersistentStatus `yaml:"direct-messages"`
  629. }
  630. Retention struct {
  631. AllowIndividualDelete bool `yaml:"allow-individual-delete"`
  632. EnableAccountIndexing bool `yaml:"enable-account-indexing"`
  633. }
  634. TagmsgStorage struct {
  635. Default bool
  636. Whitelist []string
  637. Blacklist []string
  638. } `yaml:"tagmsg-storage"`
  639. }
  640. Filename string
  641. }
  642. // OperClass defines an assembled operator class.
  643. type OperClass struct {
  644. Title string
  645. WhoisLine string `yaml:"whois-line"`
  646. Capabilities utils.HashSet[string] // map to make lookups much easier
  647. }
  648. // OperatorClasses returns a map of assembled operator classes from the given config.
  649. func (conf *Config) OperatorClasses() (map[string]*OperClass, error) {
  650. fixupCapability := func(capab string) string {
  651. return strings.TrimPrefix(strings.TrimPrefix(capab, "oper:"), "local_") // #868, #1442
  652. }
  653. ocs := make(map[string]*OperClass)
  654. // loop from no extends to most extended, breaking if we can't add any more
  655. lenOfLastOcs := -1
  656. for {
  657. if lenOfLastOcs == len(ocs) {
  658. return nil, errors.New("OperClasses contains a looping dependency, or a class extends from a class that doesn't exist")
  659. }
  660. lenOfLastOcs = len(ocs)
  661. var anyMissing bool
  662. for name, info := range conf.OperClasses {
  663. _, exists := ocs[name]
  664. _, extendsExists := ocs[info.Extends]
  665. if exists {
  666. // class already exists
  667. continue
  668. } else if len(info.Extends) > 0 && !extendsExists {
  669. // class we extend on doesn't exist
  670. _, exists := conf.OperClasses[info.Extends]
  671. if !exists {
  672. return nil, fmt.Errorf("Operclass [%s] extends [%s], which doesn't exist", name, info.Extends)
  673. }
  674. anyMissing = true
  675. continue
  676. }
  677. // create new operclass
  678. var oc OperClass
  679. oc.Capabilities = make(utils.HashSet[string])
  680. // get inhereted info from other operclasses
  681. if len(info.Extends) > 0 {
  682. einfo := ocs[info.Extends]
  683. for capab := range einfo.Capabilities {
  684. oc.Capabilities.Add(fixupCapability(capab))
  685. }
  686. }
  687. // add our own info
  688. oc.Title = info.Title
  689. if oc.Title == "" {
  690. oc.Title = "IRC operator"
  691. }
  692. for _, capab := range info.Capabilities {
  693. oc.Capabilities.Add(fixupCapability(capab))
  694. }
  695. if len(info.WhoisLine) > 0 {
  696. oc.WhoisLine = info.WhoisLine
  697. } else {
  698. oc.WhoisLine = "is a"
  699. if strings.Contains(strings.ToLower(string(oc.Title[0])), "aeiou") {
  700. oc.WhoisLine += "n"
  701. }
  702. oc.WhoisLine += " "
  703. oc.WhoisLine += oc.Title
  704. }
  705. ocs[name] = &oc
  706. }
  707. if !anyMissing {
  708. // we've got every operclass!
  709. break
  710. }
  711. }
  712. return ocs, nil
  713. }
  714. // Oper represents a single assembled operator's config.
  715. type Oper struct {
  716. Name string
  717. Class *OperClass
  718. WhoisLine string
  719. Vhost string
  720. Pass []byte
  721. Certfp string
  722. Auto bool
  723. Hidden bool
  724. Modes []modes.ModeChange
  725. }
  726. func (oper *Oper) HasRoleCapab(capab string) bool {
  727. return oper != nil && oper.Class.Capabilities.Has(capab)
  728. }
  729. // Operators returns a map of operator configs from the given OperClass and config.
  730. func (conf *Config) Operators(oc map[string]*OperClass) (map[string]*Oper, error) {
  731. operators := make(map[string]*Oper)
  732. for name, opConf := range conf.Opers {
  733. var oper Oper
  734. // oper name
  735. name, err := CasefoldName(name)
  736. if err != nil {
  737. return nil, fmt.Errorf("Could not casefold oper name: %s", err.Error())
  738. }
  739. oper.Name = name
  740. if opConf.Password != "" {
  741. oper.Pass, err = decodeLegacyPasswordHash(opConf.Password)
  742. if err != nil {
  743. return nil, fmt.Errorf("Oper %s has an invalid password hash: %s", oper.Name, err.Error())
  744. }
  745. }
  746. certfp := opConf.Certfp
  747. if certfp == "" && opConf.Fingerprint != nil {
  748. certfp = *opConf.Fingerprint
  749. }
  750. if certfp != "" {
  751. oper.Certfp, err = utils.NormalizeCertfp(certfp)
  752. if err != nil {
  753. return nil, fmt.Errorf("Oper %s has an invalid fingerprint: %s", oper.Name, err.Error())
  754. }
  755. }
  756. oper.Auto = opConf.Auto
  757. oper.Hidden = opConf.Hidden
  758. if oper.Pass == nil && oper.Certfp == "" {
  759. return nil, fmt.Errorf("Oper %s has neither a password nor a fingerprint", name)
  760. }
  761. oper.Vhost = opConf.Vhost
  762. if oper.Vhost != "" && !conf.Accounts.VHosts.validRegexp.MatchString(oper.Vhost) {
  763. return nil, fmt.Errorf("Oper %s has an invalid vhost: `%s`", name, oper.Vhost)
  764. }
  765. class, exists := oc[opConf.Class]
  766. if !exists {
  767. return nil, fmt.Errorf("Could not load operator [%s] - they use operclass [%s] which does not exist", name, opConf.Class)
  768. }
  769. oper.Class = class
  770. if len(opConf.WhoisLine) > 0 {
  771. oper.WhoisLine = opConf.WhoisLine
  772. } else {
  773. oper.WhoisLine = class.WhoisLine
  774. }
  775. modeStr := strings.TrimSpace(opConf.Modes)
  776. modeChanges, unknownChanges := modes.ParseUserModeChanges(strings.Split(modeStr, " ")...)
  777. if len(unknownChanges) > 0 {
  778. return nil, fmt.Errorf("Could not load operator [%s] due to unknown modes %v", name, unknownChanges)
  779. }
  780. oper.Modes = modeChanges
  781. // successful, attach to list of opers
  782. operators[name] = &oper
  783. }
  784. return operators, nil
  785. }
  786. func loadTlsConfig(config listenerConfigBlock) (tlsConfig *tls.Config, err error) {
  787. var certificates []tls.Certificate
  788. if len(config.TLSCertificates) != 0 {
  789. // SNI configuration with multiple certificates
  790. for _, certPairConf := range config.TLSCertificates {
  791. cert, err := loadCertWithLeaf(certPairConf.Cert, certPairConf.Key)
  792. if err != nil {
  793. return nil, err
  794. }
  795. certificates = append(certificates, cert)
  796. }
  797. } else if config.TLS.Cert != "" {
  798. // normal configuration with one certificate
  799. cert, err := loadCertWithLeaf(config.TLS.Cert, config.TLS.Key)
  800. if err != nil {
  801. return nil, err
  802. }
  803. certificates = append(certificates, cert)
  804. } else {
  805. // plaintext!
  806. return nil, nil
  807. }
  808. clientAuth := tls.RequestClientCert
  809. if config.WebSocket {
  810. // if Chrome receives a server request for a client certificate
  811. // on a websocket connection, it will immediately disconnect:
  812. // https://bugs.chromium.org/p/chromium/issues/detail?id=329884
  813. // work around this behavior:
  814. clientAuth = tls.NoClientCert
  815. }
  816. result := tls.Config{
  817. Certificates: certificates,
  818. ClientAuth: clientAuth,
  819. MinVersion: tlsMinVersionFromString(config.MinTLSVersion),
  820. }
  821. return &result, nil
  822. }
  823. func tlsMinVersionFromString(version string) uint16 {
  824. version = strings.ToLower(version)
  825. version = strings.TrimPrefix(version, "v")
  826. switch version {
  827. case "1", "1.0":
  828. return tls.VersionTLS10
  829. case "1.1":
  830. return tls.VersionTLS11
  831. case "1.2":
  832. return tls.VersionTLS12
  833. case "1.3":
  834. return tls.VersionTLS13
  835. default:
  836. // tls package will fill in a sane value, currently 1.0
  837. return 0
  838. }
  839. }
  840. func loadCertWithLeaf(certFile, keyFile string) (cert tls.Certificate, err error) {
  841. // LoadX509KeyPair: "On successful return, Certificate.Leaf will be nil because
  842. // the parsed form of the certificate is not retained." tls.Config:
  843. // "Note: if there are multiple Certificates, and they don't have the
  844. // optional field Leaf set, certificate selection will incur a significant
  845. // per-handshake performance cost."
  846. cert, err = tls.LoadX509KeyPair(certFile, keyFile)
  847. if err != nil {
  848. return
  849. }
  850. cert.Leaf, err = x509.ParseCertificate(cert.Certificate[0])
  851. return
  852. }
  853. // prepareListeners populates Config.Server.trueListeners
  854. func (conf *Config) prepareListeners() (err error) {
  855. if len(conf.Server.Listeners) == 0 {
  856. return fmt.Errorf("No listeners were configured")
  857. }
  858. conf.Server.trueListeners = make(map[string]utils.ListenerConfig)
  859. for addr, block := range conf.Server.Listeners {
  860. var lconf utils.ListenerConfig
  861. lconf.ProxyDeadline = RegisterTimeout
  862. lconf.Tor = block.Tor
  863. lconf.STSOnly = block.STSOnly
  864. if lconf.STSOnly && !conf.Server.STS.Enabled {
  865. return fmt.Errorf("%s is configured as a STS-only listener, but STS is disabled", addr)
  866. }
  867. lconf.TLSConfig, err = loadTlsConfig(block)
  868. if err != nil {
  869. return &CertKeyError{Err: err}
  870. }
  871. lconf.RequireProxy = block.TLS.Proxy || block.Proxy
  872. lconf.WebSocket = block.WebSocket
  873. if lconf.WebSocket && !conf.Server.EnforceUtf8 {
  874. return fmt.Errorf("enabling a websocket listener requires the use of server.enforce-utf8")
  875. }
  876. lconf.HideSTS = block.HideSTS
  877. conf.Server.trueListeners[addr] = lconf
  878. }
  879. return nil
  880. }
  881. func (config *Config) processExtjwt() (err error) {
  882. // first process the default service, which may be disabled
  883. err = config.Extjwt.Default.Postprocess()
  884. if err != nil {
  885. return
  886. }
  887. // now process the named services. it is an error if any is disabled
  888. // also, normalize the service names to lowercase
  889. services := make(map[string]jwt.JwtServiceConfig, len(config.Extjwt.Services))
  890. for service, sConf := range config.Extjwt.Services {
  891. err := sConf.Postprocess()
  892. if err != nil {
  893. return err
  894. }
  895. if !sConf.Enabled() {
  896. return fmt.Errorf("no keys enabled for extjwt service %s", service)
  897. }
  898. services[strings.ToLower(service)] = sConf
  899. }
  900. config.Extjwt.Services = services
  901. return nil
  902. }
  903. // LoadRawConfig loads the config without doing any consistency checks or postprocessing
  904. func LoadRawConfig(filename string) (config *Config, err error) {
  905. data, err := os.ReadFile(filename)
  906. if err != nil {
  907. return nil, err
  908. }
  909. err = yaml.Unmarshal(data, &config)
  910. if err != nil {
  911. return nil, err
  912. }
  913. return
  914. }
  915. // convert, e.g., "ALLOWED_ORIGINS" to "allowed-origins"
  916. func screamingSnakeToKebab(in string) (out string) {
  917. var buf strings.Builder
  918. for i := 0; i < len(in); i++ {
  919. c := in[i]
  920. switch {
  921. case c == '_':
  922. buf.WriteByte('-')
  923. case 'A' <= c && c <= 'Z':
  924. buf.WriteByte(c + ('a' - 'A'))
  925. default:
  926. buf.WriteByte(c)
  927. }
  928. }
  929. return buf.String()
  930. }
  931. func isExported(field reflect.StructField) bool {
  932. return field.PkgPath == "" // https://golang.org/pkg/reflect/#StructField
  933. }
  934. // errors caused by config overrides
  935. type configPathError struct {
  936. name string
  937. desc string
  938. fatalErr error
  939. }
  940. func (ce *configPathError) Error() string {
  941. if ce.fatalErr != nil {
  942. return fmt.Sprintf("Couldn't apply config override `%s`: %s: %v", ce.name, ce.desc, ce.fatalErr)
  943. }
  944. return fmt.Sprintf("Couldn't apply config override `%s`: %s", ce.name, ce.desc)
  945. }
  946. func mungeFromEnvironment(config *Config, envPair string) (applied bool, err *configPathError) {
  947. equalIdx := strings.IndexByte(envPair, '=')
  948. name, value := envPair[:equalIdx], envPair[equalIdx+1:]
  949. if strings.HasPrefix(name, "ERGO__") {
  950. name = strings.TrimPrefix(name, "ERGO__")
  951. } else if strings.HasPrefix(name, "ORAGONO__") {
  952. name = strings.TrimPrefix(name, "ORAGONO__")
  953. } else {
  954. return false, nil
  955. }
  956. pathComponents := strings.Split(name, "__")
  957. for i, pathComponent := range pathComponents {
  958. pathComponents[i] = screamingSnakeToKebab(pathComponent)
  959. }
  960. v := reflect.Indirect(reflect.ValueOf(config))
  961. t := v.Type()
  962. for _, component := range pathComponents {
  963. if component == "" {
  964. return false, &configPathError{name, "invalid", nil}
  965. }
  966. if v.Kind() != reflect.Struct {
  967. return false, &configPathError{name, "index into non-struct", nil}
  968. }
  969. var nextField reflect.StructField
  970. success := false
  971. n := t.NumField()
  972. // preferentially get a field with an exact yaml tag match,
  973. // then fall back to case-insensitive comparison of field names
  974. for i := 0; i < n; i++ {
  975. field := t.Field(i)
  976. if isExported(field) && field.Tag.Get("yaml") == component {
  977. nextField = field
  978. success = true
  979. break
  980. }
  981. }
  982. if !success {
  983. for i := 0; i < n; i++ {
  984. field := t.Field(i)
  985. if isExported(field) && strings.ToLower(field.Name) == component {
  986. nextField = field
  987. success = true
  988. break
  989. }
  990. }
  991. }
  992. if !success {
  993. return false, &configPathError{name, fmt.Sprintf("couldn't resolve path component: `%s`", component), nil}
  994. }
  995. v = v.FieldByName(nextField.Name)
  996. // dereference pointer field if necessary, initialize new value if necessary
  997. if v.Kind() == reflect.Ptr {
  998. if v.IsNil() {
  999. v.Set(reflect.New(v.Type().Elem()))
  1000. }
  1001. v = reflect.Indirect(v)
  1002. }
  1003. t = v.Type()
  1004. }
  1005. yamlErr := yaml.Unmarshal([]byte(value), v.Addr().Interface())
  1006. if yamlErr != nil {
  1007. return false, &configPathError{name, "couldn't deserialize YAML", yamlErr}
  1008. }
  1009. return true, nil
  1010. }
  1011. // LoadConfig loads the given YAML configuration file.
  1012. func LoadConfig(filename string) (config *Config, err error) {
  1013. config, err = LoadRawConfig(filename)
  1014. if err != nil {
  1015. return nil, err
  1016. }
  1017. if config.AllowEnvironmentOverrides {
  1018. for _, envPair := range os.Environ() {
  1019. applied, envErr := mungeFromEnvironment(config, envPair)
  1020. if envErr != nil {
  1021. if envErr.fatalErr != nil {
  1022. return nil, envErr
  1023. } else {
  1024. log.Println(envErr.Error())
  1025. }
  1026. } else if applied {
  1027. log.Printf("applied environment override: %s\n", envPair)
  1028. }
  1029. }
  1030. }
  1031. config.Filename = filename
  1032. if config.Network.Name == "" {
  1033. return nil, errors.New("Network name missing")
  1034. }
  1035. if config.Server.Name == "" {
  1036. return nil, errors.New("Server name missing")
  1037. }
  1038. if !utils.IsServerName(config.Server.Name) {
  1039. return nil, errors.New("Server name must match the format of a hostname")
  1040. }
  1041. config.Server.nameCasefolded = strings.ToLower(config.Server.Name)
  1042. if config.Datastore.Path == "" {
  1043. return nil, errors.New("Datastore path missing")
  1044. }
  1045. //dan: automagically fix identlen until a few releases in the future (from now, 0.12.0), being a newly-introduced limit
  1046. if config.Limits.IdentLen < 1 {
  1047. config.Limits.IdentLen = 20
  1048. }
  1049. if config.Limits.NickLen < 1 || config.Limits.ChannelLen < 2 || config.Limits.AwayLen < 1 || config.Limits.KickLen < 1 || config.Limits.TopicLen < 1 {
  1050. return nil, errors.New("One or more limits values are too low")
  1051. }
  1052. if config.Limits.RegistrationMessages == 0 {
  1053. config.Limits.RegistrationMessages = 1024
  1054. }
  1055. if config.Server.MaxLineLen < DefaultMaxLineLen {
  1056. config.Server.MaxLineLen = DefaultMaxLineLen
  1057. }
  1058. if config.Datastore.MySQL.Enabled {
  1059. if config.Limits.NickLen > mysql.MaxTargetLength || config.Limits.ChannelLen > mysql.MaxTargetLength {
  1060. return nil, fmt.Errorf("to use MySQL, nick and channel length limits must be %d or lower", mysql.MaxTargetLength)
  1061. }
  1062. }
  1063. if config.Server.CoerceIdent != "" {
  1064. if config.Server.CheckIdent {
  1065. return nil, errors.New("Can't configure both check-ident and coerce-ident")
  1066. }
  1067. if config.Server.CoerceIdent[0] != '~' {
  1068. return nil, errors.New("coerce-ident value must start with a ~")
  1069. }
  1070. if !isIdent(config.Server.CoerceIdent[1:]) {
  1071. return nil, errors.New("coerce-ident must be valid as an IRC user/ident field")
  1072. }
  1073. }
  1074. config.Server.supportedCaps = caps.NewCompleteSet()
  1075. config.Server.capValues = make(caps.Values)
  1076. err = config.prepareListeners()
  1077. if err != nil {
  1078. return nil, fmt.Errorf("failed to prepare listeners: %v", err)
  1079. }
  1080. for _, glob := range config.Server.WebSockets.AllowedOrigins {
  1081. globre, err := utils.CompileGlob(glob, false)
  1082. if err != nil {
  1083. return nil, fmt.Errorf("invalid websocket allowed-origin expression: %s", glob)
  1084. }
  1085. config.Server.WebSockets.allowedOriginRegexps = append(config.Server.WebSockets.allowedOriginRegexps, globre)
  1086. }
  1087. if config.Server.STS.Enabled {
  1088. if config.Server.STS.Port < 0 || config.Server.STS.Port > 65535 {
  1089. return nil, fmt.Errorf("STS port is incorrect, should be 0 if disabled: %d", config.Server.STS.Port)
  1090. }
  1091. if config.Server.STS.STSOnlyBanner != "" {
  1092. for _, line := range strings.Split(config.Server.STS.STSOnlyBanner, "\n") {
  1093. config.Server.STS.bannerLines = append(config.Server.STS.bannerLines, strings.TrimSpace(line))
  1094. }
  1095. } else {
  1096. 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)}
  1097. }
  1098. } else {
  1099. config.Server.supportedCaps.Disable(caps.STS)
  1100. config.Server.STS.Duration = 0
  1101. }
  1102. // set this even if STS is disabled
  1103. config.Server.capValues[caps.STS] = config.Server.STS.Value()
  1104. config.Server.lookupHostnames = utils.BoolDefaultTrue(config.Server.LookupHostnames)
  1105. // process webirc blocks
  1106. var newWebIRC []webircConfig
  1107. for _, webirc := range config.Server.WebIRC {
  1108. // skip webirc blocks with no hosts (such as the example one)
  1109. if len(webirc.Hosts) == 0 {
  1110. continue
  1111. }
  1112. err = webirc.Populate()
  1113. if err != nil {
  1114. return nil, fmt.Errorf("Could not parse WebIRC config: %s", err.Error())
  1115. }
  1116. newWebIRC = append(newWebIRC, webirc)
  1117. }
  1118. config.Server.WebIRC = newWebIRC
  1119. if config.Limits.Multiline.MaxBytes <= 0 {
  1120. config.Server.supportedCaps.Disable(caps.Multiline)
  1121. } else {
  1122. var multilineCapValue string
  1123. if config.Limits.Multiline.MaxLines == 0 {
  1124. multilineCapValue = fmt.Sprintf("max-bytes=%d", config.Limits.Multiline.MaxBytes)
  1125. } else {
  1126. multilineCapValue = fmt.Sprintf("max-bytes=%d,max-lines=%d", config.Limits.Multiline.MaxBytes, config.Limits.Multiline.MaxLines)
  1127. }
  1128. config.Server.capValues[caps.Multiline] = multilineCapValue
  1129. }
  1130. // handle legacy name 'bouncer' for 'multiclient' section:
  1131. if config.Accounts.Bouncer != nil {
  1132. config.Accounts.Multiclient = *config.Accounts.Bouncer
  1133. }
  1134. if !config.Accounts.Multiclient.Enabled {
  1135. config.Accounts.Multiclient.AlwaysOn = PersistentDisabled
  1136. } else if config.Accounts.Multiclient.AlwaysOn >= PersistentOptOut {
  1137. config.Accounts.Multiclient.AllowedByDefault = true
  1138. }
  1139. if !config.Accounts.NickReservation.Enabled {
  1140. config.Accounts.NickReservation.ForceNickEqualsAccount = false
  1141. }
  1142. if config.Accounts.NickReservation.ForceNickEqualsAccount && !config.Accounts.Multiclient.Enabled {
  1143. return nil, errors.New("force-nick-equals-account requires enabling multiclient as well")
  1144. }
  1145. // handle guest format, including the legacy key rename-prefix
  1146. if config.Accounts.NickReservation.GuestFormat == "" {
  1147. renamePrefix := config.Accounts.NickReservation.RenamePrefix
  1148. if renamePrefix == "" {
  1149. renamePrefix = "Guest-"
  1150. }
  1151. config.Accounts.NickReservation.GuestFormat = renamePrefix + "*"
  1152. }
  1153. config.Accounts.NickReservation.guestRegexp, config.Accounts.NickReservation.guestRegexpFolded, err = compileGuestRegexp(config.Accounts.NickReservation.GuestFormat, config.Server.Casemapping)
  1154. if err != nil {
  1155. return nil, err
  1156. }
  1157. var newLogConfigs []logger.LoggingConfig
  1158. for _, logConfig := range config.Logging {
  1159. // methods
  1160. methods := make(map[string]bool)
  1161. for _, method := range strings.Split(logConfig.Method, " ") {
  1162. if len(method) > 0 {
  1163. methods[strings.ToLower(method)] = true
  1164. }
  1165. }
  1166. if methods["file"] && logConfig.Filename == "" {
  1167. return nil, errors.New("Logging configuration specifies 'file' method but 'filename' is empty")
  1168. }
  1169. logConfig.MethodFile = methods["file"]
  1170. logConfig.MethodStdout = methods["stdout"]
  1171. logConfig.MethodStderr = methods["stderr"]
  1172. // levels
  1173. level, exists := logger.LogLevelNames[strings.ToLower(logConfig.LevelString)]
  1174. if !exists {
  1175. return nil, fmt.Errorf("Could not translate log leve [%s]", logConfig.LevelString)
  1176. }
  1177. logConfig.Level = level
  1178. // types
  1179. for _, typeStr := range strings.Split(logConfig.TypeString, " ") {
  1180. if len(typeStr) == 0 {
  1181. continue
  1182. }
  1183. if typeStr == "-" {
  1184. return nil, errors.New("Encountered logging type '-' with no type to exclude")
  1185. }
  1186. if typeStr[0] == '-' {
  1187. typeStr = typeStr[1:]
  1188. logConfig.ExcludedTypes = append(logConfig.ExcludedTypes, typeStr)
  1189. } else {
  1190. logConfig.Types = append(logConfig.Types, typeStr)
  1191. }
  1192. }
  1193. if len(logConfig.Types) < 1 {
  1194. return nil, errors.New("Logger has no types to log")
  1195. }
  1196. newLogConfigs = append(newLogConfigs, logConfig)
  1197. }
  1198. config.Logging = newLogConfigs
  1199. if config.Accounts.Registration.EmailVerification.Enabled {
  1200. err := config.Accounts.Registration.EmailVerification.Postprocess(config.Server.Name)
  1201. if err != nil {
  1202. return nil, err
  1203. }
  1204. } else {
  1205. // TODO: this processes the legacy "callback" config, clean this up in 2.5 or later
  1206. // TODO: also clean up the legacy "inline" MTA config format (from ee05a4324dfde)
  1207. mailtoEnabled := false
  1208. for _, name := range config.Accounts.Registration.LegacyEnabledCallbacks {
  1209. if name == "mailto" {
  1210. mailtoEnabled = true
  1211. break
  1212. }
  1213. }
  1214. if mailtoEnabled {
  1215. config.Accounts.Registration.EmailVerification = config.Accounts.Registration.LegacyCallbacks.Mailto
  1216. config.Accounts.Registration.EmailVerification.Enabled = true
  1217. err := config.Accounts.Registration.EmailVerification.Postprocess(config.Server.Name)
  1218. if err != nil {
  1219. return nil, err
  1220. }
  1221. }
  1222. }
  1223. config.Accounts.defaultUserModes = ParseDefaultUserModes(config.Accounts.DefaultUserModes)
  1224. if config.Server.Password != "" {
  1225. config.Server.passwordBytes, err = decodeLegacyPasswordHash(config.Server.Password)
  1226. if err != nil {
  1227. return nil, err
  1228. }
  1229. if config.Accounts.LoginViaPassCommand && !config.Accounts.SkipServerPassword {
  1230. return nil, errors.New("Using a server password and login-via-pass-command requires skip-server-password as well")
  1231. }
  1232. // #1634: accounts.registration.allow-before-connect is an auth bypass
  1233. // for configurations that start from default and then enable server.password
  1234. config.Accounts.Registration.AllowBeforeConnect = false
  1235. }
  1236. if config.Accounts.RequireSasl.Enabled {
  1237. // minor gotcha: Tor listeners will typically be loopback and
  1238. // therefore exempted from require-sasl. if require-sasl is enabled
  1239. // for non-Tor (non-local) connections, enable it for Tor as well:
  1240. config.Server.TorListeners.RequireSasl = true
  1241. }
  1242. config.Accounts.RequireSasl.exemptedNets, err = utils.ParseNetList(config.Accounts.RequireSasl.Exempted)
  1243. if err != nil {
  1244. return nil, fmt.Errorf("Could not parse require-sasl exempted nets: %v", err.Error())
  1245. }
  1246. config.Server.proxyAllowedFromNets, err = utils.ParseNetList(config.Server.ProxyAllowedFrom)
  1247. if err != nil {
  1248. return nil, fmt.Errorf("Could not parse proxy-allowed-from nets: %v", err.Error())
  1249. }
  1250. config.Server.secureNets, err = utils.ParseNetList(config.Server.SecureNetDefs)
  1251. if err != nil {
  1252. return nil, fmt.Errorf("Could not parse secure-nets: %v\n", err.Error())
  1253. }
  1254. rawRegexp := config.Accounts.VHosts.ValidRegexpRaw
  1255. if rawRegexp != "" {
  1256. regexp, err := regexp.Compile(rawRegexp)
  1257. if err == nil {
  1258. config.Accounts.VHosts.validRegexp = regexp
  1259. } else {
  1260. log.Printf("invalid vhost regexp: %s\n", err.Error())
  1261. }
  1262. }
  1263. if config.Accounts.VHosts.validRegexp == nil {
  1264. config.Accounts.VHosts.validRegexp = defaultValidVhostRegex
  1265. }
  1266. if config.Accounts.AuthenticationEnabled {
  1267. saslCapValues := []string{"PLAIN", "EXTERNAL"}
  1268. if config.Accounts.AdvertiseSCRAM {
  1269. saslCapValues = append(saslCapValues, "SCRAM-SHA-256")
  1270. }
  1271. if config.Accounts.OAuth2.Enabled {
  1272. saslCapValues = append(saslCapValues, "OAUTHBEARER")
  1273. }
  1274. config.Server.capValues[caps.SASL] = strings.Join(saslCapValues, ",")
  1275. } else {
  1276. config.Server.supportedCaps.Disable(caps.SASL)
  1277. }
  1278. if err := config.Accounts.OAuth2.Postprocess(); err != nil {
  1279. return nil, err
  1280. }
  1281. if err := config.Accounts.JWTAuth.Postprocess(); err != nil {
  1282. return nil, err
  1283. }
  1284. if config.Accounts.OAuth2.Enabled && config.Accounts.OAuth2.AuthScript && !config.Accounts.AuthScript.Enabled {
  1285. return nil, fmt.Errorf("oauth2 is enabled with auth-script, but no auth-script is enabled")
  1286. }
  1287. var bearerCapValues []string
  1288. if config.Accounts.OAuth2.Enabled {
  1289. bearerCapValues = append(bearerCapValues, "oauth2")
  1290. }
  1291. if config.Accounts.JWTAuth.Enabled {
  1292. bearerCapValues = append(bearerCapValues, "jwt")
  1293. }
  1294. if len(bearerCapValues) != 0 {
  1295. config.Server.capValues[caps.Bearer] = strings.Join(bearerCapValues, ",")
  1296. } else {
  1297. config.Server.supportedCaps.Disable(caps.Bearer)
  1298. }
  1299. if !config.Accounts.Registration.Enabled {
  1300. config.Server.supportedCaps.Disable(caps.AccountRegistration)
  1301. } else {
  1302. var registerValues []string
  1303. if config.Accounts.Registration.AllowBeforeConnect {
  1304. registerValues = append(registerValues, "before-connect")
  1305. }
  1306. if config.Accounts.Registration.EmailVerification.Enabled {
  1307. registerValues = append(registerValues, "email-required")
  1308. }
  1309. if config.Accounts.RequireSasl.Enabled {
  1310. registerValues = append(registerValues, "account-required")
  1311. }
  1312. if len(registerValues) != 0 {
  1313. config.Server.capValues[caps.AccountRegistration] = strings.Join(registerValues, ",")
  1314. }
  1315. }
  1316. maxSendQBytes, err := bytefmt.ToBytes(config.Server.MaxSendQString)
  1317. if err != nil {
  1318. return nil, fmt.Errorf("Could not parse maximum SendQ size (make sure it only contains whole numbers): %s", err.Error())
  1319. }
  1320. config.Server.MaxSendQBytes = int(maxSendQBytes)
  1321. config.languageManager, err = languages.NewManager(config.Languages.Enabled, config.Languages.Path, config.Languages.Default)
  1322. if err != nil {
  1323. return nil, fmt.Errorf("Could not load languages: %s", err.Error())
  1324. }
  1325. config.Server.capValues[caps.Languages] = config.languageManager.CapValue()
  1326. if len(config.Fakelag.CommandBudgets) != 0 {
  1327. // normalize command names to uppercase:
  1328. commandBudgets := make(map[string]int, len(config.Fakelag.CommandBudgets))
  1329. for command, budget := range config.Fakelag.CommandBudgets {
  1330. commandBudgets[strings.ToUpper(command)] = budget
  1331. }
  1332. config.Fakelag.CommandBudgets = commandBudgets
  1333. } else {
  1334. config.Fakelag.CommandBudgets = nil
  1335. }
  1336. if config.Server.Relaymsg.Enabled {
  1337. for _, char := range protocolBreakingNameCharacters {
  1338. if strings.ContainsRune(config.Server.Relaymsg.Separators, char) {
  1339. return nil, fmt.Errorf("RELAYMSG separators cannot include the characters %s", protocolBreakingNameCharacters)
  1340. }
  1341. }
  1342. config.Server.capValues[caps.Relaymsg] = config.Server.Relaymsg.Separators
  1343. } else {
  1344. config.Server.supportedCaps.Disable(caps.Relaymsg)
  1345. }
  1346. config.Debug.recoverFromErrors = utils.BoolDefaultTrue(config.Debug.RecoverFromErrors)
  1347. // process operator definitions, store them to config.operators
  1348. operclasses, err := config.OperatorClasses()
  1349. if err != nil {
  1350. return nil, err
  1351. }
  1352. opers, err := config.Operators(operclasses)
  1353. if err != nil {
  1354. return nil, err
  1355. }
  1356. config.operators = opers
  1357. // parse default channel modes
  1358. config.Channels.defaultModes = ParseDefaultChannelModes(config.Channels.DefaultModes)
  1359. if config.Accounts.Registration.BcryptCost == 0 {
  1360. config.Accounts.Registration.BcryptCost = passwd.DefaultCost
  1361. }
  1362. if config.Channels.MaxChannelsPerClient == 0 {
  1363. config.Channels.MaxChannelsPerClient = 100
  1364. }
  1365. if config.Channels.Registration.MaxChannelsPerAccount == 0 {
  1366. config.Channels.Registration.MaxChannelsPerAccount = 15
  1367. }
  1368. config.Server.Compatibility.forceTrailing = utils.BoolDefaultTrue(config.Server.Compatibility.ForceTrailing)
  1369. config.Server.Compatibility.allowTruncation = utils.BoolDefaultTrue(config.Server.Compatibility.AllowTruncation)
  1370. config.loadMOTD()
  1371. // in the current implementation, we disable history by creating a history buffer
  1372. // with zero capacity. but the `enabled` config option MUST be respected regardless
  1373. // of this detail
  1374. if !config.History.Enabled {
  1375. config.History.ChannelLength = 0
  1376. config.History.ClientLength = 0
  1377. config.Server.supportedCaps.Disable(caps.Chathistory)
  1378. config.Server.supportedCaps.Disable(caps.EventPlayback)
  1379. config.Server.supportedCaps.Disable(caps.ZNCPlayback)
  1380. }
  1381. if !config.History.Enabled || !config.History.Persistent.Enabled {
  1382. config.History.Persistent.Enabled = false
  1383. config.History.Persistent.UnregisteredChannels = false
  1384. config.History.Persistent.RegisteredChannels = PersistentDisabled
  1385. config.History.Persistent.DirectMessages = PersistentDisabled
  1386. }
  1387. if config.History.Persistent.Enabled && !config.Datastore.MySQL.Enabled {
  1388. return nil, fmt.Errorf("You must configure a MySQL server in order to enable persistent history")
  1389. }
  1390. if config.History.ZNCMax == 0 {
  1391. config.History.ZNCMax = config.History.ChathistoryMax
  1392. }
  1393. if config.History.Restrictions.QueryCutoff != "" {
  1394. config.History.Restrictions.queryCutoff, err = historyCutoffFromString(config.History.Restrictions.QueryCutoff)
  1395. if err != nil {
  1396. return nil, fmt.Errorf("invalid value of history.query-restrictions: %w", err)
  1397. }
  1398. } else {
  1399. if config.History.Restrictions.EnforceRegistrationDate_ {
  1400. config.History.Restrictions.queryCutoff = HistoryCutoffRegistrationTime
  1401. } else {
  1402. config.History.Restrictions.queryCutoff = HistoryCutoffNone
  1403. }
  1404. }
  1405. config.Roleplay.addSuffix = utils.BoolDefaultTrue(config.Roleplay.AddSuffix)
  1406. config.Datastore.MySQL.ExpireTime = time.Duration(config.History.Restrictions.ExpireTime)
  1407. config.Datastore.MySQL.TrackAccountMessages = config.History.Retention.EnableAccountIndexing
  1408. if config.Datastore.MySQL.MaxConns == 0 {
  1409. // #1622: not putting an upper limit on the number of MySQL connections is
  1410. // potentially dangerous. as a naive heuristic, assume they're running on the
  1411. // same machine:
  1412. config.Datastore.MySQL.MaxConns = runtime.NumCPU()
  1413. }
  1414. config.Server.Cloaks.Initialize()
  1415. if config.Server.Cloaks.Enabled {
  1416. if !utils.IsHostname(config.Server.Cloaks.Netname) {
  1417. return nil, fmt.Errorf("Invalid netname for cloaked hostnames: %s", config.Server.Cloaks.Netname)
  1418. }
  1419. }
  1420. err = config.processExtjwt()
  1421. if err != nil {
  1422. return nil, err
  1423. }
  1424. // now that all postprocessing is complete, regenerate ISUPPORT:
  1425. err = config.generateISupport()
  1426. if err != nil {
  1427. return nil, err
  1428. }
  1429. // #1428: Tor listeners should never see STS
  1430. config.Server.supportedCapsWithoutSTS = caps.NewSet()
  1431. config.Server.supportedCapsWithoutSTS.Union(config.Server.supportedCaps)
  1432. config.Server.supportedCapsWithoutSTS.Disable(caps.STS)
  1433. return config, nil
  1434. }
  1435. func (config *Config) getOutputPath(filename string) string {
  1436. return filepath.Join(config.Server.OutputPath, filename)
  1437. }
  1438. func (config *Config) isRelaymsgIdentifier(nick string) bool {
  1439. if !config.Server.Relaymsg.Enabled {
  1440. return false
  1441. }
  1442. if strings.HasPrefix(nick, "#") {
  1443. return false // #2114
  1444. }
  1445. for _, char := range config.Server.Relaymsg.Separators {
  1446. if strings.ContainsRune(nick, char) {
  1447. return true
  1448. }
  1449. }
  1450. return false
  1451. }
  1452. // setISupport sets up our RPL_ISUPPORT reply.
  1453. func (config *Config) generateISupport() (err error) {
  1454. maxTargetsString := strconv.Itoa(maxTargets)
  1455. // add RPL_ISUPPORT tokens
  1456. isupport := &config.Server.isupport
  1457. isupport.Initialize()
  1458. isupport.Add("AWAYLEN", strconv.Itoa(config.Limits.AwayLen))
  1459. isupport.Add("BOT", "B")
  1460. isupport.Add("CASEMAPPING", "ascii")
  1461. isupport.Add("CHANLIMIT", fmt.Sprintf("%s:%d", chanTypes, config.Channels.MaxChannelsPerClient))
  1462. isupport.Add("CHANMODES", chanmodesToken)
  1463. if config.History.Enabled && config.History.ChathistoryMax > 0 {
  1464. isupport.Add("CHATHISTORY", strconv.Itoa(config.History.ChathistoryMax))
  1465. // Kiwi expects this legacy token name:
  1466. isupport.Add("draft/CHATHISTORY", strconv.Itoa(config.History.ChathistoryMax))
  1467. }
  1468. isupport.Add("CHANNELLEN", strconv.Itoa(config.Limits.ChannelLen))
  1469. isupport.Add("CHANTYPES", chanTypes)
  1470. isupport.Add("ELIST", "U")
  1471. isupport.Add("EXCEPTS", "")
  1472. if config.Extjwt.Default.Enabled() || len(config.Extjwt.Services) != 0 {
  1473. isupport.Add("EXTJWT", "1")
  1474. }
  1475. isupport.Add("EXTBAN", ",m")
  1476. isupport.Add("FORWARD", "f")
  1477. isupport.Add("INVEX", "")
  1478. isupport.Add("KICKLEN", strconv.Itoa(config.Limits.KickLen))
  1479. isupport.Add("MAXLIST", fmt.Sprintf("beI:%s", strconv.Itoa(config.Limits.ChanListModes)))
  1480. isupport.Add("MAXTARGETS", maxTargetsString)
  1481. isupport.Add("MSGREFTYPES", "msgid,timestamp")
  1482. isupport.Add("MODES", "")
  1483. isupport.Add("MONITOR", strconv.Itoa(config.Limits.MonitorEntries))
  1484. isupport.Add("NETWORK", config.Network.Name)
  1485. isupport.Add("NICKLEN", strconv.Itoa(config.Limits.NickLen))
  1486. isupport.Add("PREFIX", "(qaohv)~&@%+")
  1487. if config.Roleplay.Enabled {
  1488. isupport.Add("RPCHAN", "E")
  1489. isupport.Add("RPUSER", "E")
  1490. }
  1491. isupport.Add("STATUSMSG", "~&@%+")
  1492. 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))
  1493. isupport.Add("TOPICLEN", strconv.Itoa(config.Limits.TopicLen))
  1494. if config.Server.Casemapping == CasemappingPRECIS {
  1495. isupport.Add("UTF8MAPPING", precisUTF8MappingToken)
  1496. }
  1497. if config.Server.EnforceUtf8 {
  1498. isupport.Add("UTF8ONLY", "")
  1499. }
  1500. isupport.Add("WHOX", "")
  1501. err = isupport.RegenerateCachedReply()
  1502. return
  1503. }
  1504. // Diff returns changes in supported caps across a rehash.
  1505. func (config *Config) Diff(oldConfig *Config) (addedCaps, removedCaps *caps.Set) {
  1506. addedCaps = caps.NewSet()
  1507. removedCaps = caps.NewSet()
  1508. if oldConfig == nil {
  1509. return
  1510. }
  1511. if oldConfig.Server.capValues[caps.Languages] != config.Server.capValues[caps.Languages] {
  1512. // XXX updated caps get a DEL line and then a NEW line with the new value
  1513. addedCaps.Add(caps.Languages)
  1514. removedCaps.Add(caps.Languages)
  1515. }
  1516. if !oldConfig.Accounts.AuthenticationEnabled && config.Accounts.AuthenticationEnabled {
  1517. addedCaps.Add(caps.SASL)
  1518. } else if oldConfig.Accounts.AuthenticationEnabled && !config.Accounts.AuthenticationEnabled {
  1519. removedCaps.Add(caps.SASL)
  1520. }
  1521. if oldConfig.Limits.Multiline.MaxBytes != 0 && config.Limits.Multiline.MaxBytes == 0 {
  1522. removedCaps.Add(caps.Multiline)
  1523. } else if oldConfig.Limits.Multiline.MaxBytes == 0 && config.Limits.Multiline.MaxBytes != 0 {
  1524. addedCaps.Add(caps.Multiline)
  1525. } else if oldConfig.Limits.Multiline != config.Limits.Multiline {
  1526. removedCaps.Add(caps.Multiline)
  1527. addedCaps.Add(caps.Multiline)
  1528. }
  1529. if oldConfig.Server.STS.Enabled != config.Server.STS.Enabled || oldConfig.Server.capValues[caps.STS] != config.Server.capValues[caps.STS] {
  1530. // XXX: STS is always removed by CAP NEW sts=duration=0, not CAP DEL
  1531. // so the appropriate notify is always a CAP NEW; put it in addedCaps for any change
  1532. addedCaps.Add(caps.STS)
  1533. }
  1534. return
  1535. }
  1536. // determine whether we need to resize / create / destroy
  1537. // the in-memory history buffers:
  1538. func (config *Config) historyChangedFrom(oldConfig *Config) bool {
  1539. return config.History.Enabled != oldConfig.History.Enabled ||
  1540. config.History.ChannelLength != oldConfig.History.ChannelLength ||
  1541. config.History.ClientLength != oldConfig.History.ClientLength ||
  1542. config.History.AutoresizeWindow != oldConfig.History.AutoresizeWindow ||
  1543. config.History.Persistent != oldConfig.History.Persistent
  1544. }
  1545. func compileGuestRegexp(guestFormat string, casemapping Casemapping) (standard, folded *regexp.Regexp, err error) {
  1546. if strings.Count(guestFormat, "?") != 0 || strings.Count(guestFormat, "*") != 1 {
  1547. err = errors.New("guest format must contain 1 '*' and no '?'s")
  1548. return
  1549. }
  1550. standard, err = utils.CompileGlob(guestFormat, true)
  1551. if err != nil {
  1552. return
  1553. }
  1554. starIndex := strings.IndexByte(guestFormat, '*')
  1555. initial := guestFormat[:starIndex]
  1556. final := guestFormat[starIndex+1:]
  1557. initialFolded, err := casefoldWithSetting(initial, casemapping)
  1558. if err != nil {
  1559. return
  1560. }
  1561. finalFolded, err := casefoldWithSetting(final, casemapping)
  1562. if err != nil {
  1563. return
  1564. }
  1565. folded, err = utils.CompileGlob(fmt.Sprintf("%s*%s", initialFolded, finalFolded), false)
  1566. return
  1567. }
  1568. func (config *Config) loadMOTD() error {
  1569. if config.Server.MOTD != "" {
  1570. file, err := os.Open(config.Server.MOTD)
  1571. if err != nil {
  1572. return err
  1573. }
  1574. defer file.Close()
  1575. contents, err := io.ReadAll(file)
  1576. if err != nil {
  1577. return err
  1578. }
  1579. lines := bytes.Split(contents, []byte{'\n'})
  1580. for i, line := range lines {
  1581. lineToSend := string(bytes.TrimRight(line, "\r\n"))
  1582. if len(lineToSend) == 0 && i == len(lines)-1 {
  1583. // if the last line of the MOTD was properly terminated with \n,
  1584. // there's no need to send a blank line to clients
  1585. continue
  1586. }
  1587. if config.Server.MOTDFormatting {
  1588. lineToSend = ircfmt.Unescape(lineToSend)
  1589. }
  1590. // "- " is the required prefix for MOTD
  1591. lineToSend = fmt.Sprintf("- %s", lineToSend)
  1592. config.Server.motdLines = append(config.Server.motdLines, lineToSend)
  1593. }
  1594. }
  1595. return nil
  1596. }