Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

config.go 43KB

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