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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  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. MaxSendQString string `yaml:"max-sendq"`
  145. MaxSendQBytes uint64
  146. ConnectionLimiter connection_limits.LimiterConfig `yaml:"connection-limits"`
  147. ConnectionThrottler connection_limits.ThrottlerConfig `yaml:"connection-throttling"`
  148. }
  149. Datastore struct {
  150. Path string
  151. }
  152. Accounts struct {
  153. Registration AccountRegistrationConfig
  154. AuthenticationEnabled bool `yaml:"authentication-enabled"`
  155. }
  156. Channels struct {
  157. DefaultModes *string `yaml:"default-modes"`
  158. Registration ChannelRegistrationConfig
  159. }
  160. OperClasses map[string]*OperClassConfig `yaml:"oper-classes"`
  161. Opers map[string]*OperConfig
  162. Logging []logger.LoggingConfig
  163. Debug struct {
  164. StackImpact StackImpactConfig
  165. }
  166. Limits struct {
  167. AwayLen uint `yaml:"awaylen"`
  168. ChanListModes uint `yaml:"chan-list-modes"`
  169. ChannelLen uint `yaml:"channellen"`
  170. KickLen uint `yaml:"kicklen"`
  171. MonitorEntries uint `yaml:"monitor-entries"`
  172. NickLen uint `yaml:"nicklen"`
  173. TopicLen uint `yaml:"topiclen"`
  174. WhowasEntries uint `yaml:"whowas-entries"`
  175. LineLen LineLenConfig `yaml:"linelen"`
  176. }
  177. Filename string
  178. }
  179. // OperClass defines an assembled operator class.
  180. type OperClass struct {
  181. Title string
  182. WhoisLine string `yaml:"whois-line"`
  183. Capabilities map[string]bool // map to make lookups much easier
  184. }
  185. // OperatorClasses returns a map of assembled operator classes from the given config.
  186. func (conf *Config) OperatorClasses() (*map[string]OperClass, error) {
  187. ocs := make(map[string]OperClass)
  188. // loop from no extends to most extended, breaking if we can't add any more
  189. lenOfLastOcs := -1
  190. for {
  191. if lenOfLastOcs == len(ocs) {
  192. return nil, errors.New("OperClasses contains a looping dependency, or a class extends from a class that doesn't exist")
  193. }
  194. lenOfLastOcs = len(ocs)
  195. var anyMissing bool
  196. for name, info := range conf.OperClasses {
  197. _, exists := ocs[name]
  198. _, extendsExists := ocs[info.Extends]
  199. if exists {
  200. // class already exists
  201. continue
  202. } else if len(info.Extends) > 0 && !extendsExists {
  203. // class we extend on doesn't exist
  204. _, exists := conf.OperClasses[info.Extends]
  205. if !exists {
  206. return nil, fmt.Errorf("Operclass [%s] extends [%s], which doesn't exist", name, info.Extends)
  207. }
  208. anyMissing = true
  209. continue
  210. }
  211. // create new operclass
  212. var oc OperClass
  213. oc.Capabilities = make(map[string]bool)
  214. // get inhereted info from other operclasses
  215. if len(info.Extends) > 0 {
  216. einfo, _ := ocs[info.Extends]
  217. for capab := range einfo.Capabilities {
  218. oc.Capabilities[capab] = true
  219. }
  220. }
  221. // add our own info
  222. oc.Title = info.Title
  223. for _, capab := range info.Capabilities {
  224. oc.Capabilities[capab] = true
  225. }
  226. if len(info.WhoisLine) > 0 {
  227. oc.WhoisLine = info.WhoisLine
  228. } else {
  229. oc.WhoisLine = "is a"
  230. if strings.Contains(strings.ToLower(string(oc.Title[0])), "aeiou") {
  231. oc.WhoisLine += "n"
  232. }
  233. oc.WhoisLine += " "
  234. oc.WhoisLine += oc.Title
  235. }
  236. ocs[name] = oc
  237. }
  238. if !anyMissing {
  239. // we've got every operclass!
  240. break
  241. }
  242. }
  243. return &ocs, nil
  244. }
  245. // Oper represents a single assembled operator's config.
  246. type Oper struct {
  247. Class *OperClass
  248. WhoisLine string
  249. Vhost string
  250. Pass []byte
  251. Modes string
  252. }
  253. // Operators returns a map of operator configs from the given OperClass and config.
  254. func (conf *Config) Operators(oc *map[string]OperClass) (map[string]Oper, error) {
  255. operators := make(map[string]Oper)
  256. for name, opConf := range conf.Opers {
  257. var oper Oper
  258. // oper name
  259. name, err := CasefoldName(name)
  260. if err != nil {
  261. return nil, fmt.Errorf("Could not casefold oper name: %s", err.Error())
  262. }
  263. oper.Pass = opConf.PasswordBytes()
  264. oper.Vhost = opConf.Vhost
  265. class, exists := (*oc)[opConf.Class]
  266. if !exists {
  267. return nil, fmt.Errorf("Could not load operator [%s] - they use operclass [%s] which does not exist", name, opConf.Class)
  268. }
  269. oper.Class = &class
  270. if len(opConf.WhoisLine) > 0 {
  271. oper.WhoisLine = opConf.WhoisLine
  272. } else {
  273. oper.WhoisLine = class.WhoisLine
  274. }
  275. oper.Modes = strings.TrimSpace(opConf.Modes)
  276. // successful, attach to list of opers
  277. operators[name] = oper
  278. }
  279. return operators, nil
  280. }
  281. // TLSListeners returns a list of TLS listeners and their configs.
  282. func (conf *Config) TLSListeners() map[string]*tls.Config {
  283. tlsListeners := make(map[string]*tls.Config)
  284. for s, tlsListenersConf := range conf.Server.TLSListeners {
  285. config, err := tlsListenersConf.Config()
  286. config.ClientAuth = tls.RequestClientCert
  287. if err != nil {
  288. log.Fatal(err)
  289. }
  290. tlsListeners[s] = config
  291. }
  292. return tlsListeners
  293. }
  294. // LoadConfig loads the given YAML configuration file.
  295. func LoadConfig(filename string) (config *Config, err error) {
  296. data, err := ioutil.ReadFile(filename)
  297. if err != nil {
  298. return nil, err
  299. }
  300. err = yaml.Unmarshal(data, &config)
  301. if err != nil {
  302. return nil, err
  303. }
  304. config.Filename = filename
  305. // we need this so PasswordBytes returns the correct info
  306. if config.Server.Password != "" {
  307. config.Server.PassConfig.Password = config.Server.Password
  308. }
  309. if config.Network.Name == "" {
  310. return nil, errors.New("Network name missing")
  311. }
  312. if config.Server.Name == "" {
  313. return nil, errors.New("Server name missing")
  314. }
  315. if !utils.IsHostname(config.Server.Name) {
  316. return nil, errors.New("Server name must match the format of a hostname")
  317. }
  318. if config.Datastore.Path == "" {
  319. return nil, errors.New("Datastore path missing")
  320. }
  321. if len(config.Server.Listen) == 0 {
  322. return nil, errors.New("Server listening addresses missing")
  323. }
  324. if config.Limits.NickLen < 1 || config.Limits.ChannelLen < 2 || config.Limits.AwayLen < 1 || config.Limits.KickLen < 1 || config.Limits.TopicLen < 1 {
  325. return nil, errors.New("Limits aren't setup properly, check them and make them sane")
  326. }
  327. if config.Server.STS.Enabled {
  328. config.Server.STS.Duration, err = custime.ParseDuration(config.Server.STS.DurationString)
  329. if err != nil {
  330. return nil, fmt.Errorf("Could not parse STS duration: %s", err.Error())
  331. }
  332. if config.Server.STS.Port < 0 || config.Server.STS.Port > 65535 {
  333. return nil, fmt.Errorf("STS port is incorrect, should be 0 if disabled: %d", config.Server.STS.Port)
  334. }
  335. }
  336. if config.Server.ConnectionThrottler.Enabled {
  337. config.Server.ConnectionThrottler.Duration, err = time.ParseDuration(config.Server.ConnectionThrottler.DurationString)
  338. if err != nil {
  339. return nil, fmt.Errorf("Could not parse connection-throttle duration: %s", err.Error())
  340. }
  341. config.Server.ConnectionThrottler.BanDuration, err = time.ParseDuration(config.Server.ConnectionThrottler.BanDurationString)
  342. if err != nil {
  343. return nil, fmt.Errorf("Could not parse connection-throttle ban-duration: %s", err.Error())
  344. }
  345. }
  346. if config.Limits.LineLen.Tags < 512 || config.Limits.LineLen.Rest < 512 {
  347. return nil, errors.New("Line lengths must be 512 or greater (check the linelen section under server->limits)")
  348. }
  349. var newLogConfigs []logger.LoggingConfig
  350. for _, logConfig := range config.Logging {
  351. // methods
  352. methods := make(map[string]bool)
  353. for _, method := range strings.Split(logConfig.Method, " ") {
  354. if len(method) > 0 {
  355. methods[strings.ToLower(method)] = true
  356. }
  357. }
  358. if methods["file"] && logConfig.Filename == "" {
  359. return nil, errors.New("Logging configuration specifies 'file' method but 'filename' is empty")
  360. }
  361. logConfig.MethodFile = methods["file"]
  362. logConfig.MethodStdout = methods["stdout"]
  363. logConfig.MethodStderr = methods["stderr"]
  364. // levels
  365. level, exists := logger.LogLevelNames[strings.ToLower(logConfig.LevelString)]
  366. if !exists {
  367. return nil, fmt.Errorf("Could not translate log leve [%s]", logConfig.LevelString)
  368. }
  369. logConfig.Level = level
  370. // types
  371. for _, typeStr := range strings.Split(logConfig.TypeString, " ") {
  372. if len(typeStr) == 0 {
  373. continue
  374. }
  375. if typeStr == "-" {
  376. return nil, errors.New("Encountered logging type '-' with no type to exclude")
  377. }
  378. if typeStr[0] == '-' {
  379. typeStr = typeStr[1:]
  380. logConfig.ExcludedTypes = append(logConfig.ExcludedTypes, typeStr)
  381. } else {
  382. logConfig.Types = append(logConfig.Types, typeStr)
  383. }
  384. }
  385. if len(logConfig.Types) < 1 {
  386. return nil, errors.New("Logger has no types to log")
  387. }
  388. newLogConfigs = append(newLogConfigs, logConfig)
  389. }
  390. config.Logging = newLogConfigs
  391. config.Server.MaxSendQBytes, err = bytefmt.ToBytes(config.Server.MaxSendQString)
  392. if err != nil {
  393. return nil, fmt.Errorf("Could not parse maximum SendQ size (make sure it only contains whole numbers): %s", err.Error())
  394. }
  395. return config, nil
  396. }