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 35KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177
  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 time.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 time.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 time.Duration `yaml:"duration-real"`
  377. DurationString string `yaml:"duration"`
  378. Port int
  379. Preload bool
  380. STSOnlyBanner string `yaml:"sts-only-banner"`
  381. bannerLines []string
  382. }
  383. // Value returns the STS value to advertise in CAP
  384. func (sts *STSConfig) Value() string {
  385. val := fmt.Sprintf("duration=%d", int(sts.Duration.Seconds()))
  386. if sts.Enabled && sts.Port > 0 {
  387. val += fmt.Sprintf(",port=%d", sts.Port)
  388. }
  389. if sts.Enabled && sts.Preload {
  390. val += ",preload"
  391. }
  392. return val
  393. }
  394. type FakelagConfig struct {
  395. Enabled bool
  396. Window time.Duration
  397. BurstLimit uint `yaml:"burst-limit"`
  398. MessagesPerWindow uint `yaml:"messages-per-window"`
  399. Cooldown time.Duration
  400. }
  401. type TorListenersConfig struct {
  402. Listeners []string // legacy only
  403. RequireSasl bool `yaml:"require-sasl"`
  404. Vhost string
  405. MaxConnections int `yaml:"max-connections"`
  406. ThrottleDuration time.Duration `yaml:"throttle-duration"`
  407. MaxConnectionsPerDuration int `yaml:"max-connections-per-duration"`
  408. }
  409. // Config defines the overall configuration.
  410. type Config struct {
  411. Network struct {
  412. Name string
  413. }
  414. Server struct {
  415. Password string
  416. passwordBytes []byte
  417. Name string
  418. nameCasefolded string
  419. // Listeners is the new style for configuring listeners:
  420. Listeners map[string]listenerConfigBlock
  421. UnixBindMode os.FileMode `yaml:"unix-bind-mode"`
  422. TorListeners TorListenersConfig `yaml:"tor-listeners"`
  423. // Listen and TLSListeners are the legacy style:
  424. Listen []string
  425. TLSListeners map[string]TLSListenConfig `yaml:"tls-listeners"`
  426. // either way, the result is this:
  427. trueListeners map[string]listenerConfig
  428. STS STSConfig
  429. LookupHostnames *bool `yaml:"lookup-hostnames"`
  430. lookupHostnames bool
  431. ForwardConfirmHostnames bool `yaml:"forward-confirm-hostnames"`
  432. CheckIdent bool `yaml:"check-ident"`
  433. MOTD string
  434. motdLines []string
  435. MOTDFormatting bool `yaml:"motd-formatting"`
  436. ProxyAllowedFrom []string `yaml:"proxy-allowed-from"`
  437. proxyAllowedFromNets []net.IPNet
  438. WebIRC []webircConfig `yaml:"webirc"`
  439. MaxSendQString string `yaml:"max-sendq"`
  440. MaxSendQBytes int
  441. AllowPlaintextResume bool `yaml:"allow-plaintext-resume"`
  442. Compatibility struct {
  443. ForceTrailing *bool `yaml:"force-trailing"`
  444. forceTrailing bool
  445. SendUnprefixedSasl bool `yaml:"send-unprefixed-sasl"`
  446. }
  447. isupport isupport.List
  448. IPLimits connection_limits.LimiterConfig `yaml:"ip-limits"`
  449. Cloaks cloaks.CloakConfig `yaml:"ip-cloaking"`
  450. SecureNetDefs []string `yaml:"secure-nets"`
  451. secureNets []net.IPNet
  452. supportedCaps *caps.Set
  453. capValues caps.Values
  454. Casemapping Casemapping
  455. }
  456. Languages struct {
  457. Enabled bool
  458. Path string
  459. Default string
  460. }
  461. languageManager *languages.Manager
  462. Datastore struct {
  463. Path string
  464. AutoUpgrade bool
  465. MySQL struct {
  466. Enabled bool
  467. Host string
  468. Port int
  469. User string
  470. Password string
  471. HistoryDatabase string `yaml:"history-database"`
  472. }
  473. }
  474. Accounts AccountConfig
  475. Channels struct {
  476. DefaultModes *string `yaml:"default-modes"`
  477. defaultModes modes.Modes
  478. MaxChannelsPerClient int `yaml:"max-channels-per-client"`
  479. OpOnlyCreation bool `yaml:"operator-only-creation"`
  480. Registration ChannelRegistrationConfig
  481. }
  482. OperClasses map[string]*OperClassConfig `yaml:"oper-classes"`
  483. Opers map[string]*OperConfig
  484. // parsed operator definitions, unexported so they can't be defined
  485. // directly in YAML:
  486. operators map[string]*Oper
  487. Logging []logger.LoggingConfig
  488. Debug struct {
  489. RecoverFromErrors *bool `yaml:"recover-from-errors"`
  490. recoverFromErrors bool
  491. PprofListener *string `yaml:"pprof-listener"`
  492. }
  493. Limits Limits
  494. Fakelag FakelagConfig
  495. History struct {
  496. Enabled bool
  497. ChannelLength int `yaml:"channel-length"`
  498. ClientLength int `yaml:"client-length"`
  499. AutoresizeWindow time.Duration `yaml:"autoresize-window"`
  500. AutoreplayOnJoin int `yaml:"autoreplay-on-join"`
  501. ChathistoryMax int `yaml:"chathistory-maxmessages"`
  502. ZNCMax int `yaml:"znc-maxmessages"`
  503. Restrictions struct {
  504. ExpireTime time.Duration `yaml:"expire-time"`
  505. EnforceRegistrationDate bool `yaml:"enforce-registration-date"`
  506. GracePeriod time.Duration `yaml:"grace-period"`
  507. }
  508. Persistent struct {
  509. Enabled bool
  510. UnregisteredChannels bool `yaml:"unregistered-channels"`
  511. RegisteredChannels PersistentStatus `yaml:"registered-channels"`
  512. DirectMessages PersistentStatus `yaml:"direct-messages"`
  513. }
  514. }
  515. Filename string
  516. }
  517. // OperClass defines an assembled operator class.
  518. type OperClass struct {
  519. Title string
  520. WhoisLine string `yaml:"whois-line"`
  521. Capabilities map[string]bool // map to make lookups much easier
  522. }
  523. // OperatorClasses returns a map of assembled operator classes from the given config.
  524. func (conf *Config) OperatorClasses() (map[string]*OperClass, error) {
  525. ocs := make(map[string]*OperClass)
  526. // loop from no extends to most extended, breaking if we can't add any more
  527. lenOfLastOcs := -1
  528. for {
  529. if lenOfLastOcs == len(ocs) {
  530. return nil, ErrOperClassDependencies
  531. }
  532. lenOfLastOcs = len(ocs)
  533. var anyMissing bool
  534. for name, info := range conf.OperClasses {
  535. _, exists := ocs[name]
  536. _, extendsExists := ocs[info.Extends]
  537. if exists {
  538. // class already exists
  539. continue
  540. } else if len(info.Extends) > 0 && !extendsExists {
  541. // class we extend on doesn't exist
  542. _, exists := conf.OperClasses[info.Extends]
  543. if !exists {
  544. return nil, fmt.Errorf("Operclass [%s] extends [%s], which doesn't exist", name, info.Extends)
  545. }
  546. anyMissing = true
  547. continue
  548. }
  549. // create new operclass
  550. var oc OperClass
  551. oc.Capabilities = make(map[string]bool)
  552. // get inhereted info from other operclasses
  553. if len(info.Extends) > 0 {
  554. einfo := ocs[info.Extends]
  555. for capab := range einfo.Capabilities {
  556. oc.Capabilities[capab] = true
  557. }
  558. }
  559. // add our own info
  560. oc.Title = info.Title
  561. for _, capab := range info.Capabilities {
  562. oc.Capabilities[capab] = true
  563. }
  564. if len(info.WhoisLine) > 0 {
  565. oc.WhoisLine = info.WhoisLine
  566. } else {
  567. oc.WhoisLine = "is a"
  568. if strings.Contains(strings.ToLower(string(oc.Title[0])), "aeiou") {
  569. oc.WhoisLine += "n"
  570. }
  571. oc.WhoisLine += " "
  572. oc.WhoisLine += oc.Title
  573. }
  574. ocs[name] = &oc
  575. }
  576. if !anyMissing {
  577. // we've got every operclass!
  578. break
  579. }
  580. }
  581. return ocs, nil
  582. }
  583. // Oper represents a single assembled operator's config.
  584. type Oper struct {
  585. Name string
  586. Class *OperClass
  587. WhoisLine string
  588. Vhost string
  589. Pass []byte
  590. Fingerprint string
  591. Auto bool
  592. Modes []modes.ModeChange
  593. }
  594. // Operators returns a map of operator configs from the given OperClass and config.
  595. func (conf *Config) Operators(oc map[string]*OperClass) (map[string]*Oper, error) {
  596. operators := make(map[string]*Oper)
  597. for name, opConf := range conf.Opers {
  598. var oper Oper
  599. // oper name
  600. name, err := CasefoldName(name)
  601. if err != nil {
  602. return nil, fmt.Errorf("Could not casefold oper name: %s", err.Error())
  603. }
  604. oper.Name = name
  605. if opConf.Password != "" {
  606. oper.Pass, err = decodeLegacyPasswordHash(opConf.Password)
  607. if err != nil {
  608. return nil, fmt.Errorf("Oper %s has an invalid password hash: %s", oper.Name, err.Error())
  609. }
  610. }
  611. if opConf.Fingerprint != "" {
  612. oper.Fingerprint, err = utils.NormalizeCertfp(opConf.Fingerprint)
  613. if err != nil {
  614. return nil, fmt.Errorf("Oper %s has an invalid fingerprint: %s", oper.Name, err.Error())
  615. }
  616. }
  617. oper.Auto = opConf.Auto
  618. if oper.Pass == nil && oper.Fingerprint == "" {
  619. return nil, fmt.Errorf("Oper %s has neither a password nor a fingerprint", name)
  620. }
  621. oper.Vhost = opConf.Vhost
  622. class, exists := oc[opConf.Class]
  623. if !exists {
  624. return nil, fmt.Errorf("Could not load operator [%s] - they use operclass [%s] which does not exist", name, opConf.Class)
  625. }
  626. oper.Class = class
  627. if len(opConf.WhoisLine) > 0 {
  628. oper.WhoisLine = opConf.WhoisLine
  629. } else {
  630. oper.WhoisLine = class.WhoisLine
  631. }
  632. modeStr := strings.TrimSpace(opConf.Modes)
  633. modeChanges, unknownChanges := modes.ParseUserModeChanges(strings.Split(modeStr, " ")...)
  634. if len(unknownChanges) > 0 {
  635. return nil, fmt.Errorf("Could not load operator [%s] due to unknown modes %v", name, unknownChanges)
  636. }
  637. oper.Modes = modeChanges
  638. // successful, attach to list of opers
  639. operators[name] = &oper
  640. }
  641. return operators, nil
  642. }
  643. func loadTlsConfig(config TLSListenConfig) (tlsConfig *tls.Config, err error) {
  644. cert, err := tls.LoadX509KeyPair(config.Cert, config.Key)
  645. if err != nil {
  646. return nil, ErrInvalidCertKeyPair
  647. }
  648. result := tls.Config{
  649. Certificates: []tls.Certificate{cert},
  650. ClientAuth: tls.RequestClientCert,
  651. }
  652. return &result, nil
  653. }
  654. // prepareListeners populates Config.Server.trueListeners
  655. func (conf *Config) prepareListeners() (err error) {
  656. listeners := make(map[string]listenerConfig)
  657. if 0 < len(conf.Server.Listeners) {
  658. for addr, block := range conf.Server.Listeners {
  659. var lconf listenerConfig
  660. lconf.Tor = block.Tor
  661. lconf.STSOnly = block.STSOnly
  662. if lconf.STSOnly && !conf.Server.STS.Enabled {
  663. return fmt.Errorf("%s is configured as a STS-only listener, but STS is disabled", addr)
  664. }
  665. if block.TLS.Cert != "" {
  666. tlsConfig, err := loadTlsConfig(block.TLS)
  667. if err != nil {
  668. return err
  669. }
  670. lconf.TLSConfig = tlsConfig
  671. lconf.ProxyBeforeTLS = block.TLS.Proxy
  672. }
  673. listeners[addr] = lconf
  674. }
  675. } else if 0 < len(conf.Server.Listen) {
  676. log.Printf("WARNING: configuring listeners via the legacy `server.listen` config option")
  677. log.Printf("This will be removed in a later release: you should update to use `server.listeners`")
  678. torListeners := make(map[string]bool, len(conf.Server.TorListeners.Listeners))
  679. for _, addr := range conf.Server.TorListeners.Listeners {
  680. torListeners[addr] = true
  681. }
  682. for _, addr := range conf.Server.Listen {
  683. var lconf listenerConfig
  684. lconf.Tor = torListeners[addr]
  685. tlsListenConf, ok := conf.Server.TLSListeners[addr]
  686. if ok {
  687. tlsConfig, err := loadTlsConfig(tlsListenConf)
  688. if err != nil {
  689. return err
  690. }
  691. lconf.TLSConfig = tlsConfig
  692. }
  693. listeners[addr] = lconf
  694. }
  695. } else {
  696. return fmt.Errorf("No listeners were configured")
  697. }
  698. conf.Server.trueListeners = listeners
  699. return nil
  700. }
  701. // LoadRawConfig loads the config without doing any consistency checks or postprocessing
  702. func LoadRawConfig(filename string) (config *Config, err error) {
  703. data, err := ioutil.ReadFile(filename)
  704. if err != nil {
  705. return nil, err
  706. }
  707. err = yaml.Unmarshal(data, &config)
  708. if err != nil {
  709. return nil, err
  710. }
  711. return
  712. }
  713. // LoadConfig loads the given YAML configuration file.
  714. func LoadConfig(filename string) (config *Config, err error) {
  715. config, err = LoadRawConfig(filename)
  716. if err != nil {
  717. return nil, err
  718. }
  719. config.Filename = filename
  720. if config.Network.Name == "" {
  721. return nil, ErrNetworkNameMissing
  722. }
  723. if config.Server.Name == "" {
  724. return nil, ErrServerNameMissing
  725. }
  726. if !utils.IsServerName(config.Server.Name) {
  727. return nil, ErrServerNameNotHostname
  728. }
  729. config.Server.nameCasefolded = strings.ToLower(config.Server.Name)
  730. if config.Datastore.Path == "" {
  731. return nil, ErrDatastorePathMissing
  732. }
  733. //dan: automagically fix identlen until a few releases in the future (from now, 0.12.0), being a newly-introduced limit
  734. if config.Limits.IdentLen < 1 {
  735. config.Limits.IdentLen = 20
  736. }
  737. if config.Limits.NickLen < 1 || config.Limits.ChannelLen < 2 || config.Limits.AwayLen < 1 || config.Limits.KickLen < 1 || config.Limits.TopicLen < 1 {
  738. return nil, ErrLimitsAreInsane
  739. }
  740. if config.Limits.RegistrationMessages == 0 {
  741. config.Limits.RegistrationMessages = 1024
  742. }
  743. config.Server.supportedCaps = caps.NewCompleteSet()
  744. config.Server.capValues = make(caps.Values)
  745. err = config.prepareListeners()
  746. if err != nil {
  747. return nil, fmt.Errorf("failed to prepare listeners: %v", err)
  748. }
  749. if config.Server.STS.Enabled {
  750. config.Server.STS.Duration, err = custime.ParseDuration(config.Server.STS.DurationString)
  751. if err != nil {
  752. return nil, fmt.Errorf("Could not parse STS duration: %s", err.Error())
  753. }
  754. if config.Server.STS.Port < 0 || config.Server.STS.Port > 65535 {
  755. return nil, fmt.Errorf("STS port is incorrect, should be 0 if disabled: %d", config.Server.STS.Port)
  756. }
  757. if config.Server.STS.STSOnlyBanner != "" {
  758. for _, line := range strings.Split(config.Server.STS.STSOnlyBanner, "\n") {
  759. config.Server.STS.bannerLines = append(config.Server.STS.bannerLines, strings.TrimSpace(line))
  760. }
  761. } else {
  762. 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)}
  763. }
  764. } else {
  765. config.Server.supportedCaps.Disable(caps.STS)
  766. config.Server.STS.Duration = 0
  767. }
  768. // set this even if STS is disabled
  769. config.Server.capValues[caps.STS] = config.Server.STS.Value()
  770. // lookup-hostnames defaults to true if unset
  771. if config.Server.LookupHostnames != nil {
  772. config.Server.lookupHostnames = *config.Server.LookupHostnames
  773. } else {
  774. config.Server.lookupHostnames = true
  775. }
  776. // process webirc blocks
  777. var newWebIRC []webircConfig
  778. for _, webirc := range config.Server.WebIRC {
  779. // skip webirc blocks with no hosts (such as the example one)
  780. if len(webirc.Hosts) == 0 {
  781. continue
  782. }
  783. err = webirc.Populate()
  784. if err != nil {
  785. return nil, fmt.Errorf("Could not parse WebIRC config: %s", err.Error())
  786. }
  787. newWebIRC = append(newWebIRC, webirc)
  788. }
  789. config.Server.WebIRC = newWebIRC
  790. if config.Limits.Multiline.MaxBytes <= 0 {
  791. config.Server.supportedCaps.Disable(caps.Multiline)
  792. } else {
  793. var multilineCapValue string
  794. if config.Limits.Multiline.MaxLines == 0 {
  795. multilineCapValue = fmt.Sprintf("max-bytes=%d", config.Limits.Multiline.MaxBytes)
  796. } else {
  797. multilineCapValue = fmt.Sprintf("max-bytes=%d,max-lines=%d", config.Limits.Multiline.MaxBytes, config.Limits.Multiline.MaxLines)
  798. }
  799. config.Server.capValues[caps.Multiline] = multilineCapValue
  800. }
  801. if !config.Accounts.Bouncer.Enabled {
  802. config.Accounts.Bouncer.AlwaysOn = PersistentDisabled
  803. config.Server.supportedCaps.Disable(caps.Bouncer)
  804. } else if config.Accounts.Bouncer.AlwaysOn >= PersistentOptOut {
  805. config.Accounts.Bouncer.AllowedByDefault = true
  806. }
  807. var newLogConfigs []logger.LoggingConfig
  808. for _, logConfig := range config.Logging {
  809. // methods
  810. methods := make(map[string]bool)
  811. for _, method := range strings.Split(logConfig.Method, " ") {
  812. if len(method) > 0 {
  813. methods[strings.ToLower(method)] = true
  814. }
  815. }
  816. if methods["file"] && logConfig.Filename == "" {
  817. return nil, ErrLoggerFilenameMissing
  818. }
  819. logConfig.MethodFile = methods["file"]
  820. logConfig.MethodStdout = methods["stdout"]
  821. logConfig.MethodStderr = methods["stderr"]
  822. // levels
  823. level, exists := logger.LogLevelNames[strings.ToLower(logConfig.LevelString)]
  824. if !exists {
  825. return nil, fmt.Errorf("Could not translate log leve [%s]", logConfig.LevelString)
  826. }
  827. logConfig.Level = level
  828. // types
  829. for _, typeStr := range strings.Split(logConfig.TypeString, " ") {
  830. if len(typeStr) == 0 {
  831. continue
  832. }
  833. if typeStr == "-" {
  834. return nil, ErrLoggerExcludeEmpty
  835. }
  836. if typeStr[0] == '-' {
  837. typeStr = typeStr[1:]
  838. logConfig.ExcludedTypes = append(logConfig.ExcludedTypes, typeStr)
  839. } else {
  840. logConfig.Types = append(logConfig.Types, typeStr)
  841. }
  842. }
  843. if len(logConfig.Types) < 1 {
  844. return nil, ErrLoggerHasNoTypes
  845. }
  846. newLogConfigs = append(newLogConfigs, logConfig)
  847. }
  848. config.Logging = newLogConfigs
  849. // hardcode this for now
  850. config.Accounts.Registration.EnabledCredentialTypes = []string{"passphrase", "certfp"}
  851. for i, name := range config.Accounts.Registration.EnabledCallbacks {
  852. if name == "none" {
  853. // we store "none" as "*" internally
  854. config.Accounts.Registration.EnabledCallbacks[i] = "*"
  855. }
  856. }
  857. sort.Strings(config.Accounts.Registration.EnabledCallbacks)
  858. config.Accounts.RequireSasl.exemptedNets, err = utils.ParseNetList(config.Accounts.RequireSasl.Exempted)
  859. if err != nil {
  860. return nil, fmt.Errorf("Could not parse require-sasl exempted nets: %v", err.Error())
  861. }
  862. config.Server.proxyAllowedFromNets, err = utils.ParseNetList(config.Server.ProxyAllowedFrom)
  863. if err != nil {
  864. return nil, fmt.Errorf("Could not parse proxy-allowed-from nets: %v", err.Error())
  865. }
  866. config.Server.secureNets, err = utils.ParseNetList(config.Server.SecureNetDefs)
  867. if err != nil {
  868. return nil, fmt.Errorf("Could not parse secure-nets: %v\n", err.Error())
  869. }
  870. rawRegexp := config.Accounts.VHosts.ValidRegexpRaw
  871. if rawRegexp != "" {
  872. regexp, err := regexp.Compile(rawRegexp)
  873. if err == nil {
  874. config.Accounts.VHosts.ValidRegexp = regexp
  875. } else {
  876. log.Printf("invalid vhost regexp: %s\n", err.Error())
  877. }
  878. }
  879. if config.Accounts.VHosts.ValidRegexp == nil {
  880. config.Accounts.VHosts.ValidRegexp = defaultValidVhostRegex
  881. }
  882. for _, vhost := range config.Accounts.VHosts.OfferList {
  883. if !config.Accounts.VHosts.ValidRegexp.MatchString(vhost) {
  884. return nil, fmt.Errorf("invalid offered vhost: %s", vhost)
  885. }
  886. }
  887. if !config.Accounts.LoginThrottling.Enabled {
  888. config.Accounts.LoginThrottling.MaxAttempts = 0 // limit of 0 means disabled
  889. }
  890. config.Server.capValues[caps.SASL] = "PLAIN,EXTERNAL"
  891. if !config.Accounts.AuthenticationEnabled {
  892. config.Server.supportedCaps.Disable(caps.SASL)
  893. }
  894. maxSendQBytes, err := bytefmt.ToBytes(config.Server.MaxSendQString)
  895. if err != nil {
  896. return nil, fmt.Errorf("Could not parse maximum SendQ size (make sure it only contains whole numbers): %s", err.Error())
  897. }
  898. config.Server.MaxSendQBytes = int(maxSendQBytes)
  899. config.languageManager, err = languages.NewManager(config.Languages.Enabled, config.Languages.Path, config.Languages.Default)
  900. if err != nil {
  901. return nil, fmt.Errorf("Could not load languages: %s", err.Error())
  902. }
  903. config.Server.capValues[caps.Languages] = config.languageManager.CapValue()
  904. // RecoverFromErrors defaults to true
  905. if config.Debug.RecoverFromErrors != nil {
  906. config.Debug.recoverFromErrors = *config.Debug.RecoverFromErrors
  907. } else {
  908. config.Debug.recoverFromErrors = true
  909. }
  910. // process operator definitions, store them to config.operators
  911. operclasses, err := config.OperatorClasses()
  912. if err != nil {
  913. return nil, err
  914. }
  915. opers, err := config.Operators(operclasses)
  916. if err != nil {
  917. return nil, err
  918. }
  919. config.operators = opers
  920. // parse default channel modes
  921. config.Channels.defaultModes = ParseDefaultChannelModes(config.Channels.DefaultModes)
  922. if config.Server.Password != "" {
  923. config.Server.passwordBytes, err = decodeLegacyPasswordHash(config.Server.Password)
  924. if err != nil {
  925. return nil, err
  926. }
  927. }
  928. if config.Accounts.Registration.BcryptCost == 0 {
  929. config.Accounts.Registration.BcryptCost = passwd.DefaultCost
  930. }
  931. if config.Channels.MaxChannelsPerClient == 0 {
  932. config.Channels.MaxChannelsPerClient = 100
  933. }
  934. if config.Channels.Registration.MaxChannelsPerAccount == 0 {
  935. config.Channels.Registration.MaxChannelsPerAccount = 15
  936. }
  937. forceTrailingPtr := config.Server.Compatibility.ForceTrailing
  938. if forceTrailingPtr != nil {
  939. config.Server.Compatibility.forceTrailing = *forceTrailingPtr
  940. } else {
  941. config.Server.Compatibility.forceTrailing = true
  942. }
  943. config.loadMOTD()
  944. // in the current implementation, we disable history by creating a history buffer
  945. // with zero capacity. but the `enabled` config option MUST be respected regardless
  946. // of this detail
  947. if !config.History.Enabled {
  948. config.History.ChannelLength = 0
  949. config.History.ClientLength = 0
  950. }
  951. if !config.History.Enabled || !config.History.Persistent.Enabled {
  952. config.History.Persistent.UnregisteredChannels = false
  953. config.History.Persistent.RegisteredChannels = PersistentDisabled
  954. config.History.Persistent.DirectMessages = PersistentDisabled
  955. }
  956. if config.History.ZNCMax == 0 {
  957. config.History.ZNCMax = config.History.ChathistoryMax
  958. }
  959. config.Server.Cloaks.Initialize()
  960. if config.Server.Cloaks.Enabled {
  961. if config.Server.Cloaks.Secret == "" || config.Server.Cloaks.Secret == "siaELnk6Kaeo65K3RCrwJjlWaZ-Bt3WuZ2L8MXLbNb4" {
  962. return nil, fmt.Errorf("You must generate a new value of server.ip-cloaking.secret to enable cloaking")
  963. }
  964. if !utils.IsHostname(config.Server.Cloaks.Netname) {
  965. return nil, fmt.Errorf("Invalid netname for cloaked hostnames: %s", config.Server.Cloaks.Netname)
  966. }
  967. }
  968. // now that all postprocessing is complete, regenerate ISUPPORT:
  969. err = config.generateISupport()
  970. if err != nil {
  971. return nil, err
  972. }
  973. err = config.prepareListeners()
  974. if err != nil {
  975. return nil, fmt.Errorf("failed to prepare listeners: %v", err)
  976. }
  977. return config, nil
  978. }
  979. // setISupport sets up our RPL_ISUPPORT reply.
  980. func (config *Config) generateISupport() (err error) {
  981. maxTargetsString := strconv.Itoa(maxTargets)
  982. // add RPL_ISUPPORT tokens
  983. isupport := &config.Server.isupport
  984. isupport.Initialize()
  985. isupport.Add("AWAYLEN", strconv.Itoa(config.Limits.AwayLen))
  986. isupport.Add("CASEMAPPING", "ascii")
  987. isupport.Add("CHANLIMIT", fmt.Sprintf("%s:%d", chanTypes, config.Channels.MaxChannelsPerClient))
  988. 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()}, ","))
  989. if config.History.Enabled && config.History.ChathistoryMax > 0 {
  990. isupport.Add("draft/CHATHISTORY", strconv.Itoa(config.History.ChathistoryMax))
  991. }
  992. isupport.Add("CHANNELLEN", strconv.Itoa(config.Limits.ChannelLen))
  993. isupport.Add("CHANTYPES", chanTypes)
  994. isupport.Add("ELIST", "U")
  995. isupport.Add("EXCEPTS", "")
  996. isupport.Add("INVEX", "")
  997. isupport.Add("KICKLEN", strconv.Itoa(config.Limits.KickLen))
  998. isupport.Add("MAXLIST", fmt.Sprintf("beI:%s", strconv.Itoa(config.Limits.ChanListModes)))
  999. isupport.Add("MAXTARGETS", maxTargetsString)
  1000. isupport.Add("MODES", "")
  1001. isupport.Add("MONITOR", strconv.Itoa(config.Limits.MonitorEntries))
  1002. isupport.Add("NETWORK", config.Network.Name)
  1003. isupport.Add("NICKLEN", strconv.Itoa(config.Limits.NickLen))
  1004. isupport.Add("PREFIX", "(qaohv)~&@%+")
  1005. isupport.Add("RPCHAN", "E")
  1006. isupport.Add("RPUSER", "E")
  1007. isupport.Add("STATUSMSG", "~&@%+")
  1008. 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))
  1009. isupport.Add("TOPICLEN", strconv.Itoa(config.Limits.TopicLen))
  1010. if config.Server.Casemapping == CasemappingPRECIS {
  1011. isupport.Add("UTF8MAPPING", precisUTF8MappingToken)
  1012. }
  1013. err = isupport.RegenerateCachedReply()
  1014. return
  1015. }
  1016. // Diff returns changes in supported caps across a rehash.
  1017. func (config *Config) Diff(oldConfig *Config) (addedCaps, removedCaps *caps.Set) {
  1018. addedCaps = caps.NewSet()
  1019. removedCaps = caps.NewSet()
  1020. if oldConfig == nil {
  1021. return
  1022. }
  1023. if oldConfig.Server.capValues[caps.Languages] != config.Server.capValues[caps.Languages] {
  1024. // XXX updated caps get a DEL line and then a NEW line with the new value
  1025. addedCaps.Add(caps.Languages)
  1026. removedCaps.Add(caps.Languages)
  1027. }
  1028. if !oldConfig.Accounts.AuthenticationEnabled && config.Accounts.AuthenticationEnabled {
  1029. addedCaps.Add(caps.SASL)
  1030. } else if oldConfig.Accounts.AuthenticationEnabled && !config.Accounts.AuthenticationEnabled {
  1031. removedCaps.Add(caps.SASL)
  1032. }
  1033. if !oldConfig.Accounts.Bouncer.Enabled && config.Accounts.Bouncer.Enabled {
  1034. addedCaps.Add(caps.Bouncer)
  1035. } else if oldConfig.Accounts.Bouncer.Enabled && !config.Accounts.Bouncer.Enabled {
  1036. removedCaps.Add(caps.Bouncer)
  1037. }
  1038. if oldConfig.Limits.Multiline.MaxBytes != 0 && config.Limits.Multiline.MaxBytes == 0 {
  1039. removedCaps.Add(caps.Multiline)
  1040. } else if oldConfig.Limits.Multiline.MaxBytes == 0 && config.Limits.Multiline.MaxBytes != 0 {
  1041. addedCaps.Add(caps.Multiline)
  1042. } else if oldConfig.Limits.Multiline != config.Limits.Multiline {
  1043. removedCaps.Add(caps.Multiline)
  1044. addedCaps.Add(caps.Multiline)
  1045. }
  1046. if oldConfig.Server.STS.Enabled != config.Server.STS.Enabled || oldConfig.Server.capValues[caps.STS] != config.Server.capValues[caps.STS] {
  1047. // XXX: STS is always removed by CAP NEW sts=duration=0, not CAP DEL
  1048. // so the appropriate notify is always a CAP NEW; put it in addedCaps for any change
  1049. addedCaps.Add(caps.STS)
  1050. }
  1051. return
  1052. }