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

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