backend.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  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. Svc *Service
  14. // Store the constructor for making an new processor decorator.
  15. processors map[string]processorConstructor
  16. b Backend
  17. )
  18. func init() {
  19. Svc = &Service{}
  20. processors = make(map[string]processorConstructor)
  21. }
  22. type processorConstructor func() Decorator
  23. // Backends process received mail. Depending on the implementation, they can store mail in the database,
  24. // write to a file, check for spam, re-transmit to another server, etc.
  25. // Must return an SMTP message (i.e. "250 OK") and a boolean indicating
  26. // whether the message was processed successfully.
  27. type Backend interface {
  28. // Public methods
  29. Process(*envelope.Envelope) Result
  30. ValidateRcpt(e *envelope.Envelope) RcptError
  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 notifyMsg struct {
  38. err error
  39. queuedID string
  40. }
  41. // Result 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 Result 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 result string
  51. func (br result) 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 result) 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 NewResult(message string) Result {
  68. return result(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 Errors []error
  90. // implement the Error interface
  91. func (e Errors) Error() string {
  92. if len(e) == 1 {
  93. return e[0].Error()
  94. }
  95. // multiple errors
  96. msg := ""
  97. for _, err := range e {
  98. msg += "\n" + err.Error()
  99. }
  100. return msg
  101. }
  102. // New retrieve a backend specified by the backendName, and initialize it using
  103. // backendConfig
  104. func New(backendName string, backendConfig BackendConfig, l log.Logger) (Backend, error) {
  105. Svc.StoreMainlog(l)
  106. gateway := &BackendGateway{config: backendConfig}
  107. err := gateway.Initialize(backendConfig)
  108. if err != nil {
  109. return nil, fmt.Errorf("error while initializing the backend: %s", err)
  110. }
  111. gateway.State = BackendStateRunning
  112. b = Backend(gateway)
  113. return b, nil
  114. }
  115. func GetBackend() Backend {
  116. return b
  117. }
  118. type Service struct {
  119. initializers []ProcessorInitializer
  120. shutdowners []ProcessorShutdowner
  121. sync.Mutex
  122. mainlog atomic.Value
  123. }
  124. // Get loads the log.logger in an atomic operation. Returns a stderr logger if not able to load
  125. func Log() log.Logger {
  126. if v, ok := Svc.mainlog.Load().(log.Logger); ok {
  127. return v
  128. }
  129. l, _ := log.GetLogger(log.OutputStderr.String())
  130. return l
  131. }
  132. func (s *Service) StoreMainlog(l log.Logger) {
  133. s.mainlog.Store(l)
  134. }
  135. // AddInitializer adds a function that implements ProcessorShutdowner to be called when initializing
  136. func (s *Service) AddInitializer(i ProcessorInitializer) {
  137. s.Lock()
  138. defer s.Unlock()
  139. s.initializers = append(s.initializers, i)
  140. }
  141. // AddShutdowner adds a function that implements ProcessorShutdowner to be called when shutting down
  142. func (s *Service) AddShutdowner(sh ProcessorShutdowner) {
  143. s.Lock()
  144. defer s.Unlock()
  145. s.shutdowners = append(s.shutdowners, sh)
  146. }
  147. // Initialize initializes all the processors one-by-one and returns any errors.
  148. // Subsequent calls to Initialize will not call the initializer again unless it failed on the previous call
  149. // so Initialize may be called again to retry after getting errors
  150. func (s *Service) initialize(backend BackendConfig) Errors {
  151. s.Lock()
  152. defer s.Unlock()
  153. var errors Errors
  154. failed := make([]ProcessorInitializer, 0)
  155. for i := range s.initializers {
  156. if err := s.initializers[i].Initialize(backend); err != nil {
  157. errors = append(errors, err)
  158. failed = append(failed, s.initializers[i])
  159. }
  160. }
  161. // keep only the failed initializers
  162. s.initializers = failed
  163. return errors
  164. }
  165. // Shutdown shuts down all the processors by calling their shutdowners (if any)
  166. // Subsequent calls to Shutdown will not call the shutdowners again unless it failed on the previous call
  167. // so Shutdown may be called again to retry after getting errors
  168. func (s *Service) shutdown() Errors {
  169. s.Lock()
  170. defer s.Unlock()
  171. var errors Errors
  172. failed := make([]ProcessorShutdowner, 0)
  173. for i := range s.shutdowners {
  174. if err := s.shutdowners[i].Shutdown(); err != nil {
  175. errors = append(errors, err)
  176. failed = append(failed, s.shutdowners[i])
  177. }
  178. }
  179. s.shutdowners = failed
  180. return errors
  181. }
  182. // AddProcessor adds a new processor, which becomes available to the backend_config.process_stack option
  183. // Use to add your own custom processor when using backends as a package, or after importing an external
  184. // processor.
  185. func (s *Service) AddProcessor(name string, p processorConstructor) {
  186. // wrap in a constructor since we want to defer calling it
  187. var c processorConstructor
  188. c = func() Decorator {
  189. return p()
  190. }
  191. // add to our processors list
  192. processors[strings.ToLower(name)] = c
  193. }
  194. // extractConfig loads the backend config. It has already been unmarshalled
  195. // configData contains data from the main config file's "backend_config" value
  196. // configType is a Processor's specific config value.
  197. // The reason why using reflection is because we'll get a nice error message if the field is missing
  198. // the alternative solution would be to json.Marshal() and json.Unmarshal() however that will not give us any
  199. // error messages
  200. func (s *Service) ExtractConfig(configData BackendConfig, configType BaseConfig) (interface{}, error) {
  201. // Use reflection so that we can provide a nice error message
  202. v := reflect.ValueOf(configType).Elem() // so that we can set the values
  203. //m := reflect.ValueOf(configType).Elem()
  204. t := reflect.TypeOf(configType).Elem()
  205. typeOfT := v.Type()
  206. for i := 0; i < v.NumField(); i++ {
  207. f := v.Field(i)
  208. // read the tags of the config struct
  209. field_name := t.Field(i).Tag.Get("json")
  210. if len(field_name) > 0 {
  211. // parse the tag to
  212. // get the field name from struct tag
  213. split := strings.Split(field_name, ",")
  214. field_name = split[0]
  215. } else {
  216. // could have no tag
  217. // so use the reflected field name
  218. field_name = typeOfT.Field(i).Name
  219. }
  220. if f.Type().Name() == "int" {
  221. // in json, there is no int, only floats...
  222. if intVal, converted := configData[field_name].(float64); converted {
  223. v.Field(i).SetInt(int64(intVal))
  224. } else if intVal, converted := configData[field_name].(int); converted {
  225. v.Field(i).SetInt(int64(intVal))
  226. } else {
  227. return configType, convertError("property missing/invalid: '" + field_name + "' of expected type: " + f.Type().Name())
  228. }
  229. }
  230. if f.Type().Name() == "string" {
  231. if stringVal, converted := configData[field_name].(string); converted {
  232. v.Field(i).SetString(stringVal)
  233. } else {
  234. return configType, convertError("missing/invalid: '" + field_name + "' of type: " + f.Type().Name())
  235. }
  236. }
  237. if f.Type().Name() == "bool" {
  238. if boolVal, converted := configData[field_name].(bool); converted {
  239. v.Field(i).SetBool(boolVal)
  240. } else {
  241. return configType, convertError("missing/invalid: '" + field_name + "' of type: " + f.Type().Name())
  242. }
  243. }
  244. }
  245. return configType, nil
  246. }