Home | History | Annotate | Download | only in libvncserver
      1 /*
      2  * sockets.c - deal with TCP & UDP sockets.
      3  *
      4  * This code should be independent of any changes in the RFB protocol.  It just
      5  * deals with the X server scheduling stuff, calling rfbNewClientConnection and
      6  * rfbProcessClientMessage to actually deal with the protocol.  If a socket
      7  * needs to be closed for any reason then rfbCloseClient should be called. In turn,
      8  * rfbClientConnectionGone will be called by rfbProcessEvents (non-threaded case)
      9  * or clientInput (threaded case) in main.c.  To make an active
     10  * connection out, call rfbConnect - note that this does _not_ call
     11  * rfbNewClientConnection.
     12  *
     13  * This file is divided into two types of function.  Those beginning with
     14  * "rfb" are specific to sockets using the RFB protocol.  Those without the
     15  * "rfb" prefix are more general socket routines (which are used by the http
     16  * code).
     17  *
     18  * Thanks to Karl Hakimian for pointing out that some platforms return EAGAIN
     19  * not EWOULDBLOCK.
     20  */
     21 
     22 /*
     23  *  Copyright (C) 2011-2012 Christian Beier <dontmind (at) freeshell.org>
     24  *  Copyright (C) 2005 Rohit Kumar, Johannes E. Schindelin
     25  *  OSXvnc Copyright (C) 2001 Dan McGuirk <mcguirk (at) incompleteness.net>.
     26  *  Original Xvnc code Copyright (C) 1999 AT&T Laboratories Cambridge.
     27  *  All Rights Reserved.
     28  *
     29  *  This is free software; you can redistribute it and/or modify
     30  *  it under the terms of the GNU General Public License as published by
     31  *  the Free Software Foundation; either version 2 of the License, or
     32  *  (at your option) any later version.
     33  *
     34  *  This software is distributed in the hope that it will be useful,
     35  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
     36  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     37  *  GNU General Public License for more details.
     38  *
     39  *  You should have received a copy of the GNU General Public License
     40  *  along with this software; if not, write to the Free Software
     41  *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,
     42  *  USA.
     43  */
     44 
     45 #ifdef __STRICT_ANSI__
     46 #define _BSD_SOURCE
     47 #ifdef __linux__
     48 /* Setting this on other systems hides definitions such as INADDR_LOOPBACK.
     49  * The check should be for __GLIBC__ in fact. */
     50 # define _POSIX_SOURCE
     51 #endif
     52 #endif
     53 
     54 #include <rfb/rfb.h>
     55 
     56 #ifdef LIBVNCSERVER_HAVE_SYS_TYPES_H
     57 #include <sys/types.h>
     58 #endif
     59 
     60 #ifdef LIBVNCSERVER_HAVE_SYS_TIME_H
     61 #include <sys/time.h>
     62 #endif
     63 #ifdef LIBVNCSERVER_HAVE_SYS_SOCKET_H
     64 #include <sys/socket.h>
     65 #endif
     66 #ifdef LIBVNCSERVER_HAVE_NETINET_IN_H
     67 #include <netinet/in.h>
     68 #include <netinet/tcp.h>
     69 #include <netdb.h>
     70 #include <arpa/inet.h>
     71 #endif
     72 #ifdef LIBVNCSERVER_HAVE_UNISTD_H
     73 #include <unistd.h>
     74 #endif
     75 
     76 #ifdef LIBVNCSERVER_WITH_WEBSOCKETS
     77 #include "rfbssl.h"
     78 #endif
     79 
     80 #if defined(__linux__) && defined(NEED_TIMEVAL)
     81 struct timeval
     82 {
     83    long int tv_sec,tv_usec;
     84 }
     85 ;
     86 #endif
     87 
     88 #ifdef LIBVNCSERVER_HAVE_FCNTL_H
     89 #include <fcntl.h>
     90 #endif
     91 
     92 #include <errno.h>
     93 
     94 #ifdef USE_LIBWRAP
     95 #include <syslog.h>
     96 #include <tcpd.h>
     97 int allow_severity=LOG_INFO;
     98 int deny_severity=LOG_WARNING;
     99 #endif
    100 
    101 #if defined(WIN32)
    102 #include <winsock2.h>
    103 #include <ws2tcpip.h>
    104 #ifndef __MINGW32__
    105 #pragma warning (disable: 4018 4761)
    106 #endif
    107 #define read(sock,buf,len) recv(sock,buf,len,0)
    108 #define EWOULDBLOCK WSAEWOULDBLOCK
    109 #define ETIMEDOUT WSAETIMEDOUT
    110 #define write(sock,buf,len) send(sock,buf,len,0)
    111 #else
    112 #define closesocket close
    113 #endif
    114 
    115 #ifdef _MSC_VER
    116 #define SHUT_RD   0x00
    117 #define SHUT_WR   0x01
    118 #define SHUT_RDWR 0x02
    119 #define snprintf _snprintf /* Missing in MSVC */
    120 #endif
    121 
    122 int rfbMaxClientWait = 20000;   /* time (ms) after which we decide client has
    123                                    gone away - needed to stop us hanging */
    124 
    125 /*
    126  * rfbInitSockets sets up the TCP and UDP sockets to listen for RFB
    127  * connections.  It does nothing if called again.
    128  */
    129 
    130 void
    131 rfbInitSockets(rfbScreenInfoPtr rfbScreen)
    132 {
    133     in_addr_t iface = rfbScreen->listenInterface;
    134 
    135     if (rfbScreen->socketState == RFB_SOCKET_READY) {
    136         return;
    137     }
    138 
    139     rfbScreen->socketState = RFB_SOCKET_READY;
    140 
    141     if (rfbScreen->inetdSock != -1) {
    142 	const int one = 1;
    143 
    144         if(!rfbSetNonBlocking(rfbScreen->inetdSock))
    145 	    return;
    146 
    147 	if (setsockopt(rfbScreen->inetdSock, IPPROTO_TCP, TCP_NODELAY,
    148 		       (char *)&one, sizeof(one)) < 0) {
    149 	    rfbLogPerror("setsockopt");
    150 	    return;
    151 	}
    152 
    153     	FD_ZERO(&(rfbScreen->allFds));
    154     	FD_SET(rfbScreen->inetdSock, &(rfbScreen->allFds));
    155     	rfbScreen->maxFd = rfbScreen->inetdSock;
    156 	return;
    157     }
    158 
    159     if(rfbScreen->autoPort) {
    160         int i;
    161         FD_ZERO(&(rfbScreen->allFds));
    162 
    163         rfbLog("Autoprobing TCP port \n");
    164         for (i = 5900; i < 6000; i++) {
    165             if ((rfbScreen->listenSock = rfbListenOnTCPPort(i, iface)) >= 0) {
    166 		rfbScreen->port = i;
    167 		break;
    168 	    }
    169         }
    170 
    171         if (i >= 6000) {
    172 	    rfbLogPerror("Failure autoprobing");
    173 	    return;
    174         }
    175 
    176         rfbLog("Autoprobing selected TCP port %d\n", rfbScreen->port);
    177         FD_SET(rfbScreen->listenSock, &(rfbScreen->allFds));
    178         rfbScreen->maxFd = rfbScreen->listenSock;
    179 
    180 #ifdef LIBVNCSERVER_IPv6
    181         rfbLog("Autoprobing TCP6 port \n");
    182 	for (i = 5900; i < 6000; i++) {
    183             if ((rfbScreen->listen6Sock = rfbListenOnTCP6Port(i, rfbScreen->listen6Interface)) >= 0) {
    184 		rfbScreen->ipv6port = i;
    185 		break;
    186 	    }
    187         }
    188 
    189         if (i >= 6000) {
    190 	    rfbLogPerror("Failure autoprobing");
    191 	    return;
    192         }
    193 
    194         rfbLog("Autoprobing selected TCP6 port %d\n", rfbScreen->ipv6port);
    195 	FD_SET(rfbScreen->listen6Sock, &(rfbScreen->allFds));
    196 	rfbScreen->maxFd = max((int)rfbScreen->listen6Sock,rfbScreen->maxFd);
    197 #endif
    198     }
    199     else
    200     {
    201 	    if(rfbScreen->port>0) {
    202       FD_ZERO(&(rfbScreen->allFds));
    203 
    204       if ((rfbScreen->listenSock = rfbListenOnTCPPort(rfbScreen->port, iface)) < 0) {
    205 	rfbLogPerror("ListenOnTCPPort");
    206 	return;
    207       }
    208       rfbLog("Listening for VNC connections on TCP port %d\n", rfbScreen->port);
    209 
    210       FD_SET(rfbScreen->listenSock, &(rfbScreen->allFds));
    211       rfbScreen->maxFd = rfbScreen->listenSock;
    212 	    }
    213 
    214 #ifdef LIBVNCSERVER_IPv6
    215 	    if (rfbScreen->ipv6port>0) {
    216       if ((rfbScreen->listen6Sock = rfbListenOnTCP6Port(rfbScreen->ipv6port, rfbScreen->listen6Interface)) < 0) {
    217 	/* ListenOnTCP6Port has its own detailed error printout */
    218 	return;
    219       }
    220       rfbLog("Listening for VNC connections on TCP6 port %d\n", rfbScreen->ipv6port);
    221 
    222       FD_SET(rfbScreen->listen6Sock, &(rfbScreen->allFds));
    223       rfbScreen->maxFd = max((int)rfbScreen->listen6Sock,rfbScreen->maxFd);
    224 	    }
    225 #endif
    226 
    227     }
    228 
    229     if (rfbScreen->udpPort != 0) {
    230 	rfbLog("rfbInitSockets: listening for input on UDP port %d\n",rfbScreen->udpPort);
    231 
    232 	if ((rfbScreen->udpSock = rfbListenOnUDPPort(rfbScreen->udpPort, iface)) < 0) {
    233 	    rfbLogPerror("ListenOnUDPPort");
    234 	    return;
    235 	}
    236 	rfbLog("Listening for VNC connections on TCP port %d\n", rfbScreen->port);
    237 
    238 	FD_SET(rfbScreen->udpSock, &(rfbScreen->allFds));
    239 	rfbScreen->maxFd = max((int)rfbScreen->udpSock,rfbScreen->maxFd);
    240     }
    241 }
    242 
    243 void rfbShutdownSockets(rfbScreenInfoPtr rfbScreen)
    244 {
    245     if (rfbScreen->socketState!=RFB_SOCKET_READY)
    246 	return;
    247 
    248     rfbScreen->socketState = RFB_SOCKET_SHUTDOWN;
    249 
    250     if(rfbScreen->inetdSock>-1) {
    251 	closesocket(rfbScreen->inetdSock);
    252 	FD_CLR(rfbScreen->inetdSock,&rfbScreen->allFds);
    253 	rfbScreen->inetdSock=-1;
    254     }
    255 
    256     if(rfbScreen->listenSock>-1) {
    257 	closesocket(rfbScreen->listenSock);
    258 	FD_CLR(rfbScreen->listenSock,&rfbScreen->allFds);
    259 	rfbScreen->listenSock=-1;
    260     }
    261 
    262     if(rfbScreen->listen6Sock>-1) {
    263 	closesocket(rfbScreen->listen6Sock);
    264 	FD_CLR(rfbScreen->listen6Sock,&rfbScreen->allFds);
    265 	rfbScreen->listen6Sock=-1;
    266     }
    267 
    268     if(rfbScreen->udpSock>-1) {
    269 	closesocket(rfbScreen->udpSock);
    270 	FD_CLR(rfbScreen->udpSock,&rfbScreen->allFds);
    271 	rfbScreen->udpSock=-1;
    272     }
    273 }
    274 
    275 /*
    276  * rfbCheckFds is called from ProcessInputEvents to check for input on the RFB
    277  * socket(s).  If there is input to process, the appropriate function in the
    278  * RFB server code will be called (rfbNewClientConnection,
    279  * rfbProcessClientMessage, etc).
    280  */
    281 
    282 int
    283 rfbCheckFds(rfbScreenInfoPtr rfbScreen,long usec)
    284 {
    285     int nfds;
    286     fd_set fds;
    287     struct timeval tv;
    288     struct sockaddr_in addr;
    289     socklen_t addrlen = sizeof(addr);
    290     char buf[6];
    291     rfbClientIteratorPtr i;
    292     rfbClientPtr cl;
    293     int result = 0;
    294 
    295     if (!rfbScreen->inetdInitDone && rfbScreen->inetdSock != -1) {
    296 	rfbNewClientConnection(rfbScreen,rfbScreen->inetdSock);
    297 	rfbScreen->inetdInitDone = TRUE;
    298     }
    299 
    300     do {
    301 	memcpy((char *)&fds, (char *)&(rfbScreen->allFds), sizeof(fd_set));
    302 	tv.tv_sec = 0;
    303 	tv.tv_usec = usec;
    304 	nfds = select(rfbScreen->maxFd + 1, &fds, NULL, NULL /* &fds */, &tv);
    305 	if (nfds == 0) {
    306 	    /* timed out, check for async events */
    307             i = rfbGetClientIterator(rfbScreen);
    308             while((cl = rfbClientIteratorNext(i))) {
    309                 if (cl->onHold)
    310                     continue;
    311                 if (FD_ISSET(cl->sock, &(rfbScreen->allFds)))
    312                     rfbSendFileTransferChunk(cl);
    313             }
    314             rfbReleaseClientIterator(i);
    315 	    return result;
    316 	}
    317 
    318 	if (nfds < 0) {
    319 #ifdef WIN32
    320 	    errno = WSAGetLastError();
    321 #endif
    322 	    if (errno != EINTR)
    323 		rfbLogPerror("rfbCheckFds: select");
    324 	    return -1;
    325 	}
    326 
    327 	result += nfds;
    328 
    329 	if (rfbScreen->listenSock != -1 && FD_ISSET(rfbScreen->listenSock, &fds)) {
    330 
    331 	    if (!rfbProcessNewConnection(rfbScreen))
    332                 return -1;
    333 
    334 	    FD_CLR(rfbScreen->listenSock, &fds);
    335 	    if (--nfds == 0)
    336 		return result;
    337 	}
    338 
    339 	if (rfbScreen->listen6Sock != -1 && FD_ISSET(rfbScreen->listen6Sock, &fds)) {
    340 
    341 	    if (!rfbProcessNewConnection(rfbScreen))
    342                 return -1;
    343 
    344 	    FD_CLR(rfbScreen->listen6Sock, &fds);
    345 	    if (--nfds == 0)
    346 		return result;
    347 	}
    348 
    349 	if ((rfbScreen->udpSock != -1) && FD_ISSET(rfbScreen->udpSock, &fds)) {
    350 	    if(!rfbScreen->udpClient)
    351 		rfbNewUDPClient(rfbScreen);
    352 	    if (recvfrom(rfbScreen->udpSock, buf, 1, MSG_PEEK,
    353 			(struct sockaddr *)&addr, &addrlen) < 0) {
    354 		rfbLogPerror("rfbCheckFds: UDP: recvfrom");
    355 		rfbDisconnectUDPSock(rfbScreen);
    356 		rfbScreen->udpSockConnected = FALSE;
    357 	    } else {
    358 		if (!rfbScreen->udpSockConnected ||
    359 			(memcmp(&addr, &rfbScreen->udpRemoteAddr, addrlen) != 0))
    360 		{
    361 		    /* new remote end */
    362 		    rfbLog("rfbCheckFds: UDP: got connection\n");
    363 
    364 		    memcpy(&rfbScreen->udpRemoteAddr, &addr, addrlen);
    365 		    rfbScreen->udpSockConnected = TRUE;
    366 
    367 		    if (connect(rfbScreen->udpSock,
    368 				(struct sockaddr *)&addr, addrlen) < 0) {
    369 			rfbLogPerror("rfbCheckFds: UDP: connect");
    370 			rfbDisconnectUDPSock(rfbScreen);
    371 			return -1;
    372 		    }
    373 
    374 		    rfbNewUDPConnection(rfbScreen,rfbScreen->udpSock);
    375 		}
    376 
    377 		rfbProcessUDPInput(rfbScreen);
    378 	    }
    379 
    380 	    FD_CLR(rfbScreen->udpSock, &fds);
    381 	    if (--nfds == 0)
    382 		return result;
    383 	}
    384 
    385 	i = rfbGetClientIterator(rfbScreen);
    386 	while((cl = rfbClientIteratorNext(i))) {
    387 
    388 	    if (cl->onHold)
    389 		continue;
    390 
    391             if (FD_ISSET(cl->sock, &(rfbScreen->allFds)))
    392             {
    393                 if (FD_ISSET(cl->sock, &fds))
    394                     rfbProcessClientMessage(cl);
    395                 else
    396                     rfbSendFileTransferChunk(cl);
    397             }
    398 	}
    399 	rfbReleaseClientIterator(i);
    400     } while(rfbScreen->handleEventsEagerly);
    401     return result;
    402 }
    403 
    404 rfbBool
    405 rfbProcessNewConnection(rfbScreenInfoPtr rfbScreen)
    406 {
    407     const int one = 1;
    408     int sock = -1;
    409 #ifdef LIBVNCSERVER_IPv6
    410     struct sockaddr_storage addr;
    411 #else
    412     struct sockaddr_in addr;
    413 #endif
    414     socklen_t addrlen = sizeof(addr);
    415     fd_set listen_fds;
    416     int chosen_listen_sock = -1;
    417 
    418     /* Do another select() call to find out which listen socket
    419        has an incoming connection pending. We know that at least
    420        one of them has, so this should not block for too long! */
    421     FD_ZERO(&listen_fds);
    422     if(rfbScreen->listenSock >= 0)
    423       FD_SET(rfbScreen->listenSock, &listen_fds);
    424     if(rfbScreen->listen6Sock >= 0)
    425       FD_SET(rfbScreen->listen6Sock, &listen_fds);
    426     if (select(rfbScreen->maxFd+1, &listen_fds, NULL, NULL, NULL) == -1) {
    427       rfbLogPerror("rfbProcessNewConnection: error in select");
    428       return FALSE;
    429     }
    430     if (rfbScreen->listenSock >= 0 && FD_ISSET(rfbScreen->listenSock, &listen_fds))
    431       chosen_listen_sock = rfbScreen->listenSock;
    432     if (rfbScreen->listen6Sock >= 0 && FD_ISSET(rfbScreen->listen6Sock, &listen_fds))
    433       chosen_listen_sock = rfbScreen->listen6Sock;
    434 
    435     if ((sock = accept(chosen_listen_sock,
    436 		       (struct sockaddr *)&addr, &addrlen)) < 0) {
    437       rfbLogPerror("rfbCheckFds: accept");
    438       return FALSE;
    439     }
    440 
    441     if(!rfbSetNonBlocking(sock)) {
    442       closesocket(sock);
    443       return FALSE;
    444     }
    445 
    446     if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
    447 		   (char *)&one, sizeof(one)) < 0) {
    448       rfbLogPerror("rfbCheckFds: setsockopt");
    449       closesocket(sock);
    450       return FALSE;
    451     }
    452 
    453 #ifdef USE_LIBWRAP
    454     if(!hosts_ctl("vnc",STRING_UNKNOWN,inet_ntoa(addr.sin_addr),
    455 		  STRING_UNKNOWN)) {
    456       rfbLog("Rejected connection from client %s\n",
    457 	     inet_ntoa(addr.sin_addr));
    458       closesocket(sock);
    459       return FALSE;
    460     }
    461 #endif
    462 
    463 #ifdef LIBVNCSERVER_IPv6
    464     {
    465         char host[1024];
    466         if(getnameinfo((struct sockaddr*)&addr, addrlen, host, sizeof(host), NULL, 0, NI_NUMERICHOST) != 0) {
    467             rfbLogPerror("rfbProcessNewConnection: error in getnameinfo");
    468         }
    469         rfbLog("Got connection from client %s\n", host);
    470     }
    471 #else
    472     rfbLog("Got connection from client %s\n", inet_ntoa(addr.sin_addr));
    473 #endif
    474 
    475     rfbNewClient(rfbScreen,sock);
    476 
    477     return TRUE;
    478 }
    479 
    480 
    481 void
    482 rfbDisconnectUDPSock(rfbScreenInfoPtr rfbScreen)
    483 {
    484   rfbScreen->udpSockConnected = FALSE;
    485 }
    486 
    487 
    488 
    489 void
    490 rfbCloseClient(rfbClientPtr cl)
    491 {
    492     rfbExtensionData* extension;
    493 
    494     for(extension=cl->extensions; extension; extension=extension->next)
    495 	if(extension->extension->close)
    496 	    extension->extension->close(cl, extension->data);
    497 
    498     LOCK(cl->updateMutex);
    499 #ifdef LIBVNCSERVER_HAVE_LIBPTHREAD
    500     if (cl->sock != -1)
    501 #endif
    502       {
    503 	FD_CLR(cl->sock,&(cl->screen->allFds));
    504 	if(cl->sock==cl->screen->maxFd)
    505 	  while(cl->screen->maxFd>0
    506 		&& !FD_ISSET(cl->screen->maxFd,&(cl->screen->allFds)))
    507 	    cl->screen->maxFd--;
    508 #ifdef LIBVNCSERVER_WITH_WEBSOCKETS
    509 	if (cl->sslctx)
    510 	    rfbssl_destroy(cl);
    511 	free(cl->wspath);
    512 #endif
    513 #ifndef __MINGW32__
    514 	shutdown(cl->sock,SHUT_RDWR);
    515 #endif
    516 	closesocket(cl->sock);
    517 	cl->sock = -1;
    518       }
    519     TSIGNAL(cl->updateCond);
    520     UNLOCK(cl->updateMutex);
    521 }
    522 
    523 
    524 /*
    525  * rfbConnect is called to make a connection out to a given TCP address.
    526  */
    527 
    528 int
    529 rfbConnect(rfbScreenInfoPtr rfbScreen,
    530            char *host,
    531            int port)
    532 {
    533     int sock;
    534     int one = 1;
    535 
    536     rfbLog("Making connection to client on host %s port %d\n",
    537 	   host,port);
    538 
    539     if ((sock = rfbConnectToTcpAddr(host, port)) < 0) {
    540 	rfbLogPerror("connection failed");
    541 	return -1;
    542     }
    543 
    544     if(!rfbSetNonBlocking(sock)) {
    545         closesocket(sock);
    546 	return -1;
    547     }
    548 
    549     if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
    550 		   (char *)&one, sizeof(one)) < 0) {
    551 	rfbLogPerror("setsockopt failed");
    552 	closesocket(sock);
    553 	return -1;
    554     }
    555 
    556     /* AddEnabledDevice(sock); */
    557     FD_SET(sock, &rfbScreen->allFds);
    558     rfbScreen->maxFd = max(sock,rfbScreen->maxFd);
    559 
    560     return sock;
    561 }
    562 
    563 /*
    564  * ReadExact reads an exact number of bytes from a client.  Returns 1 if
    565  * those bytes have been read, 0 if the other end has closed, or -1 if an error
    566  * occurred (errno is set to ETIMEDOUT if it timed out).
    567  */
    568 
    569 int
    570 rfbReadExactTimeout(rfbClientPtr cl, char* buf, int len, int timeout)
    571 {
    572     int sock = cl->sock;
    573     int n;
    574     fd_set fds;
    575     struct timeval tv;
    576 
    577     while (len > 0) {
    578 #ifdef LIBVNCSERVER_WITH_WEBSOCKETS
    579         if (cl->wsctx) {
    580             n = webSocketsDecode(cl, buf, len);
    581         } else if (cl->sslctx) {
    582 	    n = rfbssl_read(cl, buf, len);
    583 	} else {
    584             n = read(sock, buf, len);
    585         }
    586 #else
    587         n = read(sock, buf, len);
    588 #endif
    589 
    590         if (n > 0) {
    591 
    592             buf += n;
    593             len -= n;
    594 
    595         } else if (n == 0) {
    596 
    597             return 0;
    598 
    599         } else {
    600 #ifdef WIN32
    601 	    errno = WSAGetLastError();
    602 #endif
    603 	    if (errno == EINTR)
    604 		continue;
    605 
    606 #ifdef LIBVNCSERVER_ENOENT_WORKAROUND
    607 	    if (errno != ENOENT)
    608 #endif
    609             if (errno != EWOULDBLOCK && errno != EAGAIN) {
    610                 return n;
    611             }
    612 
    613 #ifdef LIBVNCSERVER_WITH_WEBSOCKETS
    614 	    if (cl->sslctx) {
    615 		if (rfbssl_pending(cl))
    616 		    continue;
    617 	    }
    618 #endif
    619             FD_ZERO(&fds);
    620             FD_SET(sock, &fds);
    621             tv.tv_sec = timeout / 1000;
    622             tv.tv_usec = (timeout % 1000) * 1000;
    623             n = select(sock+1, &fds, NULL, &fds, &tv);
    624             if (n < 0) {
    625                 rfbLogPerror("ReadExact: select");
    626                 return n;
    627             }
    628             if (n == 0) {
    629                 rfbErr("ReadExact: select timeout\n");
    630                 errno = ETIMEDOUT;
    631                 return -1;
    632             }
    633         }
    634     }
    635 #undef DEBUG_READ_EXACT
    636 #ifdef DEBUG_READ_EXACT
    637     rfbLog("ReadExact %d bytes\n",len);
    638     for(n=0;n<len;n++)
    639 	    fprintf(stderr,"%02x ",(unsigned char)buf[n]);
    640     fprintf(stderr,"\n");
    641 #endif
    642 
    643     return 1;
    644 }
    645 
    646 int rfbReadExact(rfbClientPtr cl,char* buf,int len)
    647 {
    648   /* favor the per-screen value if set */
    649   if(cl->screen && cl->screen->maxClientWait)
    650     return(rfbReadExactTimeout(cl,buf,len,cl->screen->maxClientWait));
    651   else
    652     return(rfbReadExactTimeout(cl,buf,len,rfbMaxClientWait));
    653 }
    654 
    655 /*
    656  * PeekExact peeks at an exact number of bytes from a client.  Returns 1 if
    657  * those bytes have been read, 0 if the other end has closed, or -1 if an
    658  * error occurred (errno is set to ETIMEDOUT if it timed out).
    659  */
    660 
    661 int
    662 rfbPeekExactTimeout(rfbClientPtr cl, char* buf, int len, int timeout)
    663 {
    664     int sock = cl->sock;
    665     int n;
    666     fd_set fds;
    667     struct timeval tv;
    668 
    669     while (len > 0) {
    670 #ifdef LIBVNCSERVER_WITH_WEBSOCKETS
    671 	if (cl->sslctx)
    672 	    n = rfbssl_peek(cl, buf, len);
    673 	else
    674 #endif
    675 	    n = recv(sock, buf, len, MSG_PEEK);
    676 
    677         if (n == len) {
    678 
    679             break;
    680 
    681         } else if (n == 0) {
    682 
    683             return 0;
    684 
    685         } else {
    686 #ifdef WIN32
    687 	    errno = WSAGetLastError();
    688 #endif
    689 	    if (errno == EINTR)
    690 		continue;
    691 
    692 #ifdef LIBVNCSERVER_ENOENT_WORKAROUND
    693 	    if (errno != ENOENT)
    694 #endif
    695             if (errno != EWOULDBLOCK && errno != EAGAIN) {
    696                 return n;
    697             }
    698 
    699 #ifdef LIBVNCSERVER_WITH_WEBSOCKETS
    700 	    if (cl->sslctx) {
    701 		if (rfbssl_pending(cl))
    702 		    continue;
    703 	    }
    704 #endif
    705             FD_ZERO(&fds);
    706             FD_SET(sock, &fds);
    707             tv.tv_sec = timeout / 1000;
    708             tv.tv_usec = (timeout % 1000) * 1000;
    709             n = select(sock+1, &fds, NULL, &fds, &tv);
    710             if (n < 0) {
    711                 rfbLogPerror("PeekExact: select");
    712                 return n;
    713             }
    714             if (n == 0) {
    715                 errno = ETIMEDOUT;
    716                 return -1;
    717             }
    718         }
    719     }
    720 #undef DEBUG_READ_EXACT
    721 #ifdef DEBUG_READ_EXACT
    722     rfbLog("PeekExact %d bytes\n",len);
    723     for(n=0;n<len;n++)
    724 	    fprintf(stderr,"%02x ",(unsigned char)buf[n]);
    725     fprintf(stderr,"\n");
    726 #endif
    727 
    728     return 1;
    729 }
    730 
    731 /*
    732  * WriteExact writes an exact number of bytes to a client.  Returns 1 if
    733  * those bytes have been written, or -1 if an error occurred (errno is set to
    734  * ETIMEDOUT if it timed out).
    735  */
    736 
    737 int
    738 rfbWriteExact(rfbClientPtr cl,
    739               const char *buf,
    740               int len)
    741 {
    742     int sock = cl->sock;
    743     int n;
    744     fd_set fds;
    745     struct timeval tv;
    746     int totalTimeWaited = 0;
    747     const int timeout = (cl->screen && cl->screen->maxClientWait) ? cl->screen->maxClientWait : rfbMaxClientWait;
    748 
    749 #undef DEBUG_WRITE_EXACT
    750 #ifdef DEBUG_WRITE_EXACT
    751     rfbLog("WriteExact %d bytes\n",len);
    752     for(n=0;n<len;n++)
    753 	    fprintf(stderr,"%02x ",(unsigned char)buf[n]);
    754     fprintf(stderr,"\n");
    755 #endif
    756 
    757 #ifdef LIBVNCSERVER_WITH_WEBSOCKETS
    758     if (cl->wsctx) {
    759         char *tmp = NULL;
    760         if ((len = webSocketsEncode(cl, buf, len, &tmp)) < 0) {
    761             rfbErr("WriteExact: WebSockets encode error\n");
    762             return -1;
    763         }
    764         buf = tmp;
    765     }
    766 #endif
    767 
    768     LOCK(cl->outputMutex);
    769     while (len > 0) {
    770 #ifdef LIBVNCSERVER_WITH_WEBSOCKETS
    771         if (cl->sslctx)
    772 	    n = rfbssl_write(cl, buf, len);
    773 	else
    774 #endif
    775 	    n = write(sock, buf, len);
    776 
    777         if (n > 0) {
    778 
    779             buf += n;
    780             len -= n;
    781 
    782         } else if (n == 0) {
    783 
    784             rfbErr("WriteExact: write returned 0?\n");
    785             return 0;
    786 
    787         } else {
    788 #ifdef WIN32
    789 			errno = WSAGetLastError();
    790 #endif
    791 	    if (errno == EINTR)
    792 		continue;
    793 
    794             if (errno != EWOULDBLOCK && errno != EAGAIN) {
    795 	        UNLOCK(cl->outputMutex);
    796                 return n;
    797             }
    798 
    799             /* Retry every 5 seconds until we exceed timeout.  We
    800                need to do this because select doesn't necessarily return
    801                immediately when the other end has gone away */
    802 
    803             FD_ZERO(&fds);
    804             FD_SET(sock, &fds);
    805             tv.tv_sec = 5;
    806             tv.tv_usec = 0;
    807             n = select(sock+1, NULL, &fds, NULL /* &fds */, &tv);
    808 	    if (n < 0) {
    809 #ifdef WIN32
    810                 errno=WSAGetLastError();
    811 #endif
    812        	        if(errno==EINTR)
    813 		    continue;
    814                 rfbLogPerror("WriteExact: select");
    815                 UNLOCK(cl->outputMutex);
    816                 return n;
    817             }
    818             if (n == 0) {
    819                 totalTimeWaited += 5000;
    820                 if (totalTimeWaited >= timeout) {
    821                     errno = ETIMEDOUT;
    822                     UNLOCK(cl->outputMutex);
    823                     return -1;
    824                 }
    825             } else {
    826                 totalTimeWaited = 0;
    827             }
    828         }
    829     }
    830     UNLOCK(cl->outputMutex);
    831     return 1;
    832 }
    833 
    834 /* currently private, called by rfbProcessArguments() */
    835 int
    836 rfbStringToAddr(char *str, in_addr_t *addr)  {
    837     if (str == NULL || *str == '\0' || strcmp(str, "any") == 0) {
    838         *addr = htonl(INADDR_ANY);
    839     } else if (strcmp(str, "localhost") == 0) {
    840         *addr = htonl(INADDR_LOOPBACK);
    841     } else {
    842         struct hostent *hp;
    843         if ((*addr = inet_addr(str)) == htonl(INADDR_NONE)) {
    844             if (!(hp = gethostbyname(str))) {
    845                 return 0;
    846             }
    847             *addr = *(unsigned long *)hp->h_addr;
    848         }
    849     }
    850     return 1;
    851 }
    852 
    853 int
    854 rfbListenOnTCPPort(int port,
    855                    in_addr_t iface)
    856 {
    857     struct sockaddr_in addr;
    858     int sock;
    859     int one = 1;
    860 
    861     memset(&addr, 0, sizeof(addr));
    862     addr.sin_family = AF_INET;
    863     addr.sin_port = htons(port);
    864     addr.sin_addr.s_addr = iface;
    865 
    866     if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
    867 	return -1;
    868     }
    869     if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
    870 		   (char *)&one, sizeof(one)) < 0) {
    871 	closesocket(sock);
    872 	return -1;
    873     }
    874     if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
    875 	closesocket(sock);
    876 	return -1;
    877     }
    878     if (listen(sock, 32) < 0) {
    879 	closesocket(sock);
    880 	return -1;
    881     }
    882 
    883     return sock;
    884 }
    885 
    886 
    887 int
    888 rfbListenOnTCP6Port(int port,
    889                     const char* iface)
    890 {
    891 #ifndef LIBVNCSERVER_IPv6
    892     rfbLogPerror("This LibVNCServer does not have IPv6 support");
    893     return -1;
    894 #else
    895     int sock;
    896     int one = 1;
    897     int rv;
    898     struct addrinfo hints, *servinfo, *p;
    899     char port_str[8];
    900 
    901     snprintf(port_str, 8, "%d", port);
    902 
    903     memset(&hints, 0, sizeof(hints));
    904     hints.ai_family = AF_INET6;
    905     hints.ai_socktype = SOCK_STREAM;
    906     hints.ai_flags = AI_PASSIVE; /* fill in wildcard address if iface == NULL */
    907 
    908     if ((rv = getaddrinfo(iface, port_str, &hints, &servinfo)) != 0) {
    909         rfbErr("rfbListenOnTCP6Port error in getaddrinfo: %s\n", gai_strerror(rv));
    910         return -1;
    911     }
    912 
    913     /* loop through all the results and bind to the first we can */
    914     for(p = servinfo; p != NULL; p = p->ai_next) {
    915         if ((sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) < 0) {
    916             continue;
    917         }
    918 
    919 #ifdef IPV6_V6ONLY
    920 	/* we have seperate IPv4 and IPv6 sockets since some OS's do not support dual binding */
    921 	if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (char *)&one, sizeof(one)) < 0) {
    922 	  rfbLogPerror("rfbListenOnTCP6Port error in setsockopt IPV6_V6ONLY");
    923 	  closesocket(sock);
    924 	  freeaddrinfo(servinfo);
    925 	  return -1;
    926 	}
    927 #endif
    928 
    929 	if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *)&one, sizeof(one)) < 0) {
    930 	  rfbLogPerror("rfbListenOnTCP6Port: error in setsockopt SO_REUSEADDR");
    931 	  closesocket(sock);
    932 	  freeaddrinfo(servinfo);
    933 	  return -1;
    934 	}
    935 
    936 	if (bind(sock, p->ai_addr, p->ai_addrlen) < 0) {
    937 	  closesocket(sock);
    938 	  continue;
    939 	}
    940 
    941         break;
    942     }
    943 
    944     if (p == NULL)  {
    945         rfbLogPerror("rfbListenOnTCP6Port: error in bind IPv6 socket");
    946         freeaddrinfo(servinfo);
    947         return -1;
    948     }
    949 
    950     /* all done with this structure now */
    951     freeaddrinfo(servinfo);
    952 
    953     if (listen(sock, 32) < 0) {
    954         rfbLogPerror("rfbListenOnTCP6Port: error in listen on IPv6 socket");
    955 	closesocket(sock);
    956 	return -1;
    957     }
    958 
    959     return sock;
    960 #endif
    961 }
    962 
    963 
    964 int
    965 rfbConnectToTcpAddr(char *host,
    966                     int port)
    967 {
    968     int sock;
    969 #ifdef LIBVNCSERVER_IPv6
    970     struct addrinfo hints, *servinfo, *p;
    971     int rv;
    972     char port_str[8];
    973 
    974     snprintf(port_str, 8, "%d", port);
    975 
    976     memset(&hints, 0, sizeof hints);
    977     hints.ai_family = AF_UNSPEC;
    978     hints.ai_socktype = SOCK_STREAM;
    979 
    980     if ((rv = getaddrinfo(host, port_str, &hints, &servinfo)) != 0) {
    981         rfbErr("rfbConnectToTcpAddr: error in getaddrinfo: %s\n", gai_strerror(rv));
    982         return -1;
    983     }
    984 
    985     /* loop through all the results and connect to the first we can */
    986     for(p = servinfo; p != NULL; p = p->ai_next) {
    987         if ((sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) < 0)
    988             continue;
    989 
    990         if (connect(sock, p->ai_addr, p->ai_addrlen) < 0) {
    991             closesocket(sock);
    992             continue;
    993         }
    994 
    995         break;
    996     }
    997 
    998     /* all failed */
    999     if (p == NULL) {
   1000         rfbLogPerror("rfbConnectToTcoAddr: failed to connect\n");
   1001         sock = -1; /* set return value */
   1002     }
   1003 
   1004     /* all done with this structure now */
   1005     freeaddrinfo(servinfo);
   1006 #else
   1007     struct hostent *hp;
   1008     struct sockaddr_in addr;
   1009 
   1010     memset(&addr, 0, sizeof(addr));
   1011     addr.sin_family = AF_INET;
   1012     addr.sin_port = htons(port);
   1013 
   1014     if ((addr.sin_addr.s_addr = inet_addr(host)) == htonl(INADDR_NONE))
   1015     {
   1016 	if (!(hp = gethostbyname(host))) {
   1017 	    errno = EINVAL;
   1018 	    return -1;
   1019 	}
   1020 	addr.sin_addr.s_addr = *(unsigned long *)hp->h_addr;
   1021     }
   1022 
   1023     if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
   1024 	return -1;
   1025     }
   1026 
   1027     if (connect(sock, (struct sockaddr *)&addr, (sizeof(addr))) < 0) {
   1028 	closesocket(sock);
   1029 	return -1;
   1030     }
   1031 #endif
   1032     return sock;
   1033 }
   1034 
   1035 int
   1036 rfbListenOnUDPPort(int port,
   1037                    in_addr_t iface)
   1038 {
   1039     struct sockaddr_in addr;
   1040     int sock;
   1041     int one = 1;
   1042 
   1043     memset(&addr, 0, sizeof(addr));
   1044     addr.sin_family = AF_INET;
   1045     addr.sin_port = htons(port);
   1046     addr.sin_addr.s_addr = iface;
   1047 
   1048     if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
   1049 	return -1;
   1050     }
   1051     if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
   1052 		   (char *)&one, sizeof(one)) < 0) {
   1053 	return -1;
   1054     }
   1055     if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
   1056 	return -1;
   1057     }
   1058 
   1059     return sock;
   1060 }
   1061 
   1062 /*
   1063  * rfbSetNonBlocking sets a socket into non-blocking mode.
   1064  */
   1065 rfbBool
   1066 rfbSetNonBlocking(int sock)
   1067 {
   1068 #ifdef WIN32
   1069   unsigned long block=1;
   1070   if(ioctlsocket(sock, FIONBIO, &block) == SOCKET_ERROR) {
   1071     errno=WSAGetLastError();
   1072 #else
   1073   int flags = fcntl(sock, F_GETFL);
   1074   if(flags < 0 || fcntl(sock, F_SETFL, flags | O_NONBLOCK) < 0) {
   1075 #endif
   1076     rfbLogPerror("Setting socket to non-blocking failed");
   1077     return FALSE;
   1078   }
   1079   return TRUE;
   1080 }
   1081