2 * Copyright (C) 1999 AT&T Laboratories Cambridge. All Rights Reserved.
4 * This is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This software is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this software; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
21 * sockets.c - functions to deal with sockets.
24 #ifdef __STRICT_ANSI__
31 #include <rfb/rfbclient.h>
34 #define EWOULDBLOCK WSAEWOULDBLOCK
35 #define close closesocket
36 #define read(sock,buf,len) recv(sock,buf,len,0)
37 #define write(sock,buf,len) send(sock,buf,len,0)
39 #include <sys/socket.h>
40 #include <netinet/in.h>
41 #include <netinet/tcp.h>
42 #include <arpa/inet.h>
46 void PrintInHex(char *buf, int len);
48 rfbBool errorMessageOnReadFailure = TRUE;
51 * ReadFromRFBServer is called whenever we want to read some data from the RFB
52 * server. It is non-trivial for two reasons:
54 * 1. For efficiency it performs some intelligent buffering, avoiding invoking
55 * the read() system call too often. For small chunks of data, it simply
56 * copies the data out of an internal buffer. For large amounts of data it
57 * reads directly into the buffer provided by the caller.
59 * 2. Whenever read() would block, it invokes the Xt event dispatching
60 * mechanism to process X events. In fact, this is the only place these
61 * events are processed, as there is no XtAppMainLoop in the program.
65 ReadFromRFBServer(rfbClient* client, char *out, unsigned int n)
67 #undef DEBUG_READ_EXACT
68 #ifdef DEBUG_READ_EXACT
71 rfbClientLog("ReadFromRFBServer %d bytes\n",n);
73 if (client->serverPort==-1) {
75 rfbVNCRec* rec = client->vncRec;
78 if (rec->readTimestamp) {
79 rec->readTimestamp = FALSE;
80 if (!fread(&tv,sizeof(struct timeval),1,rec->file))
83 tv.tv_sec = rfbClientSwap32IfLE (tv.tv_sec);
84 tv.tv_usec = rfbClientSwap32IfLE (tv.tv_usec);
86 if (rec->tv.tv_sec!=0 && !rec->doNotSleep) {
88 diff.tv_sec = tv.tv_sec - rec->tv.tv_sec;
89 diff.tv_usec = tv.tv_usec - rec->tv.tv_usec;
92 diff.tv_usec+=1000000;
96 usleep (diff.tv_usec);
98 Sleep (diff.tv_sec * 1000 + diff.tv_usec/1000);
105 return (fread(out,1,n,rec->file)<0?FALSE:TRUE);
108 if (n <= client->buffered) {
109 memcpy(out, client->bufoutptr, n);
110 client->bufoutptr += n;
111 client->buffered -= n;
112 #ifdef DEBUG_READ_EXACT
118 memcpy(out, client->bufoutptr, client->buffered);
120 out += client->buffered;
121 n -= client->buffered;
123 client->bufoutptr = client->buf;
124 client->buffered = 0;
126 if (n <= RFB_BUF_SIZE) {
128 while (client->buffered < n) {
129 int i = read(client->sock, client->buf + client->buffered, RFB_BUF_SIZE - client->buffered);
133 errno=WSAGetLastError();
135 if (errno == EWOULDBLOCK || errno == EAGAIN) {
141 rfbClientErr("read (%d: %s)\n",errno,strerror(errno));
145 if (errorMessageOnReadFailure) {
146 rfbClientLog("VNC server closed connection\n");
151 client->buffered += i;
154 memcpy(out, client->bufoutptr, n);
155 client->bufoutptr += n;
156 client->buffered -= n;
161 int i = read(client->sock, out, n);
165 errno=WSAGetLastError();
167 if (errno == EWOULDBLOCK || errno == EAGAIN) {
173 rfbClientErr("read (%s)\n",strerror(errno));
177 if (errorMessageOnReadFailure) {
178 rfbClientLog("VNC server closed connection\n");
188 #ifdef DEBUG_READ_EXACT
192 fprintf(stderr,"%02x ",(unsigned char)oout[ii]);
193 fprintf(stderr,"\n");
202 * Write an exact number of bytes, and don't return until you've sent them.
206 WriteToRFBServer(rfbClient* client, char *buf, int n)
212 if (client->serverPort==-1)
213 return TRUE; /* vncrec playing */
216 j = write(client->sock, buf + i, (n - i));
219 if (errno == EWOULDBLOCK ||
220 #ifdef LIBVNCSERVER_ENOENT_WORKAROUND
225 FD_SET(client->sock,&fds);
227 if (select(client->sock+1, NULL, &fds, NULL, NULL) <= 0) {
228 rfbClientErr("select\n");
233 rfbClientErr("write\n");
237 rfbClientLog("write failed\n");
248 * ConnectToTcpAddr connects to the given TCP port.
252 ConnectClientToTcpAddr(unsigned int host, int port)
255 struct sockaddr_in addr;
260 static rfbBool WSAinitted=FALSE;
263 int i=WSAStartup(MAKEWORD(2,0),&trash);
265 rfbClientErr("Couldn't init Windows Sockets\n");
271 addr.sin_family = AF_INET;
272 addr.sin_port = htons(port);
273 addr.sin_addr.s_addr = host;
275 sock = socket(AF_INET, SOCK_STREAM, 0);
278 errno=WSAGetLastError();
280 rfbClientErr("ConnectToTcpAddr: socket (%s)\n",strerror(errno));
284 if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
285 rfbClientErr("ConnectToTcpAddr: connect\n");
290 if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
291 (char *)&one, sizeof(one)) < 0) {
292 rfbClientErr("ConnectToTcpAddr: setsockopt\n");
303 * FindFreeTcpPort tries to find unused TCP port in the range
304 * (TUNNEL_PORT_OFFSET, TUNNEL_PORT_OFFSET + 99]. Returns 0 on failure.
308 FindFreeTcpPort(void)
311 struct sockaddr_in addr;
313 addr.sin_family = AF_INET;
314 addr.sin_addr.s_addr = htonl(INADDR_ANY);
316 sock = socket(AF_INET, SOCK_STREAM, 0);
318 rfbClientErr(": FindFreeTcpPort: socket\n");
322 for (port = TUNNEL_PORT_OFFSET + 99; port > TUNNEL_PORT_OFFSET; port--) {
323 addr.sin_port = htons((unsigned short)port);
324 if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) == 0) {
336 * ListenAtTcpPort starts listening at the given TCP port.
340 ListenAtTcpPort(int port)
343 struct sockaddr_in addr;
346 addr.sin_family = AF_INET;
347 addr.sin_port = htons(port);
348 addr.sin_addr.s_addr = htonl(INADDR_ANY);
350 sock = socket(AF_INET, SOCK_STREAM, 0);
352 rfbClientErr("ListenAtTcpPort: socket\n");
356 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
357 (const char *)&one, sizeof(one)) < 0) {
358 rfbClientErr("ListenAtTcpPort: setsockopt\n");
363 if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
364 rfbClientErr("ListenAtTcpPort: bind\n");
369 if (listen(sock, 5) < 0) {
370 rfbClientErr("ListenAtTcpPort: listen\n");
380 * AcceptTcpConnection accepts a TCP connection.
384 AcceptTcpConnection(int listenSock)
387 struct sockaddr_in addr;
388 int addrlen = sizeof(addr);
391 sock = accept(listenSock, (struct sockaddr *) &addr, &addrlen);
393 rfbClientErr("AcceptTcpConnection: accept\n");
397 if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
398 (char *)&one, sizeof(one)) < 0) {
399 rfbClientErr("AcceptTcpConnection: setsockopt\n");
409 * SetNonBlocking sets a socket into non-blocking mode.
413 SetNonBlocking(int sock)
416 if (fcntl(sock, F_SETFL, O_NONBLOCK) < 0) {
417 rfbClientErr("AcceptTcpConnection: fcntl\n");
421 rfbClientErr("O_NONBLOCK on MinGW32 NOT IMPLEMENTED\n");
428 * StringToIPAddr - convert a host string to an IP address.
432 StringToIPAddr(const char *str, unsigned int *addr)
436 if (strcmp(str,"") == 0) {
437 *addr = 0; /* local */
441 *addr = inet_addr(str);
446 hp = gethostbyname(str);
449 *addr = *(unsigned int *)hp->h_addr;
458 * Test if the other end of a socket is on the same machine.
462 SameMachine(int sock)
464 struct sockaddr_in peeraddr, myaddr;
465 int addrlen = sizeof(struct sockaddr_in);
467 getpeername(sock, (struct sockaddr *)&peeraddr, &addrlen);
468 getsockname(sock, (struct sockaddr *)&myaddr, &addrlen);
470 return (peeraddr.sin_addr.s_addr == myaddr.sin_addr.s_addr);
475 * Print out the contents of a packet for debugging.
479 PrintInHex(char *buf, int len)
486 rfbClientLog("ReadExact: ");
488 for (i = 0; i < len; i++)
490 if ((i % 16 == 0) && (i != 0)) {
494 str[i % 16] = (((c > 31) && (c < 127)) ? c : '.');
495 rfbClientLog("%02x ",(unsigned char)c);
500 rfbClientLog("%s\n",str);
505 for (j = i % 16; j < 16; j++)
508 if ((j % 4) == 3) rfbClientLog(" ");
511 rfbClientLog("%s\n",str);
517 int WaitForMessage(rfbClient* client,unsigned int usecs)
520 struct timeval timeout;
523 if (client->serverPort==-1)
524 /* playing back vncrec file */
527 timeout.tv_sec=(usecs/1000000);
528 timeout.tv_usec=(usecs%1000000);
531 FD_SET(client->sock,&fds);
533 num=select(client->sock+1, &fds, NULL, NULL, &timeout);
535 rfbClientLog("Waiting for message failed: %d (%s)\n",errno,strerror(errno));