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

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