Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

config.go 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732
  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. AutoreplayOnJoin int `yaml:"autoreplay-on-join"`
  239. }
  240. Filename string
  241. }
  242. // OperClass defines an assembled operator class.
  243. type OperClass struct {
  244. Title string
  245. WhoisLine string `yaml:"whois-line"`
  246. Capabilities map[string]bool // map to make lookups much easier
  247. }
  248. // OperatorClasses returns a map of assembled operator classes from the given config.
  249. func (conf *Config) OperatorClasses() (map[string]*OperClass, error) {
  250. ocs := make(map[string]*OperClass)
  251. // loop from no extends to most extended, breaking if we can't add any more
  252. lenOfLastOcs := -1
  253. for {
  254. if lenOfLastOcs == len(ocs) {
  255. return nil, ErrOperClassDependencies
  256. }
  257. lenOfLastOcs = len(ocs)
  258. var anyMissing bool
  259. for name, info := range conf.OperClasses {
  260. _, exists := ocs[name]
  261. _, extendsExists := ocs[info.Extends]
  262. if exists {
  263. // class already exists
  264. continue
  265. } else if len(info.Extends) > 0 && !extendsExists {
  266. // class we extend on doesn't exist
  267. _, exists := conf.OperClasses[info.Extends]
  268. if !exists {
  269. return nil, fmt.Errorf("Operclass [%s] extends [%s], which doesn't exist", name, info.Extends)
  270. }
  271. anyMissing = true
  272. continue
  273. }
  274. // create new operclass
  275. var oc OperClass
  276. oc.Capabilities = make(map[string]bool)
  277. // get inhereted info from other operclasses
  278. if len(info.Extends) > 0 {
  279. einfo, _ := ocs[info.Extends]
  280. for capab := range einfo.Capabilities {
  281. oc.Capabilities[capab] = true
  282. }
  283. }
  284. // add our own info
  285. oc.Title = info.Title
  286. for _, capab := range info.Capabilities {
  287. oc.Capabilities[capab] = true
  288. }
  289. if len(info.WhoisLine) > 0 {
  290. oc.WhoisLine = info.WhoisLine
  291. } else {
  292. oc.WhoisLine = "is a"
  293. if strings.Contains(strings.ToLower(string(oc.Title[0])), "aeiou") {
  294. oc.WhoisLine += "n"
  295. }
  296. oc.WhoisLine += " "
  297. oc.WhoisLine += oc.Title
  298. }
  299. ocs[name] = &oc
  300. }
  301. if !anyMissing {
  302. // we've got every operclass!
  303. break
  304. }
  305. }
  306. return ocs, nil
  307. }
  308. // Oper represents a single assembled operator's config.
  309. type Oper struct {
  310. Name string
  311. Class *OperClass
  312. WhoisLine string
  313. Vhost string
  314. Pass []byte
  315. Modes []modes.ModeChange
  316. }
  317. // Operators returns a map of operator configs from the given OperClass and config.
  318. func (conf *Config) Operators(oc map[string]*OperClass) (map[string]*Oper, error) {
  319. operators := make(map[string]*Oper)
  320. for name, opConf := range conf.Opers {
  321. var oper Oper
  322. // oper name
  323. name, err := CasefoldName(name)
  324. if err != nil {
  325. return nil, fmt.Errorf("Could not casefold oper name: %s", err.Error())
  326. }
  327. oper.Name = name
  328. oper.Pass, err = decodeLegacyPasswordHash(opConf.Password)
  329. if err != nil {
  330. return nil, err
  331. }
  332. oper.Vhost = opConf.Vhost
  333. class, exists := oc[opConf.Class]
  334. if !exists {
  335. return nil, fmt.Errorf("Could not load operator [%s] - they use operclass [%s] which does not exist", name, opConf.Class)
  336. }
  337. oper.Class = class
  338. if len(opConf.WhoisLine) > 0 {
  339. oper.WhoisLine = opConf.WhoisLine
  340. } else {
  341. oper.WhoisLine = class.WhoisLine
  342. }
  343. modeStr := strings.TrimSpace(opConf.Modes)
  344. modeChanges, unknownChanges := modes.ParseUserModeChanges(strings.Split(modeStr, " ")...)
  345. if len(unknownChanges) > 0 {
  346. return nil, fmt.Errorf("Could not load operator [%s] due to unknown modes %v", name, unknownChanges)
  347. }
  348. oper.Modes = modeChanges
  349. // successful, attach to list of opers
  350. operators[name] = &oper
  351. }
  352. return operators, nil
  353. }
  354. // TLSListeners returns a list of TLS listeners and their configs.
  355. func (conf *Config) TLSListeners() (map[string]*tls.Config, error) {
  356. tlsListeners := make(map[string]*tls.Config)
  357. for s, tlsListenersConf := range conf.Server.TLSListeners {
  358. config, err := tlsListenersConf.Config()
  359. if err != nil {
  360. return nil, err
  361. }
  362. config.ClientAuth = tls.RequestClientCert
  363. tlsListeners[s] = config
  364. }
  365. return tlsListeners, nil
  366. }
  367. // LoadConfig loads the given YAML configuration file.
  368. func LoadConfig(filename string) (config *Config, err error) {
  369. data, err := ioutil.ReadFile(filename)
  370. if err != nil {
  371. return nil, err
  372. }
  373. err = yaml.Unmarshal(data, &config)
  374. if err != nil {
  375. return nil, err
  376. }
  377. config.Filename = filename
  378. if config.Network.Name == "" {
  379. return nil, ErrNetworkNameMissing
  380. }
  381. if config.Server.Name == "" {
  382. return nil, ErrServerNameMissing
  383. }
  384. if !utils.IsHostname(config.Server.Name) {
  385. return nil, ErrServerNameNotHostname
  386. }
  387. if config.Datastore.Path == "" {
  388. return nil, ErrDatastorePathMissing
  389. }
  390. if len(config.Server.Listen) == 0 {
  391. return nil, ErrNoListenersDefined
  392. }
  393. if config.Limits.NickLen < 1 || config.Limits.ChannelLen < 2 || config.Limits.AwayLen < 1 || config.Limits.KickLen < 1 || config.Limits.TopicLen < 1 {
  394. return nil, ErrLimitsAreInsane
  395. }
  396. if config.Server.STS.Enabled {
  397. config.Server.STS.Duration, err = custime.ParseDuration(config.Server.STS.DurationString)
  398. if err != nil {
  399. return nil, fmt.Errorf("Could not parse STS duration: %s", err.Error())
  400. }
  401. if config.Server.STS.Port < 0 || config.Server.STS.Port > 65535 {
  402. return nil, fmt.Errorf("STS port is incorrect, should be 0 if disabled: %d", config.Server.STS.Port)
  403. }
  404. }
  405. if config.Server.ConnectionThrottler.Enabled {
  406. config.Server.ConnectionThrottler.Duration, err = time.ParseDuration(config.Server.ConnectionThrottler.DurationString)
  407. if err != nil {
  408. return nil, fmt.Errorf("Could not parse connection-throttle duration: %s", err.Error())
  409. }
  410. config.Server.ConnectionThrottler.BanDuration, err = time.ParseDuration(config.Server.ConnectionThrottler.BanDurationString)
  411. if err != nil {
  412. return nil, fmt.Errorf("Could not parse connection-throttle ban-duration: %s", err.Error())
  413. }
  414. }
  415. // process webirc blocks
  416. var newWebIRC []webircConfig
  417. for _, webirc := range config.Server.WebIRC {
  418. // skip webirc blocks with no hosts (such as the example one)
  419. if len(webirc.Hosts) == 0 {
  420. continue
  421. }
  422. err = webirc.Populate()
  423. if err != nil {
  424. return nil, fmt.Errorf("Could not parse WebIRC config: %s", err.Error())
  425. }
  426. newWebIRC = append(newWebIRC, webirc)
  427. }
  428. config.Server.WebIRC = newWebIRC
  429. // process limits
  430. if config.Limits.LineLen.Tags < 512 || config.Limits.LineLen.Rest < 512 {
  431. return nil, ErrLineLengthsTooSmall
  432. }
  433. var newLogConfigs []logger.LoggingConfig
  434. for _, logConfig := range config.Logging {
  435. // methods
  436. methods := make(map[string]bool)
  437. for _, method := range strings.Split(logConfig.Method, " ") {
  438. if len(method) > 0 {
  439. methods[strings.ToLower(method)] = true
  440. }
  441. }
  442. if methods["file"] && logConfig.Filename == "" {
  443. return nil, ErrLoggerFilenameMissing
  444. }
  445. logConfig.MethodFile = methods["file"]
  446. logConfig.MethodStdout = methods["stdout"]
  447. logConfig.MethodStderr = methods["stderr"]
  448. // levels
  449. level, exists := logger.LogLevelNames[strings.ToLower(logConfig.LevelString)]
  450. if !exists {
  451. return nil, fmt.Errorf("Could not translate log leve [%s]", logConfig.LevelString)
  452. }
  453. logConfig.Level = level
  454. // types
  455. for _, typeStr := range strings.Split(logConfig.TypeString, " ") {
  456. if len(typeStr) == 0 {
  457. continue
  458. }
  459. if typeStr == "-" {
  460. return nil, ErrLoggerExcludeEmpty
  461. }
  462. if typeStr[0] == '-' {
  463. typeStr = typeStr[1:]
  464. logConfig.ExcludedTypes = append(logConfig.ExcludedTypes, typeStr)
  465. } else {
  466. logConfig.Types = append(logConfig.Types, typeStr)
  467. }
  468. }
  469. if len(logConfig.Types) < 1 {
  470. return nil, ErrLoggerHasNoTypes
  471. }
  472. newLogConfigs = append(newLogConfigs, logConfig)
  473. }
  474. config.Logging = newLogConfigs
  475. // hardcode this for now
  476. config.Accounts.Registration.EnabledCredentialTypes = []string{"passphrase", "certfp"}
  477. for i, name := range config.Accounts.Registration.EnabledCallbacks {
  478. if name == "none" {
  479. // we store "none" as "*" internally
  480. config.Accounts.Registration.EnabledCallbacks[i] = "*"
  481. }
  482. }
  483. rawRegexp := config.Accounts.VHosts.ValidRegexpRaw
  484. if rawRegexp != "" {
  485. regexp, err := regexp.Compile(rawRegexp)
  486. if err == nil {
  487. config.Accounts.VHosts.ValidRegexp = regexp
  488. } else {
  489. log.Printf("invalid vhost regexp: %s\n", err.Error())
  490. }
  491. }
  492. if config.Accounts.VHosts.ValidRegexp == nil {
  493. config.Accounts.VHosts.ValidRegexp = defaultValidVhostRegex
  494. }
  495. maxSendQBytes, err := bytefmt.ToBytes(config.Server.MaxSendQString)
  496. if err != nil {
  497. return nil, fmt.Errorf("Could not parse maximum SendQ size (make sure it only contains whole numbers): %s", err.Error())
  498. }
  499. config.Server.MaxSendQBytes = int(maxSendQBytes)
  500. // get language files
  501. config.Languages.Data = make(map[string]languages.LangData)
  502. if config.Languages.Enabled {
  503. files, err := ioutil.ReadDir(config.Languages.Path)
  504. if err != nil {
  505. return nil, fmt.Errorf("Could not load language files: %s", err.Error())
  506. }
  507. for _, f := range files {
  508. // skip dirs
  509. if f.IsDir() {
  510. continue
  511. }
  512. // only load core .lang.yaml files, and ignore help/irc files
  513. name := f.Name()
  514. lowerName := strings.ToLower(name)
  515. if !strings.HasSuffix(lowerName, ".lang.yaml") {
  516. continue
  517. }
  518. // don't load our example files in practice
  519. if strings.HasPrefix(lowerName, "example") {
  520. continue
  521. }
  522. // load core info file
  523. data, err = ioutil.ReadFile(filepath.Join(config.Languages.Path, name))
  524. if err != nil {
  525. return nil, fmt.Errorf("Could not load language file [%s]: %s", name, err.Error())
  526. }
  527. var langInfo languages.LangData
  528. err = yaml.Unmarshal(data, &langInfo)
  529. if err != nil {
  530. return nil, fmt.Errorf("Could not parse language file [%s]: %s", name, err.Error())
  531. }
  532. langInfo.Translations = make(map[string]string)
  533. // load actual translation files
  534. var tlList map[string]string
  535. // load irc strings file
  536. ircName := strings.TrimSuffix(name, ".lang.yaml") + "-irc.lang.json"
  537. data, err = ioutil.ReadFile(filepath.Join(config.Languages.Path, ircName))
  538. if err != nil {
  539. return nil, fmt.Errorf("Could not load language's irc file [%s]: %s", ircName, err.Error())
  540. }
  541. err = json.Unmarshal(data, &tlList)
  542. if err != nil {
  543. return nil, fmt.Errorf("Could not parse language's irc file [%s]: %s", ircName, err.Error())
  544. }
  545. for key, value := range tlList {
  546. // because of how crowdin works, this is how we skip untranslated lines
  547. if key == value || value == "" {
  548. continue
  549. }
  550. langInfo.Translations[key] = value
  551. }
  552. // load help strings file
  553. helpName := strings.TrimSuffix(name, ".lang.yaml") + "-help.lang.json"
  554. data, err = ioutil.ReadFile(filepath.Join(config.Languages.Path, helpName))
  555. if err != nil {
  556. return nil, fmt.Errorf("Could not load language's help file [%s]: %s", helpName, err.Error())
  557. }
  558. err = json.Unmarshal(data, &tlList)
  559. if err != nil {
  560. return nil, fmt.Errorf("Could not parse language's help file [%s]: %s", helpName, err.Error())
  561. }
  562. for key, value := range tlList {
  563. // because of how crowdin works, this is how we skip untranslated lines
  564. if key == value || value == "" {
  565. continue
  566. }
  567. langInfo.Translations[key] = value
  568. }
  569. // confirm that values are correct
  570. if langInfo.Code == "en" {
  571. 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")
  572. }
  573. if langInfo.Code == "" || langInfo.Name == "" || langInfo.Contributors == "" {
  574. return nil, fmt.Errorf("Code, name or contributors is empty in language file [%s]", name)
  575. }
  576. if len(langInfo.Translations) == 0 {
  577. return nil, fmt.Errorf("Language [%s / %s] contains no translations", langInfo.Code, langInfo.Name)
  578. }
  579. // check for duplicate languages
  580. _, exists := config.Languages.Data[strings.ToLower(langInfo.Code)]
  581. if exists {
  582. return nil, fmt.Errorf("Language code [%s] defined twice", langInfo.Code)
  583. }
  584. // and insert into lang info
  585. config.Languages.Data[strings.ToLower(langInfo.Code)] = langInfo
  586. }
  587. // confirm that default language exists
  588. if config.Languages.Default == "" {
  589. config.Languages.Default = "en"
  590. } else {
  591. config.Languages.Default = strings.ToLower(config.Languages.Default)
  592. }
  593. _, exists := config.Languages.Data[config.Languages.Default]
  594. if config.Languages.Default != "en" && !exists {
  595. return nil, fmt.Errorf("Cannot find default language [%s]", config.Languages.Default)
  596. }
  597. }
  598. // RecoverFromErrors defaults to true
  599. if config.Debug.RecoverFromErrors == nil {
  600. config.Debug.RecoverFromErrors = new(bool)
  601. *config.Debug.RecoverFromErrors = true
  602. }
  603. // casefold/validate server name
  604. config.Server.nameCasefolded, err = Casefold(config.Server.Name)
  605. if err != nil {
  606. return nil, fmt.Errorf("Server name isn't valid [%s]: %s", config.Server.Name, err.Error())
  607. }
  608. // process operator definitions, store them to config.operators
  609. operclasses, err := config.OperatorClasses()
  610. if err != nil {
  611. return nil, err
  612. }
  613. opers, err := config.Operators(operclasses)
  614. if err != nil {
  615. return nil, err
  616. }
  617. config.operators = opers
  618. // parse default channel modes
  619. config.Channels.defaultModes = ParseDefaultChannelModes(config.Channels.DefaultModes)
  620. if config.Server.Password != "" {
  621. config.Server.passwordBytes, err = decodeLegacyPasswordHash(config.Server.Password)
  622. if err != nil {
  623. return nil, err
  624. }
  625. }
  626. if config.Accounts.Registration.BcryptCost == 0 {
  627. config.Accounts.Registration.BcryptCost = passwd.DefaultCost
  628. }
  629. // in the current implementation, we disable history by creating a history buffer
  630. // with zero capacity. but the `enabled` config option MUST be respected regardless
  631. // of this detail
  632. if !config.History.Enabled {
  633. config.History.ChannelLength = 0
  634. config.History.ClientLength = 0
  635. }
  636. return config, nil
  637. }