backend.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. package backends
  2. import (
  3. "fmt"
  4. "github.com/flashmob/go-guerrilla/envelope"
  5. "github.com/flashmob/go-guerrilla/log"
  6. "reflect"
  7. "strconv"
  8. "strings"
  9. "sync"
  10. "sync/atomic"
  11. )
  12. var (
  13. Service *BackendService
  14. // deprecated backends system
  15. backends = map[string]Backend{}
  16. // new backends system
  17. Processors map[string]ProcessorConstructor
  18. )
  19. func init() {
  20. Service = &BackendService{}
  21. Processors = make(map[string]ProcessorConstructor)
  22. }
  23. type ProcessorConstructor func() Decorator
  24. // Backends process received mail. Depending on the implementation, they can store mail in the database,
  25. // write to a file, check for spam, re-transmit to another server, etc.
  26. // Must return an SMTP message (i.e. "250 OK") and a boolean indicating
  27. // whether the message was processed successfully.
  28. type Backend interface {
  29. // Public methods
  30. Process(*envelope.Envelope) BackendResult
  31. Initialize(BackendConfig) error
  32. Shutdown() error
  33. }
  34. type BackendConfig map[string]interface{}
  35. // All config structs extend from this
  36. type BaseConfig interface{}
  37. type saveStatus struct {
  38. err error
  39. queuedID string
  40. }
  41. // BackendResult represents a response to an SMTP client after receiving DATA.
  42. // The String method should return an SMTP message ready to send back to the
  43. // client, for example `250 OK: Message received`.
  44. type BackendResult interface {
  45. fmt.Stringer
  46. // Code should return the SMTP code associated with this response, ie. `250`
  47. Code() int
  48. }
  49. // Internal implementation of BackendResult for use by backend implementations.
  50. type backendResult string
  51. func (br backendResult) String() string {
  52. return string(br)
  53. }
  54. // Parses the SMTP code from the first 3 characters of the SMTP message.
  55. // Returns 554 if code cannot be parsed.
  56. func (br backendResult) Code() int {
  57. trimmed := strings.TrimSpace(string(br))
  58. if len(trimmed) < 3 {
  59. return 554
  60. }
  61. code, err := strconv.Atoi(trimmed[:3])
  62. if err != nil {
  63. return 554
  64. }
  65. return code
  66. }
  67. func NewBackendResult(message string) BackendResult {
  68. return backendResult(message)
  69. }
  70. type ProcessorInitializer interface {
  71. Initialize(backendConfig BackendConfig) error
  72. }
  73. type ProcessorShutdowner interface {
  74. Shutdown() error
  75. }
  76. type Initialize func(backendConfig BackendConfig) error
  77. type Shutdown func() error
  78. // Satisfy ProcessorInitializer interface
  79. // So we can now pass an anonymous function that implements ProcessorInitializer
  80. func (i Initialize) Initialize(backendConfig BackendConfig) error {
  81. // delegate to the anonymous function
  82. return i(backendConfig)
  83. }
  84. // satisfy ProcessorShutdowner interface, same concept as Initialize type
  85. func (s Shutdown) Shutdown() error {
  86. // delegate
  87. return s()
  88. }
  89. type BackendService struct {
  90. Initializers []ProcessorInitializer
  91. Shutdowners []ProcessorShutdowner
  92. sync.Mutex
  93. mainlog atomic.Value
  94. }
  95. // Get loads the log.logger in an atomic operation. Returns a stderr logger if not able to load
  96. func Log() log.Logger {
  97. if v, ok := Service.mainlog.Load().(log.Logger); ok {
  98. return v
  99. }
  100. l, _ := log.GetLogger(log.OutputStderr.String())
  101. return l
  102. }
  103. func (b *BackendService) StoreMainlog(l log.Logger) {
  104. b.mainlog.Store(l)
  105. }
  106. // AddInitializer adds a function that impliments ProcessorShutdowner to be called when initializing
  107. func (b *BackendService) AddInitializer(i ProcessorInitializer) {
  108. b.Lock()
  109. defer b.Unlock()
  110. b.Initializers = append(b.Initializers, i)
  111. }
  112. // AddShutdowner adds a function that impliments ProcessorShutdowner to be called when shutting down
  113. func (b *BackendService) AddShutdowner(i ProcessorShutdowner) {
  114. b.Lock()
  115. defer b.Unlock()
  116. b.Shutdowners = append(b.Shutdowners, i)
  117. }
  118. // Initialize initializes all the processors by
  119. func (b *BackendService) Initialize(backend BackendConfig) {
  120. b.Lock()
  121. defer b.Unlock()
  122. for i := range b.Initializers {
  123. b.Initializers[i].Initialize(backend)
  124. }
  125. }
  126. // Shutdown shuts down all the processor by calling their shutdowners
  127. // It also clears the initializers and shutdowners that were set with AddInitializer and AddShutdowner
  128. func (b *BackendService) Shutdown() {
  129. b.Lock()
  130. defer b.Unlock()
  131. for i := range b.Shutdowners {
  132. b.Shutdowners[i].Shutdown()
  133. }
  134. b.Initializers = make([]ProcessorInitializer, 0)
  135. b.Shutdowners = make([]ProcessorShutdowner, 0)
  136. }
  137. // AddProcessor adds a new processor, which becomes available to the backend_config.process_line option
  138. func (b *BackendService) AddProcessor(name string, p ProcessorConstructor) {
  139. // wrap in a constructor since we want to defer calling it
  140. var c ProcessorConstructor
  141. c = func() Decorator {
  142. return p()
  143. }
  144. // add to our processors list
  145. Processors[strings.ToLower(name)] = c
  146. }
  147. // extractConfig loads the backend config. It has already been unmarshalled
  148. // configData contains data from the main config file's "backend_config" value
  149. // configType is a Processor's specific config value.
  150. // The reason why using reflection is because we'll get a nice error message if the field is missing
  151. // the alternative solution would be to json.Marshal() and json.Unmarshal() however that will not give us any
  152. // error messages
  153. func (b *BackendService) ExtractConfig(configData BackendConfig, configType BaseConfig) (interface{}, error) {
  154. // Use reflection so that we can provide a nice error message
  155. s := reflect.ValueOf(configType).Elem() // so that we can set the values
  156. m := reflect.ValueOf(configType).Elem()
  157. t := reflect.TypeOf(configType).Elem()
  158. typeOfT := s.Type()
  159. for i := 0; i < m.NumField(); i++ {
  160. f := s.Field(i)
  161. // read the tags of the config struct
  162. field_name := t.Field(i).Tag.Get("json")
  163. if len(field_name) > 0 {
  164. // parse the tag to
  165. // get the field name from struct tag
  166. split := strings.Split(field_name, ",")
  167. field_name = split[0]
  168. } else {
  169. // could have no tag
  170. // so use the reflected field name
  171. field_name = typeOfT.Field(i).Name
  172. }
  173. if f.Type().Name() == "int" {
  174. // in json, there is no int, only floats...
  175. if intVal, converted := configData[field_name].(float64); converted {
  176. s.Field(i).SetInt(int64(intVal))
  177. } else if intVal, converted := configData[field_name].(int); converted {
  178. s.Field(i).SetInt(int64(intVal))
  179. } else {
  180. return configType, convertError("property missing/invalid: '" + field_name + "' of expected type: " + f.Type().Name())
  181. }
  182. }
  183. if f.Type().Name() == "string" {
  184. if stringVal, converted := configData[field_name].(string); converted {
  185. s.Field(i).SetString(stringVal)
  186. } else {
  187. return configType, convertError("missing/invalid: '" + field_name + "' of type: " + f.Type().Name())
  188. }
  189. }
  190. if f.Type().Name() == "bool" {
  191. if boolVal, converted := configData[field_name].(bool); converted {
  192. s.Field(i).SetBool(boolVal)
  193. } else {
  194. return configType, convertError("missing/invalid: '" + field_name + "' of type: " + f.Type().Name())
  195. }
  196. }
  197. }
  198. return configType, nil
  199. }