Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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