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.

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