backend.go 9.7 KB

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