HALF ECHO LEARN / REFERENCE COLLECTION
v262.2src/core/socket.c
Git blob: 3eea7e4c0557a4acc7b3916226c5571929f54015
Lines 1001–2000 of 3,800
case SOCKET_MQUEUE:
(void) mq_unlink(p->path);
break;
case SOCKET_SOCKET:
(void) socket_address_unlink(&p->address);
break;
default:
;
}
}
if (s->remove_on_stop)
STRV_FOREACH(i, s->symlinks)
(void) unlink(*i);
/* Note that we don't return NULL here, since s has not been freed. */
}
DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(Socket*, socket_close_fds, NULL);
#define log_socket_option_errno(s, e, option) \
({ \
int _e_ = (e); \
log_unit_full_errno( \
UNIT(s), \
ERRNO_IS_NOT_SUPPORTED(_e_) || \
ERRNO_IS_PRIVILEGE(_e_) ? LOG_DEBUG : LOG_WARNING, \
_e_, \
"Failed to set %s socket option, ignoring: %m", \
option); \
})
static void socket_apply_socket_options(Socket *s, SocketPort *p, int fd) {
int r;
assert(s);
assert(p);
assert(fd >= 0);
if (s->keep_alive) {
r = setsockopt_int(fd, SOL_SOCKET, SO_KEEPALIVE, true);
if (r < 0)
log_socket_option_errno(s, r, "SO_KEEPALIVE");
}
if (timestamp_is_set(s->keep_alive_time)) {
r = setsockopt_int(fd, SOL_TCP, TCP_KEEPIDLE, s->keep_alive_time / USEC_PER_SEC);
if (r < 0)
log_socket_option_errno(s, r, "TCP_KEEPIDLE");
}
if (s->keep_alive_interval > 0) {
r = setsockopt_int(fd, SOL_TCP, TCP_KEEPINTVL, s->keep_alive_interval / USEC_PER_SEC);
if (r < 0)
log_socket_option_errno(s, r, "TCP_KEEPINTVL");
}
if (s->keep_alive_cnt > 0) {
r = setsockopt_int(fd, SOL_TCP, TCP_KEEPCNT, s->keep_alive_cnt);
if (r < 0)
log_socket_option_errno(s, r, "TCP_KEEPCNT");
}
if (s->defer_accept > 0) {
r = setsockopt_int(fd, SOL_TCP, TCP_DEFER_ACCEPT, s->defer_accept / USEC_PER_SEC);
if (r < 0)
log_socket_option_errno(s, r, "TCP_DEFER_ACCEPT");
}
if (s->no_delay) {
if (s->socket_protocol == IPPROTO_SCTP) {
r = setsockopt_int(fd, SOL_SCTP, SCTP_NODELAY, true);
if (r < 0)
log_socket_option_errno(s, r, "SCTP_NODELAY");
} else {
r = setsockopt_int(fd, SOL_TCP, TCP_NODELAY, true);
if (r < 0)
log_socket_option_errno(s, r, "TCP_NODELAY");
}
}
if (s->broadcast) {
r = setsockopt_int(fd, SOL_SOCKET, SO_BROADCAST, true);
if (r < 0)
log_socket_option_errno(s, r, "SO_BROADCAST");
}
if (s->pass_cred) {
r = setsockopt_int(fd, SOL_SOCKET, SO_PASSCRED, true);
if (r < 0)
log_socket_option_errno(s, r, "SO_PASSCRED");
}
if (s->pass_pidfd) {
r = setsockopt_int(fd, SOL_SOCKET, SO_PASSPIDFD, true);
if (r < 0)
log_socket_option_errno(s, r, "SO_PASSPIDFD");
}
if (s->pass_sec) {
r = setsockopt_int(fd, SOL_SOCKET, SO_PASSSEC, true);
if (r < 0)
log_socket_option_errno(s, r, "SO_PASSSEC");
}
if (s->pass_pktinfo) {
r = socket_set_recvpktinfo(fd, socket_address_family(&p->address), true);
if (r < 0)
log_socket_option_errno(s, r, "packet info");
}
if (!s->pass_rights) {
r = setsockopt_int(fd, SOL_SOCKET, SO_PASSRIGHTS, false);
if (r < 0)
log_socket_option_errno(s, r, "SO_PASSRIGHTS");
}
if (s->timestamping != SOCKET_TIMESTAMPING_OFF) {
r = setsockopt_int(fd, SOL_SOCKET,
s->timestamping == SOCKET_TIMESTAMPING_NS ? SO_TIMESTAMPNS : SO_TIMESTAMP,
true);
if (r < 0)
log_socket_option_errno(s, r, "timestamping");
}
if (s->priority >= 0) {
r = setsockopt_int(fd, SOL_SOCKET, SO_PRIORITY, s->priority);
if (r < 0)
log_socket_option_errno(s, r, "SO_PRIORITY");
}
if (s->receive_buffer > 0) {
r = fd_set_rcvbuf(fd, s->receive_buffer, false);
if (r < 0)
log_socket_option_errno(s, r, "SO_RCVBUF/SO_RCVBUFFORCE");
}
if (s->send_buffer > 0) {
r = fd_set_sndbuf(fd, s->send_buffer, false);
if (r < 0)
log_socket_option_errno(s, r, "SO_SNDBUF/SO_SNDBUFFORCE");
}
if (s->mark >= 0) {
r = setsockopt_int(fd, SOL_SOCKET, SO_MARK, s->mark);
if (r < 0)
log_socket_option_errno(s, r, "SO_MARK");
}
if (s->ip_tos >= 0) {
r = setsockopt_int(fd, IPPROTO_IP, IP_TOS, s->ip_tos);
if (r < 0)
log_socket_option_errno(s, r, "IP_TOS");
}
if (s->ip_ttl >= 0) {
r = socket_set_ttl(fd, socket_address_family(&p->address), s->ip_ttl);
if (r < 0)
log_socket_option_errno(s, r, "IP_TTL/IPV6_UNICAST_HOPS");
}
if (s->tcp_congestion)
if (setsockopt(fd, SOL_TCP, TCP_CONGESTION, s->tcp_congestion, strlen(s->tcp_congestion)+1) < 0)
log_socket_option_errno(s, errno, "TCP_CONGESTION");
if (s->smack_ip_in) {
r = mac_smack_apply_fd(fd, SMACK_ATTR_IPIN, s->smack_ip_in);
if (r < 0)
log_unit_warning_errno(UNIT(s), r, "Failed to apply SMACK label for IP input, ignoring: %m");
}
if (s->smack_ip_out) {
r = mac_smack_apply_fd(fd, SMACK_ATTR_IPOUT, s->smack_ip_out);
if (r < 0)
log_unit_warning_errno(UNIT(s), r, "Failed to apply SMACK label for IP output, ignoring: %m");
}
}
static void socket_apply_fifo_options(Socket *s, int fd) {
int r;
assert(s);
assert(fd >= 0);
if (s->pipe_size > 0)
if (fcntl(fd, F_SETPIPE_SZ, s->pipe_size) < 0)
log_unit_warning_errno(UNIT(s), errno, "Setting pipe size failed, ignoring: %m");
if (s->smack) {
r = mac_smack_apply_fd(fd, SMACK_ATTR_ACCESS, s->smack);
if (r < 0)
log_unit_error_errno(UNIT(s), r, "SMACK relabelling failed, ignoring: %m");
}
}
static int fifo_address_create(
const char *path,
mode_t directory_mode,
mode_t socket_mode) {
_cleanup_close_ int fd = -EBADF;
mode_t old_mask;
struct stat st;
int r;
assert(path);
(void) mkdir_parents_label(path, directory_mode);
r = mac_selinux_create_file_prepare(path, S_IFIFO, /* label_context= */ NULL);
if (r < 0)
return r;
/* Enforce the right access mode for the fifo */
old_mask = umask(~socket_mode);
/* Include the original umask in our mask */
(void) umask(~socket_mode | old_mask);
r = mkfifo(path, socket_mode);
(void) umask(old_mask);
if (r < 0 && errno != EEXIST) {
r = -errno;
goto fail;
}
fd = open(path, O_RDWR | O_CLOEXEC | O_NOCTTY | O_NONBLOCK | O_NOFOLLOW);
if (fd < 0) {
r = -errno;
goto fail;
}
mac_selinux_create_file_clear();
if (fstat(fd, &st) < 0) {
r = -errno;
goto fail;
}
if (!S_ISFIFO(st.st_mode) ||
(st.st_mode & 0777) != (socket_mode & ~old_mask) ||
st.st_uid != getuid() ||
st.st_gid != getgid()) {
r = -EEXIST;
goto fail;
}
return TAKE_FD(fd);
fail:
mac_selinux_create_file_clear();
return r;
}
static int special_address_create(const char *path, bool writable) {
_cleanup_close_ int fd = -EBADF;
struct stat st;
assert(path);
fd = open(path, (writable ? O_RDWR : O_RDONLY)|O_CLOEXEC|O_NOCTTY|O_NONBLOCK|O_NOFOLLOW);
if (fd < 0)
return -errno;
if (fstat(fd, &st) < 0)
return -errno;
/* Check whether this is a /proc, /sys or /dev file or char device */
if (!S_ISREG(st.st_mode) && !S_ISCHR(st.st_mode))
return -EEXIST;
return TAKE_FD(fd);
}
static int usbffs_address_create_at(int dfd, const char *name) {
_cleanup_close_ int fd = -EBADF;
struct stat st;
assert(dfd >= 0);
assert(name);
fd = openat(dfd, name, O_RDWR|O_CLOEXEC|O_NOCTTY|O_NONBLOCK|O_NOFOLLOW);
if (fd < 0)
return -errno;
if (fstat(fd, &st) < 0)
return -errno;
/* Check whether this is a regular file (ffs endpoint) */
if (!S_ISREG(st.st_mode))
return -EEXIST;
return TAKE_FD(fd);
}
static int mq_address_create(
const char *path,
mode_t mq_mode,
long maxmsg,
long msgsize) {
_cleanup_close_ int fd = -EBADF;
struct stat st;
mode_t old_mask;
struct mq_attr _attr, *attr = NULL;
assert(path);
if (maxmsg > 0 && msgsize > 0) {
_attr = (struct mq_attr) {
.mq_flags = O_NONBLOCK,
.mq_maxmsg = maxmsg,
.mq_msgsize = msgsize,
};
attr = &_attr;
}
/* Enforce the right access mode for the mq */
old_mask = umask(~mq_mode);
/* Include the original umask in our mask */
(void) umask(~mq_mode | old_mask);
fd = mq_open(path, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_CREAT, mq_mode, attr);
(void) umask(old_mask);
if (fd < 0)
return -errno;
if (fstat(fd, &st) < 0)
return -errno;
if ((st.st_mode & 0777) != (mq_mode & ~old_mask) ||
st.st_uid != getuid() ||
st.st_gid != getgid())
return -EEXIST;
return TAKE_FD(fd);
}
static int socket_symlink(Socket *s) {
int r;
assert(s);
const char *target = socket_find_symlink_target(s);
if (!target)
return 0;
STRV_FOREACH(linkpath, s->symlinks) {
(void) mkdir_parents_label(*linkpath, s->directory_mode);
r = symlink_idempotent(target, *linkpath, false);
if (r == -EEXIST && s->remove_on_stop) {
/* If there's already something where we want to create the symlink, and the
* destructive RemoveOnStop= mode is set, then we might as well try to remove what
* already exists and try again. */
if (unlink(*linkpath) >= 0)
r = symlink_idempotent(target, *linkpath, false);
}
if (r < 0)
log_unit_warning_errno(UNIT(s), r, "Failed to create symlink %s %s %s, ignoring: %m",
*linkpath, glyph(GLYPH_ARROW_RIGHT), target);
}
return 0;
}
static int usbffs_write_descs(int fd, Service *s) {
int r;
assert(fd >= 0);
assert(s);
if (!s->usb_function_descriptors || !s->usb_function_strings)
return -EINVAL;
r = copy_file_fd(s->usb_function_descriptors, fd, 0);
if (r < 0)
return r;
return copy_file_fd(s->usb_function_strings, fd, 0);
}
static int usbffs_dispatch_eps(SocketPort *p, int dfd) {
_cleanup_free_ DirectoryEntries *des = NULL;
int r;
assert(p);
assert(dfd >= 0);
r = readdir_all(dfd, RECURSE_DIR_SORT|RECURSE_DIR_IGNORE_DOT, &des);
if (r < 0)
return r;
p->auxiliary_fds = new(int, des->n_entries);
if (!p->auxiliary_fds)
return -ENOMEM;
FOREACH_ARRAY(i, des->entries, des->n_entries) {
const struct dirent *de = *i;
if (streq(de->d_name, "ep0"))
continue;
r = usbffs_address_create_at(dfd, de->d_name);
if (r < 0)
goto fail;
p->auxiliary_fds[p->n_auxiliary_fds++] = r;
}
assert(p->n_auxiliary_fds < des->n_entries);
return 0;
fail:
socket_port_close_auxiliary_fds(p);
return r;
}
int socket_load_service_unit(Socket *s, int cfd, Unit **ret) {
int r;
/* Figure out what the unit that will be used to handle the connections on the socket looks like.
*
* If cfd < 0, then we don't have a connection yet. In case of Accept=yes sockets, use a fake
* instance name.
*/
assert(s);
assert(ret);
if (UNIT_ISSET(s->service)) {
*ret = UNIT_DEREF(s->service);
return 0;
}
if (!s->accept)
return -ENODATA;
/* Build the instance name and load the unit */
_cleanup_free_ char *prefix = NULL, *instance = NULL, *name = NULL;
r = unit_name_to_prefix(UNIT(s)->id, &prefix);
if (r < 0)
return r;
if (cfd >= 0) {
r = instance_from_socket(cfd, s->n_accepted, &instance);
if (ERRNO_IS_NEG_DISCONNECT(r))
/* ENOTCONN is legitimate if TCP RST was received. Other socket families might return
* different errors. This connection is over, but the socket unit lives on. */
return log_unit_debug_errno(UNIT(s), r,
"Got error %s on incoming socket, assuming aborted connection attempt, ignoring.",
ERRNO_NAME(r));
if (r < 0)
return r;
}
/* For accepting sockets, we don't know how the instance will be called until we get a connection and
* can figure out what the peer name is. So let's use "internal" as the instance to make it clear
* that this is not an actual peer name. We use "unknown" when we cannot figure out the peer. */
r = unit_name_build(prefix, instance ?: "internal", ".service", &name);
if (r < 0)
return r;
return manager_load_unit(UNIT(s)->manager, name, NULL, NULL, ret);
}
static int socket_determine_selinux_label(Socket *s, char **ret) {
Unit *service;
int r;
assert(s);
assert(ret);
r = socket_load_service_unit(s, /* cfd= */ -EBADF, &service);
if (r == -ENODATA) {
*ret = NULL;
return 0;
}
if (r < 0)
return r;
r = service_determine_exec_selinux_label(SERVICE(service), ret);
if (r == -ENODATA) {
*ret = NULL;
return 0;
}
return r;
}
static int socket_address_listen_do(
Socket *s,
const SocketAddress *address,
const char *selinux_label) {
assert(s);
assert(address);
return socket_address_listen(
address,
SOCK_CLOEXEC|SOCK_NONBLOCK,
s->backlog,
s->bind_ipv6_only,
s->bind_to_device,
s->reuse_port,
s->free_bind,
s->transparent,
s->directory_mode,
s->socket_mode,
selinux_label,
s->smack,
s->xattr_entrypoint,
s->xattr_listen);
}
#define log_address_error_errno(u, address, error, fmt) \
({ \
_cleanup_free_ char *_t = NULL; \
\
(void) socket_address_print(address, &_t); \
log_unit_error_errno(u, error, fmt, strna(_t)); \
})
static bool fork_needed(const SocketAddress *address, Socket *s) {
assert(address);
assert(s);
/* Check if we need to do the cgroup or netns stuff. If not we can do things much simpler. */
/* If there are any NFTSet= directives with cgroup source, we need the cgroup */
Unit *u = UNIT(s);
CGroupContext *c = unit_get_cgroup_context(u);
if (c)
FOREACH_ARRAY(nft_set, c->nft_set_context.sets, c->nft_set_context.n_sets)
if (nft_set->source == NFT_SET_SOURCE_CGROUP)
return true;
if (IN_SET(address->sockaddr.sa.sa_family, AF_INET, AF_INET6) &&
bpf_program_supported() > 0) /* If BPF firewalling isn't supported anyway — there's no point in this forking complexity */
return true;
return exec_needs_network_namespace(&s->exec_context);
}
static int socket_address_listen_in_cgroup(
Socket *s,
const SocketAddress *address,
const char *label) {
int r;
assert(s);
assert(address);
/* This is a wrapper around socket_address_listen(), that forks off a helper process inside the
* socket's cgroup and network namespace in which the socket is actually created. This way we ensure
* the socket is actually properly attached to the unit's cgroup for the purpose of BPF filtering and
* such. */
if (!fork_needed(address, s)) {
/* Shortcut things... */
r = socket_address_listen_do(s, address, label);
if (r < 0)
return log_address_error_errno(UNIT(s), address, r, "Failed to create listening socket (%s): %m");
return r;
}
r = unit_setup_exec_runtime(UNIT(s));
if (r < 0)
return log_unit_error_errno(UNIT(s), r, "Failed to acquire runtime: %m");
if (s->exec_runtime && s->exec_runtime->shared) {
if (s->exec_context.user_namespace_path &&
s->exec_runtime->shared->userns_storage_socket[0] >= 0) {
r = open_shareable_ns_path(s->exec_runtime->shared->userns_storage_socket, s->exec_context.user_namespace_path, CLONE_NEWUSER);
if (r < 0)
return log_unit_error_errno(UNIT(s), r, "Failed to open user namespace path %s: %m", s->exec_context.user_namespace_path);
}
if (s->exec_context.network_namespace_path &&
s->exec_runtime->shared->netns_storage_socket[0] >= 0) {
r = open_shareable_ns_path(s->exec_runtime->shared->netns_storage_socket, s->exec_context.network_namespace_path, CLONE_NEWNET);
if (r < 0)
return log_unit_error_errno(UNIT(s), r, "Failed to open network namespace path %s: %m", s->exec_context.network_namespace_path);
}
if (s->exec_context.ipc_namespace_path &&
s->exec_runtime->shared->ipcns_storage_socket[0] >= 0) {
r = open_shareable_ns_path(s->exec_runtime->shared->ipcns_storage_socket, s->exec_context.ipc_namespace_path, CLONE_NEWIPC);
if (r < 0)
return log_unit_error_errno(UNIT(s), r, "Failed to open IPC namespace path %s: %m", s->exec_context.ipc_namespace_path);
}
}
_cleanup_(pidref_done) PidRef pid = PIDREF_NULL;
_cleanup_close_pair_ int pair[2] = EBADF_PAIR;
_cleanup_close_ int fd = -EBADF;
if (socketpair(AF_UNIX, SOCK_SEQPACKET|SOCK_CLOEXEC, 0, pair) < 0)
return log_unit_error_errno(UNIT(s), errno, "Failed to create communication channel: %m");
r = unit_fork_helper_process(UNIT(s), "(sd-listen)", /* into_cgroup= */ true, &pid);
if (r < 0)
return log_unit_error_errno(UNIT(s), r, "Failed to fork off listener stub process: %m");
if (r == 0) {
/* Child */
pair[0] = safe_close(pair[0]);
if (exec_needs_network_namespace(&s->exec_context) &&
s->exec_runtime &&
s->exec_runtime->shared &&
s->exec_runtime->shared->netns_storage_socket[0] >= 0) {
if (namespace_type_supported(NAMESPACE_NET)) {
r = setup_shareable_ns(s->exec_runtime->shared->netns_storage_socket, CLONE_NEWNET);
if (r < 0) {
log_unit_error_errno(UNIT(s), r, "Failed to join network namespace: %m");
_exit(EXIT_NETWORK);
}
} else if (s->exec_context.network_namespace_path) {
log_unit_error(UNIT(s), "Network namespace path configured but network namespaces not supported.");
_exit(EXIT_NETWORK);
} else
log_unit_warning(UNIT(s), "PrivateNetwork=yes is configured, but the kernel does not support network namespaces, ignoring.");
}
fd = socket_address_listen_do(s, address, label);
if (fd < 0) {
log_address_error_errno(UNIT(s), address, fd, "Failed to create listening socket (%s): %m");
_exit(EXIT_FAILURE);
}
r = send_one_fd(pair[1], fd, 0);
if (r < 0) {
log_address_error_errno(UNIT(s), address, r, "Failed to send listening socket (%s) to parent: %m");
_exit(EXIT_FAILURE);
}
_exit(EXIT_SUCCESS);
}
pair[1] = safe_close(pair[1]);
fd = receive_one_fd(pair[0], 0);
/* We synchronously wait for the helper, as it shouldn't be slow */
r = pidref_wait_for_terminate_and_check("(sd-listen)", &pid, WAIT_LOG_ABNORMAL);
if (r < 0)
return r;
if (fd < 0)
return log_address_error_errno(UNIT(s), address, fd, "Failed to receive listening socket (%s): %m");
return TAKE_FD(fd);
}
static int socket_open_fds(Socket *orig_s) {
_cleanup_(socket_close_fdsp) Socket *s = orig_s;
_cleanup_freecon_ char *label = NULL;
bool know_label = false;
int r;
assert(s);
LIST_FOREACH(port, p, s->ports) {
if (p->fd >= 0)
continue;
switch (p->type) {
case SOCKET_SOCKET:
if (!know_label) {
/* Figure out the label, if we don't it know yet. We do it once for the first
* socket where we need this and remember it for the rest. */
r = socket_determine_selinux_label(s, &label);
if (r < 0)
return log_unit_error_errno(UNIT(s), r, "Failed to determine SELinux label: %m");
know_label = true;
}
/* Apply the socket protocol */
switch (p->address.type) {
case SOCK_STREAM:
if (IN_SET(s->socket_protocol, IPPROTO_SCTP, IPPROTO_MPTCP))
p->address.protocol = s->socket_protocol;
break;
case SOCK_SEQPACKET:
if (s->socket_protocol == IPPROTO_SCTP)
p->address.protocol = s->socket_protocol;
break;
case SOCK_DGRAM:
if (s->socket_protocol == IPPROTO_UDPLITE)
p->address.protocol = s->socket_protocol;
break;
}
p->fd = socket_address_listen_in_cgroup(s, &p->address, label);
if (p->fd < 0)
return p->fd;
socket_apply_socket_options(s, p, p->fd);
socket_symlink(s);
break;
case SOCKET_SPECIAL:
p->fd = special_address_create(p->path, s->writable);
if (p->fd < 0)
return log_unit_error_errno(UNIT(s), p->fd, "Failed to open special file '%s': %m", p->path);
break;
case SOCKET_FIFO:
p->fd = fifo_address_create(
p->path,
s->directory_mode,
s->socket_mode);
if (p->fd < 0)
return log_unit_error_errno(UNIT(s), p->fd, "Failed to open FIFO '%s': %m", p->path);
socket_apply_fifo_options(s, p->fd);
socket_symlink(s);
break;
case SOCKET_MQUEUE:
p->fd = mq_address_create(
p->path,
s->socket_mode,
s->mq_maxmsg,
s->mq_msgsize);
if (p->fd < 0)
return log_unit_error_errno(UNIT(s), p->fd, "Failed to open message queue '%s': %m", p->path);
break;
case SOCKET_USB_FUNCTION: {
_cleanup_close_ int dfd = -EBADF;
dfd = open(p->path, O_DIRECTORY|O_CLOEXEC);
if (dfd < 0)
return log_unit_error_errno(UNIT(s), errno,
"Failed to open USB FunctionFS dir '%s': %m", p->path);
p->fd = usbffs_address_create_at(dfd, "ep0");
if (p->fd < 0)
return log_unit_error_errno(UNIT(s), p->fd, "Failed to open USB FunctionFS ep0: %m");
r = usbffs_write_descs(p->fd, SERVICE(UNIT_DEREF(s->service)));
if (r < 0)
return log_unit_error_errno(UNIT(s), r, "Failed to write to USB FunctionFS ep0: %m");
r = usbffs_dispatch_eps(p, dfd);
if (r < 0)
return log_unit_error_errno(UNIT(s), r, "Failed to dispatch USB FunctionFS eps: %m");
break;
}
default:
assert_not_reached();
}
}
TAKE_PTR(s);
return 0;
}
static void socket_unwatch_fds(Socket *s) {
int r;
assert(s);
LIST_FOREACH(port, p, s->ports) {
if (p->fd < 0)
continue;
r = sd_event_source_set_enabled(p->event_source, SD_EVENT_OFF);
if (r < 0)
log_unit_debug_errno(UNIT(s), r, "Failed to disable event source: %m");
}
}
static int socket_watch_fds(Socket *s) {
int r;
assert(s);
LIST_FOREACH(port, p, s->ports) {
if (p->fd < 0)
continue;
if (p->event_source) {
r = sd_event_source_set_enabled(p->event_source, SD_EVENT_ON);
if (r < 0)
goto fail;
} else {
r = sd_event_add_io(UNIT(s)->manager->event, &p->event_source, p->fd, EPOLLIN, socket_dispatch_io, p);
if (r < 0)
goto fail;
(void) sd_event_source_set_description(p->event_source, "socket-port-io");
}
r = sd_event_source_set_ratelimit(p->event_source, s->poll_limit.interval, s->poll_limit.burst);
if (r < 0)
log_unit_debug_errno(UNIT(s), r, "Failed to set poll limit on I/O event source, ignoring: %m");
}
return 0;
fail:
log_unit_warning_errno(UNIT(s), r, "Failed to watch listening fds: %m");
socket_unwatch_fds(s);
return r;
}
enum {
SOCKET_OPEN_NONE,
SOCKET_OPEN_SOME,
SOCKET_OPEN_ALL,
};
static int socket_check_open(Socket *s) {
bool have_open = false, have_closed = false;
assert(s);
LIST_FOREACH(port, p, s->ports) {
if (p->fd < 0)
have_closed = true;
else
have_open = true;
if (have_open && have_closed)
return SOCKET_OPEN_SOME;
}
if (have_open)
return SOCKET_OPEN_ALL;
return SOCKET_OPEN_NONE;
}
static void socket_set_state(Socket *s, SocketState state) {
SocketState old_state;
assert(s);
if (s->state != state)
bus_unit_send_pending_change_signal(UNIT(s), false);
old_state = s->state;
s->state = state;
if (!SOCKET_STATE_WITH_PROCESS(state) && state != SOCKET_DEFERRED)
s->timer_event_source = sd_event_source_disable_unref(s->timer_event_source);
if (!SOCKET_STATE_WITH_PROCESS(state)) {
socket_unwatch_control_pid(s);
s->control_command = NULL;
s->control_command_id = _SOCKET_EXEC_COMMAND_INVALID;
}
if (state != SOCKET_LISTENING)
socket_unwatch_fds(s);
if (!IN_SET(state,
SOCKET_START_OPEN,
SOCKET_START_CHOWN,
SOCKET_START_POST,
SOCKET_LISTENING,
SOCKET_DEFERRED,
SOCKET_RUNNING,
SOCKET_STOP_PRE,
SOCKET_STOP_PRE_SIGTERM,
SOCKET_STOP_PRE_SIGKILL))
socket_close_fds(s);
if (state != SOCKET_DEFERRED)
unit_remove_from_stop_notify_queue(UNIT(s));
if (state != old_state)
log_unit_debug(UNIT(s), "Changed %s -> %s", socket_state_to_string(old_state), socket_state_to_string(state));
unit_notify(UNIT(s), state_translation_table[old_state], state_translation_table[state], /* reload_success= */ true);
}
static usec_t socket_coldplug_timeout(Socket *s) {
assert(s);
if (s->deserialized_state == SOCKET_CLEANING)
return usec_add(UNIT(s)->state_change_timestamp.monotonic, s->exec_context.timeout_clean_usec);
return usec_add(UNIT(s)->state_change_timestamp.monotonic, s->timeout_usec);
}
static int socket_coldplug(Unit *u) {
Socket *s = ASSERT_PTR(SOCKET(u));
int r;
assert(s->state == SOCKET_DEAD);
if (s->deserialized_state == s->state)
return 0;
/* Patch "deferred" back to "listening" and let socket_enter_running() figure out what to do.
* This saves us the trouble of handling flipping of DeferTrigger= vs Accept= during reload. */
if (s->deserialized_state == SOCKET_DEFERRED)
s->deserialized_state = SOCKET_LISTENING;
if (SOCKET_STATE_WITH_PROCESS(s->deserialized_state)) {
if (pidref_is_set(&s->control_pid) &&
pidref_is_unwaited(&s->control_pid) > 0) {
r = unit_watch_pidref(UNIT(s), &s->control_pid, /* exclusive= */ false);
if (r < 0)
return r;
}
r = socket_arm_timer(s, /* relative= */ false, socket_coldplug_timeout(s));
if (r < 0)
return r;
}
if (IN_SET(s->deserialized_state,
SOCKET_START_OPEN,
SOCKET_START_CHOWN,
SOCKET_START_POST,
SOCKET_LISTENING,
SOCKET_RUNNING)) {
/* Originally, we used to simply reopen all sockets here that we didn't have file descriptors
* for. However, this is problematic, as we won't traverse through the SOCKET_START_CHOWN
* state for them, and thus the UID/GID wouldn't be right. Hence, instead simply check if we
* have all fds open, and if there's a mismatch, warn loudly.
*
* Note that SOCKET_START_OPEN requires no special treatment, as it's only intermediate
* between SOCKET_START_PRE and SOCKET_START_CHOWN and shall otherwise not be observed.
* It's listed only for consistency. */
r = socket_check_open(s);
if (r == SOCKET_OPEN_NONE)
log_unit_warning(UNIT(s),
"Unit configuration changed while unit was running, "
"and no socket file descriptors are open. "
"Unit not functional until restarted.");
else if (r == SOCKET_OPEN_SOME)
log_unit_warning(UNIT(s),
"Unit configuration changed while unit was running, "
"and some socket file descriptors have not been opened yet. "
"Unit not fully functional until restarted.");
}
if (s->deserialized_state == SOCKET_LISTENING) {
r = socket_watch_fds(s);
if (r < 0)
return r;
}
if (!IN_SET(s->deserialized_state, SOCKET_DEAD, SOCKET_FAILED, SOCKET_CLEANING))
(void) unit_setup_exec_runtime(u);
socket_set_state(s, s->deserialized_state);
return 0;
}
static int socket_spawn(Socket *s, ExecCommand *c, PidRef *ret_pid) {
_cleanup_(exec_params_shallow_clear) ExecParameters exec_params = EXEC_PARAMETERS_INIT(
EXEC_APPLY_SANDBOXING|EXEC_APPLY_CHROOT|EXEC_APPLY_TTY_STDIN);
_cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
int r;
assert(s);
assert(c);
assert(ret_pid);
r = unit_prepare_exec(UNIT(s));
if (r < 0)
return r;
r = socket_arm_timer(s, /* relative= */ true, s->timeout_usec);
if (r < 0)
return r;
r = unit_set_exec_params(UNIT(s), &exec_params);
if (r < 0)
return r;