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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350
  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.UnregisteredChannels = false
  1034. config.History.Persistent.RegisteredChannels = PersistentDisabled
  1035. config.History.Persistent.DirectMessages = PersistentDisabled
  1036. }
  1037. if config.History.ZNCMax == 0 {
  1038. config.History.ZNCMax = config.History.ChathistoryMax
  1039. }
  1040. config.Roleplay.enabled = utils.BoolDefaultTrue(config.Roleplay.Enabled)
  1041. config.Roleplay.addSuffix = utils.BoolDefaultTrue(config.Roleplay.AddSuffix)
  1042. config.Datastore.MySQL.ExpireTime = time.Duration(config.History.Restrictions.ExpireTime)
  1043. config.Datastore.MySQL.TrackAccountMessages = config.History.Retention.EnableAccountIndexing
  1044. config.Server.Cloaks.Initialize()
  1045. if config.Server.Cloaks.Enabled {
  1046. if !utils.IsHostname(config.Server.Cloaks.Netname) {
  1047. return nil, fmt.Errorf("Invalid netname for cloaked hostnames: %s", config.Server.Cloaks.Netname)
  1048. }
  1049. }
  1050. err = config.processExtjwt()
  1051. if err != nil {
  1052. return nil, err
  1053. }
  1054. // now that all postprocessing is complete, regenerate ISUPPORT:
  1055. err = config.generateISupport()
  1056. if err != nil {
  1057. return nil, err
  1058. }
  1059. err = config.prepareListeners()
  1060. if err != nil {
  1061. return nil, fmt.Errorf("failed to prepare listeners: %v", err)
  1062. }
  1063. return config, nil
  1064. }
  1065. func (config *Config) getOutputPath(filename string) string {
  1066. return filepath.Join(config.Server.OutputPath, filename)
  1067. }
  1068. // setISupport sets up our RPL_ISUPPORT reply.
  1069. func (config *Config) generateISupport() (err error) {
  1070. maxTargetsString := strconv.Itoa(maxTargets)
  1071. // add RPL_ISUPPORT tokens
  1072. isupport := &config.Server.isupport
  1073. isupport.Initialize()
  1074. isupport.Add("AWAYLEN", strconv.Itoa(config.Limits.AwayLen))
  1075. isupport.Add("BOT", "B")
  1076. isupport.Add("CASEMAPPING", "ascii")
  1077. isupport.Add("CHANLIMIT", fmt.Sprintf("%s:%d", chanTypes, config.Channels.MaxChannelsPerClient))
  1078. 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()}, ","))
  1079. if config.History.Enabled && config.History.ChathistoryMax > 0 {
  1080. isupport.Add("draft/CHATHISTORY", strconv.Itoa(config.History.ChathistoryMax))
  1081. }
  1082. isupport.Add("CHANNELLEN", strconv.Itoa(config.Limits.ChannelLen))
  1083. isupport.Add("CHANTYPES", chanTypes)
  1084. isupport.Add("ELIST", "U")
  1085. isupport.Add("EXCEPTS", "")
  1086. if config.Extjwt.Default.Enabled() || len(config.Extjwt.Services) != 0 {
  1087. isupport.Add("EXTJWT", "1")
  1088. }
  1089. isupport.Add("INVEX", "")
  1090. isupport.Add("KICKLEN", strconv.Itoa(config.Limits.KickLen))
  1091. isupport.Add("MAXLIST", fmt.Sprintf("beI:%s", strconv.Itoa(config.Limits.ChanListModes)))
  1092. isupport.Add("MAXTARGETS", maxTargetsString)
  1093. isupport.Add("MODES", "")
  1094. isupport.Add("MONITOR", strconv.Itoa(config.Limits.MonitorEntries))
  1095. isupport.Add("NETWORK", config.Network.Name)
  1096. isupport.Add("NICKLEN", strconv.Itoa(config.Limits.NickLen))
  1097. isupport.Add("PREFIX", "(qaohv)~&@%+")
  1098. if config.Roleplay.enabled {
  1099. isupport.Add("RPCHAN", "E")
  1100. isupport.Add("RPUSER", "E")
  1101. }
  1102. isupport.Add("STATUSMSG", "~&@%+")
  1103. 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))
  1104. isupport.Add("TOPICLEN", strconv.Itoa(config.Limits.TopicLen))
  1105. if config.Server.Casemapping == CasemappingPRECIS {
  1106. isupport.Add("UTF8MAPPING", precisUTF8MappingToken)
  1107. }
  1108. isupport.Add("WHOX", "")
  1109. err = isupport.RegenerateCachedReply()
  1110. return
  1111. }
  1112. // Diff returns changes in supported caps across a rehash.
  1113. func (config *Config) Diff(oldConfig *Config) (addedCaps, removedCaps *caps.Set) {
  1114. addedCaps = caps.NewSet()
  1115. removedCaps = caps.NewSet()
  1116. if oldConfig == nil {
  1117. return
  1118. }
  1119. if oldConfig.Server.capValues[caps.Languages] != config.Server.capValues[caps.Languages] {
  1120. // XXX updated caps get a DEL line and then a NEW line with the new value
  1121. addedCaps.Add(caps.Languages)
  1122. removedCaps.Add(caps.Languages)
  1123. }
  1124. if !oldConfig.Accounts.AuthenticationEnabled && config.Accounts.AuthenticationEnabled {
  1125. addedCaps.Add(caps.SASL)
  1126. } else if oldConfig.Accounts.AuthenticationEnabled && !config.Accounts.AuthenticationEnabled {
  1127. removedCaps.Add(caps.SASL)
  1128. }
  1129. if oldConfig.Limits.Multiline.MaxBytes != 0 && config.Limits.Multiline.MaxBytes == 0 {
  1130. removedCaps.Add(caps.Multiline)
  1131. } else if oldConfig.Limits.Multiline.MaxBytes == 0 && config.Limits.Multiline.MaxBytes != 0 {
  1132. addedCaps.Add(caps.Multiline)
  1133. } else if oldConfig.Limits.Multiline != config.Limits.Multiline {
  1134. removedCaps.Add(caps.Multiline)
  1135. addedCaps.Add(caps.Multiline)
  1136. }
  1137. if oldConfig.Server.STS.Enabled != config.Server.STS.Enabled || oldConfig.Server.capValues[caps.STS] != config.Server.capValues[caps.STS] {
  1138. // XXX: STS is always removed by CAP NEW sts=duration=0, not CAP DEL
  1139. // so the appropriate notify is always a CAP NEW; put it in addedCaps for any change
  1140. addedCaps.Add(caps.STS)
  1141. }
  1142. return
  1143. }
  1144. // determine whether we need to resize / create / destroy
  1145. // the in-memory history buffers:
  1146. func (config *Config) historyChangedFrom(oldConfig *Config) bool {
  1147. return config.History.Enabled != oldConfig.History.Enabled ||
  1148. config.History.ChannelLength != oldConfig.History.ChannelLength ||
  1149. config.History.ClientLength != oldConfig.History.ClientLength ||
  1150. config.History.AutoresizeWindow != oldConfig.History.AutoresizeWindow ||
  1151. config.History.Persistent != oldConfig.History.Persistent
  1152. }
  1153. func compileGuestRegexp(guestFormat string, casemapping Casemapping) (standard, folded *regexp.Regexp, err error) {
  1154. if strings.Count(guestFormat, "?") != 0 || strings.Count(guestFormat, "*") != 1 {
  1155. err = errors.New("guest format must contain 1 '*' and no '?'s")
  1156. return
  1157. }
  1158. standard, err = utils.CompileGlob(guestFormat, true)
  1159. if err != nil {
  1160. return
  1161. }
  1162. starIndex := strings.IndexByte(guestFormat, '*')
  1163. initial := guestFormat[:starIndex]
  1164. final := guestFormat[starIndex+1:]
  1165. initialFolded, err := casefoldWithSetting(initial, casemapping)
  1166. if err != nil {
  1167. return
  1168. }
  1169. finalFolded, err := casefoldWithSetting(final, casemapping)
  1170. if err != nil {
  1171. return
  1172. }
  1173. folded, err = utils.CompileGlob(fmt.Sprintf("%s*%s", initialFolded, finalFolded), false)
  1174. return
  1175. }
  1176. func (config *Config) loadMOTD() error {
  1177. if config.Server.MOTD != "" {
  1178. file, err := os.Open(config.Server.MOTD)
  1179. if err != nil {
  1180. return err
  1181. }
  1182. defer file.Close()
  1183. contents, err := ioutil.ReadAll(file)
  1184. if err != nil {
  1185. return err
  1186. }
  1187. lines := bytes.Split(contents, []byte{'\n'})
  1188. for i, line := range lines {
  1189. lineToSend := string(bytes.TrimRight(line, "\r\n"))
  1190. if len(lineToSend) == 0 && i == len(lines)-1 {
  1191. // if the last line of the MOTD was properly terminated with \n,
  1192. // there's no need to send a blank line to clients
  1193. continue
  1194. }
  1195. if config.Server.MOTDFormatting {
  1196. lineToSend = ircfmt.Unescape(lineToSend)
  1197. }
  1198. // "- " is the required prefix for MOTD
  1199. lineToSend = fmt.Sprintf("- %s", lineToSend)
  1200. config.Server.motdLines = append(config.Server.motdLines, lineToSend)
  1201. }
  1202. }
  1203. return nil
  1204. }