added SyncRtpCommand
[anytun.git] / PracticalSocket.cpp
blob5d39557eb7ee32dbdc57e29b8185b268bfe6b74b
1 /*
2 * anytun
4 * The secure anycast tunneling protocol (satp) defines a protocol used
5 * for communication between any combination of unicast and anycast
6 * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel
7 * mode and allows tunneling of every ETHER TYPE protocol (e.g.
8 * ethernet, ip, arp ...). satp directly includes cryptography and
9 * message authentication based on the methodes used by SRTP. It is
10 * intended to deliver a generic, scaleable and secure solution for
11 * tunneling and relaying of packets of any protocol.
14 * Copyright (C) 2007 anytun.org <satp@wirdorange.org>
16 * This program is free software; you can redistribute it and/or modify
17 * it under the terms of the GNU General Public License version 2
18 * as published by the Free Software Foundation.
20 * This program is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 * GNU General Public License for more details.
25 * You should have received a copy of the GNU General Public License
26 * along with this program (see the file COPYING included with this
27 * distribution); if not, write to the Free Software Foundation, Inc.,
28 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
31 // this is from: http://cs.ecs.baylor.edu/~donahoo/practical/CSockets/practical/
32 // and this is their header:
34 * C++ sockets on Unix and Windows
35 * Copyright (C) 2002
37 * This program is free software; you can redistribute it and/or modify
38 * it under the terms of the GNU General Public License as published by
39 * the Free Software Foundation; either version 2 of the License, or
40 * (at your option) any later version.
42 * This program is distributed in the hope that it will be useful,
43 * but WITHOUT ANY WARRANTY; without even the implied warranty of
44 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
45 * GNU General Public License for more details.
47 * You should have received a copy of the GNU General Public License
48 * along with this program; if not, write to the Free Software
49 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
52 #include "PracticalSocket.h"
54 #ifdef WIN32
55 #include <winsock.h> // For socket(), connect(), send(), and recv()
56 typedef int socklen_t;
57 typedef char raw_type; // Type used for raw data on this platform
58 #else
59 #include <sys/types.h> // For data types
60 #include <sys/socket.h> // For socket(), connect(), send(), and recv()
61 #include <netdb.h> // For gethostbyname()
62 #include <arpa/inet.h> // For inet_addr()
63 #include <unistd.h> // For close()
64 #include <netinet/in.h> // For sockaddr_in
65 typedef void raw_type; // Type used for raw data on this platform
66 #endif
68 #include <errno.h> // For errno
70 using namespace std;
72 #ifdef WIN32
73 static bool initialized = false;
74 #endif
76 // SocketException Code
78 SocketException::SocketException(const string &message, bool inclSysMsg)
79 throw() : userMessage(message) {
80 if (inclSysMsg) {
81 userMessage.append(": ");
82 userMessage.append(strerror(errno));
86 SocketException::~SocketException() throw() {
89 const char *SocketException::what() const throw() {
90 return userMessage.c_str();
93 // Function to fill in address structure given an address and port
94 static void fillAddr(const string &address, unsigned short port,
95 sockaddr_in &addr) {
96 memset(&addr, 0, sizeof(addr)); // Zero out address structure
97 addr.sin_family = AF_INET; // Internet address
99 hostent *host; // Resolve name
100 if ((host = gethostbyname(address.c_str())) == NULL) {
101 // strerror() will not work for gethostbyname() and hstrerror()
102 // is supposedly obsolete
103 throw SocketException("Failed to resolve name (gethostbyname())");
105 addr.sin_addr.s_addr = *((unsigned long *) host->h_addr_list[0]);
107 addr.sin_port = htons(port); // Assign port in network byte order
110 // Socket Code
112 Socket::Socket(int type, int protocol) throw(SocketException) {
113 #ifdef WIN32
114 if (!initialized) {
115 WORD wVersionRequested;
116 WSADATA wsaData;
118 wVersionRequested = MAKEWORD(2, 0); // Request WinSock v2.0
119 if (WSAStartup(wVersionRequested, &wsaData) != 0) { // Load WinSock DLL
120 throw SocketException("Unable to load WinSock DLL");
122 initialized = true;
124 #endif
126 // Make a new socket
127 if ((sockDesc = socket(PF_INET, type, protocol)) < 0) {
128 throw SocketException("Socket creation failed (socket())", true);
132 Socket::Socket(int sockDesc) {
133 this->sockDesc = sockDesc;
136 Socket::~Socket() {
137 #ifdef WIN32
138 ::closesocket(sockDesc);
139 #else
140 ::close(sockDesc);
141 #endif
142 sockDesc = -1;
145 string Socket::getLocalAddress() throw(SocketException) {
146 sockaddr_in addr;
147 unsigned int addr_len = sizeof(addr);
149 if (getsockname(sockDesc, (sockaddr *) &addr, (socklen_t *) &addr_len) < 0) {
150 throw SocketException("Fetch of local address failed (getsockname())", true);
152 return inet_ntoa(addr.sin_addr);
155 unsigned short Socket::getLocalPort() throw(SocketException) {
156 sockaddr_in addr;
157 unsigned int addr_len = sizeof(addr);
159 if (getsockname(sockDesc, (sockaddr *) &addr, (socklen_t *) &addr_len) < 0) {
160 throw SocketException("Fetch of local port failed (getsockname())", true);
162 return ntohs(addr.sin_port);
165 void Socket::setLocalPort(unsigned short localPort) throw(SocketException) {
166 // Bind the socket to its port
167 sockaddr_in localAddr;
168 memset(&localAddr, 0, sizeof(localAddr));
169 localAddr.sin_family = AF_INET;
170 localAddr.sin_addr.s_addr = htonl(INADDR_ANY);
171 localAddr.sin_port = htons(localPort);
173 if (bind(sockDesc, (sockaddr *) &localAddr, sizeof(sockaddr_in)) < 0) {
174 throw SocketException("Set of local port failed (bind())", true);
178 void Socket::setLocalAddressAndPort(const string &localAddress,
179 unsigned short localPort) throw(SocketException) {
180 // Get the address of the requested host
181 sockaddr_in localAddr;
182 fillAddr(localAddress, localPort, localAddr);
184 if (bind(sockDesc, (sockaddr *) &localAddr, sizeof(sockaddr_in)) < 0) {
185 throw SocketException("Set of local address and port failed (bind())", true);
189 void Socket::setSocketOpt(int optionName, const void* optionValue, socklen_t optionLen)
190 throw(SocketException)
192 if (::setsockopt(sockDesc, SOL_SOCKET, optionName, optionValue, optionLen) < 0) {
193 throw SocketException("setSockopt failed", true);
197 void Socket::cleanUp() throw(SocketException) {
198 #ifdef WIN32
199 if (WSACleanup() != 0) {
200 throw SocketException("WSACleanup() failed");
202 #endif
205 unsigned short Socket::resolveService(const string &service,
206 const string &protocol) {
207 struct servent *serv; /* Structure containing service information */
209 if ((serv = getservbyname(service.c_str(), protocol.c_str())) == NULL)
210 return atoi(service.c_str()); /* Service is port number */
211 else
212 return ntohs(serv->s_port); /* Found port (network byte order) by name */
215 // CommunicatingSocket Code
217 CommunicatingSocket::CommunicatingSocket(int type, int protocol)
218 throw(SocketException) : Socket(type, protocol) {
221 CommunicatingSocket::CommunicatingSocket(int newConnSD) : Socket(newConnSD) {
224 void CommunicatingSocket::connect(const string &foreignAddress,
225 unsigned short foreignPort) throw(SocketException) {
226 // Get the address of the requested host
227 sockaddr_in destAddr;
228 fillAddr(foreignAddress, foreignPort, destAddr);
230 // Try to connect to the given port
231 if (::connect(sockDesc, (sockaddr *) &destAddr, sizeof(destAddr)) < 0) {
232 throw SocketException("Connect failed (connect())", true);
236 void CommunicatingSocket::send(const void *buffer, int bufferLen)
237 throw(SocketException) {
238 if (::send(sockDesc, (raw_type *) buffer, bufferLen, 0) < 0) {
239 throw SocketException("Send failed (send())", true);
243 int CommunicatingSocket::recv(void *buffer, int bufferLen)
244 throw(SocketException) {
245 int rtn;
246 if ((rtn = ::recv(sockDesc, (raw_type *) buffer, bufferLen, 0)) < 0) {
247 throw SocketException("Received failed (recv())", true);
250 return rtn;
253 string CommunicatingSocket::getForeignAddress()
254 throw(SocketException) {
255 sockaddr_in addr;
256 unsigned int addr_len = sizeof(addr);
258 if (getpeername(sockDesc, (sockaddr *) &addr,(socklen_t *) &addr_len) < 0) {
259 throw SocketException("Fetch of foreign address failed (getpeername())", true);
261 return inet_ntoa(addr.sin_addr);
264 unsigned short CommunicatingSocket::getForeignPort() throw(SocketException) {
265 sockaddr_in addr;
266 unsigned int addr_len = sizeof(addr);
268 if (getpeername(sockDesc, (sockaddr *) &addr, (socklen_t *) &addr_len) < 0) {
269 throw SocketException("Fetch of foreign port failed (getpeername())", true);
271 return ntohs(addr.sin_port);
274 // TCPSocket Code
276 TCPSocket::TCPSocket()
277 throw(SocketException) : CommunicatingSocket(SOCK_STREAM,
278 IPPROTO_TCP) {
281 TCPSocket::TCPSocket(const string &foreignAddress, unsigned short foreignPort)
282 throw(SocketException) : CommunicatingSocket(SOCK_STREAM, IPPROTO_TCP) {
283 connect(foreignAddress, foreignPort);
286 TCPSocket::TCPSocket(int newConnSD) : CommunicatingSocket(newConnSD) {
289 // TCPServerSocket Code
291 TCPServerSocket::TCPServerSocket(unsigned short localPort, int queueLen)
292 throw(SocketException) : Socket(SOCK_STREAM, IPPROTO_TCP) {
293 const int opt = 1;
294 setSocketOpt(SO_REUSEADDR, &opt, sizeof(opt));
295 setLocalPort(localPort);
296 setListen(queueLen);
299 TCPServerSocket::TCPServerSocket(const string &localAddress,
300 unsigned short localPort, int queueLen)
301 throw(SocketException) : Socket(SOCK_STREAM, IPPROTO_TCP) {
302 const int opt = 1;
303 setSocketOpt(SO_REUSEADDR, &opt, sizeof(opt));
304 setLocalAddressAndPort(localAddress, localPort);
305 setListen(queueLen);
308 TCPSocket *TCPServerSocket::accept() throw(SocketException) {
309 int newConnSD;
310 if ((newConnSD = ::accept(sockDesc, NULL, 0)) < 0) {
311 throw SocketException("Accept failed (accept())", true);
314 return new TCPSocket(newConnSD);
317 void TCPServerSocket::setListen(int queueLen) throw(SocketException) {
318 if (listen(sockDesc, queueLen) < 0) {
319 throw SocketException("Set listening socket failed (listen())", true);
323 // UDPSocket Code
325 UDPSocket::UDPSocket() throw(SocketException) : CommunicatingSocket(SOCK_DGRAM,
326 IPPROTO_UDP) {
328 const int opt = 1;
329 setSocketOpt(SO_REUSEADDR, &opt, sizeof(opt));
330 setBroadcast();
333 UDPSocket::UDPSocket(unsigned short localPort) throw(SocketException) :
334 CommunicatingSocket(SOCK_DGRAM, IPPROTO_UDP) {
335 const int opt = 1;
336 setSocketOpt(SO_REUSEADDR, &opt, sizeof(opt));
337 setLocalPort(localPort);
338 setBroadcast();
341 UDPSocket::UDPSocket(const string &localAddress, unsigned short localPort)
342 throw(SocketException) : CommunicatingSocket(SOCK_DGRAM, IPPROTO_UDP) {
343 const int opt = 1;
344 setSocketOpt(SO_REUSEADDR, &opt, sizeof(opt));
345 setLocalAddressAndPort(localAddress, localPort);
346 setBroadcast();
349 void UDPSocket::setBroadcast() {
350 // If this fails, we'll hear about it when we try to send. This will allow
351 // system that cannot broadcast to continue if they don't plan to broadcast
352 int broadcastPermission = 1;
353 setsockopt(sockDesc, SOL_SOCKET, SO_BROADCAST,
354 (raw_type *) &broadcastPermission, sizeof(broadcastPermission));
357 void UDPSocket::disconnect() throw(SocketException) {
358 sockaddr_in nullAddr;
359 memset(&nullAddr, 0, sizeof(nullAddr));
360 nullAddr.sin_family = AF_UNSPEC;
362 // Try to disconnect
363 if (::connect(sockDesc, (sockaddr *) &nullAddr, sizeof(nullAddr)) < 0) {
364 #ifdef WIN32
365 if (errno != WSAEAFNOSUPPORT) {
366 #else
367 if (errno != EAFNOSUPPORT) {
368 #endif
369 throw SocketException("Disconnect failed (connect())", true);
374 void UDPSocket::sendTo(const void *buffer, int bufferLen,
375 const string &foreignAddress, unsigned short foreignPort)
376 throw(SocketException) {
377 sockaddr_in destAddr;
378 fillAddr(foreignAddress, foreignPort, destAddr);
380 // Write out the whole buffer as a single message.
381 if (sendto(sockDesc, (raw_type *) buffer, bufferLen, 0,
382 (sockaddr *) &destAddr, sizeof(destAddr)) != bufferLen) {
383 throw SocketException("Send failed (sendto())", true);
387 int UDPSocket::recvFrom(void *buffer, int bufferLen, string &sourceAddress,
388 unsigned short &sourcePort) throw(SocketException) {
389 sockaddr_in clntAddr;
390 socklen_t addrLen = sizeof(clntAddr);
391 int rtn;
392 if ((rtn = recvfrom(sockDesc, (raw_type *) buffer, bufferLen, 0,
393 (sockaddr *) &clntAddr, (socklen_t *) &addrLen)) < 0) {
394 throw SocketException("Receive failed (recvfrom())", true);
396 sourceAddress = inet_ntoa(clntAddr.sin_addr);
397 sourcePort = ntohs(clntAddr.sin_port);
399 return rtn;
402 void UDPSocket::setMulticastTTL(unsigned char multicastTTL) throw(SocketException) {
403 if (setsockopt(sockDesc, IPPROTO_IP, IP_MULTICAST_TTL,
404 (raw_type *) &multicastTTL, sizeof(multicastTTL)) < 0) {
405 throw SocketException("Multicast TTL set failed (setsockopt())", true);
409 void UDPSocket::joinGroup(const string &multicastGroup) throw(SocketException) {
410 struct ip_mreq multicastRequest;
412 multicastRequest.imr_multiaddr.s_addr = inet_addr(multicastGroup.c_str());
413 multicastRequest.imr_interface.s_addr = htonl(INADDR_ANY);
414 if (setsockopt(sockDesc, IPPROTO_IP, IP_ADD_MEMBERSHIP,
415 (raw_type *) &multicastRequest,
416 sizeof(multicastRequest)) < 0) {
417 throw SocketException("Multicast group join failed (setsockopt())", true);
421 void UDPSocket::leaveGroup(const string &multicastGroup) throw(SocketException) {
422 struct ip_mreq multicastRequest;
424 multicastRequest.imr_multiaddr.s_addr = inet_addr(multicastGroup.c_str());
425 multicastRequest.imr_interface.s_addr = htonl(INADDR_ANY);
426 if (setsockopt(sockDesc, IPPROTO_IP, IP_DROP_MEMBERSHIP,
427 (raw_type *) &multicastRequest,
428 sizeof(multicastRequest)) < 0) {
429 throw SocketException("Multicast group leave failed (setsockopt())", true);