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

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