VirtualBox

source: vbox/trunk/src/VBox/GuestHost/OpenGL/util/tcpip.c@ 62814

Last change on this file since 62814 was 62814, checked in by vboxsync, 9 years ago

GuestHost/OpenGL: warnings

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 38.8 KB
Line 
1/* Copyright (c) 2001, Stanford University
2 * All rights reserved
3 *
4 * See the file LICENSE.txt for information on redistributing this software.
5 */
6
7#ifdef WINDOWS
8#define WIN32_LEAN_AND_MEAN
9# ifdef VBOX
10# include <iprt/win/winsock2.h>
11# else /* !VBOX */
12#pragma warning( push, 3 )
13#include <winsock2.h>
14#pragma warning( pop )
15#pragma warning( disable : 4514 )
16#pragma warning( disable : 4127 )
17typedef int ssize_t;
18# endif /* !VBOX */
19#else
20#include <sys/types.h>
21#include <sys/wait.h>
22#ifdef OSF1
23typedef int socklen_t;
24#endif
25#include <sys/socket.h>
26#include <sys/time.h>
27#include <netinet/in.h>
28#include <netinet/tcp.h>
29#include <arpa/inet.h>
30#include <netdb.h>
31#include <unistd.h>
32#endif
33
34#include <limits.h>
35#include <stdlib.h>
36#include <stdio.h>
37#include <errno.h>
38#include <signal.h>
39#include <string.h>
40#ifdef AIX
41#include <strings.h>
42#endif
43
44#ifdef LINUX
45#include <sys/ioctl.h>
46#include <unistd.h>
47#endif
48
49#include "cr_error.h"
50#include "cr_mem.h"
51#include "cr_string.h"
52#include "cr_bufpool.h"
53#include "cr_net.h"
54#include "cr_endian.h"
55#include "cr_threads.h"
56#include "cr_environment.h"
57#include "net_internals.h"
58
59#ifdef ADDRINFO
60#define PF PF_UNSPEC
61#endif
62
63#ifdef WINDOWS
64# undef EADDRINUSE
65#define EADDRINUSE WSAEADDRINUSE
66# undef ECONNREFUSED
67#define ECONNREFUSED WSAECONNREFUSED
68#endif
69
70#ifdef WINDOWS
71
72#undef ECONNRESET
73#define ECONNRESET WSAECONNRESET
74#undef EINTR
75#define EINTR WSAEINTR
76
77int crTCPIPErrno( void )
78{
79 return WSAGetLastError( );
80}
81
82char *crTCPIPErrorString( int err )
83{
84 static char buf[512], *temp;
85
86 sprintf( buf, "err=%d", err );
87
88#define X(x) crStrcpy(buf,x); break
89
90 switch ( err )
91 {
92 case WSAECONNREFUSED: X( "connection refused" );
93 case WSAECONNRESET: X( "connection reset" );
94 default:
95 FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER |
96 FORMAT_MESSAGE_FROM_SYSTEM |
97 FORMAT_MESSAGE_MAX_WIDTH_MASK, NULL, err,
98 MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ),
99 (LPTSTR) &temp, 0, NULL );
100 if ( temp )
101 {
102 crStrncpy( buf, temp, sizeof(buf)-1 );
103 buf[sizeof(buf)-1] = 0;
104 }
105 }
106
107#undef X
108
109 temp = buf + crStrlen(buf) - 1;
110 while ( temp > buf && isspace( *temp ) )
111 {
112 *temp = '\0';
113 temp--;
114 }
115
116 return buf;
117}
118
119#else /* WINDOWS */
120
121int crTCPIPErrno( void )
122{
123 int err = errno;
124 errno = 0;
125 return err;
126}
127
128char *crTCPIPErrorString( int err )
129{
130 static char buf[512], *temp;
131
132 temp = strerror( err );
133 if ( temp )
134 {
135 crStrncpy( buf, temp, sizeof(buf)-1 );
136 buf[sizeof(buf)-1] = 0;
137 }
138 else
139 {
140 sprintf( buf, "err=%d", err );
141 }
142
143 return buf;
144}
145
146#endif /* WINDOWS */
147
148
149/*
150 * Socket callbacks. When a socket is created or destroyed we will
151 * call these callback functions.
152 * XXX Currently only implemented for TCP/IP.
153 * XXX Maybe have lists of callbacks?
154 */
155static CRSocketCallbackProc SocketCreateCallback = NULL;
156static CRSocketCallbackProc SocketDestroyCallback = NULL;
157
158void
159crRegisterSocketCallback(int mode, CRSocketCallbackProc proc)
160{
161 if (mode == CR_SOCKET_CREATE) {
162 SocketCreateCallback = proc;
163 }
164 else if (mode == CR_SOCKET_DESTROY) {
165 SocketDestroyCallback = proc;
166 }
167 else {
168 crError("Invalid crRegisterSocketCallbac mode=%d", mode);
169 }
170}
171
172
173
174void crCloseSocket( CRSocket sock )
175{
176 int fail;
177
178 if (sock <= 0)
179 return;
180
181 if (SocketDestroyCallback) {
182 SocketDestroyCallback(CR_SOCKET_DESTROY, sock);
183 }
184
185#ifdef WINDOWS
186 fail = ( closesocket( sock ) != 0 );
187#else
188 shutdown( sock, 2 /* RDWR */ );
189 fail = ( close( sock ) != 0 );
190#endif
191 if ( fail )
192 {
193 int err = crTCPIPErrno( );
194 crWarning( "crCloseSocket( sock=%d ): %s",
195 sock, crTCPIPErrorString( err ) );
196 }
197}
198
199cr_tcpip_data cr_tcpip;
200
201/**
202 * Read len bytes from socket, and store in buffer.
203 * \return 1 if success, -1 if error, 0 if sender exited.
204 */
205int
206__tcpip_read_exact( CRSocket sock, void *buf, unsigned int len )
207{
208 char *dst = (char *) buf;
209 /*
210 * Shouldn't write to a non-existent socket, ie when
211 * crTCPIPDoDisconnect has removed it from the pool
212 */
213 if ( sock <= 0 )
214 return 1;
215
216 while ( len > 0 )
217 {
218 const int num_read = recv( sock, dst, (int) len, 0 );
219
220#ifdef WINDOWS_XXXX
221 /* MWE: why is this necessary for windows??? Does it return a
222 "good" value for num_bytes despite having a reset
223 connection? */
224 if ( crTCPIPErrno( ) == ECONNRESET )
225 return -1;
226#endif
227
228 if ( num_read < 0 )
229 {
230 int error = crTCPIPErrno();
231 switch( error )
232 {
233 case EINTR:
234 crWarning( "__tcpip_read_exact(TCPIP): "
235 "caught an EINTR, looping for more data" );
236 continue;
237 case EFAULT:
238 crWarning( "EFAULT" );
239 break;
240 case EINVAL:
241 crWarning( "EINVAL" );
242 break;
243 default:
244 break;
245 }
246 crWarning( "Bad bad bad socket error: %s", crTCPIPErrorString( error ) );
247 return -1;
248 }
249
250 if ( num_read == 0 )
251 {
252 /* client exited gracefully */
253 return 0;
254 }
255
256 dst += num_read;
257 len -= num_read;
258 }
259
260 return 1;
261}
262
263void
264crTCPIPReadExact( CRConnection *conn, void *buf, unsigned int len )
265{
266 if ( __tcpip_read_exact( conn->tcp_socket, buf, len ) <= 0 )
267 {
268 __tcpip_dead_connection( conn );
269 }
270}
271
272/**
273 * Write the given buffer of len bytes on the socket.
274 * \return 1 if OK, negative value if error.
275 */
276int
277__tcpip_write_exact( CRSocket sock, const void *buf, unsigned int len )
278{
279 const char *src = (const char *) buf;
280
281 /*
282 * Shouldn't write to a non-existent socket, ie when
283 * crTCPIPDoDisconnect has removed it from the pool
284 */
285 if ( sock <= 0 )
286 return 1;
287
288 while ( len > 0 )
289 {
290 const int num_written = send( sock, src, len, 0 );
291 if ( num_written <= 0 )
292 {
293 int err;
294 if ( (err = crTCPIPErrno( )) == EINTR )
295 {
296 crWarning("__tcpip_write_exact(TCPIP): caught an EINTR, continuing");
297 continue;
298 }
299
300 return -err;
301 }
302
303 len -= num_written;
304 src += num_written;
305 }
306
307 return 1;
308}
309
310void
311crTCPIPWriteExact( CRConnection *conn, const void *buf, unsigned int len )
312{
313 if ( __tcpip_write_exact( conn->tcp_socket, buf, len) <= 0 )
314 {
315 __tcpip_dead_connection( conn );
316 }
317}
318
319
320/**
321 * Make sockets do what we want:
322 *
323 * 1) Change the size of the send/receive buffers to 64K
324 * 2) Turn off Nagle's algorithm
325 */
326static void
327spankSocket( CRSocket sock )
328{
329 /* why do we do 1) ? things work much better for me to push the
330 * the buffer size way up -- karl
331 */
332#ifdef LINUX
333 int sndbuf = 1*1024*1024;
334#else
335 int sndbuf = 64*1024;
336#endif
337
338 int rcvbuf = sndbuf;
339 int so_reuseaddr = 1;
340 int tcp_nodelay = 1;
341
342 if ( setsockopt( sock, SOL_SOCKET, SO_SNDBUF,
343 (char *) &sndbuf, sizeof(sndbuf) ) )
344 {
345 int err = crTCPIPErrno( );
346 crWarning( "setsockopt( SO_SNDBUF=%d ) : %s",
347 sndbuf, crTCPIPErrorString( err ) );
348 }
349
350 if ( setsockopt( sock, SOL_SOCKET, SO_RCVBUF,
351 (char *) &rcvbuf, sizeof(rcvbuf) ) )
352 {
353 int err = crTCPIPErrno( );
354 crWarning( "setsockopt( SO_RCVBUF=%d ) : %s",
355 rcvbuf, crTCPIPErrorString( err ) );
356 }
357
358
359 if ( setsockopt( sock, SOL_SOCKET, SO_REUSEADDR,
360 (char *) &so_reuseaddr, sizeof(so_reuseaddr) ) )
361 {
362 int err = crTCPIPErrno( );
363 crWarning( "setsockopt( SO_REUSEADDR=%d ) : %s",
364 so_reuseaddr, crTCPIPErrorString( err ) );
365 }
366
367 if ( setsockopt( sock, IPPROTO_TCP, TCP_NODELAY,
368 (char *) &tcp_nodelay, sizeof(tcp_nodelay) ) )
369 {
370 int err = crTCPIPErrno( );
371 crWarning( "setsockopt( TCP_NODELAY=%d )"
372 " : %s", tcp_nodelay, crTCPIPErrorString( err ) );
373 }
374}
375
376
377#if defined( WINDOWS ) || defined( IRIX ) || defined( IRIX64 )
378typedef int socklen_t;
379#endif
380
381
382/**
383 * Create a listening socket using the given port.
384 * Caller can then pass the socket to accept().
385 * If the port is one that's been seen before, we'll reuse/return the
386 * previously create socket.
387 */
388static int
389CreateListeningSocket(int port)
390{
391 /* XXX should use an unbounded list here instead of parallel arrays... */
392#define MAX_PORTS 100
393 static int ports[MAX_PORTS];
394 static int sockets[MAX_PORTS];
395 static int count = 0;
396 int i, sock = -1;
397
398 /* search to see if we've seen this port before */
399 for (i = 0; i < count; i++) {
400 if (ports[i] == port) {
401 return sockets[i];
402 }
403 }
404
405 /* new port so create new socket */
406 {
407 int err;
408#ifndef ADDRINFO
409 struct sockaddr_in servaddr;
410#endif
411
412 /* with the new OOB stuff, we can have multiple ports being
413 * accepted on, so we need to redo the server socket every time.
414 */
415#ifndef ADDRINFO
416 sock = socket( AF_INET, SOCK_STREAM, 0 );
417 if ( sock == -1 )
418 {
419 err = crTCPIPErrno( );
420 crError( "Couldn't create socket: %s", crTCPIPErrorString( err ) );
421 }
422 spankSocket( sock );
423
424 servaddr.sin_family = AF_INET;
425 servaddr.sin_addr.s_addr = INADDR_ANY;
426 servaddr.sin_port = htons( (short) port );
427
428 if ( bind( sock, (struct sockaddr *) &servaddr, sizeof(servaddr) ) )
429 {
430 err = crTCPIPErrno( );
431 crError( "Couldn't bind to socket (port=%d): %s",
432 port, crTCPIPErrorString( err ) );
433 }
434
435 if ( listen( sock, 100 /* max pending connections */ ) )
436 {
437 err = crTCPIPErrno( );
438 crError( "Couldn't listen on socket: %s", crTCPIPErrorString( err ) );
439 }
440#else
441 char port_s[NI_MAXSERV];
442 struct addrinfo *res,*cur;
443 struct addrinfo hints;
444
445 sprintf(port_s, "%u", (short unsigned) port);
446
447 crMemset(&hints, 0, sizeof(hints));
448 hints.ai_flags = AI_PASSIVE;
449 hints.ai_family = PF;
450 hints.ai_socktype = SOCK_STREAM;
451
452 err = getaddrinfo( NULL, port_s, &hints, &res );
453 if ( err )
454 crError( "Couldn't find local TCP port %s: %s",
455 port_s, gai_strerror(err) );
456
457 for (cur=res;cur;cur=cur->ai_next)
458 {
459 sock = socket( cur->ai_family, cur->ai_socktype, cur->ai_protocol );
460 if ( sock == -1 )
461 {
462 err = crTCPIPErrno( );
463 if (err != EAFNOSUPPORT)
464 crWarning("Couldn't create socket of family %i: %s, trying another",
465 cur->ai_family, crTCPIPErrorString( err ) );
466 continue;
467 }
468 spankSocket( sock );
469
470 if ( bind( sock, cur->ai_addr, cur->ai_addrlen ) )
471 {
472 err = crTCPIPErrno( );
473 crWarning( "Couldn't bind to socket (port=%d): %s",
474 port, crTCPIPErrorString( err ) );
475 crCloseSocket( sock );
476 continue;
477 }
478
479 if ( listen( sock, 100 /* max pending connections */ ) )
480 {
481 err = crTCPIPErrno( );
482 crWarning("Couldn't listen on socket: %s", crTCPIPErrorString(err));
483 crCloseSocket( sock );
484 continue;
485 }
486 break;
487 }
488 freeaddrinfo(res);
489 if (!cur)
490 crError( "Couldn't find/bind local TCP port %s", port_s);
491#endif
492 }
493
494 /* save the new port/socket */
495 if (count == MAX_PORTS) {
496 crError("Fatal error in tcpip layer: too many listening ports/sockets");
497 }
498 ports[count] = port;
499 sockets[count] = sock;
500 count++;
501
502 return sock;
503}
504
505
506
507
508void
509crTCPIPAccept( CRConnection *conn, const char *hostname, unsigned short port )
510{
511 int err;
512 socklen_t addr_length;
513#ifndef ADDRINFO
514 struct hostent *host;
515 struct in_addr sin_addr;
516 struct sockaddr addr;
517#else
518 struct sockaddr_storage addr;
519 char host[NI_MAXHOST];
520#endif
521
522 cr_tcpip.server_sock = CreateListeningSocket(port);
523
524 /* If brokered, we'll contact the mothership to broker the network
525 * connection. We'll send the mothership our hostname, the port and
526 * our endianness and will get in return a connection ID number.
527 */
528 if (conn->broker) {
529 crError("There shouldn't be any brokered connections in VirtualBox");
530 }
531
532 addr_length = sizeof( addr );
533 conn->tcp_socket = accept( cr_tcpip.server_sock, (struct sockaddr *) &addr, &addr_length );
534 if (conn->tcp_socket == -1)
535 {
536 err = crTCPIPErrno( );
537 crError( "Couldn't accept client: %s", crTCPIPErrorString( err ) );
538 }
539
540 if (SocketCreateCallback) {
541 SocketCreateCallback(CR_SOCKET_CREATE, conn->tcp_socket);
542 }
543
544#ifndef ADDRINFO
545 sin_addr = ((struct sockaddr_in *) &addr)->sin_addr;
546 host = gethostbyaddr( (char *) &sin_addr, sizeof( sin_addr), AF_INET );
547 if (host == NULL )
548 {
549 char *temp = inet_ntoa( sin_addr );
550 conn->hostname = crStrdup( temp );
551 }
552#else
553 err = getnameinfo ( (struct sockaddr *) &addr, addr_length,
554 host, sizeof( host),
555 NULL, 0, NI_NAMEREQD);
556 if ( err )
557 {
558 err = getnameinfo ( (struct sockaddr *) &addr, addr_length,
559 host, sizeof( host),
560 NULL, 0, NI_NUMERICHOST);
561 if ( err ) /* shouldn't ever happen */
562 conn->hostname = crStrdup("unknown ?!");
563 else
564 conn->hostname = crStrdup( host );
565 }
566#endif
567 else
568 {
569 char *temp;
570#ifndef ADDRINFO
571 conn->hostname = crStrdup( host->h_name );
572#else
573 conn->hostname = crStrdup( host );
574#endif
575
576 temp = conn->hostname;
577 while (*temp && *temp != '.' )
578 temp++;
579 *temp = '\0';
580 }
581
582#ifdef RECV_BAIL_OUT
583 err = sizeof(unsigned int);
584 if ( getsockopt( conn->tcp_socket, SOL_SOCKET, SO_RCVBUF,
585 (char *) &conn->krecv_buf_size, &err ) )
586 {
587 conn->krecv_buf_size = 0;
588 }
589#endif
590
591 crDebug( "Accepted connection from \"%s\".", conn->hostname );
592}
593
594
595void *
596crTCPIPAlloc( CRConnection *conn )
597{
598 CRTCPIPBuffer *buf;
599
600#ifdef CHROMIUM_THREADSAFE
601 crLockMutex(&cr_tcpip.mutex);
602#endif
603
604 buf = (CRTCPIPBuffer *) crBufferPoolPop( cr_tcpip.bufpool, conn->buffer_size );
605
606 if ( buf == NULL )
607 {
608 crDebug("Buffer pool %p was empty; allocated new %d byte buffer.",
609 cr_tcpip.bufpool,
610 (unsigned int)sizeof(CRTCPIPBuffer) + conn->buffer_size);
611 buf = (CRTCPIPBuffer *)
612 crAlloc( sizeof(CRTCPIPBuffer) + conn->buffer_size );
613 buf->magic = CR_TCPIP_BUFFER_MAGIC;
614 buf->kind = CRTCPIPMemory;
615 buf->pad = 0;
616 buf->allocated = conn->buffer_size;
617 }
618
619#ifdef CHROMIUM_THREADSAFE
620 crUnlockMutex(&cr_tcpip.mutex);
621#endif
622
623 return (void *)( buf + 1 );
624}
625
626
627static void
628crTCPIPSingleRecv( CRConnection *conn, void *buf, unsigned int len )
629{
630 crTCPIPReadExact( conn, buf, len );
631}
632
633
634static void
635crTCPIPSend( CRConnection *conn, void **bufp,
636 const void *start, unsigned int len )
637{
638 if ( !conn || conn->type == CR_NO_CONNECTION )
639 return;
640
641 if (!bufp) {
642 /* We're sending a user-allocated buffer.
643 * Simply write the length & the payload and return.
644 */
645 const int sendable_len = conn->swap ? SWAP32(len) : len;
646 crTCPIPWriteExact( conn, &sendable_len, sizeof(len) );
647 if (conn->type == CR_NO_CONNECTION)
648 return;
649 crTCPIPWriteExact( conn, start, len );
650 }
651 else {
652 /* The region [start .. start + len + 1] lies within a buffer that
653 * was allocated with crTCPIPAlloc() and can be put into the free
654 * buffer pool when we're done sending it.
655 */
656 CRTCPIPBuffer *tcpip_buffer;
657 unsigned int *lenp;
658
659 tcpip_buffer = (CRTCPIPBuffer *)(*bufp) - 1;
660
661 CRASSERT( tcpip_buffer->magic == CR_TCPIP_BUFFER_MAGIC );
662
663 /* All of the buffers passed to the send function were allocated
664 * with crTCPIPAlloc(), which includes a header with a 4 byte
665 * pad field, to insure that we always have a place to write
666 * the length field, even when start == *bufp.
667 */
668 lenp = (unsigned int *) start - 1;
669 *lenp = conn->swap ? SWAP32(len) : len;
670
671 crTCPIPWriteExact(conn, lenp, len + sizeof(unsigned int));
672
673 /* Reclaim this pointer for reuse */
674#ifdef CHROMIUM_THREADSAFE
675 crLockMutex(&cr_tcpip.mutex);
676#endif
677 crBufferPoolPush(cr_tcpip.bufpool, tcpip_buffer, tcpip_buffer->allocated);
678#ifdef CHROMIUM_THREADSAFE
679 crUnlockMutex(&cr_tcpip.mutex);
680#endif
681 /* Since the buffer's now in the 'free' buffer pool, the caller can't
682 * use it any more. Setting bufp to NULL will make sure the caller
683 * doesn't try to re-use the buffer.
684 */
685 *bufp = NULL;
686 }
687}
688
689
690void
691__tcpip_dead_connection( CRConnection *conn )
692{
693 crDebug( "Dead connection (sock=%d, host=%s), removing from pool",
694 conn->tcp_socket, conn->hostname );
695 /* remove from connection pool */
696 crTCPIPDoDisconnect( conn );
697}
698
699
700int
701__crSelect( int n, fd_set *readfds, int sec, int usec )
702{
703 for ( ; ; )
704 {
705 int err, num_ready;
706
707 if (sec || usec)
708 {
709 /* We re-init everytime for Linux, as it corrupts
710 * the timeout structure, but other OS's
711 * don't have a problem with it.
712 */
713 struct timeval timeout;
714 timeout.tv_sec = sec;
715 timeout.tv_usec = usec;
716 num_ready = select( n, readfds, NULL, NULL, &timeout );
717 }
718 else
719 num_ready = select( n, readfds, NULL, NULL, NULL );
720
721 if ( num_ready >= 0 )
722 {
723 return num_ready;
724 }
725
726 err = crTCPIPErrno( );
727 if ( err == EINTR )
728 {
729 crWarning( "select interrupted by an unblocked signal, trying again" );
730 }
731 else
732 {
733 crError( "select failed: %s", crTCPIPErrorString( err ) );
734 }
735 }
736}
737
738
739void
740crTCPIPFree( CRConnection *conn, void *buf )
741{
742 CRTCPIPBuffer *tcpip_buffer = (CRTCPIPBuffer *) buf - 1;
743
744 CRASSERT( tcpip_buffer->magic == CR_TCPIP_BUFFER_MAGIC );
745 conn->recv_credits += tcpip_buffer->len;
746
747 switch ( tcpip_buffer->kind )
748 {
749 case CRTCPIPMemory:
750#ifdef CHROMIUM_THREADSAFE
751 crLockMutex(&cr_tcpip.mutex);
752#endif
753 if (cr_tcpip.bufpool) {
754 /* pool may have been deallocated just a bit earlier in response
755 * to a SIGPIPE (Broken Pipe) signal.
756 */
757 crBufferPoolPush( cr_tcpip.bufpool, tcpip_buffer, tcpip_buffer->allocated );
758 }
759#ifdef CHROMIUM_THREADSAFE
760 crUnlockMutex(&cr_tcpip.mutex);
761#endif
762 break;
763
764 case CRTCPIPMemoryBig:
765 crFree( tcpip_buffer );
766 break;
767
768 default:
769 crError( "Weird buffer kind trying to free in crTCPIPFree: %d", tcpip_buffer->kind );
770 }
771}
772
773
774/**
775 * Check if message type is GATHER. If so, process it specially.
776 * \return number of bytes which were consumed
777 */
778static int
779crTCPIPUserbufRecv(CRConnection *conn, CRMessage *msg)
780{
781 if (msg->header.type == CR_MESSAGE_GATHER) {
782 /* grab the offset and the length */
783 const int len = 2 * sizeof(unsigned int); /* was unsigned long!!!! */
784 unsigned int buf[2];
785
786 if (__tcpip_read_exact(conn->tcp_socket, buf, len) <= 0)
787 {
788 __tcpip_dead_connection( conn );
789 }
790 msg->gather.offset = buf[0];
791 msg->gather.len = buf[1];
792
793 /* read the rest into the userbuf */
794 if (buf[0] + buf[1] > (unsigned int) conn->userbuf_len)
795 {
796 crDebug("userbuf for Gather Message is too small!");
797 return len;
798 }
799
800 if (__tcpip_read_exact(conn->tcp_socket,
801 conn->userbuf + buf[0], buf[1]) <= 0)
802 {
803 __tcpip_dead_connection( conn );
804 }
805 return len + buf[1];
806 }
807 else {
808 return 0;
809 }
810}
811
812
813/**
814 * Receive the next message on the given connection.
815 * If we're being called by crTCPIPRecv(), we already know there's
816 * something to receive.
817 */
818static void
819crTCPIPReceiveMessage(CRConnection *conn)
820{
821 CRMessage *msg;
822 CRMessageType cached_type;
823 CRTCPIPBuffer *tcpip_buffer;
824 unsigned int len, total, leftover;
825 const int sock = conn->tcp_socket;
826
827 /* Our gigE board is acting odd. If we recv() an amount
828 * less than what is already in the RECVBUF, performance
829 * goes into the toilet (somewhere around a factor of 3).
830 * This is an ugly hack, but seems to get around whatever
831 * funk is being produced
832 *
833 * Remember to set your kernel recv buffers to be bigger
834 * than the framebuffer 'chunk' you are sending (see
835 * sysctl -a | grep rmem) , or this will really have no
836 * effect. --karl
837 */
838#ifdef RECV_BAIL_OUT
839 {
840 int inbuf;
841 (void) recv(sock, &len, sizeof(len), MSG_PEEK);
842 ioctl(conn->tcp_socket, FIONREAD, &inbuf);
843
844 if ((conn->krecv_buf_size > len) && (inbuf < len))
845 return;
846 }
847#endif
848
849 /* this reads the length of the message */
850 if ( __tcpip_read_exact( sock, &len, sizeof(len)) <= 0 )
851 {
852 __tcpip_dead_connection( conn );
853 return;
854 }
855
856 if (conn->swap)
857 len = SWAP32(len);
858
859 CRASSERT( len > 0 );
860
861 if ( len <= conn->buffer_size )
862 {
863 /* put in pre-allocated buffer */
864 tcpip_buffer = (CRTCPIPBuffer *) crTCPIPAlloc( conn ) - 1;
865 }
866 else
867 {
868 /* allocate new buffer */
869 tcpip_buffer = (CRTCPIPBuffer *) crAlloc( sizeof(*tcpip_buffer) + len );
870 tcpip_buffer->magic = CR_TCPIP_BUFFER_MAGIC;
871 tcpip_buffer->kind = CRTCPIPMemoryBig;
872 tcpip_buffer->pad = 0;
873 }
874
875 tcpip_buffer->len = len;
876
877 /* if we have set a userbuf, and there is room in it, we probably
878 * want to stick the message into that, instead of our allocated
879 * buffer.
880 */
881 leftover = 0;
882 total = len;
883 if ((conn->userbuf != NULL)
884 && (conn->userbuf_len >= (int) sizeof(CRMessageHeader)))
885 {
886 leftover = len - sizeof(CRMessageHeader);
887 total = sizeof(CRMessageHeader);
888 }
889
890 if ( __tcpip_read_exact( sock, tcpip_buffer + 1, total) <= 0 )
891 {
892 crWarning( "Bad juju: %d %d on socket 0x%x", tcpip_buffer->allocated,
893 total, sock );
894 crFree( tcpip_buffer );
895 __tcpip_dead_connection( conn );
896 return;
897 }
898
899 conn->recv_credits -= total;
900 conn->total_bytes_recv += total;
901
902 msg = (CRMessage *) (tcpip_buffer + 1);
903 cached_type = msg->header.type;
904 if (conn->swap)
905 {
906 msg->header.type = (CRMessageType) SWAP32( msg->header.type );
907 msg->header.conn_id = (CRMessageType) SWAP32( msg->header.conn_id );
908 }
909
910 /* if there is still data pending, it should go into the user buffer */
911 if (leftover)
912 {
913 const unsigned int handled = crTCPIPUserbufRecv(conn, msg);
914
915 /* if there is anything left, plop it into the recv_buffer */
916 if (leftover - handled)
917 {
918 if ( __tcpip_read_exact( sock, tcpip_buffer + 1 + total, leftover-handled) <= 0 )
919 {
920 crWarning( "Bad juju: %d %d", tcpip_buffer->allocated, leftover-handled);
921 crFree( tcpip_buffer );
922 __tcpip_dead_connection( conn );
923 return;
924 }
925 }
926
927 conn->recv_credits -= handled;
928 conn->total_bytes_recv += handled;
929 }
930
931 crNetDispatchMessage( cr_tcpip.recv_list, conn, msg, len );
932#if 0
933 crLogRead( len );
934#endif
935
936 /* CR_MESSAGE_OPCODES is freed in crserverlib/server_stream.c with crNetFree.
937 * OOB messages are the programmer's problem. -- Humper 12/17/01
938 */
939 if (cached_type != CR_MESSAGE_OPCODES
940 && cached_type != CR_MESSAGE_OOB
941 && cached_type != CR_MESSAGE_GATHER)
942 {
943 crTCPIPFree( conn, tcpip_buffer + 1 );
944 }
945}
946
947
948/**
949 * Loop over all TCP/IP connections, reading incoming data on those
950 * that are ready.
951 */
952int
953crTCPIPRecv( void )
954{
955 /* ensure we don't get caught with a new thread connecting */
956 const int num_conns = cr_tcpip.num_conns;
957 int num_ready, max_fd, i;
958 fd_set read_fds;
959 int msock = -1; /* assumed mothership socket */
960#if CRAPPFAKER_SHOULD_DIE
961 int none_left = 1;
962#endif
963
964#ifdef CHROMIUM_THREADSAFE
965 crLockMutex(&cr_tcpip.recvmutex);
966#endif
967
968 /*
969 * Loop over all connections and determine which are TCP/IP connections
970 * that are ready to be read.
971 */
972 max_fd = 0;
973 FD_ZERO( &read_fds );
974 for ( i = 0; i < num_conns; i++ )
975 {
976 CRConnection *conn = cr_tcpip.conns[i];
977 if ( !conn || conn->type == CR_NO_CONNECTION )
978 continue;
979
980#if CRAPPFAKER_SHOULD_DIE
981 none_left = 0;
982#endif
983
984 if ( conn->recv_credits > 0 || conn->type != CR_TCPIP )
985 {
986 /*
987 * NOTE: may want to always put the FD in the descriptor
988 * set so we'll notice broken connections. Down in the
989 * loop that iterates over the ready sockets only peek
990 * (MSG_PEEK flag to recv()?) if the connection isn't
991 * enabled.
992 */
993#if 0 /* not used - see below */
994#ifndef ADDRINFO
995 struct sockaddr s;
996#else
997 struct sockaddr_storage s;
998#endif
999 socklen_t slen;
1000#endif
1001 fd_set only_fd; /* testing single fd */
1002 CRSocket sock = conn->tcp_socket;
1003
1004 if ( (int) sock + 1 > max_fd )
1005 max_fd = (int) sock + 1;
1006 FD_SET( sock, &read_fds );
1007
1008 /* KLUDGE CITY......
1009 *
1010 * With threads there's a race condition between
1011 * TCPIPRecv and TCPIPSingleRecv when new
1012 * clients are connecting, thus new mothership
1013 * connections are also being established.
1014 * This code below is to check that we're not
1015 * in a state of accepting the socket without
1016 * connecting to it otherwise we fail with
1017 * ENOTCONN later. But, this is really a side
1018 * effect of this routine catching a motherships
1019 * socket connection and reading data that wasn't
1020 * really meant for us. It was really meant for
1021 * TCPIPSingleRecv. So, if we detect an
1022 * in-progress connection we set the msock id
1023 * so that we can assume the motherships socket
1024 * and skip over them.
1025 */
1026
1027 FD_ZERO(&only_fd);
1028 FD_SET( sock, &only_fd );
1029
1030#if 0 /* Disabled on Dec 13 2005 by BrianP - seems to cause trouble */
1031 slen = sizeof( s );
1032 /* Check that the socket is REALLY connected */
1033 /* Doesn't this call introduce some inefficiency??? (BP) */
1034 if (getpeername(sock, (struct sockaddr *) &s, &slen) < 0) {
1035 /* Another kludge.....
1036 * If we disconnect a socket without writing
1037 * anything to it, we end up here. Detect
1038 * the disconnected socket by checking if
1039 * we've ever sent something and then
1040 * disconnect it.
1041 *
1042 * I think the networking layer needs
1043 * a bit of a re-write.... Alan.
1044 */
1045 if (conn->total_bytes_sent > 0) {
1046 crTCPIPDoDisconnect( conn );
1047 }
1048 FD_CLR(sock, &read_fds);
1049 msock = sock;
1050 }
1051#endif
1052 /*
1053 * Nope, that last socket we've just caught in
1054 * the connecting phase. We've probably found
1055 * a mothership connection here, and we shouldn't
1056 * process it
1057 */
1058 if ((int)sock == msock+1)
1059 FD_CLR(sock, &read_fds);
1060 }
1061 }
1062
1063#if CRAPPFAKER_SHOULD_DIE
1064 if (none_left) {
1065 /*
1066 * Caught no more connections.
1067 * Review this if we want to try
1068 * restarting crserver's dynamically.
1069 */
1070#ifdef CHROMIUM_THREADSAFE
1071 crUnlockMutex(&cr_tcpip.recvmutex);
1072#endif
1073 crError("No more connections to process, terminating...\n");
1074 exit(0); /* shouldn't get here */
1075 }
1076#endif
1077
1078 if (!max_fd) {
1079#ifdef CHROMIUM_THREADSAFE
1080 crUnlockMutex(&cr_tcpip.recvmutex);
1081#endif
1082 return 0;
1083 }
1084
1085 if ( num_conns ) {
1086 num_ready = __crSelect( max_fd, &read_fds, 0, 500 );
1087 }
1088 else {
1089 crWarning( "Waiting for first connection..." );
1090 num_ready = __crSelect( max_fd, &read_fds, 0, 0 );
1091 }
1092
1093 if ( num_ready == 0 ) {
1094#ifdef CHROMIUM_THREADSAFE
1095 crUnlockMutex(&cr_tcpip.recvmutex);
1096#endif
1097 return 0;
1098 }
1099
1100 /*
1101 * Loop over connections, receive data on the TCP/IP connections that
1102 * we determined are ready above.
1103 */
1104 for ( i = 0; i < num_conns; i++ )
1105 {
1106 CRConnection *conn = cr_tcpip.conns[i];
1107 CRSocket sock;
1108
1109 if ( !conn || conn->type == CR_NO_CONNECTION )
1110 continue;
1111
1112 /* Added by Samuel Thibault during TCP/IP / UDP code factorization */
1113 if ( conn->type != CR_TCPIP )
1114 continue;
1115
1116 sock = conn->tcp_socket;
1117 if ( !FD_ISSET( sock, &read_fds ) )
1118 continue;
1119
1120 if (conn->threaded)
1121 continue;
1122
1123 crTCPIPReceiveMessage(conn);
1124 }
1125
1126#ifdef CHROMIUM_THREADSAFE
1127 crUnlockMutex(&cr_tcpip.recvmutex);
1128#endif
1129
1130 return 1;
1131}
1132
1133
1134static void
1135crTCPIPHandleNewMessage( CRConnection *conn, CRMessage *msg, unsigned int len )
1136{
1137 CRTCPIPBuffer *buf = ((CRTCPIPBuffer *) msg) - 1;
1138
1139 /* build a header so we can delete the message later */
1140 buf->magic = CR_TCPIP_BUFFER_MAGIC;
1141 buf->kind = CRTCPIPMemory;
1142 buf->len = len;
1143 buf->pad = 0;
1144
1145 crNetDispatchMessage( cr_tcpip.recv_list, conn, msg, len );
1146}
1147
1148
1149static void
1150crTCPIPInstantReclaim( CRConnection *conn, CRMessage *mess )
1151{
1152 crTCPIPFree( conn, mess );
1153}
1154
1155
1156void
1157crTCPIPInit( CRNetReceiveFuncList *rfl, CRNetCloseFuncList *cfl,
1158 unsigned int mtu )
1159{
1160 (void) mtu;
1161
1162 cr_tcpip.recv_list = rfl;
1163 cr_tcpip.close_list = cfl;
1164 if ( cr_tcpip.initialized )
1165 {
1166 return;
1167 }
1168
1169 cr_tcpip.initialized = 1;
1170
1171 cr_tcpip.num_conns = 0;
1172 cr_tcpip.conns = NULL;
1173
1174 cr_tcpip.server_sock = -1;
1175
1176#ifdef CHROMIUM_THREADSAFE
1177 crInitMutex(&cr_tcpip.mutex);
1178 crInitMutex(&cr_tcpip.recvmutex);
1179#endif
1180 cr_tcpip.bufpool = crBufferPoolInit(16);
1181}
1182
1183
1184/**
1185 * The function that actually connects. This should only be called by clients
1186 * Servers have another way to set up the socket.
1187 */
1188int
1189crTCPIPDoConnect( CRConnection *conn )
1190{
1191 int err;
1192#ifndef ADDRINFO
1193 struct sockaddr_in servaddr;
1194 struct hostent *hp;
1195 int i;
1196
1197 conn->tcp_socket = socket( AF_INET, SOCK_STREAM, 0 );
1198 if ( conn->tcp_socket < 0 )
1199 {
1200 int err = crTCPIPErrno( );
1201 crWarning( "socket error: %s", crTCPIPErrorString( err ) );
1202 cr_tcpip.conns[conn->index] = NULL; /* remove from table */
1203 return 0;
1204 }
1205
1206 if (SocketCreateCallback) {
1207 SocketCreateCallback(CR_SOCKET_CREATE, conn->tcp_socket);
1208 }
1209
1210 /* Set up the socket the way *we* want. */
1211 spankSocket( conn->tcp_socket );
1212
1213 /* Standard Berkeley sockets mumbo jumbo */
1214 hp = gethostbyname( conn->hostname );
1215 if ( !hp )
1216 {
1217 crWarning( "Unknown host: \"%s\"", conn->hostname );
1218 cr_tcpip.conns[conn->index] = NULL; /* remove from table */
1219 return 0;
1220 }
1221
1222 crMemset( &servaddr, 0, sizeof(servaddr) );
1223 servaddr.sin_family = AF_INET;
1224 servaddr.sin_port = htons( (short) conn->port );
1225
1226 crMemcpy((char *) &servaddr.sin_addr, hp->h_addr, sizeof(servaddr.sin_addr));
1227#else
1228 char port_s[NI_MAXSERV];
1229 struct addrinfo *res,*cur;
1230 struct addrinfo hints;
1231
1232 sprintf(port_s, "%u", (short unsigned) conn->port);
1233
1234 crMemset(&hints, 0, sizeof(hints));
1235 hints.ai_family = PF;
1236 hints.ai_socktype = SOCK_STREAM;
1237
1238 err = getaddrinfo( conn->hostname, port_s, &hints, &res);
1239 if ( err )
1240 {
1241 crWarning( "Unknown host: \"%s\": %s", conn->hostname, gai_strerror(err) );
1242 cr_tcpip.conns[conn->index] = NULL; /* remove from table */
1243 return 0;
1244 }
1245#endif
1246
1247 /* If brokered, we'll contact the mothership to broker the network
1248 * connection. We'll send the mothership our hostname, the port and
1249 * our endianness and will get in return a connection ID number.
1250 */
1251 if (conn->broker)
1252 {
1253 crError("There shouldn't be any brokered connections in VirtualBox");
1254 }
1255
1256#ifndef ADDRINFO
1257 for (i=1;i;)
1258#else
1259 for (cur=res;cur;)
1260#endif
1261 {
1262#ifndef ADDRINFO
1263
1264#ifdef RECV_BAIL_OUT
1265 err = sizeof(unsigned int);
1266 if ( getsockopt( conn->tcp_socket, SOL_SOCKET, SO_RCVBUF,
1267 (char *) &conn->krecv_buf_size, &err ) )
1268 {
1269 conn->krecv_buf_size = 0;
1270 }
1271#endif
1272 if ( !connect( conn->tcp_socket, (struct sockaddr *) &servaddr,
1273 sizeof(servaddr) ) )
1274 return 1;
1275#else
1276
1277 conn->tcp_socket = socket( cur->ai_family, cur->ai_socktype, cur->ai_protocol );
1278 if ( conn->tcp_socket < 0 )
1279 {
1280 int err = crTCPIPErrno( );
1281 if (err != EAFNOSUPPORT)
1282 crWarning( "socket error: %s, trying another way", crTCPIPErrorString( err ) );
1283 cur=cur->ai_next;
1284 continue;
1285 }
1286
1287 if (SocketCreateCallback) {
1288 SocketCreateCallback(CR_SOCKET_CREATE, conn->tcp_socket);
1289 }
1290
1291 err = 1;
1292 setsockopt(conn->tcp_socket, SOL_SOCKET, SO_REUSEADDR, &err, sizeof(int));
1293
1294 /* Set up the socket the way *we* want. */
1295 spankSocket( conn->tcp_socket );
1296
1297#if RECV_BAIL_OUT
1298 err = sizeof(unsigned int);
1299 if ( getsockopt( conn->tcp_socket, SOL_SOCKET, SO_RCVBUF,
1300 (char *) &conn->krecv_buf_size, &err ) )
1301 {
1302 conn->krecv_buf_size = 0;
1303 }
1304#endif
1305
1306 if ( !connect( conn->tcp_socket, cur->ai_addr, cur->ai_addrlen ) ) {
1307 freeaddrinfo(res);
1308 return 1;
1309 }
1310#endif
1311
1312 err = crTCPIPErrno( );
1313 if ( err == EADDRINUSE || err == ECONNREFUSED )
1314 crWarning( "Connection refused to %s:%d, %s",
1315 conn->hostname, conn->port, crTCPIPErrorString( err ) );
1316
1317 else if ( err == EINTR )
1318 {
1319 crWarning( "connection to %s:%d "
1320 "interrupted, trying again", conn->hostname, conn->port );
1321 continue;
1322 }
1323 else
1324 crWarning( "Couldn't connect to %s:%d, %s",
1325 conn->hostname, conn->port, crTCPIPErrorString( err ) );
1326 crCloseSocket( conn->tcp_socket );
1327#ifndef ADDRINFO
1328 i=0;
1329#else
1330 cur=cur->ai_next;
1331#endif
1332 }
1333#ifdef ADDRINFO
1334 freeaddrinfo(res);
1335 crWarning( "Couldn't find any suitable way to connect to %s", conn->hostname );
1336#endif
1337 cr_tcpip.conns[conn->index] = NULL; /* remove from table */
1338 return 0;
1339}
1340
1341
1342/**
1343 * Disconnect this connection, but don't free(conn).
1344 */
1345void
1346crTCPIPDoDisconnect( CRConnection *conn )
1347{
1348 int num_conns = cr_tcpip.num_conns;
1349 int none_left = 1;
1350 int i;
1351
1352 /* If this connection has already been disconnected (e.g.
1353 * if the connection has been lost and disabled through
1354 * a call to __tcpip_dead_connection(), which will then
1355 * call this routine), don't disconnect it again; if we
1356 * do, and if a new valid connection appears in the same
1357 * slot (conn->index), we'll effectively disable the
1358 * valid connection by mistake, leaving us unable to
1359 * receive inbound data on that connection.
1360 */
1361 if (conn->type == CR_NO_CONNECTION) return;
1362
1363 crCloseSocket( conn->tcp_socket );
1364 if (conn->hostname) {
1365 crFree(conn->hostname);
1366 conn->hostname = NULL;
1367 }
1368 conn->tcp_socket = 0;
1369 conn->type = CR_NO_CONNECTION;
1370 cr_tcpip.conns[conn->index] = NULL;
1371
1372 /* see if any connections remain */
1373 for (i = 0; i < num_conns; i++)
1374 {
1375 if ( cr_tcpip.conns[i] && cr_tcpip.conns[i]->type != CR_NO_CONNECTION )
1376 none_left = 0; /* found a live connection */
1377 }
1378
1379#if 0 /* disabled on 13 Dec 2005 by BrianP - this prevents future client
1380 * connections after the last one goes away.
1381 */
1382 if (none_left && cr_tcpip.server_sock != -1)
1383 {
1384 crDebug("Closing master socket (probably quitting).");
1385 crCloseSocket( cr_tcpip.server_sock );
1386 cr_tcpip.server_sock = -1;
1387#ifdef CHROMIUM_THREADSAFE
1388 crFreeMutex(&cr_tcpip.mutex);
1389 crFreeMutex(&cr_tcpip.recvmutex);
1390#endif
1391 crBufferPoolFree( cr_tcpip.bufpool );
1392 cr_tcpip.bufpool = NULL;
1393 last_port = 0;
1394 cr_tcpip.initialized = 0;
1395 }
1396#endif
1397}
1398
1399
1400/**
1401 * Initialize a CRConnection for tcp/ip. This is called via the
1402 * InitConnection() function (and from the UDP module).
1403 */
1404void
1405crTCPIPConnection( CRConnection *conn )
1406{
1407 int i, found = 0;
1408 int n_bytes;
1409
1410 CRASSERT( cr_tcpip.initialized );
1411
1412 conn->type = CR_TCPIP;
1413 conn->Alloc = crTCPIPAlloc;
1414 conn->Send = crTCPIPSend;
1415 conn->SendExact = crTCPIPWriteExact;
1416 conn->Recv = crTCPIPSingleRecv;
1417 conn->RecvMsg = crTCPIPReceiveMessage;
1418 conn->Free = crTCPIPFree;
1419 conn->Accept = crTCPIPAccept;
1420 conn->Connect = crTCPIPDoConnect;
1421 conn->Disconnect = crTCPIPDoDisconnect;
1422 conn->InstantReclaim = crTCPIPInstantReclaim;
1423 conn->HandleNewMessage = crTCPIPHandleNewMessage;
1424 conn->index = cr_tcpip.num_conns;
1425 conn->sizeof_buffer_header = sizeof( CRTCPIPBuffer );
1426 conn->actual_network = 1;
1427
1428 conn->krecv_buf_size = 0;
1429
1430 /* Find a free slot */
1431 for (i = 0; i < cr_tcpip.num_conns; i++) {
1432 if (cr_tcpip.conns[i] == NULL) {
1433 conn->index = i;
1434 cr_tcpip.conns[i] = conn;
1435 found = 1;
1436 break;
1437 }
1438 }
1439
1440 /* Realloc connection stack if we couldn't find a free slot */
1441 if (found == 0) {
1442 n_bytes = ( cr_tcpip.num_conns + 1 ) * sizeof(*cr_tcpip.conns);
1443 crRealloc( (void **) &cr_tcpip.conns, n_bytes );
1444 cr_tcpip.conns[cr_tcpip.num_conns++] = conn;
1445 }
1446}
1447
1448
1449int crGetHostname( char *buf, unsigned int len )
1450{
1451 const char *override;
1452 int ret;
1453
1454 override = crGetenv("CR_HOSTNAME");
1455 if (override)
1456 {
1457 crStrncpy(buf, override, len);
1458 ret = 0;
1459 }
1460 else
1461 ret = gethostname( buf, len );
1462 return ret;
1463}
1464
1465
1466CRConnection** crTCPIPDump( int *num )
1467{
1468 *num = cr_tcpip.num_conns;
1469
1470 return cr_tcpip.conns;
1471}
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette