backend.go 8.2 KB

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