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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341
  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. OfferList []string `yaml:"offer-list"`
  293. }
  294. type NickEnforcementMethod int
  295. const (
  296. // NickEnforcementOptional is the zero value; it serializes to
  297. // "optional" in the yaml config, and "default" as an arg to `NS ENFORCE`.
  298. // in both cases, it means "defer to the other source of truth", i.e.,
  299. // in the config, defer to the user's custom setting, and as a custom setting,
  300. // defer to the default in the config. if both are NickEnforcementOptional then
  301. // there is no enforcement.
  302. // XXX: these are serialized as numbers in the database, so beware of collisions
  303. // when refactoring (any numbers currently in use must keep their meanings, or
  304. // else be fixed up by a schema change)
  305. NickEnforcementOptional NickEnforcementMethod = iota
  306. NickEnforcementNone
  307. NickEnforcementStrict
  308. )
  309. func nickReservationToString(method NickEnforcementMethod) string {
  310. switch method {
  311. case NickEnforcementOptional:
  312. return "default"
  313. case NickEnforcementNone:
  314. return "none"
  315. case NickEnforcementStrict:
  316. return "strict"
  317. default:
  318. return ""
  319. }
  320. }
  321. func nickReservationFromString(method string) (NickEnforcementMethod, error) {
  322. switch strings.ToLower(method) {
  323. case "default":
  324. return NickEnforcementOptional, nil
  325. case "optional":
  326. return NickEnforcementOptional, nil
  327. case "none":
  328. return NickEnforcementNone, nil
  329. case "strict":
  330. return NickEnforcementStrict, nil
  331. default:
  332. return NickEnforcementOptional, fmt.Errorf("invalid nick-reservation.method value: %s", method)
  333. }
  334. }
  335. func (nr *NickEnforcementMethod) UnmarshalYAML(unmarshal func(interface{}) error) error {
  336. var orig string
  337. var err error
  338. if err = unmarshal(&orig); err != nil {
  339. return err
  340. }
  341. method, err := nickReservationFromString(orig)
  342. if err == nil {
  343. *nr = method
  344. }
  345. return err
  346. }
  347. func (cm *Casemapping) UnmarshalYAML(unmarshal func(interface{}) error) (err error) {
  348. var orig string
  349. if err = unmarshal(&orig); err != nil {
  350. return err
  351. }
  352. var result Casemapping
  353. switch strings.ToLower(orig) {
  354. case "ascii":
  355. result = CasemappingASCII
  356. case "precis", "rfc7613", "rfc8265":
  357. result = CasemappingPRECIS
  358. case "permissive", "fun":
  359. result = CasemappingPermissive
  360. default:
  361. return fmt.Errorf("invalid casemapping value: %s", orig)
  362. }
  363. *cm = result
  364. return nil
  365. }
  366. // OperClassConfig defines a specific operator class.
  367. type OperClassConfig struct {
  368. Title string
  369. WhoisLine string
  370. Extends string
  371. Capabilities []string
  372. }
  373. // OperConfig defines a specific operator's configuration.
  374. type OperConfig struct {
  375. Class string
  376. Vhost string
  377. WhoisLine string `yaml:"whois-line"`
  378. Password string
  379. Fingerprint *string // legacy name for certfp, #1050
  380. Certfp string
  381. Auto bool
  382. Modes string
  383. }
  384. // Various server-enforced limits on data size.
  385. type Limits struct {
  386. AwayLen int `yaml:"awaylen"`
  387. ChanListModes int `yaml:"chan-list-modes"`
  388. ChannelLen int `yaml:"channellen"`
  389. IdentLen int `yaml:"identlen"`
  390. KickLen int `yaml:"kicklen"`
  391. MonitorEntries int `yaml:"monitor-entries"`
  392. NickLen int `yaml:"nicklen"`
  393. TopicLen int `yaml:"topiclen"`
  394. WhowasEntries int `yaml:"whowas-entries"`
  395. RegistrationMessages int `yaml:"registration-messages"`
  396. Multiline struct {
  397. MaxBytes int `yaml:"max-bytes"`
  398. MaxLines int `yaml:"max-lines"`
  399. }
  400. }
  401. // STSConfig controls the STS configuration/
  402. type STSConfig struct {
  403. Enabled bool
  404. Duration custime.Duration
  405. Port int
  406. Preload bool
  407. STSOnlyBanner string `yaml:"sts-only-banner"`
  408. bannerLines []string
  409. }
  410. // Value returns the STS value to advertise in CAP
  411. func (sts *STSConfig) Value() string {
  412. val := fmt.Sprintf("duration=%d", int(time.Duration(sts.Duration).Seconds()))
  413. if sts.Enabled && sts.Port > 0 {
  414. val += fmt.Sprintf(",port=%d", sts.Port)
  415. }
  416. if sts.Enabled && sts.Preload {
  417. val += ",preload"
  418. }
  419. return val
  420. }
  421. type FakelagConfig struct {
  422. Enabled bool
  423. Window time.Duration
  424. BurstLimit uint `yaml:"burst-limit"`
  425. MessagesPerWindow uint `yaml:"messages-per-window"`
  426. Cooldown time.Duration
  427. }
  428. type TorListenersConfig struct {
  429. Listeners []string // legacy only
  430. RequireSasl bool `yaml:"require-sasl"`
  431. Vhost string
  432. MaxConnections int `yaml:"max-connections"`
  433. ThrottleDuration time.Duration `yaml:"throttle-duration"`
  434. MaxConnectionsPerDuration int `yaml:"max-connections-per-duration"`
  435. }
  436. // Config defines the overall configuration.
  437. type Config struct {
  438. Network struct {
  439. Name string
  440. }
  441. Server struct {
  442. Password string
  443. passwordBytes []byte
  444. Name string
  445. nameCasefolded string
  446. // Listeners is the new style for configuring listeners:
  447. Listeners map[string]listenerConfigBlock
  448. UnixBindMode os.FileMode `yaml:"unix-bind-mode"`
  449. TorListeners TorListenersConfig `yaml:"tor-listeners"`
  450. WebSockets struct {
  451. AllowedOrigins []string `yaml:"allowed-origins"`
  452. allowedOriginRegexps []*regexp.Regexp
  453. }
  454. // they get parsed into this internal representation:
  455. trueListeners map[string]utils.ListenerConfig
  456. STS STSConfig
  457. LookupHostnames *bool `yaml:"lookup-hostnames"`
  458. lookupHostnames bool
  459. ForwardConfirmHostnames bool `yaml:"forward-confirm-hostnames"`
  460. CheckIdent bool `yaml:"check-ident"`
  461. MOTD string
  462. motdLines []string
  463. MOTDFormatting bool `yaml:"motd-formatting"`
  464. ProxyAllowedFrom []string `yaml:"proxy-allowed-from"`
  465. proxyAllowedFromNets []net.IPNet
  466. WebIRC []webircConfig `yaml:"webirc"`
  467. MaxSendQString string `yaml:"max-sendq"`
  468. MaxSendQBytes int
  469. AllowPlaintextResume bool `yaml:"allow-plaintext-resume"`
  470. Compatibility struct {
  471. ForceTrailing *bool `yaml:"force-trailing"`
  472. forceTrailing bool
  473. SendUnprefixedSasl bool `yaml:"send-unprefixed-sasl"`
  474. }
  475. isupport isupport.List
  476. IPLimits connection_limits.LimiterConfig `yaml:"ip-limits"`
  477. Cloaks cloaks.CloakConfig `yaml:"ip-cloaking"`
  478. SecureNetDefs []string `yaml:"secure-nets"`
  479. secureNets []net.IPNet
  480. supportedCaps *caps.Set
  481. capValues caps.Values
  482. Casemapping Casemapping
  483. EnforceUtf8 bool `yaml:"enforce-utf8"`
  484. OutputPath string `yaml:"output-path"`
  485. }
  486. Roleplay struct {
  487. Enabled *bool
  488. enabled bool
  489. RequireChanops bool `yaml:"require-chanops"`
  490. RequireOper bool `yaml:"require-oper"`
  491. AddSuffix *bool `yaml:"add-suffix"`
  492. addSuffix bool
  493. }
  494. Extjwt struct {
  495. Default jwt.JwtServiceConfig `yaml:",inline"`
  496. Services map[string]jwt.JwtServiceConfig `yaml:"services"`
  497. }
  498. Languages struct {
  499. Enabled bool
  500. Path string
  501. Default string
  502. }
  503. languageManager *languages.Manager
  504. Datastore struct {
  505. Path string
  506. AutoUpgrade bool
  507. MySQL mysql.Config
  508. }
  509. Accounts AccountConfig
  510. Channels struct {
  511. DefaultModes *string `yaml:"default-modes"`
  512. defaultModes modes.Modes
  513. MaxChannelsPerClient int `yaml:"max-channels-per-client"`
  514. OpOnlyCreation bool `yaml:"operator-only-creation"`
  515. Registration struct {
  516. Enabled bool
  517. OperatorOnly bool `yaml:"operator-only"`
  518. MaxChannelsPerAccount int `yaml:"max-channels-per-account"`
  519. }
  520. ListDelay time.Duration `yaml:"list-delay"`
  521. }
  522. OperClasses map[string]*OperClassConfig `yaml:"oper-classes"`
  523. Opers map[string]*OperConfig
  524. // parsed operator definitions, unexported so they can't be defined
  525. // directly in YAML:
  526. operators map[string]*Oper
  527. Logging []logger.LoggingConfig
  528. Debug struct {
  529. RecoverFromErrors *bool `yaml:"recover-from-errors"`
  530. recoverFromErrors bool
  531. PprofListener *string `yaml:"pprof-listener"`
  532. }
  533. Limits Limits
  534. Fakelag FakelagConfig
  535. History struct {
  536. Enabled bool
  537. ChannelLength int `yaml:"channel-length"`
  538. ClientLength int `yaml:"client-length"`
  539. AutoresizeWindow custime.Duration `yaml:"autoresize-window"`
  540. AutoreplayOnJoin int `yaml:"autoreplay-on-join"`
  541. ChathistoryMax int `yaml:"chathistory-maxmessages"`
  542. ZNCMax int `yaml:"znc-maxmessages"`
  543. Restrictions struct {
  544. ExpireTime custime.Duration `yaml:"expire-time"`
  545. EnforceRegistrationDate bool `yaml:"enforce-registration-date"`
  546. GracePeriod custime.Duration `yaml:"grace-period"`
  547. }
  548. Persistent struct {
  549. Enabled bool
  550. UnregisteredChannels bool `yaml:"unregistered-channels"`
  551. RegisteredChannels PersistentStatus `yaml:"registered-channels"`
  552. DirectMessages PersistentStatus `yaml:"direct-messages"`
  553. }
  554. Retention struct {
  555. AllowIndividualDelete bool `yaml:"allow-individual-delete"`
  556. EnableAccountIndexing bool `yaml:"enable-account-indexing"`
  557. }
  558. }
  559. Filename string
  560. }
  561. // OperClass defines an assembled operator class.
  562. type OperClass struct {
  563. Title string
  564. WhoisLine string `yaml:"whois-line"`
  565. Capabilities StringSet // map to make lookups much easier
  566. }
  567. // OperatorClasses returns a map of assembled operator classes from the given config.
  568. func (conf *Config) OperatorClasses() (map[string]*OperClass, error) {
  569. fixupCapability := func(capab string) string {
  570. return strings.TrimPrefix(capab, "oper:") // #868
  571. }
  572. ocs := make(map[string]*OperClass)
  573. // loop from no extends to most extended, breaking if we can't add any more
  574. lenOfLastOcs := -1
  575. for {
  576. if lenOfLastOcs == len(ocs) {
  577. return nil, ErrOperClassDependencies
  578. }
  579. lenOfLastOcs = len(ocs)
  580. var anyMissing bool
  581. for name, info := range conf.OperClasses {
  582. _, exists := ocs[name]
  583. _, extendsExists := ocs[info.Extends]
  584. if exists {
  585. // class already exists
  586. continue
  587. } else if len(info.Extends) > 0 && !extendsExists {
  588. // class we extend on doesn't exist
  589. _, exists := conf.OperClasses[info.Extends]
  590. if !exists {
  591. return nil, fmt.Errorf("Operclass [%s] extends [%s], which doesn't exist", name, info.Extends)
  592. }
  593. anyMissing = true
  594. continue
  595. }
  596. // create new operclass
  597. var oc OperClass
  598. oc.Capabilities = make(StringSet)
  599. // get inhereted info from other operclasses
  600. if len(info.Extends) > 0 {
  601. einfo := ocs[info.Extends]
  602. for capab := range einfo.Capabilities {
  603. oc.Capabilities.Add(fixupCapability(capab))
  604. }
  605. }
  606. // add our own info
  607. oc.Title = info.Title
  608. for _, capab := range info.Capabilities {
  609. oc.Capabilities.Add(fixupCapability(capab))
  610. }
  611. if len(info.WhoisLine) > 0 {
  612. oc.WhoisLine = info.WhoisLine
  613. } else {
  614. oc.WhoisLine = "is a"
  615. if strings.Contains(strings.ToLower(string(oc.Title[0])), "aeiou") {
  616. oc.WhoisLine += "n"
  617. }
  618. oc.WhoisLine += " "
  619. oc.WhoisLine += oc.Title
  620. }
  621. ocs[name] = &oc
  622. }
  623. if !anyMissing {
  624. // we've got every operclass!
  625. break
  626. }
  627. }
  628. return ocs, nil
  629. }
  630. // Oper represents a single assembled operator's config.
  631. type Oper struct {
  632. Name string
  633. Class *OperClass
  634. WhoisLine string
  635. Vhost string
  636. Pass []byte
  637. Certfp string
  638. Auto bool
  639. Modes []modes.ModeChange
  640. }
  641. // Operators returns a map of operator configs from the given OperClass and config.
  642. func (conf *Config) Operators(oc map[string]*OperClass) (map[string]*Oper, error) {
  643. operators := make(map[string]*Oper)
  644. for name, opConf := range conf.Opers {
  645. var oper Oper
  646. // oper name
  647. name, err := CasefoldName(name)
  648. if err != nil {
  649. return nil, fmt.Errorf("Could not casefold oper name: %s", err.Error())
  650. }
  651. oper.Name = name
  652. if opConf.Password != "" {
  653. oper.Pass, err = decodeLegacyPasswordHash(opConf.Password)
  654. if err != nil {
  655. return nil, fmt.Errorf("Oper %s has an invalid password hash: %s", oper.Name, err.Error())
  656. }
  657. }
  658. certfp := opConf.Certfp
  659. if certfp == "" && opConf.Fingerprint != nil {
  660. certfp = *opConf.Fingerprint
  661. }
  662. if certfp != "" {
  663. oper.Certfp, err = utils.NormalizeCertfp(certfp)
  664. if err != nil {
  665. return nil, fmt.Errorf("Oper %s has an invalid fingerprint: %s", oper.Name, err.Error())
  666. }
  667. }
  668. oper.Auto = opConf.Auto
  669. if oper.Pass == nil && oper.Certfp == "" {
  670. return nil, fmt.Errorf("Oper %s has neither a password nor a fingerprint", name)
  671. }
  672. oper.Vhost = opConf.Vhost
  673. class, exists := oc[opConf.Class]
  674. if !exists {
  675. return nil, fmt.Errorf("Could not load operator [%s] - they use operclass [%s] which does not exist", name, opConf.Class)
  676. }
  677. oper.Class = class
  678. if len(opConf.WhoisLine) > 0 {
  679. oper.WhoisLine = opConf.WhoisLine
  680. } else {
  681. oper.WhoisLine = class.WhoisLine
  682. }
  683. modeStr := strings.TrimSpace(opConf.Modes)
  684. modeChanges, unknownChanges := modes.ParseUserModeChanges(strings.Split(modeStr, " ")...)
  685. if len(unknownChanges) > 0 {
  686. return nil, fmt.Errorf("Could not load operator [%s] due to unknown modes %v", name, unknownChanges)
  687. }
  688. oper.Modes = modeChanges
  689. // successful, attach to list of opers
  690. operators[name] = &oper
  691. }
  692. return operators, nil
  693. }
  694. func loadTlsConfig(config TLSListenConfig, webSocket bool) (tlsConfig *tls.Config, err error) {
  695. cert, err := tls.LoadX509KeyPair(config.Cert, config.Key)
  696. if err != nil {
  697. return nil, &CertKeyError{Err: err}
  698. }
  699. clientAuth := tls.RequestClientCert
  700. if webSocket {
  701. // if Chrome receives a server request for a client certificate
  702. // on a websocket connection, it will immediately disconnect:
  703. // https://bugs.chromium.org/p/chromium/issues/detail?id=329884
  704. // work around this behavior:
  705. clientAuth = tls.NoClientCert
  706. }
  707. result := tls.Config{
  708. Certificates: []tls.Certificate{cert},
  709. ClientAuth: clientAuth,
  710. }
  711. return &result, nil
  712. }
  713. // prepareListeners populates Config.Server.trueListeners
  714. func (conf *Config) prepareListeners() (err error) {
  715. if len(conf.Server.Listeners) == 0 {
  716. return fmt.Errorf("No listeners were configured")
  717. }
  718. conf.Server.trueListeners = make(map[string]utils.ListenerConfig)
  719. for addr, block := range conf.Server.Listeners {
  720. var lconf utils.ListenerConfig
  721. lconf.ProxyDeadline = RegisterTimeout
  722. lconf.Tor = block.Tor
  723. lconf.STSOnly = block.STSOnly
  724. if lconf.STSOnly && !conf.Server.STS.Enabled {
  725. return fmt.Errorf("%s is configured as a STS-only listener, but STS is disabled", addr)
  726. }
  727. if block.TLS.Cert != "" {
  728. tlsConfig, err := loadTlsConfig(block.TLS, block.WebSocket)
  729. if err != nil {
  730. return err
  731. }
  732. lconf.TLSConfig = tlsConfig
  733. lconf.RequireProxy = block.TLS.Proxy
  734. }
  735. lconf.WebSocket = block.WebSocket
  736. conf.Server.trueListeners[addr] = lconf
  737. }
  738. return nil
  739. }
  740. func (config *Config) processExtjwt() (err error) {
  741. // first process the default service, which may be disabled
  742. err = config.Extjwt.Default.Postprocess()
  743. if err != nil {
  744. return
  745. }
  746. // now process the named services. it is an error if any is disabled
  747. // also, normalize the service names to lowercase
  748. services := make(map[string]jwt.JwtServiceConfig, len(config.Extjwt.Services))
  749. for service, sConf := range config.Extjwt.Services {
  750. err := sConf.Postprocess()
  751. if err != nil {
  752. return err
  753. }
  754. if !sConf.Enabled() {
  755. return fmt.Errorf("no keys enabled for extjwt service %s", service)
  756. }
  757. services[strings.ToLower(service)] = sConf
  758. }
  759. config.Extjwt.Services = services
  760. return nil
  761. }
  762. // LoadRawConfig loads the config without doing any consistency checks or postprocessing
  763. func LoadRawConfig(filename string) (config *Config, err error) {
  764. data, err := ioutil.ReadFile(filename)
  765. if err != nil {
  766. return nil, err
  767. }
  768. err = yaml.Unmarshal(data, &config)
  769. if err != nil {
  770. return nil, err
  771. }
  772. return
  773. }
  774. // LoadConfig loads the given YAML configuration file.
  775. func LoadConfig(filename string) (config *Config, err error) {
  776. config, err = LoadRawConfig(filename)
  777. if err != nil {
  778. return nil, err
  779. }
  780. config.Filename = filename
  781. if config.Network.Name == "" {
  782. return nil, ErrNetworkNameMissing
  783. }
  784. if config.Server.Name == "" {
  785. return nil, ErrServerNameMissing
  786. }
  787. if !utils.IsServerName(config.Server.Name) {
  788. return nil, ErrServerNameNotHostname
  789. }
  790. config.Server.nameCasefolded = strings.ToLower(config.Server.Name)
  791. if config.Datastore.Path == "" {
  792. return nil, ErrDatastorePathMissing
  793. }
  794. //dan: automagically fix identlen until a few releases in the future (from now, 0.12.0), being a newly-introduced limit
  795. if config.Limits.IdentLen < 1 {
  796. config.Limits.IdentLen = 20
  797. }
  798. if config.Limits.NickLen < 1 || config.Limits.ChannelLen < 2 || config.Limits.AwayLen < 1 || config.Limits.KickLen < 1 || config.Limits.TopicLen < 1 {
  799. return nil, ErrLimitsAreInsane
  800. }
  801. if config.Limits.RegistrationMessages == 0 {
  802. config.Limits.RegistrationMessages = 1024
  803. }
  804. if config.Datastore.MySQL.Enabled {
  805. if config.Limits.NickLen > mysql.MaxTargetLength || config.Limits.ChannelLen > mysql.MaxTargetLength {
  806. return nil, fmt.Errorf("to use MySQL, nick and channel length limits must be %d or lower", mysql.MaxTargetLength)
  807. }
  808. }
  809. config.Server.supportedCaps = caps.NewCompleteSet()
  810. config.Server.capValues = make(caps.Values)
  811. err = config.prepareListeners()
  812. if err != nil {
  813. return nil, fmt.Errorf("failed to prepare listeners: %v", err)
  814. }
  815. for _, glob := range config.Server.WebSockets.AllowedOrigins {
  816. globre, err := utils.CompileGlob(glob, false)
  817. if err != nil {
  818. return nil, fmt.Errorf("invalid websocket allowed-origin expression: %s", glob)
  819. }
  820. config.Server.WebSockets.allowedOriginRegexps = append(config.Server.WebSockets.allowedOriginRegexps, globre)
  821. }
  822. if config.Server.STS.Enabled {
  823. if config.Server.STS.Port < 0 || config.Server.STS.Port > 65535 {
  824. return nil, fmt.Errorf("STS port is incorrect, should be 0 if disabled: %d", config.Server.STS.Port)
  825. }
  826. if config.Server.STS.STSOnlyBanner != "" {
  827. for _, line := range strings.Split(config.Server.STS.STSOnlyBanner, "\n") {
  828. config.Server.STS.bannerLines = append(config.Server.STS.bannerLines, strings.TrimSpace(line))
  829. }
  830. } else {
  831. 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)}
  832. }
  833. } else {
  834. config.Server.supportedCaps.Disable(caps.STS)
  835. config.Server.STS.Duration = 0
  836. }
  837. // set this even if STS is disabled
  838. config.Server.capValues[caps.STS] = config.Server.STS.Value()
  839. config.Server.lookupHostnames = utils.BoolDefaultTrue(config.Server.LookupHostnames)
  840. // process webirc blocks
  841. var newWebIRC []webircConfig
  842. for _, webirc := range config.Server.WebIRC {
  843. // skip webirc blocks with no hosts (such as the example one)
  844. if len(webirc.Hosts) == 0 {
  845. continue
  846. }
  847. err = webirc.Populate()
  848. if err != nil {
  849. return nil, fmt.Errorf("Could not parse WebIRC config: %s", err.Error())
  850. }
  851. newWebIRC = append(newWebIRC, webirc)
  852. }
  853. config.Server.WebIRC = newWebIRC
  854. if config.Limits.Multiline.MaxBytes <= 0 {
  855. config.Server.supportedCaps.Disable(caps.Multiline)
  856. } else {
  857. var multilineCapValue string
  858. if config.Limits.Multiline.MaxLines == 0 {
  859. multilineCapValue = fmt.Sprintf("max-bytes=%d", config.Limits.Multiline.MaxBytes)
  860. } else {
  861. multilineCapValue = fmt.Sprintf("max-bytes=%d,max-lines=%d", config.Limits.Multiline.MaxBytes, config.Limits.Multiline.MaxLines)
  862. }
  863. config.Server.capValues[caps.Multiline] = multilineCapValue
  864. }
  865. // handle legacy name 'bouncer' for 'multiclient' section:
  866. if config.Accounts.Bouncer != nil {
  867. config.Accounts.Multiclient = *config.Accounts.Bouncer
  868. }
  869. if !config.Accounts.Multiclient.Enabled {
  870. config.Accounts.Multiclient.AlwaysOn = PersistentDisabled
  871. } else if config.Accounts.Multiclient.AlwaysOn >= PersistentOptOut {
  872. config.Accounts.Multiclient.AllowedByDefault = true
  873. }
  874. if config.Accounts.NickReservation.ForceNickEqualsAccount && !config.Accounts.Multiclient.Enabled {
  875. return nil, errors.New("force-nick-equals-account requires enabling multiclient as well")
  876. }
  877. // handle guest format, including the legacy key rename-prefix
  878. if config.Accounts.NickReservation.GuestFormat == "" {
  879. renamePrefix := config.Accounts.NickReservation.RenamePrefix
  880. if renamePrefix == "" {
  881. renamePrefix = "Guest-"
  882. }
  883. config.Accounts.NickReservation.GuestFormat = renamePrefix + "*"
  884. }
  885. config.Accounts.NickReservation.guestRegexp, config.Accounts.NickReservation.guestRegexpFolded, err = compileGuestRegexp(config.Accounts.NickReservation.GuestFormat, config.Server.Casemapping)
  886. if err != nil {
  887. return nil, err
  888. }
  889. var newLogConfigs []logger.LoggingConfig
  890. for _, logConfig := range config.Logging {
  891. // methods
  892. methods := make(map[string]bool)
  893. for _, method := range strings.Split(logConfig.Method, " ") {
  894. if len(method) > 0 {
  895. methods[strings.ToLower(method)] = true
  896. }
  897. }
  898. if methods["file"] && logConfig.Filename == "" {
  899. return nil, ErrLoggerFilenameMissing
  900. }
  901. logConfig.MethodFile = methods["file"]
  902. logConfig.MethodStdout = methods["stdout"]
  903. logConfig.MethodStderr = methods["stderr"]
  904. // levels
  905. level, exists := logger.LogLevelNames[strings.ToLower(logConfig.LevelString)]
  906. if !exists {
  907. return nil, fmt.Errorf("Could not translate log leve [%s]", logConfig.LevelString)
  908. }
  909. logConfig.Level = level
  910. // types
  911. for _, typeStr := range strings.Split(logConfig.TypeString, " ") {
  912. if len(typeStr) == 0 {
  913. continue
  914. }
  915. if typeStr == "-" {
  916. return nil, ErrLoggerExcludeEmpty
  917. }
  918. if typeStr[0] == '-' {
  919. typeStr = typeStr[1:]
  920. logConfig.ExcludedTypes = append(logConfig.ExcludedTypes, typeStr)
  921. } else {
  922. logConfig.Types = append(logConfig.Types, typeStr)
  923. }
  924. }
  925. if len(logConfig.Types) < 1 {
  926. return nil, ErrLoggerHasNoTypes
  927. }
  928. newLogConfigs = append(newLogConfigs, logConfig)
  929. }
  930. config.Logging = newLogConfigs
  931. // hardcode this for now
  932. config.Accounts.Registration.EnabledCredentialTypes = []string{"passphrase", "certfp"}
  933. mailtoEnabled := false
  934. for i, name := range config.Accounts.Registration.EnabledCallbacks {
  935. if name == "none" {
  936. // we store "none" as "*" internally
  937. config.Accounts.Registration.EnabledCallbacks[i] = "*"
  938. } else if name == "mailto" {
  939. mailtoEnabled = true
  940. }
  941. }
  942. sort.Strings(config.Accounts.Registration.EnabledCallbacks)
  943. if mailtoEnabled {
  944. err := config.Accounts.Registration.Callbacks.Mailto.Postprocess(config.Server.Name)
  945. if err != nil {
  946. return nil, err
  947. }
  948. }
  949. config.Accounts.defaultUserModes = ParseDefaultUserModes(config.Accounts.DefaultUserModes)
  950. config.Accounts.RequireSasl.exemptedNets, err = utils.ParseNetList(config.Accounts.RequireSasl.Exempted)
  951. if err != nil {
  952. return nil, fmt.Errorf("Could not parse require-sasl exempted nets: %v", err.Error())
  953. }
  954. config.Server.proxyAllowedFromNets, err = utils.ParseNetList(config.Server.ProxyAllowedFrom)
  955. if err != nil {
  956. return nil, fmt.Errorf("Could not parse proxy-allowed-from nets: %v", err.Error())
  957. }
  958. config.Server.secureNets, err = utils.ParseNetList(config.Server.SecureNetDefs)
  959. if err != nil {
  960. return nil, fmt.Errorf("Could not parse secure-nets: %v\n", err.Error())
  961. }
  962. rawRegexp := config.Accounts.VHosts.ValidRegexpRaw
  963. if rawRegexp != "" {
  964. regexp, err := regexp.Compile(rawRegexp)
  965. if err == nil {
  966. config.Accounts.VHosts.ValidRegexp = regexp
  967. } else {
  968. log.Printf("invalid vhost regexp: %s\n", err.Error())
  969. }
  970. }
  971. if config.Accounts.VHosts.ValidRegexp == nil {
  972. config.Accounts.VHosts.ValidRegexp = defaultValidVhostRegex
  973. }
  974. for _, vhost := range config.Accounts.VHosts.OfferList {
  975. if !config.Accounts.VHosts.ValidRegexp.MatchString(vhost) {
  976. return nil, fmt.Errorf("invalid offered vhost: %s", vhost)
  977. }
  978. }
  979. config.Server.capValues[caps.SASL] = "PLAIN,EXTERNAL"
  980. if !config.Accounts.AuthenticationEnabled {
  981. config.Server.supportedCaps.Disable(caps.SASL)
  982. }
  983. maxSendQBytes, err := bytefmt.ToBytes(config.Server.MaxSendQString)
  984. if err != nil {
  985. return nil, fmt.Errorf("Could not parse maximum SendQ size (make sure it only contains whole numbers): %s", err.Error())
  986. }
  987. config.Server.MaxSendQBytes = int(maxSendQBytes)
  988. config.languageManager, err = languages.NewManager(config.Languages.Enabled, config.Languages.Path, config.Languages.Default)
  989. if err != nil {
  990. return nil, fmt.Errorf("Could not load languages: %s", err.Error())
  991. }
  992. config.Server.capValues[caps.Languages] = config.languageManager.CapValue()
  993. config.Debug.recoverFromErrors = utils.BoolDefaultTrue(config.Debug.RecoverFromErrors)
  994. // process operator definitions, store them to config.operators
  995. operclasses, err := config.OperatorClasses()
  996. if err != nil {
  997. return nil, err
  998. }
  999. opers, err := config.Operators(operclasses)
  1000. if err != nil {
  1001. return nil, err
  1002. }
  1003. config.operators = opers
  1004. // parse default channel modes
  1005. config.Channels.defaultModes = ParseDefaultChannelModes(config.Channels.DefaultModes)
  1006. if config.Server.Password != "" {
  1007. config.Server.passwordBytes, err = decodeLegacyPasswordHash(config.Server.Password)
  1008. if err != nil {
  1009. return nil, err
  1010. }
  1011. if config.Accounts.LoginViaPassCommand && !config.Accounts.SkipServerPassword {
  1012. return nil, errors.New("Using a server password and login-via-pass-command requires skip-server-password as well")
  1013. }
  1014. }
  1015. if config.Accounts.Registration.BcryptCost == 0 {
  1016. config.Accounts.Registration.BcryptCost = passwd.DefaultCost
  1017. }
  1018. if config.Channels.MaxChannelsPerClient == 0 {
  1019. config.Channels.MaxChannelsPerClient = 100
  1020. }
  1021. if config.Channels.Registration.MaxChannelsPerAccount == 0 {
  1022. config.Channels.Registration.MaxChannelsPerAccount = 15
  1023. }
  1024. config.Server.Compatibility.forceTrailing = utils.BoolDefaultTrue(config.Server.Compatibility.ForceTrailing)
  1025. config.loadMOTD()
  1026. // in the current implementation, we disable history by creating a history buffer
  1027. // with zero capacity. but the `enabled` config option MUST be respected regardless
  1028. // of this detail
  1029. if !config.History.Enabled {
  1030. config.History.ChannelLength = 0
  1031. config.History.ClientLength = 0
  1032. }
  1033. if !config.History.Enabled || !config.History.Persistent.Enabled {
  1034. config.History.Persistent.UnregisteredChannels = false
  1035. config.History.Persistent.RegisteredChannels = PersistentDisabled
  1036. config.History.Persistent.DirectMessages = PersistentDisabled
  1037. }
  1038. if config.History.ZNCMax == 0 {
  1039. config.History.ZNCMax = config.History.ChathistoryMax
  1040. }
  1041. config.Roleplay.enabled = utils.BoolDefaultTrue(config.Roleplay.Enabled)
  1042. config.Roleplay.addSuffix = utils.BoolDefaultTrue(config.Roleplay.AddSuffix)
  1043. config.Datastore.MySQL.ExpireTime = time.Duration(config.History.Restrictions.ExpireTime)
  1044. config.Datastore.MySQL.TrackAccountMessages = config.History.Retention.EnableAccountIndexing
  1045. config.Server.Cloaks.Initialize()
  1046. if config.Server.Cloaks.Enabled {
  1047. if !utils.IsHostname(config.Server.Cloaks.Netname) {
  1048. return nil, fmt.Errorf("Invalid netname for cloaked hostnames: %s", config.Server.Cloaks.Netname)
  1049. }
  1050. }
  1051. err = config.processExtjwt()
  1052. if err != nil {
  1053. return nil, err
  1054. }
  1055. // now that all postprocessing is complete, regenerate ISUPPORT:
  1056. err = config.generateISupport()
  1057. if err != nil {
  1058. return nil, err
  1059. }
  1060. err = config.prepareListeners()
  1061. if err != nil {
  1062. return nil, fmt.Errorf("failed to prepare listeners: %v", err)
  1063. }
  1064. return config, nil
  1065. }
  1066. func (config *Config) getOutputPath(filename string) string {
  1067. return filepath.Join(config.Server.OutputPath, filename)
  1068. }
  1069. // setISupport sets up our RPL_ISUPPORT reply.
  1070. func (config *Config) generateISupport() (err error) {
  1071. maxTargetsString := strconv.Itoa(maxTargets)
  1072. // add RPL_ISUPPORT tokens
  1073. isupport := &config.Server.isupport
  1074. isupport.Initialize()
  1075. isupport.Add("AWAYLEN", strconv.Itoa(config.Limits.AwayLen))
  1076. isupport.Add("BOT", "B")
  1077. isupport.Add("CASEMAPPING", "ascii")
  1078. isupport.Add("CHANLIMIT", fmt.Sprintf("%s:%d", chanTypes, config.Channels.MaxChannelsPerClient))
  1079. 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()}, ","))
  1080. if config.History.Enabled && config.History.ChathistoryMax > 0 {
  1081. isupport.Add("draft/CHATHISTORY", strconv.Itoa(config.History.ChathistoryMax))
  1082. }
  1083. isupport.Add("CHANNELLEN", strconv.Itoa(config.Limits.ChannelLen))
  1084. isupport.Add("CHANTYPES", chanTypes)
  1085. isupport.Add("ELIST", "U")
  1086. isupport.Add("EXCEPTS", "")
  1087. if config.Extjwt.Default.Enabled() || len(config.Extjwt.Services) != 0 {
  1088. isupport.Add("EXTJWT", "1")
  1089. }
  1090. isupport.Add("INVEX", "")
  1091. isupport.Add("KICKLEN", strconv.Itoa(config.Limits.KickLen))
  1092. isupport.Add("MAXLIST", fmt.Sprintf("beI:%s", strconv.Itoa(config.Limits.ChanListModes)))
  1093. isupport.Add("MAXTARGETS", maxTargetsString)
  1094. isupport.Add("MODES", "")
  1095. isupport.Add("MONITOR", strconv.Itoa(config.Limits.MonitorEntries))
  1096. isupport.Add("NETWORK", config.Network.Name)
  1097. isupport.Add("NICKLEN", strconv.Itoa(config.Limits.NickLen))
  1098. isupport.Add("PREFIX", "(qaohv)~&@%+")
  1099. if config.Roleplay.enabled {
  1100. isupport.Add("RPCHAN", "E")
  1101. isupport.Add("RPUSER", "E")
  1102. }
  1103. isupport.Add("STATUSMSG", "~&@%+")
  1104. 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))
  1105. isupport.Add("TOPICLEN", strconv.Itoa(config.Limits.TopicLen))
  1106. if config.Server.Casemapping == CasemappingPRECIS {
  1107. isupport.Add("UTF8MAPPING", precisUTF8MappingToken)
  1108. }
  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. func compileGuestRegexp(guestFormat string, casemapping Casemapping) (standard, folded *regexp.Regexp, err error) {
  1145. if strings.Count(guestFormat, "?") != 0 || strings.Count(guestFormat, "*") != 1 {
  1146. err = errors.New("guest format must contain 1 '*' and no '?'s")
  1147. return
  1148. }
  1149. standard, err = utils.CompileGlob(guestFormat, true)
  1150. if err != nil {
  1151. return
  1152. }
  1153. starIndex := strings.IndexByte(guestFormat, '*')
  1154. initial := guestFormat[:starIndex]
  1155. final := guestFormat[starIndex+1:]
  1156. initialFolded, err := casefoldWithSetting(initial, casemapping)
  1157. if err != nil {
  1158. return
  1159. }
  1160. finalFolded, err := casefoldWithSetting(final, casemapping)
  1161. if err != nil {
  1162. return
  1163. }
  1164. folded, err = utils.CompileGlob(fmt.Sprintf("%s*%s", initialFolded, finalFolded), false)
  1165. return
  1166. }
  1167. func (config *Config) loadMOTD() error {
  1168. if config.Server.MOTD != "" {
  1169. file, err := os.Open(config.Server.MOTD)
  1170. if err != nil {
  1171. return err
  1172. }
  1173. defer file.Close()
  1174. contents, err := ioutil.ReadAll(file)
  1175. if err != nil {
  1176. return err
  1177. }
  1178. lines := bytes.Split(contents, []byte{'\n'})
  1179. for i, line := range lines {
  1180. lineToSend := string(bytes.TrimRight(line, "\r\n"))
  1181. if len(lineToSend) == 0 && i == len(lines)-1 {
  1182. // if the last line of the MOTD was properly terminated with \n,
  1183. // there's no need to send a blank line to clients
  1184. continue
  1185. }
  1186. if config.Server.MOTDFormatting {
  1187. lineToSend = ircfmt.Unescape(lineToSend)
  1188. }
  1189. // "- " is the required prefix for MOTD
  1190. lineToSend = fmt.Sprintf("- %s", lineToSend)
  1191. config.Server.motdLines = append(config.Server.motdLines, lineToSend)
  1192. }
  1193. }
  1194. return nil
  1195. }