~ubuntu-branches/ubuntu/saucy/clamav/saucy-backports

« back to all changes in this revision

Viewing changes to .pc/0007-bb-11028-fixed-a-deadlock-issue-with-fanotify-and-lo.patch/clamd/server-th.c

  • Committer: Package Import Robot
  • Author(s): Scott Kitterman
  • Date: 2014-07-15 01:08:10 UTC
  • mfrom: (0.35.47 sid)
  • Revision ID: package-import@ubuntu.com-20140715010810-ru66ek4fun2iseba
Tags: 0.98.4+dfsg-2~ubuntu13.10.1
No-change backport to saucy (LP: #1341962)

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/*
 
2
 *  Copyright (C) 2007-2009 Sourcefire, Inc.
 
3
 *
 
4
 *  Authors: Tomasz Kojm, Trog, Török Edvin
 
5
 *
 
6
 *  This program is free software; you can redistribute it and/or modify
 
7
 *  it under the terms of the GNU General Public License as published by
 
8
 *  the Free Software Foundation; either version 2 of the License, or
 
9
 *  (at your option) any later version.
 
10
 *
 
11
 *  This program is distributed in the hope that it will be useful,
 
12
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 
13
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
14
 *  GNU General Public License for more details.
 
15
 *
 
16
 *  You should have received a copy of the GNU General Public License
 
17
 *  along with this program; if not, write to the Free Software
 
18
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 
19
 *  MA 02110-1301, USA.
 
20
 */
 
21
 
 
22
#if HAVE_CONFIG_H
 
23
#include "clamav-config.h"
 
24
#endif
 
25
 
 
26
#include <pthread.h>
 
27
#include <errno.h>
 
28
#include <signal.h>
 
29
#include <stdio.h>
 
30
#include <string.h>
 
31
#include <time.h>
 
32
#include <sys/types.h>
 
33
#ifndef _WIN32
 
34
#include <sys/socket.h>
 
35
#include <sys/time.h>
 
36
#include <sys/resource.h>
 
37
#include <arpa/inet.h>
 
38
#endif
 
39
#ifdef  HAVE_UNISTD_H
 
40
#include <unistd.h>
 
41
#endif
 
42
 
 
43
#include <openssl/ssl.h>
 
44
#include <openssl/err.h>
 
45
#include "libclamav/crypto.h"
 
46
 
 
47
#include <fcntl.h>
 
48
#ifdef C_SOLARIS
 
49
#include <stdio_ext.h>
 
50
#endif
 
51
#include "libclamav/clamav.h"
 
52
 
 
53
#include "shared/output.h"
 
54
#include "shared/optparser.h"
 
55
 
 
56
#include "fan.h"
 
57
#include "server.h"
 
58
#include "thrmgr.h"
 
59
#include "session.h"
 
60
#include "others.h"
 
61
#include "shared.h"
 
62
#include "libclamav/others.h"
 
63
#include "libclamav/readdb.h"
 
64
#include "libclamav/cltypes.h"
 
65
 
 
66
#define BUFFSIZE 1024
 
67
 
 
68
int progexit = 0;
 
69
pthread_mutex_t exit_mutex = PTHREAD_MUTEX_INITIALIZER;
 
70
int reload = 0;
 
71
time_t reloaded_time = 0;
 
72
pthread_mutex_t reload_mutex = PTHREAD_MUTEX_INITIALIZER;
 
73
int sighup = 0;
 
74
static struct cl_stat dbstat;
 
75
 
 
76
void *event_wake_recv = NULL;
 
77
void *event_wake_accept = NULL;
 
78
 
 
79
static void scanner_thread(void *arg)
 
80
{
 
81
        client_conn_t *conn = (client_conn_t *) arg;
 
82
#ifndef _WIN32
 
83
        sigset_t sigset;
 
84
#endif
 
85
        int ret;
 
86
        int virus=0, errors = 0;
 
87
 
 
88
#ifndef _WIN32
 
89
    /* ignore all signals */
 
90
    sigfillset(&sigset);
 
91
    /* The behavior of a process is undefined after it ignores a 
 
92
     * SIGFPE, SIGILL, SIGSEGV, or SIGBUS signal */
 
93
    sigdelset(&sigset, SIGFPE);
 
94
    sigdelset(&sigset, SIGILL);
 
95
    sigdelset(&sigset, SIGSEGV);
 
96
#ifdef SIGBUS
 
97
    sigdelset(&sigset, SIGBUS);
 
98
#endif
 
99
    sigdelset(&sigset, SIGTSTP);
 
100
    sigdelset(&sigset, SIGCONT);
 
101
    pthread_sigmask(SIG_SETMASK, &sigset, NULL);
 
102
#endif
 
103
 
 
104
    ret = command(conn, &virus);
 
105
    if (ret == -1) {
 
106
        pthread_mutex_lock(&exit_mutex);
 
107
        progexit = 1;
 
108
        pthread_mutex_unlock(&exit_mutex);
 
109
        errors = 1;
 
110
    } else
 
111
        errors = ret;
 
112
 
 
113
    thrmgr_setactiveengine(NULL);
 
114
 
 
115
    if (conn->filename)
 
116
        free(conn->filename);
 
117
    logg("$Finished scanthread\n");
 
118
    if (thrmgr_group_finished(conn->group, virus ? EXIT_OTHER :
 
119
                              errors ? EXIT_ERROR : EXIT_OK)) {
 
120
        logg("$Scanthread: connection shut down (FD %d)\n", conn->sd);
 
121
        /* close connection if we were last in group */
 
122
        shutdown(conn->sd, 2);
 
123
        closesocket(conn->sd);
 
124
    }
 
125
    cl_engine_free(conn->engine);
 
126
    free(conn);
 
127
    return;
 
128
}
 
129
 
 
130
static int syncpipe_wake_recv_w = -1;
 
131
 
 
132
void sighandler_th(int sig)
 
133
{
 
134
    int action = 0;
 
135
    switch(sig) {
 
136
        case SIGINT:
 
137
        case SIGTERM:
 
138
            progexit = 1;
 
139
            action = 1;
 
140
            break;
 
141
 
 
142
#ifdef  SIGHUP
 
143
        case SIGHUP:
 
144
            sighup = 1;
 
145
            action = 1;
 
146
            break;
 
147
#endif
 
148
 
 
149
#ifdef  SIGUSR2
 
150
        case SIGUSR2:
 
151
            reload = 1;
 
152
            action = 1;
 
153
            break;
 
154
#endif
 
155
 
 
156
        default:
 
157
            break; /* Take no action on other signals - e.g. SIGPIPE */
 
158
    }
 
159
    /* a signal doesn't always wake poll(), for example on FreeBSD */
 
160
    if (action && syncpipe_wake_recv_w != -1)
 
161
        if (write(syncpipe_wake_recv_w, "", 1) != 1)
 
162
            logg("$Failed to write to syncpipe\n");
 
163
}
 
164
 
 
165
static struct cl_engine *reload_db(struct cl_engine *engine, unsigned int dboptions, const struct optstruct *opts, int do_check, int *ret)
 
166
{
 
167
        const char *dbdir;
 
168
        int retval;
 
169
        unsigned int sigs = 0;
 
170
        struct cl_settings *settings = NULL;
 
171
 
 
172
    *ret = 0;
 
173
    if(do_check) {
 
174
        if(!dbstat.entries) {
 
175
            logg("No stats for Database check - forcing reload\n");
 
176
            return engine;
 
177
        }
 
178
 
 
179
        if(cl_statchkdir(&dbstat) == 1) {
 
180
            logg("SelfCheck: Database modification detected. Forcing reload.\n");
 
181
            return engine;
 
182
        } else {
 
183
            logg("SelfCheck: Database status OK.\n");
 
184
            return NULL;
 
185
        }
 
186
    }
 
187
 
 
188
    /* release old structure */
 
189
    if(engine) {
 
190
        /* copy current settings */
 
191
        settings = cl_engine_settings_copy(engine);
 
192
        if(!settings)
 
193
            logg("^Can't make a copy of the current engine settings\n");
 
194
 
 
195
        thrmgr_setactiveengine(NULL);
 
196
        cl_engine_free(engine);
 
197
    }
 
198
 
 
199
    dbdir = optget(opts, "DatabaseDirectory")->strarg;
 
200
    logg("Reading databases from %s\n", dbdir);
 
201
 
 
202
    if(dbstat.entries)
 
203
        cl_statfree(&dbstat);
 
204
 
 
205
    memset(&dbstat, 0, sizeof(struct cl_stat));
 
206
    if((retval = cl_statinidir(dbdir, &dbstat))) {
 
207
        logg("!cl_statinidir() failed: %s\n", cl_strerror(retval));
 
208
        *ret = 1;
 
209
        if(settings)
 
210
            cl_engine_settings_free(settings);
 
211
        return NULL;
 
212
    }
 
213
 
 
214
    if(!(engine = cl_engine_new())) {
 
215
        logg("!Can't initialize antivirus engine\n");
 
216
        *ret = 1;
 
217
        if(settings)
 
218
            cl_engine_settings_free(settings);
 
219
        return NULL;
 
220
    }
 
221
 
 
222
    if(settings) {
 
223
        retval = cl_engine_settings_apply(engine, settings);
 
224
        if(retval != CL_SUCCESS) {
 
225
            logg("^Can't apply previous engine settings: %s\n", cl_strerror(retval));
 
226
            logg("^Using default engine settings\n");
 
227
        }
 
228
        cl_engine_settings_free(settings);
 
229
    }
 
230
 
 
231
    if((retval = cl_load(dbdir, engine, &sigs, dboptions))) {
 
232
        logg("!reload db failed: %s\n", cl_strerror(retval));
 
233
        cl_engine_free(engine);
 
234
        *ret = 1;
 
235
        return NULL;
 
236
    }
 
237
 
 
238
    if((retval = cl_engine_compile(engine)) != 0) {
 
239
        logg("!Database initialization error: can't compile engine: %s\n", cl_strerror(retval));
 
240
        cl_engine_free(engine);
 
241
        *ret = 1;
 
242
        return NULL;
 
243
    }
 
244
    logg("Database correctly reloaded (%u signatures)\n", sigs);
 
245
 
 
246
    thrmgr_setactiveengine(engine);
 
247
    return engine;
 
248
}
 
249
 
 
250
/*
 
251
 * zCOMMANDS are delimited by \0
 
252
 * nCOMMANDS are delimited by \n
 
253
 * Old-style non-prefixed commands are one packet, optionally delimited by \n,
 
254
 * with trailing \r|\n ignored
 
255
 */
 
256
static const char *get_cmd(struct fd_buf *buf, size_t off, size_t *len, char *term, int *oldstyle)
 
257
{
 
258
    char *pos;
 
259
    if (!buf->off || off >= buf->off) {
 
260
        *len = 0;
 
261
        return NULL;
 
262
    }
 
263
 
 
264
    *term = '\n';
 
265
    switch (buf->buffer[off]) {
 
266
        /* commands terminated by delimiters */
 
267
        case 'z':
 
268
            *term = '\0';
 
269
        case 'n':
 
270
            pos = memchr(buf->buffer + off, *term, buf->off - off);
 
271
            if (!pos) {
 
272
                /* we don't have another full command yet */
 
273
                *len = 0;
 
274
                return NULL;
 
275
            }
 
276
            *pos = '\0';
 
277
            if (*term) {
 
278
                *len = cli_chomp(buf->buffer + off);
 
279
            } else {
 
280
                *len = pos - buf->buffer - off;
 
281
            }
 
282
            *oldstyle = 0;
 
283
            return buf->buffer + off + 1;
 
284
        default:
 
285
            /* one packet = one command */
 
286
            if (off)
 
287
                return NULL;
 
288
            pos = memchr(buf->buffer, '\n', buf->off);
 
289
            if (pos) {
 
290
                *len = pos - buf->buffer;
 
291
                *pos = '\0';
 
292
            } else {
 
293
                *len = buf->off;
 
294
                buf->buffer[buf->off] = '\0';
 
295
            }
 
296
            cli_chomp(buf->buffer);
 
297
            *oldstyle = 1;
 
298
            return buf->buffer;
 
299
    }
 
300
}
 
301
 
 
302
struct acceptdata {
 
303
    struct fd_data fds;
 
304
    struct fd_data recv_fds;
 
305
    pthread_cond_t cond_nfds;
 
306
    int max_queue;
 
307
    int commandtimeout;
 
308
    int syncpipe_wake_recv[2];
 
309
    int syncpipe_wake_accept[2];
 
310
};
 
311
 
 
312
#define ACCEPTDATA_INIT(mutex1, mutex2) { FDS_INIT(mutex1), FDS_INIT(mutex2), PTHREAD_COND_INITIALIZER, 0, 0, {-1, -1}, {-1, -1}}
 
313
 
 
314
static void *acceptloop_th(void *arg)
 
315
{
 
316
    char buff[BUFFSIZE + 1];
 
317
    size_t i;
 
318
    struct acceptdata *data = (struct acceptdata*)arg;
 
319
    struct fd_data *fds = &data->fds;
 
320
    struct fd_data *recv_fds = &data->recv_fds;
 
321
    int max_queue = data->max_queue;
 
322
    int commandtimeout = data->commandtimeout;
 
323
 
 
324
    pthread_mutex_lock(fds->buf_mutex);
 
325
    for (;;) {
 
326
        /* Block waiting for data to become available for reading */
 
327
        int new_sd = fds_poll_recv(fds, -1, 0, event_wake_accept);
 
328
#ifdef _WIN32
 
329
        ResetEvent(event_wake_accept);
 
330
#endif
 
331
        /* TODO: what about sockets that get rm-ed? */
 
332
        if (!fds->nfds) {
 
333
            /* no more sockets to poll, all gave an error */
 
334
            logg("!Main socket gone: fatal\n");
 
335
            break;
 
336
        }
 
337
 
 
338
        if (new_sd == -1 && errno != EINTR) {
 
339
            logg("!Failed to poll sockets, fatal\n");
 
340
            pthread_mutex_lock(&exit_mutex);
 
341
            progexit = 1;
 
342
            pthread_mutex_unlock(&exit_mutex);
 
343
            break;
 
344
        }
 
345
 
 
346
        /* accept() loop */
 
347
        for (i=0;i < fds->nfds && new_sd >= 0; i++) {
 
348
            struct fd_buf *buf = &fds->buf[i];
 
349
            if (!buf->got_newdata)
 
350
                continue;
 
351
#ifndef _WIN32
 
352
            if (buf->fd == data->syncpipe_wake_accept[0]) {
 
353
                /* dummy sync pipe, just to wake us */
 
354
                if (read(buf->fd, buff, sizeof(buff)) < 0) {
 
355
                    logg("^Syncpipe read failed\n");
 
356
                }
 
357
                continue;
 
358
            }
 
359
#endif
 
360
            if (buf->got_newdata == -1) {
 
361
                logg("$Acceptloop closed FD: %d\n", buf->fd);
 
362
                shutdown(buf->fd, 2);
 
363
                closesocket(buf->fd);
 
364
                buf->fd = -1;
 
365
                continue;
 
366
            }
 
367
 
 
368
            /* don't accept unlimited number of connections, or
 
369
             * we'll run out of file descriptors */
 
370
            pthread_mutex_lock(recv_fds->buf_mutex);
 
371
            while (recv_fds->nfds > (unsigned)max_queue) {
 
372
                pthread_mutex_lock(&exit_mutex);
 
373
                if(progexit) {
 
374
                    pthread_mutex_unlock(&exit_mutex);
 
375
                    break;
 
376
                }
 
377
                pthread_mutex_unlock(&exit_mutex);
 
378
                pthread_cond_wait(&data->cond_nfds, recv_fds->buf_mutex);
 
379
            }
 
380
            pthread_mutex_unlock(recv_fds->buf_mutex);
 
381
 
 
382
            pthread_mutex_lock(&exit_mutex);
 
383
            if(progexit) {
 
384
                pthread_mutex_unlock(&exit_mutex);
 
385
                break;
 
386
            }
 
387
            pthread_mutex_unlock(&exit_mutex);
 
388
 
 
389
            /* listen only socket */
 
390
            new_sd = accept(fds->buf[i].fd, NULL, NULL);
 
391
 
 
392
            if (new_sd >= 0) {
 
393
                int ret, flags;
 
394
#ifdef F_GETFL
 
395
                flags = fcntl(new_sd, F_GETFL, 0);
 
396
                if (flags != -1) {
 
397
                    if (fcntl(new_sd, F_SETFL, flags | O_NONBLOCK) == -1) {
 
398
                        logg("^Can't set socket to nonblocking mode, errno %d\n",
 
399
                             errno);
 
400
                    }
 
401
                } else {
 
402
                        logg("^Can't get socket flags, errno %d\n", errno);
 
403
                }
 
404
#else
 
405
                logg("^Nonblocking sockets not available!\n");
 
406
#endif
 
407
                logg("$Got new connection, FD %d\n", new_sd);
 
408
                pthread_mutex_lock(recv_fds->buf_mutex);
 
409
                ret = fds_add(recv_fds, new_sd, 0, commandtimeout);
 
410
                pthread_mutex_unlock(recv_fds->buf_mutex);
 
411
 
 
412
                if (ret == -1) {
 
413
                    logg("!fds_add failed\n");
 
414
                    closesocket(new_sd);
 
415
                    continue;
 
416
                }
 
417
 
 
418
                /* notify recvloop */
 
419
#ifdef _WIN32
 
420
                SetEvent(event_wake_recv);
 
421
#else
 
422
                if (write(data->syncpipe_wake_recv[1], "", 1) == -1) {
 
423
                    logg("!write syncpipe failed\n");
 
424
                    continue;
 
425
                }
 
426
#endif
 
427
            } else if (errno != EINTR) {
 
428
                /* very bad - need to exit or restart */
 
429
#ifdef HAVE_STRERROR_R
 
430
                strerror_r(errno, buff, BUFFSIZE);
 
431
                logg("!accept() failed: %s\n", buff);
 
432
#else
 
433
                logg("!accept() failed\n");
 
434
#endif
 
435
                /* give the poll loop a chance to close disconnected FDs */
 
436
                break;
 
437
            }
 
438
 
 
439
        }
 
440
 
 
441
        /* handle progexit */
 
442
        pthread_mutex_lock(&exit_mutex);
 
443
        if (progexit) {
 
444
            pthread_mutex_unlock(&exit_mutex);
 
445
            break;
 
446
        }
 
447
        pthread_mutex_unlock(&exit_mutex);
 
448
    }
 
449
    pthread_mutex_unlock(fds->buf_mutex);
 
450
 
 
451
    for (i=0;i < fds->nfds; i++) {
 
452
        if (fds->buf[i].fd == -1)
 
453
            continue;
 
454
        logg("$Shutdown: closed fd %d\n", fds->buf[i].fd);
 
455
        shutdown(fds->buf[i].fd, 2);
 
456
        closesocket(fds->buf[i].fd);
 
457
    }
 
458
    fds_free(fds);
 
459
    pthread_mutex_destroy(fds->buf_mutex);
 
460
    pthread_mutex_lock(&exit_mutex);
 
461
    progexit = 1;
 
462
    pthread_mutex_unlock(&exit_mutex);
 
463
#ifdef _WIN32
 
464
    SetEvent(event_wake_recv);
 
465
#else
 
466
    if (write(data->syncpipe_wake_recv[1], "", 1) < 0) {
 
467
        logg("$Syncpipe write failed\n");
 
468
    }
 
469
#endif
 
470
    return NULL;
 
471
}
 
472
 
 
473
static const char* parse_dispatch_cmd(client_conn_t *conn, struct fd_buf *buf, size_t *ppos, int *error, const struct optstruct *opts, int readtimeout)
 
474
{
 
475
    const char *cmd = NULL;
 
476
    int rc;
 
477
    size_t cmdlen;
 
478
    char term;
 
479
    int oldstyle;
 
480
    size_t pos = *ppos;
 
481
    /* Parse & dispatch commands */
 
482
    while ((conn->mode == MODE_COMMAND) &&
 
483
           (cmd = get_cmd(buf, pos, &cmdlen, &term, &oldstyle)) != NULL) {
 
484
        const char *argument;
 
485
        enum commands cmdtype;
 
486
        if (conn->group && oldstyle) {
 
487
            logg("$Received oldstyle command inside IDSESSION: %s\n", cmd);
 
488
            conn_reply_error(conn, "Only nCMDS\\n and zCMDS\\0 are accepted inside IDSESSION.");
 
489
            *error = 1;
 
490
            break;
 
491
        }
 
492
        cmdtype = parse_command(cmd, &argument, oldstyle);
 
493
        logg("$got command %s (%u, %u), argument: %s\n",
 
494
             cmd, (unsigned)cmdlen, (unsigned)cmdtype, argument ? argument : "");
 
495
        if (cmdtype == COMMAND_FILDES) {
 
496
            if (buf->buffer + buf->off <= cmd + strlen("FILDES\n")) {
 
497
                /* we need the extra byte from recvmsg */
 
498
                conn->mode = MODE_WAITANCILL;
 
499
                buf->mode = MODE_WAITANCILL;
 
500
                /* put term back */
 
501
                buf->buffer[pos + cmdlen] = term;
 
502
                cmdlen = 0;
 
503
                logg("$RECVTH: mode -> MODE_WAITANCILL\n");
 
504
                break;
 
505
            }
 
506
            /* eat extra \0 for controlmsg */
 
507
            cmdlen++;
 
508
            logg("$RECVTH: FILDES command complete\n");
 
509
        }
 
510
        conn->term = term;
 
511
        buf->term = term;
 
512
 
 
513
        if ((rc = execute_or_dispatch_command(conn, cmdtype, argument)) < 0) {
 
514
            logg("!Command dispatch failed\n");
 
515
            if(rc == -1 && optget(opts, "ExitOnOOM")->enabled) {
 
516
                pthread_mutex_lock(&exit_mutex);
 
517
                progexit = 1;
 
518
                pthread_mutex_unlock(&exit_mutex);
 
519
            }
 
520
            *error = 1;
 
521
        }
 
522
        if (thrmgr_group_need_terminate(conn->group)) {
 
523
            logg("$Receive thread: have to terminate group\n");
 
524
            *error = CL_ETIMEOUT;
 
525
            break;
 
526
        }
 
527
        if (*error || !conn->group || rc) {
 
528
            if (rc && thrmgr_group_finished(conn->group, EXIT_OK)) {
 
529
                logg("$Receive thread: closing conn (FD %d), group finished\n", conn->sd);
 
530
                /* if there are no more active jobs */
 
531
                shutdown(conn->sd, 2);
 
532
                closesocket(conn->sd);
 
533
                buf->fd = -1;
 
534
                conn->group = NULL;
 
535
            } else if (conn->mode != MODE_STREAM) {
 
536
                logg("$mode -> MODE_WAITREPLY\n");
 
537
                /* no more commands are accepted */
 
538
                conn->mode = MODE_WAITREPLY;
 
539
                /* Stop monitoring this FD, it will be closed either
 
540
                 * by us, or by the scanner thread. 
 
541
                 * Never close a file descriptor that is being
 
542
                 * monitored by poll()/select() from another thread,
 
543
                 * because this can lead to subtle bugs such as:
 
544
                 * Other thread closes file descriptor -> POLLHUP is
 
545
                 * set, but the poller thread doesn't wake up yet.
 
546
                 * Another client opens a connection and sends some
 
547
                 * data. If the socket reuses the previous file descriptor,
 
548
                 * then POLLIN is set on the file descriptor too.
 
549
                 * When poll() wakes up it sees POLLIN | POLLHUP
 
550
                 * and thinks that the client has sent some data,
 
551
                 * and closed the connection, so clamd closes the
 
552
                 * connection in turn resulting in a bug.
 
553
                 *
 
554
                 * If we wouldn't have poll()-ed the file descriptor
 
555
                 * we closed in another thread, but rather made sure
 
556
                 * that we don't put a FD that we're about to close
 
557
                 * into poll()'s list of watched fds; then POLLHUP
 
558
                 * would be set, but the file descriptor would stay
 
559
                 * open, until we wake up from poll() and close it.
 
560
                 * Thus a new connection won't be able to reuse the
 
561
                 * same FD, and there is no bug.
 
562
                 * */
 
563
                buf->fd = -1;
 
564
            }
 
565
        }
 
566
        /* we received a command, set readtimeout */
 
567
        time(&buf->timeout_at);
 
568
        buf->timeout_at += readtimeout;
 
569
        pos += cmdlen+1;
 
570
        if (conn->mode == MODE_STREAM) {
 
571
            /* TODO: this doesn't belong here */
 
572
            buf->dumpname = conn->filename;
 
573
            buf->dumpfd = conn->scanfd;
 
574
            logg("$Receive thread: INSTREAM: %s fd %u\n", buf->dumpname, buf->dumpfd);
 
575
        }
 
576
        if (conn->mode != MODE_COMMAND) {
 
577
            logg("$Breaking command loop, mode is no longer MODE_COMMAND\n");
 
578
            break;
 
579
        }
 
580
        conn->id++;
 
581
    }
 
582
    *ppos = pos;
 
583
    buf->mode = conn->mode;
 
584
    buf->id = conn->id;
 
585
    buf->group = conn->group;
 
586
    buf->quota = conn->quota;
 
587
    if (conn->scanfd != -1 && conn->scanfd != buf->dumpfd) {
 
588
        logg("$Unclaimed file descriptor received, closing: %d\n", conn->scanfd);
 
589
        close(conn->scanfd);
 
590
        /* protocol error */
 
591
        conn_reply_error(conn, "PROTOCOL ERROR: ancillary data sent without FILDES.");
 
592
        *error = 1;
 
593
        return NULL;
 
594
    }
 
595
    if (!*error) {
 
596
        /* move partial command to beginning of buffer */
 
597
        if (pos < buf->off) {
 
598
            memmove (buf->buffer, &buf->buffer[pos], buf->off - pos);
 
599
            buf->off -= pos;
 
600
        } else
 
601
            buf->off = 0;
 
602
        if (buf->off)
 
603
            logg("$Moved partial command: %lu\n", (unsigned long)buf->off);
 
604
        else
 
605
            logg("$Consumed entire command\n");
 
606
        /* adjust pos to account for the buffer shuffle */
 
607
        pos = 0;
 
608
    }
 
609
    *ppos = pos;
 
610
    return cmd;
 
611
}
 
612
 
 
613
/* static const unsigned char* parse_dispatch_cmd(client_conn_t *conn, struct fd_buf *buf, size_t *ppos, int *error, const struct optstruct *opts, int readtimeout) */
 
614
static int handle_stream(client_conn_t *conn, struct fd_buf *buf, const struct optstruct *opts, int *error, size_t *ppos, int readtimeout)
 
615
{
 
616
    int rc;
 
617
    size_t pos = *ppos;
 
618
    size_t cmdlen;
 
619
    
 
620
    logg("$mode == MODE_STREAM\n");
 
621
    /* we received some data, set readtimeout */
 
622
    time(&buf->timeout_at);
 
623
    buf->timeout_at += readtimeout;
 
624
    while (pos <= buf->off) {
 
625
        if (!buf->chunksize) {
 
626
            /* read chunksize */
 
627
            if (buf->off-pos >= 4) {
 
628
                uint32_t cs;
 
629
                memmove(&cs, buf->buffer + pos, 4);
 
630
                pos += 4;
 
631
                buf->chunksize = ntohl(cs);
 
632
                logg("$Got chunksize: %u\n", buf->chunksize);
 
633
                if (!buf->chunksize) {
 
634
                    /* chunksize 0 marks end of stream */
 
635
                    conn->scanfd = buf->dumpfd;
 
636
                    conn->term = buf->term;
 
637
                    buf->dumpfd = -1;
 
638
                    buf->mode = buf->group ? MODE_COMMAND : MODE_WAITREPLY;
 
639
                    if (buf->mode == MODE_WAITREPLY)
 
640
                        buf->fd = -1;
 
641
                    logg("$Chunks complete\n");
 
642
                    buf->dumpname = NULL;
 
643
                    if ((rc = execute_or_dispatch_command(conn, COMMAND_INSTREAMSCAN, NULL)) < 0) {
 
644
                        logg("!Command dispatch failed\n");
 
645
                        if(rc == -1 && optget(opts, "ExitOnOOM")->enabled) {
 
646
                            pthread_mutex_lock(&exit_mutex);
 
647
                            progexit = 1;
 
648
                            pthread_mutex_unlock(&exit_mutex);
 
649
                        }
 
650
                        *error = 1;
 
651
                    } else {
 
652
                        memmove (buf->buffer, &buf->buffer[pos], buf->off - pos);
 
653
                        buf->off -= pos;
 
654
                        *ppos = 0;
 
655
                        buf->id++;
 
656
                        return 0;
 
657
                    }
 
658
                }
 
659
                if (buf->chunksize > buf->quota) {
 
660
                    logg("^INSTREAM: Size limit reached, (requested: %lu, max: %lu)\n",
 
661
                         (unsigned long)buf->chunksize, (unsigned long)buf->quota);
 
662
                    conn_reply_error(conn, "INSTREAM size limit exceeded.");
 
663
                    *error = 1;
 
664
                    *ppos = pos;
 
665
                    return -1;
 
666
                } else {
 
667
                    buf->quota -= buf->chunksize;
 
668
                }
 
669
                logg("$Quota Remaining: %lu\n", buf->quota);
 
670
            } else {
 
671
                /* need more data, so return and wait for some */
 
672
                memmove (buf->buffer, &buf->buffer[pos], buf->off - pos);
 
673
                buf->off -= pos;
 
674
                *ppos = 0;
 
675
                return -1;
 
676
            }
 
677
        }
 
678
        if (pos + buf->chunksize < buf->off)
 
679
            cmdlen = buf->chunksize;
 
680
        else
 
681
            cmdlen = buf->off - pos;
 
682
        buf->chunksize -= cmdlen;
 
683
        if (cli_writen(buf->dumpfd, buf->buffer + pos, cmdlen) < 0) {
 
684
            conn_reply_error(conn, "Error writing to temporary file");
 
685
            logg("!INSTREAM: Can't write to temporary file.\n");
 
686
            *error = 1;
 
687
        }
 
688
        logg("$Processed %lu bytes of chunkdata, pos %lu\n", cmdlen, pos);
 
689
        pos += cmdlen;
 
690
        if (pos == buf->off) {
 
691
            buf->off = 0;
 
692
            pos = 0;
 
693
            /* need more data, so return and wait for some */
 
694
            *ppos = pos;
 
695
            return -1;
 
696
        }
 
697
    }
 
698
    *ppos = pos;
 
699
    return 0;
 
700
}
 
701
 
 
702
int recvloop_th(int *socketds, unsigned nsockets, struct cl_engine *engine, unsigned int dboptions, const struct optstruct *opts)
 
703
{
 
704
        int max_threads, max_queue, readtimeout, ret = 0;
 
705
        unsigned int options = 0;
 
706
        char timestr[32];
 
707
#ifndef _WIN32
 
708
        struct sigaction sigact;
 
709
        sigset_t sigset;
 
710
        struct rlimit rlim;
 
711
#endif
 
712
        mode_t old_umask;
 
713
        const struct optstruct *opt;
 
714
        char buff[BUFFSIZE + 1];
 
715
        pid_t mainpid;
 
716
        int idletimeout;
 
717
        unsigned long long val;
 
718
        size_t i, j, rr_last = 0;
 
719
        pthread_t accept_th;
 
720
        pthread_mutex_t fds_mutex = PTHREAD_MUTEX_INITIALIZER;
 
721
        pthread_mutex_t recvfds_mutex = PTHREAD_MUTEX_INITIALIZER;
 
722
        struct acceptdata acceptdata = ACCEPTDATA_INIT(&fds_mutex, &recvfds_mutex);
 
723
        struct fd_data *fds = &acceptdata.recv_fds;
 
724
        time_t start_time, current_time;
 
725
        unsigned int selfchk;
 
726
        threadpool_t *thr_pool;
 
727
 
 
728
#if defined(FANOTIFY) || defined(CLAMAUTH)
 
729
        pthread_t fan_pid;
 
730
        pthread_attr_t fan_attr;
 
731
        struct thrarg *tharg = NULL; /* shut up gcc */
 
732
#endif
 
733
 
 
734
#ifndef _WIN32
 
735
        memset(&sigact, 0, sizeof(struct sigaction));
 
736
#endif
 
737
 
 
738
    /* set up limits */
 
739
    if((opt = optget(opts, "MaxScanSize"))->active) {
 
740
        if((ret = cl_engine_set_num(engine, CL_ENGINE_MAX_SCANSIZE, opt->numarg))) {
 
741
            logg("!cl_engine_set_num(CL_ENGINE_MAX_SCANSIZE) failed: %s\n", cl_strerror(ret));
 
742
            cl_engine_free(engine);
 
743
            return 1;
 
744
        }
 
745
    }
 
746
    val = cl_engine_get_num(engine, CL_ENGINE_MAX_SCANSIZE, NULL);
 
747
    if(val)
 
748
        logg("Limits: Global size limit set to %llu bytes.\n", val);
 
749
    else
 
750
        logg("^Limits: Global size limit protection disabled.\n");
 
751
 
 
752
    if((opt = optget(opts, "MaxFileSize"))->active) {
 
753
        if((ret = cl_engine_set_num(engine, CL_ENGINE_MAX_FILESIZE, opt->numarg))) {
 
754
            logg("!cl_engine_set_num(CL_ENGINE_MAX_FILESIZE) failed: %s\n", cl_strerror(ret));
 
755
            cl_engine_free(engine);
 
756
            return 1;
 
757
        }
 
758
    }
 
759
    val = cl_engine_get_num(engine, CL_ENGINE_MAX_FILESIZE, NULL);
 
760
    if(val)
 
761
        logg("Limits: File size limit set to %llu bytes.\n", val);
 
762
    else
 
763
        logg("^Limits: File size limit protection disabled.\n");
 
764
 
 
765
#ifndef _WIN32
 
766
    if(getrlimit(RLIMIT_FSIZE, &rlim) == 0) {
 
767
        if(rlim.rlim_cur < (rlim_t) cl_engine_get_num(engine, CL_ENGINE_MAX_FILESIZE, NULL))
 
768
            logg("^System limit for file size is lower than engine->maxfilesize\n");
 
769
        if(rlim.rlim_cur < (rlim_t) cl_engine_get_num(engine, CL_ENGINE_MAX_SCANSIZE, NULL))
 
770
            logg("^System limit for file size is lower than engine->maxscansize\n");
 
771
    } else {
 
772
        logg("^Cannot obtain resource limits for file size\n");
 
773
    }
 
774
#endif
 
775
 
 
776
    if((opt = optget(opts, "MaxRecursion"))->active) {
 
777
        if((ret = cl_engine_set_num(engine, CL_ENGINE_MAX_RECURSION, opt->numarg))) {
 
778
            logg("!cl_engine_set_num(CL_ENGINE_MAX_RECURSION) failed: %s\n", cl_strerror(ret));
 
779
            cl_engine_free(engine);
 
780
            return 1;
 
781
        }
 
782
    }
 
783
    val = cl_engine_get_num(engine, CL_ENGINE_MAX_RECURSION, NULL);
 
784
    if(val)
 
785
        logg("Limits: Recursion level limit set to %u.\n", (unsigned int) val);
 
786
    else
 
787
        logg("^Limits: Recursion level limit protection disabled.\n");
 
788
 
 
789
    if((opt = optget(opts, "MaxFiles"))->active) {
 
790
        if((ret = cl_engine_set_num(engine, CL_ENGINE_MAX_FILES, opt->numarg))) {
 
791
            logg("!cl_engine_set_num(CL_ENGINE_MAX_FILES) failed: %s\n", cl_strerror(ret));
 
792
            cl_engine_free(engine);
 
793
            return 1;
 
794
        }
 
795
    }
 
796
    val = cl_engine_get_num(engine, CL_ENGINE_MAX_FILES, NULL);
 
797
    if(val)
 
798
        logg("Limits: Files limit set to %u.\n", (unsigned int) val);
 
799
    else
 
800
        logg("^Limits: Files limit protection disabled.\n");
 
801
 
 
802
#ifndef _WIN32
 
803
    if (getrlimit(RLIMIT_CORE, &rlim) == 0) {
 
804
        logg("*Limits: Core-dump limit is %lu.\n", (unsigned long)rlim.rlim_cur);
 
805
    }
 
806
#endif
 
807
 
 
808
    /* Engine max sizes */
 
809
 
 
810
    if((opt = optget(opts, "MaxEmbeddedPE"))->active) {
 
811
        if((ret = cl_engine_set_num(engine, CL_ENGINE_MAX_EMBEDDEDPE, opt->numarg))) {
 
812
            logg("!cli_engine_set_num(CL_ENGINE_MAX_EMBEDDEDPE) failed: %s\n", cl_strerror(ret));
 
813
            cl_engine_free(engine);
 
814
            return 1;
 
815
        }
 
816
    }
 
817
    val = cl_engine_get_num(engine, CL_ENGINE_MAX_EMBEDDEDPE, NULL);
 
818
    logg("Limits: MaxEmbeddedPE limit set to %llu bytes.\n", val);
 
819
 
 
820
    if((opt = optget(opts, "MaxHTMLNormalize"))->active) {
 
821
        if((ret = cl_engine_set_num(engine, CL_ENGINE_MAX_HTMLNORMALIZE, opt->numarg))) {
 
822
            logg("!cli_engine_set_num(CL_ENGINE_MAX_HTMLNORMALIZE) failed: %s\n", cl_strerror(ret));
 
823
            cl_engine_free(engine);
 
824
            return 1;
 
825
        }
 
826
    }
 
827
    val = cl_engine_get_num(engine, CL_ENGINE_MAX_HTMLNORMALIZE, NULL);
 
828
    logg("Limits: MaxHTMLNormalize limit set to %llu bytes.\n", val);
 
829
 
 
830
    if((opt = optget(opts, "MaxHTMLNoTags"))->active) {
 
831
        if((ret = cl_engine_set_num(engine, CL_ENGINE_MAX_HTMLNOTAGS, opt->numarg))) {
 
832
            logg("!cli_engine_set_num(CL_ENGINE_MAX_HTMLNOTAGS) failed: %s\n", cl_strerror(ret));
 
833
            cl_engine_free(engine);
 
834
            return 1;
 
835
        }
 
836
    }
 
837
    val = cl_engine_get_num(engine, CL_ENGINE_MAX_HTMLNOTAGS, NULL);
 
838
    logg("Limits: MaxHTMLNoTags limit set to %llu bytes.\n", val);
 
839
 
 
840
    if((opt = optget(opts, "MaxScriptNormalize"))->active) {
 
841
        if((ret = cl_engine_set_num(engine, CL_ENGINE_MAX_SCRIPTNORMALIZE, opt->numarg))) {
 
842
            logg("!cli_engine_set_num(CL_ENGINE_MAX_SCRIPTNORMALIZE) failed: %s\n", cl_strerror(ret));
 
843
            cl_engine_free(engine);
 
844
            return 1;
 
845
        }
 
846
    }
 
847
    val = cl_engine_get_num(engine, CL_ENGINE_MAX_SCRIPTNORMALIZE, NULL);
 
848
    logg("Limits: MaxScriptNormalize limit set to %llu bytes.\n", val);
 
849
 
 
850
    if((opt = optget(opts, "MaxZipTypeRcg"))->active) {
 
851
        if((ret = cl_engine_set_num(engine, CL_ENGINE_MAX_ZIPTYPERCG, opt->numarg))) {
 
852
            logg("!cli_engine_set_num(CL_ENGINE_MAX_ZIPTYPERCG) failed: %s\n", cl_strerror(ret));
 
853
            cl_engine_free(engine);
 
854
            return 1;
 
855
        }
 
856
    }
 
857
    val = cl_engine_get_num(engine, CL_ENGINE_MAX_ZIPTYPERCG, NULL);
 
858
    logg("Limits: MaxZipTypeRcg limit set to %llu bytes.\n", val);
 
859
 
 
860
    if((opt = optget(opts, "MaxPartitions"))->active) {
 
861
        if((ret = cl_engine_set_num(engine, CL_ENGINE_MAX_PARTITIONS, opt->numarg))) {
 
862
            logg("!cli_engine_set_num(MaxPartitions) failed: %s\n", cl_strerror(ret));
 
863
            cl_engine_free(engine);
 
864
            return 1;
 
865
        }
 
866
    }
 
867
    val = cl_engine_get_num(engine, CL_ENGINE_MAX_PARTITIONS, NULL);
 
868
    logg("Limits: MaxPartitions limit set to %llu.\n", val);
 
869
 
 
870
    if((opt = optget(opts, "MaxIconsPE"))->active) {
 
871
        if((ret = cl_engine_set_num(engine, CL_ENGINE_MAX_ICONSPE, opt->numarg))) {
 
872
            logg("!cli_engine_set_num(MaxIconsPE) failed: %s\n", cl_strerror(ret));
 
873
            cl_engine_free(engine);
 
874
            return 1;
 
875
        }
 
876
    }
 
877
    val = cl_engine_get_num(engine, CL_ENGINE_MAX_ICONSPE, NULL);
 
878
    logg("Limits: MaxIconsPE limit set to %llu.\n", val);
 
879
 
 
880
    if(optget(opts, "ScanArchive")->enabled) {
 
881
        logg("Archive support enabled.\n");
 
882
        options |= CL_SCAN_ARCHIVE;
 
883
 
 
884
        if(optget(opts, "ArchiveBlockEncrypted")->enabled) {
 
885
            logg("Archive: Blocking encrypted archives.\n");
 
886
            options |= CL_SCAN_BLOCKENCRYPTED;
 
887
        }
 
888
 
 
889
    } else {
 
890
        logg("Archive support disabled.\n");
 
891
    }
 
892
 
 
893
    if(optget(opts, "AlgorithmicDetection")->enabled) {
 
894
        logg("Algorithmic detection enabled.\n");
 
895
        options |= CL_SCAN_ALGORITHMIC;
 
896
    } else {
 
897
        logg("Algorithmic detection disabled.\n");
 
898
    }
 
899
 
 
900
    if(optget(opts, "ScanPE")->enabled) {
 
901
        logg("Portable Executable support enabled.\n");
 
902
        options |= CL_SCAN_PE;
 
903
    } else {
 
904
        logg("Portable Executable support disabled.\n");
 
905
    }
 
906
 
 
907
    if(optget(opts, "ScanELF")->enabled) {
 
908
        logg("ELF support enabled.\n");
 
909
        options |= CL_SCAN_ELF;
 
910
    } else {
 
911
        logg("ELF support disabled.\n");
 
912
    }
 
913
 
 
914
    if(optget(opts, "ScanPE")->enabled || optget(opts, "ScanELF")->enabled) {
 
915
        if(optget(opts, "DetectBrokenExecutables")->enabled) {
 
916
            logg("Detection of broken executables enabled.\n");
 
917
            options |= CL_SCAN_BLOCKBROKEN;
 
918
        }
 
919
    }
 
920
 
 
921
    if(optget(opts, "ScanMail")->enabled) {
 
922
        logg("Mail files support enabled.\n");
 
923
        options |= CL_SCAN_MAIL;
 
924
 
 
925
        if(optget(opts, "ScanPartialMessages")->enabled) {
 
926
            logg("Mail: RFC1341 handling enabled.\n");
 
927
            options |= CL_SCAN_PARTIAL_MESSAGE;
 
928
        }
 
929
 
 
930
    } else {
 
931
        logg("Mail files support disabled.\n");
 
932
    }
 
933
 
 
934
    if(optget(opts, "ScanOLE2")->enabled) {
 
935
        logg("OLE2 support enabled.\n");
 
936
        options |= CL_SCAN_OLE2;
 
937
        if(optget(opts, "OLE2BlockMacros")->enabled) {
 
938
            logg("OLE2: Blocking all VBA macros.\n");
 
939
            options |= CL_SCAN_BLOCKMACROS;
 
940
        }
 
941
    } else {
 
942
        logg("OLE2 support disabled.\n");
 
943
    }
 
944
 
 
945
    if(optget(opts, "ScanPDF")->enabled) {
 
946
        logg("PDF support enabled.\n");
 
947
        options |= CL_SCAN_PDF;
 
948
    } else {
 
949
        logg("PDF support disabled.\n");
 
950
    }
 
951
 
 
952
    if(optget(opts, "ScanSWF")->enabled) {
 
953
        logg("SWF support enabled.\n");
 
954
        options |= CL_SCAN_SWF;
 
955
    } else {
 
956
        logg("SWF support disabled.\n");
 
957
    }
 
958
 
 
959
    if(optget(opts, "ScanHTML")->enabled) {
 
960
        logg("HTML support enabled.\n");
 
961
        options |= CL_SCAN_HTML;
 
962
    } else {
 
963
        logg("HTML support disabled.\n");
 
964
    }
 
965
 
 
966
    if(optget(opts,"PhishingScanURLs")->enabled) {
 
967
 
 
968
        if(optget(opts,"PhishingAlwaysBlockCloak")->enabled) {
 
969
            options |= CL_SCAN_PHISHING_BLOCKCLOAK; 
 
970
            logg("Phishing: Always checking for cloaked urls\n");
 
971
        }
 
972
 
 
973
        if(optget(opts,"PhishingAlwaysBlockSSLMismatch")->enabled) {
 
974
            options |= CL_SCAN_PHISHING_BLOCKSSL;
 
975
            logg("Phishing: Always checking for ssl mismatches\n");
 
976
        }
 
977
    }
 
978
 
 
979
    if(optget(opts,"PartitionIntersection")->enabled) {
 
980
        options |= CL_SCAN_PARTITION_INTXN;
 
981
        logg("Raw DMG: Always checking for partitons intersections\n");
 
982
    }
 
983
 
 
984
    if(optget(opts,"HeuristicScanPrecedence")->enabled) {
 
985
            options |= CL_SCAN_HEURISTIC_PRECEDENCE;
 
986
            logg("Heuristic: precedence enabled\n");
 
987
    }
 
988
 
 
989
    if(optget(opts, "StructuredDataDetection")->enabled) {
 
990
        options |= CL_SCAN_STRUCTURED;
 
991
 
 
992
        if((opt = optget(opts, "StructuredMinCreditCardCount"))->enabled) {
 
993
            if((ret = cl_engine_set_num(engine, CL_ENGINE_MIN_CC_COUNT, opt->numarg))) {
 
994
                logg("!cl_engine_set_num(CL_ENGINE_MIN_CC_COUNT) failed: %s\n", cl_strerror(ret));
 
995
                cl_engine_free(engine);
 
996
                return 1;
 
997
            }
 
998
        }
 
999
        val = cl_engine_get_num(engine, CL_ENGINE_MIN_CC_COUNT, NULL);
 
1000
        logg("Structured: Minimum Credit Card Number Count set to %u\n", (unsigned int) val);
 
1001
 
 
1002
        if((opt = optget(opts, "StructuredMinSSNCount"))->enabled) {
 
1003
            if((ret = cl_engine_set_num(engine, CL_ENGINE_MIN_SSN_COUNT, opt->numarg))) {
 
1004
                logg("!cl_engine_set_num(CL_ENGINE_MIN_SSN_COUNT) failed: %s\n", cl_strerror(ret));
 
1005
                cl_engine_free(engine);
 
1006
                return 1;
 
1007
            }
 
1008
        }
 
1009
        val = cl_engine_get_num(engine, CL_ENGINE_MIN_SSN_COUNT, NULL);
 
1010
        logg("Structured: Minimum Social Security Number Count set to %u\n", (unsigned int) val);
 
1011
 
 
1012
        if(optget(opts, "StructuredSSNFormatNormal")->enabled)
 
1013
            options |= CL_SCAN_STRUCTURED_SSN_NORMAL;
 
1014
 
 
1015
        if(optget(opts, "StructuredSSNFormatStripped")->enabled)
 
1016
            options |= CL_SCAN_STRUCTURED_SSN_STRIPPED;
 
1017
    }
 
1018
 
 
1019
#ifdef HAVE__INTERNAL__SHA_COLLECT
 
1020
    if(optget(opts, "DevCollectHashes")->enabled)
 
1021
        options |= CL_SCAN_INTERNAL_COLLECT_SHA;
 
1022
#endif
 
1023
 
 
1024
    selfchk = optget(opts, "SelfCheck")->numarg;
 
1025
    if(!selfchk) {
 
1026
        logg("Self checking disabled.\n");
 
1027
    } else {
 
1028
        logg("Self checking every %u seconds.\n", selfchk);
 
1029
    }
 
1030
    memset(&dbstat, 0, sizeof(dbstat));
 
1031
 
 
1032
    /* save the PID */
 
1033
    mainpid = getpid();
 
1034
    if((opt = optget(opts, "PidFile"))->enabled) {
 
1035
            FILE *fd;
 
1036
        old_umask = umask(0002);
 
1037
        if((fd = fopen(opt->strarg, "w")) == NULL) {
 
1038
            logg("!Can't save PID in file %s\n", opt->strarg);
 
1039
        } else {
 
1040
            if (fprintf(fd, "%u\n", (unsigned int) mainpid)<0) {
 
1041
                logg("!Can't save PID in file %s\n", opt->strarg);
 
1042
            }
 
1043
            fclose(fd);
 
1044
        }
 
1045
        umask(old_umask);
 
1046
    }
 
1047
 
 
1048
    logg("*Listening daemon: PID: %u\n", (unsigned int) mainpid);
 
1049
    max_threads = optget(opts, "MaxThreads")->numarg;
 
1050
    max_queue = optget(opts, "MaxQueue")->numarg;
 
1051
    acceptdata.commandtimeout = optget(opts, "CommandReadTimeout")->numarg;
 
1052
    readtimeout = optget(opts, "ReadTimeout")->numarg;
 
1053
 
 
1054
#if !defined(_WIN32) && defined(RLIMIT_NOFILE)
 
1055
    if (getrlimit(RLIMIT_NOFILE, &rlim) == 0) {
 
1056
        /* don't warn if default value is too high, silently fix it */
 
1057
        unsigned maxrec;
 
1058
        int max_max_queue;
 
1059
        unsigned warn = optget(opts, "MaxQueue")->active;
 
1060
        const unsigned clamdfiles = 6;
 
1061
        /* Condition to not run out of file descriptors:
 
1062
         * MaxThreads * MaxRecursion + (MaxQueue - MaxThreads) + CLAMDFILES < RLIMIT_NOFILE 
 
1063
         * CLAMDFILES is 6: 3 standard FD + logfile + 2 FD for reloading the DB
 
1064
         * */
 
1065
#ifdef C_SOLARIS
 
1066
#ifdef HAVE_ENABLE_EXTENDED_FILE_STDIO
 
1067
        if (enable_extended_FILE_stdio(-1, -1) == -1) {
 
1068
            logg("^Unable to set extended FILE stdio, clamd will be limited to max 256 open files\n");
 
1069
            rlim.rlim_cur = rlim.rlim_cur > 255 ? 255 : rlim.rlim_cur;
 
1070
        }
 
1071
#elif !defined(_LP64)
 
1072
        if (rlim.rlim_cur > 255) {
 
1073
            rlim.rlim_cur = 255;
 
1074
            logg("^Solaris only supports 256 open files for 32-bit processes, you need at least Solaris 10u4, or compile as 64-bit to support more!\n");
 
1075
        }
 
1076
#endif
 
1077
#endif
 
1078
        opt = optget(opts,"MaxRecursion");
 
1079
        maxrec = opt->numarg;
 
1080
        max_max_queue = rlim.rlim_cur - maxrec * max_threads - clamdfiles + max_threads;
 
1081
        if (max_queue < max_threads) {
 
1082
            max_queue = max_threads;
 
1083
            if (warn)
 
1084
                logg("^MaxQueue value too low, increasing to: %d\n", max_queue);
 
1085
        }
 
1086
        if (max_max_queue < max_threads) {
 
1087
            logg("^MaxThreads * MaxRecursion is too high: %d, open file descriptor limit is: %lu\n",
 
1088
                 maxrec*max_threads, (unsigned long)rlim.rlim_cur);
 
1089
            max_max_queue = max_threads;
 
1090
        }
 
1091
        if (max_queue > max_max_queue) {
 
1092
            max_queue = max_max_queue;
 
1093
            if (warn)
 
1094
                logg("^MaxQueue value too high, lowering to: %d\n", max_queue);
 
1095
        } else if (max_queue < 2*max_threads && max_queue < max_max_queue) {
 
1096
            max_queue = 2*max_threads;
 
1097
            if (max_queue > max_max_queue)
 
1098
                max_queue = max_max_queue;
 
1099
            /* always warn here */
 
1100
            logg("^MaxQueue is lower than twice MaxThreads, increasing to: %d\n", max_queue);
 
1101
        }
 
1102
    }
 
1103
#endif
 
1104
    logg("*MaxQueue set to: %d\n", max_queue);
 
1105
    acceptdata.max_queue = max_queue;
 
1106
 
 
1107
    if(optget(opts, "ScanOnAccess")->enabled)
 
1108
#if defined(FANOTIFY) || defined(CLAMAUTH)
 
1109
    {
 
1110
        do {
 
1111
            if(pthread_attr_init(&fan_attr)) break;
 
1112
            pthread_attr_setdetachstate(&fan_attr, PTHREAD_CREATE_JOINABLE);
 
1113
            if(!(tharg = (struct thrarg *) malloc(sizeof(struct thrarg)))) break;
 
1114
            tharg->opts = opts;
 
1115
            tharg->engine = engine;
 
1116
            tharg->options = options;
 
1117
            if(!pthread_create(&fan_pid, &fan_attr, fan_th, tharg)) break;
 
1118
            free(tharg);
 
1119
            tharg=NULL;
 
1120
        } while(0);
 
1121
        if (!tharg) logg("!Unable to start on-access scan\n");
 
1122
    }
 
1123
#else
 
1124
        logg("!On-access scan is not available\n");
 
1125
#endif
 
1126
 
 
1127
#ifndef _WIN32
 
1128
    /* set up signal handling */
 
1129
    sigfillset(&sigset);
 
1130
    sigdelset(&sigset, SIGINT);
 
1131
    sigdelset(&sigset, SIGTERM);
 
1132
    sigdelset(&sigset, SIGSEGV);
 
1133
    sigdelset(&sigset, SIGHUP);
 
1134
    sigdelset(&sigset, SIGPIPE);
 
1135
    sigdelset(&sigset, SIGUSR2);
 
1136
    /* The behavior of a process is undefined after it ignores a 
 
1137
     * SIGFPE, SIGILL, SIGSEGV, or SIGBUS signal */
 
1138
    sigdelset(&sigset, SIGFPE);
 
1139
    sigdelset(&sigset, SIGILL);
 
1140
    sigdelset(&sigset, SIGSEGV);
 
1141
#ifdef SIGBUS    
 
1142
    sigdelset(&sigset, SIGBUS);
 
1143
#endif
 
1144
    sigdelset(&sigset, SIGTSTP);
 
1145
    sigdelset(&sigset, SIGCONT);
 
1146
    sigprocmask(SIG_SETMASK, &sigset, NULL);
 
1147
 
 
1148
    /* SIGINT, SIGTERM, SIGSEGV */
 
1149
    sigact.sa_handler = sighandler_th;
 
1150
    sigemptyset(&sigact.sa_mask);
 
1151
    sigaddset(&sigact.sa_mask, SIGINT);
 
1152
    sigaddset(&sigact.sa_mask, SIGTERM);
 
1153
    sigaddset(&sigact.sa_mask, SIGHUP);
 
1154
    sigaddset(&sigact.sa_mask, SIGPIPE);
 
1155
    sigaddset(&sigact.sa_mask, SIGUSR2);
 
1156
    sigaction(SIGINT, &sigact, NULL);
 
1157
    sigaction(SIGTERM, &sigact, NULL);
 
1158
    sigaction(SIGHUP, &sigact, NULL);
 
1159
    sigaction(SIGPIPE, &sigact, NULL);
 
1160
    sigaction(SIGUSR2, &sigact, NULL);
 
1161
#endif
 
1162
 
 
1163
    idletimeout = optget(opts, "IdleTimeout")->numarg;
 
1164
 
 
1165
    for (i=0;i < nsockets;i++)
 
1166
        if (fds_add(&acceptdata.fds, socketds[i], 1, 0) == -1) {
 
1167
            logg("!fds_add failed\n");
 
1168
            cl_engine_free(engine);
 
1169
            return 1;
 
1170
        }
 
1171
#ifdef _WIN32
 
1172
        event_wake_accept = CreateEvent(NULL, TRUE, FALSE, NULL);
 
1173
        event_wake_recv = CreateEvent(NULL, TRUE, FALSE, NULL);
 
1174
#else
 
1175
    if (pipe(acceptdata.syncpipe_wake_recv) == -1 ||
 
1176
        (pipe(acceptdata.syncpipe_wake_accept) == -1)) {
 
1177
 
 
1178
        logg("!pipe failed\n");
 
1179
        exit(-1);
 
1180
    }
 
1181
    syncpipe_wake_recv_w = acceptdata.syncpipe_wake_recv[1];
 
1182
 
 
1183
    if (fds_add(fds, acceptdata.syncpipe_wake_recv[0], 1, 0) == -1 ||
 
1184
        fds_add(&acceptdata.fds, acceptdata.syncpipe_wake_accept[0], 1, 0)) {
 
1185
        logg("!failed to add pipe fd\n");
 
1186
        exit(-1);
 
1187
    }
 
1188
#endif
 
1189
 
 
1190
    if ((thr_pool = thrmgr_new(max_threads, idletimeout, max_queue, scanner_thread)) == NULL) {
 
1191
        logg("!thrmgr_new failed\n");
 
1192
        exit(-1);
 
1193
    }
 
1194
 
 
1195
    if (pthread_create(&accept_th, NULL, acceptloop_th, &acceptdata)) {
 
1196
        logg("!pthread_create failed\n");
 
1197
        exit(-1);
 
1198
    }
 
1199
 
 
1200
    time(&start_time);
 
1201
    for(;;) {
 
1202
        int new_sd;
 
1203
 
 
1204
        /* Block waiting for connection on any of the sockets */
 
1205
        pthread_mutex_lock(fds->buf_mutex);
 
1206
        fds_cleanup(fds);
 
1207
        /* signal that we can accept more connections */
 
1208
        if (fds->nfds <= (unsigned)max_queue)
 
1209
            pthread_cond_signal(&acceptdata.cond_nfds);
 
1210
        new_sd = fds_poll_recv(fds, selfchk ? (int)selfchk : -1, 1, event_wake_recv);
 
1211
#ifdef _WIN32
 
1212
        ResetEvent(event_wake_recv);
 
1213
#else
 
1214
        if (!fds->nfds) {
 
1215
            /* at least the dummy/sync pipe should have remained */
 
1216
            logg("!All recv() descriptors gone: fatal\n");
 
1217
            pthread_mutex_lock(&exit_mutex);
 
1218
            progexit = 1;
 
1219
            pthread_mutex_unlock(&exit_mutex);
 
1220
            pthread_mutex_unlock(fds->buf_mutex);
 
1221
            break;
 
1222
        }
 
1223
#endif
 
1224
        if (new_sd == -1 && errno != EINTR) {
 
1225
            logg("!Failed to poll sockets, fatal\n");
 
1226
            pthread_mutex_lock(&exit_mutex);
 
1227
            progexit = 1;
 
1228
            pthread_mutex_unlock(&exit_mutex);
 
1229
        }
 
1230
 
 
1231
 
 
1232
        if(fds->nfds) i = (rr_last + 1) % fds->nfds;
 
1233
        for (j = 0;  j < fds->nfds && new_sd >= 0; j++, i = (i+1) % fds->nfds) {
 
1234
            size_t pos = 0;
 
1235
            int error = 0;
 
1236
            struct fd_buf *buf = &fds->buf[i];
 
1237
            if (!buf->got_newdata)
 
1238
                continue;
 
1239
 
 
1240
#ifndef _WIN32
 
1241
            if (buf->fd == acceptdata.syncpipe_wake_recv[0]) {
 
1242
                /* dummy sync pipe, just to wake us */
 
1243
                if (read(buf->fd, buff, sizeof(buff)) < 0) {
 
1244
                    logg("^Syncpipe read failed\n");
 
1245
                }
 
1246
                continue;
 
1247
            }
 
1248
#endif
 
1249
            if (buf->got_newdata == -1) {
 
1250
                if (buf->mode == MODE_WAITREPLY) {
 
1251
                    logg("$mode WAIT_REPLY -> closed\n");
 
1252
                    buf->fd = -1;
 
1253
                    thrmgr_group_terminate(buf->group);
 
1254
                    thrmgr_group_finished(buf->group, EXIT_ERROR);
 
1255
                    continue;
 
1256
                } else {
 
1257
                    logg("$client read error or EOF on read\n");
 
1258
                    error = 1;
 
1259
                }
 
1260
            }
 
1261
 
 
1262
            if (buf->fd != -1 && buf->got_newdata == -2) {
 
1263
                logg("$Client read timed out\n");
 
1264
                mdprintf(buf->fd, "COMMAND READ TIMED OUT\n");
 
1265
                error = 1;
 
1266
            }
 
1267
 
 
1268
            rr_last = i;
 
1269
            if (buf->mode == MODE_WAITANCILL) {
 
1270
                buf->mode = MODE_COMMAND;
 
1271
                logg("$mode -> MODE_COMMAND\n");
 
1272
            }
 
1273
            while (!error && buf->fd != -1 && buf->buffer && pos < buf->off &&
 
1274
                   buf->mode != MODE_WAITANCILL) {
 
1275
                client_conn_t conn;
 
1276
                const char *cmd = NULL;
 
1277
                int rc;
 
1278
                /* New data available to read on socket. */
 
1279
 
 
1280
                memset(&conn, 0, sizeof(conn));
 
1281
                conn.scanfd = buf->recvfd;
 
1282
                buf->recvfd = -1;
 
1283
                conn.sd = buf->fd;
 
1284
                conn.options = options;
 
1285
                conn.opts = opts;
 
1286
                conn.thrpool = thr_pool;
 
1287
                conn.engine = engine;
 
1288
                conn.group = buf->group;
 
1289
                conn.id = buf->id;
 
1290
                conn.quota = buf->quota;
 
1291
                conn.filename = buf->dumpname;
 
1292
                conn.mode = buf->mode;
 
1293
                conn.term = buf->term;
 
1294
 
 
1295
                /* Parse & dispatch command */
 
1296
                cmd = parse_dispatch_cmd(&conn, buf, &pos, &error, opts, readtimeout);
 
1297
 
 
1298
                if (conn.mode == MODE_COMMAND && !cmd)
 
1299
                    break;
 
1300
                if (!error) {
 
1301
                    if (buf->mode == MODE_WAITREPLY && buf->off) {
 
1302
                        /* Client is not supposed to send anything more */
 
1303
                        logg("^Client sent garbage after last command: %lu bytes\n", (unsigned long)buf->off);
 
1304
                        buf->buffer[buf->off] = '\0';
 
1305
                        logg("$Garbage: %s\n", buf->buffer);
 
1306
                        error = 1;
 
1307
                    } else if (buf->mode == MODE_STREAM) {
 
1308
                        rc = handle_stream(&conn, buf, opts, &error, &pos, readtimeout);
 
1309
                        if (rc == -1)
 
1310
                            break;
 
1311
                        else
 
1312
                            continue;
 
1313
                    }
 
1314
                }
 
1315
                if (error && error != CL_ETIMEOUT) {
 
1316
                    conn_reply_error(&conn, "Error processing command.");
 
1317
                }
 
1318
            }
 
1319
            if (error) {
 
1320
                if (buf->dumpfd != -1) {
 
1321
                    close(buf->dumpfd);
 
1322
                    if (buf->dumpname) {
 
1323
                        cli_unlink(buf->dumpname);
 
1324
                        free(buf->dumpname);
 
1325
                    }
 
1326
                    buf->dumpfd = -1;
 
1327
                }
 
1328
                thrmgr_group_terminate(buf->group);
 
1329
                if (thrmgr_group_finished(buf->group, EXIT_ERROR)) {
 
1330
                    if (buf->fd < 0) {
 
1331
                        logg("$Skipping shutdown of bad socket after error (FD %d)\n", buf->fd);
 
1332
                    }
 
1333
                    else {
 
1334
                        logg("$Shutting down socket after error (FD %d)\n", buf->fd);
 
1335
                        shutdown(buf->fd, 2);
 
1336
                        closesocket(buf->fd);
 
1337
                    }
 
1338
                } else
 
1339
                    logg("$Socket not shut down due to active tasks\n");
 
1340
                buf->fd = -1;
 
1341
            }
 
1342
        }
 
1343
        pthread_mutex_unlock(fds->buf_mutex);
 
1344
 
 
1345
        /* handle progexit */
 
1346
        pthread_mutex_lock(&exit_mutex);
 
1347
        if (progexit) {
 
1348
            pthread_mutex_unlock(&exit_mutex);
 
1349
            pthread_mutex_lock(fds->buf_mutex);
 
1350
            for (i=0;i < fds->nfds; i++) {
 
1351
                if (fds->buf[i].fd == -1)
 
1352
                    continue;
 
1353
                thrmgr_group_terminate(fds->buf[i].group);
 
1354
                if (thrmgr_group_finished(fds->buf[i].group, EXIT_ERROR)) {
 
1355
                    logg("$Shutdown closed fd %d\n", fds->buf[i].fd);
 
1356
                    shutdown(fds->buf[i].fd, 2);
 
1357
                    closesocket(fds->buf[i].fd);
 
1358
                    fds->buf[i].fd = -1;
 
1359
                }
 
1360
            }
 
1361
            pthread_mutex_unlock(fds->buf_mutex);
 
1362
            break;
 
1363
        }
 
1364
        pthread_mutex_unlock(&exit_mutex);
 
1365
 
 
1366
        /* SIGHUP */
 
1367
        if (sighup) {
 
1368
            logg("SIGHUP caught: re-opening log file.\n");
 
1369
            logg_close();
 
1370
            sighup = 0;
 
1371
            if(!logg_file && (opt = optget(opts, "LogFile"))->enabled)
 
1372
                logg_file = opt->strarg;
 
1373
        }
 
1374
 
 
1375
        /* SelfCheck */
 
1376
        if(selfchk) {
 
1377
            time(&current_time);
 
1378
            if((current_time - start_time) >= (time_t)selfchk) {
 
1379
                if(reload_db(engine, dboptions, opts, TRUE, &ret)) {
 
1380
                    pthread_mutex_lock(&reload_mutex);
 
1381
                    reload = 1;
 
1382
                    pthread_mutex_unlock(&reload_mutex);
 
1383
                }
 
1384
                time(&start_time);
 
1385
            }
 
1386
        }
 
1387
 
 
1388
        /* DB reload */
 
1389
        pthread_mutex_lock(&reload_mutex);
 
1390
        if(reload) {
 
1391
            pthread_mutex_unlock(&reload_mutex);
 
1392
#if defined(FANOTIFY) || defined(CLAMAUTH)
 
1393
            if(optget(opts, "ScanOnAccess")->enabled && tharg) {
 
1394
                logg("Restarting on-access scan\n");
 
1395
                pthread_kill(fan_pid, SIGUSR1);
 
1396
                pthread_join(fan_pid, NULL);
 
1397
            }
 
1398
#endif
 
1399
            engine = reload_db(engine, dboptions, opts, FALSE, &ret);
 
1400
            if(ret) {
 
1401
                logg("Terminating because of a fatal error.\n");
 
1402
                if(new_sd >= 0)
 
1403
                    closesocket(new_sd);
 
1404
                break;
 
1405
            }
 
1406
 
 
1407
            pthread_mutex_lock(&reload_mutex);
 
1408
            reload = 0;
 
1409
            time(&reloaded_time);
 
1410
            pthread_mutex_unlock(&reload_mutex);
 
1411
#if defined(FANOTIFY) || defined(CLAMAUTH)
 
1412
            if(optget(opts, "ScanOnAccess")->enabled && tharg) {
 
1413
                tharg->engine = engine;
 
1414
                pthread_create(&fan_pid, &fan_attr, fan_th, tharg);
 
1415
            }
 
1416
#endif
 
1417
            time(&start_time);
 
1418
        } else {
 
1419
            pthread_mutex_unlock(&reload_mutex);
 
1420
        }
 
1421
    }
 
1422
 
 
1423
    pthread_mutex_lock(&exit_mutex);
 
1424
    progexit = 1;
 
1425
    pthread_mutex_unlock(&exit_mutex);
 
1426
#ifdef _WIN32
 
1427
    SetEvent(event_wake_accept);
 
1428
#else
 
1429
    if (write(acceptdata.syncpipe_wake_accept[1], "", 1) < 0) {
 
1430
        logg("^Write to syncpipe failed\n");
 
1431
    }
 
1432
#endif
 
1433
    /* Destroy the thread manager.
 
1434
     * This waits for all current tasks to end
 
1435
     */
 
1436
    logg("*Waiting for all threads to finish\n");
 
1437
    thrmgr_destroy(thr_pool);
 
1438
#if defined(FANOTIFY) || defined(CLAMAUTH)
 
1439
    if(optget(opts, "ScanOnAccess")->enabled && tharg) {
 
1440
        logg("Stopping on-access scan\n");
 
1441
        pthread_kill(fan_pid, SIGUSR1);
 
1442
        pthread_join(fan_pid, NULL);
 
1443
    }
 
1444
#endif
 
1445
    if(engine) {
 
1446
        thrmgr_setactiveengine(NULL);
 
1447
        cl_engine_free(engine);
 
1448
    }
 
1449
 
 
1450
    pthread_join(accept_th, NULL);
 
1451
    fds_free(fds);
 
1452
    pthread_mutex_destroy(fds->buf_mutex);
 
1453
    pthread_cond_destroy(&acceptdata.cond_nfds);
 
1454
#ifdef _WIN32
 
1455
    CloseHandle(event_wake_accept);
 
1456
    CloseHandle(event_wake_recv);
 
1457
#else
 
1458
    close(acceptdata.syncpipe_wake_accept[1]);
 
1459
    close(acceptdata.syncpipe_wake_recv[1]);
 
1460
#endif
 
1461
    if(dbstat.entries)
 
1462
        cl_statfree(&dbstat);
 
1463
    logg("*Shutting down the main socket%s.\n", (nsockets > 1) ? "s" : "");
 
1464
    for (i = 0; i < nsockets; i++)
 
1465
        shutdown(socketds[i], 2);
 
1466
 
 
1467
    if((opt = optget(opts, "PidFile"))->enabled) {
 
1468
        if(unlink(opt->strarg) == -1)
 
1469
            logg("!Can't unlink the pid file %s\n", opt->strarg);
 
1470
        else
 
1471
            logg("Pid file removed.\n");
 
1472
    }
 
1473
 
 
1474
    time(&current_time);
 
1475
    logg("--- Stopped at %s", cli_ctime(&current_time, timestr, sizeof(timestr)));
 
1476
 
 
1477
    return ret;
 
1478
}