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

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