Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

config.go 21KB

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