p_sql.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. package backends
  2. import (
  3. "database/sql"
  4. "fmt"
  5. "strings"
  6. "github.com/flashmob/go-guerrilla/mail"
  7. "math/big"
  8. "net"
  9. "runtime/debug"
  10. "github.com/flashmob/go-guerrilla/response"
  11. )
  12. // ----------------------------------------------------------------------------------
  13. // Processor Name: sql
  14. // ----------------------------------------------------------------------------------
  15. // Description : Saves the e.Data (email data) and e.DeliveryHeader together in sql
  16. // : using the hash generated by the "hash" processor and stored in
  17. // : e.Hashes
  18. // ----------------------------------------------------------------------------------
  19. // Config Options: mail_table string - name of table for storing emails
  20. // : sql_driver string - database driver name, eg. mysql
  21. // : sql_dsn string - driver-specific data source name
  22. // : primary_mail_host string - primary host name
  23. // --------------:-------------------------------------------------------------------
  24. // Input : e.Data
  25. // : e.DeliveryHeader generated by ParseHeader() processor
  26. // : e.MailFrom
  27. // : e.Subject - generated by by ParseHeader() processor
  28. // ----------------------------------------------------------------------------------
  29. // Output : Sets e.QueuedId with the first item fromHashes[0]
  30. // ----------------------------------------------------------------------------------
  31. func init() {
  32. processors["sql"] = func() Decorator {
  33. return SQL()
  34. }
  35. }
  36. type SQLProcessorConfig struct {
  37. Table string `json:"mail_table"`
  38. Driver string `json:"sql_driver"`
  39. DSN string `json:"sql_dsn"`
  40. PrimaryHost string `json:"primary_mail_host"`
  41. }
  42. type SQLProcessor struct {
  43. cache stmtCache
  44. config *SQLProcessorConfig
  45. }
  46. func (s *SQLProcessor) connect() (*sql.DB, error) {
  47. var db *sql.DB
  48. var err error
  49. if db, err = sql.Open(s.config.Driver, s.config.DSN); err != nil {
  50. Log().Error("cannot open database: ", err)
  51. return nil, err
  52. }
  53. // do we have permission to access the table?
  54. _, err = db.Query("SELECT mail_id FROM " + s.config.Table + " LIMIT 1")
  55. if err != nil {
  56. return nil, err
  57. }
  58. return db, err
  59. }
  60. // prepares the sql query with the number of rows that can be batched with it
  61. func (s *SQLProcessor) prepareInsertQuery(rows int, db *sql.DB) *sql.Stmt {
  62. if rows == 0 {
  63. panic("rows argument cannot be 0")
  64. }
  65. if s.cache[rows-1] != nil {
  66. return s.cache[rows-1]
  67. }
  68. sqlstr := "INSERT INTO " + s.config.Table + " "
  69. sqlstr += "(`date`, `to`, `from`, `subject`, `body`, `mail`, `spam_score`, "
  70. sqlstr += "`hash`, `content_type`, `recipient`, `has_attach`, `ip_addr`, "
  71. sqlstr += "`return_path`, `is_tls`, `message_id`, `reply_to`, `sender`)"
  72. sqlstr += " VALUES "
  73. values := "(NOW(), ?, ?, ?, ? , ?, 0, ?, ?, ?, 0, ?, ?, ?, ?, ?, ?)"
  74. // add more rows
  75. comma := ""
  76. for i := 0; i < rows; i++ {
  77. sqlstr += comma + values
  78. if comma == "" {
  79. comma = ","
  80. }
  81. }
  82. stmt, sqlErr := db.Prepare(sqlstr)
  83. if sqlErr != nil {
  84. Log().WithError(sqlErr).Panic("failed while db.Prepare(INSERT...)")
  85. }
  86. // cache it
  87. s.cache[rows-1] = stmt
  88. return stmt
  89. }
  90. func (s *SQLProcessor) doQuery(c int, db *sql.DB, insertStmt *sql.Stmt, vals *[]interface{}) (execErr error) {
  91. defer func() {
  92. if r := recover(); r != nil {
  93. Log().Error("Recovered form panic:", r, string(debug.Stack()))
  94. sum := 0
  95. for _, v := range *vals {
  96. if str, ok := v.(string); ok {
  97. sum = sum + len(str)
  98. }
  99. }
  100. Log().Errorf("panic while inserting query [%s] size:%d, err %v", r, sum, execErr)
  101. panic("query failed")
  102. }
  103. }()
  104. // prepare the query used to insert when rows reaches batchMax
  105. insertStmt = s.prepareInsertQuery(c, db)
  106. _, execErr = insertStmt.Exec(*vals...)
  107. if execErr != nil {
  108. Log().WithError(execErr).Error("There was a problem the insert")
  109. }
  110. return
  111. }
  112. // for storing ip addresses in the ip_addr column
  113. func (s *SQLProcessor) ip2bint(ip string) *big.Int {
  114. bint := big.NewInt(0)
  115. addr := net.ParseIP(ip)
  116. if strings.Index(ip, "::") > 0 {
  117. bint.SetBytes(addr.To16())
  118. } else {
  119. bint.SetBytes(addr.To4())
  120. }
  121. return bint
  122. }
  123. func (s *SQLProcessor) fillAddressFromHeader(e *mail.Envelope, headerKey string) string {
  124. if v, ok := e.Header[headerKey]; ok {
  125. addr, err := mail.NewAddress(v[0])
  126. if err != nil {
  127. return ""
  128. }
  129. return addr.String()
  130. }
  131. return ""
  132. }
  133. func SQL() Decorator {
  134. var config *SQLProcessorConfig
  135. var vals []interface{}
  136. var db *sql.DB
  137. s := &SQLProcessor{}
  138. // open the database connection (it will also check if we can select the table)
  139. Svc.AddInitializer(InitializeWith(func(backendConfig BackendConfig) error {
  140. configType := BaseConfig(&SQLProcessorConfig{})
  141. bcfg, err := Svc.ExtractConfig(backendConfig, configType)
  142. if err != nil {
  143. return err
  144. }
  145. config = bcfg.(*SQLProcessorConfig)
  146. s.config = config
  147. db, err = s.connect()
  148. if err != nil {
  149. return err
  150. }
  151. return nil
  152. }))
  153. // shutdown will close the database connection
  154. Svc.AddShutdowner(ShutdownWith(func() error {
  155. if db != nil {
  156. return db.Close()
  157. }
  158. return nil
  159. }))
  160. return func(p Processor) Processor {
  161. return ProcessWith(func(e *mail.Envelope, task SelectTask) (Result, error) {
  162. if task == TaskSaveMail {
  163. var to, body string
  164. hash := ""
  165. if len(e.Hashes) > 0 {
  166. // if saved in redis, hash will be the redis key
  167. hash = e.Hashes[0]
  168. e.QueuedId = e.Hashes[0]
  169. }
  170. var co *compressor
  171. // a compressor was set by the Compress processor
  172. if c, ok := e.Values["zlib-compressor"]; ok {
  173. body = "gzip"
  174. co = c.(*compressor)
  175. }
  176. // was saved in redis by the Redis processor
  177. if _, ok := e.Values["redis"]; ok {
  178. body = "redis"
  179. }
  180. for i := range e.RcptTo {
  181. // use the To header, otherwise rcpt to
  182. to = trimToLimit(s.fillAddressFromHeader(e, "To"), 255)
  183. if to == "" {
  184. // trimToLimit(strings.TrimSpace(e.RcptTo[i].User)+"@"+config.PrimaryHost, 255)
  185. to = trimToLimit(strings.TrimSpace(e.RcptTo[i].String()), 255)
  186. }
  187. mid := trimToLimit(s.fillAddressFromHeader(e, "Message-Id"), 255)
  188. if mid == "" {
  189. mid = fmt.Sprintf("%s.%s@%s", hash, e.RcptTo[i].User, config.PrimaryHost)
  190. }
  191. // replyTo is the 'Reply-to' header, it may be blank
  192. replyTo := trimToLimit(s.fillAddressFromHeader(e, "Reply-To"), 255)
  193. // sender is the 'Sender' header, it may be blank
  194. sender := trimToLimit(s.fillAddressFromHeader(e, "Sender"), 255)
  195. recipient := trimToLimit(strings.TrimSpace(e.RcptTo[i].String()), 255)
  196. contentType := ""
  197. if v, ok := e.Header["Content-Type"]; ok {
  198. contentType = trimToLimit(v[0], 255)
  199. }
  200. // build the values for the query
  201. vals = []interface{}{} // clear the vals
  202. vals = append(vals,
  203. to,
  204. trimToLimit(e.MailFrom.String(), 255), // from
  205. trimToLimit(e.Subject, 255),
  206. body, // body describes how to interpret the data, eg 'redis' means stored in redis, and 'gzip' stored in mysql, using gzip compression
  207. )
  208. // `mail` column
  209. if body == "redis" {
  210. // data already saved in redis
  211. vals = append(vals, "")
  212. } else if co != nil {
  213. // use a compressor (automatically adds e.DeliveryHeader)
  214. vals = append(vals, co.String())
  215. } else {
  216. vals = append(vals, e.String())
  217. }
  218. vals = append(vals,
  219. hash, // hash (redis hash if saved in redis)
  220. contentType,
  221. recipient,
  222. s.ip2bint(e.RemoteIP).Bytes(), // ip_addr store as varbinary(16)
  223. trimToLimit(e.MailFrom.String(), 255), // return_path
  224. // is_tls
  225. e.TLS,
  226. // message_id
  227. mid,
  228. // reply_to
  229. replyTo,
  230. sender,
  231. )
  232. stmt := s.prepareInsertQuery(1, db)
  233. err := s.doQuery(1, db, stmt, &vals)
  234. if err != nil {
  235. return NewResult(fmt.Sprint("554 Error: could not save email")), StorageError
  236. }
  237. }
  238. // continue to the next Processor in the decorator chain
  239. return p.Process(e, task)
  240. } else if task == TaskValidateRcpt {
  241. // if you need to validate the e.Rcpt then change to:
  242. if len(e.RcptTo) > 0 {
  243. // since this is called each time a recipient is added
  244. // validate only the _last_ recipient that was appended
  245. last := e.RcptTo[len(e.RcptTo)-1]
  246. if len(last.User) > 255 {
  247. // return with an error
  248. return NewResult(response.Canned.FailRcptCmd), NoSuchUser
  249. }
  250. }
  251. // continue to the next processor
  252. return p.Process(e, task)
  253. } else {
  254. return p.Process(e, task)
  255. }
  256. })
  257. }
  258. }