Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

config.go 35KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172
  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. "crypto/tls"
  8. "fmt"
  9. "io/ioutil"
  10. "log"
  11. "net"
  12. "os"
  13. "regexp"
  14. "sort"
  15. "strconv"
  16. "strings"
  17. "time"
  18. "code.cloudfoundry.org/bytefmt"
  19. "github.com/oragono/oragono/irc/caps"
  20. "github.com/oragono/oragono/irc/cloaks"
  21. "github.com/oragono/oragono/irc/connection_limits"
  22. "github.com/oragono/oragono/irc/custime"
  23. "github.com/oragono/oragono/irc/isupport"
  24. "github.com/oragono/oragono/irc/languages"
  25. "github.com/oragono/oragono/irc/ldap"
  26. "github.com/oragono/oragono/irc/logger"
  27. "github.com/oragono/oragono/irc/modes"
  28. "github.com/oragono/oragono/irc/passwd"
  29. "github.com/oragono/oragono/irc/utils"
  30. "gopkg.in/yaml.v2"
  31. )
  32. // here's how this works: exported (capitalized) members of the config structs
  33. // are defined in the YAML file and deserialized directly from there. They may
  34. // be postprocessed and overwritten by LoadConfig. Unexported (lowercase) members
  35. // are derived from the exported members in LoadConfig.
  36. // TLSListenConfig defines configuration options for listening on TLS.
  37. type TLSListenConfig struct {
  38. Cert string
  39. Key string
  40. Proxy bool
  41. }
  42. // This is the YAML-deserializable type of the value of the `Server.Listeners` map
  43. type listenerConfigBlock struct {
  44. TLS TLSListenConfig
  45. Tor bool
  46. STSOnly bool `yaml:"sts-only"`
  47. }
  48. // listenerConfig is the config governing a particular listener (bound address),
  49. // in particular whether it has TLS or Tor (or both) enabled.
  50. type listenerConfig struct {
  51. TLSConfig *tls.Config
  52. Tor bool
  53. STSOnly bool
  54. ProxyBeforeTLS bool
  55. }
  56. type PersistentStatus uint
  57. const (
  58. PersistentUnspecified PersistentStatus = iota
  59. PersistentDisabled
  60. PersistentOptIn
  61. PersistentOptOut
  62. PersistentMandatory
  63. )
  64. func persistentStatusToString(status PersistentStatus) string {
  65. switch status {
  66. case PersistentUnspecified:
  67. return "default"
  68. case PersistentDisabled:
  69. return "disabled"
  70. case PersistentOptIn:
  71. return "opt-in"
  72. case PersistentOptOut:
  73. return "opt-out"
  74. case PersistentMandatory:
  75. return "mandatory"
  76. default:
  77. return ""
  78. }
  79. }
  80. func persistentStatusFromString(status string) (PersistentStatus, error) {
  81. switch strings.ToLower(status) {
  82. case "default":
  83. return PersistentUnspecified, nil
  84. case "":
  85. return PersistentDisabled, nil
  86. case "opt-in":
  87. return PersistentOptIn, nil
  88. case "opt-out":
  89. return PersistentOptOut, nil
  90. case "mandatory":
  91. return PersistentMandatory, nil
  92. default:
  93. b, err := utils.StringToBool(status)
  94. if b {
  95. return PersistentMandatory, err
  96. } else {
  97. return PersistentDisabled, err
  98. }
  99. }
  100. }
  101. func (ps *PersistentStatus) UnmarshalYAML(unmarshal func(interface{}) error) error {
  102. var orig string
  103. var err error
  104. if err = unmarshal(&orig); err != nil {
  105. return err
  106. }
  107. result, err := persistentStatusFromString(orig)
  108. if err == nil {
  109. if result == PersistentUnspecified {
  110. result = PersistentDisabled
  111. }
  112. *ps = result
  113. }
  114. return err
  115. }
  116. func persistenceEnabled(serverSetting, clientSetting PersistentStatus) (enabled bool) {
  117. if serverSetting == PersistentDisabled {
  118. return false
  119. } else if serverSetting == PersistentMandatory {
  120. return true
  121. } else if clientSetting == PersistentDisabled {
  122. return false
  123. } else if clientSetting == PersistentMandatory {
  124. return true
  125. } else if serverSetting == PersistentOptOut {
  126. return true
  127. } else {
  128. return false
  129. }
  130. }
  131. type HistoryStatus uint
  132. const (
  133. HistoryDefault HistoryStatus = iota
  134. HistoryDisabled
  135. HistoryEphemeral
  136. HistoryPersistent
  137. )
  138. func historyStatusFromString(str string) (status HistoryStatus, err error) {
  139. switch strings.ToLower(str) {
  140. case "default":
  141. return HistoryDefault, nil
  142. case "ephemeral":
  143. return HistoryEphemeral, nil
  144. case "persistent":
  145. return HistoryPersistent, nil
  146. default:
  147. b, err := utils.StringToBool(str)
  148. if b {
  149. return HistoryPersistent, err
  150. } else {
  151. return HistoryDisabled, err
  152. }
  153. }
  154. }
  155. func historyStatusToString(status HistoryStatus) string {
  156. switch status {
  157. case HistoryDefault:
  158. return "default"
  159. case HistoryDisabled:
  160. return "disabled"
  161. case HistoryEphemeral:
  162. return "ephemeral"
  163. case HistoryPersistent:
  164. return "persistent"
  165. default:
  166. return ""
  167. }
  168. }
  169. func historyEnabled(serverSetting PersistentStatus, localSetting HistoryStatus) (result HistoryStatus) {
  170. if serverSetting == PersistentDisabled {
  171. return HistoryDisabled
  172. } else if serverSetting == PersistentMandatory {
  173. return HistoryPersistent
  174. } else if serverSetting == PersistentOptOut {
  175. if localSetting == HistoryDefault {
  176. return HistoryPersistent
  177. } else {
  178. return localSetting
  179. }
  180. } else if serverSetting == PersistentOptIn {
  181. if localSetting >= HistoryEphemeral {
  182. return localSetting
  183. } else {
  184. return HistoryDisabled
  185. }
  186. } else {
  187. return HistoryDisabled
  188. }
  189. }
  190. type AccountConfig struct {
  191. Registration AccountRegistrationConfig
  192. AuthenticationEnabled bool `yaml:"authentication-enabled"`
  193. RequireSasl struct {
  194. Enabled bool
  195. Exempted []string
  196. exemptedNets []net.IPNet
  197. } `yaml:"require-sasl"`
  198. LDAP ldap.ServerConfig
  199. LoginThrottling struct {
  200. Enabled bool
  201. Duration time.Duration
  202. MaxAttempts int `yaml:"max-attempts"`
  203. } `yaml:"login-throttling"`
  204. SkipServerPassword bool `yaml:"skip-server-password"`
  205. NickReservation NickReservationConfig `yaml:"nick-reservation"`
  206. Bouncer struct {
  207. Enabled bool
  208. AllowedByDefault bool `yaml:"allowed-by-default"`
  209. AlwaysOn PersistentStatus `yaml:"always-on"`
  210. }
  211. VHosts VHostConfig
  212. }
  213. // AccountRegistrationConfig controls account registration.
  214. type AccountRegistrationConfig struct {
  215. Enabled bool
  216. EnabledCallbacks []string `yaml:"enabled-callbacks"`
  217. EnabledCredentialTypes []string `yaml:"-"`
  218. VerifyTimeout custime.Duration `yaml:"verify-timeout"`
  219. Callbacks struct {
  220. Mailto struct {
  221. Server string
  222. Port int
  223. TLS struct {
  224. Enabled bool
  225. InsecureSkipVerify bool `yaml:"insecure_skip_verify"`
  226. ServerName string `yaml:"servername"`
  227. }
  228. Username string
  229. Password string
  230. Sender string
  231. VerifyMessageSubject string `yaml:"verify-message-subject"`
  232. VerifyMessage string `yaml:"verify-message"`
  233. }
  234. }
  235. BcryptCost uint `yaml:"bcrypt-cost"`
  236. }
  237. type VHostConfig struct {
  238. Enabled bool
  239. MaxLength int `yaml:"max-length"`
  240. ValidRegexpRaw string `yaml:"valid-regexp"`
  241. ValidRegexp *regexp.Regexp
  242. UserRequests struct {
  243. Enabled bool
  244. Channel string
  245. Cooldown custime.Duration
  246. } `yaml:"user-requests"`
  247. OfferList []string `yaml:"offer-list"`
  248. }
  249. type NickEnforcementMethod int
  250. const (
  251. // NickEnforcementOptional is the zero value; it serializes to
  252. // "optional" in the yaml config, and "default" as an arg to `NS ENFORCE`.
  253. // in both cases, it means "defer to the other source of truth", i.e.,
  254. // in the config, defer to the user's custom setting, and as a custom setting,
  255. // defer to the default in the config. if both are NickEnforcementOptional then
  256. // there is no enforcement.
  257. // XXX: these are serialized as numbers in the database, so beware of collisions
  258. // when refactoring (any numbers currently in use must keep their meanings, or
  259. // else be fixed up by a schema change)
  260. NickEnforcementOptional NickEnforcementMethod = iota
  261. NickEnforcementNone
  262. NickEnforcementWithTimeout
  263. NickEnforcementStrict
  264. )
  265. func nickReservationToString(method NickEnforcementMethod) string {
  266. switch method {
  267. case NickEnforcementOptional:
  268. return "default"
  269. case NickEnforcementNone:
  270. return "none"
  271. case NickEnforcementWithTimeout:
  272. return "timeout"
  273. case NickEnforcementStrict:
  274. return "strict"
  275. default:
  276. return ""
  277. }
  278. }
  279. func nickReservationFromString(method string) (NickEnforcementMethod, error) {
  280. switch strings.ToLower(method) {
  281. case "default":
  282. return NickEnforcementOptional, nil
  283. case "optional":
  284. return NickEnforcementOptional, nil
  285. case "none":
  286. return NickEnforcementNone, nil
  287. case "timeout":
  288. return NickEnforcementWithTimeout, nil
  289. case "strict":
  290. return NickEnforcementStrict, nil
  291. default:
  292. return NickEnforcementOptional, fmt.Errorf("invalid nick-reservation.method value: %s", method)
  293. }
  294. }
  295. func (nr *NickEnforcementMethod) UnmarshalYAML(unmarshal func(interface{}) error) error {
  296. var orig string
  297. var err error
  298. if err = unmarshal(&orig); err != nil {
  299. return err
  300. }
  301. method, err := nickReservationFromString(orig)
  302. if err == nil {
  303. *nr = method
  304. }
  305. return err
  306. }
  307. func (cm *Casemapping) UnmarshalYAML(unmarshal func(interface{}) error) (err error) {
  308. var orig string
  309. if err = unmarshal(&orig); err != nil {
  310. return err
  311. }
  312. var result Casemapping
  313. switch strings.ToLower(orig) {
  314. case "ascii":
  315. result = CasemappingASCII
  316. case "precis", "rfc7613", "rfc8265":
  317. result = CasemappingPRECIS
  318. case "permissive", "fun":
  319. result = CasemappingPermissive
  320. default:
  321. return fmt.Errorf("invalid casemapping value: %s", orig)
  322. }
  323. *cm = result
  324. return nil
  325. }
  326. type NickReservationConfig struct {
  327. Enabled bool
  328. AdditionalNickLimit int `yaml:"additional-nick-limit"`
  329. Method NickEnforcementMethod
  330. AllowCustomEnforcement bool `yaml:"allow-custom-enforcement"`
  331. RenameTimeout time.Duration `yaml:"rename-timeout"`
  332. RenamePrefix string `yaml:"rename-prefix"`
  333. }
  334. // ChannelRegistrationConfig controls channel registration.
  335. type ChannelRegistrationConfig struct {
  336. Enabled bool
  337. MaxChannelsPerAccount int `yaml:"max-channels-per-account"`
  338. }
  339. // OperClassConfig defines a specific operator class.
  340. type OperClassConfig struct {
  341. Title string
  342. WhoisLine string
  343. Extends string
  344. Capabilities []string
  345. }
  346. // OperConfig defines a specific operator's configuration.
  347. type OperConfig struct {
  348. Class string
  349. Vhost string
  350. WhoisLine string `yaml:"whois-line"`
  351. Password string
  352. Fingerprint string
  353. Auto bool
  354. Modes string
  355. }
  356. // Various server-enforced limits on data size.
  357. type Limits struct {
  358. AwayLen int `yaml:"awaylen"`
  359. ChanListModes int `yaml:"chan-list-modes"`
  360. ChannelLen int `yaml:"channellen"`
  361. IdentLen int `yaml:"identlen"`
  362. KickLen int `yaml:"kicklen"`
  363. MonitorEntries int `yaml:"monitor-entries"`
  364. NickLen int `yaml:"nicklen"`
  365. TopicLen int `yaml:"topiclen"`
  366. WhowasEntries int `yaml:"whowas-entries"`
  367. RegistrationMessages int `yaml:"registration-messages"`
  368. Multiline struct {
  369. MaxBytes int `yaml:"max-bytes"`
  370. MaxLines int `yaml:"max-lines"`
  371. }
  372. }
  373. // STSConfig controls the STS configuration/
  374. type STSConfig struct {
  375. Enabled bool
  376. Duration custime.Duration
  377. Port int
  378. Preload bool
  379. STSOnlyBanner string `yaml:"sts-only-banner"`
  380. bannerLines []string
  381. }
  382. // Value returns the STS value to advertise in CAP
  383. func (sts *STSConfig) Value() string {
  384. val := fmt.Sprintf("duration=%d", int(time.Duration(sts.Duration).Seconds()))
  385. if sts.Enabled && sts.Port > 0 {
  386. val += fmt.Sprintf(",port=%d", sts.Port)
  387. }
  388. if sts.Enabled && sts.Preload {
  389. val += ",preload"
  390. }
  391. return val
  392. }
  393. type FakelagConfig struct {
  394. Enabled bool
  395. Window time.Duration
  396. BurstLimit uint `yaml:"burst-limit"`
  397. MessagesPerWindow uint `yaml:"messages-per-window"`
  398. Cooldown time.Duration
  399. }
  400. type TorListenersConfig struct {
  401. Listeners []string // legacy only
  402. RequireSasl bool `yaml:"require-sasl"`
  403. Vhost string
  404. MaxConnections int `yaml:"max-connections"`
  405. ThrottleDuration time.Duration `yaml:"throttle-duration"`
  406. MaxConnectionsPerDuration int `yaml:"max-connections-per-duration"`
  407. }
  408. // Config defines the overall configuration.
  409. type Config struct {
  410. Network struct {
  411. Name string
  412. }
  413. Server struct {
  414. Password string
  415. passwordBytes []byte
  416. Name string
  417. nameCasefolded string
  418. // Listeners is the new style for configuring listeners:
  419. Listeners map[string]listenerConfigBlock
  420. UnixBindMode os.FileMode `yaml:"unix-bind-mode"`
  421. TorListeners TorListenersConfig `yaml:"tor-listeners"`
  422. // Listen and TLSListeners are the legacy style:
  423. Listen []string
  424. TLSListeners map[string]TLSListenConfig `yaml:"tls-listeners"`
  425. // either way, the result is this:
  426. trueListeners map[string]listenerConfig
  427. STS STSConfig
  428. LookupHostnames *bool `yaml:"lookup-hostnames"`
  429. lookupHostnames bool
  430. ForwardConfirmHostnames bool `yaml:"forward-confirm-hostnames"`
  431. CheckIdent bool `yaml:"check-ident"`
  432. MOTD string
  433. motdLines []string
  434. MOTDFormatting bool `yaml:"motd-formatting"`
  435. ProxyAllowedFrom []string `yaml:"proxy-allowed-from"`
  436. proxyAllowedFromNets []net.IPNet
  437. WebIRC []webircConfig `yaml:"webirc"`
  438. MaxSendQString string `yaml:"max-sendq"`
  439. MaxSendQBytes int
  440. AllowPlaintextResume bool `yaml:"allow-plaintext-resume"`
  441. Compatibility struct {
  442. ForceTrailing *bool `yaml:"force-trailing"`
  443. forceTrailing bool
  444. SendUnprefixedSasl bool `yaml:"send-unprefixed-sasl"`
  445. }
  446. isupport isupport.List
  447. IPLimits connection_limits.LimiterConfig `yaml:"ip-limits"`
  448. Cloaks cloaks.CloakConfig `yaml:"ip-cloaking"`
  449. SecureNetDefs []string `yaml:"secure-nets"`
  450. secureNets []net.IPNet
  451. supportedCaps *caps.Set
  452. capValues caps.Values
  453. Casemapping Casemapping
  454. }
  455. Languages struct {
  456. Enabled bool
  457. Path string
  458. Default string
  459. }
  460. languageManager *languages.Manager
  461. Datastore struct {
  462. Path string
  463. AutoUpgrade bool
  464. MySQL struct {
  465. Enabled bool
  466. Host string
  467. Port int
  468. User string
  469. Password string
  470. HistoryDatabase string `yaml:"history-database"`
  471. }
  472. }
  473. Accounts AccountConfig
  474. Channels struct {
  475. DefaultModes *string `yaml:"default-modes"`
  476. defaultModes modes.Modes
  477. MaxChannelsPerClient int `yaml:"max-channels-per-client"`
  478. OpOnlyCreation bool `yaml:"operator-only-creation"`
  479. Registration ChannelRegistrationConfig
  480. }
  481. OperClasses map[string]*OperClassConfig `yaml:"oper-classes"`
  482. Opers map[string]*OperConfig
  483. // parsed operator definitions, unexported so they can't be defined
  484. // directly in YAML:
  485. operators map[string]*Oper
  486. Logging []logger.LoggingConfig
  487. Debug struct {
  488. RecoverFromErrors *bool `yaml:"recover-from-errors"`
  489. recoverFromErrors bool
  490. PprofListener *string `yaml:"pprof-listener"`
  491. }
  492. Limits Limits
  493. Fakelag FakelagConfig
  494. History struct {
  495. Enabled bool
  496. ChannelLength int `yaml:"channel-length"`
  497. ClientLength int `yaml:"client-length"`
  498. AutoresizeWindow time.Duration `yaml:"autoresize-window"`
  499. AutoreplayOnJoin int `yaml:"autoreplay-on-join"`
  500. ChathistoryMax int `yaml:"chathistory-maxmessages"`
  501. ZNCMax int `yaml:"znc-maxmessages"`
  502. Restrictions struct {
  503. ExpireTime custime.Duration `yaml:"expire-time"`
  504. EnforceRegistrationDate bool `yaml:"enforce-registration-date"`
  505. GracePeriod custime.Duration `yaml:"grace-period"`
  506. }
  507. Persistent struct {
  508. Enabled bool
  509. UnregisteredChannels bool `yaml:"unregistered-channels"`
  510. RegisteredChannels PersistentStatus `yaml:"registered-channels"`
  511. DirectMessages PersistentStatus `yaml:"direct-messages"`
  512. }
  513. }
  514. Filename string
  515. }
  516. // OperClass defines an assembled operator class.
  517. type OperClass struct {
  518. Title string
  519. WhoisLine string `yaml:"whois-line"`
  520. Capabilities map[string]bool // map to make lookups much easier
  521. }
  522. // OperatorClasses returns a map of assembled operator classes from the given config.
  523. func (conf *Config) OperatorClasses() (map[string]*OperClass, error) {
  524. ocs := make(map[string]*OperClass)
  525. // loop from no extends to most extended, breaking if we can't add any more
  526. lenOfLastOcs := -1
  527. for {
  528. if lenOfLastOcs == len(ocs) {
  529. return nil, ErrOperClassDependencies
  530. }
  531. lenOfLastOcs = len(ocs)
  532. var anyMissing bool
  533. for name, info := range conf.OperClasses {
  534. _, exists := ocs[name]
  535. _, extendsExists := ocs[info.Extends]
  536. if exists {
  537. // class already exists
  538. continue
  539. } else if len(info.Extends) > 0 && !extendsExists {
  540. // class we extend on doesn't exist
  541. _, exists := conf.OperClasses[info.Extends]
  542. if !exists {
  543. return nil, fmt.Errorf("Operclass [%s] extends [%s], which doesn't exist", name, info.Extends)
  544. }
  545. anyMissing = true
  546. continue
  547. }
  548. // create new operclass
  549. var oc OperClass
  550. oc.Capabilities = make(map[string]bool)
  551. // get inhereted info from other operclasses
  552. if len(info.Extends) > 0 {
  553. einfo := ocs[info.Extends]
  554. for capab := range einfo.Capabilities {
  555. oc.Capabilities[capab] = true
  556. }
  557. }
  558. // add our own info
  559. oc.Title = info.Title
  560. for _, capab := range info.Capabilities {
  561. oc.Capabilities[capab] = true
  562. }
  563. if len(info.WhoisLine) > 0 {
  564. oc.WhoisLine = info.WhoisLine
  565. } else {
  566. oc.WhoisLine = "is a"
  567. if strings.Contains(strings.ToLower(string(oc.Title[0])), "aeiou") {
  568. oc.WhoisLine += "n"
  569. }
  570. oc.WhoisLine += " "
  571. oc.WhoisLine += oc.Title
  572. }
  573. ocs[name] = &oc
  574. }
  575. if !anyMissing {
  576. // we've got every operclass!
  577. break
  578. }
  579. }
  580. return ocs, nil
  581. }
  582. // Oper represents a single assembled operator's config.
  583. type Oper struct {
  584. Name string
  585. Class *OperClass
  586. WhoisLine string
  587. Vhost string
  588. Pass []byte
  589. Fingerprint string
  590. Auto bool
  591. Modes []modes.ModeChange
  592. }
  593. // Operators returns a map of operator configs from the given OperClass and config.
  594. func (conf *Config) Operators(oc map[string]*OperClass) (map[string]*Oper, error) {
  595. operators := make(map[string]*Oper)
  596. for name, opConf := range conf.Opers {
  597. var oper Oper
  598. // oper name
  599. name, err := CasefoldName(name)
  600. if err != nil {
  601. return nil, fmt.Errorf("Could not casefold oper name: %s", err.Error())
  602. }
  603. oper.Name = name
  604. if opConf.Password != "" {
  605. oper.Pass, err = decodeLegacyPasswordHash(opConf.Password)
  606. if err != nil {
  607. return nil, fmt.Errorf("Oper %s has an invalid password hash: %s", oper.Name, err.Error())
  608. }
  609. }
  610. if opConf.Fingerprint != "" {
  611. oper.Fingerprint, err = utils.NormalizeCertfp(opConf.Fingerprint)
  612. if err != nil {
  613. return nil, fmt.Errorf("Oper %s has an invalid fingerprint: %s", oper.Name, err.Error())
  614. }
  615. }
  616. oper.Auto = opConf.Auto
  617. if oper.Pass == nil && oper.Fingerprint == "" {
  618. return nil, fmt.Errorf("Oper %s has neither a password nor a fingerprint", name)
  619. }
  620. oper.Vhost = opConf.Vhost
  621. class, exists := oc[opConf.Class]
  622. if !exists {
  623. return nil, fmt.Errorf("Could not load operator [%s] - they use operclass [%s] which does not exist", name, opConf.Class)
  624. }
  625. oper.Class = class
  626. if len(opConf.WhoisLine) > 0 {
  627. oper.WhoisLine = opConf.WhoisLine
  628. } else {
  629. oper.WhoisLine = class.WhoisLine
  630. }
  631. modeStr := strings.TrimSpace(opConf.Modes)
  632. modeChanges, unknownChanges := modes.ParseUserModeChanges(strings.Split(modeStr, " ")...)
  633. if len(unknownChanges) > 0 {
  634. return nil, fmt.Errorf("Could not load operator [%s] due to unknown modes %v", name, unknownChanges)
  635. }
  636. oper.Modes = modeChanges
  637. // successful, attach to list of opers
  638. operators[name] = &oper
  639. }
  640. return operators, nil
  641. }
  642. func loadTlsConfig(config TLSListenConfig) (tlsConfig *tls.Config, err error) {
  643. cert, err := tls.LoadX509KeyPair(config.Cert, config.Key)
  644. if err != nil {
  645. return nil, ErrInvalidCertKeyPair
  646. }
  647. result := tls.Config{
  648. Certificates: []tls.Certificate{cert},
  649. ClientAuth: tls.RequestClientCert,
  650. }
  651. return &result, nil
  652. }
  653. // prepareListeners populates Config.Server.trueListeners
  654. func (conf *Config) prepareListeners() (err error) {
  655. listeners := make(map[string]listenerConfig)
  656. if 0 < len(conf.Server.Listeners) {
  657. for addr, block := range conf.Server.Listeners {
  658. var lconf listenerConfig
  659. lconf.Tor = block.Tor
  660. lconf.STSOnly = block.STSOnly
  661. if lconf.STSOnly && !conf.Server.STS.Enabled {
  662. return fmt.Errorf("%s is configured as a STS-only listener, but STS is disabled", addr)
  663. }
  664. if block.TLS.Cert != "" {
  665. tlsConfig, err := loadTlsConfig(block.TLS)
  666. if err != nil {
  667. return err
  668. }
  669. lconf.TLSConfig = tlsConfig
  670. lconf.ProxyBeforeTLS = block.TLS.Proxy
  671. }
  672. listeners[addr] = lconf
  673. }
  674. } else if 0 < len(conf.Server.Listen) {
  675. log.Printf("WARNING: configuring listeners via the legacy `server.listen` config option")
  676. log.Printf("This will be removed in a later release: you should update to use `server.listeners`")
  677. torListeners := make(map[string]bool, len(conf.Server.TorListeners.Listeners))
  678. for _, addr := range conf.Server.TorListeners.Listeners {
  679. torListeners[addr] = true
  680. }
  681. for _, addr := range conf.Server.Listen {
  682. var lconf listenerConfig
  683. lconf.Tor = torListeners[addr]
  684. tlsListenConf, ok := conf.Server.TLSListeners[addr]
  685. if ok {
  686. tlsConfig, err := loadTlsConfig(tlsListenConf)
  687. if err != nil {
  688. return err
  689. }
  690. lconf.TLSConfig = tlsConfig
  691. }
  692. listeners[addr] = lconf
  693. }
  694. } else {
  695. return fmt.Errorf("No listeners were configured")
  696. }
  697. conf.Server.trueListeners = listeners
  698. return nil
  699. }
  700. // LoadRawConfig loads the config without doing any consistency checks or postprocessing
  701. func LoadRawConfig(filename string) (config *Config, err error) {
  702. data, err := ioutil.ReadFile(filename)
  703. if err != nil {
  704. return nil, err
  705. }
  706. err = yaml.Unmarshal(data, &config)
  707. if err != nil {
  708. return nil, err
  709. }
  710. return
  711. }
  712. // LoadConfig loads the given YAML configuration file.
  713. func LoadConfig(filename string) (config *Config, err error) {
  714. config, err = LoadRawConfig(filename)
  715. if err != nil {
  716. return nil, err
  717. }
  718. config.Filename = filename
  719. if config.Network.Name == "" {
  720. return nil, ErrNetworkNameMissing
  721. }
  722. if config.Server.Name == "" {
  723. return nil, ErrServerNameMissing
  724. }
  725. if !utils.IsServerName(config.Server.Name) {
  726. return nil, ErrServerNameNotHostname
  727. }
  728. config.Server.nameCasefolded = strings.ToLower(config.Server.Name)
  729. if config.Datastore.Path == "" {
  730. return nil, ErrDatastorePathMissing
  731. }
  732. //dan: automagically fix identlen until a few releases in the future (from now, 0.12.0), being a newly-introduced limit
  733. if config.Limits.IdentLen < 1 {
  734. config.Limits.IdentLen = 20
  735. }
  736. if config.Limits.NickLen < 1 || config.Limits.ChannelLen < 2 || config.Limits.AwayLen < 1 || config.Limits.KickLen < 1 || config.Limits.TopicLen < 1 {
  737. return nil, ErrLimitsAreInsane
  738. }
  739. if config.Limits.RegistrationMessages == 0 {
  740. config.Limits.RegistrationMessages = 1024
  741. }
  742. config.Server.supportedCaps = caps.NewCompleteSet()
  743. config.Server.capValues = make(caps.Values)
  744. err = config.prepareListeners()
  745. if err != nil {
  746. return nil, fmt.Errorf("failed to prepare listeners: %v", err)
  747. }
  748. if config.Server.STS.Enabled {
  749. if config.Server.STS.Port < 0 || config.Server.STS.Port > 65535 {
  750. return nil, fmt.Errorf("STS port is incorrect, should be 0 if disabled: %d", config.Server.STS.Port)
  751. }
  752. if config.Server.STS.STSOnlyBanner != "" {
  753. for _, line := range strings.Split(config.Server.STS.STSOnlyBanner, "\n") {
  754. config.Server.STS.bannerLines = append(config.Server.STS.bannerLines, strings.TrimSpace(line))
  755. }
  756. } else {
  757. 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)}
  758. }
  759. } else {
  760. config.Server.supportedCaps.Disable(caps.STS)
  761. config.Server.STS.Duration = 0
  762. }
  763. // set this even if STS is disabled
  764. config.Server.capValues[caps.STS] = config.Server.STS.Value()
  765. // lookup-hostnames defaults to true if unset
  766. if config.Server.LookupHostnames != nil {
  767. config.Server.lookupHostnames = *config.Server.LookupHostnames
  768. } else {
  769. config.Server.lookupHostnames = true
  770. }
  771. // process webirc blocks
  772. var newWebIRC []webircConfig
  773. for _, webirc := range config.Server.WebIRC {
  774. // skip webirc blocks with no hosts (such as the example one)
  775. if len(webirc.Hosts) == 0 {
  776. continue
  777. }
  778. err = webirc.Populate()
  779. if err != nil {
  780. return nil, fmt.Errorf("Could not parse WebIRC config: %s", err.Error())
  781. }
  782. newWebIRC = append(newWebIRC, webirc)
  783. }
  784. config.Server.WebIRC = newWebIRC
  785. if config.Limits.Multiline.MaxBytes <= 0 {
  786. config.Server.supportedCaps.Disable(caps.Multiline)
  787. } else {
  788. var multilineCapValue string
  789. if config.Limits.Multiline.MaxLines == 0 {
  790. multilineCapValue = fmt.Sprintf("max-bytes=%d", config.Limits.Multiline.MaxBytes)
  791. } else {
  792. multilineCapValue = fmt.Sprintf("max-bytes=%d,max-lines=%d", config.Limits.Multiline.MaxBytes, config.Limits.Multiline.MaxLines)
  793. }
  794. config.Server.capValues[caps.Multiline] = multilineCapValue
  795. }
  796. if !config.Accounts.Bouncer.Enabled {
  797. config.Accounts.Bouncer.AlwaysOn = PersistentDisabled
  798. config.Server.supportedCaps.Disable(caps.Bouncer)
  799. } else if config.Accounts.Bouncer.AlwaysOn >= PersistentOptOut {
  800. config.Accounts.Bouncer.AllowedByDefault = true
  801. }
  802. var newLogConfigs []logger.LoggingConfig
  803. for _, logConfig := range config.Logging {
  804. // methods
  805. methods := make(map[string]bool)
  806. for _, method := range strings.Split(logConfig.Method, " ") {
  807. if len(method) > 0 {
  808. methods[strings.ToLower(method)] = true
  809. }
  810. }
  811. if methods["file"] && logConfig.Filename == "" {
  812. return nil, ErrLoggerFilenameMissing
  813. }
  814. logConfig.MethodFile = methods["file"]
  815. logConfig.MethodStdout = methods["stdout"]
  816. logConfig.MethodStderr = methods["stderr"]
  817. // levels
  818. level, exists := logger.LogLevelNames[strings.ToLower(logConfig.LevelString)]
  819. if !exists {
  820. return nil, fmt.Errorf("Could not translate log leve [%s]", logConfig.LevelString)
  821. }
  822. logConfig.Level = level
  823. // types
  824. for _, typeStr := range strings.Split(logConfig.TypeString, " ") {
  825. if len(typeStr) == 0 {
  826. continue
  827. }
  828. if typeStr == "-" {
  829. return nil, ErrLoggerExcludeEmpty
  830. }
  831. if typeStr[0] == '-' {
  832. typeStr = typeStr[1:]
  833. logConfig.ExcludedTypes = append(logConfig.ExcludedTypes, typeStr)
  834. } else {
  835. logConfig.Types = append(logConfig.Types, typeStr)
  836. }
  837. }
  838. if len(logConfig.Types) < 1 {
  839. return nil, ErrLoggerHasNoTypes
  840. }
  841. newLogConfigs = append(newLogConfigs, logConfig)
  842. }
  843. config.Logging = newLogConfigs
  844. // hardcode this for now
  845. config.Accounts.Registration.EnabledCredentialTypes = []string{"passphrase", "certfp"}
  846. for i, name := range config.Accounts.Registration.EnabledCallbacks {
  847. if name == "none" {
  848. // we store "none" as "*" internally
  849. config.Accounts.Registration.EnabledCallbacks[i] = "*"
  850. }
  851. }
  852. sort.Strings(config.Accounts.Registration.EnabledCallbacks)
  853. config.Accounts.RequireSasl.exemptedNets, err = utils.ParseNetList(config.Accounts.RequireSasl.Exempted)
  854. if err != nil {
  855. return nil, fmt.Errorf("Could not parse require-sasl exempted nets: %v", err.Error())
  856. }
  857. config.Server.proxyAllowedFromNets, err = utils.ParseNetList(config.Server.ProxyAllowedFrom)
  858. if err != nil {
  859. return nil, fmt.Errorf("Could not parse proxy-allowed-from nets: %v", err.Error())
  860. }
  861. config.Server.secureNets, err = utils.ParseNetList(config.Server.SecureNetDefs)
  862. if err != nil {
  863. return nil, fmt.Errorf("Could not parse secure-nets: %v\n", err.Error())
  864. }
  865. rawRegexp := config.Accounts.VHosts.ValidRegexpRaw
  866. if rawRegexp != "" {
  867. regexp, err := regexp.Compile(rawRegexp)
  868. if err == nil {
  869. config.Accounts.VHosts.ValidRegexp = regexp
  870. } else {
  871. log.Printf("invalid vhost regexp: %s\n", err.Error())
  872. }
  873. }
  874. if config.Accounts.VHosts.ValidRegexp == nil {
  875. config.Accounts.VHosts.ValidRegexp = defaultValidVhostRegex
  876. }
  877. for _, vhost := range config.Accounts.VHosts.OfferList {
  878. if !config.Accounts.VHosts.ValidRegexp.MatchString(vhost) {
  879. return nil, fmt.Errorf("invalid offered vhost: %s", vhost)
  880. }
  881. }
  882. if !config.Accounts.LoginThrottling.Enabled {
  883. config.Accounts.LoginThrottling.MaxAttempts = 0 // limit of 0 means disabled
  884. }
  885. config.Server.capValues[caps.SASL] = "PLAIN,EXTERNAL"
  886. if !config.Accounts.AuthenticationEnabled {
  887. config.Server.supportedCaps.Disable(caps.SASL)
  888. }
  889. maxSendQBytes, err := bytefmt.ToBytes(config.Server.MaxSendQString)
  890. if err != nil {
  891. return nil, fmt.Errorf("Could not parse maximum SendQ size (make sure it only contains whole numbers): %s", err.Error())
  892. }
  893. config.Server.MaxSendQBytes = int(maxSendQBytes)
  894. config.languageManager, err = languages.NewManager(config.Languages.Enabled, config.Languages.Path, config.Languages.Default)
  895. if err != nil {
  896. return nil, fmt.Errorf("Could not load languages: %s", err.Error())
  897. }
  898. config.Server.capValues[caps.Languages] = config.languageManager.CapValue()
  899. // RecoverFromErrors defaults to true
  900. if config.Debug.RecoverFromErrors != nil {
  901. config.Debug.recoverFromErrors = *config.Debug.RecoverFromErrors
  902. } else {
  903. config.Debug.recoverFromErrors = true
  904. }
  905. // process operator definitions, store them to config.operators
  906. operclasses, err := config.OperatorClasses()
  907. if err != nil {
  908. return nil, err
  909. }
  910. opers, err := config.Operators(operclasses)
  911. if err != nil {
  912. return nil, err
  913. }
  914. config.operators = opers
  915. // parse default channel modes
  916. config.Channels.defaultModes = ParseDefaultChannelModes(config.Channels.DefaultModes)
  917. if config.Server.Password != "" {
  918. config.Server.passwordBytes, err = decodeLegacyPasswordHash(config.Server.Password)
  919. if err != nil {
  920. return nil, err
  921. }
  922. }
  923. if config.Accounts.Registration.BcryptCost == 0 {
  924. config.Accounts.Registration.BcryptCost = passwd.DefaultCost
  925. }
  926. if config.Channels.MaxChannelsPerClient == 0 {
  927. config.Channels.MaxChannelsPerClient = 100
  928. }
  929. if config.Channels.Registration.MaxChannelsPerAccount == 0 {
  930. config.Channels.Registration.MaxChannelsPerAccount = 15
  931. }
  932. forceTrailingPtr := config.Server.Compatibility.ForceTrailing
  933. if forceTrailingPtr != nil {
  934. config.Server.Compatibility.forceTrailing = *forceTrailingPtr
  935. } else {
  936. config.Server.Compatibility.forceTrailing = true
  937. }
  938. config.loadMOTD()
  939. // in the current implementation, we disable history by creating a history buffer
  940. // with zero capacity. but the `enabled` config option MUST be respected regardless
  941. // of this detail
  942. if !config.History.Enabled {
  943. config.History.ChannelLength = 0
  944. config.History.ClientLength = 0
  945. }
  946. if !config.History.Enabled || !config.History.Persistent.Enabled {
  947. config.History.Persistent.UnregisteredChannels = false
  948. config.History.Persistent.RegisteredChannels = PersistentDisabled
  949. config.History.Persistent.DirectMessages = PersistentDisabled
  950. }
  951. if config.History.ZNCMax == 0 {
  952. config.History.ZNCMax = config.History.ChathistoryMax
  953. }
  954. config.Server.Cloaks.Initialize()
  955. if config.Server.Cloaks.Enabled {
  956. if config.Server.Cloaks.Secret == "" || config.Server.Cloaks.Secret == "siaELnk6Kaeo65K3RCrwJjlWaZ-Bt3WuZ2L8MXLbNb4" {
  957. return nil, fmt.Errorf("You must generate a new value of server.ip-cloaking.secret to enable cloaking")
  958. }
  959. if !utils.IsHostname(config.Server.Cloaks.Netname) {
  960. return nil, fmt.Errorf("Invalid netname for cloaked hostnames: %s", config.Server.Cloaks.Netname)
  961. }
  962. }
  963. // now that all postprocessing is complete, regenerate ISUPPORT:
  964. err = config.generateISupport()
  965. if err != nil {
  966. return nil, err
  967. }
  968. err = config.prepareListeners()
  969. if err != nil {
  970. return nil, fmt.Errorf("failed to prepare listeners: %v", err)
  971. }
  972. return config, nil
  973. }
  974. // setISupport sets up our RPL_ISUPPORT reply.
  975. func (config *Config) generateISupport() (err error) {
  976. maxTargetsString := strconv.Itoa(maxTargets)
  977. // add RPL_ISUPPORT tokens
  978. isupport := &config.Server.isupport
  979. isupport.Initialize()
  980. isupport.Add("AWAYLEN", strconv.Itoa(config.Limits.AwayLen))
  981. isupport.Add("CASEMAPPING", "ascii")
  982. isupport.Add("CHANLIMIT", fmt.Sprintf("%s:%d", chanTypes, config.Channels.MaxChannelsPerClient))
  983. isupport.Add("CHANMODES", strings.Join([]string{modes.Modes{modes.BanMask, modes.ExceptMask, modes.InviteMask}.String(), "", modes.Modes{modes.UserLimit, modes.Key}.String(), modes.Modes{modes.InviteOnly, modes.Moderated, modes.NoOutside, modes.OpOnlyTopic, modes.ChanRoleplaying, modes.Secret}.String()}, ","))
  984. if config.History.Enabled && config.History.ChathistoryMax > 0 {
  985. isupport.Add("draft/CHATHISTORY", strconv.Itoa(config.History.ChathistoryMax))
  986. }
  987. isupport.Add("CHANNELLEN", strconv.Itoa(config.Limits.ChannelLen))
  988. isupport.Add("CHANTYPES", chanTypes)
  989. isupport.Add("ELIST", "U")
  990. isupport.Add("EXCEPTS", "")
  991. isupport.Add("INVEX", "")
  992. isupport.Add("KICKLEN", strconv.Itoa(config.Limits.KickLen))
  993. isupport.Add("MAXLIST", fmt.Sprintf("beI:%s", strconv.Itoa(config.Limits.ChanListModes)))
  994. isupport.Add("MAXTARGETS", maxTargetsString)
  995. isupport.Add("MODES", "")
  996. isupport.Add("MONITOR", strconv.Itoa(config.Limits.MonitorEntries))
  997. isupport.Add("NETWORK", config.Network.Name)
  998. isupport.Add("NICKLEN", strconv.Itoa(config.Limits.NickLen))
  999. isupport.Add("PREFIX", "(qaohv)~&@%+")
  1000. isupport.Add("RPCHAN", "E")
  1001. isupport.Add("RPUSER", "E")
  1002. isupport.Add("STATUSMSG", "~&@%+")
  1003. isupport.Add("TARGMAX", fmt.Sprintf("NAMES:1,LIST:1,KICK:1,WHOIS:1,USERHOST:10,PRIVMSG:%s,TAGMSG:%s,NOTICE:%s,MONITOR:", maxTargetsString, maxTargetsString, maxTargetsString))
  1004. isupport.Add("TOPICLEN", strconv.Itoa(config.Limits.TopicLen))
  1005. if config.Server.Casemapping == CasemappingPRECIS {
  1006. isupport.Add("UTF8MAPPING", precisUTF8MappingToken)
  1007. }
  1008. err = isupport.RegenerateCachedReply()
  1009. return
  1010. }
  1011. // Diff returns changes in supported caps across a rehash.
  1012. func (config *Config) Diff(oldConfig *Config) (addedCaps, removedCaps *caps.Set) {
  1013. addedCaps = caps.NewSet()
  1014. removedCaps = caps.NewSet()
  1015. if oldConfig == nil {
  1016. return
  1017. }
  1018. if oldConfig.Server.capValues[caps.Languages] != config.Server.capValues[caps.Languages] {
  1019. // XXX updated caps get a DEL line and then a NEW line with the new value
  1020. addedCaps.Add(caps.Languages)
  1021. removedCaps.Add(caps.Languages)
  1022. }
  1023. if !oldConfig.Accounts.AuthenticationEnabled && config.Accounts.AuthenticationEnabled {
  1024. addedCaps.Add(caps.SASL)
  1025. } else if oldConfig.Accounts.AuthenticationEnabled && !config.Accounts.AuthenticationEnabled {
  1026. removedCaps.Add(caps.SASL)
  1027. }
  1028. if !oldConfig.Accounts.Bouncer.Enabled && config.Accounts.Bouncer.Enabled {
  1029. addedCaps.Add(caps.Bouncer)
  1030. } else if oldConfig.Accounts.Bouncer.Enabled && !config.Accounts.Bouncer.Enabled {
  1031. removedCaps.Add(caps.Bouncer)
  1032. }
  1033. if oldConfig.Limits.Multiline.MaxBytes != 0 && config.Limits.Multiline.MaxBytes == 0 {
  1034. removedCaps.Add(caps.Multiline)
  1035. } else if oldConfig.Limits.Multiline.MaxBytes == 0 && config.Limits.Multiline.MaxBytes != 0 {
  1036. addedCaps.Add(caps.Multiline)
  1037. } else if oldConfig.Limits.Multiline != config.Limits.Multiline {
  1038. removedCaps.Add(caps.Multiline)
  1039. addedCaps.Add(caps.Multiline)
  1040. }
  1041. if oldConfig.Server.STS.Enabled != config.Server.STS.Enabled || oldConfig.Server.capValues[caps.STS] != config.Server.capValues[caps.STS] {
  1042. // XXX: STS is always removed by CAP NEW sts=duration=0, not CAP DEL
  1043. // so the appropriate notify is always a CAP NEW; put it in addedCaps for any change
  1044. addedCaps.Add(caps.STS)
  1045. }
  1046. return
  1047. }