-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
176 lines (152 loc) · 4.23 KB
/
server.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
package main
import (
"bytes"
"fmt"
"io/ioutil"
"net"
"net/mail"
"os"
"strings"
"time"
config "github.com/mailway-app/config"
"github.com/mailway-app/golib/rate"
"github.com/mhale/smtpd"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
dkim "github.com/toorop/go-dkim"
)
var (
unknownError = errors.New("unknown error")
rateError = errors.New("450 4.4.2 Temporarily rate limited; suspicious behavior")
rateAltSMTPLimiter = rate.NewRaterLimiter()
RATE_ALT_SMTP_LIMIT = 100
)
const (
// MAIL_STATUS_RECEIVED = 0
// MAIL_STATUS_PROCESSED = 1
MAIL_STATUS_DELIVERED = 2
// MAIL_STATUS_SPAM = 3
MAIL_STATUS_DELIVERY_ERROR = 4
)
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
type Address struct {
*mail.Address
domain string
}
func parseAddress(v string) (*Address, error) {
e, err := mail.ParseAddress(v)
if err != nil {
return nil, err
}
domain := strings.Split(e.Address, "@")[1]
return &Address{
e,
domain,
}, nil
}
func rcptHandler(remoteAddr net.Addr, from string, to string) bool {
_, err := parseAddress(to)
if err != nil {
log.Printf("rcptHandler: failed to parse to: %s\n", err)
return false
}
return true
}
func logger(remoteIP, verb, line string) {
log.Printf("%s %s %s\n", remoteIP, verb, line)
}
func Run(addr string, handler smtpd.Handler, rcpt smtpd.HandlerRcpt) error {
smtpd.Debug = true
srv := &smtpd.Server{
Addr: addr,
Handler: handler,
HandlerRcpt: rcpt,
Appname: "mailout",
Hostname: config.CurrConfig.InstanceHostname,
Timeout: 3 * time.Minute,
LogRead: logger,
LogWrite: logger,
}
log.Infof("Forwarding listening on %s", addr)
return srv.ListenAndServe()
}
func mailHandler(origin net.Addr, from string, to []string, in []byte) error {
for _, to := range to {
log.Printf("sending mail to %s", to)
msg, err := mail.ReadMessage(bytes.NewReader(in))
if err != nil {
log.Errorf("failed to parse email: %s", err)
return unknownError
}
uuid := msg.Header.Get("Mw-Int-Id")
domain := msg.Header.Get("Mw-Int-Domain")
file := fmt.Sprintf("%s/%s.eml", config.RUNTIME_LOCATION, uuid)
toAddress, err := parseAddress(to)
if err != nil {
log.Errorf("ParseAddress: %s", err)
return unknownError
}
smtpServer, err := findMX(toAddress.domain, 1)
if err != nil {
log.Errorf("could not findMX: %s", err)
return unknownError
}
serializedTo := strings.ReplaceAll(to, "@", "=")
returnPath := fmt.Sprintf("bounces+%s+%s@%s", uuid, serializedTo, domain)
outMail, err := prepareEmail(in)
if err != nil {
return errors.Wrap(err, "could not prepare email for sending")
}
signedData := outMail
_, err = os.Stat(config.CurrConfig.OutDKIMPath)
if err == nil {
options := dkim.NewSigOptions()
privateKey, err := ioutil.ReadFile(config.CurrConfig.OutDKIMPath)
check(err)
options.PrivateKey = privateKey
options.Domain = domain
options.Algo = "rsa-sha256"
options.Selector = "smtp"
options.SignatureExpireIn = 3600
options.Headers = []string{"Content-Type", "To", "Subject", "Date", "From", "MIME-Version", "Sender"}
options.AddSignatureTimestamp = true
options.Canonicalization = "relaxed/relaxed"
err = dkim.Sign(&signedData, options)
if err != nil {
log.Errorf("could not sign email: %s\n", err)
return unknownError
}
} else {
log.Warnf("couldn't sign email because key was not found at %s: %s", config.CurrConfig.OutDKIMPath, err)
}
err = sendMailToServer(
smtpServer, returnPath, from, to, signedData, outMail, domain, uuid)
if err != nil {
check(updateMailStatus(
config.CurrConfig.ServerJWT, domain, uuid, MAIL_STATUS_DELIVERY_ERROR))
return errors.Wrap(err, "could not send email")
}
check(updateMailStatus(config.CurrConfig.ServerJWT, domain, uuid, MAIL_STATUS_DELIVERED))
check(os.Remove(file))
}
return nil
}
func main() {
if err := config.Init(); err != nil {
log.Fatalf("failed to init config: %s", err)
}
if config.CurrConfig.InstanceHostname == "" {
log.Fatal("instance hostname is needed")
}
if v := config.CurrConfig.MailoutRateAltSMTPCount; v > 0 {
RATE_ALT_SMTP_LIMIT = v
}
addr := fmt.Sprintf("127.0.0.1:%d", config.CurrConfig.PortMailout)
if err := Run(addr, mailHandler, rcptHandler); err != nil {
log.Fatal(err)
}
}