Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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