clamav/clamd/clamd_others.c

722 lines
20 KiB
C
Raw Normal View History

2003-07-29 15:48:06 +00:00
/*
* Copyright (C) 2013-2022 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
* Copyright (C) 2007-2013 Sourcefire, Inc.
*
* Authors: Tomasz Kojm, Trog, Török Edvin
2003-07-29 15:48:06 +00:00
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
2003-07-29 15:48:06 +00:00
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
2003-07-29 15:48:06 +00:00
*/
#if HAVE_CONFIG_H
#include "clamav-config.h"
#endif
2009-02-13 11:05:14 +00:00
/* must be first because it may define _XOPEN_SOURCE */
Add CMake build tooling This patch adds experimental-quality CMake build tooling. The libmspack build required a modification to use "" instead of <> for header #includes. This will hopefully be included in the libmspack upstream project when adding CMake build tooling to libmspack. Removed use of libltdl when using CMake. Flex & Bison are now required to build. If -DMAINTAINER_MODE, then GPERF is also required, though it currently doesn't actually do anything. TODO! I found that the autotools build system was generating the lexer output but not actually compiling it, instead using previously generated (and manually renamed) lexer c source. As a consequence, changes to the .l and .y files weren't making it into the build. To resolve this, I removed generated flex/bison files and fixed the tooling to use the freshly generated files. Flex and bison are now required build tools. On Windows, this adds a dependency on the winflexbison package, which can be obtained using Chocolatey or may be manually installed. CMake tooling only has partial support for building with external LLVM library, and no support for the internal LLVM (to be removed in the future). I.e. The CMake build currently only supports the bytecode interpreter. Many files used include paths relative to the top source directory or relative to the current project, rather than relative to each build target. Modern CMake support requires including internal dependency headers the same way you would external dependency headers (albeit with "" instead of <>). This meant correcting all header includes to be relative to the build targets and not relative to the workspace. For example, ... ```c include "../libclamav/clamav.h" include "clamd/clamd_others.h" ``` ... becomes: ```c // libclamav include "clamav.h" // clamd include "clamd_others.h" ``` Fixes header name conflicts by renaming a few of the files. Converted the "shared" code into a static library, which depends on libclamav. The ironically named "shared" static library provides features common to the ClamAV apps which are not required in libclamav itself and are not intended for use by downstream projects. This change was required for correct modern CMake practices but was also required to use the automake "subdir-objects" option. This eliminates warnings when running autoreconf which, in the next version of autoconf & automake are likely to break the build. libclamav used to build in multiple stages where an earlier stage is a static library containing utils required by the "shared" code. Linking clamdscan and clamdtop with this libclamav utils static lib allowed these two apps to function without libclamav. While this is nice in theory, the practical gains are minimal and it complicates the build system. As such, the autotools and CMake tooling was simplified for improved maintainability and this feature was thrown out. clamdtop and clamdscan now require libclamav to function. Removed the nopthreads version of the autotools libclamav_internal_utils static library and added pthread linking to a couple apps that may have issues building on some platforms without it, with the intention of removing needless complexity from the source. Kept the regular version of libclamav_internal_utils.la though it is no longer used anywhere but in libclamav. Added an experimental doxygen build option which attempts to build clamav.h and libfreshclam doxygen html docs. The CMake build tooling also may build the example program(s), which isn't a feature in the Autotools build system. Changed C standard to C90+ due to inline linking issues with socket.h when linking libfreshclam.so on Linux. Generate common.rc for win32. Fix tabs/spaces in shared Makefile.am, and remove vestigial ifndef from misc.c. Add CMake files to the automake dist, so users can try the new CMake tooling w/out having to build from a git clone. clamonacc changes: - Renamed FANOTIFY macro to HAVE_SYS_FANOTIFY_H to better match other similar macros. - Added a new clamav-clamonacc.service systemd unit file, based on the work of ChadDevOps & Aaron Brighton. - Added missing clamonacc man page. Updates to clamdscan man page, add missing options. Remove vestigial CL_NOLIBCLAMAV definitions (all apps now use libclamav). Rename Windows mspack.dll to libmspack.dll so all ClamAV-built libraries have the lib-prefix with Visual Studio as with CMake.
2020-08-13 00:25:34 -07:00
#include "fdpassing.h"
2003-07-29 15:48:06 +00:00
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#ifdef HAVE_UNISTD_H
2003-07-29 15:48:06 +00:00
#include <unistd.h>
#endif
2003-07-29 15:48:06 +00:00
#include <fcntl.h>
#include <time.h>
#include <sys/stat.h>
#include <errno.h>
#ifndef _WIN32
2004-03-09 12:28:08 +00:00
#include <sys/time.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#endif
#if HAVE_SYS_PARAM_H
#include <sys/param.h>
#endif
#ifdef HAVE_SYS_TYPES_H
2004-03-09 12:28:08 +00:00
#include <sys/types.h>
#endif
#ifdef HAVE_SYS_FILIO_H
2004-10-09 23:38:19 +00:00
#include <sys/filio.h>
#endif
#include <pthread.h>
2004-06-27 07:22:19 +00:00
#if HAVE_POLL
#if HAVE_POLL_H
#include <poll.h>
#else /* HAVE_POLL_H */
#if HAVE_SYS_SELECT_H
#include <sys/select.h>
#endif /* HAVE_SYS_SELECT_H */
#endif /* HAVE_POLL_H */
#endif /* HAVE_POLL */
2003-07-29 15:48:06 +00:00
#include <limits.h>
2006-09-05 20:45:39 +00:00
Add CMake build tooling This patch adds experimental-quality CMake build tooling. The libmspack build required a modification to use "" instead of <> for header #includes. This will hopefully be included in the libmspack upstream project when adding CMake build tooling to libmspack. Removed use of libltdl when using CMake. Flex & Bison are now required to build. If -DMAINTAINER_MODE, then GPERF is also required, though it currently doesn't actually do anything. TODO! I found that the autotools build system was generating the lexer output but not actually compiling it, instead using previously generated (and manually renamed) lexer c source. As a consequence, changes to the .l and .y files weren't making it into the build. To resolve this, I removed generated flex/bison files and fixed the tooling to use the freshly generated files. Flex and bison are now required build tools. On Windows, this adds a dependency on the winflexbison package, which can be obtained using Chocolatey or may be manually installed. CMake tooling only has partial support for building with external LLVM library, and no support for the internal LLVM (to be removed in the future). I.e. The CMake build currently only supports the bytecode interpreter. Many files used include paths relative to the top source directory or relative to the current project, rather than relative to each build target. Modern CMake support requires including internal dependency headers the same way you would external dependency headers (albeit with "" instead of <>). This meant correcting all header includes to be relative to the build targets and not relative to the workspace. For example, ... ```c include "../libclamav/clamav.h" include "clamd/clamd_others.h" ``` ... becomes: ```c // libclamav include "clamav.h" // clamd include "clamd_others.h" ``` Fixes header name conflicts by renaming a few of the files. Converted the "shared" code into a static library, which depends on libclamav. The ironically named "shared" static library provides features common to the ClamAV apps which are not required in libclamav itself and are not intended for use by downstream projects. This change was required for correct modern CMake practices but was also required to use the automake "subdir-objects" option. This eliminates warnings when running autoreconf which, in the next version of autoconf & automake are likely to break the build. libclamav used to build in multiple stages where an earlier stage is a static library containing utils required by the "shared" code. Linking clamdscan and clamdtop with this libclamav utils static lib allowed these two apps to function without libclamav. While this is nice in theory, the practical gains are minimal and it complicates the build system. As such, the autotools and CMake tooling was simplified for improved maintainability and this feature was thrown out. clamdtop and clamdscan now require libclamav to function. Removed the nopthreads version of the autotools libclamav_internal_utils static library and added pthread linking to a couple apps that may have issues building on some platforms without it, with the intention of removing needless complexity from the source. Kept the regular version of libclamav_internal_utils.la though it is no longer used anywhere but in libclamav. Added an experimental doxygen build option which attempts to build clamav.h and libfreshclam doxygen html docs. The CMake build tooling also may build the example program(s), which isn't a feature in the Autotools build system. Changed C standard to C90+ due to inline linking issues with socket.h when linking libfreshclam.so on Linux. Generate common.rc for win32. Fix tabs/spaces in shared Makefile.am, and remove vestigial ifndef from misc.c. Add CMake files to the automake dist, so users can try the new CMake tooling w/out having to build from a git clone. clamonacc changes: - Renamed FANOTIFY macro to HAVE_SYS_FANOTIFY_H to better match other similar macros. - Added a new clamav-clamonacc.service systemd unit file, based on the work of ChadDevOps & Aaron Brighton. - Added missing clamonacc man page. Updates to clamdscan man page, add missing options. Remove vestigial CL_NOLIBCLAMAV definitions (all apps now use libclamav). Rename Windows mspack.dll to libmspack.dll so all ClamAV-built libraries have the lib-prefix with Visual Studio as with CMake.
2020-08-13 00:25:34 -07:00
// libclamav
#include "clamav.h"
#include "scanners.h"
#include "others.h"
// common
Add CMake build tooling This patch adds experimental-quality CMake build tooling. The libmspack build required a modification to use "" instead of <> for header #includes. This will hopefully be included in the libmspack upstream project when adding CMake build tooling to libmspack. Removed use of libltdl when using CMake. Flex & Bison are now required to build. If -DMAINTAINER_MODE, then GPERF is also required, though it currently doesn't actually do anything. TODO! I found that the autotools build system was generating the lexer output but not actually compiling it, instead using previously generated (and manually renamed) lexer c source. As a consequence, changes to the .l and .y files weren't making it into the build. To resolve this, I removed generated flex/bison files and fixed the tooling to use the freshly generated files. Flex and bison are now required build tools. On Windows, this adds a dependency on the winflexbison package, which can be obtained using Chocolatey or may be manually installed. CMake tooling only has partial support for building with external LLVM library, and no support for the internal LLVM (to be removed in the future). I.e. The CMake build currently only supports the bytecode interpreter. Many files used include paths relative to the top source directory or relative to the current project, rather than relative to each build target. Modern CMake support requires including internal dependency headers the same way you would external dependency headers (albeit with "" instead of <>). This meant correcting all header includes to be relative to the build targets and not relative to the workspace. For example, ... ```c include "../libclamav/clamav.h" include "clamd/clamd_others.h" ``` ... becomes: ```c // libclamav include "clamav.h" // clamd include "clamd_others.h" ``` Fixes header name conflicts by renaming a few of the files. Converted the "shared" code into a static library, which depends on libclamav. The ironically named "shared" static library provides features common to the ClamAV apps which are not required in libclamav itself and are not intended for use by downstream projects. This change was required for correct modern CMake practices but was also required to use the automake "subdir-objects" option. This eliminates warnings when running autoreconf which, in the next version of autoconf & automake are likely to break the build. libclamav used to build in multiple stages where an earlier stage is a static library containing utils required by the "shared" code. Linking clamdscan and clamdtop with this libclamav utils static lib allowed these two apps to function without libclamav. While this is nice in theory, the practical gains are minimal and it complicates the build system. As such, the autotools and CMake tooling was simplified for improved maintainability and this feature was thrown out. clamdtop and clamdscan now require libclamav to function. Removed the nopthreads version of the autotools libclamav_internal_utils static library and added pthread linking to a couple apps that may have issues building on some platforms without it, with the intention of removing needless complexity from the source. Kept the regular version of libclamav_internal_utils.la though it is no longer used anywhere but in libclamav. Added an experimental doxygen build option which attempts to build clamav.h and libfreshclam doxygen html docs. The CMake build tooling also may build the example program(s), which isn't a feature in the Autotools build system. Changed C standard to C90+ due to inline linking issues with socket.h when linking libfreshclam.so on Linux. Generate common.rc for win32. Fix tabs/spaces in shared Makefile.am, and remove vestigial ifndef from misc.c. Add CMake files to the automake dist, so users can try the new CMake tooling w/out having to build from a git clone. clamonacc changes: - Renamed FANOTIFY macro to HAVE_SYS_FANOTIFY_H to better match other similar macros. - Added a new clamav-clamonacc.service systemd unit file, based on the work of ChadDevOps & Aaron Brighton. - Added missing clamonacc man page. Updates to clamdscan man page, add missing options. Remove vestigial CL_NOLIBCLAMAV definitions (all apps now use libclamav). Rename Windows mspack.dll to libmspack.dll so all ClamAV-built libraries have the lib-prefix with Visual Studio as with CMake.
2020-08-13 00:25:34 -07:00
#include "optparser.h"
#include "output.h"
#include "misc.h"
#include "clamd_others.h"
2010-11-04 16:42:08 +01:00
static pthread_mutex_t virusaction_lock = PTHREAD_MUTEX_INITIALIZER;
static void xfree(void *p)
{
if (p)
free(p);
}
#ifdef _WIN32
void virusaction(const char *filename, const char *virname,
const struct optstruct *opts)
{
if (optget(opts, "VirusEvent")->enabled)
logg("^VirusEvent is not supported on this platform"); /* Yet */
}
#else
#define VE_FILENAME "CLAM_VIRUSEVENT_FILENAME"
#define VE_VIRUSNAME "CLAM_VIRUSEVENT_VIRUSNAME"
void virusaction(const char *filename, const char *virname,
const struct optstruct *opts)
2003-08-06 03:05:51 +00:00
{
2012-07-03 15:13:18 -04:00
pid_t pid;
const struct optstruct *opt;
char *buffer_file, *buffer_vir, *buffer_cmd, *path;
2012-07-03 15:13:18 -04:00
const char *pt;
size_t i, j, v = 0, f = 0, len;
2012-07-03 15:13:18 -04:00
char *env[4];
if (!(opt = optget(opts, "VirusEvent"))->enabled)
2012-07-03 15:13:18 -04:00
return;
path = getenv("PATH");
env[0] = path ? strdup(path) : NULL;
j = env[0] ? 1 : 0;
2012-07-03 15:13:18 -04:00
/* Allocate env vars.. to be portable env vars should not be freed */
buffer_file =
(char *)malloc(strlen(VE_FILENAME) + strlen(filename) + 2);
if (buffer_file) {
sprintf(buffer_file, "%s=%s", VE_FILENAME, filename);
2012-07-03 15:13:18 -04:00
env[j++] = buffer_file;
}
buffer_vir =
(char *)malloc(strlen(VE_VIRUSNAME) + strlen(virname) + 2);
if (buffer_vir) {
sprintf(buffer_vir, "%s=%s", VE_VIRUSNAME, virname);
2012-07-03 15:13:18 -04:00
env[j++] = buffer_vir;
}
env[j++] = NULL;
pt = opt->strarg;
while ((pt = strstr(pt, "%v"))) {
2012-07-03 15:13:18 -04:00
pt += 2;
v++;
}
pt = opt->strarg;
while ((pt = strstr(pt, "%f"))) {
pt += 2;
f++;
}
len = strlen(opt->strarg);
2012-07-03 15:13:18 -04:00
buffer_cmd =
(char *)calloc(len + v * strlen(virname) + f * strlen(filename) + 1, sizeof(char));
if (!buffer_cmd) {
2012-07-05 10:47:30 -04:00
if (path)
xfree(env[0]);
xfree(buffer_file);
xfree(buffer_vir);
2012-07-03 15:13:18 -04:00
return;
}
for (i = 0, j = 0; i < len; i++) {
if (i + 1 < len && opt->strarg[i] == '%' && opt->strarg[i + 1] == 'v') {
strcat(buffer_cmd, virname);
j += strlen(virname);
2012-07-03 15:13:18 -04:00
i++;
} else if (i + 1 < len && opt->strarg[i] == '%' && opt->strarg[i + 1] == 'f') {
strcat(buffer_cmd, filename);
j += strlen(filename);
i++;
} else {
2012-07-03 15:13:18 -04:00
buffer_cmd[j++] = opt->strarg[i];
}
}
pthread_mutex_lock(&virusaction_lock);
2012-07-03 15:13:18 -04:00
/* We can only call async-signal-safe functions after fork(). */
pid = vfork();
if (pid == 0) { /* child */
_exit(execle("/bin/sh", "sh", "-c", buffer_cmd, NULL, env));
} else if (pid > 0) { /* parent */
pthread_mutex_unlock(&virusaction_lock);
while (waitpid(pid, NULL, 0) == -1 && errno == EINTR) continue;
} else {
pthread_mutex_unlock(&virusaction_lock);
logg("!VirusEvent: fork failed.\n");
2012-07-03 15:13:18 -04:00
}
2012-07-05 10:47:30 -04:00
if (path)
xfree(env[0]);
xfree(buffer_cmd);
xfree(buffer_file);
xfree(buffer_vir);
2003-08-06 03:05:51 +00:00
}
2009-09-24 16:08:52 +02:00
#endif /* _WIN32 */
/* Function: writen
Try hard to write the specified number of bytes
*/
int writen(int fd, void *buff, unsigned int count)
{
2012-07-03 15:13:18 -04:00
int retval;
unsigned int todo;
unsigned char *current;
todo = count;
current = (unsigned char *)buff;
2012-07-03 15:13:18 -04:00
do {
retval = write(fd, current, todo);
if (retval < 0) {
if (errno == EINTR) {
2012-07-03 15:13:18 -04:00
continue;
}
return -1;
}
todo -= retval;
current += retval;
} while (todo > 0);
2012-07-03 15:13:18 -04:00
return count;
}
2012-07-03 15:13:18 -04:00
static int
realloc_polldata(struct fd_data *data)
{
#ifdef HAVE_POLL
if (data->poll_data_nfds == data->nfds)
2012-07-03 15:13:18 -04:00
return 0;
if (data->poll_data)
free(data->poll_data);
data->poll_data = malloc(data->nfds * sizeof(*data->poll_data));
if (!data->poll_data) {
logg("!realloc_polldata: Memory allocation failed for poll_data\n");
2012-07-03 15:13:18 -04:00
return -1;
}
data->poll_data_nfds = data->nfds;
#endif
return 0;
}
int poll_fd(int fd, int timeout_sec, int check_signals)
{
int ret;
struct fd_data fds = FDS_INIT(NULL);
2012-07-03 15:13:18 -04:00
if (fds_add(&fds, fd, 1, timeout_sec) == -1)
2012-07-03 15:13:18 -04:00
return -1;
do {
ret = fds_poll_recv(&fds, timeout_sec, check_signals, NULL);
} while (ret == -1 && errno == EINTR);
fds_free(&fds);
return ret;
}
void fds_cleanup(struct fd_data *data)
{
struct fd_buf *newbuf;
2012-07-03 15:13:18 -04:00
unsigned i, j;
for (i = 0, j = 0; i < data->nfds; i++) {
if (data->buf[i].fd < 0) {
2012-07-03 15:13:18 -04:00
if (data->buf[i].buffer)
free(data->buf[i].buffer);
2012-07-03 15:13:18 -04:00
continue;
}
if (i != j)
data->buf[j] = data->buf[i];
j++;
}
if (j == data->nfds)
2012-07-03 15:13:18 -04:00
return;
for (i = j; i < data->nfds; i++)
data->buf[i].fd = -1;
data->nfds = j;
logg("$Number of file descriptors polled: %u fds\n",
(unsigned)data->nfds);
/* Shrink buffer */
newbuf = realloc(data->buf, j * sizeof(*newbuf));
2012-07-03 15:13:18 -04:00
if (!j)
data->buf = NULL;
2010-01-30 04:19:23 +01:00
else if (newbuf)
data->buf = newbuf; /* non-fatal if shrink fails */
}
2012-07-03 15:13:18 -04:00
static int
read_fd_data(struct fd_buf *buf)
{
ssize_t n;
2012-07-03 15:13:18 -04:00
buf->got_newdata = 1;
if (!buf->buffer) /* listen-only socket */
2012-07-03 15:13:18 -04:00
return 1;
if (buf->off >= buf->bufsize)
2012-07-03 15:13:18 -04:00
return -1;
/* Read the pending packet, it may contain more than one command, but
2020-01-03 15:44:07 -05:00
* that is to the cmdparser to handle.
2012-07-03 15:13:18 -04:00
* It will handle 1st command, and then move leftover to beginning of buffer
*/
#ifdef HAVE_FD_PASSING
2012-07-03 15:13:18 -04:00
{
struct msghdr msg;
struct cmsghdr *cmsg;
union {
unsigned char buff[CMSG_SPACE(sizeof(int))];
2012-07-03 15:13:18 -04:00
struct cmsghdr hdr;
} b;
struct iovec iov[1];
if (buf->recvfd != -1) {
logg("$Closing unclaimed FD: %d\n", buf->recvfd);
close(buf->recvfd);
2012-07-03 15:13:18 -04:00
buf->recvfd = -1;
}
memset(&msg, 0, sizeof(msg));
iov[0].iov_base = buf->buffer + buf->off;
iov[0].iov_len = buf->bufsize - buf->off;
msg.msg_iov = iov;
msg.msg_iovlen = 1;
msg.msg_control = b.buff;
msg.msg_controllen = sizeof(b.buff);
n = recvmsg(buf->fd, &msg, 0);
2012-07-03 15:13:18 -04:00
if (n < 0)
return -1;
if (msg.msg_flags & MSG_TRUNC) {
logg("^Message truncated at %d bytes\n", (int)n);
2012-07-03 15:13:18 -04:00
return -1;
}
if (msg.msg_flags & MSG_CTRUNC) {
2012-07-03 15:13:18 -04:00
if (msg.msg_controllen > 0)
logg("^Control message truncated at %d bytes, %d data read\n", (int)msg.msg_controllen, (int)n);
2012-07-03 15:13:18 -04:00
else
logg("^Control message truncated, no control data received, %d bytes read"
#ifdef C_LINUX
"(Is SELinux/AppArmor enabled, and blocking file descriptor passing?)"
#endif
"\n",
(int)n);
2012-07-03 15:13:18 -04:00
return -1;
}
if (msg.msg_controllen) {
for (cmsg = CMSG_FIRSTHDR(&msg); cmsg != NULL;
cmsg = CMSG_NXTHDR(&msg, cmsg)) {
if (cmsg->cmsg_len == CMSG_LEN(sizeof(int)) &&
2012-07-03 15:13:18 -04:00
cmsg->cmsg_level == SOL_SOCKET &&
cmsg->cmsg_type == SCM_RIGHTS) {
if (buf->recvfd != -1) {
logg("$Unclaimed file descriptor received. closing: %d\n", buf->recvfd);
close(buf->recvfd);
2012-07-03 15:13:18 -04:00
}
buf->recvfd = *(int *)CMSG_DATA(cmsg);
logg("$Receveived a file descriptor: %d\n", buf->recvfd);
2012-07-03 15:13:18 -04:00
}
}
}
}
#else
n = recv(buf->fd, buf->buffer + buf->off, buf->bufsize - buf->off, 0);
2012-07-03 15:13:18 -04:00
if (n < 0)
return -1;
#endif
2012-07-03 15:13:18 -04:00
buf->off += n;
return n;
}
2012-07-03 15:13:18 -04:00
static int
buf_init(struct fd_buf *buf, int listen_only, int timeout)
{
buf->off = 0;
buf->got_newdata = 0;
buf->recvfd = -1;
buf->mode = MODE_COMMAND;
buf->id = 0;
buf->dumpfd = -1;
buf->chunksize = 0;
buf->quota = 0;
buf->dumpname = NULL;
buf->group = NULL;
buf->term = '\0';
if (!listen_only) {
if (!buf->buffer) {
2012-07-03 15:13:18 -04:00
buf->bufsize = PATH_MAX + 8;
/* plus extra space for a \0 so we can make sure every command is \0
* terminated */
if (!(buf->buffer = malloc(buf->bufsize + 1))) {
logg("!add_fd: Memory allocation failed for command buffer\n");
2012-07-03 15:13:18 -04:00
return -1;
}
}
} else {
2012-07-03 15:13:18 -04:00
if (buf->buffer)
free(buf->buffer);
2012-07-03 15:13:18 -04:00
buf->bufsize = 0;
buf->buffer = NULL;
2012-07-03 15:13:18 -04:00
}
if (timeout) {
time(&buf->timeout_at);
2012-07-03 15:13:18 -04:00
buf->timeout_at += timeout;
} else {
2012-07-03 15:13:18 -04:00
buf->timeout_at = 0;
}
return 0;
}
int fds_add(struct fd_data *data, int fd, int listen_only, int timeout)
{
struct fd_buf *buf;
unsigned n;
if (fd < 0) {
logg("!add_fd: invalid fd passed to add_fd\n");
2012-07-03 15:13:18 -04:00
return -1;
}
/* we may already have this fd, if
* the old FD got closed, and the kernel reused the FD */
for (n = 0; n < data->nfds; n++)
if (data->buf[n].fd == fd) {
2012-07-03 15:13:18 -04:00
/* clear stale data in buffer */
if (buf_init(&data->buf[n], listen_only, timeout) < 0)
2012-07-03 15:13:18 -04:00
return -1;
return 0;
}
n++;
buf = realloc(data->buf, n * sizeof(*buf));
if (!buf) {
logg("!add_fd: Memory allocation failed for fd_buf\n");
2012-07-03 15:13:18 -04:00
return -1;
}
data->buf = buf;
data->nfds = n;
2012-07-03 15:13:18 -04:00
data->buf[n - 1].buffer = NULL;
if (buf_init(&data->buf[n - 1], listen_only, timeout) < 0)
2012-07-03 15:13:18 -04:00
return -1;
data->buf[n - 1].fd = fd;
return 0;
}
2012-07-03 15:13:18 -04:00
static inline void
fds_lock(struct fd_data *data)
{
if (data->buf_mutex)
pthread_mutex_lock(data->buf_mutex);
}
2012-07-03 15:13:18 -04:00
static inline void
fds_unlock(struct fd_data *data)
{
if (data->buf_mutex)
pthread_mutex_unlock(data->buf_mutex);
}
void fds_remove(struct fd_data *data, int fd)
{
size_t i;
fds_lock(data);
if (data->buf) {
for (i = 0; i < data->nfds; i++) {
if (data->buf[i].fd == fd) {
2012-07-03 15:13:18 -04:00
data->buf[i].fd = -1;
break;
}
}
}
fds_unlock(data);
}
#define BUFFSIZE 1024
/* Wait till data is available to be read on any of the fds,
* read available data on all fds, and mark them as appropriate.
* One of the fds should be a pipe, used by the accept thread to wake us.
* timeout is specified in seconds, if check_signals is non-zero, then
* poll_recv_fds() will return upon receipt of a signal, even if no data
* is received on any of the sockets.
* Must be called with buf_mutex lock held.
*/
/* TODO: handle ReadTimeout */
int fds_poll_recv(struct fd_data *data, int timeout, int check_signals,
void *event)
{
unsigned fdsok = data->nfds;
size_t i;
int retval;
time_t now, closest_timeout;
UNUSEDPARAM(event);
/* we must have at least one fd, the control fd! */
fds_cleanup(data);
2010-01-29 19:34:02 +01:00
#ifndef _WIN32
if (!data->nfds)
2012-07-03 15:13:18 -04:00
return 0;
2010-01-29 19:34:02 +01:00
#endif
for (i = 0; i < data->nfds; i++) {
2012-07-03 15:13:18 -04:00
data->buf[i].got_newdata = 0;
}
time(&now);
if (timeout > 0)
2012-07-03 15:13:18 -04:00
closest_timeout = now + timeout;
else
2012-07-03 15:13:18 -04:00
closest_timeout = 0;
for (i = 0; i < data->nfds; i++) {
2012-07-03 15:13:18 -04:00
time_t timeout_at = data->buf[i].timeout_at;
if (timeout_at && timeout_at < now) {
2012-07-03 15:13:18 -04:00
/* timed out */
data->buf[i].got_newdata = -2;
/* we must return immediately from poll/select, we have a timeout! */
closest_timeout = now;
} else {
2012-07-03 15:13:18 -04:00
if (!closest_timeout)
closest_timeout = timeout_at;
else if (timeout_at && timeout_at < closest_timeout)
closest_timeout = timeout_at;
}
}
if (closest_timeout)
2012-07-03 15:13:18 -04:00
timeout = closest_timeout - now;
else
2012-07-03 15:13:18 -04:00
timeout = -1;
if (timeout > 0)
logg("$fds_poll_recv: timeout after %d seconds\n", timeout);
#ifdef HAVE_POLL
/* Use poll() if available, preferred because:
* - can poll any number of FDs
* - can notify of both data available / socket disconnected events
* - when it says POLLIN it is guaranteed that a following recv() won't
2020-01-03 15:44:07 -05:00
* block (select may say that data is available to read, but a following
* recv() may still block according to the manpage
*/
if (realloc_polldata(data) == -1)
2012-07-03 15:13:18 -04:00
return -1;
if (timeout > 0) {
2012-07-03 15:13:18 -04:00
/* seconds to ms */
timeout *= 1000;
}
for (i = 0; i < data->nfds; i++) {
data->poll_data[i].fd = data->buf[i].fd;
data->poll_data[i].events = POLLIN;
2012-07-03 15:13:18 -04:00
data->poll_data[i].revents = 0;
}
do {
2012-07-03 15:13:18 -04:00
int n = data->nfds;
fds_unlock(data);
2010-01-29 18:57:50 +01:00
#ifdef _WIN32
retval = poll_with_event(data->poll_data, n, timeout, event);
2010-01-29 18:57:50 +01:00
#else
retval = poll(data->poll_data, n, timeout);
2010-01-29 18:57:50 +01:00
#endif
fds_lock(data);
2012-07-03 15:13:18 -04:00
if (retval > 0) {
2012-07-03 15:13:18 -04:00
fdsok = 0;
/* nfds may change during poll, but not
* poll_data_nfds */
for (i = 0; i < data->poll_data_nfds; i++) {
2012-07-03 15:13:18 -04:00
short revents;
if (data->buf[i].fd < 0)
continue;
if (data->buf[i].fd != data->poll_data[i].fd) {
2012-07-03 15:13:18 -04:00
/* should never happen */
logg("!poll_recv_fds FD mismatch\n");
2012-07-03 15:13:18 -04:00
continue;
}
revents = data->poll_data[i].revents;
if (revents & (POLLIN | POLLHUP)) {
logg("$Received POLLIN|POLLHUP on fd %d\n",
data->poll_data[i].fd);
2012-07-03 15:13:18 -04:00
}
2010-03-21 11:44:07 +01:00
#ifndef _WIN32
if (revents & POLLHUP) {
2012-07-03 15:13:18 -04:00
/* avoid SHUT_WR problem on Mac OS X */
int ret = send(data->poll_data[i].fd, &n, 0, 0);
2012-07-03 15:13:18 -04:00
if (!ret || (ret == -1 && errno == EINTR))
revents &= ~POLLHUP;
}
2010-03-21 11:44:07 +01:00
#endif
if (revents & POLLIN) {
int ret = read_fd_data(&data->buf[i]);
2012-07-03 15:13:18 -04:00
/* Data available to be read */
if (ret == -1)
revents |= POLLERR;
else if (!ret)
revents = POLLHUP;
}
if (revents & (POLLHUP | POLLERR | POLLNVAL)) {
if (revents & (POLLHUP | POLLNVAL)) {
2012-07-03 15:13:18 -04:00
/* remote disconnected */
logg("*Client disconnected (FD %d)\n",
data->poll_data[i].fd);
} else {
2012-07-03 15:13:18 -04:00
/* error on file descriptor */
logg("^Error condition on fd %d\n",
data->poll_data[i].fd);
2012-07-03 15:13:18 -04:00
}
data->buf[i].got_newdata = -1;
} else {
2012-07-03 15:13:18 -04:00
fdsok++;
}
}
}
} while (retval == -1 && !check_signals && errno == EINTR);
#else
2010-01-28 23:36:37 +01:00
{
2012-07-03 15:13:18 -04:00
fd_set rfds;
struct timeval tv;
int maxfd = -1;
for (i = 0; i < data->nfds; i++) {
2012-07-03 15:13:18 -04:00
int fd = data->buf[i].fd;
if (fd >= FD_SETSIZE) {
logg("!File descriptor is too high for FD_SET\n");
2012-07-03 15:13:18 -04:00
return -1;
}
maxfd = MAX(maxfd, fd);
2012-07-03 15:13:18 -04:00
}
do {
FD_ZERO(&rfds);
for (i = 0; i < data->nfds; i++) {
2012-07-03 15:13:18 -04:00
int fd = data->buf[i].fd;
if (fd >= 0)
FD_SET(fd, &rfds);
2012-07-03 15:13:18 -04:00
}
tv.tv_sec = timeout;
2012-07-03 15:13:18 -04:00
tv.tv_usec = 0;
fds_unlock(data);
2012-07-03 15:13:18 -04:00
retval =
select(maxfd + 1, &rfds, NULL, NULL,
timeout >= 0 ? &tv : NULL);
fds_lock(data);
if (retval > 0) {
2012-07-03 15:13:18 -04:00
fdsok = data->nfds;
for (i = 0; i < data->nfds; i++) {
if (data->buf[i].fd < 0) {
2012-07-03 15:13:18 -04:00
fdsok--;
continue;
}
if (FD_ISSET(data->buf[i].fd, &rfds)) {
int ret = read_fd_data(&data->buf[i]);
if (ret == -1 || !ret) {
2012-07-03 15:13:18 -04:00
if (ret == -1)
logg("!Error condition on fd %d\n",
data->buf[i].fd);
else {
2012-07-03 15:13:18 -04:00
/* avoid SHUT_WR problem on Mac OS X */
int ret = send(data->buf[i].fd, &i, 0, 0);
2012-07-03 15:13:18 -04:00
if (!ret || (ret == -1 && errno == EINTR))
continue;
logg("*Client disconnected\n");
2012-07-03 15:13:18 -04:00
}
data->buf[i].got_newdata = -1;
}
}
}
}
if (retval < 0 && errno == EBADF) {
2012-07-03 15:13:18 -04:00
/* unlike poll(), select() won't tell us which FD is bad, so
* we have to check them one by one. */
tv.tv_sec = 0;
2012-07-03 15:13:18 -04:00
tv.tv_usec = 0;
/* with tv == 0 it doesn't check for EBADF */
FD_ZERO(&rfds);
for (i = 0; i < data->nfds; i++) {
2012-07-03 15:13:18 -04:00
if (data->buf[i].fd == -1)
continue;
FD_SET(data->buf[i].fd, &rfds);
do {
2012-07-03 15:13:18 -04:00
retval =
select(data->buf[i].fd + 1, &rfds, NULL, NULL,
&tv);
} while (retval == -1 && errno == EINTR);
if (retval == -1) {
2012-07-03 15:13:18 -04:00
data->buf[i].fd = -1;
} else {
FD_CLR(data->buf[i].fd, &rfds);
2012-07-03 15:13:18 -04:00
}
}
retval = -1;
errno = EINTR;
2012-07-03 15:13:18 -04:00
continue;
}
} while (retval == -1 && !check_signals && errno == EINTR);
2010-01-28 23:36:37 +01:00
}
#endif
if (retval == -1 && errno != EINTR) {
2012-07-03 15:13:18 -04:00
char err[128];
#ifdef HAVE_POLL
logg("!poll_recv_fds: poll failed: %s\n",
cli_strerror(errno, err, sizeof(err)));
#else
logg("!poll_recv_fds: select failed: %s\n",
cli_strerror(errno, err, sizeof(err)));
#endif
}
return retval;
}
void fds_free(struct fd_data *data)
{
unsigned i;
fds_lock(data);
for (i = 0; i < data->nfds; i++) {
if (data->buf[i].buffer) {
free(data->buf[i].buffer);
2012-07-03 15:13:18 -04:00
}
}
if (data->buf)
free(data->buf);
#ifdef HAVE_POLL
if (data->poll_data)
free(data->poll_data);
#endif
data->buf = NULL;
data->nfds = 0;
fds_unlock(data);
}