1 /* 2 * Copyright 2019 Intel Corporation 3 * SPDX-License-Identifier: MIT 4 */ 5 6 #include <errno.h> 7 8 #include "os_socket.h" 9 10 #if defined(__linux__) 11 12 #include <fcntl.h> 13 #include <poll.h> 14 #include <stddef.h> 15 #include <string.h> 16 #include <sys/socket.h> 17 #include <sys/un.h> 18 #include <unistd.h> 19 20 int 21 os_socket_listen_abstract(const char *path, int count) 22 { 23 int s = socket(AF_UNIX, SOCK_STREAM, 0); 24 if (s < 0) 25 return -1; 26 27 struct sockaddr_un addr; 28 memset(&addr, 0, sizeof(addr)); 29 addr.sun_family = AF_UNIX; 30 strncpy(addr.sun_path + 1, path, sizeof(addr.sun_path) - 2); 31 32 /* Create an abstract socket */ 33 int ret = bind(s, (struct sockaddr*)&addr, 34 offsetof(struct sockaddr_un, sun_path) + 35 strlen(path) + 1); 36 if (ret < 0) { 37 close(s); 38 return -1; 39 } 40 41 if (listen(s, count) < 0) { 42 close(s); 43 return -1; 44 } 45 46 return s; 47 } 48 49 int 50 os_socket_accept(int s) 51 { 52 return accept(s, NULL, NULL); 53 } 54 55 ssize_t 56 os_socket_recv(int socket, void *buffer, size_t length, int flags) 57 { 58 return recv(socket, buffer, length, flags); 59 } 60 61 ssize_t 62 os_socket_send(int socket, const void *buffer, size_t length, int flags) 63 { 64 return send(socket, buffer, length, flags); 65 } 66 67 void 68 os_socket_block(int s, bool block) 69 { 70 int old = fcntl(s, F_GETFL, 0); 71 if (old == -1) 72 return; 73 74 /* TODO obey block */ 75 if (block) 76 fcntl(s, F_SETFL, old & ~O_NONBLOCK); 77 else 78 fcntl(s, F_SETFL, old | O_NONBLOCK); 79 } 80 81 void 82 os_socket_close(int s) 83 { 84 close(s); 85 } 86 87 #else 88 89 int 90 os_socket_listen_abstract(const char *path, int count) 91 { 92 errno = -ENOSYS; 93 return -1; 94 } 95 96 int 97 os_socket_accept(int s) 98 { 99 errno = -ENOSYS; 100 return -1; 101 } 102 103 ssize_t 104 os_socket_recv(int socket, void *buffer, size_t length, int flags) 105 { 106 errno = -ENOSYS; 107 return -1; 108 } 109 110 ssize_t 111 os_socket_send(int socket, const void *buffer, size_t length, int flags) 112 { 113 errno = -ENOSYS; 114 return -1; 115 } 116 117 void 118 os_socket_block(int s, bool block) 119 { 120 } 121 122 void 123 os_socket_close(int s) 124 { 125 } 126 127 #endif 128