|
| 1 | +#include <dcf_sdk/dcf_plugin_manager.h> |
| 2 | +#include <sys/socket.h> |
| 3 | +#include <sys/un.h> |
| 4 | +#include <unistd.h> |
| 5 | + |
| 6 | +typedef struct { |
| 7 | + int sock; |
| 8 | + struct sockaddr_un addr; |
| 9 | +} UnixSocketTransport; |
| 10 | + |
| 11 | +bool unixsocket_setup(void* self, const char* path, int unused) { |
| 12 | + UnixSocketTransport* ust = (UnixSocketTransport*)self; |
| 13 | + ust->sock = socket(AF_UNIX, SOCK_STREAM, 0); |
| 14 | + if (ust->sock < 0) return false; |
| 15 | + memset(&ust->addr, 0, sizeof(ust->addr)); |
| 16 | + ust->addr.sun_family = AF_UNIX; |
| 17 | + strncpy(ust->addr.sun_path, path, sizeof(ust->addr.sun_path) - 1); |
| 18 | + unlink(path); |
| 19 | + if (bind(ust->sock, (struct sockaddr*)&ust->addr, sizeof(ust->addr)) < 0) { |
| 20 | + close(ust->sock); |
| 21 | + return false; |
| 22 | + } |
| 23 | + listen(ust->sock, 5); |
| 24 | + return true; |
| 25 | +} |
| 26 | + |
| 27 | +bool unixsocket_send(void* self, const uint8_t* data, size_t size, const char* target) { |
| 28 | + UnixSocketTransport* ust = (UnixSocketTransport*)self; |
| 29 | + int client_sock = socket(AF_UNIX, SOCK_STREAM, 0); |
| 30 | + struct sockaddr_un target_addr; |
| 31 | + memset(&target_addr, 0, sizeof(target_addr)); |
| 32 | + target_addr.sun_family = AF_UNIX; |
| 33 | + strncpy(target_addr.sun_path, target, sizeof(target_addr.sun_path) - 1); |
| 34 | + if (connect(client_sock, (struct sockaddr*)&target_addr, sizeof(target_addr)) < 0) { |
| 35 | + close(client_sock); |
| 36 | + return false; |
| 37 | + } |
| 38 | + uint32_t len = htonl(size); |
| 39 | + send(client_sock, &len, sizeof(len), 0); |
| 40 | + ssize_t sent = send(client_sock, data, size, 0); |
| 41 | + close(client_sock); |
| 42 | + return sent == size; |
| 43 | +} |
| 44 | + |
| 45 | +uint8_t* unixsocket_receive(void* self, size_t* size) { |
| 46 | + UnixSocketTransport* ust = (UnixSocketTransport*)self; |
| 47 | + int client_sock = accept(ust->sock, NULL, NULL); |
| 48 | + if (client_sock < 0) return NULL; |
| 49 | + uint32_t len; |
| 50 | + recv(client_sock, &len, sizeof(len), 0); |
| 51 | + len = ntohl(len); |
| 52 | + uint8_t* buf = malloc(len); |
| 53 | + *size = recv(client_sock, buf, len, 0); |
| 54 | + close(client_sock); |
| 55 | + if (*size != len) { free(buf); return NULL; } |
| 56 | + return buf; |
| 57 | +} |
| 58 | + |
| 59 | +void unixsocket_destroy(void* self) { |
| 60 | + UnixSocketTransport* ust = (UnixSocketTransport*)self; |
| 61 | + unlink(ust->addr.sun_path); |
| 62 | + close(ust->sock); |
| 63 | + free(self); |
| 64 | +} |
| 65 | + |
| 66 | +ITransport iface = {unixsocket_setup, unixsocket_send, unixsocket_receive, unixsocket_destroy}; |
| 67 | + |
| 68 | +void* create_plugin() { return calloc(1, sizeof(UnixSocketTransport)); } |
| 69 | + |
| 70 | +const char* get_plugin_version() { return "1.0"; } |
0 commit comments