#define _GNU_SOURCE #include "ui-socket.h" #include #include #include #include #include #include #include #include #define MAX_MESSAGE_SIZE 1024 // Mutex for thread safety static pthread_mutex_t socket_mutex = PTHREAD_MUTEX_INITIALIZER; static int ui_socket_fd = -1; // Global socket file descriptor int init_ui_socket(const char *filename) { if (!filename) { return -1; } // Create the socket ui_socket_fd = socket(AF_UNIX, SOCK_STREAM, 0); if (ui_socket_fd == -1) { perror("socket"); return -1; } // Remove the socket file if it already exists if (unlink(filename) == -1 && errno != ENOENT) { // ENOENT means the file does not exist, which is fine perror("unlink"); close(ui_socket_fd); ui_socket_fd = -1; return -1; } // Set up the socket address structure struct sockaddr_un addr; memset(&addr, 0, sizeof(struct sockaddr_un)); addr.sun_family = AF_UNIX; strncpy(addr.sun_path, filename, sizeof(addr.sun_path) - 1); // Bind the socket if (bind(ui_socket_fd, (struct sockaddr *)&addr, sizeof(struct sockaddr_un)) == -1) { perror("bind"); close(ui_socket_fd); ui_socket_fd = -1; return -1; } // Listen for incoming connections if (listen(ui_socket_fd, 5) == -1) { perror("listen"); close(ui_socket_fd); ui_socket_fd = -1; return -1; } return 0; } int ask_access(const char *filename, struct process_info pi) { if (!filename || ui_socket_fd == -1) { return -1; } // Lock the mutex for thread safety pthread_mutex_lock(&socket_mutex); int client_fd = accept(ui_socket_fd, NULL, NULL); if (client_fd == -1) { perror("accept"); pthread_mutex_unlock(&socket_mutex); return -1; } // Prepare the message to send to the GUI char message[MAX_MESSAGE_SIZE]; int len_filename = strlen(filename); int len_name = strlen(pi.name); snprintf(message, sizeof(message), "r%04d%s%04d%04d%s%04d", len_filename, filename, pi.PID, len_name, pi.name, pi.UID); // Send the message to the GUI if (send(client_fd, message, strlen(message), 0) == -1) { perror("send"); close(client_fd); pthread_mutex_unlock(&socket_mutex); return -1; } // Receive the response from the GUI char response[2]; if (recv(client_fd, response, sizeof(response), 0) == -1) { perror("recv"); close(client_fd); pthread_mutex_unlock(&socket_mutex); return -1; } close(client_fd); pthread_mutex_unlock(&socket_mutex); // Process the response if (response[0] == 'a' && response[1] == 'y') { return 0; // Access granted } else if (response[0] == 'a' && response[1] == 'n') { return 1; // Access denied } return -1; // Invalid response }