31 #define SHUT_RDWR SD_BOTH 32 #define SHUT_WR SD_SEND 33 #define LASTERROR WSAGetLastError() 34 #define ERRNO_INTR WSAEINTR 35 typedef int socklen_t;
36 typedef IN_ADDR in_addr_t;
40 #include <sys/types.h> 41 #include <sys/socket.h> 42 #include <sys/select.h> 43 #include <netinet/in.h> 45 #include <arpa/inet.h> 46 #define closesocket(a) close(a) 47 #define LASTERROR errno 48 #define ERRNO_INTR EINTR 55 static int __addressFamily(SOCKET_AF_t saf)
73 sockaddr_storage data;
78 inline sockaddr* sa() {
return (sockaddr*)&data; }
79 inline int sa_family() {
return data.ss_family; }
80 void Clear(
int family)
82 memset(&data, 0,
sizeof(data));
83 data.ss_family = family;
84 sa_len = (family == AF_INET ?
sizeof(sockaddr_in) :
sizeof(sockaddr_in6));
95 static char my_hostname[SOCKET_HOSTNAME_MAXSIZE];
96 static volatile net_socket_t my_socket;
98 static void __sigHandler(
int sig)
100 closesocket(my_socket);
101 my_socket = INVALID_SOCKET_VALUE;
105 TcpSocket::TcpSocket()
107 , m_socket(INVALID_SOCKET_VALUE)
108 , m_rcvbuf(SOCKET_RCVBUF_MINSIZE)
110 , m_attempt(SOCKET_READ_ATTEMPT)
113 , m_buflen(SOCKET_BUFFER_SIZE)
118 TcpSocket::~TcpSocket()
126 static int __connectAddr(
struct addrinfo *addr, net_socket_t *s,
int rcvbuf)
129 void (*old_sighandler)(int);
133 int err = 0, opt_rcvbuf;
135 if ((my_hostname[0] ==
'\0') && (gethostname(my_hostname,
sizeof (my_hostname)) < 0))
138 DBG(DBG_ERROR,
"%s: gethostname failed (%d)\n", __FUNCTION__, err);
142 *s = socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
143 if (*s == INVALID_SOCKET_VALUE)
146 DBG(DBG_ERROR,
"%s: invalid socket (%d)\n", __FUNCTION__, err);
150 opt_rcvbuf = (rcvbuf < SOCKET_RCVBUF_MINSIZE ? SOCKET_RCVBUF_MINSIZE : rcvbuf);
151 size =
sizeof (opt_rcvbuf);
152 if (setsockopt(*s, SOL_SOCKET, SO_RCVBUF, (
char *)&opt_rcvbuf, size))
153 DBG(DBG_WARN,
"%s: could not set rcvbuf from socket (%d)\n", __FUNCTION__, LASTERROR);
154 if (getsockopt(*s, SOL_SOCKET, SO_RCVBUF, (
char *)&opt_rcvbuf, &size))
155 DBG(DBG_WARN,
"%s: could not get rcvbuf from socket (%d)\n", __FUNCTION__, LASTERROR);
159 if (setsockopt(*s, SOL_SOCKET, SO_NOSIGPIPE, (
void *)&opt_set,
sizeof(
int)))
160 DBG(DBG_WARN,
"%s: could not set nosigpipe from socket (%d)\n", __FUNCTION__, LASTERROR);
164 old_sighandler = signal(SIGALRM, __sigHandler);
165 old_alarm = alarm(5);
168 if (connect(*s, addr->ai_addr, addr->ai_addrlen) < 0)
171 DBG(DBG_ERROR,
"%s: failed to connect (%d)\n", __FUNCTION__, err);
173 *s = INVALID_SOCKET_VALUE;
175 signal(SIGALRM, old_sighandler);
181 my_socket = INVALID_SOCKET_VALUE;
182 signal(SIGALRM, old_sighandler);
185 DBG(DBG_PROTO,
"%s: connected to socket(%p)\n", __FUNCTION__, s);
191 struct addrinfo hints;
192 struct addrinfo *result, *addr;
199 if (rcvbuf > SOCKET_RCVBUF_MINSIZE)
202 memset(&hints, 0,
sizeof (hints));
203 hints.ai_family = AF_UNSPEC;
204 hints.ai_socktype = SOCK_STREAM;
205 hints.ai_protocol = IPPROTO_TCP;
206 snprintf(service,
sizeof(service),
"%u", port);
208 err = getaddrinfo(server, service, &hints, &result);
214 DBG(DBG_ERROR,
"%s: the specified host is unknown\n", __FUNCTION__);
217 DBG(DBG_ERROR,
"%s: a non-recoverable failure in name resolution occurred\n", __FUNCTION__);
220 DBG(DBG_ERROR,
"%s: a memory allocation failure occurred\n", __FUNCTION__);
223 DBG(DBG_ERROR,
"%s: a temporary error occurred on an authoritative name server\n", __FUNCTION__);
226 DBG(DBG_ERROR,
"%s: unknown error %d\n", __FUNCTION__, err);
233 for (addr = result; addr; addr = addr->ai_next)
235 err = __connectAddr(addr, &m_socket, m_rcvbuf);
239 freeaddrinfo(result);
241 return (err ?
false :
true);
249 #if defined(__WINDOWS__) || defined(SO_NOSIGPIPE) 250 size_t s = send(m_socket, msg, size, 0);
256 #elif defined(MSG_NOSIGNAL) 257 size_t s = send(m_socket, msg, size, MSG_NOSIGNAL);
264 sigset_t sig_block, sig_restore, sig_pending;
265 sigemptyset(&sig_block);
266 sigaddset(&sig_block, SIGPIPE);
272 if (pthread_sigmask(SIG_BLOCK, &sig_block, &sig_restore) != 0)
277 int sigpipe_pending = -1;
278 if (sigpending(&sig_pending) != -1)
279 sigpipe_pending = sigismember(&sig_pending, SIGPIPE);
280 if (sigpipe_pending == -1)
282 pthread_sigmask(SIG_SETMASK, &sig_restore, NULL);
286 size_t s = send(m_socket, msg, size, 0);
297 if (m_errno == EPIPE && sigpipe_pending == 0)
303 while ((sig = sigtimedwait(&sig_block, 0, &ts)) == -1 && LASTERROR == EINTR);
305 pthread_sigmask(SIG_SETMASK, &sig_restore, NULL);
308 pthread_sigmask(SIG_SETMASK, &sig_restore, NULL);
324 char *p = (
char*)buf;
329 if (m_bufptr < m_buffer + m_rcvlen)
331 rcvlen = m_rcvlen - (m_bufptr - m_buffer);
334 memcpy(p, m_bufptr, rcvlen);
342 else if ((m_buffer =
new char[m_buflen]) == NULL)
345 DBG(DBG_ERROR,
"%s: cannot allocate %u bytes for buffer\n", __FUNCTION__, m_buflen);
354 int r = 0, hangcount = 0;
360 FD_SET(m_socket, &fds);
361 r = select(m_socket + 1, &fds, NULL, NULL, &tv);
367 if ((r = recv(m_socket, m_buffer, m_buflen, 0)) > 0)
373 memcpy(p, m_buffer, s);
374 m_bufptr = m_buffer + s;
383 if ((r = recv(m_socket, p, n, 0)) > 0)
393 DBG(DBG_WARN,
"%s: socket(%p) timed out (%d)\n", __FUNCTION__, &m_socket, hangcount);
395 if (++hangcount >= m_attempt)
401 if (m_errno != ERRNO_INTR)
420 shutdown(m_socket, SHUT_RDWR);
427 FD_SET(m_socket, &fds);
428 r = select(m_socket + 1, &fds, NULL, NULL, &tv);
430 r = recv(m_socket, buf,
sizeof(buf), 0);
433 closesocket(m_socket);
434 m_socket = INVALID_SOCKET_VALUE;
441 return (m_socket == INVALID_SOCKET_VALUE ?
false :
true);
452 FD_SET(m_socket, &fds);
453 r = select(m_socket + 1, &fds, NULL, NULL, timeout);
464 char host[INET6_ADDRSTRLEN];
465 memset(host, 0, INET6_ADDRSTRLEN);
470 char addr[
sizeof(sockaddr_in6)];
471 socklen_t addr_len =
sizeof(addr);
473 if (getsockname(m_socket, (sockaddr*)&addr, &addr_len) == 0)
474 getnameinfo((sockaddr*)&addr, addr_len, host,
sizeof(host), NULL, 0, NI_NUMERICHOST);
491 TcpServerSocket::TcpServerSocket()
492 : m_socket(INVALID_SOCKET_VALUE)
494 , m_requestQueueSize(0)
499 TcpServerSocket::~TcpServerSocket()
514 m_addr->Clear(__addressFamily(af));
515 m_socket = socket(m_addr->sa_family(), SOCK_STREAM, 0);
519 DBG(DBG_ERROR,
"%s: invalid socket (%d)\n", __FUNCTION__, m_errno);
526 int opt_exclusive = 1;
527 if (setsockopt(m_socket, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (
char*)&opt_exclusive,
sizeof(opt_exclusive)))
530 DBG(DBG_ERROR,
"%s: could not set exclusiveaddruse from socket (%d)\n", __FUNCTION__, m_errno);
536 int opt_reuseaddr = 1;
537 if (setsockopt(m_socket, SOL_SOCKET, SO_REUSEADDR, (
char*)&opt_reuseaddr,
sizeof(opt_reuseaddr)))
540 DBG(DBG_ERROR,
"%s: could not set reuseaddr from socket (%d)\n", __FUNCTION__, m_errno);
550 return (m_socket == INVALID_SOCKET_VALUE ?
false :
true);
559 m_addr->Clear(m_addr->sa_family());
560 switch (m_addr->sa_family())
564 sockaddr_in* sa = (sockaddr_in*)m_addr->sa();
565 sa->sin_addr.s_addr = htonl(INADDR_ANY);
566 sa->sin_port = htons(port);
567 r = bind(m_socket, m_addr->sa(), m_addr->sa_len);
572 sockaddr_in6* sa = (sockaddr_in6*)m_addr->sa();
573 sa->sin6_addr = in6addr_any;
574 sa->sin6_port = htons(port);
575 r = bind(m_socket, m_addr->sa(), m_addr->sa_len);
583 DBG(DBG_ERROR,
"%s: could not bind to address (%d)\n", __FUNCTION__, m_errno);
594 if (listen(m_socket, queueSize))
597 DBG(DBG_ERROR,
"%s: listen failed (%d)\n", __FUNCTION__, m_errno);
600 m_requestQueueSize = queueSize;
606 socket.m_socket = accept(m_socket, m_addr->sa(), &m_addr->sa_len);
610 DBG(DBG_ERROR,
"%s: accept failed (%d)\n", __FUNCTION__, m_errno);
616 if (setsockopt(socket.m_socket, SOL_SOCKET, SO_NOSIGPIPE, (
void *)&opt_set,
sizeof(
int)))
617 DBG(DBG_WARN,
"%s: could not set nosigpipe from socket (%d)\n", __FUNCTION__, LASTERROR);
628 closesocket(m_socket);
629 m_socket = INVALID_SOCKET_VALUE;
638 UdpSocket::UdpSocket()
639 : m_socket(INVALID_SOCKET_VALUE)
643 , m_buflen(SOCKET_BUFFER_SIZE)
650 UdpSocket::UdpSocket(
size_t bufferSize)
651 : m_socket(INVALID_SOCKET_VALUE)
655 , m_buflen(bufferSize)
662 UdpSocket::~UdpSocket()
666 closesocket(m_socket);
667 m_socket = INVALID_SOCKET_VALUE;
682 m_buffer = m_bufptr = NULL;
688 return Open(af) && SetAddress(target, port);
693 if (IsValid() && m_addr->sa_family() != __addressFamily(af))
695 closesocket(m_socket);
696 m_socket = INVALID_SOCKET_VALUE;
698 if (m_socket == INVALID_SOCKET_VALUE)
700 m_addr->Clear(__addressFamily(af));
701 m_from->Clear(AF_UNSPEC);
702 if ((m_socket = socket(m_addr->sa_family(), SOCK_DGRAM, IPPROTO_UDP)) == INVALID_SOCKET_VALUE)
705 DBG(DBG_ERROR,
"%s: create socket failed (%d)\n", __FUNCTION__, m_errno);
708 if (broadcast && af == SOCKET_AF_INET4)
712 if (setsockopt(m_socket, SOL_SOCKET, SO_BROADCAST, (
char*)&_broadcast,
sizeof(_broadcast)))
715 DBG(DBG_ERROR,
"%s: could not set SO_BROADCAST from socket (%d)\n", __FUNCTION__, m_errno);
728 DBG(DBG_ERROR,
"%s: invalid socket\n", __FUNCTION__);
732 unsigned char _addr[
sizeof(
struct in6_addr)];
733 if (inet_pton(m_addr->sa_family(), target, &_addr) == 0)
736 DBG(DBG_ERROR,
"%s: invalid address (%s)\n", __FUNCTION__, target);
740 m_addr->Clear(m_addr->sa_family());
741 switch(m_addr->sa_family())
745 sockaddr_in* sa = (sockaddr_in*)m_addr->sa();
746 memcpy(&(sa->sin_addr.s_addr), _addr,
sizeof(in_addr_t));
747 sa->sin_port = htons(port);
752 sockaddr_in6* sa = (sockaddr_in6*)m_addr->sa();
753 memcpy(&(sa->sin6_addr), _addr,
sizeof(
struct in6_addr));
754 sa->sin6_port = htons(port);
759 DBG(DBG_ERROR,
"%s: address familly unknown (%d)\n", __FUNCTION__, m_addr->sa_family());
771 switch(m_addr->sa_family())
776 unsigned char _ttl = (
unsigned char) multicastTTL;
777 if (setsockopt(m_socket, IPPROTO_IP, IP_MULTICAST_TTL, (
char*)&_ttl,
sizeof(_ttl)))
780 DBG(DBG_ERROR,
"%s: could not set IP_MULTICAST_TTL from socket (%d)\n", __FUNCTION__, m_errno);
788 if (setsockopt(m_socket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, (
char*)&multicastTTL,
sizeof(multicastTTL)))
791 DBG(DBG_ERROR,
"%s: could not set IPV6_MULTICAST_HOPS from socket (%d)\n", __FUNCTION__, m_errno);
798 DBG(DBG_ERROR,
"%s: address familly unknown (%d)\n", __FUNCTION__, m_addr->sa_family());
809 size_t s = sendto(m_socket, buf, size, 0, m_addr->sa(), m_addr->sa_len);
832 if (m_bufptr < m_buffer + m_rcvlen)
834 len = m_rcvlen - (m_bufptr - m_buffer);
837 memcpy(buf, m_bufptr, len);
842 else if ((m_buffer =
new char[m_buflen]) == NULL)
845 DBG(DBG_ERROR,
"%s: cannot allocate %u bytes for buffer\n", __FUNCTION__, m_buflen);
858 FD_SET(m_socket, &fds);
859 r = select(m_socket + 1, &fds, NULL, NULL, &tv);
862 if ((r = recvfrom(m_socket, m_buffer, m_buflen, 0, m_from->sa(), &m_from->sa_len)) > 0)
865 if (m_rcvlen == m_buflen)
866 DBG(DBG_WARN,
"%s: datagram have been truncated (%d)\n", __FUNCTION__, r);
869 memcpy(buf, m_buffer, len);
876 DBG(DBG_DEBUG,
"%s: socket(%p) timed out\n", __FUNCTION__, &m_socket);
881 DBG(DBG_ERROR,
"%s: socket(%p) read error (%d)\n", __FUNCTION__, &m_socket, m_errno);
891 return (m_socket == INVALID_SOCKET_VALUE ?
false :
true);
896 char host[INET6_ADDRSTRLEN];
897 memset(host, 0, INET6_ADDRSTRLEN);
898 getnameinfo(m_from->sa(), m_from->sa_len, host,
sizeof(host), NULL, 0, NI_NUMERICHOST);
907 UdpServerSocket::UdpServerSocket()
908 : m_socket(INVALID_SOCKET_VALUE)
912 , m_buflen(SOCKET_BUFFER_SIZE)
917 m_timeout.tv_sec = SOCKET_READ_TIMEOUT_SEC;
918 m_timeout.tv_usec = SOCKET_READ_TIMEOUT_USEC;
922 UdpServerSocket::UdpServerSocket(
size_t bufferSize)
923 : m_socket(INVALID_SOCKET_VALUE)
927 , m_buflen(bufferSize)
932 m_timeout.tv_sec = SOCKET_READ_TIMEOUT_SEC;
933 m_timeout.tv_usec = SOCKET_READ_TIMEOUT_USEC;
936 UdpServerSocket::~UdpServerSocket()
940 closesocket(m_socket);
941 m_socket = INVALID_SOCKET_VALUE;
956 m_buffer = m_bufptr = NULL;
965 m_addr->Clear(__addressFamily(af));
966 m_socket = socket(m_addr->sa_family(), SOCK_DGRAM, 0);
970 DBG(DBG_ERROR,
"%s: invalid socket (%d)\n", __FUNCTION__, m_errno);
974 int opt_reuseaddr = 1;
975 if (setsockopt(m_socket, SOL_SOCKET, SO_REUSEADDR, (
char*)&opt_reuseaddr,
sizeof(opt_reuseaddr)))
978 DBG(DBG_ERROR,
"%s: could not set reuseaddr from socket (%d)\n", __FUNCTION__, m_errno);
986 return (m_socket == INVALID_SOCKET_VALUE ?
false :
true);
994 m_addr->Clear(m_addr->sa_family());
995 switch (m_addr->sa_family())
999 sockaddr_in* sa = (sockaddr_in*)m_addr->sa();
1000 sa->sin_addr.s_addr = htonl(INADDR_ANY);
1001 sa->sin_port = htons(port);
1006 sockaddr_in6* sa = (sockaddr_in6*)m_addr->sa();
1007 sa->sin6_addr = in6addr_any;
1008 sa->sin6_port = htons(port);
1013 DBG(DBG_ERROR,
"%s: address familly unknown (%d)\n", __FUNCTION__, m_addr->sa_family());
1017 if (bind(m_socket, m_addr->sa(), m_addr->sa_len) != 0)
1019 m_errno = LASTERROR;
1020 DBG(DBG_ERROR,
"%s: could not bind to address (%d)\n", __FUNCTION__, m_errno);
1032 switch(m_addr->sa_family())
1037 unsigned char _ttl = (
unsigned char) multicastTTL;
1038 if (setsockopt(m_socket, IPPROTO_IP, IP_MULTICAST_TTL, (
char*)&_ttl,
sizeof(_ttl)))
1040 m_errno = LASTERROR;
1041 DBG(DBG_ERROR,
"%s: could not set IP_MULTICAST_TTL from socket (%d)\n", __FUNCTION__, m_errno);
1049 if (setsockopt(m_socket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, (
char*)&multicastTTL,
sizeof(multicastTTL)))
1051 m_errno = LASTERROR;
1052 DBG(DBG_ERROR,
"%s: could not set IPV6_MULTICAST_HOPS from socket (%d)\n", __FUNCTION__, m_errno);
1059 DBG(DBG_ERROR,
"%s: address familly unknown (%d)\n", __FUNCTION__, m_addr->sa_family());
1071 switch(m_addr->sa_family())
1075 struct ip_mreq mreq;
1076 if (inet_pton(AF_INET, group, &mreq.imr_multiaddr) == 0)
1078 m_errno = LASTERROR;
1079 DBG(DBG_ERROR,
"%s: invalid address (%d)\n", __FUNCTION__, m_errno);
1082 mreq.imr_interface.s_addr = htonl(INADDR_ANY);
1083 if (setsockopt(m_socket, IPPROTO_IP, join ? IP_ADD_MEMBERSHIP : IP_DROP_MEMBERSHIP, reinterpret_cast<const char*>(&mreq),
sizeof(mreq)))
1085 m_errno = LASTERROR;
1086 DBG(DBG_ERROR,
"%s: could not set multicast membership from socket (%d)\n", __FUNCTION__, m_errno);
1093 struct ipv6_mreq mreq;
1094 if (inet_pton(AF_INET6, group, &mreq.ipv6mr_multiaddr) == 0)
1096 m_errno = LASTERROR;
1097 DBG(DBG_ERROR,
"%s: invalid address (%d)\n", __FUNCTION__, m_errno);
1100 mreq.ipv6mr_interface = 0;
1101 if (setsockopt(m_socket, IPPROTO_IPV6, join ? IPV6_JOIN_GROUP : IPV6_LEAVE_GROUP, reinterpret_cast<const char*>(&mreq),
sizeof(mreq)))
1103 m_errno = LASTERROR;
1104 DBG(DBG_ERROR,
"%s: could not set multicast membership from socket (%d)\n", __FUNCTION__, m_errno);
1111 DBG(DBG_ERROR,
"%s: address familly unknown (%d)\n", __FUNCTION__, m_addr->sa_family());
1118 size_t UdpServerSocket::AwaitIncoming(timeval timeout)
1124 if (!m_buffer && (m_buffer =
new char[m_buflen]) == NULL)
1127 DBG(DBG_ERROR,
"%s: cannot allocate %u bytes for buffer\n", __FUNCTION__, m_buflen);
1131 m_bufptr = m_buffer;
1134 struct timeval tv = timeout;
1139 FD_SET(m_socket, &fds);
1140 r = select(m_socket + 1, &fds, NULL, NULL, &tv);
1143 if ((r = recvfrom(m_socket, m_buffer, m_buflen, 0, m_from->sa(), &m_from->sa_len)) > 0)
1146 if (m_rcvlen == m_buflen)
1147 DBG(DBG_WARN,
"%s: datagram have been truncated (%d)\n", __FUNCTION__, r);
1152 m_errno = ETIMEDOUT;
1153 DBG(DBG_DEBUG,
"%s: socket(%p) timed out\n", __FUNCTION__, &m_socket);
1157 m_errno = LASTERROR;
1158 DBG(DBG_ERROR,
"%s: socket(%p) read error (%d)\n", __FUNCTION__, &m_socket, m_errno);
1166 size_t UdpServerSocket::AwaitIncoming()
1168 return AwaitIncoming(m_timeout);
1173 char host[INET6_ADDRSTRLEN];
1174 memset(host, 0, INET6_ADDRSTRLEN);
1175 getnameinfo(m_from->sa(), m_from->sa_len, host,
sizeof(host), NULL, 0, NI_NUMERICHOST);
1186 if (m_buffer && m_bufptr < m_buffer + m_rcvlen)
1188 len = m_rcvlen - (m_bufptr - m_buffer);
1191 memcpy(buf, m_bufptr, len);
size_t ReadData(void *buf, size_t n)
bool SetAddress(const char *target, unsigned port)
int Listen(timeval *timeout)
virtual void Disconnect()
bool SetMulticastTTL(int multicastTTL)
bool Create(SOCKET_AF_t af)
bool SetMulticastMembership(const char *group, bool join)
virtual bool SendData(const char *buf, size_t size)
void SetReadAttempt(int n)
std::string GetRemoteAddrInfo() const
static const char * GetMyHostName()
bool SetMulticastTTL(int multicastTTL)
bool AcceptConnection(TcpSocket &socket)
bool SendData(const char *buf, size_t size)
virtual bool Connect(const char *server, unsigned port, int rcvbuf)
virtual size_t ReceiveData(void *buf, size_t n)
bool ListenConnection(int queueSize=SOCKET_CONNECTION_REQUESTS)
std::string GetRemoteAddrInfo() const
std::string GetHostAddrInfo()
bool Create(SOCKET_AF_t af)
virtual bool IsValid() const
size_t ReceiveData(void *buf, size_t n)
bool Open(SOCKET_AF_t af, const char *target, unsigned port)