Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

config.go 39KB

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