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 #include <MacHeaders.c>
33 #define OTUNIXERRORS 1
34 #include <OpenTransport.h>
35 #include <OpenTransportProviders.h>
36 #include <OpenTptInternet.h>
39 #define OTAssert( str , cond ) /* does not exists in Carbon */
53 * INADDR_BROADCAST is identical to INADDR_NONE which is not defined
54 * on all unices. INADDR_BROADCAST should be fine to indicate an error.
56 #ifndef INADDR_BROADCAST
57 #define INADDR_BROADCAST 0xFFFFFFFFUL
60 #define INADDR_NONE INADDR_BROADCAST
63 #define INADDR_ANY 0x0UL
65 #ifndef __GSOCKET_STANDALONE__
67 #include "wx/mac/macnotfy.h"
68 #include "wx/mac/gsockmac.h"
69 #include "wx/gsocket.h"
76 #endif /* __GSOCKET_STANDALONE__ */
82 extern pascal void OTDebugStr(const char* str
);
87 InetSvcRef gInetSvcRef
= 0 ;
90 OSStatus
DoNegotiateIPReuseAddrOption(EndpointRef ep
, Boolean enableReuseIPMode
);
92 /* Input: ep - endpointref on which to negotiate the option
93 enableReuseIPMode - desired option setting - true/false
94 Return: kOTNoError indicates that the option was successfully negotiated
95 OSStatus is an error if < 0, otherwise, the status field is
98 IMPORTANT NOTE: The endpoint is assumed to be in synchronous more, otherwise
99 this code will not function as desired
103 OSStatus
DoNegotiateIPReuseAddrOption(EndpointRef ep
, Boolean enableReuseIPMode
)
106 UInt8 buf
[kOTFourByteOptionSize
]; // define buffer for fourByte Option size
107 TOption
* opt
; // option ptr to make items easier to access
112 if (!OTIsSynchronous(ep
))
116 opt
= (TOption
*)buf
; // set option ptr to buffer
118 req
.opt
.len
= sizeof(buf
);
119 req
.flags
= T_NEGOTIATE
; // negotiate for option
122 ret
.opt
.maxlen
= kOTFourByteOptionSize
;
124 opt
->level
= INET_IP
; // dealing with an IP Level function
126 opt
->name
= kIP_REUSEADDR
;
128 opt
->name
= IP_REUSEADDR
;
130 opt
->len
= kOTFourByteOptionSize
;
132 *(UInt32
*)opt
->value
= enableReuseIPMode
; // set the desired option level, true or false
134 err
= OTOptionManagement(ep
, &req
, &ret
);
136 // if no error then return the option status value
137 if (err
== kOTNoError
)
139 if (opt
->status
!= T_SUCCESS
)
149 pascal void OTInetEventHandler(void*s
, OTEventCode event
, OTResult
, void *cookie
) ;
150 pascal void OTInetEventHandler(void*s
, OTEventCode event
, OTResult result
, void *cookie
)
153 GSocket
* sock
= (GSocket
*) s
;
155 if ( event
== kOTSyncIdleEvent
)
163 wxMacAddEvent( sock
->m_mac_events
, _GSocket_Internal_Proc
, event
, s
, wakeUp
) ;
169 static void SetDefaultEndpointModes(EndpointRef ep
, void *data
)
170 // This routine sets the supplied endpoint into the default
171 // mode used in this application. The specifics are:
172 // blocking, synchronous, and using synch idle events with
173 // the standard YieldingNotifier.
175 OSStatus junk
= kOTNoError
;
176 OTAssert ("SetDefaultEndpointModes:invalid ref", ep
!= kOTInvalidEndpointRef
) ;
177 junk
= OTSetAsynchronous(ep
);
178 OTAssert("SetDefaultEndpointModes: Could not set asynchronous", junk
== noErr
);
180 junk = OTSetBlocking(ep);
181 OTAssert("SetDefaultEndpointModes: Could not set blocking", junk == noErr);
182 junk = OTSetSynchronous(ep);
183 OTAssert("SetDefaultEndpointModes: Could not set synchronous", junk == noErr);
184 junk = OTSetBlocking(ep);
185 OTAssert("SetDefaultEndpointModes: Could not set blocking", junk == noErr);
187 junk
= OTInstallNotifier(ep
, OTInetEventHandler
, data
);
188 OTAssert("SetDefaultEndpointModes: Could not install notifier", junk
== noErr
);
190 junk = OTUseSyncIdleEvents(ep, true);
191 OTAssert("SetDefaultEndpointModes: Could not use sync idle events", junk == noErr);
195 /* Global initialisers */
202 int GSocket_Verify_Inited() ;
203 int GSocket_Verify_Inited()
207 // Marc Newsam: added the clientcontext variable
208 // however, documentation is unclear how this works
209 OTClientContextPtr clientcontext
;
214 InitOpenTransportInContext(kInitOTForApplicationMask
, &clientcontext
);
216 gInetSvcRef
= OTOpenInternetServicesInContext(kDefaultInternetServicesPath
,
217 NULL
, &err
, clientcontext
);
222 InitOpenTransport() ;
224 gInetSvcRef
= OTOpenInternetServices(kDefaultInternetServicesPath
, NULL
, &err
);
226 if ( gInetSvcRef
== NULL
|| err
!= kOTNoError
)
228 OTAssert("Could not open Inet Services", err
== noErr
);
234 void GSocket_Cleanup()
236 if ( gOTInited
!= 0 )
238 if ( gInetSvcRef
!= NULL
)
239 OTCloseProvider( gInetSvcRef
);
241 CloseOpenTransportInContext( NULL
) ;
243 CloseOpenTransport() ;
248 /* Constructors / Destructors for GSocket */
250 GSocket
*GSocket_new()
256 if ( GSocket_Verify_Inited() == FALSE
)
259 socket
= (GSocket
*)malloc(sizeof(GSocket
));
264 socket
->m_endpoint
= NULL
;
265 for (i
=0;i
<GSOCK_MAX_EVENT
;i
++)
267 socket
->m_cbacks
[i
] = NULL
;
269 socket
->m_detected
= 0;
270 socket
->m_local
= NULL
;
271 socket
->m_peer
= NULL
;
272 socket
->m_error
= GSOCK_NOERROR
;
273 socket
->m_server
= FALSE
;
274 socket
->m_stream
= TRUE
;
275 socket
->m_non_blocking
= FALSE
;
276 socket
->m_timeout
= 1*1000;
277 /* 10 sec * 1000 millisec */
278 socket
->m_takesEvents
= TRUE
;
279 socket
->m_mac_events
= wxMacGetNotifierTable() ;
283 void GSocket_destroy(GSocket
*socket
)
285 assert(socket
!= NULL
);
287 /* Check that the socket is really shutdowned */
288 if (socket
->m_endpoint
!= kOTInvalidEndpointRef
)
289 GSocket_Shutdown(socket
);
292 /* Destroy private addresses */
294 GAddress_destroy(socket
->m_local
);
297 GAddress_destroy(socket
->m_peer
);
299 /* Destroy the socket itself */
304 * Disallow further read/write operations on this socket, close
305 * the fd and disable all callbacks.
307 void GSocket_Shutdown(GSocket
*socket
)
312 assert(socket
!= NULL
);
314 /* If socket has been created, shutdown it */
315 if (socket
->m_endpoint
!= kOTInvalidEndpointRef
)
317 err
= OTSndOrderlyDisconnect( socket
->m_endpoint
) ;
318 if ( err
!= kOTNoError
)
322 err
= OTRcvOrderlyDisconnect( socket
->m_endpoint
) ;
323 err
= OTUnbind( socket
->m_endpoint
) ;
324 err
= OTCloseProvider( socket
->m_endpoint
) ;
325 socket
->m_endpoint
= kOTInvalidEndpointRef
;
328 /* Disable GUI callbacks */
329 for (evt
= 0; evt
< GSOCK_MAX_EVENT
; evt
++)
330 socket
->m_cbacks
[evt
] = NULL
;
332 socket
->m_detected
= 0;
333 _GSocket_Disable_Events(socket
);
334 wxMacRemoveAllNotifiersForData( wxMacGetNotifierTable() , socket
) ;
338 /* Address handling */
344 * Set or get the local or peer address for this socket. The 'set'
345 * functions return GSOCK_NOERROR on success, an error code otherwise.
346 * The 'get' functions return a pointer to a GAddress object on success,
347 * or NULL otherwise, in which case they set the error code of the
348 * corresponding GSocket.
351 * GSOCK_INVSOCK - the socket is not valid.
352 * GSOCK_INVADDR - the address is not valid.
354 GSocketError
GSocket_SetLocal(GSocket
*socket
, GAddress
*address
)
356 assert(socket
!= NULL
);
358 /* the socket must be initialized, or it must be a server */
359 if ((socket
->m_endpoint
!= kOTInvalidEndpointRef
&& !socket
->m_server
))
361 socket
->m_error
= GSOCK_INVSOCK
;
362 return GSOCK_INVSOCK
;
366 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
368 socket
->m_error
= GSOCK_INVADDR
;
369 return GSOCK_INVADDR
;
373 GAddress_destroy(socket
->m_local
);
375 socket
->m_local
= GAddress_copy(address
);
377 return GSOCK_NOERROR
;
380 GSocketError
GSocket_SetPeer(GSocket
*socket
, GAddress
*address
)
382 assert(socket
!= NULL
);
385 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
387 socket
->m_error
= GSOCK_INVADDR
;
388 return GSOCK_INVADDR
;
392 GAddress_destroy(socket
->m_peer
);
394 socket
->m_peer
= GAddress_copy(address
);
396 return GSOCK_NOERROR
;
399 GAddress
*GSocket_GetLocal(GSocket
*socket
)
401 GAddress
*address
= NULL
;
405 assert(socket
!= NULL
);
407 /* try to get it from the m_local var first */
409 return GAddress_copy(socket
->m_local
);
411 /* else, if the socket is initialized, try getsockname */
412 if (socket
->m_endpoint
== kOTInvalidEndpointRef
)
414 socket
->m_error
= GSOCK_INVSOCK
;
419 /* we do not support multihoming with this code at the moment
420 OTGetProtAddress will have to be used then - but we don't have a handy
421 method to use right now
424 InetInterfaceInfo info
;
425 OTInetGetInterfaceInfo(&info
, kDefaultInetInterface
);
426 loc
.fHost
= info
.fAddress
;
428 loc
.fAddressType
= AF_INET
;
431 /* got a valid address from getsockname, create a GAddress object */
432 address
= GAddress_new();
435 socket
->m_error
= GSOCK_MEMERR
;
439 err
= _GAddress_translate_from(address
, &loc
);
440 if (err
!= GSOCK_NOERROR
)
442 GAddress_destroy(address
);
443 socket
->m_error
= err
;
450 GAddress
*GSocket_GetPeer(GSocket
*socket
)
452 assert(socket
!= NULL
);
454 /* try to get it from the m_peer var */
456 return GAddress_copy(socket
->m_peer
);
461 /* Server specific parts */
463 /* GSocket_SetServer:
464 * Sets up this socket as a server. The local address must have been
465 * set with GSocket_SetLocal() before GSocket_SetServer() is called.
466 * Returns GSOCK_NOERROR on success, one of the following otherwise:
469 * GSOCK_INVSOCK - the socket is in use.
470 * GSOCK_INVADDR - the local address has not been set.
471 * GSOCK_IOERR - low-level error.
473 GSocketError
GSocket_SetServer(GSocket
*sck
)
480 /* must not be in use */
481 if (sck
->m_endpoint
!= kOTInvalidEndpointRef
)
483 sck
->m_error
= GSOCK_INVSOCK
;
484 return GSOCK_INVSOCK
;
487 /* the local addr must have been set */
490 sck
->m_error
= GSOCK_INVADDR
;
491 return GSOCK_INVADDR
;
494 /* Initialize all fields */
495 sck
->m_stream
= TRUE
;
496 sck
->m_server
= TRUE
;
497 sck
->m_oriented
= TRUE
;
501 /* Create the socket */
502 sck
->m_endpoint
= socket(sck
->m_local
->m_realfamily
, SOCK_STREAM
, 0);
503 socket_set_ref( sck
->m_endpoint
, (unsigned long) &gMacNetEvents
, (unsigned long) sck
) ;
504 if (sck
->m_endpoint
== kOTInvalidEndpointRef
)
506 sck
->m_error
= GSOCK_IOERR
;
510 ioctl(sck
->m_endpoint
, FIONBIO
, &arg
);
511 _GSocket_Enable_Events(sck
);
513 /* Bind to the local address,
514 * retrieve the actual address bound,
515 * and listen up to 5 connections.
517 if ((bind(sck
->m_endpoint
, sck
->m_local
->m_addr
, sck
->m_local
->m_len
) != 0) ||
518 (getsockname(sck
->m_endpoint
,
519 sck
->m_local
->m_addr
,
520 (SOCKLEN_T
*) &sck
->m_local
->m_len
) != 0) ||
521 (listen(sck
->m_endpoint
, 5) != 0))
523 close(sck
->m_endpoint
);
524 sck
->m_endpoint
= -1;
525 sck
->m_error
= GSOCK_IOERR
;
529 return GSOCK_NOERROR
;
532 /* GSocket_WaitConnection:
533 * Waits for an incoming client connection. Returns a pointer to
534 * a GSocket object, or NULL if there was an error, in which case
535 * the last error field will be updated for the calling GSocket.
537 * Error codes (set in the calling GSocket)
538 * GSOCK_INVSOCK - the socket is not valid or not a server.
539 * GSOCK_TIMEDOUT - timeout, no incoming connections.
540 * GSOCK_WOULDBLOCK - the call would block and the socket is nonblocking.
541 * GSOCK_MEMERR - couldn't allocate memory.
542 * GSOCK_IOERR - low-level error.
544 GSocket
*GSocket_WaitConnection(GSocket
*socket
)
546 GSocket
*connection
= NULL
;
551 assert(socket
!= NULL
);
553 /* Reenable CONNECTION events */
554 socket
->m_detected
&= ~GSOCK_CONNECTION_FLAG
;
556 /* If the socket has already been created, we exit immediately */
557 if (socket
->m_endpoint
== kOTInvalidEndpointRef
|| !socket
->m_server
)
559 socket
->m_error
= GSOCK_INVSOCK
;
563 /* Create a GSocket object for the new connection */
564 connection
= GSocket_new();
568 socket
->m_error
= GSOCK_MEMERR
;
572 /* Wait for a connection (with timeout) */
573 if (_GSocket_Input_Timeout(socket
) == GSOCK_TIMEDOUT
)
575 GSocket_destroy(connection
);
576 /* socket->m_error set by _GSocket_Input_Timeout */
582 connection
->m_endpoint
= accept(socket
->m_endpoint
, &from
, (SOCKLEN_T
*) &fromlen
);
585 if (connection
->m_endpoint
== kOTInvalidEndpointRef
)
587 if (errno
== EWOULDBLOCK
)
588 socket
->m_error
= GSOCK_WOULDBLOCK
;
590 socket
->m_error
= GSOCK_IOERR
;
592 GSocket_destroy(connection
);
596 /* Initialize all fields */
597 connection
->m_server
= FALSE
;
598 connection
->m_stream
= TRUE
;
599 connection
->m_oriented
= TRUE
;
601 /* Setup the peer address field */
602 connection
->m_peer
= GAddress_new();
603 if (!connection
->m_peer
)
605 GSocket_destroy(connection
);
606 socket
->m_error
= GSOCK_MEMERR
;
611 err
= _GAddress_translate_from(connection
->m_peer
, &from
, fromlen
);
612 if (err
!= GSOCK_NOERROR
)
614 GAddress_destroy(connection
->m_peer
);
615 GSocket_destroy(connection
);
616 socket
->m_error
= err
;
620 ioctl(connection
->m_endpoint
, FIONBIO
, &arg
);
622 _GSocket_Enable_Events(connection
);
627 /* Datagram sockets */
629 /* GSocket_SetNonOriented:
630 * Sets up this socket as a non-connection oriented (datagram) socket.
631 * Before using this function, the local address must have been set
632 * with GSocket_SetLocal(), or the call will fail. Returns GSOCK_NOERROR
633 * on success, or one of the following otherwise.
636 * GSOCK_INVSOCK - the socket is in use.
637 * GSOCK_INVADDR - the local address has not been set.
638 * GSOCK_IOERR - low-level error.
640 GSocketError
GSocket_SetNonOriented(GSocket
*sck
)
646 if (sck
->m_endpoint
!= kOTInvalidEndpointRef
)
648 sck
->m_error
= GSOCK_INVSOCK
;
649 return GSOCK_INVSOCK
;
654 sck
->m_error
= GSOCK_INVADDR
;
655 return GSOCK_INVADDR
;
658 /* Initialize all fields */
659 sck
->m_stream
= FALSE
;
660 sck
->m_server
= FALSE
;
661 sck
->m_oriented
= FALSE
;
663 /* Create the socket */
667 sck
->m_endpoint
= socket(sck
->m_local
->m_realfamily
, SOCK_DGRAM
, 0);
668 socket_set_ref( sck
->m_endpoint
, (unsigned long) &gMacNetEvents
, (unsigned long) sck
) ;
670 if (sck
->m_endpoint
== kOTInvalidEndpointRef
)
672 sck
->m_error
= GSOCK_IOERR
;
678 ioctl(sck
->m_endpoint
, FIONBIO
, &arg
);
680 _GSocket_Enable_Events(sck
);
682 /* Bind to the local address,
683 * and retrieve the actual address bound.
687 if ((bind(sck
->m_endpoint
, sck
->m_local
->m_addr
, sck
->m_local
->m_len
) != 0) ||
688 (getsockname(sck
->m_endpoint
,
689 sck
->m_local
->m_addr
,
690 (SOCKLEN_T
*) &sck
->m_local
->m_len
) != 0))
692 close(sck
->m_endpoint
);
693 sck
->m_endpoint
= -1;
694 sck
->m_error
= GSOCK_IOERR
;
698 return GSOCK_NOERROR
;
701 /* Client specific parts */
704 * For stream (connection oriented) sockets, GSocket_Connect() tries
705 * to establish a client connection to a server using the peer address
706 * as established with GSocket_SetPeer(). Returns GSOCK_NOERROR if the
707 * connection has been succesfully established, or one of the error
708 * codes listed below. Note that for nonblocking sockets, a return
709 * value of GSOCK_WOULDBLOCK doesn't mean a failure. The connection
710 * request can be completed later; you should use GSocket_Select()
711 * to poll for GSOCK_CONNECTION | GSOCK_LOST, or wait for the
712 * corresponding asynchronous events.
714 * For datagram (non connection oriented) sockets, GSocket_Connect()
715 * just sets the peer address established with GSocket_SetPeer() as
716 * default destination.
719 * GSOCK_INVSOCK - the socket is in use or not valid.
720 * GSOCK_INVADDR - the peer address has not been established.
721 * GSOCK_TIMEDOUT - timeout, the connection failed.
722 * GSOCK_WOULDBLOCK - connection in progress (nonblocking sockets only)
723 * GSOCK_MEMERR - couldn't allocate memory.
724 * GSOCK_IOERR - low-level error.
726 GSocketError
GSocket_Connect(GSocket
*sck
, GSocketStream stream
)
733 OSStatus err
= kOTNoError
;
738 /* Enable CONNECTION events (needed for nonblocking connections) */
739 sck
->m_detected
&= ~GSOCK_CONNECTION_FLAG
;
741 if (sck
->m_endpoint
!= kOTInvalidEndpointRef
)
743 sck
->m_error
= GSOCK_INVSOCK
;
744 return GSOCK_INVSOCK
;
749 sck
->m_error
= GSOCK_INVADDR
;
750 return GSOCK_INVADDR
;
753 /* Streamed or dgram socket? */
754 sck
->m_stream
= (stream
== GSOCK_STREAMED
);
755 sck
->m_oriented
= TRUE
;
756 sck
->m_server
= FALSE
;
758 /* Create the socket */
761 OTOpenEndpointInContext( OTCreateConfiguration( kTCPName
) , 0 , &info
, &err
, NULL
) ;
764 OTOpenEndpoint( OTCreateConfiguration( kTCPName
) , 0 , &info
, &err
) ;
766 if ( sck
->m_endpoint
== kOTInvalidEndpointRef
|| err
!= kOTNoError
)
768 sck
->m_endpoint
= kOTInvalidEndpointRef
;
769 sck
->m_error
= GSOCK_IOERR
;
772 err
= OTBind( sck
->m_endpoint
, nil
, nil
) ;
773 if ( err
!= kOTNoError
)
777 SetDefaultEndpointModes( sck
->m_endpoint
, sck
) ;
780 ioctl(sck
->m_endpoint
, FIONBIO
, &arg
);
782 _GSocket_Enable_Events(sck
);
784 _GAddress_translate_to( sck
->m_peer
, &addr
) ;
785 memset( &peer
, 0 , sizeof( TCall
) ) ;
786 peer
.addr
.len
= sizeof( InetAddress
) ;
787 peer
.addr
.buf
= (unsigned char*) &addr
;
788 err
= OTConnect( sck
->m_endpoint
, &peer
, nil
) ;
791 /* If connect failed with EINPROGRESS and the GSocket object
792 * is in blocking mode, we select() for the specified timeout
793 * checking for writability to see if the connection request
797 if ((err
== kOTNoDataErr
) && (!sck
->m_non_blocking
))
799 if (_GSocket_Output_Timeout(sck
) == GSOCK_TIMEDOUT
)
801 OTSndOrderlyDisconnect( sck
->m_endpoint
) ;
802 sck
->m_endpoint
= kOTInvalidEndpointRef
;
803 /* sck->m_error is set in _GSocket_Output_Timeout */
804 return GSOCK_TIMEDOUT
;
810 SOCKLEN_T len = sizeof(error);
812 getsockopt(sck->m_endpoint, SOL_SOCKET, SO_ERROR, (void*) &error, &len);
816 return GSOCK_NOERROR
;
820 /* If connect failed with EINPROGRESS and the GSocket object
821 * is set to nonblocking, we set m_error to GSOCK_WOULDBLOCK
822 * (and return GSOCK_WOULDBLOCK) but we don't close the socket;
823 * this way if the connection completes, a GSOCK_CONNECTION
824 * event will be generated, if enabled.
826 if ((err
== kOTNoDataErr
) && (sck
->m_non_blocking
))
828 sck
->m_error
= GSOCK_WOULDBLOCK
;
829 return GSOCK_WOULDBLOCK
;
832 /* If connect failed with an error other than EINPROGRESS,
833 * then the call to GSocket_Connect has failed.
835 OTSndOrderlyDisconnect( sck
->m_endpoint
) ;
837 sck
->m_endpoint
= kOTInvalidEndpointRef
;
838 sck
->m_error
= GSOCK_IOERR
;
841 // OTInetEventHandler(sck, T_CONNECT , kOTNoError , NULL ) ;
842 return GSOCK_NOERROR
;
847 /* Like recv(), send(), ... */
848 int GSocket_Read(GSocket
*socket
, char *buffer
, int size
)
852 assert(socket
!= NULL
);
854 /* Reenable INPUT events */
855 socket
->m_detected
&= ~GSOCK_INPUT_FLAG
;
857 if (socket
->m_endpoint
== kOTInvalidEndpointRef
|| socket
->m_server
)
859 socket
->m_error
= GSOCK_INVSOCK
;
863 /* If the socket is blocking, wait for data (with a timeout) */
864 if (_GSocket_Input_Timeout(socket
) == GSOCK_TIMEDOUT
)
868 if (socket
->m_stream
)
869 ret
= _GSocket_Recv_Stream(socket
, buffer
, size
);
871 ret
= _GSocket_Recv_Dgram(socket
, buffer
, size
);
875 if (errno
== EWOULDBLOCK
)
876 socket
->m_error
= GSOCK_WOULDBLOCK
;
878 socket
->m_error
= GSOCK_IOERR
;
884 int GSocket_Write(GSocket
*socket
, const char *buffer
, int size
)
888 assert(socket
!= NULL
);
890 if (socket
->m_endpoint
== kOTInvalidEndpointRef
|| socket
->m_server
)
892 socket
->m_error
= GSOCK_INVSOCK
;
896 /* If the socket is blocking, wait for writability (with a timeout) */
897 if (_GSocket_Output_Timeout(socket
) == GSOCK_TIMEDOUT
)
901 if (socket
->m_stream
)
902 ret
= _GSocket_Send_Stream(socket
, buffer
, size
);
904 ret
= _GSocket_Send_Dgram(socket
, buffer
, size
);
908 if (errno
== EWOULDBLOCK
)
909 socket
->m_error
= GSOCK_WOULDBLOCK
;
911 socket
->m_error
= GSOCK_IOERR
;
913 /* Only reenable OUTPUT events after an error (just like WSAAsyncSelect
914 * in MSW). Once the first OUTPUT event is received, users can assume
915 * that the socket is writable until a read operation fails. Only then
916 * will further OUTPUT events be posted.
918 socket
->m_detected
&= ~GSOCK_OUTPUT_FLAG
;
926 * Polls the socket to determine its status. This function will
927 * check for the events specified in the 'flags' parameter, and
928 * it will return a mask indicating which operations can be
929 * performed. This function won't block, regardless of the
930 * mode (blocking | nonblocking) of the socket.
932 GSocketEventFlags
GSocket_Select(GSocket
*socket
, GSocketEventFlags flags
)
935 assert(socket
!= NULL
);
936 wxMacProcessNotifierEvents() ;
938 state = OTGetEndpointState(socket->m_endpoint);
940 if ( ( flags & GSOCK_INPUT_FLAG ) && ! ( socket->m_detected & GSOCK_INPUT_FLAG ) )
943 OTCountDataBytes( socket->m_endpoint , &sz ) ;
944 if ( state == T_INCON || sz > 0 )
946 socket->m_detected |= GSOCK_INPUT_FLAG ;
947 (socket->m_cbacks[GSOCK_INPUT])(socket, GSOCK_INPUT, socket->m_data[GSOCK_INPUT]);
950 if ( ( flags & GSOCK_INPUT_FLAG ) && ! ( socket->m_detected & GSOCK_OUTPUT_FLAG ) )
952 if ( state == T_DATAXFER || state == T_INREL )
954 socket->m_detected |=GSOCK_OUTPUT_FLAG ;
955 (socket->m_cbacks[GSOCK_OUTPUT])(socket, GSOCK_OUTPUT, socket->m_data[GSOCK_OUTPUT]);
959 return ( flags
& socket
->m_detected
) ;
964 /* GSocket_SetNonBlocking:
965 * Sets the socket to non-blocking mode. All IO calls will return
968 void GSocket_SetNonBlocking(GSocket
*socket
, int non_block
)
970 assert(socket
!= NULL
);
972 socket
->m_non_blocking
= non_block
;
975 /* GSocket_SetTimeout:
976 * Sets the timeout for blocking calls. Time is expressed in
979 void GSocket_SetTimeout(GSocket
*socket
, unsigned long millisec
)
981 assert(socket
!= NULL
);
983 // this is usually set too high and we have not yet been able to detect a closed
984 // stream, thus we leave the 10 sec timeout
985 // socket->m_timeout = millisec;
989 * Returns the last error occured for this socket. Note that successful
990 * operations do not clear this back to GSOCK_NOERROR, so use it only
993 GSocketError
GSocket_GetError(GSocket
*socket
)
995 assert(socket
!= NULL
);
997 return socket
->m_error
;
1003 * There is data to be read in the input buffer. If, after a read
1004 * operation, there is still data available, the callback function will
1007 * The socket is available for writing. That is, the next write call
1008 * won't block. This event is generated only once, when the connection is
1009 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
1010 * when the output buffer empties again. This means that the app should
1011 * assume that it can write since the first OUTPUT event, and no more
1012 * OUTPUT events will be generated unless an error occurs.
1014 * Connection succesfully established, for client sockets, or incoming
1015 * client connection, for server sockets. Wait for this event (also watch
1016 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
1018 * The connection is lost (or a connection request failed); this could
1019 * be due to a failure, or due to the peer closing it gracefully.
1022 /* GSocket_SetCallback:
1023 * Enables the callbacks specified by 'flags'. Note that 'flags'
1024 * may be a combination of flags OR'ed toghether, so the same
1025 * callback function can be made to accept different events.
1026 * The callback function must have the following prototype:
1028 * void function(GSocket *socket, GSocketEvent event, char *cdata)
1030 void GSocket_SetCallback(GSocket
*socket
, GSocketEventFlags flags
,
1031 GSocketCallback callback
, char *cdata
)
1035 assert(socket
!= NULL
);
1037 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1039 if ((flags
& (1 << count
)) != 0)
1041 socket
->m_cbacks
[count
] = callback
;
1042 socket
->m_data
[count
] = cdata
;
1047 /* GSocket_UnsetCallback:
1048 * Disables all callbacks specified by 'flags', which may be a
1049 * combination of flags OR'ed toghether.
1051 void GSocket_UnsetCallback(GSocket
*socket
, GSocketEventFlags flags
)
1055 assert(socket
!= NULL
);
1057 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1059 if ((flags
& (1 << count
)) != 0)
1061 socket
->m_cbacks
[count
] = NULL
;
1062 socket
->m_data
[count
] = NULL
;
1068 #define CALL_CALLBACK(socket, event) { \
1069 _GSocket_Disable(socket, event); \
1070 if (socket->m_cbacks[event]) \
1071 socket->m_cbacks[event](socket, event, socket->m_data[event]); \
1074 int _GSocket_Recv_Stream(GSocket
*socket
, char *buffer
, int size
)
1078 OTByteCount sz
= 0 ;
1080 OTCountDataBytes( socket
->m_endpoint
, &sz
) ;
1083 res
= OTRcv( socket
->m_endpoint
, buffer
, size
, &flags
) ;
1089 // we simulate another read event if there are still bytes
1090 if ( socket
->m_takesEvents
)
1092 OTByteCount sz
= 0 ;
1093 OTCountDataBytes( socket
->m_endpoint
, &sz
) ;
1096 socket
->m_detected
|= GSOCK_INPUT_FLAG
;
1097 (socket
->m_cbacks
[GSOCK_INPUT
])(socket
, GSOCK_INPUT
, socket
->m_data
[GSOCK_INPUT
]);
1103 int _GSocket_Recv_Dgram(GSocket
*socket
, char *buffer
, int size
)
1108 struct sockaddr from
;
1109 SOCKLEN_T fromlen
= sizeof(from
);
1112 fromlen
= sizeof(from
);
1114 ret
= recvfrom(socket
->m_endpoint
, buffer
, size
, 0, &from
, (SOCKLEN_T
*) &fromlen
);
1119 /* Translate a system address into a GSocket address */
1120 if (!socket
->m_peer
)
1122 socket
->m_peer
= GAddress_new();
1123 if (!socket
->m_peer
)
1125 socket
->m_error
= GSOCK_MEMERR
;
1129 err
= _GAddress_translate_from(socket
->m_peer
, &from
, fromlen
);
1130 if (err
!= GSOCK_NOERROR
)
1132 GAddress_destroy(socket
->m_peer
);
1133 socket
->m_peer
= NULL
;
1134 socket
->m_error
= err
;
1141 int _GSocket_Send_Stream(GSocket
*socket
, const char *buffer
, int size
)
1146 res
= OTSnd( socket
->m_endpoint
, (void*) buffer
, size
, flags
) ;
1150 int _GSocket_Send_Dgram(GSocket
*socket
, const char *buffer
, int size
)
1155 struct sockaddr
*addr
;
1159 if (!socket
->m_peer
)
1161 socket
->m_error
= GSOCK_INVADDR
;
1165 err
= _GAddress_translate_to(socket
->m_peer
, &addr
, &len
);
1166 if (err
!= GSOCK_NOERROR
)
1168 socket
->m_error
= err
;
1172 ret
= sendto(socket
->m_endpoint
, buffer
, size
, 0, addr
, len
);
1174 /* Frees memory allocated from _GAddress_translate_to */
1182 * -------------------------------------------------------------------------
1184 * -------------------------------------------------------------------------
1187 /* CHECK_ADDRESS verifies that the current family is either GSOCK_NOFAMILY
1188 * or GSOCK_*family*, and if it is GSOCK_NOFAMILY, it initalizes address
1189 * to be a GSOCK_*family*. In other cases, it returns GSOCK_INVADDR.
1191 #define CHECK_ADDRESS(address, family, retval) \
1193 if (address->m_family == GSOCK_NOFAMILY) \
1194 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1195 return address->m_error; \
1196 if (address->m_family != GSOCK_##family) \
1198 address->m_error = GSOCK_INVADDR; \
1203 GAddress
*GAddress_new()
1207 if ((address
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1210 address
->m_family
= GSOCK_NOFAMILY
;
1211 address
->m_host
= INADDR_NONE
;
1212 address
->m_port
= 0 ;
1217 GAddress
*GAddress_copy(GAddress
*address
)
1221 assert(address
!= NULL
);
1223 if ((addr2
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1226 memcpy(addr2
, address
, sizeof(GAddress
));
1230 void GAddress_destroy(GAddress
*address
)
1232 assert(address
!= NULL
);
1237 void GAddress_SetFamily(GAddress
*address
, GAddressType type
)
1239 assert(address
!= NULL
);
1241 address
->m_family
= type
;
1244 GAddressType
GAddress_GetFamily(GAddress
*address
)
1246 assert(address
!= NULL
);
1248 return address
->m_family
;
1251 GSocketError
_GAddress_translate_from(GAddress
*address
,
1254 switch (addr
->fAddressType
)
1257 address
->m_family
= GSOCK_INET
;
1261 address
->m_family
= GSOCK_INET6
;
1266 address
->m_error
= GSOCK_INVOP
;
1270 address
->m_host
= addr
->fHost
;
1271 address
->m_port
= addr
->fPort
;
1272 return GSOCK_NOERROR
;
1275 GSocketError
_GAddress_translate_to(GAddress
*address
,
1278 if ( GSocket_Verify_Inited() == FALSE
)
1279 return GSOCK_IOERR
;
1280 memset(addr
, 0 , sizeof(struct InetAddress
));
1281 OTInitInetAddress( addr
, address
->m_port
, address
->m_host
) ;
1282 return GSOCK_NOERROR
;
1286 * -------------------------------------------------------------------------
1287 * Internet address family
1288 * -------------------------------------------------------------------------
1291 GSocketError
_GAddress_Init_INET(GAddress
*address
)
1293 address
->m_family
= GSOCK_INET
;
1294 address
->m_host
= kOTAnyInetAddress
;
1296 return GSOCK_NOERROR
;
1299 GSocketError
GAddress_INET_SetHostName(GAddress
*address
, const char *hostname
)
1301 InetHostInfo hinfo
;
1304 if ( GSocket_Verify_Inited() == FALSE
)
1305 return GSOCK_IOERR
;
1307 assert(address
!= NULL
);
1309 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1310 ret
= OTInetStringToAddress( gInetSvcRef
, (char*) hostname
, &hinfo
) ;
1311 if ( ret
!= kOTNoError
)
1313 address
->m_host
= INADDR_NONE
;
1314 address
->m_error
= GSOCK_NOHOST
;
1315 return GSOCK_NOHOST
;
1317 address
->m_host
= hinfo
.addrs
[0] ;
1318 return GSOCK_NOERROR
;
1321 GSocketError
GAddress_INET_SetAnyAddress(GAddress
*address
)
1323 return GAddress_INET_SetHostAddress(address
, INADDR_ANY
);
1326 GSocketError
GAddress_INET_SetHostAddress(GAddress
*address
,
1327 unsigned long hostaddr
)
1329 struct in_addr
*addr
;
1331 assert(address
!= NULL
);
1333 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1335 address
->m_host
= hostaddr
;
1337 return GSOCK_NOERROR
;
1340 struct service_entry
1343 unsigned short port
;
1346 typedef struct service_entry service_entry
;
1348 service_entry gServices
[] =
1350 { "http" , 80 , "tcp" }
1353 GSocketError
GAddress_INET_SetPortName(GAddress
*address
, const char *port
,
1354 const char *protocol
)
1359 assert(address
!= NULL
);
1360 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1364 address
->m_error
= GSOCK_INVPORT
;
1365 return GSOCK_INVPORT
;
1367 for ( i
= 0 ; i
< sizeof( gServices
) / sizeof( service_entry
) ; ++i
)
1369 if ( strcmp( port
, gServices
[i
].name
) == 0 )
1371 if ( protocol
== NULL
|| strcmp( protocol
, gServices
[i
].protocol
) )
1373 address
->m_port
= gServices
[i
].port
;
1374 return GSOCK_NOERROR
;
1379 if (isdigit(port
[0]))
1381 address
->m_port
= atoi(port
);
1382 return GSOCK_NOERROR
;
1385 address
->m_error
= GSOCK_INVPORT
;
1386 return GSOCK_INVPORT
;
1389 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 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
)
1654 GSocketError
GAddress_UNIX_SetPath(GAddress
*addr
, const char *path
)
1658 #endif /* wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__) */