選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

config.go 17KB

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