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

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