選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

config.go 14KB

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