1 /* -------------------------------------------------------------------------
2 * Project: GSocket (Generic Socket) for WX
4 * Authors: Guilhem Lavaux,
5 * Guillermo Rodriguez Garcia <guille@iies.es> (maintainer)
7 * Purpose: GSocket main mac file
9 * -------------------------------------------------------------------------
13 * PLEASE don't put C++ comments here - this is a C source file.
16 #ifndef __GSOCKET_STANDALONE__
18 #include "wx/platform.h"
21 #if wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__)
24 #include <CoreServices/CoreServices.h>
33 #include <MacHeaders.c>
34 #define OTUNIXERRORS 1
35 #include <OpenTransport.h>
36 #include <OpenTransportProviders.h>
37 #include <OpenTptInternet.h>
40 #define OTAssert( str , cond ) /* does not exists in Carbon */
54 * INADDR_BROADCAST is identical to INADDR_NONE which is not defined
55 * on all unices. INADDR_BROADCAST should be fine to indicate an error.
57 #ifndef INADDR_BROADCAST
58 #define INADDR_BROADCAST 0xFFFFFFFFUL
61 #define INADDR_NONE INADDR_BROADCAST
64 #define INADDR_ANY 0x0UL
66 #ifndef __GSOCKET_STANDALONE__
68 #include "wx/mac/macnotfy.h"
69 #include "wx/mac/gsockmac.h"
70 #include "wx/gsocket.h"
77 #endif /* __GSOCKET_STANDALONE__ */
83 extern pascal void OTDebugStr(const char* str
);
88 InetSvcRef gInetSvcRef
= 0 ;
91 OSStatus
DoNegotiateIPReuseAddrOption(EndpointRef ep
, Boolean enableReuseIPMode
);
93 /* Input: ep - endpointref on which to negotiate the option
94 enableReuseIPMode - desired option setting - true/false
95 Return: kOTNoError indicates that the option was successfully negotiated
96 OSStatus is an error if < 0, otherwise, the status field is
99 IMPORTANT NOTE: The endpoint is assumed to be in synchronous more, otherwise
100 this code will not function as desired
104 OSStatus
DoNegotiateIPReuseAddrOption(EndpointRef ep
, Boolean enableReuseIPMode
)
107 UInt8 buf
[kOTFourByteOptionSize
]; // define buffer for fourByte Option size
108 TOption
* opt
; // option ptr to make items easier to access
113 if (!OTIsSynchronous(ep
))
117 opt
= (TOption
*)buf
; // set option ptr to buffer
119 req
.opt
.len
= sizeof(buf
);
120 req
.flags
= T_NEGOTIATE
; // negotiate for option
123 ret
.opt
.maxlen
= kOTFourByteOptionSize
;
125 opt
->level
= INET_IP
; // dealing with an IP Level function
127 opt
->name
= kIP_REUSEADDR
;
129 opt
->name
= IP_REUSEADDR
;
131 opt
->len
= kOTFourByteOptionSize
;
133 *(UInt32
*)opt
->value
= enableReuseIPMode
; // set the desired option level, true or false
135 err
= OTOptionManagement(ep
, &req
, &ret
);
137 // if no error then return the option status value
138 if (err
== kOTNoError
)
140 if (opt
->status
!= T_SUCCESS
)
150 pascal void OTInetEventHandler(void*s
, OTEventCode event
, OTResult
, void *cookie
) ;
151 pascal void OTInetEventHandler(void*s
, OTEventCode event
, OTResult result
, void *cookie
)
154 GSocket
* sock
= (GSocket
*) s
;
156 if ( event
== kOTSyncIdleEvent
)
164 wxMacAddEvent( sock
->m_mac_events
, _GSocket_Internal_Proc
, event
, s
, wakeUp
) ;
170 static void SetDefaultEndpointModes(EndpointRef ep
, void *data
)
171 // This routine sets the supplied endpoint into the default
172 // mode used in this application. The specifics are:
173 // blocking, synchronous, and using synch idle events with
174 // the standard YieldingNotifier.
176 OSStatus junk
= kOTNoError
;
177 OTAssert ("SetDefaultEndpointModes:invalid ref", ep
!= kOTInvalidEndpointRef
) ;
178 junk
= OTSetAsynchronous(ep
);
179 OTAssert("SetDefaultEndpointModes: Could not set asynchronous", junk
== noErr
);
181 junk = OTSetBlocking(ep);
182 OTAssert("SetDefaultEndpointModes: Could not set blocking", junk == noErr);
183 junk = OTSetSynchronous(ep);
184 OTAssert("SetDefaultEndpointModes: Could not set synchronous", junk == noErr);
185 junk = OTSetBlocking(ep);
186 OTAssert("SetDefaultEndpointModes: Could not set blocking", junk == noErr);
188 junk
= OTInstallNotifier(ep
, OTInetEventHandler
, data
);
189 OTAssert("SetDefaultEndpointModes: Could not install notifier", junk
== noErr
);
191 junk = OTUseSyncIdleEvents(ep, true);
192 OTAssert("SetDefaultEndpointModes: Could not use sync idle events", junk == noErr);
196 /* Global initialisers */
203 int GSocket_Verify_Inited() ;
204 int GSocket_Verify_Inited()
208 // Marc Newsam: added the clientcontext variable
209 // however, documentation is unclear how this works
210 OTClientContextPtr clientcontext
;
215 InitOpenTransportInContext(kInitOTForApplicationMask
, &clientcontext
);
217 gInetSvcRef
= OTOpenInternetServicesInContext(kDefaultInternetServicesPath
,
218 NULL
, &err
, clientcontext
);
223 InitOpenTransport() ;
225 gInetSvcRef
= OTOpenInternetServices(kDefaultInternetServicesPath
, NULL
, &err
);
227 if ( gInetSvcRef
== NULL
|| err
!= kOTNoError
)
229 OTAssert("Could not open Inet Services", err
== noErr
);
235 void GSocket_Cleanup()
237 if ( gOTInited
!= 0 )
239 if ( gInetSvcRef
!= NULL
)
240 OTCloseProvider( gInetSvcRef
);
242 CloseOpenTransportInContext( NULL
) ;
244 CloseOpenTransport() ;
249 /* Constructors / Destructors for GSocket */
251 GSocket
*GSocket_new()
257 if ( GSocket_Verify_Inited() == FALSE
)
260 socket
= (GSocket
*)malloc(sizeof(GSocket
));
265 socket
->m_endpoint
= NULL
;
266 for (i
=0;i
<GSOCK_MAX_EVENT
;i
++)
268 socket
->m_cbacks
[i
] = NULL
;
270 socket
->m_detected
= 0;
271 socket
->m_local
= NULL
;
272 socket
->m_peer
= NULL
;
273 socket
->m_error
= GSOCK_NOERROR
;
274 socket
->m_server
= FALSE
;
275 socket
->m_stream
= TRUE
;
276 socket
->m_non_blocking
= FALSE
;
277 socket
->m_timeout
= 1*1000;
278 /* 10 sec * 1000 millisec */
279 socket
->m_takesEvents
= TRUE
;
280 socket
->m_mac_events
= wxMacGetNotifierTable() ;
284 void GSocket_destroy(GSocket
*socket
)
286 assert(socket
!= NULL
);
288 /* Check that the socket is really shutdowned */
289 if (socket
->m_endpoint
!= kOTInvalidEndpointRef
)
290 GSocket_Shutdown(socket
);
293 /* Destroy private addresses */
295 GAddress_destroy(socket
->m_local
);
298 GAddress_destroy(socket
->m_peer
);
300 /* Destroy the socket itself */
305 * Disallow further read/write operations on this socket, close
306 * the fd and disable all callbacks.
308 void GSocket_Shutdown(GSocket
*socket
)
313 assert(socket
!= NULL
);
315 /* If socket has been created, shutdown it */
316 if (socket
->m_endpoint
!= kOTInvalidEndpointRef
)
318 err
= OTSndOrderlyDisconnect( socket
->m_endpoint
) ;
319 if ( err
!= kOTNoError
)
323 err
= OTRcvOrderlyDisconnect( socket
->m_endpoint
) ;
324 err
= OTUnbind( socket
->m_endpoint
) ;
325 err
= OTCloseProvider( socket
->m_endpoint
) ;
326 socket
->m_endpoint
= kOTInvalidEndpointRef
;
329 /* Disable GUI callbacks */
330 for (evt
= 0; evt
< GSOCK_MAX_EVENT
; evt
++)
331 socket
->m_cbacks
[evt
] = NULL
;
333 socket
->m_detected
= 0;
334 _GSocket_Disable_Events(socket
);
335 wxMacRemoveAllNotifiersForData( wxMacGetNotifierTable() , socket
) ;
339 /* Address handling */
345 * Set or get the local or peer address for this socket. The 'set'
346 * functions return GSOCK_NOERROR on success, an error code otherwise.
347 * The 'get' functions return a pointer to a GAddress object on success,
348 * or NULL otherwise, in which case they set the error code of the
349 * corresponding GSocket.
352 * GSOCK_INVSOCK - the socket is not valid.
353 * GSOCK_INVADDR - the address is not valid.
355 GSocketError
GSocket_SetLocal(GSocket
*socket
, GAddress
*address
)
357 assert(socket
!= NULL
);
359 /* the socket must be initialized, or it must be a server */
360 if ((socket
->m_endpoint
!= kOTInvalidEndpointRef
&& !socket
->m_server
))
362 socket
->m_error
= GSOCK_INVSOCK
;
363 return GSOCK_INVSOCK
;
367 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
369 socket
->m_error
= GSOCK_INVADDR
;
370 return GSOCK_INVADDR
;
374 GAddress_destroy(socket
->m_local
);
376 socket
->m_local
= GAddress_copy(address
);
378 return GSOCK_NOERROR
;
381 GSocketError
GSocket_SetPeer(GSocket
*socket
, GAddress
*address
)
383 assert(socket
!= NULL
);
386 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
388 socket
->m_error
= GSOCK_INVADDR
;
389 return GSOCK_INVADDR
;
393 GAddress_destroy(socket
->m_peer
);
395 socket
->m_peer
= GAddress_copy(address
);
397 return GSOCK_NOERROR
;
400 GAddress
*GSocket_GetLocal(GSocket
*socket
)
402 GAddress
*address
= NULL
;
406 assert(socket
!= NULL
);
408 /* try to get it from the m_local var first */
410 return GAddress_copy(socket
->m_local
);
412 /* else, if the socket is initialized, try getsockname */
413 if (socket
->m_endpoint
== kOTInvalidEndpointRef
)
415 socket
->m_error
= GSOCK_INVSOCK
;
420 /* we do not support multihoming with this code at the moment
421 OTGetProtAddress will have to be used then - but we don't have a handy
422 method to use right now
425 InetInterfaceInfo info
;
426 OTInetGetInterfaceInfo(&info
, kDefaultInetInterface
);
427 loc
.fHost
= info
.fAddress
;
429 loc
.fAddressType
= AF_INET
;
432 /* got a valid address from getsockname, create a GAddress object */
433 address
= GAddress_new();
436 socket
->m_error
= GSOCK_MEMERR
;
440 err
= _GAddress_translate_from(address
, &loc
);
441 if (err
!= GSOCK_NOERROR
)
443 GAddress_destroy(address
);
444 socket
->m_error
= err
;
451 GAddress
*GSocket_GetPeer(GSocket
*socket
)
453 assert(socket
!= NULL
);
455 /* try to get it from the m_peer var */
457 return GAddress_copy(socket
->m_peer
);
462 /* Server specific parts */
464 /* GSocket_SetServer:
465 * Sets up this socket as a server. The local address must have been
466 * set with GSocket_SetLocal() before GSocket_SetServer() is called.
467 * Returns GSOCK_NOERROR on success, one of the following otherwise:
470 * GSOCK_INVSOCK - the socket is in use.
471 * GSOCK_INVADDR - the local address has not been set.
472 * GSOCK_IOERR - low-level error.
474 GSocketError
GSocket_SetServer(GSocket
*sck
)
481 /* must not be in use */
482 if (sck
->m_endpoint
!= kOTInvalidEndpointRef
)
484 sck
->m_error
= GSOCK_INVSOCK
;
485 return GSOCK_INVSOCK
;
488 /* the local addr must have been set */
491 sck
->m_error
= GSOCK_INVADDR
;
492 return GSOCK_INVADDR
;
495 /* Initialize all fields */
496 sck
->m_stream
= TRUE
;
497 sck
->m_server
= TRUE
;
498 sck
->m_oriented
= TRUE
;
502 /* Create the socket */
503 sck
->m_endpoint
= socket(sck
->m_local
->m_realfamily
, SOCK_STREAM
, 0);
504 socket_set_ref( sck
->m_endpoint
, (unsigned long) &gMacNetEvents
, (unsigned long) sck
) ;
505 if (sck
->m_endpoint
== kOTInvalidEndpointRef
)
507 sck
->m_error
= GSOCK_IOERR
;
511 ioctl(sck
->m_endpoint
, FIONBIO
, &arg
);
512 _GSocket_Enable_Events(sck
);
514 /* Bind to the local address,
515 * retrieve the actual address bound,
516 * and listen up to 5 connections.
518 if ((bind(sck
->m_endpoint
, sck
->m_local
->m_addr
, sck
->m_local
->m_len
) != 0) ||
519 (getsockname(sck
->m_endpoint
,
520 sck
->m_local
->m_addr
,
521 (SOCKLEN_T
*) &sck
->m_local
->m_len
) != 0) ||
522 (listen(sck
->m_endpoint
, 5) != 0))
524 close(sck
->m_endpoint
);
525 sck
->m_endpoint
= -1;
526 sck
->m_error
= GSOCK_IOERR
;
530 return GSOCK_NOERROR
;
533 /* GSocket_WaitConnection:
534 * Waits for an incoming client connection. Returns a pointer to
535 * a GSocket object, or NULL if there was an error, in which case
536 * the last error field will be updated for the calling GSocket.
538 * Error codes (set in the calling GSocket)
539 * GSOCK_INVSOCK - the socket is not valid or not a server.
540 * GSOCK_TIMEDOUT - timeout, no incoming connections.
541 * GSOCK_WOULDBLOCK - the call would block and the socket is nonblocking.
542 * GSOCK_MEMERR - couldn't allocate memory.
543 * GSOCK_IOERR - low-level error.
545 GSocket
*GSocket_WaitConnection(GSocket
*socket
)
547 GSocket
*connection
= NULL
;
552 assert(socket
!= NULL
);
554 /* Reenable CONNECTION events */
555 socket
->m_detected
&= ~GSOCK_CONNECTION_FLAG
;
557 /* If the socket has already been created, we exit immediately */
558 if (socket
->m_endpoint
== kOTInvalidEndpointRef
|| !socket
->m_server
)
560 socket
->m_error
= GSOCK_INVSOCK
;
564 /* Create a GSocket object for the new connection */
565 connection
= GSocket_new();
569 socket
->m_error
= GSOCK_MEMERR
;
573 /* Wait for a connection (with timeout) */
574 if (_GSocket_Input_Timeout(socket
) == GSOCK_TIMEDOUT
)
576 GSocket_destroy(connection
);
577 /* socket->m_error set by _GSocket_Input_Timeout */
583 connection
->m_endpoint
= accept(socket
->m_endpoint
, &from
, (SOCKLEN_T
*) &fromlen
);
586 if (connection
->m_endpoint
== kOTInvalidEndpointRef
)
588 if (errno
== EWOULDBLOCK
)
589 socket
->m_error
= GSOCK_WOULDBLOCK
;
591 socket
->m_error
= GSOCK_IOERR
;
593 GSocket_destroy(connection
);
597 /* Initialize all fields */
598 connection
->m_server
= FALSE
;
599 connection
->m_stream
= TRUE
;
600 connection
->m_oriented
= TRUE
;
602 /* Setup the peer address field */
603 connection
->m_peer
= GAddress_new();
604 if (!connection
->m_peer
)
606 GSocket_destroy(connection
);
607 socket
->m_error
= GSOCK_MEMERR
;
612 err
= _GAddress_translate_from(connection
->m_peer
, &from
, fromlen
);
613 if (err
!= GSOCK_NOERROR
)
615 GAddress_destroy(connection
->m_peer
);
616 GSocket_destroy(connection
);
617 socket
->m_error
= err
;
621 ioctl(connection
->m_endpoint
, FIONBIO
, &arg
);
623 _GSocket_Enable_Events(connection
);
628 /* Datagram sockets */
630 /* GSocket_SetNonOriented:
631 * Sets up this socket as a non-connection oriented (datagram) socket.
632 * Before using this function, the local address must have been set
633 * with GSocket_SetLocal(), or the call will fail. Returns GSOCK_NOERROR
634 * on success, or one of the following otherwise.
637 * GSOCK_INVSOCK - the socket is in use.
638 * GSOCK_INVADDR - the local address has not been set.
639 * GSOCK_IOERR - low-level error.
641 GSocketError
GSocket_SetNonOriented(GSocket
*sck
)
647 if (sck
->m_endpoint
!= kOTInvalidEndpointRef
)
649 sck
->m_error
= GSOCK_INVSOCK
;
650 return GSOCK_INVSOCK
;
655 sck
->m_error
= GSOCK_INVADDR
;
656 return GSOCK_INVADDR
;
659 /* Initialize all fields */
660 sck
->m_stream
= FALSE
;
661 sck
->m_server
= FALSE
;
662 sck
->m_oriented
= FALSE
;
664 /* Create the socket */
668 sck
->m_endpoint
= socket(sck
->m_local
->m_realfamily
, SOCK_DGRAM
, 0);
669 socket_set_ref( sck
->m_endpoint
, (unsigned long) &gMacNetEvents
, (unsigned long) sck
) ;
671 if (sck
->m_endpoint
== kOTInvalidEndpointRef
)
673 sck
->m_error
= GSOCK_IOERR
;
679 ioctl(sck
->m_endpoint
, FIONBIO
, &arg
);
681 _GSocket_Enable_Events(sck
);
683 /* Bind to the local address,
684 * and retrieve the actual address bound.
688 if ((bind(sck
->m_endpoint
, sck
->m_local
->m_addr
, sck
->m_local
->m_len
) != 0) ||
689 (getsockname(sck
->m_endpoint
,
690 sck
->m_local
->m_addr
,
691 (SOCKLEN_T
*) &sck
->m_local
->m_len
) != 0))
693 close(sck
->m_endpoint
);
694 sck
->m_endpoint
= -1;
695 sck
->m_error
= GSOCK_IOERR
;
699 return GSOCK_NOERROR
;
702 /* Client specific parts */
705 * For stream (connection oriented) sockets, GSocket_Connect() tries
706 * to establish a client connection to a server using the peer address
707 * as established with GSocket_SetPeer(). Returns GSOCK_NOERROR if the
708 * connection has been succesfully established, or one of the error
709 * codes listed below. Note that for nonblocking sockets, a return
710 * value of GSOCK_WOULDBLOCK doesn't mean a failure. The connection
711 * request can be completed later; you should use GSocket_Select()
712 * to poll for GSOCK_CONNECTION | GSOCK_LOST, or wait for the
713 * corresponding asynchronous events.
715 * For datagram (non connection oriented) sockets, GSocket_Connect()
716 * just sets the peer address established with GSocket_SetPeer() as
717 * default destination.
720 * GSOCK_INVSOCK - the socket is in use or not valid.
721 * GSOCK_INVADDR - the peer address has not been established.
722 * GSOCK_TIMEDOUT - timeout, the connection failed.
723 * GSOCK_WOULDBLOCK - connection in progress (nonblocking sockets only)
724 * GSOCK_MEMERR - couldn't allocate memory.
725 * GSOCK_IOERR - low-level error.
727 GSocketError
GSocket_Connect(GSocket
*sck
, GSocketStream stream
)
734 OSStatus err
= kOTNoError
;
739 /* Enable CONNECTION events (needed for nonblocking connections) */
740 sck
->m_detected
&= ~GSOCK_CONNECTION_FLAG
;
742 if (sck
->m_endpoint
!= kOTInvalidEndpointRef
)
744 sck
->m_error
= GSOCK_INVSOCK
;
745 return GSOCK_INVSOCK
;
750 sck
->m_error
= GSOCK_INVADDR
;
751 return GSOCK_INVADDR
;
754 /* Streamed or dgram socket? */
755 sck
->m_stream
= (stream
== GSOCK_STREAMED
);
756 sck
->m_oriented
= TRUE
;
757 sck
->m_server
= FALSE
;
759 /* Create the socket */
762 OTOpenEndpointInContext( OTCreateConfiguration( kTCPName
) , 0 , &info
, &err
, NULL
) ;
765 OTOpenEndpoint( OTCreateConfiguration( kTCPName
) , 0 , &info
, &err
) ;
767 if ( sck
->m_endpoint
== kOTInvalidEndpointRef
|| err
!= kOTNoError
)
769 sck
->m_endpoint
= kOTInvalidEndpointRef
;
770 sck
->m_error
= GSOCK_IOERR
;
773 err
= OTBind( sck
->m_endpoint
, nil
, nil
) ;
774 if ( err
!= kOTNoError
)
778 SetDefaultEndpointModes( sck
->m_endpoint
, sck
) ;
781 ioctl(sck
->m_endpoint
, FIONBIO
, &arg
);
783 _GSocket_Enable_Events(sck
);
785 _GAddress_translate_to( sck
->m_peer
, &addr
) ;
786 memset( &peer
, 0 , sizeof( TCall
) ) ;
787 peer
.addr
.len
= sizeof( InetAddress
) ;
788 peer
.addr
.buf
= (unsigned char*) &addr
;
789 err
= OTConnect( sck
->m_endpoint
, &peer
, nil
) ;
792 /* If connect failed with EINPROGRESS and the GSocket object
793 * is in blocking mode, we select() for the specified timeout
794 * checking for writability to see if the connection request
798 if ((err
== kOTNoDataErr
) && (!sck
->m_non_blocking
))
800 if (_GSocket_Output_Timeout(sck
) == GSOCK_TIMEDOUT
)
802 OTSndOrderlyDisconnect( sck
->m_endpoint
) ;
803 sck
->m_endpoint
= kOTInvalidEndpointRef
;
804 /* sck->m_error is set in _GSocket_Output_Timeout */
805 return GSOCK_TIMEDOUT
;
811 SOCKLEN_T len = sizeof(error);
813 getsockopt(sck->m_endpoint, SOL_SOCKET, SO_ERROR, (void*) &error, &len);
817 return GSOCK_NOERROR
;
821 /* If connect failed with EINPROGRESS and the GSocket object
822 * is set to nonblocking, we set m_error to GSOCK_WOULDBLOCK
823 * (and return GSOCK_WOULDBLOCK) but we don't close the socket;
824 * this way if the connection completes, a GSOCK_CONNECTION
825 * event will be generated, if enabled.
827 if ((err
== kOTNoDataErr
) && (sck
->m_non_blocking
))
829 sck
->m_error
= GSOCK_WOULDBLOCK
;
830 return GSOCK_WOULDBLOCK
;
833 /* If connect failed with an error other than EINPROGRESS,
834 * then the call to GSocket_Connect has failed.
836 OTSndOrderlyDisconnect( sck
->m_endpoint
) ;
838 sck
->m_endpoint
= kOTInvalidEndpointRef
;
839 sck
->m_error
= GSOCK_IOERR
;
842 // OTInetEventHandler(sck, T_CONNECT , kOTNoError , NULL ) ;
843 return GSOCK_NOERROR
;
848 /* Like recv(), send(), ... */
849 int GSocket_Read(GSocket
*socket
, char *buffer
, int size
)
853 assert(socket
!= NULL
);
855 /* Reenable INPUT events */
856 socket
->m_detected
&= ~GSOCK_INPUT_FLAG
;
858 if (socket
->m_endpoint
== kOTInvalidEndpointRef
|| socket
->m_server
)
860 socket
->m_error
= GSOCK_INVSOCK
;
864 /* If the socket is blocking, wait for data (with a timeout) */
865 if (_GSocket_Input_Timeout(socket
) == GSOCK_TIMEDOUT
)
869 if (socket
->m_stream
)
870 ret
= _GSocket_Recv_Stream(socket
, buffer
, size
);
872 ret
= _GSocket_Recv_Dgram(socket
, buffer
, size
);
876 if (errno
== EWOULDBLOCK
)
877 socket
->m_error
= GSOCK_WOULDBLOCK
;
879 socket
->m_error
= GSOCK_IOERR
;
885 int GSocket_Write(GSocket
*socket
, const char *buffer
, int size
)
889 assert(socket
!= NULL
);
891 if (socket
->m_endpoint
== kOTInvalidEndpointRef
|| socket
->m_server
)
893 socket
->m_error
= GSOCK_INVSOCK
;
897 /* If the socket is blocking, wait for writability (with a timeout) */
898 if (_GSocket_Output_Timeout(socket
) == GSOCK_TIMEDOUT
)
902 if (socket
->m_stream
)
903 ret
= _GSocket_Send_Stream(socket
, buffer
, size
);
905 ret
= _GSocket_Send_Dgram(socket
, buffer
, size
);
909 if (errno
== EWOULDBLOCK
)
910 socket
->m_error
= GSOCK_WOULDBLOCK
;
912 socket
->m_error
= GSOCK_IOERR
;
914 /* Only reenable OUTPUT events after an error (just like WSAAsyncSelect
915 * in MSW). Once the first OUTPUT event is received, users can assume
916 * that the socket is writable until a read operation fails. Only then
917 * will further OUTPUT events be posted.
919 socket
->m_detected
&= ~GSOCK_OUTPUT_FLAG
;
927 * Polls the socket to determine its status. This function will
928 * check for the events specified in the 'flags' parameter, and
929 * it will return a mask indicating which operations can be
930 * performed. This function won't block, regardless of the
931 * mode (blocking | nonblocking) of the socket.
933 GSocketEventFlags
GSocket_Select(GSocket
*socket
, GSocketEventFlags flags
)
936 assert(socket
!= NULL
);
937 wxMacProcessNotifierEvents() ;
939 state = OTGetEndpointState(socket->m_endpoint);
941 if ( ( flags & GSOCK_INPUT_FLAG ) && ! ( socket->m_detected & GSOCK_INPUT_FLAG ) )
944 OTCountDataBytes( socket->m_endpoint , &sz ) ;
945 if ( state == T_INCON || sz > 0 )
947 socket->m_detected |= GSOCK_INPUT_FLAG ;
948 (socket->m_cbacks[GSOCK_INPUT])(socket, GSOCK_INPUT, socket->m_data[GSOCK_INPUT]);
951 if ( ( flags & GSOCK_INPUT_FLAG ) && ! ( socket->m_detected & GSOCK_OUTPUT_FLAG ) )
953 if ( state == T_DATAXFER || state == T_INREL )
955 socket->m_detected |=GSOCK_OUTPUT_FLAG ;
956 (socket->m_cbacks[GSOCK_OUTPUT])(socket, GSOCK_OUTPUT, socket->m_data[GSOCK_OUTPUT]);
960 return ( flags
& socket
->m_detected
) ;
965 /* GSocket_SetNonBlocking:
966 * Sets the socket to non-blocking mode. All IO calls will return
969 void GSocket_SetNonBlocking(GSocket
*socket
, int non_block
)
971 assert(socket
!= NULL
);
973 socket
->m_non_blocking
= non_block
;
976 /* GSocket_SetTimeout:
977 * Sets the timeout for blocking calls. Time is expressed in
980 void GSocket_SetTimeout(GSocket
*socket
, unsigned long millisec
)
982 assert(socket
!= NULL
);
984 // this is usually set too high and we have not yet been able to detect a closed
985 // stream, thus we leave the 10 sec timeout
986 // socket->m_timeout = millisec;
990 * Returns the last error occured for this socket. Note that successful
991 * operations do not clear this back to GSOCK_NOERROR, so use it only
994 GSocketError
GSocket_GetError(GSocket
*socket
)
996 assert(socket
!= NULL
);
998 return socket
->m_error
;
1004 * There is data to be read in the input buffer. If, after a read
1005 * operation, there is still data available, the callback function will
1008 * The socket is available for writing. That is, the next write call
1009 * won't block. This event is generated only once, when the connection is
1010 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
1011 * when the output buffer empties again. This means that the app should
1012 * assume that it can write since the first OUTPUT event, and no more
1013 * OUTPUT events will be generated unless an error occurs.
1015 * Connection succesfully established, for client sockets, or incoming
1016 * client connection, for server sockets. Wait for this event (also watch
1017 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
1019 * The connection is lost (or a connection request failed); this could
1020 * be due to a failure, or due to the peer closing it gracefully.
1023 /* GSocket_SetCallback:
1024 * Enables the callbacks specified by 'flags'. Note that 'flags'
1025 * may be a combination of flags OR'ed toghether, so the same
1026 * callback function can be made to accept different events.
1027 * The callback function must have the following prototype:
1029 * void function(GSocket *socket, GSocketEvent event, char *cdata)
1031 void GSocket_SetCallback(GSocket
*socket
, GSocketEventFlags flags
,
1032 GSocketCallback callback
, char *cdata
)
1036 assert(socket
!= NULL
);
1038 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1040 if ((flags
& (1 << count
)) != 0)
1042 socket
->m_cbacks
[count
] = callback
;
1043 socket
->m_data
[count
] = cdata
;
1048 /* GSocket_UnsetCallback:
1049 * Disables all callbacks specified by 'flags', which may be a
1050 * combination of flags OR'ed toghether.
1052 void GSocket_UnsetCallback(GSocket
*socket
, GSocketEventFlags flags
)
1056 assert(socket
!= NULL
);
1058 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1060 if ((flags
& (1 << count
)) != 0)
1062 socket
->m_cbacks
[count
] = NULL
;
1063 socket
->m_data
[count
] = NULL
;
1069 #define CALL_CALLBACK(socket, event) { \
1070 _GSocket_Disable(socket, event); \
1071 if (socket->m_cbacks[event]) \
1072 socket->m_cbacks[event](socket, event, socket->m_data[event]); \
1075 int _GSocket_Recv_Stream(GSocket
*socket
, char *buffer
, int size
)
1079 OTByteCount sz
= 0 ;
1081 OTCountDataBytes( socket
->m_endpoint
, &sz
) ;
1084 res
= OTRcv( socket
->m_endpoint
, buffer
, size
, &flags
) ;
1090 // we simulate another read event if there are still bytes
1091 if ( socket
->m_takesEvents
)
1093 OTByteCount sz
= 0 ;
1094 OTCountDataBytes( socket
->m_endpoint
, &sz
) ;
1097 socket
->m_detected
|= GSOCK_INPUT_FLAG
;
1098 (socket
->m_cbacks
[GSOCK_INPUT
])(socket
, GSOCK_INPUT
, socket
->m_data
[GSOCK_INPUT
]);
1104 int _GSocket_Recv_Dgram(GSocket
*socket
, char *buffer
, int size
)
1109 struct sockaddr from
;
1110 SOCKLEN_T fromlen
= sizeof(from
);
1113 fromlen
= sizeof(from
);
1115 ret
= recvfrom(socket
->m_endpoint
, buffer
, size
, 0, &from
, (SOCKLEN_T
*) &fromlen
);
1120 /* Translate a system address into a GSocket address */
1121 if (!socket
->m_peer
)
1123 socket
->m_peer
= GAddress_new();
1124 if (!socket
->m_peer
)
1126 socket
->m_error
= GSOCK_MEMERR
;
1130 err
= _GAddress_translate_from(socket
->m_peer
, &from
, fromlen
);
1131 if (err
!= GSOCK_NOERROR
)
1133 GAddress_destroy(socket
->m_peer
);
1134 socket
->m_peer
= NULL
;
1135 socket
->m_error
= err
;
1142 int _GSocket_Send_Stream(GSocket
*socket
, const char *buffer
, int size
)
1147 res
= OTSnd( socket
->m_endpoint
, (void*) buffer
, size
, flags
) ;
1151 int _GSocket_Send_Dgram(GSocket
*socket
, const char *buffer
, int size
)
1156 struct sockaddr
*addr
;
1160 if (!socket
->m_peer
)
1162 socket
->m_error
= GSOCK_INVADDR
;
1166 err
= _GAddress_translate_to(socket
->m_peer
, &addr
, &len
);
1167 if (err
!= GSOCK_NOERROR
)
1169 socket
->m_error
= err
;
1173 ret
= sendto(socket
->m_endpoint
, buffer
, size
, 0, addr
, len
);
1175 /* Frees memory allocated from _GAddress_translate_to */
1183 * -------------------------------------------------------------------------
1185 * -------------------------------------------------------------------------
1188 /* CHECK_ADDRESS verifies that the current family is either GSOCK_NOFAMILY
1189 * or GSOCK_*family*, and if it is GSOCK_NOFAMILY, it initalizes address
1190 * to be a GSOCK_*family*. In other cases, it returns GSOCK_INVADDR.
1192 #define CHECK_ADDRESS(address, family, retval) \
1194 if (address->m_family == GSOCK_NOFAMILY) \
1195 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1196 return address->m_error; \
1197 if (address->m_family != GSOCK_##family) \
1199 address->m_error = GSOCK_INVADDR; \
1204 GAddress
*GAddress_new()
1208 if ((address
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1211 address
->m_family
= GSOCK_NOFAMILY
;
1212 address
->m_host
= INADDR_NONE
;
1213 address
->m_port
= 0 ;
1218 GAddress
*GAddress_copy(GAddress
*address
)
1222 assert(address
!= NULL
);
1224 if ((addr2
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1227 memcpy(addr2
, address
, sizeof(GAddress
));
1231 void GAddress_destroy(GAddress
*address
)
1233 assert(address
!= NULL
);
1238 void GAddress_SetFamily(GAddress
*address
, GAddressType type
)
1240 assert(address
!= NULL
);
1242 address
->m_family
= type
;
1245 GAddressType
GAddress_GetFamily(GAddress
*address
)
1247 assert(address
!= NULL
);
1249 return address
->m_family
;
1252 GSocketError
_GAddress_translate_from(GAddress
*address
,
1255 switch (addr
->fAddressType
)
1258 address
->m_family
= GSOCK_INET
;
1262 address
->m_family
= GSOCK_INET6
;
1267 address
->m_error
= GSOCK_INVOP
;
1271 address
->m_host
= addr
->fHost
;
1272 address
->m_port
= addr
->fPort
;
1273 return GSOCK_NOERROR
;
1276 GSocketError
_GAddress_translate_to(GAddress
*address
,
1279 if ( GSocket_Verify_Inited() == FALSE
)
1280 return GSOCK_IOERR
;
1281 memset(addr
, 0 , sizeof(struct InetAddress
));
1282 OTInitInetAddress( addr
, address
->m_port
, address
->m_host
) ;
1283 return GSOCK_NOERROR
;
1287 * -------------------------------------------------------------------------
1288 * Internet address family
1289 * -------------------------------------------------------------------------
1292 GSocketError
_GAddress_Init_INET(GAddress
*address
)
1294 address
->m_family
= GSOCK_INET
;
1295 address
->m_host
= kOTAnyInetAddress
;
1297 return GSOCK_NOERROR
;
1300 GSocketError
GAddress_INET_SetHostName(GAddress
*address
, const char *hostname
)
1302 InetHostInfo hinfo
;
1305 if ( GSocket_Verify_Inited() == FALSE
)
1306 return GSOCK_IOERR
;
1308 assert(address
!= NULL
);
1310 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1311 ret
= OTInetStringToAddress( gInetSvcRef
, (char*) hostname
, &hinfo
) ;
1312 if ( ret
!= kOTNoError
)
1314 address
->m_host
= INADDR_NONE
;
1315 address
->m_error
= GSOCK_NOHOST
;
1316 return GSOCK_NOHOST
;
1318 address
->m_host
= hinfo
.addrs
[0] ;
1319 return GSOCK_NOERROR
;
1322 GSocketError
GAddress_INET_SetAnyAddress(GAddress
*address
)
1324 return GAddress_INET_SetHostAddress(address
, INADDR_ANY
);
1327 GSocketError
GAddress_INET_SetHostAddress(GAddress
*address
,
1328 unsigned long hostaddr
)
1330 struct in_addr
*addr
;
1332 assert(address
!= NULL
);
1334 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1336 address
->m_host
= hostaddr
;
1338 return GSOCK_NOERROR
;
1341 struct service_entry
1344 unsigned short port
;
1347 typedef struct service_entry service_entry
;
1349 service_entry gServices
[] =
1351 { "http" , 80 , "tcp" }
1354 GSocketError
GAddress_INET_SetPortName(GAddress
*address
, const char *port
,
1355 const char *protocol
)
1360 assert(address
!= NULL
);
1361 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1365 address
->m_error
= GSOCK_INVPORT
;
1366 return GSOCK_INVPORT
;
1368 for ( i
= 0 ; i
< sizeof( gServices
) / sizeof( service_entry
) ; ++i
)
1370 if ( strcmp( port
, gServices
[i
].name
) == 0 )
1372 if ( protocol
== NULL
|| strcmp( protocol
, gServices
[i
].protocol
) )
1374 address
->m_port
= gServices
[i
].port
;
1375 return GSOCK_NOERROR
;
1380 if (isdigit(port
[0]))
1382 address
->m_port
= atoi(port
);
1383 return GSOCK_NOERROR
;
1386 address
->m_error
= GSOCK_INVPORT
;
1387 return GSOCK_INVPORT
;
1390 GSocketError
GAddress_INET_SetPort(GAddress
*address
, unsigned short port
)
1394 assert(address
!= NULL
);
1395 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1396 address
->m_port
= port
;
1398 return GSOCK_NOERROR
;
1401 GSocketError
GAddress_INET_GetHostName(GAddress
*address
, char *hostname
, size_t sbuf
)
1403 InetDomainName name
;
1404 if ( GSocket_Verify_Inited() == FALSE
)
1405 return GSOCK_IOERR
;
1407 assert(address
!= NULL
);
1408 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1410 OTInetAddressToName( gInetSvcRef
, address
->m_host
, name
) ;
1411 strncpy( hostname
, name
, sbuf
) ;
1412 return GSOCK_NOERROR
;
1415 unsigned long GAddress_INET_GetHostAddress(GAddress
*address
)
1417 assert(address
!= NULL
);
1418 CHECK_ADDRESS(address
, INET
, 0);
1420 return address
->m_host
;
1423 unsigned short GAddress_INET_GetPort(GAddress
*address
)
1425 assert(address
!= NULL
);
1426 CHECK_ADDRESS(address
, INET
, 0);
1428 return address
->m_port
;
1431 void _GSocket_Enable_Events(GSocket
*socket
)
1433 if ( socket
->m_takesEvents
)
1438 socket
->m_takesEvents
= TRUE
;
1439 state
= OTGetEndpointState(socket
->m_endpoint
);
1442 OTByteCount sz
= 0 ;
1443 OTCountDataBytes( socket
->m_endpoint
, &sz
) ;
1444 if ( state
== T_INCON
|| sz
> 0 )
1446 socket
->m_detected
|= GSOCK_INPUT_FLAG
;
1447 (socket
->m_cbacks
[GSOCK_INPUT
])(socket
, GSOCK_INPUT
, socket
->m_data
[GSOCK_INPUT
]);
1451 if ( state
== T_DATAXFER
|| state
== T_INREL
)
1453 socket
->m_detected
|=GSOCK_OUTPUT_FLAG
;
1454 (socket
->m_cbacks
[GSOCK_OUTPUT
])(socket
, GSOCK_OUTPUT
, socket
->m_data
[GSOCK_OUTPUT
]);
1460 void _GSocket_Disable_Events(GSocket
*socket
)
1462 socket
->m_takesEvents
= FALSE
;
1465 /* _GSocket_Input_Timeout:
1466 * For blocking sockets, wait until data is available or
1467 * until timeout ellapses.
1469 GSocketError
_GSocket_Input_Timeout(GSocket
*socket
)
1471 if ( !socket
->m_non_blocking
)
1473 UnsignedWide now
, start
;
1474 short formerTakesEvents
= socket
->m_takesEvents
;
1475 Microseconds(&start
);
1477 socket
->m_takesEvents
= FALSE
;
1479 while( (now
.hi
* 4294967296.0 + now
.lo
) - (start
.hi
* 4294967296.0 + start
.lo
) < socket
->m_timeout
* 1000.0 )
1482 OTByteCount sz
= 0 ;
1483 state
= OTGetEndpointState(socket
->m_endpoint
);
1485 OTCountDataBytes( socket
->m_endpoint
, &sz
) ;
1486 if ( state
== T_INCON
|| sz
> 0 )
1488 socket
->m_takesEvents
= formerTakesEvents
;
1489 return GSOCK_NOERROR
;
1493 socket
->m_takesEvents
= formerTakesEvents
;
1494 socket
->m_error
= GSOCK_TIMEDOUT
;
1495 return GSOCK_TIMEDOUT
;
1497 return GSOCK_NOERROR
;
1500 /* _GSocket_Output_Timeout:
1501 * For blocking sockets, wait until data can be sent without
1502 * blocking or until timeout ellapses.
1504 GSocketError
_GSocket_Output_Timeout(GSocket
*socket
)
1506 if ( !socket
->m_non_blocking
)
1508 UnsignedWide now
, start
;
1509 short formerTakesEvents
= socket
->m_takesEvents
;
1510 Microseconds(&start
);
1512 socket
->m_takesEvents
= FALSE
;
1514 while( (now
.hi
* 4294967296.0 + now
.lo
) - (start
.hi
* 4294967296.0 + start
.lo
) < socket
->m_timeout
* 1000.0 )
1517 state
= OTGetEndpointState(socket
->m_endpoint
);
1519 if ( state
== T_DATAXFER
|| state
== T_INREL
)
1521 socket
->m_takesEvents
= formerTakesEvents
;
1522 return GSOCK_NOERROR
;
1526 socket
->m_takesEvents
= formerTakesEvents
;
1527 socket
->m_error
= GSOCK_TIMEDOUT
;
1528 return GSOCK_TIMEDOUT
;
1530 return GSOCK_NOERROR
;
1534 * There is data to be read in the input buffer. If, after a read
1535 * operation, there is still data available, the callback function will
1538 * The socket is available for writing. That is, the next write call
1539 * won't block. This event is generated only once, when the connection is
1540 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
1541 * when the output buffer empties again. This means that the app should
1542 * assume that it can write since the first OUTPUT event, and no more
1543 * OUTPUT events will be generated unless an error occurs.
1545 * Connection succesfully established, for client sockets, or incoming
1546 * client connection, for server sockets. Wait for this event (also watch
1547 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
1549 * The connection is lost (or a connection request failed); this could
1550 * be due to a failure, or due to the peer closing it gracefully.
1553 void _GSocket_Internal_Proc(unsigned long e
, void* d
)
1556 GSocket
* socket
= (GSocket
*) d
;
1557 OTEventCode ev
= (OTEventCode
) e
;
1559 GSocketEvent event2
;
1560 GSocketCallback cback
;
1562 GSocketCallback cback2
;
1567 event
= GSOCK_MAX_EVENT
;
1568 event2
= GSOCK_MAX_EVENT
;
1574 /* Check that the socket still exists (it has not been
1575 * destroyed) and for safety, check that the m_endpoint field
1576 * is what we expect it to be.
1578 if ((socket
!= NULL
) && (socket
->m_takesEvents
))
1583 event
= GSOCK_CONNECTION
;
1586 event
= GSOCK_CONNECTION
;
1587 event2
= GSOCK_OUTPUT
;
1591 retCall
.addr
.buf
= NULL
;
1592 retCall
.addr
.maxlen
= 0;
1593 retCall
.opt
.buf
= NULL
;
1594 retCall
.opt
.maxlen
= 0;
1595 retCall
.udata
.buf
= NULL
;
1596 retCall
.udata
.maxlen
= 0;
1597 OTRcvConnect( socket
->m_endpoint
, &retCall
) ;
1601 event
= GSOCK_LOST
;
1605 event
= GSOCK_OUTPUT
;
1608 event
= GSOCK_INPUT
;
1611 event
= GSOCK_INPUT
;
1614 if (event
!= GSOCK_MAX_EVENT
)
1616 cback
= socket
->m_cbacks
[event
];
1617 data
= socket
->m_data
[event
];
1619 if (event
== GSOCK_LOST
)
1620 socket
->m_detected
= GSOCK_LOST_FLAG
;
1622 socket
->m_detected
|= (1 << event
);
1624 if (event2
!= GSOCK_MAX_EVENT
)
1626 cback2
= socket
->m_cbacks
[event2
];
1627 data2
= socket
->m_data
[event2
];
1629 if (event2
== GSOCK_LOST
)
1630 socket
->m_detected
= GSOCK_LOST_FLAG
;
1632 socket
->m_detected
|= (1 << event2
);
1636 /* OK, we can now leave the critical section because we have
1637 * already obtained the callback address (we make no further
1638 * accesses to socket->whatever). However, the app should
1639 * be prepared to handle events from a socket that has just
1644 (cback
)(socket
, event
, data
);
1646 (cback2
)(socket
, event2
, data2
);
1650 /* Hack added for Mac OS X */
1651 GSocketError
GAddress_UNIX_GetPath(GAddress
*addr
, char *path
, size_t buf
)
1655 GSocketError
GAddress_UNIX_SetPath(GAddress
*addr
, const char *path
)
1659 #endif /* wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__) */