backend.go 9.6 KB

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