backend.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. package backends
  2. import (
  3. "fmt"
  4. "github.com/flashmob/go-guerrilla/log"
  5. "github.com/flashmob/go-guerrilla/mail"
  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(*mail.Envelope) Result
  30. ValidateRcpt(e *mail.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 InitializeWith func(backendConfig BackendConfig) error
  77. type ShutdownWith func() error
  78. // Satisfy ProcessorInitializer interface
  79. // So we can now pass an anonymous function that implements ProcessorInitializer
  80. func (i InitializeWith) Initialize(backendConfig BackendConfig) error {
  81. // delegate to the anonymous function
  82. return i(backendConfig)
  83. }
  84. // satisfy ProcessorShutdowner interface, same concept as InitializeWith type
  85. func (s ShutdownWith) 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 convertError(name string) error {
  116. return fmt.Errorf("failed to load backend config (%s)", name)
  117. }
  118. func GetBackend() Backend {
  119. return b
  120. }
  121. type Service struct {
  122. initializers []ProcessorInitializer
  123. shutdowners []ProcessorShutdowner
  124. sync.Mutex
  125. mainlog atomic.Value
  126. }
  127. // Get loads the log.logger in an atomic operation. Returns a stderr logger if not able to load
  128. func Log() log.Logger {
  129. if v, ok := Svc.mainlog.Load().(log.Logger); ok {
  130. return v
  131. }
  132. l, _ := log.GetLogger(log.OutputStderr.String())
  133. return l
  134. }
  135. func (s *Service) StoreMainlog(l log.Logger) {
  136. s.mainlog.Store(l)
  137. }
  138. // AddInitializer adds a function that implements ProcessorShutdowner to be called when initializing
  139. func (s *Service) AddInitializer(i ProcessorInitializer) {
  140. s.Lock()
  141. defer s.Unlock()
  142. s.initializers = append(s.initializers, i)
  143. }
  144. // AddShutdowner adds a function that implements ProcessorShutdowner to be called when shutting down
  145. func (s *Service) AddShutdowner(sh ProcessorShutdowner) {
  146. s.Lock()
  147. defer s.Unlock()
  148. s.shutdowners = append(s.shutdowners, sh)
  149. }
  150. // Initialize initializes all the processors one-by-one and returns any errors.
  151. // Subsequent calls to Initialize will not call the initializer again unless it failed on the previous call
  152. // so Initialize may be called again to retry after getting errors
  153. func (s *Service) initialize(backend BackendConfig) Errors {
  154. s.Lock()
  155. defer s.Unlock()
  156. var errors Errors
  157. failed := make([]ProcessorInitializer, 0)
  158. for i := range s.initializers {
  159. if err := s.initializers[i].Initialize(backend); err != nil {
  160. errors = append(errors, err)
  161. failed = append(failed, s.initializers[i])
  162. }
  163. }
  164. // keep only the failed initializers
  165. s.initializers = failed
  166. return errors
  167. }
  168. // Shutdown shuts down all the processors by calling their shutdowners (if any)
  169. // Subsequent calls to Shutdown will not call the shutdowners again unless it failed on the previous call
  170. // so Shutdown may be called again to retry after getting errors
  171. func (s *Service) shutdown() Errors {
  172. s.Lock()
  173. defer s.Unlock()
  174. var errors Errors
  175. failed := make([]ProcessorShutdowner, 0)
  176. for i := range s.shutdowners {
  177. if err := s.shutdowners[i].Shutdown(); err != nil {
  178. errors = append(errors, err)
  179. failed = append(failed, s.shutdowners[i])
  180. }
  181. }
  182. s.shutdowners = failed
  183. return errors
  184. }
  185. // AddProcessor adds a new processor, which becomes available to the backend_config.process_stack option
  186. // Use to add your own custom processor when using backends as a package, or after importing an external
  187. // processor.
  188. func (s *Service) AddProcessor(name string, p processorConstructor) {
  189. // wrap in a constructor since we want to defer calling it
  190. var c processorConstructor
  191. c = func() Decorator {
  192. return p()
  193. }
  194. // add to our processors list
  195. processors[strings.ToLower(name)] = c
  196. }
  197. // extractConfig loads the backend config. It has already been unmarshalled
  198. // configData contains data from the main config file's "backend_config" value
  199. // configType is a Processor's specific config value.
  200. // The reason why using reflection is because we'll get a nice error message if the field is missing
  201. // the alternative solution would be to json.Marshal() and json.Unmarshal() however that will not give us any
  202. // error messages
  203. func (s *Service) ExtractConfig(configData BackendConfig, configType BaseConfig) (interface{}, error) {
  204. // Use reflection so that we can provide a nice error message
  205. v := reflect.ValueOf(configType).Elem() // so that we can set the values
  206. //m := reflect.ValueOf(configType).Elem()
  207. t := reflect.TypeOf(configType).Elem()
  208. typeOfT := v.Type()
  209. for i := 0; i < v.NumField(); i++ {
  210. f := v.Field(i)
  211. // read the tags of the config struct
  212. field_name := t.Field(i).Tag.Get("json")
  213. omitempty := false
  214. if len(field_name) > 0 {
  215. // parse the tag to
  216. // get the field name from struct tag
  217. split := strings.Split(field_name, ",")
  218. field_name = split[0]
  219. if len(split) > 1 {
  220. if split[1] == "omitempty" {
  221. omitempty = true
  222. }
  223. }
  224. } else {
  225. // could have no tag
  226. // so use the reflected field name
  227. field_name = typeOfT.Field(i).Name
  228. }
  229. if f.Type().Name() == "int" {
  230. // in json, there is no int, only floats...
  231. if intVal, converted := configData[field_name].(float64); converted {
  232. v.Field(i).SetInt(int64(intVal))
  233. } else if intVal, converted := configData[field_name].(int); converted {
  234. v.Field(i).SetInt(int64(intVal))
  235. } else if !omitempty {
  236. return configType, convertError("property missing/invalid: '" + field_name + "' of expected type: " + f.Type().Name())
  237. }
  238. }
  239. if f.Type().Name() == "string" {
  240. if stringVal, converted := configData[field_name].(string); converted {
  241. v.Field(i).SetString(stringVal)
  242. } else if !omitempty {
  243. return configType, convertError("missing/invalid: '" + field_name + "' of type: " + f.Type().Name())
  244. }
  245. }
  246. if f.Type().Name() == "bool" {
  247. if boolVal, converted := configData[field_name].(bool); converted {
  248. v.Field(i).SetBool(boolVal)
  249. } else if !omitempty {
  250. return configType, convertError("missing/invalid: '" + field_name + "' of type: " + f.Type().Name())
  251. }
  252. }
  253. }
  254. return configType, nil
  255. }