2 Copyright 2020 Chris Tallon
4 This file is part of VOMP.
6 VOMP is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
11 VOMP is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with VOMP. If not, see <https://www.gnu.org/licenses/>.
20 #include <string.h> // memcmp
26 #include <unistd.h> // pipe2
27 #include <fcntl.h> // pipe2-O_NONBLOCK fcntl
28 #include <sys/socket.h> // socket connect getaddrinfo
29 #include <netdb.h> // getaddrinfo
30 #include <sys/select.h> // select
31 #include <linux/if_packet.h> // for getMAC
32 #include <net/ethernet.h> // for getMAC
33 #include <ifaddrs.h> // getifaddrs
34 #include <sys/un.h> // uds
37 #include <sys/types.h> // socket connect getaddrinfo
38 #include <string.h> // memset
39 #include <errno.h> // errno var
40 #include <stdlib.h> // malloc / free
49 static const char* TAG = "TCP";
56 CLOSESOCKET(abortSocket);
58 if (abortPipe[0] != -1)
70 logger = LogNT::getInstance();
73 abortSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
74 if (abortSocket == INVALID_SOCKET)
76 logger->crit(TAG, "socket error");
80 if (pipe2(abortPipe, O_NONBLOCK) == -1)
82 logger->crit(TAG, "pipe2 error");
91 bool TCP::connectSocket(const std::string& socketFile)
93 if (connected) return false;
95 int pathLength = strlen(socketFile.c_str()); // Specifically use strlen rather than std::string length stuff
96 if (pathLength > 107) { logger->crit(TAG, "socket name too long"); return false; }
98 sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
99 if (sockfd == -1) { logger->crit(TAG, "socket error"); return false; }
101 fcntl(sockfd, F_SETFL, O_NONBLOCK);
103 struct sockaddr_un uds;
104 uds.sun_family = AF_UNIX;
105 strcpy(uds.sun_path, socketFile.c_str());
106 int connectResult = ::connect(sockfd, (struct sockaddr *)&uds, pathLength + sizeof(uds.sun_family));
108 if (connectResult == 0) // success
114 return waitForConnect(connectResult);
118 bool TCP::connect(const std::string& ip, USHORT port)
120 if (connected) return false;
122 struct addrinfo hints;
123 memset(&hints, 0, sizeof(struct addrinfo));
124 hints.ai_family = AF_UNSPEC;
125 hints.ai_socktype = SOCK_STREAM;
126 hints.ai_flags = AI_NUMERICHOST | AI_NUMERICSERV;
128 struct addrinfo* aip;
130 SNPRINTF(portString, 10, "%u", port);
131 int gaiResult = getaddrinfo(ip.c_str(), portString, &hints, &aip);
133 if ((gaiResult != 0) || !aip)
135 logger->crit(TAG, "getaddrinfo error");
139 sockfd = socket(aip->ai_family, SOCK_STREAM, 0);
140 if (sockfd == -1) { logger->crit(TAG, "socket error"); return false; }
144 ioctlsocket(sockfd, FIONBIO, ¶m);
146 fcntl(sockfd, F_SETFL, O_NONBLOCK);
150 // There should only be one aip result..
151 int connectResult = ::connect(sockfd, aip->ai_addr, aip->ai_addrlen);
155 if (connectResult == 0) // success
161 return waitForConnect(connectResult);
164 bool TCP::waitForConnect(int connectResult)
167 if ((connectResult != SOCKET_ERROR) || (WSAGetLastError() != WSAEWOULDBLOCK))
169 if (errno != EINPROGRESS)
174 logger->crit(TAG, "connect error");
178 // Wait for connect to complete
181 FD_SET(sockfd, &writefds);
189 FD_SET(abortSocket, &readfds);
191 FD_SET(abortPipe[0], &readfds);
192 if (abortPipe[0] > maxfd) maxfd = abortPipe[0];
196 tv.tv_sec = 20; // Allow 5s for a connect
199 int selectResult = select(maxfd + 1, &readfds, &writefds, NULL, &tv);
201 if (FD_ISSET(abortSocket, &readfds))
203 if (FD_ISSET(abortPipe[0], &readfds))
208 logger->info(TAG, "connect/select aborting");
212 if ((selectResult == 1) || FD_ISSET(sockfd, &writefds))
214 logger->info(TAG, "Connected");
222 logger->crit(TAG, "connect/select error");
229 if (!connected) return;
236 while (recv(abortSocket, waste, 10, 0) > 0) ;
238 while (::read(abortPipe[0], waste, 10) > 0) ;
245 recStringBufStart = 0;
246 recStringBufUsed = 0;
255 void TCP::abortCall()
258 CLOSESOCKET(abortSocket);
260 ::write(abortPipe[1], "X", 1);
264 bool TCP::write(void* src, ULONG numBytes)
266 if (!connected) return false;
268 std::lock_guard<std::mutex> lg(writeMutex);
269 int result = send(sockfd, reinterpret_cast<char*>(src), numBytes, 0); // FIXME does send return < numBytes? Might need loop
270 if (result < 0) return false;
271 if (static_cast<ULONG>(result) != numBytes) return false;
276 bool TCP::read(void* dst, ULONG numBytes, int timeoutSec)
278 if (!connected) return false;
283 ULONG totalReceived = 0;
285 char* pointer = static_cast<char*>(dst); // WIN32 requires char*
289 if (++abortCount == 1000)
291 logger->error(TAG, "abortCount = 1000 - runaway error, or packet arrived in > 1000 pieces??");
296 FD_SET(sockfd, &readfds);
297 int maxfd = sockfd; // WIN32 ignores
300 FD_SET(abortSocket, &readfds);
302 FD_SET(abortPipe[0], &readfds);
303 if (abortPipe[0] > maxfd) maxfd = abortPipe[0];
309 tv.tv_sec = timeoutSec;
311 selectResult = select(maxfd + 1, &readfds, NULL, NULL, &tv);
315 selectResult = select(maxfd + 1, &readfds, NULL, NULL, NULL);
318 if (selectResult == -1) { shutdown(); return false; }
319 if (selectResult == 0) return false;
322 if (FD_ISSET(abortSocket, &readfds)) { logger->debug(TAG, "Aborting..."); return false; }
324 if (FD_ISSET(abortPipe[0], &readfds)) { logger->debug(TAG, "Aborting..."); return false; }
327 int recvResult = recv(sockfd, pointer, numBytes - totalReceived, 0);
328 if (recvResult == -1) { shutdown(); return false; }
329 totalReceived += recvResult;
330 pointer += recvResult;
332 } while (totalReceived < numBytes);
337 std::stringstream TCP::readString(bool* result, int timeoutSec)
341 std::stringstream ss;
343 if (!connected) return ss;
350 if (!recStringBuf) recStringBuf = static_cast<char*>(malloc(recStringBufSize));
351 if (!recStringBuf) return ss;
353 // Absorb over-read from last time?
354 if (recStringBufUsed)
356 ss.write(&recStringBuf[recStringBufStart], recStringBufUsed);
357 recStringBufStart = 0;
358 recStringBufUsed = 0;
363 if (++abortCount == 20)
365 logger->debug(TAG, "abortCount = 20");
370 FD_SET(sockfd, &readfds);
371 int maxfd = sockfd; // WIN32 ignores
374 FD_SET(abortSocket, &readfds);
376 FD_SET(abortPipe[0], &readfds);
377 if (abortPipe[0] > maxfd) maxfd = abortPipe[0];
383 tv.tv_sec = timeoutSec;
385 selectResult = select(maxfd + 1, &readfds, NULL, NULL, &tv);
389 selectResult = select(maxfd + 1, &readfds, NULL, NULL, NULL);
392 if (selectResult == -1) { shutdown(); return ss; }
393 if (selectResult == 0) return ss;
396 if (FD_ISSET(abortSocket, &readfds)) { logger->debug(TAG, "Aborting..."); return ss; }
398 if (FD_ISSET(abortPipe[0], &readfds)) { logger->debug(TAG, "Aborting..."); return ss; }
401 int recvResult = recv(sockfd, &recStringBuf[recStringBufUsed], recStringBufSize - recStringBufUsed, 0);
402 if (recvResult == -1) { shutdown(); return ss; }
403 recStringBufUsed += recvResult;
405 // Do we have a full string?
406 for(int i = 0; i < recStringBufUsed; i++)
408 if (recStringBuf[i] == '\n')
411 ss.write(recStringBuf, i);
413 if ((i + 1) != recStringBufUsed) // over read
415 i += 1; // Advance over \n
416 recStringBufStart = i;
417 recStringBufUsed -= i;
421 recStringBufUsed = 0;
428 // no \n in buffer, go around
432 MACAddress TCP::getMAC()
435 MACAddress macerror{ 00, 00, 00, 00, 00, 00 };
436 if (!connected) return macerror;
439 struct sockaddr - man 2 bind
440 struct sockaddr_in - man 7 ip
441 struct sockaddr_in6 - man 7 ipv6
442 struct sockaddr_ll - man 7 packet
445 // Measured sizeof(struct sockaddr_in) = 16, and in6 = 28
447 unsigned char gsnBuffer[buflen];
448 struct sockaddr* sap = reinterpret_cast<struct sockaddr*>(gsnBuffer);
449 if (getsockname(sockfd, sap, &buflen) == -1) return macerror;
452 unsigned char my6Addr[16];
454 if (sap->sa_family == AF_INET)
456 struct sockaddr_in* sap4 = reinterpret_cast<struct sockaddr_in*>(gsnBuffer);
457 my4AddrU32 = sap4->sin_addr.s_addr;
459 else if (sap->sa_family == AF_INET6)
461 struct sockaddr_in6* sap6 = reinterpret_cast<struct sockaddr_in6*>(gsnBuffer);
462 memcpy(my6Addr, sap6->sin6_addr.s6_addr, 16);
469 struct ifaddrs* ifAddrs;
470 if (getifaddrs(&ifAddrs) == -1) return macerror;
474 for(struct ifaddrs* ifa = ifAddrs; ifa != NULL; ifa = ifa->ifa_next)
476 if (ifa->ifa_addr->sa_family != sap->sa_family) continue;
478 if (sap->sa_family == AF_INET)
480 struct sockaddr_in* test = reinterpret_cast<struct sockaddr_in*>(ifa->ifa_addr);
481 if (test->sin_addr.s_addr == my4AddrU32)
483 ifName = ifa->ifa_name;
487 else if (sap->sa_family == AF_INET6)
489 struct sockaddr_in6* test = reinterpret_cast<struct sockaddr_in6*>(ifa->ifa_addr);
490 if (!memcmp(my6Addr, test->sin6_addr.s6_addr, 16))
492 ifName = ifa->ifa_name;
500 freeifaddrs(ifAddrs);
504 // Walk the list again to get the MAC for ifName using family == AF_PACKET
505 MACAddress toReturn = macerror;
507 for(struct ifaddrs* ifa = ifAddrs; ifa != NULL; ifa = ifa->ifa_next)
509 if (ifa->ifa_addr->sa_family != AF_PACKET) continue;
510 if (strcmp(ifName, ifa->ifa_name)) continue;
511 struct sockaddr_ll* sall = reinterpret_cast<struct sockaddr_ll*>(ifa->ifa_addr);
512 if (sall->sll_halen != 6) continue;
514 memcpy(&toReturn, sall->sll_addr, 6);
518 freeifaddrs(ifAddrs);
522 PIP_ADAPTER_INFO daptinfo = NULL;
524 GetAdaptersInfo(daptinfo, &size);
525 daptinfo = (PIP_ADAPTER_INFO)new char[size + 1];
526 MACAddress macresult;
527 memcpy(¯esult, "ABCDEF", 6);//Dummy Address
528 sockaddr_in sock_address;
529 int sockname_len = sizeof(sock_address);
530 getsockname(sockfd, (sockaddr*)&sock_address, &sockname_len);
531 ULONG sockip = sock_address.sin_addr.s_addr;
532 if (GetAdaptersInfo(daptinfo, &size) == ERROR_SUCCESS)
534 PIP_ADAPTER_INFO daptinfo_it = daptinfo;
535 while (daptinfo_it != NULL)
537 ULONG ipaddress = inet_addr(daptinfo_it->IpAddressList.IpAddress.String);
538 if (ipaddress == sockip)
540 memcpy(¯esult, daptinfo_it->Address, 6);
543 daptinfo_it = daptinfo_it->Next;
544 if (daptinfo_it == daptinfo) break;