1 /* -------------------------------------------------------------------------
2 * Project: GSocket (Generic Socket) for WX
4 * Authors: Guilhem Lavaux,
5 * Guillermo Rodriguez Garcia <guille@iies.es> (maintainer)
7 * Purpose: GSocket main mac file
9 * -------------------------------------------------------------------------
13 * PLEASE don't put C++ comments here - this is a C source file.
16 #ifndef __GSOCKET_STANDALONE__
20 #if wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__)
23 #include <CoreServices/CoreServices.h>
32 #define OTUNIXERRORS 1
33 #include <OpenTransport.h>
34 #include <OpenTransportProviders.h>
35 #include <OpenTptInternet.h>
38 #define OTAssert( str , cond ) /* does not exists in Carbon */
52 * INADDR_BROADCAST is identical to INADDR_NONE which is not defined
53 * on all unices. INADDR_BROADCAST should be fine to indicate an error.
55 #ifndef INADDR_BROADCAST
56 #define INADDR_BROADCAST 0xFFFFFFFFUL
59 #define INADDR_NONE INADDR_BROADCAST
62 #define INADDR_ANY 0x0UL
64 #ifndef __GSOCKET_STANDALONE__
66 #include "wx/mac/macnotfy.h"
67 #include "wx/mac/gsockmac.h"
68 #include "wx/gsocket.h"
75 #endif /* __GSOCKET_STANDALONE__ */
81 extern pascal void OTDebugStr(const char* str
);
86 InetSvcRef gInetSvcRef
= 0 ;
89 OSStatus
DoNegotiateIPReuseAddrOption(EndpointRef ep
, Boolean enableReuseIPMode
);
91 /* Input: ep - endpointref on which to negotiate the option
92 enableReuseIPMode - desired option setting - true/false
93 Return: kOTNoError indicates that the option was successfully negotiated
94 OSStatus is an error if < 0, otherwise, the status field is
97 IMPORTANT NOTE: The endpoint is assumed to be in synchronous more, otherwise
98 this code will not function as desired
102 OSStatus
DoNegotiateIPReuseAddrOption(EndpointRef ep
, Boolean enableReuseIPMode
)
105 UInt8 buf
[kOTFourByteOptionSize
]; // define buffer for fourByte Option size
106 TOption
* opt
; // option ptr to make items easier to access
111 if (!OTIsSynchronous(ep
))
115 opt
= (TOption
*)buf
; // set option ptr to buffer
117 req
.opt
.len
= sizeof(buf
);
118 req
.flags
= T_NEGOTIATE
; // negotiate for option
121 ret
.opt
.maxlen
= kOTFourByteOptionSize
;
123 opt
->level
= INET_IP
; // dealing with an IP Level function
125 opt
->name
= kIP_REUSEADDR
;
127 opt
->name
= IP_REUSEADDR
;
129 opt
->len
= kOTFourByteOptionSize
;
131 *(UInt32
*)opt
->value
= enableReuseIPMode
; // set the desired option level, true or false
133 err
= OTOptionManagement(ep
, &req
, &ret
);
135 // if no error then return the option status value
136 if (err
== kOTNoError
)
138 if (opt
->status
!= T_SUCCESS
)
148 pascal void OTInetEventHandler(void*s
, OTEventCode event
, OTResult
, void *cookie
) ;
149 pascal void OTInetEventHandler(void*s
, OTEventCode event
, OTResult result
, void *cookie
)
152 GSocket
* sock
= (GSocket
*) s
;
154 if ( event
== kOTSyncIdleEvent
)
162 wxMacAddEvent( sock
->m_mac_events
, _GSocket_Internal_Proc
, event
, s
, wakeUp
) ;
168 static void SetDefaultEndpointModes(EndpointRef ep
, void *data
)
169 // This routine sets the supplied endpoint into the default
170 // mode used in this application. The specifics are:
171 // blocking, synchronous, and using synch idle events with
172 // the standard YieldingNotifier.
174 OSStatus junk
= kOTNoError
;
175 OTAssert ("SetDefaultEndpointModes:invalid ref", ep
!= kOTInvalidEndpointRef
) ;
176 junk
= OTSetAsynchronous(ep
);
177 OTAssert("SetDefaultEndpointModes: Could not set asynchronous", junk
== noErr
);
179 junk = OTSetBlocking(ep);
180 OTAssert("SetDefaultEndpointModes: Could not set blocking", junk == noErr);
181 junk = OTSetSynchronous(ep);
182 OTAssert("SetDefaultEndpointModes: Could not set synchronous", junk == noErr);
183 junk = OTSetBlocking(ep);
184 OTAssert("SetDefaultEndpointModes: Could not set blocking", junk == noErr);
186 junk
= OTInstallNotifier(ep
, OTInetEventHandler
, data
);
187 OTAssert("SetDefaultEndpointModes: Could not install notifier", junk
== noErr
);
189 junk = OTUseSyncIdleEvents(ep, true);
190 OTAssert("SetDefaultEndpointModes: Could not use sync idle events", junk == noErr);
194 /* Global initialisers */
200 InitOpenTransportInContext( kInitOTForApplicationMask
, NULL
) ;
202 InitOpenTransport() ;
204 gInetSvcRef
= OTOpenInternetServices(kDefaultInternetServicesPath
, NULL
, &err
);
205 if ( gInetSvcRef
== NULL
|| err
!= kOTNoError
)
207 OTAssert("Could not open Inet Services", err
== noErr
);
213 void GSocket_Cleanup()
215 if ( gInetSvcRef
!= NULL
)
216 OTCloseProvider( gInetSvcRef
);
218 CloseOpenTransportInContext( NULL
) ;
220 CloseOpenTransport() ;
224 /* Constructors / Destructors for GSocket */
226 GSocket
*GSocket_new()
231 socket
= (GSocket
*)malloc(sizeof(GSocket
));
236 socket
->m_endpoint
= NULL
;
237 for (i
=0;i
<GSOCK_MAX_EVENT
;i
++)
239 socket
->m_cbacks
[i
] = NULL
;
241 socket
->m_detected
= 0;
242 socket
->m_local
= NULL
;
243 socket
->m_peer
= NULL
;
244 socket
->m_error
= GSOCK_NOERROR
;
245 socket
->m_server
= FALSE
;
246 socket
->m_stream
= TRUE
;
247 socket
->m_non_blocking
= FALSE
;
248 socket
->m_timeout
= 10*60*1000;
249 /* 10 minutes * 60 sec * 1000 millisec */
250 socket
->m_takesEvents
= TRUE
;
251 socket
->m_mac_events
= wxMacGetNotifierTable() ;
255 void GSocket_destroy(GSocket
*socket
)
257 assert(socket
!= NULL
);
259 /* Check that the socket is really shutdowned */
260 if (socket
->m_endpoint
!= kOTInvalidEndpointRef
)
261 GSocket_Shutdown(socket
);
264 /* Destroy private addresses */
266 GAddress_destroy(socket
->m_local
);
269 GAddress_destroy(socket
->m_peer
);
271 /* Destroy the socket itself */
276 * Disallow further read/write operations on this socket, close
277 * the fd and disable all callbacks.
279 void GSocket_Shutdown(GSocket
*socket
)
284 assert(socket
!= NULL
);
286 /* If socket has been created, shutdown it */
287 if (socket
->m_endpoint
!= kOTInvalidEndpointRef
)
289 err
= OTSndOrderlyDisconnect( socket
->m_endpoint
) ;
290 if ( err
!= kOTNoError
)
294 err
= OTRcvOrderlyDisconnect( socket
->m_endpoint
) ;
295 err
= OTUnbind( socket
->m_endpoint
) ;
296 err
= OTCloseProvider( socket
->m_endpoint
) ;
297 socket
->m_endpoint
= kOTInvalidEndpointRef
;
300 /* Disable GUI callbacks */
301 for (evt
= 0; evt
< GSOCK_MAX_EVENT
; evt
++)
302 socket
->m_cbacks
[evt
] = NULL
;
304 socket
->m_detected
= 0;
305 _GSocket_Disable_Events(socket
);
306 wxMacRemoveAllNotifiersForData( wxMacGetNotifierTable() , socket
) ;
310 /* Address handling */
316 * Set or get the local or peer address for this socket. The 'set'
317 * functions return GSOCK_NOERROR on success, an error code otherwise.
318 * The 'get' functions return a pointer to a GAddress object on success,
319 * or NULL otherwise, in which case they set the error code of the
320 * corresponding GSocket.
323 * GSOCK_INVSOCK - the socket is not valid.
324 * GSOCK_INVADDR - the address is not valid.
326 GSocketError
GSocket_SetLocal(GSocket
*socket
, GAddress
*address
)
328 assert(socket
!= NULL
);
330 /* the socket must be initialized, or it must be a server */
331 if ((socket
->m_endpoint
!= kOTInvalidEndpointRef
&& !socket
->m_server
))
333 socket
->m_error
= GSOCK_INVSOCK
;
334 return GSOCK_INVSOCK
;
338 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
340 socket
->m_error
= GSOCK_INVADDR
;
341 return GSOCK_INVADDR
;
345 GAddress_destroy(socket
->m_local
);
347 socket
->m_local
= GAddress_copy(address
);
349 return GSOCK_NOERROR
;
352 GSocketError
GSocket_SetPeer(GSocket
*socket
, GAddress
*address
)
354 assert(socket
!= NULL
);
357 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
359 socket
->m_error
= GSOCK_INVADDR
;
360 return GSOCK_INVADDR
;
364 GAddress_destroy(socket
->m_peer
);
366 socket
->m_peer
= GAddress_copy(address
);
368 return GSOCK_NOERROR
;
371 GAddress
*GSocket_GetLocal(GSocket
*socket
)
373 GAddress
*address
= NULL
;
377 assert(socket
!= NULL
);
379 /* try to get it from the m_local var first */
381 return GAddress_copy(socket
->m_local
);
383 /* else, if the socket is initialized, try getsockname */
384 if (socket
->m_endpoint
== kOTInvalidEndpointRef
)
386 socket
->m_error
= GSOCK_INVSOCK
;
391 /* we do not support multihoming with this code at the moment
392 OTGetProtAddress will have to be used then - but we don't have a handy
393 method to use right now
396 InetInterfaceInfo info
;
397 OTInetGetInterfaceInfo(&info
, kDefaultInetInterface
);
398 loc
.fHost
= info
.fAddress
;
400 loc
.fAddressType
= AF_INET
;
403 /* got a valid address from getsockname, create a GAddress object */
404 address
= GAddress_new();
407 socket
->m_error
= GSOCK_MEMERR
;
411 err
= _GAddress_translate_from(address
, &loc
);
412 if (err
!= GSOCK_NOERROR
)
414 GAddress_destroy(address
);
415 socket
->m_error
= err
;
422 GAddress
*GSocket_GetPeer(GSocket
*socket
)
424 assert(socket
!= NULL
);
426 /* try to get it from the m_peer var */
428 return GAddress_copy(socket
->m_peer
);
433 /* Server specific parts */
435 /* GSocket_SetServer:
436 * Sets up this socket as a server. The local address must have been
437 * set with GSocket_SetLocal() before GSocket_SetServer() is called.
438 * Returns GSOCK_NOERROR on success, one of the following otherwise:
441 * GSOCK_INVSOCK - the socket is in use.
442 * GSOCK_INVADDR - the local address has not been set.
443 * GSOCK_IOERR - low-level error.
445 GSocketError
GSocket_SetServer(GSocket
*sck
)
452 /* must not be in use */
453 if (sck
->m_endpoint
!= kOTInvalidEndpointRef
)
455 sck
->m_error
= GSOCK_INVSOCK
;
456 return GSOCK_INVSOCK
;
459 /* the local addr must have been set */
462 sck
->m_error
= GSOCK_INVADDR
;
463 return GSOCK_INVADDR
;
466 /* Initialize all fields */
467 sck
->m_stream
= TRUE
;
468 sck
->m_server
= TRUE
;
469 sck
->m_oriented
= TRUE
;
473 /* Create the socket */
474 sck
->m_endpoint
= socket(sck
->m_local
->m_realfamily
, SOCK_STREAM
, 0);
475 socket_set_ref( sck
->m_endpoint
, (unsigned long) &gMacNetEvents
, (unsigned long) sck
) ;
476 if (sck
->m_endpoint
== kOTInvalidEndpointRef
)
478 sck
->m_error
= GSOCK_IOERR
;
482 ioctl(sck
->m_endpoint
, FIONBIO
, &arg
);
483 _GSocket_Enable_Events(sck
);
485 /* Bind to the local address,
486 * retrieve the actual address bound,
487 * and listen up to 5 connections.
489 if ((bind(sck
->m_endpoint
, sck
->m_local
->m_addr
, sck
->m_local
->m_len
) != 0) ||
490 (getsockname(sck
->m_endpoint
,
491 sck
->m_local
->m_addr
,
492 (SOCKLEN_T
*) &sck
->m_local
->m_len
) != 0) ||
493 (listen(sck
->m_endpoint
, 5) != 0))
495 close(sck
->m_endpoint
);
496 sck
->m_endpoint
= -1;
497 sck
->m_error
= GSOCK_IOERR
;
501 return GSOCK_NOERROR
;
504 /* GSocket_WaitConnection:
505 * Waits for an incoming client connection. Returns a pointer to
506 * a GSocket object, or NULL if there was an error, in which case
507 * the last error field will be updated for the calling GSocket.
509 * Error codes (set in the calling GSocket)
510 * GSOCK_INVSOCK - the socket is not valid or not a server.
511 * GSOCK_TIMEDOUT - timeout, no incoming connections.
512 * GSOCK_WOULDBLOCK - the call would block and the socket is nonblocking.
513 * GSOCK_MEMERR - couldn't allocate memory.
514 * GSOCK_IOERR - low-level error.
516 GSocket
*GSocket_WaitConnection(GSocket
*socket
)
518 GSocket
*connection
= NULL
;
523 assert(socket
!= NULL
);
525 /* Reenable CONNECTION events */
526 socket
->m_detected
&= ~GSOCK_CONNECTION_FLAG
;
528 /* If the socket has already been created, we exit immediately */
529 if (socket
->m_endpoint
== kOTInvalidEndpointRef
|| !socket
->m_server
)
531 socket
->m_error
= GSOCK_INVSOCK
;
535 /* Create a GSocket object for the new connection */
536 connection
= GSocket_new();
540 socket
->m_error
= GSOCK_MEMERR
;
544 /* Wait for a connection (with timeout) */
545 if (_GSocket_Input_Timeout(socket
) == GSOCK_TIMEDOUT
)
547 GSocket_destroy(connection
);
548 /* socket->m_error set by _GSocket_Input_Timeout */
554 connection
->m_endpoint
= accept(socket
->m_endpoint
, &from
, (SOCKLEN_T
*) &fromlen
);
557 if (connection
->m_endpoint
== kOTInvalidEndpointRef
)
559 if (errno
== EWOULDBLOCK
)
560 socket
->m_error
= GSOCK_WOULDBLOCK
;
562 socket
->m_error
= GSOCK_IOERR
;
564 GSocket_destroy(connection
);
568 /* Initialize all fields */
569 connection
->m_server
= FALSE
;
570 connection
->m_stream
= TRUE
;
571 connection
->m_oriented
= TRUE
;
573 /* Setup the peer address field */
574 connection
->m_peer
= GAddress_new();
575 if (!connection
->m_peer
)
577 GSocket_destroy(connection
);
578 socket
->m_error
= GSOCK_MEMERR
;
583 err
= _GAddress_translate_from(connection
->m_peer
, &from
, fromlen
);
584 if (err
!= GSOCK_NOERROR
)
586 GAddress_destroy(connection
->m_peer
);
587 GSocket_destroy(connection
);
588 socket
->m_error
= err
;
592 ioctl(connection
->m_endpoint
, FIONBIO
, &arg
);
594 _GSocket_Enable_Events(connection
);
599 /* Datagram sockets */
601 /* GSocket_SetNonOriented:
602 * Sets up this socket as a non-connection oriented (datagram) socket.
603 * Before using this function, the local address must have been set
604 * with GSocket_SetLocal(), or the call will fail. Returns GSOCK_NOERROR
605 * on success, or one of the following otherwise.
608 * GSOCK_INVSOCK - the socket is in use.
609 * GSOCK_INVADDR - the local address has not been set.
610 * GSOCK_IOERR - low-level error.
612 GSocketError
GSocket_SetNonOriented(GSocket
*sck
)
618 if (sck
->m_endpoint
!= kOTInvalidEndpointRef
)
620 sck
->m_error
= GSOCK_INVSOCK
;
621 return GSOCK_INVSOCK
;
626 sck
->m_error
= GSOCK_INVADDR
;
627 return GSOCK_INVADDR
;
630 /* Initialize all fields */
631 sck
->m_stream
= FALSE
;
632 sck
->m_server
= FALSE
;
633 sck
->m_oriented
= FALSE
;
635 /* Create the socket */
639 sck
->m_endpoint
= socket(sck
->m_local
->m_realfamily
, SOCK_DGRAM
, 0);
640 socket_set_ref( sck
->m_endpoint
, (unsigned long) &gMacNetEvents
, (unsigned long) sck
) ;
642 if (sck
->m_endpoint
== kOTInvalidEndpointRef
)
644 sck
->m_error
= GSOCK_IOERR
;
650 ioctl(sck
->m_endpoint
, FIONBIO
, &arg
);
652 _GSocket_Enable_Events(sck
);
654 /* Bind to the local address,
655 * and retrieve the actual address bound.
659 if ((bind(sck
->m_endpoint
, sck
->m_local
->m_addr
, sck
->m_local
->m_len
) != 0) ||
660 (getsockname(sck
->m_endpoint
,
661 sck
->m_local
->m_addr
,
662 (SOCKLEN_T
*) &sck
->m_local
->m_len
) != 0))
664 close(sck
->m_endpoint
);
665 sck
->m_endpoint
= -1;
666 sck
->m_error
= GSOCK_IOERR
;
670 return GSOCK_NOERROR
;
673 /* Client specific parts */
676 * For stream (connection oriented) sockets, GSocket_Connect() tries
677 * to establish a client connection to a server using the peer address
678 * as established with GSocket_SetPeer(). Returns GSOCK_NOERROR if the
679 * connection has been succesfully established, or one of the error
680 * codes listed below. Note that for nonblocking sockets, a return
681 * value of GSOCK_WOULDBLOCK doesn't mean a failure. The connection
682 * request can be completed later; you should use GSocket_Select()
683 * to poll for GSOCK_CONNECTION | GSOCK_LOST, or wait for the
684 * corresponding asynchronous events.
686 * For datagram (non connection oriented) sockets, GSocket_Connect()
687 * just sets the peer address established with GSocket_SetPeer() as
688 * default destination.
691 * GSOCK_INVSOCK - the socket is in use or not valid.
692 * GSOCK_INVADDR - the peer address has not been established.
693 * GSOCK_TIMEDOUT - timeout, the connection failed.
694 * GSOCK_WOULDBLOCK - connection in progress (nonblocking sockets only)
695 * GSOCK_MEMERR - couldn't allocate memory.
696 * GSOCK_IOERR - low-level error.
698 GSocketError
GSocket_Connect(GSocket
*sck
, GSocketStream stream
)
705 OSStatus err
= kOTNoError
;
710 /* Enable CONNECTION events (needed for nonblocking connections) */
711 sck
->m_detected
&= ~GSOCK_CONNECTION_FLAG
;
713 if (sck
->m_endpoint
!= kOTInvalidEndpointRef
)
715 sck
->m_error
= GSOCK_INVSOCK
;
716 return GSOCK_INVSOCK
;
721 sck
->m_error
= GSOCK_INVADDR
;
722 return GSOCK_INVADDR
;
725 /* Streamed or dgram socket? */
726 sck
->m_stream
= (stream
== GSOCK_STREAMED
);
727 sck
->m_oriented
= TRUE
;
728 sck
->m_server
= FALSE
;
730 /* Create the socket */
733 OTOpenEndpointInContext( OTCreateConfiguration( kTCPName
) , 0 , &info
, &err
, NULL
) ;
736 OTOpenEndpoint( OTCreateConfiguration( kTCPName
) , 0 , &info
, &err
) ;
738 if ( sck
->m_endpoint
== kOTInvalidEndpointRef
|| err
!= kOTNoError
)
740 sck
->m_endpoint
= kOTInvalidEndpointRef
;
741 sck
->m_error
= GSOCK_IOERR
;
744 err
= OTBind( sck
->m_endpoint
, nil
, nil
) ;
745 if ( err
!= kOTNoError
)
749 SetDefaultEndpointModes( sck
->m_endpoint
, sck
) ;
752 ioctl(sck
->m_endpoint
, FIONBIO
, &arg
);
754 _GSocket_Enable_Events(sck
);
756 _GAddress_translate_to( sck
->m_peer
, &addr
) ;
757 memset( &peer
, 0 , sizeof( TCall
) ) ;
758 peer
.addr
.len
= sizeof( InetAddress
) ;
759 peer
.addr
.buf
= (unsigned char*) &addr
;
760 err
= OTConnect( sck
->m_endpoint
, &peer
, nil
) ;
763 /* If connect failed with EINPROGRESS and the GSocket object
764 * is in blocking mode, we select() for the specified timeout
765 * checking for writability to see if the connection request
769 if ((err
== kOTNoDataErr
) && (!sck
->m_non_blocking
))
771 if (_GSocket_Output_Timeout(sck
) == GSOCK_TIMEDOUT
)
773 OTSndOrderlyDisconnect( sck
->m_endpoint
) ;
774 sck
->m_endpoint
= kOTInvalidEndpointRef
;
775 /* sck->m_error is set in _GSocket_Output_Timeout */
776 return GSOCK_TIMEDOUT
;
782 SOCKLEN_T len = sizeof(error);
784 getsockopt(sck->m_endpoint, SOL_SOCKET, SO_ERROR, (void*) &error, &len);
788 return GSOCK_NOERROR
;
792 /* If connect failed with EINPROGRESS and the GSocket object
793 * is set to nonblocking, we set m_error to GSOCK_WOULDBLOCK
794 * (and return GSOCK_WOULDBLOCK) but we don't close the socket;
795 * this way if the connection completes, a GSOCK_CONNECTION
796 * event will be generated, if enabled.
798 if ((err
== kOTNoDataErr
) && (sck
->m_non_blocking
))
800 sck
->m_error
= GSOCK_WOULDBLOCK
;
801 return GSOCK_WOULDBLOCK
;
804 /* If connect failed with an error other than EINPROGRESS,
805 * then the call to GSocket_Connect has failed.
807 OTSndOrderlyDisconnect( sck
->m_endpoint
) ;
809 sck
->m_endpoint
= kOTInvalidEndpointRef
;
810 sck
->m_error
= GSOCK_IOERR
;
813 // OTInetEventHandler(sck, T_CONNECT , kOTNoError , NULL ) ;
814 return GSOCK_NOERROR
;
819 /* Like recv(), send(), ... */
820 int GSocket_Read(GSocket
*socket
, char *buffer
, int size
)
824 assert(socket
!= NULL
);
826 /* Reenable INPUT events */
827 socket
->m_detected
&= ~GSOCK_INPUT_FLAG
;
829 if (socket
->m_endpoint
== kOTInvalidEndpointRef
|| socket
->m_server
)
831 socket
->m_error
= GSOCK_INVSOCK
;
835 /* If the socket is blocking, wait for data (with a timeout) */
836 if (_GSocket_Input_Timeout(socket
) == GSOCK_TIMEDOUT
)
840 if (socket
->m_stream
)
841 ret
= _GSocket_Recv_Stream(socket
, buffer
, size
);
843 ret
= _GSocket_Recv_Dgram(socket
, buffer
, size
);
847 if (errno
== EWOULDBLOCK
)
848 socket
->m_error
= GSOCK_WOULDBLOCK
;
850 socket
->m_error
= GSOCK_IOERR
;
856 int GSocket_Write(GSocket
*socket
, const char *buffer
, int size
)
860 assert(socket
!= NULL
);
862 if (socket
->m_endpoint
== kOTInvalidEndpointRef
|| socket
->m_server
)
864 socket
->m_error
= GSOCK_INVSOCK
;
868 /* If the socket is blocking, wait for writability (with a timeout) */
869 if (_GSocket_Output_Timeout(socket
) == GSOCK_TIMEDOUT
)
873 if (socket
->m_stream
)
874 ret
= _GSocket_Send_Stream(socket
, buffer
, size
);
876 ret
= _GSocket_Send_Dgram(socket
, buffer
, size
);
880 if (errno
== EWOULDBLOCK
)
881 socket
->m_error
= GSOCK_WOULDBLOCK
;
883 socket
->m_error
= GSOCK_IOERR
;
885 /* Only reenable OUTPUT events after an error (just like WSAAsyncSelect
886 * in MSW). Once the first OUTPUT event is received, users can assume
887 * that the socket is writable until a read operation fails. Only then
888 * will further OUTPUT events be posted.
890 socket
->m_detected
&= ~GSOCK_OUTPUT_FLAG
;
898 * Polls the socket to determine its status. This function will
899 * check for the events specified in the 'flags' parameter, and
900 * it will return a mask indicating which operations can be
901 * performed. This function won't block, regardless of the
902 * mode (blocking | nonblocking) of the socket.
904 GSocketEventFlags
GSocket_Select(GSocket
*socket
, GSocketEventFlags flags
)
907 assert(socket
!= NULL
);
908 wxMacProcessNotifierEvents() ;
910 state = OTGetEndpointState(socket->m_endpoint);
912 if ( ( flags & GSOCK_INPUT_FLAG ) && ! ( socket->m_detected & GSOCK_INPUT_FLAG ) )
915 OTCountDataBytes( socket->m_endpoint , &sz ) ;
916 if ( state == T_INCON || sz > 0 )
918 socket->m_detected |= GSOCK_INPUT_FLAG ;
919 (socket->m_cbacks[GSOCK_INPUT])(socket, GSOCK_INPUT, socket->m_data[GSOCK_INPUT]);
922 if ( ( flags & GSOCK_INPUT_FLAG ) && ! ( socket->m_detected & GSOCK_OUTPUT_FLAG ) )
924 if ( state == T_DATAXFER || state == T_INREL )
926 socket->m_detected |=GSOCK_OUTPUT_FLAG ;
927 (socket->m_cbacks[GSOCK_OUTPUT])(socket, GSOCK_OUTPUT, socket->m_data[GSOCK_OUTPUT]);
931 return ( flags
& socket
->m_detected
) ;
936 /* GSocket_SetNonBlocking:
937 * Sets the socket to non-blocking mode. All IO calls will return
940 void GSocket_SetNonBlocking(GSocket
*socket
, int non_block
)
942 assert(socket
!= NULL
);
944 socket
->m_non_blocking
= non_block
;
947 /* GSocket_SetTimeout:
948 * Sets the timeout for blocking calls. Time is expressed in
951 void GSocket_SetTimeout(GSocket
*socket
, unsigned long millisec
)
953 assert(socket
!= NULL
);
955 socket
->m_timeout
= millisec
;
959 * Returns the last error occured for this socket. Note that successful
960 * operations do not clear this back to GSOCK_NOERROR, so use it only
963 GSocketError
GSocket_GetError(GSocket
*socket
)
965 assert(socket
!= NULL
);
967 return socket
->m_error
;
973 * There is data to be read in the input buffer. If, after a read
974 * operation, there is still data available, the callback function will
977 * The socket is available for writing. That is, the next write call
978 * won't block. This event is generated only once, when the connection is
979 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
980 * when the output buffer empties again. This means that the app should
981 * assume that it can write since the first OUTPUT event, and no more
982 * OUTPUT events will be generated unless an error occurs.
984 * Connection succesfully established, for client sockets, or incoming
985 * client connection, for server sockets. Wait for this event (also watch
986 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
988 * The connection is lost (or a connection request failed); this could
989 * be due to a failure, or due to the peer closing it gracefully.
992 /* GSocket_SetCallback:
993 * Enables the callbacks specified by 'flags'. Note that 'flags'
994 * may be a combination of flags OR'ed toghether, so the same
995 * callback function can be made to accept different events.
996 * The callback function must have the following prototype:
998 * void function(GSocket *socket, GSocketEvent event, char *cdata)
1000 void GSocket_SetCallback(GSocket
*socket
, GSocketEventFlags flags
,
1001 GSocketCallback callback
, char *cdata
)
1005 assert(socket
!= NULL
);
1007 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1009 if ((flags
& (1 << count
)) != 0)
1011 socket
->m_cbacks
[count
] = callback
;
1012 socket
->m_data
[count
] = cdata
;
1017 /* GSocket_UnsetCallback:
1018 * Disables all callbacks specified by 'flags', which may be a
1019 * combination of flags OR'ed toghether.
1021 void GSocket_UnsetCallback(GSocket
*socket
, GSocketEventFlags flags
)
1025 assert(socket
!= NULL
);
1027 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1029 if ((flags
& (1 << count
)) != 0)
1031 socket
->m_cbacks
[count
] = NULL
;
1032 socket
->m_data
[count
] = NULL
;
1038 #define CALL_CALLBACK(socket, event) { \
1039 _GSocket_Disable(socket, event); \
1040 if (socket->m_cbacks[event]) \
1041 socket->m_cbacks[event](socket, event, socket->m_data[event]); \
1044 int _GSocket_Recv_Stream(GSocket
*socket
, char *buffer
, int size
)
1048 OTByteCount sz
= 0 ;
1050 OTCountDataBytes( socket
->m_endpoint
, &sz
) ;
1051 res
= OTRcv( socket
->m_endpoint
, buffer
, size
, &flags
) ;
1057 // we simulate another read event if there are still bytes
1058 if ( socket
->m_takesEvents
)
1060 OTByteCount sz
= 0 ;
1061 OTCountDataBytes( socket
->m_endpoint
, &sz
) ;
1064 socket
->m_detected
|= GSOCK_INPUT_FLAG
;
1065 (socket
->m_cbacks
[GSOCK_INPUT
])(socket
, GSOCK_INPUT
, socket
->m_data
[GSOCK_INPUT
]);
1071 int _GSocket_Recv_Dgram(GSocket
*socket
, char *buffer
, int size
)
1076 struct sockaddr from
;
1077 SOCKLEN_T fromlen
= sizeof(from
);
1080 fromlen
= sizeof(from
);
1082 ret
= recvfrom(socket
->m_endpoint
, buffer
, size
, 0, &from
, (SOCKLEN_T
*) &fromlen
);
1087 /* Translate a system address into a GSocket address */
1088 if (!socket
->m_peer
)
1090 socket
->m_peer
= GAddress_new();
1091 if (!socket
->m_peer
)
1093 socket
->m_error
= GSOCK_MEMERR
;
1097 err
= _GAddress_translate_from(socket
->m_peer
, &from
, fromlen
);
1098 if (err
!= GSOCK_NOERROR
)
1100 GAddress_destroy(socket
->m_peer
);
1101 socket
->m_peer
= NULL
;
1102 socket
->m_error
= err
;
1109 int _GSocket_Send_Stream(GSocket
*socket
, const char *buffer
, int size
)
1114 res
= OTSnd( socket
->m_endpoint
, (void*) buffer
, size
, flags
) ;
1118 int _GSocket_Send_Dgram(GSocket
*socket
, const char *buffer
, int size
)
1123 struct sockaddr
*addr
;
1127 if (!socket
->m_peer
)
1129 socket
->m_error
= GSOCK_INVADDR
;
1133 err
= _GAddress_translate_to(socket
->m_peer
, &addr
, &len
);
1134 if (err
!= GSOCK_NOERROR
)
1136 socket
->m_error
= err
;
1140 ret
= sendto(socket
->m_endpoint
, buffer
, size
, 0, addr
, len
);
1142 /* Frees memory allocated from _GAddress_translate_to */
1150 * -------------------------------------------------------------------------
1152 * -------------------------------------------------------------------------
1155 /* CHECK_ADDRESS verifies that the current family is either GSOCK_NOFAMILY
1156 * or GSOCK_*family*, and if it is GSOCK_NOFAMILY, it initalizes address
1157 * to be a GSOCK_*family*. In other cases, it returns GSOCK_INVADDR.
1159 #define CHECK_ADDRESS(address, family, retval) \
1161 if (address->m_family == GSOCK_NOFAMILY) \
1162 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1163 return address->m_error; \
1164 if (address->m_family != GSOCK_##family) \
1166 address->m_error = GSOCK_INVADDR; \
1171 GAddress
*GAddress_new()
1175 if ((address
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1178 address
->m_family
= GSOCK_NOFAMILY
;
1179 address
->m_host
= INADDR_NONE
;
1180 address
->m_port
= 0 ;
1185 GAddress
*GAddress_copy(GAddress
*address
)
1189 assert(address
!= NULL
);
1191 if ((addr2
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1194 memcpy(addr2
, address
, sizeof(GAddress
));
1198 void GAddress_destroy(GAddress
*address
)
1200 assert(address
!= NULL
);
1205 void GAddress_SetFamily(GAddress
*address
, GAddressType type
)
1207 assert(address
!= NULL
);
1209 address
->m_family
= type
;
1212 GAddressType
GAddress_GetFamily(GAddress
*address
)
1214 assert(address
!= NULL
);
1216 return address
->m_family
;
1219 GSocketError
_GAddress_translate_from(GAddress
*address
,
1222 switch (addr
->fAddressType
)
1225 address
->m_family
= GSOCK_INET
;
1229 address
->m_family
= GSOCK_INET6
;
1234 address
->m_error
= GSOCK_INVOP
;
1238 address
->m_host
= addr
->fHost
;
1239 address
->m_port
= addr
->fPort
;
1240 return GSOCK_NOERROR
;
1243 GSocketError
_GAddress_translate_to(GAddress
*address
,
1246 memset(addr
, 0 , sizeof(struct InetAddress
));
1247 OTInitInetAddress( addr
, address
->m_port
, address
->m_host
) ;
1248 return GSOCK_NOERROR
;
1252 * -------------------------------------------------------------------------
1253 * Internet address family
1254 * -------------------------------------------------------------------------
1257 GSocketError
_GAddress_Init_INET(GAddress
*address
)
1259 address
->m_family
= GSOCK_INET
;
1260 address
->m_host
= kOTAnyInetAddress
;
1262 return GSOCK_NOERROR
;
1265 GSocketError
GAddress_INET_SetHostName(GAddress
*address
, const char *hostname
)
1267 InetHostInfo hinfo
;
1270 assert(address
!= NULL
);
1272 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1273 ret
= OTInetStringToAddress( gInetSvcRef
, (char*) hostname
, &hinfo
) ;
1274 if ( ret
!= kOTNoError
)
1276 address
->m_host
= INADDR_NONE
;
1277 address
->m_error
= GSOCK_NOHOST
;
1278 return GSOCK_NOHOST
;
1280 address
->m_host
= hinfo
.addrs
[0] ;
1281 return GSOCK_NOERROR
;
1284 GSocketError
GAddress_INET_SetAnyAddress(GAddress
*address
)
1286 return GAddress_INET_SetHostAddress(address
, INADDR_ANY
);
1289 GSocketError
GAddress_INET_SetHostAddress(GAddress
*address
,
1290 unsigned long hostaddr
)
1292 struct in_addr
*addr
;
1294 assert(address
!= NULL
);
1296 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1298 address
->m_host
= hostaddr
;
1300 return GSOCK_NOERROR
;
1303 struct service_entry
1306 unsigned short port
;
1309 typedef struct service_entry service_entry
;
1311 service_entry gServices
[] =
1313 { "http" , 80 , "tcp" }
1316 GSocketError
GAddress_INET_SetPortName(GAddress
*address
, const char *port
,
1317 const char *protocol
)
1322 assert(address
!= NULL
);
1323 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1327 address
->m_error
= GSOCK_INVPORT
;
1328 return GSOCK_INVPORT
;
1330 for ( i
= 0 ; i
< sizeof( gServices
) / sizeof( service_entry
) ; ++i
)
1332 if ( strcmp( port
, gServices
[i
].name
) == 0 )
1334 if ( protocol
== NULL
|| strcmp( protocol
, gServices
[i
].protocol
) )
1336 address
->m_port
= gServices
[i
].port
;
1337 return GSOCK_NOERROR
;
1342 if (isdigit(port
[0]))
1344 address
->m_port
= atoi(port
);
1345 return GSOCK_NOERROR
;
1348 address
->m_error
= GSOCK_INVPORT
;
1349 return GSOCK_INVPORT
;
1352 GSocketError
GAddress_INET_SetPort(GAddress
*address
, unsigned short port
)
1356 assert(address
!= NULL
);
1357 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1358 address
->m_port
= port
;
1360 return GSOCK_NOERROR
;
1363 GSocketError
GAddress_INET_GetHostName(GAddress
*address
, char *hostname
, size_t sbuf
)
1365 InetDomainName name
;
1367 assert(address
!= NULL
);
1368 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1370 OTInetAddressToName( gInetSvcRef
, address
->m_host
, name
) ;
1371 strncpy( hostname
, name
, sbuf
) ;
1372 return GSOCK_NOERROR
;
1375 unsigned long GAddress_INET_GetHostAddress(GAddress
*address
)
1377 assert(address
!= NULL
);
1378 CHECK_ADDRESS(address
, INET
, 0);
1380 return address
->m_host
;
1383 unsigned short GAddress_INET_GetPort(GAddress
*address
)
1385 assert(address
!= NULL
);
1386 CHECK_ADDRESS(address
, INET
, 0);
1388 return address
->m_port
;
1391 void _GSocket_Enable_Events(GSocket
*socket
)
1393 if ( socket
->m_takesEvents
)
1398 socket
->m_takesEvents
= TRUE
;
1399 state
= OTGetEndpointState(socket
->m_endpoint
);
1402 OTByteCount sz
= 0 ;
1403 OTCountDataBytes( socket
->m_endpoint
, &sz
) ;
1404 if ( state
== T_INCON
|| sz
> 0 )
1406 socket
->m_detected
|= GSOCK_INPUT_FLAG
;
1407 (socket
->m_cbacks
[GSOCK_INPUT
])(socket
, GSOCK_INPUT
, socket
->m_data
[GSOCK_INPUT
]);
1411 if ( state
== T_DATAXFER
|| state
== T_INREL
)
1413 socket
->m_detected
|=GSOCK_OUTPUT_FLAG
;
1414 (socket
->m_cbacks
[GSOCK_OUTPUT
])(socket
, GSOCK_OUTPUT
, socket
->m_data
[GSOCK_OUTPUT
]);
1420 void _GSocket_Disable_Events(GSocket
*socket
)
1422 socket
->m_takesEvents
= FALSE
;
1425 /* _GSocket_Input_Timeout:
1426 * For blocking sockets, wait until data is available or
1427 * until timeout ellapses.
1429 GSocketError
_GSocket_Input_Timeout(GSocket
*socket
)
1431 if ( !socket
->m_non_blocking
)
1433 UnsignedWide now
, start
;
1434 short formerTakesEvents
= socket
->m_takesEvents
;
1435 Microseconds(&start
);
1437 socket
->m_takesEvents
= FALSE
;
1439 while( (now
.hi
* 4294967296.0 + now
.lo
) - (start
.hi
* 4294967296.0 + start
.lo
) < socket
->m_timeout
* 1000.0 )
1442 OTByteCount sz
= 0 ;
1443 state
= OTGetEndpointState(socket
->m_endpoint
);
1445 OTCountDataBytes( socket
->m_endpoint
, &sz
) ;
1446 if ( state
== T_INCON
|| sz
> 0 )
1448 socket
->m_takesEvents
= formerTakesEvents
;
1449 return GSOCK_NOERROR
;
1453 socket
->m_takesEvents
= formerTakesEvents
;
1454 socket
->m_error
= GSOCK_TIMEDOUT
;
1455 return GSOCK_TIMEDOUT
;
1457 return GSOCK_NOERROR
;
1460 /* _GSocket_Output_Timeout:
1461 * For blocking sockets, wait until data can be sent without
1462 * blocking or until timeout ellapses.
1464 GSocketError
_GSocket_Output_Timeout(GSocket
*socket
)
1466 if ( !socket
->m_non_blocking
)
1468 UnsignedWide now
, start
;
1469 short formerTakesEvents
= socket
->m_takesEvents
;
1470 Microseconds(&start
);
1472 socket
->m_takesEvents
= FALSE
;
1474 while( (now
.hi
* 4294967296.0 + now
.lo
) - (start
.hi
* 4294967296.0 + start
.lo
) < socket
->m_timeout
* 1000.0 )
1477 state
= OTGetEndpointState(socket
->m_endpoint
);
1479 if ( state
== T_DATAXFER
|| state
== T_INREL
)
1481 socket
->m_takesEvents
= formerTakesEvents
;
1482 return GSOCK_NOERROR
;
1486 socket
->m_takesEvents
= formerTakesEvents
;
1487 socket
->m_error
= GSOCK_TIMEDOUT
;
1488 return GSOCK_TIMEDOUT
;
1490 return GSOCK_NOERROR
;
1494 * There is data to be read in the input buffer. If, after a read
1495 * operation, there is still data available, the callback function will
1498 * The socket is available for writing. That is, the next write call
1499 * won't block. This event is generated only once, when the connection is
1500 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
1501 * when the output buffer empties again. This means that the app should
1502 * assume that it can write since the first OUTPUT event, and no more
1503 * OUTPUT events will be generated unless an error occurs.
1505 * Connection succesfully established, for client sockets, or incoming
1506 * client connection, for server sockets. Wait for this event (also watch
1507 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
1509 * The connection is lost (or a connection request failed); this could
1510 * be due to a failure, or due to the peer closing it gracefully.
1513 void _GSocket_Internal_Proc(unsigned long e
, void* d
)
1516 GSocket
* socket
= (GSocket
*) d
;
1517 OTEventCode ev
= (OTEventCode
) e
;
1519 GSocketEvent event2
;
1520 GSocketCallback cback
;
1522 GSocketCallback cback2
;
1527 event
= GSOCK_MAX_EVENT
;
1528 event2
= GSOCK_MAX_EVENT
;
1534 /* Check that the socket still exists (it has not been
1535 * destroyed) and for safety, check that the m_endpoint field
1536 * is what we expect it to be.
1538 if ((socket
!= NULL
) && (socket
->m_takesEvents
))
1543 event
= GSOCK_CONNECTION
;
1546 event
= GSOCK_CONNECTION
;
1547 event2
= GSOCK_OUTPUT
;
1551 retCall
.addr
.buf
= NULL
;
1552 retCall
.addr
.maxlen
= 0;
1553 retCall
.opt
.buf
= NULL
;
1554 retCall
.opt
.maxlen
= 0;
1555 retCall
.udata
.buf
= NULL
;
1556 retCall
.udata
.maxlen
= 0;
1557 OTRcvConnect( socket
->m_endpoint
, &retCall
) ;
1561 event
= GSOCK_LOST
;
1565 event
= GSOCK_OUTPUT
;
1568 event
= GSOCK_INPUT
;
1571 event
= GSOCK_INPUT
;
1574 if (event
!= GSOCK_MAX_EVENT
)
1576 cback
= socket
->m_cbacks
[event
];
1577 data
= socket
->m_data
[event
];
1579 if (event
== GSOCK_LOST
)
1580 socket
->m_detected
= GSOCK_LOST_FLAG
;
1582 socket
->m_detected
|= (1 << event
);
1584 if (event2
!= GSOCK_MAX_EVENT
)
1586 cback2
= socket
->m_cbacks
[event2
];
1587 data2
= socket
->m_data
[event2
];
1589 if (event2
== GSOCK_LOST
)
1590 socket
->m_detected
= GSOCK_LOST_FLAG
;
1592 socket
->m_detected
|= (1 << event2
);
1596 /* OK, we can now leave the critical section because we have
1597 * already obtained the callback address (we make no further
1598 * accesses to socket->whatever). However, the app should
1599 * be prepared to handle events from a socket that has just
1604 (cback
)(socket
, event
, data
);
1606 (cback2
)(socket
, event2
, data2
);
1610 /* Hack added for Mac OS X */
1611 GSocketError
GAddress_UNIX_GetPath(GAddress
*addr
, char *path
, size_t buf
)
1615 GSocketError
GAddress_UNIX_SetPath(GAddress
*addr
, const char *path
)
1619 #endif /* wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__) */