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

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