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

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