From b0854bb3aad5f7b0cf461dae13f9e19a0c02199d Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Thu, 16 Apr 2020 16:46:45 +0200 Subject: [PATCH] chg: SOCKET: connections (@xianling1998) --- client/src/uart/uart_posix.c | 47 ++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/client/src/uart/uart_posix.c b/client/src/uart/uart_posix.c index 0077924cf..0e05f8389 100644 --- a/client/src/uart/uart_posix.c +++ b/client/src/uart/uart_posix.c @@ -48,6 +48,8 @@ #include #include #include +#include "sys/socket.h" +#include "sys/un.h" #include "comms.h" @@ -156,6 +158,51 @@ serial_port uart_open(const char *pcPortName, uint32_t speed) { return sp; } + // The socket for abstract namespace implement. + // Is local socket buffer, not a TCP or any net connection! + // so, you can't connect with address like: 127.0.0.1, or any IP + // see http://man7.org/linux/man-pages/man7/unix.7.html + if (memcmp(pcPortName, "socket:", 7) == 0) { + if (strlen(pcPortName) <= 7) { + free(sp); + return INVALID_SERIAL_PORT; + } + + // we must use max timeout! + timeout.tv_usec = UART_TCP_CLIENT_RX_TIMEOUT_MS * 1000; + + size_t servernameLen = (strlen(pcPortName) - 7) + 1; + char serverNameBuf[servernameLen]; + memset(serverNameBuf, '\0', servernameLen); + for (int i = 7, j = 0; j < servernameLen; ++i, ++j) { + serverNameBuf[j] = pcPortName[i]; + } + serverNameBuf[servernameLen - 1] = '\0'; + + int localsocket, len; + struct sockaddr_un remote; + + remote.sun_path[0] = '\0'; // abstract namespace + strcpy(remote.sun_path + 1, serverNameBuf); + remote.sun_family = AF_LOCAL; + int nameLen = strlen(serverNameBuf); + len = 1 + nameLen + offsetof(struct sockaddr_un, sun_path); + + if ((localsocket = socket(PF_LOCAL, SOCK_STREAM, 0)) == -1) { + free(sp); + return INVALID_SERIAL_PORT; + } + + if (connect(localsocket, (struct sockaddr *) &remote, len) == -1) { + free(sp); + return INVALID_SERIAL_PORT; + } + + sp->fd = localsocket; + + return sp; + } + sp->fd = open(pcPortName, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK); if (sp->fd == -1) { uart_close(sp);