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

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