processor.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. package chunk
  2. import (
  3. "errors"
  4. "net"
  5. "github.com/flashmob/go-guerrilla/backends"
  6. "github.com/flashmob/go-guerrilla/mail"
  7. "github.com/flashmob/go-guerrilla/mail/mimeparse"
  8. )
  9. // ----------------------------------------------------------------------------------
  10. // Processor Name: ChunkSaver
  11. // ----------------------------------------------------------------------------------
  12. // Description : Takes the stream and saves it in chunks. Chunks are split on the
  13. // : chunksaver_chunk_size config setting, and also at the end of MIME parts,
  14. // : and after a header. This allows for basic de-duplication: we can take a
  15. // : hash of each chunk, then check the database to see if we have it already.
  16. // : We don't need to write it to the database, but take the reference of the
  17. // : previously saved chunk and only increment the reference count.
  18. // : The rationale to put headers and bodies into separate chunks is
  19. // : due to headers often containing more unique data, while the bodies are
  20. // : often duplicated, especially for messages that are CC'd or forwarded
  21. // ----------------------------------------------------------------------------------
  22. // Requires : "mimeanalyzer" stream processor to be enabled before it
  23. // ----------------------------------------------------------------------------------
  24. // Config Options: chunksaver_chunk_size - maximum chunk size, in bytes
  25. // --------------:-------------------------------------------------------------------
  26. // Input : e.MimeParts Which is of type *mime.Parts, as populated by "mimeanalyzer"
  27. // ----------------------------------------------------------------------------------
  28. // Output : Messages are saved using the Storage interface
  29. // : See store_sql.go and store_sql.go as examples
  30. // ----------------------------------------------------------------------------------
  31. func init() {
  32. backends.Streamers["chunksaver"] = func() *backends.StreamDecorator {
  33. return Chunksaver()
  34. }
  35. }
  36. type Config struct {
  37. // ChunkMaxBytes controls the maximum buffer size for saving
  38. // 16KB default.
  39. ChunkMaxBytes int `json:"chunksaver_chunk_size,omitempty"`
  40. StorageEngine string `json:"chunksaver_storage_engine,omitempty"`
  41. CompressLevel int `json:"chunksaver_compress_level,omitempty"`
  42. }
  43. //const chunkMaxBytes = 1024 * 16 // 16Kb is the default, change using chunksaver_chunk_size config setting
  44. /**
  45. *
  46. * A chunk ends ether:
  47. * after xKB or after end of a part, or end of header
  48. *
  49. * - buffer first chunk
  50. * - if didn't receive first chunk for more than x bytes, save normally
  51. *
  52. */
  53. func Chunksaver() *backends.StreamDecorator {
  54. sd := &backends.StreamDecorator{}
  55. sd.Decorate =
  56. func(sp backends.StreamProcessor, a ...interface{}) backends.StreamProcessor {
  57. var (
  58. envelope *mail.Envelope
  59. chunkBuffer *ChunkingBufferMime
  60. msgPos uint
  61. database Storage
  62. written int64
  63. // just some headers from the first mime-part
  64. subject string
  65. to string
  66. from string
  67. progress int // tracks which mime parts were processed
  68. )
  69. var config *Config
  70. // optional dependency injection (you can pass your own instance of Storage or ChunkingBufferMime)
  71. for i := range a {
  72. if db, ok := a[i].(Storage); ok {
  73. database = db
  74. }
  75. if buff, ok := a[i].(*ChunkingBufferMime); ok {
  76. chunkBuffer = buff
  77. }
  78. }
  79. backends.Svc.AddInitializer(backends.InitializeWith(func(backendConfig backends.BackendConfig) error {
  80. configType := backends.BaseConfig(&Config{})
  81. bcfg, err := backends.Svc.ExtractConfig(backendConfig, configType)
  82. if err != nil {
  83. return err
  84. }
  85. config = bcfg.(*Config)
  86. if chunkBuffer == nil {
  87. chunkBuffer = NewChunkedBytesBufferMime()
  88. }
  89. // configure storage if none was injected
  90. if database == nil {
  91. if config.StorageEngine == "memory" {
  92. db := new(StoreMemory)
  93. db.CompressLevel = config.CompressLevel
  94. database = db
  95. } else {
  96. db := new(StoreSQL)
  97. database = db
  98. }
  99. }
  100. err = database.Initialize(backendConfig)
  101. if err != nil {
  102. return err
  103. }
  104. // configure the chunks buffer
  105. if config.ChunkMaxBytes > 0 {
  106. chunkBuffer.CapTo(config.ChunkMaxBytes)
  107. } else {
  108. chunkBuffer.CapTo(chunkMaxBytes)
  109. }
  110. chunkBuffer.SetDatabase(database)
  111. return nil
  112. }))
  113. backends.Svc.AddShutdowner(backends.ShutdownWith(func() error {
  114. err := database.Shutdown()
  115. return err
  116. }))
  117. var writeTo uint
  118. var pos int
  119. sd.Open = func(e *mail.Envelope) error {
  120. // create a new entry & grab the id
  121. written = 0
  122. progress = 0
  123. var ip net.IPAddr
  124. if ret := net.ParseIP(e.RemoteIP); ret != nil {
  125. ip = net.IPAddr{IP: ret}
  126. }
  127. mid, err := database.OpenMessage(
  128. e.MailFrom.String(),
  129. e.Helo,
  130. e.RcptTo[0].String(),
  131. ip,
  132. e.MailFrom.String(),
  133. e.TLS,
  134. e.TransportType,
  135. )
  136. if err != nil {
  137. return err
  138. }
  139. e.MessageID = mid
  140. envelope = e
  141. return nil
  142. }
  143. sd.Close = func() (err error) {
  144. err = chunkBuffer.Flush()
  145. if err != nil {
  146. // TODO we could delete the half saved message here
  147. return err
  148. }
  149. defer chunkBuffer.Reset()
  150. if envelope.MessageID > 0 {
  151. err = database.CloseMessage(
  152. envelope.MessageID,
  153. written,
  154. &chunkBuffer.Info,
  155. subject,
  156. envelope.QueuedId,
  157. to,
  158. from,
  159. )
  160. if err != nil {
  161. return err
  162. }
  163. }
  164. return nil
  165. }
  166. fillVars := func(parts *mimeparse.Parts, subject, to, from string) (string, string, string) {
  167. if len(*parts) > 0 {
  168. if subject == "" {
  169. if val, ok := (*parts)[0].Headers["Subject"]; ok {
  170. subject = val[0]
  171. }
  172. }
  173. if to == "" {
  174. if val, ok := (*parts)[0].Headers["To"]; ok {
  175. addr, err := mail.NewAddress(val[0])
  176. if err == nil {
  177. to = addr.String()
  178. }
  179. }
  180. }
  181. if from == "" {
  182. if val, ok := (*parts)[0].Headers["From"]; ok {
  183. addr, err := mail.NewAddress(val[0])
  184. if err == nil {
  185. from = addr.String()
  186. }
  187. }
  188. }
  189. }
  190. return subject, to, from
  191. }
  192. // end() triggers a buffer flush, at the end of a header or part-boundary
  193. end := func(part *mimeparse.Part, offset uint, p []byte, start uint) (int, error) {
  194. var err error
  195. var count int
  196. // write out any unwritten bytes
  197. writeTo = start - offset
  198. size := uint(len(p))
  199. if writeTo > size {
  200. writeTo = size
  201. }
  202. if writeTo > 0 {
  203. count, err = chunkBuffer.Write(p[pos:writeTo])
  204. written += int64(count)
  205. pos += count
  206. if err != nil {
  207. return count, err
  208. }
  209. } else {
  210. count = 0
  211. }
  212. err = chunkBuffer.Flush()
  213. if err != nil {
  214. return count, err
  215. }
  216. chunkBuffer.CurrentPart(part)
  217. return count, nil
  218. }
  219. return backends.StreamProcessWith(func(p []byte) (count int, err error) {
  220. pos = 0
  221. if envelope.MimeParts == nil {
  222. return count, errors.New("no message headers found")
  223. } else if len(*envelope.MimeParts) > 0 {
  224. parts := envelope.MimeParts
  225. subject, to, from = fillVars(parts, subject, to, from)
  226. offset := msgPos
  227. chunkBuffer.CurrentPart((*parts)[0])
  228. for i := progress; i < len(*parts); i++ {
  229. part := (*parts)[i]
  230. // break chunk on new part
  231. if part.StartingPos > 0 && part.StartingPos >= msgPos {
  232. count, err = end(part, offset, p, part.StartingPos)
  233. if err != nil {
  234. return count, err
  235. }
  236. // end of a part here
  237. //fmt.Println("->N --end of part ---")
  238. msgPos = part.StartingPos
  239. }
  240. // break chunk on header
  241. if part.StartingPosBody > 0 && part.StartingPosBody >= msgPos {
  242. count, err = end(part, offset, p, part.StartingPosBody)
  243. if err != nil {
  244. return count, err
  245. }
  246. // end of a header here
  247. //fmt.Println("->H --end of header --")
  248. msgPos += uint(count)
  249. }
  250. // if on the latest (last) part, and yet there is still data to be written out
  251. if len(*parts)-1 == i && len(p) > pos {
  252. count, _ = chunkBuffer.Write(p[pos:])
  253. written += int64(count)
  254. pos += count
  255. msgPos += uint(count)
  256. }
  257. // if there's no more data
  258. if pos >= len(p) {
  259. break
  260. }
  261. }
  262. if len(*parts) > 2 {
  263. progress = len(*parts) - 2 // skip to 2nd last part, assume previous parts are already processed
  264. }
  265. }
  266. return sp.Write(p)
  267. })
  268. }
  269. return sd
  270. }