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

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