-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproxy.go
107 lines (91 loc) · 2.08 KB
/
proxy.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package main
import (
"bytes"
"errors"
"io"
"io/ioutil"
"log"
"os"
"github.com/emersion/go-sasl"
"github.com/emersion/go-smtp"
)
// The Backend implements SMTP server methods.
type Backend struct {
upstream string
}
func (b *Backend) init() error {
upstream := os.Getenv("SMTP_PROXY_UPSTREAM")
if upstream == "" {
return errors.New("not found smtp upstream in envs")
}
b.upstream = upstream
return nil
}
func (b *Backend) NewSession(conn *smtp.Conn) (smtp.Session, error) {
return &Session{
clientIP: conn.Conn().RemoteAddr().String(),
upstream: b.upstream,
}, nil
}
// A Session is returned after EHLO.
type Session struct {
clientIP string
upstream string
user string
password string
from string
to string
data []byte
}
func (s *Session) AuthPlain(username, password string) error {
s.user = username
s.password = password
return nil
}
func (s *Session) Mail(from string, opts *smtp.MailOptions) error {
s.from = from
return nil
}
func (s *Session) Rcpt(to string) error {
s.to = to
return nil
}
func (s *Session) Data(r io.Reader) error {
b, err := ioutil.ReadAll(r)
if err != nil {
log.Printf("failed to read data: %s, %s, %s (%s)", s.upstream, s.from, s.to, err)
return err
}
s.data = b
return nil
}
func (s *Session) Reset() {
}
func (s *Session) Logout() error {
defer s.reset()
if s.user == "" || s.password == "" || s.from == "" || s.to == "" || s.data == nil {
log.Printf("not send mail: %s, \"%s\", \"%s\" (empty)", s.upstream, s.from, s.to)
return nil
}
if err := s.toUpstream(); err != nil {
log.Printf("failed to send mail: %s, %s, %s (%s)", s.upstream, s.from, s.to, err)
return err
}
return nil
}
func (s *Session) reset() {
s.user = ""
s.password = ""
s.from = ""
s.to = ""
s.data = nil
}
func (s *Session) toUpstream() error {
auth := sasl.NewPlainClient("", s.user, s.password)
rd := bytes.NewReader(s.data)
if err := smtp.SendMail(s.upstream, auth, s.from, []string{s.to}, rd); err != nil {
return err
}
log.Printf("client: %s, send mail: %s, %s (%d)", s.clientIP, s.from, s.to, len(s.data))
return nil
}