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.

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