Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

config.go 18KB

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