summaryrefslogtreecommitdiffstats
path: root/lib/isc/unix
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--lib/isc/unix/Makefile.in48
-rw-r--r--lib/isc/unix/dir.c268
-rw-r--r--lib/isc/unix/errno.c24
-rw-r--r--lib/isc/unix/errno2result.c131
-rw-r--r--lib/isc/unix/errno2result.h37
-rw-r--r--lib/isc/unix/file.c840
-rw-r--r--lib/isc/unix/fsaccess.c87
-rw-r--r--lib/isc/unix/ifiter_getifaddrs.c240
l---------lib/isc/unix/include/.clang-format1
-rw-r--r--lib/isc/unix/include/Makefile.in19
-rw-r--r--lib/isc/unix/include/isc/Makefile.in37
-rw-r--r--lib/isc/unix/include/isc/align.h20
-rw-r--r--lib/isc/unix/include/isc/dir.h75
-rw-r--r--lib/isc/unix/include/isc/net.h310
-rw-r--r--lib/isc/unix/include/isc/netdb.h51
-rw-r--r--lib/isc/unix/include/isc/offset.h28
-rw-r--r--lib/isc/unix/include/isc/stat.h47
-rw-r--r--lib/isc/unix/include/isc/stdatomic.h224
-rw-r--r--lib/isc/unix/include/isc/stdtime.h64
-rw-r--r--lib/isc/unix/include/isc/syslog.h41
-rw-r--r--lib/isc/unix/include/isc/time.h452
-rw-r--r--lib/isc/unix/interfaceiter.c301
-rw-r--r--lib/isc/unix/meminfo.c50
-rw-r--r--lib/isc/unix/net.c860
-rw-r--r--lib/isc/unix/os.c68
-rw-r--r--lib/isc/unix/pk11_api.c708
-rw-r--r--lib/isc/unix/resource.c219
-rw-r--r--lib/isc/unix/socket.c5521
-rw-r--r--lib/isc/unix/socket_p.h27
-rw-r--r--lib/isc/unix/stdio.c152
-rw-r--r--lib/isc/unix/stdtime.c68
-rw-r--r--lib/isc/unix/syslog.c73
-rw-r--r--lib/isc/unix/time.c553
33 files changed, 11644 insertions, 0 deletions
diff --git a/lib/isc/unix/Makefile.in b/lib/isc/unix/Makefile.in
new file mode 100644
index 0000000..4af7d6e
--- /dev/null
+++ b/lib/isc/unix/Makefile.in
@@ -0,0 +1,48 @@
+# Copyright (C) Internet Systems Consortium, Inc. ("ISC")
+#
+# SPDX-License-Identifier: MPL-2.0
+#
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, you can obtain one at https://mozilla.org/MPL/2.0/.
+#
+# See the COPYRIGHT file distributed with this work for additional
+# information regarding copyright ownership.
+
+srcdir = @srcdir@
+VPATH = @srcdir@
+top_srcdir = @top_srcdir@
+
+CINCLUDES = -I${srcdir}/include \
+ -I${srcdir}/../pthreads/include \
+ -I../include \
+ -I${srcdir}/../include \
+ -I${srcdir}/.. \
+ ${OPENSSL_CFLAGS} \
+ ${JSON_C_CFLAGS} \
+ ${LIBXML2_CFLAGS}
+
+CDEFINES =
+CWARNINGS =
+
+# Alphabetically
+OBJS = pk11_api.@O@ \
+ dir.@O@ errno.@O@ errno2result.@O@ \
+ file.@O@ fsaccess.@O@ interfaceiter.@O@ \
+ meminfo.@O@ \
+ net.@O@ os.@O@ resource.@O@ socket.@O@ stdio.@O@ stdtime.@O@ \
+ syslog.@O@ time.@O@
+
+# Alphabetically
+SRCS = pk11_api.c \
+ dir.c errno.c errno2result.c \
+ file.c fsaccess.c interfaceiter.c meminfo.c \
+ net.c os.c resource.c socket.c stdio.c stdtime.c \
+ syslog.c time.c
+
+SUBDIRS = include
+TARGETS = ${OBJS}
+
+@BIND9_MAKE_RULES@
+
+interfaceiter.@O@: interfaceiter.c ifiter_getifaddrs.c
diff --git a/lib/isc/unix/dir.c b/lib/isc/unix/dir.c
new file mode 100644
index 0000000..b7eabe9
--- /dev/null
+++ b/lib/isc/unix/dir.c
@@ -0,0 +1,268 @@
+/*
+ * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
+ *
+ * SPDX-License-Identifier: MPL-2.0
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, you can obtain one at https://mozilla.org/MPL/2.0/.
+ *
+ * See the COPYRIGHT file distributed with this work for additional
+ * information regarding copyright ownership.
+ */
+
+/*! \file */
+
+#include <ctype.h>
+#include <errno.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include <isc/dir.h>
+#include <isc/magic.h>
+#include <isc/netdb.h>
+#include <isc/print.h>
+#include <isc/string.h>
+#include <isc/util.h>
+
+#include "errno2result.h"
+
+#define ISC_DIR_MAGIC ISC_MAGIC('D', 'I', 'R', '*')
+#define VALID_DIR(dir) ISC_MAGIC_VALID(dir, ISC_DIR_MAGIC)
+
+void
+isc_dir_init(isc_dir_t *dir) {
+ REQUIRE(dir != NULL);
+
+ dir->entry.name[0] = '\0';
+ dir->entry.length = 0;
+
+ dir->handle = NULL;
+
+ dir->magic = ISC_DIR_MAGIC;
+}
+
+/*!
+ * \brief Allocate workspace and open directory stream. If either one fails,
+ * NULL will be returned.
+ */
+isc_result_t
+isc_dir_open(isc_dir_t *dir, const char *dirname) {
+ char *p;
+ isc_result_t result = ISC_R_SUCCESS;
+
+ REQUIRE(VALID_DIR(dir));
+ REQUIRE(dirname != NULL);
+
+ /*
+ * Copy directory name. Need to have enough space for the name,
+ * a possible path separator, the wildcard, and the final NUL.
+ */
+ if (strlen(dirname) + 3 > sizeof(dir->dirname)) {
+ /* XXXDCL ? */
+ return (ISC_R_NOSPACE);
+ }
+ strlcpy(dir->dirname, dirname, sizeof(dir->dirname));
+
+ /*
+ * Append path separator, if needed, and "*".
+ */
+ p = dir->dirname + strlen(dir->dirname);
+ if (dir->dirname < p && *(p - 1) != '/') {
+ *p++ = '/';
+ }
+ *p++ = '*';
+ *p = '\0';
+
+ /*
+ * Open stream.
+ */
+ dir->handle = opendir(dirname);
+
+ if (dir->handle == NULL) {
+ return (isc__errno2result(errno));
+ }
+
+ return (result);
+}
+
+/*!
+ * \brief Return previously retrieved file or get next one.
+ *
+ * Unix's dirent has
+ * separate open and read functions, but the Win32 and DOS interfaces open
+ * the dir stream and reads the first file in one operation.
+ */
+isc_result_t
+isc_dir_read(isc_dir_t *dir) {
+ struct dirent *entry;
+
+ REQUIRE(VALID_DIR(dir) && dir->handle != NULL);
+
+ /*
+ * Fetch next file in directory.
+ */
+ entry = readdir(dir->handle);
+
+ if (entry == NULL) {
+ return (ISC_R_NOMORE);
+ }
+
+ /*
+ * Make sure that the space for the name is long enough.
+ */
+ if (sizeof(dir->entry.name) <= strlen(entry->d_name)) {
+ return (ISC_R_UNEXPECTED);
+ }
+
+ strlcpy(dir->entry.name, entry->d_name, sizeof(dir->entry.name));
+
+ /*
+ * Some dirents have d_namlen, but it is not portable.
+ */
+ dir->entry.length = strlen(entry->d_name);
+
+ return (ISC_R_SUCCESS);
+}
+
+/*!
+ * \brief Close directory stream.
+ */
+void
+isc_dir_close(isc_dir_t *dir) {
+ REQUIRE(VALID_DIR(dir) && dir->handle != NULL);
+
+ (void)closedir(dir->handle);
+ dir->handle = NULL;
+}
+
+/*!
+ * \brief Reposition directory stream at start.
+ */
+isc_result_t
+isc_dir_reset(isc_dir_t *dir) {
+ REQUIRE(VALID_DIR(dir) && dir->handle != NULL);
+
+ rewinddir(dir->handle);
+
+ return (ISC_R_SUCCESS);
+}
+
+isc_result_t
+isc_dir_chdir(const char *dirname) {
+ /*!
+ * \brief Change the current directory to 'dirname'.
+ */
+
+ REQUIRE(dirname != NULL);
+
+ if (chdir(dirname) < 0) {
+ return (isc__errno2result(errno));
+ }
+
+ return (ISC_R_SUCCESS);
+}
+
+isc_result_t
+isc_dir_chroot(const char *dirname) {
+#ifdef HAVE_CHROOT
+ void *tmp;
+#endif /* ifdef HAVE_CHROOT */
+
+ REQUIRE(dirname != NULL);
+
+#ifdef HAVE_CHROOT
+ /*
+ * Try to use getservbyname and getprotobyname before chroot.
+ * If WKS records are used in a zone under chroot, Name Service Switch
+ * may fail to load library in chroot.
+ * Do not report errors if it fails, we do not need any result now.
+ */
+ tmp = getprotobyname("udp");
+ if (tmp != NULL) {
+ (void)getservbyname("domain", "udp");
+ }
+
+ if (chroot(dirname) < 0 || chdir("/") < 0) {
+ return (isc__errno2result(errno));
+ }
+
+ return (ISC_R_SUCCESS);
+#else /* ifdef HAVE_CHROOT */
+ return (ISC_R_NOTIMPLEMENTED);
+#endif /* ifdef HAVE_CHROOT */
+}
+
+isc_result_t
+isc_dir_createunique(char *templet) {
+ isc_result_t result;
+ char *x;
+ char *p;
+ int i;
+ int pid;
+
+ REQUIRE(templet != NULL);
+
+ /*!
+ * \brief mkdtemp is not portable, so this emulates it.
+ */
+
+ pid = getpid();
+
+ /*
+ * Replace trailing Xs with the process-id, zero-filled.
+ */
+ for (x = templet + strlen(templet) - 1; *x == 'X' && x >= templet;
+ x--, pid /= 10)
+ {
+ *x = pid % 10 + '0';
+ }
+
+ x++; /* Set x to start of ex-Xs. */
+
+ do {
+ i = mkdir(templet, 0700);
+ if (i == 0 || errno != EEXIST) {
+ break;
+ }
+
+ /*
+ * The BSD algorithm.
+ */
+ p = x;
+ while (*p != '\0') {
+ if (isdigit((unsigned char)*p)) {
+ *p = 'a';
+ } else if (*p != 'z') {
+ ++*p;
+ } else {
+ /*
+ * Reset character and move to next.
+ */
+ *p++ = 'a';
+ continue;
+ }
+
+ break;
+ }
+
+ if (*p == '\0') {
+ /*
+ * Tried all combinations. errno should already
+ * be EEXIST, but ensure it is anyway for
+ * isc__errno2result().
+ */
+ errno = EEXIST;
+ break;
+ }
+ } while (1);
+
+ if (i == -1) {
+ result = isc__errno2result(errno);
+ } else {
+ result = ISC_R_SUCCESS;
+ }
+
+ return (result);
+}
diff --git a/lib/isc/unix/errno.c b/lib/isc/unix/errno.c
new file mode 100644
index 0000000..5875f3b
--- /dev/null
+++ b/lib/isc/unix/errno.c
@@ -0,0 +1,24 @@
+/*
+ * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
+ *
+ * SPDX-License-Identifier: MPL-2.0
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, you can obtain one at https://mozilla.org/MPL/2.0/.
+ *
+ * See the COPYRIGHT file distributed with this work for additional
+ * information regarding copyright ownership.
+ */
+
+/*! \file */
+
+#include <isc/errno.h>
+#include <isc/util.h>
+
+#include "errno2result.h"
+
+isc_result_t
+isc_errno_toresult(int err) {
+ return (isc___errno2result(err, false, 0, 0));
+}
diff --git a/lib/isc/unix/errno2result.c b/lib/isc/unix/errno2result.c
new file mode 100644
index 0000000..6f752df
--- /dev/null
+++ b/lib/isc/unix/errno2result.c
@@ -0,0 +1,131 @@
+/*
+ * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
+ *
+ * SPDX-License-Identifier: MPL-2.0
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, you can obtain one at https://mozilla.org/MPL/2.0/.
+ *
+ * See the COPYRIGHT file distributed with this work for additional
+ * information regarding copyright ownership.
+ */
+
+/*! \file */
+
+#include "errno2result.h"
+#include <stdbool.h>
+
+#include <isc/platform.h>
+#include <isc/result.h>
+#include <isc/strerr.h>
+#include <isc/string.h>
+#include <isc/util.h>
+
+/*%
+ * Convert a POSIX errno value into an isc_result_t. The
+ * list of supported errno values is not complete; new users
+ * of this function should add any expected errors that are
+ * not already there.
+ */
+isc_result_t
+isc___errno2result(int posixerrno, bool dolog, const char *file,
+ unsigned int line) {
+ char strbuf[ISC_STRERRORSIZE];
+
+ switch (posixerrno) {
+ case ENOTDIR:
+ case ELOOP:
+ case EINVAL: /* XXX sometimes this is not for files */
+ case ENAMETOOLONG:
+ case EBADF:
+ return (ISC_R_INVALIDFILE);
+ case ENOENT:
+ return (ISC_R_FILENOTFOUND);
+ case EACCES:
+ case EPERM:
+ return (ISC_R_NOPERM);
+ case EEXIST:
+ return (ISC_R_FILEEXISTS);
+ case EIO:
+ return (ISC_R_IOERROR);
+ case ENOMEM:
+ return (ISC_R_NOMEMORY);
+ case ENFILE:
+ case EMFILE:
+ return (ISC_R_TOOMANYOPENFILES);
+#ifdef EDQUOT
+ case EDQUOT:
+ return (ISC_R_DISCQUOTA);
+#endif /* ifdef EDQUOT */
+ case ENOSPC:
+ return (ISC_R_DISCFULL);
+#ifdef EOVERFLOW
+ case EOVERFLOW:
+ return (ISC_R_RANGE);
+#endif /* ifdef EOVERFLOW */
+ case EPIPE:
+#ifdef ECONNRESET
+ case ECONNRESET:
+#endif /* ifdef ECONNRESET */
+#ifdef ECONNABORTED
+ case ECONNABORTED:
+#endif /* ifdef ECONNABORTED */
+ return (ISC_R_CONNECTIONRESET);
+#ifdef ENOTCONN
+ case ENOTCONN:
+ return (ISC_R_NOTCONNECTED);
+#endif /* ifdef ENOTCONN */
+#ifdef ETIMEDOUT
+ case ETIMEDOUT:
+ return (ISC_R_TIMEDOUT);
+#endif /* ifdef ETIMEDOUT */
+#ifdef ENOBUFS
+ case ENOBUFS:
+ return (ISC_R_NORESOURCES);
+#endif /* ifdef ENOBUFS */
+#ifdef EAFNOSUPPORT
+ case EAFNOSUPPORT:
+ return (ISC_R_FAMILYNOSUPPORT);
+#endif /* ifdef EAFNOSUPPORT */
+#ifdef ENETDOWN
+ case ENETDOWN:
+ return (ISC_R_NETDOWN);
+#endif /* ifdef ENETDOWN */
+#ifdef EHOSTDOWN
+ case EHOSTDOWN:
+ return (ISC_R_HOSTDOWN);
+#endif /* ifdef EHOSTDOWN */
+#ifdef ENETUNREACH
+ case ENETUNREACH:
+ return (ISC_R_NETUNREACH);
+#endif /* ifdef ENETUNREACH */
+#ifdef EHOSTUNREACH
+ case EHOSTUNREACH:
+ return (ISC_R_HOSTUNREACH);
+#endif /* ifdef EHOSTUNREACH */
+#ifdef EADDRINUSE
+ case EADDRINUSE:
+ return (ISC_R_ADDRINUSE);
+#endif /* ifdef EADDRINUSE */
+ case EADDRNOTAVAIL:
+ return (ISC_R_ADDRNOTAVAIL);
+ case ECONNREFUSED:
+ return (ISC_R_CONNREFUSED);
+ default:
+ if (dolog) {
+ strerror_r(posixerrno, strbuf, sizeof(strbuf));
+ UNEXPECTED_ERROR(file, line,
+ "unable to convert errno "
+ "to isc_result: %d: %s",
+ posixerrno, strbuf);
+ }
+ /*
+ * XXXDCL would be nice if perhaps this function could
+ * return the system's error string, so the caller
+ * might have something more descriptive than "unexpected
+ * error" to log with.
+ */
+ return (ISC_R_UNEXPECTED);
+ }
+}
diff --git a/lib/isc/unix/errno2result.h b/lib/isc/unix/errno2result.h
new file mode 100644
index 0000000..05de1f2
--- /dev/null
+++ b/lib/isc/unix/errno2result.h
@@ -0,0 +1,37 @@
+/*
+ * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
+ *
+ * SPDX-License-Identifier: MPL-2.0
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, you can obtain one at https://mozilla.org/MPL/2.0/.
+ *
+ * See the COPYRIGHT file distributed with this work for additional
+ * information regarding copyright ownership.
+ */
+
+#ifndef UNIX_ERRNO2RESULT_H
+#define UNIX_ERRNO2RESULT_H 1
+
+/*! \file */
+
+/* XXXDCL this should be moved to lib/isc/include/isc/errno2result.h. */
+
+#include <errno.h> /* Provides errno. */
+#include <stdbool.h>
+
+#include <isc/lang.h>
+#include <isc/types.h>
+
+ISC_LANG_BEGINDECLS
+
+#define isc__errno2result(x) isc___errno2result(x, true, __FILE__, __LINE__)
+
+isc_result_t
+isc___errno2result(int posixerrno, bool dolog, const char *file,
+ unsigned int line);
+
+ISC_LANG_ENDDECLS
+
+#endif /* UNIX_ERRNO2RESULT_H */
diff --git a/lib/isc/unix/file.c b/lib/isc/unix/file.c
new file mode 100644
index 0000000..0604f14
--- /dev/null
+++ b/lib/isc/unix/file.c
@@ -0,0 +1,840 @@
+/*
+ * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
+ *
+ * SPDX-License-Identifier: MPL-2.0
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, you can obtain one at https://mozilla.org/MPL/2.0/.
+ *
+ * See the COPYRIGHT file distributed with this work for additional
+ * information regarding copyright ownership.
+ */
+
+/*
+ * Portions Copyright (c) 1987, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/*! \file */
+
+#include <errno.h>
+#include <fcntl.h>
+#include <inttypes.h>
+#include <limits.h>
+#include <stdbool.h>
+#include <stdlib.h>
+#include <sys/stat.h>
+#include <sys/time.h>
+#include <time.h> /* Required for utimes on some platforms. */
+#include <unistd.h> /* Required for mkstemp on NetBSD. */
+
+#ifdef HAVE_SYS_MMAN_H
+#include <sys/mman.h>
+#endif /* ifdef HAVE_SYS_MMAN_H */
+
+#include <isc/dir.h>
+#include <isc/file.h>
+#include <isc/log.h>
+#include <isc/md.h>
+#include <isc/mem.h>
+#include <isc/platform.h>
+#include <isc/print.h>
+#include <isc/random.h>
+#include <isc/string.h>
+#include <isc/time.h>
+#include <isc/util.h>
+
+#include "errno2result.h"
+
+/*
+ * XXXDCL As the API for accessing file statistics undoubtedly gets expanded,
+ * it might be good to provide a mechanism that allows for the results
+ * of a previous stat() to be used again without having to do another stat,
+ * such as perl's mechanism of using "_" in place of a file name to indicate
+ * that the results of the last stat should be used. But then you get into
+ * annoying MP issues. BTW, Win32 has stat().
+ */
+static isc_result_t
+file_stats(const char *file, struct stat *stats) {
+ isc_result_t result = ISC_R_SUCCESS;
+
+ REQUIRE(file != NULL);
+ REQUIRE(stats != NULL);
+
+ if (stat(file, stats) != 0) {
+ result = isc__errno2result(errno);
+ }
+
+ return (result);
+}
+
+static isc_result_t
+fd_stats(int fd, struct stat *stats) {
+ isc_result_t result = ISC_R_SUCCESS;
+
+ REQUIRE(stats != NULL);
+
+ if (fstat(fd, stats) != 0) {
+ result = isc__errno2result(errno);
+ }
+
+ return (result);
+}
+
+isc_result_t
+isc_file_getsizefd(int fd, off_t *size) {
+ isc_result_t result;
+ struct stat stats;
+
+ REQUIRE(size != NULL);
+
+ result = fd_stats(fd, &stats);
+
+ if (result == ISC_R_SUCCESS) {
+ *size = stats.st_size;
+ }
+
+ return (result);
+}
+
+isc_result_t
+isc_file_mode(const char *file, mode_t *modep) {
+ isc_result_t result;
+ struct stat stats;
+
+ REQUIRE(modep != NULL);
+
+ result = file_stats(file, &stats);
+ if (result == ISC_R_SUCCESS) {
+ *modep = (stats.st_mode & 07777);
+ }
+
+ return (result);
+}
+
+isc_result_t
+isc_file_getmodtime(const char *file, isc_time_t *modtime) {
+ isc_result_t result;
+ struct stat stats;
+
+ REQUIRE(file != NULL);
+ REQUIRE(modtime != NULL);
+
+ result = file_stats(file, &stats);
+
+ if (result == ISC_R_SUCCESS) {
+#if defined(HAVE_STAT_NSEC)
+ isc_time_set(modtime, stats.st_mtime, stats.st_mtim.tv_nsec);
+#else /* if defined(HAVE_STAT_NSEC) */
+ isc_time_set(modtime, stats.st_mtime, 0);
+#endif /* if defined(HAVE_STAT_NSEC) */
+ }
+
+ return (result);
+}
+
+isc_result_t
+isc_file_getsize(const char *file, off_t *size) {
+ isc_result_t result;
+ struct stat stats;
+
+ REQUIRE(file != NULL);
+ REQUIRE(size != NULL);
+
+ result = file_stats(file, &stats);
+
+ if (result == ISC_R_SUCCESS) {
+ *size = stats.st_size;
+ }
+
+ return (result);
+}
+
+isc_result_t
+isc_file_settime(const char *file, isc_time_t *when) {
+ struct timeval times[2];
+
+ REQUIRE(file != NULL && when != NULL);
+
+ /*
+ * tv_sec is at least a 32 bit quantity on all platforms we're
+ * dealing with, but it is signed on most (all?) of them,
+ * so we need to make sure the high bit isn't set. This unfortunately
+ * loses when either:
+ * * tv_sec becomes a signed 64 bit integer but long is 32 bits
+ * and isc_time_seconds > LONG_MAX, or
+ * * isc_time_seconds is changed to be > 32 bits but long is 32 bits
+ * and isc_time_seconds has at least 33 significant bits.
+ */
+ times[0].tv_sec = times[1].tv_sec = (long)isc_time_seconds(when);
+
+ /*
+ * Here is the real check for the high bit being set.
+ */
+ if ((times[0].tv_sec &
+ (1ULL << (sizeof(times[0].tv_sec) * CHAR_BIT - 1))) != 0)
+ {
+ return (ISC_R_RANGE);
+ }
+
+ /*
+ * isc_time_nanoseconds guarantees a value that divided by 1000 will
+ * fit into the minimum possible size tv_usec field.
+ */
+ times[0].tv_usec = times[1].tv_usec =
+ (int32_t)(isc_time_nanoseconds(when) / 1000);
+
+ if (utimes(file, times) < 0) {
+ return (isc__errno2result(errno));
+ }
+
+ return (ISC_R_SUCCESS);
+}
+
+#undef TEMPLATE
+#define TEMPLATE "tmp-XXXXXXXXXX" /*%< 14 characters. */
+
+isc_result_t
+isc_file_mktemplate(const char *path, char *buf, size_t buflen) {
+ return (isc_file_template(path, TEMPLATE, buf, buflen));
+}
+
+isc_result_t
+isc_file_template(const char *path, const char *templet, char *buf,
+ size_t buflen) {
+ const char *s;
+
+ REQUIRE(templet != NULL);
+ REQUIRE(buf != NULL);
+
+ if (path == NULL) {
+ path = "";
+ }
+
+ s = strrchr(templet, '/');
+ if (s != NULL) {
+ templet = s + 1;
+ }
+
+ s = strrchr(path, '/');
+
+ if (s != NULL) {
+ size_t prefixlen = s - path + 1;
+ if ((prefixlen + strlen(templet) + 1) > buflen) {
+ return (ISC_R_NOSPACE);
+ }
+
+ /* Copy 'prefixlen' bytes and NUL terminate. */
+ strlcpy(buf, path, ISC_MIN(prefixlen + 1, buflen));
+ strlcat(buf, templet, buflen);
+ } else {
+ if ((strlen(templet) + 1) > buflen) {
+ return (ISC_R_NOSPACE);
+ }
+
+ strlcpy(buf, templet, buflen);
+ }
+
+ return (ISC_R_SUCCESS);
+}
+
+static const char alphnum[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuv"
+ "wxyz0123456789";
+
+isc_result_t
+isc_file_renameunique(const char *file, char *templet) {
+ char *x;
+ char *cp;
+
+ REQUIRE(file != NULL);
+ REQUIRE(templet != NULL);
+
+ cp = templet;
+ while (*cp != '\0') {
+ cp++;
+ }
+ if (cp == templet) {
+ return (ISC_R_FAILURE);
+ }
+
+ x = cp--;
+ while (cp >= templet && *cp == 'X') {
+ *cp = alphnum[isc_random_uniform(sizeof(alphnum) - 1)];
+ x = cp--;
+ }
+ while (link(file, templet) == -1) {
+ if (errno != EEXIST) {
+ return (isc__errno2result(errno));
+ }
+ for (cp = x;;) {
+ const char *t;
+ if (*cp == '\0') {
+ return (ISC_R_FAILURE);
+ }
+ t = strchr(alphnum, *cp);
+ if (t == NULL || *++t == '\0') {
+ *cp++ = alphnum[0];
+ } else {
+ *cp = *t;
+ break;
+ }
+ }
+ }
+ if (unlink(file) < 0) {
+ if (errno != ENOENT) {
+ return (isc__errno2result(errno));
+ }
+ }
+ return (ISC_R_SUCCESS);
+}
+
+isc_result_t
+isc_file_openunique(char *templet, FILE **fp) {
+ int mode = S_IWUSR | S_IRUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
+ return (isc_file_openuniquemode(templet, mode, fp));
+}
+
+isc_result_t
+isc_file_openuniqueprivate(char *templet, FILE **fp) {
+ int mode = S_IWUSR | S_IRUSR;
+ return (isc_file_openuniquemode(templet, mode, fp));
+}
+
+isc_result_t
+isc_file_openuniquemode(char *templet, int mode, FILE **fp) {
+ int fd;
+ FILE *f;
+ isc_result_t result = ISC_R_SUCCESS;
+ char *x;
+ char *cp;
+
+ REQUIRE(templet != NULL);
+ REQUIRE(fp != NULL && *fp == NULL);
+
+ cp = templet;
+ while (*cp != '\0') {
+ cp++;
+ }
+ if (cp == templet) {
+ return (ISC_R_FAILURE);
+ }
+
+ x = cp--;
+ while (cp >= templet && *cp == 'X') {
+ *cp = alphnum[isc_random_uniform(sizeof(alphnum) - 1)];
+ x = cp--;
+ }
+
+ while ((fd = open(templet, O_RDWR | O_CREAT | O_EXCL, mode)) == -1) {
+ if (errno != EEXIST) {
+ return (isc__errno2result(errno));
+ }
+ for (cp = x;;) {
+ char *t;
+ if (*cp == '\0') {
+ return (ISC_R_FAILURE);
+ }
+ t = strchr(alphnum, *cp);
+ if (t == NULL || *++t == '\0') {
+ *cp++ = alphnum[0];
+ } else {
+ *cp = *t;
+ break;
+ }
+ }
+ }
+ f = fdopen(fd, "w+");
+ if (f == NULL) {
+ result = isc__errno2result(errno);
+ if (remove(templet) < 0) {
+ isc_log_write(isc_lctx, ISC_LOGCATEGORY_GENERAL,
+ ISC_LOGMODULE_FILE, ISC_LOG_ERROR,
+ "remove '%s': failed", templet);
+ }
+ (void)close(fd);
+ } else {
+ *fp = f;
+ }
+
+ return (result);
+}
+
+isc_result_t
+isc_file_bopenunique(char *templet, FILE **fp) {
+ int mode = S_IWUSR | S_IRUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
+ return (isc_file_openuniquemode(templet, mode, fp));
+}
+
+isc_result_t
+isc_file_bopenuniqueprivate(char *templet, FILE **fp) {
+ int mode = S_IWUSR | S_IRUSR;
+ return (isc_file_openuniquemode(templet, mode, fp));
+}
+
+isc_result_t
+isc_file_bopenuniquemode(char *templet, int mode, FILE **fp) {
+ return (isc_file_openuniquemode(templet, mode, fp));
+}
+
+isc_result_t
+isc_file_remove(const char *filename) {
+ int r;
+
+ REQUIRE(filename != NULL);
+
+ r = unlink(filename);
+ if (r == 0) {
+ return (ISC_R_SUCCESS);
+ } else {
+ return (isc__errno2result(errno));
+ }
+}
+
+isc_result_t
+isc_file_rename(const char *oldname, const char *newname) {
+ int r;
+
+ REQUIRE(oldname != NULL);
+ REQUIRE(newname != NULL);
+
+ r = rename(oldname, newname);
+ if (r == 0) {
+ return (ISC_R_SUCCESS);
+ } else {
+ return (isc__errno2result(errno));
+ }
+}
+
+bool
+isc_file_exists(const char *pathname) {
+ struct stat stats;
+
+ REQUIRE(pathname != NULL);
+
+ return (file_stats(pathname, &stats) == ISC_R_SUCCESS);
+}
+
+isc_result_t
+isc_file_isplainfile(const char *filename) {
+ /*
+ * This function returns success if filename is a plain file.
+ */
+ struct stat filestat;
+ memset(&filestat, 0, sizeof(struct stat));
+
+ if ((stat(filename, &filestat)) == -1) {
+ return (isc__errno2result(errno));
+ }
+
+ if (!S_ISREG(filestat.st_mode)) {
+ return (ISC_R_INVALIDFILE);
+ }
+
+ return (ISC_R_SUCCESS);
+}
+
+isc_result_t
+isc_file_isplainfilefd(int fd) {
+ /*
+ * This function returns success if filename is a plain file.
+ */
+ struct stat filestat;
+ memset(&filestat, 0, sizeof(struct stat));
+
+ if ((fstat(fd, &filestat)) == -1) {
+ return (isc__errno2result(errno));
+ }
+
+ if (!S_ISREG(filestat.st_mode)) {
+ return (ISC_R_INVALIDFILE);
+ }
+
+ return (ISC_R_SUCCESS);
+}
+
+isc_result_t
+isc_file_isdirectory(const char *filename) {
+ /*
+ * This function returns success if filename exists and is a
+ * directory.
+ */
+ struct stat filestat;
+ memset(&filestat, 0, sizeof(struct stat));
+
+ if ((stat(filename, &filestat)) == -1) {
+ return (isc__errno2result(errno));
+ }
+
+ if (!S_ISDIR(filestat.st_mode)) {
+ return (ISC_R_INVALIDFILE);
+ }
+
+ return (ISC_R_SUCCESS);
+}
+
+bool
+isc_file_isabsolute(const char *filename) {
+ REQUIRE(filename != NULL);
+ return (filename[0] == '/');
+}
+
+bool
+isc_file_iscurrentdir(const char *filename) {
+ REQUIRE(filename != NULL);
+ return (filename[0] == '.' && filename[1] == '\0');
+}
+
+bool
+isc_file_ischdiridempotent(const char *filename) {
+ REQUIRE(filename != NULL);
+ if (isc_file_isabsolute(filename)) {
+ return (true);
+ }
+ if (isc_file_iscurrentdir(filename)) {
+ return (true);
+ }
+ return (false);
+}
+
+const char *
+isc_file_basename(const char *filename) {
+ const char *s;
+
+ REQUIRE(filename != NULL);
+
+ s = strrchr(filename, '/');
+ if (s == NULL) {
+ return (filename);
+ }
+
+ return (s + 1);
+}
+
+isc_result_t
+isc_file_progname(const char *filename, char *buf, size_t buflen) {
+ const char *base;
+ size_t len;
+
+ REQUIRE(filename != NULL);
+ REQUIRE(buf != NULL);
+
+ base = isc_file_basename(filename);
+ len = strlen(base) + 1;
+
+ if (len > buflen) {
+ return (ISC_R_NOSPACE);
+ }
+ memmove(buf, base, len);
+
+ return (ISC_R_SUCCESS);
+}
+
+/*
+ * Put the absolute name of the current directory into 'dirname', which is
+ * a buffer of at least 'length' characters. End the string with the
+ * appropriate path separator, such that the final product could be
+ * concatenated with a relative pathname to make a valid pathname string.
+ */
+static isc_result_t
+dir_current(char *dirname, size_t length) {
+ char *cwd;
+ isc_result_t result = ISC_R_SUCCESS;
+
+ REQUIRE(dirname != NULL);
+ REQUIRE(length > 0U);
+
+ cwd = getcwd(dirname, length);
+
+ if (cwd == NULL) {
+ if (errno == ERANGE) {
+ result = ISC_R_NOSPACE;
+ } else {
+ result = isc__errno2result(errno);
+ }
+ } else {
+ if (strlen(dirname) + 1 == length) {
+ result = ISC_R_NOSPACE;
+ } else if (dirname[1] != '\0') {
+ strlcat(dirname, "/", length);
+ }
+ }
+
+ return (result);
+}
+
+isc_result_t
+isc_file_absolutepath(const char *filename, char *path, size_t pathlen) {
+ isc_result_t result;
+ result = dir_current(path, pathlen);
+ if (result != ISC_R_SUCCESS) {
+ return (result);
+ }
+ if (strlen(path) + strlen(filename) + 1 > pathlen) {
+ return (ISC_R_NOSPACE);
+ }
+ strlcat(path, filename, pathlen);
+ return (ISC_R_SUCCESS);
+}
+
+isc_result_t
+isc_file_truncate(const char *filename, isc_offset_t size) {
+ isc_result_t result = ISC_R_SUCCESS;
+
+ if (truncate(filename, size) < 0) {
+ result = isc__errno2result(errno);
+ }
+ return (result);
+}
+
+isc_result_t
+isc_file_safecreate(const char *filename, FILE **fp) {
+ isc_result_t result;
+ int flags;
+ struct stat sb;
+ FILE *f;
+ int fd;
+
+ REQUIRE(filename != NULL);
+ REQUIRE(fp != NULL && *fp == NULL);
+
+ result = file_stats(filename, &sb);
+ if (result == ISC_R_SUCCESS) {
+ if ((sb.st_mode & S_IFREG) == 0) {
+ return (ISC_R_INVALIDFILE);
+ }
+ flags = O_WRONLY | O_TRUNC;
+ } else if (result == ISC_R_FILENOTFOUND) {
+ flags = O_WRONLY | O_CREAT | O_EXCL;
+ } else {
+ return (result);
+ }
+
+ fd = open(filename, flags, S_IRUSR | S_IWUSR);
+ if (fd == -1) {
+ return (isc__errno2result(errno));
+ }
+
+ f = fdopen(fd, "w");
+ if (f == NULL) {
+ result = isc__errno2result(errno);
+ close(fd);
+ return (result);
+ }
+
+ *fp = f;
+ return (ISC_R_SUCCESS);
+}
+
+isc_result_t
+isc_file_splitpath(isc_mem_t *mctx, const char *path, char **dirname,
+ char const **bname) {
+ char *dir;
+ const char *file, *slash;
+
+ if (path == NULL) {
+ return (ISC_R_INVALIDFILE);
+ }
+
+ slash = strrchr(path, '/');
+
+ if (slash == path) {
+ file = ++slash;
+ dir = isc_mem_strdup(mctx, "/");
+ } else if (slash != NULL) {
+ file = ++slash;
+ dir = isc_mem_allocate(mctx, slash - path);
+ strlcpy(dir, path, slash - path);
+ } else {
+ file = path;
+ dir = isc_mem_strdup(mctx, ".");
+ }
+
+ if (dir == NULL) {
+ return (ISC_R_NOMEMORY);
+ }
+
+ if (*file == '\0') {
+ isc_mem_free(mctx, dir);
+ return (ISC_R_INVALIDFILE);
+ }
+
+ *dirname = dir;
+ *bname = file;
+
+ return (ISC_R_SUCCESS);
+}
+
+void *
+isc_file_mmap(void *addr, size_t len, int prot, int flags, int fd,
+ off_t offset) {
+#ifdef HAVE_MMAP
+ return (mmap(addr, len, prot, flags, fd, offset));
+#else /* ifdef HAVE_MMAP */
+ void *buf;
+ ssize_t ret;
+ off_t end;
+
+ UNUSED(addr);
+ UNUSED(prot);
+ UNUSED(flags);
+
+ end = lseek(fd, 0, SEEK_END);
+ lseek(fd, offset, SEEK_SET);
+ if (end - offset < (off_t)len) {
+ len = end - offset;
+ }
+
+ buf = malloc(len);
+ if (buf == NULL) {
+ return (NULL);
+ }
+
+ ret = read(fd, buf, len);
+ if (ret != (ssize_t)len) {
+ free(buf);
+ buf = NULL;
+ }
+
+ return (buf);
+#endif /* ifdef HAVE_MMAP */
+}
+
+int
+isc_file_munmap(void *addr, size_t len) {
+#ifdef HAVE_MMAP
+ return (munmap(addr, len));
+#else /* ifdef HAVE_MMAP */
+ UNUSED(len);
+
+ free(addr);
+ return (0);
+#endif /* ifdef HAVE_MMAP */
+}
+
+#define DISALLOW "\\/ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+
+static isc_result_t
+digest2hex(unsigned char *digest, unsigned int digestlen, char *hash,
+ size_t hashlen) {
+ unsigned int i;
+ int ret;
+ for (i = 0; i < digestlen; i++) {
+ size_t left = hashlen - i * 2;
+ ret = snprintf(hash + i * 2, left, "%02x", digest[i]);
+ if (ret < 0 || (size_t)ret >= left) {
+ return (ISC_R_NOSPACE);
+ }
+ }
+ return (ISC_R_SUCCESS);
+}
+
+isc_result_t
+isc_file_sanitize(const char *dir, const char *base, const char *ext,
+ char *path, size_t length) {
+ char buf[PATH_MAX];
+ unsigned char digest[ISC_MAX_MD_SIZE];
+ unsigned int digestlen;
+ char hash[ISC_MAX_MD_SIZE * 2 + 1];
+ size_t l = 0;
+ isc_result_t err;
+
+ REQUIRE(base != NULL);
+ REQUIRE(path != NULL);
+
+ l = strlen(base) + 1;
+
+ /*
+ * allow room for a full sha256 hash (64 chars
+ * plus null terminator)
+ */
+ if (l < 65U) {
+ l = 65;
+ }
+
+ if (dir != NULL) {
+ l += strlen(dir) + 1;
+ }
+ if (ext != NULL) {
+ l += strlen(ext) + 1;
+ }
+
+ if (l > length || l > (unsigned)PATH_MAX) {
+ return (ISC_R_NOSPACE);
+ }
+
+ /* Check whether the full-length SHA256 hash filename exists */
+ err = isc_md(ISC_MD_SHA256, (const unsigned char *)base, strlen(base),
+ digest, &digestlen);
+ if (err != ISC_R_SUCCESS) {
+ return (err);
+ }
+
+ err = digest2hex(digest, digestlen, hash, sizeof(hash));
+ if (err != ISC_R_SUCCESS) {
+ return (err);
+ }
+
+ snprintf(buf, sizeof(buf), "%s%s%s%s%s", dir != NULL ? dir : "",
+ dir != NULL ? "/" : "", hash, ext != NULL ? "." : "",
+ ext != NULL ? ext : "");
+ if (isc_file_exists(buf)) {
+ strlcpy(path, buf, length);
+ return (ISC_R_SUCCESS);
+ }
+
+ /* Check for a truncated SHA256 hash filename */
+ hash[16] = '\0';
+ snprintf(buf, sizeof(buf), "%s%s%s%s%s", dir != NULL ? dir : "",
+ dir != NULL ? "/" : "", hash, ext != NULL ? "." : "",
+ ext != NULL ? ext : "");
+ if (isc_file_exists(buf)) {
+ strlcpy(path, buf, length);
+ return (ISC_R_SUCCESS);
+ }
+
+ /*
+ * If neither hash filename already exists, then we'll use
+ * the original base name if it has no disallowed characters,
+ * or the truncated hash name if it does.
+ */
+ if (strpbrk(base, DISALLOW) != NULL) {
+ strlcpy(path, buf, length);
+ return (ISC_R_SUCCESS);
+ }
+
+ snprintf(buf, sizeof(buf), "%s%s%s%s%s", dir != NULL ? dir : "",
+ dir != NULL ? "/" : "", base, ext != NULL ? "." : "",
+ ext != NULL ? ext : "");
+ strlcpy(path, buf, length);
+ return (ISC_R_SUCCESS);
+}
+
+bool
+isc_file_isdirwritable(const char *path) {
+ return (access(path, W_OK | X_OK) == 0);
+}
diff --git a/lib/isc/unix/fsaccess.c b/lib/isc/unix/fsaccess.c
new file mode 100644
index 0000000..306cdfd
--- /dev/null
+++ b/lib/isc/unix/fsaccess.c
@@ -0,0 +1,87 @@
+/*
+ * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
+ *
+ * SPDX-License-Identifier: MPL-2.0
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, you can obtain one at https://mozilla.org/MPL/2.0/.
+ *
+ * See the COPYRIGHT file distributed with this work for additional
+ * information regarding copyright ownership.
+ */
+
+#include <errno.h>
+#include <stdbool.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+
+#include "errno2result.h"
+
+/*! \file
+ * \brief
+ * The OS-independent part of the API is in lib/isc.
+ */
+#include "../fsaccess.c"
+
+isc_result_t
+isc_fsaccess_set(const char *path, isc_fsaccess_t access) {
+ struct stat statb;
+ mode_t mode;
+ bool is_dir = false;
+ isc_fsaccess_t bits;
+ isc_result_t result;
+
+ if (stat(path, &statb) != 0) {
+ return (isc__errno2result(errno));
+ }
+
+ if ((statb.st_mode & S_IFDIR) != 0) {
+ is_dir = true;
+ } else if ((statb.st_mode & S_IFREG) == 0) {
+ return (ISC_R_INVALIDFILE);
+ }
+
+ result = check_bad_bits(access, is_dir);
+ if (result != ISC_R_SUCCESS) {
+ return (result);
+ }
+
+ /*
+ * Done with checking bad bits. Set mode_t.
+ */
+ mode = 0;
+
+#define SET_AND_CLEAR1(modebit) \
+ if ((access & bits) != 0) { \
+ mode |= modebit; \
+ access &= ~bits; \
+ }
+#define SET_AND_CLEAR(user, group, other) \
+ SET_AND_CLEAR1(user); \
+ bits <<= STEP; \
+ SET_AND_CLEAR1(group); \
+ bits <<= STEP; \
+ SET_AND_CLEAR1(other);
+
+ bits = ISC_FSACCESS_READ | ISC_FSACCESS_LISTDIRECTORY;
+
+ SET_AND_CLEAR(S_IRUSR, S_IRGRP, S_IROTH);
+
+ bits = ISC_FSACCESS_WRITE | ISC_FSACCESS_CREATECHILD |
+ ISC_FSACCESS_DELETECHILD;
+
+ SET_AND_CLEAR(S_IWUSR, S_IWGRP, S_IWOTH);
+
+ bits = ISC_FSACCESS_EXECUTE | ISC_FSACCESS_ACCESSCHILD;
+
+ SET_AND_CLEAR(S_IXUSR, S_IXGRP, S_IXOTH);
+
+ INSIST(access == 0);
+
+ if (chmod(path, mode) < 0) {
+ return (isc__errno2result(errno));
+ }
+
+ return (ISC_R_SUCCESS);
+}
diff --git a/lib/isc/unix/ifiter_getifaddrs.c b/lib/isc/unix/ifiter_getifaddrs.c
new file mode 100644
index 0000000..9f8b31a
--- /dev/null
+++ b/lib/isc/unix/ifiter_getifaddrs.c
@@ -0,0 +1,240 @@
+/*
+ * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
+ *
+ * SPDX-License-Identifier: MPL-2.0
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, you can obtain one at https://mozilla.org/MPL/2.0/.
+ *
+ * See the COPYRIGHT file distributed with this work for additional
+ * information regarding copyright ownership.
+ */
+
+/*! \file
+ * \brief
+ * Obtain the list of network interfaces using the getifaddrs(3) library.
+ */
+
+#include <ifaddrs.h>
+#include <stdbool.h>
+
+#include <isc/strerr.h>
+
+/*% Iterator Magic */
+#define IFITER_MAGIC ISC_MAGIC('I', 'F', 'I', 'G')
+/*% Valid Iterator */
+#define VALID_IFITER(t) ISC_MAGIC_VALID(t, IFITER_MAGIC)
+
+#ifdef __linux
+static bool seenv6 = false;
+#endif /* ifdef __linux */
+
+/*% Iterator structure */
+struct isc_interfaceiter {
+ unsigned int magic; /*%< Magic number. */
+ isc_mem_t *mctx;
+ void *buf; /*%< (unused) */
+ unsigned int bufsize; /*%< (always 0) */
+ struct ifaddrs *ifaddrs; /*%< List of ifaddrs */
+ struct ifaddrs *pos; /*%< Ptr to current ifaddr */
+ isc_interface_t current; /*%< Current interface data. */
+ isc_result_t result; /*%< Last result code. */
+#ifdef __linux
+ FILE *proc;
+ char entry[ISC_IF_INET6_SZ];
+ isc_result_t valid;
+#endif /* ifdef __linux */
+};
+
+isc_result_t
+isc_interfaceiter_create(isc_mem_t *mctx, isc_interfaceiter_t **iterp) {
+ isc_interfaceiter_t *iter;
+ isc_result_t result;
+ char strbuf[ISC_STRERRORSIZE];
+
+ REQUIRE(mctx != NULL);
+ REQUIRE(iterp != NULL);
+ REQUIRE(*iterp == NULL);
+
+ iter = isc_mem_get(mctx, sizeof(*iter));
+
+ iter->mctx = mctx;
+ iter->buf = NULL;
+ iter->bufsize = 0;
+ iter->ifaddrs = NULL;
+#ifdef __linux
+ /*
+ * Only open "/proc/net/if_inet6" if we have never seen a IPv6
+ * address returned by getifaddrs().
+ */
+ if (!seenv6) {
+ iter->proc = fopen("/proc/net/if_inet6", "r");
+ } else {
+ iter->proc = NULL;
+ }
+ iter->valid = ISC_R_FAILURE;
+#endif /* ifdef __linux */
+
+ if (getifaddrs(&iter->ifaddrs) < 0) {
+ strerror_r(errno, strbuf, sizeof(strbuf));
+ UNEXPECTED_ERROR(__FILE__, __LINE__,
+ "getting interface addresses: getifaddrs: %s",
+ strbuf);
+ result = ISC_R_UNEXPECTED;
+ goto failure;
+ }
+
+ /*
+ * A newly created iterator has an undefined position
+ * until isc_interfaceiter_first() is called.
+ */
+ iter->pos = NULL;
+ iter->result = ISC_R_FAILURE;
+
+ iter->magic = IFITER_MAGIC;
+ *iterp = iter;
+ return (ISC_R_SUCCESS);
+
+failure:
+#ifdef __linux
+ if (iter->proc != NULL) {
+ fclose(iter->proc);
+ }
+#endif /* ifdef __linux */
+ if (iter->ifaddrs != NULL) { /* just in case */
+ freeifaddrs(iter->ifaddrs);
+ }
+ isc_mem_put(mctx, iter, sizeof(*iter));
+ return (result);
+}
+
+/*
+ * Get information about the current interface to iter->current.
+ * If successful, return ISC_R_SUCCESS.
+ * If the interface has an unsupported address family,
+ * return ISC_R_IGNORE.
+ */
+
+static isc_result_t
+internal_current(isc_interfaceiter_t *iter) {
+ struct ifaddrs *ifa;
+ int family;
+ unsigned int namelen;
+
+ REQUIRE(VALID_IFITER(iter));
+
+ ifa = iter->pos;
+
+#ifdef __linux
+ if (iter->pos == NULL) {
+ return (linux_if_inet6_current(iter));
+ }
+#endif /* ifdef __linux */
+
+ INSIST(ifa != NULL);
+ INSIST(ifa->ifa_name != NULL);
+
+ if (ifa->ifa_addr == NULL) {
+ return (ISC_R_IGNORE);
+ }
+
+ family = ifa->ifa_addr->sa_family;
+ if (family != AF_INET && family != AF_INET6) {
+ return (ISC_R_IGNORE);
+ }
+
+#ifdef __linux
+ if (family == AF_INET6) {
+ seenv6 = true;
+ }
+#endif /* ifdef __linux */
+
+ memset(&iter->current, 0, sizeof(iter->current));
+
+ namelen = strlen(ifa->ifa_name);
+ if (namelen > sizeof(iter->current.name) - 1) {
+ namelen = sizeof(iter->current.name) - 1;
+ }
+
+ memset(iter->current.name, 0, sizeof(iter->current.name));
+ memmove(iter->current.name, ifa->ifa_name, namelen);
+
+ iter->current.flags = 0;
+
+ if ((ifa->ifa_flags & IFF_UP) != 0) {
+ iter->current.flags |= INTERFACE_F_UP;
+ }
+
+ if ((ifa->ifa_flags & IFF_POINTOPOINT) != 0) {
+ iter->current.flags |= INTERFACE_F_POINTTOPOINT;
+ }
+
+ if ((ifa->ifa_flags & IFF_LOOPBACK) != 0) {
+ iter->current.flags |= INTERFACE_F_LOOPBACK;
+ }
+
+ iter->current.af = family;
+
+ get_addr(family, &iter->current.address, ifa->ifa_addr, ifa->ifa_name);
+
+ if (ifa->ifa_netmask != NULL) {
+ get_addr(family, &iter->current.netmask, ifa->ifa_netmask,
+ ifa->ifa_name);
+ }
+
+ if (ifa->ifa_dstaddr != NULL &&
+ (iter->current.flags & INTERFACE_F_POINTTOPOINT) != 0)
+ {
+ get_addr(family, &iter->current.dstaddress, ifa->ifa_dstaddr,
+ ifa->ifa_name);
+ }
+
+ return (ISC_R_SUCCESS);
+}
+
+/*
+ * Step the iterator to the next interface. Unlike
+ * isc_interfaceiter_next(), this may leave the iterator
+ * positioned on an interface that will ultimately
+ * be ignored. Return ISC_R_NOMORE if there are no more
+ * interfaces, otherwise ISC_R_SUCCESS.
+ */
+static isc_result_t
+internal_next(isc_interfaceiter_t *iter) {
+ if (iter->pos != NULL) {
+ iter->pos = iter->pos->ifa_next;
+ }
+ if (iter->pos == NULL) {
+#ifdef __linux
+ if (!seenv6) {
+ return (linux_if_inet6_next(iter));
+ }
+#endif /* ifdef __linux */
+ return (ISC_R_NOMORE);
+ }
+
+ return (ISC_R_SUCCESS);
+}
+
+static void
+internal_destroy(isc_interfaceiter_t *iter) {
+#ifdef __linux
+ if (iter->proc != NULL) {
+ fclose(iter->proc);
+ }
+ iter->proc = NULL;
+#endif /* ifdef __linux */
+ if (iter->ifaddrs) {
+ freeifaddrs(iter->ifaddrs);
+ }
+ iter->ifaddrs = NULL;
+}
+
+static void
+internal_first(isc_interfaceiter_t *iter) {
+#ifdef __linux
+ linux_if_inet6_first(iter);
+#endif /* ifdef __linux */
+ iter->pos = iter->ifaddrs;
+}
diff --git a/lib/isc/unix/include/.clang-format b/lib/isc/unix/include/.clang-format
new file mode 120000
index 0000000..e919bba
--- /dev/null
+++ b/lib/isc/unix/include/.clang-format
@@ -0,0 +1 @@
+../../../../.clang-format.headers \ No newline at end of file
diff --git a/lib/isc/unix/include/Makefile.in b/lib/isc/unix/include/Makefile.in
new file mode 100644
index 0000000..60a0a67
--- /dev/null
+++ b/lib/isc/unix/include/Makefile.in
@@ -0,0 +1,19 @@
+# Copyright (C) Internet Systems Consortium, Inc. ("ISC")
+#
+# SPDX-License-Identifier: MPL-2.0
+#
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, you can obtain one at https://mozilla.org/MPL/2.0/.
+#
+# See the COPYRIGHT file distributed with this work for additional
+# information regarding copyright ownership.
+
+srcdir = @srcdir@
+VPATH = @srcdir@
+top_srcdir = @top_srcdir@
+
+SUBDIRS = isc
+TARGETS =
+
+@BIND9_MAKE_RULES@
diff --git a/lib/isc/unix/include/isc/Makefile.in b/lib/isc/unix/include/isc/Makefile.in
new file mode 100644
index 0000000..06f7806
--- /dev/null
+++ b/lib/isc/unix/include/isc/Makefile.in
@@ -0,0 +1,37 @@
+# Copyright (C) Internet Systems Consortium, Inc. ("ISC")
+#
+# SPDX-License-Identifier: MPL-2.0
+#
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, you can obtain one at https://mozilla.org/MPL/2.0/.
+#
+# See the COPYRIGHT file distributed with this work for additional
+# information regarding copyright ownership.
+
+srcdir = @srcdir@
+VPATH = @srcdir@
+top_srcdir = @top_srcdir@
+
+VERSION=@BIND9_VERSION@
+
+HEADERS = align.h dir.h net.h netdb.h offset.h stat.h \
+ stdatomic.h stdtime.h syslog.h time.h
+
+SUBDIRS =
+TARGETS =
+
+@BIND9_MAKE_RULES@
+
+installdirs:
+ $(SHELL) ${top_srcdir}/mkinstalldirs ${DESTDIR}${includedir}/isc
+
+install:: installdirs
+ for i in ${HEADERS}; do \
+ ${INSTALL_DATA} $(srcdir)/$$i ${DESTDIR}${includedir}/isc || exit 1; \
+ done
+
+uninstall::
+ for i in ${HEADERS}; do \
+ rm -f ${DESTDIR}${includedir}/isc/$$i || exit 1; \
+ done
diff --git a/lib/isc/unix/include/isc/align.h b/lib/isc/unix/include/isc/align.h
new file mode 100644
index 0000000..7b72e9d
--- /dev/null
+++ b/lib/isc/unix/include/isc/align.h
@@ -0,0 +1,20 @@
+/*
+ * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
+ *
+ * SPDX-License-Identifier: MPL-2.0
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, you can obtain one at https://mozilla.org/MPL/2.0/.
+ *
+ * See the COPYRIGHT file distributed with this work for additional
+ * information regarding copyright ownership.
+ */
+
+#pragma once
+
+#ifdef HAVE_STDALIGN_H
+#include <stdalign.h>
+#else /* ifdef HAVE_STDALIGN_H */
+#define alignas(x) __attribute__((__aligned__(x)))
+#endif /* ifdef HAVE_STDALIGN_H */
diff --git a/lib/isc/unix/include/isc/dir.h b/lib/isc/unix/include/isc/dir.h
new file mode 100644
index 0000000..89d1338
--- /dev/null
+++ b/lib/isc/unix/include/isc/dir.h
@@ -0,0 +1,75 @@
+/*
+ * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
+ *
+ * SPDX-License-Identifier: MPL-2.0
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, you can obtain one at https://mozilla.org/MPL/2.0/.
+ *
+ * See the COPYRIGHT file distributed with this work for additional
+ * information regarding copyright ownership.
+ */
+
+#ifndef ISC_DIR_H
+#define ISC_DIR_H 1
+
+/*! \file */
+
+#include <dirent.h>
+
+#include <isc/lang.h>
+#include <isc/platform.h>
+#include <isc/result.h>
+
+#include <sys/types.h> /* Required on some systems. */
+
+/*% Directory Entry */
+typedef struct isc_direntry {
+ char name[NAME_MAX];
+ unsigned int length;
+} isc_direntry_t;
+
+/*% Directory */
+typedef struct isc_dir {
+ unsigned int magic;
+ char dirname[PATH_MAX];
+ isc_direntry_t entry;
+ DIR *handle;
+} isc_dir_t;
+
+ISC_LANG_BEGINDECLS
+
+void
+isc_dir_init(isc_dir_t *dir);
+
+isc_result_t
+isc_dir_open(isc_dir_t *dir, const char *dirname);
+
+isc_result_t
+isc_dir_read(isc_dir_t *dir);
+
+isc_result_t
+isc_dir_reset(isc_dir_t *dir);
+
+void
+isc_dir_close(isc_dir_t *dir);
+
+isc_result_t
+isc_dir_chdir(const char *dirname);
+
+isc_result_t
+isc_dir_chroot(const char *dirname);
+
+isc_result_t
+isc_dir_createunique(char *templet);
+/*!<
+ * Use a templet (such as from isc_file_mktemplate()) to create a uniquely
+ * named, empty directory. The templet string is modified in place.
+ * If result == ISC_R_SUCCESS, it is the name of the directory that was
+ * created.
+ */
+
+ISC_LANG_ENDDECLS
+
+#endif /* ISC_DIR_H */
diff --git a/lib/isc/unix/include/isc/net.h b/lib/isc/unix/include/isc/net.h
new file mode 100644
index 0000000..ead9c7f
--- /dev/null
+++ b/lib/isc/unix/include/isc/net.h
@@ -0,0 +1,310 @@
+/*
+ * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
+ *
+ * SPDX-License-Identifier: MPL-2.0
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, you can obtain one at https://mozilla.org/MPL/2.0/.
+ *
+ * See the COPYRIGHT file distributed with this work for additional
+ * information regarding copyright ownership.
+ */
+
+#ifndef ISC_NET_H
+#define ISC_NET_H 1
+
+/*****
+***** Module Info
+*****/
+
+/*! \file
+ * \brief
+ * Basic Networking Types
+ *
+ * This module is responsible for defining the following basic networking
+ * types:
+ *
+ *\li struct in_addr
+ *\li struct in6_addr
+ *\li struct in6_pktinfo
+ *\li struct sockaddr
+ *\li struct sockaddr_in
+ *\li struct sockaddr_in6
+ *\li struct sockaddr_storage
+ *\li in_port_t
+ *
+ * It ensures that the AF_ and PF_ macros are defined.
+ *
+ * It declares ntoh[sl]() and hton[sl]().
+ *
+ * It declares inet_ntop(), and inet_pton().
+ *
+ * It ensures that #INADDR_LOOPBACK, #INADDR_ANY, #IN6ADDR_ANY_INIT,
+ * IN6ADDR_V4MAPPED_INIT, in6addr_any, and in6addr_loopback are available.
+ *
+ * It ensures that IN_MULTICAST() is available to check for multicast
+ * addresses.
+ *
+ * MP:
+ *\li No impact.
+ *
+ * Reliability:
+ *\li No anticipated impact.
+ *
+ * Resources:
+ *\li N/A.
+ *
+ * Security:
+ *\li No anticipated impact.
+ *
+ * Standards:
+ *\li BSD Socket API
+ *\li RFC2553
+ */
+
+/***
+ *** Imports.
+ ***/
+#include <inttypes.h>
+
+#include <isc/lang.h>
+#include <isc/platform.h>
+#include <isc/types.h>
+
+#include <arpa/inet.h> /* Contractual promise. */
+#include <net/if.h>
+#include <netinet/in.h> /* Contractual promise. */
+#include <sys/socket.h> /* Contractual promise. */
+#include <sys/types.h>
+
+#ifndef IN6ADDR_LOOPBACK_INIT
+#ifdef s6_addr
+/*% IPv6 address loopback init */
+#define IN6ADDR_LOOPBACK_INIT \
+ { \
+ { \
+ { \
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 \
+ } \
+ } \
+ }
+#else /* ifdef s6_addr */
+#define IN6ADDR_LOOPBACK_INIT \
+ { \
+ { \
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 \
+ } \
+ }
+#endif /* ifdef s6_addr */
+#endif /* ifndef IN6ADDR_LOOPBACK_INIT */
+
+#ifndef IN6ADDR_V4MAPPED_INIT
+#ifdef s6_addr
+/*% IPv6 v4mapped prefix init */
+#define IN6ADDR_V4MAPPED_INIT \
+ { \
+ { \
+ { \
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 0, \
+ 0, 0, 0 \
+ } \
+ } \
+ }
+#else /* ifdef s6_addr */
+#define IN6ADDR_V4MAPPED_INIT \
+ { \
+ { \
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 0, 0, 0, 0 \
+ } \
+ }
+#endif /* ifdef s6_addr */
+#endif /* ifndef IN6ADDR_V4MAPPED_INIT */
+
+#ifndef IN6_IS_ADDR_V4MAPPED
+/*% Is IPv6 address V4 mapped? */
+#define IN6_IS_ADDR_V4MAPPED(x) \
+ (memcmp((x)->s6_addr, in6addr_any.s6_addr, 10) == 0 && \
+ (x)->s6_addr[10] == 0xff && (x)->s6_addr[11] == 0xff)
+#endif /* ifndef IN6_IS_ADDR_V4MAPPED */
+
+#ifndef IN6_IS_ADDR_V4COMPAT
+/*% Is IPv6 address V4 compatible? */
+#define IN6_IS_ADDR_V4COMPAT(x) \
+ (memcmp((x)->s6_addr, in6addr_any.s6_addr, 12) == 0 && \
+ ((x)->s6_addr[12] != 0 || (x)->s6_addr[13] != 0 || \
+ (x)->s6_addr[14] != 0 || \
+ ((x)->s6_addr[15] != 0 && (x)->s6_addr[15] != 1)))
+#endif /* ifndef IN6_IS_ADDR_V4COMPAT */
+
+#ifndef IN6_IS_ADDR_MULTICAST
+/*% Is IPv6 address multicast? */
+#define IN6_IS_ADDR_MULTICAST(a) ((a)->s6_addr[0] == 0xff)
+#endif /* ifndef IN6_IS_ADDR_MULTICAST */
+
+#ifndef IN6_IS_ADDR_LINKLOCAL
+/*% Is IPv6 address linklocal? */
+#define IN6_IS_ADDR_LINKLOCAL(a) \
+ (((a)->s6_addr[0] == 0xfe) && (((a)->s6_addr[1] & 0xc0) == 0x80))
+#endif /* ifndef IN6_IS_ADDR_LINKLOCAL */
+
+#ifndef IN6_IS_ADDR_SITELOCAL
+/*% is IPv6 address sitelocal? */
+#define IN6_IS_ADDR_SITELOCAL(a) \
+ (((a)->s6_addr[0] == 0xfe) && (((a)->s6_addr[1] & 0xc0) == 0xc0))
+#endif /* ifndef IN6_IS_ADDR_SITELOCAL */
+
+#ifndef IN6_IS_ADDR_LOOPBACK
+/*% is IPv6 address loopback? */
+#define IN6_IS_ADDR_LOOPBACK(x) \
+ (memcmp((x)->s6_addr, in6addr_loopback.s6_addr, 16) == 0)
+#endif /* ifndef IN6_IS_ADDR_LOOPBACK */
+
+#ifndef AF_INET6
+/*% IPv6 */
+#define AF_INET6 99
+#endif /* ifndef AF_INET6 */
+
+#ifndef PF_INET6
+/*% IPv6 */
+#define PF_INET6 AF_INET6
+#endif /* ifndef PF_INET6 */
+
+#ifndef INADDR_ANY
+/*% inaddr any */
+#define INADDR_ANY 0x00000000UL
+#endif /* ifndef INADDR_ANY */
+
+#ifndef INADDR_LOOPBACK
+/*% inaddr loopback */
+#define INADDR_LOOPBACK 0x7f000001UL
+#endif /* ifndef INADDR_LOOPBACK */
+
+#ifndef MSG_TRUNC
+/*%
+ * If this system does not have MSG_TRUNC (as returned from recvmsg())
+ * ISC_PLATFORM_RECVOVERFLOW will be defined. This will enable the MSG_TRUNC
+ * faking code in socket.c.
+ */
+#define ISC_PLATFORM_RECVOVERFLOW
+#endif /* ifndef MSG_TRUNC */
+
+/*% IP address. */
+#define ISC__IPADDR(x) ((uint32_t)htonl((uint32_t)(x)))
+
+/*% Is IP address multicast? */
+#define ISC_IPADDR_ISMULTICAST(i) \
+ (((uint32_t)(i)&ISC__IPADDR(0xf0000000)) == ISC__IPADDR(0xe0000000))
+
+#define ISC_IPADDR_ISEXPERIMENTAL(i) \
+ (((uint32_t)(i)&ISC__IPADDR(0xf0000000)) == ISC__IPADDR(0xf0000000))
+
+/***
+ *** Functions.
+ ***/
+
+ISC_LANG_BEGINDECLS
+
+isc_result_t
+isc_net_probeipv4(void);
+/*%<
+ * Check if the system's kernel supports IPv4.
+ *
+ * Returns:
+ *
+ *\li #ISC_R_SUCCESS IPv4 is supported.
+ *\li #ISC_R_NOTFOUND IPv4 is not supported.
+ *\li #ISC_R_DISABLED IPv4 is disabled.
+ *\li #ISC_R_UNEXPECTED
+ */
+
+isc_result_t
+isc_net_probeipv6(void);
+/*%<
+ * Check if the system's kernel supports IPv6.
+ *
+ * Returns:
+ *
+ *\li #ISC_R_SUCCESS IPv6 is supported.
+ *\li #ISC_R_NOTFOUND IPv6 is not supported.
+ *\li #ISC_R_DISABLED IPv6 is disabled.
+ *\li #ISC_R_UNEXPECTED
+ */
+
+isc_result_t
+isc_net_probe_ipv6only(void);
+/*%<
+ * Check if the system's kernel supports the IPV6_V6ONLY socket option.
+ *
+ * Returns:
+ *
+ *\li #ISC_R_SUCCESS the option is supported for both TCP and UDP.
+ *\li #ISC_R_NOTFOUND IPv6 itself or the option is not supported.
+ *\li #ISC_R_UNEXPECTED
+ */
+
+isc_result_t
+isc_net_probe_ipv6pktinfo(void);
+/*
+ * Check if the system's kernel supports the IPV6_(RECV)PKTINFO socket option
+ * for UDP sockets.
+ *
+ * Returns:
+ *
+ * \li #ISC_R_SUCCESS the option is supported.
+ * \li #ISC_R_NOTFOUND IPv6 itself or the option is not supported.
+ * \li #ISC_R_UNEXPECTED
+ */
+
+void
+isc_net_disableipv4(void);
+
+void
+isc_net_disableipv6(void);
+
+void
+isc_net_enableipv4(void);
+
+void
+isc_net_enableipv6(void);
+
+isc_result_t
+isc_net_probeunix(void);
+/*
+ * Returns whether UNIX domain sockets are supported.
+ */
+
+#define ISC_NET_DSCPRECVV4 0x01 /* Can receive sent DSCP value IPv4 */
+#define ISC_NET_DSCPRECVV6 0x02 /* Can receive sent DSCP value IPv6 */
+#define ISC_NET_DSCPSETV4 0x04 /* Can set DSCP on socket IPv4 */
+#define ISC_NET_DSCPSETV6 0x08 /* Can set DSCP on socket IPv6 */
+#define ISC_NET_DSCPPKTV4 0x10 /* Can set DSCP on per packet IPv4 */
+#define ISC_NET_DSCPPKTV6 0x20 /* Can set DSCP on per packet IPv6 */
+#define ISC_NET_DSCPALL 0x3f /* All valid flags */
+
+unsigned int
+isc_net_probedscp(void);
+/*%<
+ * Probe the level of DSCP support.
+ */
+
+isc_result_t
+isc_net_getudpportrange(int af, in_port_t *low, in_port_t *high);
+/*%<
+ * Returns system's default range of ephemeral UDP ports, if defined.
+ * If the range is not available or unknown, ISC_NET_PORTRANGELOW and
+ * ISC_NET_PORTRANGEHIGH will be returned.
+ *
+ * Requires:
+ *
+ *\li 'low' and 'high' must be non NULL.
+ *
+ * Returns:
+ *
+ *\li *low and *high will be the ports specifying the low and high ends of
+ * the range.
+ */
+
+ISC_LANG_ENDDECLS
+
+#endif /* ISC_NET_H */
diff --git a/lib/isc/unix/include/isc/netdb.h b/lib/isc/unix/include/isc/netdb.h
new file mode 100644
index 0000000..dab845a
--- /dev/null
+++ b/lib/isc/unix/include/isc/netdb.h
@@ -0,0 +1,51 @@
+/*
+ * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
+ *
+ * SPDX-License-Identifier: MPL-2.0
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, you can obtain one at https://mozilla.org/MPL/2.0/.
+ *
+ * See the COPYRIGHT file distributed with this work for additional
+ * information regarding copyright ownership.
+ */
+
+#ifndef ISC_NETDB_H
+#define ISC_NETDB_H 1
+
+/*****
+***** Module Info
+*****/
+
+/*! \file
+ * \brief
+ * Portable netdb.h support.
+ *
+ * This module is responsible for defining the get<x>by<y> APIs.
+ *
+ * MP:
+ *\li No impact.
+ *
+ * Reliability:
+ *\li No anticipated impact.
+ *
+ * Resources:
+ *\li N/A.
+ *
+ * Security:
+ *\li No anticipated impact.
+ *
+ * Standards:
+ *\li BSD API
+ */
+
+/***
+ *** Imports.
+ ***/
+
+#include <netdb.h>
+
+#include <isc/net.h>
+
+#endif /* ISC_NETDB_H */
diff --git a/lib/isc/unix/include/isc/offset.h b/lib/isc/unix/include/isc/offset.h
new file mode 100644
index 0000000..fa24ae4
--- /dev/null
+++ b/lib/isc/unix/include/isc/offset.h
@@ -0,0 +1,28 @@
+/*
+ * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
+ *
+ * SPDX-License-Identifier: MPL-2.0
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, you can obtain one at https://mozilla.org/MPL/2.0/.
+ *
+ * See the COPYRIGHT file distributed with this work for additional
+ * information regarding copyright ownership.
+ */
+
+#ifndef ISC_OFFSET_H
+#define ISC_OFFSET_H 1
+
+/*! \file
+ * \brief
+ * File offsets are operating-system dependent.
+ */
+#include <limits.h> /* Required for CHAR_BIT. */
+#include <stddef.h> /* For Linux Standard Base. */
+
+#include <sys/types.h>
+
+typedef off_t isc_offset_t;
+
+#endif /* ISC_OFFSET_H */
diff --git a/lib/isc/unix/include/isc/stat.h b/lib/isc/unix/include/isc/stat.h
new file mode 100644
index 0000000..6ddddd7
--- /dev/null
+++ b/lib/isc/unix/include/isc/stat.h
@@ -0,0 +1,47 @@
+/*
+ * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
+ *
+ * SPDX-License-Identifier: MPL-2.0
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, you can obtain one at https://mozilla.org/MPL/2.0/.
+ *
+ * See the COPYRIGHT file distributed with this work for additional
+ * information regarding copyright ownership.
+ */
+
+#ifndef ISC_STAT_H
+#define ISC_STAT_H 1
+
+/*****
+***** Module Info
+*****/
+
+/*
+ * Portable <sys/stat.h> support.
+ *
+ * This module is responsible for defining S_IS??? macros.
+ *
+ * MP:
+ * No impact.
+ *
+ * Reliability:
+ * No anticipated impact.
+ *
+ * Resources:
+ * N/A.
+ *
+ * Security:
+ * No anticipated impact.
+ *
+ */
+
+/***
+ *** Imports.
+ ***/
+
+#include <sys/stat.h>
+#include <sys/types.h>
+
+#endif /* ISC_STAT_H */
diff --git a/lib/isc/unix/include/isc/stdatomic.h b/lib/isc/unix/include/isc/stdatomic.h
new file mode 100644
index 0000000..f071b6a
--- /dev/null
+++ b/lib/isc/unix/include/isc/stdatomic.h
@@ -0,0 +1,224 @@
+/*
+ * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
+ *
+ * SPDX-License-Identifier: MPL-2.0
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, you can obtain one at https://mozilla.org/MPL/2.0/.
+ *
+ * See the COPYRIGHT file distributed with this work for additional
+ * information regarding copyright ownership.
+ */
+
+#pragma once
+
+#include <inttypes.h>
+#include <stdbool.h>
+#include <stddef.h>
+#if HAVE_UCHAR_H
+#include <uchar.h>
+#endif /* HAVE_UCHAR_H */
+
+#if !defined(__has_feature)
+#define __has_feature(x) 0
+#endif /* if !defined(__has_feature) */
+
+#if !defined(__has_extension)
+#define __has_extension(x) __has_feature(x)
+#endif /* if !defined(__has_extension) */
+
+#if !defined(__GNUC_PREREQ__)
+#if defined(__GNUC__) && defined(__GNUC_MINOR__)
+#define __GNUC_PREREQ__(maj, min) \
+ ((__GNUC__ << 16) + __GNUC_MINOR__ >= ((maj) << 16) + (min))
+#else /* if defined(__GNUC__) && defined(__GNUC_MINOR__) */
+#define __GNUC_PREREQ__(maj, min) 0
+#endif /* if defined(__GNUC__) && defined(__GNUC_MINOR__) */
+#endif /* if !defined(__GNUC_PREREQ__) */
+
+#if !defined(__CLANG_ATOMICS) && !defined(__GNUC_ATOMICS)
+#if __has_extension(c_atomic) || __has_extension(cxx_atomic)
+#define __CLANG_ATOMICS
+#elif __GNUC_PREREQ__(4, 7)
+#define __GNUC_ATOMICS
+#elif !defined(__GNUC__)
+#error "isc/stdatomic.h does not support your compiler"
+#endif /* if __has_extension(c_atomic) || __has_extension(cxx_atomic) */
+#endif /* if !defined(__CLANG_ATOMICS) && !defined(__GNUC_ATOMICS) */
+
+#ifndef __ATOMIC_RELAXED
+#define __ATOMIC_RELAXED 0
+#endif /* ifndef __ATOMIC_RELAXED */
+#ifndef __ATOMIC_CONSUME
+#define __ATOMIC_CONSUME 1
+#endif /* ifndef __ATOMIC_CONSUME */
+#ifndef __ATOMIC_ACQUIRE
+#define __ATOMIC_ACQUIRE 2
+#endif /* ifndef __ATOMIC_ACQUIRE */
+#ifndef __ATOMIC_RELEASE
+#define __ATOMIC_RELEASE 3
+#endif /* ifndef __ATOMIC_RELEASE */
+#ifndef __ATOMIC_ACQ_REL
+#define __ATOMIC_ACQ_REL 4
+#endif /* ifndef __ATOMIC_ACQ_REL */
+#ifndef __ATOMIC_SEQ_CST
+#define __ATOMIC_SEQ_CST 5
+#endif /* ifndef __ATOMIC_SEQ_CST */
+
+enum memory_order {
+ memory_order_relaxed = __ATOMIC_RELAXED,
+ memory_order_consume = __ATOMIC_CONSUME,
+ memory_order_acquire = __ATOMIC_ACQUIRE,
+ memory_order_release = __ATOMIC_RELEASE,
+ memory_order_acq_rel = __ATOMIC_ACQ_REL,
+ memory_order_seq_cst = __ATOMIC_SEQ_CST
+};
+
+typedef enum memory_order memory_order;
+
+#ifndef HAVE_UCHAR_H
+typedef uint_least16_t char16_t;
+typedef uint_least32_t char32_t;
+#endif /* HAVE_UCHAR_H */
+
+typedef bool atomic_bool;
+typedef char atomic_char;
+typedef signed char atomic_schar;
+typedef unsigned char atomic_uchar;
+typedef short atomic_short;
+typedef unsigned short atomic_ushort;
+typedef int atomic_int;
+typedef unsigned int atomic_uint;
+typedef long atomic_long;
+typedef unsigned long atomic_ulong;
+typedef long long atomic_llong;
+typedef unsigned long long atomic_ullong;
+typedef char16_t atomic_char16_t;
+typedef char32_t atomic_char32_t;
+typedef wchar_t atomic_wchar_t;
+typedef int_least8_t atomic_int_least8_t;
+typedef uint_least8_t atomic_uint_least8_t;
+typedef int_least16_t atomic_int_least16_t;
+typedef uint_least16_t atomic_uint_least16_t;
+typedef int_least32_t atomic_int_least32_t;
+typedef uint_least32_t atomic_uint_least32_t;
+typedef int_least64_t atomic_int_least64_t;
+typedef uint_least64_t atomic_uint_least64_t;
+typedef int_fast8_t atomic_int_fast8_t;
+typedef uint_fast8_t atomic_uint_fast8_t;
+typedef int_fast16_t atomic_int_fast16_t;
+typedef uint_fast16_t atomic_uint_fast16_t;
+typedef int_fast32_t atomic_int_fast32_t;
+typedef uint_fast32_t atomic_uint_fast32_t;
+typedef int_fast64_t atomic_int_fast64_t;
+typedef uint_fast64_t atomic_uint_fast64_t;
+typedef intptr_t atomic_intptr_t;
+typedef uintptr_t atomic_uintptr_t;
+typedef size_t atomic_size_t;
+typedef ptrdiff_t atomic_ptrdiff_t;
+typedef intmax_t atomic_intmax_t;
+typedef uintmax_t atomic_uintmax_t;
+
+#if defined(__CLANG_ATOMICS) /* __c11_atomic builtins */
+#define atomic_init(obj, desired) __c11_atomic_init(obj, desired)
+#define atomic_load_explicit(obj, order) __c11_atomic_load(obj, order)
+#define atomic_store_explicit(obj, desired, order) \
+ __c11_atomic_store(obj, desired, order)
+#define atomic_fetch_add_explicit(obj, arg, order) \
+ __c11_atomic_fetch_add(obj, arg, order)
+#define atomic_fetch_sub_explicit(obj, arg, order) \
+ __c11_atomic_fetch_sub(obj, arg, order)
+#define atomic_fetch_and_explicit(obj, arg, order) \
+ __c11_atomic_fetch_and(obj, arg, order)
+#define atomic_fetch_or_explicit(obj, arg, order) \
+ __c11_atomic_fetch_or(obj, arg, order)
+#define atomic_compare_exchange_strong_explicit(obj, expected, desired, succ, \
+ fail) \
+ __c11_atomic_compare_exchange_strong_explicit(obj, expected, desired, \
+ succ, fail)
+#define atomic_compare_exchange_weak_explicit(obj, expected, desired, succ, \
+ fail) \
+ __c11_atomic_compare_exchange_weak_explicit(obj, expected, desired, \
+ succ, fail)
+#define atomic_exchange_explicit(obj, desired, order) \
+ __c11_atomic_exchange_explicit(obj, expected, order)
+#elif defined(__GNUC_ATOMICS) /* __atomic builtins */
+#define atomic_init(obj, desired) (*obj = desired)
+#define atomic_load_explicit(obj, order) __atomic_load_n(obj, order)
+#define atomic_store_explicit(obj, desired, order) \
+ __atomic_store_n(obj, desired, order)
+#define atomic_fetch_add_explicit(obj, arg, order) \
+ __atomic_fetch_add(obj, arg, order)
+#define atomic_fetch_sub_explicit(obj, arg, order) \
+ __atomic_fetch_sub(obj, arg, order)
+#define atomic_fetch_and_explicit(obj, arg, order) \
+ __atomic_fetch_and(obj, arg, order)
+#define atomic_fetch_or_explicit(obj, arg, order) \
+ __atomic_fetch_or(obj, arg, order)
+#define atomic_compare_exchange_strong_explicit(obj, expected, desired, succ, \
+ fail) \
+ __atomic_compare_exchange_n(obj, expected, desired, 0, succ, fail)
+#define atomic_compare_exchange_weak_explicit(obj, expected, desired, succ, \
+ fail) \
+ __atomic_compare_exchange_n(obj, expected, desired, 1, succ, fail)
+#define atomic_exchange_explicit(obj, desired, order) \
+ __atomic_exchange_n(obj, desired, order)
+#else /* __sync builtins */
+#define atomic_init(obj, desired) (*obj = desired)
+#define atomic_load_explicit(obj, order) __sync_fetch_and_add(obj, 0)
+#define atomic_store_explicit(obj, desired, order) \
+ do { \
+ __sync_synchronize(); \
+ *obj = desired; \
+ __sync_synchronize(); \
+ } while (0);
+#define atomic_fetch_add_explicit(obj, arg, order) \
+ __sync_fetch_and_add(obj, arg)
+#define atomic_fetch_sub_explicit(obj, arg, order) \
+ __sync_fetch_and_sub(obj, arg, order)
+#define atomic_fetch_and_explicit(obj, arg, order) \
+ __sync_fetch_and_and(obj, arg, order)
+#define atomic_fetch_or_explicit(obj, arg, order) \
+ __sync_fetch_and_or(obj, arg, order)
+#define atomic_compare_exchange_strong_explicit(obj, expected, desired, succ, \
+ fail) \
+ ({ \
+ __typeof__(obj) __v; \
+ _Bool __r; \
+ __v = (__typeof__(obj))__sync_val_compare_and_swap( \
+ obj, *(expected), desired); \
+ __r = ((__typeof__(obj))*(expected) == __v); \
+ *(expected) = __v; \
+ __r; \
+ })
+#define atomic_compare_exchange_weak_explicit(obj, expected, desired, succ, \
+ fail) \
+ atomic_compare_exchange_strong_explicit(obj, expected, desired, succ, \
+ fail)
+#define atomic_exchange_explicit(obj, desired, order) \
+ __sync_lock_test_and_set(obj, desired)
+
+#endif /* if defined(__CLANG_ATOMICS) */
+
+#define atomic_load(obj) atomic_load_explicit(obj, memory_order_seq_cst)
+#define atomic_store(obj, arg) \
+ atomic_store_explicit(obj, arg, memory_order_seq_cst)
+#define atomic_fetch_add(obj, arg) \
+ atomic_fetch_add_explicit(obj, arg, memory_order_seq_cst)
+#define atomic_fetch_sub(obj, arg) \
+ atomic_fetch_sub_explicit(obj, arg, memory_order_seq_cst)
+#define atomic_fetch_and(obj, arg) \
+ atomic_fetch_and_explicit(obj, arg, memory_order_seq_cst)
+#define atomic_fetch_or(obj, arg) \
+ atomic_fetch_or_explicit(obj, arg, memory_order_seq_cst)
+#define atomic_compare_exchange_strong(obj, expected, desired) \
+ atomic_compare_exchange_strong_explicit(obj, expected, desired, \
+ memory_order_seq_cst, \
+ memory_order_seq_cst)
+#define atomic_compare_exchange_weak(obj, expected, desired) \
+ atomic_compare_exchange_weak_explicit(obj, expected, desired, \
+ memory_order_seq_cst, \
+ memory_order_seq_cst)
+#define atomic_exchange(obj, desired) \
+ atomic_exchange_explicit(obj, desired, memory_order_seq_cst)
diff --git a/lib/isc/unix/include/isc/stdtime.h b/lib/isc/unix/include/isc/stdtime.h
new file mode 100644
index 0000000..e38a2c6
--- /dev/null
+++ b/lib/isc/unix/include/isc/stdtime.h
@@ -0,0 +1,64 @@
+/*
+ * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
+ *
+ * SPDX-License-Identifier: MPL-2.0
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, you can obtain one at https://mozilla.org/MPL/2.0/.
+ *
+ * See the COPYRIGHT file distributed with this work for additional
+ * information regarding copyright ownership.
+ */
+
+#ifndef ISC_STDTIME_H
+#define ISC_STDTIME_H 1
+
+/*! \file */
+
+#include <inttypes.h>
+#include <stdlib.h>
+
+#include <isc/lang.h>
+
+/*%
+ * It's public information that 'isc_stdtime_t' is an unsigned integral type.
+ * Applications that want maximum portability should not assume anything
+ * about its size.
+ */
+typedef uint32_t isc_stdtime_t;
+
+ISC_LANG_BEGINDECLS
+/* */
+void
+isc_stdtime_get(isc_stdtime_t *t);
+/*%<
+ * Set 't' to the number of seconds since 00:00:00 UTC, January 1, 1970.
+ *
+ * Requires:
+ *
+ *\li 't' is a valid pointer.
+ */
+
+void
+isc_stdtime_tostring(isc_stdtime_t t, char *out, size_t outlen);
+/*
+ * Convert 't' into a null-terminated string of the form
+ * "Wed Jun 30 21:49:08 1993". Store the string in the 'out'
+ * buffer.
+ *
+ * Requires:
+ *
+ * 't' is a valid time.
+ * 'out' is a valid pointer.
+ * 'outlen' is at least 26.
+ */
+
+#define isc_stdtime_convert32(t, t32p) (*(t32p) = t)
+/*
+ * Convert the standard time to its 32-bit version.
+ */
+
+ISC_LANG_ENDDECLS
+
+#endif /* ISC_STDTIME_H */
diff --git a/lib/isc/unix/include/isc/syslog.h b/lib/isc/unix/include/isc/syslog.h
new file mode 100644
index 0000000..f46dc1a
--- /dev/null
+++ b/lib/isc/unix/include/isc/syslog.h
@@ -0,0 +1,41 @@
+/*
+ * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
+ *
+ * SPDX-License-Identifier: MPL-2.0
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, you can obtain one at https://mozilla.org/MPL/2.0/.
+ *
+ * See the COPYRIGHT file distributed with this work for additional
+ * information regarding copyright ownership.
+ */
+
+#ifndef ISC_SYSLOG_H
+#define ISC_SYSLOG_H 1
+
+/*! \file */
+
+#include <isc/lang.h>
+#include <isc/types.h>
+
+ISC_LANG_BEGINDECLS
+
+isc_result_t
+isc_syslog_facilityfromstring(const char *str, int *facilityp);
+/*%<
+ * Convert 'str' to the appropriate syslog facility constant.
+ *
+ * Requires:
+ *
+ *\li 'str' is not NULL
+ *\li 'facilityp' is not NULL
+ *
+ * Returns:
+ * \li #ISC_R_SUCCESS
+ * \li #ISC_R_NOTFOUND
+ */
+
+ISC_LANG_ENDDECLS
+
+#endif /* ISC_SYSLOG_H */
diff --git a/lib/isc/unix/include/isc/time.h b/lib/isc/unix/include/isc/time.h
new file mode 100644
index 0000000..ecec64d
--- /dev/null
+++ b/lib/isc/unix/include/isc/time.h
@@ -0,0 +1,452 @@
+/*
+ * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
+ *
+ * SPDX-License-Identifier: MPL-2.0
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, you can obtain one at https://mozilla.org/MPL/2.0/.
+ *
+ * See the COPYRIGHT file distributed with this work for additional
+ * information regarding copyright ownership.
+ */
+
+#ifndef ISC_TIME_H
+#define ISC_TIME_H 1
+
+/*! \file */
+
+#include <inttypes.h>
+#include <stdbool.h>
+
+#include <isc/lang.h>
+#include <isc/types.h>
+
+/***
+ *** Intervals
+ ***/
+
+/*!
+ * \brief
+ * The contents of this structure are private, and MUST NOT be accessed
+ * directly by callers.
+ *
+ * The contents are exposed only to allow callers to avoid dynamic allocation.
+ */
+struct isc_interval {
+ unsigned int seconds;
+ unsigned int nanoseconds;
+};
+
+extern const isc_interval_t *const isc_interval_zero;
+
+/*
+ * ISC_FORMATHTTPTIMESTAMP_SIZE needs to be 30 in C locale and potentially
+ * more for other locales to handle longer national abbreviations when
+ * expanding strftime's %a and %b.
+ */
+#define ISC_FORMATHTTPTIMESTAMP_SIZE 50
+
+ISC_LANG_BEGINDECLS
+
+void
+isc_interval_set(isc_interval_t *i, unsigned int seconds,
+ unsigned int nanoseconds);
+/*%<
+ * Set 'i' to a value representing an interval of 'seconds' seconds and
+ * 'nanoseconds' nanoseconds, suitable for use in isc_time_add() and
+ * isc_time_subtract().
+ *
+ * Requires:
+ *
+ *\li 't' is a valid pointer.
+ *\li nanoseconds < 1000000000.
+ */
+
+bool
+isc_interval_iszero(const isc_interval_t *i);
+/*%<
+ * Returns true iff. 'i' is the zero interval.
+ *
+ * Requires:
+ *
+ *\li 'i' is a valid pointer.
+ */
+
+/***
+ *** Absolute Times
+ ***/
+
+/*%
+ * The contents of this structure are private, and MUST NOT be accessed
+ * directly by callers.
+ *
+ * The contents are exposed only to allow callers to avoid dynamic allocation.
+ */
+
+struct isc_time {
+ unsigned int seconds;
+ unsigned int nanoseconds;
+};
+
+extern const isc_time_t *const isc_time_epoch;
+
+void
+isc_time_set(isc_time_t *t, unsigned int seconds, unsigned int nanoseconds);
+/*%<
+ * Set 't' to a value which represents the given number of seconds and
+ * nanoseconds since 00:00:00 January 1, 1970, UTC.
+ *
+ * Notes:
+ *\li The Unix version of this call is equivalent to:
+ *\code
+ * isc_time_settoepoch(t);
+ * isc_interval_set(i, seconds, nanoseconds);
+ * isc_time_add(t, i, t);
+ *\endcode
+ *
+ * Requires:
+ *\li 't' is a valid pointer.
+ *\li nanoseconds < 1000000000.
+ */
+
+void
+isc_time_settoepoch(isc_time_t *t);
+/*%<
+ * Set 't' to the time of the epoch.
+ *
+ * Notes:
+ *\li The date of the epoch is platform-dependent.
+ *
+ * Requires:
+ *
+ *\li 't' is a valid pointer.
+ */
+
+bool
+isc_time_isepoch(const isc_time_t *t);
+/*%<
+ * Returns true iff. 't' is the epoch ("time zero").
+ *
+ * Requires:
+ *
+ *\li 't' is a valid pointer.
+ */
+
+isc_result_t
+isc_time_now(isc_time_t *t);
+/*%<
+ * Set 't' to the current absolute time.
+ *
+ * Requires:
+ *
+ *\li 't' is a valid pointer.
+ *
+ * Returns:
+ *
+ *\li Success
+ *\li Unexpected error
+ * Getting the time from the system failed.
+ *\li Out of range
+ * The time from the system is too large to be represented
+ * in the current definition of isc_time_t.
+ */
+
+isc_result_t
+isc_time_now_hires(isc_time_t *t);
+/*%<
+ * Set 't' to the current absolute time. Uses higher resolution clocks
+ * recommended when microsecond accuracy is required.
+ *
+ * Requires:
+ *
+ *\li 't' is a valid pointer.
+ *
+ * Returns:
+ *
+ *\li Success
+ *\li Unexpected error
+ * Getting the time from the system failed.
+ *\li Out of range
+ * The time from the system is too large to be represented
+ * in the current definition of isc_time_t.
+ */
+
+isc_result_t
+isc_time_nowplusinterval(isc_time_t *t, const isc_interval_t *i);
+/*%<
+ * Set *t to the current absolute time + i.
+ *
+ * Note:
+ *\li This call is equivalent to:
+ *
+ *\code
+ * isc_time_now(t);
+ * isc_time_add(t, i, t);
+ *\endcode
+ *
+ * Requires:
+ *
+ *\li 't' and 'i' are valid pointers.
+ *
+ * Returns:
+ *
+ *\li Success
+ *\li Unexpected error
+ * Getting the time from the system failed.
+ *\li Out of range
+ * The interval added to the time from the system is too large to
+ * be represented in the current definition of isc_time_t.
+ */
+
+int
+isc_time_compare(const isc_time_t *t1, const isc_time_t *t2);
+/*%<
+ * Compare the times referenced by 't1' and 't2'
+ *
+ * Requires:
+ *
+ *\li 't1' and 't2' are valid pointers.
+ *
+ * Returns:
+ *
+ *\li -1 t1 < t2 (comparing times, not pointers)
+ *\li 0 t1 = t2
+ *\li 1 t1 > t2
+ */
+
+isc_result_t
+isc_time_add(const isc_time_t *t, const isc_interval_t *i, isc_time_t *result);
+/*%<
+ * Add 'i' to 't', storing the result in 'result'.
+ *
+ * Requires:
+ *
+ *\li 't', 'i', and 'result' are valid pointers.
+ *
+ * Returns:
+ *\li Success
+ *\li Out of range
+ * The interval added to the time is too large to
+ * be represented in the current definition of isc_time_t.
+ */
+
+isc_result_t
+isc_time_subtract(const isc_time_t *t, const isc_interval_t *i,
+ isc_time_t *result);
+/*%<
+ * Subtract 'i' from 't', storing the result in 'result'.
+ *
+ * Requires:
+ *
+ *\li 't', 'i', and 'result' are valid pointers.
+ *
+ * Returns:
+ *\li Success
+ *\li Out of range
+ * The interval is larger than the time since the epoch.
+ */
+
+uint64_t
+isc_time_microdiff(const isc_time_t *t1, const isc_time_t *t2);
+/*%<
+ * Find the difference in microseconds between time t1 and time t2.
+ * t2 is the subtrahend of t1; ie, difference = t1 - t2.
+ *
+ * Requires:
+ *
+ *\li 't1' and 't2' are valid pointers.
+ *
+ * Returns:
+ *\li The difference of t1 - t2, or 0 if t1 <= t2.
+ */
+
+uint32_t
+isc_time_seconds(const isc_time_t *t);
+/*%<
+ * Return the number of seconds since the epoch stored in a time structure.
+ *
+ * Requires:
+ *
+ *\li 't' is a valid pointer.
+ */
+
+isc_result_t
+isc_time_secondsastimet(const isc_time_t *t, time_t *secondsp);
+/*%<
+ * Ensure the number of seconds in an isc_time_t is representable by a time_t.
+ *
+ * Notes:
+ *\li The number of seconds stored in an isc_time_t might be larger
+ * than the number of seconds a time_t is able to handle. Since
+ * time_t is mostly opaque according to the ANSI/ISO standard
+ * (essentially, all you can be sure of is that it is an arithmetic type,
+ * not even necessarily integral), it can be tricky to ensure that
+ * the isc_time_t is in the range a time_t can handle. Use this
+ * function in place of isc_time_seconds() any time you need to set a
+ * time_t from an isc_time_t.
+ *
+ * Requires:
+ *\li 't' is a valid pointer.
+ *
+ * Returns:
+ *\li Success
+ *\li Out of range
+ */
+
+uint32_t
+isc_time_nanoseconds(const isc_time_t *t);
+/*%<
+ * Return the number of nanoseconds stored in a time structure.
+ *
+ * Notes:
+ *\li This is the number of nanoseconds in excess of the number
+ * of seconds since the epoch; it will always be less than one
+ * full second.
+ *
+ * Requires:
+ *\li 't' is a valid pointer.
+ *
+ * Ensures:
+ *\li The returned value is less than 1*10^9.
+ */
+
+void
+isc_time_formattimestamp(const isc_time_t *t, char *buf, unsigned int len);
+/*%<
+ * Format the time 't' into the buffer 'buf' of length 'len',
+ * using a format like "30-Aug-2000 04:06:47.997" and the local time zone.
+ * If the text does not fit in the buffer, the result is indeterminate,
+ * but is always guaranteed to be null terminated.
+ *
+ * Requires:
+ *\li 'len' > 0
+ *\li 'buf' points to an array of at least len chars
+ *
+ */
+
+void
+isc_time_formathttptimestamp(const isc_time_t *t, char *buf, unsigned int len);
+/*%<
+ * Format the time 't' into the buffer 'buf' of length 'len',
+ * using a format like "Mon, 30 Aug 2000 04:06:47 GMT"
+ * If the text does not fit in the buffer, the result is indeterminate,
+ * but is always guaranteed to be null terminated.
+ *
+ * Requires:
+ *\li 'len' > 0
+ *\li 'buf' points to an array of at least len chars
+ *
+ */
+
+isc_result_t
+isc_time_parsehttptimestamp(char *input, isc_time_t *t);
+/*%<
+ * Parse the time in 'input' into the isc_time_t pointed to by 't',
+ * expecting a format like "Mon, 30 Aug 2000 04:06:47 GMT"
+ *
+ * Requires:
+ *\li 'buf' and 't' are not NULL.
+ */
+
+void
+isc_time_formatISO8601L(const isc_time_t *t, char *buf, unsigned int len);
+/*%<
+ * Format the time 't' into the buffer 'buf' of length 'len',
+ * using the ISO8601 format: "yyyy-mm-ddThh:mm:ss"
+ * If the text does not fit in the buffer, the result is indeterminate,
+ * but is always guaranteed to be null terminated.
+ *
+ * Requires:
+ *\li 'len' > 0
+ *\li 'buf' points to an array of at least len chars
+ *
+ */
+
+void
+isc_time_formatISO8601Lms(const isc_time_t *t, char *buf, unsigned int len);
+/*%<
+ * Format the time 't' into the buffer 'buf' of length 'len',
+ * using the ISO8601 format: "yyyy-mm-ddThh:mm:ss.sss"
+ * If the text does not fit in the buffer, the result is indeterminate,
+ * but is always guaranteed to be null terminated.
+ *
+ * Requires:
+ *\li 'len' > 0
+ *\li 'buf' points to an array of at least len chars
+ *
+ */
+
+void
+isc_time_formatISO8601Lus(const isc_time_t *t, char *buf, unsigned int len);
+/*%<
+ * Format the time 't' into the buffer 'buf' of length 'len',
+ * using the ISO8601 format: "yyyy-mm-ddThh:mm:ss.ssssss"
+ * If the text does not fit in the buffer, the result is indeterminate,
+ * but is always guaranteed to be null terminated.
+ *
+ * Requires:
+ *\li 'len' > 0
+ *\li 'buf' points to an array of at least len chars
+ *
+ */
+
+void
+isc_time_formatISO8601(const isc_time_t *t, char *buf, unsigned int len);
+/*%<
+ * Format the time 't' into the buffer 'buf' of length 'len',
+ * using the ISO8601 format: "yyyy-mm-ddThh:mm:ssZ"
+ * If the text does not fit in the buffer, the result is indeterminate,
+ * but is always guaranteed to be null terminated.
+ *
+ * Requires:
+ *\li 'len' > 0
+ *\li 'buf' points to an array of at least len chars
+ *
+ */
+
+void
+isc_time_formatISO8601ms(const isc_time_t *t, char *buf, unsigned int len);
+/*%<
+ * Format the time 't' into the buffer 'buf' of length 'len',
+ * using the ISO8601 format: "yyyy-mm-ddThh:mm:ss.sssZ"
+ * If the text does not fit in the buffer, the result is indeterminate,
+ * but is always guaranteed to be null terminated.
+ *
+ * Requires:
+ *\li 'len' > 0
+ *\li 'buf' points to an array of at least len chars
+ *
+ */
+
+void
+isc_time_formatISO8601us(const isc_time_t *t, char *buf, unsigned int len);
+/*%<
+ * Format the time 't' into the buffer 'buf' of length 'len',
+ * using the ISO8601 format: "yyyy-mm-ddThh:mm:ss.ssssssZ"
+ * If the text does not fit in the buffer, the result is indeterminate,
+ * but is always guaranteed to be null terminated.
+ *
+ * Requires:
+ *\li 'len' > 0
+ *\li 'buf' points to an array of at least len chars
+ *
+ */
+
+void
+isc_time_formatshorttimestamp(const isc_time_t *t, char *buf, unsigned int len);
+/*%<
+ * Format the time 't' into the buffer 'buf' of length 'len',
+ * using the format "yyyymmddhhmmsssss" useful for file timestamping.
+ * If the text does not fit in the buffer, the result is indeterminate,
+ * but is always guaranteed to be null terminated.
+ *
+ * Requires:
+ *\li 'len' > 0
+ *\li 'buf' points to an array of at least len chars
+ *
+ */
+
+ISC_LANG_ENDDECLS
+
+#endif /* ISC_TIME_H */
diff --git a/lib/isc/unix/interfaceiter.c b/lib/isc/unix/interfaceiter.c
new file mode 100644
index 0000000..a1f6c9d
--- /dev/null
+++ b/lib/isc/unix/interfaceiter.c
@@ -0,0 +1,301 @@
+/*
+ * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
+ *
+ * SPDX-License-Identifier: MPL-2.0
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, you can obtain one at https://mozilla.org/MPL/2.0/.
+ *
+ * See the COPYRIGHT file distributed with this work for additional
+ * information regarding copyright ownership.
+ */
+
+/*! \file */
+
+#include <sys/ioctl.h>
+#include <sys/types.h>
+#ifdef HAVE_SYS_SOCKIO_H
+#include <sys/sockio.h> /* Required for ifiter_ioctl.c. */
+#endif /* ifdef HAVE_SYS_SOCKIO_H */
+
+#include <errno.h>
+#include <inttypes.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+
+#include <isc/interfaceiter.h>
+#include <isc/log.h>
+#include <isc/magic.h>
+#include <isc/mem.h>
+#include <isc/net.h>
+#include <isc/print.h>
+#include <isc/result.h>
+#include <isc/strerr.h>
+#include <isc/string.h>
+#include <isc/types.h>
+#include <isc/util.h>
+
+/* Must follow <isc/net.h>. */
+#ifdef HAVE_NET_IF6_H
+#include <net/if6.h>
+#endif /* ifdef HAVE_NET_IF6_H */
+#include <net/if.h>
+
+/* Common utility functions */
+
+/*%
+ * Extract the network address part from a "struct sockaddr".
+ * \brief
+ * The address family is given explicitly
+ * instead of using src->sa_family, because the latter does not work
+ * for copying a network mask obtained by SIOCGIFNETMASK (it does
+ * not have a valid address family).
+ */
+
+static void
+get_addr(unsigned int family, isc_netaddr_t *dst, struct sockaddr *src,
+ char *ifname) {
+ struct sockaddr_in6 *sa6;
+
+#if !defined(HAVE_IF_NAMETOINDEX)
+ UNUSED(ifname);
+#endif /* if !defined(HAVE_IF_NAMETOINDEX) */
+
+ /* clear any remaining value for safety */
+ memset(dst, 0, sizeof(*dst));
+
+ dst->family = family;
+ switch (family) {
+ case AF_INET:
+ memmove(&dst->type.in, &((struct sockaddr_in *)src)->sin_addr,
+ sizeof(struct in_addr));
+ break;
+ case AF_INET6:
+ sa6 = (struct sockaddr_in6 *)src;
+ memmove(&dst->type.in6, &sa6->sin6_addr,
+ sizeof(struct in6_addr));
+ if (sa6->sin6_scope_id != 0) {
+ isc_netaddr_setzone(dst, sa6->sin6_scope_id);
+ } else {
+ /*
+ * BSD variants embed scope zone IDs in the 128bit
+ * address as a kernel internal form. Unfortunately,
+ * the embedded IDs are not hidden from applications
+ * when getting access to them by sysctl or ioctl.
+ * We convert the internal format to the pure address
+ * part and the zone ID part.
+ * Since multicast addresses should not appear here
+ * and they cannot be distinguished from netmasks,
+ * we only consider unicast link-local addresses.
+ */
+ if (IN6_IS_ADDR_LINKLOCAL(&sa6->sin6_addr)) {
+ uint16_t zone16;
+
+ memmove(&zone16, &sa6->sin6_addr.s6_addr[2],
+ sizeof(zone16));
+ zone16 = ntohs(zone16);
+ if (zone16 != 0) {
+ /* the zone ID is embedded */
+ isc_netaddr_setzone(dst,
+ (uint32_t)zone16);
+ dst->type.in6.s6_addr[2] = 0;
+ dst->type.in6.s6_addr[3] = 0;
+#ifdef HAVE_IF_NAMETOINDEX
+ } else if (ifname != NULL) {
+ unsigned int zone;
+
+ /*
+ * sin6_scope_id is still not provided,
+ * but the corresponding interface name
+ * is know. Use the interface ID as
+ * the link ID.
+ */
+ zone = if_nametoindex(ifname);
+ if (zone != 0) {
+ isc_netaddr_setzone(
+ dst, (uint32_t)zone);
+ }
+#endif /* ifdef HAVE_IF_NAMETOINDEX */
+ }
+ }
+ }
+ break;
+ default:
+ UNREACHABLE();
+ }
+}
+
+/*
+ * Include system-dependent code.
+ */
+
+#ifdef __linux
+#define ISC_IF_INET6_SZ \
+ sizeof("00000000000000000000000000000001 01 80 10 80 " \
+ "XXXXXXloXXXXXXXX\n")
+static isc_result_t
+linux_if_inet6_next(isc_interfaceiter_t *);
+static isc_result_t
+linux_if_inet6_current(isc_interfaceiter_t *);
+static void
+linux_if_inet6_first(isc_interfaceiter_t *iter);
+#endif /* ifdef __linux */
+
+#include "ifiter_getifaddrs.c"
+
+#ifdef __linux
+static void
+linux_if_inet6_first(isc_interfaceiter_t *iter) {
+ if (iter->proc != NULL) {
+ rewind(iter->proc);
+ (void)linux_if_inet6_next(iter);
+ } else {
+ iter->valid = ISC_R_NOMORE;
+ }
+}
+
+static isc_result_t
+linux_if_inet6_next(isc_interfaceiter_t *iter) {
+ if (iter->proc != NULL &&
+ fgets(iter->entry, sizeof(iter->entry), iter->proc) != NULL)
+ {
+ iter->valid = ISC_R_SUCCESS;
+ } else {
+ iter->valid = ISC_R_NOMORE;
+ }
+ return (iter->valid);
+}
+
+static isc_result_t
+linux_if_inet6_current(isc_interfaceiter_t *iter) {
+ char address[33];
+ char name[IF_NAMESIZE + 1];
+ struct in6_addr addr6;
+ unsigned int ifindex, prefix, flag3, flag4;
+ int res;
+ unsigned int i;
+
+ if (iter->valid != ISC_R_SUCCESS) {
+ return (iter->valid);
+ }
+ if (iter->proc == NULL) {
+ isc_log_write(isc_lctx, ISC_LOGCATEGORY_GENERAL,
+ ISC_LOGMODULE_INTERFACE, ISC_LOG_ERROR,
+ "/proc/net/if_inet6:iter->proc == NULL");
+ return (ISC_R_FAILURE);
+ }
+
+ res = sscanf(iter->entry, "%32[a-f0-9] %x %x %x %x %16s\n", address,
+ &ifindex, &prefix, &flag3, &flag4, name);
+ if (res != 6) {
+ isc_log_write(isc_lctx, ISC_LOGCATEGORY_GENERAL,
+ ISC_LOGMODULE_INTERFACE, ISC_LOG_ERROR,
+ "/proc/net/if_inet6:sscanf() -> %d (expected 6)",
+ res);
+ return (ISC_R_FAILURE);
+ }
+ if (strlen(address) != 32) {
+ isc_log_write(isc_lctx, ISC_LOGCATEGORY_GENERAL,
+ ISC_LOGMODULE_INTERFACE, ISC_LOG_ERROR,
+ "/proc/net/if_inet6:strlen(%s) != 32", address);
+ return (ISC_R_FAILURE);
+ }
+ for (i = 0; i < 16; i++) {
+ unsigned char byte;
+ static const char hex[] = "0123456789abcdef";
+ byte = ((strchr(hex, address[i * 2]) - hex) << 4) |
+ (strchr(hex, address[i * 2 + 1]) - hex);
+ addr6.s6_addr[i] = byte;
+ }
+ iter->current.af = AF_INET6;
+ iter->current.flags = INTERFACE_F_UP;
+ isc_netaddr_fromin6(&iter->current.address, &addr6);
+ if (isc_netaddr_islinklocal(&iter->current.address)) {
+ isc_netaddr_setzone(&iter->current.address, (uint32_t)ifindex);
+ }
+ for (i = 0; i < 16; i++) {
+ if (prefix > 8) {
+ addr6.s6_addr[i] = 0xff;
+ prefix -= 8;
+ } else {
+ addr6.s6_addr[i] = (0xff << (8 - prefix)) & 0xff;
+ prefix = 0;
+ }
+ }
+ isc_netaddr_fromin6(&iter->current.netmask, &addr6);
+ strlcpy(iter->current.name, name, sizeof(iter->current.name));
+ return (ISC_R_SUCCESS);
+}
+#endif /* ifdef __linux */
+
+/*
+ * The remaining code is common to the sysctl and ioctl case.
+ */
+
+isc_result_t
+isc_interfaceiter_current(isc_interfaceiter_t *iter, isc_interface_t *ifdata) {
+ REQUIRE(iter->result == ISC_R_SUCCESS);
+ memmove(ifdata, &iter->current, sizeof(*ifdata));
+ return (ISC_R_SUCCESS);
+}
+
+isc_result_t
+isc_interfaceiter_first(isc_interfaceiter_t *iter) {
+ isc_result_t result;
+
+ REQUIRE(VALID_IFITER(iter));
+
+ internal_first(iter);
+ for (;;) {
+ result = internal_current(iter);
+ if (result != ISC_R_IGNORE) {
+ break;
+ }
+ result = internal_next(iter);
+ if (result != ISC_R_SUCCESS) {
+ break;
+ }
+ }
+ iter->result = result;
+ return (result);
+}
+
+isc_result_t
+isc_interfaceiter_next(isc_interfaceiter_t *iter) {
+ isc_result_t result;
+
+ REQUIRE(VALID_IFITER(iter));
+ REQUIRE(iter->result == ISC_R_SUCCESS);
+
+ for (;;) {
+ result = internal_next(iter);
+ if (result != ISC_R_SUCCESS) {
+ break;
+ }
+ result = internal_current(iter);
+ if (result != ISC_R_IGNORE) {
+ break;
+ }
+ }
+ iter->result = result;
+ return (result);
+}
+
+void
+isc_interfaceiter_destroy(isc_interfaceiter_t **iterp) {
+ isc_interfaceiter_t *iter;
+ REQUIRE(iterp != NULL);
+ iter = *iterp;
+ *iterp = NULL;
+ REQUIRE(VALID_IFITER(iter));
+
+ internal_destroy(iter);
+ if (iter->buf != NULL) {
+ isc_mem_put(iter->mctx, iter->buf, iter->bufsize);
+ }
+
+ iter->magic = 0;
+ isc_mem_put(iter->mctx, iter, sizeof(*iter));
+}
diff --git a/lib/isc/unix/meminfo.c b/lib/isc/unix/meminfo.c
new file mode 100644
index 0000000..612ccea
--- /dev/null
+++ b/lib/isc/unix/meminfo.c
@@ -0,0 +1,50 @@
+/*
+ * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
+ *
+ * SPDX-License-Identifier: MPL-2.0
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, you can obtain one at https://mozilla.org/MPL/2.0/.
+ *
+ * See the COPYRIGHT file distributed with this work for additional
+ * information regarding copyright ownership.
+ */
+
+#include <inttypes.h>
+#include <unistd.h>
+
+#include <isc/meminfo.h>
+#if defined(HAVE_SYS_SYSCTL_H) && !defined(__linux__)
+#include <sys/sysctl.h>
+#endif /* if defined(HAVE_SYS_SYSCTL_H) && !defined(__linux__) */
+
+uint64_t
+isc_meminfo_totalphys(void) {
+#if defined(CTL_HW) && (defined(HW_PHYSMEM64) || defined(HW_MEMSIZE))
+ int mib[2];
+ mib[0] = CTL_HW;
+#if defined(HW_MEMSIZE)
+ mib[1] = HW_MEMSIZE;
+#elif defined(HW_PHYSMEM64)
+ mib[1] = HW_PHYSMEM64;
+#endif /* if defined(HW_MEMSIZE) */
+ uint64_t size = 0;
+ size_t len = sizeof(size);
+ if (sysctl(mib, 2, &size, &len, NULL, 0) == 0) {
+ return (size);
+ }
+#endif /* if defined(CTL_HW) && (defined(HW_PHYSMEM64) || defined(HW_MEMSIZE)) \
+ * */
+#if defined(_SC_PHYS_PAGES) && defined(_SC_PAGESIZE)
+ long pages = sysconf(_SC_PHYS_PAGES);
+ long pagesize = sysconf(_SC_PAGESIZE);
+
+ if (pages == -1 || pagesize == -1) {
+ return (0);
+ }
+
+ return ((size_t)pages * pagesize);
+#endif /* if defined(_SC_PHYS_PAGES) && defined(_SC_PAGESIZE) */
+ return (0);
+}
diff --git a/lib/isc/unix/net.c b/lib/isc/unix/net.c
new file mode 100644
index 0000000..1e43b4b
--- /dev/null
+++ b/lib/isc/unix/net.c
@@ -0,0 +1,860 @@
+/*
+ * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
+ *
+ * SPDX-License-Identifier: MPL-2.0
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, you can obtain one at https://mozilla.org/MPL/2.0/.
+ *
+ * See the COPYRIGHT file distributed with this work for additional
+ * information regarding copyright ownership.
+ */
+
+#include <stdbool.h>
+#include <sys/types.h>
+
+#if defined(HAVE_SYS_SYSCTL_H) && !defined(__linux__)
+#if defined(HAVE_SYS_PARAM_H)
+#include <sys/param.h>
+#endif /* if defined(HAVE_SYS_PARAM_H) */
+#include <sys/sysctl.h>
+#endif /* if defined(HAVE_SYS_SYSCTL_H) && !defined(__linux__) */
+#include <errno.h>
+#include <fcntl.h>
+#include <sys/uio.h>
+#include <unistd.h>
+
+#include <isc/log.h>
+#include <isc/net.h>
+#include <isc/netdb.h>
+#include <isc/once.h>
+#include <isc/strerr.h>
+#include <isc/string.h>
+#include <isc/util.h>
+
+#ifndef socklen_t
+#define socklen_t unsigned int
+#endif /* ifndef socklen_t */
+
+/*%
+ * Definitions about UDP port range specification. This is a total mess of
+ * portability variants: some use sysctl (but the sysctl names vary), some use
+ * system-specific interfaces, some have the same interface for IPv4 and IPv6,
+ * some separate them, etc...
+ */
+
+/*%
+ * The last resort defaults: use all non well known port space
+ */
+#ifndef ISC_NET_PORTRANGELOW
+#define ISC_NET_PORTRANGELOW 1024
+#endif /* ISC_NET_PORTRANGELOW */
+#ifndef ISC_NET_PORTRANGEHIGH
+#define ISC_NET_PORTRANGEHIGH 65535
+#endif /* ISC_NET_PORTRANGEHIGH */
+
+#ifdef HAVE_SYSCTLBYNAME
+
+/*%
+ * sysctl variants
+ */
+#if defined(__FreeBSD__) || defined(__APPLE__) || defined(__DragonFly__)
+#define USE_SYSCTL_PORTRANGE
+#define SYSCTL_V4PORTRANGE_LOW "net.inet.ip.portrange.hifirst"
+#define SYSCTL_V4PORTRANGE_HIGH "net.inet.ip.portrange.hilast"
+#define SYSCTL_V6PORTRANGE_LOW "net.inet.ip.portrange.hifirst"
+#define SYSCTL_V6PORTRANGE_HIGH "net.inet.ip.portrange.hilast"
+#endif /* if defined(__FreeBSD__) || defined(__APPLE__) || \
+ * defined(__DragonFly__) */
+
+#ifdef __NetBSD__
+#define USE_SYSCTL_PORTRANGE
+#define SYSCTL_V4PORTRANGE_LOW "net.inet.ip.anonportmin"
+#define SYSCTL_V4PORTRANGE_HIGH "net.inet.ip.anonportmax"
+#define SYSCTL_V6PORTRANGE_LOW "net.inet6.ip6.anonportmin"
+#define SYSCTL_V6PORTRANGE_HIGH "net.inet6.ip6.anonportmax"
+#endif /* ifdef __NetBSD__ */
+
+#else /* !HAVE_SYSCTLBYNAME */
+
+#ifdef __OpenBSD__
+#define USE_SYSCTL_PORTRANGE
+#define SYSCTL_V4PORTRANGE_LOW \
+ { \
+ CTL_NET, PF_INET, IPPROTO_IP, IPCTL_IPPORT_HIFIRSTAUTO \
+ }
+#define SYSCTL_V4PORTRANGE_HIGH \
+ { \
+ CTL_NET, PF_INET, IPPROTO_IP, IPCTL_IPPORT_HILASTAUTO \
+ }
+/* Same for IPv6 */
+#define SYSCTL_V6PORTRANGE_LOW SYSCTL_V4PORTRANGE_LOW
+#define SYSCTL_V6PORTRANGE_HIGH SYSCTL_V4PORTRANGE_HIGH
+#endif /* ifdef __OpenBSD__ */
+
+#endif /* HAVE_SYSCTLBYNAME */
+
+static isc_once_t once_ipv6only = ISC_ONCE_INIT;
+#ifdef __notyet__
+static isc_once_t once_ipv6pktinfo = ISC_ONCE_INIT;
+#endif /* ifdef __notyet__ */
+
+#ifndef ISC_CMSG_IP_TOS
+#ifdef __APPLE__
+#define ISC_CMSG_IP_TOS 0 /* As of 10.8.2. */
+#else /* ! __APPLE__ */
+#define ISC_CMSG_IP_TOS 1
+#endif /* ! __APPLE__ */
+#endif /* ! ISC_CMSG_IP_TOS */
+
+static isc_once_t once = ISC_ONCE_INIT;
+static isc_once_t once_dscp = ISC_ONCE_INIT;
+
+static isc_result_t ipv4_result = ISC_R_NOTFOUND;
+static isc_result_t ipv6_result = ISC_R_NOTFOUND;
+static isc_result_t unix_result = ISC_R_NOTFOUND;
+static isc_result_t ipv6only_result = ISC_R_NOTFOUND;
+static isc_result_t ipv6pktinfo_result = ISC_R_NOTFOUND;
+static unsigned int dscp_result = 0;
+
+static isc_result_t
+try_proto(int domain) {
+ int s;
+ isc_result_t result = ISC_R_SUCCESS;
+ char strbuf[ISC_STRERRORSIZE];
+
+ s = socket(domain, SOCK_STREAM, 0);
+ if (s == -1) {
+ switch (errno) {
+#ifdef EAFNOSUPPORT
+ case EAFNOSUPPORT:
+#endif /* ifdef EAFNOSUPPORT */
+#ifdef EPFNOSUPPORT
+ case EPFNOSUPPORT:
+#endif /* ifdef EPFNOSUPPORT */
+#ifdef EPROTONOSUPPORT
+ case EPROTONOSUPPORT:
+#endif /* ifdef EPROTONOSUPPORT */
+#ifdef EINVAL
+ case EINVAL:
+#endif /* ifdef EINVAL */
+ return (ISC_R_NOTFOUND);
+ default:
+ strerror_r(errno, strbuf, sizeof(strbuf));
+ UNEXPECTED_ERROR(__FILE__, __LINE__,
+ "socket() failed: %s", strbuf);
+ return (ISC_R_UNEXPECTED);
+ }
+ }
+
+ if (domain == PF_INET6) {
+ struct sockaddr_in6 sin6;
+ unsigned int len;
+
+ /*
+ * Check to see if IPv6 is broken, as is common on Linux.
+ */
+ len = sizeof(sin6);
+ if (getsockname(s, (struct sockaddr *)&sin6, (void *)&len) < 0)
+ {
+ isc_log_write(isc_lctx, ISC_LOGCATEGORY_GENERAL,
+ ISC_LOGMODULE_SOCKET, ISC_LOG_ERROR,
+ "retrieving the address of an IPv6 "
+ "socket from the kernel failed.");
+ isc_log_write(isc_lctx, ISC_LOGCATEGORY_GENERAL,
+ ISC_LOGMODULE_SOCKET, ISC_LOG_ERROR,
+ "IPv6 is not supported.");
+ result = ISC_R_NOTFOUND;
+ } else {
+ if (len == sizeof(struct sockaddr_in6)) {
+ result = ISC_R_SUCCESS;
+ } else {
+ isc_log_write(isc_lctx, ISC_LOGCATEGORY_GENERAL,
+ ISC_LOGMODULE_SOCKET,
+ ISC_LOG_ERROR,
+ "IPv6 structures in kernel and "
+ "user space do not match.");
+ isc_log_write(isc_lctx, ISC_LOGCATEGORY_GENERAL,
+ ISC_LOGMODULE_SOCKET,
+ ISC_LOG_ERROR,
+ "IPv6 is not supported.");
+ result = ISC_R_NOTFOUND;
+ }
+ }
+ }
+
+ (void)close(s);
+
+ return (result);
+}
+
+static void
+initialize_action(void) {
+ ipv4_result = try_proto(PF_INET);
+ ipv6_result = try_proto(PF_INET6);
+#ifdef ISC_PLATFORM_HAVESYSUNH
+ unix_result = try_proto(PF_UNIX);
+#endif /* ifdef ISC_PLATFORM_HAVESYSUNH */
+}
+
+static void
+initialize(void) {
+ RUNTIME_CHECK(isc_once_do(&once, initialize_action) == ISC_R_SUCCESS);
+}
+
+isc_result_t
+isc_net_probeipv4(void) {
+ initialize();
+ return (ipv4_result);
+}
+
+isc_result_t
+isc_net_probeipv6(void) {
+ initialize();
+ return (ipv6_result);
+}
+
+isc_result_t
+isc_net_probeunix(void) {
+ initialize();
+ return (unix_result);
+}
+
+static void
+try_ipv6only(void) {
+#ifdef IPV6_V6ONLY
+ int s, on;
+ char strbuf[ISC_STRERRORSIZE];
+#endif /* ifdef IPV6_V6ONLY */
+ isc_result_t result;
+
+ result = isc_net_probeipv6();
+ if (result != ISC_R_SUCCESS) {
+ ipv6only_result = result;
+ return;
+ }
+
+#ifndef IPV6_V6ONLY
+ ipv6only_result = ISC_R_NOTFOUND;
+ return;
+#else /* ifndef IPV6_V6ONLY */
+ /* check for TCP sockets */
+ s = socket(PF_INET6, SOCK_STREAM, 0);
+ if (s == -1) {
+ strerror_r(errno, strbuf, sizeof(strbuf));
+ UNEXPECTED_ERROR(__FILE__, __LINE__, "socket() failed: %s",
+ strbuf);
+ ipv6only_result = ISC_R_UNEXPECTED;
+ return;
+ }
+
+ on = 1;
+ if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)) < 0) {
+ ipv6only_result = ISC_R_NOTFOUND;
+ goto close;
+ }
+
+ close(s);
+
+ /* check for UDP sockets */
+ s = socket(PF_INET6, SOCK_DGRAM, 0);
+ if (s == -1) {
+ strerror_r(errno, strbuf, sizeof(strbuf));
+ UNEXPECTED_ERROR(__FILE__, __LINE__, "socket() failed: %s",
+ strbuf);
+ ipv6only_result = ISC_R_UNEXPECTED;
+ return;
+ }
+
+ on = 1;
+ if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)) < 0) {
+ ipv6only_result = ISC_R_NOTFOUND;
+ goto close;
+ }
+
+ ipv6only_result = ISC_R_SUCCESS;
+
+close:
+ close(s);
+ return;
+#endif /* IPV6_V6ONLY */
+}
+
+static void
+initialize_ipv6only(void) {
+ RUNTIME_CHECK(isc_once_do(&once_ipv6only, try_ipv6only) ==
+ ISC_R_SUCCESS);
+}
+
+#ifdef __notyet__
+static void
+try_ipv6pktinfo(void) {
+ int s, on;
+ char strbuf[ISC_STRERRORSIZE];
+ isc_result_t result;
+ int optname;
+
+ result = isc_net_probeipv6();
+ if (result != ISC_R_SUCCESS) {
+ ipv6pktinfo_result = result;
+ return;
+ }
+
+ /* we only use this for UDP sockets */
+ s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_UDP);
+ if (s == -1) {
+ strerror_r(errno, strbuf, sizeof(strbuf));
+ UNEXPECTED_ERROR(__FILE__, __LINE__, "socket() failed: %s",
+ strbuf);
+ ipv6pktinfo_result = ISC_R_UNEXPECTED;
+ return;
+ }
+
+#ifdef IPV6_RECVPKTINFO
+ optname = IPV6_RECVPKTINFO;
+#else /* ifdef IPV6_RECVPKTINFO */
+ optname = IPV6_PKTINFO;
+#endif /* ifdef IPV6_RECVPKTINFO */
+ on = 1;
+ if (setsockopt(s, IPPROTO_IPV6, optname, &on, sizeof(on)) < 0) {
+ ipv6pktinfo_result = ISC_R_NOTFOUND;
+ goto close;
+ }
+
+ ipv6pktinfo_result = ISC_R_SUCCESS;
+
+close:
+ close(s);
+ return;
+}
+
+static void
+initialize_ipv6pktinfo(void) {
+ RUNTIME_CHECK(isc_once_do(&once_ipv6pktinfo, try_ipv6pktinfo) ==
+ ISC_R_SUCCESS);
+}
+#endif /* ifdef __notyet__ */
+
+isc_result_t
+isc_net_probe_ipv6only(void) {
+ initialize_ipv6only();
+ return (ipv6only_result);
+}
+
+isc_result_t
+isc_net_probe_ipv6pktinfo(void) {
+/*
+ * XXXWPK if pktinfo were supported then we could listen on :: for ipv6 and get
+ * the information about the destination address from pktinfo structure passed
+ * in recvmsg but this method is not portable and libuv doesn't support it - so
+ * we need to listen on all interfaces.
+ * We should verify that this doesn't impact performance (we already do it for
+ * ipv4) and either remove all the ipv6pktinfo detection code from above
+ * or think of fixing libuv.
+ */
+#ifdef __notyet__
+ initialize_ipv6pktinfo();
+#endif /* ifdef __notyet__ */
+ return (ipv6pktinfo_result);
+}
+
+#if ISC_CMSG_IP_TOS || defined(IPV6_TCLASS)
+
+static socklen_t
+cmsg_len(socklen_t len) {
+#ifdef CMSG_LEN
+ return (CMSG_LEN(len));
+#else /* ifdef CMSG_LEN */
+ socklen_t hdrlen;
+
+ /*
+ * Cast NULL so that any pointer arithmetic performed by CMSG_DATA
+ * is correct.
+ */
+ hdrlen = (socklen_t)CMSG_DATA(((struct cmsghdr *)NULL));
+ return (hdrlen + len);
+#endif /* ifdef CMSG_LEN */
+}
+
+static socklen_t
+cmsg_space(socklen_t len) {
+#ifdef CMSG_SPACE
+ return (CMSG_SPACE(len));
+#else /* ifdef CMSG_SPACE */
+ struct msghdr msg;
+ struct cmsghdr *cmsgp;
+ /*
+ * XXX: The buffer length is an ad-hoc value, but should be enough
+ * in a practical sense.
+ */
+ char dummybuf[sizeof(struct cmsghdr) + 1024];
+
+ memset(&msg, 0, sizeof(msg));
+ msg.msg_control = dummybuf;
+ msg.msg_controllen = sizeof(dummybuf);
+
+ cmsgp = (struct cmsghdr *)dummybuf;
+ cmsgp->cmsg_len = cmsg_len(len);
+
+ cmsgp = CMSG_NXTHDR(&msg, cmsgp);
+ if (cmsgp != NULL) {
+ return ((char *)cmsgp - (char *)msg.msg_control);
+ } else {
+ return (0);
+ }
+#endif /* ifdef CMSG_SPACE */
+}
+
+/*
+ * Make a fd non-blocking.
+ */
+static isc_result_t
+make_nonblock(int fd) {
+ int ret;
+ int flags;
+ char strbuf[ISC_STRERRORSIZE];
+#ifdef USE_FIONBIO_IOCTL
+ int on = 1;
+
+ ret = ioctl(fd, FIONBIO, (char *)&on);
+#else /* ifdef USE_FIONBIO_IOCTL */
+ flags = fcntl(fd, F_GETFL, 0);
+ flags |= PORT_NONBLOCK;
+ ret = fcntl(fd, F_SETFL, flags);
+#endif /* ifdef USE_FIONBIO_IOCTL */
+
+ if (ret == -1) {
+ strerror_r(errno, strbuf, sizeof(strbuf));
+ UNEXPECTED_ERROR(__FILE__, __LINE__,
+#ifdef USE_FIONBIO_IOCTL
+ "ioctl(%d, FIONBIO, &on): %s", fd,
+#else /* ifdef USE_FIONBIO_IOCTL */
+ "fcntl(%d, F_SETFL, %d): %s", fd, flags,
+#endif /* ifdef USE_FIONBIO_IOCTL */
+ strbuf);
+
+ return (ISC_R_UNEXPECTED);
+ }
+
+ return (ISC_R_SUCCESS);
+}
+
+static bool
+cmsgsend(int s, int level, int type, struct addrinfo *res) {
+ char strbuf[ISC_STRERRORSIZE];
+ struct sockaddr_storage ss;
+ socklen_t len = sizeof(ss);
+ struct msghdr msg;
+ union {
+ struct cmsghdr h;
+ unsigned char b[256];
+ } control;
+ struct cmsghdr *cmsgp;
+ int dscp = (46 << 2); /* Expedited forwarding. */
+ struct iovec iovec;
+ char buf[1] = { 0 };
+ isc_result_t result;
+
+ if (bind(s, res->ai_addr, res->ai_addrlen) < 0) {
+ strerror_r(errno, strbuf, sizeof(strbuf));
+ isc_log_write(isc_lctx, ISC_LOGCATEGORY_GENERAL,
+ ISC_LOGMODULE_SOCKET, ISC_LOG_DEBUG(10),
+ "bind: %s", strbuf);
+ return (false);
+ }
+
+ if (getsockname(s, (struct sockaddr *)&ss, &len) < 0) {
+ strerror_r(errno, strbuf, sizeof(strbuf));
+ isc_log_write(isc_lctx, ISC_LOGCATEGORY_GENERAL,
+ ISC_LOGMODULE_SOCKET, ISC_LOG_DEBUG(10),
+ "getsockname: %s", strbuf);
+ return (false);
+ }
+
+ iovec.iov_base = buf;
+ iovec.iov_len = sizeof(buf);
+
+ memset(&msg, 0, sizeof(msg));
+ msg.msg_name = (struct sockaddr *)&ss;
+ msg.msg_namelen = len;
+ msg.msg_iov = &iovec;
+ msg.msg_iovlen = 1;
+ msg.msg_control = (void *)&control;
+ msg.msg_controllen = 0;
+ msg.msg_flags = 0;
+
+ cmsgp = msg.msg_control;
+
+ switch (type) {
+#ifdef IP_TOS
+ case IP_TOS:
+ memset(cmsgp, 0, cmsg_space(sizeof(char)));
+ cmsgp->cmsg_level = level;
+ cmsgp->cmsg_type = type;
+ cmsgp->cmsg_len = cmsg_len(sizeof(char));
+ *(unsigned char *)CMSG_DATA(cmsgp) = dscp;
+ msg.msg_controllen += cmsg_space(sizeof(char));
+ break;
+#endif /* ifdef IP_TOS */
+#ifdef IPV6_TCLASS
+ case IPV6_TCLASS:
+ memset(cmsgp, 0, cmsg_space(sizeof(dscp)));
+ cmsgp->cmsg_level = level;
+ cmsgp->cmsg_type = type;
+ cmsgp->cmsg_len = cmsg_len(sizeof(dscp));
+ memmove(CMSG_DATA(cmsgp), &dscp, sizeof(dscp));
+ msg.msg_controllen += cmsg_space(sizeof(dscp));
+ break;
+#endif /* ifdef IPV6_TCLASS */
+ default:
+ UNREACHABLE();
+ }
+
+ if (sendmsg(s, &msg, 0) < 0) {
+ int debug = ISC_LOG_DEBUG(10);
+ const char *typestr;
+ switch (errno) {
+#ifdef ENOPROTOOPT
+ case ENOPROTOOPT:
+#endif /* ifdef ENOPROTOOPT */
+#ifdef EOPNOTSUPP
+ case EOPNOTSUPP:
+#endif /* ifdef EOPNOTSUPP */
+ case EINVAL:
+ case EPERM:
+ break;
+ default:
+ debug = ISC_LOG_NOTICE;
+ }
+ strerror_r(errno, strbuf, sizeof(strbuf));
+ if (debug != ISC_LOG_NOTICE) {
+ isc_log_write(isc_lctx, ISC_LOGCATEGORY_GENERAL,
+ ISC_LOGMODULE_SOCKET, ISC_LOG_DEBUG(10),
+ "sendmsg: %s", strbuf);
+ } else {
+ typestr = (type == IP_TOS) ? "IP_TOS" : "IPV6_TCLASS";
+ UNEXPECTED_ERROR(__FILE__, __LINE__,
+ "probing "
+ "sendmsg() with %s=%02x failed: %s",
+ typestr, dscp, strbuf);
+ }
+ return (false);
+ }
+
+ /*
+ * Make sure the message actually got sent.
+ */
+ result = make_nonblock(s);
+ RUNTIME_CHECK(result == ISC_R_SUCCESS);
+
+ iovec.iov_base = buf;
+ iovec.iov_len = sizeof(buf);
+
+ memset(&msg, 0, sizeof(msg));
+ msg.msg_name = (struct sockaddr *)&ss;
+ msg.msg_namelen = sizeof(ss);
+ msg.msg_iov = &iovec;
+ msg.msg_iovlen = 1;
+ msg.msg_control = NULL;
+ msg.msg_controllen = 0;
+ msg.msg_flags = 0;
+
+ if (recvmsg(s, &msg, 0) < 0) {
+ return (false);
+ }
+
+ return (true);
+}
+#endif /* if ISC_CMSG_IP_TOS || defined(IPV6_TCLASS) */
+
+static void
+try_dscp_v4(void) {
+#ifdef IP_TOS
+ char strbuf[ISC_STRERRORSIZE];
+ struct addrinfo hints, *res0;
+ int s, dscp = 0, n;
+#ifdef IP_RECVTOS
+ int on = 1;
+#endif /* IP_RECVTOS */
+
+ memset(&hints, 0, sizeof(hints));
+ hints.ai_family = AF_INET;
+ hints.ai_socktype = SOCK_DGRAM;
+ hints.ai_protocol = IPPROTO_UDP;
+#ifdef AI_NUMERICHOST
+ hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
+#else /* ifdef AI_NUMERICHOST */
+ hints.ai_flags = AI_PASSIVE;
+#endif /* ifdef AI_NUMERICHOST */
+
+ n = getaddrinfo("127.0.0.1", NULL, &hints, &res0);
+ if (n != 0 || res0 == NULL) {
+ isc_log_write(isc_lctx, ISC_LOGCATEGORY_GENERAL,
+ ISC_LOGMODULE_SOCKET, ISC_LOG_DEBUG(10),
+ "getaddrinfo(127.0.0.1): %s", gai_strerror(n));
+ return;
+ }
+
+ s = socket(res0->ai_family, res0->ai_socktype, res0->ai_protocol);
+
+ if (s == -1) {
+ strerror_r(errno, strbuf, sizeof(strbuf));
+ isc_log_write(isc_lctx, ISC_LOGCATEGORY_GENERAL,
+ ISC_LOGMODULE_SOCKET, ISC_LOG_DEBUG(10),
+ "socket: %s", strbuf);
+ freeaddrinfo(res0);
+ return;
+ }
+
+ if (setsockopt(s, IPPROTO_IP, IP_TOS, &dscp, sizeof(dscp)) == 0) {
+ dscp_result |= ISC_NET_DSCPSETV4;
+ }
+
+#ifdef IP_RECVTOS
+ on = 1;
+ if (setsockopt(s, IPPROTO_IP, IP_RECVTOS, &on, sizeof(on)) == 0) {
+ dscp_result |= ISC_NET_DSCPRECVV4;
+ }
+#endif /* IP_RECVTOS */
+
+#if ISC_CMSG_IP_TOS
+ if (cmsgsend(s, IPPROTO_IP, IP_TOS, res0)) {
+ dscp_result |= ISC_NET_DSCPPKTV4;
+ }
+#endif /* ISC_CMSG_IP_TOS */
+
+ freeaddrinfo(res0);
+ close(s);
+
+#endif /* IP_TOS */
+}
+
+static void
+try_dscp_v6(void) {
+#ifdef IPV6_TCLASS
+ char strbuf[ISC_STRERRORSIZE];
+ struct addrinfo hints, *res0;
+ int s, dscp = 0, n;
+#if defined(IPV6_RECVTCLASS)
+ int on = 1;
+#endif /* IPV6_RECVTCLASS */
+
+ memset(&hints, 0, sizeof(hints));
+ hints.ai_family = AF_INET6;
+ hints.ai_socktype = SOCK_DGRAM;
+ hints.ai_protocol = IPPROTO_UDP;
+#ifdef AI_NUMERICHOST
+ hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
+#else /* ifdef AI_NUMERICHOST */
+ hints.ai_flags = AI_PASSIVE;
+#endif /* ifdef AI_NUMERICHOST */
+
+ n = getaddrinfo("::1", NULL, &hints, &res0);
+ if (n != 0 || res0 == NULL) {
+ isc_log_write(isc_lctx, ISC_LOGCATEGORY_GENERAL,
+ ISC_LOGMODULE_SOCKET, ISC_LOG_DEBUG(10),
+ "getaddrinfo(::1): %s", gai_strerror(n));
+ return;
+ }
+
+ s = socket(res0->ai_family, res0->ai_socktype, res0->ai_protocol);
+ if (s == -1) {
+ strerror_r(errno, strbuf, sizeof(strbuf));
+ isc_log_write(isc_lctx, ISC_LOGCATEGORY_GENERAL,
+ ISC_LOGMODULE_SOCKET, ISC_LOG_DEBUG(10),
+ "socket: %s", strbuf);
+ freeaddrinfo(res0);
+ return;
+ }
+ if (setsockopt(s, IPPROTO_IPV6, IPV6_TCLASS, &dscp, sizeof(dscp)) == 0)
+ {
+ dscp_result |= ISC_NET_DSCPSETV6;
+ }
+
+#ifdef IPV6_RECVTCLASS
+ on = 1;
+ if (setsockopt(s, IPPROTO_IPV6, IPV6_RECVTCLASS, &on, sizeof(on)) == 0)
+ {
+ dscp_result |= ISC_NET_DSCPRECVV6;
+ }
+#endif /* IPV6_RECVTCLASS */
+
+ if (cmsgsend(s, IPPROTO_IPV6, IPV6_TCLASS, res0)) {
+ dscp_result |= ISC_NET_DSCPPKTV6;
+ }
+
+ freeaddrinfo(res0);
+ close(s);
+
+#endif /* IPV6_TCLASS */
+}
+
+static void
+try_dscp(void) {
+ try_dscp_v4();
+ try_dscp_v6();
+}
+
+static void
+initialize_dscp(void) {
+ RUNTIME_CHECK(isc_once_do(&once_dscp, try_dscp) == ISC_R_SUCCESS);
+}
+
+unsigned int
+isc_net_probedscp(void) {
+ initialize_dscp();
+ return (dscp_result);
+}
+
+#if defined(USE_SYSCTL_PORTRANGE)
+#if defined(HAVE_SYSCTLBYNAME)
+static isc_result_t
+getudpportrange_sysctl(int af, in_port_t *low, in_port_t *high) {
+ int port_low, port_high;
+ size_t portlen;
+ const char *sysctlname_lowport, *sysctlname_hiport;
+
+ if (af == AF_INET) {
+ sysctlname_lowport = SYSCTL_V4PORTRANGE_LOW;
+ sysctlname_hiport = SYSCTL_V4PORTRANGE_HIGH;
+ } else {
+ sysctlname_lowport = SYSCTL_V6PORTRANGE_LOW;
+ sysctlname_hiport = SYSCTL_V6PORTRANGE_HIGH;
+ }
+ portlen = sizeof(port_low);
+ if (sysctlbyname(sysctlname_lowport, &port_low, &portlen, NULL, 0) < 0)
+ {
+ return (ISC_R_FAILURE);
+ }
+ portlen = sizeof(port_high);
+ if (sysctlbyname(sysctlname_hiport, &port_high, &portlen, NULL, 0) < 0)
+ {
+ return (ISC_R_FAILURE);
+ }
+ if ((port_low & ~0xffff) != 0 || (port_high & ~0xffff) != 0) {
+ return (ISC_R_RANGE);
+ }
+
+ *low = (in_port_t)port_low;
+ *high = (in_port_t)port_high;
+
+ return (ISC_R_SUCCESS);
+}
+#else /* !HAVE_SYSCTLBYNAME */
+static isc_result_t
+getudpportrange_sysctl(int af, in_port_t *low, in_port_t *high) {
+ int mib_lo4[4] = SYSCTL_V4PORTRANGE_LOW;
+ int mib_hi4[4] = SYSCTL_V4PORTRANGE_HIGH;
+ int mib_lo6[4] = SYSCTL_V6PORTRANGE_LOW;
+ int mib_hi6[4] = SYSCTL_V6PORTRANGE_HIGH;
+ int *mib_lo, *mib_hi, miblen;
+ int port_low, port_high;
+ size_t portlen;
+
+ if (af == AF_INET) {
+ mib_lo = mib_lo4;
+ mib_hi = mib_hi4;
+ miblen = sizeof(mib_lo4) / sizeof(mib_lo4[0]);
+ } else {
+ mib_lo = mib_lo6;
+ mib_hi = mib_hi6;
+ miblen = sizeof(mib_lo6) / sizeof(mib_lo6[0]);
+ }
+
+ portlen = sizeof(port_low);
+ if (sysctl(mib_lo, miblen, &port_low, &portlen, NULL, 0) < 0) {
+ return (ISC_R_FAILURE);
+ }
+
+ portlen = sizeof(port_high);
+ if (sysctl(mib_hi, miblen, &port_high, &portlen, NULL, 0) < 0) {
+ return (ISC_R_FAILURE);
+ }
+
+ if ((port_low & ~0xffff) != 0 || (port_high & ~0xffff) != 0) {
+ return (ISC_R_RANGE);
+ }
+
+ *low = (in_port_t)port_low;
+ *high = (in_port_t)port_high;
+
+ return (ISC_R_SUCCESS);
+}
+#endif /* HAVE_SYSCTLBYNAME */
+#endif /* USE_SYSCTL_PORTRANGE */
+
+isc_result_t
+isc_net_getudpportrange(int af, in_port_t *low, in_port_t *high) {
+ int result = ISC_R_FAILURE;
+#if !defined(USE_SYSCTL_PORTRANGE) && defined(__linux)
+ FILE *fp;
+#endif /* if !defined(USE_SYSCTL_PORTRANGE) && defined(__linux) */
+
+ REQUIRE(low != NULL && high != NULL);
+
+#if defined(USE_SYSCTL_PORTRANGE)
+ result = getudpportrange_sysctl(af, low, high);
+#elif defined(__linux)
+
+ UNUSED(af);
+
+ /*
+ * Linux local ports are address family agnostic.
+ */
+ fp = fopen("/proc/sys/net/ipv4/ip_local_port_range", "r");
+ if (fp != NULL) {
+ int n;
+ unsigned int l, h;
+
+ n = fscanf(fp, "%u %u", &l, &h);
+ if (n == 2 && (l & ~0xffff) == 0 && (h & ~0xffff) == 0) {
+ *low = l;
+ *high = h;
+ result = ISC_R_SUCCESS;
+ }
+ fclose(fp);
+ }
+#else /* if defined(USE_SYSCTL_PORTRANGE) */
+ UNUSED(af);
+#endif /* if defined(USE_SYSCTL_PORTRANGE) */
+
+ if (result != ISC_R_SUCCESS) {
+ *low = ISC_NET_PORTRANGELOW;
+ *high = ISC_NET_PORTRANGEHIGH;
+ }
+
+ return (ISC_R_SUCCESS); /* we currently never fail in this function */
+}
+
+void
+isc_net_disableipv4(void) {
+ initialize();
+ if (ipv4_result == ISC_R_SUCCESS) {
+ ipv4_result = ISC_R_DISABLED;
+ }
+}
+
+void
+isc_net_disableipv6(void) {
+ initialize();
+ if (ipv6_result == ISC_R_SUCCESS) {
+ ipv6_result = ISC_R_DISABLED;
+ }
+}
+
+void
+isc_net_enableipv4(void) {
+ initialize();
+ if (ipv4_result == ISC_R_DISABLED) {
+ ipv4_result = ISC_R_SUCCESS;
+ }
+}
+
+void
+isc_net_enableipv6(void) {
+ initialize();
+ if (ipv6_result == ISC_R_DISABLED) {
+ ipv6_result = ISC_R_SUCCESS;
+ }
+}
diff --git a/lib/isc/unix/os.c b/lib/isc/unix/os.c
new file mode 100644
index 0000000..5577587
--- /dev/null
+++ b/lib/isc/unix/os.c
@@ -0,0 +1,68 @@
+/*
+ * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
+ *
+ * SPDX-License-Identifier: MPL-2.0
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, you can obtain one at https://mozilla.org/MPL/2.0/.
+ *
+ * See the COPYRIGHT file distributed with this work for additional
+ * information regarding copyright ownership.
+ */
+
+#include <isc/os.h>
+
+#ifdef HAVE_SYSCONF
+
+#include <unistd.h>
+
+static long
+sysconf_ncpus(void) {
+#if defined(_SC_NPROCESSORS_ONLN)
+ return (sysconf((_SC_NPROCESSORS_ONLN)));
+#elif defined(_SC_NPROC_ONLN)
+ return (sysconf((_SC_NPROC_ONLN)));
+#else /* if defined(_SC_NPROCESSORS_ONLN) */
+ return (0);
+#endif /* if defined(_SC_NPROCESSORS_ONLN) */
+}
+#endif /* HAVE_SYSCONF */
+
+#if defined(HAVE_SYS_SYSCTL_H) && defined(HAVE_SYSCTLBYNAME)
+#include <sys/param.h> /* for NetBSD */
+#include <sys/sysctl.h>
+#include <sys/types.h> /* for FreeBSD */
+
+static int
+sysctl_ncpus(void) {
+ int ncpu, result;
+ size_t len;
+
+ len = sizeof(ncpu);
+ result = sysctlbyname("hw.ncpu", &ncpu, &len, 0, 0);
+ if (result != -1) {
+ return (ncpu);
+ }
+ return (0);
+}
+#endif /* if defined(HAVE_SYS_SYSCTL_H) && defined(HAVE_SYSCTLBYNAME) */
+
+unsigned int
+isc_os_ncpus(void) {
+ long ncpus = 0;
+
+#if defined(HAVE_SYSCONF)
+ ncpus = sysconf_ncpus();
+#endif /* if defined(HAVE_SYSCONF) */
+#if defined(HAVE_SYS_SYSCTL_H) && defined(HAVE_SYSCTLBYNAME)
+ if (ncpus <= 0) {
+ ncpus = sysctl_ncpus();
+ }
+#endif /* if defined(HAVE_SYS_SYSCTL_H) && defined(HAVE_SYSCTLBYNAME) */
+ if (ncpus <= 0) {
+ ncpus = 1;
+ }
+
+ return ((unsigned int)ncpus);
+}
diff --git a/lib/isc/unix/pk11_api.c b/lib/isc/unix/pk11_api.c
new file mode 100644
index 0000000..babd1a9
--- /dev/null
+++ b/lib/isc/unix/pk11_api.c
@@ -0,0 +1,708 @@
+/*
+ * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
+ *
+ * SPDX-License-Identifier: MPL-2.0
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, you can obtain one at https://mozilla.org/MPL/2.0/.
+ *
+ * See the COPYRIGHT file distributed with this work for additional
+ * information regarding copyright ownership.
+ */
+
+/*! \file */
+
+#include <dlfcn.h>
+#include <string.h>
+
+#include <isc/log.h>
+#include <isc/mem.h>
+#include <isc/once.h>
+#include <isc/print.h>
+#include <isc/stdio.h>
+#include <isc/thread.h>
+#include <isc/util.h>
+
+#include <pkcs11/pkcs11.h>
+
+#define KEEP_PKCS11_NAMES
+#include <pk11/internal.h>
+#include <pk11/pk11.h>
+
+static void *hPK11 = NULL;
+static char loaderrmsg[1024];
+
+CK_RV
+pkcs_C_Initialize(CK_VOID_PTR pReserved) {
+ CK_C_Initialize sym;
+
+ if (hPK11 != NULL) {
+ return (CKR_CRYPTOKI_ALREADY_INITIALIZED);
+ }
+
+ hPK11 = dlopen(pk11_get_lib_name(), RTLD_NOW);
+
+ if (hPK11 == NULL) {
+ snprintf(loaderrmsg, sizeof(loaderrmsg),
+ "dlopen(\"%s\") failed: %s\n", pk11_get_lib_name(),
+ dlerror());
+ return (CKR_LIBRARY_LOAD_FAILED);
+ }
+ sym = (CK_C_Initialize)dlsym(hPK11, "C_Initialize");
+ if (sym == NULL) {
+ return (CKR_FUNCTION_NOT_SUPPORTED);
+ }
+ return ((*sym)(pReserved));
+}
+
+char *
+pk11_get_load_error_message(void) {
+ return (loaderrmsg);
+}
+
+CK_RV
+pkcs_C_Finalize(CK_VOID_PTR pReserved) {
+ CK_C_Finalize sym;
+ CK_RV rv;
+
+ if (hPK11 == NULL) {
+ return (CKR_LIBRARY_LOAD_FAILED);
+ }
+ sym = (CK_C_Finalize)dlsym(hPK11, "C_Finalize");
+ if (sym == NULL) {
+ return (CKR_FUNCTION_NOT_SUPPORTED);
+ }
+ rv = (*sym)(pReserved);
+ if ((rv == CKR_OK) && (dlclose(hPK11) != 0)) {
+ return (CKR_LIBRARY_LOAD_FAILED);
+ }
+ hPK11 = NULL;
+ return (rv);
+}
+
+CK_RV
+pkcs_C_GetSlotList(CK_BBOOL tokenPresent, CK_SLOT_ID_PTR pSlotList,
+ CK_ULONG_PTR pulCount) {
+ static CK_C_GetSlotList sym = NULL;
+ static void *pPK11 = NULL;
+
+ if (hPK11 == NULL) {
+ return (CKR_LIBRARY_LOAD_FAILED);
+ }
+ if ((sym == NULL) || (hPK11 != pPK11)) {
+ pPK11 = hPK11;
+ sym = (CK_C_GetSlotList)dlsym(hPK11, "C_GetSlotList");
+ }
+ if (sym == NULL) {
+ return (CKR_FUNCTION_NOT_SUPPORTED);
+ }
+ return ((*sym)(tokenPresent, pSlotList, pulCount));
+}
+
+CK_RV
+pkcs_C_GetTokenInfo(CK_SLOT_ID slotID, CK_TOKEN_INFO_PTR pInfo) {
+ static CK_C_GetTokenInfo sym = NULL;
+ static void *pPK11 = NULL;
+
+ if (hPK11 == NULL) {
+ return (CKR_LIBRARY_LOAD_FAILED);
+ }
+ if ((sym == NULL) || (hPK11 != pPK11)) {
+ pPK11 = hPK11;
+ sym = (CK_C_GetTokenInfo)dlsym(hPK11, "C_GetTokenInfo");
+ }
+ if (sym == NULL) {
+ return (CKR_FUNCTION_NOT_SUPPORTED);
+ }
+ return ((*sym)(slotID, pInfo));
+}
+
+CK_RV
+pkcs_C_GetMechanismInfo(CK_SLOT_ID slotID, CK_MECHANISM_TYPE type,
+ CK_MECHANISM_INFO_PTR pInfo) {
+ static CK_C_GetMechanismInfo sym = NULL;
+ static void *pPK11 = NULL;
+
+ if (hPK11 == NULL) {
+ return (CKR_LIBRARY_LOAD_FAILED);
+ }
+ if ((sym == NULL) || (hPK11 != pPK11)) {
+ pPK11 = hPK11;
+ sym = (CK_C_GetMechanismInfo)dlsym(hPK11, "C_GetMechanismInfo");
+ }
+ if (sym == NULL) {
+ return (CKR_FUNCTION_NOT_SUPPORTED);
+ }
+ return ((*sym)(slotID, type, pInfo));
+}
+
+CK_RV
+pkcs_C_OpenSession(CK_SLOT_ID slotID, CK_FLAGS flags, CK_VOID_PTR pApplication,
+ CK_RV (*Notify)(CK_SESSION_HANDLE hSession,
+ CK_NOTIFICATION event,
+ CK_VOID_PTR pApplication),
+ CK_SESSION_HANDLE_PTR phSession) {
+ static CK_C_OpenSession sym = NULL;
+ static void *pPK11 = NULL;
+
+ if (hPK11 == NULL) {
+ hPK11 = dlopen(pk11_get_lib_name(), RTLD_NOW);
+ }
+ if (hPK11 == NULL) {
+ snprintf(loaderrmsg, sizeof(loaderrmsg),
+ "dlopen(\"%s\") failed: %s\n", pk11_get_lib_name(),
+ dlerror());
+ return (CKR_LIBRARY_LOAD_FAILED);
+ }
+ if ((sym == NULL) || (hPK11 != pPK11)) {
+ pPK11 = hPK11;
+ sym = (CK_C_OpenSession)dlsym(hPK11, "C_OpenSession");
+ }
+ if (sym == NULL) {
+ return (CKR_FUNCTION_NOT_SUPPORTED);
+ }
+ return ((*sym)(slotID, flags, pApplication, Notify, phSession));
+}
+
+CK_RV
+pkcs_C_CloseSession(CK_SESSION_HANDLE hSession) {
+ static CK_C_CloseSession sym = NULL;
+ static void *pPK11 = NULL;
+
+ if (hPK11 == NULL) {
+ return (CKR_LIBRARY_LOAD_FAILED);
+ }
+ if ((sym == NULL) || (hPK11 != pPK11)) {
+ pPK11 = hPK11;
+ sym = (CK_C_CloseSession)dlsym(hPK11, "C_CloseSession");
+ }
+ if (sym == NULL) {
+ return (CKR_FUNCTION_NOT_SUPPORTED);
+ }
+ return ((*sym)(hSession));
+}
+
+CK_RV
+pkcs_C_Login(CK_SESSION_HANDLE hSession, CK_USER_TYPE userType,
+ CK_CHAR_PTR pPin, CK_ULONG usPinLen) {
+ static CK_C_Login sym = NULL;
+ static void *pPK11 = NULL;
+
+ if (hPK11 == NULL) {
+ return (CKR_LIBRARY_LOAD_FAILED);
+ }
+ if ((sym == NULL) || (hPK11 != pPK11)) {
+ pPK11 = hPK11;
+ sym = (CK_C_Login)dlsym(hPK11, "C_Login");
+ }
+ if (sym == NULL) {
+ return (CKR_FUNCTION_NOT_SUPPORTED);
+ }
+ return ((*sym)(hSession, userType, pPin, usPinLen));
+}
+
+CK_RV
+pkcs_C_Logout(CK_SESSION_HANDLE hSession) {
+ static CK_C_Logout sym = NULL;
+ static void *pPK11 = NULL;
+
+ if (hPK11 == NULL) {
+ return (CKR_LIBRARY_LOAD_FAILED);
+ }
+ if ((sym == NULL) || (hPK11 != pPK11)) {
+ pPK11 = hPK11;
+ sym = (CK_C_Logout)dlsym(hPK11, "C_Logout");
+ }
+ if (sym == NULL) {
+ return (CKR_FUNCTION_NOT_SUPPORTED);
+ }
+ return ((*sym)(hSession));
+}
+
+CK_RV
+pkcs_C_CreateObject(CK_SESSION_HANDLE hSession, CK_ATTRIBUTE_PTR pTemplate,
+ CK_ULONG usCount, CK_OBJECT_HANDLE_PTR phObject) {
+ static CK_C_CreateObject sym = NULL;
+ static void *pPK11 = NULL;
+
+ if (hPK11 == NULL) {
+ return (CKR_LIBRARY_LOAD_FAILED);
+ }
+ if ((sym == NULL) || (hPK11 != pPK11)) {
+ pPK11 = hPK11;
+ sym = (CK_C_CreateObject)dlsym(hPK11, "C_CreateObject");
+ }
+ if (sym == NULL) {
+ return (CKR_FUNCTION_NOT_SUPPORTED);
+ }
+ return ((*sym)(hSession, pTemplate, usCount, phObject));
+}
+
+CK_RV
+pkcs_C_DestroyObject(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject) {
+ static CK_C_DestroyObject sym = NULL;
+ static void *pPK11 = NULL;
+
+ if (hPK11 == NULL) {
+ return (CKR_LIBRARY_LOAD_FAILED);
+ }
+ if ((sym == NULL) || (hPK11 != pPK11)) {
+ pPK11 = hPK11;
+ sym = (CK_C_DestroyObject)dlsym(hPK11, "C_DestroyObject");
+ }
+ if (sym == NULL) {
+ return (CKR_FUNCTION_NOT_SUPPORTED);
+ }
+ return ((*sym)(hSession, hObject));
+}
+
+CK_RV
+pkcs_C_GetAttributeValue(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject,
+ CK_ATTRIBUTE_PTR pTemplate, CK_ULONG usCount) {
+ static CK_C_GetAttributeValue sym = NULL;
+ static void *pPK11 = NULL;
+
+ if (hPK11 == NULL) {
+ return (CKR_LIBRARY_LOAD_FAILED);
+ }
+ if ((sym == NULL) || (hPK11 != pPK11)) {
+ pPK11 = hPK11;
+ sym = (CK_C_GetAttributeValue)dlsym(hPK11, "C_"
+ "GetAttributeValue");
+ }
+ if (sym == NULL) {
+ return (CKR_FUNCTION_NOT_SUPPORTED);
+ }
+ return ((*sym)(hSession, hObject, pTemplate, usCount));
+}
+
+CK_RV
+pkcs_C_SetAttributeValue(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject,
+ CK_ATTRIBUTE_PTR pTemplate, CK_ULONG usCount) {
+ static CK_C_SetAttributeValue sym = NULL;
+ static void *pPK11 = NULL;
+
+ if (hPK11 == NULL) {
+ return (CKR_LIBRARY_LOAD_FAILED);
+ }
+ if ((sym == NULL) || (hPK11 != pPK11)) {
+ pPK11 = hPK11;
+ sym = (CK_C_SetAttributeValue)dlsym(hPK11, "C_"
+ "SetAttributeValue");
+ }
+ if (sym == NULL) {
+ return (CKR_FUNCTION_NOT_SUPPORTED);
+ }
+ return ((*sym)(hSession, hObject, pTemplate, usCount));
+}
+
+CK_RV
+pkcs_C_FindObjectsInit(CK_SESSION_HANDLE hSession, CK_ATTRIBUTE_PTR pTemplate,
+ CK_ULONG usCount) {
+ static CK_C_FindObjectsInit sym = NULL;
+ static void *pPK11 = NULL;
+
+ if (hPK11 == NULL) {
+ return (CKR_LIBRARY_LOAD_FAILED);
+ }
+ if ((sym == NULL) || (hPK11 != pPK11)) {
+ pPK11 = hPK11;
+ sym = (CK_C_FindObjectsInit)dlsym(hPK11, "C_FindObjectsInit");
+ }
+ if (sym == NULL) {
+ return (CKR_FUNCTION_NOT_SUPPORTED);
+ }
+ return ((*sym)(hSession, pTemplate, usCount));
+}
+
+CK_RV
+pkcs_C_FindObjects(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE_PTR phObject,
+ CK_ULONG usMaxObjectCount, CK_ULONG_PTR pusObjectCount) {
+ static CK_C_FindObjects sym = NULL;
+ static void *pPK11 = NULL;
+
+ if (hPK11 == NULL) {
+ return (CKR_LIBRARY_LOAD_FAILED);
+ }
+ if ((sym == NULL) || (hPK11 != pPK11)) {
+ pPK11 = hPK11;
+ sym = (CK_C_FindObjects)dlsym(hPK11, "C_FindObjects");
+ }
+ if (sym == NULL) {
+ return (CKR_FUNCTION_NOT_SUPPORTED);
+ }
+ return ((*sym)(hSession, phObject, usMaxObjectCount, pusObjectCount));
+}
+
+CK_RV
+pkcs_C_FindObjectsFinal(CK_SESSION_HANDLE hSession) {
+ static CK_C_FindObjectsFinal sym = NULL;
+ static void *pPK11 = NULL;
+
+ if (hPK11 == NULL) {
+ return (CKR_LIBRARY_LOAD_FAILED);
+ }
+ if ((sym == NULL) || (hPK11 != pPK11)) {
+ pPK11 = hPK11;
+ sym = (CK_C_FindObjectsFinal)dlsym(hPK11, "C_FindObjectsFinal");
+ }
+ if (sym == NULL) {
+ return (CKR_FUNCTION_NOT_SUPPORTED);
+ }
+ return ((*sym)(hSession));
+}
+
+CK_RV
+pkcs_C_EncryptInit(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism,
+ CK_OBJECT_HANDLE hKey) {
+ static CK_C_EncryptInit sym = NULL;
+ static void *pPK11 = NULL;
+
+ if (hPK11 == NULL) {
+ return (CKR_LIBRARY_LOAD_FAILED);
+ }
+ if ((sym == NULL) || (hPK11 != pPK11)) {
+ pPK11 = hPK11;
+ sym = (CK_C_EncryptInit)dlsym(hPK11, "C_EncryptInit");
+ }
+ if (sym == NULL) {
+ return (CKR_FUNCTION_NOT_SUPPORTED);
+ }
+ return ((*sym)(hSession, pMechanism, hKey));
+}
+
+CK_RV
+pkcs_C_Encrypt(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pData,
+ CK_ULONG ulDataLen, CK_BYTE_PTR pEncryptedData,
+ CK_ULONG_PTR pulEncryptedDataLen) {
+ static CK_C_Encrypt sym = NULL;
+ static void *pPK11 = NULL;
+
+ if (hPK11 == NULL) {
+ return (CKR_LIBRARY_LOAD_FAILED);
+ }
+ if ((sym == NULL) || (hPK11 != pPK11)) {
+ pPK11 = hPK11;
+ sym = (CK_C_Encrypt)dlsym(hPK11, "C_Encrypt");
+ }
+ if (sym == NULL) {
+ return (CKR_FUNCTION_NOT_SUPPORTED);
+ }
+ return ((*sym)(hSession, pData, ulDataLen, pEncryptedData,
+ pulEncryptedDataLen));
+}
+
+CK_RV
+pkcs_C_DigestInit(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism) {
+ static CK_C_DigestInit sym = NULL;
+ static void *pPK11 = NULL;
+
+ if (hPK11 == NULL) {
+ return (CKR_LIBRARY_LOAD_FAILED);
+ }
+ if ((sym == NULL) || (hPK11 != pPK11)) {
+ pPK11 = hPK11;
+ sym = (CK_C_DigestInit)dlsym(hPK11, "C_DigestInit");
+ }
+ if (sym == NULL) {
+ return (CKR_FUNCTION_NOT_SUPPORTED);
+ }
+ return ((*sym)(hSession, pMechanism));
+}
+
+CK_RV
+pkcs_C_DigestUpdate(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pPart,
+ CK_ULONG ulPartLen) {
+ static CK_C_DigestUpdate sym = NULL;
+ static void *pPK11 = NULL;
+
+ if (hPK11 == NULL) {
+ return (CKR_LIBRARY_LOAD_FAILED);
+ }
+ if ((sym == NULL) || (hPK11 != pPK11)) {
+ pPK11 = hPK11;
+ sym = (CK_C_DigestUpdate)dlsym(hPK11, "C_DigestUpdate");
+ }
+ if (sym == NULL) {
+ return (CKR_FUNCTION_NOT_SUPPORTED);
+ }
+ return ((*sym)(hSession, pPart, ulPartLen));
+}
+
+CK_RV
+pkcs_C_DigestFinal(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pDigest,
+ CK_ULONG_PTR pulDigestLen) {
+ static CK_C_DigestFinal sym = NULL;
+ static void *pPK11 = NULL;
+
+ if (hPK11 == NULL) {
+ return (CKR_LIBRARY_LOAD_FAILED);
+ }
+ if ((sym == NULL) || (hPK11 != pPK11)) {
+ pPK11 = hPK11;
+ sym = (CK_C_DigestFinal)dlsym(hPK11, "C_DigestFinal");
+ }
+ if (sym == NULL) {
+ return (CKR_FUNCTION_NOT_SUPPORTED);
+ }
+ return ((*sym)(hSession, pDigest, pulDigestLen));
+}
+
+CK_RV
+pkcs_C_SignInit(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism,
+ CK_OBJECT_HANDLE hKey) {
+ static CK_C_SignInit sym = NULL;
+ static void *pPK11 = NULL;
+
+ if (hPK11 == NULL) {
+ return (CKR_LIBRARY_LOAD_FAILED);
+ }
+ if ((sym == NULL) || (hPK11 != pPK11)) {
+ pPK11 = hPK11;
+ sym = (CK_C_SignInit)dlsym(hPK11, "C_SignInit");
+ }
+ if (sym == NULL) {
+ return (CKR_FUNCTION_NOT_SUPPORTED);
+ }
+ return ((*sym)(hSession, pMechanism, hKey));
+}
+
+CK_RV
+pkcs_C_Sign(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pData, CK_ULONG ulDataLen,
+ CK_BYTE_PTR pSignature, CK_ULONG_PTR pulSignatureLen) {
+ static CK_C_Sign sym = NULL;
+ static void *pPK11 = NULL;
+
+ if (hPK11 == NULL) {
+ return (CKR_LIBRARY_LOAD_FAILED);
+ }
+ if ((sym == NULL) || (hPK11 != pPK11)) {
+ pPK11 = hPK11;
+ sym = (CK_C_Sign)dlsym(hPK11, "C_Sign");
+ }
+ if (sym == NULL) {
+ return (CKR_FUNCTION_NOT_SUPPORTED);
+ }
+ return ((*sym)(hSession, pData, ulDataLen, pSignature,
+ pulSignatureLen));
+}
+
+CK_RV
+pkcs_C_SignUpdate(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pPart,
+ CK_ULONG ulPartLen) {
+ static CK_C_SignUpdate sym = NULL;
+ static void *pPK11 = NULL;
+
+ if (hPK11 == NULL) {
+ return (CKR_LIBRARY_LOAD_FAILED);
+ }
+ if ((sym == NULL) || (hPK11 != pPK11)) {
+ pPK11 = hPK11;
+ sym = (CK_C_SignUpdate)dlsym(hPK11, "C_SignUpdate");
+ }
+ if (sym == NULL) {
+ return (CKR_FUNCTION_NOT_SUPPORTED);
+ }
+ return ((*sym)(hSession, pPart, ulPartLen));
+}
+
+CK_RV
+pkcs_C_SignFinal(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pSignature,
+ CK_ULONG_PTR pulSignatureLen) {
+ static CK_C_SignFinal sym = NULL;
+ static void *pPK11 = NULL;
+
+ if (hPK11 == NULL) {
+ return (CKR_LIBRARY_LOAD_FAILED);
+ }
+ if ((sym == NULL) || (hPK11 != pPK11)) {
+ pPK11 = hPK11;
+ sym = (CK_C_SignFinal)dlsym(hPK11, "C_SignFinal");
+ }
+ if (sym == NULL) {
+ return (CKR_FUNCTION_NOT_SUPPORTED);
+ }
+ return ((*sym)(hSession, pSignature, pulSignatureLen));
+}
+
+CK_RV
+pkcs_C_VerifyInit(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism,
+ CK_OBJECT_HANDLE hKey) {
+ static CK_C_VerifyInit sym = NULL;
+ static void *pPK11 = NULL;
+
+ if (hPK11 == NULL) {
+ return (CKR_LIBRARY_LOAD_FAILED);
+ }
+ if ((sym == NULL) || (hPK11 != pPK11)) {
+ pPK11 = hPK11;
+ sym = (CK_C_VerifyInit)dlsym(hPK11, "C_VerifyInit");
+ }
+ if (sym == NULL) {
+ return (CKR_FUNCTION_NOT_SUPPORTED);
+ }
+ return ((*sym)(hSession, pMechanism, hKey));
+}
+
+CK_RV
+pkcs_C_Verify(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pData, CK_ULONG ulDataLen,
+ CK_BYTE_PTR pSignature, CK_ULONG ulSignatureLen) {
+ static CK_C_Verify sym = NULL;
+ static void *pPK11 = NULL;
+
+ if (hPK11 == NULL) {
+ return (CKR_LIBRARY_LOAD_FAILED);
+ }
+ if ((sym == NULL) || (hPK11 != pPK11)) {
+ pPK11 = hPK11;
+ sym = (CK_C_Verify)dlsym(hPK11, "C_Verify");
+ }
+ if (sym == NULL) {
+ return (CKR_FUNCTION_NOT_SUPPORTED);
+ }
+ return ((*sym)(hSession, pData, ulDataLen, pSignature, ulSignatureLen));
+}
+
+CK_RV
+pkcs_C_VerifyUpdate(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pPart,
+ CK_ULONG ulPartLen) {
+ static CK_C_VerifyUpdate sym = NULL;
+ static void *pPK11 = NULL;
+
+ if (hPK11 == NULL) {
+ return (CKR_LIBRARY_LOAD_FAILED);
+ }
+ if ((sym == NULL) || (hPK11 != pPK11)) {
+ pPK11 = hPK11;
+ sym = (CK_C_VerifyUpdate)dlsym(hPK11, "C_VerifyUpdate");
+ }
+ if (sym == NULL) {
+ return (CKR_FUNCTION_NOT_SUPPORTED);
+ }
+ return ((*sym)(hSession, pPart, ulPartLen));
+}
+
+CK_RV
+pkcs_C_VerifyFinal(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pSignature,
+ CK_ULONG ulSignatureLen) {
+ static CK_C_VerifyFinal sym = NULL;
+ static void *pPK11 = NULL;
+
+ if (hPK11 == NULL) {
+ return (CKR_LIBRARY_LOAD_FAILED);
+ }
+ if ((sym == NULL) || (hPK11 != pPK11)) {
+ pPK11 = hPK11;
+ sym = (CK_C_VerifyFinal)dlsym(hPK11, "C_VerifyFinal");
+ }
+ if (sym == NULL) {
+ return (CKR_FUNCTION_NOT_SUPPORTED);
+ }
+ return ((*sym)(hSession, pSignature, ulSignatureLen));
+}
+
+CK_RV
+pkcs_C_GenerateKey(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism,
+ CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount,
+ CK_OBJECT_HANDLE_PTR phKey) {
+ static CK_C_GenerateKey sym = NULL;
+ static void *pPK11 = NULL;
+
+ if (hPK11 == NULL) {
+ return (CKR_LIBRARY_LOAD_FAILED);
+ }
+ if ((sym == NULL) || (hPK11 != pPK11)) {
+ pPK11 = hPK11;
+ sym = (CK_C_GenerateKey)dlsym(hPK11, "C_GenerateKey");
+ }
+ if (sym == NULL) {
+ return (CKR_FUNCTION_NOT_SUPPORTED);
+ }
+ return ((*sym)(hSession, pMechanism, pTemplate, ulCount, phKey));
+}
+
+CK_RV
+pkcs_C_GenerateKeyPair(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism,
+ CK_ATTRIBUTE_PTR pPublicKeyTemplate,
+ CK_ULONG usPublicKeyAttributeCount,
+ CK_ATTRIBUTE_PTR pPrivateKeyTemplate,
+ CK_ULONG usPrivateKeyAttributeCount,
+ CK_OBJECT_HANDLE_PTR phPrivateKey,
+ CK_OBJECT_HANDLE_PTR phPublicKey) {
+ static CK_C_GenerateKeyPair sym = NULL;
+ static void *pPK11 = NULL;
+
+ if (hPK11 == NULL) {
+ return (CKR_LIBRARY_LOAD_FAILED);
+ }
+ if ((sym == NULL) || (hPK11 != pPK11)) {
+ pPK11 = hPK11;
+ sym = (CK_C_GenerateKeyPair)dlsym(hPK11, "C_GenerateKeyPair");
+ }
+ if (sym == NULL) {
+ return (CKR_FUNCTION_NOT_SUPPORTED);
+ }
+ return ((*sym)(hSession, pMechanism, pPublicKeyTemplate,
+ usPublicKeyAttributeCount, pPrivateKeyTemplate,
+ usPrivateKeyAttributeCount, phPrivateKey, phPublicKey));
+}
+
+CK_RV
+pkcs_C_DeriveKey(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism,
+ CK_OBJECT_HANDLE hBaseKey, CK_ATTRIBUTE_PTR pTemplate,
+ CK_ULONG ulAttributeCount, CK_OBJECT_HANDLE_PTR phKey) {
+ static CK_C_DeriveKey sym = NULL;
+ static void *pPK11 = NULL;
+
+ if (hPK11 == NULL) {
+ return (CKR_LIBRARY_LOAD_FAILED);
+ }
+ if ((sym == NULL) || (hPK11 != pPK11)) {
+ pPK11 = hPK11;
+ sym = (CK_C_DeriveKey)dlsym(hPK11, "C_DeriveKey");
+ }
+ if (sym == NULL) {
+ return (CKR_FUNCTION_NOT_SUPPORTED);
+ }
+ return ((*sym)(hSession, pMechanism, hBaseKey, pTemplate,
+ ulAttributeCount, phKey));
+}
+
+CK_RV
+pkcs_C_SeedRandom(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pSeed,
+ CK_ULONG ulSeedLen) {
+ static CK_C_SeedRandom sym = NULL;
+ static void *pPK11 = NULL;
+
+ if (hPK11 == NULL) {
+ return (CKR_LIBRARY_LOAD_FAILED);
+ }
+ if ((sym == NULL) || (hPK11 != pPK11)) {
+ pPK11 = hPK11;
+ sym = (CK_C_SeedRandom)dlsym(hPK11, "C_SeedRandom");
+ }
+ if (sym == NULL) {
+ return (CKR_FUNCTION_NOT_SUPPORTED);
+ }
+ return ((*sym)(hSession, pSeed, ulSeedLen));
+}
+
+CK_RV
+pkcs_C_GenerateRandom(CK_SESSION_HANDLE hSession, CK_BYTE_PTR RandomData,
+ CK_ULONG ulRandomLen) {
+ static CK_C_GenerateRandom sym = NULL;
+ static void *pPK11 = NULL;
+
+ if (hPK11 == NULL) {
+ return (CKR_LIBRARY_LOAD_FAILED);
+ }
+ if ((sym == NULL) || (hPK11 != pPK11)) {
+ pPK11 = hPK11;
+ sym = (CK_C_GenerateRandom)dlsym(hPK11, "C_GenerateRandom");
+ }
+ if (sym == NULL) {
+ return (CKR_FUNCTION_NOT_SUPPORTED);
+ }
+ return ((*sym)(hSession, RandomData, ulRandomLen));
+}
diff --git a/lib/isc/unix/resource.c b/lib/isc/unix/resource.c
new file mode 100644
index 0000000..6020b39
--- /dev/null
+++ b/lib/isc/unix/resource.c
@@ -0,0 +1,219 @@
+/*
+ * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
+ *
+ * SPDX-License-Identifier: MPL-2.0
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, you can obtain one at https://mozilla.org/MPL/2.0/.
+ *
+ * See the COPYRIGHT file distributed with this work for additional
+ * information regarding copyright ownership.
+ */
+
+#include <inttypes.h>
+#include <stdbool.h>
+#include <sys/resource.h>
+#include <sys/time.h> /* Required on some systems for <sys/resource.h>. */
+#include <sys/types.h>
+
+#include <isc/platform.h>
+#include <isc/resource.h>
+#include <isc/result.h>
+#include <isc/util.h>
+
+#ifdef __linux__
+#include <linux/fs.h> /* To get the large NR_OPEN. */
+#endif /* ifdef __linux__ */
+
+#include "errno2result.h"
+
+static isc_result_t
+resource2rlim(isc_resource_t resource, int *rlim_resource) {
+ isc_result_t result = ISC_R_SUCCESS;
+
+ switch (resource) {
+ case isc_resource_coresize:
+ *rlim_resource = RLIMIT_CORE;
+ break;
+ case isc_resource_cputime:
+ *rlim_resource = RLIMIT_CPU;
+ break;
+ case isc_resource_datasize:
+ *rlim_resource = RLIMIT_DATA;
+ break;
+ case isc_resource_filesize:
+ *rlim_resource = RLIMIT_FSIZE;
+ break;
+ case isc_resource_lockedmemory:
+#ifdef RLIMIT_MEMLOCK
+ *rlim_resource = RLIMIT_MEMLOCK;
+#else /* ifdef RLIMIT_MEMLOCK */
+ result = ISC_R_NOTIMPLEMENTED;
+#endif /* ifdef RLIMIT_MEMLOCK */
+ break;
+ case isc_resource_openfiles:
+#ifdef RLIMIT_NOFILE
+ *rlim_resource = RLIMIT_NOFILE;
+#else /* ifdef RLIMIT_NOFILE */
+ result = ISC_R_NOTIMPLEMENTED;
+#endif /* ifdef RLIMIT_NOFILE */
+ break;
+ case isc_resource_processes:
+#ifdef RLIMIT_NPROC
+ *rlim_resource = RLIMIT_NPROC;
+#else /* ifdef RLIMIT_NPROC */
+ result = ISC_R_NOTIMPLEMENTED;
+#endif /* ifdef RLIMIT_NPROC */
+ break;
+ case isc_resource_residentsize:
+#ifdef RLIMIT_RSS
+ *rlim_resource = RLIMIT_RSS;
+#else /* ifdef RLIMIT_RSS */
+ result = ISC_R_NOTIMPLEMENTED;
+#endif /* ifdef RLIMIT_RSS */
+ break;
+ case isc_resource_stacksize:
+ *rlim_resource = RLIMIT_STACK;
+ break;
+ default:
+ /*
+ * This test is not very robust if isc_resource_t
+ * changes, but generates a clear assertion message.
+ */
+ REQUIRE(resource >= isc_resource_coresize &&
+ resource <= isc_resource_stacksize);
+
+ result = ISC_R_RANGE;
+ break;
+ }
+
+ return (result);
+}
+
+isc_result_t
+isc_resource_setlimit(isc_resource_t resource, isc_resourcevalue_t value) {
+ struct rlimit rl;
+ rlim_t rlim_value;
+ int unixresult;
+ int unixresource;
+ isc_result_t result;
+
+ result = resource2rlim(resource, &unixresource);
+ if (result != ISC_R_SUCCESS) {
+ return (result);
+ }
+
+ if (value == ISC_RESOURCE_UNLIMITED) {
+ rlim_value = RLIM_INFINITY;
+ } else {
+ /*
+ * isc_resourcevalue_t was chosen as an unsigned 64 bit
+ * integer so that it could contain the maximum range of
+ * reasonable values. Unfortunately, this exceeds the typical
+ * range on Unix systems. Ensure the range of
+ * rlim_t is not overflowed.
+ */
+ isc_resourcevalue_t rlim_max;
+ bool rlim_t_is_signed = (((double)(rlim_t)-1) < 0);
+
+ if (rlim_t_is_signed) {
+ rlim_max = ~((rlim_t)1 << (sizeof(rlim_t) * 8 - 1));
+ } else {
+ rlim_max = (rlim_t)-1;
+ }
+
+ if (value > rlim_max) {
+ value = rlim_max;
+ }
+
+ rlim_value = value;
+ }
+
+ rl.rlim_cur = rl.rlim_max = rlim_value;
+ unixresult = setrlimit(unixresource, &rl);
+
+ if (unixresult == 0) {
+ return (ISC_R_SUCCESS);
+ }
+
+#if defined(OPEN_MAX) && defined(__APPLE__)
+ /*
+ * The Darwin kernel doesn't accept RLIM_INFINITY for rlim_cur; the
+ * maximum possible value is OPEN_MAX. BIND8 used to use
+ * sysconf(_SC_OPEN_MAX) for such a case, but this value is much
+ * smaller than OPEN_MAX and is not really effective.
+ */
+ if (resource == isc_resource_openfiles && rlim_value == RLIM_INFINITY) {
+ rl.rlim_cur = OPEN_MAX;
+ unixresult = setrlimit(unixresource, &rl);
+ if (unixresult == 0) {
+ return (ISC_R_SUCCESS);
+ }
+ }
+#elif defined(__linux__)
+#ifndef NR_OPEN
+#define NR_OPEN (1024 * 1024)
+#endif /* ifndef NR_OPEN */
+
+ /*
+ * Some Linux kernels don't accept RLIM_INFINIT; the maximum
+ * possible value is the NR_OPEN defined in linux/fs.h.
+ */
+ if (resource == isc_resource_openfiles && rlim_value == RLIM_INFINITY) {
+ rl.rlim_cur = rl.rlim_max = NR_OPEN;
+ unixresult = setrlimit(unixresource, &rl);
+ if (unixresult == 0) {
+ return (ISC_R_SUCCESS);
+ }
+ }
+#endif /* if defined(OPEN_MAX) && defined(__APPLE__) */
+ if (resource == isc_resource_openfiles && rlim_value == RLIM_INFINITY) {
+ if (getrlimit(unixresource, &rl) == 0) {
+ rl.rlim_cur = rl.rlim_max;
+ unixresult = setrlimit(unixresource, &rl);
+ if (unixresult == 0) {
+ return (ISC_R_SUCCESS);
+ }
+ }
+ }
+ return (isc__errno2result(errno));
+}
+
+isc_result_t
+isc_resource_getlimit(isc_resource_t resource, isc_resourcevalue_t *value) {
+ int unixresource;
+ struct rlimit rl;
+ isc_result_t result;
+
+ result = resource2rlim(resource, &unixresource);
+ if (result != ISC_R_SUCCESS) {
+ return (result);
+ }
+
+ if (getrlimit(unixresource, &rl) != 0) {
+ return (isc__errno2result(errno));
+ }
+
+ *value = rl.rlim_max;
+ return (ISC_R_SUCCESS);
+}
+
+isc_result_t
+isc_resource_getcurlimit(isc_resource_t resource, isc_resourcevalue_t *value) {
+ int unixresource;
+ struct rlimit rl;
+ isc_result_t result;
+
+ result = resource2rlim(resource, &unixresource);
+ if (result != ISC_R_SUCCESS) {
+ return (result);
+ }
+
+ if (getrlimit(unixresource, &rl) != 0) {
+ return (isc__errno2result(errno));
+ }
+
+ *value = rl.rlim_cur;
+ return (ISC_R_SUCCESS);
+}
diff --git a/lib/isc/unix/socket.c b/lib/isc/unix/socket.c
new file mode 100644
index 0000000..d6578ea
--- /dev/null
+++ b/lib/isc/unix/socket.c
@@ -0,0 +1,5521 @@
+/*
+ * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
+ *
+ * SPDX-License-Identifier: MPL-2.0
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, you can obtain one at https://mozilla.org/MPL/2.0/.
+ *
+ * See the COPYRIGHT file distributed with this work for additional
+ * information regarding copyright ownership.
+ */
+
+/*! \file */
+
+#include <inttypes.h>
+#include <stdbool.h>
+#include <sys/param.h>
+#include <sys/socket.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#if defined(HAVE_SYS_SYSCTL_H) && !defined(__linux__)
+#include <sys/sysctl.h>
+#endif /* if defined(HAVE_SYS_SYSCTL_H) && !defined(__linux__) */
+#include <sys/time.h>
+#include <sys/uio.h>
+
+#if defined(HAVE_LINUX_NETLINK_H) && defined(HAVE_LINUX_RTNETLINK_H)
+#include <linux/netlink.h>
+#include <linux/rtnetlink.h>
+#endif /* if defined(HAVE_LINUX_NETLINK_H) && defined(HAVE_LINUX_RTNETLINK_H) \
+ */
+
+#include <errno.h>
+#include <fcntl.h>
+#include <stddef.h>
+#include <stdlib.h>
+#include <unistd.h>
+
+#include <isc/app.h>
+#include <isc/buffer.h>
+#include <isc/condition.h>
+#include <isc/formatcheck.h>
+#include <isc/list.h>
+#include <isc/log.h>
+#include <isc/mem.h>
+#include <isc/mutex.h>
+#include <isc/net.h>
+#include <isc/once.h>
+#include <isc/platform.h>
+#include <isc/print.h>
+#include <isc/refcount.h>
+#include <isc/region.h>
+#include <isc/resource.h>
+#include <isc/socket.h>
+#include <isc/stats.h>
+#include <isc/strerr.h>
+#include <isc/string.h>
+#include <isc/task.h>
+#include <isc/thread.h>
+#include <isc/util.h>
+
+#ifdef ISC_PLATFORM_HAVESYSUNH
+#include <sys/un.h>
+#endif /* ifdef ISC_PLATFORM_HAVESYSUNH */
+#ifdef HAVE_KQUEUE
+#include <sys/event.h>
+#endif /* ifdef HAVE_KQUEUE */
+#ifdef HAVE_EPOLL_CREATE1
+#include <sys/epoll.h>
+#endif /* ifdef HAVE_EPOLL_CREATE1 */
+#if defined(HAVE_SYS_DEVPOLL_H)
+#include <sys/devpoll.h>
+#elif defined(HAVE_DEVPOLL_H)
+#include <devpoll.h>
+#endif /* if defined(HAVE_SYS_DEVPOLL_H) */
+
+#include <netinet/tcp.h>
+
+#include "errno2result.h"
+
+#ifdef ENABLE_TCP_FASTOPEN
+#include <netinet/tcp.h>
+#endif /* ifdef ENABLE_TCP_FASTOPEN */
+
+#ifdef HAVE_JSON_C
+#include <json_object.h>
+#endif /* HAVE_JSON_C */
+
+#ifdef HAVE_LIBXML2
+#include <libxml/xmlwriter.h>
+#define ISC_XMLCHAR (const xmlChar *)
+#endif /* HAVE_LIBXML2 */
+
+/*%
+ * Choose the most preferable multiplex method.
+ */
+#if defined(HAVE_KQUEUE)
+#define USE_KQUEUE
+#elif defined(HAVE_EPOLL_CREATE1)
+#define USE_EPOLL
+#elif defined(HAVE_SYS_DEVPOLL_H) || defined(HAVE_DEVPOLL_H)
+#define USE_DEVPOLL
+typedef struct {
+ unsigned int want_read : 1, want_write : 1;
+} pollinfo_t;
+#else /* if defined(HAVE_KQUEUE) */
+#define USE_SELECT
+#endif /* HAVE_KQUEUE */
+
+/*
+ * Set by the -T dscp option on the command line. If set to a value
+ * other than -1, we check to make sure DSCP values match it, and
+ * assert if not.
+ */
+int isc_dscp_check_value = -1;
+
+/*%
+ * Maximum number of allowable open sockets. This is also the maximum
+ * allowable socket file descriptor.
+ *
+ * Care should be taken before modifying this value for select():
+ * The API standard doesn't ensure select() accept more than (the system default
+ * of) FD_SETSIZE descriptors, and the default size should in fact be fine in
+ * the vast majority of cases. This constant should therefore be increased only
+ * when absolutely necessary and possible, i.e., the server is exhausting all
+ * available file descriptors (up to FD_SETSIZE) and the select() function
+ * and FD_xxx macros support larger values than FD_SETSIZE (which may not
+ * always by true, but we keep using some of them to ensure as much
+ * portability as possible). Note also that overall server performance
+ * may be rather worsened with a larger value of this constant due to
+ * inherent scalability problems of select().
+ *
+ * As a special note, this value shouldn't have to be touched if
+ * this is a build for an authoritative only DNS server.
+ */
+#ifndef ISC_SOCKET_MAXSOCKETS
+#if defined(USE_KQUEUE) || defined(USE_EPOLL) || defined(USE_DEVPOLL)
+#ifdef TUNE_LARGE
+#define ISC_SOCKET_MAXSOCKETS 21000
+#else /* ifdef TUNE_LARGE */
+#define ISC_SOCKET_MAXSOCKETS 4096
+#endif /* TUNE_LARGE */
+#elif defined(USE_SELECT)
+#define ISC_SOCKET_MAXSOCKETS FD_SETSIZE
+#endif /* USE_KQUEUE... */
+#endif /* ISC_SOCKET_MAXSOCKETS */
+
+#ifdef USE_SELECT
+/*%
+ * Mac OS X needs a special definition to support larger values in select().
+ * We always define this because a larger value can be specified run-time.
+ */
+#ifdef __APPLE__
+#define _DARWIN_UNLIMITED_SELECT
+#endif /* __APPLE__ */
+#endif /* USE_SELECT */
+
+#ifdef ISC_SOCKET_USE_POLLWATCH
+/*%
+ * If this macro is defined, enable workaround for a Solaris /dev/poll kernel
+ * bug: DP_POLL ioctl could keep sleeping even if socket I/O is possible for
+ * some of the specified FD. The idea is based on the observation that it's
+ * likely for a busy server to keep receiving packets. It specifically works
+ * as follows: the socket watcher is first initialized with the state of
+ * "poll_idle". While it's in the idle state it keeps sleeping until a socket
+ * event occurs. When it wakes up for a socket I/O event, it moves to the
+ * poll_active state, and sets the poll timeout to a short period
+ * (ISC_SOCKET_POLLWATCH_TIMEOUT msec). If timeout occurs in this state, the
+ * watcher goes to the poll_checking state with the same timeout period.
+ * In this state, the watcher tries to detect whether this is a break
+ * during intermittent events or the kernel bug is triggered. If the next
+ * polling reports an event within the short period, the previous timeout is
+ * likely to be a kernel bug, and so the watcher goes back to the active state.
+ * Otherwise, it moves to the idle state again.
+ *
+ * It's not clear whether this is a thread-related bug, but since we've only
+ * seen this with threads, this workaround is used only when enabling threads.
+ */
+
+typedef enum { poll_idle, poll_active, poll_checking } pollstate_t;
+
+#ifndef ISC_SOCKET_POLLWATCH_TIMEOUT
+#define ISC_SOCKET_POLLWATCH_TIMEOUT 10
+#endif /* ISC_SOCKET_POLLWATCH_TIMEOUT */
+#endif /* ISC_SOCKET_USE_POLLWATCH */
+
+/*%
+ * Per-FD lock buckets, we shuffle them around a bit as FDs come in herds.
+ */
+#define FDLOCK_BITS 10
+#define FDLOCK_COUNT (1 << FDLOCK_BITS)
+#define FDLOCK_ID(fd) \
+ (((fd) % (FDLOCK_COUNT) >> (FDLOCK_BITS / 2)) | \
+ (((fd) << (FDLOCK_BITS / 2)) % (FDLOCK_COUNT)))
+
+/*%
+ * Maximum number of events communicated with the kernel. There should normally
+ * be no need for having a large number.
+ */
+#if defined(USE_KQUEUE) || defined(USE_EPOLL) || defined(USE_DEVPOLL)
+#ifndef ISC_SOCKET_MAXEVENTS
+#ifdef TUNE_LARGE
+#define ISC_SOCKET_MAXEVENTS 2048
+#else /* ifdef TUNE_LARGE */
+#define ISC_SOCKET_MAXEVENTS 64
+#endif /* TUNE_LARGE */
+#endif /* ifndef ISC_SOCKET_MAXEVENTS */
+#endif /* if defined(USE_KQUEUE) || defined(USE_EPOLL) || defined(USE_DEVPOLL) \
+ * */
+
+/*%
+ * Some systems define the socket length argument as an int, some as size_t,
+ * some as socklen_t. This is here so it can be easily changed if needed.
+ */
+#ifndef socklen_t
+#define socklen_t unsigned int
+#endif /* ifndef socklen_t */
+
+/*%
+ * Define what the possible "soft" errors can be. These are non-fatal returns
+ * of various network related functions, like recv() and so on.
+ *
+ * For some reason, BSDI (and perhaps others) will sometimes return <0
+ * from recv() but will have errno==0. This is broken, but we have to
+ * work around it here.
+ */
+#define SOFT_ERROR(e) \
+ ((e) == EAGAIN || (e) == EWOULDBLOCK || (e) == ENOBUFS || \
+ (e) == EINTR || (e) == 0)
+
+#define DLVL(x) ISC_LOGCATEGORY_GENERAL, ISC_LOGMODULE_SOCKET, ISC_LOG_DEBUG(x)
+
+/*!<
+ * DLVL(90) -- Function entry/exit and other tracing.
+ * DLVL(70) -- Socket "correctness" -- including returning of events, etc.
+ * DLVL(60) -- Socket data send/receive
+ * DLVL(50) -- Event tracing, including receiving/sending completion events.
+ * DLVL(20) -- Socket creation/destruction.
+ */
+#define TRACE_LEVEL 90
+#define CORRECTNESS_LEVEL 70
+#define IOEVENT_LEVEL 60
+#define EVENT_LEVEL 50
+#define CREATION_LEVEL 20
+
+#define TRACE DLVL(TRACE_LEVEL)
+#define CORRECTNESS DLVL(CORRECTNESS_LEVEL)
+#define IOEVENT DLVL(IOEVENT_LEVEL)
+#define EVENT DLVL(EVENT_LEVEL)
+#define CREATION DLVL(CREATION_LEVEL)
+
+typedef isc_event_t intev_t;
+
+#define SOCKET_MAGIC ISC_MAGIC('I', 'O', 'i', 'o')
+#define VALID_SOCKET(s) ISC_MAGIC_VALID(s, SOCKET_MAGIC)
+
+/*!
+ * IPv6 control information. If the socket is an IPv6 socket we want
+ * to collect the destination address and interface so the client can
+ * set them on outgoing packets.
+ */
+#ifndef USE_CMSG
+#define USE_CMSG 1
+#endif /* ifndef USE_CMSG */
+
+/*%
+ * NetBSD and FreeBSD can timestamp packets. XXXMLG Should we have
+ * a setsockopt() like interface to request timestamps, and if the OS
+ * doesn't do it for us, call gettimeofday() on every UDP receive?
+ */
+#ifdef SO_TIMESTAMP
+#ifndef USE_CMSG
+#define USE_CMSG 1
+#endif /* ifndef USE_CMSG */
+#endif /* ifdef SO_TIMESTAMP */
+
+#if defined(SO_RCVBUF) && defined(ISC_RECV_BUFFER_SIZE)
+#define SET_RCVBUF
+#endif
+
+#if defined(SO_SNDBUF) && defined(ISC_SEND_BUFFER_SIZE)
+#define SET_SNDBUF
+#endif
+
+/*%
+ * Instead of calculating the cmsgbuf lengths every time we take
+ * a rule of thumb approach - sizes are taken from x86_64 linux,
+ * multiplied by 2, everything should fit. Those sizes are not
+ * large enough to cause any concern.
+ */
+#if defined(USE_CMSG)
+#define CMSG_SP_IN6PKT 40
+#else /* if defined(USE_CMSG) */
+#define CMSG_SP_IN6PKT 0
+#endif /* if defined(USE_CMSG) */
+
+#if defined(USE_CMSG) && defined(SO_TIMESTAMP)
+#define CMSG_SP_TIMESTAMP 32
+#else /* if defined(USE_CMSG) && defined(SO_TIMESTAMP) */
+#define CMSG_SP_TIMESTAMP 0
+#endif /* if defined(USE_CMSG) && defined(SO_TIMESTAMP) */
+
+#if defined(USE_CMSG) && (defined(IPV6_TCLASS) || defined(IP_TOS))
+#define CMSG_SP_TCTOS 24
+#else /* if defined(USE_CMSG) && (defined(IPV6_TCLASS) || defined(IP_TOS)) */
+#define CMSG_SP_TCTOS 0
+#endif /* if defined(USE_CMSG) && (defined(IPV6_TCLASS) || defined(IP_TOS)) */
+
+#define CMSG_SP_INT 24
+
+/* Align cmsg buffers to be safe on SPARC etc. */
+#define RECVCMSGBUFLEN \
+ ISC_ALIGN(2 * (CMSG_SP_IN6PKT + CMSG_SP_TIMESTAMP + CMSG_SP_TCTOS) + \
+ 1, \
+ sizeof(void *))
+#define SENDCMSGBUFLEN \
+ ISC_ALIGN(2 * (CMSG_SP_IN6PKT + CMSG_SP_INT + CMSG_SP_TCTOS) + 1, \
+ sizeof(void *))
+
+/*%
+ * The number of times a send operation is repeated if the result is EINTR.
+ */
+#define NRETRIES 10
+
+typedef struct isc__socketthread isc__socketthread_t;
+
+#define NEWCONNSOCK(ev) ((ev)->newsocket)
+
+struct isc_socket {
+ /* Not locked. */
+ unsigned int magic;
+ isc_socketmgr_t *manager;
+ isc_mutex_t lock;
+ isc_sockettype_t type;
+ const isc_statscounter_t *statsindex;
+ isc_refcount_t references;
+
+ /* Locked by socket lock. */
+ ISC_LINK(isc_socket_t) link;
+ int fd;
+ int pf;
+ int threadid;
+ char name[16];
+ void *tag;
+
+ ISC_LIST(isc_socketevent_t) send_list;
+ ISC_LIST(isc_socketevent_t) recv_list;
+ ISC_LIST(isc_socket_newconnev_t) accept_list;
+ ISC_LIST(isc_socket_connev_t) connect_list;
+
+ isc_sockaddr_t peer_address; /* remote address */
+
+ unsigned int listener : 1, /* listener socket */
+ connected : 1, connecting : 1, /* connect pending
+ * */
+ bound : 1, /* bound to local addr */
+ dupped : 1, active : 1, /* currently active */
+ pktdscp : 1; /* per packet dscp */
+
+#ifdef ISC_PLATFORM_RECVOVERFLOW
+ unsigned char overflow; /* used for MSG_TRUNC fake */
+#endif /* ifdef ISC_PLATFORM_RECVOVERFLOW */
+
+ unsigned int dscp;
+};
+
+#define SOCKET_MANAGER_MAGIC ISC_MAGIC('I', 'O', 'm', 'g')
+#define VALID_MANAGER(m) ISC_MAGIC_VALID(m, SOCKET_MANAGER_MAGIC)
+
+struct isc_socketmgr {
+ /* Not locked. */
+ unsigned int magic;
+ isc_mem_t *mctx;
+ isc_mutex_t lock;
+ isc_stats_t *stats;
+ int nthreads;
+ isc__socketthread_t *threads;
+ unsigned int maxsocks;
+ /* Locked by manager lock. */
+ ISC_LIST(isc_socket_t) socklist;
+ int reserved; /* unlocked */
+ isc_condition_t shutdown_ok;
+ size_t maxudp;
+};
+
+struct isc__socketthread {
+ isc_socketmgr_t *manager;
+ int threadid;
+ isc_thread_t thread;
+ int pipe_fds[2];
+ isc_mutex_t *fdlock;
+ /* Locked by fdlock. */
+ isc_socket_t **fds;
+ int *fdstate;
+#ifdef USE_KQUEUE
+ int kqueue_fd;
+ int nevents;
+ struct kevent *events;
+#endif /* USE_KQUEUE */
+#ifdef USE_EPOLL
+ int epoll_fd;
+ int nevents;
+ struct epoll_event *events;
+ uint32_t *epoll_events;
+#endif /* USE_EPOLL */
+#ifdef USE_DEVPOLL
+ int devpoll_fd;
+ isc_resourcevalue_t open_max;
+ unsigned int calls;
+ int nevents;
+ struct pollfd *events;
+ pollinfo_t *fdpollinfo;
+#endif /* USE_DEVPOLL */
+#ifdef USE_SELECT
+ int fd_bufsize;
+ fd_set *read_fds;
+ fd_set *read_fds_copy;
+ fd_set *write_fds;
+ fd_set *write_fds_copy;
+ int maxfd;
+#endif /* USE_SELECT */
+};
+
+#define CLOSED 0 /* this one must be zero */
+#define MANAGED 1
+#define CLOSE_PENDING 2
+
+/*
+ * send() and recv() iovec counts
+ */
+#define MAXSCATTERGATHER_SEND (ISC_SOCKET_MAXSCATTERGATHER)
+#ifdef ISC_PLATFORM_RECVOVERFLOW
+#define MAXSCATTERGATHER_RECV (ISC_SOCKET_MAXSCATTERGATHER + 1)
+#else /* ifdef ISC_PLATFORM_RECVOVERFLOW */
+#define MAXSCATTERGATHER_RECV (ISC_SOCKET_MAXSCATTERGATHER)
+#endif /* ifdef ISC_PLATFORM_RECVOVERFLOW */
+
+static isc_result_t
+socket_create(isc_socketmgr_t *manager0, int pf, isc_sockettype_t type,
+ isc_socket_t **socketp, isc_socket_t *dup_socket);
+static void
+send_recvdone_event(isc_socket_t *, isc_socketevent_t **);
+static void
+send_senddone_event(isc_socket_t *, isc_socketevent_t **);
+static void
+send_connectdone_event(isc_socket_t *, isc_socket_connev_t **);
+static void
+free_socket(isc_socket_t **);
+static isc_result_t
+allocate_socket(isc_socketmgr_t *, isc_sockettype_t, isc_socket_t **);
+static void
+destroy(isc_socket_t **);
+static void
+internal_accept(isc_socket_t *);
+static void
+internal_connect(isc_socket_t *);
+static void
+internal_recv(isc_socket_t *);
+static void
+internal_send(isc_socket_t *);
+static void
+process_cmsg(isc_socket_t *, struct msghdr *, isc_socketevent_t *);
+static void
+build_msghdr_send(isc_socket_t *, char *, isc_socketevent_t *, struct msghdr *,
+ struct iovec *, size_t *);
+static void
+build_msghdr_recv(isc_socket_t *, char *, isc_socketevent_t *, struct msghdr *,
+ struct iovec *, size_t *);
+static bool
+process_ctlfd(isc__socketthread_t *thread);
+static void
+setdscp(isc_socket_t *sock, isc_dscp_t dscp);
+
+#define SELECT_POKE_SHUTDOWN (-1)
+#define SELECT_POKE_NOTHING (-2)
+#define SELECT_POKE_READ (-3)
+#define SELECT_POKE_ACCEPT (-3) /*%< Same as _READ */
+#define SELECT_POKE_WRITE (-4)
+#define SELECT_POKE_CONNECT (-4) /*%< Same as _WRITE */
+#define SELECT_POKE_CLOSE (-5)
+
+/*%
+ * Shortcut index arrays to get access to statistics counters.
+ */
+enum {
+ STATID_OPEN = 0,
+ STATID_OPENFAIL = 1,
+ STATID_CLOSE = 2,
+ STATID_BINDFAIL = 3,
+ STATID_CONNECTFAIL = 4,
+ STATID_CONNECT = 5,
+ STATID_ACCEPTFAIL = 6,
+ STATID_ACCEPT = 7,
+ STATID_SENDFAIL = 8,
+ STATID_RECVFAIL = 9,
+ STATID_ACTIVE = 10
+};
+static const isc_statscounter_t udp4statsindex[] = {
+ isc_sockstatscounter_udp4open,
+ isc_sockstatscounter_udp4openfail,
+ isc_sockstatscounter_udp4close,
+ isc_sockstatscounter_udp4bindfail,
+ isc_sockstatscounter_udp4connectfail,
+ isc_sockstatscounter_udp4connect,
+ -1,
+ -1,
+ isc_sockstatscounter_udp4sendfail,
+ isc_sockstatscounter_udp4recvfail,
+ isc_sockstatscounter_udp4active
+};
+static const isc_statscounter_t udp6statsindex[] = {
+ isc_sockstatscounter_udp6open,
+ isc_sockstatscounter_udp6openfail,
+ isc_sockstatscounter_udp6close,
+ isc_sockstatscounter_udp6bindfail,
+ isc_sockstatscounter_udp6connectfail,
+ isc_sockstatscounter_udp6connect,
+ -1,
+ -1,
+ isc_sockstatscounter_udp6sendfail,
+ isc_sockstatscounter_udp6recvfail,
+ isc_sockstatscounter_udp6active
+};
+static const isc_statscounter_t tcp4statsindex[] = {
+ isc_sockstatscounter_tcp4open, isc_sockstatscounter_tcp4openfail,
+ isc_sockstatscounter_tcp4close, isc_sockstatscounter_tcp4bindfail,
+ isc_sockstatscounter_tcp4connectfail, isc_sockstatscounter_tcp4connect,
+ isc_sockstatscounter_tcp4acceptfail, isc_sockstatscounter_tcp4accept,
+ isc_sockstatscounter_tcp4sendfail, isc_sockstatscounter_tcp4recvfail,
+ isc_sockstatscounter_tcp4active
+};
+static const isc_statscounter_t tcp6statsindex[] = {
+ isc_sockstatscounter_tcp6open, isc_sockstatscounter_tcp6openfail,
+ isc_sockstatscounter_tcp6close, isc_sockstatscounter_tcp6bindfail,
+ isc_sockstatscounter_tcp6connectfail, isc_sockstatscounter_tcp6connect,
+ isc_sockstatscounter_tcp6acceptfail, isc_sockstatscounter_tcp6accept,
+ isc_sockstatscounter_tcp6sendfail, isc_sockstatscounter_tcp6recvfail,
+ isc_sockstatscounter_tcp6active
+};
+static const isc_statscounter_t unixstatsindex[] = {
+ isc_sockstatscounter_unixopen, isc_sockstatscounter_unixopenfail,
+ isc_sockstatscounter_unixclose, isc_sockstatscounter_unixbindfail,
+ isc_sockstatscounter_unixconnectfail, isc_sockstatscounter_unixconnect,
+ isc_sockstatscounter_unixacceptfail, isc_sockstatscounter_unixaccept,
+ isc_sockstatscounter_unixsendfail, isc_sockstatscounter_unixrecvfail,
+ isc_sockstatscounter_unixactive
+};
+static const isc_statscounter_t rawstatsindex[] = {
+ isc_sockstatscounter_rawopen,
+ isc_sockstatscounter_rawopenfail,
+ isc_sockstatscounter_rawclose,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ isc_sockstatscounter_rawrecvfail,
+ isc_sockstatscounter_rawactive
+};
+
+static int
+gen_threadid(isc_socket_t *sock);
+
+static int
+gen_threadid(isc_socket_t *sock) {
+ return (sock->fd % sock->manager->nthreads);
+}
+
+static void
+manager_log(isc_socketmgr_t *sockmgr, isc_logcategory_t *category,
+ isc_logmodule_t *module, int level, const char *fmt, ...)
+ ISC_FORMAT_PRINTF(5, 6);
+static void
+manager_log(isc_socketmgr_t *sockmgr, isc_logcategory_t *category,
+ isc_logmodule_t *module, int level, const char *fmt, ...) {
+ char msgbuf[2048];
+ va_list ap;
+
+ if (!isc_log_wouldlog(isc_lctx, level)) {
+ return;
+ }
+
+ va_start(ap, fmt);
+ vsnprintf(msgbuf, sizeof(msgbuf), fmt, ap);
+ va_end(ap);
+
+ isc_log_write(isc_lctx, category, module, level, "sockmgr %p: %s",
+ sockmgr, msgbuf);
+}
+
+static void
+thread_log(isc__socketthread_t *thread, isc_logcategory_t *category,
+ isc_logmodule_t *module, int level, const char *fmt, ...)
+ ISC_FORMAT_PRINTF(5, 6);
+static void
+thread_log(isc__socketthread_t *thread, isc_logcategory_t *category,
+ isc_logmodule_t *module, int level, const char *fmt, ...) {
+ char msgbuf[2048];
+ va_list ap;
+
+ if (!isc_log_wouldlog(isc_lctx, level)) {
+ return;
+ }
+
+ va_start(ap, fmt);
+ vsnprintf(msgbuf, sizeof(msgbuf), fmt, ap);
+ va_end(ap);
+
+ isc_log_write(isc_lctx, category, module, level,
+ "sockmgr %p thread %d: %s", thread->manager,
+ thread->threadid, msgbuf);
+}
+
+static void
+socket_log(isc_socket_t *sock, const isc_sockaddr_t *address,
+ isc_logcategory_t *category, isc_logmodule_t *module, int level,
+ const char *fmt, ...) ISC_FORMAT_PRINTF(6, 7);
+static void
+socket_log(isc_socket_t *sock, const isc_sockaddr_t *address,
+ isc_logcategory_t *category, isc_logmodule_t *module, int level,
+ const char *fmt, ...) {
+ char msgbuf[2048];
+ char peerbuf[ISC_SOCKADDR_FORMATSIZE];
+ va_list ap;
+
+ if (!isc_log_wouldlog(isc_lctx, level)) {
+ return;
+ }
+
+ va_start(ap, fmt);
+ vsnprintf(msgbuf, sizeof(msgbuf), fmt, ap);
+ va_end(ap);
+
+ if (address == NULL) {
+ isc_log_write(isc_lctx, category, module, level,
+ "socket %p: %s", sock, msgbuf);
+ } else {
+ isc_sockaddr_format(address, peerbuf, sizeof(peerbuf));
+ isc_log_write(isc_lctx, category, module, level,
+ "socket %p %s: %s", sock, peerbuf, msgbuf);
+ }
+}
+
+/*%
+ * Increment socket-related statistics counters.
+ */
+static void
+inc_stats(isc_stats_t *stats, isc_statscounter_t counterid) {
+ REQUIRE(counterid != -1);
+
+ if (stats != NULL) {
+ isc_stats_increment(stats, counterid);
+ }
+}
+
+/*%
+ * Decrement socket-related statistics counters.
+ */
+static void
+dec_stats(isc_stats_t *stats, isc_statscounter_t counterid) {
+ REQUIRE(counterid != -1);
+
+ if (stats != NULL) {
+ isc_stats_decrement(stats, counterid);
+ }
+}
+
+static isc_result_t
+watch_fd(isc__socketthread_t *thread, int fd, int msg) {
+ isc_result_t result = ISC_R_SUCCESS;
+
+#ifdef USE_KQUEUE
+ struct kevent evchange;
+
+ memset(&evchange, 0, sizeof(evchange));
+ if (msg == SELECT_POKE_READ) {
+ evchange.filter = EVFILT_READ;
+ } else {
+ evchange.filter = EVFILT_WRITE;
+ }
+ evchange.flags = EV_ADD;
+ evchange.ident = fd;
+ if (kevent(thread->kqueue_fd, &evchange, 1, NULL, 0, NULL) != 0) {
+ result = isc__errno2result(errno);
+ }
+
+ return (result);
+#elif defined(USE_EPOLL)
+ struct epoll_event event;
+ uint32_t oldevents;
+ int ret;
+ int op;
+
+ oldevents = thread->epoll_events[fd];
+ if (msg == SELECT_POKE_READ) {
+ thread->epoll_events[fd] |= EPOLLIN;
+ } else {
+ thread->epoll_events[fd] |= EPOLLOUT;
+ }
+
+ event.events = thread->epoll_events[fd];
+ memset(&event.data, 0, sizeof(event.data));
+ event.data.fd = fd;
+
+ op = (oldevents == 0U) ? EPOLL_CTL_ADD : EPOLL_CTL_MOD;
+ if (thread->fds[fd] != NULL) {
+ LOCK(&thread->fds[fd]->lock);
+ }
+ ret = epoll_ctl(thread->epoll_fd, op, fd, &event);
+ if (thread->fds[fd] != NULL) {
+ UNLOCK(&thread->fds[fd]->lock);
+ }
+ if (ret == -1) {
+ if (errno == EEXIST) {
+ UNEXPECTED_ERROR(__FILE__, __LINE__,
+ "epoll_ctl(ADD/MOD) returned "
+ "EEXIST for fd %d",
+ fd);
+ }
+ result = isc__errno2result(errno);
+ }
+
+ return (result);
+#elif defined(USE_DEVPOLL)
+ struct pollfd pfd;
+
+ memset(&pfd, 0, sizeof(pfd));
+ if (msg == SELECT_POKE_READ) {
+ pfd.events = POLLIN;
+ } else {
+ pfd.events = POLLOUT;
+ }
+ pfd.fd = fd;
+ pfd.revents = 0;
+ if (write(thread->devpoll_fd, &pfd, sizeof(pfd)) == -1) {
+ result = isc__errno2result(errno);
+ } else {
+ if (msg == SELECT_POKE_READ) {
+ thread->fdpollinfo[fd].want_read = 1;
+ } else {
+ thread->fdpollinfo[fd].want_write = 1;
+ }
+ }
+
+ return (result);
+#elif defined(USE_SELECT)
+ LOCK(&thread->manager->lock);
+ if (msg == SELECT_POKE_READ) {
+ FD_SET(fd, thread->read_fds);
+ }
+ if (msg == SELECT_POKE_WRITE) {
+ FD_SET(fd, thread->write_fds);
+ }
+ UNLOCK(&thread->manager->lock);
+
+ return (result);
+#endif /* ifdef USE_KQUEUE */
+}
+
+static isc_result_t
+unwatch_fd(isc__socketthread_t *thread, int fd, int msg) {
+ isc_result_t result = ISC_R_SUCCESS;
+
+#ifdef USE_KQUEUE
+ struct kevent evchange;
+
+ memset(&evchange, 0, sizeof(evchange));
+ if (msg == SELECT_POKE_READ) {
+ evchange.filter = EVFILT_READ;
+ } else {
+ evchange.filter = EVFILT_WRITE;
+ }
+ evchange.flags = EV_DELETE;
+ evchange.ident = fd;
+ if (kevent(thread->kqueue_fd, &evchange, 1, NULL, 0, NULL) != 0) {
+ result = isc__errno2result(errno);
+ }
+
+ return (result);
+#elif defined(USE_EPOLL)
+ struct epoll_event event;
+ int ret;
+ int op;
+
+ if (msg == SELECT_POKE_READ) {
+ thread->epoll_events[fd] &= ~(EPOLLIN);
+ } else {
+ thread->epoll_events[fd] &= ~(EPOLLOUT);
+ }
+
+ event.events = thread->epoll_events[fd];
+ memset(&event.data, 0, sizeof(event.data));
+ event.data.fd = fd;
+
+ op = (event.events == 0U) ? EPOLL_CTL_DEL : EPOLL_CTL_MOD;
+ ret = epoll_ctl(thread->epoll_fd, op, fd, &event);
+ if (ret == -1 && errno != ENOENT) {
+ char strbuf[ISC_STRERRORSIZE];
+ strerror_r(errno, strbuf, sizeof(strbuf));
+ UNEXPECTED_ERROR(__FILE__, __LINE__, "epoll_ctl(DEL), %d: %s",
+ fd, strbuf);
+ result = ISC_R_UNEXPECTED;
+ }
+ return (result);
+#elif defined(USE_DEVPOLL)
+ struct pollfd pfds[2];
+ size_t writelen = sizeof(pfds[0]);
+
+ memset(pfds, 0, sizeof(pfds));
+ pfds[0].events = POLLREMOVE;
+ pfds[0].fd = fd;
+
+ /*
+ * Canceling read or write polling via /dev/poll is tricky. Since it
+ * only provides a way of canceling per FD, we may need to re-poll the
+ * socket for the other operation.
+ */
+ if (msg == SELECT_POKE_READ && thread->fdpollinfo[fd].want_write == 1) {
+ pfds[1].events = POLLOUT;
+ pfds[1].fd = fd;
+ writelen += sizeof(pfds[1]);
+ }
+ if (msg == SELECT_POKE_WRITE && thread->fdpollinfo[fd].want_read == 1) {
+ pfds[1].events = POLLIN;
+ pfds[1].fd = fd;
+ writelen += sizeof(pfds[1]);
+ }
+
+ if (write(thread->devpoll_fd, pfds, writelen) == -1) {
+ result = isc__errno2result(errno);
+ } else {
+ if (msg == SELECT_POKE_READ) {
+ thread->fdpollinfo[fd].want_read = 0;
+ } else {
+ thread->fdpollinfo[fd].want_write = 0;
+ }
+ }
+
+ return (result);
+#elif defined(USE_SELECT)
+ LOCK(&thread->manager->lock);
+ if (msg == SELECT_POKE_READ) {
+ FD_CLR(fd, thread->read_fds);
+ } else if (msg == SELECT_POKE_WRITE) {
+ FD_CLR(fd, thread->write_fds);
+ }
+ UNLOCK(&thread->manager->lock);
+
+ return (result);
+#endif /* ifdef USE_KQUEUE */
+}
+
+/*
+ * A poke message was received, perform a proper watch/unwatch
+ * on a fd provided
+ */
+static void
+wakeup_socket(isc__socketthread_t *thread, int fd, int msg) {
+ isc_result_t result;
+ int lockid = FDLOCK_ID(fd);
+
+ /*
+ * This is a wakeup on a socket. If the socket is not in the
+ * process of being closed, start watching it for either reads
+ * or writes.
+ */
+
+ INSIST(fd >= 0 && fd < (int)thread->manager->maxsocks);
+
+ if (msg == SELECT_POKE_CLOSE) {
+ LOCK(&thread->fdlock[lockid]);
+ INSIST(thread->fdstate[fd] == CLOSE_PENDING);
+ thread->fdstate[fd] = CLOSED;
+ (void)unwatch_fd(thread, fd, SELECT_POKE_READ);
+ (void)unwatch_fd(thread, fd, SELECT_POKE_WRITE);
+ (void)close(fd);
+ UNLOCK(&thread->fdlock[lockid]);
+ return;
+ }
+
+ LOCK(&thread->fdlock[lockid]);
+ if (thread->fdstate[fd] == CLOSE_PENDING) {
+ /*
+ * We accept (and ignore) any error from unwatch_fd() as we are
+ * closing the socket, hoping it doesn't leave dangling state in
+ * the kernel.
+ * Note that unwatch_fd() must be called after releasing the
+ * fdlock; otherwise it could cause deadlock due to a lock order
+ * reversal.
+ */
+ (void)unwatch_fd(thread, fd, SELECT_POKE_READ);
+ (void)unwatch_fd(thread, fd, SELECT_POKE_WRITE);
+ UNLOCK(&thread->fdlock[lockid]);
+ return;
+ }
+ if (thread->fdstate[fd] != MANAGED) {
+ UNLOCK(&thread->fdlock[lockid]);
+ return;
+ }
+
+ /*
+ * Set requested bit.
+ */
+ result = watch_fd(thread, fd, msg);
+ if (result != ISC_R_SUCCESS) {
+ /*
+ * XXXJT: what should we do? Ignoring the failure of watching
+ * a socket will make the application dysfunctional, but there
+ * seems to be no reasonable recovery process.
+ */
+ isc_log_write(isc_lctx, ISC_LOGCATEGORY_GENERAL,
+ ISC_LOGMODULE_SOCKET, ISC_LOG_ERROR,
+ "failed to start watching FD (%d): %s", fd,
+ isc_result_totext(result));
+ }
+ UNLOCK(&thread->fdlock[lockid]);
+}
+
+/*
+ * Poke the select loop when there is something for us to do.
+ * The write is required (by POSIX) to complete. That is, we
+ * will not get partial writes.
+ */
+static void
+select_poke(isc_socketmgr_t *mgr, int threadid, int fd, int msg) {
+ int cc;
+ int buf[2];
+ char strbuf[ISC_STRERRORSIZE];
+
+ buf[0] = fd;
+ buf[1] = msg;
+
+ do {
+ cc = write(mgr->threads[threadid].pipe_fds[1], buf,
+ sizeof(buf));
+#ifdef ENOSR
+ /*
+ * Treat ENOSR as EAGAIN but loop slowly as it is
+ * unlikely to clear fast.
+ */
+ if (cc < 0 && errno == ENOSR) {
+ sleep(1);
+ errno = EAGAIN;
+ }
+#endif /* ifdef ENOSR */
+ } while (cc < 0 && SOFT_ERROR(errno));
+
+ if (cc < 0) {
+ strerror_r(errno, strbuf, sizeof(strbuf));
+ FATAL_ERROR(__FILE__, __LINE__,
+ "write() failed during watcher poke: %s", strbuf);
+ }
+
+ INSIST(cc == sizeof(buf));
+}
+
+/*
+ * Read a message on the internal fd.
+ */
+static void
+select_readmsg(isc__socketthread_t *thread, int *fd, int *msg) {
+ int buf[2];
+ int cc;
+ char strbuf[ISC_STRERRORSIZE];
+
+ cc = read(thread->pipe_fds[0], buf, sizeof(buf));
+ if (cc < 0) {
+ *msg = SELECT_POKE_NOTHING;
+ *fd = -1; /* Silence compiler. */
+ if (SOFT_ERROR(errno)) {
+ return;
+ }
+
+ strerror_r(errno, strbuf, sizeof(strbuf));
+ FATAL_ERROR(__FILE__, __LINE__,
+ "read() failed during watcher poke: %s", strbuf);
+ }
+ INSIST(cc == sizeof(buf));
+
+ *fd = buf[0];
+ *msg = buf[1];
+}
+
+/*
+ * Make a fd non-blocking.
+ */
+static isc_result_t
+make_nonblock(int fd) {
+ int ret;
+ char strbuf[ISC_STRERRORSIZE];
+#ifdef USE_FIONBIO_IOCTL
+ int on = 1;
+#else /* ifdef USE_FIONBIO_IOCTL */
+ int flags;
+#endif /* ifdef USE_FIONBIO_IOCTL */
+
+#ifdef USE_FIONBIO_IOCTL
+ ret = ioctl(fd, FIONBIO, (char *)&on);
+#else /* ifdef USE_FIONBIO_IOCTL */
+ flags = fcntl(fd, F_GETFL, 0);
+ flags |= PORT_NONBLOCK;
+ ret = fcntl(fd, F_SETFL, flags);
+#endif /* ifdef USE_FIONBIO_IOCTL */
+
+ if (ret == -1) {
+ strerror_r(errno, strbuf, sizeof(strbuf));
+ UNEXPECTED_ERROR(__FILE__, __LINE__,
+#ifdef USE_FIONBIO_IOCTL
+ "ioctl(%d, FIONBIO, &on): %s", fd,
+#else /* ifdef USE_FIONBIO_IOCTL */
+ "fcntl(%d, F_SETFL, %d): %s", fd, flags,
+#endif /* ifdef USE_FIONBIO_IOCTL */
+ strbuf);
+
+ return (ISC_R_UNEXPECTED);
+ }
+
+ return (ISC_R_SUCCESS);
+}
+
+#ifdef USE_CMSG
+/*
+ * Not all OSes support advanced CMSG macros: CMSG_LEN and CMSG_SPACE.
+ * In order to ensure as much portability as possible, we provide wrapper
+ * functions of these macros.
+ * Note that cmsg_space() could run slow on OSes that do not have
+ * CMSG_SPACE.
+ */
+static socklen_t
+cmsg_len(socklen_t len) {
+#ifdef CMSG_LEN
+ return (CMSG_LEN(len));
+#else /* ifdef CMSG_LEN */
+ socklen_t hdrlen;
+
+ /*
+ * Cast NULL so that any pointer arithmetic performed by CMSG_DATA
+ * is correct.
+ */
+ hdrlen = (socklen_t)CMSG_DATA(((struct cmsghdr *)NULL));
+ return (hdrlen + len);
+#endif /* ifdef CMSG_LEN */
+}
+
+static socklen_t
+cmsg_space(socklen_t len) {
+#ifdef CMSG_SPACE
+ return (CMSG_SPACE(len));
+#else /* ifdef CMSG_SPACE */
+ struct msghdr msg;
+ struct cmsghdr *cmsgp;
+ /*
+ * XXX: The buffer length is an ad-hoc value, but should be enough
+ * in a practical sense.
+ */
+ char dummybuf[sizeof(struct cmsghdr) + 1024];
+
+ memset(&msg, 0, sizeof(msg));
+ msg.msg_control = dummybuf;
+ msg.msg_controllen = sizeof(dummybuf);
+
+ cmsgp = (struct cmsghdr *)dummybuf;
+ cmsgp->cmsg_len = cmsg_len(len);
+
+ cmsgp = CMSG_NXTHDR(&msg, cmsgp);
+ if (cmsgp != NULL) {
+ return ((char *)cmsgp - (char *)msg.msg_control);
+ } else {
+ return (0);
+ }
+#endif /* ifdef CMSG_SPACE */
+}
+#endif /* USE_CMSG */
+
+/*
+ * Process control messages received on a socket.
+ */
+static void
+process_cmsg(isc_socket_t *sock, struct msghdr *msg, isc_socketevent_t *dev) {
+#ifdef USE_CMSG
+ struct cmsghdr *cmsgp;
+ struct in6_pktinfo *pktinfop;
+#ifdef SO_TIMESTAMP
+ void *timevalp;
+#endif /* ifdef SO_TIMESTAMP */
+#endif /* ifdef USE_CMSG */
+
+ /*
+ * sock is used only when ISC_NET_BSD44MSGHDR and USE_CMSG are defined.
+ * msg and dev are used only when ISC_NET_BSD44MSGHDR is defined.
+ * They are all here, outside of the CPP tests, because it is
+ * more consistent with the usual ISC coding style.
+ */
+ UNUSED(sock);
+ UNUSED(msg);
+ UNUSED(dev);
+
+#ifdef MSG_TRUNC
+ if ((msg->msg_flags & MSG_TRUNC) != 0) {
+ dev->attributes |= ISC_SOCKEVENTATTR_TRUNC;
+ }
+#endif /* ifdef MSG_TRUNC */
+
+#ifdef MSG_CTRUNC
+ if ((msg->msg_flags & MSG_CTRUNC) != 0) {
+ dev->attributes |= ISC_SOCKEVENTATTR_CTRUNC;
+ }
+#endif /* ifdef MSG_CTRUNC */
+
+#ifndef USE_CMSG
+ return;
+#else /* ifndef USE_CMSG */
+ if (msg->msg_controllen == 0U || msg->msg_control == NULL) {
+ return;
+ }
+
+#ifdef SO_TIMESTAMP
+ timevalp = NULL;
+#endif /* ifdef SO_TIMESTAMP */
+ pktinfop = NULL;
+
+ cmsgp = CMSG_FIRSTHDR(msg);
+ while (cmsgp != NULL) {
+ socket_log(sock, NULL, TRACE, "processing cmsg %p", cmsgp);
+
+ if (cmsgp->cmsg_level == IPPROTO_IPV6 &&
+ cmsgp->cmsg_type == IPV6_PKTINFO)
+ {
+ pktinfop = (struct in6_pktinfo *)CMSG_DATA(cmsgp);
+ memmove(&dev->pktinfo, pktinfop,
+ sizeof(struct in6_pktinfo));
+ dev->attributes |= ISC_SOCKEVENTATTR_PKTINFO;
+ socket_log(sock, NULL, TRACE,
+ "interface received on ifindex %u",
+ dev->pktinfo.ipi6_ifindex);
+ if (IN6_IS_ADDR_MULTICAST(&pktinfop->ipi6_addr)) {
+ dev->attributes |= ISC_SOCKEVENTATTR_MULTICAST;
+ }
+ goto next;
+ }
+
+#ifdef SO_TIMESTAMP
+ if (cmsgp->cmsg_level == SOL_SOCKET &&
+ cmsgp->cmsg_type == SCM_TIMESTAMP)
+ {
+ struct timeval tv;
+ timevalp = CMSG_DATA(cmsgp);
+ memmove(&tv, timevalp, sizeof(tv));
+ dev->timestamp.seconds = tv.tv_sec;
+ dev->timestamp.nanoseconds = tv.tv_usec * 1000;
+ dev->attributes |= ISC_SOCKEVENTATTR_TIMESTAMP;
+ goto next;
+ }
+#endif /* ifdef SO_TIMESTAMP */
+
+#ifdef IPV6_TCLASS
+ if (cmsgp->cmsg_level == IPPROTO_IPV6 &&
+ cmsgp->cmsg_type == IPV6_TCLASS)
+ {
+ dev->dscp = *(int *)CMSG_DATA(cmsgp);
+ dev->dscp >>= 2;
+ dev->attributes |= ISC_SOCKEVENTATTR_DSCP;
+ goto next;
+ }
+#endif /* ifdef IPV6_TCLASS */
+
+#ifdef IP_TOS
+ if (cmsgp->cmsg_level == IPPROTO_IP &&
+ (cmsgp->cmsg_type == IP_TOS
+#ifdef IP_RECVTOS
+ || cmsgp->cmsg_type == IP_RECVTOS
+#endif /* ifdef IP_RECVTOS */
+ ))
+ {
+ dev->dscp = (int)*(unsigned char *)CMSG_DATA(cmsgp);
+ dev->dscp >>= 2;
+ dev->attributes |= ISC_SOCKEVENTATTR_DSCP;
+ goto next;
+ }
+#endif /* ifdef IP_TOS */
+ next:
+ cmsgp = CMSG_NXTHDR(msg, cmsgp);
+ }
+#endif /* USE_CMSG */
+}
+
+/*
+ * Construct an iov array and attach it to the msghdr passed in. This is
+ * the SEND constructor, which will use the used region of the buffer
+ * (if using a buffer list) or will use the internal region (if a single
+ * buffer I/O is requested).
+ *
+ * Nothing can be NULL, and the done event must list at least one buffer
+ * on the buffer linked list for this function to be meaningful.
+ *
+ * If write_countp != NULL, *write_countp will hold the number of bytes
+ * this transaction can send.
+ */
+static void
+build_msghdr_send(isc_socket_t *sock, char *cmsgbuf, isc_socketevent_t *dev,
+ struct msghdr *msg, struct iovec *iov, size_t *write_countp) {
+ unsigned int iovcount;
+ size_t write_count;
+ struct cmsghdr *cmsgp;
+
+ memset(msg, 0, sizeof(*msg));
+
+ if (!sock->connected) {
+ msg->msg_name = (void *)&dev->address.type.sa;
+ msg->msg_namelen = dev->address.length;
+ } else {
+ msg->msg_name = NULL;
+ msg->msg_namelen = 0;
+ }
+
+ write_count = dev->region.length - dev->n;
+ iov[0].iov_base = (void *)(dev->region.base + dev->n);
+ iov[0].iov_len = write_count;
+ iovcount = 1;
+
+ msg->msg_iov = iov;
+ msg->msg_iovlen = iovcount;
+ msg->msg_control = NULL;
+ msg->msg_controllen = 0;
+ msg->msg_flags = 0;
+#if defined(USE_CMSG)
+
+ if ((sock->type == isc_sockettype_udp) &&
+ ((dev->attributes & ISC_SOCKEVENTATTR_PKTINFO) != 0))
+ {
+ struct in6_pktinfo *pktinfop;
+
+ socket_log(sock, NULL, TRACE, "sendto pktinfo data, ifindex %u",
+ dev->pktinfo.ipi6_ifindex);
+
+ msg->msg_control = (void *)cmsgbuf;
+ msg->msg_controllen = cmsg_space(sizeof(struct in6_pktinfo));
+ INSIST(msg->msg_controllen <= SENDCMSGBUFLEN);
+
+ cmsgp = (struct cmsghdr *)cmsgbuf;
+ cmsgp->cmsg_level = IPPROTO_IPV6;
+ cmsgp->cmsg_type = IPV6_PKTINFO;
+ cmsgp->cmsg_len = cmsg_len(sizeof(struct in6_pktinfo));
+ pktinfop = (struct in6_pktinfo *)CMSG_DATA(cmsgp);
+ memmove(pktinfop, &dev->pktinfo, sizeof(struct in6_pktinfo));
+ }
+
+#if defined(IPV6_USE_MIN_MTU)
+ if ((sock->type == isc_sockettype_udp) && (sock->pf == AF_INET6) &&
+ ((dev->attributes & ISC_SOCKEVENTATTR_USEMINMTU) != 0))
+ {
+ int use_min_mtu = 1; /* -1, 0, 1 */
+
+ cmsgp = (struct cmsghdr *)(cmsgbuf + msg->msg_controllen);
+ msg->msg_control = (void *)cmsgbuf;
+ msg->msg_controllen += cmsg_space(sizeof(use_min_mtu));
+ INSIST(msg->msg_controllen <= SENDCMSGBUFLEN);
+
+ cmsgp->cmsg_level = IPPROTO_IPV6;
+ cmsgp->cmsg_type = IPV6_USE_MIN_MTU;
+ cmsgp->cmsg_len = cmsg_len(sizeof(use_min_mtu));
+ memmove(CMSG_DATA(cmsgp), &use_min_mtu, sizeof(use_min_mtu));
+ }
+#endif /* if defined(IPV6_USE_MIN_MTU) */
+
+ if (isc_dscp_check_value > -1) {
+ if (sock->type == isc_sockettype_udp) {
+ INSIST((int)dev->dscp == isc_dscp_check_value);
+ } else if (sock->type == isc_sockettype_tcp) {
+ INSIST((int)sock->dscp == isc_dscp_check_value);
+ }
+ }
+
+#if defined(IP_TOS) || (defined(IPPROTO_IPV6) && defined(IPV6_TCLASS))
+ if ((sock->type == isc_sockettype_udp) &&
+ ((dev->attributes & ISC_SOCKEVENTATTR_DSCP) != 0))
+ {
+ int dscp = (dev->dscp << 2) & 0xff;
+
+ INSIST(dev->dscp < 0x40);
+
+#ifdef IP_TOS
+ if (sock->pf == AF_INET && sock->pktdscp) {
+ cmsgp = (struct cmsghdr *)(cmsgbuf +
+ msg->msg_controllen);
+ msg->msg_control = (void *)cmsgbuf;
+ msg->msg_controllen += cmsg_space(sizeof(dscp));
+ INSIST(msg->msg_controllen <= SENDCMSGBUFLEN);
+
+ cmsgp->cmsg_level = IPPROTO_IP;
+ cmsgp->cmsg_type = IP_TOS;
+ cmsgp->cmsg_len = cmsg_len(sizeof(char));
+ *(unsigned char *)CMSG_DATA(cmsgp) = dscp;
+ } else if (sock->pf == AF_INET && sock->dscp != dev->dscp) {
+ if (setsockopt(sock->fd, IPPROTO_IP, IP_TOS,
+ (void *)&dscp, sizeof(int)) < 0)
+ {
+ char strbuf[ISC_STRERRORSIZE];
+ strerror_r(errno, strbuf, sizeof(strbuf));
+ UNEXPECTED_ERROR(__FILE__, __LINE__,
+ "setsockopt(%d, IP_TOS, %.02x)"
+ " failed: %s",
+ sock->fd, dscp >> 2, strbuf);
+ } else {
+ sock->dscp = dscp;
+ }
+ }
+#endif /* ifdef IP_TOS */
+#if defined(IPPROTO_IPV6) && defined(IPV6_TCLASS)
+ if (sock->pf == AF_INET6 && sock->pktdscp) {
+ cmsgp = (struct cmsghdr *)(cmsgbuf +
+ msg->msg_controllen);
+ msg->msg_control = (void *)cmsgbuf;
+ msg->msg_controllen += cmsg_space(sizeof(dscp));
+ INSIST(msg->msg_controllen <= SENDCMSGBUFLEN);
+
+ cmsgp->cmsg_level = IPPROTO_IPV6;
+ cmsgp->cmsg_type = IPV6_TCLASS;
+ cmsgp->cmsg_len = cmsg_len(sizeof(dscp));
+ memmove(CMSG_DATA(cmsgp), &dscp, sizeof(dscp));
+ } else if (sock->pf == AF_INET6 && sock->dscp != dev->dscp) {
+ if (setsockopt(sock->fd, IPPROTO_IPV6, IPV6_TCLASS,
+ (void *)&dscp, sizeof(int)) < 0)
+ {
+ char strbuf[ISC_STRERRORSIZE];
+ strerror_r(errno, strbuf, sizeof(strbuf));
+ UNEXPECTED_ERROR(__FILE__, __LINE__,
+ "setsockopt(%d, IPV6_TCLASS, "
+ "%.02x) failed: %s",
+ sock->fd, dscp >> 2, strbuf);
+ } else {
+ sock->dscp = dscp;
+ }
+ }
+#endif /* if defined(IPPROTO_IPV6) && defined(IPV6_TCLASS) */
+ if (msg->msg_controllen != 0 &&
+ msg->msg_controllen < SENDCMSGBUFLEN)
+ {
+ memset(cmsgbuf + msg->msg_controllen, 0,
+ SENDCMSGBUFLEN - msg->msg_controllen);
+ }
+ }
+#endif /* if defined(IP_TOS) || (defined(IPPROTO_IPV6) && \
+ * defined(IPV6_TCLASS)) \
+ * */
+#endif /* USE_CMSG */
+
+ if (write_countp != NULL) {
+ *write_countp = write_count;
+ }
+}
+
+/*
+ * Construct an iov array and attach it to the msghdr passed in. This is
+ * the RECV constructor, which will use the available region of the buffer
+ * (if using a buffer list) or will use the internal region (if a single
+ * buffer I/O is requested).
+ *
+ * Nothing can be NULL, and the done event must list at least one buffer
+ * on the buffer linked list for this function to be meaningful.
+ *
+ * If read_countp != NULL, *read_countp will hold the number of bytes
+ * this transaction can receive.
+ */
+static void
+build_msghdr_recv(isc_socket_t *sock, char *cmsgbuf, isc_socketevent_t *dev,
+ struct msghdr *msg, struct iovec *iov, size_t *read_countp) {
+ unsigned int iovcount;
+ size_t read_count;
+
+ memset(msg, 0, sizeof(struct msghdr));
+
+ if (sock->type == isc_sockettype_udp) {
+ memset(&dev->address, 0, sizeof(dev->address));
+ msg->msg_name = (void *)&dev->address.type.sa;
+ msg->msg_namelen = sizeof(dev->address.type);
+ } else { /* TCP */
+ msg->msg_name = NULL;
+ msg->msg_namelen = 0;
+ dev->address = sock->peer_address;
+ }
+
+ read_count = dev->region.length - dev->n;
+ iov[0].iov_base = (void *)(dev->region.base + dev->n);
+ iov[0].iov_len = read_count;
+ iovcount = 1;
+
+ /*
+ * If needed, set up to receive that one extra byte.
+ */
+#ifdef ISC_PLATFORM_RECVOVERFLOW
+ if (sock->type == isc_sockettype_udp) {
+ INSIST(iovcount < MAXSCATTERGATHER_RECV);
+ iov[iovcount].iov_base = (void *)(&sock->overflow);
+ iov[iovcount].iov_len = 1;
+ iovcount++;
+ }
+#endif /* ifdef ISC_PLATFORM_RECVOVERFLOW */
+
+ msg->msg_iov = iov;
+ msg->msg_iovlen = iovcount;
+
+#if defined(USE_CMSG)
+ msg->msg_control = cmsgbuf;
+ msg->msg_controllen = RECVCMSGBUFLEN;
+#else /* if defined(USE_CMSG) */
+ msg->msg_control = NULL;
+ msg->msg_controllen = 0;
+#endif /* USE_CMSG */
+ msg->msg_flags = 0;
+
+ if (read_countp != NULL) {
+ *read_countp = read_count;
+ }
+}
+
+static void
+set_dev_address(const isc_sockaddr_t *address, isc_socket_t *sock,
+ isc_socketevent_t *dev) {
+ if (sock->type == isc_sockettype_udp) {
+ if (address != NULL) {
+ dev->address = *address;
+ } else {
+ dev->address = sock->peer_address;
+ }
+ } else if (sock->type == isc_sockettype_tcp) {
+ INSIST(address == NULL);
+ dev->address = sock->peer_address;
+ }
+}
+
+static void
+destroy_socketevent(isc_event_t *event) {
+ isc_socketevent_t *ev = (isc_socketevent_t *)event;
+
+ (ev->destroy)(event);
+}
+
+static isc_socketevent_t *
+allocate_socketevent(isc_mem_t *mctx, void *sender, isc_eventtype_t eventtype,
+ isc_taskaction_t action, void *arg) {
+ isc_socketevent_t *ev;
+
+ ev = (isc_socketevent_t *)isc_event_allocate(mctx, sender, eventtype,
+ action, arg, sizeof(*ev));
+
+ ev->result = ISC_R_UNSET;
+ ISC_LINK_INIT(ev, ev_link);
+ ev->region.base = NULL;
+ ev->n = 0;
+ ev->offset = 0;
+ ev->attributes = 0;
+ ev->destroy = ev->ev_destroy;
+ ev->ev_destroy = destroy_socketevent;
+ ev->dscp = 0;
+
+ return (ev);
+}
+
+#if defined(ISC_SOCKET_DEBUG)
+static void
+dump_msg(struct msghdr *msg) {
+ unsigned int i;
+
+ printf("MSGHDR %p\n", msg);
+ printf("\tname %p, namelen %ld\n", msg->msg_name,
+ (long)msg->msg_namelen);
+ printf("\tiov %p, iovlen %ld\n", msg->msg_iov, (long)msg->msg_iovlen);
+ for (i = 0; i < (unsigned int)msg->msg_iovlen; i++) {
+ printf("\t\t%u\tbase %p, len %ld\n", i,
+ msg->msg_iov[i].iov_base, (long)msg->msg_iov[i].iov_len);
+ }
+ printf("\tcontrol %p, controllen %ld\n", msg->msg_control,
+ (long)msg->msg_controllen);
+}
+#endif /* if defined(ISC_SOCKET_DEBUG) */
+
+#define DOIO_SUCCESS 0 /* i/o ok, event sent */
+#define DOIO_SOFT 1 /* i/o ok, soft error, no event sent */
+#define DOIO_HARD 2 /* i/o error, event sent */
+#define DOIO_EOF 3 /* EOF, no event sent */
+
+static int
+doio_recv(isc_socket_t *sock, isc_socketevent_t *dev) {
+ int cc;
+ struct iovec iov[MAXSCATTERGATHER_RECV];
+ size_t read_count;
+ struct msghdr msghdr;
+ int recv_errno;
+ char strbuf[ISC_STRERRORSIZE];
+ char cmsgbuf[RECVCMSGBUFLEN] = { 0 };
+
+ build_msghdr_recv(sock, cmsgbuf, dev, &msghdr, iov, &read_count);
+
+#if defined(ISC_SOCKET_DEBUG)
+ dump_msg(&msghdr);
+#endif /* if defined(ISC_SOCKET_DEBUG) */
+
+ cc = recvmsg(sock->fd, &msghdr, 0);
+ recv_errno = errno;
+
+#if defined(ISC_SOCKET_DEBUG)
+ dump_msg(&msghdr);
+#endif /* if defined(ISC_SOCKET_DEBUG) */
+
+ if (cc < 0) {
+ if (SOFT_ERROR(recv_errno)) {
+ return (DOIO_SOFT);
+ }
+
+ if (isc_log_wouldlog(isc_lctx, IOEVENT_LEVEL)) {
+ strerror_r(recv_errno, strbuf, sizeof(strbuf));
+ socket_log(sock, NULL, IOEVENT,
+ "doio_recv: recvmsg(%d) %d bytes, err %d/%s",
+ sock->fd, cc, recv_errno, strbuf);
+ }
+
+#define SOFT_OR_HARD(_system, _isc) \
+ if (recv_errno == _system) { \
+ if (sock->connected) { \
+ dev->result = _isc; \
+ inc_stats(sock->manager->stats, \
+ sock->statsindex[STATID_RECVFAIL]); \
+ return (DOIO_HARD); \
+ } \
+ return (DOIO_SOFT); \
+ }
+#define ALWAYS_HARD(_system, _isc) \
+ if (recv_errno == _system) { \
+ dev->result = _isc; \
+ inc_stats(sock->manager->stats, \
+ sock->statsindex[STATID_RECVFAIL]); \
+ return (DOIO_HARD); \
+ }
+
+ SOFT_OR_HARD(ECONNREFUSED, ISC_R_CONNREFUSED);
+ SOFT_OR_HARD(ENETUNREACH, ISC_R_NETUNREACH);
+ SOFT_OR_HARD(EHOSTUNREACH, ISC_R_HOSTUNREACH);
+ SOFT_OR_HARD(EHOSTDOWN, ISC_R_HOSTDOWN);
+ SOFT_OR_HARD(ENOBUFS, ISC_R_NORESOURCES);
+ /*
+ * Older operating systems may still return EPROTO in some
+ * situations, for example when receiving ICMP/ICMPv6 errors.
+ * A real life scenario is when ICMPv6 returns code 5 or 6.
+ * These codes are introduced in RFC 4443 from March 2006,
+ * and the document obsoletes RFC 1885. But unfortunately not
+ * all operating systems have caught up with the new standard
+ * (in 2020) and thus a generic protocol error is returned.
+ */
+ SOFT_OR_HARD(EPROTO, ISC_R_HOSTUNREACH);
+ /* Should never get this one but it was seen. */
+#ifdef ENOPROTOOPT
+ SOFT_OR_HARD(ENOPROTOOPT, ISC_R_HOSTUNREACH);
+#endif /* ifdef ENOPROTOOPT */
+ SOFT_OR_HARD(EINVAL, ISC_R_HOSTUNREACH);
+
+#undef SOFT_OR_HARD
+#undef ALWAYS_HARD
+
+ dev->result = isc__errno2result(recv_errno);
+ inc_stats(sock->manager->stats,
+ sock->statsindex[STATID_RECVFAIL]);
+ return (DOIO_HARD);
+ }
+
+ /*
+ * On TCP and UNIX sockets, zero length reads indicate EOF,
+ * while on UDP sockets, zero length reads are perfectly valid,
+ * although strange.
+ */
+ switch (sock->type) {
+ case isc_sockettype_tcp:
+ case isc_sockettype_unix:
+ if (cc == 0) {
+ return (DOIO_EOF);
+ }
+ break;
+ case isc_sockettype_udp:
+ case isc_sockettype_raw:
+ break;
+ default:
+ UNREACHABLE();
+ }
+
+ if (sock->type == isc_sockettype_udp) {
+ dev->address.length = msghdr.msg_namelen;
+ if (isc_sockaddr_getport(&dev->address) == 0) {
+ if (isc_log_wouldlog(isc_lctx, IOEVENT_LEVEL)) {
+ socket_log(sock, &dev->address, IOEVENT,
+ "dropping source port zero packet");
+ }
+ return (DOIO_SOFT);
+ }
+ /*
+ * Simulate a firewall blocking UDP responses bigger than
+ * 'maxudp' bytes.
+ */
+ if (sock->manager->maxudp != 0 &&
+ cc > (int)sock->manager->maxudp)
+ {
+ return (DOIO_SOFT);
+ }
+ }
+
+ socket_log(sock, &dev->address, IOEVENT, "packet received correctly");
+
+ /*
+ * Overflow bit detection. If we received MORE bytes than we should,
+ * this indicates an overflow situation. Set the flag in the
+ * dev entry and adjust how much we read by one.
+ */
+#ifdef ISC_PLATFORM_RECVOVERFLOW
+ if ((sock->type == isc_sockettype_udp) && ((size_t)cc > read_count)) {
+ dev->attributes |= ISC_SOCKEVENTATTR_TRUNC;
+ cc--;
+ }
+#endif /* ifdef ISC_PLATFORM_RECVOVERFLOW */
+
+ /*
+ * If there are control messages attached, run through them and pull
+ * out the interesting bits.
+ */
+ process_cmsg(sock, &msghdr, dev);
+
+ /*
+ * update the buffers (if any) and the i/o count
+ */
+ dev->n += cc;
+
+ /*
+ * If we read less than we expected, update counters,
+ * and let the upper layer poke the descriptor.
+ */
+ if (((size_t)cc != read_count) && (dev->n < dev->minimum)) {
+ return (DOIO_SOFT);
+ }
+
+ /*
+ * Full reads are posted, or partials if partials are ok.
+ */
+ dev->result = ISC_R_SUCCESS;
+ return (DOIO_SUCCESS);
+}
+
+/*
+ * Returns:
+ * DOIO_SUCCESS The operation succeeded. dev->result contains
+ * ISC_R_SUCCESS.
+ *
+ * DOIO_HARD A hard or unexpected I/O error was encountered.
+ * dev->result contains the appropriate error.
+ *
+ * DOIO_SOFT A soft I/O error was encountered. No senddone
+ * event was sent. The operation should be retried.
+ *
+ * No other return values are possible.
+ */
+static int
+doio_send(isc_socket_t *sock, isc_socketevent_t *dev) {
+ int cc;
+ struct iovec iov[MAXSCATTERGATHER_SEND];
+ size_t write_count;
+ struct msghdr msghdr;
+ char addrbuf[ISC_SOCKADDR_FORMATSIZE];
+ int attempts = 0;
+ int send_errno;
+ char strbuf[ISC_STRERRORSIZE];
+ char cmsgbuf[SENDCMSGBUFLEN] = { 0 };
+
+ build_msghdr_send(sock, cmsgbuf, dev, &msghdr, iov, &write_count);
+
+resend:
+ if (sock->type == isc_sockettype_udp && sock->manager->maxudp != 0 &&
+ write_count > sock->manager->maxudp)
+ {
+ cc = write_count;
+ } else {
+ cc = sendmsg(sock->fd, &msghdr, 0);
+ }
+ send_errno = errno;
+
+ /*
+ * Check for error or block condition.
+ */
+ if (cc < 0) {
+ if (send_errno == EINTR && ++attempts < NRETRIES) {
+ goto resend;
+ }
+
+ if (SOFT_ERROR(send_errno)) {
+ if (errno == EWOULDBLOCK || errno == EAGAIN) {
+ dev->result = ISC_R_WOULDBLOCK;
+ }
+ return (DOIO_SOFT);
+ }
+
+#define SOFT_OR_HARD(_system, _isc) \
+ if (send_errno == _system) { \
+ if (sock->connected) { \
+ dev->result = _isc; \
+ inc_stats(sock->manager->stats, \
+ sock->statsindex[STATID_SENDFAIL]); \
+ return (DOIO_HARD); \
+ } \
+ return (DOIO_SOFT); \
+ }
+#define ALWAYS_HARD(_system, _isc) \
+ if (send_errno == _system) { \
+ dev->result = _isc; \
+ inc_stats(sock->manager->stats, \
+ sock->statsindex[STATID_SENDFAIL]); \
+ return (DOIO_HARD); \
+ }
+
+ SOFT_OR_HARD(ECONNREFUSED, ISC_R_CONNREFUSED);
+ ALWAYS_HARD(EACCES, ISC_R_NOPERM);
+ ALWAYS_HARD(EAFNOSUPPORT, ISC_R_ADDRNOTAVAIL);
+ ALWAYS_HARD(EADDRNOTAVAIL, ISC_R_ADDRNOTAVAIL);
+ ALWAYS_HARD(EHOSTUNREACH, ISC_R_HOSTUNREACH);
+#ifdef EHOSTDOWN
+ ALWAYS_HARD(EHOSTDOWN, ISC_R_HOSTUNREACH);
+#endif /* ifdef EHOSTDOWN */
+ ALWAYS_HARD(ENETUNREACH, ISC_R_NETUNREACH);
+ SOFT_OR_HARD(ENOBUFS, ISC_R_NORESOURCES);
+ ALWAYS_HARD(EPERM, ISC_R_HOSTUNREACH);
+ ALWAYS_HARD(EPIPE, ISC_R_NOTCONNECTED);
+ ALWAYS_HARD(ECONNRESET, ISC_R_CONNECTIONRESET);
+
+#undef SOFT_OR_HARD
+#undef ALWAYS_HARD
+
+ /*
+ * The other error types depend on whether or not the
+ * socket is UDP or TCP. If it is UDP, some errors
+ * that we expect to be fatal under TCP are merely
+ * annoying, and are really soft errors.
+ *
+ * However, these soft errors are still returned as
+ * a status.
+ */
+ isc_sockaddr_format(&dev->address, addrbuf, sizeof(addrbuf));
+ strerror_r(send_errno, strbuf, sizeof(strbuf));
+ UNEXPECTED_ERROR(__FILE__, __LINE__, "internal_send: %s: %s",
+ addrbuf, strbuf);
+ dev->result = isc__errno2result(send_errno);
+ inc_stats(sock->manager->stats,
+ sock->statsindex[STATID_SENDFAIL]);
+ return (DOIO_HARD);
+ }
+
+ if (cc == 0) {
+ inc_stats(sock->manager->stats,
+ sock->statsindex[STATID_SENDFAIL]);
+ UNEXPECTED_ERROR(__FILE__, __LINE__,
+ "doio_send: send() returned 0");
+ }
+
+ /*
+ * If we write less than we expected, update counters, poke.
+ */
+ dev->n += cc;
+ if ((size_t)cc != write_count) {
+ return (DOIO_SOFT);
+ }
+
+ /*
+ * Exactly what we wanted to write. We're done with this
+ * entry. Post its completion event.
+ */
+ dev->result = ISC_R_SUCCESS;
+ return (DOIO_SUCCESS);
+}
+
+/*
+ * Kill.
+ *
+ * Caller must ensure that the socket is not locked and no external
+ * references exist.
+ */
+static void
+socketclose(isc__socketthread_t *thread, isc_socket_t *sock, int fd) {
+ int lockid = FDLOCK_ID(fd);
+ /*
+ * No one has this socket open, so the watcher doesn't have to be
+ * poked, and the socket doesn't have to be locked.
+ */
+ LOCK(&thread->fdlock[lockid]);
+ thread->fds[fd] = NULL;
+ thread->fdstate[fd] = CLOSE_PENDING;
+ UNLOCK(&thread->fdlock[lockid]);
+ select_poke(thread->manager, thread->threadid, fd, SELECT_POKE_CLOSE);
+
+ inc_stats(thread->manager->stats, sock->statsindex[STATID_CLOSE]);
+
+ LOCK(&sock->lock);
+ if (sock->active == 1) {
+ dec_stats(thread->manager->stats,
+ sock->statsindex[STATID_ACTIVE]);
+ sock->active = 0;
+ }
+ UNLOCK(&sock->lock);
+
+ /*
+ * update manager->maxfd here (XXX: this should be implemented more
+ * efficiently)
+ */
+#ifdef USE_SELECT
+ LOCK(&thread->manager->lock);
+ if (thread->maxfd == fd) {
+ int i;
+
+ thread->maxfd = 0;
+ for (i = fd - 1; i >= 0; i--) {
+ lockid = FDLOCK_ID(i);
+
+ LOCK(&thread->fdlock[lockid]);
+ if (thread->fdstate[i] == MANAGED) {
+ thread->maxfd = i;
+ UNLOCK(&thread->fdlock[lockid]);
+ break;
+ }
+ UNLOCK(&thread->fdlock[lockid]);
+ }
+ if (thread->maxfd < thread->pipe_fds[0]) {
+ thread->maxfd = thread->pipe_fds[0];
+ }
+ }
+
+ UNLOCK(&thread->manager->lock);
+#endif /* USE_SELECT */
+}
+
+static void
+destroy(isc_socket_t **sockp) {
+ int fd = 0;
+ isc_socket_t *sock = *sockp;
+ isc_socketmgr_t *manager = sock->manager;
+ isc__socketthread_t *thread = NULL;
+
+ socket_log(sock, NULL, CREATION, "destroying");
+
+ isc_refcount_destroy(&sock->references);
+
+ LOCK(&sock->lock);
+ INSIST(ISC_LIST_EMPTY(sock->connect_list));
+ INSIST(ISC_LIST_EMPTY(sock->accept_list));
+ INSIST(ISC_LIST_EMPTY(sock->recv_list));
+ INSIST(ISC_LIST_EMPTY(sock->send_list));
+ INSIST(sock->fd >= -1 && sock->fd < (int)manager->maxsocks);
+
+ if (sock->fd >= 0) {
+ fd = sock->fd;
+ thread = &manager->threads[sock->threadid];
+ sock->fd = -1;
+ sock->threadid = -1;
+ }
+ UNLOCK(&sock->lock);
+
+ if (fd > 0) {
+ socketclose(thread, sock, fd);
+ }
+
+ LOCK(&manager->lock);
+
+ ISC_LIST_UNLINK(manager->socklist, sock, link);
+
+ if (ISC_LIST_EMPTY(manager->socklist)) {
+ SIGNAL(&manager->shutdown_ok);
+ }
+
+ /* can't unlock manager as its memory context is still used */
+ free_socket(sockp);
+
+ UNLOCK(&manager->lock);
+}
+
+static isc_result_t
+allocate_socket(isc_socketmgr_t *manager, isc_sockettype_t type,
+ isc_socket_t **socketp) {
+ isc_socket_t *sock;
+
+ sock = isc_mem_get(manager->mctx, sizeof(*sock));
+
+ sock->magic = 0;
+ isc_refcount_init(&sock->references, 0);
+
+ sock->manager = manager;
+ sock->type = type;
+ sock->fd = -1;
+ sock->threadid = -1;
+ sock->dscp = 0; /* TOS/TCLASS is zero until set. */
+ sock->dupped = 0;
+ sock->statsindex = NULL;
+ sock->active = 0;
+
+ ISC_LINK_INIT(sock, link);
+
+ memset(sock->name, 0, sizeof(sock->name));
+ sock->tag = NULL;
+
+ /*
+ * Set up list of readers and writers to be initially empty.
+ */
+ ISC_LIST_INIT(sock->recv_list);
+ ISC_LIST_INIT(sock->send_list);
+ ISC_LIST_INIT(sock->accept_list);
+ ISC_LIST_INIT(sock->connect_list);
+
+ sock->listener = 0;
+ sock->connected = 0;
+ sock->connecting = 0;
+ sock->bound = 0;
+ sock->pktdscp = 0;
+
+ /*
+ * Initialize the lock.
+ */
+ isc_mutex_init(&sock->lock);
+
+ sock->magic = SOCKET_MAGIC;
+ *socketp = sock;
+
+ return (ISC_R_SUCCESS);
+}
+
+/*
+ * This event requires that the various lists be empty, that the reference
+ * count be 1, and that the magic number is valid. The other socket bits,
+ * like the lock, must be initialized as well. The fd associated must be
+ * marked as closed, by setting it to -1 on close, or this routine will
+ * also close the socket.
+ */
+static void
+free_socket(isc_socket_t **socketp) {
+ isc_socket_t *sock = *socketp;
+ *socketp = NULL;
+
+ INSIST(VALID_SOCKET(sock));
+ isc_refcount_destroy(&sock->references);
+ LOCK(&sock->lock);
+ INSIST(!sock->connecting);
+ INSIST(ISC_LIST_EMPTY(sock->recv_list));
+ INSIST(ISC_LIST_EMPTY(sock->send_list));
+ INSIST(ISC_LIST_EMPTY(sock->accept_list));
+ INSIST(ISC_LIST_EMPTY(sock->connect_list));
+ INSIST(!ISC_LINK_LINKED(sock, link));
+ UNLOCK(&sock->lock);
+
+ sock->magic = 0;
+
+ isc_mutex_destroy(&sock->lock);
+
+ isc_mem_put(sock->manager->mctx, sock, sizeof(*sock));
+}
+
+#if defined(SET_RCVBUF)
+static isc_once_t rcvbuf_once = ISC_ONCE_INIT;
+static int rcvbuf = ISC_RECV_BUFFER_SIZE;
+
+static void
+set_rcvbuf(void) {
+ int fd;
+ int max = rcvbuf, min;
+ socklen_t len;
+
+ fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
+ if (fd == -1) {
+ switch (errno) {
+ case EPROTONOSUPPORT:
+ case EPFNOSUPPORT:
+ case EAFNOSUPPORT:
+ /*
+ * Linux 2.2 (and maybe others) return EINVAL instead of
+ * EAFNOSUPPORT.
+ */
+ case EINVAL:
+ fd = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP);
+ break;
+ }
+ }
+ if (fd == -1) {
+ return;
+ }
+
+ len = sizeof(min);
+ if (getsockopt(fd, SOL_SOCKET, SO_RCVBUF, (void *)&min, &len) == 0 &&
+ min < rcvbuf)
+ {
+ again:
+ if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, (void *)&rcvbuf,
+ sizeof(rcvbuf)) == -1)
+ {
+ if (errno == ENOBUFS && rcvbuf > min) {
+ max = rcvbuf - 1;
+ rcvbuf = (rcvbuf + min) / 2;
+ goto again;
+ } else {
+ rcvbuf = min;
+ goto cleanup;
+ }
+ } else {
+ min = rcvbuf;
+ }
+ if (min != max) {
+ rcvbuf = max;
+ goto again;
+ }
+ }
+cleanup:
+ close(fd);
+}
+#endif /* ifdef SO_RCVBUF */
+
+#if defined(SET_SNDBUF)
+static isc_once_t sndbuf_once = ISC_ONCE_INIT;
+static int sndbuf = ISC_SEND_BUFFER_SIZE;
+
+static void
+set_sndbuf(void) {
+ int fd;
+ int max = sndbuf, min;
+ socklen_t len;
+
+ fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
+ if (fd == -1) {
+ switch (errno) {
+ case EPROTONOSUPPORT:
+ case EPFNOSUPPORT:
+ case EAFNOSUPPORT:
+ /*
+ * Linux 2.2 (and maybe others) return EINVAL instead of
+ * EAFNOSUPPORT.
+ */
+ case EINVAL:
+ fd = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP);
+ break;
+ }
+ }
+ if (fd == -1) {
+ return;
+ }
+
+ len = sizeof(min);
+ if (getsockopt(fd, SOL_SOCKET, SO_SNDBUF, (void *)&min, &len) == 0 &&
+ min < sndbuf)
+ {
+ again:
+ if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (void *)&sndbuf,
+ sizeof(sndbuf)) == -1)
+ {
+ if (errno == ENOBUFS && sndbuf > min) {
+ max = sndbuf - 1;
+ sndbuf = (sndbuf + min) / 2;
+ goto again;
+ } else {
+ sndbuf = min;
+ goto cleanup;
+ }
+ } else {
+ min = sndbuf;
+ }
+ if (min != max) {
+ sndbuf = max;
+ goto again;
+ }
+ }
+cleanup:
+ close(fd);
+}
+#endif /* ifdef SO_SNDBUF */
+
+static void
+use_min_mtu(isc_socket_t *sock) {
+#if !defined(IPV6_USE_MIN_MTU) && !defined(IPV6_MTU)
+ UNUSED(sock);
+#endif /* if !defined(IPV6_USE_MIN_MTU) && !defined(IPV6_MTU) */
+#ifdef IPV6_USE_MIN_MTU
+ /* use minimum MTU */
+ if (sock->pf == AF_INET6) {
+ int on = 1;
+ (void)setsockopt(sock->fd, IPPROTO_IPV6, IPV6_USE_MIN_MTU,
+ (void *)&on, sizeof(on));
+ }
+#endif /* ifdef IPV6_USE_MIN_MTU */
+#if defined(IPV6_MTU)
+ /*
+ * Use minimum MTU on IPv6 sockets.
+ */
+ if (sock->pf == AF_INET6) {
+ int mtu = 1280;
+ (void)setsockopt(sock->fd, IPPROTO_IPV6, IPV6_MTU, &mtu,
+ sizeof(mtu));
+ }
+#endif /* if defined(IPV6_MTU) */
+}
+
+static void
+set_tcp_maxseg(isc_socket_t *sock, int size) {
+#ifdef TCP_MAXSEG
+ if (sock->type == isc_sockettype_tcp) {
+ (void)setsockopt(sock->fd, IPPROTO_TCP, TCP_MAXSEG,
+ (void *)&size, sizeof(size));
+ }
+#endif /* ifdef TCP_MAXSEG */
+}
+
+static void
+set_ip_disable_pmtud(isc_socket_t *sock) {
+ /*
+ * Disable Path MTU Discover on IP packets
+ */
+ if (sock->pf == AF_INET6) {
+#if defined(IPV6_DONTFRAG)
+ (void)setsockopt(sock->fd, IPPROTO_IPV6, IPV6_DONTFRAG,
+ &(int){ 0 }, sizeof(int));
+#endif
+#if defined(IPV6_MTU_DISCOVER) && defined(IP_PMTUDISC_OMIT)
+ (void)setsockopt(sock->fd, IPPROTO_IPV6, IPV6_MTU_DISCOVER,
+ &(int){ IP_PMTUDISC_OMIT }, sizeof(int));
+#endif
+ } else if (sock->pf == AF_INET) {
+#if defined(IP_DONTFRAG)
+ (void)setsockopt(sock->fd, IPPROTO_IP, IP_DONTFRAG, &(int){ 0 },
+ sizeof(int));
+#endif
+#if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_OMIT)
+ (void)setsockopt(sock->fd, IPPROTO_IP, IP_MTU_DISCOVER,
+ &(int){ IP_PMTUDISC_OMIT }, sizeof(int));
+#endif
+ }
+}
+
+static isc_result_t
+opensocket(isc_socketmgr_t *manager, isc_socket_t *sock,
+ isc_socket_t *dup_socket) {
+ isc_result_t result;
+ char strbuf[ISC_STRERRORSIZE];
+ const char *err = "socket";
+ int tries = 0;
+#if defined(USE_CMSG) || defined(SO_NOSIGPIPE)
+ int on = 1;
+#endif /* if defined(USE_CMSG) || defined(SO_NOSIGPIPE) */
+#if defined(SET_RCVBUF) || defined(SET_SNDBUF)
+ socklen_t optlen;
+ int size = 0;
+#endif
+
+again:
+ if (dup_socket == NULL) {
+ switch (sock->type) {
+ case isc_sockettype_udp:
+ sock->fd = socket(sock->pf, SOCK_DGRAM, IPPROTO_UDP);
+ break;
+ case isc_sockettype_tcp:
+ sock->fd = socket(sock->pf, SOCK_STREAM, IPPROTO_TCP);
+ break;
+ case isc_sockettype_unix:
+ sock->fd = socket(sock->pf, SOCK_STREAM, 0);
+ break;
+ case isc_sockettype_raw:
+ errno = EPFNOSUPPORT;
+ /*
+ * PF_ROUTE is a alias for PF_NETLINK on linux.
+ */
+#if defined(PF_ROUTE)
+ if (sock->fd == -1 && sock->pf == PF_ROUTE) {
+#ifdef NETLINK_ROUTE
+ sock->fd = socket(sock->pf, SOCK_RAW,
+ NETLINK_ROUTE);
+#else /* ifdef NETLINK_ROUTE */
+ sock->fd = socket(sock->pf, SOCK_RAW, 0);
+#endif /* ifdef NETLINK_ROUTE */
+ if (sock->fd != -1) {
+#ifdef NETLINK_ROUTE
+ struct sockaddr_nl sa;
+ int n;
+
+ /*
+ * Do an implicit bind.
+ */
+ memset(&sa, 0, sizeof(sa));
+ sa.nl_family = AF_NETLINK;
+ sa.nl_groups = RTMGRP_IPV4_IFADDR |
+ RTMGRP_IPV6_IFADDR;
+ n = bind(sock->fd,
+ (struct sockaddr *)&sa,
+ sizeof(sa));
+ if (n < 0) {
+ close(sock->fd);
+ sock->fd = -1;
+ }
+#endif /* ifdef NETLINK_ROUTE */
+ sock->bound = 1;
+ }
+ }
+#endif /* if defined(PF_ROUTE) */
+ break;
+ }
+ } else {
+ sock->fd = dup(dup_socket->fd);
+ sock->dupped = 1;
+ sock->bound = dup_socket->bound;
+ }
+ if (sock->fd == -1 && errno == EINTR && tries++ < 42) {
+ goto again;
+ }
+
+#ifdef F_DUPFD
+ /*
+ * Leave a space for stdio and TCP to work in.
+ */
+ if (manager->reserved != 0 && sock->type == isc_sockettype_udp &&
+ sock->fd >= 0 && sock->fd < manager->reserved)
+ {
+ int newfd, tmp;
+ newfd = fcntl(sock->fd, F_DUPFD, manager->reserved);
+ tmp = errno;
+ (void)close(sock->fd);
+ errno = tmp;
+ sock->fd = newfd;
+ err = "isc_socket_create: fcntl/reserved";
+ } else if (sock->fd >= 0 && sock->fd < 20) {
+ int newfd, tmp;
+ newfd = fcntl(sock->fd, F_DUPFD, 20);
+ tmp = errno;
+ (void)close(sock->fd);
+ errno = tmp;
+ sock->fd = newfd;
+ err = "isc_socket_create: fcntl";
+ }
+#endif /* ifdef F_DUPFD */
+
+ if (sock->fd >= (int)manager->maxsocks) {
+ (void)close(sock->fd);
+ isc_log_write(isc_lctx, ISC_LOGCATEGORY_GENERAL,
+ ISC_LOGMODULE_SOCKET, ISC_LOG_ERROR,
+ "socket: file descriptor exceeds limit (%d/%u)",
+ sock->fd, manager->maxsocks);
+ inc_stats(manager->stats, sock->statsindex[STATID_OPENFAIL]);
+ return (ISC_R_NORESOURCES);
+ }
+
+ if (sock->fd < 0) {
+ switch (errno) {
+ case EMFILE:
+ case ENFILE:
+ strerror_r(errno, strbuf, sizeof(strbuf));
+ isc_log_write(isc_lctx, ISC_LOGCATEGORY_GENERAL,
+ ISC_LOGMODULE_SOCKET, ISC_LOG_ERROR,
+ "%s: %s", err, strbuf);
+ FALLTHROUGH;
+ case ENOBUFS:
+ inc_stats(manager->stats,
+ sock->statsindex[STATID_OPENFAIL]);
+ return (ISC_R_NORESOURCES);
+
+ case EPROTONOSUPPORT:
+ case EPFNOSUPPORT:
+ case EAFNOSUPPORT:
+ /*
+ * Linux 2.2 (and maybe others) return EINVAL instead of
+ * EAFNOSUPPORT.
+ */
+ case EINVAL:
+ inc_stats(manager->stats,
+ sock->statsindex[STATID_OPENFAIL]);
+ return (ISC_R_FAMILYNOSUPPORT);
+
+ default:
+ strerror_r(errno, strbuf, sizeof(strbuf));
+ UNEXPECTED_ERROR(__FILE__, __LINE__, "%s() failed: %s",
+ err, strbuf);
+ inc_stats(manager->stats,
+ sock->statsindex[STATID_OPENFAIL]);
+ return (ISC_R_UNEXPECTED);
+ }
+ }
+
+ if (dup_socket != NULL) {
+ goto setup_done;
+ }
+
+ result = make_nonblock(sock->fd);
+ if (result != ISC_R_SUCCESS) {
+ (void)close(sock->fd);
+ inc_stats(manager->stats, sock->statsindex[STATID_OPENFAIL]);
+ return (result);
+ }
+
+#ifdef SO_NOSIGPIPE
+ if (setsockopt(sock->fd, SOL_SOCKET, SO_NOSIGPIPE, (void *)&on,
+ sizeof(on)) < 0)
+ {
+ strerror_r(errno, strbuf, sizeof(strbuf));
+ UNEXPECTED_ERROR(__FILE__, __LINE__,
+ "setsockopt(%d, SO_NOSIGPIPE) failed: %s",
+ sock->fd, strbuf);
+ /* Press on... */
+ }
+#endif /* ifdef SO_NOSIGPIPE */
+
+ /*
+ * Use minimum mtu if possible.
+ */
+ if (sock->type == isc_sockettype_tcp && sock->pf == AF_INET6) {
+ use_min_mtu(sock);
+ set_tcp_maxseg(sock, 1280 - 20 - 40); /* 1280 - TCP - IPV6 */
+ }
+
+#if defined(USE_CMSG) || defined(SET_RCVBUF) || defined(SET_SNDBUF)
+ if (sock->type == isc_sockettype_udp) {
+#if defined(USE_CMSG)
+#if defined(SO_TIMESTAMP)
+ if (setsockopt(sock->fd, SOL_SOCKET, SO_TIMESTAMP, (void *)&on,
+ sizeof(on)) < 0 &&
+ errno != ENOPROTOOPT)
+ {
+ strerror_r(errno, strbuf, sizeof(strbuf));
+ UNEXPECTED_ERROR(__FILE__, __LINE__,
+ "setsockopt(%d, SO_TIMESTAMP) failed: "
+ "%s",
+ sock->fd, strbuf);
+ /* Press on... */
+ }
+#endif /* SO_TIMESTAMP */
+
+#ifdef IPV6_RECVPKTINFO
+ /* RFC 3542 */
+ if ((sock->pf == AF_INET6) &&
+ (setsockopt(sock->fd, IPPROTO_IPV6, IPV6_RECVPKTINFO,
+ (void *)&on, sizeof(on)) < 0))
+ {
+ strerror_r(errno, strbuf, sizeof(strbuf));
+ UNEXPECTED_ERROR(__FILE__, __LINE__,
+ "setsockopt(%d, IPV6_RECVPKTINFO) "
+ "failed: %s",
+ sock->fd, strbuf);
+ }
+#else /* ifdef IPV6_RECVPKTINFO */
+ /* RFC 2292 */
+ if ((sock->pf == AF_INET6) &&
+ (setsockopt(sock->fd, IPPROTO_IPV6, IPV6_PKTINFO,
+ (void *)&on, sizeof(on)) < 0))
+ {
+ strerror_r(errno, strbuf, sizeof(strbuf));
+ UNEXPECTED_ERROR(__FILE__, __LINE__,
+ "setsockopt(%d, IPV6_PKTINFO) failed: "
+ "%s",
+ sock->fd, strbuf);
+ }
+#endif /* IPV6_RECVPKTINFO */
+#endif /* defined(USE_CMSG) */
+
+#if defined(SET_RCVBUF)
+ optlen = sizeof(size);
+ if (getsockopt(sock->fd, SOL_SOCKET, SO_RCVBUF, (void *)&size,
+ &optlen) == 0 &&
+ size < rcvbuf)
+ {
+ RUNTIME_CHECK(isc_once_do(&rcvbuf_once, set_rcvbuf) ==
+ ISC_R_SUCCESS);
+ if (setsockopt(sock->fd, SOL_SOCKET, SO_RCVBUF,
+ (void *)&rcvbuf, sizeof(rcvbuf)) == -1)
+ {
+ strerror_r(errno, strbuf, sizeof(strbuf));
+ UNEXPECTED_ERROR(__FILE__, __LINE__,
+ "setsockopt(%d, SO_RCVBUF, "
+ "%d) failed: %s",
+ sock->fd, rcvbuf, strbuf);
+ }
+ }
+#endif /* if defined(SET_RCVBUF) */
+
+#if defined(SET_SNDBUF)
+ optlen = sizeof(size);
+ if (getsockopt(sock->fd, SOL_SOCKET, SO_SNDBUF, (void *)&size,
+ &optlen) == 0 &&
+ size < sndbuf)
+ {
+ RUNTIME_CHECK(isc_once_do(&sndbuf_once, set_sndbuf) ==
+ ISC_R_SUCCESS);
+ if (setsockopt(sock->fd, SOL_SOCKET, SO_SNDBUF,
+ (void *)&sndbuf, sizeof(sndbuf)) == -1)
+ {
+ strerror_r(errno, strbuf, sizeof(strbuf));
+ UNEXPECTED_ERROR(__FILE__, __LINE__,
+ "setsockopt(%d, SO_SNDBUF, "
+ "%d) failed: %s",
+ sock->fd, sndbuf, strbuf);
+ }
+ }
+#endif /* if defined(SO_SNDBUF) */
+ }
+#ifdef IPV6_RECVTCLASS
+ if ((sock->pf == AF_INET6) &&
+ (setsockopt(sock->fd, IPPROTO_IPV6, IPV6_RECVTCLASS, (void *)&on,
+ sizeof(on)) < 0))
+ {
+ strerror_r(errno, strbuf, sizeof(strbuf));
+ UNEXPECTED_ERROR(__FILE__, __LINE__,
+ "setsockopt(%d, IPV6_RECVTCLASS) "
+ "failed: %s",
+ sock->fd, strbuf);
+ }
+#endif /* ifdef IPV6_RECVTCLASS */
+#ifdef IP_RECVTOS
+ if ((sock->pf == AF_INET) &&
+ (setsockopt(sock->fd, IPPROTO_IP, IP_RECVTOS, (void *)&on,
+ sizeof(on)) < 0))
+ {
+ strerror_r(errno, strbuf, sizeof(strbuf));
+ UNEXPECTED_ERROR(__FILE__, __LINE__,
+ "setsockopt(%d, IP_RECVTOS) "
+ "failed: %s",
+ sock->fd, strbuf);
+ }
+#endif /* ifdef IP_RECVTOS */
+#endif /* defined(USE_CMSG) || defined(SET_RCVBUF) || defined(SET_SNDBUF) */
+
+ set_ip_disable_pmtud(sock);
+
+setup_done:
+ inc_stats(manager->stats, sock->statsindex[STATID_OPEN]);
+ if (sock->active == 0) {
+ inc_stats(manager->stats, sock->statsindex[STATID_ACTIVE]);
+ sock->active = 1;
+ }
+
+ return (ISC_R_SUCCESS);
+}
+
+/*
+ * Create a 'type' socket or duplicate an existing socket, managed
+ * by 'manager'. Events will be posted to 'task' and when dispatched
+ * 'action' will be called with 'arg' as the arg value. The new
+ * socket is returned in 'socketp'.
+ */
+static isc_result_t
+socket_create(isc_socketmgr_t *manager, int pf, isc_sockettype_t type,
+ isc_socket_t **socketp, isc_socket_t *dup_socket) {
+ isc_socket_t *sock = NULL;
+ isc__socketthread_t *thread;
+ isc_result_t result;
+ int lockid;
+
+ REQUIRE(VALID_MANAGER(manager));
+ REQUIRE(socketp != NULL && *socketp == NULL);
+
+ result = allocate_socket(manager, type, &sock);
+ if (result != ISC_R_SUCCESS) {
+ return (result);
+ }
+
+ switch (sock->type) {
+ case isc_sockettype_udp:
+ sock->statsindex = (pf == AF_INET) ? udp4statsindex
+ : udp6statsindex;
+#define DCSPPKT(pf) ((pf == AF_INET) ? ISC_NET_DSCPPKTV4 : ISC_NET_DSCPPKTV6)
+ sock->pktdscp = (isc_net_probedscp() & DCSPPKT(pf)) != 0;
+ break;
+ case isc_sockettype_tcp:
+ sock->statsindex = (pf == AF_INET) ? tcp4statsindex
+ : tcp6statsindex;
+ break;
+ case isc_sockettype_unix:
+ sock->statsindex = unixstatsindex;
+ break;
+ case isc_sockettype_raw:
+ sock->statsindex = rawstatsindex;
+ break;
+ default:
+ UNREACHABLE();
+ }
+
+ sock->pf = pf;
+
+ result = opensocket(manager, sock, dup_socket);
+ if (result != ISC_R_SUCCESS) {
+ free_socket(&sock);
+ return (result);
+ }
+
+ if (sock->fd == -1) {
+ abort();
+ }
+ sock->threadid = gen_threadid(sock);
+ isc_refcount_increment0(&sock->references);
+ thread = &manager->threads[sock->threadid];
+ *socketp = sock;
+
+ /*
+ * Note we don't have to lock the socket like we normally would because
+ * there are no external references to it yet.
+ */
+
+ lockid = FDLOCK_ID(sock->fd);
+ LOCK(&thread->fdlock[lockid]);
+ thread->fds[sock->fd] = sock;
+ thread->fdstate[sock->fd] = MANAGED;
+#if defined(USE_EPOLL)
+ thread->epoll_events[sock->fd] = 0;
+#endif /* if defined(USE_EPOLL) */
+#ifdef USE_DEVPOLL
+ INSIST(thread->fdpollinfo[sock->fd].want_read == 0 &&
+ thread->fdpollinfo[sock->fd].want_write == 0);
+#endif /* ifdef USE_DEVPOLL */
+ UNLOCK(&thread->fdlock[lockid]);
+
+ LOCK(&manager->lock);
+ ISC_LIST_APPEND(manager->socklist, sock, link);
+#ifdef USE_SELECT
+ if (thread->maxfd < sock->fd) {
+ thread->maxfd = sock->fd;
+ }
+#endif /* ifdef USE_SELECT */
+ UNLOCK(&manager->lock);
+
+ socket_log(sock, NULL, CREATION,
+ dup_socket != NULL ? "dupped" : "created");
+
+ return (ISC_R_SUCCESS);
+}
+
+/*%
+ * Create a new 'type' socket managed by 'manager'. Events
+ * will be posted to 'task' and when dispatched 'action' will be
+ * called with 'arg' as the arg value. The new socket is returned
+ * in 'socketp'.
+ */
+isc_result_t
+isc_socket_create(isc_socketmgr_t *manager0, int pf, isc_sockettype_t type,
+ isc_socket_t **socketp) {
+ return (socket_create(manager0, pf, type, socketp, NULL));
+}
+
+/*%
+ * Duplicate an existing socket. The new socket is returned
+ * in 'socketp'.
+ */
+isc_result_t
+isc_socket_dup(isc_socket_t *sock, isc_socket_t **socketp) {
+ REQUIRE(VALID_SOCKET(sock));
+ REQUIRE(socketp != NULL && *socketp == NULL);
+
+ return (socket_create(sock->manager, sock->pf, sock->type, socketp,
+ sock));
+}
+
+isc_result_t
+isc_socket_open(isc_socket_t *sock) {
+ isc_result_t result;
+ isc__socketthread_t *thread;
+
+ REQUIRE(VALID_SOCKET(sock));
+
+ LOCK(&sock->lock);
+
+ REQUIRE(isc_refcount_current(&sock->references) >= 1);
+ REQUIRE(sock->fd == -1);
+ REQUIRE(sock->threadid == -1);
+
+ result = opensocket(sock->manager, sock, NULL);
+
+ UNLOCK(&sock->lock);
+
+ if (result != ISC_R_SUCCESS) {
+ sock->fd = -1;
+ } else {
+ sock->threadid = gen_threadid(sock);
+ thread = &sock->manager->threads[sock->threadid];
+ int lockid = FDLOCK_ID(sock->fd);
+
+ LOCK(&thread->fdlock[lockid]);
+ thread->fds[sock->fd] = sock;
+ thread->fdstate[sock->fd] = MANAGED;
+#if defined(USE_EPOLL)
+ thread->epoll_events[sock->fd] = 0;
+#endif /* if defined(USE_EPOLL) */
+#ifdef USE_DEVPOLL
+ INSIST(thread->fdpollinfo[sock->fd].want_read == 0 &&
+ thread->fdpollinfo[sock->fd].want_write == 0);
+#endif /* ifdef USE_DEVPOLL */
+ UNLOCK(&thread->fdlock[lockid]);
+
+#ifdef USE_SELECT
+ LOCK(&sock->manager->lock);
+ if (thread->maxfd < sock->fd) {
+ thread->maxfd = sock->fd;
+ }
+ UNLOCK(&sock->manager->lock);
+#endif /* ifdef USE_SELECT */
+ }
+
+ return (result);
+}
+
+/*
+ * Attach to a socket. Caller must explicitly detach when it is done.
+ */
+void
+isc_socket_attach(isc_socket_t *sock, isc_socket_t **socketp) {
+ REQUIRE(VALID_SOCKET(sock));
+ REQUIRE(socketp != NULL && *socketp == NULL);
+
+ int old_refs = isc_refcount_increment(&sock->references);
+ REQUIRE(old_refs > 0);
+
+ *socketp = sock;
+}
+
+/*
+ * Dereference a socket. If this is the last reference to it, clean things
+ * up by destroying the socket.
+ */
+void
+isc_socket_detach(isc_socket_t **socketp) {
+ isc_socket_t *sock;
+
+ REQUIRE(socketp != NULL);
+ sock = *socketp;
+ REQUIRE(VALID_SOCKET(sock));
+ if (isc_refcount_decrement(&sock->references) == 1) {
+ destroy(&sock);
+ }
+
+ *socketp = NULL;
+}
+
+isc_result_t
+isc_socket_close(isc_socket_t *sock) {
+ int fd;
+ isc_socketmgr_t *manager;
+ isc__socketthread_t *thread;
+ fflush(stdout);
+ REQUIRE(VALID_SOCKET(sock));
+
+ LOCK(&sock->lock);
+
+ REQUIRE(sock->fd >= 0 && sock->fd < (int)sock->manager->maxsocks);
+
+ INSIST(!sock->connecting);
+ INSIST(ISC_LIST_EMPTY(sock->recv_list));
+ INSIST(ISC_LIST_EMPTY(sock->send_list));
+ INSIST(ISC_LIST_EMPTY(sock->accept_list));
+ INSIST(ISC_LIST_EMPTY(sock->connect_list));
+
+ manager = sock->manager;
+ thread = &manager->threads[sock->threadid];
+ fd = sock->fd;
+ sock->fd = -1;
+ sock->threadid = -1;
+
+ sock->dupped = 0;
+ memset(sock->name, 0, sizeof(sock->name));
+ sock->tag = NULL;
+ sock->listener = 0;
+ sock->connected = 0;
+ sock->connecting = 0;
+ sock->bound = 0;
+ isc_sockaddr_any(&sock->peer_address);
+
+ UNLOCK(&sock->lock);
+
+ socketclose(thread, sock, fd);
+
+ return (ISC_R_SUCCESS);
+}
+
+/*
+ * Dequeue an item off the given socket's read queue, set the result code
+ * in the done event to the one provided, and send it to the task it was
+ * destined for.
+ *
+ * If the event to be sent is on a list, remove it before sending. If
+ * asked to, send and detach from the socket as well.
+ *
+ * Caller must have the socket locked if the event is attached to the socket.
+ */
+static void
+send_recvdone_event(isc_socket_t *sock, isc_socketevent_t **dev) {
+ isc_task_t *task;
+
+ task = (*dev)->ev_sender;
+
+ (*dev)->ev_sender = sock;
+
+ if (ISC_LINK_LINKED(*dev, ev_link)) {
+ ISC_LIST_DEQUEUE(sock->recv_list, *dev, ev_link);
+ }
+
+ if (((*dev)->attributes & ISC_SOCKEVENTATTR_ATTACHED) != 0) {
+ isc_task_sendtoanddetach(&task, (isc_event_t **)dev,
+ sock->threadid);
+ } else {
+ isc_task_sendto(task, (isc_event_t **)dev, sock->threadid);
+ }
+}
+
+/*
+ * See comments for send_recvdone_event() above.
+ *
+ * Caller must have the socket locked if the event is attached to the socket.
+ */
+static void
+send_senddone_event(isc_socket_t *sock, isc_socketevent_t **dev) {
+ isc_task_t *task;
+
+ INSIST(dev != NULL && *dev != NULL);
+
+ task = (*dev)->ev_sender;
+ (*dev)->ev_sender = sock;
+
+ if (ISC_LINK_LINKED(*dev, ev_link)) {
+ ISC_LIST_DEQUEUE(sock->send_list, *dev, ev_link);
+ }
+
+ if (((*dev)->attributes & ISC_SOCKEVENTATTR_ATTACHED) != 0) {
+ isc_task_sendtoanddetach(&task, (isc_event_t **)dev,
+ sock->threadid);
+ } else {
+ isc_task_sendto(task, (isc_event_t **)dev, sock->threadid);
+ }
+}
+
+/*
+ * See comments for send_recvdone_event() above.
+ *
+ * Caller must have the socket locked if the event is attached to the socket.
+ */
+static void
+send_connectdone_event(isc_socket_t *sock, isc_socket_connev_t **dev) {
+ isc_task_t *task;
+
+ INSIST(dev != NULL && *dev != NULL);
+
+ task = (*dev)->ev_sender;
+ (*dev)->ev_sender = sock;
+
+ if (ISC_LINK_LINKED(*dev, ev_link)) {
+ ISC_LIST_DEQUEUE(sock->connect_list, *dev, ev_link);
+ }
+
+ isc_task_sendtoanddetach(&task, (isc_event_t **)dev, sock->threadid);
+}
+
+/*
+ * Call accept() on a socket, to get the new file descriptor. The listen
+ * socket is used as a prototype to create a new isc_socket_t. The new
+ * socket has one outstanding reference. The task receiving the event
+ * will be detached from just after the event is delivered.
+ *
+ * On entry to this function, the event delivered is the internal
+ * readable event, and the first item on the accept_list should be
+ * the done event we want to send. If the list is empty, this is a no-op,
+ * so just unlock and return.
+ */
+static void
+internal_accept(isc_socket_t *sock) {
+ isc_socketmgr_t *manager;
+ isc__socketthread_t *thread, *nthread;
+ isc_socket_newconnev_t *dev;
+ isc_task_t *task;
+ socklen_t addrlen;
+ int fd;
+ isc_result_t result = ISC_R_SUCCESS;
+ char strbuf[ISC_STRERRORSIZE];
+ const char *err = "accept";
+
+ INSIST(VALID_SOCKET(sock));
+ REQUIRE(sock->fd >= 0);
+
+ socket_log(sock, NULL, TRACE, "internal_accept called, locked socket");
+
+ manager = sock->manager;
+ INSIST(VALID_MANAGER(manager));
+ thread = &manager->threads[sock->threadid];
+
+ INSIST(sock->listener);
+
+ /*
+ * Get the first item off the accept list.
+ * If it is empty, unlock the socket and return.
+ */
+ dev = ISC_LIST_HEAD(sock->accept_list);
+ if (dev == NULL) {
+ unwatch_fd(thread, sock->fd, SELECT_POKE_ACCEPT);
+ UNLOCK(&sock->lock);
+ return;
+ }
+
+ /*
+ * Try to accept the new connection. If the accept fails with
+ * EAGAIN or EINTR, simply poke the watcher to watch this socket
+ * again. Also ignore ECONNRESET, which has been reported to
+ * be spuriously returned on Linux 2.2.19 although it is not
+ * a documented error for accept(). ECONNABORTED has been
+ * reported for Solaris 8. The rest are thrown in not because
+ * we have seen them but because they are ignored by other
+ * daemons such as BIND 8 and Apache.
+ */
+
+ addrlen = sizeof(NEWCONNSOCK(dev)->peer_address.type);
+ memset(&NEWCONNSOCK(dev)->peer_address.type, 0, addrlen);
+ fd = accept(sock->fd, &NEWCONNSOCK(dev)->peer_address.type.sa,
+ (void *)&addrlen);
+
+#ifdef F_DUPFD
+ /*
+ * Leave a space for stdio to work in.
+ */
+ if (fd >= 0 && fd < 20) {
+ int newfd, tmp;
+ newfd = fcntl(fd, F_DUPFD, 20);
+ tmp = errno;
+ (void)close(fd);
+ errno = tmp;
+ fd = newfd;
+ err = "accept/fcntl";
+ }
+#endif /* ifdef F_DUPFD */
+
+ if (fd < 0) {
+ if (SOFT_ERROR(errno)) {
+ goto soft_error;
+ }
+ switch (errno) {
+ case ENFILE:
+ case EMFILE:
+ isc_log_write(isc_lctx, ISC_LOGCATEGORY_GENERAL,
+ ISC_LOGMODULE_SOCKET, ISC_LOG_ERROR,
+ "%s: too many open file descriptors",
+ err);
+ goto soft_error;
+
+ case ENOBUFS:
+ case ENOMEM:
+ case ECONNRESET:
+ case ECONNABORTED:
+ case EHOSTUNREACH:
+ case EHOSTDOWN:
+ case ENETUNREACH:
+ case ENETDOWN:
+ case ECONNREFUSED:
+#ifdef EPROTO
+ case EPROTO:
+#endif /* ifdef EPROTO */
+#ifdef ENONET
+ case ENONET:
+#endif /* ifdef ENONET */
+ goto soft_error;
+ default:
+ break;
+ }
+ strerror_r(errno, strbuf, sizeof(strbuf));
+ UNEXPECTED_ERROR(__FILE__, __LINE__,
+ "internal_accept: %s() failed: %s", err,
+ strbuf);
+ fd = -1;
+ result = ISC_R_UNEXPECTED;
+ } else {
+ if (addrlen == 0U) {
+ UNEXPECTED_ERROR(__FILE__, __LINE__,
+ "internal_accept(): "
+ "accept() failed to return "
+ "remote address");
+
+ (void)close(fd);
+ goto soft_error;
+ } else if (NEWCONNSOCK(dev)->peer_address.type.sa.sa_family !=
+ sock->pf)
+ {
+ UNEXPECTED_ERROR(
+ __FILE__, __LINE__,
+ "internal_accept(): "
+ "accept() returned peer address "
+ "family %u (expected %u)",
+ NEWCONNSOCK(dev)->peer_address.type.sa.sa_family,
+ sock->pf);
+ (void)close(fd);
+ goto soft_error;
+ } else if (fd >= (int)manager->maxsocks) {
+ isc_log_write(isc_lctx, ISC_LOGCATEGORY_GENERAL,
+ ISC_LOGMODULE_SOCKET, ISC_LOG_ERROR,
+ "accept: file descriptor exceeds limit "
+ "(%d/%u)",
+ fd, manager->maxsocks);
+ (void)close(fd);
+ goto soft_error;
+ }
+ }
+
+ if (fd != -1) {
+ NEWCONNSOCK(dev)->peer_address.length = addrlen;
+ NEWCONNSOCK(dev)->pf = sock->pf;
+ }
+
+ /*
+ * Pull off the done event.
+ */
+ ISC_LIST_UNLINK(sock->accept_list, dev, ev_link);
+
+ /*
+ * Poke watcher if there are more pending accepts.
+ */
+ if (ISC_LIST_EMPTY(sock->accept_list)) {
+ unwatch_fd(thread, sock->fd, SELECT_POKE_ACCEPT);
+ }
+
+ if (fd != -1) {
+ result = make_nonblock(fd);
+ if (result != ISC_R_SUCCESS) {
+ (void)close(fd);
+ fd = -1;
+ }
+ }
+
+ /*
+ * We need to unlock sock->lock now to be able to lock manager->lock
+ * without risking a deadlock with xmlstats.
+ */
+ UNLOCK(&sock->lock);
+
+ /*
+ * -1 means the new socket didn't happen.
+ */
+ if (fd != -1) {
+ int lockid = FDLOCK_ID(fd);
+
+ NEWCONNSOCK(dev)->fd = fd;
+ NEWCONNSOCK(dev)->threadid = gen_threadid(NEWCONNSOCK(dev));
+ NEWCONNSOCK(dev)->bound = 1;
+ NEWCONNSOCK(dev)->connected = 1;
+ nthread = &manager->threads[NEWCONNSOCK(dev)->threadid];
+
+ /*
+ * We already hold a lock on one fdlock in accepting thread,
+ * we need to make sure that we don't double lock.
+ */
+ bool same_bucket = (sock->threadid ==
+ NEWCONNSOCK(dev)->threadid) &&
+ (FDLOCK_ID(sock->fd) == lockid);
+
+ /*
+ * Use minimum mtu if possible.
+ */
+ use_min_mtu(NEWCONNSOCK(dev));
+ set_tcp_maxseg(NEWCONNSOCK(dev), 1280 - 20 - 40);
+
+ /*
+ * Ensure DSCP settings are inherited across accept.
+ */
+ setdscp(NEWCONNSOCK(dev), sock->dscp);
+
+ /*
+ * Save away the remote address
+ */
+ dev->address = NEWCONNSOCK(dev)->peer_address;
+
+ if (NEWCONNSOCK(dev)->active == 0) {
+ inc_stats(manager->stats,
+ NEWCONNSOCK(dev)->statsindex[STATID_ACTIVE]);
+ NEWCONNSOCK(dev)->active = 1;
+ }
+
+ if (!same_bucket) {
+ LOCK(&nthread->fdlock[lockid]);
+ }
+ nthread->fds[fd] = NEWCONNSOCK(dev);
+ nthread->fdstate[fd] = MANAGED;
+#if defined(USE_EPOLL)
+ nthread->epoll_events[fd] = 0;
+#endif /* if defined(USE_EPOLL) */
+ if (!same_bucket) {
+ UNLOCK(&nthread->fdlock[lockid]);
+ }
+
+ LOCK(&manager->lock);
+
+#ifdef USE_SELECT
+ if (nthread->maxfd < fd) {
+ nthread->maxfd = fd;
+ }
+#endif /* ifdef USE_SELECT */
+
+ socket_log(sock, &NEWCONNSOCK(dev)->peer_address, CREATION,
+ "accepted connection, new socket %p",
+ dev->newsocket);
+
+ ISC_LIST_APPEND(manager->socklist, NEWCONNSOCK(dev), link);
+
+ UNLOCK(&manager->lock);
+
+ inc_stats(manager->stats, sock->statsindex[STATID_ACCEPT]);
+ } else {
+ inc_stats(manager->stats, sock->statsindex[STATID_ACCEPTFAIL]);
+ isc_refcount_decrementz(&NEWCONNSOCK(dev)->references);
+ free_socket((isc_socket_t **)&dev->newsocket);
+ }
+
+ /*
+ * Fill in the done event details and send it off.
+ */
+ dev->result = result;
+ task = dev->ev_sender;
+ dev->ev_sender = sock;
+
+ isc_task_sendtoanddetach(&task, ISC_EVENT_PTR(&dev), sock->threadid);
+ return;
+
+soft_error:
+ watch_fd(thread, sock->fd, SELECT_POKE_ACCEPT);
+ UNLOCK(&sock->lock);
+
+ inc_stats(manager->stats, sock->statsindex[STATID_ACCEPTFAIL]);
+ return;
+}
+
+static void
+internal_recv(isc_socket_t *sock) {
+ isc_socketevent_t *dev;
+
+ INSIST(VALID_SOCKET(sock));
+ REQUIRE(sock->fd >= 0);
+
+ dev = ISC_LIST_HEAD(sock->recv_list);
+ if (dev == NULL) {
+ goto finish;
+ }
+
+ socket_log(sock, NULL, IOEVENT, "internal_recv: event %p -> task %p",
+ dev, dev->ev_sender);
+
+ /*
+ * Try to do as much I/O as possible on this socket. There are no
+ * limits here, currently.
+ */
+ while (dev != NULL) {
+ switch (doio_recv(sock, dev)) {
+ case DOIO_SOFT:
+ goto finish;
+
+ case DOIO_EOF:
+ /*
+ * read of 0 means the remote end was closed.
+ * Run through the event queue and dispatch all
+ * the events with an EOF result code.
+ */
+ do {
+ dev->result = ISC_R_EOF;
+ send_recvdone_event(sock, &dev);
+ dev = ISC_LIST_HEAD(sock->recv_list);
+ } while (dev != NULL);
+ goto finish;
+
+ case DOIO_SUCCESS:
+ case DOIO_HARD:
+ send_recvdone_event(sock, &dev);
+ break;
+ }
+
+ dev = ISC_LIST_HEAD(sock->recv_list);
+ }
+
+finish:
+ if (ISC_LIST_EMPTY(sock->recv_list)) {
+ unwatch_fd(&sock->manager->threads[sock->threadid], sock->fd,
+ SELECT_POKE_READ);
+ }
+}
+
+static void
+internal_send(isc_socket_t *sock) {
+ isc_socketevent_t *dev;
+
+ INSIST(VALID_SOCKET(sock));
+ REQUIRE(sock->fd >= 0);
+
+ dev = ISC_LIST_HEAD(sock->send_list);
+ if (dev == NULL) {
+ goto finish;
+ }
+ socket_log(sock, NULL, EVENT, "internal_send: event %p -> task %p", dev,
+ dev->ev_sender);
+
+ /*
+ * Try to do as much I/O as possible on this socket. There are no
+ * limits here, currently.
+ */
+ while (dev != NULL) {
+ switch (doio_send(sock, dev)) {
+ case DOIO_SOFT:
+ goto finish;
+
+ case DOIO_HARD:
+ case DOIO_SUCCESS:
+ send_senddone_event(sock, &dev);
+ break;
+ }
+
+ dev = ISC_LIST_HEAD(sock->send_list);
+ }
+
+finish:
+ if (ISC_LIST_EMPTY(sock->send_list)) {
+ unwatch_fd(&sock->manager->threads[sock->threadid], sock->fd,
+ SELECT_POKE_WRITE);
+ }
+}
+
+/*
+ * Process read/writes on each fd here. Avoid locking
+ * and unlocking twice if both reads and writes are possible.
+ */
+static void
+process_fd(isc__socketthread_t *thread, int fd, bool readable, bool writeable) {
+ isc_socket_t *sock;
+ int lockid = FDLOCK_ID(fd);
+
+ /*
+ * If the socket is going to be closed, don't do more I/O.
+ */
+ LOCK(&thread->fdlock[lockid]);
+ if (thread->fdstate[fd] == CLOSE_PENDING) {
+ UNLOCK(&thread->fdlock[lockid]);
+
+ (void)unwatch_fd(thread, fd, SELECT_POKE_READ);
+ (void)unwatch_fd(thread, fd, SELECT_POKE_WRITE);
+ return;
+ }
+
+ sock = thread->fds[fd];
+ if (sock == NULL) {
+ UNLOCK(&thread->fdlock[lockid]);
+ return;
+ }
+
+ LOCK(&sock->lock);
+
+ if (sock->fd < 0) {
+ /*
+ * Sock is being closed - the final external reference
+ * is gone but it was not yet removed from event loop
+ * and fdstate[]/fds[] as destroy() is waiting on
+ * thread->fdlock[lockid] or sock->lock that we're holding.
+ * Just release the locks and bail.
+ */
+ UNLOCK(&sock->lock);
+ UNLOCK(&thread->fdlock[lockid]);
+ return;
+ }
+
+ REQUIRE(readable || writeable);
+ if (writeable) {
+ if (sock->connecting) {
+ internal_connect(sock);
+ } else {
+ internal_send(sock);
+ }
+ }
+
+ if (readable) {
+ if (sock->listener) {
+ internal_accept(sock); /* unlocks sock */
+ } else {
+ internal_recv(sock);
+ UNLOCK(&sock->lock);
+ }
+ } else {
+ UNLOCK(&sock->lock);
+ }
+
+ UNLOCK(&thread->fdlock[lockid]);
+
+ /*
+ * Socket destruction might be pending, it will resume
+ * after releasing fdlock and sock->lock.
+ */
+}
+
+/*
+ * process_fds is different for different event loops
+ * it takes the events from event loops and for each FD
+ * launches process_fd
+ */
+#ifdef USE_KQUEUE
+static bool
+process_fds(isc__socketthread_t *thread, struct kevent *events, int nevents) {
+ int i;
+ bool readable, writable;
+ bool done = false;
+ bool have_ctlevent = false;
+ if (nevents == thread->nevents) {
+ /*
+ * This is not an error, but something unexpected. If this
+ * happens, it may indicate the need for increasing
+ * ISC_SOCKET_MAXEVENTS.
+ */
+ thread_log(thread, ISC_LOGCATEGORY_GENERAL,
+ ISC_LOGMODULE_SOCKET, ISC_LOG_INFO,
+ "maximum number of FD events (%d) received",
+ nevents);
+ }
+
+ for (i = 0; i < nevents; i++) {
+ REQUIRE(events[i].ident < thread->manager->maxsocks);
+ if (events[i].ident == (uintptr_t)thread->pipe_fds[0]) {
+ have_ctlevent = true;
+ continue;
+ }
+ readable = (events[i].filter == EVFILT_READ);
+ writable = (events[i].filter == EVFILT_WRITE);
+ process_fd(thread, events[i].ident, readable, writable);
+ }
+
+ if (have_ctlevent) {
+ done = process_ctlfd(thread);
+ }
+
+ return (done);
+}
+#elif defined(USE_EPOLL)
+static bool
+process_fds(isc__socketthread_t *thread, struct epoll_event *events,
+ int nevents) {
+ int i;
+ bool done = false;
+ bool have_ctlevent = false;
+
+ if (nevents == thread->nevents) {
+ thread_log(thread, ISC_LOGCATEGORY_GENERAL,
+ ISC_LOGMODULE_SOCKET, ISC_LOG_INFO,
+ "maximum number of FD events (%d) received",
+ nevents);
+ }
+
+ for (i = 0; i < nevents; i++) {
+ REQUIRE(events[i].data.fd < (int)thread->manager->maxsocks);
+ if (events[i].data.fd == thread->pipe_fds[0]) {
+ have_ctlevent = true;
+ continue;
+ }
+ if ((events[i].events & EPOLLERR) != 0 ||
+ (events[i].events & EPOLLHUP) != 0)
+ {
+ /*
+ * epoll does not set IN/OUT bits on an erroneous
+ * condition, so we need to try both anyway. This is a
+ * bit inefficient, but should be okay for such rare
+ * events. Note also that the read or write attempt
+ * won't block because we use non-blocking sockets.
+ */
+ int fd = events[i].data.fd;
+ events[i].events |= thread->epoll_events[fd];
+ }
+ process_fd(thread, events[i].data.fd,
+ (events[i].events & EPOLLIN) != 0,
+ (events[i].events & EPOLLOUT) != 0);
+ }
+
+ if (have_ctlevent) {
+ done = process_ctlfd(thread);
+ }
+
+ return (done);
+}
+#elif defined(USE_DEVPOLL)
+static bool
+process_fds(isc__socketthread_t *thread, struct pollfd *events, int nevents) {
+ int i;
+ bool done = false;
+ bool have_ctlevent = false;
+
+ if (nevents == thread->nevents) {
+ thread_log(thread, ISC_LOGCATEGORY_GENERAL,
+ ISC_LOGMODULE_SOCKET, ISC_LOG_INFO,
+ "maximum number of FD events (%d) received",
+ nevents);
+ }
+
+ for (i = 0; i < nevents; i++) {
+ REQUIRE(events[i].fd < (int)thread->manager->maxsocks);
+ if (events[i].fd == thread->pipe_fds[0]) {
+ have_ctlevent = true;
+ continue;
+ }
+ process_fd(thread, events[i].fd,
+ (events[i].events & POLLIN) != 0,
+ (events[i].events & POLLOUT) != 0);
+ }
+
+ if (have_ctlevent) {
+ done = process_ctlfd(thread);
+ }
+
+ return (done);
+}
+#elif defined(USE_SELECT)
+static void
+process_fds(isc__socketthread_t *thread, int maxfd, fd_set *readfds,
+ fd_set *writefds) {
+ int i;
+
+ REQUIRE(maxfd <= (int)thread->manager->maxsocks);
+
+ for (i = 0; i < maxfd; i++) {
+ if (i == thread->pipe_fds[0] || i == thread->pipe_fds[1]) {
+ continue;
+ }
+ process_fd(thread, i, FD_ISSET(i, readfds),
+ FD_ISSET(i, writefds));
+ }
+}
+#endif /* ifdef USE_KQUEUE */
+
+static bool
+process_ctlfd(isc__socketthread_t *thread) {
+ int msg, fd;
+
+ for (;;) {
+ select_readmsg(thread, &fd, &msg);
+
+ thread_log(thread, IOEVENT,
+ "watcher got message %d for socket %d", msg, fd);
+
+ /*
+ * Nothing to read?
+ */
+ if (msg == SELECT_POKE_NOTHING) {
+ break;
+ }
+
+ /*
+ * Handle shutdown message. We really should
+ * jump out of this loop right away, but
+ * it doesn't matter if we have to do a little
+ * more work first.
+ */
+ if (msg == SELECT_POKE_SHUTDOWN) {
+ return (true);
+ }
+
+ /*
+ * This is a wakeup on a socket. Look
+ * at the event queue for both read and write,
+ * and decide if we need to watch on it now
+ * or not.
+ */
+ wakeup_socket(thread, fd, msg);
+ }
+
+ return (false);
+}
+
+/*
+ * This is the thread that will loop forever, always in a select or poll
+ * call.
+ *
+ * When select returns something to do, do whatever's necessary and post
+ * an event to the task that was requesting the action.
+ */
+static isc_threadresult_t
+netthread(void *uap) {
+ isc__socketthread_t *thread = uap;
+ isc_socketmgr_t *manager = thread->manager;
+ (void)manager;
+ bool done;
+ int cc;
+#ifdef USE_KQUEUE
+ const char *fnname = "kevent()";
+#elif defined(USE_EPOLL)
+ const char *fnname = "epoll_wait()";
+#elif defined(USE_DEVPOLL)
+ isc_result_t result;
+ const char *fnname = "ioctl(DP_POLL)";
+ struct dvpoll dvp;
+ int pass;
+#if defined(ISC_SOCKET_USE_POLLWATCH)
+ pollstate_t pollstate = poll_idle;
+#endif /* if defined(ISC_SOCKET_USE_POLLWATCH) */
+#elif defined(USE_SELECT)
+ const char *fnname = "select()";
+ int maxfd;
+ int ctlfd;
+#endif /* ifdef USE_KQUEUE */
+ char strbuf[ISC_STRERRORSIZE];
+
+#if defined(USE_SELECT)
+ /*
+ * Get the control fd here. This will never change.
+ */
+ ctlfd = thread->pipe_fds[0];
+#endif /* if defined(USE_SELECT) */
+ done = false;
+ while (!done) {
+ do {
+#ifdef USE_KQUEUE
+ cc = kevent(thread->kqueue_fd, NULL, 0, thread->events,
+ thread->nevents, NULL);
+#elif defined(USE_EPOLL)
+ cc = epoll_wait(thread->epoll_fd, thread->events,
+ thread->nevents, -1);
+#elif defined(USE_DEVPOLL)
+ /*
+ * Re-probe every thousand calls.
+ */
+ if (thread->calls++ > 1000U) {
+ result = isc_resource_getcurlimit(
+ isc_resource_openfiles,
+ &thread->open_max);
+ if (result != ISC_R_SUCCESS) {
+ thread->open_max = 64;
+ }
+ thread->calls = 0;
+ }
+ for (pass = 0; pass < 2; pass++) {
+ dvp.dp_fds = thread->events;
+ dvp.dp_nfds = thread->nevents;
+ if (dvp.dp_nfds >= thread->open_max) {
+ dvp.dp_nfds = thread->open_max - 1;
+ }
+#ifndef ISC_SOCKET_USE_POLLWATCH
+ dvp.dp_timeout = -1;
+#else /* ifndef ISC_SOCKET_USE_POLLWATCH */
+ if (pollstate == poll_idle) {
+ dvp.dp_timeout = -1;
+ } else {
+ dvp.dp_timeout =
+ ISC_SOCKET_POLLWATCH_TIMEOUT;
+ }
+#endif /* ISC_SOCKET_USE_POLLWATCH */
+ cc = ioctl(thread->devpoll_fd, DP_POLL, &dvp);
+ if (cc == -1 && errno == EINVAL) {
+ /*
+ * {OPEN_MAX} may have dropped. Look
+ * up the current value and try again.
+ */
+ result = isc_resource_getcurlimit(
+ isc_resource_openfiles,
+ &thread->open_max);
+ if (result != ISC_R_SUCCESS) {
+ thread->open_max = 64;
+ }
+ } else {
+ break;
+ }
+ }
+#elif defined(USE_SELECT)
+ /*
+ * We will have only one thread anyway, we can lock
+ * manager lock and don't care
+ */
+ LOCK(&manager->lock);
+ memmove(thread->read_fds_copy, thread->read_fds,
+ thread->fd_bufsize);
+ memmove(thread->write_fds_copy, thread->write_fds,
+ thread->fd_bufsize);
+ maxfd = thread->maxfd + 1;
+ UNLOCK(&manager->lock);
+
+ cc = select(maxfd, thread->read_fds_copy,
+ thread->write_fds_copy, NULL, NULL);
+#endif /* USE_KQUEUE */
+
+ if (cc < 0 && !SOFT_ERROR(errno)) {
+ strerror_r(errno, strbuf, sizeof(strbuf));
+ FATAL_ERROR(__FILE__, __LINE__, "%s failed: %s",
+ fnname, strbuf);
+ }
+
+#if defined(USE_DEVPOLL) && defined(ISC_SOCKET_USE_POLLWATCH)
+ if (cc == 0) {
+ if (pollstate == poll_active) {
+ pollstate = poll_checking;
+ } else if (pollstate == poll_checking) {
+ pollstate = poll_idle;
+ }
+ } else if (cc > 0) {
+ if (pollstate == poll_checking) {
+ /*
+ * XXX: We'd like to use a more
+ * verbose log level as it's actually an
+ * unexpected event, but the kernel bug
+ * reportedly happens pretty frequently
+ * (and it can also be a false positive)
+ * so it would be just too noisy.
+ */
+ thread_log(thread,
+ ISC_LOGCATEGORY_GENERAL,
+ ISC_LOGMODULE_SOCKET,
+ ISC_LOG_DEBUG(1),
+ "unexpected POLL timeout");
+ }
+ pollstate = poll_active;
+ }
+#endif /* if defined(USE_DEVPOLL) && defined(ISC_SOCKET_USE_POLLWATCH) */
+ } while (cc < 0);
+
+#if defined(USE_KQUEUE) || defined(USE_EPOLL) || defined(USE_DEVPOLL)
+ done = process_fds(thread, thread->events, cc);
+#elif defined(USE_SELECT)
+ process_fds(thread, maxfd, thread->read_fds_copy,
+ thread->write_fds_copy);
+
+ /*
+ * Process reads on internal, control fd.
+ */
+ if (FD_ISSET(ctlfd, thread->read_fds_copy)) {
+ done = process_ctlfd(thread);
+ }
+#endif /* if defined(USE_KQUEUE) || defined(USE_EPOLL) || defined(USE_DEVPOLL) \
+ * */
+ }
+
+ thread_log(thread, TRACE, "watcher exiting");
+ return ((isc_threadresult_t)0);
+}
+
+void
+isc_socketmgr_setreserved(isc_socketmgr_t *manager, uint32_t reserved) {
+ REQUIRE(VALID_MANAGER(manager));
+
+ manager->reserved = reserved;
+}
+
+void
+isc_socketmgr_maxudp(isc_socketmgr_t *manager, unsigned int maxudp) {
+ REQUIRE(VALID_MANAGER(manager));
+
+ manager->maxudp = maxudp;
+}
+
+/*
+ * Setup socket thread, thread->manager and thread->threadid must be filled.
+ */
+
+static isc_result_t
+setup_thread(isc__socketthread_t *thread) {
+ isc_result_t result = ISC_R_SUCCESS;
+ int i;
+ char strbuf[ISC_STRERRORSIZE];
+
+ REQUIRE(thread != NULL);
+ REQUIRE(VALID_MANAGER(thread->manager));
+ REQUIRE(thread->threadid >= 0 &&
+ thread->threadid < thread->manager->nthreads);
+
+ thread->fds =
+ isc_mem_get(thread->manager->mctx,
+ thread->manager->maxsocks * sizeof(isc_socket_t *));
+
+ memset(thread->fds, 0,
+ thread->manager->maxsocks * sizeof(isc_socket_t *));
+
+ thread->fdstate = isc_mem_get(thread->manager->mctx,
+ thread->manager->maxsocks * sizeof(int));
+
+ memset(thread->fdstate, 0, thread->manager->maxsocks * sizeof(int));
+
+ thread->fdlock = isc_mem_get(thread->manager->mctx,
+ FDLOCK_COUNT * sizeof(isc_mutex_t));
+
+ for (i = 0; i < FDLOCK_COUNT; i++) {
+ isc_mutex_init(&thread->fdlock[i]);
+ }
+
+ if (pipe(thread->pipe_fds) != 0) {
+ strerror_r(errno, strbuf, sizeof(strbuf));
+ UNEXPECTED_ERROR(__FILE__, __LINE__, "pipe() failed: %s",
+ strbuf);
+ return (ISC_R_UNEXPECTED);
+ }
+ RUNTIME_CHECK(make_nonblock(thread->pipe_fds[0]) == ISC_R_SUCCESS);
+
+#ifdef USE_KQUEUE
+ thread->nevents = ISC_SOCKET_MAXEVENTS;
+ thread->events = isc_mem_get(thread->manager->mctx,
+ sizeof(struct kevent) * thread->nevents);
+
+ thread->kqueue_fd = kqueue();
+ if (thread->kqueue_fd == -1) {
+ result = isc__errno2result(errno);
+ strerror_r(errno, strbuf, sizeof(strbuf));
+ UNEXPECTED_ERROR(__FILE__, __LINE__, "kqueue failed: %s",
+ strbuf);
+ isc_mem_put(thread->manager->mctx, thread->events,
+ sizeof(struct kevent) * thread->nevents);
+ return (result);
+ }
+
+ result = watch_fd(thread, thread->pipe_fds[0], SELECT_POKE_READ);
+ if (result != ISC_R_SUCCESS) {
+ close(thread->kqueue_fd);
+ isc_mem_put(thread->manager->mctx, thread->events,
+ sizeof(struct kevent) * thread->nevents);
+ }
+ return (result);
+
+#elif defined(USE_EPOLL)
+ thread->nevents = ISC_SOCKET_MAXEVENTS;
+ thread->epoll_events =
+ isc_mem_get(thread->manager->mctx,
+ (thread->manager->maxsocks * sizeof(uint32_t)));
+
+ memset(thread->epoll_events, 0,
+ thread->manager->maxsocks * sizeof(uint32_t));
+
+ thread->events =
+ isc_mem_get(thread->manager->mctx,
+ sizeof(struct epoll_event) * thread->nevents);
+
+ thread->epoll_fd = epoll_create(thread->nevents);
+ if (thread->epoll_fd == -1) {
+ result = isc__errno2result(errno);
+ strerror_r(errno, strbuf, sizeof(strbuf));
+ UNEXPECTED_ERROR(__FILE__, __LINE__, "epoll_create failed: %s",
+ strbuf);
+ return (result);
+ }
+
+ result = watch_fd(thread, thread->pipe_fds[0], SELECT_POKE_READ);
+ return (result);
+
+#elif defined(USE_DEVPOLL)
+ thread->nevents = ISC_SOCKET_MAXEVENTS;
+ result = isc_resource_getcurlimit(isc_resource_openfiles,
+ &thread->open_max);
+ if (result != ISC_R_SUCCESS) {
+ thread->open_max = 64;
+ }
+ thread->calls = 0;
+ thread->events = isc_mem_get(thread->manager->mctx,
+ sizeof(struct pollfd) * thread->nevents);
+
+ /*
+ * Note: fdpollinfo should be able to support all possible FDs, so
+ * it must have maxsocks entries (not nevents).
+ */
+ thread->fdpollinfo =
+ isc_mem_get(thread->manager->mctx,
+ sizeof(pollinfo_t) * thread->manager->maxsocks);
+ memset(thread->fdpollinfo, 0,
+ sizeof(pollinfo_t) * thread->manager->maxsocks);
+ thread->devpoll_fd = open("/dev/poll", O_RDWR);
+ if (thread->devpoll_fd == -1) {
+ result = isc__errno2result(errno);
+ strerror_r(errno, strbuf, sizeof(strbuf));
+ UNEXPECTED_ERROR(__FILE__, __LINE__,
+ "open(/dev/poll) failed: %s", strbuf);
+ isc_mem_put(thread->manager->mctx, thread->events,
+ sizeof(struct pollfd) * thread->nevents);
+ isc_mem_put(thread->manager->mctx, thread->fdpollinfo,
+ sizeof(pollinfo_t) * thread->manager->maxsocks);
+ return (result);
+ }
+ result = watch_fd(thread, thread->pipe_fds[0], SELECT_POKE_READ);
+ if (result != ISC_R_SUCCESS) {
+ close(thread->devpoll_fd);
+ isc_mem_put(thread->manager->mctx, thread->events,
+ sizeof(struct pollfd) * thread->nevents);
+ isc_mem_put(thread->manager->mctx, thread->fdpollinfo,
+ sizeof(pollinfo_t) * thread->manager->maxsocks);
+ return (result);
+ }
+
+ return (ISC_R_SUCCESS);
+#elif defined(USE_SELECT)
+ UNUSED(result);
+
+#if ISC_SOCKET_MAXSOCKETS > FD_SETSIZE
+ /*
+ * Note: this code should also cover the case of MAXSOCKETS <=
+ * FD_SETSIZE, but we separate the cases to avoid possible portability
+ * issues regarding howmany() and the actual representation of fd_set.
+ */
+ thread->fd_bufsize = howmany(manager->maxsocks, NFDBITS) *
+ sizeof(fd_mask);
+#else /* if ISC_SOCKET_MAXSOCKETS > FD_SETSIZE */
+ thread->fd_bufsize = sizeof(fd_set);
+#endif /* if ISC_SOCKET_MAXSOCKETS > FD_SETSIZE */
+
+ thread->read_fds = isc_mem_get(thread->manager->mctx,
+ thread->fd_bufsize);
+ thread->read_fds_copy = isc_mem_get(thread->manager->mctx,
+ thread->fd_bufsize);
+ thread->write_fds = isc_mem_get(thread->manager->mctx,
+ thread->fd_bufsize);
+ thread->write_fds_copy = isc_mem_get(thread->manager->mctx,
+ thread->fd_bufsize);
+ memset(thread->read_fds, 0, thread->fd_bufsize);
+ memset(thread->write_fds, 0, thread->fd_bufsize);
+
+ (void)watch_fd(thread, thread->pipe_fds[0], SELECT_POKE_READ);
+ thread->maxfd = thread->pipe_fds[0];
+
+ return (ISC_R_SUCCESS);
+#endif /* USE_KQUEUE */
+}
+
+static void
+cleanup_thread(isc_mem_t *mctx, isc__socketthread_t *thread) {
+ isc_result_t result;
+ int i;
+
+ result = unwatch_fd(thread, thread->pipe_fds[0], SELECT_POKE_READ);
+ if (result != ISC_R_SUCCESS) {
+ UNEXPECTED_ERROR(__FILE__, __LINE__, "epoll_ctl(DEL) failed");
+ }
+#ifdef USE_KQUEUE
+ close(thread->kqueue_fd);
+ isc_mem_put(mctx, thread->events,
+ sizeof(struct kevent) * thread->nevents);
+#elif defined(USE_EPOLL)
+ close(thread->epoll_fd);
+
+ isc_mem_put(mctx, thread->events,
+ sizeof(struct epoll_event) * thread->nevents);
+#elif defined(USE_DEVPOLL)
+ close(thread->devpoll_fd);
+ isc_mem_put(mctx, thread->events,
+ sizeof(struct pollfd) * thread->nevents);
+ isc_mem_put(mctx, thread->fdpollinfo,
+ sizeof(pollinfo_t) * thread->manager->maxsocks);
+#elif defined(USE_SELECT)
+ if (thread->read_fds != NULL) {
+ isc_mem_put(mctx, thread->read_fds, thread->fd_bufsize);
+ }
+ if (thread->read_fds_copy != NULL) {
+ isc_mem_put(mctx, thread->read_fds_copy, thread->fd_bufsize);
+ }
+ if (thread->write_fds != NULL) {
+ isc_mem_put(mctx, thread->write_fds, thread->fd_bufsize);
+ }
+ if (thread->write_fds_copy != NULL) {
+ isc_mem_put(mctx, thread->write_fds_copy, thread->fd_bufsize);
+ }
+#endif /* USE_KQUEUE */
+ for (i = 0; i < (int)thread->manager->maxsocks; i++) {
+ if (thread->fdstate[i] == CLOSE_PENDING) {
+ /* no need to lock */
+ (void)close(i);
+ }
+ }
+
+#if defined(USE_EPOLL)
+ isc_mem_put(thread->manager->mctx, thread->epoll_events,
+ thread->manager->maxsocks * sizeof(uint32_t));
+#endif /* if defined(USE_EPOLL) */
+ isc_mem_put(thread->manager->mctx, thread->fds,
+ thread->manager->maxsocks * sizeof(isc_socket_t *));
+ isc_mem_put(thread->manager->mctx, thread->fdstate,
+ thread->manager->maxsocks * sizeof(int));
+
+ for (i = 0; i < FDLOCK_COUNT; i++) {
+ isc_mutex_destroy(&thread->fdlock[i]);
+ }
+ isc_mem_put(thread->manager->mctx, thread->fdlock,
+ FDLOCK_COUNT * sizeof(isc_mutex_t));
+}
+
+isc_result_t
+isc_socketmgr_create(isc_mem_t *mctx, isc_socketmgr_t **managerp) {
+ return (isc_socketmgr_create2(mctx, managerp, 0, 1));
+}
+
+isc_result_t
+isc_socketmgr_create2(isc_mem_t *mctx, isc_socketmgr_t **managerp,
+ unsigned int maxsocks, int nthreads) {
+ int i;
+ isc_socketmgr_t *manager;
+
+ REQUIRE(managerp != NULL && *managerp == NULL);
+
+ if (maxsocks == 0) {
+ maxsocks = ISC_SOCKET_MAXSOCKETS;
+ }
+
+ manager = isc_mem_get(mctx, sizeof(*manager));
+
+ /* zero-clear so that necessary cleanup on failure will be easy */
+ memset(manager, 0, sizeof(*manager));
+ manager->maxsocks = maxsocks;
+ manager->reserved = 0;
+ manager->maxudp = 0;
+ manager->nthreads = nthreads;
+ manager->stats = NULL;
+
+ manager->magic = SOCKET_MANAGER_MAGIC;
+ manager->mctx = NULL;
+ ISC_LIST_INIT(manager->socklist);
+ isc_mutex_init(&manager->lock);
+ isc_condition_init(&manager->shutdown_ok);
+
+ /*
+ * Start up the select/poll thread.
+ */
+ manager->threads = isc_mem_get(mctx, sizeof(isc__socketthread_t) *
+ manager->nthreads);
+ isc_mem_attach(mctx, &manager->mctx);
+
+ for (i = 0; i < manager->nthreads; i++) {
+ manager->threads[i].manager = manager;
+ manager->threads[i].threadid = i;
+ setup_thread(&manager->threads[i]);
+ isc_thread_create(netthread, &manager->threads[i],
+ &manager->threads[i].thread);
+ char tname[1024];
+ sprintf(tname, "isc-socket-%d", i);
+ isc_thread_setname(manager->threads[i].thread, tname);
+ }
+
+ *managerp = manager;
+
+ return (ISC_R_SUCCESS);
+}
+
+isc_result_t
+isc_socketmgr_getmaxsockets(isc_socketmgr_t *manager, unsigned int *nsockp) {
+ REQUIRE(VALID_MANAGER(manager));
+ REQUIRE(nsockp != NULL);
+
+ *nsockp = manager->maxsocks;
+
+ return (ISC_R_SUCCESS);
+}
+
+void
+isc_socketmgr_setstats(isc_socketmgr_t *manager, isc_stats_t *stats) {
+ REQUIRE(VALID_MANAGER(manager));
+ REQUIRE(ISC_LIST_EMPTY(manager->socklist));
+ REQUIRE(manager->stats == NULL);
+ REQUIRE(isc_stats_ncounters(stats) == isc_sockstatscounter_max);
+
+ isc_stats_attach(stats, &manager->stats);
+}
+
+void
+isc_socketmgr_destroy(isc_socketmgr_t **managerp) {
+ isc_socketmgr_t *manager;
+
+ /*
+ * Destroy a socket manager.
+ */
+
+ REQUIRE(managerp != NULL);
+ manager = *managerp;
+ REQUIRE(VALID_MANAGER(manager));
+
+ LOCK(&manager->lock);
+
+ /*
+ * Wait for all sockets to be destroyed.
+ */
+ while (!ISC_LIST_EMPTY(manager->socklist)) {
+ manager_log(manager, CREATION, "sockets exist");
+ WAIT(&manager->shutdown_ok, &manager->lock);
+ }
+
+ UNLOCK(&manager->lock);
+
+ /*
+ * Here, poke our select/poll thread. Do this by closing the write
+ * half of the pipe, which will send EOF to the read half.
+ * This is currently a no-op in the non-threaded case.
+ */
+ for (int i = 0; i < manager->nthreads; i++) {
+ select_poke(manager, i, 0, SELECT_POKE_SHUTDOWN);
+ }
+
+ /*
+ * Wait for thread to exit.
+ */
+ for (int i = 0; i < manager->nthreads; i++) {
+ isc_thread_join(manager->threads[i].thread, NULL);
+ cleanup_thread(manager->mctx, &manager->threads[i]);
+ }
+ /*
+ * Clean up.
+ */
+ isc_mem_put(manager->mctx, manager->threads,
+ sizeof(isc__socketthread_t) * manager->nthreads);
+ (void)isc_condition_destroy(&manager->shutdown_ok);
+
+ if (manager->stats != NULL) {
+ isc_stats_detach(&manager->stats);
+ }
+ isc_mutex_destroy(&manager->lock);
+ manager->magic = 0;
+ isc_mem_putanddetach(&manager->mctx, manager, sizeof(*manager));
+
+ *managerp = NULL;
+}
+
+static isc_result_t
+socket_recv(isc_socket_t *sock, isc_socketevent_t *dev, isc_task_t *task,
+ unsigned int flags) {
+ int io_state;
+ bool have_lock = false;
+ isc_task_t *ntask = NULL;
+ isc_result_t result = ISC_R_SUCCESS;
+
+ dev->ev_sender = task;
+
+ if (sock->type == isc_sockettype_udp) {
+ io_state = doio_recv(sock, dev);
+ } else {
+ LOCK(&sock->lock);
+ have_lock = true;
+
+ if (ISC_LIST_EMPTY(sock->recv_list)) {
+ io_state = doio_recv(sock, dev);
+ } else {
+ io_state = DOIO_SOFT;
+ }
+ }
+
+ switch (io_state) {
+ case DOIO_SOFT:
+ /*
+ * We couldn't read all or part of the request right now, so
+ * queue it.
+ *
+ * Attach to socket and to task
+ */
+ isc_task_attach(task, &ntask);
+ dev->attributes |= ISC_SOCKEVENTATTR_ATTACHED;
+
+ if (!have_lock) {
+ LOCK(&sock->lock);
+ have_lock = true;
+ }
+
+ /*
+ * Enqueue the request. If the socket was previously not being
+ * watched, poke the watcher to start paying attention to it.
+ */
+ bool do_poke = ISC_LIST_EMPTY(sock->recv_list);
+ ISC_LIST_ENQUEUE(sock->recv_list, dev, ev_link);
+ if (do_poke) {
+ select_poke(sock->manager, sock->threadid, sock->fd,
+ SELECT_POKE_READ);
+ }
+
+ socket_log(sock, NULL, EVENT,
+ "socket_recv: event %p -> task %p", dev, ntask);
+
+ if ((flags & ISC_SOCKFLAG_IMMEDIATE) != 0) {
+ result = ISC_R_INPROGRESS;
+ }
+ break;
+
+ case DOIO_EOF:
+ dev->result = ISC_R_EOF;
+ FALLTHROUGH;
+
+ case DOIO_HARD:
+ case DOIO_SUCCESS:
+ if ((flags & ISC_SOCKFLAG_IMMEDIATE) == 0) {
+ send_recvdone_event(sock, &dev);
+ }
+ break;
+ }
+
+ if (have_lock) {
+ UNLOCK(&sock->lock);
+ }
+
+ return (result);
+}
+
+isc_result_t
+isc_socket_recv(isc_socket_t *sock, isc_region_t *region, unsigned int minimum,
+ isc_task_t *task, isc_taskaction_t action, void *arg) {
+ isc_socketevent_t *dev;
+ isc_socketmgr_t *manager;
+
+ REQUIRE(VALID_SOCKET(sock));
+ REQUIRE(action != NULL);
+
+ manager = sock->manager;
+ REQUIRE(VALID_MANAGER(manager));
+
+ INSIST(sock->bound);
+
+ dev = allocate_socketevent(manager->mctx, sock, ISC_SOCKEVENT_RECVDONE,
+ action, arg);
+ if (dev == NULL) {
+ return (ISC_R_NOMEMORY);
+ }
+
+ return (isc_socket_recv2(sock, region, minimum, task, dev, 0));
+}
+
+isc_result_t
+isc_socket_recv2(isc_socket_t *sock, isc_region_t *region, unsigned int minimum,
+ isc_task_t *task, isc_socketevent_t *event,
+ unsigned int flags) {
+ event->ev_sender = sock;
+ event->result = ISC_R_UNSET;
+ event->region = *region;
+ event->n = 0;
+ event->offset = 0;
+ event->attributes = 0;
+
+ /*
+ * UDP sockets are always partial read.
+ */
+ if (sock->type == isc_sockettype_udp) {
+ event->minimum = 1;
+ } else {
+ if (minimum == 0) {
+ event->minimum = region->length;
+ } else {
+ event->minimum = minimum;
+ }
+ }
+
+ return (socket_recv(sock, event, task, flags));
+}
+
+static isc_result_t
+socket_send(isc_socket_t *sock, isc_socketevent_t *dev, isc_task_t *task,
+ const isc_sockaddr_t *address, struct in6_pktinfo *pktinfo,
+ unsigned int flags) {
+ int io_state;
+ bool have_lock = false;
+ isc_task_t *ntask = NULL;
+ isc_result_t result = ISC_R_SUCCESS;
+
+ dev->ev_sender = task;
+
+ set_dev_address(address, sock, dev);
+ if (pktinfo != NULL) {
+ dev->attributes |= ISC_SOCKEVENTATTR_PKTINFO;
+ dev->pktinfo = *pktinfo;
+
+ if (!isc_sockaddr_issitelocal(&dev->address) &&
+ !isc_sockaddr_islinklocal(&dev->address))
+ {
+ socket_log(sock, NULL, TRACE,
+ "pktinfo structure provided, ifindex %u "
+ "(set to 0)",
+ pktinfo->ipi6_ifindex);
+
+ /*
+ * Set the pktinfo index to 0 here, to let the
+ * kernel decide what interface it should send on.
+ */
+ dev->pktinfo.ipi6_ifindex = 0;
+ }
+ }
+
+ if (sock->type == isc_sockettype_udp) {
+ io_state = doio_send(sock, dev);
+ } else {
+ LOCK(&sock->lock);
+ have_lock = true;
+
+ if (ISC_LIST_EMPTY(sock->send_list)) {
+ io_state = doio_send(sock, dev);
+ } else {
+ io_state = DOIO_SOFT;
+ }
+ }
+
+ switch (io_state) {
+ case DOIO_SOFT:
+ /*
+ * We couldn't send all or part of the request right now, so
+ * queue it unless ISC_SOCKFLAG_NORETRY is set.
+ */
+ if ((flags & ISC_SOCKFLAG_NORETRY) == 0) {
+ isc_task_attach(task, &ntask);
+ dev->attributes |= ISC_SOCKEVENTATTR_ATTACHED;
+
+ if (!have_lock) {
+ LOCK(&sock->lock);
+ have_lock = true;
+ }
+
+ /*
+ * Enqueue the request. If the socket was previously
+ * not being watched, poke the watcher to start
+ * paying attention to it.
+ */
+ bool do_poke = ISC_LIST_EMPTY(sock->send_list);
+ ISC_LIST_ENQUEUE(sock->send_list, dev, ev_link);
+ if (do_poke) {
+ select_poke(sock->manager, sock->threadid,
+ sock->fd, SELECT_POKE_WRITE);
+ }
+ socket_log(sock, NULL, EVENT,
+ "socket_send: event %p -> task %p", dev,
+ ntask);
+
+ if ((flags & ISC_SOCKFLAG_IMMEDIATE) != 0) {
+ result = ISC_R_INPROGRESS;
+ }
+ break;
+ }
+
+ FALLTHROUGH;
+
+ case DOIO_HARD:
+ case DOIO_SUCCESS:
+ if (!have_lock) {
+ LOCK(&sock->lock);
+ have_lock = true;
+ }
+ if ((flags & ISC_SOCKFLAG_IMMEDIATE) == 0) {
+ send_senddone_event(sock, &dev);
+ }
+ break;
+ }
+
+ if (have_lock) {
+ UNLOCK(&sock->lock);
+ }
+
+ return (result);
+}
+
+isc_result_t
+isc_socket_send(isc_socket_t *sock, isc_region_t *region, isc_task_t *task,
+ isc_taskaction_t action, void *arg) {
+ /*
+ * REQUIRE() checking is performed in isc_socket_sendto().
+ */
+ return (isc_socket_sendto(sock, region, task, action, arg, NULL, NULL));
+}
+
+isc_result_t
+isc_socket_sendto(isc_socket_t *sock, isc_region_t *region, isc_task_t *task,
+ isc_taskaction_t action, void *arg,
+ const isc_sockaddr_t *address, struct in6_pktinfo *pktinfo) {
+ isc_socketevent_t *dev;
+ isc_socketmgr_t *manager;
+
+ REQUIRE(VALID_SOCKET(sock));
+ REQUIRE(region != NULL);
+ REQUIRE(task != NULL);
+ REQUIRE(action != NULL);
+
+ manager = sock->manager;
+ REQUIRE(VALID_MANAGER(manager));
+
+ INSIST(sock->bound);
+
+ dev = allocate_socketevent(manager->mctx, sock, ISC_SOCKEVENT_SENDDONE,
+ action, arg);
+ if (dev == NULL) {
+ return (ISC_R_NOMEMORY);
+ }
+
+ dev->region = *region;
+
+ return (socket_send(sock, dev, task, address, pktinfo, 0));
+}
+
+isc_result_t
+isc_socket_sendto2(isc_socket_t *sock, isc_region_t *region, isc_task_t *task,
+ const isc_sockaddr_t *address, struct in6_pktinfo *pktinfo,
+ isc_socketevent_t *event, unsigned int flags) {
+ REQUIRE(VALID_SOCKET(sock));
+ REQUIRE((flags & ~(ISC_SOCKFLAG_IMMEDIATE | ISC_SOCKFLAG_NORETRY)) ==
+ 0);
+ if ((flags & ISC_SOCKFLAG_NORETRY) != 0) {
+ REQUIRE(sock->type == isc_sockettype_udp);
+ }
+ event->ev_sender = sock;
+ event->result = ISC_R_UNSET;
+ event->region = *region;
+ event->n = 0;
+ event->offset = 0;
+ event->attributes &= ~ISC_SOCKEVENTATTR_ATTACHED;
+
+ return (socket_send(sock, event, task, address, pktinfo, flags));
+}
+
+void
+isc_socket_cleanunix(const isc_sockaddr_t *sockaddr, bool active) {
+#ifdef ISC_PLATFORM_HAVESYSUNH
+ int s;
+ struct stat sb;
+ char strbuf[ISC_STRERRORSIZE];
+
+ if (sockaddr->type.sa.sa_family != AF_UNIX) {
+ return;
+ }
+
+#ifndef S_ISSOCK
+#if defined(S_IFMT) && defined(S_IFSOCK)
+#define S_ISSOCK(mode) ((mode & S_IFMT) == S_IFSOCK)
+#elif defined(_S_IFMT) && defined(S_IFSOCK)
+#define S_ISSOCK(mode) ((mode & _S_IFMT) == S_IFSOCK)
+#endif /* if defined(S_IFMT) && defined(S_IFSOCK) */
+#endif /* ifndef S_ISSOCK */
+
+#ifndef S_ISFIFO
+#if defined(S_IFMT) && defined(S_IFIFO)
+#define S_ISFIFO(mode) ((mode & S_IFMT) == S_IFIFO)
+#elif defined(_S_IFMT) && defined(S_IFIFO)
+#define S_ISFIFO(mode) ((mode & _S_IFMT) == S_IFIFO)
+#endif /* if defined(S_IFMT) && defined(S_IFIFO) */
+#endif /* ifndef S_ISFIFO */
+
+#if !defined(S_ISFIFO) && !defined(S_ISSOCK)
+/* cppcheck-suppress preprocessorErrorDirective */
+#error \
+ You need to define S_ISFIFO and S_ISSOCK as appropriate for your platform. See <sys/stat.h>.
+#endif /* if !defined(S_ISFIFO) && !defined(S_ISSOCK) */
+
+#ifndef S_ISFIFO
+#define S_ISFIFO(mode) 0
+#endif /* ifndef S_ISFIFO */
+
+#ifndef S_ISSOCK
+#define S_ISSOCK(mode) 0
+#endif /* ifndef S_ISSOCK */
+
+ if (stat(sockaddr->type.sunix.sun_path, &sb) < 0) {
+ switch (errno) {
+ case ENOENT:
+ if (active) { /* We exited cleanly last time */
+ break;
+ }
+ FALLTHROUGH;
+ default:
+ strerror_r(errno, strbuf, sizeof(strbuf));
+ isc_log_write(isc_lctx, ISC_LOGCATEGORY_GENERAL,
+ ISC_LOGMODULE_SOCKET,
+ active ? ISC_LOG_ERROR : ISC_LOG_WARNING,
+ "isc_socket_cleanunix: stat(%s): %s",
+ sockaddr->type.sunix.sun_path, strbuf);
+ return;
+ }
+ } else {
+ if (!(S_ISSOCK(sb.st_mode) || S_ISFIFO(sb.st_mode))) {
+ isc_log_write(isc_lctx, ISC_LOGCATEGORY_GENERAL,
+ ISC_LOGMODULE_SOCKET,
+ active ? ISC_LOG_ERROR : ISC_LOG_WARNING,
+ "isc_socket_cleanunix: %s: not a socket",
+ sockaddr->type.sunix.sun_path);
+ return;
+ }
+ }
+
+ if (active) {
+ if (unlink(sockaddr->type.sunix.sun_path) < 0) {
+ strerror_r(errno, strbuf, sizeof(strbuf));
+ isc_log_write(isc_lctx, ISC_LOGCATEGORY_GENERAL,
+ ISC_LOGMODULE_SOCKET, ISC_LOG_ERROR,
+ "isc_socket_cleanunix: unlink(%s): %s",
+ sockaddr->type.sunix.sun_path, strbuf);
+ }
+ return;
+ }
+
+ s = socket(AF_UNIX, SOCK_STREAM, 0);
+ if (s < 0) {
+ strerror_r(errno, strbuf, sizeof(strbuf));
+ isc_log_write(isc_lctx, ISC_LOGCATEGORY_GENERAL,
+ ISC_LOGMODULE_SOCKET, ISC_LOG_WARNING,
+ "isc_socket_cleanunix: socket(%s): %s",
+ sockaddr->type.sunix.sun_path, strbuf);
+ return;
+ }
+
+ if (connect(s, (const struct sockaddr *)&sockaddr->type.sunix,
+ sizeof(sockaddr->type.sunix)) < 0)
+ {
+ switch (errno) {
+ case ECONNREFUSED:
+ case ECONNRESET:
+ if (unlink(sockaddr->type.sunix.sun_path) < 0) {
+ strerror_r(errno, strbuf, sizeof(strbuf));
+ isc_log_write(
+ isc_lctx, ISC_LOGCATEGORY_GENERAL,
+ ISC_LOGMODULE_SOCKET, ISC_LOG_WARNING,
+ "isc_socket_cleanunix: "
+ "unlink(%s): %s",
+ sockaddr->type.sunix.sun_path, strbuf);
+ }
+ break;
+ default:
+ strerror_r(errno, strbuf, sizeof(strbuf));
+ isc_log_write(isc_lctx, ISC_LOGCATEGORY_GENERAL,
+ ISC_LOGMODULE_SOCKET, ISC_LOG_WARNING,
+ "isc_socket_cleanunix: connect(%s): %s",
+ sockaddr->type.sunix.sun_path, strbuf);
+ break;
+ }
+ }
+ close(s);
+#else /* ifdef ISC_PLATFORM_HAVESYSUNH */
+ UNUSED(sockaddr);
+ UNUSED(active);
+#endif /* ifdef ISC_PLATFORM_HAVESYSUNH */
+}
+
+isc_result_t
+isc_socket_permunix(const isc_sockaddr_t *sockaddr, uint32_t perm,
+ uint32_t owner, uint32_t group) {
+#ifdef ISC_PLATFORM_HAVESYSUNH
+ isc_result_t result = ISC_R_SUCCESS;
+ char strbuf[ISC_STRERRORSIZE];
+ char path[sizeof(sockaddr->type.sunix.sun_path)];
+#ifdef NEED_SECURE_DIRECTORY
+ char *slash;
+#endif /* ifdef NEED_SECURE_DIRECTORY */
+
+ REQUIRE(sockaddr->type.sa.sa_family == AF_UNIX);
+ INSIST(strlen(sockaddr->type.sunix.sun_path) < sizeof(path));
+ strlcpy(path, sockaddr->type.sunix.sun_path, sizeof(path));
+
+#ifdef NEED_SECURE_DIRECTORY
+ slash = strrchr(path, '/');
+ if (slash != NULL) {
+ if (slash != path) {
+ *slash = '\0';
+ } else {
+ strlcpy(path, "/", sizeof(path));
+ }
+ } else {
+ strlcpy(path, ".", sizeof(path));
+ }
+#endif /* ifdef NEED_SECURE_DIRECTORY */
+
+ if (chmod(path, perm) < 0) {
+ strerror_r(errno, strbuf, sizeof(strbuf));
+ isc_log_write(isc_lctx, ISC_LOGCATEGORY_GENERAL,
+ ISC_LOGMODULE_SOCKET, ISC_LOG_ERROR,
+ "isc_socket_permunix: chmod(%s, %d): %s", path,
+ perm, strbuf);
+ result = ISC_R_FAILURE;
+ }
+ if (chown(path, owner, group) < 0) {
+ strerror_r(errno, strbuf, sizeof(strbuf));
+ isc_log_write(isc_lctx, ISC_LOGCATEGORY_GENERAL,
+ ISC_LOGMODULE_SOCKET, ISC_LOG_ERROR,
+ "isc_socket_permunix: chown(%s, %d, %d): %s",
+ path, owner, group, strbuf);
+ result = ISC_R_FAILURE;
+ }
+ return (result);
+#else /* ifdef ISC_PLATFORM_HAVESYSUNH */
+ UNUSED(sockaddr);
+ UNUSED(perm);
+ UNUSED(owner);
+ UNUSED(group);
+ return (ISC_R_NOTIMPLEMENTED);
+#endif /* ifdef ISC_PLATFORM_HAVESYSUNH */
+}
+
+isc_result_t
+isc_socket_bind(isc_socket_t *sock, const isc_sockaddr_t *sockaddr,
+ isc_socket_options_t options) {
+ char strbuf[ISC_STRERRORSIZE];
+ int on = 1;
+
+ REQUIRE(VALID_SOCKET(sock));
+
+ LOCK(&sock->lock);
+
+ INSIST(!sock->bound);
+ INSIST(!sock->dupped);
+
+ if (sock->pf != sockaddr->type.sa.sa_family) {
+ UNLOCK(&sock->lock);
+ return (ISC_R_FAMILYMISMATCH);
+ }
+
+ /*
+ * Only set SO_REUSEADDR when we want a specific port.
+ */
+#ifdef AF_UNIX
+ if (sock->pf == AF_UNIX) {
+ goto bind_socket;
+ }
+#endif /* ifdef AF_UNIX */
+ if ((options & ISC_SOCKET_REUSEADDRESS) != 0 &&
+ isc_sockaddr_getport(sockaddr) != (in_port_t)0)
+ {
+ if (setsockopt(sock->fd, SOL_SOCKET, SO_REUSEADDR, (void *)&on,
+ sizeof(on)) < 0)
+ {
+ UNEXPECTED_ERROR(__FILE__, __LINE__,
+ "setsockopt(%d) failed", sock->fd);
+ }
+#if defined(__FreeBSD_kernel__) && defined(SO_REUSEPORT_LB)
+ if (setsockopt(sock->fd, SOL_SOCKET, SO_REUSEPORT_LB,
+ (void *)&on, sizeof(on)) < 0)
+ {
+ UNEXPECTED_ERROR(__FILE__, __LINE__,
+ "setsockopt(%d) failed", sock->fd);
+ }
+#elif defined(__linux__) && defined(SO_REUSEPORT)
+ if (setsockopt(sock->fd, SOL_SOCKET, SO_REUSEPORT, (void *)&on,
+ sizeof(on)) < 0)
+ {
+ UNEXPECTED_ERROR(__FILE__, __LINE__,
+ "setsockopt(%d) failed", sock->fd);
+ }
+#endif /* if defined(__FreeBSD_kernel__) && defined(SO_REUSEPORT_LB) */
+ /* Press on... */
+ }
+#ifdef AF_UNIX
+bind_socket:
+#endif /* ifdef AF_UNIX */
+ if (bind(sock->fd, &sockaddr->type.sa, sockaddr->length) < 0) {
+ inc_stats(sock->manager->stats,
+ sock->statsindex[STATID_BINDFAIL]);
+
+ UNLOCK(&sock->lock);
+ switch (errno) {
+ case EACCES:
+ return (ISC_R_NOPERM);
+ case EADDRNOTAVAIL:
+ return (ISC_R_ADDRNOTAVAIL);
+ case EADDRINUSE:
+ return (ISC_R_ADDRINUSE);
+ case EINVAL:
+ return (ISC_R_BOUND);
+ default:
+ strerror_r(errno, strbuf, sizeof(strbuf));
+ UNEXPECTED_ERROR(__FILE__, __LINE__, "bind: %s",
+ strbuf);
+ return (ISC_R_UNEXPECTED);
+ }
+ }
+
+ socket_log(sock, sockaddr, TRACE, "bound");
+ sock->bound = 1;
+
+ UNLOCK(&sock->lock);
+ return (ISC_R_SUCCESS);
+}
+
+/*
+ * Enable this only for specific OS versions, and only when they have repaired
+ * their problems with it. Until then, this is is broken and needs to be
+ * disabled by default. See RT22589 for details.
+ */
+#undef ENABLE_ACCEPTFILTER
+
+isc_result_t
+isc_socket_filter(isc_socket_t *sock, const char *filter) {
+#if defined(SO_ACCEPTFILTER) && defined(ENABLE_ACCEPTFILTER)
+ char strbuf[ISC_STRERRORSIZE];
+ struct accept_filter_arg afa;
+#else /* if defined(SO_ACCEPTFILTER) && defined(ENABLE_ACCEPTFILTER) */
+ UNUSED(sock);
+ UNUSED(filter);
+#endif /* if defined(SO_ACCEPTFILTER) && defined(ENABLE_ACCEPTFILTER) */
+
+ REQUIRE(VALID_SOCKET(sock));
+
+#if defined(SO_ACCEPTFILTER) && defined(ENABLE_ACCEPTFILTER)
+ bzero(&afa, sizeof(afa));
+ strlcpy(afa.af_name, filter, sizeof(afa.af_name));
+ if (setsockopt(sock->fd, SOL_SOCKET, SO_ACCEPTFILTER, &afa,
+ sizeof(afa)) == -1)
+ {
+ strerror_r(errno, strbuf, sizeof(strbuf));
+ socket_log(sock, NULL, CREATION,
+ "setsockopt(SO_ACCEPTFILTER): %s", strbuf);
+ return (ISC_R_FAILURE);
+ }
+ return (ISC_R_SUCCESS);
+#else /* if defined(SO_ACCEPTFILTER) && defined(ENABLE_ACCEPTFILTER) */
+ return (ISC_R_NOTIMPLEMENTED);
+#endif /* if defined(SO_ACCEPTFILTER) && defined(ENABLE_ACCEPTFILTER) */
+}
+
+/*
+ * Try enabling TCP Fast Open for a given socket if the OS supports it.
+ */
+static void
+set_tcp_fastopen(isc_socket_t *sock, unsigned int backlog) {
+#if defined(ENABLE_TCP_FASTOPEN) && defined(TCP_FASTOPEN)
+ char strbuf[ISC_STRERRORSIZE];
+
+/*
+ * FreeBSD, as of versions 10.3 and 11.0, defines TCP_FASTOPEN while also
+ * shipping a default kernel without TFO support, so we special-case it by
+ * performing an additional runtime check for TFO support using sysctl to
+ * prevent setsockopt() errors from being logged.
+ */
+#if defined(__FreeBSD__) && defined(HAVE_SYSCTLBYNAME)
+#define SYSCTL_TFO "net.inet.tcp.fastopen.enabled"
+ unsigned int enabled;
+ size_t enabledlen = sizeof(enabled);
+ static bool tfo_notice_logged = false;
+
+ if (sysctlbyname(SYSCTL_TFO, &enabled, &enabledlen, NULL, 0) < 0) {
+ /*
+ * This kernel does not support TCP Fast Open. There is
+ * nothing more we can do.
+ */
+ return;
+ } else if (enabled == 0) {
+ /*
+ * This kernel does support TCP Fast Open, but it is disabled
+ * by sysctl. Notify the user, but do not nag.
+ */
+ if (!tfo_notice_logged) {
+ isc_log_write(isc_lctx, ISC_LOGCATEGORY_GENERAL,
+ ISC_LOGMODULE_SOCKET, ISC_LOG_NOTICE,
+ "TCP_FASTOPEN support is disabled by "
+ "sysctl (" SYSCTL_TFO " = 0)");
+ tfo_notice_logged = true;
+ }
+ return;
+ }
+#endif /* if defined(__FreeBSD__) && defined(HAVE_SYSCTLBYNAME) */
+
+#ifdef __APPLE__
+ backlog = 1;
+#else /* ifdef __APPLE__ */
+ backlog = backlog / 2;
+ if (backlog == 0) {
+ backlog = 1;
+ }
+#endif /* ifdef __APPLE__ */
+ if (setsockopt(sock->fd, IPPROTO_TCP, TCP_FASTOPEN, (void *)&backlog,
+ sizeof(backlog)) < 0)
+ {
+ strerror_r(errno, strbuf, sizeof(strbuf));
+ UNEXPECTED_ERROR(__FILE__, __LINE__,
+ "setsockopt(%d, TCP_FASTOPEN) failed with %s",
+ sock->fd, strbuf);
+ /* TCP_FASTOPEN is experimental so ignore failures */
+ }
+#else /* if defined(ENABLE_TCP_FASTOPEN) && defined(TCP_FASTOPEN) */
+ UNUSED(sock);
+ UNUSED(backlog);
+#endif /* if defined(ENABLE_TCP_FASTOPEN) && defined(TCP_FASTOPEN) */
+}
+
+/*
+ * Set up to listen on a given socket. We do this by creating an internal
+ * event that will be dispatched when the socket has read activity. The
+ * watcher will send the internal event to the task when there is a new
+ * connection.
+ *
+ * Unlike in read, we don't preallocate a done event here. Every time there
+ * is a new connection we'll have to allocate a new one anyway, so we might
+ * as well keep things simple rather than having to track them.
+ */
+isc_result_t
+isc_socket_listen(isc_socket_t *sock, unsigned int backlog) {
+ char strbuf[ISC_STRERRORSIZE];
+
+ REQUIRE(VALID_SOCKET(sock));
+
+ LOCK(&sock->lock);
+
+ REQUIRE(!sock->listener);
+ REQUIRE(sock->bound);
+ REQUIRE(sock->type == isc_sockettype_tcp ||
+ sock->type == isc_sockettype_unix);
+
+ if (backlog == 0) {
+ backlog = SOMAXCONN;
+ }
+
+ if (listen(sock->fd, (int)backlog) < 0) {
+ UNLOCK(&sock->lock);
+ strerror_r(errno, strbuf, sizeof(strbuf));
+
+ UNEXPECTED_ERROR(__FILE__, __LINE__, "listen: %s", strbuf);
+
+ return (ISC_R_UNEXPECTED);
+ }
+
+ set_tcp_fastopen(sock, backlog);
+
+ sock->listener = 1;
+
+ UNLOCK(&sock->lock);
+ return (ISC_R_SUCCESS);
+}
+
+/*
+ * This should try to do aggressive accept() XXXMLG
+ */
+isc_result_t
+isc_socket_accept(isc_socket_t *sock, isc_task_t *task, isc_taskaction_t action,
+ void *arg) {
+ isc_socket_newconnev_t *dev;
+ isc_socketmgr_t *manager;
+ isc_task_t *ntask = NULL;
+ isc_socket_t *nsock;
+ isc_result_t result;
+ bool do_poke = false;
+
+ REQUIRE(VALID_SOCKET(sock));
+ manager = sock->manager;
+ REQUIRE(VALID_MANAGER(manager));
+
+ LOCK(&sock->lock);
+
+ REQUIRE(sock->listener);
+
+ /*
+ * Sender field is overloaded here with the task we will be sending
+ * this event to. Just before the actual event is delivered the
+ * actual ev_sender will be touched up to be the socket.
+ */
+ dev = (isc_socket_newconnev_t *)isc_event_allocate(
+ manager->mctx, task, ISC_SOCKEVENT_NEWCONN, action, arg,
+ sizeof(*dev));
+ ISC_LINK_INIT(dev, ev_link);
+
+ result = allocate_socket(manager, sock->type, &nsock);
+ if (result != ISC_R_SUCCESS) {
+ isc_event_free(ISC_EVENT_PTR(&dev));
+ UNLOCK(&sock->lock);
+ return (result);
+ }
+
+ /*
+ * Attach to socket and to task.
+ */
+ isc_task_attach(task, &ntask);
+ if (isc_task_exiting(ntask)) {
+ free_socket(&nsock);
+ isc_task_detach(&ntask);
+ isc_event_free(ISC_EVENT_PTR(&dev));
+ UNLOCK(&sock->lock);
+ return (ISC_R_SHUTTINGDOWN);
+ }
+ isc_refcount_increment0(&nsock->references);
+ nsock->statsindex = sock->statsindex;
+
+ dev->ev_sender = ntask;
+ dev->newsocket = nsock;
+
+ /*
+ * Poke watcher here. We still have the socket locked, so there
+ * is no race condition. We will keep the lock for such a short
+ * bit of time waking it up now or later won't matter all that much.
+ */
+ do_poke = ISC_LIST_EMPTY(sock->accept_list);
+ ISC_LIST_ENQUEUE(sock->accept_list, dev, ev_link);
+ if (do_poke) {
+ select_poke(manager, sock->threadid, sock->fd,
+ SELECT_POKE_ACCEPT);
+ }
+ UNLOCK(&sock->lock);
+ return (ISC_R_SUCCESS);
+}
+
+isc_result_t
+isc_socket_connect(isc_socket_t *sock, const isc_sockaddr_t *addr,
+ isc_task_t *task, isc_taskaction_t action, void *arg) {
+ isc_socket_connev_t *dev;
+ isc_task_t *ntask = NULL;
+ isc_socketmgr_t *manager;
+ int cc;
+ char strbuf[ISC_STRERRORSIZE];
+ char addrbuf[ISC_SOCKADDR_FORMATSIZE];
+
+ REQUIRE(VALID_SOCKET(sock));
+ REQUIRE(addr != NULL);
+ REQUIRE(task != NULL);
+ REQUIRE(action != NULL);
+
+ manager = sock->manager;
+ REQUIRE(VALID_MANAGER(manager));
+ REQUIRE(addr != NULL);
+
+ if (isc_sockaddr_ismulticast(addr)) {
+ return (ISC_R_MULTICAST);
+ }
+
+ LOCK(&sock->lock);
+
+ dev = (isc_socket_connev_t *)isc_event_allocate(
+ manager->mctx, sock, ISC_SOCKEVENT_CONNECT, action, arg,
+ sizeof(*dev));
+ ISC_LINK_INIT(dev, ev_link);
+
+ if (sock->connecting) {
+ INSIST(isc_sockaddr_equal(&sock->peer_address, addr));
+ goto queue;
+ }
+
+ if (sock->connected) {
+ INSIST(isc_sockaddr_equal(&sock->peer_address, addr));
+ dev->result = ISC_R_SUCCESS;
+ isc_task_sendto(task, ISC_EVENT_PTR(&dev), sock->threadid);
+
+ UNLOCK(&sock->lock);
+
+ return (ISC_R_SUCCESS);
+ }
+
+ /*
+ * Try to do the connect right away, as there can be only one
+ * outstanding, and it might happen to complete.
+ */
+ sock->peer_address = *addr;
+ cc = connect(sock->fd, &addr->type.sa, addr->length);
+ if (cc < 0) {
+ /*
+ * The socket is nonblocking and the connection cannot be
+ * completed immediately. It is possible to select(2) or
+ * poll(2) for completion by selecting the socket for writing.
+ * After select(2) indicates writability, use getsockopt(2) to
+ * read the SO_ERROR option at level SOL_SOCKET to determine
+ * whether connect() completed successfully (SO_ERROR is zero)
+ * or unsuccessfully (SO_ERROR is one of the usual error codes
+ * listed here, explaining the reason for the failure).
+ */
+ if (sock->type == isc_sockettype_udp && errno == EINPROGRESS) {
+ cc = 0;
+ goto success;
+ }
+ if (SOFT_ERROR(errno) || errno == EINPROGRESS) {
+ goto queue;
+ }
+
+ switch (errno) {
+#define ERROR_MATCH(a, b) \
+ case a: \
+ dev->result = b; \
+ goto err_exit;
+ ERROR_MATCH(EACCES, ISC_R_NOPERM);
+ ERROR_MATCH(EADDRNOTAVAIL, ISC_R_ADDRNOTAVAIL);
+ ERROR_MATCH(EAFNOSUPPORT, ISC_R_ADDRNOTAVAIL);
+ ERROR_MATCH(ECONNREFUSED, ISC_R_CONNREFUSED);
+ ERROR_MATCH(EHOSTUNREACH, ISC_R_HOSTUNREACH);
+#ifdef EHOSTDOWN
+ ERROR_MATCH(EHOSTDOWN, ISC_R_HOSTUNREACH);
+#endif /* ifdef EHOSTDOWN */
+ ERROR_MATCH(ENETUNREACH, ISC_R_NETUNREACH);
+ ERROR_MATCH(ENOBUFS, ISC_R_NORESOURCES);
+ ERROR_MATCH(EPERM, ISC_R_HOSTUNREACH);
+ ERROR_MATCH(EPIPE, ISC_R_NOTCONNECTED);
+ ERROR_MATCH(ETIMEDOUT, ISC_R_TIMEDOUT);
+ ERROR_MATCH(ECONNRESET, ISC_R_CONNECTIONRESET);
+#undef ERROR_MATCH
+ }
+
+ sock->connected = 0;
+
+ strerror_r(errno, strbuf, sizeof(strbuf));
+ isc_sockaddr_format(addr, addrbuf, sizeof(addrbuf));
+ UNEXPECTED_ERROR(__FILE__, __LINE__, "connect(%s) %d/%s",
+ addrbuf, errno, strbuf);
+
+ UNLOCK(&sock->lock);
+ inc_stats(sock->manager->stats,
+ sock->statsindex[STATID_CONNECTFAIL]);
+ isc_event_free(ISC_EVENT_PTR(&dev));
+ return (ISC_R_UNEXPECTED);
+
+ err_exit:
+ sock->connected = 0;
+ isc_task_sendto(task, ISC_EVENT_PTR(&dev), sock->threadid);
+
+ UNLOCK(&sock->lock);
+ inc_stats(sock->manager->stats,
+ sock->statsindex[STATID_CONNECTFAIL]);
+ return (ISC_R_SUCCESS);
+ }
+
+ /*
+ * If connect completed, fire off the done event.
+ */
+success:
+ if (cc == 0) {
+ sock->connected = 1;
+ sock->bound = 1;
+ dev->result = ISC_R_SUCCESS;
+ isc_task_sendto(task, ISC_EVENT_PTR(&dev), sock->threadid);
+
+ UNLOCK(&sock->lock);
+
+ inc_stats(sock->manager->stats,
+ sock->statsindex[STATID_CONNECT]);
+
+ return (ISC_R_SUCCESS);
+ }
+
+queue:
+
+ /*
+ * Attach to task.
+ */
+ isc_task_attach(task, &ntask);
+
+ dev->ev_sender = ntask;
+
+ /*
+ * Poke watcher here. We still have the socket locked, so there
+ * is no race condition. We will keep the lock for such a short
+ * bit of time waking it up now or later won't matter all that much.
+ */
+ bool do_poke = ISC_LIST_EMPTY(sock->connect_list);
+ ISC_LIST_ENQUEUE(sock->connect_list, dev, ev_link);
+ if (do_poke && !sock->connecting) {
+ sock->connecting = 1;
+ select_poke(manager, sock->threadid, sock->fd,
+ SELECT_POKE_CONNECT);
+ }
+
+ UNLOCK(&sock->lock);
+ return (ISC_R_SUCCESS);
+}
+
+/*
+ * Called when a socket with a pending connect() finishes.
+ */
+static void
+internal_connect(isc_socket_t *sock) {
+ isc_socket_connev_t *dev;
+ int cc;
+ isc_result_t result;
+ socklen_t optlen;
+ char strbuf[ISC_STRERRORSIZE];
+ char peerbuf[ISC_SOCKADDR_FORMATSIZE];
+
+ INSIST(VALID_SOCKET(sock));
+ REQUIRE(sock->fd >= 0);
+
+ /*
+ * Get the first item off the connect list.
+ * If it is empty, unlock the socket and return.
+ */
+ dev = ISC_LIST_HEAD(sock->connect_list);
+ if (dev == NULL) {
+ INSIST(!sock->connecting);
+ goto finish;
+ }
+
+ INSIST(sock->connecting);
+ sock->connecting = 0;
+
+ /*
+ * Get any possible error status here.
+ */
+ optlen = sizeof(cc);
+ if (getsockopt(sock->fd, SOL_SOCKET, SO_ERROR, (void *)&cc,
+ (void *)&optlen) != 0)
+ {
+ cc = errno;
+ } else {
+ errno = cc;
+ }
+
+ if (errno != 0) {
+ /*
+ * If the error is EAGAIN, just re-select on this
+ * fd and pretend nothing strange happened.
+ */
+ if (SOFT_ERROR(errno) || errno == EINPROGRESS) {
+ sock->connecting = 1;
+ return;
+ }
+
+ inc_stats(sock->manager->stats,
+ sock->statsindex[STATID_CONNECTFAIL]);
+
+ /*
+ * Translate other errors into ISC_R_* flavors.
+ */
+ switch (errno) {
+#define ERROR_MATCH(a, b) \
+ case a: \
+ result = b; \
+ break;
+ ERROR_MATCH(EACCES, ISC_R_NOPERM);
+ ERROR_MATCH(EADDRNOTAVAIL, ISC_R_ADDRNOTAVAIL);
+ ERROR_MATCH(EAFNOSUPPORT, ISC_R_ADDRNOTAVAIL);
+ ERROR_MATCH(ECONNREFUSED, ISC_R_CONNREFUSED);
+ ERROR_MATCH(EHOSTUNREACH, ISC_R_HOSTUNREACH);
+#ifdef EHOSTDOWN
+ ERROR_MATCH(EHOSTDOWN, ISC_R_HOSTUNREACH);
+#endif /* ifdef EHOSTDOWN */
+ ERROR_MATCH(ENETUNREACH, ISC_R_NETUNREACH);
+ ERROR_MATCH(ENOBUFS, ISC_R_NORESOURCES);
+ ERROR_MATCH(EPERM, ISC_R_HOSTUNREACH);
+ ERROR_MATCH(EPIPE, ISC_R_NOTCONNECTED);
+ ERROR_MATCH(ETIMEDOUT, ISC_R_TIMEDOUT);
+ ERROR_MATCH(ECONNRESET, ISC_R_CONNECTIONRESET);
+#undef ERROR_MATCH
+ default:
+ result = ISC_R_UNEXPECTED;
+ isc_sockaddr_format(&sock->peer_address, peerbuf,
+ sizeof(peerbuf));
+ strerror_r(errno, strbuf, sizeof(strbuf));
+ UNEXPECTED_ERROR(__FILE__, __LINE__,
+ "internal_connect: connect(%s) %s",
+ peerbuf, strbuf);
+ }
+ } else {
+ inc_stats(sock->manager->stats,
+ sock->statsindex[STATID_CONNECT]);
+ result = ISC_R_SUCCESS;
+ sock->connected = 1;
+ sock->bound = 1;
+ }
+
+ do {
+ dev->result = result;
+ send_connectdone_event(sock, &dev);
+ dev = ISC_LIST_HEAD(sock->connect_list);
+ } while (dev != NULL);
+
+finish:
+ unwatch_fd(&sock->manager->threads[sock->threadid], sock->fd,
+ SELECT_POKE_CONNECT);
+}
+
+isc_result_t
+isc_socket_getpeername(isc_socket_t *sock, isc_sockaddr_t *addressp) {
+ isc_result_t result;
+
+ REQUIRE(VALID_SOCKET(sock));
+ REQUIRE(addressp != NULL);
+
+ LOCK(&sock->lock);
+
+ if (sock->connected) {
+ *addressp = sock->peer_address;
+ result = ISC_R_SUCCESS;
+ } else {
+ result = ISC_R_NOTCONNECTED;
+ }
+
+ UNLOCK(&sock->lock);
+
+ return (result);
+}
+
+isc_result_t
+isc_socket_getsockname(isc_socket_t *sock, isc_sockaddr_t *addressp) {
+ socklen_t len;
+ isc_result_t result;
+ char strbuf[ISC_STRERRORSIZE];
+
+ REQUIRE(VALID_SOCKET(sock));
+ REQUIRE(addressp != NULL);
+
+ LOCK(&sock->lock);
+
+ if (!sock->bound) {
+ result = ISC_R_NOTBOUND;
+ goto out;
+ }
+
+ result = ISC_R_SUCCESS;
+
+ len = sizeof(addressp->type);
+ if (getsockname(sock->fd, &addressp->type.sa, (void *)&len) < 0) {
+ strerror_r(errno, strbuf, sizeof(strbuf));
+ UNEXPECTED_ERROR(__FILE__, __LINE__, "getsockname: %s", strbuf);
+ result = ISC_R_UNEXPECTED;
+ goto out;
+ }
+ addressp->length = (unsigned int)len;
+
+out:
+ UNLOCK(&sock->lock);
+
+ return (result);
+}
+
+/*
+ * Run through the list of events on this socket, and cancel the ones
+ * queued for task "task" of type "how". "how" is a bitmask.
+ */
+void
+isc_socket_cancel(isc_socket_t *sock, isc_task_t *task, unsigned int how) {
+ REQUIRE(VALID_SOCKET(sock));
+
+ /*
+ * Quick exit if there is nothing to do. Don't even bother locking
+ * in this case.
+ */
+ if (how == 0) {
+ return;
+ }
+
+ LOCK(&sock->lock);
+
+ /*
+ * All of these do the same thing, more or less.
+ * Each will:
+ * o If the internal event is marked as "posted" try to
+ * remove it from the task's queue. If this fails, mark it
+ * as canceled instead, and let the task clean it up later.
+ * o For each I/O request for that task of that type, post
+ * its done event with status of "ISC_R_CANCELED".
+ * o Reset any state needed.
+ */
+ if (((how & ISC_SOCKCANCEL_RECV) != 0) &&
+ !ISC_LIST_EMPTY(sock->recv_list))
+ {
+ isc_socketevent_t *dev;
+ isc_socketevent_t *next;
+ isc_task_t *current_task;
+
+ dev = ISC_LIST_HEAD(sock->recv_list);
+
+ while (dev != NULL) {
+ current_task = dev->ev_sender;
+ next = ISC_LIST_NEXT(dev, ev_link);
+
+ if ((task == NULL) || (task == current_task)) {
+ dev->result = ISC_R_CANCELED;
+ send_recvdone_event(sock, &dev);
+ }
+ dev = next;
+ }
+ }
+
+ if (((how & ISC_SOCKCANCEL_SEND) != 0) &&
+ !ISC_LIST_EMPTY(sock->send_list))
+ {
+ isc_socketevent_t *dev;
+ isc_socketevent_t *next;
+ isc_task_t *current_task;
+
+ dev = ISC_LIST_HEAD(sock->send_list);
+
+ while (dev != NULL) {
+ current_task = dev->ev_sender;
+ next = ISC_LIST_NEXT(dev, ev_link);
+
+ if ((task == NULL) || (task == current_task)) {
+ dev->result = ISC_R_CANCELED;
+ send_senddone_event(sock, &dev);
+ }
+ dev = next;
+ }
+ }
+
+ if (((how & ISC_SOCKCANCEL_ACCEPT) != 0) &&
+ !ISC_LIST_EMPTY(sock->accept_list))
+ {
+ isc_socket_newconnev_t *dev;
+ isc_socket_newconnev_t *next;
+ isc_task_t *current_task;
+
+ dev = ISC_LIST_HEAD(sock->accept_list);
+ while (dev != NULL) {
+ current_task = dev->ev_sender;
+ next = ISC_LIST_NEXT(dev, ev_link);
+
+ if ((task == NULL) || (task == current_task)) {
+ ISC_LIST_UNLINK(sock->accept_list, dev,
+ ev_link);
+
+ isc_refcount_decrementz(
+ &NEWCONNSOCK(dev)->references);
+ free_socket((isc_socket_t **)&dev->newsocket);
+
+ dev->result = ISC_R_CANCELED;
+ dev->ev_sender = sock;
+ isc_task_sendtoanddetach(&current_task,
+ ISC_EVENT_PTR(&dev),
+ sock->threadid);
+ }
+
+ dev = next;
+ }
+ }
+
+ if (((how & ISC_SOCKCANCEL_CONNECT) != 0) &&
+ !ISC_LIST_EMPTY(sock->connect_list))
+ {
+ isc_socket_connev_t *dev;
+ isc_socket_connev_t *next;
+ isc_task_t *current_task;
+
+ INSIST(sock->connecting);
+ sock->connecting = 0;
+
+ dev = ISC_LIST_HEAD(sock->connect_list);
+
+ while (dev != NULL) {
+ current_task = dev->ev_sender;
+ next = ISC_LIST_NEXT(dev, ev_link);
+
+ if ((task == NULL) || (task == current_task)) {
+ dev->result = ISC_R_CANCELED;
+ send_connectdone_event(sock, &dev);
+ }
+ dev = next;
+ }
+ }
+
+ UNLOCK(&sock->lock);
+}
+
+isc_sockettype_t
+isc_socket_gettype(isc_socket_t *sock) {
+ REQUIRE(VALID_SOCKET(sock));
+
+ return (sock->type);
+}
+
+void
+isc_socket_ipv6only(isc_socket_t *sock, bool yes) {
+#if defined(IPV6_V6ONLY) && !defined(__OpenBSD__)
+ int onoff = yes ? 1 : 0;
+#else /* if defined(IPV6_V6ONLY) */
+ UNUSED(yes);
+ UNUSED(sock);
+#endif /* if defined(IPV6_V6ONLY) */
+
+ REQUIRE(VALID_SOCKET(sock));
+ INSIST(!sock->dupped);
+
+#if defined(IPV6_V6ONLY) && !defined(__OpenBSD__)
+ if (sock->pf == AF_INET6) {
+ if (setsockopt(sock->fd, IPPROTO_IPV6, IPV6_V6ONLY,
+ (void *)&onoff, sizeof(int)) < 0)
+ {
+ char strbuf[ISC_STRERRORSIZE];
+ strerror_r(errno, strbuf, sizeof(strbuf));
+ UNEXPECTED_ERROR(__FILE__, __LINE__,
+ "setsockopt(%d, IPV6_V6ONLY) failed: "
+ "%s",
+ sock->fd, strbuf);
+ }
+ }
+#endif /* ifdef IPV6_V6ONLY */
+}
+
+static void
+setdscp(isc_socket_t *sock, isc_dscp_t dscp) {
+#if defined(IP_TOS) || defined(IPV6_TCLASS)
+ int value = dscp << 2;
+#endif /* if defined(IP_TOS) || defined(IPV6_TCLASS) */
+
+ sock->dscp = dscp;
+
+#ifdef IP_TOS
+ if (sock->pf == AF_INET) {
+ if (setsockopt(sock->fd, IPPROTO_IP, IP_TOS, (void *)&value,
+ sizeof(value)) < 0)
+ {
+ char strbuf[ISC_STRERRORSIZE];
+ strerror_r(errno, strbuf, sizeof(strbuf));
+ UNEXPECTED_ERROR(__FILE__, __LINE__,
+ "setsockopt(%d, IP_TOS, %.02x) "
+ "failed: %s",
+ sock->fd, value >> 2, strbuf);
+ }
+ }
+#endif /* ifdef IP_TOS */
+#ifdef IPV6_TCLASS
+ if (sock->pf == AF_INET6) {
+ if (setsockopt(sock->fd, IPPROTO_IPV6, IPV6_TCLASS,
+ (void *)&value, sizeof(value)) < 0)
+ {
+ char strbuf[ISC_STRERRORSIZE];
+ strerror_r(errno, strbuf, sizeof(strbuf));
+ UNEXPECTED_ERROR(__FILE__, __LINE__,
+ "setsockopt(%d, IPV6_TCLASS, %.02x) "
+ "failed: %s",
+ sock->fd, dscp >> 2, strbuf);
+ }
+ }
+#endif /* ifdef IPV6_TCLASS */
+}
+
+void
+isc_socket_dscp(isc_socket_t *sock, isc_dscp_t dscp) {
+ REQUIRE(VALID_SOCKET(sock));
+ REQUIRE(dscp < 0x40);
+
+#if !defined(IP_TOS) && !defined(IPV6_TCLASS)
+ UNUSED(dscp);
+#else /* if !defined(IP_TOS) && !defined(IPV6_TCLASS) */
+ if (dscp < 0) {
+ return;
+ }
+
+ /* The DSCP value must not be changed once it has been set. */
+ if (isc_dscp_check_value != -1) {
+ INSIST(dscp == isc_dscp_check_value);
+ }
+#endif /* if !defined(IP_TOS) && !defined(IPV6_TCLASS) */
+
+#ifdef notyet
+ REQUIRE(!sock->dupped);
+#endif /* ifdef notyet */
+
+ setdscp(sock, dscp);
+}
+
+isc_socketevent_t *
+isc_socket_socketevent(isc_mem_t *mctx, void *sender, isc_eventtype_t eventtype,
+ isc_taskaction_t action, void *arg) {
+ return (allocate_socketevent(mctx, sender, eventtype, action, arg));
+}
+
+void
+isc_socket_setname(isc_socket_t *sock, const char *name, void *tag) {
+ /*
+ * Name 'sock'.
+ */
+
+ REQUIRE(VALID_SOCKET(sock));
+
+ LOCK(&sock->lock);
+ strlcpy(sock->name, name, sizeof(sock->name));
+ sock->tag = tag;
+ UNLOCK(&sock->lock);
+}
+
+const char *
+isc_socket_getname(isc_socket_t *sock) {
+ return (sock->name);
+}
+
+void *
+isc_socket_gettag(isc_socket_t *sock) {
+ return (sock->tag);
+}
+
+int
+isc_socket_getfd(isc_socket_t *sock) {
+ return ((short)sock->fd);
+}
+
+static isc_once_t hasreuseport_once = ISC_ONCE_INIT;
+static bool hasreuseport = false;
+
+static void
+init_hasreuseport() {
+/*
+ * SO_REUSEPORT works very differently on *BSD and on Linux (because why not).
+ * We only want to use it on Linux, if it's available. On BSD we want to dup()
+ * sockets instead of re-binding them.
+ */
+#if (defined(SO_REUSEPORT) && defined(__linux__)) || \
+ (defined(SO_REUSEPORT_LB) && defined(__FreeBSD_kernel__))
+ int sock, yes = 1;
+ sock = socket(AF_INET, SOCK_DGRAM, 0);
+ if (sock < 0) {
+ sock = socket(AF_INET6, SOCK_DGRAM, 0);
+ if (sock < 0) {
+ return;
+ }
+ }
+ if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *)&yes,
+ sizeof(yes)) < 0)
+ {
+ close(sock);
+ return;
+#if defined(__FreeBSD_kernel__)
+ } else if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT_LB, (void *)&yes,
+ sizeof(yes)) < 0)
+#else /* if defined(__FreeBSD_kernel__) */
+ } else if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, (void *)&yes,
+ sizeof(yes)) < 0)
+#endif /* if defined(__FreeBSD_kernel__) */
+ {
+ close(sock);
+ return;
+ }
+ hasreuseport = true;
+ close(sock);
+#endif /* if (defined(SO_REUSEPORT) && defined(__linux__)) || \
+ * (defined(SO_REUSEPORT_LB) && defined(__FreeBSD_kernel__)) */
+}
+
+bool
+isc_socket_hasreuseport() {
+ RUNTIME_CHECK(isc_once_do(&hasreuseport_once, init_hasreuseport) ==
+ ISC_R_SUCCESS);
+ return (hasreuseport);
+}
+
+#if defined(HAVE_LIBXML2) || defined(HAVE_JSON_C)
+static const char *
+_socktype(isc_sockettype_t type) {
+ switch (type) {
+ case isc_sockettype_udp:
+ return ("udp");
+ case isc_sockettype_tcp:
+ return ("tcp");
+ case isc_sockettype_unix:
+ return ("unix");
+ default:
+ return ("not-initialized");
+ }
+}
+#endif /* if defined(HAVE_LIBXML2) || defined(HAVE_JSON_C) */
+
+#ifdef HAVE_LIBXML2
+#define TRY0(a) \
+ do { \
+ xmlrc = (a); \
+ if (xmlrc < 0) \
+ goto error; \
+ } while (0)
+int
+isc_socketmgr_renderxml(isc_socketmgr_t *mgr, void *writer0) {
+ isc_socket_t *sock = NULL;
+ char peerbuf[ISC_SOCKADDR_FORMATSIZE];
+ isc_sockaddr_t addr;
+ socklen_t len;
+ int xmlrc;
+ xmlTextWriterPtr writer = (xmlTextWriterPtr)writer0;
+
+ LOCK(&mgr->lock);
+
+ TRY0(xmlTextWriterStartElement(writer, ISC_XMLCHAR "sockets"));
+ sock = ISC_LIST_HEAD(mgr->socklist);
+ while (sock != NULL) {
+ LOCK(&sock->lock);
+ TRY0(xmlTextWriterStartElement(writer, ISC_XMLCHAR "socket"));
+
+ TRY0(xmlTextWriterStartElement(writer, ISC_XMLCHAR "id"));
+ TRY0(xmlTextWriterWriteFormatString(writer, "%p", sock));
+ TRY0(xmlTextWriterEndElement(writer));
+
+ if (sock->name[0] != 0) {
+ TRY0(xmlTextWriterStartElement(writer,
+ ISC_XMLCHAR "name"));
+ TRY0(xmlTextWriterWriteFormatString(writer, "%s",
+ sock->name));
+ TRY0(xmlTextWriterEndElement(writer)); /* name */
+ }
+
+ TRY0(xmlTextWriterStartElement(writer,
+ ISC_XMLCHAR "references"));
+ TRY0(xmlTextWriterWriteFormatString(
+ writer, "%d",
+ (int)isc_refcount_current(&sock->references)));
+ TRY0(xmlTextWriterEndElement(writer));
+
+ TRY0(xmlTextWriterWriteElement(
+ writer, ISC_XMLCHAR "type",
+ ISC_XMLCHAR _socktype(sock->type)));
+
+ if (sock->connected) {
+ isc_sockaddr_format(&sock->peer_address, peerbuf,
+ sizeof(peerbuf));
+ TRY0(xmlTextWriterWriteElement(
+ writer, ISC_XMLCHAR "peer-address",
+ ISC_XMLCHAR peerbuf));
+ }
+
+ len = sizeof(addr);
+ if (getsockname(sock->fd, &addr.type.sa, (void *)&len) == 0) {
+ isc_sockaddr_format(&addr, peerbuf, sizeof(peerbuf));
+ TRY0(xmlTextWriterWriteElement(
+ writer, ISC_XMLCHAR "local-address",
+ ISC_XMLCHAR peerbuf));
+ }
+
+ TRY0(xmlTextWriterStartElement(writer, ISC_XMLCHAR "states"));
+ if (sock->listener) {
+ TRY0(xmlTextWriterWriteElement(writer,
+ ISC_XMLCHAR "state",
+ ISC_XMLCHAR "listener"));
+ }
+ if (sock->connected) {
+ TRY0(xmlTextWriterWriteElement(
+ writer, ISC_XMLCHAR "state",
+ ISC_XMLCHAR "connected"));
+ }
+ if (sock->connecting) {
+ TRY0(xmlTextWriterWriteElement(
+ writer, ISC_XMLCHAR "state",
+ ISC_XMLCHAR "connecting"));
+ }
+ if (sock->bound) {
+ TRY0(xmlTextWriterWriteElement(writer,
+ ISC_XMLCHAR "state",
+ ISC_XMLCHAR "bound"));
+ }
+
+ TRY0(xmlTextWriterEndElement(writer)); /* states */
+
+ TRY0(xmlTextWriterEndElement(writer)); /* socket */
+
+ UNLOCK(&sock->lock);
+ sock = ISC_LIST_NEXT(sock, link);
+ }
+ TRY0(xmlTextWriterEndElement(writer)); /* sockets */
+
+error:
+ if (sock != NULL) {
+ UNLOCK(&sock->lock);
+ }
+
+ UNLOCK(&mgr->lock);
+
+ return (xmlrc);
+}
+#endif /* HAVE_LIBXML2 */
+
+#ifdef HAVE_JSON_C
+#define CHECKMEM(m) \
+ do { \
+ if (m == NULL) { \
+ result = ISC_R_NOMEMORY; \
+ goto error; \
+ } \
+ } while (0)
+
+isc_result_t
+isc_socketmgr_renderjson(isc_socketmgr_t *mgr, void *stats0) {
+ isc_result_t result = ISC_R_SUCCESS;
+ isc_socket_t *sock = NULL;
+ char peerbuf[ISC_SOCKADDR_FORMATSIZE];
+ isc_sockaddr_t addr;
+ socklen_t len;
+ json_object *obj, *array = json_object_new_array();
+ json_object *stats = (json_object *)stats0;
+
+ CHECKMEM(array);
+
+ LOCK(&mgr->lock);
+
+ sock = ISC_LIST_HEAD(mgr->socklist);
+ while (sock != NULL) {
+ json_object *states, *entry = json_object_new_object();
+ char buf[255];
+
+ CHECKMEM(entry);
+ json_object_array_add(array, entry);
+
+ LOCK(&sock->lock);
+
+ snprintf(buf, sizeof(buf), "%p", sock);
+ obj = json_object_new_string(buf);
+ CHECKMEM(obj);
+ json_object_object_add(entry, "id", obj);
+
+ if (sock->name[0] != 0) {
+ obj = json_object_new_string(sock->name);
+ CHECKMEM(obj);
+ json_object_object_add(entry, "name", obj);
+ }
+
+ obj = json_object_new_int(
+ (int)isc_refcount_current(&sock->references));
+ CHECKMEM(obj);
+ json_object_object_add(entry, "references", obj);
+
+ obj = json_object_new_string(_socktype(sock->type));
+ CHECKMEM(obj);
+ json_object_object_add(entry, "type", obj);
+
+ if (sock->connected) {
+ isc_sockaddr_format(&sock->peer_address, peerbuf,
+ sizeof(peerbuf));
+ obj = json_object_new_string(peerbuf);
+ CHECKMEM(obj);
+ json_object_object_add(entry, "peer-address", obj);
+ }
+
+ len = sizeof(addr);
+ if (getsockname(sock->fd, &addr.type.sa, (void *)&len) == 0) {
+ isc_sockaddr_format(&addr, peerbuf, sizeof(peerbuf));
+ obj = json_object_new_string(peerbuf);
+ CHECKMEM(obj);
+ json_object_object_add(entry, "local-address", obj);
+ }
+
+ states = json_object_new_array();
+ CHECKMEM(states);
+ json_object_object_add(entry, "states", states);
+
+ if (sock->listener) {
+ obj = json_object_new_string("listener");
+ CHECKMEM(obj);
+ json_object_array_add(states, obj);
+ }
+
+ if (sock->connected) {
+ obj = json_object_new_string("connected");
+ CHECKMEM(obj);
+ json_object_array_add(states, obj);
+ }
+
+ if (sock->connecting) {
+ obj = json_object_new_string("connecting");
+ CHECKMEM(obj);
+ json_object_array_add(states, obj);
+ }
+
+ if (sock->bound) {
+ obj = json_object_new_string("bound");
+ CHECKMEM(obj);
+ json_object_array_add(states, obj);
+ }
+
+ UNLOCK(&sock->lock);
+ sock = ISC_LIST_NEXT(sock, link);
+ }
+
+ json_object_object_add(stats, "sockets", array);
+ array = NULL;
+ result = ISC_R_SUCCESS;
+
+error:
+ if (array != NULL) {
+ json_object_put(array);
+ }
+
+ if (sock != NULL) {
+ UNLOCK(&sock->lock);
+ }
+
+ UNLOCK(&mgr->lock);
+
+ return (result);
+}
+#endif /* HAVE_JSON_C */
diff --git a/lib/isc/unix/socket_p.h b/lib/isc/unix/socket_p.h
new file mode 100644
index 0000000..3323cab
--- /dev/null
+++ b/lib/isc/unix/socket_p.h
@@ -0,0 +1,27 @@
+/*
+ * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
+ *
+ * SPDX-License-Identifier: MPL-2.0
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, you can obtain one at https://mozilla.org/MPL/2.0/.
+ *
+ * See the COPYRIGHT file distributed with this work for additional
+ * information regarding copyright ownership.
+ */
+
+#ifndef ISC_SOCKET_P_H
+#define ISC_SOCKET_P_H
+
+/*! \file */
+
+#include <sys/time.h>
+
+typedef struct isc_socketwait isc_socketwait_t;
+int
+isc__socketmgr_waitevents(isc_socketmgr_t *, struct timeval *,
+ isc_socketwait_t **);
+isc_result_t
+isc__socketmgr_dispatch(isc_socketmgr_t *, isc_socketwait_t *);
+#endif /* ISC_SOCKET_P_H */
diff --git a/lib/isc/unix/stdio.c b/lib/isc/unix/stdio.c
new file mode 100644
index 0000000..12ab678
--- /dev/null
+++ b/lib/isc/unix/stdio.c
@@ -0,0 +1,152 @@
+/*
+ * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
+ *
+ * SPDX-License-Identifier: MPL-2.0
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, you can obtain one at https://mozilla.org/MPL/2.0/.
+ *
+ * See the COPYRIGHT file distributed with this work for additional
+ * information regarding copyright ownership.
+ */
+
+#include <errno.h>
+#include <unistd.h>
+
+#include <isc/stat.h>
+#include <isc/stdio.h>
+#include <isc/util.h>
+
+#include "errno2result.h"
+
+isc_result_t
+isc_stdio_open(const char *filename, const char *mode, FILE **fp) {
+ FILE *f;
+
+ f = fopen(filename, mode);
+ if (f == NULL) {
+ return (isc__errno2result(errno));
+ }
+ *fp = f;
+ return (ISC_R_SUCCESS);
+}
+
+isc_result_t
+isc_stdio_close(FILE *f) {
+ int r;
+
+ r = fclose(f);
+ if (r == 0) {
+ return (ISC_R_SUCCESS);
+ } else {
+ return (isc__errno2result(errno));
+ }
+}
+
+isc_result_t
+isc_stdio_seek(FILE *f, off_t offset, int whence) {
+ int r;
+
+ r = fseeko(f, offset, whence);
+ if (r == 0) {
+ return (ISC_R_SUCCESS);
+ } else {
+ return (isc__errno2result(errno));
+ }
+}
+
+isc_result_t
+isc_stdio_tell(FILE *f, off_t *offsetp) {
+ off_t r;
+
+ REQUIRE(offsetp != NULL);
+
+ r = ftello(f);
+ if (r >= 0) {
+ *offsetp = r;
+ return (ISC_R_SUCCESS);
+ } else {
+ return (isc__errno2result(errno));
+ }
+}
+
+isc_result_t
+isc_stdio_read(void *ptr, size_t size, size_t nmemb, FILE *f, size_t *nret) {
+ isc_result_t result = ISC_R_SUCCESS;
+ size_t r;
+
+ clearerr(f);
+ r = fread(ptr, size, nmemb, f);
+ if (r != nmemb) {
+ if (feof(f)) {
+ result = ISC_R_EOF;
+ } else {
+ result = isc__errno2result(errno);
+ }
+ }
+ if (nret != NULL) {
+ *nret = r;
+ }
+ return (result);
+}
+
+isc_result_t
+isc_stdio_write(const void *ptr, size_t size, size_t nmemb, FILE *f,
+ size_t *nret) {
+ isc_result_t result = ISC_R_SUCCESS;
+ size_t r;
+
+ clearerr(f);
+ r = fwrite(ptr, size, nmemb, f);
+ if (r != nmemb) {
+ result = isc__errno2result(errno);
+ }
+ if (nret != NULL) {
+ *nret = r;
+ }
+ return (result);
+}
+
+isc_result_t
+isc_stdio_flush(FILE *f) {
+ int r;
+
+ r = fflush(f);
+ if (r == 0) {
+ return (ISC_R_SUCCESS);
+ } else {
+ return (isc__errno2result(errno));
+ }
+}
+
+/*
+ * OpenBSD has deprecated ENOTSUP in favor of EOPNOTSUPP.
+ */
+#if defined(EOPNOTSUPP) && !defined(ENOTSUP)
+#define ENOTSUP EOPNOTSUPP
+#endif /* if defined(EOPNOTSUPP) && !defined(ENOTSUP) */
+
+isc_result_t
+isc_stdio_sync(FILE *f) {
+ struct stat buf;
+ int r;
+
+ if (fstat(fileno(f), &buf) != 0) {
+ return (isc__errno2result(errno));
+ }
+
+ /*
+ * Only call fsync() on regular files.
+ */
+ if ((buf.st_mode & S_IFMT) != S_IFREG) {
+ return (ISC_R_SUCCESS);
+ }
+
+ r = fsync(fileno(f));
+ if (r == 0) {
+ return (ISC_R_SUCCESS);
+ } else {
+ return (isc__errno2result(errno));
+ }
+}
diff --git a/lib/isc/unix/stdtime.c b/lib/isc/unix/stdtime.c
new file mode 100644
index 0000000..ada19d0
--- /dev/null
+++ b/lib/isc/unix/stdtime.c
@@ -0,0 +1,68 @@
+/*
+ * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
+ *
+ * SPDX-License-Identifier: MPL-2.0
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, you can obtain one at https://mozilla.org/MPL/2.0/.
+ *
+ * See the COPYRIGHT file distributed with this work for additional
+ * information regarding copyright ownership.
+ */
+
+/*! \file */
+
+#include <errno.h>
+#include <stdbool.h>
+#include <stddef.h> /* NULL */
+#include <stdlib.h> /* NULL */
+#include <syslog.h>
+#include <time.h>
+
+#include <isc/stdtime.h>
+#include <isc/strerr.h>
+#include <isc/util.h>
+
+#define NS_PER_S 1000000000 /*%< Nanoseconds per second. */
+
+#if defined(CLOCK_REALTIME_COARSE)
+#define CLOCKSOURCE CLOCK_REALTIME_COARSE
+#elif defined(CLOCK_REALTIME_FAST)
+#define CLOCKSOURCE CLOCK_REALTIME_FAST
+#else /* if defined(CLOCK_REALTIME_COARSE) */
+#define CLOCKSOURCE CLOCK_REALTIME
+#endif /* if defined(CLOCK_REALTIME_COARSE) */
+
+void
+isc_stdtime_get(isc_stdtime_t *t) {
+ REQUIRE(t != NULL);
+
+ struct timespec ts;
+
+ if (clock_gettime(CLOCKSOURCE, &ts) == -1) {
+ char strbuf[ISC_STRERRORSIZE];
+ strerror_r(errno, strbuf, sizeof(strbuf));
+ isc_error_fatal(__FILE__, __LINE__, "clock_gettime failed: %s",
+ strbuf);
+ }
+
+ REQUIRE(ts.tv_sec > 0 && ts.tv_nsec >= 0 && ts.tv_nsec < NS_PER_S);
+
+ *t = (isc_stdtime_t)ts.tv_sec;
+}
+
+void
+isc_stdtime_tostring(isc_stdtime_t t, char *out, size_t outlen) {
+ time_t when;
+
+ REQUIRE(out != NULL);
+ REQUIRE(outlen >= 26);
+
+ UNUSED(outlen);
+
+ /* time_t and isc_stdtime_t might be different sizes */
+ when = t;
+ INSIST((ctime_r(&when, out) != NULL));
+ *(out + strlen(out) - 1) = '\0';
+}
diff --git a/lib/isc/unix/syslog.c b/lib/isc/unix/syslog.c
new file mode 100644
index 0000000..81b99ca
--- /dev/null
+++ b/lib/isc/unix/syslog.c
@@ -0,0 +1,73 @@
+/*
+ * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
+ *
+ * SPDX-License-Identifier: MPL-2.0
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, you can obtain one at https://mozilla.org/MPL/2.0/.
+ *
+ * See the COPYRIGHT file distributed with this work for additional
+ * information regarding copyright ownership.
+ */
+
+/*! \file */
+
+#include <stdlib.h>
+#include <syslog.h>
+
+#include <isc/result.h>
+#include <isc/string.h>
+#include <isc/syslog.h>
+#include <isc/util.h>
+
+static struct dsn_c_pvt_sfnt {
+ int val;
+ const char *strval;
+} facilities[] = { { LOG_KERN, "kern" },
+ { LOG_USER, "user" },
+ { LOG_MAIL, "mail" },
+ { LOG_DAEMON, "daemon" },
+ { LOG_AUTH, "auth" },
+ { LOG_SYSLOG, "syslog" },
+ { LOG_LPR, "lpr" },
+#ifdef LOG_NEWS
+ { LOG_NEWS, "news" },
+#endif /* ifdef LOG_NEWS */
+#ifdef LOG_UUCP
+ { LOG_UUCP, "uucp" },
+#endif /* ifdef LOG_UUCP */
+#ifdef LOG_CRON
+ { LOG_CRON, "cron" },
+#endif /* ifdef LOG_CRON */
+#ifdef LOG_AUTHPRIV
+ { LOG_AUTHPRIV, "authpriv" },
+#endif /* ifdef LOG_AUTHPRIV */
+#ifdef LOG_FTP
+ { LOG_FTP, "ftp" },
+#endif /* ifdef LOG_FTP */
+ { LOG_LOCAL0, "local0" },
+ { LOG_LOCAL1, "local1" },
+ { LOG_LOCAL2, "local2" },
+ { LOG_LOCAL3, "local3" },
+ { LOG_LOCAL4, "local4" },
+ { LOG_LOCAL5, "local5" },
+ { LOG_LOCAL6, "local6" },
+ { LOG_LOCAL7, "local7" },
+ { 0, NULL } };
+
+isc_result_t
+isc_syslog_facilityfromstring(const char *str, int *facilityp) {
+ int i;
+
+ REQUIRE(str != NULL);
+ REQUIRE(facilityp != NULL);
+
+ for (i = 0; facilities[i].strval != NULL; i++) {
+ if (strcasecmp(facilities[i].strval, str) == 0) {
+ *facilityp = facilities[i].val;
+ return (ISC_R_SUCCESS);
+ }
+ }
+ return (ISC_R_NOTFOUND);
+}
diff --git a/lib/isc/unix/time.c b/lib/isc/unix/time.c
new file mode 100644
index 0000000..02291e4
--- /dev/null
+++ b/lib/isc/unix/time.c
@@ -0,0 +1,553 @@
+/*
+ * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
+ *
+ * SPDX-License-Identifier: MPL-2.0
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, you can obtain one at https://mozilla.org/MPL/2.0/.
+ *
+ * See the COPYRIGHT file distributed with this work for additional
+ * information regarding copyright ownership.
+ */
+
+/*! \file */
+
+#include <errno.h>
+#include <inttypes.h>
+#include <limits.h>
+#include <stdbool.h>
+#include <stdlib.h>
+#include <sys/time.h> /* Required for struct timeval on some platforms. */
+#include <syslog.h>
+#include <time.h>
+
+#include <isc/log.h>
+#include <isc/platform.h>
+#include <isc/print.h>
+#include <isc/strerr.h>
+#include <isc/string.h>
+#include <isc/time.h>
+#include <isc/tm.h>
+#include <isc/util.h>
+
+#define NS_PER_S 1000000000 /*%< Nanoseconds per second. */
+#define NS_PER_US 1000 /*%< Nanoseconds per microsecond. */
+#define NS_PER_MS 1000000 /*%< Nanoseconds per millisecond. */
+
+#if defined(CLOCK_REALTIME)
+#define CLOCKSOURCE_HIRES CLOCK_REALTIME
+#endif /* #if defined(CLOCK_REALTIME) */
+
+#if defined(CLOCK_REALTIME_COARSE)
+#define CLOCKSOURCE CLOCK_REALTIME_COARSE
+#elif defined(CLOCK_REALTIME_FAST)
+#define CLOCKSOURCE CLOCK_REALTIME_FAST
+#else /* if defined(CLOCK_REALTIME_COARSE) */
+#define CLOCKSOURCE CLOCK_REALTIME
+#endif /* if defined(CLOCK_REALTIME_COARSE) */
+
+#if !defined(CLOCKSOURCE_HIRES)
+#define CLOCKSOURCE_HIRES CLOCKSOURCE
+#endif /* #ifndef CLOCKSOURCE_HIRES */
+
+/*%
+ *** Intervals
+ ***/
+
+#if !defined(UNIT_TESTING)
+static const isc_interval_t zero_interval = { 0, 0 };
+const isc_interval_t *const isc_interval_zero = &zero_interval;
+#endif
+
+void
+isc_interval_set(isc_interval_t *i, unsigned int seconds,
+ unsigned int nanoseconds) {
+ REQUIRE(i != NULL);
+ REQUIRE(nanoseconds < NS_PER_S);
+
+ i->seconds = seconds;
+ i->nanoseconds = nanoseconds;
+}
+
+bool
+isc_interval_iszero(const isc_interval_t *i) {
+ REQUIRE(i != NULL);
+ INSIST(i->nanoseconds < NS_PER_S);
+
+ if (i->seconds == 0 && i->nanoseconds == 0) {
+ return (true);
+ }
+
+ return (false);
+}
+
+/***
+ *** Absolute Times
+ ***/
+
+#if !defined(UNIT_TESTING)
+static const isc_time_t epoch = { 0, 0 };
+const isc_time_t *const isc_time_epoch = &epoch;
+#endif
+
+void
+isc_time_set(isc_time_t *t, unsigned int seconds, unsigned int nanoseconds) {
+ REQUIRE(t != NULL);
+ REQUIRE(nanoseconds < NS_PER_S);
+
+ t->seconds = seconds;
+ t->nanoseconds = nanoseconds;
+}
+
+void
+isc_time_settoepoch(isc_time_t *t) {
+ REQUIRE(t != NULL);
+
+ t->seconds = 0;
+ t->nanoseconds = 0;
+}
+
+bool
+isc_time_isepoch(const isc_time_t *t) {
+ REQUIRE(t != NULL);
+ INSIST(t->nanoseconds < NS_PER_S);
+
+ if (t->seconds == 0 && t->nanoseconds == 0) {
+ return (true);
+ }
+
+ return (false);
+}
+
+static isc_result_t
+time_now(isc_time_t *t, clockid_t clock) {
+ struct timespec ts;
+ char strbuf[ISC_STRERRORSIZE];
+
+ REQUIRE(t != NULL);
+
+ if (clock_gettime(clock, &ts) == -1) {
+ strerror_r(errno, strbuf, sizeof(strbuf));
+ UNEXPECTED_ERROR(__FILE__, __LINE__, "%s", strbuf);
+ return (ISC_R_UNEXPECTED);
+ }
+
+ if (ts.tv_sec < 0 || ts.tv_nsec < 0 || ts.tv_nsec >= NS_PER_S) {
+ return (ISC_R_UNEXPECTED);
+ }
+
+ /*
+ * Ensure the tv_sec value fits in t->seconds.
+ */
+ if (sizeof(ts.tv_sec) > sizeof(t->seconds) &&
+ ((ts.tv_sec | (unsigned int)-1) ^ (unsigned int)-1) != 0U)
+ {
+ return (ISC_R_RANGE);
+ }
+
+ t->seconds = ts.tv_sec;
+ t->nanoseconds = ts.tv_nsec;
+
+ return (ISC_R_SUCCESS);
+}
+
+isc_result_t
+isc_time_now_hires(isc_time_t *t) {
+ return time_now(t, CLOCKSOURCE_HIRES);
+}
+
+isc_result_t
+isc_time_now(isc_time_t *t) {
+ return time_now(t, CLOCKSOURCE);
+}
+
+isc_result_t
+isc_time_nowplusinterval(isc_time_t *t, const isc_interval_t *i) {
+ struct timespec ts;
+ char strbuf[ISC_STRERRORSIZE];
+
+ REQUIRE(t != NULL);
+ REQUIRE(i != NULL);
+ INSIST(i->nanoseconds < NS_PER_S);
+
+ if (clock_gettime(CLOCKSOURCE, &ts) == -1) {
+ strerror_r(errno, strbuf, sizeof(strbuf));
+ UNEXPECTED_ERROR(__FILE__, __LINE__, "%s", strbuf);
+ return (ISC_R_UNEXPECTED);
+ }
+
+ if (ts.tv_sec < 0 || ts.tv_nsec < 0 || ts.tv_nsec >= NS_PER_S) {
+ return (ISC_R_UNEXPECTED);
+ }
+
+ /*
+ * Ensure the resulting seconds value fits in the size of an
+ * unsigned int. (It is written this way as a slight optimization;
+ * note that even if both values == INT_MAX, then when added
+ * and getting another 1 added below the result is UINT_MAX.)
+ */
+ if ((ts.tv_sec > INT_MAX || i->seconds > INT_MAX) &&
+ ((long long)ts.tv_sec + i->seconds > UINT_MAX))
+ {
+ return (ISC_R_RANGE);
+ }
+
+ t->seconds = ts.tv_sec + i->seconds;
+ t->nanoseconds = ts.tv_nsec + i->nanoseconds;
+ if (t->nanoseconds >= NS_PER_S) {
+ t->seconds++;
+ t->nanoseconds -= NS_PER_S;
+ }
+
+ return (ISC_R_SUCCESS);
+}
+
+int
+isc_time_compare(const isc_time_t *t1, const isc_time_t *t2) {
+ REQUIRE(t1 != NULL && t2 != NULL);
+ INSIST(t1->nanoseconds < NS_PER_S && t2->nanoseconds < NS_PER_S);
+
+ if (t1->seconds < t2->seconds) {
+ return (-1);
+ }
+ if (t1->seconds > t2->seconds) {
+ return (1);
+ }
+ if (t1->nanoseconds < t2->nanoseconds) {
+ return (-1);
+ }
+ if (t1->nanoseconds > t2->nanoseconds) {
+ return (1);
+ }
+ return (0);
+}
+
+isc_result_t
+isc_time_add(const isc_time_t *t, const isc_interval_t *i, isc_time_t *result) {
+ REQUIRE(t != NULL && i != NULL && result != NULL);
+ REQUIRE(t->nanoseconds < NS_PER_S && i->nanoseconds < NS_PER_S);
+
+ /* Seconds */
+ if (t->seconds > UINT_MAX - i->seconds) {
+ return (ISC_R_RANGE);
+ }
+ result->seconds = t->seconds + i->seconds;
+
+ /* Nanoseconds */
+ result->nanoseconds = t->nanoseconds + i->nanoseconds;
+ if (result->nanoseconds >= NS_PER_S) {
+ if (result->seconds == UINT_MAX) {
+ return (ISC_R_RANGE);
+ }
+ result->nanoseconds -= NS_PER_S;
+ result->seconds++;
+ }
+
+ return (ISC_R_SUCCESS);
+}
+
+isc_result_t
+isc_time_subtract(const isc_time_t *t, const isc_interval_t *i,
+ isc_time_t *result) {
+ REQUIRE(t != NULL && i != NULL && result != NULL);
+ REQUIRE(t->nanoseconds < NS_PER_S && i->nanoseconds < NS_PER_S);
+
+ /* Seconds */
+ if (t->seconds < i->seconds) {
+ return (ISC_R_RANGE);
+ }
+ result->seconds = t->seconds - i->seconds;
+
+ /* Nanoseconds */
+ if (t->nanoseconds >= i->nanoseconds) {
+ result->nanoseconds = t->nanoseconds - i->nanoseconds;
+ } else {
+ if (result->seconds == 0) {
+ return (ISC_R_RANGE);
+ }
+ result->seconds--;
+ result->nanoseconds = NS_PER_S + t->nanoseconds -
+ i->nanoseconds;
+ }
+
+ return (ISC_R_SUCCESS);
+}
+
+uint64_t
+isc_time_microdiff(const isc_time_t *t1, const isc_time_t *t2) {
+ uint64_t i1, i2, i3;
+
+ REQUIRE(t1 != NULL && t2 != NULL);
+ INSIST(t1->nanoseconds < NS_PER_S && t2->nanoseconds < NS_PER_S);
+
+ i1 = (uint64_t)t1->seconds * NS_PER_S + t1->nanoseconds;
+ i2 = (uint64_t)t2->seconds * NS_PER_S + t2->nanoseconds;
+
+ if (i1 <= i2) {
+ return (0);
+ }
+
+ i3 = i1 - i2;
+
+ /*
+ * Convert to microseconds.
+ */
+ i3 /= NS_PER_US;
+
+ return (i3);
+}
+
+uint32_t
+isc_time_seconds(const isc_time_t *t) {
+ REQUIRE(t != NULL);
+ INSIST(t->nanoseconds < NS_PER_S);
+
+ return ((uint32_t)t->seconds);
+}
+
+isc_result_t
+isc_time_secondsastimet(const isc_time_t *t, time_t *secondsp) {
+ time_t seconds;
+
+ REQUIRE(t != NULL);
+ INSIST(t->nanoseconds < NS_PER_S);
+
+ /*
+ * Ensure that the number of seconds represented by t->seconds
+ * can be represented by a time_t. Since t->seconds is an
+ * unsigned int and since time_t is mostly opaque, this is
+ * trickier than it seems. (This standardized opaqueness of
+ * time_t is *very* frustrating; time_t is not even limited to
+ * being an integral type.)
+ *
+ * The mission, then, is to avoid generating any kind of warning
+ * about "signed versus unsigned" while trying to determine if
+ * the unsigned int t->seconds is out range for tv_sec,
+ * which is pretty much only true if time_t is a signed integer
+ * of the same size as the return value of isc_time_seconds.
+ *
+ * If the paradox in the if clause below is true, t->seconds is
+ * out of range for time_t.
+ */
+ seconds = (time_t)t->seconds;
+
+ INSIST(sizeof(unsigned int) == sizeof(uint32_t));
+ INSIST(sizeof(time_t) >= sizeof(uint32_t));
+
+ if (t->seconds > (~0U >> 1) && seconds <= (time_t)(~0U >> 1)) {
+ return (ISC_R_RANGE);
+ }
+
+ *secondsp = seconds;
+
+ return (ISC_R_SUCCESS);
+}
+
+uint32_t
+isc_time_nanoseconds(const isc_time_t *t) {
+ REQUIRE(t != NULL);
+
+ ENSURE(t->nanoseconds < NS_PER_S);
+
+ return ((uint32_t)t->nanoseconds);
+}
+
+void
+isc_time_formattimestamp(const isc_time_t *t, char *buf, unsigned int len) {
+ time_t now;
+ unsigned int flen;
+ struct tm tm;
+
+ REQUIRE(t != NULL);
+ INSIST(t->nanoseconds < NS_PER_S);
+ REQUIRE(buf != NULL);
+ REQUIRE(len > 0);
+
+ now = (time_t)t->seconds;
+ flen = strftime(buf, len, "%d-%b-%Y %X", localtime_r(&now, &tm));
+ INSIST(flen < len);
+ if (flen != 0) {
+ snprintf(buf + flen, len - flen, ".%03u",
+ t->nanoseconds / NS_PER_MS);
+ } else {
+ strlcpy(buf, "99-Bad-9999 99:99:99.999", len);
+ }
+}
+
+void
+isc_time_formathttptimestamp(const isc_time_t *t, char *buf, unsigned int len) {
+ time_t now;
+ unsigned int flen;
+ struct tm tm;
+
+ REQUIRE(t != NULL);
+ INSIST(t->nanoseconds < NS_PER_S);
+ REQUIRE(buf != NULL);
+ REQUIRE(len > 0);
+
+ /*
+ * 5 spaces, 1 comma, 3 GMT, 2 %d, 4 %Y, 8 %H:%M:%S, 3+ %a, 3+
+ * %b (29+)
+ */
+ now = (time_t)t->seconds;
+ flen = strftime(buf, len, "%a, %d %b %Y %H:%M:%S GMT",
+ gmtime_r(&now, &tm));
+ INSIST(flen < len);
+}
+
+isc_result_t
+isc_time_parsehttptimestamp(char *buf, isc_time_t *t) {
+ struct tm t_tm;
+ time_t when;
+ char *p;
+
+ REQUIRE(buf != NULL);
+ REQUIRE(t != NULL);
+
+ p = isc_tm_strptime(buf, "%a, %d %b %Y %H:%M:%S", &t_tm);
+ if (p == NULL) {
+ return (ISC_R_UNEXPECTED);
+ }
+ when = isc_tm_timegm(&t_tm);
+ if (when == -1) {
+ return (ISC_R_UNEXPECTED);
+ }
+ isc_time_set(t, when, 0);
+ return (ISC_R_SUCCESS);
+}
+
+void
+isc_time_formatISO8601L(const isc_time_t *t, char *buf, unsigned int len) {
+ time_t now;
+ unsigned int flen;
+ struct tm tm;
+
+ REQUIRE(t != NULL);
+ INSIST(t->nanoseconds < NS_PER_S);
+ REQUIRE(buf != NULL);
+ REQUIRE(len > 0);
+
+ now = (time_t)t->seconds;
+ flen = strftime(buf, len, "%Y-%m-%dT%H:%M:%S", localtime_r(&now, &tm));
+ INSIST(flen < len);
+}
+
+void
+isc_time_formatISO8601Lms(const isc_time_t *t, char *buf, unsigned int len) {
+ time_t now;
+ unsigned int flen;
+ struct tm tm;
+
+ REQUIRE(t != NULL);
+ INSIST(t->nanoseconds < NS_PER_S);
+ REQUIRE(buf != NULL);
+ REQUIRE(len > 0);
+
+ now = (time_t)t->seconds;
+ flen = strftime(buf, len, "%Y-%m-%dT%H:%M:%S", localtime_r(&now, &tm));
+ INSIST(flen < len);
+ if (flen > 0U && len - flen >= 6) {
+ snprintf(buf + flen, len - flen, ".%03u",
+ t->nanoseconds / NS_PER_MS);
+ }
+}
+
+void
+isc_time_formatISO8601Lus(const isc_time_t *t, char *buf, unsigned int len) {
+ time_t now;
+ unsigned int flen;
+ struct tm tm;
+
+ REQUIRE(t != NULL);
+ INSIST(t->nanoseconds < NS_PER_S);
+ REQUIRE(buf != NULL);
+ REQUIRE(len > 0);
+
+ now = (time_t)t->seconds;
+ flen = strftime(buf, len, "%Y-%m-%dT%H:%M:%S", localtime_r(&now, &tm));
+ INSIST(flen < len);
+ if (flen > 0U && len - flen >= 6) {
+ snprintf(buf + flen, len - flen, ".%06u",
+ t->nanoseconds / NS_PER_US);
+ }
+}
+
+void
+isc_time_formatISO8601(const isc_time_t *t, char *buf, unsigned int len) {
+ time_t now;
+ unsigned int flen;
+ struct tm tm;
+
+ REQUIRE(t != NULL);
+ INSIST(t->nanoseconds < NS_PER_S);
+ REQUIRE(buf != NULL);
+ REQUIRE(len > 0);
+
+ now = (time_t)t->seconds;
+ flen = strftime(buf, len, "%Y-%m-%dT%H:%M:%SZ", gmtime_r(&now, &tm));
+ INSIST(flen < len);
+}
+
+void
+isc_time_formatISO8601ms(const isc_time_t *t, char *buf, unsigned int len) {
+ time_t now;
+ unsigned int flen;
+ struct tm tm;
+
+ REQUIRE(t != NULL);
+ INSIST(t->nanoseconds < NS_PER_S);
+ REQUIRE(buf != NULL);
+ REQUIRE(len > 0);
+
+ now = (time_t)t->seconds;
+ flen = strftime(buf, len, "%Y-%m-%dT%H:%M:%SZ", gmtime_r(&now, &tm));
+ INSIST(flen < len);
+ if (flen > 0U && len - flen >= 5) {
+ flen -= 1; /* rewind one character (Z) */
+ snprintf(buf + flen, len - flen, ".%03uZ",
+ t->nanoseconds / NS_PER_MS);
+ }
+}
+
+void
+isc_time_formatISO8601us(const isc_time_t *t, char *buf, unsigned int len) {
+ time_t now;
+ unsigned int flen;
+ struct tm tm;
+
+ REQUIRE(t != NULL);
+ INSIST(t->nanoseconds < NS_PER_S);
+ REQUIRE(buf != NULL);
+ REQUIRE(len > 0);
+
+ now = (time_t)t->seconds;
+ flen = strftime(buf, len, "%Y-%m-%dT%H:%M:%SZ", gmtime_r(&now, &tm));
+ INSIST(flen < len);
+ if (flen > 0U && len - flen >= 5) {
+ flen -= 1; /* rewind one character (Z) */
+ snprintf(buf + flen, len - flen, ".%06uZ",
+ t->nanoseconds / NS_PER_US);
+ }
+}
+
+void
+isc_time_formatshorttimestamp(const isc_time_t *t, char *buf,
+ unsigned int len) {
+ time_t now;
+ unsigned int flen;
+ struct tm tm;
+
+ REQUIRE(t != NULL);
+ INSIST(t->nanoseconds < NS_PER_S);
+ REQUIRE(buf != NULL);
+ REQUIRE(len > 0);
+
+ now = (time_t)t->seconds;
+ flen = strftime(buf, len, "%Y%m%d%H%M%S", gmtime_r(&now, &tm));
+ INSIST(flen < len);
+ if (flen > 0U && len - flen >= 5) {
+ snprintf(buf + flen, len - flen, "%03u",
+ t->nanoseconds / NS_PER_MS);
+ }
+}