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

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