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

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