~ubuntu-branches/ubuntu/utopic/clamav/utopic-updates

« back to all changes in this revision

Viewing changes to .pc/0007-Add-an-additional-n-after-the-number-in-the-pidfile.patch/clamd/server-th.c

  • Committer: Package Import Robot
  • Author(s): Scott Kitterman
  • Date: 2014-04-25 15:01:05 UTC
  • mfrom: (0.35.41 sid)
  • Revision ID: package-import@ubuntu.com-20140425150105-n4wqi1w9yjgktgfb
Tags: 0.98.1+dfsg-5ubuntu1
* Merge from Debian unstable.  Remaining changes:
  - Drop build-dep on electric-fence (in Universe)

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