Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

config.go 17KB

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