backend.go 8.7 KB

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