update about dialog
[presencevnc] / libvnc / libvncclient / sockets.c
1 /*
2  *  Copyright (C) 1999 AT&T Laboratories Cambridge.  All Rights Reserved.
3  *
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.
8  *
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.
13  *
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,
17  *  USA.
18  */
19
20 /*
21  * sockets.c - functions to deal with sockets.
22  */
23
24 #ifdef __STRICT_ANSI__
25 #define _BSD_SOURCE
26 #endif
27 #include <unistd.h>
28 #include <errno.h>
29 #include <fcntl.h>
30 #include <assert.h>
31 #include <rfb/rfbclient.h>
32 #ifdef WIN32
33 #include <winsock2.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)
38 #else
39 #include <sys/socket.h>
40 #include <netinet/in.h>
41 #include <netinet/tcp.h>
42 #include <arpa/inet.h>
43 #include <netdb.h>
44 #endif
45
46 void PrintInHex(char *buf, int len);
47
48 rfbBool errorMessageOnReadFailure = TRUE;
49
50 /*
51  * ReadFromRFBServer is called whenever we want to read some data from the RFB
52  * server.  It is non-trivial for two reasons:
53  *
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.
58  *
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.
62  */
63
64 rfbBool
65 ReadFromRFBServer(rfbClient* client, char *out, unsigned int n)
66 {
67 #undef DEBUG_READ_EXACT
68 #ifdef DEBUG_READ_EXACT
69         char* oout=out;
70         int nn=n;
71         rfbClientLog("ReadFromRFBServer %d bytes\n",n);
72 #endif
73   if (client->serverPort==-1) {
74     /* vncrec playing */
75     rfbVNCRec* rec = client->vncRec;
76     struct timeval tv;
77
78     if (rec->readTimestamp) {
79       rec->readTimestamp = FALSE;
80       if (!fread(&tv,sizeof(struct timeval),1,rec->file))
81         return FALSE;
82
83       tv.tv_sec = rfbClientSwap32IfLE (tv.tv_sec);
84       tv.tv_usec = rfbClientSwap32IfLE (tv.tv_usec);
85
86       if (rec->tv.tv_sec!=0 && !rec->doNotSleep) {
87         struct timeval diff;
88         diff.tv_sec = tv.tv_sec - rec->tv.tv_sec;
89         diff.tv_usec = tv.tv_usec - rec->tv.tv_usec;
90         if(diff.tv_usec<0) {
91           diff.tv_sec--;
92           diff.tv_usec+=1000000;
93         }
94 #ifndef __MINGW32__
95         sleep (diff.tv_sec);
96         usleep (diff.tv_usec);
97 #else
98         Sleep (diff.tv_sec * 1000 + diff.tv_usec/1000);
99 #endif
100       }
101
102       rec->tv=tv;
103     }
104     
105     return (fread(out,1,n,rec->file)<0?FALSE:TRUE);
106   }
107   
108   if (n <= client->buffered) {
109     memcpy(out, client->bufoutptr, n);
110     client->bufoutptr += n;
111     client->buffered -= n;
112 #ifdef DEBUG_READ_EXACT
113     goto hexdump;
114 #endif
115     return TRUE;
116   }
117
118   memcpy(out, client->bufoutptr, client->buffered);
119
120   out += client->buffered;
121   n -= client->buffered;
122
123   client->bufoutptr = client->buf;
124   client->buffered = 0;
125
126   if (n <= RFB_BUF_SIZE) {
127
128     while (client->buffered < n) {
129       int i = read(client->sock, client->buf + client->buffered, RFB_BUF_SIZE - client->buffered);
130       if (i <= 0) {
131         if (i < 0) {
132 #ifdef WIN32
133           errno=WSAGetLastError();
134 #endif
135           if (errno == EWOULDBLOCK || errno == EAGAIN) {
136             /* TODO:
137                ProcessXtEvents();
138             */
139             i = 0;
140           } else {
141             rfbClientErr("read (%d: %s)\n",errno,strerror(errno));
142             return FALSE;
143           }
144         } else {
145           if (errorMessageOnReadFailure) {
146             rfbClientLog("VNC server closed connection\n");
147           }
148           return FALSE;
149         }
150       }
151       client->buffered += i;
152     }
153
154     memcpy(out, client->bufoutptr, n);
155     client->bufoutptr += n;
156     client->buffered -= n;
157
158   } else {
159
160     while (n > 0) {
161       int i = read(client->sock, out, n);
162       if (i <= 0) {
163         if (i < 0) {
164 #ifdef WIN32
165           errno=WSAGetLastError();
166 #endif
167           if (errno == EWOULDBLOCK || errno == EAGAIN) {
168             /* TODO:
169                ProcessXtEvents();
170             */
171             i = 0;
172           } else {
173             rfbClientErr("read (%s)\n",strerror(errno));
174             return FALSE;
175           }
176         } else {
177           if (errorMessageOnReadFailure) {
178             rfbClientLog("VNC server closed connection\n");
179           }
180           return FALSE;
181         }
182       }
183       out += i;
184       n -= i;
185     }
186   }
187
188 #ifdef DEBUG_READ_EXACT
189 hexdump:
190   { int ii;
191     for(ii=0;ii<nn;ii++)
192       fprintf(stderr,"%02x ",(unsigned char)oout[ii]);
193     fprintf(stderr,"\n");
194   }
195 #endif
196
197   return TRUE;
198 }
199
200
201 /*
202  * Write an exact number of bytes, and don't return until you've sent them.
203  */
204
205 rfbBool
206 WriteToRFBServer(rfbClient* client, char *buf, int n)
207 {
208   fd_set fds;
209   int i = 0;
210   int j;
211
212   if (client->serverPort==-1)
213     return TRUE; /* vncrec playing */
214
215   while (i < n) {
216     j = write(client->sock, buf + i, (n - i));
217     if (j <= 0) {
218       if (j < 0) {
219         if (errno == EWOULDBLOCK ||
220 #ifdef LIBVNCSERVER_ENOENT_WORKAROUND
221                 errno == ENOENT ||
222 #endif
223                 errno == EAGAIN) {
224           FD_ZERO(&fds);
225           FD_SET(client->sock,&fds);
226
227           if (select(client->sock+1, NULL, &fds, NULL, NULL) <= 0) {
228             rfbClientErr("select\n");
229             return FALSE;
230           }
231           j = 0;
232         } else {
233           rfbClientErr("write\n");
234           return FALSE;
235         }
236       } else {
237         rfbClientLog("write failed\n");
238         return FALSE;
239       }
240     }
241     i += j;
242   }
243   return TRUE;
244 }
245
246
247 /*
248  * ConnectToTcpAddr connects to the given TCP port.
249  */
250
251 int
252 ConnectClientToTcpAddr(unsigned int host, int port)
253 {
254   int sock;
255   struct sockaddr_in addr;
256   int one = 1;
257
258 #ifdef WIN32
259   WSADATA trash;
260   static rfbBool WSAinitted=FALSE;
261   if(!WSAinitted) {
262     WSAinitted=TRUE;
263     int i=WSAStartup(MAKEWORD(2,0),&trash);
264     if(i!=0) {
265       rfbClientErr("Couldn't init Windows Sockets\n");
266       return -1;
267     }
268   }
269 #endif
270
271   addr.sin_family = AF_INET;
272   addr.sin_port = htons(port);
273   addr.sin_addr.s_addr = host;
274
275   sock = socket(AF_INET, SOCK_STREAM, 0);
276   if (sock < 0) {
277 #ifdef WIN32
278     errno=WSAGetLastError();
279 #endif
280     rfbClientErr("ConnectToTcpAddr: socket (%s)\n",strerror(errno));
281     return -1;
282   }
283
284   if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
285     rfbClientErr("ConnectToTcpAddr: connect\n");
286     close(sock);
287     return -1;
288   }
289
290   if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
291                  (char *)&one, sizeof(one)) < 0) {
292     rfbClientErr("ConnectToTcpAddr: setsockopt\n");
293     close(sock);
294     return -1;
295   }
296
297   return sock;
298 }
299
300
301
302 /*
303  * FindFreeTcpPort tries to find unused TCP port in the range
304  * (TUNNEL_PORT_OFFSET, TUNNEL_PORT_OFFSET + 99]. Returns 0 on failure.
305  */
306
307 int
308 FindFreeTcpPort(void)
309 {
310   int sock, port;
311   struct sockaddr_in addr;
312
313   addr.sin_family = AF_INET;
314   addr.sin_addr.s_addr = htonl(INADDR_ANY);
315
316   sock = socket(AF_INET, SOCK_STREAM, 0);
317   if (sock < 0) {
318     rfbClientErr(": FindFreeTcpPort: socket\n");
319     return 0;
320   }
321
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) {
325       close(sock);
326       return port;
327     }
328   }
329
330   close(sock);
331   return 0;
332 }
333
334
335 /*
336  * ListenAtTcpPort starts listening at the given TCP port.
337  */
338
339 int
340 ListenAtTcpPort(int port)
341 {
342   int sock;
343   struct sockaddr_in addr;
344   int one = 1;
345
346   addr.sin_family = AF_INET;
347   addr.sin_port = htons(port);
348   addr.sin_addr.s_addr = htonl(INADDR_ANY);
349
350   sock = socket(AF_INET, SOCK_STREAM, 0);
351   if (sock < 0) {
352     rfbClientErr("ListenAtTcpPort: socket\n");
353     return -1;
354   }
355
356   if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
357                  (const char *)&one, sizeof(one)) < 0) {
358     rfbClientErr("ListenAtTcpPort: setsockopt\n");
359     close(sock);
360     return -1;
361   }
362
363   if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
364     rfbClientErr("ListenAtTcpPort: bind\n");
365     close(sock);
366     return -1;
367   }
368
369   if (listen(sock, 5) < 0) {
370     rfbClientErr("ListenAtTcpPort: listen\n");
371     close(sock);
372     return -1;
373   }
374
375   return sock;
376 }
377
378
379 /*
380  * AcceptTcpConnection accepts a TCP connection.
381  */
382
383 int
384 AcceptTcpConnection(int listenSock)
385 {
386   int sock;
387   struct sockaddr_in addr;
388   int addrlen = sizeof(addr);
389   int one = 1;
390
391   sock = accept(listenSock, (struct sockaddr *) &addr, &addrlen);
392   if (sock < 0) {
393     rfbClientErr("AcceptTcpConnection: accept\n");
394     return -1;
395   }
396
397   if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
398                  (char *)&one, sizeof(one)) < 0) {
399     rfbClientErr("AcceptTcpConnection: setsockopt\n");
400     close(sock);
401     return -1;
402   }
403
404   return sock;
405 }
406
407
408 /*
409  * SetNonBlocking sets a socket into non-blocking mode.
410  */
411
412 rfbBool
413 SetNonBlocking(int sock)
414 {
415 #ifndef __MINGW32__
416   if (fcntl(sock, F_SETFL, O_NONBLOCK) < 0) {
417     rfbClientErr("AcceptTcpConnection: fcntl\n");
418     return FALSE;
419   }
420 #else
421   rfbClientErr("O_NONBLOCK on MinGW32 NOT IMPLEMENTED\n");
422 #endif
423   return TRUE;
424 }
425
426
427 /*
428  * StringToIPAddr - convert a host string to an IP address.
429  */
430
431 rfbBool
432 StringToIPAddr(const char *str, unsigned int *addr)
433 {
434   struct hostent *hp;
435
436   if (strcmp(str,"") == 0) {
437     *addr = 0; /* local */
438     return TRUE;
439   }
440
441   *addr = inet_addr(str);
442
443   if (*addr != -1)
444     return TRUE;
445
446   hp = gethostbyname(str);
447
448   if (hp) {
449     *addr = *(unsigned int *)hp->h_addr;
450     return TRUE;
451   }
452
453   return FALSE;
454 }
455
456
457 /*
458  * Test if the other end of a socket is on the same machine.
459  */
460
461 rfbBool
462 SameMachine(int sock)
463 {
464   struct sockaddr_in peeraddr, myaddr;
465   int addrlen = sizeof(struct sockaddr_in);
466
467   getpeername(sock, (struct sockaddr *)&peeraddr, &addrlen);
468   getsockname(sock, (struct sockaddr *)&myaddr, &addrlen);
469
470   return (peeraddr.sin_addr.s_addr == myaddr.sin_addr.s_addr);
471 }
472
473
474 /*
475  * Print out the contents of a packet for debugging.
476  */
477
478 void
479 PrintInHex(char *buf, int len)
480 {
481   int i, j;
482   char c, str[17];
483
484   str[16] = 0;
485
486   rfbClientLog("ReadExact: ");
487
488   for (i = 0; i < len; i++)
489     {
490       if ((i % 16 == 0) && (i != 0)) {
491         rfbClientLog("           ");
492       }
493       c = buf[i];
494       str[i % 16] = (((c > 31) && (c < 127)) ? c : '.');
495       rfbClientLog("%02x ",(unsigned char)c);
496       if ((i % 4) == 3)
497         rfbClientLog(" ");
498       if ((i % 16) == 15)
499         {
500           rfbClientLog("%s\n",str);
501         }
502     }
503   if ((i % 16) != 0)
504     {
505       for (j = i % 16; j < 16; j++)
506         {
507           rfbClientLog("   ");
508           if ((j % 4) == 3) rfbClientLog(" ");
509         }
510       str[i % 16] = 0;
511       rfbClientLog("%s\n",str);
512     }
513
514   fflush(stderr);
515 }
516
517 int WaitForMessage(rfbClient* client,unsigned int usecs)
518 {
519   fd_set fds;
520   struct timeval timeout;
521   int num;
522
523   if (client->serverPort==-1)
524     /* playing back vncrec file */
525     return 1;
526   
527   timeout.tv_sec=(usecs/1000000);
528   timeout.tv_usec=(usecs%1000000);
529
530   FD_ZERO(&fds);
531   FD_SET(client->sock,&fds);
532
533   num=select(client->sock+1, &fds, NULL, NULL, &timeout);
534   if(num<0)
535     rfbClientLog("Waiting for message failed: %d (%s)\n",errno,strerror(errno));
536
537   return num;
538 }