HALF ECHO LEARN / REFERENCE COLLECTION
v262.2src/varlinkctl/varlinkctl.c
Git blob: bf4c56945a9c5c0f3c246e7b14048b999b93f3e7
Lines 1001–1518 of 1,518
* lives in our process their fds. Hence we will now no longer bubble up any
* errors. */
r = move_fd(mfd, STDIN_FILENO, /* cloexec= */ false);
if (r < 0) {
log_error_errno(r, "Failed to move reply to STDIN_FILENO: %m");
_exit(EXIT_FAILURE);
}
(void) exec_with_listen_fds(exec_cmdline, fd_array, m);
/* This is only reached on failure, otherwise we continue with exec_cmdline. */
_exit(EXIT_FAILURE);
}
if (arg_quiet)
return r;
pager_open(arg_pager_flags);
sd_json_variant_dump(reply, arg_json_format_flags, stdout, NULL);
return r;
}
return 0;
}
VERB(verb_validate_idl, "validate-idl", "[FILE]\0", 1, 2, 0, "Validate interface description");
static int verb_validate_idl(int argc, char *argv[], uintptr_t _data, void *userdata) {
_cleanup_(sd_varlink_interface_freep) sd_varlink_interface *vi = NULL;
_cleanup_free_ char *text = NULL;
const char *fname;
unsigned line = 1, column = 1;
int r;
fname = argc > 1 ? argv[1] : NULL;
if (fname) {
r = read_full_file(fname, &text, NULL);
if (r < 0)
return log_error_errno(r, "Failed to read interface description file '%s': %m", fname);
} else {
r = read_full_stream(stdin, &text, NULL);
if (r < 0)
return log_error_errno(r, "Failed to read interface description from stdin: %m");
fname = "<stdin>";
}
r = sd_varlink_idl_parse(text, &line, &column, &vi);
if (r == -EBADMSG)
return log_error_errno(r, "%s:%u:%u: Bad syntax.", fname, line, column);
if (r == -ENETUNREACH)
return log_error_errno(r, "%s:%u:%u: Failed to parse interface description due an unresolved type.", fname, line, column);
if (r < 0)
return log_error_errno(r, "%s:%u:%u: Failed to parse interface description: %m", fname, line, column);
r = varlink_idl_consistent(vi, LOG_ERR);
if (r == -EUCLEAN)
return log_error_errno(r, "Interface is inconsistent.");
if (r == -ENOTUNIQ)
return log_error_errno(r, "Field or symbol not unique in interface.");
if (r < 0)
return log_error_errno(r, "Failed to check interface for consistency: %m");
if (arg_quiet)
return 0;
pager_open(arg_pager_flags);
r = sd_varlink_idl_dump(stdout, vi, SD_VARLINK_IDL_FORMAT_COLOR_AUTO, break_columns());
if (r < 0)
return log_error_errno(r, "Failed to format parsed interface description: %m");
return 0;
}
VERB_NOARG(verb_list_registry, "list-registry", "Show list of services in the service registry");
static int verb_list_registry(int argc, char *argv[], uintptr_t _data, void *userdata) {
int r;
assert(argc <= 1);
_cleanup_free_ char *reg_path = NULL;
r = runtime_directory_generic(arg_runtime_scope, "varlink/registry", ®_path);
if (r < 0)
return log_error_errno(r, "Failed to determine registry path: %m");
_cleanup_(table_unrefp) Table *table = table_new("interface", "entrypoint");
if (!table)
return log_oom();
(void) table_set_sort(table, (size_t) 0);
_cleanup_close_ int regfd = open(reg_path, O_DIRECTORY|O_CLOEXEC);
if (regfd < 0) {
if (errno != ENOENT)
return log_error_errno(errno, "Failed to open '%s': %m", reg_path);
} else {
_cleanup_free_ DirectoryEntries *des = NULL;
r = readdir_all(regfd, RECURSE_DIR_IGNORE_DOT|RECURSE_DIR_ENSURE_TYPE, &des);
if (r < 0)
return log_error_errno(r, "Failed to enumerate '%s': %m", reg_path);
FOREACH_ARRAY(i, des->entries, des->n_entries) {
struct dirent *de = *i;
if (!varlink_idl_interface_name_is_valid(de->d_name)) {
log_debug("Found file '%s' whose names does not qualify as valid Varlink interface name, skipping.", de->d_name);
continue;
}
_cleanup_free_ char *j = path_join(reg_path, de->d_name);
if (!j)
return log_oom();
switch (de->d_type) {
case DT_LNK: {
_cleanup_free_ char *resolved = NULL;
r = chase(j, /* root= */ NULL, CHASE_MUST_BE_SOCKET, &resolved, /* ret_fd= */ NULL);
if (r < 0) {
log_warning_errno(r, "Failed to resolve '%s', skipping: %m", j);
continue;
}
_cleanup_free_ char *address = strjoin("unix:", resolved);
if (!address)
return log_oom();
r = table_add_many(
table,
TABLE_STRING, de->d_name,
TABLE_STRING, address);
if (r < 0)
return r;
break;
}
case DT_SOCK: {
_cleanup_free_ char *address = strjoin("unix:", j);
if (!address)
return log_oom();
r = table_add_many(
table,
TABLE_STRING, de->d_name,
TABLE_STRING, address);
if (r < 0)
return r;
break;
}
default:
log_debug("Ignoring inode '%s' of unexpected type: %m", de->d_name);
}
}
}
if (!table_isempty(table) || sd_json_format_enabled(arg_json_format_flags)) {
r = table_print_with_pager(table, arg_json_format_flags, arg_pager_flags, /* show_header= */ true);
if (r < 0)
return log_error_errno(r, "Failed to output table: %m");
}
if (arg_legend && !sd_json_format_enabled(arg_json_format_flags)) {
if (table_isempty(table))
printf("No services registered.\n");
else
printf("\n%zu registered services listed.\n", table_get_rows(table) - 1);
}
return 0;
}
VERB_NOARG(verb_list_sockets, "list-sockets", "List listening Varlink entrypoint sockets");
static int verb_list_sockets(int argc, char *argv[], uintptr_t _data, void *userdata) {
int r;
assert(argc <= 1);
/* Enumerates listening, file-system bound AF_UNIX SOCK_STREAM sockets via the sock_diag netlink API,
* and lists those that are marked as Varlink entrypoints (i.e. carry the "user.varlink" xattr set to
* "entrypoint"). */
r = socket_xattr_supported();
if (r < 0)
return log_error_errno(r, "Failed to check if S_IFSOCK inodes support xattrs: %m");
if (r == 0)
return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "This kernel does not support extended attributes on socket inodes, cannot enumerate Varlink sockets.");
_cleanup_(sd_netlink_unrefp) sd_netlink *nl = NULL;
r = sd_sock_diag_socket_open(&nl);
if (r < 0)
return log_error_errno(r, "Failed to open sock_diag netlink socket: %m");
_cleanup_(sd_netlink_message_unrefp) sd_netlink_message *req = NULL;
r = sd_sock_diag_message_new_unix_dump(nl, &req, 1U << TCP_LISTEN, UDIAG_SHOW_NAME|UDIAG_SHOW_VFS);
if (r < 0)
return log_error_errno(r, "Failed to allocate AF_UNIX socket dump request: %m");
_cleanup_(sd_netlink_message_unrefp) sd_netlink_message *reply = NULL;
r = sd_netlink_call(nl, req, /* timeout= */ 0, &reply);
if (r < 0)
return log_error_errno(r, "Failed to issue AF_UNIX socket dump: %m");
_cleanup_(table_unrefp) Table *table = table_new("path", "access");
if (!table)
return log_oom();
(void) table_set_sort(table, (size_t) 0);
for (sd_netlink_message *m = reply; m; m = sd_netlink_message_next(m)) {
r = sd_netlink_message_get_errno(m);
if (r < 0) {
log_warning_errno(r, "Error in AF_UNIX socket dump entry, ignoring: %m");
continue;
}
struct unix_diag_msg udm;
r = sd_sock_diag_message_get_unix(m, &udm);
if (r < 0) {
log_warning_errno(r, "Failed to read AF_UNIX socket dump header, ignoring: %m");
continue;
}
/* We only care about listening stream sockets. The kernel already filtered by state, but
* there's no way to filter by type in the request, so we do that here (and double check the
* state for good measure). */
if (udm.udiag_type != SOCK_STREAM)
continue;
if (udm.udiag_state != TCP_LISTEN)
continue;
/* Read the bound name. This is not NUL terminated on the wire, hence read it as raw data. */
_cleanup_free_ void *name = NULL;
size_t name_size = 0;
r = sd_netlink_message_read_data(m, UNIX_DIAG_NAME, &name_size, &name);
if (r == -ENODATA) /* unnamed socket */
continue;
if (r < 0)
return log_error_errno(r, "Failed to read AF_UNIX socket name: %m");
/* Safely turn the raw, not necessarily NUL-terminated, name into a C string. This also
* rejects any name with embedded NUL bytes. */
_cleanup_free_ char *path = NULL;
r = make_cstring(name, name_size, MAKE_CSTRING_ALLOW_TRAILING_NUL, &path);
if (r < 0) {
log_debug_errno(r, "Failed to convert AF_UNIX socket name to string, skipping: %m");
continue;
}
if (!path_is_absolute(path)) {
log_debug("Got non-absolute AF_UNIX socket path '%s', skipping.", path);
continue;
}
/* The kernel also reports the backing VFS inode/device, but only for file-system bound
* sockets. We require it, both as a filter and to validate the path below. */
_cleanup_free_ void *vfs = NULL;
size_t vfs_size = 0;
r = sd_netlink_message_read_data(m, UNIX_DIAG_VFS, &vfs_size, &vfs);
if (r == -ENODATA)
continue; /* not fs bound */
if (r < 0)
return log_error_errno(r, "Failed to read AF_UNIX socket VFS data: %m");
if (vfs_size != sizeof(struct unix_diag_vfs)) {
log_warning("Got AF_UNIX socket VFS data of unexpected size, skipping.");
continue;
}
const struct unix_diag_vfs *uv = vfs;
/* Validate the path the kernel reported: open it (without following a final-component
* symlink), and verify it really is a socket whose inode and backing device match what
* netlink told us. This guards against the path having been unlinked/replaced in the
* meantime, so that we only ever read xattrs off the right inode. */
_cleanup_close_ int fd = open(path, O_PATH|O_CLOEXEC|O_NOFOLLOW);
if (fd < 0) {
log_debug_errno(errno, "Failed to open reported AF_UNIX socket path '%s', skipping: %m", path);
continue;
}
struct stat st;
if (fstat(fd, &st) < 0) {
log_debug_errno(errno, "Failed to stat reported AF_UNIX socket path '%s', skipping: %m", path);
continue;
}
if (!S_ISSOCK(st.st_mode)) {
log_debug("Reported AF_UNIX socket path '%s' is not a socket, skipping.", path);
continue;
}
/* the unix_diag_vfs structure only gives us 32bit inode numbers, which it truncates. hence lets truncate the value before comparison */
if (((st.st_ino ^ uv->udiag_vfs_ino) & UINT32_MAX) != 0) {
log_debug("Inode of reported AF_UNIX socket path '%s' does not match netlink data, skipping.", path);
continue;
}
/* udiag_vfs_dev carries the kernel-internal dev_t encoding, which differs from the userspace
* dev_t in st_dev — hence translate before comparing. */
if (STAT_DEV_TO_KERNEL(st.st_dev) != uv->udiag_vfs_dev) {
log_debug("Backing device of reported AF_UNIX socket path '%s' does not match netlink data, skipping.", path);
continue;
}
/* The path is validated now, hence we may safely read the Varlink role xattr off the fd. We
* only list sockets that are marked as Varlink entrypoints. */
_cleanup_free_ char *role = NULL;
r = fgetxattr_malloc(fd, "user.varlink", &role, /* ret_size= */ NULL);
if (r < 0) {
if (!ERRNO_IS_NEG_XATTR_ABSENT(r))
log_debug_errno(r, "Failed to read 'user.varlink' xattr of '%s', skipping: %m", path);
continue;
}
if (!streq(role, "entrypoint"))
continue;
_cleanup_free_ char *no = NULL;
r = access_fd(fd, W_OK);
if (r < 0) {
no = strjoin("no (", ERRNO_NAME(r), ")");
if (!no)
return log_oom();
}
r = table_add_many(
table,
TABLE_PATH, path,
TABLE_STRING, no ?: "yes",
TABLE_SET_COLOR, ansi_highlight_green_red(!no));
if (r < 0)
return r;
}
if (!table_isempty(table) || sd_json_format_enabled(arg_json_format_flags)) {
r = table_print_with_pager(table, arg_json_format_flags, arg_pager_flags, /* show_header= */ true);
if (r < 0)
return log_error_errno(r, "Failed to output table: %m");
}
if (arg_legend && !sd_json_format_enabled(arg_json_format_flags)) {
if (table_isempty(table))
printf("No sockets found.\n");
else
printf("\n%zu entrypoint sockets listed.\n", table_get_rows(table) - 1);
}
return 0;
}
/* Build a minimal IDL from a qualified method name so that introspection works. The parsed interface is
* returned to the caller who must keep it alive for the lifetime of the server
* (sd_varlink_server_add_interface() borrows the pointer). */
static int varlink_server_add_interface_from_method(sd_varlink_server *s, const char *method, sd_varlink_interface **ret_interface) {
assert(s);
assert(method);
assert(ret_interface);
const char *dot = strrchr(method, '.');
assert(dot);
_cleanup_free_ char *interface_name = strndup(method, dot - method);
if (!interface_name)
return log_oom();
/* Note that we do not need to put the upgrade flag comment here, it is added automatically
* by varlink_idl_format_symbol() because of the SD_VARLINK_REQUIRES_UPGRADE flag. */
_cleanup_free_ char *idl_text = strjoin(
"interface ", interface_name, "\n"
"\n"
"method ", dot + 1, " () -> ()\n");
if (!idl_text)
return log_oom();
_cleanup_(sd_varlink_interface_freep) sd_varlink_interface *iface = NULL;
int r = sd_varlink_idl_parse(idl_text, /* reterr_line= */ NULL, /* reterr_column= */ NULL, &iface);
if (r < 0)
return log_error_errno(r, "Failed to parse IDL for method '%s': %m", method);
/* Mark the method as requiring the upgrade flag so introspection shows the annotation */
assert(iface->symbols[0] && iface->symbols[0]->symbol_type == SD_VARLINK_METHOD);
((sd_varlink_symbol*) iface->symbols[0])->symbol_flags |= SD_VARLINK_REQUIRES_UPGRADE;
r = sd_varlink_server_add_interface(s, iface);
if (r < 0)
return r;
*ret_interface = TAKE_PTR(iface);
return 0;
}
static int method_serve_upgrade(sd_varlink *link, sd_json_variant *parameters, sd_varlink_method_flags_t flags, void *userdata) {
char **exec_cmdline = ASSERT_PTR(userdata);
_cleanup_close_ int input_fd = -EBADF, output_fd = -EBADF;
int r;
if (!FLAGS_SET(flags, SD_VARLINK_METHOD_UPGRADE))
return sd_varlink_error(link, SD_VARLINK_ERROR_EXPECTED_UPGRADE, NULL);
r = sd_varlink_reply_and_upgrade(link, /* parameters= */ NULL, &input_fd, &output_fd);
if (r < 0)
return log_error_errno(r, "Failed to upgrade connection: %m");
/* Copy exec_cmdline before forking: pidref_safe_fork() calls rename_process() which
* overwrites the argv area that exec_cmdline points into. */
_cleanup_strv_free_ char **cmdline_copy = strv_copy(exec_cmdline);
if (!cmdline_copy)
return log_oom();
r = pidref_safe_fork_full(
"(serve)",
(int[]) { input_fd, output_fd, STDERR_FILENO },
/* except_fds= */ NULL, /* n_except_fds= */ 0,
FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_REARRANGE_STDIO|FORK_DETACH|FORK_LOG,
/* ret= */ NULL);
if (r < 0)
return r;
if (r == 0) {
execvp(cmdline_copy[0], cmdline_copy);
log_error_errno(errno, "Failed to execute '%s': %m", cmdline_copy[0]);
_exit(EXIT_FAILURE);
}
return 0;
}
VERB(verb_serve, "serve", "METHOD CMDLINE…\0", 3, VERB_ANY, 0, "Serve a command via varlink protocol upgrade");
static int verb_serve(int argc, char *argv[], uintptr_t _data, void *userdata) {
_cleanup_(sd_varlink_server_unrefp) sd_varlink_server *s = NULL;
_cleanup_(sd_event_unrefp) sd_event *event = NULL;
const char *method;
char **exec_cmdline;
int r, n;
assert(argc >= 3); /* Guaranteed by verb dispatch table */
method = argv[1];
exec_cmdline = argv + 2;
r = varlink_idl_qualified_symbol_name_is_valid(method);
if (r < 0)
return log_error_errno(r, "Failed to validate method name '%s': %m", method);
if (r == 0)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Not a valid qualified method name: '%s'", method);
/* Require socket activation */
n = sd_listen_fds(/* unset_environment= */ true);
if (n < 0)
return log_error_errno(n, "Failed to determine passed file descriptors: %m");
if (n == 0)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "No file descriptors passed via socket activation.");
if (n > 1)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Expected exactly one socket activation fd, got %d.", n);
r = sd_event_default(&event);
if (r < 0)
return log_error_errno(r, "Failed to get event loop: %m");
r = sd_varlink_server_new(&s, SD_VARLINK_SERVER_INHERIT_USERDATA|SD_VARLINK_SERVER_UPGRADABLE);
if (r < 0)
return log_error_errno(r, "Failed to allocate varlink server: %m");
_cleanup_free_ char *description = strjoin("serve:", method);
if (!description)
return log_oom();
r = sd_varlink_server_set_description(s, description);
if (r < 0)
return log_error_errno(r, "Failed to set server description: %m");
r = sd_varlink_server_bind_method(s, method, method_serve_upgrade);
if (r < 0)
return log_error_errno(r, "Failed to bind method '%s': %m", method);
_cleanup_(sd_varlink_interface_freep) sd_varlink_interface *iface = NULL;
r = varlink_server_add_interface_from_method(s, method, &iface);
if (r < 0)
return log_error_errno(r, "Failed to add interface for method '%s': %m", method);
sd_varlink_server_set_userdata(s, exec_cmdline);
r = sd_varlink_server_listen_fd(s, SD_LISTEN_FDS_START);
if (r < 0)
return log_error_errno(r, "Failed to listen on socket activation fd: %m");
r = sd_varlink_server_attach_event(s, event, SD_EVENT_PRIORITY_NORMAL);
if (r < 0)
return log_error_errno(r, "Failed to attach varlink server to event loop: %m");
(void) sd_notify(/* unset_environment= */ false, "READY=1");
r = sd_event_loop(event);
if (r < 0)
return log_error_errno(r, "Failed to run event loop: %m");
return 0;
}
VERB_COMMON_HELP_AUTO();
static int run(int argc, char *argv[]) {
int r;
log_setup();
char **args = NULL; /* unnecessary initialization to appease gcc <= 13 */
r = parse_argv(argc, argv, &args);
if (r <= 0)
return r;
return dispatch_verb(args, NULL);
}
DEFINE_MAIN_FUNCTION(run);