blob: 93cdceb29936e79da09eaee294be5a338007b0f6 [file] [log] [blame]
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001/* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved.
2 *
3 * This is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This software is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License
14 * along with this software; if not, write to the Free Software
15 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
16 * USA.
17 */
18
Adam Tkac8aee1a82009-09-04 12:08:56 +000019#ifdef HAVE_CONFIG_H
20#include <config.h>
Adam Tkacad1cbd92008-10-06 14:08:00 +000021#endif
22
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000023#ifdef WIN32
24//#include <io.h>
25#include <winsock2.h>
26#define errorNumber WSAGetLastError()
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000027#else
28#define errorNumber errno
29#define closesocket close
30#include <sys/types.h>
31#include <sys/socket.h>
32#include <arpa/inet.h>
33#include <netinet/in.h>
34#include <netinet/tcp.h>
35#include <netdb.h>
36#include <unistd.h>
37#include <errno.h>
38#include <string.h>
39#include <signal.h>
40#include <fcntl.h>
41#endif
42
Adam Tkac04b7fd22008-03-19 16:14:48 +000043#include <stdlib.h>
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000044#include <network/TcpSocket.h>
Adam Tkacbe4c3ac2008-12-10 16:42:33 +000045#include <os/net.h>
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000046#include <rfb/util.h>
47#include <rfb/LogWriter.h>
48
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000049#ifndef INADDR_NONE
50#define INADDR_NONE ((unsigned long)-1)
51#endif
52#ifndef INADDR_LOOPBACK
53#define INADDR_LOOPBACK ((unsigned long)0x7F000001)
54#endif
55
56using namespace network;
57using namespace rdr;
58
Adam Tkac9cb6a422008-11-14 15:56:15 +000059typedef struct vnc_sockaddr {
60 union {
61 sockaddr sa;
62 sockaddr_in sin;
63#ifdef HAVE_GETADDRINFO
64 sockaddr_in6 sin6;
65#endif
66 } u;
67} vnc_sockaddr_t;
68
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000069static rfb::LogWriter vlog("TcpSocket");
70
71/* Tunnelling support. */
72int network::findFreeTcpPort (void)
73{
74 int sock, port;
75 struct sockaddr_in addr;
76 memset(&addr, 0, sizeof(addr));
77 addr.sin_family = AF_INET;
78 addr.sin_addr.s_addr = INADDR_ANY;
79
80 if ((sock = socket (AF_INET, SOCK_STREAM, 0)) < 0)
81 throw SocketException ("unable to create socket", errorNumber);
82
83 for (port = TUNNEL_PORT_OFFSET + 99; port > TUNNEL_PORT_OFFSET; port--) {
84 addr.sin_port = htons ((unsigned short) port);
85 if (bind (sock, (struct sockaddr *)&addr, sizeof (addr)) == 0) {
86 closesocket (sock);
87 return port;
88 }
89 }
90 throw SocketException ("no free port in range", 0);
91 return 0;
92}
93
94
95// -=- Socket initialisation
96static bool socketsInitialised = false;
97static void initSockets() {
98 if (socketsInitialised)
99 return;
100#ifdef WIN32
101 WORD requiredVersion = MAKEWORD(2,0);
102 WSADATA initResult;
103
104 if (WSAStartup(requiredVersion, &initResult) != 0)
105 throw SocketException("unable to initialise Winsock2", errorNumber);
106#else
107 signal(SIGPIPE, SIG_IGN);
108#endif
109 socketsInitialised = true;
110}
111
112
113// -=- TcpSocket
114
115TcpSocket::TcpSocket(int sock, bool close)
116 : Socket(new FdInStream(sock), new FdOutStream(sock), true), closeFd(close)
117{
118}
119
120TcpSocket::TcpSocket(const char *host, int port)
121 : closeFd(true)
122{
Adam Tkac9cb6a422008-11-14 15:56:15 +0000123 int sock, err, result, family;
124 vnc_sockaddr_t sa;
Adam Tkacbe4c3ac2008-12-10 16:42:33 +0000125 socklen_t salen;
Adam Tkac9cb6a422008-11-14 15:56:15 +0000126#ifdef HAVE_GETADDRINFO
127 struct addrinfo *ai, *current, hints;
128#endif
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000129
130 // - Create a socket
131 initSockets();
Adam Tkac9cb6a422008-11-14 15:56:15 +0000132
133#ifdef HAVE_GETADDRINFO
134 memset(&hints, 0, sizeof(struct addrinfo));
135 hints.ai_family = AF_UNSPEC;
136 hints.ai_socktype = SOCK_STREAM;
137 hints.ai_canonname = NULL;
138 hints.ai_addr = NULL;
139 hints.ai_next = NULL;
140
141 if ((result = getaddrinfo(host, NULL, &hints, &ai)) != 0) {
142 throw Exception("unable to resolve host by name: %s",
143 gai_strerror(result));
144 }
145
146 for (current = ai; current != NULL; current = current->ai_next) {
147 family = current->ai_family;
148 if (family != AF_INET && family != AF_INET6)
149 continue;
150
151 salen = current->ai_addrlen;
152 memcpy(&sa, current->ai_addr, salen);
153
154 if (family == AF_INET)
155 sa.u.sin.sin_port = htons(port);
156 else
157 sa.u.sin6.sin6_port = htons(port);
158
159#else /* HAVE_GETADDRINFO */
160 family = AF_INET;
161 salen = sizeof(struct sockaddr_in);
162
163 /* Try processing the host as an IP address */
164 memset(&sa, 0, sizeof(sa));
165 sa.u.sin.sin_family = AF_INET;
166 sa.u.sin.sin_addr.s_addr = inet_addr((char *)host);
167 sa.u.sin.sin_port = htons(port);
168 if ((int)sa.u.sin.sin_addr.s_addr == -1) {
169 /* Host was not an IP address - try resolving as DNS name */
170 struct hostent *hostinfo;
171 hostinfo = gethostbyname((char *)host);
172 if (hostinfo && hostinfo->h_addr) {
173 sa.u.sin.sin_addr.s_addr = ((struct in_addr *)hostinfo->h_addr)->s_addr;
174 } else {
175 err = errorNumber;
176 throw SocketException("unable to resolve host by name", err);
177 }
178 }
179#endif /* HAVE_GETADDRINFO */
180
181 sock = socket (family, SOCK_STREAM, 0);
182 if (sock == -1) {
183 err = errorNumber;
184#ifdef HAVE_GETADDRINFO
185 freeaddrinfo(ai);
186#endif /* HAVE_GETADDRINFO */
187 throw SocketException("unable to create socket", err);
188 }
189
190 /* Attempt to connect to the remote host */
Adam Tkacc9cda3b2009-10-30 11:13:34 +0000191 while ((result = connect(sock, &sa.u.sa, salen)) == -1) {
Adam Tkac9cb6a422008-11-14 15:56:15 +0000192 err = errorNumber;
193#ifndef WIN32
194 if (err == EINTR)
195 continue;
196#endif
197 closesocket(sock);
198 break;
199 }
200
201#ifdef HAVE_GETADDRINFO
202 if (result == 0)
203 break;
Adam Tkac9cb6a422008-11-14 15:56:15 +0000204 }
205
206 freeaddrinfo(ai);
207#endif /* HAVE_GETADDRINFO */
208
209 if (result == -1)
210 throw SocketException("unable connect to socket", err);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000211
212#ifndef WIN32
213 // - By default, close the socket on exec()
214 fcntl(sock, F_SETFD, FD_CLOEXEC);
215#endif
216
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000217 // Disable Nagle's algorithm, to reduce latency
218 enableNagles(sock, false);
219
220 // Create the input and output streams
221 instream = new FdInStream(sock);
222 outstream = new FdOutStream(sock);
223 ownStreams = true;
224}
225
226TcpSocket::~TcpSocket() {
227 if (closeFd)
228 closesocket(getFd());
229}
230
231char* TcpSocket::getMyAddress() {
232 struct sockaddr_in info;
233 struct in_addr addr;
Adam Tkacbe4c3ac2008-12-10 16:42:33 +0000234 socklen_t info_size = sizeof(info);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000235
236 getsockname(getFd(), (struct sockaddr *)&info, &info_size);
237 memcpy(&addr, &info.sin_addr, sizeof(addr));
238
239 char* name = inet_ntoa(addr);
240 if (name) {
Adam Tkacd36b6262009-09-04 10:57:20 +0000241 return rfb::strDup(name);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000242 } else {
Adam Tkacd36b6262009-09-04 10:57:20 +0000243 return rfb::strDup("");
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000244 }
245}
246
247int TcpSocket::getMyPort() {
248 return getSockPort(getFd());
249}
250
251char* TcpSocket::getMyEndpoint() {
252 rfb::CharArray address; address.buf = getMyAddress();
253 int port = getMyPort();
254
255 int buflen = strlen(address.buf) + 32;
256 char* buffer = new char[buflen];
257 sprintf(buffer, "%s::%d", address.buf, port);
258 return buffer;
259}
260
261char* TcpSocket::getPeerAddress() {
262 struct sockaddr_in info;
263 struct in_addr addr;
Adam Tkacbe4c3ac2008-12-10 16:42:33 +0000264 socklen_t info_size = sizeof(info);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000265
266 getpeername(getFd(), (struct sockaddr *)&info, &info_size);
267 memcpy(&addr, &info.sin_addr, sizeof(addr));
268
269 char* name = inet_ntoa(addr);
270 if (name) {
Adam Tkacd36b6262009-09-04 10:57:20 +0000271 return rfb::strDup(name);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000272 } else {
Adam Tkacd36b6262009-09-04 10:57:20 +0000273 return rfb::strDup("");
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000274 }
275}
276
277int TcpSocket::getPeerPort() {
278 struct sockaddr_in info;
Adam Tkacbe4c3ac2008-12-10 16:42:33 +0000279 socklen_t info_size = sizeof(info);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000280
281 getpeername(getFd(), (struct sockaddr *)&info, &info_size);
282 return ntohs(info.sin_port);
283}
284
285char* TcpSocket::getPeerEndpoint() {
286 rfb::CharArray address; address.buf = getPeerAddress();
287 int port = getPeerPort();
288
289 int buflen = strlen(address.buf) + 32;
290 char* buffer = new char[buflen];
291 sprintf(buffer, "%s::%d", address.buf, port);
292 return buffer;
293}
294
295bool TcpSocket::sameMachine() {
Adam Tkac897814f2009-11-12 10:32:43 +0000296 vnc_sockaddr_t peeraddr, myaddr;
297 socklen_t addrlen;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000298
Adam Tkac897814f2009-11-12 10:32:43 +0000299 addrlen = sizeof(peeraddr);
300 if (getpeername(getFd(), &peeraddr.u.sa, &addrlen) < 0)
301 throw SocketException ("unable to get peer address", errorNumber);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000302
Adam Tkac897814f2009-11-12 10:32:43 +0000303 addrlen = sizeof(myaddr); /* need to reset, since getpeername overwrote */
304 if (getsockname(getFd(), &myaddr.u.sa, &addrlen) < 0)
305 throw SocketException ("unable to get my address", errorNumber);
306
307 if (peeraddr.u.sa.sa_family != myaddr.u.sa.sa_family)
308 return false;
309
310#ifdef HAVE_GETADDRINFO
311 if (peeraddr.u.sa.sa_family == AF_INET6)
312 return IN6_ARE_ADDR_EQUAL(&peeraddr.u.sin6.sin6_addr,
313 &myaddr.u.sin6.sin6_addr);
314#endif
315
316 return (peeraddr.u.sin.sin_addr.s_addr == myaddr.u.sin.sin_addr.s_addr);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000317}
318
319void TcpSocket::shutdown()
320{
321 Socket::shutdown();
322 ::shutdown(getFd(), 2);
323}
324
325bool TcpSocket::enableNagles(int sock, bool enable) {
326 int one = enable ? 0 : 1;
327 if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
328 (char *)&one, sizeof(one)) < 0) {
329 int e = errorNumber;
330 vlog.error("unable to setsockopt TCP_NODELAY: %d", e);
331 return false;
332 }
333 return true;
334}
335
336bool TcpSocket::isSocket(int sock)
337{
338 struct sockaddr_in info;
Adam Tkacbe4c3ac2008-12-10 16:42:33 +0000339 socklen_t info_size = sizeof(info);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000340 return getsockname(sock, (struct sockaddr *)&info, &info_size) >= 0;
341}
342
343bool TcpSocket::isConnected(int sock)
344{
345 struct sockaddr_in info;
Adam Tkacbe4c3ac2008-12-10 16:42:33 +0000346 socklen_t info_size = sizeof(info);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000347 return getpeername(sock, (struct sockaddr *)&info, &info_size) >= 0;
348}
349
350int TcpSocket::getSockPort(int sock)
351{
352 struct sockaddr_in info;
Adam Tkacbe4c3ac2008-12-10 16:42:33 +0000353 socklen_t info_size = sizeof(info);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000354 if (getsockname(sock, (struct sockaddr *)&info, &info_size) < 0)
355 return 0;
356 return ntohs(info.sin_port);
357}
358
359
360TcpListener::TcpListener(int port, bool localhostOnly, int sock, bool close_)
361 : closeFd(close_)
362{
363 if (sock != -1) {
364 fd = sock;
365 return;
366 }
367
368 initSockets();
369 if ((fd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
370 throw SocketException("unable to create listening socket", errorNumber);
371
372#ifndef WIN32
373 // - By default, close the socket on exec()
374 fcntl(fd, F_SETFD, FD_CLOEXEC);
375
376 int one = 1;
377 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
378 (char *)&one, sizeof(one)) < 0) {
379 int e = errorNumber;
380 closesocket(fd);
381 throw SocketException("unable to create listening socket", e);
382 }
383#endif
384
385 // - Bind it to the desired port
386 struct sockaddr_in addr;
387 memset(&addr, 0, sizeof(addr));
388 addr.sin_family = AF_INET;
389 addr.sin_port = htons(port);
390 if (localhostOnly)
391 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
392 else
393 addr.sin_addr.s_addr = htonl(INADDR_ANY);
394 if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
395 int e = errorNumber;
396 closesocket(fd);
397 throw SocketException("unable to bind listening socket", e);
398 }
399
400 // - Set it to be a listening socket
401 if (listen(fd, 5) < 0) {
402 int e = errorNumber;
403 closesocket(fd);
404 throw SocketException("unable to set socket to listening mode", e);
405 }
406}
407
408TcpListener::~TcpListener() {
409 if (closeFd) closesocket(fd);
410}
411
412void TcpListener::shutdown()
413{
414#ifdef WIN32
415 closesocket(getFd());
416#else
417 ::shutdown(getFd(), 2);
418#endif
419}
420
421
422Socket*
423TcpListener::accept() {
424 int new_sock = -1;
425
426 // Accept an incoming connection
427 if ((new_sock = ::accept(fd, 0, 0)) < 0)
428 throw SocketException("unable to accept new connection", errorNumber);
429
430#ifndef WIN32
431 // - By default, close the socket on exec()
432 fcntl(new_sock, F_SETFD, FD_CLOEXEC);
433#endif
434
435 // Disable Nagle's algorithm, to reduce latency
436 TcpSocket::enableNagles(new_sock, false);
437
438 // Create the socket object & check connection is allowed
439 TcpSocket* s = new TcpSocket(new_sock);
440 if (filter && !filter->verifyConnection(s)) {
441 delete s;
442 return 0;
443 }
444 return s;
445}
446
447void TcpListener::getMyAddresses(std::list<char*>* result) {
448 const hostent* addrs = gethostbyname(0);
449 if (addrs == 0)
450 throw rdr::SystemException("gethostbyname", errorNumber);
451 if (addrs->h_addrtype != AF_INET)
452 throw rdr::Exception("getMyAddresses: bad family");
453 for (int i=0; addrs->h_addr_list[i] != 0; i++) {
454 const char* addrC = inet_ntoa(*((struct in_addr*)addrs->h_addr_list[i]));
455 char* addr = new char[strlen(addrC)+1];
456 strcpy(addr, addrC);
457 result->push_back(addr);
458 }
459}
460
461int TcpListener::getMyPort() {
462 return TcpSocket::getSockPort(getFd());
463}
464
465
466TcpFilter::TcpFilter(const char* spec) {
467 rfb::CharArray tmp;
Adam Tkacd36b6262009-09-04 10:57:20 +0000468 tmp.buf = rfb::strDup(spec);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000469 while (tmp.buf) {
470 rfb::CharArray first;
471 rfb::strSplit(tmp.buf, ',', &first.buf, &tmp.buf);
472 if (strlen(first.buf))
473 filter.push_back(parsePattern(first.buf));
474 }
475}
476
477TcpFilter::~TcpFilter() {
478}
479
480
481static bool
482patternMatchIP(const TcpFilter::Pattern& pattern, const char* value) {
483 unsigned long address = inet_addr((char *)value);
484 if (address == INADDR_NONE) return false;
485 return ((pattern.address & pattern.mask) == (address & pattern.mask));
486}
487
488bool
489TcpFilter::verifyConnection(Socket* s) {
490 rfb::CharArray name;
491
492 name.buf = s->getPeerAddress();
493 std::list<TcpFilter::Pattern>::iterator i;
494 for (i=filter.begin(); i!=filter.end(); i++) {
495 if (patternMatchIP(*i, name.buf)) {
496 switch ((*i).action) {
497 case Accept:
498 vlog.debug("ACCEPT %s", name.buf);
499 return true;
500 case Query:
501 vlog.debug("QUERY %s", name.buf);
502 s->setRequiresQuery();
503 return true;
504 case Reject:
505 vlog.debug("REJECT %s", name.buf);
506 return false;
507 }
508 }
509 }
510
511 vlog.debug("[REJECT] %s", name.buf);
512 return false;
513}
514
515
516TcpFilter::Pattern TcpFilter::parsePattern(const char* p) {
517 TcpFilter::Pattern pattern;
518
519 bool expandMask = false;
520 rfb::CharArray addr, mask;
521
522 if (rfb::strSplit(&p[1], '/', &addr.buf, &mask.buf)) {
523 if (rfb::strContains(mask.buf, '.')) {
524 pattern.mask = inet_addr(mask.buf);
525 } else {
526 pattern.mask = atoi(mask.buf);
527 expandMask = true;
528 }
529 } else {
530 pattern.mask = 32;
531 expandMask = true;
532 }
533 if (expandMask) {
534 unsigned long expanded = 0;
535 // *** check endianness!
536 for (int i=0; i<(int)pattern.mask; i++)
537 expanded |= 1<<(31-i);
538 pattern.mask = htonl(expanded);
539 }
540
541 pattern.address = inet_addr(addr.buf) & pattern.mask;
542 if ((pattern.address == INADDR_NONE) ||
543 (pattern.address == 0)) pattern.mask = 0;
544
545 switch(p[0]) {
546 case '+': pattern.action = TcpFilter::Accept; break;
547 case '-': pattern.action = TcpFilter::Reject; break;
548 case '?': pattern.action = TcpFilter::Query; break;
549 };
550
551 return pattern;
552}
553
554char* TcpFilter::patternToStr(const TcpFilter::Pattern& p) {
555 in_addr tmp;
556 rfb::CharArray addr, mask;
557 tmp.s_addr = p.address;
Adam Tkacd36b6262009-09-04 10:57:20 +0000558 addr.buf = rfb::strDup(inet_ntoa(tmp));
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000559 tmp.s_addr = p.mask;
Adam Tkacd36b6262009-09-04 10:57:20 +0000560 mask.buf = rfb::strDup(inet_ntoa(tmp));
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000561 char* result = new char[strlen(addr.buf)+1+strlen(mask.buf)+1+1];
562 switch (p.action) {
563 case Accept: result[0] = '+'; break;
564 case Reject: result[0] = '-'; break;
565 case Query: result[0] = '?'; break;
566 };
567 result[1] = 0;
568 strcat(result, addr.buf);
569 strcat(result, "/");
570 strcat(result, mask.buf);
571 return result;
572}