Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659
  1. // Copyright (c) 2012-2014 Jeremy Latt
  2. // Copyright (c) 2014-2015 Edmund Huber
  3. // Copyright (c) 2016-2017 Daniel Oaks <daniel@danieloaks.net>
  4. // released under the MIT license
  5. package irc
  6. import (
  7. "crypto/tls"
  8. "encoding/json"
  9. "errors"
  10. "fmt"
  11. "io/ioutil"
  12. "log"
  13. "path/filepath"
  14. "strings"
  15. "time"
  16. "code.cloudfoundry.org/bytefmt"
  17. "github.com/oragono/oragono/irc/connection_limits"
  18. "github.com/oragono/oragono/irc/custime"
  19. "github.com/oragono/oragono/irc/languages"
  20. "github.com/oragono/oragono/irc/logger"
  21. "github.com/oragono/oragono/irc/passwd"
  22. "github.com/oragono/oragono/irc/utils"
  23. "gopkg.in/yaml.v2"
  24. )
  25. // PassConfig holds the connection password.
  26. type PassConfig struct {
  27. Password string
  28. }
  29. // TLSListenConfig defines configuration options for listening on TLS.
  30. type TLSListenConfig struct {
  31. Cert string
  32. Key string
  33. }
  34. // Config returns the TLS contiguration assicated with this TLSListenConfig.
  35. func (conf *TLSListenConfig) Config() (*tls.Config, error) {
  36. cert, err := tls.LoadX509KeyPair(conf.Cert, conf.Key)
  37. if err != nil {
  38. return nil, ErrInvalidCertKeyPair
  39. }
  40. return &tls.Config{
  41. Certificates: []tls.Certificate{cert},
  42. }, err
  43. }
  44. // PasswordBytes returns the bytes represented by the password hash.
  45. func (conf *PassConfig) PasswordBytes() []byte {
  46. bytes, err := passwd.DecodePasswordHash(conf.Password)
  47. if err != nil {
  48. log.Fatal("decode password error: ", err)
  49. }
  50. return bytes
  51. }
  52. type AccountConfig struct {
  53. Registration AccountRegistrationConfig
  54. AuthenticationEnabled bool `yaml:"authentication-enabled"`
  55. SkipServerPassword bool `yaml:"skip-server-password"`
  56. NickReservation NickReservationConfig `yaml:"nick-reservation"`
  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. AllowMultiplePerConnection bool `yaml:"allow-multiple-per-connection"`
  81. }
  82. type NickReservationMethod int
  83. const (
  84. NickReservationWithTimeout NickReservationMethod = iota
  85. NickReservationStrict
  86. )
  87. func (nr *NickReservationMethod) UnmarshalYAML(unmarshal func(interface{}) error) error {
  88. var orig, raw string
  89. var err error
  90. if err = unmarshal(&orig); err != nil {
  91. return err
  92. }
  93. if raw, err = Casefold(orig); err != nil {
  94. return err
  95. }
  96. if raw == "timeout" {
  97. *nr = NickReservationWithTimeout
  98. } else if raw == "strict" {
  99. *nr = NickReservationStrict
  100. } else {
  101. return errors.New(fmt.Sprintf("invalid nick-reservation.method value: %s", orig))
  102. }
  103. return nil
  104. }
  105. type NickReservationConfig struct {
  106. Enabled bool
  107. AdditionalNickLimit int `yaml:"additional-nick-limit"`
  108. Method NickReservationMethod
  109. RenameTimeout time.Duration `yaml:"rename-timeout"`
  110. RenamePrefix string `yaml:"rename-prefix"`
  111. }
  112. // ChannelRegistrationConfig controls channel registration.
  113. type ChannelRegistrationConfig struct {
  114. Enabled bool
  115. }
  116. // OperClassConfig defines a specific operator class.
  117. type OperClassConfig struct {
  118. Title string
  119. WhoisLine string
  120. Extends string
  121. Capabilities []string
  122. }
  123. // OperConfig defines a specific operator's configuration.
  124. type OperConfig struct {
  125. Class string
  126. Vhost string
  127. WhoisLine string `yaml:"whois-line"`
  128. Password string
  129. Modes string
  130. }
  131. // PasswordBytes returns the bytes represented by the password hash.
  132. func (conf *OperConfig) PasswordBytes() []byte {
  133. bytes, err := passwd.DecodePasswordHash(conf.Password)
  134. if err != nil {
  135. log.Fatal("decode password error: ", err)
  136. }
  137. return bytes
  138. }
  139. // LineLenConfig controls line lengths.
  140. type LineLenConfig struct {
  141. Tags int
  142. Rest int
  143. }
  144. // STSConfig controls the STS configuration/
  145. type STSConfig struct {
  146. Enabled bool
  147. Duration time.Duration `yaml:"duration-real"`
  148. DurationString string `yaml:"duration"`
  149. Port int
  150. Preload bool
  151. }
  152. // Value returns the STS value to advertise in CAP
  153. func (sts *STSConfig) Value() string {
  154. val := fmt.Sprintf("duration=%d", int(sts.Duration.Seconds()))
  155. if sts.Enabled && sts.Port > 0 {
  156. val += fmt.Sprintf(",port=%d", sts.Port)
  157. }
  158. if sts.Enabled && sts.Preload {
  159. val += ",preload"
  160. }
  161. return val
  162. }
  163. // StackImpactConfig is the config used for StackImpact's profiling.
  164. type StackImpactConfig struct {
  165. Enabled bool
  166. AgentKey string `yaml:"agent-key"`
  167. AppName string `yaml:"app-name"`
  168. }
  169. type FakelagConfig struct {
  170. Enabled bool
  171. Window time.Duration
  172. BurstLimit uint `yaml:"burst-limit"`
  173. MessagesPerWindow uint `yaml:"messages-per-window"`
  174. Cooldown time.Duration
  175. }
  176. // Config defines the overall configuration.
  177. type Config struct {
  178. Network struct {
  179. Name string
  180. }
  181. Server struct {
  182. PassConfig
  183. Password string
  184. Name string
  185. Listen []string
  186. TLSListeners map[string]*TLSListenConfig `yaml:"tls-listeners"`
  187. STS STSConfig
  188. CheckIdent bool `yaml:"check-ident"`
  189. MOTD string
  190. MOTDFormatting bool `yaml:"motd-formatting"`
  191. ProxyAllowedFrom []string `yaml:"proxy-allowed-from"`
  192. WebIRC []webircConfig `yaml:"webirc"`
  193. MaxSendQString string `yaml:"max-sendq"`
  194. MaxSendQBytes int
  195. ConnectionLimiter connection_limits.LimiterConfig `yaml:"connection-limits"`
  196. ConnectionThrottler connection_limits.ThrottlerConfig `yaml:"connection-throttling"`
  197. }
  198. Languages struct {
  199. Enabled bool
  200. Path string
  201. Default string
  202. Data map[string]languages.LangData
  203. }
  204. Datastore struct {
  205. Path string
  206. }
  207. Accounts AccountConfig
  208. Channels struct {
  209. DefaultModes *string `yaml:"default-modes"`
  210. Registration ChannelRegistrationConfig
  211. }
  212. OperClasses map[string]*OperClassConfig `yaml:"oper-classes"`
  213. Opers map[string]*OperConfig
  214. Logging []logger.LoggingConfig
  215. Debug struct {
  216. RecoverFromErrors *bool `yaml:"recover-from-errors"`
  217. PprofListener *string `yaml:"pprof-listener"`
  218. StackImpact StackImpactConfig
  219. }
  220. Limits struct {
  221. AwayLen uint `yaml:"awaylen"`
  222. ChanListModes uint `yaml:"chan-list-modes"`
  223. ChannelLen uint `yaml:"channellen"`
  224. KickLen uint `yaml:"kicklen"`
  225. MonitorEntries uint `yaml:"monitor-entries"`
  226. NickLen uint `yaml:"nicklen"`
  227. TopicLen uint `yaml:"topiclen"`
  228. WhowasEntries uint `yaml:"whowas-entries"`
  229. LineLen LineLenConfig `yaml:"linelen"`
  230. }
  231. Fakelag FakelagConfig
  232. Filename string
  233. }
  234. // OperClass defines an assembled operator class.
  235. type OperClass struct {
  236. Title string
  237. WhoisLine string `yaml:"whois-line"`
  238. Capabilities map[string]bool // map to make lookups much easier
  239. }
  240. // OperatorClasses returns a map of assembled operator classes from the given config.
  241. func (conf *Config) OperatorClasses() (*map[string]OperClass, error) {
  242. ocs := make(map[string]OperClass)
  243. // loop from no extends to most extended, breaking if we can't add any more
  244. lenOfLastOcs := -1
  245. for {
  246. if lenOfLastOcs == len(ocs) {
  247. return nil, ErrOperClassDependencies
  248. }
  249. lenOfLastOcs = len(ocs)
  250. var anyMissing bool
  251. for name, info := range conf.OperClasses {
  252. _, exists := ocs[name]
  253. _, extendsExists := ocs[info.Extends]
  254. if exists {
  255. // class already exists
  256. continue
  257. } else if len(info.Extends) > 0 && !extendsExists {
  258. // class we extend on doesn't exist
  259. _, exists := conf.OperClasses[info.Extends]
  260. if !exists {
  261. return nil, fmt.Errorf("Operclass [%s] extends [%s], which doesn't exist", name, info.Extends)
  262. }
  263. anyMissing = true
  264. continue
  265. }
  266. // create new operclass
  267. var oc OperClass
  268. oc.Capabilities = make(map[string]bool)
  269. // get inhereted info from other operclasses
  270. if len(info.Extends) > 0 {
  271. einfo, _ := ocs[info.Extends]
  272. for capab := range einfo.Capabilities {
  273. oc.Capabilities[capab] = true
  274. }
  275. }
  276. // add our own info
  277. oc.Title = info.Title
  278. for _, capab := range info.Capabilities {
  279. oc.Capabilities[capab] = true
  280. }
  281. if len(info.WhoisLine) > 0 {
  282. oc.WhoisLine = info.WhoisLine
  283. } else {
  284. oc.WhoisLine = "is a"
  285. if strings.Contains(strings.ToLower(string(oc.Title[0])), "aeiou") {
  286. oc.WhoisLine += "n"
  287. }
  288. oc.WhoisLine += " "
  289. oc.WhoisLine += oc.Title
  290. }
  291. ocs[name] = oc
  292. }
  293. if !anyMissing {
  294. // we've got every operclass!
  295. break
  296. }
  297. }
  298. return &ocs, nil
  299. }
  300. // Oper represents a single assembled operator's config.
  301. type Oper struct {
  302. Class *OperClass
  303. WhoisLine string
  304. Vhost string
  305. Pass []byte
  306. Modes string
  307. }
  308. // Operators returns a map of operator configs from the given OperClass and config.
  309. func (conf *Config) Operators(oc *map[string]OperClass) (map[string]Oper, error) {
  310. operators := make(map[string]Oper)
  311. for name, opConf := range conf.Opers {
  312. var oper Oper
  313. // oper name
  314. name, err := CasefoldName(name)
  315. if err != nil {
  316. return nil, fmt.Errorf("Could not casefold oper name: %s", err.Error())
  317. }
  318. oper.Pass = opConf.PasswordBytes()
  319. oper.Vhost = opConf.Vhost
  320. class, exists := (*oc)[opConf.Class]
  321. if !exists {
  322. return nil, fmt.Errorf("Could not load operator [%s] - they use operclass [%s] which does not exist", name, opConf.Class)
  323. }
  324. oper.Class = &class
  325. if len(opConf.WhoisLine) > 0 {
  326. oper.WhoisLine = opConf.WhoisLine
  327. } else {
  328. oper.WhoisLine = class.WhoisLine
  329. }
  330. oper.Modes = strings.TrimSpace(opConf.Modes)
  331. // successful, attach to list of opers
  332. operators[name] = oper
  333. }
  334. return operators, nil
  335. }
  336. // TLSListeners returns a list of TLS listeners and their configs.
  337. func (conf *Config) TLSListeners() map[string]*tls.Config {
  338. tlsListeners := make(map[string]*tls.Config)
  339. for s, tlsListenersConf := range conf.Server.TLSListeners {
  340. config, err := tlsListenersConf.Config()
  341. if err != nil {
  342. log.Fatal(err)
  343. }
  344. config.ClientAuth = tls.RequestClientCert
  345. tlsListeners[s] = config
  346. }
  347. return tlsListeners
  348. }
  349. // LoadConfig loads the given YAML configuration file.
  350. func LoadConfig(filename string) (config *Config, err error) {
  351. data, err := ioutil.ReadFile(filename)
  352. if err != nil {
  353. return nil, err
  354. }
  355. err = yaml.Unmarshal(data, &config)
  356. if err != nil {
  357. return nil, err
  358. }
  359. config.Filename = filename
  360. // we need this so PasswordBytes returns the correct info
  361. if config.Server.Password != "" {
  362. config.Server.PassConfig.Password = config.Server.Password
  363. }
  364. if config.Network.Name == "" {
  365. return nil, ErrNetworkNameMissing
  366. }
  367. if config.Server.Name == "" {
  368. return nil, ErrServerNameMissing
  369. }
  370. if !utils.IsHostname(config.Server.Name) {
  371. return nil, ErrServerNameNotHostname
  372. }
  373. if config.Datastore.Path == "" {
  374. return nil, ErrDatastorePathMissing
  375. }
  376. if len(config.Server.Listen) == 0 {
  377. return nil, ErrNoListenersDefined
  378. }
  379. if config.Limits.NickLen < 1 || config.Limits.ChannelLen < 2 || config.Limits.AwayLen < 1 || config.Limits.KickLen < 1 || config.Limits.TopicLen < 1 {
  380. return nil, ErrLimitsAreInsane
  381. }
  382. if config.Server.STS.Enabled {
  383. config.Server.STS.Duration, err = custime.ParseDuration(config.Server.STS.DurationString)
  384. if err != nil {
  385. return nil, fmt.Errorf("Could not parse STS duration: %s", err.Error())
  386. }
  387. if config.Server.STS.Port < 0 || config.Server.STS.Port > 65535 {
  388. return nil, fmt.Errorf("STS port is incorrect, should be 0 if disabled: %d", config.Server.STS.Port)
  389. }
  390. }
  391. if config.Server.ConnectionThrottler.Enabled {
  392. config.Server.ConnectionThrottler.Duration, err = time.ParseDuration(config.Server.ConnectionThrottler.DurationString)
  393. if err != nil {
  394. return nil, fmt.Errorf("Could not parse connection-throttle duration: %s", err.Error())
  395. }
  396. config.Server.ConnectionThrottler.BanDuration, err = time.ParseDuration(config.Server.ConnectionThrottler.BanDurationString)
  397. if err != nil {
  398. return nil, fmt.Errorf("Could not parse connection-throttle ban-duration: %s", err.Error())
  399. }
  400. }
  401. // process webirc blocks
  402. var newWebIRC []webircConfig
  403. for _, webirc := range config.Server.WebIRC {
  404. // skip webirc blocks with no hosts (such as the example one)
  405. if len(webirc.Hosts) == 0 {
  406. continue
  407. }
  408. err = webirc.Populate()
  409. if err != nil {
  410. return nil, fmt.Errorf("Could not parse WebIRC config: %s", err.Error())
  411. }
  412. newWebIRC = append(newWebIRC, webirc)
  413. }
  414. config.Server.WebIRC = newWebIRC
  415. // process limits
  416. if config.Limits.LineLen.Tags < 512 || config.Limits.LineLen.Rest < 512 {
  417. return nil, ErrLineLengthsTooSmall
  418. }
  419. var newLogConfigs []logger.LoggingConfig
  420. for _, logConfig := range config.Logging {
  421. // methods
  422. methods := make(map[string]bool)
  423. for _, method := range strings.Split(logConfig.Method, " ") {
  424. if len(method) > 0 {
  425. methods[strings.ToLower(method)] = true
  426. }
  427. }
  428. if methods["file"] && logConfig.Filename == "" {
  429. return nil, ErrLoggerFilenameMissing
  430. }
  431. logConfig.MethodFile = methods["file"]
  432. logConfig.MethodStdout = methods["stdout"]
  433. logConfig.MethodStderr = methods["stderr"]
  434. // levels
  435. level, exists := logger.LogLevelNames[strings.ToLower(logConfig.LevelString)]
  436. if !exists {
  437. return nil, fmt.Errorf("Could not translate log leve [%s]", logConfig.LevelString)
  438. }
  439. logConfig.Level = level
  440. // types
  441. for _, typeStr := range strings.Split(logConfig.TypeString, " ") {
  442. if len(typeStr) == 0 {
  443. continue
  444. }
  445. if typeStr == "-" {
  446. return nil, ErrLoggerExcludeEmpty
  447. }
  448. if typeStr[0] == '-' {
  449. typeStr = typeStr[1:]
  450. logConfig.ExcludedTypes = append(logConfig.ExcludedTypes, typeStr)
  451. } else {
  452. logConfig.Types = append(logConfig.Types, typeStr)
  453. }
  454. }
  455. if len(logConfig.Types) < 1 {
  456. return nil, ErrLoggerHasNoTypes
  457. }
  458. newLogConfigs = append(newLogConfigs, logConfig)
  459. }
  460. config.Logging = newLogConfigs
  461. // hardcode this for now
  462. config.Accounts.Registration.EnabledCredentialTypes = []string{"passphrase", "certfp"}
  463. for i, name := range config.Accounts.Registration.EnabledCallbacks {
  464. if name == "none" {
  465. // we store "none" as "*" internally
  466. config.Accounts.Registration.EnabledCallbacks[i] = "*"
  467. }
  468. }
  469. maxSendQBytes, err := bytefmt.ToBytes(config.Server.MaxSendQString)
  470. if err != nil {
  471. return nil, fmt.Errorf("Could not parse maximum SendQ size (make sure it only contains whole numbers): %s", err.Error())
  472. }
  473. config.Server.MaxSendQBytes = int(maxSendQBytes)
  474. // get language files
  475. config.Languages.Data = make(map[string]languages.LangData)
  476. if config.Languages.Enabled {
  477. files, err := ioutil.ReadDir(config.Languages.Path)
  478. if err != nil {
  479. return nil, fmt.Errorf("Could not load language files: %s", err.Error())
  480. }
  481. for _, f := range files {
  482. // skip dirs
  483. if f.IsDir() {
  484. continue
  485. }
  486. // only load core .lang.yaml files, and ignore help/irc files
  487. name := f.Name()
  488. lowerName := strings.ToLower(name)
  489. if !strings.HasSuffix(lowerName, ".lang.yaml") {
  490. continue
  491. }
  492. // don't load our example files in practice
  493. if strings.HasPrefix(lowerName, "example") {
  494. continue
  495. }
  496. // load core info file
  497. data, err = ioutil.ReadFile(filepath.Join(config.Languages.Path, name))
  498. if err != nil {
  499. return nil, fmt.Errorf("Could not load language file [%s]: %s", name, err.Error())
  500. }
  501. var langInfo languages.LangData
  502. err = yaml.Unmarshal(data, &langInfo)
  503. if err != nil {
  504. return nil, fmt.Errorf("Could not parse language file [%s]: %s", name, err.Error())
  505. }
  506. langInfo.Translations = make(map[string]string)
  507. // load actual translation files
  508. var tlList map[string]string
  509. // load irc strings file
  510. ircName := strings.TrimSuffix(name, ".lang.yaml") + "-irc.lang.json"
  511. data, err = ioutil.ReadFile(filepath.Join(config.Languages.Path, ircName))
  512. if err != nil {
  513. return nil, fmt.Errorf("Could not load language's irc file [%s]: %s", ircName, err.Error())
  514. }
  515. err = json.Unmarshal(data, &tlList)
  516. if err != nil {
  517. return nil, fmt.Errorf("Could not parse language's irc file [%s]: %s", ircName, err.Error())
  518. }
  519. for key, value := range tlList {
  520. // because of how crowdin works, this is how we skip untranslated lines
  521. if key == value || value == "" {
  522. continue
  523. }
  524. langInfo.Translations[key] = value
  525. }
  526. // load help strings file
  527. helpName := strings.TrimSuffix(name, ".lang.yaml") + "-help.lang.json"
  528. data, err = ioutil.ReadFile(filepath.Join(config.Languages.Path, helpName))
  529. if err != nil {
  530. return nil, fmt.Errorf("Could not load language's help file [%s]: %s", helpName, err.Error())
  531. }
  532. err = json.Unmarshal(data, &tlList)
  533. if err != nil {
  534. return nil, fmt.Errorf("Could not parse language's help file [%s]: %s", helpName, err.Error())
  535. }
  536. for key, value := range tlList {
  537. // because of how crowdin works, this is how we skip untranslated lines
  538. if key == value || value == "" {
  539. continue
  540. }
  541. langInfo.Translations[key] = value
  542. }
  543. // confirm that values are correct
  544. if langInfo.Code == "en" {
  545. 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")
  546. }
  547. if langInfo.Code == "" || langInfo.Name == "" || langInfo.Contributors == "" {
  548. return nil, fmt.Errorf("Code, name or contributors is empty in language file [%s]", name)
  549. }
  550. if len(langInfo.Translations) == 0 {
  551. return nil, fmt.Errorf("Language [%s / %s] contains no translations", langInfo.Code, langInfo.Name)
  552. }
  553. // check for duplicate languages
  554. _, exists := config.Languages.Data[strings.ToLower(langInfo.Code)]
  555. if exists {
  556. return nil, fmt.Errorf("Language code [%s] defined twice", langInfo.Code)
  557. }
  558. // and insert into lang info
  559. config.Languages.Data[strings.ToLower(langInfo.Code)] = langInfo
  560. }
  561. // confirm that default language exists
  562. if config.Languages.Default == "" {
  563. config.Languages.Default = "en"
  564. } else {
  565. config.Languages.Default = strings.ToLower(config.Languages.Default)
  566. }
  567. _, exists := config.Languages.Data[config.Languages.Default]
  568. if config.Languages.Default != "en" && !exists {
  569. return nil, fmt.Errorf("Cannot find default language [%s]", config.Languages.Default)
  570. }
  571. }
  572. return config, nil
  573. }