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
36 #include <sys/types.h> // socket connect getaddrinfo
37 #include <string.h> // memset
38 #include <errno.h> // errno var
39 #include <stdlib.h> // malloc / free
48 static const char* TAG = "TCP";
55 CLOSESOCKET(abortSocket);
57 if (abortPipe[0] != -1)
69 logger = LogNT::getInstance();
72 abortSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
73 if (abortSocket == INVALID_SOCKET)
75 logger->crit(TAG, "socket error");
79 if (pipe2(abortPipe, O_NONBLOCK) == -1)
81 logger->crit(TAG, "pipe2 error");
89 bool TCP::connect(const std::string& ip, USHORT port)
91 if (connected) return false;
93 struct addrinfo hints;
94 memset(&hints, 0, sizeof(struct addrinfo));
95 hints.ai_family = AF_UNSPEC;
96 hints.ai_socktype = SOCK_STREAM;
97 hints.ai_flags = AI_NUMERICHOST | AI_NUMERICSERV;
101 SNPRINTF(portString, 10, "%u", port);
102 int gaiResult = getaddrinfo(ip.c_str(), portString, &hints, &aip);
104 if ((gaiResult != 0) || !aip)
106 logger->crit(TAG, "getaddrinfo error");
110 sockfd = socket(aip->ai_family, SOCK_STREAM, 0);
111 if (sockfd == -1) { logger->crit(TAG, "socket error"); return false; }
115 ioctlsocket(sockfd, FIONBIO, ¶m);
117 fcntl(sockfd, F_SETFL, O_NONBLOCK);
121 // There should only be one aip result..
122 int connectResult = ::connect(sockfd, aip->ai_addr, aip->ai_addrlen);
124 if (connectResult == 0) // success
132 if ((connectResult != SOCKET_ERROR) || (WSAGetLastError() != WSAEWOULDBLOCK))
134 if (errno != EINPROGRESS)
139 logger->crit(TAG, "connect error");
143 // Wait for connect to complete
146 FD_SET(sockfd, &writefds);
154 FD_SET(abortSocket, &readfds);
156 FD_SET(abortPipe[0], &readfds);
157 if (abortPipe[0] > maxfd) maxfd = abortPipe[0];
161 tv.tv_sec = 20; // Allow 5s for a connect
164 int selectResult = select(maxfd + 1, &readfds, &writefds, NULL, &tv);
166 if (FD_ISSET(abortSocket, &readfds))
168 if (FD_ISSET(abortPipe[0], &readfds))
173 logger->info(TAG, "connect/select aborting");
177 if ((selectResult == 1) || FD_ISSET(sockfd, &writefds))
180 logger->info(TAG, "Connected");
188 logger->crit(TAG, "connect/select error");
195 if (!connected) return;
202 while (recv(abortSocket, waste, 10, 0) > 0) ;
204 while (::read(abortPipe[0], waste, 10) > 0) ;
211 recStringBufStart = 0;
212 recStringBufUsed = 0;
221 void TCP::abortCall()
224 CLOSESOCKET(abortSocket);
226 ::write(abortPipe[1], "X", 1);
230 bool TCP::write(void* src, ULONG numBytes)
232 if (!connected) return false;
234 std::lock_guard<std::mutex> lg(writeMutex);
235 int result = send(sockfd, reinterpret_cast<char*>(src), numBytes, 0); // FIXME does send return < numBytes? Might need loop
236 if (result < 0) return false;
237 if (static_cast<ULONG>(result) != numBytes) return false;
242 bool TCP::read(void* dst, ULONG numBytes, int timeoutSec)
244 if (!connected) return false;
249 ULONG totalReceived = 0;
251 char* pointer = static_cast<char*>(dst); // WIN32 requires char*
255 if (++abortCount == 1000)
257 logger->error(TAG, "abortCount = 1000 - runaway error, or packet arrived in > 1000 pieces??");
262 FD_SET(sockfd, &readfds);
263 int maxfd = sockfd; // WIN32 ignores
266 FD_SET(abortSocket, &readfds);
268 FD_SET(abortPipe[0], &readfds);
269 if (abortPipe[0] > maxfd) maxfd = abortPipe[0];
275 tv.tv_sec = timeoutSec;
277 selectResult = select(maxfd + 1, &readfds, NULL, NULL, &tv);
281 selectResult = select(maxfd + 1, &readfds, NULL, NULL, NULL);
284 if (selectResult == -1) { shutdown(); return false; }
285 if (selectResult == 0) return false;
288 if (FD_ISSET(abortSocket, &readfds)) { logger->debug(TAG, "Aborting..."); return false; }
290 if (FD_ISSET(abortPipe[0], &readfds)) { logger->debug(TAG, "Aborting..."); return false; }
293 int recvResult = recv(sockfd, pointer, numBytes - totalReceived, 0);
294 if (recvResult == -1) { shutdown(); return false; }
295 totalReceived += recvResult;
296 pointer += recvResult;
298 } while (totalReceived < numBytes);
303 std::stringstream TCP::readString(bool* result, int timeoutSec)
307 std::stringstream ss;
309 if (!connected) return ss;
316 if (!recStringBuf) recStringBuf = static_cast<char*>(malloc(recStringBufSize));
317 if (!recStringBuf) return ss;
319 // Absorb over-read from last time?
320 if (recStringBufUsed)
322 ss.write(&recStringBuf[recStringBufStart], recStringBufUsed);
323 recStringBufStart = 0;
324 recStringBufUsed = 0;
329 if (++abortCount == 20)
331 logger->debug(TAG, "abortCount = 20");
336 FD_SET(sockfd, &readfds);
337 int maxfd = sockfd; // WIN32 ignores
340 FD_SET(abortSocket, &readfds);
342 FD_SET(abortPipe[0], &readfds);
343 if (abortPipe[0] > maxfd) maxfd = abortPipe[0];
349 tv.tv_sec = timeoutSec;
351 selectResult = select(maxfd + 1, &readfds, NULL, NULL, &tv);
355 selectResult = select(maxfd + 1, &readfds, NULL, NULL, NULL);
358 if (selectResult == -1) { shutdown(); return ss; }
359 if (selectResult == 0) return ss;
362 if (FD_ISSET(abortSocket, &readfds)) { logger->debug(TAG, "Aborting..."); return ss; }
364 if (FD_ISSET(abortPipe[0], &readfds)) { logger->debug(TAG, "Aborting..."); return ss; }
367 int recvResult = recv(sockfd, &recStringBuf[recStringBufUsed], recStringBufSize - recStringBufUsed, 0);
368 if (recvResult == -1) { shutdown(); return ss; }
369 recStringBufUsed += recvResult;
371 // Do we have a full string?
372 for(int i = 0; i < recStringBufUsed; i++)
374 if (recStringBuf[i] == '\n')
377 ss.write(recStringBuf, i);
379 if ((i + 1) != recStringBufUsed) // over read
381 i += 1; // Advance over \n
382 recStringBufStart = i;
383 recStringBufUsed -= i;
387 recStringBufUsed = 0;
394 // no \n in buffer, go around
398 MACAddress TCP::getMAC()
401 MACAddress macerror{ 00, 00, 00, 00, 00, 00 };
402 if (!connected) return macerror;
405 struct sockaddr - man 2 bind
406 struct sockaddr_in - man 7 ip
407 struct sockaddr_in6 - man 7 ipv6
408 struct sockaddr_ll - man 7 packet
411 // Measured sizeof(struct sockaddr_in) = 16, and in6 = 28
413 unsigned char gsnBuffer[buflen];
414 struct sockaddr* sap = reinterpret_cast<struct sockaddr*>(gsnBuffer);
415 if (getsockname(sockfd, sap, &buflen) == -1) return macerror;
418 unsigned char my6Addr[16];
420 if (sap->sa_family == AF_INET)
422 struct sockaddr_in* sap4 = reinterpret_cast<struct sockaddr_in*>(gsnBuffer);
423 my4AddrU32 = sap4->sin_addr.s_addr;
425 else if (sap->sa_family == AF_INET6)
427 struct sockaddr_in6* sap6 = reinterpret_cast<struct sockaddr_in6*>(gsnBuffer);
428 memcpy(my6Addr, sap6->sin6_addr.s6_addr, 16);
435 struct ifaddrs* ifAddrs;
436 if (getifaddrs(&ifAddrs) == -1) return macerror;
440 for(struct ifaddrs* ifa = ifAddrs; ifa != NULL; ifa = ifa->ifa_next)
442 if (ifa->ifa_addr->sa_family != sap->sa_family) continue;
444 if (sap->sa_family == AF_INET)
446 struct sockaddr_in* test = reinterpret_cast<struct sockaddr_in*>(ifa->ifa_addr);
447 if (test->sin_addr.s_addr == my4AddrU32)
449 ifName = ifa->ifa_name;
453 else if (sap->sa_family == AF_INET6)
455 struct sockaddr_in6* test = reinterpret_cast<struct sockaddr_in6*>(ifa->ifa_addr);
456 if (!memcmp(my6Addr, test->sin6_addr.s6_addr, 16))
458 ifName = ifa->ifa_name;
466 freeifaddrs(ifAddrs);
470 // Walk the list again to get the MAC for ifName using family == AF_PACKET
471 MACAddress toReturn = macerror;
473 for(struct ifaddrs* ifa = ifAddrs; ifa != NULL; ifa = ifa->ifa_next)
475 if (ifa->ifa_addr->sa_family != AF_PACKET) continue;
476 if (strcmp(ifName, ifa->ifa_name)) continue;
477 struct sockaddr_ll* sall = reinterpret_cast<struct sockaddr_ll*>(ifa->ifa_addr);
478 if (sall->sll_halen != 6) continue;
480 memcpy(&toReturn, sall->sll_addr, 6);
484 freeifaddrs(ifAddrs);
488 PIP_ADAPTER_INFO daptinfo = NULL;
490 GetAdaptersInfo(daptinfo, &size);
491 daptinfo = (PIP_ADAPTER_INFO)new char[size + 1];
492 MACAddress macresult;
493 memcpy(¯esult, "ABCDEF", 6);//Dummy Address
494 sockaddr_in sock_address;
495 int sockname_len = sizeof(sock_address);
496 getsockname(sockfd, (sockaddr*)&sock_address, &sockname_len);
497 ULONG sockip = sock_address.sin_addr.s_addr;
498 if (GetAdaptersInfo(daptinfo, &size) == ERROR_SUCCESS)
500 PIP_ADAPTER_INFO daptinfo_it = daptinfo;
501 while (daptinfo_it != NULL)
503 ULONG ipaddress = inet_addr(daptinfo_it->IpAddressList.IpAddress.String);
504 if (ipaddress == sockip)
506 memcpy(¯esult, daptinfo_it->Address, 6);
509 daptinfo_it = daptinfo_it->Next;
510 if (daptinfo_it == daptinfo) break;