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

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