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

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