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

config.go 51KB

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