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

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