-
Notifications
You must be signed in to change notification settings - Fork 1
/
fprot.go
618 lines (520 loc) · 12.5 KB
/
fprot.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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
// Copyright (C) 2018-2021 Andrew Colin Kissa <[email protected]>
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at http://mozilla.org/MPL/2.0/.
/*
Package fprot Golang F-Prot client
Fprot - Golang F-Prot client
*/
package fprot
import (
"bytes"
"context"
"fmt"
"io"
"net"
"net/textproto"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
"time"
)
const (
defaultTimeout = 15 * time.Second
defaultSleep = 1 * time.Second
defaultCmdTimeout = 1 * time.Minute
chunkSize = 1024
genericErr = "ERROR: %s"
invalidRespErr = "Invalid server response: %s"
pathNotDirErr = "The path: %s is not a directory"
noSizeErr = "The content length could not be determined"
)
const (
// NoMatch 0 No signature was matched
NoMatch StatusCode = 0
// Infected 1 Atleast one virus-infected object was found
Infected StatusCode = 1
// HeuristicMatch 2 Atleast one suspicious (heuristic match) object was found
HeuristicMatch StatusCode = 2
// UserError 4 Interrupted by user
UserError StatusCode = 4
// RestrictionError 8 Scan restriction caused scan to skip files
RestrictionError StatusCode = 8
// SystemError 16 Platform error
SystemError StatusCode = 16
// InternalError 32 Internal engine error
InternalError StatusCode = 32
// SkipError 64 Atleast one object was not scanned
SkipError StatusCode = 64
// DisinfectError 128 Atleast one object was disinfected
DisinfectError StatusCode = 128
)
const (
// Help is the HELP command
Help Command = iota + 1
// ScanFile is the SCAN FILE command
ScanFile
// ScanStream is the SCAN STREAM command
ScanStream
// Queue is the QUEUE command
Queue
// ScanQueue is the SCAN command
ScanQueue
// Quit is the QUIT command
Quit
)
var (
// ZeroTime holds the zero value of time
ZeroTime time.Time
helpRe = regexp.MustCompile(`^FPSCAND:(?P<version>\S+)\s*ENGINE:(?P<engine>\S+)\s*PROTOCOL:(?P<protocol>\S+)\s*SIGNATURE:(?P<sig>\S+)\s*UPTIME:(?P<uptime>\S+)$`)
responseRe = regexp.MustCompile(`^(?P<statuscode>[0-9]+)\s<(?P<status>[^:]+)(?::\s+(?P<signature>.+?))?>\s?(?P<filename>.+?)?(?:->(?P<aname>.*))?$`)
)
type readerWithLen interface {
Len() int
}
// StatusCode represents the returned status code
type StatusCode int
func (c StatusCode) String() (s string) {
switch c {
case NoMatch:
s = "No signature was matched"
case Infected:
s = "Atleast one virus-infected object was found"
case HeuristicMatch:
s = "Atleast one suspicious (heuristic match) object was found"
case UserError:
s = "Scanning interrupted by user"
case RestrictionError:
s = "Scan restriction caused scan to skip files"
case SystemError:
s = "Platform error"
case InternalError:
s = "Internal Engine error"
case SkipError:
s = "Atleast one object was not scanned"
case DisinfectError:
s = "Atleast one object was disinfected"
default:
s = ""
}
return
}
// A Command represents a Fprot Command
type Command int
func (c Command) String() (s string) {
n := [...]string{
"",
"HELP",
"SCAN FILE",
"SCAN STREAM",
"QUEUE",
"SCAN",
"QUIT",
}
if c < Help || c > Quit {
s = ""
return
}
s = n[c]
return
}
// Info is the server information
type Info struct {
Version string
Engine string
Protocol string
Signature string
Uptime string
}
// Response is the response from the server
type Response struct {
Filename string
ArchiveItem string
Signature string
Status string
StatusCode StatusCode
Infected bool
Raw string
}
// A Client represents a Fprot client.
type Client struct {
address string
connTimeout time.Duration
connRetries int
connSleep time.Duration
cmdTimeout time.Duration
tc *textproto.Conn
m sync.Mutex
conn net.Conn
}
// SetConnTimeout sets the connection timeout
func (c *Client) SetConnTimeout(t time.Duration) {
if t > 0 {
c.connTimeout = t
}
}
// SetCmdTimeout sets the cmd timeout
func (c *Client) SetCmdTimeout(t time.Duration) {
if t > 0 {
c.cmdTimeout = t
}
}
// SetConnRetries sets the number of times
// connection is retried
func (c *Client) SetConnRetries(s int) {
if s < 0 {
s = 0
}
c.connRetries = s
}
// SetConnSleep sets the connection retry sleep
// duration in seconds
func (c *Client) SetConnSleep(s time.Duration) {
if s > 0 {
c.connSleep = s
}
}
// Info returns server information
func (c *Client) Info(ctx context.Context) (i Info, err error) {
var s string
if s, err = c.basicCmd(ctx, Help); err != nil {
return
}
ms := helpRe.FindStringSubmatch(s)
if ms == nil {
err = fmt.Errorf(invalidRespErr, s)
return
}
i = Info{
Version: string(ms[1]),
Engine: string(ms[2]),
Protocol: string(ms[3]),
Signature: string(ms[4]),
Uptime: string(ms[5]),
}
return
}
// Close closes the server connection
func (c *Client) Close(ctx context.Context) (err error) {
_, err = c.basicCmd(ctx, Quit)
c.tc.Close()
return
}
// ScanFile submits a single file for scanning
func (c *Client) ScanFile(ctx context.Context, f string) (r []*Response, err error) {
r, err = c.fileCmd(ctx, ScanFile, f)
return
}
// ScanFiles submits multiple files for scanning
func (c *Client) ScanFiles(ctx context.Context, f ...string) (r []*Response, err error) {
r, err = c.fileCmd(ctx, ScanFile, f...)
return
}
// ScanStream submits a stream for scanning
func (c *Client) ScanStream(ctx context.Context, f ...string) (r []*Response, err error) {
r, err = c.fileCmd(ctx, ScanStream, f...)
return
}
// ScanReader submits an io reader via a stream for scanning
func (c *Client) ScanReader(ctx context.Context, i io.Reader) (r []*Response, err error) {
r, err = c.readerCmd(ctx, i)
return
}
// ScanDir submits a directory for scanning
func (c *Client) ScanDir(ctx context.Context, d string) (r []*Response, err error) {
var fl []string
if fl, err = getFiles(d); err != nil {
return
}
r, err = c.fileCmd(ctx, ScanFile, fl...)
return
}
// ScanDirStream submits a directory for scanning as streams
func (c *Client) ScanDirStream(ctx context.Context, d string) (r []*Response, err error) {
var fl []string
if fl, err = getFiles(d); err != nil {
return
}
r, err = c.fileCmd(ctx, ScanStream, fl...)
return
}
func (c *Client) dial(ctx context.Context) (conn net.Conn, err error) {
d := &net.Dialer{
Timeout: c.connTimeout,
}
for i := 0; i <= c.connRetries; i++ {
conn, err = d.Dial("tcp4", c.address)
if e, ok := err.(net.Error); ok && e.Timeout() {
time.Sleep(c.connSleep)
continue
}
break
}
return
}
func (c *Client) basicCmd(ctx context.Context, cmd Command) (r string, err error) {
var id uint
c.m.Lock()
if c.tc == nil {
if c.conn, err = c.dial(ctx); err != nil {
c.m.Unlock()
return
}
c.tc = textproto.NewConn(c.conn)
}
c.m.Unlock()
defer c.conn.SetDeadline(ZeroTime)
c.conn.SetDeadline(time.Now().Add(c.cmdTimeout))
if id, err = c.tc.Cmd("%s", cmd); err != nil {
return
}
c.tc.StartResponse(id)
defer c.tc.EndResponse(id)
if cmd == Quit {
return
}
c.conn.SetDeadline(time.Now().Add(c.cmdTimeout))
if r, err = c.tc.ReadLine(); err != nil {
return
}
if cmd == Help {
c.conn.SetDeadline(time.Now().Add(c.cmdTimeout))
if _, err = c.tc.ReadLine(); err != nil {
return
}
}
return
}
func (c *Client) fileCmd(ctx context.Context, cmd Command, p ...string) (r []*Response, err error) {
var n int
n = len(p)
if n == 0 || p[0] == "" {
err = fmt.Errorf("Atleast one path to scan is required")
return
}
c.m.Lock()
if c.tc == nil {
if c.conn, err = c.dial(ctx); err != nil {
c.m.Unlock()
return
}
c.tc = textproto.NewConn(c.conn)
}
c.m.Unlock()
defer c.conn.SetDeadline(ZeroTime)
id := c.tc.Next()
c.tc.StartRequest(id)
if cmd == ScanStream {
if err = c.streamScan(n, p...); err != nil {
c.tc.EndRequest(id)
return
}
} else if cmd == ScanFile {
if err = c.fileScan(n, p...); err != nil {
c.tc.EndRequest(id)
return
}
}
c.tc.W.Flush()
c.tc.EndRequest(id)
c.tc.StartResponse(id)
defer c.tc.EndResponse(id)
r, err = c.processResponse(n)
return
}
func (c *Client) fileScan(n int, p ...string) (err error) {
if n > 1 {
c.conn.SetDeadline(time.Now().Add(c.cmdTimeout))
if err = c.tc.PrintfLine("%s", Queue); err != nil {
return
}
for _, fn := range p {
c.conn.SetDeadline(time.Now().Add(c.cmdTimeout))
if err = c.tc.PrintfLine("%s %s", ScanFile, fn); err != nil {
return
}
}
c.conn.SetDeadline(time.Now().Add(c.cmdTimeout))
if err = c.tc.PrintfLine("%s", ScanQueue); err != nil {
return
}
} else {
c.conn.SetDeadline(time.Now().Add(c.cmdTimeout))
if err = c.tc.PrintfLine("%s %s", ScanFile, p[0]); err != nil {
return
}
}
return
}
func (c *Client) streamScan(n int, p ...string) (err error) {
if n > 1 {
c.conn.SetDeadline(time.Now().Add(c.cmdTimeout))
if err = c.tc.PrintfLine("%s", Queue); err != nil {
return
}
for _, fn := range p {
if err = c.streamCmd(fn); err != nil {
return
}
}
c.conn.SetDeadline(time.Now().Add(c.cmdTimeout))
if err = c.tc.PrintfLine("%s", ScanQueue); err != nil {
return
}
} else {
if err = c.streamCmd(p[0]); err != nil {
return
}
}
return
}
func (c *Client) readerCmd(ctx context.Context, i io.Reader) (r []*Response, err error) {
var clen int64
var stat os.FileInfo
c.m.Lock()
if c.tc == nil {
if c.conn, err = c.dial(ctx); err != nil {
c.m.Unlock()
return
}
c.tc = textproto.NewConn(c.conn)
}
c.m.Unlock()
defer c.conn.SetDeadline(ZeroTime)
switch v := i.(type) {
case readerWithLen:
clen = int64(v.Len())
case *os.File:
stat, err = v.Stat()
if err != nil {
return
}
clen = stat.Size()
default:
err = fmt.Errorf(noSizeErr)
return
}
id := c.tc.Next()
c.tc.StartRequest(id)
c.conn.SetDeadline(time.Now().Add(c.cmdTimeout))
if err = c.tc.PrintfLine("%s stream SIZE %d", ScanStream, clen); err != nil {
c.tc.EndRequest(id)
return
}
c.conn.SetDeadline(time.Now().Add(c.cmdTimeout))
if _, err = io.Copy(c.tc.Writer.W, i); err != nil {
c.tc.EndRequest(id)
return
}
c.tc.W.Flush()
c.tc.EndRequest(id)
c.tc.StartResponse(id)
defer c.tc.EndResponse(id)
r, err = c.processResponse(1)
return
}
func (c *Client) streamCmd(fn string) (err error) {
var f *os.File
var stat os.FileInfo
if f, err = os.Open(fn); err != nil {
return
}
defer f.Close()
if stat, err = f.Stat(); err != nil {
return
}
c.conn.SetDeadline(time.Now().Add(c.cmdTimeout))
if err = c.tc.PrintfLine("%s %s SIZE %d", ScanStream, fn, stat.Size()); err != nil {
return
}
c.conn.SetDeadline(time.Now().Add(c.cmdTimeout))
if _, err = io.Copy(c.tc.Writer.W, f); err != nil {
return
}
c.tc.W.Flush()
return
}
func (c *Client) processResponse(n int) (r []*Response, err error) {
var sc int
var gerr error
var lineb []byte
for num := 0; num < n; num++ {
c.conn.SetDeadline(time.Now().Add(c.cmdTimeout))
lineb, err = c.tc.R.ReadBytes('\n')
if err != nil {
if err == io.EOF {
err = nil
break
}
return
}
mb := responseRe.FindSubmatch(bytes.TrimRight(lineb, "\n"))
if mb == nil {
err = fmt.Errorf(invalidRespErr, lineb)
break
}
rs := Response{}
sc, err = strconv.Atoi(string(mb[1]))
if err != nil {
return
}
rs.StatusCode = StatusCode(sc)
rs.Status = string(mb[2])
rs.Signature = string(mb[3])
rs.Filename = string(mb[4])
rs.ArchiveItem = string(mb[5])
rs.Raw = string(mb[0])
r = append(r, &rs)
if rs.StatusCode&(UserError|RestrictionError|SystemError|InternalError|SkipError|DisinfectError) != 0 {
if gerr == nil {
gerr = fmt.Errorf(genericErr, rs.Status)
}
}
if rs.StatusCode&(Infected|DisinfectError|HeuristicMatch) != 0 {
rs.Infected = true
}
}
err = gerr
return
}
// NewClient creates and returns a new instance of Client
func NewClient(address string) (c *Client, err error) {
if address == "" {
address = "127.0.0.1:10200"
} else {
if !strings.Contains(address, ":") || strings.Count(address, ":") > 1 {
err = fmt.Errorf("The supplied address is invalid")
return
}
}
c = &Client{
address: address,
connTimeout: defaultTimeout,
connSleep: defaultSleep,
cmdTimeout: defaultCmdTimeout,
}
return
}
func getFiles(d string) (fl []string, err error) {
var stat os.FileInfo
if stat, err = os.Stat(d); os.IsNotExist(err) {
return
}
if !stat.IsDir() {
err = fmt.Errorf(pathNotDirErr, d)
return
}
err = filepath.Walk(d, func(path string, f os.FileInfo, err error) error {
if !f.IsDir() {
fl = append(fl, path)
}
return nil
})
if err != nil {
return
}
return
}