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

config.go 52KB

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