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

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