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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660
  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. "encoding/json"
  9. "errors"
  10. "fmt"
  11. "io/ioutil"
  12. "log"
  13. "path/filepath"
  14. "strings"
  15. "time"
  16. "code.cloudfoundry.org/bytefmt"
  17. "github.com/oragono/oragono/irc/connection_limits"
  18. "github.com/oragono/oragono/irc/custime"
  19. "github.com/oragono/oragono/irc/languages"
  20. "github.com/oragono/oragono/irc/logger"
  21. "github.com/oragono/oragono/irc/passwd"
  22. "github.com/oragono/oragono/irc/utils"
  23. "gopkg.in/yaml.v2"
  24. )
  25. // PassConfig holds the connection password.
  26. type PassConfig struct {
  27. Password string
  28. }
  29. // TLSListenConfig defines configuration options for listening on TLS.
  30. type TLSListenConfig struct {
  31. Cert string
  32. Key string
  33. }
  34. // Config returns the TLS contiguration assicated with this TLSListenConfig.
  35. func (conf *TLSListenConfig) Config() (*tls.Config, error) {
  36. cert, err := tls.LoadX509KeyPair(conf.Cert, conf.Key)
  37. if err != nil {
  38. return nil, ErrInvalidCertKeyPair
  39. }
  40. return &tls.Config{
  41. Certificates: []tls.Certificate{cert},
  42. }, err
  43. }
  44. // PasswordBytes returns the bytes represented by the password hash.
  45. func (conf *PassConfig) PasswordBytes() []byte {
  46. bytes, err := passwd.DecodePasswordHash(conf.Password)
  47. if err != nil {
  48. log.Fatal("decode password error: ", err)
  49. }
  50. return bytes
  51. }
  52. type AccountConfig struct {
  53. Registration AccountRegistrationConfig
  54. AuthenticationEnabled bool `yaml:"authentication-enabled"`
  55. SkipServerPassword bool `yaml:"skip-server-password"`
  56. NickReservation NickReservationConfig `yaml:"nick-reservation"`
  57. }
  58. // AccountRegistrationConfig controls account registration.
  59. type AccountRegistrationConfig struct {
  60. Enabled bool
  61. EnabledCallbacks []string `yaml:"enabled-callbacks"`
  62. EnabledCredentialTypes []string `yaml:"-"`
  63. VerifyTimeout time.Duration `yaml:"verify-timeout"`
  64. Callbacks struct {
  65. Mailto struct {
  66. Server string
  67. Port int
  68. TLS struct {
  69. Enabled bool
  70. InsecureSkipVerify bool `yaml:"insecure_skip_verify"`
  71. ServerName string `yaml:"servername"`
  72. }
  73. Username string
  74. Password string
  75. Sender string
  76. VerifyMessageSubject string `yaml:"verify-message-subject"`
  77. VerifyMessage string `yaml:"verify-message"`
  78. }
  79. }
  80. AllowMultiplePerConnection bool `yaml:"allow-multiple-per-connection"`
  81. }
  82. type NickReservationMethod int
  83. const (
  84. NickReservationWithTimeout NickReservationMethod = iota
  85. NickReservationStrict
  86. )
  87. func (nr *NickReservationMethod) UnmarshalYAML(unmarshal func(interface{}) error) error {
  88. var orig, raw string
  89. var err error
  90. if err = unmarshal(&orig); err != nil {
  91. return err
  92. }
  93. if raw, err = Casefold(orig); err != nil {
  94. return err
  95. }
  96. if raw == "timeout" {
  97. *nr = NickReservationWithTimeout
  98. } else if raw == "strict" {
  99. *nr = NickReservationStrict
  100. } else {
  101. return errors.New(fmt.Sprintf("invalid nick-reservation.method value: %s", orig))
  102. }
  103. return nil
  104. }
  105. type NickReservationConfig struct {
  106. Enabled bool
  107. AdditionalNickLimit int `yaml:"additional-nick-limit"`
  108. Method NickReservationMethod
  109. RenameTimeout time.Duration `yaml:"rename-timeout"`
  110. RenamePrefix string `yaml:"rename-prefix"`
  111. }
  112. // ChannelRegistrationConfig controls channel registration.
  113. type ChannelRegistrationConfig struct {
  114. Enabled bool
  115. }
  116. // OperClassConfig defines a specific operator class.
  117. type OperClassConfig struct {
  118. Title string
  119. WhoisLine string
  120. Extends string
  121. Capabilities []string
  122. }
  123. // OperConfig defines a specific operator's configuration.
  124. type OperConfig struct {
  125. Class string
  126. Vhost string
  127. WhoisLine string `yaml:"whois-line"`
  128. Password string
  129. Modes string
  130. }
  131. // PasswordBytes returns the bytes represented by the password hash.
  132. func (conf *OperConfig) PasswordBytes() []byte {
  133. bytes, err := passwd.DecodePasswordHash(conf.Password)
  134. if err != nil {
  135. log.Fatal("decode password error: ", err)
  136. }
  137. return bytes
  138. }
  139. // LineLenConfig controls line lengths.
  140. type LineLenConfig struct {
  141. Tags int
  142. Rest int
  143. }
  144. // STSConfig controls the STS configuration/
  145. type STSConfig struct {
  146. Enabled bool
  147. Duration time.Duration `yaml:"duration-real"`
  148. DurationString string `yaml:"duration"`
  149. Port int
  150. Preload bool
  151. }
  152. // Value returns the STS value to advertise in CAP
  153. func (sts *STSConfig) Value() string {
  154. val := fmt.Sprintf("duration=%d", int(sts.Duration.Seconds()))
  155. if sts.Enabled && sts.Port > 0 {
  156. val += fmt.Sprintf(",port=%d", sts.Port)
  157. }
  158. if sts.Enabled && sts.Preload {
  159. val += ",preload"
  160. }
  161. return val
  162. }
  163. // StackImpactConfig is the config used for StackImpact's profiling.
  164. type StackImpactConfig struct {
  165. Enabled bool
  166. AgentKey string `yaml:"agent-key"`
  167. AppName string `yaml:"app-name"`
  168. }
  169. type FakelagConfig struct {
  170. Enabled bool
  171. Window time.Duration
  172. BurstLimit uint `yaml:"burst-limit"`
  173. MessagesPerWindow uint `yaml:"messages-per-window"`
  174. Cooldown time.Duration
  175. }
  176. // Config defines the overall configuration.
  177. type Config struct {
  178. Network struct {
  179. Name string
  180. }
  181. Server struct {
  182. PassConfig
  183. Password string
  184. Name string
  185. Listen []string
  186. TLSListeners map[string]*TLSListenConfig `yaml:"tls-listeners"`
  187. STS STSConfig
  188. CheckIdent bool `yaml:"check-ident"`
  189. MOTD string
  190. MOTDFormatting bool `yaml:"motd-formatting"`
  191. ProxyAllowedFrom []string `yaml:"proxy-allowed-from"`
  192. WebIRC []webircConfig `yaml:"webirc"`
  193. MaxSendQString string `yaml:"max-sendq"`
  194. MaxSendQBytes int
  195. ConnectionLimiter connection_limits.LimiterConfig `yaml:"connection-limits"`
  196. ConnectionThrottler connection_limits.ThrottlerConfig `yaml:"connection-throttling"`
  197. }
  198. Languages struct {
  199. Enabled bool
  200. Path string
  201. Default string
  202. Data map[string]languages.LangData
  203. }
  204. Datastore struct {
  205. Path string
  206. AutoUpgrade bool
  207. }
  208. Accounts AccountConfig
  209. Channels struct {
  210. DefaultModes *string `yaml:"default-modes"`
  211. Registration ChannelRegistrationConfig
  212. }
  213. OperClasses map[string]*OperClassConfig `yaml:"oper-classes"`
  214. Opers map[string]*OperConfig
  215. Logging []logger.LoggingConfig
  216. Debug struct {
  217. RecoverFromErrors *bool `yaml:"recover-from-errors"`
  218. PprofListener *string `yaml:"pprof-listener"`
  219. StackImpact StackImpactConfig
  220. }
  221. Limits struct {
  222. AwayLen uint `yaml:"awaylen"`
  223. ChanListModes uint `yaml:"chan-list-modes"`
  224. ChannelLen uint `yaml:"channellen"`
  225. KickLen uint `yaml:"kicklen"`
  226. MonitorEntries uint `yaml:"monitor-entries"`
  227. NickLen uint `yaml:"nicklen"`
  228. TopicLen uint `yaml:"topiclen"`
  229. WhowasEntries uint `yaml:"whowas-entries"`
  230. LineLen LineLenConfig `yaml:"linelen"`
  231. }
  232. Fakelag FakelagConfig
  233. Filename string
  234. }
  235. // OperClass defines an assembled operator class.
  236. type OperClass struct {
  237. Title string
  238. WhoisLine string `yaml:"whois-line"`
  239. Capabilities map[string]bool // map to make lookups much easier
  240. }
  241. // OperatorClasses returns a map of assembled operator classes from the given config.
  242. func (conf *Config) OperatorClasses() (*map[string]OperClass, error) {
  243. ocs := make(map[string]OperClass)
  244. // loop from no extends to most extended, breaking if we can't add any more
  245. lenOfLastOcs := -1
  246. for {
  247. if lenOfLastOcs == len(ocs) {
  248. return nil, ErrOperClassDependencies
  249. }
  250. lenOfLastOcs = len(ocs)
  251. var anyMissing bool
  252. for name, info := range conf.OperClasses {
  253. _, exists := ocs[name]
  254. _, extendsExists := ocs[info.Extends]
  255. if exists {
  256. // class already exists
  257. continue
  258. } else if len(info.Extends) > 0 && !extendsExists {
  259. // class we extend on doesn't exist
  260. _, exists := conf.OperClasses[info.Extends]
  261. if !exists {
  262. return nil, fmt.Errorf("Operclass [%s] extends [%s], which doesn't exist", name, info.Extends)
  263. }
  264. anyMissing = true
  265. continue
  266. }
  267. // create new operclass
  268. var oc OperClass
  269. oc.Capabilities = make(map[string]bool)
  270. // get inhereted info from other operclasses
  271. if len(info.Extends) > 0 {
  272. einfo, _ := ocs[info.Extends]
  273. for capab := range einfo.Capabilities {
  274. oc.Capabilities[capab] = true
  275. }
  276. }
  277. // add our own info
  278. oc.Title = info.Title
  279. for _, capab := range info.Capabilities {
  280. oc.Capabilities[capab] = true
  281. }
  282. if len(info.WhoisLine) > 0 {
  283. oc.WhoisLine = info.WhoisLine
  284. } else {
  285. oc.WhoisLine = "is a"
  286. if strings.Contains(strings.ToLower(string(oc.Title[0])), "aeiou") {
  287. oc.WhoisLine += "n"
  288. }
  289. oc.WhoisLine += " "
  290. oc.WhoisLine += oc.Title
  291. }
  292. ocs[name] = oc
  293. }
  294. if !anyMissing {
  295. // we've got every operclass!
  296. break
  297. }
  298. }
  299. return &ocs, nil
  300. }
  301. // Oper represents a single assembled operator's config.
  302. type Oper struct {
  303. Class *OperClass
  304. WhoisLine string
  305. Vhost string
  306. Pass []byte
  307. Modes string
  308. }
  309. // Operators returns a map of operator configs from the given OperClass and config.
  310. func (conf *Config) Operators(oc *map[string]OperClass) (map[string]Oper, error) {
  311. operators := make(map[string]Oper)
  312. for name, opConf := range conf.Opers {
  313. var oper Oper
  314. // oper name
  315. name, err := CasefoldName(name)
  316. if err != nil {
  317. return nil, fmt.Errorf("Could not casefold oper name: %s", err.Error())
  318. }
  319. oper.Pass = opConf.PasswordBytes()
  320. oper.Vhost = opConf.Vhost
  321. class, exists := (*oc)[opConf.Class]
  322. if !exists {
  323. return nil, fmt.Errorf("Could not load operator [%s] - they use operclass [%s] which does not exist", name, opConf.Class)
  324. }
  325. oper.Class = &class
  326. if len(opConf.WhoisLine) > 0 {
  327. oper.WhoisLine = opConf.WhoisLine
  328. } else {
  329. oper.WhoisLine = class.WhoisLine
  330. }
  331. oper.Modes = strings.TrimSpace(opConf.Modes)
  332. // successful, attach to list of opers
  333. operators[name] = oper
  334. }
  335. return operators, nil
  336. }
  337. // TLSListeners returns a list of TLS listeners and their configs.
  338. func (conf *Config) TLSListeners() map[string]*tls.Config {
  339. tlsListeners := make(map[string]*tls.Config)
  340. for s, tlsListenersConf := range conf.Server.TLSListeners {
  341. config, err := tlsListenersConf.Config()
  342. if err != nil {
  343. log.Fatal(err)
  344. }
  345. config.ClientAuth = tls.RequestClientCert
  346. tlsListeners[s] = config
  347. }
  348. return tlsListeners
  349. }
  350. // LoadConfig loads the given YAML configuration file.
  351. func LoadConfig(filename string) (config *Config, err error) {
  352. data, err := ioutil.ReadFile(filename)
  353. if err != nil {
  354. return nil, err
  355. }
  356. err = yaml.Unmarshal(data, &config)
  357. if err != nil {
  358. return nil, err
  359. }
  360. config.Filename = filename
  361. // we need this so PasswordBytes returns the correct info
  362. if config.Server.Password != "" {
  363. config.Server.PassConfig.Password = config.Server.Password
  364. }
  365. if config.Network.Name == "" {
  366. return nil, ErrNetworkNameMissing
  367. }
  368. if config.Server.Name == "" {
  369. return nil, ErrServerNameMissing
  370. }
  371. if !utils.IsHostname(config.Server.Name) {
  372. return nil, ErrServerNameNotHostname
  373. }
  374. if config.Datastore.Path == "" {
  375. return nil, ErrDatastorePathMissing
  376. }
  377. if len(config.Server.Listen) == 0 {
  378. return nil, ErrNoListenersDefined
  379. }
  380. if config.Limits.NickLen < 1 || config.Limits.ChannelLen < 2 || config.Limits.AwayLen < 1 || config.Limits.KickLen < 1 || config.Limits.TopicLen < 1 {
  381. return nil, ErrLimitsAreInsane
  382. }
  383. if config.Server.STS.Enabled {
  384. config.Server.STS.Duration, err = custime.ParseDuration(config.Server.STS.DurationString)
  385. if err != nil {
  386. return nil, fmt.Errorf("Could not parse STS duration: %s", err.Error())
  387. }
  388. if config.Server.STS.Port < 0 || config.Server.STS.Port > 65535 {
  389. return nil, fmt.Errorf("STS port is incorrect, should be 0 if disabled: %d", config.Server.STS.Port)
  390. }
  391. }
  392. if config.Server.ConnectionThrottler.Enabled {
  393. config.Server.ConnectionThrottler.Duration, err = time.ParseDuration(config.Server.ConnectionThrottler.DurationString)
  394. if err != nil {
  395. return nil, fmt.Errorf("Could not parse connection-throttle duration: %s", err.Error())
  396. }
  397. config.Server.ConnectionThrottler.BanDuration, err = time.ParseDuration(config.Server.ConnectionThrottler.BanDurationString)
  398. if err != nil {
  399. return nil, fmt.Errorf("Could not parse connection-throttle ban-duration: %s", err.Error())
  400. }
  401. }
  402. // process webirc blocks
  403. var newWebIRC []webircConfig
  404. for _, webirc := range config.Server.WebIRC {
  405. // skip webirc blocks with no hosts (such as the example one)
  406. if len(webirc.Hosts) == 0 {
  407. continue
  408. }
  409. err = webirc.Populate()
  410. if err != nil {
  411. return nil, fmt.Errorf("Could not parse WebIRC config: %s", err.Error())
  412. }
  413. newWebIRC = append(newWebIRC, webirc)
  414. }
  415. config.Server.WebIRC = newWebIRC
  416. // process limits
  417. if config.Limits.LineLen.Tags < 512 || config.Limits.LineLen.Rest < 512 {
  418. return nil, ErrLineLengthsTooSmall
  419. }
  420. var newLogConfigs []logger.LoggingConfig
  421. for _, logConfig := range config.Logging {
  422. // methods
  423. methods := make(map[string]bool)
  424. for _, method := range strings.Split(logConfig.Method, " ") {
  425. if len(method) > 0 {
  426. methods[strings.ToLower(method)] = true
  427. }
  428. }
  429. if methods["file"] && logConfig.Filename == "" {
  430. return nil, ErrLoggerFilenameMissing
  431. }
  432. logConfig.MethodFile = methods["file"]
  433. logConfig.MethodStdout = methods["stdout"]
  434. logConfig.MethodStderr = methods["stderr"]
  435. // levels
  436. level, exists := logger.LogLevelNames[strings.ToLower(logConfig.LevelString)]
  437. if !exists {
  438. return nil, fmt.Errorf("Could not translate log leve [%s]", logConfig.LevelString)
  439. }
  440. logConfig.Level = level
  441. // types
  442. for _, typeStr := range strings.Split(logConfig.TypeString, " ") {
  443. if len(typeStr) == 0 {
  444. continue
  445. }
  446. if typeStr == "-" {
  447. return nil, ErrLoggerExcludeEmpty
  448. }
  449. if typeStr[0] == '-' {
  450. typeStr = typeStr[1:]
  451. logConfig.ExcludedTypes = append(logConfig.ExcludedTypes, typeStr)
  452. } else {
  453. logConfig.Types = append(logConfig.Types, typeStr)
  454. }
  455. }
  456. if len(logConfig.Types) < 1 {
  457. return nil, ErrLoggerHasNoTypes
  458. }
  459. newLogConfigs = append(newLogConfigs, logConfig)
  460. }
  461. config.Logging = newLogConfigs
  462. // hardcode this for now
  463. config.Accounts.Registration.EnabledCredentialTypes = []string{"passphrase", "certfp"}
  464. for i, name := range config.Accounts.Registration.EnabledCallbacks {
  465. if name == "none" {
  466. // we store "none" as "*" internally
  467. config.Accounts.Registration.EnabledCallbacks[i] = "*"
  468. }
  469. }
  470. maxSendQBytes, err := bytefmt.ToBytes(config.Server.MaxSendQString)
  471. if err != nil {
  472. return nil, fmt.Errorf("Could not parse maximum SendQ size (make sure it only contains whole numbers): %s", err.Error())
  473. }
  474. config.Server.MaxSendQBytes = int(maxSendQBytes)
  475. // get language files
  476. config.Languages.Data = make(map[string]languages.LangData)
  477. if config.Languages.Enabled {
  478. files, err := ioutil.ReadDir(config.Languages.Path)
  479. if err != nil {
  480. return nil, fmt.Errorf("Could not load language files: %s", err.Error())
  481. }
  482. for _, f := range files {
  483. // skip dirs
  484. if f.IsDir() {
  485. continue
  486. }
  487. // only load core .lang.yaml files, and ignore help/irc files
  488. name := f.Name()
  489. lowerName := strings.ToLower(name)
  490. if !strings.HasSuffix(lowerName, ".lang.yaml") {
  491. continue
  492. }
  493. // don't load our example files in practice
  494. if strings.HasPrefix(lowerName, "example") {
  495. continue
  496. }
  497. // load core info file
  498. data, err = ioutil.ReadFile(filepath.Join(config.Languages.Path, name))
  499. if err != nil {
  500. return nil, fmt.Errorf("Could not load language file [%s]: %s", name, err.Error())
  501. }
  502. var langInfo languages.LangData
  503. err = yaml.Unmarshal(data, &langInfo)
  504. if err != nil {
  505. return nil, fmt.Errorf("Could not parse language file [%s]: %s", name, err.Error())
  506. }
  507. langInfo.Translations = make(map[string]string)
  508. // load actual translation files
  509. var tlList map[string]string
  510. // load irc strings file
  511. ircName := strings.TrimSuffix(name, ".lang.yaml") + "-irc.lang.json"
  512. data, err = ioutil.ReadFile(filepath.Join(config.Languages.Path, ircName))
  513. if err != nil {
  514. return nil, fmt.Errorf("Could not load language's irc file [%s]: %s", ircName, err.Error())
  515. }
  516. err = json.Unmarshal(data, &tlList)
  517. if err != nil {
  518. return nil, fmt.Errorf("Could not parse language's irc file [%s]: %s", ircName, err.Error())
  519. }
  520. for key, value := range tlList {
  521. // because of how crowdin works, this is how we skip untranslated lines
  522. if key == value || value == "" {
  523. continue
  524. }
  525. langInfo.Translations[key] = value
  526. }
  527. // load help strings file
  528. helpName := strings.TrimSuffix(name, ".lang.yaml") + "-help.lang.json"
  529. data, err = ioutil.ReadFile(filepath.Join(config.Languages.Path, helpName))
  530. if err != nil {
  531. return nil, fmt.Errorf("Could not load language's help file [%s]: %s", helpName, err.Error())
  532. }
  533. err = json.Unmarshal(data, &tlList)
  534. if err != nil {
  535. return nil, fmt.Errorf("Could not parse language's help file [%s]: %s", helpName, err.Error())
  536. }
  537. for key, value := range tlList {
  538. // because of how crowdin works, this is how we skip untranslated lines
  539. if key == value || value == "" {
  540. continue
  541. }
  542. langInfo.Translations[key] = value
  543. }
  544. // confirm that values are correct
  545. if langInfo.Code == "en" {
  546. return nil, fmt.Errorf("Cannot have language file with code 'en' (this is the default language using strings inside the server code). If you're making an English variant, name it with a more specific code")
  547. }
  548. if langInfo.Code == "" || langInfo.Name == "" || langInfo.Contributors == "" {
  549. return nil, fmt.Errorf("Code, name or contributors is empty in language file [%s]", name)
  550. }
  551. if len(langInfo.Translations) == 0 {
  552. return nil, fmt.Errorf("Language [%s / %s] contains no translations", langInfo.Code, langInfo.Name)
  553. }
  554. // check for duplicate languages
  555. _, exists := config.Languages.Data[strings.ToLower(langInfo.Code)]
  556. if exists {
  557. return nil, fmt.Errorf("Language code [%s] defined twice", langInfo.Code)
  558. }
  559. // and insert into lang info
  560. config.Languages.Data[strings.ToLower(langInfo.Code)] = langInfo
  561. }
  562. // confirm that default language exists
  563. if config.Languages.Default == "" {
  564. config.Languages.Default = "en"
  565. } else {
  566. config.Languages.Default = strings.ToLower(config.Languages.Default)
  567. }
  568. _, exists := config.Languages.Data[config.Languages.Default]
  569. if config.Languages.Default != "en" && !exists {
  570. return nil, fmt.Errorf("Cannot find default language [%s]", config.Languages.Default)
  571. }
  572. }
  573. return config, nil
  574. }