You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

config.go 53KB

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