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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  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. "errors"
  9. "fmt"
  10. "io/ioutil"
  11. "log"
  12. "strings"
  13. "time"
  14. "code.cloudfoundry.org/bytefmt"
  15. "github.com/oragono/oragono/irc/connection_limits"
  16. "github.com/oragono/oragono/irc/custime"
  17. "github.com/oragono/oragono/irc/logger"
  18. "github.com/oragono/oragono/irc/passwd"
  19. "github.com/oragono/oragono/irc/utils"
  20. "gopkg.in/yaml.v2"
  21. )
  22. // PassConfig holds the connection password.
  23. type PassConfig struct {
  24. Password string
  25. }
  26. // TLSListenConfig defines configuration options for listening on TLS.
  27. type TLSListenConfig struct {
  28. Cert string
  29. Key string
  30. }
  31. // Config returns the TLS contiguration assicated with this TLSListenConfig.
  32. func (conf *TLSListenConfig) Config() (*tls.Config, error) {
  33. cert, err := tls.LoadX509KeyPair(conf.Cert, conf.Key)
  34. if err != nil {
  35. return nil, errors.New("tls cert+key: invalid pair")
  36. }
  37. return &tls.Config{
  38. Certificates: []tls.Certificate{cert},
  39. }, err
  40. }
  41. // PasswordBytes returns the bytes represented by the password hash.
  42. func (conf *PassConfig) PasswordBytes() []byte {
  43. bytes, err := passwd.DecodePasswordHash(conf.Password)
  44. if err != nil {
  45. log.Fatal("decode password error: ", err)
  46. }
  47. return bytes
  48. }
  49. // AccountRegistrationConfig controls account registration.
  50. type AccountRegistrationConfig struct {
  51. Enabled bool
  52. EnabledCallbacks []string `yaml:"enabled-callbacks"`
  53. Callbacks struct {
  54. Mailto struct {
  55. Server string
  56. Port int
  57. TLS struct {
  58. Enabled bool
  59. InsecureSkipVerify bool `yaml:"insecure_skip_verify"`
  60. ServerName string `yaml:"servername"`
  61. }
  62. Username string
  63. Password string
  64. Sender string
  65. VerifyMessageSubject string `yaml:"verify-message-subject"`
  66. VerifyMessage string `yaml:"verify-message"`
  67. }
  68. }
  69. AllowMultiplePerConnection bool `yaml:"allow-multiple-per-connection"`
  70. }
  71. // ChannelRegistrationConfig controls channel registration.
  72. type ChannelRegistrationConfig struct {
  73. Enabled bool
  74. }
  75. // OperClassConfig defines a specific operator class.
  76. type OperClassConfig struct {
  77. Title string
  78. WhoisLine string
  79. Extends string
  80. Capabilities []string
  81. }
  82. // OperConfig defines a specific operator's configuration.
  83. type OperConfig struct {
  84. Class string
  85. Vhost string
  86. WhoisLine string `yaml:"whois-line"`
  87. Password string
  88. Modes string
  89. }
  90. // PasswordBytes returns the bytes represented by the password hash.
  91. func (conf *OperConfig) PasswordBytes() []byte {
  92. bytes, err := passwd.DecodePasswordHash(conf.Password)
  93. if err != nil {
  94. log.Fatal("decode password error: ", err)
  95. }
  96. return bytes
  97. }
  98. // LineLenConfig controls line lengths.
  99. type LineLenConfig struct {
  100. Tags int
  101. Rest int
  102. }
  103. // STSConfig controls the STS configuration/
  104. type STSConfig struct {
  105. Enabled bool
  106. Duration time.Duration `yaml:"duration-real"`
  107. DurationString string `yaml:"duration"`
  108. Port int
  109. Preload bool
  110. }
  111. // Value returns the STS value to advertise in CAP
  112. func (sts *STSConfig) Value() string {
  113. val := fmt.Sprintf("duration=%d,", int(sts.Duration.Seconds()))
  114. if sts.Enabled && sts.Port > 0 {
  115. val += fmt.Sprintf(",port=%d", sts.Port)
  116. }
  117. if sts.Enabled && sts.Preload {
  118. val += ",preload"
  119. }
  120. return val
  121. }
  122. // StackImpactConfig is the config used for StackImpact's profiling.
  123. type StackImpactConfig struct {
  124. Enabled bool
  125. AgentKey string `yaml:"agent-key"`
  126. AppName string `yaml:"app-name"`
  127. }
  128. // Config defines the overall configuration.
  129. type Config struct {
  130. Network struct {
  131. Name string
  132. }
  133. Server struct {
  134. PassConfig
  135. Password string
  136. Name string
  137. Listen []string
  138. TLSListeners map[string]*TLSListenConfig `yaml:"tls-listeners"`
  139. STS STSConfig
  140. CheckIdent bool `yaml:"check-ident"`
  141. MOTD string
  142. MOTDFormatting bool `yaml:"motd-formatting"`
  143. ProxyAllowedFrom []string `yaml:"proxy-allowed-from"`
  144. WebIRC []webircConfig `yaml:"webirc"`
  145. MaxSendQString string `yaml:"max-sendq"`
  146. MaxSendQBytes uint64
  147. ConnectionLimiter connection_limits.LimiterConfig `yaml:"connection-limits"`
  148. ConnectionThrottler connection_limits.ThrottlerConfig `yaml:"connection-throttling"`
  149. }
  150. Datastore struct {
  151. Path string
  152. }
  153. Accounts struct {
  154. Registration AccountRegistrationConfig
  155. AuthenticationEnabled bool `yaml:"authentication-enabled"`
  156. }
  157. Channels struct {
  158. DefaultModes *string `yaml:"default-modes"`
  159. Registration ChannelRegistrationConfig
  160. }
  161. OperClasses map[string]*OperClassConfig `yaml:"oper-classes"`
  162. Opers map[string]*OperConfig
  163. Logging []logger.LoggingConfig
  164. Debug struct {
  165. RecoverFromErrors *bool `yaml:"recover-from-errors"`
  166. StackImpact StackImpactConfig
  167. }
  168. Limits struct {
  169. AwayLen uint `yaml:"awaylen"`
  170. ChanListModes uint `yaml:"chan-list-modes"`
  171. ChannelLen uint `yaml:"channellen"`
  172. KickLen uint `yaml:"kicklen"`
  173. MonitorEntries uint `yaml:"monitor-entries"`
  174. NickLen uint `yaml:"nicklen"`
  175. TopicLen uint `yaml:"topiclen"`
  176. WhowasEntries uint `yaml:"whowas-entries"`
  177. LineLen LineLenConfig `yaml:"linelen"`
  178. }
  179. Filename string
  180. }
  181. // OperClass defines an assembled operator class.
  182. type OperClass struct {
  183. Title string
  184. WhoisLine string `yaml:"whois-line"`
  185. Capabilities map[string]bool // map to make lookups much easier
  186. }
  187. // OperatorClasses returns a map of assembled operator classes from the given config.
  188. func (conf *Config) OperatorClasses() (*map[string]OperClass, error) {
  189. ocs := make(map[string]OperClass)
  190. // loop from no extends to most extended, breaking if we can't add any more
  191. lenOfLastOcs := -1
  192. for {
  193. if lenOfLastOcs == len(ocs) {
  194. return nil, errors.New("OperClasses contains a looping dependency, or a class extends from a class that doesn't exist")
  195. }
  196. lenOfLastOcs = len(ocs)
  197. var anyMissing bool
  198. for name, info := range conf.OperClasses {
  199. _, exists := ocs[name]
  200. _, extendsExists := ocs[info.Extends]
  201. if exists {
  202. // class already exists
  203. continue
  204. } else if len(info.Extends) > 0 && !extendsExists {
  205. // class we extend on doesn't exist
  206. _, exists := conf.OperClasses[info.Extends]
  207. if !exists {
  208. return nil, fmt.Errorf("Operclass [%s] extends [%s], which doesn't exist", name, info.Extends)
  209. }
  210. anyMissing = true
  211. continue
  212. }
  213. // create new operclass
  214. var oc OperClass
  215. oc.Capabilities = make(map[string]bool)
  216. // get inhereted info from other operclasses
  217. if len(info.Extends) > 0 {
  218. einfo, _ := ocs[info.Extends]
  219. for capab := range einfo.Capabilities {
  220. oc.Capabilities[capab] = true
  221. }
  222. }
  223. // add our own info
  224. oc.Title = info.Title
  225. for _, capab := range info.Capabilities {
  226. oc.Capabilities[capab] = true
  227. }
  228. if len(info.WhoisLine) > 0 {
  229. oc.WhoisLine = info.WhoisLine
  230. } else {
  231. oc.WhoisLine = "is a"
  232. if strings.Contains(strings.ToLower(string(oc.Title[0])), "aeiou") {
  233. oc.WhoisLine += "n"
  234. }
  235. oc.WhoisLine += " "
  236. oc.WhoisLine += oc.Title
  237. }
  238. ocs[name] = oc
  239. }
  240. if !anyMissing {
  241. // we've got every operclass!
  242. break
  243. }
  244. }
  245. return &ocs, nil
  246. }
  247. // Oper represents a single assembled operator's config.
  248. type Oper struct {
  249. Class *OperClass
  250. WhoisLine string
  251. Vhost string
  252. Pass []byte
  253. Modes string
  254. }
  255. // Operators returns a map of operator configs from the given OperClass and config.
  256. func (conf *Config) Operators(oc *map[string]OperClass) (map[string]Oper, error) {
  257. operators := make(map[string]Oper)
  258. for name, opConf := range conf.Opers {
  259. var oper Oper
  260. // oper name
  261. name, err := CasefoldName(name)
  262. if err != nil {
  263. return nil, fmt.Errorf("Could not casefold oper name: %s", err.Error())
  264. }
  265. oper.Pass = opConf.PasswordBytes()
  266. oper.Vhost = opConf.Vhost
  267. class, exists := (*oc)[opConf.Class]
  268. if !exists {
  269. return nil, fmt.Errorf("Could not load operator [%s] - they use operclass [%s] which does not exist", name, opConf.Class)
  270. }
  271. oper.Class = &class
  272. if len(opConf.WhoisLine) > 0 {
  273. oper.WhoisLine = opConf.WhoisLine
  274. } else {
  275. oper.WhoisLine = class.WhoisLine
  276. }
  277. oper.Modes = strings.TrimSpace(opConf.Modes)
  278. // successful, attach to list of opers
  279. operators[name] = oper
  280. }
  281. return operators, nil
  282. }
  283. // TLSListeners returns a list of TLS listeners and their configs.
  284. func (conf *Config) TLSListeners() map[string]*tls.Config {
  285. tlsListeners := make(map[string]*tls.Config)
  286. for s, tlsListenersConf := range conf.Server.TLSListeners {
  287. config, err := tlsListenersConf.Config()
  288. config.ClientAuth = tls.RequestClientCert
  289. if err != nil {
  290. log.Fatal(err)
  291. }
  292. tlsListeners[s] = config
  293. }
  294. return tlsListeners
  295. }
  296. // LoadConfig loads the given YAML configuration file.
  297. func LoadConfig(filename string) (config *Config, err error) {
  298. data, err := ioutil.ReadFile(filename)
  299. if err != nil {
  300. return nil, err
  301. }
  302. err = yaml.Unmarshal(data, &config)
  303. if err != nil {
  304. return nil, err
  305. }
  306. config.Filename = filename
  307. // we need this so PasswordBytes returns the correct info
  308. if config.Server.Password != "" {
  309. config.Server.PassConfig.Password = config.Server.Password
  310. }
  311. if config.Network.Name == "" {
  312. return nil, errors.New("Network name missing")
  313. }
  314. if config.Server.Name == "" {
  315. return nil, errors.New("Server name missing")
  316. }
  317. if !utils.IsHostname(config.Server.Name) {
  318. return nil, errors.New("Server name must match the format of a hostname")
  319. }
  320. if config.Datastore.Path == "" {
  321. return nil, errors.New("Datastore path missing")
  322. }
  323. if len(config.Server.Listen) == 0 {
  324. return nil, errors.New("Server listening addresses missing")
  325. }
  326. if config.Limits.NickLen < 1 || config.Limits.ChannelLen < 2 || config.Limits.AwayLen < 1 || config.Limits.KickLen < 1 || config.Limits.TopicLen < 1 {
  327. return nil, errors.New("Limits aren't setup properly, check them and make them sane")
  328. }
  329. if config.Server.STS.Enabled {
  330. config.Server.STS.Duration, err = custime.ParseDuration(config.Server.STS.DurationString)
  331. if err != nil {
  332. return nil, fmt.Errorf("Could not parse STS duration: %s", err.Error())
  333. }
  334. if config.Server.STS.Port < 0 || config.Server.STS.Port > 65535 {
  335. return nil, fmt.Errorf("STS port is incorrect, should be 0 if disabled: %d", config.Server.STS.Port)
  336. }
  337. }
  338. if config.Server.ConnectionThrottler.Enabled {
  339. config.Server.ConnectionThrottler.Duration, err = time.ParseDuration(config.Server.ConnectionThrottler.DurationString)
  340. if err != nil {
  341. return nil, fmt.Errorf("Could not parse connection-throttle duration: %s", err.Error())
  342. }
  343. config.Server.ConnectionThrottler.BanDuration, err = time.ParseDuration(config.Server.ConnectionThrottler.BanDurationString)
  344. if err != nil {
  345. return nil, fmt.Errorf("Could not parse connection-throttle ban-duration: %s", err.Error())
  346. }
  347. }
  348. // process webirc blocks
  349. var newWebIRC []webircConfig
  350. for _, webirc := range config.Server.WebIRC {
  351. // skip webirc blocks with no hosts (such as the example one)
  352. if len(webirc.Hosts) == 0 {
  353. continue
  354. }
  355. err = webirc.Populate()
  356. if err != nil {
  357. return nil, fmt.Errorf("Could not parse WebIRC config: %s", err.Error())
  358. }
  359. newWebIRC = append(newWebIRC, webirc)
  360. }
  361. config.Server.WebIRC = newWebIRC
  362. // process limits
  363. if config.Limits.LineLen.Tags < 512 || config.Limits.LineLen.Rest < 512 {
  364. return nil, errors.New("Line lengths must be 512 or greater (check the linelen section under server->limits)")
  365. }
  366. var newLogConfigs []logger.LoggingConfig
  367. for _, logConfig := range config.Logging {
  368. // methods
  369. methods := make(map[string]bool)
  370. for _, method := range strings.Split(logConfig.Method, " ") {
  371. if len(method) > 0 {
  372. methods[strings.ToLower(method)] = true
  373. }
  374. }
  375. if methods["file"] && logConfig.Filename == "" {
  376. return nil, errors.New("Logging configuration specifies 'file' method but 'filename' is empty")
  377. }
  378. logConfig.MethodFile = methods["file"]
  379. logConfig.MethodStdout = methods["stdout"]
  380. logConfig.MethodStderr = methods["stderr"]
  381. // levels
  382. level, exists := logger.LogLevelNames[strings.ToLower(logConfig.LevelString)]
  383. if !exists {
  384. return nil, fmt.Errorf("Could not translate log leve [%s]", logConfig.LevelString)
  385. }
  386. logConfig.Level = level
  387. // types
  388. for _, typeStr := range strings.Split(logConfig.TypeString, " ") {
  389. if len(typeStr) == 0 {
  390. continue
  391. }
  392. if typeStr == "-" {
  393. return nil, errors.New("Encountered logging type '-' with no type to exclude")
  394. }
  395. if typeStr[0] == '-' {
  396. typeStr = typeStr[1:]
  397. logConfig.ExcludedTypes = append(logConfig.ExcludedTypes, typeStr)
  398. } else {
  399. logConfig.Types = append(logConfig.Types, typeStr)
  400. }
  401. }
  402. if len(logConfig.Types) < 1 {
  403. return nil, errors.New("Logger has no types to log")
  404. }
  405. newLogConfigs = append(newLogConfigs, logConfig)
  406. }
  407. config.Logging = newLogConfigs
  408. config.Server.MaxSendQBytes, err = bytefmt.ToBytes(config.Server.MaxSendQString)
  409. if err != nil {
  410. return nil, fmt.Errorf("Could not parse maximum SendQ size (make sure it only contains whole numbers): %s", err.Error())
  411. }
  412. return config, nil
  413. }