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 */
201 int GSocket_Verify_Inited() ;
202 int GSocket_Verify_Inited()
206 // Marc Newsam: added the clientcontext variable
207 // however, documentation is unclear how this works
208 OTClientContextPtr clientcontext
;
213 InitOpenTransportInContext(kInitOTForApplicationMask
, &clientcontext
);
214 gInetSvcRef
= OTOpenInternetServicesInContext(kDefaultInternetServicesPath
,
215 NULL
, &err
, clientcontext
);
220 InitOpenTransport() ;
221 gInetSvcRef
= OTOpenInternetServices(kDefaultInternetServicesPath
, NULL
, &err
);
223 if ( gInetSvcRef
== NULL
|| err
!= kOTNoError
)
225 OTAssert("Could not open Inet Services", err
== noErr
);
231 void GSocket_Cleanup()
233 if ( gInetSvcRef
!= NULL
)
234 OTCloseProvider( gInetSvcRef
);
236 CloseOpenTransportInContext( NULL
) ;
238 CloseOpenTransport() ;
242 /* Constructors / Destructors for GSocket */
244 GSocket
*GSocket_new()
250 if ( GSocket_Verify_Inited() == FALSE
)
253 socket
= (GSocket
*)malloc(sizeof(GSocket
));
258 socket
->m_endpoint
= NULL
;
259 for (i
=0;i
<GSOCK_MAX_EVENT
;i
++)
261 socket
->m_cbacks
[i
] = NULL
;
263 socket
->m_detected
= 0;
264 socket
->m_local
= NULL
;
265 socket
->m_peer
= NULL
;
266 socket
->m_error
= GSOCK_NOERROR
;
267 socket
->m_server
= FALSE
;
268 socket
->m_stream
= TRUE
;
269 socket
->m_non_blocking
= FALSE
;
270 socket
->m_timeout
= 1*1000;
271 /* 10 sec * 1000 millisec */
272 socket
->m_takesEvents
= TRUE
;
273 socket
->m_mac_events
= wxMacGetNotifierTable() ;
277 void GSocket_destroy(GSocket
*socket
)
279 assert(socket
!= NULL
);
281 /* Check that the socket is really shutdowned */
282 if (socket
->m_endpoint
!= kOTInvalidEndpointRef
)
283 GSocket_Shutdown(socket
);
286 /* Destroy private addresses */
288 GAddress_destroy(socket
->m_local
);
291 GAddress_destroy(socket
->m_peer
);
293 /* Destroy the socket itself */
298 * Disallow further read/write operations on this socket, close
299 * the fd and disable all callbacks.
301 void GSocket_Shutdown(GSocket
*socket
)
306 assert(socket
!= NULL
);
308 /* If socket has been created, shutdown it */
309 if (socket
->m_endpoint
!= kOTInvalidEndpointRef
)
311 err
= OTSndOrderlyDisconnect( socket
->m_endpoint
) ;
312 if ( err
!= kOTNoError
)
316 err
= OTRcvOrderlyDisconnect( socket
->m_endpoint
) ;
317 err
= OTUnbind( socket
->m_endpoint
) ;
318 err
= OTCloseProvider( socket
->m_endpoint
) ;
319 socket
->m_endpoint
= kOTInvalidEndpointRef
;
322 /* Disable GUI callbacks */
323 for (evt
= 0; evt
< GSOCK_MAX_EVENT
; evt
++)
324 socket
->m_cbacks
[evt
] = NULL
;
326 socket
->m_detected
= 0;
327 _GSocket_Disable_Events(socket
);
328 wxMacRemoveAllNotifiersForData( wxMacGetNotifierTable() , socket
) ;
332 /* Address handling */
338 * Set or get the local or peer address for this socket. The 'set'
339 * functions return GSOCK_NOERROR on success, an error code otherwise.
340 * The 'get' functions return a pointer to a GAddress object on success,
341 * or NULL otherwise, in which case they set the error code of the
342 * corresponding GSocket.
345 * GSOCK_INVSOCK - the socket is not valid.
346 * GSOCK_INVADDR - the address is not valid.
348 GSocketError
GSocket_SetLocal(GSocket
*socket
, GAddress
*address
)
350 assert(socket
!= NULL
);
352 /* the socket must be initialized, or it must be a server */
353 if ((socket
->m_endpoint
!= kOTInvalidEndpointRef
&& !socket
->m_server
))
355 socket
->m_error
= GSOCK_INVSOCK
;
356 return GSOCK_INVSOCK
;
360 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
362 socket
->m_error
= GSOCK_INVADDR
;
363 return GSOCK_INVADDR
;
367 GAddress_destroy(socket
->m_local
);
369 socket
->m_local
= GAddress_copy(address
);
371 return GSOCK_NOERROR
;
374 GSocketError
GSocket_SetPeer(GSocket
*socket
, GAddress
*address
)
376 assert(socket
!= NULL
);
379 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
381 socket
->m_error
= GSOCK_INVADDR
;
382 return GSOCK_INVADDR
;
386 GAddress_destroy(socket
->m_peer
);
388 socket
->m_peer
= GAddress_copy(address
);
390 return GSOCK_NOERROR
;
393 GAddress
*GSocket_GetLocal(GSocket
*socket
)
395 GAddress
*address
= NULL
;
399 assert(socket
!= NULL
);
401 /* try to get it from the m_local var first */
403 return GAddress_copy(socket
->m_local
);
405 /* else, if the socket is initialized, try getsockname */
406 if (socket
->m_endpoint
== kOTInvalidEndpointRef
)
408 socket
->m_error
= GSOCK_INVSOCK
;
413 /* we do not support multihoming with this code at the moment
414 OTGetProtAddress will have to be used then - but we don't have a handy
415 method to use right now
418 InetInterfaceInfo info
;
419 OTInetGetInterfaceInfo(&info
, kDefaultInetInterface
);
420 loc
.fHost
= info
.fAddress
;
422 loc
.fAddressType
= AF_INET
;
425 /* got a valid address from getsockname, create a GAddress object */
426 address
= GAddress_new();
429 socket
->m_error
= GSOCK_MEMERR
;
433 err
= _GAddress_translate_from(address
, &loc
);
434 if (err
!= GSOCK_NOERROR
)
436 GAddress_destroy(address
);
437 socket
->m_error
= err
;
444 GAddress
*GSocket_GetPeer(GSocket
*socket
)
446 assert(socket
!= NULL
);
448 /* try to get it from the m_peer var */
450 return GAddress_copy(socket
->m_peer
);
455 /* Server specific parts */
457 /* GSocket_SetServer:
458 * Sets up this socket as a server. The local address must have been
459 * set with GSocket_SetLocal() before GSocket_SetServer() is called.
460 * Returns GSOCK_NOERROR on success, one of the following otherwise:
463 * GSOCK_INVSOCK - the socket is in use.
464 * GSOCK_INVADDR - the local address has not been set.
465 * GSOCK_IOERR - low-level error.
467 GSocketError
GSocket_SetServer(GSocket
*sck
)
474 /* must not be in use */
475 if (sck
->m_endpoint
!= kOTInvalidEndpointRef
)
477 sck
->m_error
= GSOCK_INVSOCK
;
478 return GSOCK_INVSOCK
;
481 /* the local addr must have been set */
484 sck
->m_error
= GSOCK_INVADDR
;
485 return GSOCK_INVADDR
;
488 /* Initialize all fields */
489 sck
->m_stream
= TRUE
;
490 sck
->m_server
= TRUE
;
491 sck
->m_oriented
= TRUE
;
495 /* Create the socket */
496 sck
->m_endpoint
= socket(sck
->m_local
->m_realfamily
, SOCK_STREAM
, 0);
497 socket_set_ref( sck
->m_endpoint
, (unsigned long) &gMacNetEvents
, (unsigned long) sck
) ;
498 if (sck
->m_endpoint
== kOTInvalidEndpointRef
)
500 sck
->m_error
= GSOCK_IOERR
;
504 ioctl(sck
->m_endpoint
, FIONBIO
, &arg
);
505 _GSocket_Enable_Events(sck
);
507 /* Bind to the local address,
508 * retrieve the actual address bound,
509 * and listen up to 5 connections.
511 if ((bind(sck
->m_endpoint
, sck
->m_local
->m_addr
, sck
->m_local
->m_len
) != 0) ||
512 (getsockname(sck
->m_endpoint
,
513 sck
->m_local
->m_addr
,
514 (SOCKLEN_T
*) &sck
->m_local
->m_len
) != 0) ||
515 (listen(sck
->m_endpoint
, 5) != 0))
517 close(sck
->m_endpoint
);
518 sck
->m_endpoint
= -1;
519 sck
->m_error
= GSOCK_IOERR
;
523 return GSOCK_NOERROR
;
526 /* GSocket_WaitConnection:
527 * Waits for an incoming client connection. Returns a pointer to
528 * a GSocket object, or NULL if there was an error, in which case
529 * the last error field will be updated for the calling GSocket.
531 * Error codes (set in the calling GSocket)
532 * GSOCK_INVSOCK - the socket is not valid or not a server.
533 * GSOCK_TIMEDOUT - timeout, no incoming connections.
534 * GSOCK_WOULDBLOCK - the call would block and the socket is nonblocking.
535 * GSOCK_MEMERR - couldn't allocate memory.
536 * GSOCK_IOERR - low-level error.
538 GSocket
*GSocket_WaitConnection(GSocket
*socket
)
540 GSocket
*connection
= NULL
;
545 assert(socket
!= NULL
);
547 /* Reenable CONNECTION events */
548 socket
->m_detected
&= ~GSOCK_CONNECTION_FLAG
;
550 /* If the socket has already been created, we exit immediately */
551 if (socket
->m_endpoint
== kOTInvalidEndpointRef
|| !socket
->m_server
)
553 socket
->m_error
= GSOCK_INVSOCK
;
557 /* Create a GSocket object for the new connection */
558 connection
= GSocket_new();
562 socket
->m_error
= GSOCK_MEMERR
;
566 /* Wait for a connection (with timeout) */
567 if (_GSocket_Input_Timeout(socket
) == GSOCK_TIMEDOUT
)
569 GSocket_destroy(connection
);
570 /* socket->m_error set by _GSocket_Input_Timeout */
576 connection
->m_endpoint
= accept(socket
->m_endpoint
, &from
, (SOCKLEN_T
*) &fromlen
);
579 if (connection
->m_endpoint
== kOTInvalidEndpointRef
)
581 if (errno
== EWOULDBLOCK
)
582 socket
->m_error
= GSOCK_WOULDBLOCK
;
584 socket
->m_error
= GSOCK_IOERR
;
586 GSocket_destroy(connection
);
590 /* Initialize all fields */
591 connection
->m_server
= FALSE
;
592 connection
->m_stream
= TRUE
;
593 connection
->m_oriented
= TRUE
;
595 /* Setup the peer address field */
596 connection
->m_peer
= GAddress_new();
597 if (!connection
->m_peer
)
599 GSocket_destroy(connection
);
600 socket
->m_error
= GSOCK_MEMERR
;
605 err
= _GAddress_translate_from(connection
->m_peer
, &from
, fromlen
);
606 if (err
!= GSOCK_NOERROR
)
608 GAddress_destroy(connection
->m_peer
);
609 GSocket_destroy(connection
);
610 socket
->m_error
= err
;
614 ioctl(connection
->m_endpoint
, FIONBIO
, &arg
);
616 _GSocket_Enable_Events(connection
);
621 /* Datagram sockets */
623 /* GSocket_SetNonOriented:
624 * Sets up this socket as a non-connection oriented (datagram) socket.
625 * Before using this function, the local address must have been set
626 * with GSocket_SetLocal(), or the call will fail. Returns GSOCK_NOERROR
627 * on success, or one of the following otherwise.
630 * GSOCK_INVSOCK - the socket is in use.
631 * GSOCK_INVADDR - the local address has not been set.
632 * GSOCK_IOERR - low-level error.
634 GSocketError
GSocket_SetNonOriented(GSocket
*sck
)
640 if (sck
->m_endpoint
!= kOTInvalidEndpointRef
)
642 sck
->m_error
= GSOCK_INVSOCK
;
643 return GSOCK_INVSOCK
;
648 sck
->m_error
= GSOCK_INVADDR
;
649 return GSOCK_INVADDR
;
652 /* Initialize all fields */
653 sck
->m_stream
= FALSE
;
654 sck
->m_server
= FALSE
;
655 sck
->m_oriented
= FALSE
;
657 /* Create the socket */
661 sck
->m_endpoint
= socket(sck
->m_local
->m_realfamily
, SOCK_DGRAM
, 0);
662 socket_set_ref( sck
->m_endpoint
, (unsigned long) &gMacNetEvents
, (unsigned long) sck
) ;
664 if (sck
->m_endpoint
== kOTInvalidEndpointRef
)
666 sck
->m_error
= GSOCK_IOERR
;
672 ioctl(sck
->m_endpoint
, FIONBIO
, &arg
);
674 _GSocket_Enable_Events(sck
);
676 /* Bind to the local address,
677 * and retrieve the actual address bound.
681 if ((bind(sck
->m_endpoint
, sck
->m_local
->m_addr
, sck
->m_local
->m_len
) != 0) ||
682 (getsockname(sck
->m_endpoint
,
683 sck
->m_local
->m_addr
,
684 (SOCKLEN_T
*) &sck
->m_local
->m_len
) != 0))
686 close(sck
->m_endpoint
);
687 sck
->m_endpoint
= -1;
688 sck
->m_error
= GSOCK_IOERR
;
692 return GSOCK_NOERROR
;
695 /* Client specific parts */
698 * For stream (connection oriented) sockets, GSocket_Connect() tries
699 * to establish a client connection to a server using the peer address
700 * as established with GSocket_SetPeer(). Returns GSOCK_NOERROR if the
701 * connection has been succesfully established, or one of the error
702 * codes listed below. Note that for nonblocking sockets, a return
703 * value of GSOCK_WOULDBLOCK doesn't mean a failure. The connection
704 * request can be completed later; you should use GSocket_Select()
705 * to poll for GSOCK_CONNECTION | GSOCK_LOST, or wait for the
706 * corresponding asynchronous events.
708 * For datagram (non connection oriented) sockets, GSocket_Connect()
709 * just sets the peer address established with GSocket_SetPeer() as
710 * default destination.
713 * GSOCK_INVSOCK - the socket is in use or not valid.
714 * GSOCK_INVADDR - the peer address has not been established.
715 * GSOCK_TIMEDOUT - timeout, the connection failed.
716 * GSOCK_WOULDBLOCK - connection in progress (nonblocking sockets only)
717 * GSOCK_MEMERR - couldn't allocate memory.
718 * GSOCK_IOERR - low-level error.
720 GSocketError
GSocket_Connect(GSocket
*sck
, GSocketStream stream
)
727 OSStatus err
= kOTNoError
;
732 /* Enable CONNECTION events (needed for nonblocking connections) */
733 sck
->m_detected
&= ~GSOCK_CONNECTION_FLAG
;
735 if (sck
->m_endpoint
!= kOTInvalidEndpointRef
)
737 sck
->m_error
= GSOCK_INVSOCK
;
738 return GSOCK_INVSOCK
;
743 sck
->m_error
= GSOCK_INVADDR
;
744 return GSOCK_INVADDR
;
747 /* Streamed or dgram socket? */
748 sck
->m_stream
= (stream
== GSOCK_STREAMED
);
749 sck
->m_oriented
= TRUE
;
750 sck
->m_server
= FALSE
;
752 /* Create the socket */
755 OTOpenEndpointInContext( OTCreateConfiguration( kTCPName
) , 0 , &info
, &err
, NULL
) ;
758 OTOpenEndpoint( OTCreateConfiguration( kTCPName
) , 0 , &info
, &err
) ;
760 if ( sck
->m_endpoint
== kOTInvalidEndpointRef
|| err
!= kOTNoError
)
762 sck
->m_endpoint
= kOTInvalidEndpointRef
;
763 sck
->m_error
= GSOCK_IOERR
;
766 err
= OTBind( sck
->m_endpoint
, nil
, nil
) ;
767 if ( err
!= kOTNoError
)
771 SetDefaultEndpointModes( sck
->m_endpoint
, sck
) ;
774 ioctl(sck
->m_endpoint
, FIONBIO
, &arg
);
776 _GSocket_Enable_Events(sck
);
778 _GAddress_translate_to( sck
->m_peer
, &addr
) ;
779 memset( &peer
, 0 , sizeof( TCall
) ) ;
780 peer
.addr
.len
= sizeof( InetAddress
) ;
781 peer
.addr
.buf
= (unsigned char*) &addr
;
782 err
= OTConnect( sck
->m_endpoint
, &peer
, nil
) ;
785 /* If connect failed with EINPROGRESS and the GSocket object
786 * is in blocking mode, we select() for the specified timeout
787 * checking for writability to see if the connection request
791 if ((err
== kOTNoDataErr
) && (!sck
->m_non_blocking
))
793 if (_GSocket_Output_Timeout(sck
) == GSOCK_TIMEDOUT
)
795 OTSndOrderlyDisconnect( sck
->m_endpoint
) ;
796 sck
->m_endpoint
= kOTInvalidEndpointRef
;
797 /* sck->m_error is set in _GSocket_Output_Timeout */
798 return GSOCK_TIMEDOUT
;
804 SOCKLEN_T len = sizeof(error);
806 getsockopt(sck->m_endpoint, SOL_SOCKET, SO_ERROR, (void*) &error, &len);
810 return GSOCK_NOERROR
;
814 /* If connect failed with EINPROGRESS and the GSocket object
815 * is set to nonblocking, we set m_error to GSOCK_WOULDBLOCK
816 * (and return GSOCK_WOULDBLOCK) but we don't close the socket;
817 * this way if the connection completes, a GSOCK_CONNECTION
818 * event will be generated, if enabled.
820 if ((err
== kOTNoDataErr
) && (sck
->m_non_blocking
))
822 sck
->m_error
= GSOCK_WOULDBLOCK
;
823 return GSOCK_WOULDBLOCK
;
826 /* If connect failed with an error other than EINPROGRESS,
827 * then the call to GSocket_Connect has failed.
829 OTSndOrderlyDisconnect( sck
->m_endpoint
) ;
831 sck
->m_endpoint
= kOTInvalidEndpointRef
;
832 sck
->m_error
= GSOCK_IOERR
;
835 // OTInetEventHandler(sck, T_CONNECT , kOTNoError , NULL ) ;
836 return GSOCK_NOERROR
;
841 /* Like recv(), send(), ... */
842 int GSocket_Read(GSocket
*socket
, char *buffer
, int size
)
846 assert(socket
!= NULL
);
848 /* Reenable INPUT events */
849 socket
->m_detected
&= ~GSOCK_INPUT_FLAG
;
851 if (socket
->m_endpoint
== kOTInvalidEndpointRef
|| socket
->m_server
)
853 socket
->m_error
= GSOCK_INVSOCK
;
857 /* If the socket is blocking, wait for data (with a timeout) */
858 if (_GSocket_Input_Timeout(socket
) == GSOCK_TIMEDOUT
)
862 if (socket
->m_stream
)
863 ret
= _GSocket_Recv_Stream(socket
, buffer
, size
);
865 ret
= _GSocket_Recv_Dgram(socket
, buffer
, size
);
869 if (errno
== EWOULDBLOCK
)
870 socket
->m_error
= GSOCK_WOULDBLOCK
;
872 socket
->m_error
= GSOCK_IOERR
;
878 int GSocket_Write(GSocket
*socket
, const char *buffer
, int size
)
882 assert(socket
!= NULL
);
884 if (socket
->m_endpoint
== kOTInvalidEndpointRef
|| socket
->m_server
)
886 socket
->m_error
= GSOCK_INVSOCK
;
890 /* If the socket is blocking, wait for writability (with a timeout) */
891 if (_GSocket_Output_Timeout(socket
) == GSOCK_TIMEDOUT
)
895 if (socket
->m_stream
)
896 ret
= _GSocket_Send_Stream(socket
, buffer
, size
);
898 ret
= _GSocket_Send_Dgram(socket
, buffer
, size
);
902 if (errno
== EWOULDBLOCK
)
903 socket
->m_error
= GSOCK_WOULDBLOCK
;
905 socket
->m_error
= GSOCK_IOERR
;
907 /* Only reenable OUTPUT events after an error (just like WSAAsyncSelect
908 * in MSW). Once the first OUTPUT event is received, users can assume
909 * that the socket is writable until a read operation fails. Only then
910 * will further OUTPUT events be posted.
912 socket
->m_detected
&= ~GSOCK_OUTPUT_FLAG
;
920 * Polls the socket to determine its status. This function will
921 * check for the events specified in the 'flags' parameter, and
922 * it will return a mask indicating which operations can be
923 * performed. This function won't block, regardless of the
924 * mode (blocking | nonblocking) of the socket.
926 GSocketEventFlags
GSocket_Select(GSocket
*socket
, GSocketEventFlags flags
)
929 assert(socket
!= NULL
);
930 wxMacProcessNotifierEvents() ;
932 state = OTGetEndpointState(socket->m_endpoint);
934 if ( ( flags & GSOCK_INPUT_FLAG ) && ! ( socket->m_detected & GSOCK_INPUT_FLAG ) )
937 OTCountDataBytes( socket->m_endpoint , &sz ) ;
938 if ( state == T_INCON || sz > 0 )
940 socket->m_detected |= GSOCK_INPUT_FLAG ;
941 (socket->m_cbacks[GSOCK_INPUT])(socket, GSOCK_INPUT, socket->m_data[GSOCK_INPUT]);
944 if ( ( flags & GSOCK_INPUT_FLAG ) && ! ( socket->m_detected & GSOCK_OUTPUT_FLAG ) )
946 if ( state == T_DATAXFER || state == T_INREL )
948 socket->m_detected |=GSOCK_OUTPUT_FLAG ;
949 (socket->m_cbacks[GSOCK_OUTPUT])(socket, GSOCK_OUTPUT, socket->m_data[GSOCK_OUTPUT]);
953 return ( flags
& socket
->m_detected
) ;
958 /* GSocket_SetNonBlocking:
959 * Sets the socket to non-blocking mode. All IO calls will return
962 void GSocket_SetNonBlocking(GSocket
*socket
, int non_block
)
964 assert(socket
!= NULL
);
966 socket
->m_non_blocking
= non_block
;
969 /* GSocket_SetTimeout:
970 * Sets the timeout for blocking calls. Time is expressed in
973 void GSocket_SetTimeout(GSocket
*socket
, unsigned long millisec
)
975 assert(socket
!= NULL
);
977 // this is usually set too high and we have not yet been able to detect a closed
978 // stream, thus we leave the 10 sec timeout
979 // socket->m_timeout = millisec;
983 * Returns the last error occured for this socket. Note that successful
984 * operations do not clear this back to GSOCK_NOERROR, so use it only
987 GSocketError
GSocket_GetError(GSocket
*socket
)
989 assert(socket
!= NULL
);
991 return socket
->m_error
;
997 * There is data to be read in the input buffer. If, after a read
998 * operation, there is still data available, the callback function will
1001 * The socket is available for writing. That is, the next write call
1002 * won't block. This event is generated only once, when the connection is
1003 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
1004 * when the output buffer empties again. This means that the app should
1005 * assume that it can write since the first OUTPUT event, and no more
1006 * OUTPUT events will be generated unless an error occurs.
1008 * Connection succesfully established, for client sockets, or incoming
1009 * client connection, for server sockets. Wait for this event (also watch
1010 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
1012 * The connection is lost (or a connection request failed); this could
1013 * be due to a failure, or due to the peer closing it gracefully.
1016 /* GSocket_SetCallback:
1017 * Enables the callbacks specified by 'flags'. Note that 'flags'
1018 * may be a combination of flags OR'ed toghether, so the same
1019 * callback function can be made to accept different events.
1020 * The callback function must have the following prototype:
1022 * void function(GSocket *socket, GSocketEvent event, char *cdata)
1024 void GSocket_SetCallback(GSocket
*socket
, GSocketEventFlags flags
,
1025 GSocketCallback callback
, char *cdata
)
1029 assert(socket
!= NULL
);
1031 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1033 if ((flags
& (1 << count
)) != 0)
1035 socket
->m_cbacks
[count
] = callback
;
1036 socket
->m_data
[count
] = cdata
;
1041 /* GSocket_UnsetCallback:
1042 * Disables all callbacks specified by 'flags', which may be a
1043 * combination of flags OR'ed toghether.
1045 void GSocket_UnsetCallback(GSocket
*socket
, GSocketEventFlags flags
)
1049 assert(socket
!= NULL
);
1051 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1053 if ((flags
& (1 << count
)) != 0)
1055 socket
->m_cbacks
[count
] = NULL
;
1056 socket
->m_data
[count
] = NULL
;
1062 #define CALL_CALLBACK(socket, event) { \
1063 _GSocket_Disable(socket, event); \
1064 if (socket->m_cbacks[event]) \
1065 socket->m_cbacks[event](socket, event, socket->m_data[event]); \
1068 int _GSocket_Recv_Stream(GSocket
*socket
, char *buffer
, int size
)
1072 OTByteCount sz
= 0 ;
1074 OTCountDataBytes( socket
->m_endpoint
, &sz
) ;
1077 res
= OTRcv( socket
->m_endpoint
, buffer
, size
, &flags
) ;
1083 // we simulate another read event if there are still bytes
1084 if ( socket
->m_takesEvents
)
1086 OTByteCount sz
= 0 ;
1087 OTCountDataBytes( socket
->m_endpoint
, &sz
) ;
1090 socket
->m_detected
|= GSOCK_INPUT_FLAG
;
1091 (socket
->m_cbacks
[GSOCK_INPUT
])(socket
, GSOCK_INPUT
, socket
->m_data
[GSOCK_INPUT
]);
1097 int _GSocket_Recv_Dgram(GSocket
*socket
, char *buffer
, int size
)
1102 struct sockaddr from
;
1103 SOCKLEN_T fromlen
= sizeof(from
);
1106 fromlen
= sizeof(from
);
1108 ret
= recvfrom(socket
->m_endpoint
, buffer
, size
, 0, &from
, (SOCKLEN_T
*) &fromlen
);
1113 /* Translate a system address into a GSocket address */
1114 if (!socket
->m_peer
)
1116 socket
->m_peer
= GAddress_new();
1117 if (!socket
->m_peer
)
1119 socket
->m_error
= GSOCK_MEMERR
;
1123 err
= _GAddress_translate_from(socket
->m_peer
, &from
, fromlen
);
1124 if (err
!= GSOCK_NOERROR
)
1126 GAddress_destroy(socket
->m_peer
);
1127 socket
->m_peer
= NULL
;
1128 socket
->m_error
= err
;
1135 int _GSocket_Send_Stream(GSocket
*socket
, const char *buffer
, int size
)
1140 res
= OTSnd( socket
->m_endpoint
, (void*) buffer
, size
, flags
) ;
1144 int _GSocket_Send_Dgram(GSocket
*socket
, const char *buffer
, int size
)
1149 struct sockaddr
*addr
;
1153 if (!socket
->m_peer
)
1155 socket
->m_error
= GSOCK_INVADDR
;
1159 err
= _GAddress_translate_to(socket
->m_peer
, &addr
, &len
);
1160 if (err
!= GSOCK_NOERROR
)
1162 socket
->m_error
= err
;
1166 ret
= sendto(socket
->m_endpoint
, buffer
, size
, 0, addr
, len
);
1168 /* Frees memory allocated from _GAddress_translate_to */
1176 * -------------------------------------------------------------------------
1178 * -------------------------------------------------------------------------
1181 /* CHECK_ADDRESS verifies that the current family is either GSOCK_NOFAMILY
1182 * or GSOCK_*family*, and if it is GSOCK_NOFAMILY, it initalizes address
1183 * to be a GSOCK_*family*. In other cases, it returns GSOCK_INVADDR.
1185 #define CHECK_ADDRESS(address, family, retval) \
1187 if (address->m_family == GSOCK_NOFAMILY) \
1188 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1189 return address->m_error; \
1190 if (address->m_family != GSOCK_##family) \
1192 address->m_error = GSOCK_INVADDR; \
1197 GAddress
*GAddress_new()
1201 if ((address
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1204 address
->m_family
= GSOCK_NOFAMILY
;
1205 address
->m_host
= INADDR_NONE
;
1206 address
->m_port
= 0 ;
1211 GAddress
*GAddress_copy(GAddress
*address
)
1215 assert(address
!= NULL
);
1217 if ((addr2
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1220 memcpy(addr2
, address
, sizeof(GAddress
));
1224 void GAddress_destroy(GAddress
*address
)
1226 assert(address
!= NULL
);
1231 void GAddress_SetFamily(GAddress
*address
, GAddressType type
)
1233 assert(address
!= NULL
);
1235 address
->m_family
= type
;
1238 GAddressType
GAddress_GetFamily(GAddress
*address
)
1240 assert(address
!= NULL
);
1242 return address
->m_family
;
1245 GSocketError
_GAddress_translate_from(GAddress
*address
,
1248 switch (addr
->fAddressType
)
1251 address
->m_family
= GSOCK_INET
;
1255 address
->m_family
= GSOCK_INET6
;
1260 address
->m_error
= GSOCK_INVOP
;
1264 address
->m_host
= addr
->fHost
;
1265 address
->m_port
= addr
->fPort
;
1266 return GSOCK_NOERROR
;
1269 GSocketError
_GAddress_translate_to(GAddress
*address
,
1272 if ( GSocket_Verify_Inited() == FALSE
)
1273 return GSOCK_IOERR
;
1274 memset(addr
, 0 , sizeof(struct InetAddress
));
1275 OTInitInetAddress( addr
, address
->m_port
, address
->m_host
) ;
1276 return GSOCK_NOERROR
;
1280 * -------------------------------------------------------------------------
1281 * Internet address family
1282 * -------------------------------------------------------------------------
1285 GSocketError
_GAddress_Init_INET(GAddress
*address
)
1287 address
->m_family
= GSOCK_INET
;
1288 address
->m_host
= kOTAnyInetAddress
;
1290 return GSOCK_NOERROR
;
1293 GSocketError
GAddress_INET_SetHostName(GAddress
*address
, const char *hostname
)
1295 InetHostInfo hinfo
;
1298 if ( GSocket_Verify_Inited() == FALSE
)
1299 return GSOCK_IOERR
;
1301 assert(address
!= NULL
);
1303 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1304 ret
= OTInetStringToAddress( gInetSvcRef
, (char*) hostname
, &hinfo
) ;
1305 if ( ret
!= kOTNoError
)
1307 address
->m_host
= INADDR_NONE
;
1308 address
->m_error
= GSOCK_NOHOST
;
1309 return GSOCK_NOHOST
;
1311 address
->m_host
= hinfo
.addrs
[0] ;
1312 return GSOCK_NOERROR
;
1315 GSocketError
GAddress_INET_SetAnyAddress(GAddress
*address
)
1317 return GAddress_INET_SetHostAddress(address
, INADDR_ANY
);
1320 GSocketError
GAddress_INET_SetHostAddress(GAddress
*address
,
1321 unsigned long hostaddr
)
1323 struct in_addr
*addr
;
1325 assert(address
!= NULL
);
1327 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1329 address
->m_host
= hostaddr
;
1331 return GSOCK_NOERROR
;
1334 struct service_entry
1337 unsigned short port
;
1340 typedef struct service_entry service_entry
;
1342 service_entry gServices
[] =
1344 { "http" , 80 , "tcp" }
1347 GSocketError
GAddress_INET_SetPortName(GAddress
*address
, const char *port
,
1348 const char *protocol
)
1353 assert(address
!= NULL
);
1354 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1358 address
->m_error
= GSOCK_INVPORT
;
1359 return GSOCK_INVPORT
;
1361 for ( i
= 0 ; i
< sizeof( gServices
) / sizeof( service_entry
) ; ++i
)
1363 if ( strcmp( port
, gServices
[i
].name
) == 0 )
1365 if ( protocol
== NULL
|| strcmp( protocol
, gServices
[i
].protocol
) )
1367 address
->m_port
= gServices
[i
].port
;
1368 return GSOCK_NOERROR
;
1373 if (isdigit(port
[0]))
1375 address
->m_port
= atoi(port
);
1376 return GSOCK_NOERROR
;
1379 address
->m_error
= GSOCK_INVPORT
;
1380 return GSOCK_INVPORT
;
1383 GSocketError
GAddress_INET_SetPort(GAddress
*address
, unsigned short port
)
1387 assert(address
!= NULL
);
1388 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1389 address
->m_port
= port
;
1391 return GSOCK_NOERROR
;
1394 GSocketError
GAddress_INET_GetHostName(GAddress
*address
, char *hostname
, size_t sbuf
)
1396 InetDomainName name
;
1397 if ( GSocket_Verify_Inited() == FALSE
)
1398 return GSOCK_IOERR
;
1400 assert(address
!= NULL
);
1401 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1403 OTInetAddressToName( gInetSvcRef
, address
->m_host
, name
) ;
1404 strncpy( hostname
, name
, sbuf
) ;
1405 return GSOCK_NOERROR
;
1408 unsigned long GAddress_INET_GetHostAddress(GAddress
*address
)
1410 assert(address
!= NULL
);
1411 CHECK_ADDRESS(address
, INET
, 0);
1413 return address
->m_host
;
1416 unsigned short GAddress_INET_GetPort(GAddress
*address
)
1418 assert(address
!= NULL
);
1419 CHECK_ADDRESS(address
, INET
, 0);
1421 return address
->m_port
;
1424 void _GSocket_Enable_Events(GSocket
*socket
)
1426 if ( socket
->m_takesEvents
)
1431 socket
->m_takesEvents
= TRUE
;
1432 state
= OTGetEndpointState(socket
->m_endpoint
);
1435 OTByteCount sz
= 0 ;
1436 OTCountDataBytes( socket
->m_endpoint
, &sz
) ;
1437 if ( state
== T_INCON
|| sz
> 0 )
1439 socket
->m_detected
|= GSOCK_INPUT_FLAG
;
1440 (socket
->m_cbacks
[GSOCK_INPUT
])(socket
, GSOCK_INPUT
, socket
->m_data
[GSOCK_INPUT
]);
1444 if ( state
== T_DATAXFER
|| state
== T_INREL
)
1446 socket
->m_detected
|=GSOCK_OUTPUT_FLAG
;
1447 (socket
->m_cbacks
[GSOCK_OUTPUT
])(socket
, GSOCK_OUTPUT
, socket
->m_data
[GSOCK_OUTPUT
]);
1453 void _GSocket_Disable_Events(GSocket
*socket
)
1455 socket
->m_takesEvents
= FALSE
;
1458 /* _GSocket_Input_Timeout:
1459 * For blocking sockets, wait until data is available or
1460 * until timeout ellapses.
1462 GSocketError
_GSocket_Input_Timeout(GSocket
*socket
)
1464 if ( !socket
->m_non_blocking
)
1466 UnsignedWide now
, start
;
1467 short formerTakesEvents
= socket
->m_takesEvents
;
1468 Microseconds(&start
);
1470 socket
->m_takesEvents
= FALSE
;
1472 while( (now
.hi
* 4294967296.0 + now
.lo
) - (start
.hi
* 4294967296.0 + start
.lo
) < socket
->m_timeout
* 1000.0 )
1475 OTByteCount sz
= 0 ;
1476 state
= OTGetEndpointState(socket
->m_endpoint
);
1478 OTCountDataBytes( socket
->m_endpoint
, &sz
) ;
1479 if ( state
== T_INCON
|| sz
> 0 )
1481 socket
->m_takesEvents
= formerTakesEvents
;
1482 return GSOCK_NOERROR
;
1486 socket
->m_takesEvents
= formerTakesEvents
;
1487 socket
->m_error
= GSOCK_TIMEDOUT
;
1488 return GSOCK_TIMEDOUT
;
1490 return GSOCK_NOERROR
;
1493 /* _GSocket_Output_Timeout:
1494 * For blocking sockets, wait until data can be sent without
1495 * blocking or until timeout ellapses.
1497 GSocketError
_GSocket_Output_Timeout(GSocket
*socket
)
1499 if ( !socket
->m_non_blocking
)
1501 UnsignedWide now
, start
;
1502 short formerTakesEvents
= socket
->m_takesEvents
;
1503 Microseconds(&start
);
1505 socket
->m_takesEvents
= FALSE
;
1507 while( (now
.hi
* 4294967296.0 + now
.lo
) - (start
.hi
* 4294967296.0 + start
.lo
) < socket
->m_timeout
* 1000.0 )
1510 state
= OTGetEndpointState(socket
->m_endpoint
);
1512 if ( state
== T_DATAXFER
|| state
== T_INREL
)
1514 socket
->m_takesEvents
= formerTakesEvents
;
1515 return GSOCK_NOERROR
;
1519 socket
->m_takesEvents
= formerTakesEvents
;
1520 socket
->m_error
= GSOCK_TIMEDOUT
;
1521 return GSOCK_TIMEDOUT
;
1523 return GSOCK_NOERROR
;
1527 * There is data to be read in the input buffer. If, after a read
1528 * operation, there is still data available, the callback function will
1531 * The socket is available for writing. That is, the next write call
1532 * won't block. This event is generated only once, when the connection is
1533 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
1534 * when the output buffer empties again. This means that the app should
1535 * assume that it can write since the first OUTPUT event, and no more
1536 * OUTPUT events will be generated unless an error occurs.
1538 * Connection succesfully established, for client sockets, or incoming
1539 * client connection, for server sockets. Wait for this event (also watch
1540 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
1542 * The connection is lost (or a connection request failed); this could
1543 * be due to a failure, or due to the peer closing it gracefully.
1546 void _GSocket_Internal_Proc(unsigned long e
, void* d
)
1549 GSocket
* socket
= (GSocket
*) d
;
1550 OTEventCode ev
= (OTEventCode
) e
;
1552 GSocketEvent event2
;
1553 GSocketCallback cback
;
1555 GSocketCallback cback2
;
1560 event
= GSOCK_MAX_EVENT
;
1561 event2
= GSOCK_MAX_EVENT
;
1567 /* Check that the socket still exists (it has not been
1568 * destroyed) and for safety, check that the m_endpoint field
1569 * is what we expect it to be.
1571 if ((socket
!= NULL
) && (socket
->m_takesEvents
))
1576 event
= GSOCK_CONNECTION
;
1579 event
= GSOCK_CONNECTION
;
1580 event2
= GSOCK_OUTPUT
;
1584 retCall
.addr
.buf
= NULL
;
1585 retCall
.addr
.maxlen
= 0;
1586 retCall
.opt
.buf
= NULL
;
1587 retCall
.opt
.maxlen
= 0;
1588 retCall
.udata
.buf
= NULL
;
1589 retCall
.udata
.maxlen
= 0;
1590 OTRcvConnect( socket
->m_endpoint
, &retCall
) ;
1594 event
= GSOCK_LOST
;
1598 event
= GSOCK_OUTPUT
;
1601 event
= GSOCK_INPUT
;
1604 event
= GSOCK_INPUT
;
1607 if (event
!= GSOCK_MAX_EVENT
)
1609 cback
= socket
->m_cbacks
[event
];
1610 data
= socket
->m_data
[event
];
1612 if (event
== GSOCK_LOST
)
1613 socket
->m_detected
= GSOCK_LOST_FLAG
;
1615 socket
->m_detected
|= (1 << event
);
1617 if (event2
!= GSOCK_MAX_EVENT
)
1619 cback2
= socket
->m_cbacks
[event2
];
1620 data2
= socket
->m_data
[event2
];
1622 if (event2
== GSOCK_LOST
)
1623 socket
->m_detected
= GSOCK_LOST_FLAG
;
1625 socket
->m_detected
|= (1 << event2
);
1629 /* OK, we can now leave the critical section because we have
1630 * already obtained the callback address (we make no further
1631 * accesses to socket->whatever). However, the app should
1632 * be prepared to handle events from a socket that has just
1637 (cback
)(socket
, event
, data
);
1639 (cback2
)(socket
, event2
, data2
);
1643 /* Hack added for Mac OS X */
1644 GSocketError
GAddress_UNIX_GetPath(GAddress
*addr
, char *path
, size_t buf
)
1648 GSocketError
GAddress_UNIX_SetPath(GAddress
*addr
, const char *path
)
1652 #endif /* wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__) */