p_mysql.go 9.1 KB

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