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

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