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

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