Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

config.go 43KB

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