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

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