sockets.c 14.5 KB
Newer Older
dscho's avatar
dscho committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
/*
 * sockets.c - deal with TCP & UDP sockets.
 *
 * This code should be independent of any changes in the RFB protocol.  It just
 * deals with the X server scheduling stuff, calling rfbNewClientConnection and
 * rfbProcessClientMessage to actually deal with the protocol.  If a socket
 * needs to be closed for any reason then rfbCloseClient should be called, and
 * this in turn will call rfbClientConnectionGone.  To make an active
 * connection out, call rfbConnect - note that this does _not_ call
 * rfbNewClientConnection.
 *
 * This file is divided into two types of function.  Those beginning with
 * "rfb" are specific to sockets using the RFB protocol.  Those without the
 * "rfb" prefix are more general socket routines (which are used by the http
 * code).
 *
 * Thanks to Karl Hakimian for pointing out that some platforms return EAGAIN
 * not EWOULDBLOCK.
 */

/*
 *  OSXvnc Copyright (C) 2001 Dan McGuirk <mcguirk@incompleteness.net>.
 *  Original Xvnc code Copyright (C) 1999 AT&T Laboratories Cambridge.  
 *  All Rights Reserved.
 *
 *  This is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This software is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this software; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,
 *  USA.
 */

42
#include <rfb/rfb.h>
43

44
#ifdef LIBVNCSERVER_HAVE_SYS_TYPES_H
dscho's avatar
dscho committed
45
#include <sys/types.h>
46 47
#endif

48 49 50 51 52 53 54 55
#ifdef WIN32
#pragma warning (disable: 4018 4761)
#define close closesocket
#define read(sock,buf,len) recv(sock,buf,len,0)
#define EWOULDBLOCK WSAEWOULDBLOCK
#define ETIMEDOUT WSAETIMEDOUT
#define write(sock,buf,len) send(sock,buf,len,0)
#else
56
#ifdef LIBVNCSERVER_HAVE_SYS_TIME_H
dscho's avatar
dscho committed
57
#include <sys/time.h>
58
#endif
59
#ifdef LIBVNCSERVER_HAVE_SYS_SOCKET_H
60
#include <sys/socket.h>
61
#endif
62
#ifdef LIBVNCSERVER_HAVE_NETINET_IN_H
63 64 65 66 67
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <netdb.h>
#include <arpa/inet.h>
#endif
68
#ifdef LIBVNCSERVER_HAVE_UNISTD_H
69 70 71 72
#include <unistd.h>
#endif
#endif

dscho's avatar
dscho committed
73 74 75 76 77 78 79
#if defined(__linux__) && defined(NEED_TIMEVAL)
struct timeval 
{
   long int tv_sec,tv_usec;
}
;
#endif
80

81
#ifdef LIBVNCSERVER_HAVE_FCNTL_H
dscho's avatar
dscho committed
82
#include <fcntl.h>
83 84
#endif

dscho's avatar
dscho committed
85 86
#include <errno.h>

dscho's avatar
dscho committed
87 88 89 90 91 92 93
#ifdef USE_LIBWRAP
#include <syslog.h>
#include <tcpd.h>
int allow_severity=LOG_INFO;
int deny_severity=LOG_WARNING;
#endif

94
/*#ifndef WIN32
95
int max(int i,int j) { return(i<j?j:i); }
96 97
#endif
*/
98

dscho's avatar
dscho committed
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
int rfbMaxClientWait = 20000;   /* time (ms) after which we decide client has
                                   gone away - needed to stop us hanging */

/*
 * rfbInitSockets sets up the TCP and UDP sockets to listen for RFB
 * connections.  It does nothing if called again.
 */

void
rfbInitSockets(rfbScreenInfoPtr rfbScreen)
{
    if (rfbScreen->socketInitDone)
	return;

    rfbScreen->socketInitDone = TRUE;

    if (rfbScreen->inetdSock != -1) {
	const int one = 1;

118
#ifndef WIN32
dscho's avatar
dscho committed
119 120
	if (fcntl(rfbScreen->inetdSock, F_SETFL, O_NONBLOCK) < 0) {
	    rfbLogPerror("fcntl");
121
	    return;
dscho's avatar
dscho committed
122
	}
123
#endif
dscho's avatar
dscho committed
124 125 126 127

	if (setsockopt(rfbScreen->inetdSock, IPPROTO_TCP, TCP_NODELAY,
		       (char *)&one, sizeof(one)) < 0) {
	    rfbLogPerror("setsockopt");
128
	    return;
dscho's avatar
dscho committed
129 130 131 132 133 134 135 136
	}

    	FD_ZERO(&(rfbScreen->allFds));
    	FD_SET(rfbScreen->inetdSock, &(rfbScreen->allFds));
    	rfbScreen->maxFd = rfbScreen->inetdSock;
	return;
    }

137 138 139 140 141 142 143 144 145 146 147 148 149
    if(rfbScreen->autoPort) {
        int i;
        rfbLog("Autoprobing TCP port \n");

        for (i = 5900; i < 6000; i++) {
            if ((rfbScreen->rfbListenSock = ListenOnTCPPort(i)) >= 0) {
		rfbScreen->rfbPort = i;
		break;
	    }
        }

        if (i >= 6000) {
	    rfbLogPerror("Failure autoprobing");
150
	    return;
151 152 153 154 155 156 157 158
        }

        rfbLog("Autoprobing selected port %d\n", rfbScreen->rfbPort);
        FD_ZERO(&(rfbScreen->allFds));
        FD_SET(rfbScreen->rfbListenSock, &(rfbScreen->allFds));
        rfbScreen->maxFd = rfbScreen->rfbListenSock;
    }
    else if(rfbScreen->rfbPort>0) {
dscho's avatar
dscho committed
159
      rfbLog("Listening for VNC connections on TCP port %d\n", rfbScreen->rfbPort);
dscho's avatar
dscho committed
160

dscho's avatar
dscho committed
161
      if ((rfbScreen->rfbListenSock = ListenOnTCPPort(rfbScreen->rfbPort)) < 0) {
dscho's avatar
dscho committed
162
	rfbLogPerror("ListenOnTCPPort");
163
	return;
dscho's avatar
dscho committed
164
      }
dscho's avatar
dscho committed
165

dscho's avatar
dscho committed
166 167 168 169
      FD_ZERO(&(rfbScreen->allFds));
      FD_SET(rfbScreen->rfbListenSock, &(rfbScreen->allFds));
      rfbScreen->maxFd = rfbScreen->rfbListenSock;
    }
dscho's avatar
dscho committed
170 171 172 173 174 175

    if (rfbScreen->udpPort != 0) {
	rfbLog("rfbInitSockets: listening for input on UDP port %d\n",rfbScreen->udpPort);

	if ((rfbScreen->udpSock = ListenOnUDPPort(rfbScreen->udpPort)) < 0) {
	    rfbLogPerror("ListenOnUDPPort");
176
	    return;
dscho's avatar
dscho committed
177 178
	}
	FD_SET(rfbScreen->udpSock, &(rfbScreen->allFds));
179
	rfbScreen->maxFd = max((int)rfbScreen->udpSock,rfbScreen->maxFd);
dscho's avatar
dscho committed
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
    }
}


/*
 * rfbCheckFds is called from ProcessInputEvents to check for input on the RFB
 * socket(s).  If there is input to process, the appropriate function in the
 * RFB server code will be called (rfbNewClientConnection,
 * rfbProcessClientMessage, etc).
 */

void
rfbCheckFds(rfbScreenInfoPtr rfbScreen,long usec)
{
    int nfds;
    fd_set fds;
    struct timeval tv;
    struct sockaddr_in addr;
dscho's avatar
dscho committed
198
    size_t addrlen = sizeof(addr);
dscho's avatar
dscho committed
199 200 201
    char buf[6];
    const int one = 1;
    int sock;
dscho's avatar
dscho committed
202
    rfbClientIteratorPtr i;
203
    rfbClientPtr cl;
dscho's avatar
dscho committed
204 205 206 207 208 209 210 211 212

    if (!rfbScreen->inetdInitDone && rfbScreen->inetdSock != -1) {
	rfbNewClientConnection(rfbScreen,rfbScreen->inetdSock); 
	rfbScreen->inetdInitDone = TRUE;
    }

    memcpy((char *)&fds, (char *)&(rfbScreen->allFds), sizeof(fd_set));
    tv.tv_sec = 0;
    tv.tv_usec = usec;
213
    nfds = select(rfbScreen->maxFd + 1, &fds, NULL, NULL /* &fds */, &tv);
dscho's avatar
dscho committed
214 215 216 217
    if (nfds == 0) {
	return;
    }
    if (nfds < 0) {
218 219 220
#ifdef WIN32
		errno = WSAGetLastError();
#endif
dscho's avatar
dscho committed
221 222
	if (errno != EINTR)
		rfbLogPerror("rfbCheckFds: select");
dscho's avatar
dscho committed
223 224 225 226 227 228 229 230 231 232 233
	return;
    }

    if (rfbScreen->rfbListenSock != -1 && FD_ISSET(rfbScreen->rfbListenSock, &fds)) {

	if ((sock = accept(rfbScreen->rfbListenSock,
			   (struct sockaddr *)&addr, &addrlen)) < 0) {
	    rfbLogPerror("rfbCheckFds: accept");
	    return;
	}

234
#ifndef WIN32
dscho's avatar
dscho committed
235 236 237 238 239
	if (fcntl(sock, F_SETFL, O_NONBLOCK) < 0) {
	    rfbLogPerror("rfbCheckFds: fcntl");
	    close(sock);
	    return;
	}
240
#endif
dscho's avatar
dscho committed
241 242 243 244 245 246 247 248

	if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
		       (char *)&one, sizeof(one)) < 0) {
	    rfbLogPerror("rfbCheckFds: setsockopt");
	    close(sock);
	    return;
	}

dscho's avatar
dscho committed
249 250 251 252 253 254 255 256 257 258
#ifdef USE_LIBWRAP
	if(!hosts_ctl("vnc",STRING_UNKNOWN,inet_ntoa(addr.sin_addr),
		      STRING_UNKNOWN)) {
	  rfbLog("Rejected connection from client %s\n",
		 inet_ntoa(addr.sin_addr));
	  close(sock);
	  return;
	}
#endif

dscho's avatar
dscho committed
259 260 261
	rfbLog("Got connection from client %s\n", inet_ntoa(addr.sin_addr));

	rfbNewClient(rfbScreen,sock);
262
	
dscho's avatar
dscho committed
263 264 265 266 267 268
	FD_CLR(rfbScreen->rfbListenSock, &fds);
	if (--nfds == 0)
	    return;
    }

    if ((rfbScreen->udpSock != -1) && FD_ISSET(rfbScreen->udpSock, &fds)) {
269 270
        if(!rfbScreen->udpClient)
	    rfbNewUDPClient(rfbScreen);
dscho's avatar
dscho committed
271 272 273 274
	if (recvfrom(rfbScreen->udpSock, buf, 1, MSG_PEEK,
		     (struct sockaddr *)&addr, &addrlen) < 0) {
	    rfbLogPerror("rfbCheckFds: UDP: recvfrom");
	    rfbDisconnectUDPSock(rfbScreen);
275
	    rfbScreen->udpSockConnected = FALSE;
dscho's avatar
dscho committed
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
	} else {
	    if (!rfbScreen->udpSockConnected ||
		(memcmp(&addr, &rfbScreen->udpRemoteAddr, addrlen) != 0))
	    {
		/* new remote end */
		rfbLog("rfbCheckFds: UDP: got connection\n");

		memcpy(&rfbScreen->udpRemoteAddr, &addr, addrlen);
		rfbScreen->udpSockConnected = TRUE;

		if (connect(rfbScreen->udpSock,
			    (struct sockaddr *)&addr, addrlen) < 0) {
		    rfbLogPerror("rfbCheckFds: UDP: connect");
		    rfbDisconnectUDPSock(rfbScreen);
		    return;
		}

		rfbNewUDPConnection(rfbScreen,rfbScreen->udpSock);
	    }

296
	    rfbProcessUDPInput(rfbScreen);
dscho's avatar
dscho committed
297 298 299 300 301 302 303
	}

	FD_CLR(rfbScreen->udpSock, &fds);
	if (--nfds == 0)
	    return;
    }

dscho's avatar
dscho committed
304
    i = rfbGetClientIterator(rfbScreen);
305
    while((cl = rfbClientIteratorNext(i))) {
306 307
      if (cl->onHold)
	continue;
dscho's avatar
dscho committed
308 309
      if (FD_ISSET(cl->sock, &fds) && FD_ISSET(cl->sock, &(rfbScreen->allFds)))
	rfbProcessClientMessage(cl);
dscho's avatar
dscho committed
310
    }
311
    rfbReleaseClientIterator(i);
dscho's avatar
dscho committed
312 313 314 315 316 317
}


void
rfbDisconnectUDPSock(rfbScreenInfoPtr rfbScreen)
{
318
  rfbScreen->udpSockConnected = FALSE;
dscho's avatar
dscho committed
319 320 321 322 323 324 325 326
}



void
rfbCloseClient(cl)
     rfbClientPtr cl;
{
327
    LOCK(cl->updateMutex);
328
#ifdef LIBVNCSERVER_HAVE_LIBPTHREAD
dscho's avatar
dscho committed
329 330 331 332 333
    if (cl->sock != -1)
#endif
      {
	FD_CLR(cl->sock,&(cl->screen->allFds));
	if(cl->sock==cl->screen->maxFd)
334 335
	  while(cl->screen->maxFd>0
		&& !FD_ISSET(cl->screen->maxFd,&(cl->screen->allFds)))
dscho's avatar
dscho committed
336 337 338 339 340
	    cl->screen->maxFd--;
	shutdown(cl->sock,SHUT_RDWR);
	close(cl->sock);
	cl->sock = -1;
      }
341
    TSIGNAL(cl->updateCond);
342
    UNLOCK(cl->updateMutex);
dscho's avatar
dscho committed
343 344 345
}


dscho's avatar
dscho committed
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
/*
 * rfbConnect is called to make a connection out to a given TCP address.
 */

int
rfbConnect(rfbScreen, host, port)
    rfbScreenInfoPtr rfbScreen;
    char *host;
    int port;
{
    int sock;
    int one = 1;

    rfbLog("Making connection to client on host %s port %d\n",
	   host,port);

    if ((sock = ConnectToTcpAddr(host, port)) < 0) {
	rfbLogPerror("connection failed");
	return -1;
    }

367
#ifndef WIN32
dscho's avatar
dscho committed
368 369 370 371 372
    if (fcntl(sock, F_SETFL, O_NONBLOCK) < 0) {
	rfbLogPerror("fcntl failed");
	close(sock);
	return -1;
    }
373
#endif
dscho's avatar
dscho committed
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388

    if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
		   (char *)&one, sizeof(one)) < 0) {
	rfbLogPerror("setsockopt failed");
	close(sock);
	return -1;
    }

    /* AddEnabledDevice(sock); */
    FD_SET(sock, &rfbScreen->allFds);
    rfbScreen->maxFd = max(sock,rfbScreen->maxFd);

    return sock;
}

dscho's avatar
dscho committed
389 390 391 392 393 394 395
/*
 * ReadExact reads an exact number of bytes from a client.  Returns 1 if
 * those bytes have been read, 0 if the other end has closed, or -1 if an error
 * occurred (errno is set to ETIMEDOUT if it timed out).
 */

int
dscho's avatar
dscho committed
396
ReadExactTimeout(rfbClientPtr cl, char* buf, int len, int timeout)
dscho's avatar
dscho committed
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
{
    int sock = cl->sock;
    int n;
    fd_set fds;
    struct timeval tv;

    while (len > 0) {
        n = read(sock, buf, len);

        if (n > 0) {

            buf += n;
            len -= n;

        } else if (n == 0) {

            return 0;

        } else {
416 417 418
#ifdef WIN32
			errno = WSAGetLastError();
#endif
419 420 421
	    if (errno == EINTR)
		continue;

dscho's avatar
dscho committed
422 423 424 425 426 427
            if (errno != EWOULDBLOCK && errno != EAGAIN) {
                return n;
            }

            FD_ZERO(&fds);
            FD_SET(sock, &fds);
dscho's avatar
dscho committed
428 429
            tv.tv_sec = timeout / 1000;
            tv.tv_usec = (timeout % 1000) * 1000;
430
            n = select(sock+1, &fds, NULL, &fds, &tv);
dscho's avatar
dscho committed
431 432 433 434 435 436 437 438 439 440 441 442 443
            if (n < 0) {
                rfbLogPerror("ReadExact: select");
                return n;
            }
            if (n == 0) {
                errno = ETIMEDOUT;
                return -1;
            }
        }
    }
    return 1;
}

dscho's avatar
dscho committed
444 445 446 447
int ReadExact(rfbClientPtr cl,char* buf,int len)
{
  return(ReadExactTimeout(cl,buf,len,rfbMaxClientWait));
}
dscho's avatar
dscho committed
448 449 450 451 452 453 454 455 456 457

/*
 * WriteExact writes an exact number of bytes to a client.  Returns 1 if
 * those bytes have been written, or -1 if an error occurred (errno is set to
 * ETIMEDOUT if it timed out).
 */

int
WriteExact(cl, buf, len)
     rfbClientPtr cl;
dscho's avatar
dscho committed
458
     const char *buf;
dscho's avatar
dscho committed
459 460 461 462 463 464 465 466
     int len;
{
    int sock = cl->sock;
    int n;
    fd_set fds;
    struct timeval tv;
    int totalTimeWaited = 0;

467
    LOCK(cl->outputMutex);
dscho's avatar
dscho committed
468 469 470 471 472 473 474 475 476 477
    while (len > 0) {
        n = write(sock, buf, len);

        if (n > 0) {

            buf += n;
            len -= n;

        } else if (n == 0) {

dscho's avatar
dscho committed
478
            rfbErr("WriteExact: write returned 0?\n");
479
            return 0;
dscho's avatar
dscho committed
480 481

        } else {
482 483 484
#ifdef WIN32
			errno = WSAGetLastError();
#endif
485 486 487
	    if (errno == EINTR)
		continue;

dscho's avatar
dscho committed
488
            if (errno != EWOULDBLOCK && errno != EAGAIN) {
489
	        UNLOCK(cl->outputMutex);
dscho's avatar
dscho committed
490 491 492 493 494 495 496 497 498 499 500
                return n;
            }

            /* Retry every 5 seconds until we exceed rfbMaxClientWait.  We
               need to do this because select doesn't necessarily return
               immediately when the other end has gone away */

            FD_ZERO(&fds);
            FD_SET(sock, &fds);
            tv.tv_sec = 5;
            tv.tv_usec = 0;
501
            n = select(sock+1, NULL, &fds, NULL /* &fds */, &tv);
dscho's avatar
dscho committed
502 503
            if (n < 0) {
                rfbLogPerror("WriteExact: select");
504
                UNLOCK(cl->outputMutex);
dscho's avatar
dscho committed
505 506 507 508 509 510
                return n;
            }
            if (n == 0) {
                totalTimeWaited += 5000;
                if (totalTimeWaited >= rfbMaxClientWait) {
                    errno = ETIMEDOUT;
511
                    UNLOCK(cl->outputMutex);
dscho's avatar
dscho committed
512 513 514 515 516 517 518
                    return -1;
                }
            } else {
                totalTimeWaited = 0;
            }
        }
    }
519
    UNLOCK(cl->outputMutex);
dscho's avatar
dscho committed
520 521 522 523 524 525 526 527 528 529 530
    return 1;
}

int
ListenOnTCPPort(port)
    int port;
{
    struct sockaddr_in addr;
    int sock;
    int one = 1;

dscho's avatar
dscho committed
531
    memset(&addr, 0, sizeof(addr));
dscho's avatar
dscho committed
532 533
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
dscho's avatar
dscho committed
534
    /* addr.sin_addr.s_addr = interface.s_addr; */
dscho's avatar
dscho committed
535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556
    addr.sin_addr.s_addr = INADDR_ANY;

    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
	return -1;
    }
    if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
		   (char *)&one, sizeof(one)) < 0) {
	close(sock);
	return -1;
    }
    if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
	close(sock);
	return -1;
    }
    if (listen(sock, 5) < 0) {
	close(sock);
	return -1;
    }

    return sock;
}

dscho's avatar
dscho committed
557 558 559 560 561 562 563 564 565
int
ConnectToTcpAddr(host, port)
    char *host;
    int port;
{
    struct hostent *hp;
    int sock;
    struct sockaddr_in addr;

dscho's avatar
dscho committed
566
    memset(&addr, 0, sizeof(addr));
dscho's avatar
dscho committed
567 568 569
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);

dscho's avatar
dscho committed
570
    if ((addr.sin_addr.s_addr = inet_addr(host)) == INADDR_NONE)
dscho's avatar
dscho committed
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
    {
	if (!(hp = gethostbyname(host))) {
	    errno = EINVAL;
	    return -1;
	}
	addr.sin_addr.s_addr = *(unsigned long *)hp->h_addr;
    }

    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
	return -1;
    }

    if (connect(sock, (struct sockaddr *)&addr, (sizeof(addr))) < 0) {
	close(sock);
	return -1;
    }

    return sock;
}

dscho's avatar
dscho committed
591 592 593 594 595 596 597 598
int
ListenOnUDPPort(port)
    int port;
{
    struct sockaddr_in addr;
    int sock;
    int one = 1;

dscho's avatar
dscho committed
599
    memset(&addr, 0, sizeof(addr));
dscho's avatar
dscho committed
600 601
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
dscho's avatar
dscho committed
602
    /* addr.sin_addr.s_addr = interface.s_addr; */
dscho's avatar
dscho committed
603 604 605 606 607 608 609 610 611 612 613 614 615 616 617
    addr.sin_addr.s_addr = INADDR_ANY;

    if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
	return -1;
    }
    if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
		   (char *)&one, sizeof(one)) < 0) {
	return -1;
    }
    if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
	return -1;
    }

    return sock;
}