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__
20 #if wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__)
23 #include <CoreServices/CoreServices.h>
32 #define OTUNIXERRORS 1
33 #include <OpenTransport.h>
34 #include <OpenTransportProviders.h>
35 #include <OpenTptInternet.h>
38 #define OTAssert( str , cond ) /* does not exists in Carbon */
52 * INADDR_BROADCAST is identical to INADDR_NONE which is not defined
53 * on all unices. INADDR_BROADCAST should be fine to indicate an error.
55 #ifndef INADDR_BROADCAST
56 #define INADDR_BROADCAST 0xFFFFFFFFUL
59 #define INADDR_NONE INADDR_BROADCAST
62 #define INADDR_ANY 0x0UL
64 #ifndef __GSOCKET_STANDALONE__
66 #include "wx/mac/macnotfy.h"
67 #include "wx/mac/gsockmac.h"
68 #include "wx/gsocket.h"
75 #endif /* __GSOCKET_STANDALONE__ */
81 extern pascal void OTDebugStr(const char* str
);
86 InetSvcRef gInetSvcRef
= 0 ;
89 OSStatus
DoNegotiateIPReuseAddrOption(EndpointRef ep
, Boolean enableReuseIPMode
);
91 /* Input: ep - endpointref on which to negotiate the option
92 enableReuseIPMode - desired option setting - true/false
93 Return: kOTNoError indicates that the option was successfully negotiated
94 OSStatus is an error if < 0, otherwise, the status field is
97 IMPORTANT NOTE: The endpoint is assumed to be in synchronous more, otherwise
98 this code will not function as desired
102 OSStatus
DoNegotiateIPReuseAddrOption(EndpointRef ep
, Boolean enableReuseIPMode
)
105 UInt8 buf
[kOTFourByteOptionSize
]; // define buffer for fourByte Option size
106 TOption
* opt
; // option ptr to make items easier to access
111 if (!OTIsSynchronous(ep
))
115 opt
= (TOption
*)buf
; // set option ptr to buffer
117 req
.opt
.len
= sizeof(buf
);
118 req
.flags
= T_NEGOTIATE
; // negotiate for option
121 ret
.opt
.maxlen
= kOTFourByteOptionSize
;
123 opt
->level
= INET_IP
; // dealing with an IP Level function
125 opt
->name
= kIP_REUSEADDR
;
127 opt
->name
= IP_REUSEADDR
;
129 opt
->len
= kOTFourByteOptionSize
;
131 *(UInt32
*)opt
->value
= enableReuseIPMode
; // set the desired option level, true or false
133 err
= OTOptionManagement(ep
, &req
, &ret
);
135 // if no error then return the option status value
136 if (err
== kOTNoError
)
138 if (opt
->status
!= T_SUCCESS
)
148 pascal void OTInetEventHandler(void*s
, OTEventCode event
, OTResult
, void *cookie
) ;
149 pascal void OTInetEventHandler(void*s
, OTEventCode event
, OTResult result
, void *cookie
)
152 GSocket
* sock
= (GSocket
*) s
;
154 if ( event
== kOTSyncIdleEvent
)
162 wxMacAddEvent( sock
->m_mac_events
, _GSocket_Internal_Proc
, event
, s
, wakeUp
) ;
168 static void SetDefaultEndpointModes(EndpointRef ep
, void *data
)
169 // This routine sets the supplied endpoint into the default
170 // mode used in this application. The specifics are:
171 // blocking, synchronous, and using synch idle events with
172 // the standard YieldingNotifier.
174 OSStatus junk
= kOTNoError
;
175 OTAssert ("SetDefaultEndpointModes:invalid ref", ep
!= kOTInvalidEndpointRef
) ;
176 junk
= OTSetAsynchronous(ep
);
177 OTAssert("SetDefaultEndpointModes: Could not set asynchronous", junk
== noErr
);
179 junk = OTSetBlocking(ep);
180 OTAssert("SetDefaultEndpointModes: Could not set blocking", junk == noErr);
181 junk = OTSetSynchronous(ep);
182 OTAssert("SetDefaultEndpointModes: Could not set synchronous", junk == noErr);
183 junk = OTSetBlocking(ep);
184 OTAssert("SetDefaultEndpointModes: Could not set blocking", junk == noErr);
186 junk
= OTInstallNotifier(ep
, OTInetEventHandler
, data
);
187 OTAssert("SetDefaultEndpointModes: Could not install notifier", junk
== noErr
);
189 junk = OTUseSyncIdleEvents(ep, true);
190 OTAssert("SetDefaultEndpointModes: Could not use sync idle events", junk == noErr);
194 /* Global initialisers */
200 // Marc Newsam: added the clientcontext variable
201 // however, documentation is unclear how this works
202 OTClientContextPtr clientcontext
;
204 InitOpenTransportInContext(kInitOTForApplicationMask
, &clientcontext
);
205 gInetSvcRef
= OTOpenInternetServicesInContext(kDefaultInternetServicesPath
,
206 NULL
, &err
, clientcontext
);
208 InitOpenTransport() ;
209 gInetSvcRef
= OTOpenInternetServices(kDefaultInternetServicesPath
, NULL
, &err
);
211 if ( gInetSvcRef
== NULL
|| err
!= kOTNoError
)
213 OTAssert("Could not open Inet Services", err
== noErr
);
219 void GSocket_Cleanup()
221 if ( gInetSvcRef
!= NULL
)
222 OTCloseProvider( gInetSvcRef
);
224 CloseOpenTransportInContext( NULL
) ;
226 CloseOpenTransport() ;
230 /* Constructors / Destructors for GSocket */
232 GSocket
*GSocket_new()
237 socket
= (GSocket
*)malloc(sizeof(GSocket
));
242 socket
->m_endpoint
= NULL
;
243 for (i
=0;i
<GSOCK_MAX_EVENT
;i
++)
245 socket
->m_cbacks
[i
] = NULL
;
247 socket
->m_detected
= 0;
248 socket
->m_local
= NULL
;
249 socket
->m_peer
= NULL
;
250 socket
->m_error
= GSOCK_NOERROR
;
251 socket
->m_server
= FALSE
;
252 socket
->m_stream
= TRUE
;
253 socket
->m_non_blocking
= FALSE
;
254 socket
->m_timeout
= 10*60*1000;
255 /* 10 minutes * 60 sec * 1000 millisec */
256 socket
->m_takesEvents
= TRUE
;
257 socket
->m_mac_events
= wxMacGetNotifierTable() ;
261 void GSocket_destroy(GSocket
*socket
)
263 assert(socket
!= NULL
);
265 /* Check that the socket is really shutdowned */
266 if (socket
->m_endpoint
!= kOTInvalidEndpointRef
)
267 GSocket_Shutdown(socket
);
270 /* Destroy private addresses */
272 GAddress_destroy(socket
->m_local
);
275 GAddress_destroy(socket
->m_peer
);
277 /* Destroy the socket itself */
282 * Disallow further read/write operations on this socket, close
283 * the fd and disable all callbacks.
285 void GSocket_Shutdown(GSocket
*socket
)
290 assert(socket
!= NULL
);
292 /* If socket has been created, shutdown it */
293 if (socket
->m_endpoint
!= kOTInvalidEndpointRef
)
295 err
= OTSndOrderlyDisconnect( socket
->m_endpoint
) ;
296 if ( err
!= kOTNoError
)
300 err
= OTRcvOrderlyDisconnect( socket
->m_endpoint
) ;
301 err
= OTUnbind( socket
->m_endpoint
) ;
302 err
= OTCloseProvider( socket
->m_endpoint
) ;
303 socket
->m_endpoint
= kOTInvalidEndpointRef
;
306 /* Disable GUI callbacks */
307 for (evt
= 0; evt
< GSOCK_MAX_EVENT
; evt
++)
308 socket
->m_cbacks
[evt
] = NULL
;
310 socket
->m_detected
= 0;
311 _GSocket_Disable_Events(socket
);
312 wxMacRemoveAllNotifiersForData( wxMacGetNotifierTable() , socket
) ;
316 /* Address handling */
322 * Set or get the local or peer address for this socket. The 'set'
323 * functions return GSOCK_NOERROR on success, an error code otherwise.
324 * The 'get' functions return a pointer to a GAddress object on success,
325 * or NULL otherwise, in which case they set the error code of the
326 * corresponding GSocket.
329 * GSOCK_INVSOCK - the socket is not valid.
330 * GSOCK_INVADDR - the address is not valid.
332 GSocketError
GSocket_SetLocal(GSocket
*socket
, GAddress
*address
)
334 assert(socket
!= NULL
);
336 /* the socket must be initialized, or it must be a server */
337 if ((socket
->m_endpoint
!= kOTInvalidEndpointRef
&& !socket
->m_server
))
339 socket
->m_error
= GSOCK_INVSOCK
;
340 return GSOCK_INVSOCK
;
344 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
346 socket
->m_error
= GSOCK_INVADDR
;
347 return GSOCK_INVADDR
;
351 GAddress_destroy(socket
->m_local
);
353 socket
->m_local
= GAddress_copy(address
);
355 return GSOCK_NOERROR
;
358 GSocketError
GSocket_SetPeer(GSocket
*socket
, GAddress
*address
)
360 assert(socket
!= NULL
);
363 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
365 socket
->m_error
= GSOCK_INVADDR
;
366 return GSOCK_INVADDR
;
370 GAddress_destroy(socket
->m_peer
);
372 socket
->m_peer
= GAddress_copy(address
);
374 return GSOCK_NOERROR
;
377 GAddress
*GSocket_GetLocal(GSocket
*socket
)
379 GAddress
*address
= NULL
;
383 assert(socket
!= NULL
);
385 /* try to get it from the m_local var first */
387 return GAddress_copy(socket
->m_local
);
389 /* else, if the socket is initialized, try getsockname */
390 if (socket
->m_endpoint
== kOTInvalidEndpointRef
)
392 socket
->m_error
= GSOCK_INVSOCK
;
397 /* we do not support multihoming with this code at the moment
398 OTGetProtAddress will have to be used then - but we don't have a handy
399 method to use right now
402 InetInterfaceInfo info
;
403 OTInetGetInterfaceInfo(&info
, kDefaultInetInterface
);
404 loc
.fHost
= info
.fAddress
;
406 loc
.fAddressType
= AF_INET
;
409 /* got a valid address from getsockname, create a GAddress object */
410 address
= GAddress_new();
413 socket
->m_error
= GSOCK_MEMERR
;
417 err
= _GAddress_translate_from(address
, &loc
);
418 if (err
!= GSOCK_NOERROR
)
420 GAddress_destroy(address
);
421 socket
->m_error
= err
;
428 GAddress
*GSocket_GetPeer(GSocket
*socket
)
430 assert(socket
!= NULL
);
432 /* try to get it from the m_peer var */
434 return GAddress_copy(socket
->m_peer
);
439 /* Server specific parts */
441 /* GSocket_SetServer:
442 * Sets up this socket as a server. The local address must have been
443 * set with GSocket_SetLocal() before GSocket_SetServer() is called.
444 * Returns GSOCK_NOERROR on success, one of the following otherwise:
447 * GSOCK_INVSOCK - the socket is in use.
448 * GSOCK_INVADDR - the local address has not been set.
449 * GSOCK_IOERR - low-level error.
451 GSocketError
GSocket_SetServer(GSocket
*sck
)
458 /* must not be in use */
459 if (sck
->m_endpoint
!= kOTInvalidEndpointRef
)
461 sck
->m_error
= GSOCK_INVSOCK
;
462 return GSOCK_INVSOCK
;
465 /* the local addr must have been set */
468 sck
->m_error
= GSOCK_INVADDR
;
469 return GSOCK_INVADDR
;
472 /* Initialize all fields */
473 sck
->m_stream
= TRUE
;
474 sck
->m_server
= TRUE
;
475 sck
->m_oriented
= TRUE
;
479 /* Create the socket */
480 sck
->m_endpoint
= socket(sck
->m_local
->m_realfamily
, SOCK_STREAM
, 0);
481 socket_set_ref( sck
->m_endpoint
, (unsigned long) &gMacNetEvents
, (unsigned long) sck
) ;
482 if (sck
->m_endpoint
== kOTInvalidEndpointRef
)
484 sck
->m_error
= GSOCK_IOERR
;
488 ioctl(sck
->m_endpoint
, FIONBIO
, &arg
);
489 _GSocket_Enable_Events(sck
);
491 /* Bind to the local address,
492 * retrieve the actual address bound,
493 * and listen up to 5 connections.
495 if ((bind(sck
->m_endpoint
, sck
->m_local
->m_addr
, sck
->m_local
->m_len
) != 0) ||
496 (getsockname(sck
->m_endpoint
,
497 sck
->m_local
->m_addr
,
498 (SOCKLEN_T
*) &sck
->m_local
->m_len
) != 0) ||
499 (listen(sck
->m_endpoint
, 5) != 0))
501 close(sck
->m_endpoint
);
502 sck
->m_endpoint
= -1;
503 sck
->m_error
= GSOCK_IOERR
;
507 return GSOCK_NOERROR
;
510 /* GSocket_WaitConnection:
511 * Waits for an incoming client connection. Returns a pointer to
512 * a GSocket object, or NULL if there was an error, in which case
513 * the last error field will be updated for the calling GSocket.
515 * Error codes (set in the calling GSocket)
516 * GSOCK_INVSOCK - the socket is not valid or not a server.
517 * GSOCK_TIMEDOUT - timeout, no incoming connections.
518 * GSOCK_WOULDBLOCK - the call would block and the socket is nonblocking.
519 * GSOCK_MEMERR - couldn't allocate memory.
520 * GSOCK_IOERR - low-level error.
522 GSocket
*GSocket_WaitConnection(GSocket
*socket
)
524 GSocket
*connection
= NULL
;
529 assert(socket
!= NULL
);
531 /* Reenable CONNECTION events */
532 socket
->m_detected
&= ~GSOCK_CONNECTION_FLAG
;
534 /* If the socket has already been created, we exit immediately */
535 if (socket
->m_endpoint
== kOTInvalidEndpointRef
|| !socket
->m_server
)
537 socket
->m_error
= GSOCK_INVSOCK
;
541 /* Create a GSocket object for the new connection */
542 connection
= GSocket_new();
546 socket
->m_error
= GSOCK_MEMERR
;
550 /* Wait for a connection (with timeout) */
551 if (_GSocket_Input_Timeout(socket
) == GSOCK_TIMEDOUT
)
553 GSocket_destroy(connection
);
554 /* socket->m_error set by _GSocket_Input_Timeout */
560 connection
->m_endpoint
= accept(socket
->m_endpoint
, &from
, (SOCKLEN_T
*) &fromlen
);
563 if (connection
->m_endpoint
== kOTInvalidEndpointRef
)
565 if (errno
== EWOULDBLOCK
)
566 socket
->m_error
= GSOCK_WOULDBLOCK
;
568 socket
->m_error
= GSOCK_IOERR
;
570 GSocket_destroy(connection
);
574 /* Initialize all fields */
575 connection
->m_server
= FALSE
;
576 connection
->m_stream
= TRUE
;
577 connection
->m_oriented
= TRUE
;
579 /* Setup the peer address field */
580 connection
->m_peer
= GAddress_new();
581 if (!connection
->m_peer
)
583 GSocket_destroy(connection
);
584 socket
->m_error
= GSOCK_MEMERR
;
589 err
= _GAddress_translate_from(connection
->m_peer
, &from
, fromlen
);
590 if (err
!= GSOCK_NOERROR
)
592 GAddress_destroy(connection
->m_peer
);
593 GSocket_destroy(connection
);
594 socket
->m_error
= err
;
598 ioctl(connection
->m_endpoint
, FIONBIO
, &arg
);
600 _GSocket_Enable_Events(connection
);
605 /* Datagram sockets */
607 /* GSocket_SetNonOriented:
608 * Sets up this socket as a non-connection oriented (datagram) socket.
609 * Before using this function, the local address must have been set
610 * with GSocket_SetLocal(), or the call will fail. Returns GSOCK_NOERROR
611 * on success, or one of the following otherwise.
614 * GSOCK_INVSOCK - the socket is in use.
615 * GSOCK_INVADDR - the local address has not been set.
616 * GSOCK_IOERR - low-level error.
618 GSocketError
GSocket_SetNonOriented(GSocket
*sck
)
624 if (sck
->m_endpoint
!= kOTInvalidEndpointRef
)
626 sck
->m_error
= GSOCK_INVSOCK
;
627 return GSOCK_INVSOCK
;
632 sck
->m_error
= GSOCK_INVADDR
;
633 return GSOCK_INVADDR
;
636 /* Initialize all fields */
637 sck
->m_stream
= FALSE
;
638 sck
->m_server
= FALSE
;
639 sck
->m_oriented
= FALSE
;
641 /* Create the socket */
645 sck
->m_endpoint
= socket(sck
->m_local
->m_realfamily
, SOCK_DGRAM
, 0);
646 socket_set_ref( sck
->m_endpoint
, (unsigned long) &gMacNetEvents
, (unsigned long) sck
) ;
648 if (sck
->m_endpoint
== kOTInvalidEndpointRef
)
650 sck
->m_error
= GSOCK_IOERR
;
656 ioctl(sck
->m_endpoint
, FIONBIO
, &arg
);
658 _GSocket_Enable_Events(sck
);
660 /* Bind to the local address,
661 * and retrieve the actual address bound.
665 if ((bind(sck
->m_endpoint
, sck
->m_local
->m_addr
, sck
->m_local
->m_len
) != 0) ||
666 (getsockname(sck
->m_endpoint
,
667 sck
->m_local
->m_addr
,
668 (SOCKLEN_T
*) &sck
->m_local
->m_len
) != 0))
670 close(sck
->m_endpoint
);
671 sck
->m_endpoint
= -1;
672 sck
->m_error
= GSOCK_IOERR
;
676 return GSOCK_NOERROR
;
679 /* Client specific parts */
682 * For stream (connection oriented) sockets, GSocket_Connect() tries
683 * to establish a client connection to a server using the peer address
684 * as established with GSocket_SetPeer(). Returns GSOCK_NOERROR if the
685 * connection has been succesfully established, or one of the error
686 * codes listed below. Note that for nonblocking sockets, a return
687 * value of GSOCK_WOULDBLOCK doesn't mean a failure. The connection
688 * request can be completed later; you should use GSocket_Select()
689 * to poll for GSOCK_CONNECTION | GSOCK_LOST, or wait for the
690 * corresponding asynchronous events.
692 * For datagram (non connection oriented) sockets, GSocket_Connect()
693 * just sets the peer address established with GSocket_SetPeer() as
694 * default destination.
697 * GSOCK_INVSOCK - the socket is in use or not valid.
698 * GSOCK_INVADDR - the peer address has not been established.
699 * GSOCK_TIMEDOUT - timeout, the connection failed.
700 * GSOCK_WOULDBLOCK - connection in progress (nonblocking sockets only)
701 * GSOCK_MEMERR - couldn't allocate memory.
702 * GSOCK_IOERR - low-level error.
704 GSocketError
GSocket_Connect(GSocket
*sck
, GSocketStream stream
)
711 OSStatus err
= kOTNoError
;
716 /* Enable CONNECTION events (needed for nonblocking connections) */
717 sck
->m_detected
&= ~GSOCK_CONNECTION_FLAG
;
719 if (sck
->m_endpoint
!= kOTInvalidEndpointRef
)
721 sck
->m_error
= GSOCK_INVSOCK
;
722 return GSOCK_INVSOCK
;
727 sck
->m_error
= GSOCK_INVADDR
;
728 return GSOCK_INVADDR
;
731 /* Streamed or dgram socket? */
732 sck
->m_stream
= (stream
== GSOCK_STREAMED
);
733 sck
->m_oriented
= TRUE
;
734 sck
->m_server
= FALSE
;
736 /* Create the socket */
739 OTOpenEndpointInContext( OTCreateConfiguration( kTCPName
) , 0 , &info
, &err
, NULL
) ;
742 OTOpenEndpoint( OTCreateConfiguration( kTCPName
) , 0 , &info
, &err
) ;
744 if ( sck
->m_endpoint
== kOTInvalidEndpointRef
|| err
!= kOTNoError
)
746 sck
->m_endpoint
= kOTInvalidEndpointRef
;
747 sck
->m_error
= GSOCK_IOERR
;
750 err
= OTBind( sck
->m_endpoint
, nil
, nil
) ;
751 if ( err
!= kOTNoError
)
755 SetDefaultEndpointModes( sck
->m_endpoint
, sck
) ;
758 ioctl(sck
->m_endpoint
, FIONBIO
, &arg
);
760 _GSocket_Enable_Events(sck
);
762 _GAddress_translate_to( sck
->m_peer
, &addr
) ;
763 memset( &peer
, 0 , sizeof( TCall
) ) ;
764 peer
.addr
.len
= sizeof( InetAddress
) ;
765 peer
.addr
.buf
= (unsigned char*) &addr
;
766 err
= OTConnect( sck
->m_endpoint
, &peer
, nil
) ;
769 /* If connect failed with EINPROGRESS and the GSocket object
770 * is in blocking mode, we select() for the specified timeout
771 * checking for writability to see if the connection request
775 if ((err
== kOTNoDataErr
) && (!sck
->m_non_blocking
))
777 if (_GSocket_Output_Timeout(sck
) == GSOCK_TIMEDOUT
)
779 OTSndOrderlyDisconnect( sck
->m_endpoint
) ;
780 sck
->m_endpoint
= kOTInvalidEndpointRef
;
781 /* sck->m_error is set in _GSocket_Output_Timeout */
782 return GSOCK_TIMEDOUT
;
788 SOCKLEN_T len = sizeof(error);
790 getsockopt(sck->m_endpoint, SOL_SOCKET, SO_ERROR, (void*) &error, &len);
794 return GSOCK_NOERROR
;
798 /* If connect failed with EINPROGRESS and the GSocket object
799 * is set to nonblocking, we set m_error to GSOCK_WOULDBLOCK
800 * (and return GSOCK_WOULDBLOCK) but we don't close the socket;
801 * this way if the connection completes, a GSOCK_CONNECTION
802 * event will be generated, if enabled.
804 if ((err
== kOTNoDataErr
) && (sck
->m_non_blocking
))
806 sck
->m_error
= GSOCK_WOULDBLOCK
;
807 return GSOCK_WOULDBLOCK
;
810 /* If connect failed with an error other than EINPROGRESS,
811 * then the call to GSocket_Connect has failed.
813 OTSndOrderlyDisconnect( sck
->m_endpoint
) ;
815 sck
->m_endpoint
= kOTInvalidEndpointRef
;
816 sck
->m_error
= GSOCK_IOERR
;
819 // OTInetEventHandler(sck, T_CONNECT , kOTNoError , NULL ) ;
820 return GSOCK_NOERROR
;
825 /* Like recv(), send(), ... */
826 int GSocket_Read(GSocket
*socket
, char *buffer
, int size
)
830 assert(socket
!= NULL
);
832 /* Reenable INPUT events */
833 socket
->m_detected
&= ~GSOCK_INPUT_FLAG
;
835 if (socket
->m_endpoint
== kOTInvalidEndpointRef
|| socket
->m_server
)
837 socket
->m_error
= GSOCK_INVSOCK
;
841 /* If the socket is blocking, wait for data (with a timeout) */
842 if (_GSocket_Input_Timeout(socket
) == GSOCK_TIMEDOUT
)
846 if (socket
->m_stream
)
847 ret
= _GSocket_Recv_Stream(socket
, buffer
, size
);
849 ret
= _GSocket_Recv_Dgram(socket
, buffer
, size
);
853 if (errno
== EWOULDBLOCK
)
854 socket
->m_error
= GSOCK_WOULDBLOCK
;
856 socket
->m_error
= GSOCK_IOERR
;
862 int GSocket_Write(GSocket
*socket
, const char *buffer
, int size
)
866 assert(socket
!= NULL
);
868 if (socket
->m_endpoint
== kOTInvalidEndpointRef
|| socket
->m_server
)
870 socket
->m_error
= GSOCK_INVSOCK
;
874 /* If the socket is blocking, wait for writability (with a timeout) */
875 if (_GSocket_Output_Timeout(socket
) == GSOCK_TIMEDOUT
)
879 if (socket
->m_stream
)
880 ret
= _GSocket_Send_Stream(socket
, buffer
, size
);
882 ret
= _GSocket_Send_Dgram(socket
, buffer
, size
);
886 if (errno
== EWOULDBLOCK
)
887 socket
->m_error
= GSOCK_WOULDBLOCK
;
889 socket
->m_error
= GSOCK_IOERR
;
891 /* Only reenable OUTPUT events after an error (just like WSAAsyncSelect
892 * in MSW). Once the first OUTPUT event is received, users can assume
893 * that the socket is writable until a read operation fails. Only then
894 * will further OUTPUT events be posted.
896 socket
->m_detected
&= ~GSOCK_OUTPUT_FLAG
;
904 * Polls the socket to determine its status. This function will
905 * check for the events specified in the 'flags' parameter, and
906 * it will return a mask indicating which operations can be
907 * performed. This function won't block, regardless of the
908 * mode (blocking | nonblocking) of the socket.
910 GSocketEventFlags
GSocket_Select(GSocket
*socket
, GSocketEventFlags flags
)
913 assert(socket
!= NULL
);
914 wxMacProcessNotifierEvents() ;
916 state = OTGetEndpointState(socket->m_endpoint);
918 if ( ( flags & GSOCK_INPUT_FLAG ) && ! ( socket->m_detected & GSOCK_INPUT_FLAG ) )
921 OTCountDataBytes( socket->m_endpoint , &sz ) ;
922 if ( state == T_INCON || sz > 0 )
924 socket->m_detected |= GSOCK_INPUT_FLAG ;
925 (socket->m_cbacks[GSOCK_INPUT])(socket, GSOCK_INPUT, socket->m_data[GSOCK_INPUT]);
928 if ( ( flags & GSOCK_INPUT_FLAG ) && ! ( socket->m_detected & GSOCK_OUTPUT_FLAG ) )
930 if ( state == T_DATAXFER || state == T_INREL )
932 socket->m_detected |=GSOCK_OUTPUT_FLAG ;
933 (socket->m_cbacks[GSOCK_OUTPUT])(socket, GSOCK_OUTPUT, socket->m_data[GSOCK_OUTPUT]);
937 return ( flags
& socket
->m_detected
) ;
942 /* GSocket_SetNonBlocking:
943 * Sets the socket to non-blocking mode. All IO calls will return
946 void GSocket_SetNonBlocking(GSocket
*socket
, int non_block
)
948 assert(socket
!= NULL
);
950 socket
->m_non_blocking
= non_block
;
953 /* GSocket_SetTimeout:
954 * Sets the timeout for blocking calls. Time is expressed in
957 void GSocket_SetTimeout(GSocket
*socket
, unsigned long millisec
)
959 assert(socket
!= NULL
);
961 socket
->m_timeout
= millisec
;
965 * Returns the last error occured for this socket. Note that successful
966 * operations do not clear this back to GSOCK_NOERROR, so use it only
969 GSocketError
GSocket_GetError(GSocket
*socket
)
971 assert(socket
!= NULL
);
973 return socket
->m_error
;
979 * There is data to be read in the input buffer. If, after a read
980 * operation, there is still data available, the callback function will
983 * The socket is available for writing. That is, the next write call
984 * won't block. This event is generated only once, when the connection is
985 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
986 * when the output buffer empties again. This means that the app should
987 * assume that it can write since the first OUTPUT event, and no more
988 * OUTPUT events will be generated unless an error occurs.
990 * Connection succesfully established, for client sockets, or incoming
991 * client connection, for server sockets. Wait for this event (also watch
992 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
994 * The connection is lost (or a connection request failed); this could
995 * be due to a failure, or due to the peer closing it gracefully.
998 /* GSocket_SetCallback:
999 * Enables the callbacks specified by 'flags'. Note that 'flags'
1000 * may be a combination of flags OR'ed toghether, so the same
1001 * callback function can be made to accept different events.
1002 * The callback function must have the following prototype:
1004 * void function(GSocket *socket, GSocketEvent event, char *cdata)
1006 void GSocket_SetCallback(GSocket
*socket
, GSocketEventFlags flags
,
1007 GSocketCallback callback
, char *cdata
)
1011 assert(socket
!= NULL
);
1013 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1015 if ((flags
& (1 << count
)) != 0)
1017 socket
->m_cbacks
[count
] = callback
;
1018 socket
->m_data
[count
] = cdata
;
1023 /* GSocket_UnsetCallback:
1024 * Disables all callbacks specified by 'flags', which may be a
1025 * combination of flags OR'ed toghether.
1027 void GSocket_UnsetCallback(GSocket
*socket
, GSocketEventFlags flags
)
1031 assert(socket
!= NULL
);
1033 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1035 if ((flags
& (1 << count
)) != 0)
1037 socket
->m_cbacks
[count
] = NULL
;
1038 socket
->m_data
[count
] = NULL
;
1044 #define CALL_CALLBACK(socket, event) { \
1045 _GSocket_Disable(socket, event); \
1046 if (socket->m_cbacks[event]) \
1047 socket->m_cbacks[event](socket, event, socket->m_data[event]); \
1050 int _GSocket_Recv_Stream(GSocket
*socket
, char *buffer
, int size
)
1054 OTByteCount sz
= 0 ;
1056 OTCountDataBytes( socket
->m_endpoint
, &sz
) ;
1057 res
= OTRcv( socket
->m_endpoint
, buffer
, size
, &flags
) ;
1063 // we simulate another read event if there are still bytes
1064 if ( socket
->m_takesEvents
)
1066 OTByteCount sz
= 0 ;
1067 OTCountDataBytes( socket
->m_endpoint
, &sz
) ;
1070 socket
->m_detected
|= GSOCK_INPUT_FLAG
;
1071 (socket
->m_cbacks
[GSOCK_INPUT
])(socket
, GSOCK_INPUT
, socket
->m_data
[GSOCK_INPUT
]);
1077 int _GSocket_Recv_Dgram(GSocket
*socket
, char *buffer
, int size
)
1082 struct sockaddr from
;
1083 SOCKLEN_T fromlen
= sizeof(from
);
1086 fromlen
= sizeof(from
);
1088 ret
= recvfrom(socket
->m_endpoint
, buffer
, size
, 0, &from
, (SOCKLEN_T
*) &fromlen
);
1093 /* Translate a system address into a GSocket address */
1094 if (!socket
->m_peer
)
1096 socket
->m_peer
= GAddress_new();
1097 if (!socket
->m_peer
)
1099 socket
->m_error
= GSOCK_MEMERR
;
1103 err
= _GAddress_translate_from(socket
->m_peer
, &from
, fromlen
);
1104 if (err
!= GSOCK_NOERROR
)
1106 GAddress_destroy(socket
->m_peer
);
1107 socket
->m_peer
= NULL
;
1108 socket
->m_error
= err
;
1115 int _GSocket_Send_Stream(GSocket
*socket
, const char *buffer
, int size
)
1120 res
= OTSnd( socket
->m_endpoint
, (void*) buffer
, size
, flags
) ;
1124 int _GSocket_Send_Dgram(GSocket
*socket
, const char *buffer
, int size
)
1129 struct sockaddr
*addr
;
1133 if (!socket
->m_peer
)
1135 socket
->m_error
= GSOCK_INVADDR
;
1139 err
= _GAddress_translate_to(socket
->m_peer
, &addr
, &len
);
1140 if (err
!= GSOCK_NOERROR
)
1142 socket
->m_error
= err
;
1146 ret
= sendto(socket
->m_endpoint
, buffer
, size
, 0, addr
, len
);
1148 /* Frees memory allocated from _GAddress_translate_to */
1156 * -------------------------------------------------------------------------
1158 * -------------------------------------------------------------------------
1161 /* CHECK_ADDRESS verifies that the current family is either GSOCK_NOFAMILY
1162 * or GSOCK_*family*, and if it is GSOCK_NOFAMILY, it initalizes address
1163 * to be a GSOCK_*family*. In other cases, it returns GSOCK_INVADDR.
1165 #define CHECK_ADDRESS(address, family, retval) \
1167 if (address->m_family == GSOCK_NOFAMILY) \
1168 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1169 return address->m_error; \
1170 if (address->m_family != GSOCK_##family) \
1172 address->m_error = GSOCK_INVADDR; \
1177 GAddress
*GAddress_new()
1181 if ((address
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1184 address
->m_family
= GSOCK_NOFAMILY
;
1185 address
->m_host
= INADDR_NONE
;
1186 address
->m_port
= 0 ;
1191 GAddress
*GAddress_copy(GAddress
*address
)
1195 assert(address
!= NULL
);
1197 if ((addr2
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1200 memcpy(addr2
, address
, sizeof(GAddress
));
1204 void GAddress_destroy(GAddress
*address
)
1206 assert(address
!= NULL
);
1211 void GAddress_SetFamily(GAddress
*address
, GAddressType type
)
1213 assert(address
!= NULL
);
1215 address
->m_family
= type
;
1218 GAddressType
GAddress_GetFamily(GAddress
*address
)
1220 assert(address
!= NULL
);
1222 return address
->m_family
;
1225 GSocketError
_GAddress_translate_from(GAddress
*address
,
1228 switch (addr
->fAddressType
)
1231 address
->m_family
= GSOCK_INET
;
1235 address
->m_family
= GSOCK_INET6
;
1240 address
->m_error
= GSOCK_INVOP
;
1244 address
->m_host
= addr
->fHost
;
1245 address
->m_port
= addr
->fPort
;
1246 return GSOCK_NOERROR
;
1249 GSocketError
_GAddress_translate_to(GAddress
*address
,
1252 memset(addr
, 0 , sizeof(struct InetAddress
));
1253 OTInitInetAddress( addr
, address
->m_port
, address
->m_host
) ;
1254 return GSOCK_NOERROR
;
1258 * -------------------------------------------------------------------------
1259 * Internet address family
1260 * -------------------------------------------------------------------------
1263 GSocketError
_GAddress_Init_INET(GAddress
*address
)
1265 address
->m_family
= GSOCK_INET
;
1266 address
->m_host
= kOTAnyInetAddress
;
1268 return GSOCK_NOERROR
;
1271 GSocketError
GAddress_INET_SetHostName(GAddress
*address
, const char *hostname
)
1273 InetHostInfo hinfo
;
1276 assert(address
!= NULL
);
1278 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1279 ret
= OTInetStringToAddress( gInetSvcRef
, (char*) hostname
, &hinfo
) ;
1280 if ( ret
!= kOTNoError
)
1282 address
->m_host
= INADDR_NONE
;
1283 address
->m_error
= GSOCK_NOHOST
;
1284 return GSOCK_NOHOST
;
1286 address
->m_host
= hinfo
.addrs
[0] ;
1287 return GSOCK_NOERROR
;
1290 GSocketError
GAddress_INET_SetAnyAddress(GAddress
*address
)
1292 return GAddress_INET_SetHostAddress(address
, INADDR_ANY
);
1295 GSocketError
GAddress_INET_SetHostAddress(GAddress
*address
,
1296 unsigned long hostaddr
)
1298 struct in_addr
*addr
;
1300 assert(address
!= NULL
);
1302 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1304 address
->m_host
= hostaddr
;
1306 return GSOCK_NOERROR
;
1309 struct service_entry
1312 unsigned short port
;
1315 typedef struct service_entry service_entry
;
1317 service_entry gServices
[] =
1319 { "http" , 80 , "tcp" }
1322 GSocketError
GAddress_INET_SetPortName(GAddress
*address
, const char *port
,
1323 const char *protocol
)
1328 assert(address
!= NULL
);
1329 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1333 address
->m_error
= GSOCK_INVPORT
;
1334 return GSOCK_INVPORT
;
1336 for ( i
= 0 ; i
< sizeof( gServices
) / sizeof( service_entry
) ; ++i
)
1338 if ( strcmp( port
, gServices
[i
].name
) == 0 )
1340 if ( protocol
== NULL
|| strcmp( protocol
, gServices
[i
].protocol
) )
1342 address
->m_port
= gServices
[i
].port
;
1343 return GSOCK_NOERROR
;
1348 if (isdigit(port
[0]))
1350 address
->m_port
= atoi(port
);
1351 return GSOCK_NOERROR
;
1354 address
->m_error
= GSOCK_INVPORT
;
1355 return GSOCK_INVPORT
;
1358 GSocketError
GAddress_INET_SetPort(GAddress
*address
, unsigned short port
)
1362 assert(address
!= NULL
);
1363 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1364 address
->m_port
= port
;
1366 return GSOCK_NOERROR
;
1369 GSocketError
GAddress_INET_GetHostName(GAddress
*address
, char *hostname
, size_t sbuf
)
1371 InetDomainName name
;
1373 assert(address
!= NULL
);
1374 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1376 OTInetAddressToName( gInetSvcRef
, address
->m_host
, name
) ;
1377 strncpy( hostname
, name
, sbuf
) ;
1378 return GSOCK_NOERROR
;
1381 unsigned long GAddress_INET_GetHostAddress(GAddress
*address
)
1383 assert(address
!= NULL
);
1384 CHECK_ADDRESS(address
, INET
, 0);
1386 return address
->m_host
;
1389 unsigned short GAddress_INET_GetPort(GAddress
*address
)
1391 assert(address
!= NULL
);
1392 CHECK_ADDRESS(address
, INET
, 0);
1394 return address
->m_port
;
1397 void _GSocket_Enable_Events(GSocket
*socket
)
1399 if ( socket
->m_takesEvents
)
1404 socket
->m_takesEvents
= TRUE
;
1405 state
= OTGetEndpointState(socket
->m_endpoint
);
1408 OTByteCount sz
= 0 ;
1409 OTCountDataBytes( socket
->m_endpoint
, &sz
) ;
1410 if ( state
== T_INCON
|| sz
> 0 )
1412 socket
->m_detected
|= GSOCK_INPUT_FLAG
;
1413 (socket
->m_cbacks
[GSOCK_INPUT
])(socket
, GSOCK_INPUT
, socket
->m_data
[GSOCK_INPUT
]);
1417 if ( state
== T_DATAXFER
|| state
== T_INREL
)
1419 socket
->m_detected
|=GSOCK_OUTPUT_FLAG
;
1420 (socket
->m_cbacks
[GSOCK_OUTPUT
])(socket
, GSOCK_OUTPUT
, socket
->m_data
[GSOCK_OUTPUT
]);
1426 void _GSocket_Disable_Events(GSocket
*socket
)
1428 socket
->m_takesEvents
= FALSE
;
1431 /* _GSocket_Input_Timeout:
1432 * For blocking sockets, wait until data is available or
1433 * until timeout ellapses.
1435 GSocketError
_GSocket_Input_Timeout(GSocket
*socket
)
1437 if ( !socket
->m_non_blocking
)
1439 UnsignedWide now
, start
;
1440 short formerTakesEvents
= socket
->m_takesEvents
;
1441 Microseconds(&start
);
1443 socket
->m_takesEvents
= FALSE
;
1445 while( (now
.hi
* 4294967296.0 + now
.lo
) - (start
.hi
* 4294967296.0 + start
.lo
) < socket
->m_timeout
* 1000.0 )
1448 OTByteCount sz
= 0 ;
1449 state
= OTGetEndpointState(socket
->m_endpoint
);
1451 OTCountDataBytes( socket
->m_endpoint
, &sz
) ;
1452 if ( state
== T_INCON
|| sz
> 0 )
1454 socket
->m_takesEvents
= formerTakesEvents
;
1455 return GSOCK_NOERROR
;
1459 socket
->m_takesEvents
= formerTakesEvents
;
1460 socket
->m_error
= GSOCK_TIMEDOUT
;
1461 return GSOCK_TIMEDOUT
;
1463 return GSOCK_NOERROR
;
1466 /* _GSocket_Output_Timeout:
1467 * For blocking sockets, wait until data can be sent without
1468 * blocking or until timeout ellapses.
1470 GSocketError
_GSocket_Output_Timeout(GSocket
*socket
)
1472 if ( !socket
->m_non_blocking
)
1474 UnsignedWide now
, start
;
1475 short formerTakesEvents
= socket
->m_takesEvents
;
1476 Microseconds(&start
);
1478 socket
->m_takesEvents
= FALSE
;
1480 while( (now
.hi
* 4294967296.0 + now
.lo
) - (start
.hi
* 4294967296.0 + start
.lo
) < socket
->m_timeout
* 1000.0 )
1483 state
= OTGetEndpointState(socket
->m_endpoint
);
1485 if ( state
== T_DATAXFER
|| state
== T_INREL
)
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
;
1500 * There is data to be read in the input buffer. If, after a read
1501 * operation, there is still data available, the callback function will
1504 * The socket is available for writing. That is, the next write call
1505 * won't block. This event is generated only once, when the connection is
1506 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
1507 * when the output buffer empties again. This means that the app should
1508 * assume that it can write since the first OUTPUT event, and no more
1509 * OUTPUT events will be generated unless an error occurs.
1511 * Connection succesfully established, for client sockets, or incoming
1512 * client connection, for server sockets. Wait for this event (also watch
1513 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
1515 * The connection is lost (or a connection request failed); this could
1516 * be due to a failure, or due to the peer closing it gracefully.
1519 void _GSocket_Internal_Proc(unsigned long e
, void* d
)
1522 GSocket
* socket
= (GSocket
*) d
;
1523 OTEventCode ev
= (OTEventCode
) e
;
1525 GSocketEvent event2
;
1526 GSocketCallback cback
;
1528 GSocketCallback cback2
;
1533 event
= GSOCK_MAX_EVENT
;
1534 event2
= GSOCK_MAX_EVENT
;
1540 /* Check that the socket still exists (it has not been
1541 * destroyed) and for safety, check that the m_endpoint field
1542 * is what we expect it to be.
1544 if ((socket
!= NULL
) && (socket
->m_takesEvents
))
1549 event
= GSOCK_CONNECTION
;
1552 event
= GSOCK_CONNECTION
;
1553 event2
= GSOCK_OUTPUT
;
1557 retCall
.addr
.buf
= NULL
;
1558 retCall
.addr
.maxlen
= 0;
1559 retCall
.opt
.buf
= NULL
;
1560 retCall
.opt
.maxlen
= 0;
1561 retCall
.udata
.buf
= NULL
;
1562 retCall
.udata
.maxlen
= 0;
1563 OTRcvConnect( socket
->m_endpoint
, &retCall
) ;
1567 event
= GSOCK_LOST
;
1571 event
= GSOCK_OUTPUT
;
1574 event
= GSOCK_INPUT
;
1577 event
= GSOCK_INPUT
;
1580 if (event
!= GSOCK_MAX_EVENT
)
1582 cback
= socket
->m_cbacks
[event
];
1583 data
= socket
->m_data
[event
];
1585 if (event
== GSOCK_LOST
)
1586 socket
->m_detected
= GSOCK_LOST_FLAG
;
1588 socket
->m_detected
|= (1 << event
);
1590 if (event2
!= GSOCK_MAX_EVENT
)
1592 cback2
= socket
->m_cbacks
[event2
];
1593 data2
= socket
->m_data
[event2
];
1595 if (event2
== GSOCK_LOST
)
1596 socket
->m_detected
= GSOCK_LOST_FLAG
;
1598 socket
->m_detected
|= (1 << event2
);
1602 /* OK, we can now leave the critical section because we have
1603 * already obtained the callback address (we make no further
1604 * accesses to socket->whatever). However, the app should
1605 * be prepared to handle events from a socket that has just
1610 (cback
)(socket
, event
, data
);
1612 (cback2
)(socket
, event2
, data2
);
1616 /* Hack added for Mac OS X */
1617 GSocketError
GAddress_UNIX_GetPath(GAddress
*addr
, char *path
, size_t buf
)
1621 GSocketError
GAddress_UNIX_SetPath(GAddress
*addr
, const char *path
)
1625 #endif /* wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__) */