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
)
478 /* must not be in use */
479 if (sck
->m_endpoint
!= kOTInvalidEndpointRef
)
481 sck
->m_error
= GSOCK_INVSOCK
;
482 return GSOCK_INVSOCK
;
485 /* the local addr must have been set */
488 sck
->m_error
= GSOCK_INVADDR
;
489 return GSOCK_INVADDR
;
492 /* Initialize all fields */
493 sck
->m_stream
= TRUE
;
494 sck
->m_server
= TRUE
;
495 sck
->m_oriented
= TRUE
;
499 /* Create the socket */
500 sck
->m_endpoint
= socket(sck
->m_local
->m_realfamily
, SOCK_STREAM
, 0);
501 socket_set_ref( sck
->m_endpoint
, (unsigned long) &gMacNetEvents
, (unsigned long) sck
) ;
502 if (sck
->m_endpoint
== kOTInvalidEndpointRef
)
504 sck
->m_error
= GSOCK_IOERR
;
508 ioctl(sck
->m_endpoint
, FIONBIO
, &arg
);
509 _GSocket_Enable_Events(sck
);
511 /* Bind to the local address,
512 * retrieve the actual address bound,
513 * and listen up to 5 connections.
515 if ((bind(sck
->m_endpoint
, sck
->m_local
->m_addr
, sck
->m_local
->m_len
) != 0) ||
516 (getsockname(sck
->m_endpoint
,
517 sck
->m_local
->m_addr
,
518 (SOCKLEN_T
*) &sck
->m_local
->m_len
) != 0) ||
519 (listen(sck
->m_endpoint
, 5) != 0))
521 close(sck
->m_endpoint
);
522 sck
->m_endpoint
= -1;
523 sck
->m_error
= GSOCK_IOERR
;
527 return GSOCK_NOERROR
;
530 /* GSocket_WaitConnection:
531 * Waits for an incoming client connection. Returns a pointer to
532 * a GSocket object, or NULL if there was an error, in which case
533 * the last error field will be updated for the calling GSocket.
535 * Error codes (set in the calling GSocket)
536 * GSOCK_INVSOCK - the socket is not valid or not a server.
537 * GSOCK_TIMEDOUT - timeout, no incoming connections.
538 * GSOCK_WOULDBLOCK - the call would block and the socket is nonblocking.
539 * GSOCK_MEMERR - couldn't allocate memory.
540 * GSOCK_IOERR - low-level error.
542 GSocket
*GSocket_WaitConnection(GSocket
*socket
)
544 GSocket
*connection
= NULL
;
546 assert(socket
!= NULL
);
548 /* Reenable CONNECTION events */
549 socket
->m_detected
&= ~GSOCK_CONNECTION_FLAG
;
551 /* If the socket has already been created, we exit immediately */
552 if (socket
->m_endpoint
== kOTInvalidEndpointRef
|| !socket
->m_server
)
554 socket
->m_error
= GSOCK_INVSOCK
;
558 /* Create a GSocket object for the new connection */
559 connection
= GSocket_new();
563 socket
->m_error
= GSOCK_MEMERR
;
567 /* Wait for a connection (with timeout) */
568 if (_GSocket_Input_Timeout(socket
) == GSOCK_TIMEDOUT
)
570 GSocket_destroy(connection
);
571 /* socket->m_error set by _GSocket_Input_Timeout */
577 connection
->m_endpoint
= accept(socket
->m_endpoint
, &from
, (SOCKLEN_T
*) &fromlen
);
580 if (connection
->m_endpoint
== kOTInvalidEndpointRef
)
582 if (errno
== EWOULDBLOCK
)
583 socket
->m_error
= GSOCK_WOULDBLOCK
;
585 socket
->m_error
= GSOCK_IOERR
;
587 GSocket_destroy(connection
);
591 /* Initialize all fields */
592 connection
->m_server
= FALSE
;
593 connection
->m_stream
= TRUE
;
594 connection
->m_oriented
= TRUE
;
596 /* Setup the peer address field */
597 connection
->m_peer
= GAddress_new();
598 if (!connection
->m_peer
)
600 GSocket_destroy(connection
);
601 socket
->m_error
= GSOCK_MEMERR
;
606 err
= _GAddress_translate_from(connection
->m_peer
, &from
, fromlen
);
607 if (err
!= GSOCK_NOERROR
)
609 GAddress_destroy(connection
->m_peer
);
610 GSocket_destroy(connection
);
611 socket
->m_error
= err
;
615 ioctl(connection
->m_endpoint
, FIONBIO
, &arg
);
617 _GSocket_Enable_Events(connection
);
622 /* Datagram sockets */
624 /* GSocket_SetNonOriented:
625 * Sets up this socket as a non-connection oriented (datagram) socket.
626 * Before using this function, the local address must have been set
627 * with GSocket_SetLocal(), or the call will fail. Returns GSOCK_NOERROR
628 * on success, or one of the following otherwise.
631 * GSOCK_INVSOCK - the socket is in use.
632 * GSOCK_INVADDR - the local address has not been set.
633 * GSOCK_IOERR - low-level error.
635 GSocketError
GSocket_SetNonOriented(GSocket
*sck
)
639 if (sck
->m_endpoint
!= kOTInvalidEndpointRef
)
641 sck
->m_error
= GSOCK_INVSOCK
;
642 return GSOCK_INVSOCK
;
647 sck
->m_error
= GSOCK_INVADDR
;
648 return GSOCK_INVADDR
;
651 /* Initialize all fields */
652 sck
->m_stream
= FALSE
;
653 sck
->m_server
= FALSE
;
654 sck
->m_oriented
= FALSE
;
656 /* Create the socket */
660 sck
->m_endpoint
= socket(sck
->m_local
->m_realfamily
, SOCK_DGRAM
, 0);
661 socket_set_ref( sck
->m_endpoint
, (unsigned long) &gMacNetEvents
, (unsigned long) sck
) ;
663 if (sck
->m_endpoint
== kOTInvalidEndpointRef
)
665 sck
->m_error
= GSOCK_IOERR
;
671 ioctl(sck
->m_endpoint
, FIONBIO
, &arg
);
673 _GSocket_Enable_Events(sck
);
675 /* Bind to the local address,
676 * and retrieve the actual address bound.
680 if ((bind(sck
->m_endpoint
, sck
->m_local
->m_addr
, sck
->m_local
->m_len
) != 0) ||
681 (getsockname(sck
->m_endpoint
,
682 sck
->m_local
->m_addr
,
683 (SOCKLEN_T
*) &sck
->m_local
->m_len
) != 0))
685 close(sck
->m_endpoint
);
686 sck
->m_endpoint
= -1;
687 sck
->m_error
= GSOCK_IOERR
;
691 return GSOCK_NOERROR
;
694 /* Client specific parts */
697 * For stream (connection oriented) sockets, GSocket_Connect() tries
698 * to establish a client connection to a server using the peer address
699 * as established with GSocket_SetPeer(). Returns GSOCK_NOERROR if the
700 * connection has been succesfully established, or one of the error
701 * codes listed below. Note that for nonblocking sockets, a return
702 * value of GSOCK_WOULDBLOCK doesn't mean a failure. The connection
703 * request can be completed later; you should use GSocket_Select()
704 * to poll for GSOCK_CONNECTION | GSOCK_LOST, or wait for the
705 * corresponding asynchronous events.
707 * For datagram (non connection oriented) sockets, GSocket_Connect()
708 * just sets the peer address established with GSocket_SetPeer() as
709 * default destination.
712 * GSOCK_INVSOCK - the socket is in use or not valid.
713 * GSOCK_INVADDR - the peer address has not been established.
714 * GSOCK_TIMEDOUT - timeout, the connection failed.
715 * GSOCK_WOULDBLOCK - connection in progress (nonblocking sockets only)
716 * GSOCK_MEMERR - couldn't allocate memory.
717 * GSOCK_IOERR - low-level error.
719 GSocketError
GSocket_Connect(GSocket
*sck
, GSocketStream stream
)
723 OSStatus err
= kOTNoError
;
728 /* Enable CONNECTION events (needed for nonblocking connections) */
729 sck
->m_detected
&= ~GSOCK_CONNECTION_FLAG
;
731 if (sck
->m_endpoint
!= kOTInvalidEndpointRef
)
733 sck
->m_error
= GSOCK_INVSOCK
;
734 return GSOCK_INVSOCK
;
739 sck
->m_error
= GSOCK_INVADDR
;
740 return GSOCK_INVADDR
;
743 /* Streamed or dgram socket? */
744 sck
->m_stream
= (stream
== GSOCK_STREAMED
);
745 sck
->m_oriented
= TRUE
;
746 sck
->m_server
= FALSE
;
748 /* Create the socket */
751 OTOpenEndpointInContext( OTCreateConfiguration( kTCPName
) , 0 , &info
, &err
, NULL
) ;
754 OTOpenEndpoint( OTCreateConfiguration( kTCPName
) , 0 , &info
, &err
) ;
756 if ( sck
->m_endpoint
== kOTInvalidEndpointRef
|| err
!= kOTNoError
)
758 sck
->m_endpoint
= kOTInvalidEndpointRef
;
759 sck
->m_error
= GSOCK_IOERR
;
762 err
= OTBind( sck
->m_endpoint
, nil
, nil
) ;
763 if ( err
!= kOTNoError
)
767 SetDefaultEndpointModes( sck
->m_endpoint
, sck
) ;
770 ioctl(sck
->m_endpoint
, FIONBIO
, &arg
);
772 _GSocket_Enable_Events(sck
);
774 _GAddress_translate_to( sck
->m_peer
, &addr
) ;
775 memset( &peer
, 0 , sizeof( TCall
) ) ;
776 peer
.addr
.len
= sizeof( InetAddress
) ;
777 peer
.addr
.buf
= (unsigned char*) &addr
;
778 err
= OTConnect( sck
->m_endpoint
, &peer
, nil
) ;
781 /* If connect failed with EINPROGRESS and the GSocket object
782 * is in blocking mode, we select() for the specified timeout
783 * checking for writability to see if the connection request
787 if ((err
== kOTNoDataErr
) && (!sck
->m_non_blocking
))
789 if (_GSocket_Output_Timeout(sck
) == GSOCK_TIMEDOUT
)
791 OTSndOrderlyDisconnect( sck
->m_endpoint
) ;
792 sck
->m_endpoint
= kOTInvalidEndpointRef
;
793 /* sck->m_error is set in _GSocket_Output_Timeout */
794 return GSOCK_TIMEDOUT
;
800 SOCKLEN_T len = sizeof(error);
802 getsockopt(sck->m_endpoint, SOL_SOCKET, SO_ERROR, (void*) &error, &len);
806 return GSOCK_NOERROR
;
810 /* If connect failed with EINPROGRESS and the GSocket object
811 * is set to nonblocking, we set m_error to GSOCK_WOULDBLOCK
812 * (and return GSOCK_WOULDBLOCK) but we don't close the socket;
813 * this way if the connection completes, a GSOCK_CONNECTION
814 * event will be generated, if enabled.
816 if ((err
== kOTNoDataErr
) && (sck
->m_non_blocking
))
818 sck
->m_error
= GSOCK_WOULDBLOCK
;
819 return GSOCK_WOULDBLOCK
;
822 /* If connect failed with an error other than EINPROGRESS,
823 * then the call to GSocket_Connect has failed.
825 OTSndOrderlyDisconnect( sck
->m_endpoint
) ;
827 sck
->m_endpoint
= kOTInvalidEndpointRef
;
828 sck
->m_error
= GSOCK_IOERR
;
831 // OTInetEventHandler(sck, T_CONNECT , kOTNoError , NULL ) ;
832 return GSOCK_NOERROR
;
837 /* Like recv(), send(), ... */
838 int GSocket_Read(GSocket
*socket
, char *buffer
, int size
)
842 assert(socket
!= NULL
);
844 /* Reenable INPUT events */
845 socket
->m_detected
&= ~GSOCK_INPUT_FLAG
;
847 if (socket
->m_endpoint
== kOTInvalidEndpointRef
|| socket
->m_server
)
849 socket
->m_error
= GSOCK_INVSOCK
;
853 /* If the socket is blocking, wait for data (with a timeout) */
854 if (_GSocket_Input_Timeout(socket
) == GSOCK_TIMEDOUT
)
858 if (socket
->m_stream
)
859 ret
= _GSocket_Recv_Stream(socket
, buffer
, size
);
861 ret
= _GSocket_Recv_Dgram(socket
, buffer
, size
);
865 if (errno
== EWOULDBLOCK
)
866 socket
->m_error
= GSOCK_WOULDBLOCK
;
868 socket
->m_error
= GSOCK_IOERR
;
874 int GSocket_Write(GSocket
*socket
, const char *buffer
, int size
)
878 assert(socket
!= NULL
);
880 if (socket
->m_endpoint
== kOTInvalidEndpointRef
|| socket
->m_server
)
882 socket
->m_error
= GSOCK_INVSOCK
;
886 /* If the socket is blocking, wait for writability (with a timeout) */
887 if (_GSocket_Output_Timeout(socket
) == GSOCK_TIMEDOUT
)
891 if (socket
->m_stream
)
892 ret
= _GSocket_Send_Stream(socket
, buffer
, size
);
894 ret
= _GSocket_Send_Dgram(socket
, buffer
, size
);
898 if (errno
== EWOULDBLOCK
)
899 socket
->m_error
= GSOCK_WOULDBLOCK
;
901 socket
->m_error
= GSOCK_IOERR
;
903 /* Only reenable OUTPUT events after an error (just like WSAAsyncSelect
904 * in MSW). Once the first OUTPUT event is received, users can assume
905 * that the socket is writable until a read operation fails. Only then
906 * will further OUTPUT events be posted.
908 socket
->m_detected
&= ~GSOCK_OUTPUT_FLAG
;
916 * Polls the socket to determine its status. This function will
917 * check for the events specified in the 'flags' parameter, and
918 * it will return a mask indicating which operations can be
919 * performed. This function won't block, regardless of the
920 * mode (blocking | nonblocking) of the socket.
922 GSocketEventFlags
GSocket_Select(GSocket
*socket
, GSocketEventFlags flags
)
924 assert(socket
!= NULL
);
925 wxMacProcessNotifierEvents() ;
927 state = OTGetEndpointState(socket->m_endpoint);
929 if ( ( flags & GSOCK_INPUT_FLAG ) && ! ( socket->m_detected & GSOCK_INPUT_FLAG ) )
932 OTCountDataBytes( socket->m_endpoint , &sz ) ;
933 if ( state == T_INCON || sz > 0 )
935 socket->m_detected |= GSOCK_INPUT_FLAG ;
936 (socket->m_cbacks[GSOCK_INPUT])(socket, GSOCK_INPUT, socket->m_data[GSOCK_INPUT]);
939 if ( ( flags & GSOCK_INPUT_FLAG ) && ! ( socket->m_detected & GSOCK_OUTPUT_FLAG ) )
941 if ( state == T_DATAXFER || state == T_INREL )
943 socket->m_detected |=GSOCK_OUTPUT_FLAG ;
944 (socket->m_cbacks[GSOCK_OUTPUT])(socket, GSOCK_OUTPUT, socket->m_data[GSOCK_OUTPUT]);
948 return ( flags
& socket
->m_detected
) ;
953 /* GSocket_SetNonBlocking:
954 * Sets the socket to non-blocking mode. All IO calls will return
957 void GSocket_SetNonBlocking(GSocket
*socket
, int non_block
)
959 assert(socket
!= NULL
);
961 socket
->m_non_blocking
= non_block
;
964 /* GSocket_SetTimeout:
965 * Sets the timeout for blocking calls. Time is expressed in
968 void GSocket_SetTimeout(GSocket
*socket
, unsigned long millisec
)
970 assert(socket
!= NULL
);
972 // this is usually set too high and we have not yet been able to detect a closed
973 // stream, thus we leave the 10 sec timeout
974 // socket->m_timeout = millisec;
978 * Returns the last error occured for this socket. Note that successful
979 * operations do not clear this back to GSOCK_NOERROR, so use it only
982 GSocketError
GSocket_GetError(GSocket
*socket
)
984 assert(socket
!= NULL
);
986 return socket
->m_error
;
992 * There is data to be read in the input buffer. If, after a read
993 * operation, there is still data available, the callback function will
996 * The socket is available for writing. That is, the next write call
997 * won't block. This event is generated only once, when the connection is
998 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
999 * when the output buffer empties again. This means that the app should
1000 * assume that it can write since the first OUTPUT event, and no more
1001 * OUTPUT events will be generated unless an error occurs.
1003 * Connection succesfully established, for client sockets, or incoming
1004 * client connection, for server sockets. Wait for this event (also watch
1005 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
1007 * The connection is lost (or a connection request failed); this could
1008 * be due to a failure, or due to the peer closing it gracefully.
1011 /* GSocket_SetCallback:
1012 * Enables the callbacks specified by 'flags'. Note that 'flags'
1013 * may be a combination of flags OR'ed toghether, so the same
1014 * callback function can be made to accept different events.
1015 * The callback function must have the following prototype:
1017 * void function(GSocket *socket, GSocketEvent event, char *cdata)
1019 void GSocket_SetCallback(GSocket
*socket
, GSocketEventFlags flags
,
1020 GSocketCallback callback
, char *cdata
)
1024 assert(socket
!= NULL
);
1026 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1028 if ((flags
& (1 << count
)) != 0)
1030 socket
->m_cbacks
[count
] = callback
;
1031 socket
->m_data
[count
] = cdata
;
1036 /* GSocket_UnsetCallback:
1037 * Disables all callbacks specified by 'flags', which may be a
1038 * combination of flags OR'ed toghether.
1040 void GSocket_UnsetCallback(GSocket
*socket
, GSocketEventFlags flags
)
1044 assert(socket
!= NULL
);
1046 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1048 if ((flags
& (1 << count
)) != 0)
1050 socket
->m_cbacks
[count
] = NULL
;
1051 socket
->m_data
[count
] = NULL
;
1057 #define CALL_CALLBACK(socket, event) { \
1058 _GSocket_Disable(socket, event); \
1059 if (socket->m_cbacks[event]) \
1060 socket->m_cbacks[event](socket, event, socket->m_data[event]); \
1063 int _GSocket_Recv_Stream(GSocket
*socket
, char *buffer
, int size
)
1067 OTByteCount sz
= 0 ;
1069 OTCountDataBytes( socket
->m_endpoint
, &sz
) ;
1072 res
= OTRcv( socket
->m_endpoint
, buffer
, size
, &flags
) ;
1078 // we simulate another read event if there are still bytes
1079 if ( socket
->m_takesEvents
)
1081 OTByteCount sz
= 0 ;
1082 OTCountDataBytes( socket
->m_endpoint
, &sz
) ;
1085 socket
->m_detected
|= GSOCK_INPUT_FLAG
;
1086 (socket
->m_cbacks
[GSOCK_INPUT
])(socket
, GSOCK_INPUT
, socket
->m_data
[GSOCK_INPUT
]);
1092 int _GSocket_Recv_Dgram(GSocket
*socket
, char *buffer
, int size
)
1097 struct sockaddr from
;
1098 SOCKLEN_T fromlen
= sizeof(from
);
1101 fromlen
= sizeof(from
);
1103 ret
= recvfrom(socket
->m_endpoint
, buffer
, size
, 0, &from
, (SOCKLEN_T
*) &fromlen
);
1108 /* Translate a system address into a GSocket address */
1109 if (!socket
->m_peer
)
1111 socket
->m_peer
= GAddress_new();
1112 if (!socket
->m_peer
)
1114 socket
->m_error
= GSOCK_MEMERR
;
1118 err
= _GAddress_translate_from(socket
->m_peer
, &from
, fromlen
);
1119 if (err
!= GSOCK_NOERROR
)
1121 GAddress_destroy(socket
->m_peer
);
1122 socket
->m_peer
= NULL
;
1123 socket
->m_error
= err
;
1130 int _GSocket_Send_Stream(GSocket
*socket
, const char *buffer
, int size
)
1135 res
= OTSnd( socket
->m_endpoint
, (void*) buffer
, size
, flags
) ;
1139 int _GSocket_Send_Dgram(GSocket
*socket
, const char *buffer
, int size
)
1144 struct sockaddr
*addr
;
1148 if (!socket
->m_peer
)
1150 socket
->m_error
= GSOCK_INVADDR
;
1154 err
= _GAddress_translate_to(socket
->m_peer
, &addr
, &len
);
1155 if (err
!= GSOCK_NOERROR
)
1157 socket
->m_error
= err
;
1161 ret
= sendto(socket
->m_endpoint
, buffer
, size
, 0, addr
, len
);
1163 /* Frees memory allocated from _GAddress_translate_to */
1171 * -------------------------------------------------------------------------
1173 * -------------------------------------------------------------------------
1176 /* CHECK_ADDRESS verifies that the current family is either GSOCK_NOFAMILY
1177 * or GSOCK_*family*, and if it is GSOCK_NOFAMILY, it initalizes address
1178 * to be a GSOCK_*family*. In other cases, it returns GSOCK_INVADDR.
1180 #define CHECK_ADDRESS(address, family, retval) \
1182 if (address->m_family == GSOCK_NOFAMILY) \
1183 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1184 return address->m_error; \
1185 if (address->m_family != GSOCK_##family) \
1187 address->m_error = GSOCK_INVADDR; \
1192 GAddress
*GAddress_new()
1196 if ((address
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1199 address
->m_family
= GSOCK_NOFAMILY
;
1200 address
->m_host
= INADDR_NONE
;
1201 address
->m_port
= 0 ;
1206 GAddress
*GAddress_copy(GAddress
*address
)
1210 assert(address
!= NULL
);
1212 if ((addr2
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1215 memcpy(addr2
, address
, sizeof(GAddress
));
1219 void GAddress_destroy(GAddress
*address
)
1221 assert(address
!= NULL
);
1226 void GAddress_SetFamily(GAddress
*address
, GAddressType type
)
1228 assert(address
!= NULL
);
1230 address
->m_family
= type
;
1233 GAddressType
GAddress_GetFamily(GAddress
*address
)
1235 assert(address
!= NULL
);
1237 return address
->m_family
;
1240 GSocketError
_GAddress_translate_from(GAddress
*address
,
1243 switch (addr
->fAddressType
)
1246 address
->m_family
= GSOCK_INET
;
1250 address
->m_family
= GSOCK_INET6
;
1255 address
->m_error
= GSOCK_INVOP
;
1259 address
->m_host
= addr
->fHost
;
1260 address
->m_port
= addr
->fPort
;
1261 return GSOCK_NOERROR
;
1264 GSocketError
_GAddress_translate_to(GAddress
*address
,
1267 if ( GSocket_Verify_Inited() == FALSE
)
1268 return GSOCK_IOERR
;
1269 memset(addr
, 0 , sizeof(struct InetAddress
));
1270 OTInitInetAddress( addr
, address
->m_port
, address
->m_host
) ;
1271 return GSOCK_NOERROR
;
1275 * -------------------------------------------------------------------------
1276 * Internet address family
1277 * -------------------------------------------------------------------------
1280 GSocketError
_GAddress_Init_INET(GAddress
*address
)
1282 address
->m_family
= GSOCK_INET
;
1283 address
->m_host
= kOTAnyInetAddress
;
1285 return GSOCK_NOERROR
;
1288 GSocketError
GAddress_INET_SetHostName(GAddress
*address
, const char *hostname
)
1290 InetHostInfo hinfo
;
1293 if ( GSocket_Verify_Inited() == FALSE
)
1294 return GSOCK_IOERR
;
1296 assert(address
!= NULL
);
1298 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1299 ret
= OTInetStringToAddress( gInetSvcRef
, (char*) hostname
, &hinfo
) ;
1300 if ( ret
!= kOTNoError
)
1302 address
->m_host
= INADDR_NONE
;
1303 address
->m_error
= GSOCK_NOHOST
;
1304 return GSOCK_NOHOST
;
1306 address
->m_host
= hinfo
.addrs
[0] ;
1307 return GSOCK_NOERROR
;
1310 GSocketError
GAddress_INET_SetAnyAddress(GAddress
*address
)
1312 return GAddress_INET_SetHostAddress(address
, INADDR_ANY
);
1315 GSocketError
GAddress_INET_SetHostAddress(GAddress
*address
,
1316 unsigned long hostaddr
)
1318 assert(address
!= NULL
);
1320 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1322 address
->m_host
= hostaddr
;
1324 return GSOCK_NOERROR
;
1327 struct service_entry
1330 unsigned short port
;
1333 typedef struct service_entry service_entry
;
1335 service_entry gServices
[] =
1337 { "http" , 80 , "tcp" }
1340 GSocketError
GAddress_INET_SetPortName(GAddress
*address
, const char *port
,
1341 const char *protocol
)
1345 assert(address
!= NULL
);
1346 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1350 address
->m_error
= GSOCK_INVPORT
;
1351 return GSOCK_INVPORT
;
1353 for ( i
= 0 ; i
< sizeof( gServices
) / sizeof( service_entry
) ; ++i
)
1355 if ( strcmp( port
, gServices
[i
].name
) == 0 )
1357 if ( protocol
== NULL
|| strcmp( protocol
, gServices
[i
].protocol
) )
1359 address
->m_port
= gServices
[i
].port
;
1360 return GSOCK_NOERROR
;
1365 if (isdigit(port
[0]))
1367 address
->m_port
= atoi(port
);
1368 return GSOCK_NOERROR
;
1371 address
->m_error
= GSOCK_INVPORT
;
1372 return GSOCK_INVPORT
;
1375 GSocketError
GAddress_INET_SetPort(GAddress
*address
, unsigned short port
)
1377 assert(address
!= NULL
);
1378 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1379 address
->m_port
= port
;
1381 return GSOCK_NOERROR
;
1384 GSocketError
GAddress_INET_GetHostName(GAddress
*address
, char *hostname
, size_t sbuf
)
1386 InetDomainName name
;
1387 if ( GSocket_Verify_Inited() == FALSE
)
1388 return GSOCK_IOERR
;
1390 assert(address
!= NULL
);
1391 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1393 OTInetAddressToName( gInetSvcRef
, address
->m_host
, name
) ;
1394 strncpy( hostname
, name
, sbuf
) ;
1395 return GSOCK_NOERROR
;
1398 unsigned long GAddress_INET_GetHostAddress(GAddress
*address
)
1400 assert(address
!= NULL
);
1401 CHECK_ADDRESS(address
, INET
, 0);
1403 return address
->m_host
;
1406 unsigned short GAddress_INET_GetPort(GAddress
*address
)
1408 assert(address
!= NULL
);
1409 CHECK_ADDRESS(address
, INET
, 0);
1411 return address
->m_port
;
1414 void _GSocket_Enable_Events(GSocket
*socket
)
1416 if ( socket
->m_takesEvents
)
1421 socket
->m_takesEvents
= TRUE
;
1422 state
= OTGetEndpointState(socket
->m_endpoint
);
1425 OTByteCount sz
= 0 ;
1426 OTCountDataBytes( socket
->m_endpoint
, &sz
) ;
1427 if ( state
== T_INCON
|| sz
> 0 )
1429 socket
->m_detected
|= GSOCK_INPUT_FLAG
;
1430 (socket
->m_cbacks
[GSOCK_INPUT
])(socket
, GSOCK_INPUT
, socket
->m_data
[GSOCK_INPUT
]);
1434 if ( state
== T_DATAXFER
|| state
== T_INREL
)
1436 socket
->m_detected
|=GSOCK_OUTPUT_FLAG
;
1437 (socket
->m_cbacks
[GSOCK_OUTPUT
])(socket
, GSOCK_OUTPUT
, socket
->m_data
[GSOCK_OUTPUT
]);
1443 void _GSocket_Disable_Events(GSocket
*socket
)
1445 socket
->m_takesEvents
= FALSE
;
1448 /* _GSocket_Input_Timeout:
1449 * For blocking sockets, wait until data is available or
1450 * until timeout ellapses.
1452 GSocketError
_GSocket_Input_Timeout(GSocket
*socket
)
1454 if ( !socket
->m_non_blocking
)
1456 UnsignedWide now
, start
;
1457 short formerTakesEvents
= socket
->m_takesEvents
;
1458 Microseconds(&start
);
1460 socket
->m_takesEvents
= FALSE
;
1462 while( (now
.hi
* 4294967296.0 + now
.lo
) - (start
.hi
* 4294967296.0 + start
.lo
) < socket
->m_timeout
* 1000.0 )
1465 OTByteCount sz
= 0 ;
1466 state
= OTGetEndpointState(socket
->m_endpoint
);
1468 OTCountDataBytes( socket
->m_endpoint
, &sz
) ;
1469 if ( state
== T_INCON
|| sz
> 0 )
1471 socket
->m_takesEvents
= formerTakesEvents
;
1472 return GSOCK_NOERROR
;
1476 socket
->m_takesEvents
= formerTakesEvents
;
1477 socket
->m_error
= GSOCK_TIMEDOUT
;
1478 return GSOCK_TIMEDOUT
;
1480 return GSOCK_NOERROR
;
1483 /* _GSocket_Output_Timeout:
1484 * For blocking sockets, wait until data can be sent without
1485 * blocking or until timeout ellapses.
1487 GSocketError
_GSocket_Output_Timeout(GSocket
*socket
)
1489 if ( !socket
->m_non_blocking
)
1491 UnsignedWide now
, start
;
1492 short formerTakesEvents
= socket
->m_takesEvents
;
1493 Microseconds(&start
);
1495 socket
->m_takesEvents
= FALSE
;
1497 while( (now
.hi
* 4294967296.0 + now
.lo
) - (start
.hi
* 4294967296.0 + start
.lo
) < socket
->m_timeout
* 1000.0 )
1500 state
= OTGetEndpointState(socket
->m_endpoint
);
1502 if ( state
== T_DATAXFER
|| state
== T_INREL
)
1504 socket
->m_takesEvents
= formerTakesEvents
;
1505 return GSOCK_NOERROR
;
1509 socket
->m_takesEvents
= formerTakesEvents
;
1510 socket
->m_error
= GSOCK_TIMEDOUT
;
1511 return GSOCK_TIMEDOUT
;
1513 return GSOCK_NOERROR
;
1517 * There is data to be read in the input buffer. If, after a read
1518 * operation, there is still data available, the callback function will
1521 * The socket is available for writing. That is, the next write call
1522 * won't block. This event is generated only once, when the connection is
1523 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
1524 * when the output buffer empties again. This means that the app should
1525 * assume that it can write since the first OUTPUT event, and no more
1526 * OUTPUT events will be generated unless an error occurs.
1528 * Connection succesfully established, for client sockets, or incoming
1529 * client connection, for server sockets. Wait for this event (also watch
1530 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
1532 * The connection is lost (or a connection request failed); this could
1533 * be due to a failure, or due to the peer closing it gracefully.
1536 void _GSocket_Internal_Proc(unsigned long e
, void* d
)
1539 GSocket
* socket
= (GSocket
*) d
;
1540 OTEventCode ev
= (OTEventCode
) e
;
1542 GSocketEvent event2
;
1543 GSocketCallback cback
;
1545 GSocketCallback cback2
;
1550 event
= GSOCK_MAX_EVENT
;
1551 event2
= GSOCK_MAX_EVENT
;
1557 /* Check that the socket still exists (it has not been
1558 * destroyed) and for safety, check that the m_endpoint field
1559 * is what we expect it to be.
1561 if ((socket
!= NULL
) && (socket
->m_takesEvents
))
1566 event
= GSOCK_CONNECTION
;
1569 event
= GSOCK_CONNECTION
;
1570 event2
= GSOCK_OUTPUT
;
1574 retCall
.addr
.buf
= NULL
;
1575 retCall
.addr
.maxlen
= 0;
1576 retCall
.opt
.buf
= NULL
;
1577 retCall
.opt
.maxlen
= 0;
1578 retCall
.udata
.buf
= NULL
;
1579 retCall
.udata
.maxlen
= 0;
1580 OTRcvConnect( socket
->m_endpoint
, &retCall
) ;
1584 event
= GSOCK_LOST
;
1588 event
= GSOCK_OUTPUT
;
1591 event
= GSOCK_INPUT
;
1594 event
= GSOCK_INPUT
;
1597 if (event
!= GSOCK_MAX_EVENT
)
1599 cback
= socket
->m_cbacks
[event
];
1600 data
= socket
->m_data
[event
];
1602 if (event
== GSOCK_LOST
)
1603 socket
->m_detected
= GSOCK_LOST_FLAG
;
1605 socket
->m_detected
|= (1 << event
);
1607 if (event2
!= GSOCK_MAX_EVENT
)
1609 cback2
= socket
->m_cbacks
[event2
];
1610 data2
= socket
->m_data
[event2
];
1612 if (event2
== GSOCK_LOST
)
1613 socket
->m_detected
= GSOCK_LOST_FLAG
;
1615 socket
->m_detected
|= (1 << event2
);
1619 /* OK, we can now leave the critical section because we have
1620 * already obtained the callback address (we make no further
1621 * accesses to socket->whatever). However, the app should
1622 * be prepared to handle events from a socket that has just
1627 (cback
)(socket
, event
, data
);
1629 (cback2
)(socket
, event2
, data2
);
1633 /* Hack added for Mac OS X */
1634 GSocketError
GAddress_UNIX_GetPath(GAddress
*addr
, char *path
, size_t buf
)
1636 return GSOCK_INVADDR
;
1639 GSocketError
GAddress_UNIX_SetPath(GAddress
*addr
, const char *path
)
1641 return GSOCK_INVADDR
;
1644 #endif /* wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__) */