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

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