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 41KB

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