Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

config.go 23KB

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