console-socket: Add an optional component to UNIX socket abstract names
Allows multiple instances of obmc-console-server to run concurrently
without interfering with each other.
Signed-off-by: Andrew Jeffery <andrew@aj.id.au>
Change-Id: I7ef9c14e554c687e8d606e1eaaed82a7f1c06d98
diff --git a/console-socket.c b/console-socket.c
index 9e1cf30..b0cd452 100644
--- a/console-socket.c
+++ b/console-socket.c
@@ -14,9 +14,53 @@
* limitations under the License.
*/
+#include "console-server.h"
+
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <sys/socket.h>
+#include <sys/un.h>
#include <sys/types.h>
-const char console_socket_path[] = "\0obmc-console";
-const size_t console_socket_path_len = sizeof(console_socket_path) - 1;
-const char *console_socket_path_readable = console_socket_path + 1;
+#define CONSOLE_SOCKET_PREFIX "obmc-console"
+ssize_t console_socket_path(struct sockaddr_un *addr, const char *id)
+{
+ char *sun_path;
+ ssize_t rc;
+
+ sun_path = (char *)addr + sizeof(*addr) - sizeof(addr->sun_path);
+
+ if (id) {
+ rc = snprintf(sun_path + 1, sizeof(addr->sun_path) - 1,
+ CONSOLE_SOCKET_PREFIX ".%s", id);
+ } else {
+ rc = snprintf(sun_path + 1, sizeof(addr->sun_path) - 1,
+ CONSOLE_SOCKET_PREFIX);
+ }
+
+ if (rc < 0)
+ return rc;
+
+ if (rc > (sizeof(addr->sun_path) - 1)) {
+ errno = 0;
+ return -1;
+ }
+
+ sun_path[0] = '\0';
+
+ return rc + 1 /* Capture NUL prefix */;
+}
+
+ssize_t console_socket_path_readable(const struct sockaddr_un *addr,
+ size_t addrlen, socket_path_t path)
+{
+ const char *src = (const char *)addr;
+ const size_t len = addrlen - sizeof(addr->sun_family) - 1;
+
+ memcpy(path, src + sizeof(addr->sun_family) + 1, len);
+ path[len] = '\0';
+
+ return len; /* strlen() style */
+}