-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
267 lines (240 loc) · 6.19 KB
/
main.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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
package main
import (
"bytes"
"crypto/tls"
"encoding/base64"
"encoding/json"
"errors"
"flag"
"fmt"
"github.com/coreos/go-systemd/daemon"
"github.com/mpdroog/beanstalkd" //"github.com/maxid/beanstalkd"
"github.com/mpdroog/smtpw/config"
"gopkg.in/gomail.v1"
"log"
"net/mail"
"os"
"strings"
"time"
)
const ERR_WAIT_SEC = 5
var errTimedOut = errors.New("timed out")
var verbose bool
var readonly bool
var debug bool
var hostname string
var L *log.Logger
func proc(m config.Email, skipOne bool) error {
conf, ok := config.C.From[m.From]
if !ok {
return errors.New("From does not exist: " + m.From)
}
host := conf.Hostname
if host == "" {
host = hostname
}
msg := gomail.NewMessage()
msg.SetHeader("Message-ID", fmt.Sprintf("<%s@%s>", RandText(32), host))
msg.SetHeader("X-Mailer", "smtpw")
msg.SetHeader("X-Priority", "3")
if conf.Bounce == nil {
msg.SetHeader("From", conf.Display+" <"+conf.From+">")
} else {
// Set bounce handling
// From receives bounces
// Human-clients send to Reply-To
msg.SetHeader("From", fmt.Sprintf("%s <%s>", conf.Display, *conf.Bounce))
msg.SetHeader("Reply-To", fmt.Sprintf("%s <%s>", conf.Display, conf.From))
}
bcc := conf.Bcc
if conf.AllowBCC {
bcc = append(bcc, m.BCC...)
}
msg.SetHeader("To", m.To...)
msg.SetHeader("Bcc", bcc...)
msg.SetHeader("Subject", m.Subject)
msg.SetBody("text/plain", m.Text)
if len(m.Html) > 0 {
msg.AddAlternative("text/html", m.Html)
}
for name, embed := range m.HtmlEmbed {
raw, e := base64.StdEncoding.DecodeString(embed)
if e != nil {
if skipOne {
L.Printf("WARN: HtmlEmbed: " + name + " is not base64!\n")
return nil
}
return errors.New("HtmlEmbed: " + name + " is not base64!")
}
if !strings.Contains(m.Html, fmt.Sprintf("cid:"+name)) {
if skipOne {
L.Printf("WARN: HtmlEmbed: " + name + " is not used in the HTML!")
return nil
}
return errors.New("HtmlEmbed: " + name + " is not used in the HTML!")
}
msg.Embed(gomail.CreateFile(name, raw))
}
for name, attachment := range m.Attachments {
raw, e := base64.StdEncoding.DecodeString(attachment)
if e != nil {
if skipOne {
L.Printf("WARN: Attachment: " + name + " is not base64!")
return nil
}
return errors.New("Attachment: " + name + " is not base64!")
}
msg.Attach(gomail.CreateFile(name, raw))
}
if readonly {
L.Printf("From: %s <%s>\n", conf.Display, conf.From)
L.Printf("To: %v\n", m.To)
L.Printf("Bcc: %v\n", conf.Bcc)
L.Printf("Subject: %s\n", m.Subject)
L.Printf("\ntext/plain\n")
L.Printf(m.Text)
L.Printf("\ntext/html\n")
L.Printf(m.Html)
L.Printf("\n\n")
return nil
}
cfg := gomail.SetTLSConfig(&tls.Config{ServerName: conf.Host})
if conf.Insecure {
cfg = gomail.SetTLSConfig(&tls.Config{InsecureSkipVerify: true})
}
auth := LoginAuth(conf.User, conf.Pass)
mailer := gomail.NewCustomMailer(fmt.Sprintf("%s:%d", conf.Host, conf.Port), auth, cfg)
return mailer.Send(msg)
}
func connect() (*beanstalkd.BeanstalkdClient, error) {
queue, e := beanstalkd.Dial(config.C.Beanstalk)
if e != nil {
return nil, e
}
// Only listen to email queue.
queue.Use("email")
if _, e := queue.Watch("email"); e != nil {
return nil, e
}
queue.Ignore("default")
return queue, nil
}
func main() {
var (
configPath string
skipOne bool
)
L = log.New(os.Stdout, "", log.LstdFlags)
flag.BoolVar(&verbose, "v", false, "Verbose-mode")
flag.BoolVar(&debug, "d", false, "Debug-mode")
flag.BoolVar(&skipOne, "s", false, "Delete e-mail on deverr")
flag.BoolVar(&readonly, "r", false, "Don't email but flush to stdout")
flag.StringVar(&configPath, "c", "./config.json", "Path to config.json")
flag.Parse()
if e := config.Init(configPath); e != nil {
panic(e)
}
if verbose {
L.Printf("%+v\n", config.C)
}
// TODO: Test config before starting?
queue, e := connect()
if e != nil {
panic(e)
}
hostname, e = os.Hostname()
if e != nil {
panic(e)
}
if verbose {
L.Printf("SMTPw(%s) email-tube (ignoring default)\n", hostname)
}
if readonly {
L.Printf("!! ReadOnly mode !!\n")
}
sent, e := daemon.SdNotify(false, "READY=1")
if e != nil {
panic(e)
}
if !sent {
L.Printf("SystemD notify NOT sent\n")
}
for {
job, e := queue.Reserve(15 * 60) //15min timeout
if e != nil {
if e.Error() == errTimedOut.Error() {
// Reserve timeout
continue
}
L.Printf("Beanstalkd err: %s\n", e.Error())
time.Sleep(time.Second * ERR_WAIT_SEC)
if strings.HasSuffix(e.Error(), "broken pipe") {
// Beanstalkd down, reconnect!
q, e := connect()
if e != nil {
L.Printf("Reconnect err: %s\n", e.Error())
}
if q != nil {
queue = q
}
}
continue
}
// Hackfix. Get rid of array when empty to prevent parsing issues here
if bytes.Contains(job.Data, []byte(`,"attachments":[]`)) {
job.Data = bytes.Replace(job.Data, []byte(`,"attachments":[]`), []byte(``), 1)
}
if debug {
L.Printf("JSON:\n%s\n", string(job.Data))
}
// Parse
var m config.Email
if e := json.Unmarshal(job.Data, &m); e != nil {
// Broken JSON
if skipOne {
L.Printf("WARN: Skip job as JSON is invalid\n")
queue.Delete(job.Id)
skipOne = false
continue
}
// Ignore decode trouble
L.Printf("CRIT: Invalid JSON received (msg=%s)\n", e.Error())
continue
}
if verbose {
L.Printf("Email (job=%d email=%s subject=%s)\n", job.Id, m.To[0], m.Subject)
}
ok := true
for _, addr := range m.To {
if _, e := mail.ParseAddress(addr); e != nil {
L.Printf("WARN: Job buried, invalid email=%s (msg=%s)\n", addr, e.Error())
ok = false
break
}
}
if !ok {
// email(s) invalid, bury job
queue.Bury(job.Id, 1)
continue
}
if e := proc(m, skipOne); e != nil {
// 501 Syntax error in parameters or arguments
// http://www.greenend.org.uk/rjk/tech/smtpreplies.html
if strings.HasPrefix(e.Error(), "501 ") {
L.Printf("WARN: Job buried, invalid email address(es)? (msg=%s)\n", e.Error())
queue.Bury(job.Id, 1)
continue
}
// TODO: Isolate deverr from senderr
// Processing trouble?
L.Printf("WARN: Failed sending, retry in 20sec (msg=%s)\n", e.Error())
time.Sleep(time.Second * 20)
continue
}
queue.Delete(job.Id)
if verbose {
L.Printf("Finished job %d", job.Id)
}
}
queue.Quit()
}