aboutsummaryrefslogtreecommitdiff
path: root/kms
diff options
context:
space:
mode:
Diffstat (limited to 'kms')
-rw-r--r--kms/client/kms_client.c441
-rw-r--r--kms/client/kms_client.h24
-rw-r--r--kms/kms_shared.h60
-rw-r--r--kms/server/.gitignore1
-rw-r--r--kms/server/kms_server.c572
-rw-r--r--kms/server/project.conf11
6 files changed, 1109 insertions, 0 deletions
diff --git a/kms/client/kms_client.c b/kms/client/kms_client.c
new file mode 100644
index 0000000..869bf81
--- /dev/null
+++ b/kms/client/kms_client.c
@@ -0,0 +1,441 @@
+#include "kms_client.h"
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include <errno.h>
+#include <unistd.h>
+#include <signal.h>
+#include <stdbool.h>
+#include <fcntl.h>
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <sys/wait.h>
+#include <sys/stat.h>
+#include <sys/capability.h>
+
+#define GSR_SOCKET_PAIR_LOCAL 0
+#define GSR_SOCKET_PAIR_REMOTE 1
+
+static void cleanup_socket(gsr_kms_client *self, bool kill_server);
+static int gsr_kms_client_replace_connection(gsr_kms_client *self);
+
+static bool generate_random_characters(char *buffer, int buffer_size, const char *alphabet, size_t alphabet_size) {
+ int fd = open("/dev/urandom", O_RDONLY);
+ if(fd == -1) {
+ perror("/dev/urandom");
+ return false;
+ }
+
+ if(read(fd, buffer, buffer_size) < buffer_size) {
+ fprintf(stderr, "Failed to read %d bytes from /dev/urandom\n", buffer_size);
+ close(fd);
+ return false;
+ }
+
+ for(int i = 0; i < buffer_size; ++i) {
+ unsigned char c = *(unsigned char*)&buffer[i];
+ buffer[i] = alphabet[c % alphabet_size];
+ }
+
+ close(fd);
+ return true;
+}
+
+static void close_fds(gsr_kms_response *response) {
+ for(int i = 0; i < response->num_fds; ++i) {
+ if(response->fds[i].fd > 0)
+ close(response->fds[i].fd);
+ response->fds[i].fd = 0;
+ }
+}
+
+static int send_msg_to_server(int server_fd, gsr_kms_request *request) {
+ struct iovec iov;
+ iov.iov_base = request;
+ iov.iov_len = sizeof(*request);
+
+ struct msghdr response_message = {0};
+ response_message.msg_iov = &iov;
+ response_message.msg_iovlen = 1;
+
+ char cmsgbuf[CMSG_SPACE(sizeof(int) * 1)];
+ memset(cmsgbuf, 0, sizeof(cmsgbuf));
+
+ if(request->new_connection_fd > 0) {
+ response_message.msg_control = cmsgbuf;
+ response_message.msg_controllen = sizeof(cmsgbuf);
+
+ struct cmsghdr *cmsg = CMSG_FIRSTHDR(&response_message);
+ cmsg->cmsg_level = SOL_SOCKET;
+ cmsg->cmsg_type = SCM_RIGHTS;
+ cmsg->cmsg_len = CMSG_LEN(sizeof(int) * 1);
+
+ int *fds = (int*)CMSG_DATA(cmsg);
+ fds[0] = request->new_connection_fd;
+
+ response_message.msg_controllen = cmsg->cmsg_len;
+ }
+
+ return sendmsg(server_fd, &response_message, 0);
+}
+
+static int recv_msg_from_server(int server_pid, int server_fd, gsr_kms_response *response) {
+ struct iovec iov;
+ iov.iov_base = response;
+ iov.iov_len = sizeof(*response);
+
+ struct msghdr response_message = {0};
+ response_message.msg_iov = &iov;
+ response_message.msg_iovlen = 1;
+
+ char cmsgbuf[CMSG_SPACE(sizeof(int) * GSR_KMS_MAX_PLANES)];
+ memset(cmsgbuf, 0, sizeof(cmsgbuf));
+ response_message.msg_control = cmsgbuf;
+ response_message.msg_controllen = sizeof(cmsgbuf);
+
+ int res = 0;
+ for(;;) {
+ res = recvmsg(server_fd, &response_message, MSG_DONTWAIT);
+ if(res <= 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
+ // If we are replacing the connection and closing the application at the same time
+ // then recvmsg can get stuck (because the server died), so we prevent that by doing
+ // non-blocking recvmsg and checking if the server died
+ int status = 0;
+ int wait_result = waitpid(server_pid, &status, WNOHANG);
+ if(wait_result != 0) {
+ res = -1;
+ break;
+ }
+ usleep(1000);
+ } else {
+ break;
+ }
+ }
+
+ if(res > 0 && response->num_fds > 0) {
+ struct cmsghdr *cmsg = CMSG_FIRSTHDR(&response_message);
+ if(cmsg) {
+ int *fds = (int*)CMSG_DATA(cmsg);
+ for(int i = 0; i < response->num_fds; ++i) {
+ response->fds[i].fd = fds[i];
+ }
+ } else {
+ close_fds(response);
+ }
+ }
+
+ return res;
+}
+
+/* We have to use $HOME because in flatpak there is no simple path that is accessible, read and write, that multiple flatpak instances can access */
+static bool create_socket_path(char *output_path, size_t output_path_size) {
+ const char *home = getenv("HOME");
+ if(!home)
+ home = "/tmp";
+
+ char random_characters[11];
+ random_characters[10] = '\0';
+ if(!generate_random_characters(random_characters, 10, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", 62))
+ return false;
+
+ snprintf(output_path, output_path_size, "%s/.gsr-kms-socket-%s", home, random_characters);
+ return true;
+}
+
+static void string_copy(char *dst, const char *src, int len) {
+ int src_len = strlen(src);
+ int min_len = src_len;
+ if(len - 1 < min_len)
+ min_len = len - 1;
+ memcpy(dst, src, min_len);
+ dst[min_len] = '\0';
+}
+
+static bool find_program_in_path(const char *program_name, char *filepath, int filepath_len) {
+ const char *path = getenv("PATH");
+ if(!path)
+ return false;
+
+ int program_name_len = strlen(program_name);
+ const char *end = path + strlen(path);
+ while(path != end) {
+ const char *part_end = strchr(path, ':');
+ const char *next = part_end;
+ if(part_end) {
+ next = part_end + 1;
+ } else {
+ part_end = end;
+ next = end;
+ }
+
+ int len = part_end - path;
+ if(len + 1 + program_name_len < filepath_len) {
+ memcpy(filepath, path, len);
+ filepath[len] = '/';
+ memcpy(filepath + len + 1, program_name, program_name_len);
+ filepath[len + 1 + program_name_len] = '\0';
+
+ if(access(filepath, F_OK) == 0)
+ return true;
+ }
+
+ path = next;
+ }
+
+ return false;
+}
+
+int gsr_kms_client_init(gsr_kms_client *self, const char *card_path) {
+ int result = -1;
+ self->kms_server_pid = -1;
+ self->initial_socket_fd = -1;
+ self->initial_client_fd = -1;
+ self->initial_socket_path[0] = '\0';
+ self->socket_pair[0] = -1;
+ self->socket_pair[1] = -1;
+ struct sockaddr_un local_addr = {0};
+ struct sockaddr_un remote_addr = {0};
+
+ if(!create_socket_path(self->initial_socket_path, sizeof(self->initial_socket_path))) {
+ fprintf(stderr, "gsr error: gsr_kms_client_init: failed to create path to kms socket\n");
+ return -1;
+ }
+
+ char server_filepath[PATH_MAX];
+ if(!find_program_in_path("gsr-kms-server", server_filepath, sizeof(server_filepath))) {
+ fprintf(stderr, "gsr error: gsr_kms_client_init: gsr-kms-server is not installed\n");
+ return -1;
+ }
+
+ const bool inside_flatpak = getenv("FLATPAK_ID") != NULL;
+ const char *home = getenv("HOME");
+ if(!home)
+ home = "/tmp";
+
+ bool has_perm = 0;
+ if(geteuid() == 0) {
+ has_perm = true;
+ } else {
+ cap_t kms_server_cap = cap_get_file(server_filepath);
+ if(kms_server_cap) {
+ cap_flag_value_t res = CAP_CLEAR;
+ cap_get_flag(kms_server_cap, CAP_SYS_ADMIN, CAP_PERMITTED, &res);
+ if(res == CAP_SET) {
+ //fprintf(stderr, "has permission!\n");
+ has_perm = true;
+ } else {
+ //fprintf(stderr, "No permission:(\n");
+ }
+ cap_free(kms_server_cap);
+ } else if(!inside_flatpak) {
+ if(errno == ENODATA)
+ fprintf(stderr, "gsr info: gsr_kms_client_init: gsr-kms-server is missing sys_admin cap and will require root authentication. To bypass this automatically, run: sudo setcap cap_sys_admin+ep '%s'\n", server_filepath);
+ else
+ fprintf(stderr, "gsr info: gsr_kms_client_init: failed to get cap\n");
+ }
+ }
+
+ if(socketpair(AF_UNIX, SOCK_STREAM, 0, self->socket_pair) == -1) {
+ fprintf(stderr, "gsr error: gsr_kms_client_init: socketpair failed, error: %s\n", strerror(errno));
+ goto err;
+ }
+
+ self->initial_socket_fd = socket(AF_UNIX, SOCK_STREAM, 0);
+ if(self->initial_socket_fd == -1) {
+ fprintf(stderr, "gsr error: gsr_kms_client_init: socket failed, error: %s\n", strerror(errno));
+ goto err;
+ }
+
+ local_addr.sun_family = AF_UNIX;
+ string_copy(local_addr.sun_path, self->initial_socket_path, sizeof(local_addr.sun_path));
+
+ const mode_t prev_mask = umask(0000);
+ const int bind_res = bind(self->initial_socket_fd, (struct sockaddr*)&local_addr, sizeof(local_addr.sun_family) + strlen(local_addr.sun_path));
+ umask(prev_mask);
+
+ if(bind_res == -1) {
+ fprintf(stderr, "gsr error: gsr_kms_client_init: failed to bind socket, error: %s\n", strerror(errno));
+ goto err;
+ }
+
+ if(listen(self->initial_socket_fd, 1) == -1) {
+ fprintf(stderr, "gsr error: gsr_kms_client_init: failed to listen on socket, error: %s\n", strerror(errno));
+ goto err;
+ }
+
+ pid_t pid = fork();
+ if(pid == -1) {
+ fprintf(stderr, "gsr error: gsr_kms_client_init: fork failed, error: %s\n", strerror(errno));
+ goto err;
+ } else if(pid == 0) { /* child */
+ if(inside_flatpak) {
+ const char *args[] = { "flatpak-spawn", "--host", "/var/lib/flatpak/app/com.dec05eba.gpu_screen_recorder/current/active/files/bin/kms-server-proxy", self->initial_socket_path, card_path, home, NULL };
+ execvp(args[0], (char *const*)args);
+ } else if(has_perm) {
+ const char *args[] = { server_filepath, self->initial_socket_path, card_path, NULL };
+ execvp(args[0], (char *const*)args);
+ } else {
+ const char *args[] = { "pkexec", server_filepath, self->initial_socket_path, card_path, NULL };
+ execvp(args[0], (char *const*)args);
+ }
+ fprintf(stderr, "gsr error: gsr_kms_client_init: execvp failed, error: %s\n", strerror(errno));
+ _exit(127);
+ } else { /* parent */
+ self->kms_server_pid = pid;
+ }
+
+ fprintf(stderr, "gsr info: gsr_kms_client_init: waiting for server to connect\n");
+ for(;;) {
+ struct timeval tv;
+ fd_set rfds;
+ FD_ZERO(&rfds);
+ FD_SET(self->initial_socket_fd, &rfds);
+
+ tv.tv_sec = 0;
+ tv.tv_usec = 100 * 1000; // 100 ms
+
+ int select_res = select(1 + self->initial_socket_fd, &rfds, NULL, NULL, &tv);
+ if(select_res > 0) {
+ socklen_t sock_len = 0;
+ self->initial_client_fd = accept(self->initial_socket_fd, (struct sockaddr*)&remote_addr, &sock_len);
+ if(self->initial_client_fd == -1) {
+ fprintf(stderr, "gsr error: gsr_kms_client_init: accept failed on socket, error: %s\n", strerror(errno));
+ goto err;
+ }
+ break;
+ } else {
+ int status = 0;
+ int wait_result = waitpid(self->kms_server_pid, &status, WNOHANG);
+ if(wait_result != 0) {
+ int exit_code = -1;
+ if(WIFEXITED(status))
+ exit_code = WEXITSTATUS(status);
+ fprintf(stderr, "gsr error: gsr_kms_client_init: kms server died or never started, exit code: %d\n", exit_code);
+ self->kms_server_pid = -1;
+ if(exit_code != 0)
+ result = exit_code;
+ goto err;
+ }
+ }
+ }
+ fprintf(stderr, "gsr info: gsr_kms_client_init: server connected\n");
+
+ fprintf(stderr, "gsr info: replacing file-backed unix domain socket with socketpair\n");
+ if(gsr_kms_client_replace_connection(self) != 0)
+ goto err;
+
+ cleanup_socket(self, false);
+ fprintf(stderr, "gsr info: using socketpair\n");
+
+ return 0;
+
+ err:
+ gsr_kms_client_deinit(self);
+ return result;
+}
+
+void cleanup_socket(gsr_kms_client *self, bool kill_server) {
+ if(self->initial_client_fd != -1) {
+ close(self->initial_client_fd);
+ self->initial_client_fd = -1;
+ }
+
+ if(self->initial_socket_fd != -1) {
+ close(self->initial_socket_fd);
+ self->initial_socket_fd = -1;
+ }
+
+ if(kill_server) {
+ for(int i = 0; i < 2; ++i) {
+ if(self->socket_pair[i] > 0) {
+ close(self->socket_pair[i]);
+ self->socket_pair[i] = -1;
+ }
+ }
+ }
+
+ if(kill_server && self->kms_server_pid != -1) {
+ kill(self->kms_server_pid, SIGKILL);
+ //int status;
+ //waitpid(self->kms_server_pid, &status, 0);
+ self->kms_server_pid = -1;
+ }
+
+ if(self->initial_socket_path[0] != '\0') {
+ remove(self->initial_socket_path);
+ self->initial_socket_path[0] = '\0';
+ }
+}
+
+void gsr_kms_client_deinit(gsr_kms_client *self) {
+ cleanup_socket(self, true);
+}
+
+int gsr_kms_client_replace_connection(gsr_kms_client *self) {
+ gsr_kms_response response;
+ response.version = 0;
+ response.result = KMS_RESULT_FAILED_TO_SEND;
+ response.err_msg[0] = '\0';
+
+ gsr_kms_request request;
+ request.version = GSR_KMS_PROTOCOL_VERSION;
+ request.type = KMS_REQUEST_TYPE_REPLACE_CONNECTION;
+ request.new_connection_fd = self->socket_pair[GSR_SOCKET_PAIR_REMOTE];
+ if(send_msg_to_server(self->initial_client_fd, &request) == -1) {
+ fprintf(stderr, "gsr error: gsr_kms_client_replace_connection: failed to send request message to server\n");
+ return -1;
+ }
+
+ const int recv_res = recv_msg_from_server(self->kms_server_pid, self->socket_pair[GSR_SOCKET_PAIR_LOCAL], &response);
+ if(recv_res == 0) {
+ fprintf(stderr, "gsr warning: gsr_kms_client_replace_connection: kms server shut down\n");
+ return -1;
+ } else if(recv_res == -1) {
+ fprintf(stderr, "gsr error: gsr_kms_client_replace_connection: failed to receive response\n");
+ return -1;
+ }
+
+ if(response.version != GSR_KMS_PROTOCOL_VERSION) {
+ fprintf(stderr, "gsr error: gsr_kms_client_replace_connection: expected gsr-kms-server protocol version to be %u, but it's %u\n", GSR_KMS_PROTOCOL_VERSION, response.version);
+ /*close_fds(response);*/
+ return -1;
+ }
+
+ return 0;
+}
+
+int gsr_kms_client_get_kms(gsr_kms_client *self, gsr_kms_response *response) {
+ response->version = 0;
+ response->result = KMS_RESULT_FAILED_TO_SEND;
+ response->err_msg[0] = '\0';
+
+ gsr_kms_request request;
+ request.version = GSR_KMS_PROTOCOL_VERSION;
+ request.type = KMS_REQUEST_TYPE_GET_KMS;
+ request.new_connection_fd = 0;
+ if(send_msg_to_server(self->socket_pair[GSR_SOCKET_PAIR_LOCAL], &request) == -1) {
+ fprintf(stderr, "gsr error: gsr_kms_client_get_kms: failed to send request message to server\n");
+ strcpy(response->err_msg, "failed to send");
+ return -1;
+ }
+
+ const int recv_res = recv_msg_from_server(self->kms_server_pid, self->socket_pair[GSR_SOCKET_PAIR_LOCAL], response);
+ if(recv_res == 0) {
+ fprintf(stderr, "gsr warning: gsr_kms_client_get_kms: kms server shut down\n");
+ strcpy(response->err_msg, "failed to receive");
+ return -1;
+ } else if(recv_res == -1) {
+ fprintf(stderr, "gsr error: gsr_kms_client_get_kms: failed to receive response\n");
+ strcpy(response->err_msg, "failed to receive");
+ return -1;
+ }
+
+ if(response->version != GSR_KMS_PROTOCOL_VERSION) {
+ fprintf(stderr, "gsr error: gsr_kms_client_get_kms: expected gsr-kms-server protocol version to be %u, but it's %u\n", GSR_KMS_PROTOCOL_VERSION, response->version);
+ /*close_fds(response);*/
+ strcpy(response->err_msg, "mismatching protocol version");
+ return -1;
+ }
+
+ return 0;
+}
diff --git a/kms/client/kms_client.h b/kms/client/kms_client.h
new file mode 100644
index 0000000..2d18848
--- /dev/null
+++ b/kms/client/kms_client.h
@@ -0,0 +1,24 @@
+#ifndef GSR_KMS_CLIENT_H
+#define GSR_KMS_CLIENT_H
+
+#include "../kms_shared.h"
+#include <sys/types.h>
+#include <limits.h>
+
+typedef struct gsr_kms_client gsr_kms_client;
+
+struct gsr_kms_client {
+ pid_t kms_server_pid;
+ int initial_socket_fd;
+ int initial_client_fd;
+ char initial_socket_path[PATH_MAX];
+ int socket_pair[2];
+};
+
+/* |card_path| should be a path to card, for example /dev/dri/card0 */
+int gsr_kms_client_init(gsr_kms_client *self, const char *card_path);
+void gsr_kms_client_deinit(gsr_kms_client *self);
+
+int gsr_kms_client_get_kms(gsr_kms_client *self, gsr_kms_response *response);
+
+#endif /* #define GSR_KMS_CLIENT_H */
diff --git a/kms/kms_shared.h b/kms/kms_shared.h
new file mode 100644
index 0000000..4fa9c38
--- /dev/null
+++ b/kms/kms_shared.h
@@ -0,0 +1,60 @@
+#ifndef GSR_KMS_SHARED_H
+#define GSR_KMS_SHARED_H
+
+#include <stdint.h>
+#include <stdbool.h>
+#include <drm_mode.h>
+
+#define GSR_KMS_PROTOCOL_VERSION 2
+#define GSR_KMS_MAX_PLANES 10
+
+typedef struct gsr_kms_response_fd gsr_kms_response_fd;
+typedef struct gsr_kms_response gsr_kms_response;
+
+typedef enum {
+ KMS_REQUEST_TYPE_REPLACE_CONNECTION,
+ KMS_REQUEST_TYPE_GET_KMS
+} gsr_kms_request_type;
+
+typedef enum {
+ KMS_RESULT_OK,
+ KMS_RESULT_INVALID_REQUEST,
+ KMS_RESULT_FAILED_TO_GET_PLANE,
+ KMS_RESULT_FAILED_TO_GET_PLANES,
+ KMS_RESULT_FAILED_TO_SEND
+} gsr_kms_result;
+
+typedef struct {
+ uint32_t version; /* GSR_KMS_PROTOCOL_VERSION */
+ int type; /* gsr_kms_request_type */
+ int new_connection_fd;
+} gsr_kms_request;
+
+struct gsr_kms_response_fd {
+ int fd;
+ uint32_t width;
+ uint32_t height;
+ uint32_t pitch;
+ uint32_t offset;
+ uint32_t pixel_format;
+ uint64_t modifier;
+ uint32_t connector_id; /* 0 if unknown */
+ bool is_combined_plane;
+ bool is_cursor;
+ bool has_hdr_metadata;
+ int x;
+ int y;
+ int src_w;
+ int src_h;
+ struct hdr_output_metadata hdr_metadata;
+};
+
+struct gsr_kms_response {
+ uint32_t version; /* GSR_KMS_PROTOCOL_VERSION */
+ int result; /* gsr_kms_result */
+ char err_msg[128];
+ gsr_kms_response_fd fds[GSR_KMS_MAX_PLANES];
+ int num_fds;
+};
+
+#endif /* #define GSR_KMS_SHARED_H */
diff --git a/kms/server/.gitignore b/kms/server/.gitignore
new file mode 100644
index 0000000..97420ef
--- /dev/null
+++ b/kms/server/.gitignore
@@ -0,0 +1 @@
+sibs-build/
diff --git a/kms/server/kms_server.c b/kms/server/kms_server.c
new file mode 100644
index 0000000..2eaa1ed
--- /dev/null
+++ b/kms/server/kms_server.c
@@ -0,0 +1,572 @@
+#include "../kms_shared.h"
+
+#include <stdio.h>
+#include <string.h>
+#include <errno.h>
+#include <stdlib.h>
+
+#include <unistd.h>
+#include <fcntl.h>
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <time.h>
+
+#include <xf86drm.h>
+#include <xf86drmMode.h>
+#include <drm_mode.h>
+
+#define MAX_CONNECTORS 32
+
+typedef struct {
+ int drmfd;
+ drmModePlaneResPtr planes;
+} gsr_drm;
+
+typedef struct {
+ uint32_t connector_id;
+ uint64_t crtc_id;
+ uint64_t hdr_metadata_blob_id;
+} connector_crtc_pair;
+
+typedef struct {
+ connector_crtc_pair maps[MAX_CONNECTORS];
+ int num_maps;
+} connector_to_crtc_map;
+
+static int max_int(int a, int b) {
+ return a > b ? a : b;
+}
+
+static int send_msg_to_client(int client_fd, gsr_kms_response *response) {
+ struct iovec iov;
+ iov.iov_base = response;
+ iov.iov_len = sizeof(*response);
+
+ struct msghdr response_message = {0};
+ response_message.msg_iov = &iov;
+ response_message.msg_iovlen = 1;
+
+ char cmsgbuf[CMSG_SPACE(sizeof(int) * max_int(1, response->num_fds))];
+ memset(cmsgbuf, 0, sizeof(cmsgbuf));
+
+ if(response->num_fds > 0) {
+ response_message.msg_control = cmsgbuf;
+ response_message.msg_controllen = sizeof(cmsgbuf);
+
+ struct cmsghdr *cmsg = CMSG_FIRSTHDR(&response_message);
+ cmsg->cmsg_level = SOL_SOCKET;
+ cmsg->cmsg_type = SCM_RIGHTS;
+ cmsg->cmsg_len = CMSG_LEN(sizeof(int) * response->num_fds);
+
+ int *fds = (int*)CMSG_DATA(cmsg);
+ for(int i = 0; i < response->num_fds; ++i) {
+ fds[i] = response->fds[i].fd;
+ }
+
+ response_message.msg_controllen = cmsg->cmsg_len;
+ }
+
+ return sendmsg(client_fd, &response_message, 0);
+}
+
+static int recv_msg_from_client(int client_fd, gsr_kms_request *request) {
+ struct iovec iov;
+ iov.iov_base = request;
+ iov.iov_len = sizeof(*request);
+
+ struct msghdr response_message = {0};
+ response_message.msg_iov = &iov;
+ response_message.msg_iovlen = 1;
+
+ char cmsgbuf[CMSG_SPACE(sizeof(int) * 1)];
+ memset(cmsgbuf, 0, sizeof(cmsgbuf));
+ response_message.msg_control = cmsgbuf;
+ response_message.msg_controllen = sizeof(cmsgbuf);
+
+ int res = recvmsg(client_fd, &response_message, MSG_WAITALL);
+ if(res <= 0)
+ return res;
+
+ if(request->new_connection_fd > 0) {
+ struct cmsghdr *cmsg = CMSG_FIRSTHDR(&response_message);
+ if(cmsg) {
+ int *fds = (int*)CMSG_DATA(cmsg);
+ request->new_connection_fd = fds[0];
+ } else {
+ if(request->new_connection_fd > 0) {
+ close(request->new_connection_fd);
+ request->new_connection_fd = 0;
+ }
+ }
+ }
+
+ return res;
+}
+
+static bool connector_get_property_by_name(int drmfd, drmModeConnectorPtr props, const char *name, uint64_t *result) {
+ for(int i = 0; i < props->count_props; ++i) {
+ drmModePropertyPtr prop = drmModeGetProperty(drmfd, props->props[i]);
+ if(prop) {
+ if(strcmp(name, prop->name) == 0) {
+ *result = props->prop_values[i];
+ drmModeFreeProperty(prop);
+ return true;
+ }
+ drmModeFreeProperty(prop);
+ }
+ }
+ return false;
+}
+
+typedef enum {
+ PLANE_PROPERTY_X = 1 << 0,
+ PLANE_PROPERTY_Y = 1 << 1,
+ PLANE_PROPERTY_SRC_X = 1 << 2,
+ PLANE_PROPERTY_SRC_Y = 1 << 3,
+ PLANE_PROPERTY_SRC_W = 1 << 4,
+ PLANE_PROPERTY_SRC_H = 1 << 5,
+ PLANE_PROPERTY_IS_CURSOR = 1 << 6,
+ PLANE_PROPERTY_IS_PRIMARY = 1 << 7,
+} plane_property_mask;
+
+/* Returns plane_property_mask */
+static uint32_t plane_get_properties(int drmfd, uint32_t plane_id, int *x, int *y, int *src_x, int *src_y, int *src_w, int *src_h) {
+ *x = 0;
+ *y = 0;
+ *src_x = 0;
+ *src_y = 0;
+ *src_w = 0;
+ *src_h = 0;
+
+ plane_property_mask property_mask = 0;
+
+ drmModeObjectPropertiesPtr props = drmModeObjectGetProperties(drmfd, plane_id, DRM_MODE_OBJECT_PLANE);
+ if(!props)
+ return property_mask;
+
+ // TODO: Dont do this every frame
+ for(uint32_t i = 0; i < props->count_props; ++i) {
+ drmModePropertyPtr prop = drmModeGetProperty(drmfd, props->props[i]);
+ if(!prop)
+ continue;
+
+ // SRC_* values are fixed 16.16 points
+ const uint32_t type = prop->flags & (DRM_MODE_PROP_LEGACY_TYPE | DRM_MODE_PROP_EXTENDED_TYPE);
+ if((type & DRM_MODE_PROP_SIGNED_RANGE) && strcmp(prop->name, "CRTC_X") == 0) {
+ *x = (int)props->prop_values[i];
+ property_mask |= PLANE_PROPERTY_X;
+ } else if((type & DRM_MODE_PROP_SIGNED_RANGE) && strcmp(prop->name, "CRTC_Y") == 0) {
+ *y = (int)props->prop_values[i];
+ property_mask |= PLANE_PROPERTY_Y;
+ } else if((type & DRM_MODE_PROP_RANGE) && strcmp(prop->name, "SRC_X") == 0) {
+ *src_x = (int)(props->prop_values[i] >> 16);
+ property_mask |= PLANE_PROPERTY_SRC_X;
+ } else if((type & DRM_MODE_PROP_RANGE) && strcmp(prop->name, "SRC_Y") == 0) {
+ *src_y = (int)(props->prop_values[i] >> 16);
+ property_mask |= PLANE_PROPERTY_SRC_Y;
+ } else if((type & DRM_MODE_PROP_RANGE) && strcmp(prop->name, "SRC_W") == 0) {
+ *src_w = (int)(props->prop_values[i] >> 16);
+ property_mask |= PLANE_PROPERTY_SRC_W;
+ } else if((type & DRM_MODE_PROP_RANGE) && strcmp(prop->name, "SRC_H") == 0) {
+ *src_h = (int)(props->prop_values[i] >> 16);
+ property_mask |= PLANE_PROPERTY_SRC_H;
+ } else if((type & DRM_MODE_PROP_ENUM) && strcmp(prop->name, "type") == 0) {
+ const uint64_t current_enum_value = props->prop_values[i];
+ for(int j = 0; j < prop->count_enums; ++j) {
+ if(prop->enums[j].value == current_enum_value && strcmp(prop->enums[j].name, "Primary") == 0) {
+ property_mask |= PLANE_PROPERTY_IS_PRIMARY;
+ break;
+ } else if(prop->enums[j].value == current_enum_value && strcmp(prop->enums[j].name, "Cursor") == 0) {
+ property_mask |= PLANE_PROPERTY_IS_CURSOR;
+ break;
+ }
+ }
+ }
+
+ drmModeFreeProperty(prop);
+ }
+
+ drmModeFreeObjectProperties(props);
+ return property_mask;
+}
+
+/* Returns 0 if not found */
+static const connector_crtc_pair* get_connector_pair_by_crtc_id(const connector_to_crtc_map *c2crtc_map, uint32_t crtc_id) {
+ for(int i = 0; i < c2crtc_map->num_maps; ++i) {
+ if(c2crtc_map->maps[i].crtc_id == crtc_id)
+ return &c2crtc_map->maps[i];
+ }
+ return NULL;
+}
+
+static void map_crtc_to_connector_ids(gsr_drm *drm, connector_to_crtc_map *c2crtc_map) {
+ c2crtc_map->num_maps = 0;
+ drmModeResPtr resources = drmModeGetResources(drm->drmfd);
+ if(!resources)
+ return;
+
+ for(int i = 0; i < resources->count_connectors && c2crtc_map->num_maps < MAX_CONNECTORS; ++i) {
+ drmModeConnectorPtr connector = drmModeGetConnectorCurrent(drm->drmfd, resources->connectors[i]);
+ if(!connector)
+ continue;
+
+ uint64_t crtc_id = 0;
+ connector_get_property_by_name(drm->drmfd, connector, "CRTC_ID", &crtc_id);
+
+ uint64_t hdr_output_metadata_blob_id = 0;
+ connector_get_property_by_name(drm->drmfd, connector, "HDR_OUTPUT_METADATA", &hdr_output_metadata_blob_id);
+
+ c2crtc_map->maps[c2crtc_map->num_maps].connector_id = connector->connector_id;
+ c2crtc_map->maps[c2crtc_map->num_maps].crtc_id = crtc_id;
+ c2crtc_map->maps[c2crtc_map->num_maps].hdr_metadata_blob_id = hdr_output_metadata_blob_id;
+ ++c2crtc_map->num_maps;
+
+ drmModeFreeConnector(connector);
+ }
+ drmModeFreeResources(resources);
+}
+
+static void drm_mode_cleanup_handles(int drmfd, drmModeFB2Ptr drmfb) {
+ for(int i = 0; i < 4; ++i) {
+ if(!drmfb->handles[i])
+ continue;
+
+ bool already_closed = false;
+ for(int j = 0; j < i; ++j) {
+ if(drmfb->handles[i] == drmfb->handles[j]) {
+ already_closed = true;
+ break;
+ }
+ }
+
+ if(already_closed)
+ continue;
+
+ drmCloseBufferHandle(drmfd, drmfb->handles[i]);
+ }
+}
+
+static bool get_hdr_metadata(int drm_fd, uint64_t hdr_metadata_blob_id, struct hdr_output_metadata *hdr_metadata) {
+ drmModePropertyBlobPtr hdr_metadata_blob = drmModeGetPropertyBlob(drm_fd, hdr_metadata_blob_id);
+ if(!hdr_metadata_blob)
+ return false;
+
+ if(hdr_metadata_blob->length >= sizeof(struct hdr_output_metadata))
+ *hdr_metadata = *(struct hdr_output_metadata*)hdr_metadata_blob->data;
+
+ drmModeFreePropertyBlob(hdr_metadata_blob);
+ return true;
+}
+
+static int kms_get_fb(gsr_drm *drm, gsr_kms_response *response, connector_to_crtc_map *c2crtc_map) {
+ int result = -1;
+
+ response->result = KMS_RESULT_OK;
+ response->err_msg[0] = '\0';
+ response->num_fds = 0;
+
+ for(uint32_t i = 0; i < drm->planes->count_planes && response->num_fds < GSR_KMS_MAX_PLANES; ++i) {
+ drmModePlanePtr plane = NULL;
+ drmModeFB2Ptr drmfb = NULL;
+
+ plane = drmModeGetPlane(drm->drmfd, drm->planes->planes[i]);
+ if(!plane) {
+ response->result = KMS_RESULT_FAILED_TO_GET_PLANE;
+ snprintf(response->err_msg, sizeof(response->err_msg), "failed to get drm plane with id %u, error: %s\n", drm->planes->planes[i], strerror(errno));
+ fprintf(stderr, "kms server error: %s\n", response->err_msg);
+ goto next;
+ }
+
+ if(!plane->fb_id)
+ goto next;
+
+ drmfb = drmModeGetFB2(drm->drmfd, plane->fb_id);
+ if(!drmfb) {
+ // Commented out for now because we get here if the cursor is moved to another monitor and we dont care about the cursor
+ //response->result = KMS_RESULT_FAILED_TO_GET_PLANE;
+ //snprintf(response->err_msg, sizeof(response->err_msg), "drmModeGetFB2 failed, error: %s", strerror(errno));
+ //fprintf(stderr, "kms server error: %s\n", response->err_msg);
+ goto next;
+ }
+
+ if(!drmfb->handles[0]) {
+ response->result = KMS_RESULT_FAILED_TO_GET_PLANE;
+ snprintf(response->err_msg, sizeof(response->err_msg), "drmfb handle is NULL");
+ fprintf(stderr, "kms server error: %s\n", response->err_msg);
+ goto cleanup_handles;
+ }
+
+ // TODO: Check if dimensions have changed by comparing width and height to previous time this was called.
+ // TODO: Support other plane formats than rgb (with multiple planes, such as direct YUV420 on wayland).
+
+ int fb_fd = -1;
+ const int ret = drmPrimeHandleToFD(drm->drmfd, drmfb->handles[0], O_RDONLY, &fb_fd);
+ if(ret != 0 || fb_fd == -1) {
+ response->result = KMS_RESULT_FAILED_TO_GET_PLANE;
+ snprintf(response->err_msg, sizeof(response->err_msg), "failed to get fd from drm handle, error: %s", strerror(errno));
+ fprintf(stderr, "kms server error: %s\n", response->err_msg);
+ goto cleanup_handles;
+ }
+
+ const int fd_index = response->num_fds;
+
+ int x = 0, y = 0, src_x = 0, src_y = 0, src_w = 0, src_h = 0;
+ plane_property_mask property_mask = plane_get_properties(drm->drmfd, plane->plane_id, &x, &y, &src_x, &src_y, &src_w, &src_h);
+ if((property_mask & PLANE_PROPERTY_IS_PRIMARY) || (property_mask & PLANE_PROPERTY_IS_CURSOR)) {
+ const connector_crtc_pair *crtc_pair = get_connector_pair_by_crtc_id(c2crtc_map, plane->crtc_id);
+ if(crtc_pair && crtc_pair->hdr_metadata_blob_id) {
+ response->fds[fd_index].has_hdr_metadata = get_hdr_metadata(drm->drmfd, crtc_pair->hdr_metadata_blob_id, &response->fds[fd_index].hdr_metadata);
+ } else {
+ response->fds[fd_index].has_hdr_metadata = false;
+ }
+
+ response->fds[fd_index].fd = fb_fd;
+ response->fds[fd_index].width = drmfb->width;
+ response->fds[fd_index].height = drmfb->height;
+ response->fds[fd_index].pitch = drmfb->pitches[0];
+ response->fds[fd_index].offset = drmfb->offsets[0];
+ response->fds[fd_index].pixel_format = drmfb->pixel_format;
+ response->fds[fd_index].modifier = drmfb->modifier;
+ response->fds[fd_index].connector_id = crtc_pair ? crtc_pair->connector_id : 0;
+ response->fds[fd_index].is_cursor = property_mask & PLANE_PROPERTY_IS_CURSOR;
+ response->fds[fd_index].is_combined_plane = false;
+ if(property_mask & PLANE_PROPERTY_IS_CURSOR) {
+ response->fds[fd_index].x = x;
+ response->fds[fd_index].y = y;
+ response->fds[fd_index].src_w = 0;
+ response->fds[fd_index].src_h = 0;
+ } else {
+ response->fds[fd_index].x = src_x;
+ response->fds[fd_index].y = src_y;
+ response->fds[fd_index].src_w = src_w;
+ response->fds[fd_index].src_h = src_h;
+ }
+ ++response->num_fds;
+ } else {
+ close(fb_fd);
+ }
+
+ cleanup_handles:
+ drm_mode_cleanup_handles(drm->drmfd, drmfb);
+
+ next:
+ if(drmfb)
+ drmModeFreeFB2(drmfb);
+ if(plane)
+ drmModeFreePlane(plane);
+ }
+
+ if(response->num_fds > 0)
+ response->result = KMS_RESULT_OK;
+
+ if(response->result == KMS_RESULT_OK) {
+ result = 0;
+ } else {
+ for(int i = 0; i < response->num_fds; ++i) {
+ close(response->fds[i].fd);
+ }
+ response->num_fds = 0;
+ }
+
+ return result;
+}
+
+static double clock_get_monotonic_seconds(void) {
+ struct timespec ts;
+ ts.tv_sec = 0;
+ ts.tv_nsec = 0;
+ clock_gettime(CLOCK_MONOTONIC, &ts);
+ return (double)ts.tv_sec + (double)ts.tv_nsec * 0.000000001;
+}
+
+static void string_copy(char *dst, const char *src, int len) {
+ int src_len = strlen(src);
+ int min_len = src_len;
+ if(len - 1 < min_len)
+ min_len = len - 1;
+ memcpy(dst, src, min_len);
+ dst[min_len] = '\0';
+}
+
+int main(int argc, char **argv) {
+ int res = 0;
+ int socket_fd = 0;
+ gsr_drm drm;
+ drm.drmfd = 0;
+ drm.planes = NULL;
+
+ if(argc != 3) {
+ fprintf(stderr, "usage: gsr-kms-server <domain_socket_path> <card_path>\n");
+ return 1;
+ }
+
+ const char *domain_socket_path = argv[1];
+ socket_fd = socket(AF_UNIX, SOCK_STREAM, 0);
+ if(socket_fd == -1) {
+ fprintf(stderr, "kms server error: failed to create socket, error: %s\n", strerror(errno));
+ return 2;
+ }
+
+ const char *card_path = argv[2];
+
+ drm.drmfd = open(card_path, O_RDONLY);
+ if(drm.drmfd < 0) {
+ fprintf(stderr, "kms server error: failed to open %s, error: %s", card_path, strerror(errno));
+ res = 2;
+ goto done;
+ }
+
+ if(drmSetClientCap(drm.drmfd, DRM_CLIENT_CAP_UNIVERSAL_PLANES, 1) != 0) {
+ fprintf(stderr, "kms server error: drmSetClientCap DRM_CLIENT_CAP_UNIVERSAL_PLANES failed, error: %s\n", strerror(errno));
+ res = 2;
+ goto done;
+ }
+
+ if(drmSetClientCap(drm.drmfd, DRM_CLIENT_CAP_ATOMIC, 1) != 0) {
+ fprintf(stderr, "kms server warning: drmSetClientCap DRM_CLIENT_CAP_ATOMIC failed, error: %s. The wrong monitor may be captured as a result\n", strerror(errno));
+ }
+
+ drm.planes = drmModeGetPlaneResources(drm.drmfd);
+ if(!drm.planes) {
+ fprintf(stderr, "kms server error: failed to get plane resources, error: %s\n", strerror(errno));
+ res = 2;
+ goto done;
+ }
+
+ connector_to_crtc_map c2crtc_map;
+ c2crtc_map.num_maps = 0;
+ map_crtc_to_connector_ids(&drm, &c2crtc_map);
+
+ fprintf(stderr, "kms server info: connecting to the client\n");
+ bool connected = false;
+ const double connect_timeout_sec = 5.0;
+ const double start_time = clock_get_monotonic_seconds();
+ while(clock_get_monotonic_seconds() - start_time < connect_timeout_sec) {
+ struct sockaddr_un remote_addr = {0};
+ remote_addr.sun_family = AF_UNIX;
+ string_copy(remote_addr.sun_path, domain_socket_path, sizeof(remote_addr.sun_path));
+ // TODO: Check if parent disconnected
+ if(connect(socket_fd, (struct sockaddr*)&remote_addr, sizeof(remote_addr.sun_family) + strlen(remote_addr.sun_path)) == -1) {
+ if(errno == ECONNREFUSED || errno == ENOENT) {
+ goto next;
+ } else if(errno == EISCONN) {
+ connected = true;
+ break;
+ }
+
+ fprintf(stderr, "kms server error: connect failed, error: %s (%d)\n", strerror(errno), errno);
+ res = 2;
+ goto done;
+ }
+
+ next:
+ usleep(30 * 1000); // 30 milliseconds
+ }
+
+ if(connected) {
+ fprintf(stderr, "kms server info: connected to the client\n");
+ } else {
+ fprintf(stderr, "kms server error: failed to connect to the client in %f seconds\n", connect_timeout_sec);
+ res = 2;
+ goto done;
+ }
+
+ for(;;) {
+ gsr_kms_request request;
+ request.version = 0;
+ request.type = -1;
+ request.new_connection_fd = 0;
+
+ const int recv_res = recv_msg_from_client(socket_fd, &request);
+ if(recv_res == 0) {
+ fprintf(stderr, "kms server info: kms client shutdown, shutting down the server\n");
+ res = 3;
+ goto done;
+ } else if(recv_res == -1) {
+ const int err = errno;
+ fprintf(stderr, "kms server error: failed to read all data in client request (error: %s), ignoring\n", strerror(err));
+ if(err == EBADF) {
+ fprintf(stderr, "kms server error: invalid client fd, shutting down the server\n");
+ res = 3;
+ goto done;
+ }
+ continue;
+ }
+
+ if(request.version != GSR_KMS_PROTOCOL_VERSION) {
+ fprintf(stderr, "kms server error: expected gpu screen recorder protocol version to be %u, but it's %u\n", GSR_KMS_PROTOCOL_VERSION, request.version);
+ /*
+ if(request.new_connection_fd > 0)
+ close(request.new_connection_fd);
+ */
+ continue;
+ }
+
+ switch(request.type) {
+ case KMS_REQUEST_TYPE_REPLACE_CONNECTION: {
+ gsr_kms_response response;
+ response.version = GSR_KMS_PROTOCOL_VERSION;
+ response.num_fds = 0;
+
+ if(request.new_connection_fd > 0) {
+ if(socket_fd > 0)
+ close(socket_fd);
+ socket_fd = request.new_connection_fd;
+
+ response.result = KMS_RESULT_OK;
+ if(send_msg_to_client(socket_fd, &response) == -1)
+ fprintf(stderr, "kms server error: failed to respond to client KMS_REQUEST_TYPE_REPLACE_CONNECTION request\n");
+ } else {
+ response.result = KMS_RESULT_INVALID_REQUEST;
+ snprintf(response.err_msg, sizeof(response.err_msg), "received invalid connection fd");
+ fprintf(stderr, "kms server error: %s\n", response.err_msg);
+ if(send_msg_to_client(socket_fd, &response) == -1)
+ fprintf(stderr, "kms server error: failed to respond to client request\n");
+ }
+
+ break;
+ }
+ case KMS_REQUEST_TYPE_GET_KMS: {
+ gsr_kms_response response;
+ response.version = GSR_KMS_PROTOCOL_VERSION;
+ response.num_fds = 0;
+
+ if(kms_get_fb(&drm, &response, &c2crtc_map) == 0) {
+ if(send_msg_to_client(socket_fd, &response) == -1)
+ fprintf(stderr, "kms server error: failed to respond to client KMS_REQUEST_TYPE_GET_KMS request\n");
+ } else {
+ if(send_msg_to_client(socket_fd, &response) == -1)
+ fprintf(stderr, "kms server error: failed to respond to client KMS_REQUEST_TYPE_GET_KMS request\n");
+ }
+
+ for(int i = 0; i < response.num_fds; ++i) {
+ close(response.fds[i].fd);
+ }
+
+ break;
+ }
+ default: {
+ gsr_kms_response response;
+ response.version = GSR_KMS_PROTOCOL_VERSION;
+ response.result = KMS_RESULT_INVALID_REQUEST;
+ response.num_fds = 0;
+
+ snprintf(response.err_msg, sizeof(response.err_msg), "invalid request type %d, expected %d (%s)", request.type, KMS_REQUEST_TYPE_GET_KMS, "KMS_REQUEST_TYPE_GET_KMS");
+ fprintf(stderr, "kms server error: %s\n", response.err_msg);
+ if(send_msg_to_client(socket_fd, &response) == -1)
+ fprintf(stderr, "kms server error: failed to respond to client request\n");
+
+ break;
+ }
+ }
+ }
+
+ done:
+ if(drm.planes)
+ drmModeFreePlaneResources(drm.planes);
+ if(drm.drmfd > 0)
+ close(drm.drmfd);
+ if(socket_fd > 0)
+ close(socket_fd);
+ return res;
+}
diff --git a/kms/server/project.conf b/kms/server/project.conf
new file mode 100644
index 0000000..26a1947
--- /dev/null
+++ b/kms/server/project.conf
@@ -0,0 +1,11 @@
+[package]
+name = "gsr-kms-server"
+type = "executable"
+version = "1.0.0"
+platforms = ["posix"]
+
+[config]
+error_on_warning = "true"
+
+[dependencies]
+libdrm = ">=2"