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

config.go 53KB

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