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

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