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

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