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

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