You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

config.go 34KB

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