config.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. package guerrilla
  2. import (
  3. "crypto/tls"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "github.com/flashmob/go-guerrilla/backends"
  8. "github.com/flashmob/go-guerrilla/log"
  9. "os"
  10. "reflect"
  11. "strings"
  12. )
  13. // AppConfig is the holder of the configuration of the app
  14. type AppConfig struct {
  15. // Servers can have one or more items.
  16. /// Defaults to 1 server listening on 127.0.0.1:2525
  17. Servers []ServerConfig `json:"servers"`
  18. // AllowedHosts lists which hosts to accept email for. Defaults to os.Hostname
  19. AllowedHosts []string `json:"allowed_hosts"`
  20. // PidFile is the path for writing out the process id. No output if empty
  21. PidFile string `json:"pid_file"`
  22. // LogFile is where the logs go. Use path to file, or "stderr", "stdout"
  23. // or "off". Default "stderr"
  24. LogFile string `json:"log_file,omitempty"`
  25. // LogLevel controls the lowest level we log.
  26. // "info", "debug", "error", "panic". Default "info"
  27. LogLevel string `json:"log_level,omitempty"`
  28. // BackendConfig configures the email envelope processing backend
  29. BackendConfig backends.BackendConfig `json:"backend_config"`
  30. }
  31. // ServerConfig specifies config options for a single server
  32. type ServerConfig struct {
  33. // IsEnabled set to true to start the server, false will ignore it
  34. IsEnabled bool `json:"is_enabled"`
  35. // Hostname will be used in the server's reply to HELO/EHLO. If TLS enabled
  36. // make sure that the Hostname matches the cert. Defaults to os.Hostname()
  37. Hostname string `json:"host_name"`
  38. // MaxSize is the maximum size of an email that will be accepted for delivery.
  39. // Defaults to 10 Mebibytes
  40. MaxSize int64 `json:"max_size"`
  41. // PrivateKeyFile path to cert private key in PEM format. Will be ignored if blank
  42. PrivateKeyFile string `json:"private_key_file"`
  43. // PublicKeyFile path to cert (public key) chain in PEM format.
  44. // Will be ignored if blank
  45. PublicKeyFile string `json:"public_key_file"`
  46. // Timeout specifies the connection timeout in seconds. Defaults to 30
  47. Timeout int `json:"timeout"`
  48. // Listen interface specified in <ip>:<port> - defaults to 127.0.0.1:2525
  49. ListenInterface string `json:"listen_interface"`
  50. // StartTLSOn should we offer STARTTLS command. Cert must be valid.
  51. // False by default
  52. StartTLSOn bool `json:"start_tls_on,omitempty"`
  53. // TLSAlwaysOn run this server as a pure TLS server, i.e. SMTPS
  54. TLSAlwaysOn bool `json:"tls_always_on,omitempty"`
  55. // MaxClients controls how many maxiumum clients we can handle at once.
  56. // Defaults to 100
  57. MaxClients int `json:"max_clients"`
  58. // LogFile is where the logs go. Use path to file, or "stderr", "stdout" or "off".
  59. // defaults to AppConfig.Log file setting
  60. LogFile string `json:"log_file,omitempty"`
  61. // The following used to watch certificate changes so that the TLS can be reloaded
  62. _privateKeyFile_mtime int
  63. _publicKeyFile_mtime int
  64. }
  65. // Unmarshalls json data into AppConfig struct and any other initialization of the struct
  66. // also does validation, returns error if validation failed or something went wrong
  67. func (c *AppConfig) Load(jsonBytes []byte) error {
  68. err := json.Unmarshal(jsonBytes, c)
  69. if err != nil {
  70. return fmt.Errorf("could not parse config file: %s", err)
  71. }
  72. if err = c.setDefaults(); err != nil {
  73. return err
  74. }
  75. if err = c.setBackendDefaults(); err != nil {
  76. return err
  77. }
  78. // all servers must be valid in order to continue
  79. for _, server := range c.Servers {
  80. if errs := server.Validate(); errs != nil {
  81. return errs
  82. }
  83. }
  84. // read the timestamps for the ssl keys, to determine if they need to be reloaded
  85. for i := 0; i < len(c.Servers); i++ {
  86. c.Servers[i].loadTlsKeyTimestamps()
  87. }
  88. return nil
  89. }
  90. // Emits any configuration change events onto the event bus.
  91. func (c *AppConfig) EmitChangeEvents(oldConfig *AppConfig, app Guerrilla) {
  92. // has backend changed?
  93. if !reflect.DeepEqual((*c).BackendConfig, (*oldConfig).BackendConfig) {
  94. app.Publish(EventConfigBackendConfig, c)
  95. }
  96. // has config changed, general check
  97. if !reflect.DeepEqual(oldConfig, c) {
  98. app.Publish(EventConfigNewConfig, c)
  99. }
  100. // has 'allowed hosts' changed?
  101. if !reflect.DeepEqual(oldConfig.AllowedHosts, c.AllowedHosts) {
  102. app.Publish(EventConfigAllowedHosts, c)
  103. }
  104. // has pid file changed?
  105. if strings.Compare(oldConfig.PidFile, c.PidFile) != 0 {
  106. app.Publish(EventConfigPidFile, c)
  107. }
  108. // has mainlog log changed?
  109. if strings.Compare(oldConfig.LogFile, c.LogFile) != 0 {
  110. app.Publish(EventConfigLogFile, c)
  111. }
  112. // has log level changed?
  113. if strings.Compare(oldConfig.LogLevel, c.LogLevel) != 0 {
  114. app.Publish(EventConfigLogLevel, c)
  115. }
  116. // server config changes
  117. oldServers := oldConfig.getServers()
  118. for iface, newServer := range c.getServers() {
  119. // is server is in both configs?
  120. if oldServer, ok := oldServers[iface]; ok {
  121. // since old server exists in the new config, we do not track it anymore
  122. delete(oldServers, iface)
  123. // so we know the server exists in both old & new configs
  124. newServer.emitChangeEvents(oldServer, app)
  125. } else {
  126. // start new server
  127. app.Publish(EventConfigServerNew, newServer)
  128. }
  129. }
  130. // remove any servers that don't exist anymore
  131. for _, oldserver := range oldServers {
  132. app.Publish(EventConfigServerRemove, oldserver)
  133. }
  134. }
  135. // EmitLogReopen emits log reopen events using existing config
  136. func (c *AppConfig) EmitLogReopenEvents(app Guerrilla) {
  137. app.Publish(EventConfigLogReopen, c)
  138. for _, sc := range c.getServers() {
  139. app.Publish(EventConfigServerLogReopen, sc)
  140. }
  141. }
  142. // gets the servers in a map (key by interface) for easy lookup
  143. func (c *AppConfig) getServers() map[string]*ServerConfig {
  144. servers := make(map[string]*ServerConfig, len(c.Servers))
  145. for i := 0; i < len(c.Servers); i++ {
  146. servers[c.Servers[i].ListenInterface] = &c.Servers[i]
  147. }
  148. return servers
  149. }
  150. // setDefaults fills in default server settings for values that were not configured
  151. // The defaults are:
  152. // * Server listening to 127.0.0.1:2525
  153. // * use your hostname to determine your which hosts to accept email for
  154. // * 100 maximum clients
  155. // * 10MB max message size
  156. // * log to Stderr,
  157. // * log level set to "`debug`"
  158. // * timeout to 30 sec
  159. // * Backend configured with the following processors: `HeadersParser|Header|Debugger`
  160. // where it will log the received emails.
  161. func (c *AppConfig) setDefaults() error {
  162. if c.LogFile == "" {
  163. c.LogFile = log.OutputStderr.String()
  164. }
  165. if c.LogLevel == "" {
  166. c.LogLevel = "debug"
  167. }
  168. if len(c.AllowedHosts) == 0 {
  169. if h, err := os.Hostname(); err != nil {
  170. return err
  171. } else {
  172. c.AllowedHosts = append(c.AllowedHosts, h)
  173. }
  174. }
  175. h, err := os.Hostname()
  176. if err != nil {
  177. return err
  178. }
  179. if len(c.Servers) == 0 {
  180. sc := ServerConfig{}
  181. sc.LogFile = c.LogFile
  182. sc.ListenInterface = defaultInterface
  183. sc.IsEnabled = true
  184. sc.Hostname = h
  185. sc.MaxClients = 100
  186. sc.Timeout = 30
  187. sc.MaxSize = 10 << 20 // 10 Mebibytes
  188. c.Servers = append(c.Servers, sc)
  189. } else {
  190. // make sure each server has defaults correctly configured
  191. for i := range c.Servers {
  192. if c.Servers[i].Hostname == "" {
  193. c.Servers[i].Hostname = h
  194. }
  195. if c.Servers[i].MaxClients == 0 {
  196. c.Servers[i].MaxClients = 100
  197. }
  198. if c.Servers[i].Timeout == 0 {
  199. c.Servers[i].Timeout = 20
  200. }
  201. if c.Servers[i].MaxSize == 0 {
  202. c.Servers[i].MaxSize = 10 << 20 // 10 Mebibytes
  203. }
  204. if c.Servers[i].ListenInterface == "" {
  205. return errors.New(fmt.Sprintf("Listen interface not specified for server at index %d", i))
  206. }
  207. if c.Servers[i].LogFile == "" {
  208. c.Servers[i].LogFile = c.LogFile
  209. }
  210. // validate the server config
  211. err = c.Servers[i].Validate()
  212. if err != nil {
  213. return err
  214. }
  215. }
  216. }
  217. return nil
  218. }
  219. // setBackendDefaults sets default values for the backend config,
  220. // if no backend config was added before starting, then use a default config
  221. // otherwise, see what required values were missed in the config and add any missing with defaults
  222. func (c *AppConfig) setBackendDefaults() error {
  223. if len(c.BackendConfig) == 0 {
  224. h, err := os.Hostname()
  225. if err != nil {
  226. return err
  227. }
  228. c.BackendConfig = backends.BackendConfig{
  229. "log_received_mails": true,
  230. "save_workers_size": 1,
  231. "save_process": "HeadersParser|Header|Debugger",
  232. "primary_mail_host": h,
  233. }
  234. } else {
  235. if _, ok := c.BackendConfig["save_process"]; !ok {
  236. c.BackendConfig["save_process"] = "HeadersParser|Header|Debugger"
  237. }
  238. if _, ok := c.BackendConfig["primary_mail_host"]; !ok {
  239. h, err := os.Hostname()
  240. if err != nil {
  241. return err
  242. }
  243. c.BackendConfig["primary_mail_host"] = h
  244. }
  245. if _, ok := c.BackendConfig["save_workers_size"]; !ok {
  246. c.BackendConfig["save_workers_size"] = 1
  247. }
  248. if _, ok := c.BackendConfig["log_received_mails"]; !ok {
  249. c.BackendConfig["log_received_mails"] = false
  250. }
  251. }
  252. return nil
  253. }
  254. // Emits any configuration change events on the server.
  255. // All events are fired and run synchronously
  256. func (sc *ServerConfig) emitChangeEvents(oldServer *ServerConfig, app Guerrilla) {
  257. // get a list of changes
  258. changes := getDiff(
  259. *oldServer,
  260. *sc,
  261. )
  262. if len(changes) > 0 {
  263. // something changed in the server config
  264. app.Publish(EventConfigServerConfig, sc)
  265. }
  266. // enable or disable?
  267. if _, ok := changes["IsEnabled"]; ok {
  268. if sc.IsEnabled {
  269. app.Publish(EventConfigServerStart, sc)
  270. } else {
  271. app.Publish(EventConfigServerStop, sc)
  272. }
  273. // do not emit any more events when IsEnabled changed
  274. return
  275. }
  276. // log file change?
  277. if _, ok := changes["LogFile"]; ok {
  278. app.Publish(EventConfigServerLogFile, sc)
  279. } else {
  280. // since config file has not changed, we reload it
  281. app.Publish(EventConfigServerLogReopen, sc)
  282. }
  283. // timeout changed
  284. if _, ok := changes["Timeout"]; ok {
  285. app.Publish(EventConfigServerTimeout, sc)
  286. }
  287. // max_clients changed
  288. if _, ok := changes["MaxClients"]; ok {
  289. app.Publish(EventConfigServerMaxClients, sc)
  290. }
  291. // tls changed
  292. if ok := func() bool {
  293. if _, ok := changes["PrivateKeyFile"]; ok {
  294. return true
  295. }
  296. if _, ok := changes["PublicKeyFile"]; ok {
  297. return true
  298. }
  299. if _, ok := changes["StartTLSOn"]; ok {
  300. return true
  301. }
  302. if _, ok := changes["TLSAlwaysOn"]; ok {
  303. return true
  304. }
  305. return false
  306. }(); ok {
  307. app.Publish(EventConfigServerTLSConfig, sc)
  308. }
  309. }
  310. // Loads in timestamps for the ssl keys
  311. func (sc *ServerConfig) loadTlsKeyTimestamps() error {
  312. var statErr = func(iface string, err error) error {
  313. return errors.New(
  314. fmt.Sprintf(
  315. "could not stat key for server [%s], %s",
  316. iface,
  317. err.Error()))
  318. }
  319. if info, err := os.Stat(sc.PrivateKeyFile); err == nil {
  320. sc._privateKeyFile_mtime = info.ModTime().Second()
  321. } else {
  322. return statErr(sc.ListenInterface, err)
  323. }
  324. if info, err := os.Stat(sc.PublicKeyFile); err == nil {
  325. sc._publicKeyFile_mtime = info.ModTime().Second()
  326. } else {
  327. return statErr(sc.ListenInterface, err)
  328. }
  329. return nil
  330. }
  331. // Gets the timestamp of the TLS certificates. Returns a unix time of when they were last modified
  332. // when the config was read. We use this info to determine if TLS needs to be re-loaded.
  333. func (sc *ServerConfig) getTlsKeyTimestamps() (int, int) {
  334. return sc._privateKeyFile_mtime, sc._publicKeyFile_mtime
  335. }
  336. // Validate validates the server's configuration.
  337. func (sc *ServerConfig) Validate() error {
  338. var errs Errors
  339. if sc.StartTLSOn || sc.TLSAlwaysOn {
  340. if sc.PublicKeyFile == "" {
  341. errs = append(errs, errors.New("PublicKeyFile is empty"))
  342. }
  343. if sc.PrivateKeyFile == "" {
  344. errs = append(errs, errors.New("PrivateKeyFile is empty"))
  345. }
  346. if _, err := tls.LoadX509KeyPair(sc.PublicKeyFile, sc.PrivateKeyFile); err != nil {
  347. errs = append(errs,
  348. errors.New(fmt.Sprintf("cannot use TLS config for [%s], %v", sc.ListenInterface, err)))
  349. }
  350. }
  351. if len(errs) > 0 {
  352. return errs
  353. }
  354. return nil
  355. }
  356. // Returns a diff between struct a & struct b.
  357. // Results are returned in a map, where each key is the name of the field that was different.
  358. // a and b are struct values, must not be pointer
  359. // and of the same struct type
  360. func getDiff(a interface{}, b interface{}) map[string]interface{} {
  361. ret := make(map[string]interface{}, 5)
  362. compareWith := structtomap(b)
  363. for key, val := range structtomap(a) {
  364. if val != compareWith[key] {
  365. ret[key] = compareWith[key]
  366. }
  367. }
  368. // detect tls changes (have the key files been modified?)
  369. if oldServer, ok := a.(ServerConfig); ok {
  370. t1, t2 := oldServer.getTlsKeyTimestamps()
  371. if newServer, ok := b.(ServerConfig); ok {
  372. t3, t4 := newServer.getTlsKeyTimestamps()
  373. if t1 != t3 {
  374. ret["PrivateKeyFile"] = newServer.PrivateKeyFile
  375. }
  376. if t2 != t4 {
  377. ret["PublicKeyFile"] = newServer.PublicKeyFile
  378. }
  379. }
  380. }
  381. return ret
  382. }
  383. // Convert fields of a struct to a map
  384. // only able to convert int, bool and string; not recursive
  385. func structtomap(obj interface{}) map[string]interface{} {
  386. ret := make(map[string]interface{}, 0)
  387. v := reflect.ValueOf(obj)
  388. t := v.Type()
  389. for index := 0; index < v.NumField(); index++ {
  390. vField := v.Field(index)
  391. fName := t.Field(index).Name
  392. switch vField.Kind() {
  393. case reflect.Int:
  394. value := vField.Int()
  395. ret[fName] = value
  396. case reflect.String:
  397. value := vField.String()
  398. ret[fName] = value
  399. case reflect.Bool:
  400. value := vField.Bool()
  401. ret[fName] = value
  402. }
  403. }
  404. return ret
  405. }