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

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