processor.go 8.5 KB

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