/
executor.go
307 lines (258 loc) 路 7.8 KB
/
executor.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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
package imap
import (
"errors"
"fmt"
"regexp"
"strings"
"time"
"github.com/mitchellh/mapstructure"
"github.com/yesnault/go-imap/imap"
"github.com/ovh/venom"
"github.com/ovh/venom/executors"
)
// Name for test imap
const Name = "imap"
var imapLogMask = imap.LogNone
var imapSafeLogMask = imap.LogNone
// New returns a new Test Exec
func New() venom.Executor {
return &Executor{}
}
// Executor represents a Test Exec
type Executor struct {
IMAPHost string `json:"imaphost,omitempty" yaml:"imaphost,omitempty"`
IMAPPort string `json:"imapport,omitempty" yaml:"imapport,omitempty"`
IMAPUser string `json:"imapuser,omitempty" yaml:"imapuser,omitempty"`
IMAPPassword string `json:"imappassword,omitempty" yaml:"imappassword,omitempty"`
MBox string `json:"mbox,omitempty" yaml:"mbox,omitempty"`
MBoxOnSuccess string `json:"mboxonsuccess,omitempty" yaml:"mboxonsuccess,omitempty"`
DeleteOnSuccess bool `json:"deleteonsuccess,omitempty" yaml:"deleteonsuccess,omitempty"`
SearchFrom string `json:"searchfrom,omitempty" yaml:"searchfrom,omitempty"`
SearchTo string `json:"searchto,omitempty" yaml:"searchto,omitempty"`
SearchSubject string `json:"searchsubject,omitempty" yaml:"searchsubject,omitempty"`
SearchBody string `json:"searchbody,omitempty" yaml:"searchbody,omitempty"`
}
// Mail contains an analyzed mail
type Mail struct {
From string
To string
Subject string
UID uint32
Body string
}
// Result represents a step result
type Result struct {
Executor Executor `json:"executor,omitempty" yaml:"executor,omitempty"`
Err string `json:"error" yaml:"error"`
Subject string `json:"subject,omitempty" yaml:"subject,omitempty"`
Body string `json:"body,omitempty" yaml:"body,omitempty"`
TimeSeconds float64 `json:"timeSeconds,omitempty" yaml:"timeSeconds,omitempty"`
TimeHuman string `json:"timeHuman,omitempty" yaml:"timeHuman,omitempty"`
}
// ZeroValueResult return an empty implemtation of this executor result
func (Executor) ZeroValueResult() venom.ExecutorResult {
r, _ := executors.Dump(Result{})
return r
}
// GetDefaultAssertions return default assertions for type exec
func (Executor) GetDefaultAssertions() *venom.StepAssertions {
return &venom.StepAssertions{Assertions: []string{"result.err ShouldNotExist"}}
}
// Run execute TestStep of type exec
func (Executor) Run(ctx venom.TestCaseContext, l venom.Logger, step venom.TestStep, workdir string) (venom.ExecutorResult, error) {
var e Executor
if err := mapstructure.Decode(step, &e); err != nil {
return nil, err
}
start := time.Now()
result := Result{Executor: e}
find, errs := e.getMail(l)
if errs != nil {
result.Err = errs.Error()
}
if find != nil {
result.Subject = find.Subject
result.Body = find.Body
} else if result.Err == "" {
result.Err = "searched mail not found"
}
elapsed := time.Since(start)
result.TimeSeconds = elapsed.Seconds()
result.TimeHuman = fmt.Sprintf("%s", elapsed)
result.Executor.IMAPPassword = "****hidden****" // do not output password
return executors.Dump(result)
}
func (e *Executor) getMail(l venom.Logger) (*Mail, error) {
if e.SearchFrom == "" && e.SearchSubject == "" && e.SearchBody == "" && e.SearchTo == "" {
return nil, fmt.Errorf("You have to use one of searchfrom, searchto, searchsubject or subjectbody parameters.")
}
c, errc := connect(e.IMAPHost, e.IMAPPort, e.IMAPUser, e.IMAPPassword)
if errc != nil {
return nil, fmt.Errorf("Error while connecting:%s", errc.Error())
}
defer c.Logout(5 * time.Second)
var box string
if e.MBox == "" {
box = "INBOX"
} else {
box = e.MBox
}
count, err := queryCount(c, box)
if err != nil {
return nil, fmt.Errorf("Error while queryCount:%s", err.Error())
}
l.Debugf("count messages:%d", count)
if count == 0 {
return nil, errors.New("No message to fetch")
}
messages, err := fetch(c, box, count, l)
if err != nil {
return nil, fmt.Errorf("Error while feching messages:%s", err.Error())
}
defer c.Close(false)
for _, msg := range messages {
m, erre := extract(msg, l)
if erre != nil {
l.Warnf("Cannot extract the content of the mail: %s", erre)
continue
}
found, errs := e.isSearched(m)
if errs != nil {
return nil, errs
}
if found {
if e.DeleteOnSuccess {
l.Debugf("Delete message %s", m.UID)
if err := m.delete(c); err != nil {
return nil, err
}
} else if e.MBoxOnSuccess != "" {
l.Debugf("Move to %s", e.MBoxOnSuccess)
if err := m.move(c, e.MBoxOnSuccess); err != nil {
return nil, err
}
}
return m, nil
}
}
return nil, errors.New("Mail not found")
}
func (e *Executor) isSearched(m *Mail) (bool, error) {
if e.SearchFrom != "" {
ma, erra := regexp.MatchString(e.SearchFrom, m.From)
if erra != nil || !ma {
return false, erra
}
}
if e.SearchTo != "" {
mt, erra := regexp.MatchString(e.SearchTo, m.To)
if erra != nil || !mt {
return false, erra
}
}
if e.SearchSubject != "" {
mb, errb := regexp.MatchString(e.SearchSubject, m.Subject)
if errb != nil || !mb {
return false, errb
}
}
if e.SearchBody != "" {
mc, errc := regexp.MatchString(e.SearchBody, m.Body)
if errc != nil || !mc {
return false, errc
}
}
return true, nil
}
func (m *Mail) move(c *imap.Client, mbox string) error {
seq, _ := imap.NewSeqSet("")
seq.AddNum(m.UID)
if _, err := c.UIDMove(seq, mbox); err != nil {
return fmt.Errorf("Error while move msg to %s: %v", mbox, err.Error())
}
return nil
}
func (m *Mail) delete(c *imap.Client) error {
seq, _ := imap.NewSeqSet("")
seq.AddNum(m.UID)
if _, err := c.UIDStore(seq, "+FLAGS.SILENT", imap.NewFlagSet(`\Deleted`)); err != nil {
return fmt.Errorf("Error while deleting msg, err: %s", err.Error())
}
if _, err := c.Expunge(nil); err != nil {
return fmt.Errorf("Error while expunging messages: err: %s", err.Error())
}
return nil
}
func connect(host, port, imapUsername, imapPassword string) (*imap.Client, error) {
if !strings.Contains(host, ":") {
if port == "" {
port = ":993"
} else if port != "" && !strings.HasPrefix(port, ":") {
port = ":" + port
}
}
c, errd := imap.DialTLS(host+port, nil)
if errd != nil {
return nil, fmt.Errorf("Unable to dial: %s", errd)
}
if c.Caps["STARTTLS"] {
if _, err := check(c.StartTLS(nil)); err != nil {
return nil, fmt.Errorf("Unable to start TLS: %s\n", err)
}
}
c.SetLogMask(imapSafeLogMask)
if _, err := check(c.Login(imapUsername, imapPassword)); err != nil {
return nil, fmt.Errorf("Unable to login: %s", err)
}
c.SetLogMask(imapLogMask)
return c, nil
}
func fetch(c *imap.Client, box string, nb uint32, l venom.Logger) ([]imap.Response, error) {
l.Debugf("call Select")
if _, err := c.Select(box, false); err != nil {
l.Errorf("Error with select %s", err.Error())
return []imap.Response{}, err
}
seqset, _ := imap.NewSeqSet("1:*")
cmd, err := c.Fetch(seqset, "ENVELOPE", "RFC822.HEADER", "RFC822.TEXT", "UID")
if err != nil {
l.Errorf("Error with fetch:%s", err)
return []imap.Response{}, err
}
messages := []imap.Response{}
for cmd.InProgress() {
// Wait for the next response (no timeout)
c.Recv(-1)
// Process command data
for _, rsp := range cmd.Data {
messages = append(messages, *rsp)
}
cmd.Data = nil
c.Data = nil
}
l.Debugf("Nb messages fetch:%d", len(messages))
return messages, nil
}
func queryCount(imapClient *imap.Client, box string) (uint32, error) {
cmd, errc := check(imapClient.Status(box))
if errc != nil {
return 0, errc
}
var count uint32
for _, result := range cmd.Data {
mailboxStatus := result.MailboxStatus()
if mailboxStatus != nil {
count += mailboxStatus.Messages
}
}
return count, nil
}
func check(cmd *imap.Command, erri error) (*imap.Command, error) {
if erri != nil {
return nil, erri
}
if _, err := cmd.Result(imap.OK); err != nil {
return nil, err
}
return cmd, nil
}