config.go 13 KB

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