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__)
30 #define OTUNIXERRORS 1
31 #include <OpenTransport.h>
32 #include <OpenTransportProviders.h>
33 #include <OpenTptInternet.h>
35 #define OTAssert( str , cond ) /* does not exists in Carbon */
40 * INADDR_BROADCAST is identical to INADDR_NONE which is not defined
41 * on all unices. INADDR_BROADCAST should be fine to indicate an error.
43 #ifndef INADDR_BROADCAST
44 #define INADDR_BROADCAST 0xFFFFFFFFUL
47 #define INADDR_NONE INADDR_BROADCAST
50 #define INADDR_ANY 0x0UL
52 #ifndef __GSOCKET_STANDALONE__
54 #include "wx/mac/macnotfy.h"
55 #include "wx/mac/gsockmac.h"
56 #include "wx/gsocket.h"
63 #endif /* __GSOCKET_STANDALONE__ */
69 extern pascal void OTDebugStr(const char* str
);
72 InetSvcRef gInetSvcRef
= 0 ;
75 OSStatus
DoNegotiateIPReuseAddrOption(EndpointRef ep
, Boolean enableReuseIPMode
);
77 /* Input: ep - endpointref on which to negotiate the option
78 enableReuseIPMode - desired option setting - true/false
79 Return: kOTNoError indicates that the option was successfully negotiated
80 OSStatus is an error if < 0, otherwise, the status field is
83 IMPORTANT NOTE: The endpoint is assumed to be in synchronous more, otherwise
84 this code will not function as desired
88 OSStatus
DoNegotiateIPReuseAddrOption(EndpointRef ep
, Boolean enableReuseIPMode
)
91 UInt8 buf
[kOTFourByteOptionSize
]; // define buffer for fourByte Option size
92 TOption
* opt
; // option ptr to make items easier to access
97 if (!OTIsSynchronous(ep
))
101 opt
= (TOption
*)buf
; // set option ptr to buffer
103 req
.opt
.len
= sizeof(buf
);
104 req
.flags
= T_NEGOTIATE
; // negotiate for option
107 ret
.opt
.maxlen
= kOTFourByteOptionSize
;
109 opt
->level
= INET_IP
; // dealing with an IP Level function
110 opt
->name
= IP_REUSEADDR
;
111 opt
->len
= kOTFourByteOptionSize
;
113 *(UInt32
*)opt
->value
= enableReuseIPMode
; // set the desired option level, true or false
115 err
= OTOptionManagement(ep
, &req
, &ret
);
117 // if no error then return the option status value
118 if (err
== kOTNoError
)
120 if (opt
->status
!= T_SUCCESS
)
130 pascal void OTInetEventHandler(void*s
, OTEventCode event
, OTResult
, void *cookie
) ;
131 pascal void OTInetEventHandler(void*s
, OTEventCode event
, OTResult result
, void *cookie
)
134 GSocket
* sock
= (GSocket
*) s
;
136 if ( event
== kOTSyncIdleEvent
)
144 wxMacAddEvent( sock
->m_mac_events
, _GSocket_Internal_Proc
, event
, s
, wakeUp
) ;
150 static void SetDefaultEndpointModes(EndpointRef ep
, void *data
)
151 // This routine sets the supplied endpoint into the default
152 // mode used in this application. The specifics are:
153 // blocking, synchronous, and using synch idle events with
154 // the standard YieldingNotifier.
156 OSStatus junk
= kOTNoError
;
157 OTAssert ("SetDefaultEndpointModes:invalid ref", ep
!= kOTInvalidEndpointRef
) ;
158 junk
= OTSetAsynchronous(ep
);
159 OTAssert("SetDefaultEndpointModes: Could not set asynchronous", junk
== noErr
);
161 junk = OTSetBlocking(ep);
162 OTAssert("SetDefaultEndpointModes: Could not set blocking", junk == noErr);
163 junk = OTSetSynchronous(ep);
164 OTAssert("SetDefaultEndpointModes: Could not set synchronous", junk == noErr);
165 junk = OTSetBlocking(ep);
166 OTAssert("SetDefaultEndpointModes: Could not set blocking", junk == noErr);
168 junk
= OTInstallNotifier(ep
, OTInetEventHandler
, data
);
169 OTAssert("SetDefaultEndpointModes: Could not install notifier", junk
== noErr
);
171 junk = OTUseSyncIdleEvents(ep, true);
172 OTAssert("SetDefaultEndpointModes: Could not use sync idle events", junk == noErr);
176 /* Global initialisers */
182 InitOpenTransportInContext( kInitOTForApplicationMask
, NULL
) ;
184 InitOpenTransport() ;
186 gInetSvcRef
= OTOpenInternetServices(kDefaultInternetServicesPath
, NULL
, &err
);
187 if ( gInetSvcRef
== NULL
|| err
!= kOTNoError
)
189 OTAssert("Could not open Inet Services", err
== noErr
);
195 void GSocket_Cleanup()
197 if ( gInetSvcRef
!= NULL
)
198 OTCloseProvider( gInetSvcRef
);
200 CloseOpenTransportInContext( NULL
) ;
202 CloseOpenTransport() ;
206 /* Constructors / Destructors for GSocket */
208 GSocket
*GSocket_new()
213 socket
= (GSocket
*)malloc(sizeof(GSocket
));
218 socket
->m_endpoint
= NULL
;
219 for (i
=0;i
<GSOCK_MAX_EVENT
;i
++)
221 socket
->m_cbacks
[i
] = NULL
;
223 socket
->m_detected
= 0;
224 socket
->m_local
= NULL
;
225 socket
->m_peer
= NULL
;
226 socket
->m_error
= GSOCK_NOERROR
;
227 socket
->m_server
= FALSE
;
228 socket
->m_stream
= TRUE
;
229 socket
->m_non_blocking
= FALSE
;
230 socket
->m_timeout
= 10*60*1000;
231 /* 10 minutes * 60 sec * 1000 millisec */
232 socket
->m_takesEvents
= TRUE
;
233 socket
->m_mac_events
= wxMacGetNotifierTable() ;
237 void GSocket_destroy(GSocket
*socket
)
239 assert(socket
!= NULL
);
241 /* Check that the socket is really shutdowned */
242 if (socket
->m_endpoint
!= kOTInvalidEndpointRef
)
243 GSocket_Shutdown(socket
);
246 /* Destroy private addresses */
248 GAddress_destroy(socket
->m_local
);
251 GAddress_destroy(socket
->m_peer
);
253 /* Destroy the socket itself */
258 * Disallow further read/write operations on this socket, close
259 * the fd and disable all callbacks.
261 void GSocket_Shutdown(GSocket
*socket
)
266 assert(socket
!= NULL
);
268 /* If socket has been created, shutdown it */
269 if (socket
->m_endpoint
!= kOTInvalidEndpointRef
)
271 err
= OTSndOrderlyDisconnect( socket
->m_endpoint
) ;
272 if ( err
!= kOTNoError
)
276 err
= OTRcvOrderlyDisconnect( socket
->m_endpoint
) ;
277 err
= OTUnbind( socket
->m_endpoint
) ;
278 err
= OTCloseProvider( socket
->m_endpoint
) ;
279 socket
->m_endpoint
= kOTInvalidEndpointRef
;
282 /* Disable GUI callbacks */
283 for (evt
= 0; evt
< GSOCK_MAX_EVENT
; evt
++)
284 socket
->m_cbacks
[evt
] = NULL
;
286 socket
->m_detected
= 0;
287 _GSocket_Disable_Events(socket
);
288 wxMacRemoveAllNotifiersForData( wxMacGetNotifierTable() , socket
) ;
292 /* Address handling */
298 * Set or get the local or peer address for this socket. The 'set'
299 * functions return GSOCK_NOERROR on success, an error code otherwise.
300 * The 'get' functions return a pointer to a GAddress object on success,
301 * or NULL otherwise, in which case they set the error code of the
302 * corresponding GSocket.
305 * GSOCK_INVSOCK - the socket is not valid.
306 * GSOCK_INVADDR - the address is not valid.
308 GSocketError
GSocket_SetLocal(GSocket
*socket
, GAddress
*address
)
310 assert(socket
!= NULL
);
312 /* the socket must be initialized, or it must be a server */
313 if ((socket
->m_endpoint
!= kOTInvalidEndpointRef
&& !socket
->m_server
))
315 socket
->m_error
= GSOCK_INVSOCK
;
316 return GSOCK_INVSOCK
;
320 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
322 socket
->m_error
= GSOCK_INVADDR
;
323 return GSOCK_INVADDR
;
327 GAddress_destroy(socket
->m_local
);
329 socket
->m_local
= GAddress_copy(address
);
331 return GSOCK_NOERROR
;
334 GSocketError
GSocket_SetPeer(GSocket
*socket
, GAddress
*address
)
336 assert(socket
!= NULL
);
339 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
341 socket
->m_error
= GSOCK_INVADDR
;
342 return GSOCK_INVADDR
;
346 GAddress_destroy(socket
->m_peer
);
348 socket
->m_peer
= GAddress_copy(address
);
350 return GSOCK_NOERROR
;
353 GAddress
*GSocket_GetLocal(GSocket
*socket
)
355 GAddress
*address
= NULL
;
360 assert(socket
!= NULL
);
362 /* try to get it from the m_local var first */
364 return GAddress_copy(socket
->m_local
);
366 /* else, if the socket is initialized, try getsockname */
367 if (socket
->m_endpoint
== kOTInvalidEndpointRef
)
369 socket
->m_error
= GSOCK_INVSOCK
;
374 /* we do not support multihoming with this code at the moment
375 OTGetProtAddress will have to be used then - but we don't have a handy
376 method to use right now
379 InetInterfaceInfo info
;
380 OTInetGetInterfaceInfo(&info
, kDefaultInetInterface
);
381 loc
.fHost
= info
.fAddress
;
383 loc
.fAddressType
= AF_INET
;
386 /* got a valid address from getsockname, create a GAddress object */
387 address
= GAddress_new();
390 socket
->m_error
= GSOCK_MEMERR
;
394 err
= _GAddress_translate_from(address
, &loc
);
395 if (err
!= GSOCK_NOERROR
)
397 GAddress_destroy(address
);
398 socket
->m_error
= err
;
405 GAddress
*GSocket_GetPeer(GSocket
*socket
)
407 assert(socket
!= NULL
);
409 /* try to get it from the m_peer var */
411 return GAddress_copy(socket
->m_peer
);
416 /* Server specific parts */
418 /* GSocket_SetServer:
419 * Sets up this socket as a server. The local address must have been
420 * set with GSocket_SetLocal() before GSocket_SetServer() is called.
421 * Returns GSOCK_NOERROR on success, one of the following otherwise:
424 * GSOCK_INVSOCK - the socket is in use.
425 * GSOCK_INVADDR - the local address has not been set.
426 * GSOCK_IOERR - low-level error.
428 GSocketError
GSocket_SetServer(GSocket
*sck
)
435 /* must not be in use */
436 if (sck
->m_endpoint
!= kOTInvalidEndpointRef
)
438 sck
->m_error
= GSOCK_INVSOCK
;
439 return GSOCK_INVSOCK
;
442 /* the local addr must have been set */
445 sck
->m_error
= GSOCK_INVADDR
;
446 return GSOCK_INVADDR
;
449 /* Initialize all fields */
450 sck
->m_stream
= TRUE
;
451 sck
->m_server
= TRUE
;
452 sck
->m_oriented
= TRUE
;
456 /* Create the socket */
457 sck
->m_endpoint
= socket(sck
->m_local
->m_realfamily
, SOCK_STREAM
, 0);
458 socket_set_ref( sck
->m_endpoint
, (unsigned long) &gMacNetEvents
, (unsigned long) sck
) ;
459 if (sck
->m_endpoint
== kOTInvalidEndpointRef
)
461 sck
->m_error
= GSOCK_IOERR
;
465 ioctl(sck
->m_endpoint
, FIONBIO
, &arg
);
466 _GSocket_Enable_Events(sck
);
468 /* Bind to the local address,
469 * retrieve the actual address bound,
470 * and listen up to 5 connections.
472 if ((bind(sck
->m_endpoint
, sck
->m_local
->m_addr
, sck
->m_local
->m_len
) != 0) ||
473 (getsockname(sck
->m_endpoint
,
474 sck
->m_local
->m_addr
,
475 (SOCKLEN_T
*) &sck
->m_local
->m_len
) != 0) ||
476 (listen(sck
->m_endpoint
, 5) != 0))
478 close(sck
->m_endpoint
);
479 sck
->m_endpoint
= -1;
480 sck
->m_error
= GSOCK_IOERR
;
484 return GSOCK_NOERROR
;
487 /* GSocket_WaitConnection:
488 * Waits for an incoming client connection. Returns a pointer to
489 * a GSocket object, or NULL if there was an error, in which case
490 * the last error field will be updated for the calling GSocket.
492 * Error codes (set in the calling GSocket)
493 * GSOCK_INVSOCK - the socket is not valid or not a server.
494 * GSOCK_TIMEDOUT - timeout, no incoming connections.
495 * GSOCK_WOULDBLOCK - the call would block and the socket is nonblocking.
496 * GSOCK_MEMERR - couldn't allocate memory.
497 * GSOCK_IOERR - low-level error.
499 GSocket
*GSocket_WaitConnection(GSocket
*socket
)
501 GSocket
*connection
= NULL
;
506 assert(socket
!= NULL
);
508 /* Reenable CONNECTION events */
509 socket
->m_detected
&= ~GSOCK_CONNECTION_FLAG
;
511 /* If the socket has already been created, we exit immediately */
512 if (socket
->m_endpoint
== kOTInvalidEndpointRef
|| !socket
->m_server
)
514 socket
->m_error
= GSOCK_INVSOCK
;
518 /* Create a GSocket object for the new connection */
519 connection
= GSocket_new();
523 socket
->m_error
= GSOCK_MEMERR
;
527 /* Wait for a connection (with timeout) */
528 if (_GSocket_Input_Timeout(socket
) == GSOCK_TIMEDOUT
)
530 GSocket_destroy(connection
);
531 /* socket->m_error set by _GSocket_Input_Timeout */
537 connection
->m_endpoint
= accept(socket
->m_endpoint
, &from
, (SOCKLEN_T
*) &fromlen
);
540 if (connection
->m_endpoint
== kOTInvalidEndpointRef
)
542 if (errno
== EWOULDBLOCK
)
543 socket
->m_error
= GSOCK_WOULDBLOCK
;
545 socket
->m_error
= GSOCK_IOERR
;
547 GSocket_destroy(connection
);
551 /* Initialize all fields */
552 connection
->m_server
= FALSE
;
553 connection
->m_stream
= TRUE
;
554 connection
->m_oriented
= TRUE
;
556 /* Setup the peer address field */
557 connection
->m_peer
= GAddress_new();
558 if (!connection
->m_peer
)
560 GSocket_destroy(connection
);
561 socket
->m_error
= GSOCK_MEMERR
;
566 err
= _GAddress_translate_from(connection
->m_peer
, &from
, fromlen
);
567 if (err
!= GSOCK_NOERROR
)
569 GAddress_destroy(connection
->m_peer
);
570 GSocket_destroy(connection
);
571 socket
->m_error
= err
;
575 ioctl(connection
->m_endpoint
, FIONBIO
, &arg
);
577 _GSocket_Enable_Events(connection
);
582 /* Datagram sockets */
584 /* GSocket_SetNonOriented:
585 * Sets up this socket as a non-connection oriented (datagram) socket.
586 * Before using this function, the local address must have been set
587 * with GSocket_SetLocal(), or the call will fail. Returns GSOCK_NOERROR
588 * on success, or one of the following otherwise.
591 * GSOCK_INVSOCK - the socket is in use.
592 * GSOCK_INVADDR - the local address has not been set.
593 * GSOCK_IOERR - low-level error.
595 GSocketError
GSocket_SetNonOriented(GSocket
*sck
)
601 if (sck
->m_endpoint
!= kOTInvalidEndpointRef
)
603 sck
->m_error
= GSOCK_INVSOCK
;
604 return GSOCK_INVSOCK
;
609 sck
->m_error
= GSOCK_INVADDR
;
610 return GSOCK_INVADDR
;
613 /* Initialize all fields */
614 sck
->m_stream
= FALSE
;
615 sck
->m_server
= FALSE
;
616 sck
->m_oriented
= FALSE
;
618 /* Create the socket */
622 sck
->m_endpoint
= socket(sck
->m_local
->m_realfamily
, SOCK_DGRAM
, 0);
623 socket_set_ref( sck
->m_endpoint
, (unsigned long) &gMacNetEvents
, (unsigned long) sck
) ;
625 if (sck
->m_endpoint
== kOTInvalidEndpointRef
)
627 sck
->m_error
= GSOCK_IOERR
;
633 ioctl(sck
->m_endpoint
, FIONBIO
, &arg
);
635 _GSocket_Enable_Events(sck
);
637 /* Bind to the local address,
638 * and retrieve the actual address bound.
642 if ((bind(sck
->m_endpoint
, sck
->m_local
->m_addr
, sck
->m_local
->m_len
) != 0) ||
643 (getsockname(sck
->m_endpoint
,
644 sck
->m_local
->m_addr
,
645 (SOCKLEN_T
*) &sck
->m_local
->m_len
) != 0))
647 close(sck
->m_endpoint
);
648 sck
->m_endpoint
= -1;
649 sck
->m_error
= GSOCK_IOERR
;
653 return GSOCK_NOERROR
;
656 /* Client specific parts */
659 * For stream (connection oriented) sockets, GSocket_Connect() tries
660 * to establish a client connection to a server using the peer address
661 * as established with GSocket_SetPeer(). Returns GSOCK_NOERROR if the
662 * connection has been succesfully established, or one of the error
663 * codes listed below. Note that for nonblocking sockets, a return
664 * value of GSOCK_WOULDBLOCK doesn't mean a failure. The connection
665 * request can be completed later; you should use GSocket_Select()
666 * to poll for GSOCK_CONNECTION | GSOCK_LOST, or wait for the
667 * corresponding asynchronous events.
669 * For datagram (non connection oriented) sockets, GSocket_Connect()
670 * just sets the peer address established with GSocket_SetPeer() as
671 * default destination.
674 * GSOCK_INVSOCK - the socket is in use or not valid.
675 * GSOCK_INVADDR - the peer address has not been established.
676 * GSOCK_TIMEDOUT - timeout, the connection failed.
677 * GSOCK_WOULDBLOCK - connection in progress (nonblocking sockets only)
678 * GSOCK_MEMERR - couldn't allocate memory.
679 * GSOCK_IOERR - low-level error.
681 GSocketError
GSocket_Connect(GSocket
*sck
, GSocketStream stream
)
688 OSStatus err
= kOTNoError
;
693 /* Enable CONNECTION events (needed for nonblocking connections) */
694 sck
->m_detected
&= ~GSOCK_CONNECTION_FLAG
;
696 if (sck
->m_endpoint
!= kOTInvalidEndpointRef
)
698 sck
->m_error
= GSOCK_INVSOCK
;
699 return GSOCK_INVSOCK
;
704 sck
->m_error
= GSOCK_INVADDR
;
705 return GSOCK_INVADDR
;
708 /* Streamed or dgram socket? */
709 sck
->m_stream
= (stream
== GSOCK_STREAMED
);
710 sck
->m_oriented
= TRUE
;
711 sck
->m_server
= FALSE
;
713 /* Create the socket */
716 OTOpenEndpointInContext( OTCreateConfiguration( kTCPName
) , 0 , &info
, &err
, NULL
) ;
719 OTOpenEndpoint( OTCreateConfiguration( kTCPName
) , 0 , &info
, &err
) ;
721 if ( sck
->m_endpoint
== kOTInvalidEndpointRef
|| err
!= kOTNoError
)
723 sck
->m_endpoint
= kOTInvalidEndpointRef
;
724 sck
->m_error
= GSOCK_IOERR
;
727 err
= OTBind( sck
->m_endpoint
, nil
, nil
) ;
728 if ( err
!= kOTNoError
)
732 SetDefaultEndpointModes( sck
->m_endpoint
, sck
) ;
735 ioctl(sck
->m_endpoint
, FIONBIO
, &arg
);
737 _GSocket_Enable_Events(sck
);
739 _GAddress_translate_to( sck
->m_peer
, &addr
) ;
740 memset( &peer
, 0 , sizeof( TCall
) ) ;
741 peer
.addr
.len
= sizeof( InetAddress
) ;
742 peer
.addr
.buf
= (unsigned char*) &addr
;
743 err
= OTConnect( sck
->m_endpoint
, &peer
, nil
) ;
746 /* If connect failed with EINPROGRESS and the GSocket object
747 * is in blocking mode, we select() for the specified timeout
748 * checking for writability to see if the connection request
752 if ((err
== kOTNoDataErr
) && (!sck
->m_non_blocking
))
754 if (_GSocket_Output_Timeout(sck
) == GSOCK_TIMEDOUT
)
756 OTSndOrderlyDisconnect( sck
->m_endpoint
) ;
757 sck
->m_endpoint
= kOTInvalidEndpointRef
;
758 /* sck->m_error is set in _GSocket_Output_Timeout */
759 return GSOCK_TIMEDOUT
;
765 SOCKLEN_T len = sizeof(error);
767 getsockopt(sck->m_endpoint, SOL_SOCKET, SO_ERROR, (void*) &error, &len);
771 return GSOCK_NOERROR
;
775 /* If connect failed with EINPROGRESS and the GSocket object
776 * is set to nonblocking, we set m_error to GSOCK_WOULDBLOCK
777 * (and return GSOCK_WOULDBLOCK) but we don't close the socket;
778 * this way if the connection completes, a GSOCK_CONNECTION
779 * event will be generated, if enabled.
781 if ((err
== kOTNoDataErr
) && (sck
->m_non_blocking
))
783 sck
->m_error
= GSOCK_WOULDBLOCK
;
784 return GSOCK_WOULDBLOCK
;
787 /* If connect failed with an error other than EINPROGRESS,
788 * then the call to GSocket_Connect has failed.
790 OTSndOrderlyDisconnect( sck
->m_endpoint
) ;
792 sck
->m_endpoint
= kOTInvalidEndpointRef
;
793 sck
->m_error
= GSOCK_IOERR
;
796 // OTInetEventHandler(sck, T_CONNECT , kOTNoError , NULL ) ;
797 return GSOCK_NOERROR
;
802 /* Like recv(), send(), ... */
803 int GSocket_Read(GSocket
*socket
, char *buffer
, int size
)
807 assert(socket
!= NULL
);
809 /* Reenable INPUT events */
810 socket
->m_detected
&= ~GSOCK_INPUT_FLAG
;
812 if (socket
->m_endpoint
== kOTInvalidEndpointRef
|| socket
->m_server
)
814 socket
->m_error
= GSOCK_INVSOCK
;
818 /* If the socket is blocking, wait for data (with a timeout) */
819 if (_GSocket_Input_Timeout(socket
) == GSOCK_TIMEDOUT
)
823 if (socket
->m_stream
)
824 ret
= _GSocket_Recv_Stream(socket
, buffer
, size
);
826 ret
= _GSocket_Recv_Dgram(socket
, buffer
, size
);
830 if (errno
== EWOULDBLOCK
)
831 socket
->m_error
= GSOCK_WOULDBLOCK
;
833 socket
->m_error
= GSOCK_IOERR
;
839 int GSocket_Write(GSocket
*socket
, const char *buffer
, int size
)
843 assert(socket
!= NULL
);
845 if (socket
->m_endpoint
== kOTInvalidEndpointRef
|| socket
->m_server
)
847 socket
->m_error
= GSOCK_INVSOCK
;
851 /* If the socket is blocking, wait for writability (with a timeout) */
852 if (_GSocket_Output_Timeout(socket
) == GSOCK_TIMEDOUT
)
856 if (socket
->m_stream
)
857 ret
= _GSocket_Send_Stream(socket
, buffer
, size
);
859 ret
= _GSocket_Send_Dgram(socket
, buffer
, size
);
863 if (errno
== EWOULDBLOCK
)
864 socket
->m_error
= GSOCK_WOULDBLOCK
;
866 socket
->m_error
= GSOCK_IOERR
;
868 /* Only reenable OUTPUT events after an error (just like WSAAsyncSelect
869 * in MSW). Once the first OUTPUT event is received, users can assume
870 * that the socket is writable until a read operation fails. Only then
871 * will further OUTPUT events be posted.
873 socket
->m_detected
&= ~GSOCK_OUTPUT_FLAG
;
881 * Polls the socket to determine its status. This function will
882 * check for the events specified in the 'flags' parameter, and
883 * it will return a mask indicating which operations can be
884 * performed. This function won't block, regardless of the
885 * mode (blocking | nonblocking) of the socket.
887 GSocketEventFlags
GSocket_Select(GSocket
*socket
, GSocketEventFlags flags
)
890 assert(socket
!= NULL
);
891 wxMacProcessNotifierEvents() ;
893 state = OTGetEndpointState(socket->m_endpoint);
895 if ( ( flags & GSOCK_INPUT_FLAG ) && ! ( socket->m_detected & GSOCK_INPUT_FLAG ) )
898 OTCountDataBytes( socket->m_endpoint , &sz ) ;
899 if ( state == T_INCON || sz > 0 )
901 socket->m_detected |= GSOCK_INPUT_FLAG ;
902 (socket->m_cbacks[GSOCK_INPUT])(socket, GSOCK_INPUT, socket->m_data[GSOCK_INPUT]);
905 if ( ( flags & GSOCK_INPUT_FLAG ) && ! ( socket->m_detected & GSOCK_OUTPUT_FLAG ) )
907 if ( state == T_DATAXFER || state == T_INREL )
909 socket->m_detected |=GSOCK_OUTPUT_FLAG ;
910 (socket->m_cbacks[GSOCK_OUTPUT])(socket, GSOCK_OUTPUT, socket->m_data[GSOCK_OUTPUT]);
914 return ( flags
& socket
->m_detected
) ;
919 /* GSocket_SetNonBlocking:
920 * Sets the socket to non-blocking mode. All IO calls will return
923 void GSocket_SetNonBlocking(GSocket
*socket
, int non_block
)
925 assert(socket
!= NULL
);
927 socket
->m_non_blocking
= non_block
;
930 /* GSocket_SetTimeout:
931 * Sets the timeout for blocking calls. Time is expressed in
934 void GSocket_SetTimeout(GSocket
*socket
, unsigned long millisec
)
936 assert(socket
!= NULL
);
938 socket
->m_timeout
= millisec
;
942 * Returns the last error occured for this socket. Note that successful
943 * operations do not clear this back to GSOCK_NOERROR, so use it only
946 GSocketError
GSocket_GetError(GSocket
*socket
)
948 assert(socket
!= NULL
);
950 return socket
->m_error
;
956 * There is data to be read in the input buffer. If, after a read
957 * operation, there is still data available, the callback function will
960 * The socket is available for writing. That is, the next write call
961 * won't block. This event is generated only once, when the connection is
962 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
963 * when the output buffer empties again. This means that the app should
964 * assume that it can write since the first OUTPUT event, and no more
965 * OUTPUT events will be generated unless an error occurs.
967 * Connection succesfully established, for client sockets, or incoming
968 * client connection, for server sockets. Wait for this event (also watch
969 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
971 * The connection is lost (or a connection request failed); this could
972 * be due to a failure, or due to the peer closing it gracefully.
975 /* GSocket_SetCallback:
976 * Enables the callbacks specified by 'flags'. Note that 'flags'
977 * may be a combination of flags OR'ed toghether, so the same
978 * callback function can be made to accept different events.
979 * The callback function must have the following prototype:
981 * void function(GSocket *socket, GSocketEvent event, char *cdata)
983 void GSocket_SetCallback(GSocket
*socket
, GSocketEventFlags flags
,
984 GSocketCallback callback
, char *cdata
)
988 assert(socket
!= NULL
);
990 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
992 if ((flags
& (1 << count
)) != 0)
994 socket
->m_cbacks
[count
] = callback
;
995 socket
->m_data
[count
] = cdata
;
1000 /* GSocket_UnsetCallback:
1001 * Disables all callbacks specified by 'flags', which may be a
1002 * combination of flags OR'ed toghether.
1004 void GSocket_UnsetCallback(GSocket
*socket
, GSocketEventFlags flags
)
1008 assert(socket
!= NULL
);
1010 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1012 if ((flags
& (1 << count
)) != 0)
1014 socket
->m_cbacks
[count
] = NULL
;
1015 socket
->m_data
[count
] = NULL
;
1021 #define CALL_CALLBACK(socket, event) { \
1022 _GSocket_Disable(socket, event); \
1023 if (socket->m_cbacks[event]) \
1024 socket->m_cbacks[event](socket, event, socket->m_data[event]); \
1027 int _GSocket_Recv_Stream(GSocket
*socket
, char *buffer
, int size
)
1033 OTCountDataBytes( socket
->m_endpoint
, &sz
) ;
1034 res
= OTRcv( socket
->m_endpoint
, buffer
, size
, &flags
) ;
1040 // we simulate another read event if there are still bytes
1041 if ( socket
->m_takesEvents
)
1044 OTCountDataBytes( socket
->m_endpoint
, &sz
) ;
1047 socket
->m_detected
|= GSOCK_INPUT_FLAG
;
1048 (socket
->m_cbacks
[GSOCK_INPUT
])(socket
, GSOCK_INPUT
, socket
->m_data
[GSOCK_INPUT
]);
1054 int _GSocket_Recv_Dgram(GSocket
*socket
, char *buffer
, int size
)
1059 struct sockaddr from
;
1060 SOCKLEN_T fromlen
= sizeof(from
);
1063 fromlen
= sizeof(from
);
1065 ret
= recvfrom(socket
->m_endpoint
, buffer
, size
, 0, &from
, (SOCKLEN_T
*) &fromlen
);
1070 /* Translate a system address into a GSocket address */
1071 if (!socket
->m_peer
)
1073 socket
->m_peer
= GAddress_new();
1074 if (!socket
->m_peer
)
1076 socket
->m_error
= GSOCK_MEMERR
;
1080 err
= _GAddress_translate_from(socket
->m_peer
, &from
, fromlen
);
1081 if (err
!= GSOCK_NOERROR
)
1083 GAddress_destroy(socket
->m_peer
);
1084 socket
->m_peer
= NULL
;
1085 socket
->m_error
= err
;
1092 int _GSocket_Send_Stream(GSocket
*socket
, const char *buffer
, int size
)
1097 res
= OTSnd( socket
->m_endpoint
, (void*) buffer
, size
, flags
) ;
1101 int _GSocket_Send_Dgram(GSocket
*socket
, const char *buffer
, int size
)
1106 struct sockaddr
*addr
;
1110 if (!socket
->m_peer
)
1112 socket
->m_error
= GSOCK_INVADDR
;
1116 err
= _GAddress_translate_to(socket
->m_peer
, &addr
, &len
);
1117 if (err
!= GSOCK_NOERROR
)
1119 socket
->m_error
= err
;
1123 ret
= sendto(socket
->m_endpoint
, buffer
, size
, 0, addr
, len
);
1125 /* Frees memory allocated from _GAddress_translate_to */
1133 * -------------------------------------------------------------------------
1135 * -------------------------------------------------------------------------
1138 /* CHECK_ADDRESS verifies that the current family is either GSOCK_NOFAMILY
1139 * or GSOCK_*family*, and if it is GSOCK_NOFAMILY, it initalizes address
1140 * to be a GSOCK_*family*. In other cases, it returns GSOCK_INVADDR.
1142 #define CHECK_ADDRESS(address, family, retval) \
1144 if (address->m_family == GSOCK_NOFAMILY) \
1145 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1146 return address->m_error; \
1147 if (address->m_family != GSOCK_##family) \
1149 address->m_error = GSOCK_INVADDR; \
1154 GAddress
*GAddress_new()
1158 if ((address
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1161 address
->m_family
= GSOCK_NOFAMILY
;
1162 address
->m_host
= INADDR_NONE
;
1163 address
->m_port
= 0 ;
1168 GAddress
*GAddress_copy(GAddress
*address
)
1172 assert(address
!= NULL
);
1174 if ((addr2
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1177 memcpy(addr2
, address
, sizeof(GAddress
));
1181 void GAddress_destroy(GAddress
*address
)
1183 assert(address
!= NULL
);
1188 void GAddress_SetFamily(GAddress
*address
, GAddressType type
)
1190 assert(address
!= NULL
);
1192 address
->m_family
= type
;
1195 GAddressType
GAddress_GetFamily(GAddress
*address
)
1197 assert(address
!= NULL
);
1199 return address
->m_family
;
1202 GSocketError
_GAddress_translate_from(GAddress
*address
,
1205 switch (addr
->fAddressType
)
1208 address
->m_family
= GSOCK_INET
;
1212 address
->m_family
= GSOCK_INET6
;
1217 address
->m_error
= GSOCK_INVOP
;
1221 address
->m_host
= addr
->fHost
;
1222 address
->m_port
= addr
->fPort
;
1223 return GSOCK_NOERROR
;
1226 GSocketError
_GAddress_translate_to(GAddress
*address
,
1229 memset(addr
, 0 , sizeof(struct InetAddress
));
1230 OTInitInetAddress( addr
, address
->m_port
, address
->m_host
) ;
1231 return GSOCK_NOERROR
;
1235 * -------------------------------------------------------------------------
1236 * Internet address family
1237 * -------------------------------------------------------------------------
1240 GSocketError
_GAddress_Init_INET(GAddress
*address
)
1242 address
->m_family
= GSOCK_INET
;
1243 address
->m_host
= kOTAnyInetAddress
;
1245 return GSOCK_NOERROR
;
1248 GSocketError
GAddress_INET_SetHostName(GAddress
*address
, const char *hostname
)
1250 InetHostInfo hinfo
;
1253 assert(address
!= NULL
);
1255 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1256 ret
= OTInetStringToAddress( gInetSvcRef
, (char*) hostname
, &hinfo
) ;
1257 if ( ret
!= kOTNoError
)
1259 address
->m_host
= INADDR_NONE
;
1260 address
->m_error
= GSOCK_NOHOST
;
1261 return GSOCK_NOHOST
;
1263 address
->m_host
= hinfo
.addrs
[0] ;
1264 return GSOCK_NOERROR
;
1267 GSocketError
GAddress_INET_SetAnyAddress(GAddress
*address
)
1269 return GAddress_INET_SetHostAddress(address
, INADDR_ANY
);
1272 GSocketError
GAddress_INET_SetHostAddress(GAddress
*address
,
1273 unsigned long hostaddr
)
1275 struct in_addr
*addr
;
1277 assert(address
!= NULL
);
1279 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1281 address
->m_host
= hostaddr
;
1283 return GSOCK_NOERROR
;
1286 struct service_entry
1289 unsigned short port
;
1292 typedef struct service_entry service_entry
;
1294 service_entry gServices
[] =
1296 { "http" , 80 , "tcp" }
1299 GSocketError
GAddress_INET_SetPortName(GAddress
*address
, const char *port
,
1300 const char *protocol
)
1305 assert(address
!= NULL
);
1306 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1310 address
->m_error
= GSOCK_INVPORT
;
1311 return GSOCK_INVPORT
;
1313 for ( i
= 0 ; i
< sizeof( gServices
) / sizeof( service_entry
) ; ++i
)
1315 if ( strcmp( port
, gServices
[i
].name
) == 0 )
1317 if ( protocol
== NULL
|| strcmp( protocol
, gServices
[i
].protocol
) )
1319 address
->m_port
= gServices
[i
].port
;
1320 return GSOCK_NOERROR
;
1325 if (isdigit(port
[0]))
1327 address
->m_port
= atoi(port
);
1328 return GSOCK_NOERROR
;
1331 address
->m_error
= GSOCK_INVPORT
;
1332 return GSOCK_INVPORT
;
1335 GSocketError
GAddress_INET_SetPort(GAddress
*address
, unsigned short port
)
1339 assert(address
!= NULL
);
1340 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1341 address
->m_port
= port
;
1343 return GSOCK_NOERROR
;
1346 GSocketError
GAddress_INET_GetHostName(GAddress
*address
, char *hostname
, size_t sbuf
)
1348 InetDomainName name
;
1350 assert(address
!= NULL
);
1351 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1353 OTInetAddressToName( gInetSvcRef
, address
->m_host
, &name
) ;
1354 strncpy( hostname
, name
, sbuf
) ;
1355 return GSOCK_NOERROR
;
1358 unsigned long GAddress_INET_GetHostAddress(GAddress
*address
)
1360 assert(address
!= NULL
);
1361 CHECK_ADDRESS(address
, INET
, 0);
1363 return address
->m_host
;
1366 unsigned short GAddress_INET_GetPort(GAddress
*address
)
1368 assert(address
!= NULL
);
1369 CHECK_ADDRESS(address
, INET
, 0);
1371 return address
->m_port
;
1374 void _GSocket_Enable_Events(GSocket
*socket
)
1376 if ( socket
->m_takesEvents
)
1381 socket
->m_takesEvents
= TRUE
;
1382 state
= OTGetEndpointState(socket
->m_endpoint
);
1386 OTCountDataBytes( socket
->m_endpoint
, &sz
) ;
1387 if ( state
== T_INCON
|| sz
> 0 )
1389 socket
->m_detected
|= GSOCK_INPUT_FLAG
;
1390 (socket
->m_cbacks
[GSOCK_INPUT
])(socket
, GSOCK_INPUT
, socket
->m_data
[GSOCK_INPUT
]);
1394 if ( state
== T_DATAXFER
|| state
== T_INREL
)
1396 socket
->m_detected
|=GSOCK_OUTPUT_FLAG
;
1397 (socket
->m_cbacks
[GSOCK_OUTPUT
])(socket
, GSOCK_OUTPUT
, socket
->m_data
[GSOCK_OUTPUT
]);
1403 void _GSocket_Disable_Events(GSocket
*socket
)
1405 socket
->m_takesEvents
= FALSE
;
1408 /* _GSocket_Input_Timeout:
1409 * For blocking sockets, wait until data is available or
1410 * until timeout ellapses.
1412 GSocketError
_GSocket_Input_Timeout(GSocket
*socket
)
1414 if ( !socket
->m_non_blocking
)
1416 UnsignedWide now
, start
;
1417 short formerTakesEvents
= socket
->m_takesEvents
;
1418 Microseconds(&start
);
1420 socket
->m_takesEvents
= FALSE
;
1422 while( (now
.hi
* 4294967296.0 + now
.lo
) - (start
.hi
* 4294967296.0 + start
.lo
) < socket
->m_timeout
* 1000.0 )
1426 state
= OTGetEndpointState(socket
->m_endpoint
);
1428 OTCountDataBytes( socket
->m_endpoint
, &sz
) ;
1429 if ( state
== T_INCON
|| sz
> 0 )
1431 socket
->m_takesEvents
= formerTakesEvents
;
1432 return GSOCK_NOERROR
;
1436 socket
->m_takesEvents
= formerTakesEvents
;
1437 socket
->m_error
= GSOCK_TIMEDOUT
;
1438 return GSOCK_TIMEDOUT
;
1440 return GSOCK_NOERROR
;
1443 /* _GSocket_Output_Timeout:
1444 * For blocking sockets, wait until data can be sent without
1445 * blocking or until timeout ellapses.
1447 GSocketError
_GSocket_Output_Timeout(GSocket
*socket
)
1449 if ( !socket
->m_non_blocking
)
1451 UnsignedWide now
, start
;
1452 short formerTakesEvents
= socket
->m_takesEvents
;
1453 Microseconds(&start
);
1455 socket
->m_takesEvents
= FALSE
;
1457 while( (now
.hi
* 4294967296.0 + now
.lo
) - (start
.hi
* 4294967296.0 + start
.lo
) < socket
->m_timeout
* 1000.0 )
1460 state
= OTGetEndpointState(socket
->m_endpoint
);
1462 if ( state
== T_DATAXFER
|| state
== T_INREL
)
1464 socket
->m_takesEvents
= formerTakesEvents
;
1465 return GSOCK_NOERROR
;
1469 socket
->m_takesEvents
= formerTakesEvents
;
1470 socket
->m_error
= GSOCK_TIMEDOUT
;
1471 return GSOCK_TIMEDOUT
;
1473 return GSOCK_NOERROR
;
1477 * There is data to be read in the input buffer. If, after a read
1478 * operation, there is still data available, the callback function will
1481 * The socket is available for writing. That is, the next write call
1482 * won't block. This event is generated only once, when the connection is
1483 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
1484 * when the output buffer empties again. This means that the app should
1485 * assume that it can write since the first OUTPUT event, and no more
1486 * OUTPUT events will be generated unless an error occurs.
1488 * Connection succesfully established, for client sockets, or incoming
1489 * client connection, for server sockets. Wait for this event (also watch
1490 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
1492 * The connection is lost (or a connection request failed); this could
1493 * be due to a failure, or due to the peer closing it gracefully.
1496 void _GSocket_Internal_Proc(unsigned long e
, void* d
)
1499 GSocket
* socket
= (GSocket
*) d
;
1500 OTEventCode ev
= (OTEventCode
) e
;
1502 GSocketEvent event2
;
1503 GSocketCallback cback
;
1505 GSocketCallback cback2
;
1510 event
= GSOCK_MAX_EVENT
;
1511 event2
= GSOCK_MAX_EVENT
;
1517 /* Check that the socket still exists (it has not been
1518 * destroyed) and for safety, check that the m_endpoint field
1519 * is what we expect it to be.
1521 if ((socket
!= NULL
) && (socket
->m_takesEvents
))
1526 event
= GSOCK_CONNECTION
;
1529 event
= GSOCK_CONNECTION
;
1530 event2
= GSOCK_OUTPUT
;
1534 retCall
.addr
.buf
= NULL
;
1535 retCall
.addr
.maxlen
= 0;
1536 retCall
.opt
.buf
= NULL
;
1537 retCall
.opt
.maxlen
= 0;
1538 retCall
.udata
.buf
= NULL
;
1539 retCall
.udata
.maxlen
= 0;
1540 OTRcvConnect( socket
->m_endpoint
, &retCall
) ;
1544 event
= GSOCK_LOST
;
1548 event
= GSOCK_OUTPUT
;
1551 event
= GSOCK_INPUT
;
1554 event
= GSOCK_INPUT
;
1557 if (event
!= GSOCK_MAX_EVENT
)
1559 cback
= socket
->m_cbacks
[event
];
1560 data
= socket
->m_data
[event
];
1562 if (event
== GSOCK_LOST
)
1563 socket
->m_detected
= GSOCK_LOST_FLAG
;
1565 socket
->m_detected
|= (1 << event
);
1567 if (event2
!= GSOCK_MAX_EVENT
)
1569 cback2
= socket
->m_cbacks
[event2
];
1570 data2
= socket
->m_data
[event2
];
1572 if (event2
== GSOCK_LOST
)
1573 socket
->m_detected
= GSOCK_LOST_FLAG
;
1575 socket
->m_detected
|= (1 << event2
);
1579 /* OK, we can now leave the critical section because we have
1580 * already obtained the callback address (we make no further
1581 * accesses to socket->whatever). However, the app should
1582 * be prepared to handle events from a socket that has just
1587 (cback
)(socket
, event
, data
);
1589 (cback2
)(socket
, event2
, data2
);
1593 #endif /* wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__) */