-
Notifications
You must be signed in to change notification settings - Fork 4
/
clamd.go
350 lines (291 loc) · 7.57 KB
/
clamd.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
// Package clamd is a client for ClamAV daemon over TCP or UNIX socket.
package clamd
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net"
"strings"
"sync"
"syscall"
"time"
)
// dataChunkSize is the chunk size for stream scan.
const dataChunkSize = 1024
// Available socket types.
const (
socketTypeTcp = "tcp"
socketTypeUnix = "unix"
)
// Commands and responses.
const (
cmdPing = "PING"
cmdVersion = "VERSION"
cmdReload = "RELOAD"
cmdShutdown = "SHUTDOWN"
cmdInstream = "INSTREAM"
cmdScan = "SCAN"
cmdContscan = "CONTSCAN"
resOk = "OK"
resFound = "FOUND"
resPong = "PONG"
resReloading = "RELOADING"
resNoSuchFile = "No such file or directory. ERROR"
resPermissionDenied = "Permission denied. ERROR"
resCantOpenFile = "Can't open file or directory ERROR"
)
// NewClamd returns a Clamd client with default options.
//
// Default connection is a UNIX socket on /var/run/clamav/clamd.ctl with 30 second timeout. Defaults can be changed by
// passing in Option functions.
func NewClamd(opts ...Option) *Clamd {
const (
defaultSocketType = socketTypeUnix
defaultUnixSocketName = "/var/run/clamav/clamd.ctl"
defaultTCPHost = "127.0.0.1"
defaultTCPPort = 3310
defaultTimeout = 60 * time.Second
)
c := &Clamd{
mu: sync.Mutex{},
connType: defaultSocketType,
unixSocketName: defaultUnixSocketName,
tcpHost: defaultTCPHost,
tcpPort: defaultTCPPort,
timeout: defaultTimeout,
conn: nil,
}
for _, opt := range opts {
opt(c)
}
switch c.connType {
case socketTypeTcp:
c.connStr = fmt.Sprintf("%s:%d", c.tcpHost, c.tcpPort)
case socketTypeUnix:
c.connStr = c.unixSocketName
}
c.dialer = net.Dialer{
Timeout: c.timeout,
}
return c
}
// Clamd is a client for ClamAV's daemon clamd.
type Clamd struct {
mu sync.Mutex
connType string
connStr string
unixSocketName string
tcpHost string
tcpPort int
timeout time.Duration
dialer net.Dialer
conn net.Conn
}
func (c *Clamd) l() {
c.mu.Lock()
}
func (c *Clamd) ul() {
if c.conn != nil {
_ = c.conn.Close()
}
c.mu.Unlock()
}
func (c *Clamd) writeCmd(ctx context.Context, command string) error {
var err error
c.conn, err = c.dialer.DialContext(ctx, c.connType, c.connStr)
if err != nil {
return errors.Join(ErrDial, err)
}
_, err = c.conn.Write([]byte(fmt.Sprintf("n%s\n", command)))
if err != nil {
return errors.Join(ErrCommandCall, err)
}
return err
}
func (c *Clamd) readData() (string, error) {
var buf bytes.Buffer
_, err := io.Copy(&buf, c.conn)
if err != nil {
return "", errors.Join(ErrCommandRead, err)
}
return strings.TrimSuffix(buf.String(), "\n"), err
}
func (c *Clamd) writeCmdReadData(ctx context.Context, command string) (res string, err error) {
err = c.writeCmd(ctx, command)
if err != nil {
return "", errors.Join(ErrCommandCall, err)
}
res, err = c.readData()
if err != nil {
return "", errors.Join(ErrCommandCall, err)
}
return res, err
}
// sendData sends a stream of data to clamd
//
// [dutchcoders/go-clamd]: https://github.com/dutchcoders/go-clamd
func (c *Clamd) sendData(data []byte) error {
var buf [4]byte
lenData := len(data)
buf[0] = byte(lenData >> 24)
buf[1] = byte(lenData >> 16)
buf[2] = byte(lenData >> 8)
buf[3] = byte(lenData >> 0)
a := buf
b := make([]byte, len(a))
for i := range a {
b[i] = a[i]
}
_, err := c.conn.Write(b)
if err != nil {
return err
}
_, err = c.conn.Write(data)
return err
}
// Ping checks if Clamd is up and responsive.
func (c *Clamd) Ping(ctx context.Context) (bool, error) {
c.l()
defer c.ul()
res, err := c.writeCmdReadData(ctx, cmdPing)
if err != nil {
return false, err
}
if res != resPong {
return false, errors.Join(ErrInvalidResponse, fmt.Errorf("%s", res))
}
return true, nil
}
// Version returns Clamd's version.
func (c *Clamd) Version(ctx context.Context) (string, error) {
c.l()
defer c.ul()
res, err := c.writeCmdReadData(ctx, cmdVersion)
if err != nil {
return "", err
}
return res, nil
}
// Reload Clamd virus databases.
func (c *Clamd) Reload(ctx context.Context) (bool, error) {
c.l()
defer c.ul()
res, err := c.writeCmdReadData(ctx, cmdReload)
if err != nil {
return false, err
}
if res != resReloading {
return false, errors.Join(ErrInvalidResponse, fmt.Errorf("%s", res))
}
return true, nil
}
// Shutdown stops Clamd cleanly.
func (c *Clamd) Shutdown(ctx context.Context) (bool, error) {
c.l()
defer c.ul()
_, err := c.writeCmdReadData(ctx, cmdShutdown)
if err != nil {
return false, err
}
return true, nil
}
func parseErr(res string, err error) (bool, error) {
if err != nil {
return false, err
}
if strings.HasSuffix(res, resOk) {
return true, nil
}
if strings.HasSuffix(res, resFound) {
return false, nil
}
if strings.HasSuffix(res, resNoSuchFile) {
return false, errors.Join(ErrNoSuchFileOrDir, fmt.Errorf("%s", res))
}
if strings.HasSuffix(res, resPermissionDenied) {
return false, errors.Join(ErrPermissionDenied, fmt.Errorf("%s", res))
}
if strings.HasSuffix(res, resCantOpenFile) {
return false, errors.Join(ErrCantOpenFile, fmt.Errorf("%s", res))
}
return false, errors.Join(ErrUnknown, fmt.Errorf("%s", res))
}
// Scan a file or a directory (recursively) with archive support enabled (if not disabled in clamd.conf). A full path is required.
func (c *Clamd) Scan(ctx context.Context, src string) (bool, error) {
c.l()
defer c.ul()
if src == "" {
return false, ErrEmptySrc
}
res, err := c.writeCmdReadData(ctx, fmt.Sprintf("%s %s", cmdScan, src))
return parseErr(res, err)
}
// ScanStream Scan a stream of data.This avoids the overhead of establishing new TCP connections and problems with NAT.
//
// Note: do not exceed StreamMaxLength as defined in clamd.conf, otherwise clamd will reply with INSTREAM size limit
// exceeded and close the connection. (default is 25M)
func (c *Clamd) ScanStream(ctx context.Context, r io.Reader) (bool, error) {
c.l()
defer c.ul()
err := c.writeCmd(ctx, cmdInstream)
if err != nil {
return false, err
}
for {
buf := make([]byte, dataChunkSize)
n, err := r.Read(buf)
if n > 0 {
err = c.sendData(buf[0:n])
if err != nil {
if errors.Is(err, io.ErrClosedPipe) {
return false, errors.Join(ErrSreamLimitExceeded, err)
}
if errors.Is(err, net.ErrClosed) {
return false, errors.Join(ErrSreamLimitExceeded, err)
}
if errors.Is(err, syscall.EPIPE) {
return false, errors.Join(ErrSreamLimitExceeded, err)
}
return false, err
}
}
if err != nil {
if errors.Is(err, io.EOF) {
break
}
return false, err
}
}
_, err = c.conn.Write([]byte{0, 0, 0, 0})
if err != nil {
return false, errors.Join(ErrUnknown, err)
}
res, err := c.readData()
return parseErr(res, err)
}
// ScanAll Scan file or directory (recursively) with archive support enabled and don't stop the scanning when a virus is found.
func (c *Clamd) ScanAll(ctx context.Context, src string) (bool, error) {
c.l()
defer c.ul()
if src == "" {
return false, ErrEmptySrc
}
res, err := c.writeCmdReadData(ctx, fmt.Sprintf("%s %s", cmdContscan, src))
return parseErr(res, err)
}
// Stats Replies with statistics about the scan queue, contents of scan queue, and memory usage.
func (c *Clamd) Stats(ctx context.Context) (*Stats, error) {
c.l()
defer c.ul()
res, err := c.writeCmdReadData(ctx, "STATS")
if err != nil {
return nil, err
}
stats, err := parseStats(res)
if err != nil {
return nil, err
}
return stats, nil
}