1 /* -------------------------------------------------------------------------
2 * Project: GSocket (Generic Socket) for WX
4 * Authors: Guilhem Lavaux,
5 * Guillermo Rodriguez Garcia <guille@iies.es> (maintainer)
7 * Purpose: GSocket main mac file
9 * -------------------------------------------------------------------------
13 * PLEASE don't put C++ comments here - this is a C source file.
16 #ifndef __GSOCKET_STANDALONE__
18 #include "wx/platform.h"
21 #if wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__)
24 #include <CoreServices/CoreServices.h>
33 #include <MacHeaders.c>
34 #define OTUNIXERRORS 1
35 #include <OpenTransport.h>
36 #include <OpenTransportProviders.h>
37 #include <OpenTptInternet.h>
39 #if TARGET_CARBON && !defined(OTAssert)
40 #define OTAssert( str , cond ) /* does not exists in Carbon */
54 * INADDR_BROADCAST is identical to INADDR_NONE which is not defined
55 * on all unices. INADDR_BROADCAST should be fine to indicate an error.
57 #ifndef INADDR_BROADCAST
58 #define INADDR_BROADCAST 0xFFFFFFFFUL
61 #define INADDR_NONE INADDR_BROADCAST
64 #define INADDR_ANY 0x0UL
66 #ifndef __GSOCKET_STANDALONE__
68 #include "wx/mac/macnotfy.h"
69 #include "wx/mac/gsockmac.h"
70 #include "wx/gsocket.h"
77 #endif /* __GSOCKET_STANDALONE__ */
90 extern pascal void OTDebugStr(const char* str
);
95 InetSvcRef gInetSvcRef
= 0 ;
97 OTNotifyUPP gOTNotifierUPP
= NULL
;
99 OSStatus
DoNegotiateIPReuseAddrOption(EndpointRef ep
, Boolean enableReuseIPMode
);
101 /* Input: ep - endpointref on which to negotiate the option
102 enableReuseIPMode - desired option setting - true/false
103 Return: kOTNoError indicates that the option was successfully negotiated
104 OSStatus is an error if < 0, otherwise, the status field is
107 IMPORTANT NOTE: The endpoint is assumed to be in synchronous more, otherwise
108 this code will not function as desired
112 OSStatus
DoNegotiateIPReuseAddrOption(EndpointRef ep
, Boolean enableReuseIPMode
)
115 UInt8 buf
[kOTFourByteOptionSize
]; // define buffer for fourByte Option size
116 TOption
* opt
; // option ptr to make items easier to access
121 if (!OTIsSynchronous(ep
))
125 opt
= (TOption
*)buf
; // set option ptr to buffer
127 req
.opt
.len
= sizeof(buf
);
128 req
.flags
= T_NEGOTIATE
; // negotiate for option
131 ret
.opt
.maxlen
= kOTFourByteOptionSize
;
133 opt
->level
= INET_IP
; // dealing with an IP Level function
135 opt
->name
= kIP_REUSEADDR
;
137 opt
->name
= IP_REUSEADDR
;
139 opt
->len
= kOTFourByteOptionSize
;
141 *(UInt32
*)opt
->value
= enableReuseIPMode
; // set the desired option level, true or false
143 err
= OTOptionManagement(ep
, &req
, &ret
);
145 // if no error then return the option status value
146 if (err
== kOTNoError
)
148 if (opt
->status
!= T_SUCCESS
)
158 pascal void OTInetEventHandler(void*s
, OTEventCode event
, OTResult
, void *cookie
) ;
159 pascal void OTInetEventHandler(void*s
, OTEventCode event
, OTResult result
, void *cookie
)
162 GSocket
* sock
= (GSocket
*) s
;
164 if ( event
== kOTSyncIdleEvent
)
172 wxMacAddEvent( sock
->m_mac_events
, _GSocket_Internal_Proc
, event
, s
, wakeUp
) ;
178 static void SetDefaultEndpointModes(EndpointRef ep
, void *data
)
179 // This routine sets the supplied endpoint into the default
180 // mode used in this application. The specifics are:
181 // blocking, synchronous, and using synch idle events with
182 // the standard YieldingNotifier.
184 OSStatus junk
= kOTNoError
;
185 OTAssert ("SetDefaultEndpointModes:invalid ref", ep
!= kOTInvalidEndpointRef
) ;
186 junk
= OTSetAsynchronous(ep
);
187 OTAssert("SetDefaultEndpointModes: Could not set asynchronous", junk
== noErr
);
189 junk = OTSetBlocking(ep);
190 OTAssert("SetDefaultEndpointModes: Could not set blocking", junk == noErr);
191 junk = OTSetSynchronous(ep);
192 OTAssert("SetDefaultEndpointModes: Could not set synchronous", junk == noErr);
193 junk = OTSetBlocking(ep);
194 OTAssert("SetDefaultEndpointModes: Could not set blocking", junk == noErr);
196 junk
= OTInstallNotifier(ep
, gOTNotifierUPP
, data
);
197 OTAssert("SetDefaultEndpointModes: Could not install notifier", junk
== noErr
);
199 junk = OTUseSyncIdleEvents(ep, true);
200 OTAssert("SetDefaultEndpointModes: Could not use sync idle events", junk == noErr);
204 /* Global initialisers */
206 void GSocket_SetGUIFunctions(struct GSocketGUIFunctionsTable
*table
)
208 // do nothing, wxMac doesn't have wxBase-GUI separation yet
216 int GSocket_Verify_Inited() ;
217 int GSocket_Verify_Inited()
221 // Marc Newsam: added the clientcontext variable
222 // however, documentation is unclear how this works
223 OTClientContextPtr clientcontext
;
228 InitOpenTransportInContext(kInitOTForApplicationMask
, &clientcontext
);
230 gInetSvcRef
= OTOpenInternetServicesInContext(kDefaultInternetServicesPath
,
231 NULL
, &err
, clientcontext
);
236 InitOpenTransport() ;
238 gInetSvcRef
= OTOpenInternetServices(kDefaultInternetServicesPath
, NULL
, &err
);
240 if ( gInetSvcRef
== NULL
|| err
!= kOTNoError
)
242 OTAssert("Could not open Inet Services", err
== noErr
);
245 gOTNotifierUPP
= NewOTNotifyUPP( OTInetEventHandler
) ;
249 void GSocket_Cleanup()
251 if ( gOTInited
!= 0 )
253 if ( gInetSvcRef
!= NULL
)
254 OTCloseProvider( gInetSvcRef
);
256 CloseOpenTransportInContext( NULL
) ;
258 CloseOpenTransport() ;
260 if ( gOTNotifierUPP
)
261 DisposeOTNotifyUPP( gOTNotifierUPP
) ;
265 /* Constructors / Destructors for GSocket */
267 GSocket
*GSocket_new()
273 if ( GSocket_Verify_Inited() == FALSE
)
276 socket
= (GSocket
*)malloc(sizeof(GSocket
));
281 socket
->m_endpoint
= NULL
;
282 for (i
=0;i
<GSOCK_MAX_EVENT
;i
++)
284 socket
->m_cbacks
[i
] = NULL
;
286 socket
->m_detected
= 0;
287 socket
->m_local
= NULL
;
288 socket
->m_peer
= NULL
;
289 socket
->m_error
= GSOCK_NOERROR
;
290 socket
->m_server
= FALSE
;
291 socket
->m_stream
= TRUE
;
292 socket
->m_non_blocking
= FALSE
;
293 socket
->m_timeout
= 1*1000;
294 /* 10 sec * 1000 millisec */
295 socket
->m_takesEvents
= TRUE
;
296 socket
->m_mac_events
= wxMacGetNotifierTable() ;
300 void GSocket_destroy(GSocket
*socket
)
302 assert(socket
!= NULL
);
304 /* Check that the socket is really shutdowned */
305 if (socket
->m_endpoint
!= kOTInvalidEndpointRef
)
306 GSocket_Shutdown(socket
);
309 /* Destroy private addresses */
311 GAddress_destroy(socket
->m_local
);
314 GAddress_destroy(socket
->m_peer
);
316 /* Destroy the socket itself */
321 * Disallow further read/write operations on this socket, close
322 * the fd and disable all callbacks.
324 void GSocket_Shutdown(GSocket
*socket
)
329 assert(socket
!= NULL
);
331 /* If socket has been created, shutdown it */
332 if (socket
->m_endpoint
!= kOTInvalidEndpointRef
)
334 err
= OTSndOrderlyDisconnect( socket
->m_endpoint
) ;
335 if ( err
!= kOTNoError
)
339 err
= OTRcvOrderlyDisconnect( socket
->m_endpoint
) ;
340 err
= OTUnbind( socket
->m_endpoint
) ;
341 err
= OTCloseProvider( socket
->m_endpoint
) ;
342 socket
->m_endpoint
= kOTInvalidEndpointRef
;
345 /* Disable GUI callbacks */
346 for (evt
= 0; evt
< GSOCK_MAX_EVENT
; evt
++)
347 socket
->m_cbacks
[evt
] = NULL
;
349 socket
->m_detected
= 0;
350 _GSocket_Disable_Events(socket
);
351 wxMacRemoveAllNotifiersForData( wxMacGetNotifierTable() , socket
) ;
355 /* Address handling */
361 * Set or get the local or peer address for this socket. The 'set'
362 * functions return GSOCK_NOERROR on success, an error code otherwise.
363 * The 'get' functions return a pointer to a GAddress object on success,
364 * or NULL otherwise, in which case they set the error code of the
365 * corresponding GSocket.
368 * GSOCK_INVSOCK - the socket is not valid.
369 * GSOCK_INVADDR - the address is not valid.
371 GSocketError
GSocket_SetLocal(GSocket
*socket
, GAddress
*address
)
373 assert(socket
!= NULL
);
375 /* the socket must be initialized, or it must be a server */
376 if ((socket
->m_endpoint
!= kOTInvalidEndpointRef
&& !socket
->m_server
))
378 socket
->m_error
= GSOCK_INVSOCK
;
379 return GSOCK_INVSOCK
;
383 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
385 socket
->m_error
= GSOCK_INVADDR
;
386 return GSOCK_INVADDR
;
390 GAddress_destroy(socket
->m_local
);
392 socket
->m_local
= GAddress_copy(address
);
394 return GSOCK_NOERROR
;
397 GSocketError
GSocket_SetPeer(GSocket
*socket
, GAddress
*address
)
399 assert(socket
!= NULL
);
402 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
404 socket
->m_error
= GSOCK_INVADDR
;
405 return GSOCK_INVADDR
;
409 GAddress_destroy(socket
->m_peer
);
411 socket
->m_peer
= GAddress_copy(address
);
413 return GSOCK_NOERROR
;
416 GAddress
*GSocket_GetLocal(GSocket
*socket
)
418 GAddress
*address
= NULL
;
422 assert(socket
!= NULL
);
424 /* try to get it from the m_local var first */
426 return GAddress_copy(socket
->m_local
);
428 /* else, if the socket is initialized, try getsockname */
429 if (socket
->m_endpoint
== kOTInvalidEndpointRef
)
431 socket
->m_error
= GSOCK_INVSOCK
;
436 /* we do not support multihoming with this code at the moment
437 OTGetProtAddress will have to be used then - but we don't have a handy
438 method to use right now
441 InetInterfaceInfo info
;
442 OTInetGetInterfaceInfo(&info
, kDefaultInetInterface
);
443 loc
.fHost
= info
.fAddress
;
445 loc
.fAddressType
= AF_INET
;
448 /* got a valid address from getsockname, create a GAddress object */
449 address
= GAddress_new();
452 socket
->m_error
= GSOCK_MEMERR
;
456 err
= _GAddress_translate_from(address
, &loc
);
457 if (err
!= GSOCK_NOERROR
)
459 GAddress_destroy(address
);
460 socket
->m_error
= err
;
467 GAddress
*GSocket_GetPeer(GSocket
*socket
)
469 assert(socket
!= NULL
);
471 /* try to get it from the m_peer var */
473 return GAddress_copy(socket
->m_peer
);
478 /* Server specific parts */
480 /* GSocket_SetServer:
481 * Sets up this socket as a server. The local address must have been
482 * set with GSocket_SetLocal() before GSocket_SetServer() is called.
483 * Returns GSOCK_NOERROR on success, one of the following otherwise:
486 * GSOCK_INVSOCK - the socket is in use.
487 * GSOCK_INVADDR - the local address has not been set.
488 * GSOCK_IOERR - low-level error.
490 GSocketError
GSocket_SetServer(GSocket
*sck
)
494 /* must not be in use */
495 if (sck
->m_endpoint
!= kOTInvalidEndpointRef
)
497 sck
->m_error
= GSOCK_INVSOCK
;
498 return GSOCK_INVSOCK
;
501 /* the local addr must have been set */
504 sck
->m_error
= GSOCK_INVADDR
;
505 return GSOCK_INVADDR
;
508 /* Initialize all fields */
509 sck
->m_stream
= TRUE
;
510 sck
->m_server
= TRUE
;
511 sck
->m_oriented
= TRUE
;
515 /* Create the socket */
516 sck
->m_endpoint
= socket(sck
->m_local
->m_realfamily
, SOCK_STREAM
, 0);
517 socket_set_ref( sck
->m_endpoint
, (unsigned long) &gMacNetEvents
, (unsigned long) sck
) ;
518 if (sck
->m_endpoint
== kOTInvalidEndpointRef
)
520 sck
->m_error
= GSOCK_IOERR
;
524 ioctl(sck
->m_endpoint
, FIONBIO
, &arg
);
525 _GSocket_Enable_Events(sck
);
527 /* Bind to the local address,
528 * retrieve the actual address bound,
529 * and listen up to 5 connections.
531 if ((bind(sck
->m_endpoint
, sck
->m_local
->m_addr
, sck
->m_local
->m_len
) != 0) ||
532 (getsockname(sck
->m_endpoint
,
533 sck
->m_local
->m_addr
,
534 (SOCKLEN_T
*) &sck
->m_local
->m_len
) != 0) ||
535 (listen(sck
->m_endpoint
, 5) != 0))
537 close(sck
->m_endpoint
);
538 sck
->m_endpoint
= -1;
539 sck
->m_error
= GSOCK_IOERR
;
543 return GSOCK_NOERROR
;
546 /* GSocket_WaitConnection:
547 * Waits for an incoming client connection. Returns a pointer to
548 * a GSocket object, or NULL if there was an error, in which case
549 * the last error field will be updated for the calling GSocket.
551 * Error codes (set in the calling GSocket)
552 * GSOCK_INVSOCK - the socket is not valid or not a server.
553 * GSOCK_TIMEDOUT - timeout, no incoming connections.
554 * GSOCK_WOULDBLOCK - the call would block and the socket is nonblocking.
555 * GSOCK_MEMERR - couldn't allocate memory.
556 * GSOCK_IOERR - low-level error.
558 GSocket
*GSocket_WaitConnection(GSocket
*socket
)
560 GSocket
*connection
= NULL
;
562 assert(socket
!= NULL
);
564 /* Reenable CONNECTION events */
565 socket
->m_detected
&= ~GSOCK_CONNECTION_FLAG
;
567 /* If the socket has already been created, we exit immediately */
568 if (socket
->m_endpoint
== kOTInvalidEndpointRef
|| !socket
->m_server
)
570 socket
->m_error
= GSOCK_INVSOCK
;
574 /* Create a GSocket object for the new connection */
575 connection
= GSocket_new();
579 socket
->m_error
= GSOCK_MEMERR
;
583 /* Wait for a connection (with timeout) */
584 if (_GSocket_Input_Timeout(socket
) == GSOCK_TIMEDOUT
)
586 GSocket_destroy(connection
);
587 /* socket->m_error set by _GSocket_Input_Timeout */
593 connection
->m_endpoint
= accept(socket
->m_endpoint
, &from
, (SOCKLEN_T
*) &fromlen
);
596 if (connection
->m_endpoint
== kOTInvalidEndpointRef
)
598 if (errno
== EWOULDBLOCK
)
599 socket
->m_error
= GSOCK_WOULDBLOCK
;
601 socket
->m_error
= GSOCK_IOERR
;
603 GSocket_destroy(connection
);
607 /* Initialize all fields */
608 connection
->m_server
= FALSE
;
609 connection
->m_stream
= TRUE
;
610 connection
->m_oriented
= TRUE
;
612 /* Setup the peer address field */
613 connection
->m_peer
= GAddress_new();
614 if (!connection
->m_peer
)
616 GSocket_destroy(connection
);
617 socket
->m_error
= GSOCK_MEMERR
;
622 err
= _GAddress_translate_from(connection
->m_peer
, &from
, fromlen
);
623 if (err
!= GSOCK_NOERROR
)
625 GAddress_destroy(connection
->m_peer
);
626 GSocket_destroy(connection
);
627 socket
->m_error
= err
;
631 ioctl(connection
->m_endpoint
, FIONBIO
, &arg
);
633 _GSocket_Enable_Events(connection
);
638 /* Datagram sockets */
640 /* GSocket_SetNonOriented:
641 * Sets up this socket as a non-connection oriented (datagram) socket.
642 * Before using this function, the local address must have been set
643 * with GSocket_SetLocal(), or the call will fail. Returns GSOCK_NOERROR
644 * on success, or one of the following otherwise.
647 * GSOCK_INVSOCK - the socket is in use.
648 * GSOCK_INVADDR - the local address has not been set.
649 * GSOCK_IOERR - low-level error.
651 GSocketError
GSocket_SetNonOriented(GSocket
*sck
)
655 if (sck
->m_endpoint
!= kOTInvalidEndpointRef
)
657 sck
->m_error
= GSOCK_INVSOCK
;
658 return GSOCK_INVSOCK
;
663 sck
->m_error
= GSOCK_INVADDR
;
664 return GSOCK_INVADDR
;
667 /* Initialize all fields */
668 sck
->m_stream
= FALSE
;
669 sck
->m_server
= FALSE
;
670 sck
->m_oriented
= FALSE
;
672 /* Create the socket */
676 sck
->m_endpoint
= socket(sck
->m_local
->m_realfamily
, SOCK_DGRAM
, 0);
677 socket_set_ref( sck
->m_endpoint
, (unsigned long) &gMacNetEvents
, (unsigned long) sck
) ;
679 if (sck
->m_endpoint
== kOTInvalidEndpointRef
)
681 sck
->m_error
= GSOCK_IOERR
;
687 ioctl(sck
->m_endpoint
, FIONBIO
, &arg
);
689 _GSocket_Enable_Events(sck
);
691 /* Bind to the local address,
692 * and retrieve the actual address bound.
696 if ((bind(sck
->m_endpoint
, sck
->m_local
->m_addr
, sck
->m_local
->m_len
) != 0) ||
697 (getsockname(sck
->m_endpoint
,
698 sck
->m_local
->m_addr
,
699 (SOCKLEN_T
*) &sck
->m_local
->m_len
) != 0))
701 close(sck
->m_endpoint
);
702 sck
->m_endpoint
= -1;
703 sck
->m_error
= GSOCK_IOERR
;
707 return GSOCK_NOERROR
;
710 /* Client specific parts */
713 * For stream (connection oriented) sockets, GSocket_Connect() tries
714 * to establish a client connection to a server using the peer address
715 * as established with GSocket_SetPeer(). Returns GSOCK_NOERROR if the
716 * connection has been succesfully established, or one of the error
717 * codes listed below. Note that for nonblocking sockets, a return
718 * value of GSOCK_WOULDBLOCK doesn't mean a failure. The connection
719 * request can be completed later; you should use GSocket_Select()
720 * to poll for GSOCK_CONNECTION | GSOCK_LOST, or wait for the
721 * corresponding asynchronous events.
723 * For datagram (non connection oriented) sockets, GSocket_Connect()
724 * just sets the peer address established with GSocket_SetPeer() as
725 * default destination.
728 * GSOCK_INVSOCK - the socket is in use or not valid.
729 * GSOCK_INVADDR - the peer address has not been established.
730 * GSOCK_TIMEDOUT - timeout, the connection failed.
731 * GSOCK_WOULDBLOCK - connection in progress (nonblocking sockets only)
732 * GSOCK_MEMERR - couldn't allocate memory.
733 * GSOCK_IOERR - low-level error.
735 GSocketError
GSocket_Connect(GSocket
*sck
, GSocketStream stream
)
739 OSStatus err
= kOTNoError
;
744 /* Enable CONNECTION events (needed for nonblocking connections) */
745 sck
->m_detected
&= ~GSOCK_CONNECTION_FLAG
;
747 if (sck
->m_endpoint
!= kOTInvalidEndpointRef
)
749 sck
->m_error
= GSOCK_INVSOCK
;
750 return GSOCK_INVSOCK
;
755 sck
->m_error
= GSOCK_INVADDR
;
756 return GSOCK_INVADDR
;
759 /* Streamed or dgram socket? */
760 sck
->m_stream
= (stream
== GSOCK_STREAMED
);
761 sck
->m_oriented
= TRUE
;
762 sck
->m_server
= FALSE
;
764 /* Create the socket */
767 OTOpenEndpointInContext( OTCreateConfiguration( kTCPName
) , 0 , &info
, &err
, NULL
) ;
770 OTOpenEndpoint( OTCreateConfiguration( kTCPName
) , 0 , &info
, &err
) ;
772 if ( sck
->m_endpoint
== kOTInvalidEndpointRef
|| err
!= kOTNoError
)
774 sck
->m_endpoint
= kOTInvalidEndpointRef
;
775 sck
->m_error
= GSOCK_IOERR
;
778 err
= OTBind( sck
->m_endpoint
, nil
, nil
) ;
779 if ( err
!= kOTNoError
)
783 SetDefaultEndpointModes( sck
->m_endpoint
, sck
) ;
786 ioctl(sck
->m_endpoint
, FIONBIO
, &arg
);
788 _GSocket_Enable_Events(sck
);
790 _GAddress_translate_to( sck
->m_peer
, &addr
) ;
791 memset( &peer
, 0 , sizeof( TCall
) ) ;
792 peer
.addr
.len
= sizeof( InetAddress
) ;
793 peer
.addr
.buf
= (unsigned char*) &addr
;
794 err
= OTConnect( sck
->m_endpoint
, &peer
, nil
) ;
797 /* If connect failed with EINPROGRESS and the GSocket object
798 * is in blocking mode, we select() for the specified timeout
799 * checking for writability to see if the connection request
803 if ((err
== kOTNoDataErr
) && (!sck
->m_non_blocking
))
805 if (_GSocket_Output_Timeout(sck
) == GSOCK_TIMEDOUT
)
807 OTSndOrderlyDisconnect( sck
->m_endpoint
) ;
808 sck
->m_endpoint
= kOTInvalidEndpointRef
;
809 /* sck->m_error is set in _GSocket_Output_Timeout */
810 return GSOCK_TIMEDOUT
;
816 SOCKLEN_T len = sizeof(error);
818 getsockopt(sck->m_endpoint, SOL_SOCKET, SO_ERROR, (void*) &error, &len);
822 return GSOCK_NOERROR
;
826 /* If connect failed with EINPROGRESS and the GSocket object
827 * is set to nonblocking, we set m_error to GSOCK_WOULDBLOCK
828 * (and return GSOCK_WOULDBLOCK) but we don't close the socket;
829 * this way if the connection completes, a GSOCK_CONNECTION
830 * event will be generated, if enabled.
832 if ((err
== kOTNoDataErr
) && (sck
->m_non_blocking
))
834 sck
->m_error
= GSOCK_WOULDBLOCK
;
835 return GSOCK_WOULDBLOCK
;
838 /* If connect failed with an error other than EINPROGRESS,
839 * then the call to GSocket_Connect has failed.
841 OTSndOrderlyDisconnect( sck
->m_endpoint
) ;
843 sck
->m_endpoint
= kOTInvalidEndpointRef
;
844 sck
->m_error
= GSOCK_IOERR
;
847 // OTInetEventHandler(sck, T_CONNECT , kOTNoError , NULL ) ;
848 return GSOCK_NOERROR
;
853 /* Like recv(), send(), ... */
854 int GSocket_Read(GSocket
*socket
, char *buffer
, int size
)
858 assert(socket
!= NULL
);
860 /* Reenable INPUT events */
861 socket
->m_detected
&= ~GSOCK_INPUT_FLAG
;
863 if (socket
->m_endpoint
== kOTInvalidEndpointRef
|| socket
->m_server
)
865 socket
->m_error
= GSOCK_INVSOCK
;
869 /* If the socket is blocking, wait for data (with a timeout) */
870 if (_GSocket_Input_Timeout(socket
) == GSOCK_TIMEDOUT
)
874 if (socket
->m_stream
)
875 ret
= _GSocket_Recv_Stream(socket
, buffer
, size
);
877 ret
= _GSocket_Recv_Dgram(socket
, buffer
, size
);
881 if (errno
== EWOULDBLOCK
)
882 socket
->m_error
= GSOCK_WOULDBLOCK
;
884 socket
->m_error
= GSOCK_IOERR
;
890 int GSocket_Write(GSocket
*socket
, const char *buffer
, int size
)
894 assert(socket
!= NULL
);
896 if (socket
->m_endpoint
== kOTInvalidEndpointRef
|| socket
->m_server
)
898 socket
->m_error
= GSOCK_INVSOCK
;
902 /* If the socket is blocking, wait for writability (with a timeout) */
903 if (_GSocket_Output_Timeout(socket
) == GSOCK_TIMEDOUT
)
907 if (socket
->m_stream
)
908 ret
= _GSocket_Send_Stream(socket
, buffer
, size
);
910 ret
= _GSocket_Send_Dgram(socket
, buffer
, size
);
914 if (errno
== EWOULDBLOCK
)
915 socket
->m_error
= GSOCK_WOULDBLOCK
;
917 socket
->m_error
= GSOCK_IOERR
;
919 /* Only reenable OUTPUT events after an error (just like WSAAsyncSelect
920 * in MSW). Once the first OUTPUT event is received, users can assume
921 * that the socket is writable until a read operation fails. Only then
922 * will further OUTPUT events be posted.
924 socket
->m_detected
&= ~GSOCK_OUTPUT_FLAG
;
932 * Polls the socket to determine its status. This function will
933 * check for the events specified in the 'flags' parameter, and
934 * it will return a mask indicating which operations can be
935 * performed. This function won't block, regardless of the
936 * mode (blocking | nonblocking) of the socket.
938 GSocketEventFlags
GSocket_Select(GSocket
*socket
, GSocketEventFlags flags
)
940 assert(socket
!= NULL
);
941 wxMacProcessNotifierEvents() ;
943 state = OTGetEndpointState(socket->m_endpoint);
945 if ( ( flags & GSOCK_INPUT_FLAG ) && ! ( socket->m_detected & GSOCK_INPUT_FLAG ) )
948 OTCountDataBytes( socket->m_endpoint , &sz ) ;
949 if ( state == T_INCON || sz > 0 )
951 socket->m_detected |= GSOCK_INPUT_FLAG ;
952 (socket->m_cbacks[GSOCK_INPUT])(socket, GSOCK_INPUT, socket->m_data[GSOCK_INPUT]);
955 if ( ( flags & GSOCK_INPUT_FLAG ) && ! ( socket->m_detected & GSOCK_OUTPUT_FLAG ) )
957 if ( state == T_DATAXFER || state == T_INREL )
959 socket->m_detected |=GSOCK_OUTPUT_FLAG ;
960 (socket->m_cbacks[GSOCK_OUTPUT])(socket, GSOCK_OUTPUT, socket->m_data[GSOCK_OUTPUT]);
964 return ( flags
& socket
->m_detected
) ;
969 /* GSocket_SetNonBlocking:
970 * Sets the socket to non-blocking mode. All IO calls will return
973 void GSocket_SetNonBlocking(GSocket
*socket
, int non_block
)
975 assert(socket
!= NULL
);
977 socket
->m_non_blocking
= non_block
;
980 /* GSocket_SetTimeout:
981 * Sets the timeout for blocking calls. Time is expressed in
984 void GSocket_SetTimeout(GSocket
*socket
, unsigned long millisec
)
986 assert(socket
!= NULL
);
988 // this is usually set too high and we have not yet been able to detect a closed
989 // stream, thus we leave the 10 sec timeout
990 // socket->m_timeout = millisec;
994 * Returns the last error occured for this socket. Note that successful
995 * operations do not clear this back to GSOCK_NOERROR, so use it only
998 GSocketError
GSocket_GetError(GSocket
*socket
)
1000 assert(socket
!= NULL
);
1002 return socket
->m_error
;
1008 * There is data to be read in the input buffer. If, after a read
1009 * operation, there is still data available, the callback function will
1012 * The socket is available for writing. That is, the next write call
1013 * won't block. This event is generated only once, when the connection is
1014 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
1015 * when the output buffer empties again. This means that the app should
1016 * assume that it can write since the first OUTPUT event, and no more
1017 * OUTPUT events will be generated unless an error occurs.
1019 * Connection succesfully established, for client sockets, or incoming
1020 * client connection, for server sockets. Wait for this event (also watch
1021 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
1023 * The connection is lost (or a connection request failed); this could
1024 * be due to a failure, or due to the peer closing it gracefully.
1027 /* GSocket_SetCallback:
1028 * Enables the callbacks specified by 'flags'. Note that 'flags'
1029 * may be a combination of flags OR'ed toghether, so the same
1030 * callback function can be made to accept different events.
1031 * The callback function must have the following prototype:
1033 * void function(GSocket *socket, GSocketEvent event, char *cdata)
1035 void GSocket_SetCallback(GSocket
*socket
, GSocketEventFlags flags
,
1036 GSocketCallback callback
, char *cdata
)
1040 assert(socket
!= NULL
);
1042 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1044 if ((flags
& (1 << count
)) != 0)
1046 socket
->m_cbacks
[count
] = callback
;
1047 socket
->m_data
[count
] = cdata
;
1052 /* GSocket_UnsetCallback:
1053 * Disables all callbacks specified by 'flags', which may be a
1054 * combination of flags OR'ed toghether.
1056 void GSocket_UnsetCallback(GSocket
*socket
, GSocketEventFlags flags
)
1060 assert(socket
!= NULL
);
1062 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1064 if ((flags
& (1 << count
)) != 0)
1066 socket
->m_cbacks
[count
] = NULL
;
1067 socket
->m_data
[count
] = NULL
;
1073 #define CALL_CALLBACK(socket, event) { \
1074 _GSocket_Disable(socket, event); \
1075 if (socket->m_cbacks[event]) \
1076 socket->m_cbacks[event](socket, event, socket->m_data[event]); \
1079 int _GSocket_Recv_Stream(GSocket
*socket
, char *buffer
, int size
)
1083 OTByteCount sz
= 0 ;
1085 OTCountDataBytes( socket
->m_endpoint
, &sz
) ;
1086 if ( size
> (int)sz
)
1088 res
= OTRcv( socket
->m_endpoint
, buffer
, size
, &flags
) ;
1094 // we simulate another read event if there are still bytes
1095 if ( socket
->m_takesEvents
)
1097 OTByteCount sz
= 0 ;
1098 OTCountDataBytes( socket
->m_endpoint
, &sz
) ;
1101 socket
->m_detected
|= GSOCK_INPUT_FLAG
;
1102 (socket
->m_cbacks
[GSOCK_INPUT
])(socket
, GSOCK_INPUT
, socket
->m_data
[GSOCK_INPUT
]);
1108 int _GSocket_Recv_Dgram(GSocket
*socket
, char *buffer
, int size
)
1113 struct sockaddr from
;
1114 SOCKLEN_T fromlen
= sizeof(from
);
1117 fromlen
= sizeof(from
);
1119 ret
= recvfrom(socket
->m_endpoint
, buffer
, size
, 0, &from
, (SOCKLEN_T
*) &fromlen
);
1124 /* Translate a system address into a GSocket address */
1125 if (!socket
->m_peer
)
1127 socket
->m_peer
= GAddress_new();
1128 if (!socket
->m_peer
)
1130 socket
->m_error
= GSOCK_MEMERR
;
1134 err
= _GAddress_translate_from(socket
->m_peer
, &from
, fromlen
);
1135 if (err
!= GSOCK_NOERROR
)
1137 GAddress_destroy(socket
->m_peer
);
1138 socket
->m_peer
= NULL
;
1139 socket
->m_error
= err
;
1146 int _GSocket_Send_Stream(GSocket
*socket
, const char *buffer
, int size
)
1151 res
= OTSnd( socket
->m_endpoint
, (void*) buffer
, size
, flags
) ;
1155 int _GSocket_Send_Dgram(GSocket
*socket
, const char *buffer
, int size
)
1160 struct sockaddr
*addr
;
1164 if (!socket
->m_peer
)
1166 socket
->m_error
= GSOCK_INVADDR
;
1170 err
= _GAddress_translate_to(socket
->m_peer
, &addr
, &len
);
1171 if (err
!= GSOCK_NOERROR
)
1173 socket
->m_error
= err
;
1177 ret
= sendto(socket
->m_endpoint
, buffer
, size
, 0, addr
, len
);
1179 /* Frees memory allocated from _GAddress_translate_to */
1187 * -------------------------------------------------------------------------
1189 * -------------------------------------------------------------------------
1192 /* CHECK_ADDRESS verifies that the current family is either GSOCK_NOFAMILY
1193 * or GSOCK_*family*, and if it is GSOCK_NOFAMILY, it initalizes address
1194 * to be a GSOCK_*family*. In other cases, it returns GSOCK_INVADDR.
1196 #define CHECK_ADDRESS(address, family, retval) \
1198 if (address->m_family == GSOCK_NOFAMILY) \
1199 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1200 return address->m_error; \
1201 if (address->m_family != GSOCK_##family) \
1203 address->m_error = GSOCK_INVADDR; \
1208 GAddress
*GAddress_new()
1212 if ((address
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1215 address
->m_family
= GSOCK_NOFAMILY
;
1216 address
->m_host
= INADDR_NONE
;
1217 address
->m_port
= 0 ;
1222 GAddress
*GAddress_copy(GAddress
*address
)
1226 assert(address
!= NULL
);
1228 if ((addr2
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1231 memcpy(addr2
, address
, sizeof(GAddress
));
1235 void GAddress_destroy(GAddress
*address
)
1237 assert(address
!= NULL
);
1242 void GAddress_SetFamily(GAddress
*address
, GAddressType type
)
1244 assert(address
!= NULL
);
1246 address
->m_family
= type
;
1249 GAddressType
GAddress_GetFamily(GAddress
*address
)
1251 assert(address
!= NULL
);
1253 return address
->m_family
;
1256 GSocketError
_GAddress_translate_from(GAddress
*address
,
1259 switch (addr
->fAddressType
)
1262 address
->m_family
= GSOCK_INET
;
1266 address
->m_family
= GSOCK_INET6
;
1271 address
->m_error
= GSOCK_INVOP
;
1275 address
->m_host
= addr
->fHost
;
1276 address
->m_port
= addr
->fPort
;
1277 return GSOCK_NOERROR
;
1280 GSocketError
_GAddress_translate_to(GAddress
*address
,
1283 if ( GSocket_Verify_Inited() == FALSE
)
1284 return GSOCK_IOERR
;
1285 memset(addr
, 0 , sizeof(struct InetAddress
));
1286 OTInitInetAddress( addr
, address
->m_port
, address
->m_host
) ;
1287 return GSOCK_NOERROR
;
1291 * -------------------------------------------------------------------------
1292 * Internet address family
1293 * -------------------------------------------------------------------------
1296 GSocketError
_GAddress_Init_INET(GAddress
*address
)
1298 address
->m_family
= GSOCK_INET
;
1299 address
->m_host
= kOTAnyInetAddress
;
1301 return GSOCK_NOERROR
;
1304 GSocketError
GAddress_INET_SetHostName(GAddress
*address
, const char *hostname
)
1306 InetHostInfo hinfo
;
1309 if ( GSocket_Verify_Inited() == FALSE
)
1310 return GSOCK_IOERR
;
1312 assert(address
!= NULL
);
1314 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1315 ret
= OTInetStringToAddress( gInetSvcRef
, (char*) hostname
, &hinfo
) ;
1316 if ( ret
!= kOTNoError
)
1318 address
->m_host
= INADDR_NONE
;
1319 address
->m_error
= GSOCK_NOHOST
;
1320 return GSOCK_NOHOST
;
1322 address
->m_host
= hinfo
.addrs
[0] ;
1323 return GSOCK_NOERROR
;
1326 GSocketError
GAddress_INET_SetAnyAddress(GAddress
*address
)
1328 return GAddress_INET_SetHostAddress(address
, INADDR_ANY
);
1331 GSocketError
GAddress_INET_SetHostAddress(GAddress
*address
,
1332 unsigned long hostaddr
)
1334 assert(address
!= NULL
);
1336 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1338 address
->m_host
= htonl(hostaddr
) ;
1340 return GSOCK_NOERROR
;
1343 struct service_entry
1346 unsigned short port
;
1349 typedef struct service_entry service_entry
;
1351 service_entry gServices
[] =
1353 { "http" , 80 , "tcp" }
1356 GSocketError
GAddress_INET_SetPortName(GAddress
*address
, const char *port
,
1357 const char *protocol
)
1361 assert(address
!= NULL
);
1362 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1366 address
->m_error
= GSOCK_INVPORT
;
1367 return GSOCK_INVPORT
;
1369 for ( i
= 0 ; i
< sizeof( gServices
) / sizeof( service_entry
) ; ++i
)
1371 if ( strcmp( port
, gServices
[i
].name
) == 0 )
1373 if ( protocol
== NULL
|| strcmp( protocol
, gServices
[i
].protocol
) )
1375 address
->m_port
= gServices
[i
].port
;
1376 return GSOCK_NOERROR
;
1381 if (isdigit(port
[0]))
1383 address
->m_port
= atoi(port
);
1384 return GSOCK_NOERROR
;
1387 address
->m_error
= GSOCK_INVPORT
;
1388 return GSOCK_INVPORT
;
1391 GSocketError
GAddress_INET_SetPort(GAddress
*address
, unsigned short port
)
1393 assert(address
!= NULL
);
1394 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1395 address
->m_port
= port
;
1397 return GSOCK_NOERROR
;
1400 GSocketError
GAddress_INET_GetHostName(GAddress
*address
, char *hostname
, size_t sbuf
)
1402 InetDomainName name
;
1403 if ( GSocket_Verify_Inited() == FALSE
)
1404 return GSOCK_IOERR
;
1406 assert(address
!= NULL
);
1407 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1409 OTInetAddressToName( gInetSvcRef
, address
->m_host
, name
) ;
1410 strncpy( hostname
, name
, sbuf
) ;
1411 return GSOCK_NOERROR
;
1414 unsigned long GAddress_INET_GetHostAddress(GAddress
*address
)
1416 assert(address
!= NULL
);
1417 CHECK_ADDRESS(address
, INET
, 0);
1419 return ntohl(address
->m_host
);
1422 unsigned short GAddress_INET_GetPort(GAddress
*address
)
1424 assert(address
!= NULL
);
1425 CHECK_ADDRESS(address
, INET
, 0);
1427 return address
->m_port
;
1430 void _GSocket_Enable_Events(GSocket
*socket
)
1432 if ( socket
->m_takesEvents
)
1437 socket
->m_takesEvents
= TRUE
;
1438 state
= OTGetEndpointState(socket
->m_endpoint
);
1441 OTByteCount sz
= 0 ;
1442 OTCountDataBytes( socket
->m_endpoint
, &sz
) ;
1443 if ( state
== T_INCON
|| sz
> 0 )
1445 socket
->m_detected
|= GSOCK_INPUT_FLAG
;
1446 (socket
->m_cbacks
[GSOCK_INPUT
])(socket
, GSOCK_INPUT
, socket
->m_data
[GSOCK_INPUT
]);
1450 if ( state
== T_DATAXFER
|| state
== T_INREL
)
1452 socket
->m_detected
|=GSOCK_OUTPUT_FLAG
;
1453 (socket
->m_cbacks
[GSOCK_OUTPUT
])(socket
, GSOCK_OUTPUT
, socket
->m_data
[GSOCK_OUTPUT
]);
1459 void _GSocket_Disable_Events(GSocket
*socket
)
1461 socket
->m_takesEvents
= FALSE
;
1464 /* _GSocket_Input_Timeout:
1465 * For blocking sockets, wait until data is available or
1466 * until timeout ellapses.
1468 GSocketError
_GSocket_Input_Timeout(GSocket
*socket
)
1470 if ( !socket
->m_non_blocking
)
1472 UnsignedWide now
, start
;
1473 short formerTakesEvents
= socket
->m_takesEvents
;
1474 Microseconds(&start
);
1476 socket
->m_takesEvents
= FALSE
;
1478 while( (now
.hi
* 4294967296.0 + now
.lo
) - (start
.hi
* 4294967296.0 + start
.lo
) < socket
->m_timeout
* 1000.0 )
1481 OTByteCount sz
= 0 ;
1482 state
= OTGetEndpointState(socket
->m_endpoint
);
1484 OTCountDataBytes( socket
->m_endpoint
, &sz
) ;
1485 if ( state
== T_INCON
|| sz
> 0 )
1487 socket
->m_takesEvents
= formerTakesEvents
;
1488 return GSOCK_NOERROR
;
1492 socket
->m_takesEvents
= formerTakesEvents
;
1493 socket
->m_error
= GSOCK_TIMEDOUT
;
1494 return GSOCK_TIMEDOUT
;
1496 return GSOCK_NOERROR
;
1499 /* _GSocket_Output_Timeout:
1500 * For blocking sockets, wait until data can be sent without
1501 * blocking or until timeout ellapses.
1503 GSocketError
_GSocket_Output_Timeout(GSocket
*socket
)
1505 if ( !socket
->m_non_blocking
)
1507 UnsignedWide now
, start
;
1508 short formerTakesEvents
= socket
->m_takesEvents
;
1509 Microseconds(&start
);
1511 socket
->m_takesEvents
= FALSE
;
1513 while( (now
.hi
* 4294967296.0 + now
.lo
) - (start
.hi
* 4294967296.0 + start
.lo
) < socket
->m_timeout
* 1000.0 )
1516 state
= OTGetEndpointState(socket
->m_endpoint
);
1518 if ( state
== T_DATAXFER
|| state
== T_INREL
)
1520 socket
->m_takesEvents
= formerTakesEvents
;
1521 return GSOCK_NOERROR
;
1525 socket
->m_takesEvents
= formerTakesEvents
;
1526 socket
->m_error
= GSOCK_TIMEDOUT
;
1527 return GSOCK_TIMEDOUT
;
1529 return GSOCK_NOERROR
;
1533 * There is data to be read in the input buffer. If, after a read
1534 * operation, there is still data available, the callback function will
1537 * The socket is available for writing. That is, the next write call
1538 * won't block. This event is generated only once, when the connection is
1539 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
1540 * when the output buffer empties again. This means that the app should
1541 * assume that it can write since the first OUTPUT event, and no more
1542 * OUTPUT events will be generated unless an error occurs.
1544 * Connection succesfully established, for client sockets, or incoming
1545 * client connection, for server sockets. Wait for this event (also watch
1546 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
1548 * The connection is lost (or a connection request failed); this could
1549 * be due to a failure, or due to the peer closing it gracefully.
1552 void _GSocket_Internal_Proc(unsigned long e
, void* d
)
1555 GSocket
* socket
= (GSocket
*) d
;
1556 OTEventCode ev
= (OTEventCode
) e
;
1558 GSocketEvent event2
;
1559 GSocketCallback cback
;
1561 GSocketCallback cback2
;
1566 event
= GSOCK_MAX_EVENT
;
1567 event2
= GSOCK_MAX_EVENT
;
1573 /* Check that the socket still exists (it has not been
1574 * destroyed) and for safety, check that the m_endpoint field
1575 * is what we expect it to be.
1577 if ((socket
!= NULL
) && (socket
->m_takesEvents
))
1582 event
= GSOCK_CONNECTION
;
1585 event
= GSOCK_CONNECTION
;
1586 event2
= GSOCK_OUTPUT
;
1590 retCall
.addr
.buf
= NULL
;
1591 retCall
.addr
.maxlen
= 0;
1592 retCall
.opt
.buf
= NULL
;
1593 retCall
.opt
.maxlen
= 0;
1594 retCall
.udata
.buf
= NULL
;
1595 retCall
.udata
.maxlen
= 0;
1596 OTRcvConnect( socket
->m_endpoint
, &retCall
) ;
1600 event
= GSOCK_LOST
;
1604 event
= GSOCK_OUTPUT
;
1607 event
= GSOCK_INPUT
;
1610 event
= GSOCK_INPUT
;
1613 if (event
!= GSOCK_MAX_EVENT
)
1615 cback
= socket
->m_cbacks
[event
];
1616 data
= socket
->m_data
[event
];
1618 if (event
== GSOCK_LOST
)
1619 socket
->m_detected
= GSOCK_LOST_FLAG
;
1621 socket
->m_detected
|= (1 << event
);
1623 if (event2
!= GSOCK_MAX_EVENT
)
1625 cback2
= socket
->m_cbacks
[event2
];
1626 data2
= socket
->m_data
[event2
];
1628 if (event2
== GSOCK_LOST
)
1629 socket
->m_detected
= GSOCK_LOST_FLAG
;
1631 socket
->m_detected
|= (1 << event2
);
1635 /* OK, we can now leave the critical section because we have
1636 * already obtained the callback address (we make no further
1637 * accesses to socket->whatever). However, the app should
1638 * be prepared to handle events from a socket that has just
1643 (cback
)(socket
, event
, data
);
1645 (cback2
)(socket
, event2
, data2
);
1649 /* Hack added for Mac OS X */
1650 GSocketError
GAddress_UNIX_GetPath(GAddress
*addr
, char *path
, size_t buf
)
1652 return GSOCK_INVADDR
;
1655 GSocketError
GAddress_UNIX_SetPath(GAddress
*addr
, const char *path
)
1657 return GSOCK_INVADDR
;
1660 #endif /* wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__) */