VirtualBox

source: vbox/trunk/src/VBox/GuestHost/OpenGL/util/net.c@ 53370

Last change on this file since 53370 was 53370, checked in by vboxsync, 10 years ago

4.3: build fix

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 37.0 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#include <stdio.h>
8#include <stdlib.h>
9#include <stdarg.h>
10#include <errno.h>
11#include <memory.h>
12#include <signal.h>
13
14#ifdef WINDOWS
15#define WIN32_LEAN_AND_MEAN
16#include <process.h>
17#else
18#include <unistd.h>
19#endif
20
21#include "cr_mem.h"
22#include "cr_error.h"
23#include "cr_string.h"
24#include "cr_url.h"
25#include "cr_net.h"
26#include "cr_netserver.h"
27#include "cr_pixeldata.h"
28#include "cr_environment.h"
29#include "cr_endian.h"
30#include "cr_bufpool.h"
31#include "cr_threads.h"
32#include "net_internals.h"
33
34
35#define CR_MINIMUM_MTU 1024
36
37#define CR_INITIAL_RECV_CREDITS ( 1 << 21 ) /* 2MB */
38
39/* Allow up to four processes per node. . . */
40#define CR_QUADRICS_LOWEST_RANK 0
41#define CR_QUADRICS_HIGHEST_RANK 3
42
43static struct {
44 int initialized; /* flag */
45 CRNetReceiveFuncList *recv_list; /* what to do with arriving packets */
46 CRNetCloseFuncList *close_list; /* what to do when a client goes down */
47
48 /* Number of connections using each type of interface: */
49 int use_tcpip;
50 int use_ib;
51 int use_file;
52 int use_udp;
53 int use_gm;
54 int use_sdp;
55 int use_teac;
56 int use_tcscomm;
57 int use_hgcm;
58
59 int num_clients; /* total number of clients (unused?) */
60
61#ifdef CHROMIUM_THREADSAFE
62 CRmutex mutex;
63#endif
64 int my_rank; /* Teac/TSComm only */
65} cr_net;
66
67
68
69/**
70 * Helper routine used by both crNetConnectToServer() and crNetAcceptClient().
71 * Call the protocol-specific Init() and Connection() functions.
72 *
73 */
74static void
75InitConnection(CRConnection *conn, const char *protocol, unsigned int mtu
76#if defined(VBOX_WITH_CRHGSMI) && defined(IN_GUEST)
77 , struct VBOXUHGSMI *pHgsmi
78#endif
79 )
80{
81 if (!crStrcmp(protocol, "devnull"))
82 {
83 crDevnullInit(cr_net.recv_list, cr_net.close_list, mtu);
84 crDevnullConnection(conn);
85 }
86 else if (!crStrcmp(protocol, "file"))
87 {
88 cr_net.use_file++;
89 crFileInit(cr_net.recv_list, cr_net.close_list, mtu);
90 crFileConnection(conn);
91 }
92 else if (!crStrcmp(protocol, "swapfile"))
93 {
94 /* file with byte-swapping */
95 cr_net.use_file++;
96 crFileInit(cr_net.recv_list, cr_net.close_list, mtu);
97 crFileConnection(conn);
98 conn->swap = 1;
99 }
100 else if (!crStrcmp(protocol, "tcpip"))
101 {
102 cr_net.use_tcpip++;
103 crTCPIPInit(cr_net.recv_list, cr_net.close_list, mtu);
104 crTCPIPConnection(conn);
105 }
106 else if (!crStrcmp(protocol, "udptcpip"))
107 {
108 cr_net.use_udp++;
109 crUDPTCPIPInit(cr_net.recv_list, cr_net.close_list, mtu);
110 crUDPTCPIPConnection(conn);
111 }
112#ifdef VBOX_WITH_HGCM
113 else if (!crStrcmp(protocol, "vboxhgcm"))
114 {
115 cr_net.use_hgcm++;
116 crVBoxHGCMInit(cr_net.recv_list, cr_net.close_list, mtu);
117 crVBoxHGCMConnection(conn
118#if defined(VBOX_WITH_CRHGSMI) && defined(IN_GUEST)
119 , pHgsmi
120#endif
121 );
122 }
123#endif
124#ifdef GM_SUPPORT
125 else if (!crStrcmp(protocol, "gm"))
126 {
127 cr_net.use_gm++;
128 crGmInit(cr_net.recv_list, cr_net.close_list, mtu);
129 crGmConnection(conn);
130 }
131#endif
132#ifdef TEAC_SUPPORT
133 else if (!crStrcmp(protocol, "quadrics"))
134 {
135 cr_net.use_teac++;
136 crTeacInit(cr_net.recv_list, cr_net.close_list, mtu);
137 crTeacConnection(conn);
138 }
139#endif
140#ifdef TCSCOMM_SUPPORT
141 else if (!crStrcmp(protocol, "quadrics-tcscomm"))
142 {
143 cr_net.use_tcscomm++;
144 crTcscommInit(cr_net.recv_list, cr_net.close_list, mtu);
145 crTcscommConnection(conn);
146 }
147#endif
148#ifdef SDP_SUPPORT
149 else if (!crStrcmp(protocol, "sdp"))
150 {
151 cr_net.use_sdp++;
152 crSDPInit(cr_net.recv_list, cr_net.close_list, mtu);
153 crSDPConnection(conn);
154 }
155#endif
156#ifdef IB_SUPPORT
157 else if (!crStrcmp(protocol, "ib"))
158 {
159 cr_net.use_ib++;
160 crDebug("Calling crIBInit()");
161 crIBInit(cr_net.recv_list, cr_net.close_list, mtu);
162 crIBConnection(conn);
163 crDebug("Done Calling crIBInit()");
164 }
165#endif
166#ifdef HP_MULTICAST_SUPPORT
167 else if (!crStrcmp(protocol, "hpmc"))
168 {
169 cr_net.use_hpmc++;
170 crHPMCInit(cr_net.recv_list, cr_net.close_list, mtu);
171 crHPMCConnection(conn);
172 }
173#endif
174 else
175 {
176 crError("Unknown protocol: \"%s\"", protocol);
177 }
178}
179
180
181
182/**
183 * Establish a connection with a server.
184 * \param server the server to connect to, in the form
185 * "protocol://servername:port" where the port specifier
186 * is optional and if the protocol is missing it is assumed
187 * to be "tcpip".
188 * \param default_port the port to connect to, if port not specified in the
189 * server URL string.
190 * \param mtu desired maximum transmission unit size (in bytes)
191 * \param broker either 1 or 0 to indicate if connection is brokered through
192 * the mothership
193 */
194CRConnection * crNetConnectToServer( const char *server, unsigned short default_port, int mtu, int broker
195#if defined(VBOX_WITH_CRHGSMI) && defined(IN_GUEST)
196 , struct VBOXUHGSMI *pHgsmi
197#endif
198)
199{
200 char hostname[4096], protocol[4096];
201 unsigned short port;
202 CRConnection *conn;
203
204 crDebug( "In crNetConnectToServer( \"%s\", port=%d, mtu=%d, broker=%d )",
205 server, default_port, mtu, broker );
206
207 CRASSERT( cr_net.initialized );
208
209 if (mtu < CR_MINIMUM_MTU)
210 {
211 crError( "You tried to connect to server \"%s\" with an mtu of %d, "
212 "but the minimum MTU is %d", server, mtu, CR_MINIMUM_MTU );
213 }
214
215 /* Tear the URL apart into relevant portions. */
216 if ( !crParseURL( server, protocol, hostname, &port, default_port ) ) {
217 crError( "Malformed URL: \"%s\"", server );
218 }
219
220 /* If the host name is "localhost" replace it with the _real_ name
221 * of the localhost. If we don't do this, there seems to be
222 * confusion in the mothership as to whether or not "localhost" and
223 * "foo.bar.com" are the same machine.
224 */
225 if (crStrcmp(hostname, "localhost") == 0) {
226 int rv = crGetHostname(hostname, 4096);
227 CRASSERT(rv == 0);
228 (void) rv;
229 }
230
231 /* XXX why is this here??? I think it could be moved into the
232 * crTeacConnection() function with no problem. I.e. change the
233 * connection's port, teac_rank and tcscomm_rank there. (BrianP)
234 */
235 if ( !crStrcmp( protocol, "quadrics" ) ||
236 !crStrcmp( protocol, "quadrics-tcscomm" ) ) {
237 /* For Quadrics protocols, treat "port" as "rank" */
238 if ( port > CR_QUADRICS_HIGHEST_RANK ) {
239 crWarning( "Invalid crserver rank, %d, defaulting to %d\n",
240 port, CR_QUADRICS_LOWEST_RANK );
241 port = CR_QUADRICS_LOWEST_RANK;
242 }
243 }
244 crDebug( "Connecting to %s on port %d, with protocol %s",
245 hostname, port, protocol );
246
247#ifdef SDP_SUPPORT
248 /* This makes me ill, but we need to "fix" the hostname for sdp. MCH */
249 if (!crStrcmp(protocol, "sdp")) {
250 char* temp;
251 temp = strtok(hostname, ".");
252 crStrcat(temp, crGetSDPHostnameSuffix());
253 crStrcpy(hostname, temp);
254 crDebug("SDP rename hostname: %s", hostname);
255 }
256#endif
257
258 conn = (CRConnection *) crCalloc( sizeof(*conn) );
259 if (!conn)
260 return NULL;
261
262 /* init the non-zero fields */
263 conn->type = CR_NO_CONNECTION; /* we don't know yet */
264 conn->recv_credits = CR_INITIAL_RECV_CREDITS;
265 conn->hostname = crStrdup( hostname );
266 conn->port = port;
267 conn->mtu = mtu;
268 conn->buffer_size = mtu;
269 conn->broker = broker;
270 conn->endianness = crDetermineEndianness();
271 /* XXX why are these here??? Move them into the crTeacConnection()
272 * and crTcscommConnection() functions.
273 */
274 conn->teac_id = -1;
275 conn->teac_rank = port;
276 conn->tcscomm_id = -1;
277 conn->tcscomm_rank = port;
278
279 crInitMessageList(&conn->messageList);
280
281 /* now, just dispatch to the appropriate protocol's initialization functions. */
282 InitConnection(conn, protocol, mtu
283#if defined(VBOX_WITH_CRHGSMI) && defined(IN_GUEST)
284 , pHgsmi
285#endif
286 );
287
288 if (!crNetConnect( conn ))
289 {
290 crDebug("crNetConnectToServer() failed, freeing the connection");
291 #ifdef CHROMIUM_THREADSAFE
292 crFreeMutex( &conn->messageList.lock );
293 #endif
294 conn->Disconnect(conn);
295 crFree( conn );
296 return NULL;
297 }
298
299 crDebug( "Done connecting to %s (swapping=%d)", server, conn->swap );
300 return conn;
301}
302
303/**
304 * Send a message to the receiver that another connection is needed.
305 * We send a CR_MESSAGE_NEWCLIENT packet, then call crNetServerConnect.
306 */
307void crNetNewClient( CRNetServer *ns
308#if defined(VBOX_WITH_CRHGSMI) && defined(IN_GUEST)
309 , struct VBOXUHGSMI *pHgsmi
310#endif
311)
312{
313 /*
314 unsigned int len = sizeof(CRMessageNewClient);
315 CRMessageNewClient msg;
316
317 CRASSERT( conn );
318
319 if (conn->swap)
320 msg.header.type = (CRMessageType) SWAP32(CR_MESSAGE_NEWCLIENT);
321 else
322 msg.header.type = CR_MESSAGE_NEWCLIENT;
323
324 crNetSend( conn, NULL, &msg, len );
325 */
326
327 crNetServerConnect( ns
328#if defined(VBOX_WITH_CRHGSMI) && defined(IN_GUEST)
329 , pHgsmi
330#endif
331);
332}
333
334
335/**
336 * Accept a connection from a client.
337 * \param protocol the protocol to use (such as "tcpip" or "gm")
338 * \param hostname optional hostname of the expected client (may be NULL)
339 * \param port number of the port to accept on
340 * \param mtu maximum transmission unit
341 * \param broker either 1 or 0 to indicate if connection is brokered through
342 * the mothership
343 * \return new CRConnection object, or NULL
344 */
345CRConnection *
346crNetAcceptClient( const char *protocol, const char *hostname,
347 unsigned short port, unsigned int mtu, int broker )
348{
349 CRConnection *conn;
350
351 CRASSERT( cr_net.initialized );
352
353 conn = (CRConnection *) crCalloc( sizeof( *conn ) );
354 if (!conn)
355 return NULL;
356
357 /* init the non-zero fields */
358 conn->type = CR_NO_CONNECTION; /* we don't know yet */
359 conn->recv_credits = CR_INITIAL_RECV_CREDITS;
360 conn->port = port;
361 conn->mtu = mtu;
362 conn->buffer_size = mtu;
363 conn->broker = broker;
364 conn->endianness = crDetermineEndianness();
365 conn->teac_id = -1;
366 conn->teac_rank = -1;
367 conn->tcscomm_id = -1;
368 conn->tcscomm_rank = -1;
369
370 crInitMessageList(&conn->messageList);
371
372 /* now, just dispatch to the appropriate protocol's initialization functions. */
373 crDebug("In crNetAcceptClient( protocol=\"%s\" port=%d mtu=%d )",
374 protocol, (int) port, (int) mtu);
375
376 /* special case */
377 if ( !crStrncmp( protocol, "file", crStrlen( "file" ) ) ||
378 !crStrncmp( protocol, "swapfile", crStrlen( "swapfile" ) ) )
379 {
380 char filename[4096];
381 char protocol_only[4096];
382
383 cr_net.use_file++;
384 if (!crParseURL(protocol, protocol_only, filename, NULL, 0))
385 {
386 crError( "Malformed URL: \"%s\"", protocol );
387 }
388 conn->hostname = crStrdup( filename );
389
390 /* call the protocol-specific init routines */ // ktd (add)
391 InitConnection(conn, protocol_only, mtu
392#if defined(VBOX_WITH_CRHGSMI) && defined(IN_GUEST)
393 , NULL
394#endif
395 ); // ktd (add)
396 }
397 else {
398 /* call the protocol-specific init routines */
399 InitConnection(conn, protocol, mtu
400#if defined(VBOX_WITH_CRHGSMI) && defined(IN_GUEST)
401 , NULL
402#endif
403 );
404 }
405
406 crNetAccept( conn, hostname, port );
407 return conn;
408}
409
410
411/**
412 * Close and free given connection.
413 */
414void
415crNetFreeConnection(CRConnection *conn)
416{
417 conn->Disconnect(conn);
418 crFree( conn->hostname );
419 #ifdef CHROMIUM_THREADSAFE
420 crFreeMutex( &conn->messageList.lock );
421 #endif
422 crFree(conn);
423}
424
425
426extern void __getHostInfo();
427/**
428 * Start the ball rolling. give functions to handle incoming traffic
429 * (usually placing blocks on a queue), and a handler for dropped
430 * connections.
431 */
432void crNetInit( CRNetReceiveFunc recvFunc, CRNetCloseFunc closeFunc )
433{
434 CRNetReceiveFuncList *rfl;
435 CRNetCloseFuncList *cfl;
436
437 if ( cr_net.initialized )
438 {
439 /*crDebug( "Networking already initialized!" );*/
440 }
441 else
442 {
443#ifdef WINDOWS
444 /* @todo: do we actually need that WSA stuff with VBox at all? */
445 WORD wVersionRequested = MAKEWORD(2, 0);
446 WSADATA wsaData;
447 int err;
448
449 err = WSAStartup(wVersionRequested, &wsaData);
450 if (err != 0)
451 crError("Couldn't initialize sockets on WINDOWS");
452# ifndef VBOX
453 //reinit hostname for debug messages as it's incorrect before WSAStartup gets called
454 __getHostInfo();
455# endif
456#endif
457
458 cr_net.use_gm = 0;
459 cr_net.use_udp = 0;
460 cr_net.use_tcpip = 0;
461 cr_net.use_sdp = 0;
462 cr_net.use_tcscomm = 0;
463 cr_net.use_teac = 0;
464 cr_net.use_file = 0;
465 cr_net.use_hgcm = 0;
466 cr_net.num_clients = 0;
467#ifdef CHROMIUM_THREADSAFE
468 crInitMutex(&cr_net.mutex);
469#endif
470
471 cr_net.initialized = 1;
472 cr_net.recv_list = NULL;
473 cr_net.close_list = NULL;
474 }
475
476 if (recvFunc != NULL)
477 {
478 /* check if function is already in the list */
479 for (rfl = cr_net.recv_list ; rfl ; rfl = rfl->next )
480 {
481 if (rfl->recv == recvFunc)
482 {
483 /* we've already seen this function -- do nothing */
484 break;
485 }
486 }
487 /* not in list, so insert at the head */
488 if (!rfl)
489 {
490 rfl = (CRNetReceiveFuncList *) crAlloc( sizeof (*rfl ));
491 rfl->recv = recvFunc;
492 rfl->next = cr_net.recv_list;
493 cr_net.recv_list = rfl;
494 }
495 }
496
497 if (closeFunc != NULL)
498 {
499 /* check if function is already in the list */
500 for (cfl = cr_net.close_list ; cfl ; cfl = cfl->next )
501 {
502 if (cfl->close == closeFunc)
503 {
504 /* we've already seen this function -- do nothing */
505 break;
506 }
507 }
508 /* not in list, so insert at the head */
509 if (!cfl)
510 {
511 cfl = (CRNetCloseFuncList *) crAlloc( sizeof (*cfl ));
512 cfl->close = closeFunc;
513 cfl->next = cr_net.close_list;
514 cr_net.close_list = cfl;
515 }
516 }
517}
518
519/* Free up stuff */
520void crNetTearDown()
521{
522 CRNetReceiveFuncList *rfl;
523 CRNetCloseFuncList *cfl;
524 void *tmp;
525
526 if (!cr_net.initialized) return;
527
528#ifdef CHROMIUM_THREADSAFE
529 crLockMutex(&cr_net.mutex);
530#endif
531
532 /* Note, other protocols used by chromium should free up stuff too,
533 * but VBox doesn't use them, so no other checks.
534 */
535 if (cr_net.use_hgcm)
536 crVBoxHGCMTearDown();
537
538 for (rfl = cr_net.recv_list ; rfl ; rfl = (CRNetReceiveFuncList *) tmp )
539 {
540 tmp = rfl->next;
541 crFree(rfl);
542 }
543
544 for (cfl = cr_net.close_list ; cfl ; cfl = (CRNetCloseFuncList *) tmp )
545 {
546 tmp = cfl->next;
547 crFree(cfl);
548 }
549
550 cr_net.initialized = 0;
551
552#ifdef CHROMIUM_THREADSAFE
553 crUnlockMutex(&cr_net.mutex);
554 crFreeMutex(&cr_net.mutex);
555#endif
556}
557
558CRConnection** crNetDump( int* num )
559{
560 CRConnection **c;
561
562 c = crTCPIPDump( num );
563 if ( c ) return c;
564
565 c = crDevnullDump( num );
566 if ( c ) return c;
567
568 c = crFileDump( num );
569 if ( c ) return c;
570
571#ifdef VBOX_WITH_HGCM
572 c = crVBoxHGCMDump( num );
573 if ( c ) return c;
574#endif
575#ifdef GM_SUPPORT
576 c = crGmDump( num );
577 if ( c ) return c;
578#endif
579#ifdef IB_SUPPORT
580 c = crIBDump( num );
581 if ( c ) return c;
582#endif
583#ifdef SDP_SUPPORT
584 c = crSDPDump( num );
585 if ( c ) return c;
586#endif
587
588 *num = 0;
589 return NULL;
590}
591
592
593/*
594 * Allocate a network data buffer. The size will be the mtu size specified
595 * earlier to crNetConnectToServer() or crNetAcceptClient().
596 *
597 * Buffers that will eventually be transmitted on a connection
598 * *must* be allocated using this interface. This way, we can
599 * automatically pin memory and tag blocks, and we can also use
600 * our own buffer pool management.
601 */
602void *crNetAlloc( CRConnection *conn )
603{
604 CRASSERT( conn );
605 return conn->Alloc( conn );
606}
607
608
609/**
610 * This returns a buffer (which was obtained from crNetAlloc()) back
611 * to the network layer so that it may be reused.
612 */
613void crNetFree( CRConnection *conn, void *buf )
614{
615 conn->Free( conn, buf );
616}
617
618
619void
620crInitMessageList(CRMessageList *list)
621{
622 list->head = list->tail = NULL;
623 list->numMessages = 0;
624#ifdef CHROMIUM_THREADSAFE
625 crInitMutex(&list->lock);
626 crInitCondition(&list->nonEmpty);
627#endif
628}
629
630
631/**
632 * Add a message node to the end of the message list.
633 * \param list the message list
634 * \param msg points to start of message buffer
635 * \param len length of message, in bytes
636 * \param conn connection associated with message (may be NULL)
637 */
638void
639crEnqueueMessage(CRMessageList *list, CRMessage *msg, unsigned int len,
640 CRConnection *conn)
641{
642 CRMessageListNode *node;
643
644#ifdef CHROMIUM_THREADSAFE
645 crLockMutex(&list->lock);
646#endif
647
648 node = (CRMessageListNode *) crAlloc(sizeof(CRMessageListNode));
649 node->mesg = msg;
650 node->len = len;
651 node->conn = conn;
652 node->next = NULL;
653
654 /* insert at tail */
655 if (list->tail)
656 list->tail->next = node;
657 else
658 list->head = node;
659 list->tail = node;
660
661 list->numMessages++;
662
663#ifdef CHROMIUM_THREADSAFE
664 crSignalCondition(&list->nonEmpty);
665 crUnlockMutex(&list->lock);
666#endif
667}
668
669
670/**
671 * Remove first message node from message list and return it.
672 * Don't block.
673 * \return 1 if message was dequeued, 0 otherwise.
674 */
675static int
676crDequeueMessageNoBlock(CRMessageList *list, CRMessage **msg,
677 unsigned int *len, CRConnection **conn)
678{
679 int retval;
680
681#ifdef CHROMIUM_THREADSAFE
682 crLockMutex(&list->lock);
683#endif
684
685 if (list->head) {
686 CRMessageListNode *node = list->head;
687
688 /* unlink the node */
689 list->head = node->next;
690 if (!list->head) {
691 /* empty list */
692 list->tail = NULL;
693 }
694
695 *msg = node->mesg;
696 *len = node->len;
697 if (conn)
698 *conn = node->conn;
699
700 list->numMessages--;
701
702 crFree(node);
703 retval = 1;
704 }
705 else {
706 *msg = NULL;
707 *len = 0;
708 retval = 0;
709 }
710
711#ifdef CHROMIUM_THREADSAFE
712 crUnlockMutex(&list->lock);
713#endif
714
715 return retval;
716}
717
718
719/**
720 * Remove message from tail of list. Block until non-empty if needed.
721 * \param list the message list
722 * \param msg returns start of message
723 * \param len returns message length, in bytes
724 * \param conn returns connection associated with message (may be NULL)
725 */
726void
727crDequeueMessage(CRMessageList *list, CRMessage **msg, unsigned int *len,
728 CRConnection **conn)
729{
730 CRMessageListNode *node;
731
732#ifdef CHROMIUM_THREADSAFE
733 crLockMutex(&list->lock);
734#endif
735
736#ifdef CHROMIUM_THREADSAFE
737 while (!list->head) {
738 crWaitCondition(&list->nonEmpty, &list->lock);
739 }
740#else
741 CRASSERT(list->head);
742#endif
743
744 node = list->head;
745
746 /* unlink the node */
747 list->head = node->next;
748 if (!list->head) {
749 /* empty list */
750 list->tail = NULL;
751 }
752
753 *msg = node->mesg;
754 CRASSERT((*msg)->header.type);
755 *len = node->len;
756 if (conn)
757 *conn = node->conn;
758
759 list->numMessages--;
760
761 crFree(node);
762
763#ifdef CHROMIUM_THREADSAFE
764 crUnlockMutex(&list->lock);
765#endif
766}
767
768
769
770/**
771 * Send a set of commands on a connection. Pretty straightforward, just
772 * error checking, byte counting, and a dispatch to the protocol's
773 * "send" implementation.
774 * The payload will be prefixed by a 4-byte length field.
775 *
776 * \param conn the network connection
777 * \param bufp if non-null the buffer was provided by the network layer
778 * and will be returned to the 'free' pool after it's sent.
779 * \param start points to first byte to send, which must point to a CRMessage
780 * object!
781 * \param len number of bytes to send
782 */
783void
784crNetSend(CRConnection *conn, void **bufp, const void *start, unsigned int len)
785{
786 CRMessage *msg = (CRMessage *) start;
787
788 CRASSERT( conn );
789 CRASSERT( len > 0 );
790 if ( bufp ) {
791 /* The region from [start .. start + len - 1] must lie inside the
792 * buffer pointed to by *bufp.
793 */
794 CRASSERT( start >= *bufp );
795 CRASSERT( (unsigned char *) start + len <=
796 (unsigned char *) *bufp + conn->buffer_size );
797 }
798
799#ifdef DEBUG
800 if ( conn->send_credits > CR_INITIAL_RECV_CREDITS )
801 {
802 crError( "crNetSend: send_credits=%u, looks like there is a leak (max=%u)",
803 conn->send_credits, CR_INITIAL_RECV_CREDITS );
804 }
805#endif
806
807 conn->total_bytes_sent += len;
808
809 msg->header.conn_id = conn->id;
810 conn->Send( conn, bufp, start, len );
811}
812
813
814/**
815 * Like crNetSend(), but the network layer is free to discard the data
816 * if something goes wrong. In particular, the UDP layer might discard
817 * the data in the event of transmission errors.
818 */
819void crNetBarf( CRConnection *conn, void **bufp,
820 const void *start, unsigned int len )
821{
822 CRMessage *msg = (CRMessage *) start;
823 CRASSERT( conn );
824 CRASSERT( len > 0 );
825 CRASSERT( conn->Barf );
826 if ( bufp ) {
827 CRASSERT( start >= *bufp );
828 CRASSERT( (unsigned char *) start + len <=
829 (unsigned char *) *bufp + conn->buffer_size );
830 }
831
832#ifdef DEBUG
833 if ( conn->send_credits > CR_INITIAL_RECV_CREDITS )
834 {
835 crError( "crNetBarf: send_credits=%u, looks like there is a "
836 "leak (max=%u)", conn->send_credits,
837 CR_INITIAL_RECV_CREDITS );
838 }
839#endif
840
841 conn->total_bytes_sent += len;
842
843 msg->header.conn_id = conn->id;
844 conn->Barf( conn, bufp, start, len );
845}
846
847
848/**
849 * Send a block of bytes across the connection without any sort of
850 * header/length information.
851 * \param conn the network connection
852 * \param buf points to first byte to send
853 * \param len number of bytes to send
854 */
855void crNetSendExact( CRConnection *conn, const void *buf, unsigned int len )
856{
857 CRASSERT(conn->SendExact);
858 conn->SendExact( conn, buf, len );
859}
860
861
862/**
863 * Connect to a server, as specified by the 'name' and 'buffer_size' fields
864 * of the CRNetServer parameter.
865 * When done, the CrNetServer's conn field will be initialized.
866 */
867void crNetServerConnect( CRNetServer *ns
868#if defined(VBOX_WITH_CRHGSMI) && defined(IN_GUEST)
869 , struct VBOXUHGSMI *pHgsmi
870#endif
871)
872{
873 ns->conn = crNetConnectToServer( ns->name, DEFAULT_SERVER_PORT,
874 ns->buffer_size, 0
875#if defined(VBOX_WITH_CRHGSMI) && defined(IN_GUEST)
876 , pHgsmi
877#endif
878 );
879}
880
881/**
882 * Actually set up the specified connection.
883 * Apparently, this is only called from the crNetConnectToServer function.
884 */
885int crNetConnect( CRConnection *conn )
886{
887 return conn->Connect( conn );
888}
889
890
891/**
892 * Tear down a network connection (close the socket, etc).
893 */
894void crNetDisconnect( CRConnection *conn )
895{
896 conn->Disconnect( conn );
897 crFree( conn->hostname );
898#ifdef CHROMIUM_THREADSAFE
899 crFreeMutex( &conn->messageList.lock );
900#endif
901 crFree( conn );
902}
903
904
905/**
906 * Actually set up the specified connection.
907 * Apparently, this is only called from the crNetConnectToServer function.
908 */
909void crNetAccept( CRConnection *conn, const char *hostname, unsigned short port )
910{
911 conn->Accept( conn, hostname, port );
912}
913
914
915/**
916 * Do a blocking receive on a particular connection. This only
917 * really works for TCPIP, but it's really only used (right now) by
918 * the mothership client library.
919 * Read exactly the number of bytes specified (no headers/prefixes).
920 */
921void crNetSingleRecv( CRConnection *conn, void *buf, unsigned int len )
922{
923 if (conn->type != CR_TCPIP)
924 {
925 crError( "Can't do a crNetSingleReceive on anything other than TCPIP." );
926 }
927 conn->Recv( conn, buf, len );
928}
929
930
931/**
932 * Receive a chunk of a CR_MESSAGE_MULTI_BODY/TAIL transmission.
933 * \param conn the network connection
934 * \param msg the incoming multi-part message
935 * \param len number of bytes in the message
936 */
937static void
938crNetRecvMulti( CRConnection *conn, CRMessageMulti *msg, unsigned int len )
939{
940 CRMultiBuffer *multi = &(conn->multi);
941 unsigned char *src, *dst;
942
943 CRASSERT( len > sizeof(*msg) );
944 len -= sizeof(*msg);
945
946 /* Check if there's enough room in the multi-buffer to append 'len' bytes */
947 if ( len + multi->len > multi->max )
948 {
949 if ( multi->max == 0 )
950 {
951 multi->len = conn->sizeof_buffer_header;
952 multi->max = 8192; /* arbitrary initial size */
953 }
954 /* grow the buffer by 2x until it's big enough */
955 while ( len + multi->len > multi->max )
956 {
957 multi->max <<= 1;
958 }
959 crRealloc( &multi->buf, multi->max );
960 }
961
962 dst = (unsigned char *) multi->buf + multi->len;
963 src = (unsigned char *) msg + sizeof(*msg);
964 crMemcpy( dst, src, len );
965 multi->len += len;
966
967 if (msg->header.type == CR_MESSAGE_MULTI_TAIL)
968 {
969 /* OK, we've collected the last chunk of the multi-part message */
970 conn->HandleNewMessage(
971 conn,
972 (CRMessage *) (((char *) multi->buf) + conn->sizeof_buffer_header),
973 multi->len - conn->sizeof_buffer_header );
974
975 /* clean this up before calling the user */
976 multi->buf = NULL;
977 multi->len = 0;
978 multi->max = 0;
979 }
980
981 /* Don't do this too early! */
982 conn->InstantReclaim( conn, (CRMessage *) msg );
983}
984
985
986/**
987 * Increment the connection's send_credits by msg->credits.
988 */
989static void
990crNetRecvFlowControl( CRConnection *conn, CRMessageFlowControl *msg,
991 unsigned int len )
992{
993 CRASSERT( len == sizeof(CRMessageFlowControl) );
994 conn->send_credits += (conn->swap ? SWAP32(msg->credits) : msg->credits);
995 conn->InstantReclaim( conn, (CRMessage *) msg );
996}
997
998#ifdef IN_GUEST
999/**
1000 * Called by the main receive function when we get a CR_MESSAGE_WRITEBACK
1001 * message. Writeback is used to implement glGet*() functions.
1002 */
1003static void
1004crNetRecvWriteback( CRMessageWriteback *wb )
1005{
1006 int *writeback;
1007 crMemcpy( &writeback, &(wb->writeback_ptr), sizeof( writeback ) );
1008 (*writeback)--;
1009}
1010
1011
1012/**
1013 * Called by the main receive function when we get a CR_MESSAGE_READBACK
1014 * message. Used to implement glGet*() functions.
1015 */
1016static void
1017crNetRecvReadback( CRMessageReadback *rb, unsigned int len )
1018{
1019 /* minus the header, the destination pointer,
1020 * *and* the implicit writeback pointer at the head. */
1021
1022 int payload_len = len - sizeof( *rb );
1023 int *writeback;
1024 void *dest_ptr;
1025 crMemcpy( &writeback, &(rb->writeback_ptr), sizeof( writeback ) );
1026 crMemcpy( &dest_ptr, &(rb->readback_ptr), sizeof( dest_ptr ) );
1027
1028 (*writeback)--;
1029 crMemcpy( dest_ptr, ((char *)rb) + sizeof(*rb), payload_len );
1030}
1031#endif
1032
1033/**
1034 * This is used by the SPUs that do packing (such as Pack, Tilesort and
1035 * Replicate) to process ReadPixels messages. We can't call this directly
1036 * from the message loop below because the SPU's have other housekeeping
1037 * to do for ReadPixels (such as decrementing counters).
1038 */
1039void
1040crNetRecvReadPixels( const CRMessageReadPixels *rp, unsigned int len )
1041{
1042 int payload_len = len - sizeof( *rp );
1043 char *dest_ptr;
1044 const char *src_ptr = (const char *) rp + sizeof(*rp);
1045
1046 /* set dest_ptr value */
1047 crMemcpy( &(dest_ptr), &(rp->pixels), sizeof(dest_ptr));
1048
1049 /* store pixel data in app's memory */
1050 if (rp->alignment == 1 &&
1051 rp->skipRows == 0 &&
1052 rp->skipPixels == 0 &&
1053 (rp->rowLength == 0 || rp->rowLength == rp->width)) {
1054 /* no special packing is needed */
1055 crMemcpy( dest_ptr, src_ptr, payload_len );
1056 }
1057 else {
1058 /* need special packing */
1059 CRPixelPackState packing;
1060 packing.skipRows = rp->skipRows;
1061 packing.skipPixels = rp->skipPixels;
1062 packing.alignment = rp->alignment;
1063 packing.rowLength = rp->rowLength;
1064 packing.imageHeight = 0;
1065 packing.skipImages = 0;
1066 packing.swapBytes = GL_FALSE;
1067 packing.psLSBFirst = GL_FALSE;
1068 crPixelCopy2D( rp->width, rp->height,
1069 dest_ptr, rp->format, rp->type, &packing,
1070 src_ptr, rp->format, rp->type, /*unpacking*/NULL);
1071 }
1072}
1073
1074
1075
1076/**
1077 * If an incoming message is not consumed by any of the connection's
1078 * receive callbacks, this function will get called.
1079 *
1080 * XXX Make this function static???
1081 */
1082void
1083crNetDefaultRecv( CRConnection *conn, CRMessage *msg, unsigned int len )
1084{
1085 CRMessage *pRealMsg;
1086
1087 pRealMsg = (msg->header.type!=CR_MESSAGE_REDIR_PTR) ? msg : (CRMessage*) msg->redirptr.pMessage;
1088
1089 switch (pRealMsg->header.type)
1090 {
1091 case CR_MESSAGE_GATHER:
1092 break;
1093 case CR_MESSAGE_MULTI_BODY:
1094 case CR_MESSAGE_MULTI_TAIL:
1095 crNetRecvMulti( conn, &(pRealMsg->multi), len );
1096 return;
1097 case CR_MESSAGE_FLOW_CONTROL:
1098 crNetRecvFlowControl( conn, &(pRealMsg->flowControl), len );
1099 return;
1100 case CR_MESSAGE_OPCODES:
1101 case CR_MESSAGE_OOB:
1102 {
1103 /*CRMessageOpcodes *ops = (CRMessageOpcodes *) msg;
1104 *unsigned char *data_ptr = (unsigned char *) ops + sizeof( *ops) + ((ops->numOpcodes + 3 ) & ~0x03);
1105 *crDebugOpcodes( stdout, data_ptr-1, ops->numOpcodes ); */
1106 }
1107 break;
1108 case CR_MESSAGE_READ_PIXELS:
1109 WARN(( "Can't handle read pixels" ));
1110 return;
1111 case CR_MESSAGE_WRITEBACK:
1112#ifdef IN_GUEST
1113 crNetRecvWriteback( &(pRealMsg->writeback) );
1114#else
1115 WARN(("CR_MESSAGE_WRITEBACK not expected\n"));
1116#endif
1117 return;
1118 case CR_MESSAGE_READBACK:
1119#ifdef IN_GUEST
1120 crNetRecvReadback( &(pRealMsg->readback), len );
1121#else
1122 WARN(("CR_MESSAGE_READBACK not expected\n"));
1123#endif
1124 return;
1125 case CR_MESSAGE_CRUT:
1126 /* nothing */
1127 break;
1128 default:
1129 /* We can end up here if anything strange happens in
1130 * the GM layer. In particular, if the user tries to
1131 * send unpinned memory over GM it gets sent as all
1132 * 0xAA instead. This can happen when a program exits
1133 * ungracefully, so the GM is still DMAing memory as
1134 * it is disappearing out from under it. We can also
1135 * end up here if somebody adds a message type, and
1136 * doesn't put it in the above case block. That has
1137 * an obvious fix. */
1138 {
1139 char string[128];
1140 crBytesToString( string, sizeof(string), msg, len );
1141 WARN(("crNetDefaultRecv: received a bad message: type=%d buf=[%s]\n"
1142 "Did you add a new message type and forget to tell "
1143 "crNetDefaultRecv() about it?\n",
1144 msg->header.type, string ));
1145 }
1146 }
1147
1148 /* If we make it this far, it's not a special message, so append it to
1149 * the end of the connection's list of received messages.
1150 */
1151 crEnqueueMessage(&conn->messageList, msg, len, conn);
1152}
1153
1154
1155/**
1156 * Default handler for receiving data. Called via crNetRecv().
1157 * Typically, the various implementations of the network layer call this.
1158 * \param msg this is the address of the message (of <len> bytes) the
1159 * first part of which is a CRMessage union.
1160 */
1161void
1162crNetDispatchMessage( CRNetReceiveFuncList *rfl, CRConnection *conn,
1163 CRMessage *msg, unsigned int len )
1164{
1165 for ( ; rfl ; rfl = rfl->next)
1166 {
1167 if (rfl->recv( conn, msg, len ))
1168 {
1169 /* Message was consumed by somebody (maybe a SPU).
1170 * All done.
1171 */
1172 return;
1173 }
1174 }
1175 /* Append the message to the connection's message list. It'll be
1176 * consumed later (by crNetPeekMessage or crNetGetMessage and
1177 * then freed with a call to crNetFree()). At this point, the buffer
1178 * *must* have been allocated with crNetAlloc!
1179 */
1180 crNetDefaultRecv( conn, msg, len );
1181}
1182
1183
1184/**
1185 * Return number of messages queued up on the given connection.
1186 */
1187int
1188crNetNumMessages(CRConnection *conn)
1189{
1190 return conn->messageList.numMessages;
1191}
1192
1193
1194/**
1195 * Get the next message in the connection's message list. These are
1196 * message that have already been received. We do not try to read more
1197 * bytes from the network connection.
1198 *
1199 * The crNetFree() function should be called when finished with the message!
1200 *
1201 * \param conn the network connection
1202 * \param message returns a pointer to the next message
1203 * \return length of message (header + payload, in bytes)
1204 */
1205unsigned int
1206crNetPeekMessage( CRConnection *conn, CRMessage **message )
1207{
1208 unsigned int len;
1209 CRConnection *dummyConn = NULL;
1210 if (crDequeueMessageNoBlock(&conn->messageList, message, &len, &dummyConn))
1211 return len;
1212 else
1213 return 0;
1214}
1215
1216
1217/**
1218 * Get the next message from the given network connection. If there isn't
1219 * one already in the linked list of received messages, call crNetRecv()
1220 * until we get something.
1221 *
1222 * \param message returns pointer to the message
1223 * \return total length of message (header + payload, in bytes)
1224 */
1225unsigned int
1226crNetGetMessage( CRConnection *conn, CRMessage **message )
1227{
1228 /* Keep getting work to do */
1229 for (;;)
1230 {
1231 int len = crNetPeekMessage( conn, message );
1232 if (len)
1233 return len;
1234 crNetRecv(
1235#if defined(VBOX_WITH_CRHGSMI) && defined(IN_GUEST)
1236 conn
1237#endif
1238 );
1239 }
1240
1241#if !defined(WINDOWS) && !defined(IRIX) && !defined(IRIX64)
1242 /* silence compiler */
1243 return 0;
1244#endif
1245}
1246
1247
1248/**
1249 * Read a \n-terminated string from a connection. Replace the \n with \0.
1250 * Useful for reading from the mothership.
1251 * \note This is an extremely inefficient way to read a string!
1252 *
1253 * \param conn the network connection
1254 * \param buf buffer in which to place results
1255 */
1256void crNetReadline( CRConnection *conn, void *buf )
1257{
1258 char *temp, c;
1259
1260 if (!conn || conn->type == CR_NO_CONNECTION)
1261 return;
1262
1263 if (conn->type != CR_TCPIP)
1264 {
1265 crError( "Can't do a crNetReadline on anything other than TCPIP (%d).",conn->type );
1266 }
1267 temp = (char*)buf;
1268 for (;;)
1269 {
1270 conn->Recv( conn, &c, 1 );
1271 if (c == '\n')
1272 {
1273 *temp = '\0';
1274 return;
1275 }
1276 *(temp++) = c;
1277 }
1278}
1279
1280#ifdef IN_GUEST
1281uint32_t crNetHostCapsGet()
1282{
1283#ifdef VBOX_WITH_HGCM
1284 if ( cr_net.use_hgcm )
1285 return crVBoxHGCMHostCapsGet();
1286#endif
1287 WARN(("HostCaps supportted for HGCM only!"));
1288 return 0;
1289}
1290#endif
1291
1292/**
1293 * The big boy -- call this function to see (non-blocking) if there is
1294 * any pending work. If there is, the networking layer's "work received"
1295 * handler will be called, so this function only returns a flag. Work
1296 * is assumed to be placed on queues for processing by the handler.
1297 */
1298int crNetRecv(
1299#if defined(VBOX_WITH_CRHGSMI) && defined(IN_GUEST)
1300 CRConnection *conn
1301#endif
1302 )
1303{
1304 int found_work = 0;
1305
1306 if ( cr_net.use_tcpip )
1307 found_work += crTCPIPRecv();
1308#ifdef VBOX_WITH_HGCM
1309 if ( cr_net.use_hgcm )
1310 found_work += crVBoxHGCMRecv(
1311#if defined(VBOX_WITH_CRHGSMI) && defined(IN_GUEST)
1312 conn
1313#endif
1314 );
1315#endif
1316#ifdef SDP_SUPPORT
1317 if ( cr_net.use_sdp )
1318 found_work += crSDPRecv();
1319#endif
1320#ifdef IB_SUPPORT
1321 if ( cr_net.use_ib )
1322 found_work += crIBRecv();
1323#endif
1324 if ( cr_net.use_udp )
1325 found_work += crUDPTCPIPRecv();
1326
1327 if ( cr_net.use_file )
1328 found_work += crFileRecv();
1329
1330#ifdef GM_SUPPORT
1331 if ( cr_net.use_gm )
1332 found_work += crGmRecv();
1333#endif
1334
1335#ifdef TEAC_SUPPORT
1336 if ( cr_net.use_teac )
1337 found_work += crTeacRecv();
1338#endif
1339
1340#ifdef TCSCOMM_SUPPORT
1341 if ( cr_net.use_tcscomm )
1342 found_work += crTcscommRecv();
1343#endif
1344
1345 return found_work;
1346}
1347
1348
1349/**
1350 * Teac/TSComm only
1351 */
1352void
1353crNetSetRank( int my_rank )
1354{
1355 cr_net.my_rank = my_rank;
1356#ifdef TEAC_SUPPORT
1357 crTeacSetRank( cr_net.my_rank );
1358#endif
1359#ifdef TCSCOMM_SUPPORT
1360 crTcscommSetRank( cr_net.my_rank );
1361#endif
1362}
1363
1364/**
1365 * Teac/TSComm only
1366 */
1367void
1368crNetSetContextRange( int low_context, int high_context )
1369{
1370#ifdef TEAC_SUPPORT
1371 crTeacSetContextRange( low_context, high_context );
1372#endif
1373#ifdef TCSCOMM_SUPPORT
1374 crTcscommSetContextRange( low_context, high_context );
1375#endif
1376}
1377
1378/**
1379 * Teac/TSComm only
1380 */
1381void
1382crNetSetNodeRange( const char *low_node, const char *high_node )
1383{
1384#ifdef TEAC_SUPPORT
1385 crTeacSetNodeRange( low_node, high_node );
1386#endif
1387#ifdef TCSCOMM_SUPPORT
1388 crTcscommSetNodeRange( low_node, high_node );
1389#endif
1390}
1391
1392/**
1393 * Teac/TSComm only
1394 */
1395void
1396crNetSetKey( const unsigned char* key, const int keyLength )
1397{
1398#ifdef TEAC_SUPPORT
1399 crTeacSetKey( key, keyLength );
1400#endif
1401}
Note: See TracBrowser for help on using the repository browser.

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