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. ForbidAnonNickChanges bool `yaml:"forbid-anonymous-nick-changes"`
  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. AllowBeforeConnect bool `yaml:"allow-before-connect"`
  277. Throttling ThrottleConfig
  278. // new-style (v2.4 email verification config):
  279. EmailVerification email.MailtoConfig `yaml:"email-verification"`
  280. // old-style email verification config, with "callbacks":
  281. LegacyEnabledCallbacks []string `yaml:"enabled-callbacks"`
  282. LegacyCallbacks struct {
  283. Mailto email.MailtoConfig
  284. } `yaml:"callbacks"`
  285. VerifyTimeout custime.Duration `yaml:"verify-timeout"`
  286. BcryptCost uint `yaml:"bcrypt-cost"`
  287. }
  288. type VHostConfig struct {
  289. Enabled bool
  290. MaxLength int `yaml:"max-length"`
  291. ValidRegexpRaw string `yaml:"valid-regexp"`
  292. validRegexp *regexp.Regexp
  293. }
  294. type NickEnforcementMethod int
  295. const (
  296. // NickEnforcementOptional is the zero value; it serializes to
  297. // "optional" in the yaml config, and "default" as an arg to `NS ENFORCE`.
  298. // in both cases, it means "defer to the other source of truth", i.e.,
  299. // in the config, defer to the user's custom setting, and as a custom setting,
  300. // defer to the default in the config. if both are NickEnforcementOptional then
  301. // there is no enforcement.
  302. // XXX: these are serialized as numbers in the database, so beware of collisions
  303. // when refactoring (any numbers currently in use must keep their meanings, or
  304. // else be fixed up by a schema change)
  305. NickEnforcementOptional NickEnforcementMethod = iota
  306. NickEnforcementNone
  307. NickEnforcementStrict
  308. )
  309. func nickReservationToString(method NickEnforcementMethod) string {
  310. switch method {
  311. case NickEnforcementOptional:
  312. return "default"
  313. case NickEnforcementNone:
  314. return "none"
  315. case NickEnforcementStrict:
  316. return "strict"
  317. default:
  318. return ""
  319. }
  320. }
  321. func nickReservationFromString(method string) (NickEnforcementMethod, error) {
  322. switch strings.ToLower(method) {
  323. case "default":
  324. return NickEnforcementOptional, nil
  325. case "optional":
  326. return NickEnforcementOptional, nil
  327. case "none":
  328. return NickEnforcementNone, nil
  329. case "strict":
  330. return NickEnforcementStrict, nil
  331. default:
  332. return NickEnforcementOptional, fmt.Errorf("invalid nick-reservation.method value: %s", method)
  333. }
  334. }
  335. func (nr *NickEnforcementMethod) UnmarshalYAML(unmarshal func(interface{}) error) error {
  336. var orig string
  337. var err error
  338. if err = unmarshal(&orig); err != nil {
  339. return err
  340. }
  341. method, err := nickReservationFromString(orig)
  342. if err == nil {
  343. *nr = method
  344. }
  345. return err
  346. }
  347. func (cm *Casemapping) UnmarshalYAML(unmarshal func(interface{}) error) (err error) {
  348. var orig string
  349. if err = unmarshal(&orig); err != nil {
  350. return err
  351. }
  352. var result Casemapping
  353. switch strings.ToLower(orig) {
  354. case "ascii":
  355. result = CasemappingASCII
  356. case "precis", "rfc7613", "rfc8265":
  357. result = CasemappingPRECIS
  358. case "permissive", "fun":
  359. result = CasemappingPermissive
  360. default:
  361. return fmt.Errorf("invalid casemapping value: %s", orig)
  362. }
  363. *cm = result
  364. return nil
  365. }
  366. // OperClassConfig defines a specific operator class.
  367. type OperClassConfig struct {
  368. Title string
  369. WhoisLine string
  370. Extends string
  371. Capabilities []string
  372. }
  373. // OperConfig defines a specific operator's configuration.
  374. type OperConfig struct {
  375. Class string
  376. Vhost string
  377. WhoisLine string `yaml:"whois-line"`
  378. Password string
  379. Fingerprint *string // legacy name for certfp, #1050
  380. Certfp string
  381. Auto bool
  382. Hidden bool
  383. Modes string
  384. }
  385. // Various server-enforced limits on data size.
  386. type Limits struct {
  387. AwayLen int `yaml:"awaylen"`
  388. ChanListModes int `yaml:"chan-list-modes"`
  389. ChannelLen int `yaml:"channellen"`
  390. IdentLen int `yaml:"identlen"`
  391. KickLen int `yaml:"kicklen"`
  392. MonitorEntries int `yaml:"monitor-entries"`
  393. NickLen int `yaml:"nicklen"`
  394. TopicLen int `yaml:"topiclen"`
  395. WhowasEntries int `yaml:"whowas-entries"`
  396. RegistrationMessages int `yaml:"registration-messages"`
  397. Multiline struct {
  398. MaxBytes int `yaml:"max-bytes"`
  399. MaxLines int `yaml:"max-lines"`
  400. }
  401. }
  402. // STSConfig controls the STS configuration/
  403. type STSConfig struct {
  404. Enabled bool
  405. Duration custime.Duration
  406. Port int
  407. Preload bool
  408. STSOnlyBanner string `yaml:"sts-only-banner"`
  409. bannerLines []string
  410. }
  411. // Value returns the STS value to advertise in CAP
  412. func (sts *STSConfig) Value() string {
  413. val := fmt.Sprintf("duration=%d", int(time.Duration(sts.Duration).Seconds()))
  414. if sts.Enabled && sts.Port > 0 {
  415. val += fmt.Sprintf(",port=%d", sts.Port)
  416. }
  417. if sts.Enabled && sts.Preload {
  418. val += ",preload"
  419. }
  420. return val
  421. }
  422. type FakelagConfig struct {
  423. Enabled bool
  424. Window time.Duration
  425. BurstLimit uint `yaml:"burst-limit"`
  426. MessagesPerWindow uint `yaml:"messages-per-window"`
  427. Cooldown time.Duration
  428. }
  429. type TorListenersConfig struct {
  430. Listeners []string // legacy only
  431. RequireSasl bool `yaml:"require-sasl"`
  432. Vhost string
  433. MaxConnections int `yaml:"max-connections"`
  434. ThrottleDuration time.Duration `yaml:"throttle-duration"`
  435. MaxConnectionsPerDuration int `yaml:"max-connections-per-duration"`
  436. }
  437. // Config defines the overall configuration.
  438. type Config struct {
  439. Network struct {
  440. Name string
  441. }
  442. Server struct {
  443. Password string
  444. passwordBytes []byte
  445. Name string
  446. nameCasefolded string
  447. // Listeners is the new style for configuring listeners:
  448. Listeners map[string]listenerConfigBlock
  449. UnixBindMode os.FileMode `yaml:"unix-bind-mode"`
  450. TorListeners TorListenersConfig `yaml:"tor-listeners"`
  451. WebSockets struct {
  452. AllowedOrigins []string `yaml:"allowed-origins"`
  453. allowedOriginRegexps []*regexp.Regexp
  454. }
  455. // they get parsed into this internal representation:
  456. trueListeners map[string]utils.ListenerConfig
  457. STS STSConfig
  458. LookupHostnames *bool `yaml:"lookup-hostnames"`
  459. lookupHostnames bool
  460. ForwardConfirmHostnames bool `yaml:"forward-confirm-hostnames"`
  461. CheckIdent bool `yaml:"check-ident"`
  462. CoerceIdent string `yaml:"coerce-ident"`
  463. MOTD string
  464. motdLines []string
  465. MOTDFormatting bool `yaml:"motd-formatting"`
  466. Relaymsg struct {
  467. Enabled bool
  468. Separators string
  469. AvailableToChanops bool `yaml:"available-to-chanops"`
  470. }
  471. ProxyAllowedFrom []string `yaml:"proxy-allowed-from"`
  472. proxyAllowedFromNets []net.IPNet
  473. WebIRC []webircConfig `yaml:"webirc"`
  474. MaxSendQString string `yaml:"max-sendq"`
  475. MaxSendQBytes int
  476. AllowPlaintextResume bool `yaml:"allow-plaintext-resume"`
  477. Compatibility struct {
  478. ForceTrailing *bool `yaml:"force-trailing"`
  479. forceTrailing bool
  480. SendUnprefixedSasl bool `yaml:"send-unprefixed-sasl"`
  481. }
  482. isupport isupport.List
  483. IPLimits connection_limits.LimiterConfig `yaml:"ip-limits"`
  484. Cloaks cloaks.CloakConfig `yaml:"ip-cloaking"`
  485. SecureNetDefs []string `yaml:"secure-nets"`
  486. secureNets []net.IPNet
  487. supportedCaps *caps.Set
  488. capValues caps.Values
  489. Casemapping Casemapping
  490. EnforceUtf8 bool `yaml:"enforce-utf8"`
  491. OutputPath string `yaml:"output-path"`
  492. IPCheckScript ScriptConfig `yaml:"ip-check-script"`
  493. }
  494. Roleplay struct {
  495. Enabled bool
  496. RequireChanops bool `yaml:"require-chanops"`
  497. RequireOper bool `yaml:"require-oper"`
  498. AddSuffix *bool `yaml:"add-suffix"`
  499. addSuffix bool
  500. }
  501. Extjwt struct {
  502. Default jwt.JwtServiceConfig `yaml:",inline"`
  503. Services map[string]jwt.JwtServiceConfig `yaml:"services"`
  504. }
  505. Languages struct {
  506. Enabled bool
  507. Path string
  508. Default string
  509. }
  510. languageManager *languages.Manager
  511. Datastore struct {
  512. Path string
  513. AutoUpgrade bool
  514. MySQL mysql.Config
  515. }
  516. Accounts AccountConfig
  517. Channels struct {
  518. DefaultModes *string `yaml:"default-modes"`
  519. defaultModes modes.Modes
  520. MaxChannelsPerClient int `yaml:"max-channels-per-client"`
  521. OpOnlyCreation bool `yaml:"operator-only-creation"`
  522. Registration struct {
  523. Enabled bool
  524. OperatorOnly bool `yaml:"operator-only"`
  525. MaxChannelsPerAccount int `yaml:"max-channels-per-account"`
  526. }
  527. ListDelay time.Duration `yaml:"list-delay"`
  528. }
  529. OperClasses map[string]*OperClassConfig `yaml:"oper-classes"`
  530. Opers map[string]*OperConfig
  531. // parsed operator definitions, unexported so they can't be defined
  532. // directly in YAML:
  533. operators map[string]*Oper
  534. Logging []logger.LoggingConfig
  535. Debug struct {
  536. RecoverFromErrors *bool `yaml:"recover-from-errors"`
  537. recoverFromErrors bool
  538. PprofListener *string `yaml:"pprof-listener"`
  539. }
  540. Limits Limits
  541. Fakelag FakelagConfig
  542. History struct {
  543. Enabled bool
  544. ChannelLength int `yaml:"channel-length"`
  545. ClientLength int `yaml:"client-length"`
  546. AutoresizeWindow custime.Duration `yaml:"autoresize-window"`
  547. AutoreplayOnJoin int `yaml:"autoreplay-on-join"`
  548. ChathistoryMax int `yaml:"chathistory-maxmessages"`
  549. ZNCMax int `yaml:"znc-maxmessages"`
  550. Restrictions struct {
  551. ExpireTime custime.Duration `yaml:"expire-time"`
  552. EnforceRegistrationDate bool `yaml:"enforce-registration-date"`
  553. GracePeriod custime.Duration `yaml:"grace-period"`
  554. }
  555. Persistent struct {
  556. Enabled bool
  557. UnregisteredChannels bool `yaml:"unregistered-channels"`
  558. RegisteredChannels PersistentStatus `yaml:"registered-channels"`
  559. DirectMessages PersistentStatus `yaml:"direct-messages"`
  560. }
  561. Retention struct {
  562. AllowIndividualDelete bool `yaml:"allow-individual-delete"`
  563. EnableAccountIndexing bool `yaml:"enable-account-indexing"`
  564. }
  565. TagmsgStorage struct {
  566. Default bool
  567. Whitelist []string
  568. Blacklist []string
  569. } `yaml:"tagmsg-storage"`
  570. }
  571. Filename string
  572. }
  573. // OperClass defines an assembled operator class.
  574. type OperClass struct {
  575. Title string
  576. WhoisLine string `yaml:"whois-line"`
  577. Capabilities utils.StringSet // map to make lookups much easier
  578. }
  579. // OperatorClasses returns a map of assembled operator classes from the given config.
  580. func (conf *Config) OperatorClasses() (map[string]*OperClass, error) {
  581. fixupCapability := func(capab string) string {
  582. return strings.TrimPrefix(capab, "oper:") // #868
  583. }
  584. ocs := make(map[string]*OperClass)
  585. // loop from no extends to most extended, breaking if we can't add any more
  586. lenOfLastOcs := -1
  587. for {
  588. if lenOfLastOcs == len(ocs) {
  589. return nil, errors.New("OperClasses contains a looping dependency, or a class extends from a class that doesn't exist")
  590. }
  591. lenOfLastOcs = len(ocs)
  592. var anyMissing bool
  593. for name, info := range conf.OperClasses {
  594. _, exists := ocs[name]
  595. _, extendsExists := ocs[info.Extends]
  596. if exists {
  597. // class already exists
  598. continue
  599. } else if len(info.Extends) > 0 && !extendsExists {
  600. // class we extend on doesn't exist
  601. _, exists := conf.OperClasses[info.Extends]
  602. if !exists {
  603. return nil, fmt.Errorf("Operclass [%s] extends [%s], which doesn't exist", name, info.Extends)
  604. }
  605. anyMissing = true
  606. continue
  607. }
  608. // create new operclass
  609. var oc OperClass
  610. oc.Capabilities = make(utils.StringSet)
  611. // get inhereted info from other operclasses
  612. if len(info.Extends) > 0 {
  613. einfo := ocs[info.Extends]
  614. for capab := range einfo.Capabilities {
  615. oc.Capabilities.Add(fixupCapability(capab))
  616. }
  617. }
  618. // add our own info
  619. oc.Title = info.Title
  620. for _, capab := range info.Capabilities {
  621. oc.Capabilities.Add(fixupCapability(capab))
  622. }
  623. if len(info.WhoisLine) > 0 {
  624. oc.WhoisLine = info.WhoisLine
  625. } else {
  626. oc.WhoisLine = "is a"
  627. if strings.Contains(strings.ToLower(string(oc.Title[0])), "aeiou") {
  628. oc.WhoisLine += "n"
  629. }
  630. oc.WhoisLine += " "
  631. oc.WhoisLine += oc.Title
  632. }
  633. ocs[name] = &oc
  634. }
  635. if !anyMissing {
  636. // we've got every operclass!
  637. break
  638. }
  639. }
  640. return ocs, nil
  641. }
  642. // Oper represents a single assembled operator's config.
  643. type Oper struct {
  644. Name string
  645. Class *OperClass
  646. WhoisLine string
  647. Vhost string
  648. Pass []byte
  649. Certfp string
  650. Auto bool
  651. Hidden 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. oper.Hidden = opConf.Hidden
  683. if oper.Pass == nil && oper.Certfp == "" {
  684. return nil, fmt.Errorf("Oper %s has neither a password nor a fingerprint", name)
  685. }
  686. oper.Vhost = opConf.Vhost
  687. class, exists := oc[opConf.Class]
  688. if !exists {
  689. return nil, fmt.Errorf("Could not load operator [%s] - they use operclass [%s] which does not exist", name, opConf.Class)
  690. }
  691. oper.Class = class
  692. if len(opConf.WhoisLine) > 0 {
  693. oper.WhoisLine = opConf.WhoisLine
  694. } else {
  695. oper.WhoisLine = class.WhoisLine
  696. }
  697. modeStr := strings.TrimSpace(opConf.Modes)
  698. modeChanges, unknownChanges := modes.ParseUserModeChanges(strings.Split(modeStr, " ")...)
  699. if len(unknownChanges) > 0 {
  700. return nil, fmt.Errorf("Could not load operator [%s] due to unknown modes %v", name, unknownChanges)
  701. }
  702. oper.Modes = modeChanges
  703. // successful, attach to list of opers
  704. operators[name] = &oper
  705. }
  706. return operators, nil
  707. }
  708. func loadTlsConfig(config TLSListenConfig, webSocket bool) (tlsConfig *tls.Config, err error) {
  709. cert, err := tls.LoadX509KeyPair(config.Cert, config.Key)
  710. if err != nil {
  711. return nil, &CertKeyError{Err: err}
  712. }
  713. clientAuth := tls.RequestClientCert
  714. if webSocket {
  715. // if Chrome receives a server request for a client certificate
  716. // on a websocket connection, it will immediately disconnect:
  717. // https://bugs.chromium.org/p/chromium/issues/detail?id=329884
  718. // work around this behavior:
  719. clientAuth = tls.NoClientCert
  720. }
  721. result := tls.Config{
  722. Certificates: []tls.Certificate{cert},
  723. ClientAuth: clientAuth,
  724. }
  725. return &result, nil
  726. }
  727. // prepareListeners populates Config.Server.trueListeners
  728. func (conf *Config) prepareListeners() (err error) {
  729. if len(conf.Server.Listeners) == 0 {
  730. return fmt.Errorf("No listeners were configured")
  731. }
  732. conf.Server.trueListeners = make(map[string]utils.ListenerConfig)
  733. for addr, block := range conf.Server.Listeners {
  734. var lconf utils.ListenerConfig
  735. lconf.ProxyDeadline = RegisterTimeout
  736. lconf.Tor = block.Tor
  737. lconf.STSOnly = block.STSOnly
  738. if lconf.STSOnly && !conf.Server.STS.Enabled {
  739. return fmt.Errorf("%s is configured as a STS-only listener, but STS is disabled", addr)
  740. }
  741. if block.TLS.Cert != "" {
  742. tlsConfig, err := loadTlsConfig(block.TLS, block.WebSocket)
  743. if err != nil {
  744. return err
  745. }
  746. lconf.TLSConfig = tlsConfig
  747. lconf.RequireProxy = block.TLS.Proxy
  748. }
  749. lconf.WebSocket = block.WebSocket
  750. conf.Server.trueListeners[addr] = lconf
  751. }
  752. return nil
  753. }
  754. func (config *Config) processExtjwt() (err error) {
  755. // first process the default service, which may be disabled
  756. err = config.Extjwt.Default.Postprocess()
  757. if err != nil {
  758. return
  759. }
  760. // now process the named services. it is an error if any is disabled
  761. // also, normalize the service names to lowercase
  762. services := make(map[string]jwt.JwtServiceConfig, len(config.Extjwt.Services))
  763. for service, sConf := range config.Extjwt.Services {
  764. err := sConf.Postprocess()
  765. if err != nil {
  766. return err
  767. }
  768. if !sConf.Enabled() {
  769. return fmt.Errorf("no keys enabled for extjwt service %s", service)
  770. }
  771. services[strings.ToLower(service)] = sConf
  772. }
  773. config.Extjwt.Services = services
  774. return nil
  775. }
  776. // LoadRawConfig loads the config without doing any consistency checks or postprocessing
  777. func LoadRawConfig(filename string) (config *Config, err error) {
  778. data, err := ioutil.ReadFile(filename)
  779. if err != nil {
  780. return nil, err
  781. }
  782. err = yaml.Unmarshal(data, &config)
  783. if err != nil {
  784. return nil, err
  785. }
  786. return
  787. }
  788. // LoadConfig loads the given YAML configuration file.
  789. func LoadConfig(filename string) (config *Config, err error) {
  790. config, err = LoadRawConfig(filename)
  791. if err != nil {
  792. return nil, err
  793. }
  794. config.Filename = filename
  795. if config.Network.Name == "" {
  796. return nil, errors.New("Network name missing")
  797. }
  798. if config.Server.Name == "" {
  799. return nil, errors.New("Server name missing")
  800. }
  801. if !utils.IsServerName(config.Server.Name) {
  802. return nil, errors.New("Server name must match the format of a hostname")
  803. }
  804. config.Server.nameCasefolded = strings.ToLower(config.Server.Name)
  805. if config.Datastore.Path == "" {
  806. return nil, errors.New("Datastore path missing")
  807. }
  808. //dan: automagically fix identlen until a few releases in the future (from now, 0.12.0), being a newly-introduced limit
  809. if config.Limits.IdentLen < 1 {
  810. config.Limits.IdentLen = 20
  811. }
  812. if config.Limits.NickLen < 1 || config.Limits.ChannelLen < 2 || config.Limits.AwayLen < 1 || config.Limits.KickLen < 1 || config.Limits.TopicLen < 1 {
  813. return nil, errors.New("One or more limits values are too low")
  814. }
  815. if config.Limits.RegistrationMessages == 0 {
  816. config.Limits.RegistrationMessages = 1024
  817. }
  818. if config.Datastore.MySQL.Enabled {
  819. if config.Limits.NickLen > mysql.MaxTargetLength || config.Limits.ChannelLen > mysql.MaxTargetLength {
  820. return nil, fmt.Errorf("to use MySQL, nick and channel length limits must be %d or lower", mysql.MaxTargetLength)
  821. }
  822. }
  823. if config.Server.CoerceIdent != "" {
  824. if config.Server.CheckIdent {
  825. return nil, errors.New("Can't configure both check-ident and coerce-ident")
  826. }
  827. if config.Server.CoerceIdent[0] != '~' {
  828. return nil, errors.New("coerce-ident value must start with a ~")
  829. }
  830. if !isIdent(config.Server.CoerceIdent[1:]) {
  831. return nil, errors.New("coerce-ident must be valid as an IRC user/ident field")
  832. }
  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", chanmodesToken)
  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("EXTBAN", ",m")
  1158. isupport.Add("INVEX", "")
  1159. isupport.Add("KICKLEN", strconv.Itoa(config.Limits.KickLen))
  1160. isupport.Add("MAXLIST", fmt.Sprintf("beI:%s", strconv.Itoa(config.Limits.ChanListModes)))
  1161. isupport.Add("MAXTARGETS", maxTargetsString)
  1162. isupport.Add("MODES", "")
  1163. isupport.Add("MONITOR", strconv.Itoa(config.Limits.MonitorEntries))
  1164. isupport.Add("NETWORK", config.Network.Name)
  1165. isupport.Add("NICKLEN", strconv.Itoa(config.Limits.NickLen))
  1166. isupport.Add("PREFIX", "(qaohv)~&@%+")
  1167. if config.Roleplay.Enabled {
  1168. isupport.Add("RPCHAN", "E")
  1169. isupport.Add("RPUSER", "E")
  1170. }
  1171. isupport.Add("STATUSMSG", "~&@%+")
  1172. 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))
  1173. isupport.Add("TOPICLEN", strconv.Itoa(config.Limits.TopicLen))
  1174. if config.Server.Casemapping == CasemappingPRECIS {
  1175. isupport.Add("UTF8MAPPING", precisUTF8MappingToken)
  1176. }
  1177. isupport.Add("WHOX", "")
  1178. err = isupport.RegenerateCachedReply()
  1179. return
  1180. }
  1181. // Diff returns changes in supported caps across a rehash.
  1182. func (config *Config) Diff(oldConfig *Config) (addedCaps, removedCaps *caps.Set) {
  1183. addedCaps = caps.NewSet()
  1184. removedCaps = caps.NewSet()
  1185. if oldConfig == nil {
  1186. return
  1187. }
  1188. if oldConfig.Server.capValues[caps.Languages] != config.Server.capValues[caps.Languages] {
  1189. // XXX updated caps get a DEL line and then a NEW line with the new value
  1190. addedCaps.Add(caps.Languages)
  1191. removedCaps.Add(caps.Languages)
  1192. }
  1193. if !oldConfig.Accounts.AuthenticationEnabled && config.Accounts.AuthenticationEnabled {
  1194. addedCaps.Add(caps.SASL)
  1195. } else if oldConfig.Accounts.AuthenticationEnabled && !config.Accounts.AuthenticationEnabled {
  1196. removedCaps.Add(caps.SASL)
  1197. }
  1198. if oldConfig.Limits.Multiline.MaxBytes != 0 && config.Limits.Multiline.MaxBytes == 0 {
  1199. removedCaps.Add(caps.Multiline)
  1200. } else if oldConfig.Limits.Multiline.MaxBytes == 0 && config.Limits.Multiline.MaxBytes != 0 {
  1201. addedCaps.Add(caps.Multiline)
  1202. } else if oldConfig.Limits.Multiline != config.Limits.Multiline {
  1203. removedCaps.Add(caps.Multiline)
  1204. addedCaps.Add(caps.Multiline)
  1205. }
  1206. if oldConfig.Server.STS.Enabled != config.Server.STS.Enabled || oldConfig.Server.capValues[caps.STS] != config.Server.capValues[caps.STS] {
  1207. // XXX: STS is always removed by CAP NEW sts=duration=0, not CAP DEL
  1208. // so the appropriate notify is always a CAP NEW; put it in addedCaps for any change
  1209. addedCaps.Add(caps.STS)
  1210. }
  1211. return
  1212. }
  1213. // determine whether we need to resize / create / destroy
  1214. // the in-memory history buffers:
  1215. func (config *Config) historyChangedFrom(oldConfig *Config) bool {
  1216. return config.History.Enabled != oldConfig.History.Enabled ||
  1217. config.History.ChannelLength != oldConfig.History.ChannelLength ||
  1218. config.History.ClientLength != oldConfig.History.ClientLength ||
  1219. config.History.AutoresizeWindow != oldConfig.History.AutoresizeWindow ||
  1220. config.History.Persistent != oldConfig.History.Persistent
  1221. }
  1222. func compileGuestRegexp(guestFormat string, casemapping Casemapping) (standard, folded *regexp.Regexp, err error) {
  1223. if strings.Count(guestFormat, "?") != 0 || strings.Count(guestFormat, "*") != 1 {
  1224. err = errors.New("guest format must contain 1 '*' and no '?'s")
  1225. return
  1226. }
  1227. standard, err = utils.CompileGlob(guestFormat, true)
  1228. if err != nil {
  1229. return
  1230. }
  1231. starIndex := strings.IndexByte(guestFormat, '*')
  1232. initial := guestFormat[:starIndex]
  1233. final := guestFormat[starIndex+1:]
  1234. initialFolded, err := casefoldWithSetting(initial, casemapping)
  1235. if err != nil {
  1236. return
  1237. }
  1238. finalFolded, err := casefoldWithSetting(final, casemapping)
  1239. if err != nil {
  1240. return
  1241. }
  1242. folded, err = utils.CompileGlob(fmt.Sprintf("%s*%s", initialFolded, finalFolded), false)
  1243. return
  1244. }
  1245. func (config *Config) loadMOTD() error {
  1246. if config.Server.MOTD != "" {
  1247. file, err := os.Open(config.Server.MOTD)
  1248. if err != nil {
  1249. return err
  1250. }
  1251. defer file.Close()
  1252. contents, err := ioutil.ReadAll(file)
  1253. if err != nil {
  1254. return err
  1255. }
  1256. lines := bytes.Split(contents, []byte{'\n'})
  1257. for i, line := range lines {
  1258. lineToSend := string(bytes.TrimRight(line, "\r\n"))
  1259. if len(lineToSend) == 0 && i == len(lines)-1 {
  1260. // if the last line of the MOTD was properly terminated with \n,
  1261. // there's no need to send a blank line to clients
  1262. continue
  1263. }
  1264. if config.Server.MOTDFormatting {
  1265. lineToSend = ircfmt.Unescape(lineToSend)
  1266. }
  1267. // "- " is the required prefix for MOTD
  1268. lineToSend = fmt.Sprintf("- %s", lineToSend)
  1269. config.Server.motdLines = append(config.Server.motdLines, lineToSend)
  1270. }
  1271. }
  1272. return nil
  1273. }