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__)
22 #define OTUNIXERRORS 1
24 #include <CarbonCore/CarbonCore.h>
25 #include <OT/OpenTransport.h>
26 #include <OT/OpenTransportProviders.h>
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
126 opt
->name
= IP_REUSEADDR
;
127 opt
->len
= kOTFourByteOptionSize
;
129 *(UInt32
*)opt
->value
= enableReuseIPMode
; // set the desired option level, true or false
131 err
= OTOptionManagement(ep
, &req
, &ret
);
133 // if no error then return the option status value
134 if (err
== kOTNoError
)
136 if (opt
->status
!= T_SUCCESS
)
146 pascal void OTInetEventHandler(void*s
, OTEventCode event
, OTResult
, void *cookie
) ;
147 pascal void OTInetEventHandler(void*s
, OTEventCode event
, OTResult result
, void *cookie
)
150 GSocket
* sock
= (GSocket
*) s
;
152 if ( event
== kOTSyncIdleEvent
)
160 wxMacAddEvent( sock
->m_mac_events
, _GSocket_Internal_Proc
, event
, s
, wakeUp
) ;
166 static void SetDefaultEndpointModes(EndpointRef ep
, void *data
)
167 // This routine sets the supplied endpoint into the default
168 // mode used in this application. The specifics are:
169 // blocking, synchronous, and using synch idle events with
170 // the standard YieldingNotifier.
172 OSStatus junk
= kOTNoError
;
173 OTAssert ("SetDefaultEndpointModes:invalid ref", ep
!= kOTInvalidEndpointRef
) ;
174 junk
= OTSetAsynchronous(ep
);
175 OTAssert("SetDefaultEndpointModes: Could not set asynchronous", junk
== noErr
);
177 junk = OTSetBlocking(ep);
178 OTAssert("SetDefaultEndpointModes: Could not set blocking", junk == noErr);
179 junk = OTSetSynchronous(ep);
180 OTAssert("SetDefaultEndpointModes: Could not set synchronous", junk == noErr);
181 junk = OTSetBlocking(ep);
182 OTAssert("SetDefaultEndpointModes: Could not set blocking", junk == noErr);
184 junk
= OTInstallNotifier(ep
, OTInetEventHandler
, data
);
185 OTAssert("SetDefaultEndpointModes: Could not install notifier", junk
== noErr
);
187 junk = OTUseSyncIdleEvents(ep, true);
188 OTAssert("SetDefaultEndpointModes: Could not use sync idle events", junk == noErr);
192 /* Global initialisers */
198 InitOpenTransportInContext( kInitOTForApplicationMask
, NULL
) ;
200 InitOpenTransport() ;
202 gInetSvcRef
= OTOpenInternetServices(kDefaultInternetServicesPath
, NULL
, &err
);
203 if ( gInetSvcRef
== NULL
|| err
!= kOTNoError
)
205 OTAssert("Could not open Inet Services", err
== noErr
);
211 void GSocket_Cleanup()
213 if ( gInetSvcRef
!= NULL
)
214 OTCloseProvider( gInetSvcRef
);
216 CloseOpenTransportInContext( NULL
) ;
218 CloseOpenTransport() ;
222 /* Constructors / Destructors for GSocket */
224 GSocket
*GSocket_new()
229 socket
= (GSocket
*)malloc(sizeof(GSocket
));
234 socket
->m_endpoint
= NULL
;
235 for (i
=0;i
<GSOCK_MAX_EVENT
;i
++)
237 socket
->m_cbacks
[i
] = NULL
;
239 socket
->m_detected
= 0;
240 socket
->m_local
= NULL
;
241 socket
->m_peer
= NULL
;
242 socket
->m_error
= GSOCK_NOERROR
;
243 socket
->m_server
= FALSE
;
244 socket
->m_stream
= TRUE
;
245 socket
->m_non_blocking
= FALSE
;
246 socket
->m_timeout
= 10*60*1000;
247 /* 10 minutes * 60 sec * 1000 millisec */
248 socket
->m_takesEvents
= TRUE
;
249 socket
->m_mac_events
= wxMacGetNotifierTable() ;
253 void GSocket_destroy(GSocket
*socket
)
255 assert(socket
!= NULL
);
257 /* Check that the socket is really shutdowned */
258 if (socket
->m_endpoint
!= kOTInvalidEndpointRef
)
259 GSocket_Shutdown(socket
);
262 /* Destroy private addresses */
264 GAddress_destroy(socket
->m_local
);
267 GAddress_destroy(socket
->m_peer
);
269 /* Destroy the socket itself */
274 * Disallow further read/write operations on this socket, close
275 * the fd and disable all callbacks.
277 void GSocket_Shutdown(GSocket
*socket
)
282 assert(socket
!= NULL
);
284 /* If socket has been created, shutdown it */
285 if (socket
->m_endpoint
!= kOTInvalidEndpointRef
)
287 err
= OTSndOrderlyDisconnect( socket
->m_endpoint
) ;
288 if ( err
!= kOTNoError
)
292 err
= OTRcvOrderlyDisconnect( socket
->m_endpoint
) ;
293 err
= OTUnbind( socket
->m_endpoint
) ;
294 err
= OTCloseProvider( socket
->m_endpoint
) ;
295 socket
->m_endpoint
= kOTInvalidEndpointRef
;
298 /* Disable GUI callbacks */
299 for (evt
= 0; evt
< GSOCK_MAX_EVENT
; evt
++)
300 socket
->m_cbacks
[evt
] = NULL
;
302 socket
->m_detected
= 0;
303 _GSocket_Disable_Events(socket
);
304 wxMacRemoveAllNotifiersForData( wxMacGetNotifierTable() , socket
) ;
308 /* Address handling */
314 * Set or get the local or peer address for this socket. The 'set'
315 * functions return GSOCK_NOERROR on success, an error code otherwise.
316 * The 'get' functions return a pointer to a GAddress object on success,
317 * or NULL otherwise, in which case they set the error code of the
318 * corresponding GSocket.
321 * GSOCK_INVSOCK - the socket is not valid.
322 * GSOCK_INVADDR - the address is not valid.
324 GSocketError
GSocket_SetLocal(GSocket
*socket
, GAddress
*address
)
326 assert(socket
!= NULL
);
328 /* the socket must be initialized, or it must be a server */
329 if ((socket
->m_endpoint
!= kOTInvalidEndpointRef
&& !socket
->m_server
))
331 socket
->m_error
= GSOCK_INVSOCK
;
332 return GSOCK_INVSOCK
;
336 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
338 socket
->m_error
= GSOCK_INVADDR
;
339 return GSOCK_INVADDR
;
343 GAddress_destroy(socket
->m_local
);
345 socket
->m_local
= GAddress_copy(address
);
347 return GSOCK_NOERROR
;
350 GSocketError
GSocket_SetPeer(GSocket
*socket
, GAddress
*address
)
352 assert(socket
!= NULL
);
355 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
357 socket
->m_error
= GSOCK_INVADDR
;
358 return GSOCK_INVADDR
;
362 GAddress_destroy(socket
->m_peer
);
364 socket
->m_peer
= GAddress_copy(address
);
366 return GSOCK_NOERROR
;
369 GAddress
*GSocket_GetLocal(GSocket
*socket
)
371 GAddress
*address
= NULL
;
375 assert(socket
!= NULL
);
377 /* try to get it from the m_local var first */
379 return GAddress_copy(socket
->m_local
);
381 /* else, if the socket is initialized, try getsockname */
382 if (socket
->m_endpoint
== kOTInvalidEndpointRef
)
384 socket
->m_error
= GSOCK_INVSOCK
;
389 /* we do not support multihoming with this code at the moment
390 OTGetProtAddress will have to be used then - but we don't have a handy
391 method to use right now
394 InetInterfaceInfo info
;
395 OTInetGetInterfaceInfo(&info
, kDefaultInetInterface
);
396 loc
.fHost
= info
.fAddress
;
398 loc
.fAddressType
= AF_INET
;
401 /* got a valid address from getsockname, create a GAddress object */
402 address
= GAddress_new();
405 socket
->m_error
= GSOCK_MEMERR
;
409 err
= _GAddress_translate_from(address
, &loc
);
410 if (err
!= GSOCK_NOERROR
)
412 GAddress_destroy(address
);
413 socket
->m_error
= err
;
420 GAddress
*GSocket_GetPeer(GSocket
*socket
)
422 assert(socket
!= NULL
);
424 /* try to get it from the m_peer var */
426 return GAddress_copy(socket
->m_peer
);
431 /* Server specific parts */
433 /* GSocket_SetServer:
434 * Sets up this socket as a server. The local address must have been
435 * set with GSocket_SetLocal() before GSocket_SetServer() is called.
436 * Returns GSOCK_NOERROR on success, one of the following otherwise:
439 * GSOCK_INVSOCK - the socket is in use.
440 * GSOCK_INVADDR - the local address has not been set.
441 * GSOCK_IOERR - low-level error.
443 GSocketError
GSocket_SetServer(GSocket
*sck
)
450 /* must not be in use */
451 if (sck
->m_endpoint
!= kOTInvalidEndpointRef
)
453 sck
->m_error
= GSOCK_INVSOCK
;
454 return GSOCK_INVSOCK
;
457 /* the local addr must have been set */
460 sck
->m_error
= GSOCK_INVADDR
;
461 return GSOCK_INVADDR
;
464 /* Initialize all fields */
465 sck
->m_stream
= TRUE
;
466 sck
->m_server
= TRUE
;
467 sck
->m_oriented
= TRUE
;
471 /* Create the socket */
472 sck
->m_endpoint
= socket(sck
->m_local
->m_realfamily
, SOCK_STREAM
, 0);
473 socket_set_ref( sck
->m_endpoint
, (unsigned long) &gMacNetEvents
, (unsigned long) sck
) ;
474 if (sck
->m_endpoint
== kOTInvalidEndpointRef
)
476 sck
->m_error
= GSOCK_IOERR
;
480 ioctl(sck
->m_endpoint
, FIONBIO
, &arg
);
481 _GSocket_Enable_Events(sck
);
483 /* Bind to the local address,
484 * retrieve the actual address bound,
485 * and listen up to 5 connections.
487 if ((bind(sck
->m_endpoint
, sck
->m_local
->m_addr
, sck
->m_local
->m_len
) != 0) ||
488 (getsockname(sck
->m_endpoint
,
489 sck
->m_local
->m_addr
,
490 (SOCKLEN_T
*) &sck
->m_local
->m_len
) != 0) ||
491 (listen(sck
->m_endpoint
, 5) != 0))
493 close(sck
->m_endpoint
);
494 sck
->m_endpoint
= -1;
495 sck
->m_error
= GSOCK_IOERR
;
499 return GSOCK_NOERROR
;
502 /* GSocket_WaitConnection:
503 * Waits for an incoming client connection. Returns a pointer to
504 * a GSocket object, or NULL if there was an error, in which case
505 * the last error field will be updated for the calling GSocket.
507 * Error codes (set in the calling GSocket)
508 * GSOCK_INVSOCK - the socket is not valid or not a server.
509 * GSOCK_TIMEDOUT - timeout, no incoming connections.
510 * GSOCK_WOULDBLOCK - the call would block and the socket is nonblocking.
511 * GSOCK_MEMERR - couldn't allocate memory.
512 * GSOCK_IOERR - low-level error.
514 GSocket
*GSocket_WaitConnection(GSocket
*socket
)
516 GSocket
*connection
= NULL
;
521 assert(socket
!= NULL
);
523 /* Reenable CONNECTION events */
524 socket
->m_detected
&= ~GSOCK_CONNECTION_FLAG
;
526 /* If the socket has already been created, we exit immediately */
527 if (socket
->m_endpoint
== kOTInvalidEndpointRef
|| !socket
->m_server
)
529 socket
->m_error
= GSOCK_INVSOCK
;
533 /* Create a GSocket object for the new connection */
534 connection
= GSocket_new();
538 socket
->m_error
= GSOCK_MEMERR
;
542 /* Wait for a connection (with timeout) */
543 if (_GSocket_Input_Timeout(socket
) == GSOCK_TIMEDOUT
)
545 GSocket_destroy(connection
);
546 /* socket->m_error set by _GSocket_Input_Timeout */
552 connection
->m_endpoint
= accept(socket
->m_endpoint
, &from
, (SOCKLEN_T
*) &fromlen
);
555 if (connection
->m_endpoint
== kOTInvalidEndpointRef
)
557 if (errno
== EWOULDBLOCK
)
558 socket
->m_error
= GSOCK_WOULDBLOCK
;
560 socket
->m_error
= GSOCK_IOERR
;
562 GSocket_destroy(connection
);
566 /* Initialize all fields */
567 connection
->m_server
= FALSE
;
568 connection
->m_stream
= TRUE
;
569 connection
->m_oriented
= TRUE
;
571 /* Setup the peer address field */
572 connection
->m_peer
= GAddress_new();
573 if (!connection
->m_peer
)
575 GSocket_destroy(connection
);
576 socket
->m_error
= GSOCK_MEMERR
;
581 err
= _GAddress_translate_from(connection
->m_peer
, &from
, fromlen
);
582 if (err
!= GSOCK_NOERROR
)
584 GAddress_destroy(connection
->m_peer
);
585 GSocket_destroy(connection
);
586 socket
->m_error
= err
;
590 ioctl(connection
->m_endpoint
, FIONBIO
, &arg
);
592 _GSocket_Enable_Events(connection
);
597 /* Datagram sockets */
599 /* GSocket_SetNonOriented:
600 * Sets up this socket as a non-connection oriented (datagram) socket.
601 * Before using this function, the local address must have been set
602 * with GSocket_SetLocal(), or the call will fail. Returns GSOCK_NOERROR
603 * on success, or one of the following otherwise.
606 * GSOCK_INVSOCK - the socket is in use.
607 * GSOCK_INVADDR - the local address has not been set.
608 * GSOCK_IOERR - low-level error.
610 GSocketError
GSocket_SetNonOriented(GSocket
*sck
)
616 if (sck
->m_endpoint
!= kOTInvalidEndpointRef
)
618 sck
->m_error
= GSOCK_INVSOCK
;
619 return GSOCK_INVSOCK
;
624 sck
->m_error
= GSOCK_INVADDR
;
625 return GSOCK_INVADDR
;
628 /* Initialize all fields */
629 sck
->m_stream
= FALSE
;
630 sck
->m_server
= FALSE
;
631 sck
->m_oriented
= FALSE
;
633 /* Create the socket */
637 sck
->m_endpoint
= socket(sck
->m_local
->m_realfamily
, SOCK_DGRAM
, 0);
638 socket_set_ref( sck
->m_endpoint
, (unsigned long) &gMacNetEvents
, (unsigned long) sck
) ;
640 if (sck
->m_endpoint
== kOTInvalidEndpointRef
)
642 sck
->m_error
= GSOCK_IOERR
;
648 ioctl(sck
->m_endpoint
, FIONBIO
, &arg
);
650 _GSocket_Enable_Events(sck
);
652 /* Bind to the local address,
653 * and retrieve the actual address bound.
657 if ((bind(sck
->m_endpoint
, sck
->m_local
->m_addr
, sck
->m_local
->m_len
) != 0) ||
658 (getsockname(sck
->m_endpoint
,
659 sck
->m_local
->m_addr
,
660 (SOCKLEN_T
*) &sck
->m_local
->m_len
) != 0))
662 close(sck
->m_endpoint
);
663 sck
->m_endpoint
= -1;
664 sck
->m_error
= GSOCK_IOERR
;
668 return GSOCK_NOERROR
;
671 /* Client specific parts */
674 * For stream (connection oriented) sockets, GSocket_Connect() tries
675 * to establish a client connection to a server using the peer address
676 * as established with GSocket_SetPeer(). Returns GSOCK_NOERROR if the
677 * connection has been succesfully established, or one of the error
678 * codes listed below. Note that for nonblocking sockets, a return
679 * value of GSOCK_WOULDBLOCK doesn't mean a failure. The connection
680 * request can be completed later; you should use GSocket_Select()
681 * to poll for GSOCK_CONNECTION | GSOCK_LOST, or wait for the
682 * corresponding asynchronous events.
684 * For datagram (non connection oriented) sockets, GSocket_Connect()
685 * just sets the peer address established with GSocket_SetPeer() as
686 * default destination.
689 * GSOCK_INVSOCK - the socket is in use or not valid.
690 * GSOCK_INVADDR - the peer address has not been established.
691 * GSOCK_TIMEDOUT - timeout, the connection failed.
692 * GSOCK_WOULDBLOCK - connection in progress (nonblocking sockets only)
693 * GSOCK_MEMERR - couldn't allocate memory.
694 * GSOCK_IOERR - low-level error.
696 GSocketError
GSocket_Connect(GSocket
*sck
, GSocketStream stream
)
703 OSStatus err
= kOTNoError
;
708 /* Enable CONNECTION events (needed for nonblocking connections) */
709 sck
->m_detected
&= ~GSOCK_CONNECTION_FLAG
;
711 if (sck
->m_endpoint
!= kOTInvalidEndpointRef
)
713 sck
->m_error
= GSOCK_INVSOCK
;
714 return GSOCK_INVSOCK
;
719 sck
->m_error
= GSOCK_INVADDR
;
720 return GSOCK_INVADDR
;
723 /* Streamed or dgram socket? */
724 sck
->m_stream
= (stream
== GSOCK_STREAMED
);
725 sck
->m_oriented
= TRUE
;
726 sck
->m_server
= FALSE
;
728 /* Create the socket */
731 OTOpenEndpointInContext( OTCreateConfiguration( kTCPName
) , 0 , &info
, &err
, NULL
) ;
734 OTOpenEndpoint( OTCreateConfiguration( kTCPName
) , 0 , &info
, &err
) ;
736 if ( sck
->m_endpoint
== kOTInvalidEndpointRef
|| err
!= kOTNoError
)
738 sck
->m_endpoint
= kOTInvalidEndpointRef
;
739 sck
->m_error
= GSOCK_IOERR
;
742 err
= OTBind( sck
->m_endpoint
, nil
, nil
) ;
743 if ( err
!= kOTNoError
)
747 SetDefaultEndpointModes( sck
->m_endpoint
, sck
) ;
750 ioctl(sck
->m_endpoint
, FIONBIO
, &arg
);
752 _GSocket_Enable_Events(sck
);
754 _GAddress_translate_to( sck
->m_peer
, &addr
) ;
755 memset( &peer
, 0 , sizeof( TCall
) ) ;
756 peer
.addr
.len
= sizeof( InetAddress
) ;
757 peer
.addr
.buf
= (unsigned char*) &addr
;
758 err
= OTConnect( sck
->m_endpoint
, &peer
, nil
) ;
761 /* If connect failed with EINPROGRESS and the GSocket object
762 * is in blocking mode, we select() for the specified timeout
763 * checking for writability to see if the connection request
767 if ((err
== kOTNoDataErr
) && (!sck
->m_non_blocking
))
769 if (_GSocket_Output_Timeout(sck
) == GSOCK_TIMEDOUT
)
771 OTSndOrderlyDisconnect( sck
->m_endpoint
) ;
772 sck
->m_endpoint
= kOTInvalidEndpointRef
;
773 /* sck->m_error is set in _GSocket_Output_Timeout */
774 return GSOCK_TIMEDOUT
;
780 SOCKLEN_T len = sizeof(error);
782 getsockopt(sck->m_endpoint, SOL_SOCKET, SO_ERROR, (void*) &error, &len);
786 return GSOCK_NOERROR
;
790 /* If connect failed with EINPROGRESS and the GSocket object
791 * is set to nonblocking, we set m_error to GSOCK_WOULDBLOCK
792 * (and return GSOCK_WOULDBLOCK) but we don't close the socket;
793 * this way if the connection completes, a GSOCK_CONNECTION
794 * event will be generated, if enabled.
796 if ((err
== kOTNoDataErr
) && (sck
->m_non_blocking
))
798 sck
->m_error
= GSOCK_WOULDBLOCK
;
799 return GSOCK_WOULDBLOCK
;
802 /* If connect failed with an error other than EINPROGRESS,
803 * then the call to GSocket_Connect has failed.
805 OTSndOrderlyDisconnect( sck
->m_endpoint
) ;
807 sck
->m_endpoint
= kOTInvalidEndpointRef
;
808 sck
->m_error
= GSOCK_IOERR
;
811 // OTInetEventHandler(sck, T_CONNECT , kOTNoError , NULL ) ;
812 return GSOCK_NOERROR
;
817 /* Like recv(), send(), ... */
818 int GSocket_Read(GSocket
*socket
, char *buffer
, int size
)
822 assert(socket
!= NULL
);
824 /* Reenable INPUT events */
825 socket
->m_detected
&= ~GSOCK_INPUT_FLAG
;
827 if (socket
->m_endpoint
== kOTInvalidEndpointRef
|| socket
->m_server
)
829 socket
->m_error
= GSOCK_INVSOCK
;
833 /* If the socket is blocking, wait for data (with a timeout) */
834 if (_GSocket_Input_Timeout(socket
) == GSOCK_TIMEDOUT
)
838 if (socket
->m_stream
)
839 ret
= _GSocket_Recv_Stream(socket
, buffer
, size
);
841 ret
= _GSocket_Recv_Dgram(socket
, buffer
, size
);
845 if (errno
== EWOULDBLOCK
)
846 socket
->m_error
= GSOCK_WOULDBLOCK
;
848 socket
->m_error
= GSOCK_IOERR
;
854 int GSocket_Write(GSocket
*socket
, const char *buffer
, int size
)
858 assert(socket
!= NULL
);
860 if (socket
->m_endpoint
== kOTInvalidEndpointRef
|| socket
->m_server
)
862 socket
->m_error
= GSOCK_INVSOCK
;
866 /* If the socket is blocking, wait for writability (with a timeout) */
867 if (_GSocket_Output_Timeout(socket
) == GSOCK_TIMEDOUT
)
871 if (socket
->m_stream
)
872 ret
= _GSocket_Send_Stream(socket
, buffer
, size
);
874 ret
= _GSocket_Send_Dgram(socket
, buffer
, size
);
878 if (errno
== EWOULDBLOCK
)
879 socket
->m_error
= GSOCK_WOULDBLOCK
;
881 socket
->m_error
= GSOCK_IOERR
;
883 /* Only reenable OUTPUT events after an error (just like WSAAsyncSelect
884 * in MSW). Once the first OUTPUT event is received, users can assume
885 * that the socket is writable until a read operation fails. Only then
886 * will further OUTPUT events be posted.
888 socket
->m_detected
&= ~GSOCK_OUTPUT_FLAG
;
896 * Polls the socket to determine its status. This function will
897 * check for the events specified in the 'flags' parameter, and
898 * it will return a mask indicating which operations can be
899 * performed. This function won't block, regardless of the
900 * mode (blocking | nonblocking) of the socket.
902 GSocketEventFlags
GSocket_Select(GSocket
*socket
, GSocketEventFlags flags
)
905 assert(socket
!= NULL
);
906 wxMacProcessNotifierEvents() ;
908 state = OTGetEndpointState(socket->m_endpoint);
910 if ( ( flags & GSOCK_INPUT_FLAG ) && ! ( socket->m_detected & GSOCK_INPUT_FLAG ) )
913 OTCountDataBytes( socket->m_endpoint , &sz ) ;
914 if ( state == T_INCON || sz > 0 )
916 socket->m_detected |= GSOCK_INPUT_FLAG ;
917 (socket->m_cbacks[GSOCK_INPUT])(socket, GSOCK_INPUT, socket->m_data[GSOCK_INPUT]);
920 if ( ( flags & GSOCK_INPUT_FLAG ) && ! ( socket->m_detected & GSOCK_OUTPUT_FLAG ) )
922 if ( state == T_DATAXFER || state == T_INREL )
924 socket->m_detected |=GSOCK_OUTPUT_FLAG ;
925 (socket->m_cbacks[GSOCK_OUTPUT])(socket, GSOCK_OUTPUT, socket->m_data[GSOCK_OUTPUT]);
929 return ( flags
& socket
->m_detected
) ;
934 /* GSocket_SetNonBlocking:
935 * Sets the socket to non-blocking mode. All IO calls will return
938 void GSocket_SetNonBlocking(GSocket
*socket
, int non_block
)
940 assert(socket
!= NULL
);
942 socket
->m_non_blocking
= non_block
;
945 /* GSocket_SetTimeout:
946 * Sets the timeout for blocking calls. Time is expressed in
949 void GSocket_SetTimeout(GSocket
*socket
, unsigned long millisec
)
951 assert(socket
!= NULL
);
953 socket
->m_timeout
= millisec
;
957 * Returns the last error occured for this socket. Note that successful
958 * operations do not clear this back to GSOCK_NOERROR, so use it only
961 GSocketError
GSocket_GetError(GSocket
*socket
)
963 assert(socket
!= NULL
);
965 return socket
->m_error
;
971 * There is data to be read in the input buffer. If, after a read
972 * operation, there is still data available, the callback function will
975 * The socket is available for writing. That is, the next write call
976 * won't block. This event is generated only once, when the connection is
977 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
978 * when the output buffer empties again. This means that the app should
979 * assume that it can write since the first OUTPUT event, and no more
980 * OUTPUT events will be generated unless an error occurs.
982 * Connection succesfully established, for client sockets, or incoming
983 * client connection, for server sockets. Wait for this event (also watch
984 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
986 * The connection is lost (or a connection request failed); this could
987 * be due to a failure, or due to the peer closing it gracefully.
990 /* GSocket_SetCallback:
991 * Enables the callbacks specified by 'flags'. Note that 'flags'
992 * may be a combination of flags OR'ed toghether, so the same
993 * callback function can be made to accept different events.
994 * The callback function must have the following prototype:
996 * void function(GSocket *socket, GSocketEvent event, char *cdata)
998 void GSocket_SetCallback(GSocket
*socket
, GSocketEventFlags flags
,
999 GSocketCallback callback
, char *cdata
)
1003 assert(socket
!= NULL
);
1005 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1007 if ((flags
& (1 << count
)) != 0)
1009 socket
->m_cbacks
[count
] = callback
;
1010 socket
->m_data
[count
] = cdata
;
1015 /* GSocket_UnsetCallback:
1016 * Disables all callbacks specified by 'flags', which may be a
1017 * combination of flags OR'ed toghether.
1019 void GSocket_UnsetCallback(GSocket
*socket
, GSocketEventFlags flags
)
1023 assert(socket
!= NULL
);
1025 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1027 if ((flags
& (1 << count
)) != 0)
1029 socket
->m_cbacks
[count
] = NULL
;
1030 socket
->m_data
[count
] = NULL
;
1036 #define CALL_CALLBACK(socket, event) { \
1037 _GSocket_Disable(socket, event); \
1038 if (socket->m_cbacks[event]) \
1039 socket->m_cbacks[event](socket, event, socket->m_data[event]); \
1042 int _GSocket_Recv_Stream(GSocket
*socket
, char *buffer
, int size
)
1048 OTCountDataBytes( socket
->m_endpoint
, &sz
) ;
1049 res
= OTRcv( socket
->m_endpoint
, buffer
, size
, &flags
) ;
1055 // we simulate another read event if there are still bytes
1056 if ( socket
->m_takesEvents
)
1059 OTCountDataBytes( socket
->m_endpoint
, &sz
) ;
1062 socket
->m_detected
|= GSOCK_INPUT_FLAG
;
1063 (socket
->m_cbacks
[GSOCK_INPUT
])(socket
, GSOCK_INPUT
, socket
->m_data
[GSOCK_INPUT
]);
1069 int _GSocket_Recv_Dgram(GSocket
*socket
, char *buffer
, int size
)
1074 struct sockaddr from
;
1075 SOCKLEN_T fromlen
= sizeof(from
);
1078 fromlen
= sizeof(from
);
1080 ret
= recvfrom(socket
->m_endpoint
, buffer
, size
, 0, &from
, (SOCKLEN_T
*) &fromlen
);
1085 /* Translate a system address into a GSocket address */
1086 if (!socket
->m_peer
)
1088 socket
->m_peer
= GAddress_new();
1089 if (!socket
->m_peer
)
1091 socket
->m_error
= GSOCK_MEMERR
;
1095 err
= _GAddress_translate_from(socket
->m_peer
, &from
, fromlen
);
1096 if (err
!= GSOCK_NOERROR
)
1098 GAddress_destroy(socket
->m_peer
);
1099 socket
->m_peer
= NULL
;
1100 socket
->m_error
= err
;
1107 int _GSocket_Send_Stream(GSocket
*socket
, const char *buffer
, int size
)
1112 res
= OTSnd( socket
->m_endpoint
, (void*) buffer
, size
, flags
) ;
1116 int _GSocket_Send_Dgram(GSocket
*socket
, const char *buffer
, int size
)
1121 struct sockaddr
*addr
;
1125 if (!socket
->m_peer
)
1127 socket
->m_error
= GSOCK_INVADDR
;
1131 err
= _GAddress_translate_to(socket
->m_peer
, &addr
, &len
);
1132 if (err
!= GSOCK_NOERROR
)
1134 socket
->m_error
= err
;
1138 ret
= sendto(socket
->m_endpoint
, buffer
, size
, 0, addr
, len
);
1140 /* Frees memory allocated from _GAddress_translate_to */
1148 * -------------------------------------------------------------------------
1150 * -------------------------------------------------------------------------
1153 /* CHECK_ADDRESS verifies that the current family is either GSOCK_NOFAMILY
1154 * or GSOCK_*family*, and if it is GSOCK_NOFAMILY, it initalizes address
1155 * to be a GSOCK_*family*. In other cases, it returns GSOCK_INVADDR.
1157 #define CHECK_ADDRESS(address, family, retval) \
1159 if (address->m_family == GSOCK_NOFAMILY) \
1160 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1161 return address->m_error; \
1162 if (address->m_family != GSOCK_##family) \
1164 address->m_error = GSOCK_INVADDR; \
1169 GAddress
*GAddress_new()
1173 if ((address
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1176 address
->m_family
= GSOCK_NOFAMILY
;
1177 address
->m_host
= INADDR_NONE
;
1178 address
->m_port
= 0 ;
1183 GAddress
*GAddress_copy(GAddress
*address
)
1187 assert(address
!= NULL
);
1189 if ((addr2
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1192 memcpy(addr2
, address
, sizeof(GAddress
));
1196 void GAddress_destroy(GAddress
*address
)
1198 assert(address
!= NULL
);
1203 void GAddress_SetFamily(GAddress
*address
, GAddressType type
)
1205 assert(address
!= NULL
);
1207 address
->m_family
= type
;
1210 GAddressType
GAddress_GetFamily(GAddress
*address
)
1212 assert(address
!= NULL
);
1214 return address
->m_family
;
1217 GSocketError
_GAddress_translate_from(GAddress
*address
,
1220 switch (addr
->fAddressType
)
1223 address
->m_family
= GSOCK_INET
;
1227 address
->m_family
= GSOCK_INET6
;
1232 address
->m_error
= GSOCK_INVOP
;
1236 address
->m_host
= addr
->fHost
;
1237 address
->m_port
= addr
->fPort
;
1238 return GSOCK_NOERROR
;
1241 GSocketError
_GAddress_translate_to(GAddress
*address
,
1244 memset(addr
, 0 , sizeof(struct InetAddress
));
1245 OTInitInetAddress( addr
, address
->m_port
, address
->m_host
) ;
1246 return GSOCK_NOERROR
;
1250 * -------------------------------------------------------------------------
1251 * Internet address family
1252 * -------------------------------------------------------------------------
1255 GSocketError
_GAddress_Init_INET(GAddress
*address
)
1257 address
->m_family
= GSOCK_INET
;
1258 address
->m_host
= kOTAnyInetAddress
;
1260 return GSOCK_NOERROR
;
1263 GSocketError
GAddress_INET_SetHostName(GAddress
*address
, const char *hostname
)
1265 InetHostInfo hinfo
;
1268 assert(address
!= NULL
);
1270 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1271 ret
= OTInetStringToAddress( gInetSvcRef
, (char*) hostname
, &hinfo
) ;
1272 if ( ret
!= kOTNoError
)
1274 address
->m_host
= INADDR_NONE
;
1275 address
->m_error
= GSOCK_NOHOST
;
1276 return GSOCK_NOHOST
;
1278 address
->m_host
= hinfo
.addrs
[0] ;
1279 return GSOCK_NOERROR
;
1282 GSocketError
GAddress_INET_SetAnyAddress(GAddress
*address
)
1284 return GAddress_INET_SetHostAddress(address
, INADDR_ANY
);
1287 GSocketError
GAddress_INET_SetHostAddress(GAddress
*address
,
1288 unsigned long hostaddr
)
1290 struct in_addr
*addr
;
1292 assert(address
!= NULL
);
1294 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1296 address
->m_host
= hostaddr
;
1298 return GSOCK_NOERROR
;
1301 struct service_entry
1304 unsigned short port
;
1307 typedef struct service_entry service_entry
;
1309 service_entry gServices
[] =
1311 { "http" , 80 , "tcp" }
1314 GSocketError
GAddress_INET_SetPortName(GAddress
*address
, const char *port
,
1315 const char *protocol
)
1320 assert(address
!= NULL
);
1321 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1325 address
->m_error
= GSOCK_INVPORT
;
1326 return GSOCK_INVPORT
;
1328 for ( i
= 0 ; i
< sizeof( gServices
) / sizeof( service_entry
) ; ++i
)
1330 if ( strcmp( port
, gServices
[i
].name
) == 0 )
1332 if ( protocol
== NULL
|| strcmp( protocol
, gServices
[i
].protocol
) )
1334 address
->m_port
= gServices
[i
].port
;
1335 return GSOCK_NOERROR
;
1340 if (isdigit(port
[0]))
1342 address
->m_port
= atoi(port
);
1343 return GSOCK_NOERROR
;
1346 address
->m_error
= GSOCK_INVPORT
;
1347 return GSOCK_INVPORT
;
1350 GSocketError
GAddress_INET_SetPort(GAddress
*address
, unsigned short port
)
1354 assert(address
!= NULL
);
1355 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1356 address
->m_port
= port
;
1358 return GSOCK_NOERROR
;
1361 GSocketError
GAddress_INET_GetHostName(GAddress
*address
, char *hostname
, size_t sbuf
)
1363 InetDomainName name
;
1365 assert(address
!= NULL
);
1366 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1368 OTInetAddressToName( gInetSvcRef
, address
->m_host
, &name
) ;
1369 strncpy( hostname
, name
, sbuf
) ;
1370 return GSOCK_NOERROR
;
1373 unsigned long GAddress_INET_GetHostAddress(GAddress
*address
)
1375 assert(address
!= NULL
);
1376 CHECK_ADDRESS(address
, INET
, 0);
1378 return address
->m_host
;
1381 unsigned short GAddress_INET_GetPort(GAddress
*address
)
1383 assert(address
!= NULL
);
1384 CHECK_ADDRESS(address
, INET
, 0);
1386 return address
->m_port
;
1389 void _GSocket_Enable_Events(GSocket
*socket
)
1391 if ( socket
->m_takesEvents
)
1396 socket
->m_takesEvents
= TRUE
;
1397 state
= OTGetEndpointState(socket
->m_endpoint
);
1401 OTCountDataBytes( socket
->m_endpoint
, &sz
) ;
1402 if ( state
== T_INCON
|| sz
> 0 )
1404 socket
->m_detected
|= GSOCK_INPUT_FLAG
;
1405 (socket
->m_cbacks
[GSOCK_INPUT
])(socket
, GSOCK_INPUT
, socket
->m_data
[GSOCK_INPUT
]);
1409 if ( state
== T_DATAXFER
|| state
== T_INREL
)
1411 socket
->m_detected
|=GSOCK_OUTPUT_FLAG
;
1412 (socket
->m_cbacks
[GSOCK_OUTPUT
])(socket
, GSOCK_OUTPUT
, socket
->m_data
[GSOCK_OUTPUT
]);
1418 void _GSocket_Disable_Events(GSocket
*socket
)
1420 socket
->m_takesEvents
= FALSE
;
1423 /* _GSocket_Input_Timeout:
1424 * For blocking sockets, wait until data is available or
1425 * until timeout ellapses.
1427 GSocketError
_GSocket_Input_Timeout(GSocket
*socket
)
1429 if ( !socket
->m_non_blocking
)
1431 UnsignedWide now
, start
;
1432 short formerTakesEvents
= socket
->m_takesEvents
;
1433 Microseconds(&start
);
1435 socket
->m_takesEvents
= FALSE
;
1437 while( (now
.hi
* 4294967296.0 + now
.lo
) - (start
.hi
* 4294967296.0 + start
.lo
) < socket
->m_timeout
* 1000.0 )
1441 state
= OTGetEndpointState(socket
->m_endpoint
);
1443 OTCountDataBytes( socket
->m_endpoint
, &sz
) ;
1444 if ( state
== T_INCON
|| sz
> 0 )
1446 socket
->m_takesEvents
= formerTakesEvents
;
1447 return GSOCK_NOERROR
;
1451 socket
->m_takesEvents
= formerTakesEvents
;
1452 socket
->m_error
= GSOCK_TIMEDOUT
;
1453 return GSOCK_TIMEDOUT
;
1455 return GSOCK_NOERROR
;
1458 /* _GSocket_Output_Timeout:
1459 * For blocking sockets, wait until data can be sent without
1460 * blocking or until timeout ellapses.
1462 GSocketError
_GSocket_Output_Timeout(GSocket
*socket
)
1464 if ( !socket
->m_non_blocking
)
1466 UnsignedWide now
, start
;
1467 short formerTakesEvents
= socket
->m_takesEvents
;
1468 Microseconds(&start
);
1470 socket
->m_takesEvents
= FALSE
;
1472 while( (now
.hi
* 4294967296.0 + now
.lo
) - (start
.hi
* 4294967296.0 + start
.lo
) < socket
->m_timeout
* 1000.0 )
1475 state
= OTGetEndpointState(socket
->m_endpoint
);
1477 if ( state
== T_DATAXFER
|| state
== T_INREL
)
1479 socket
->m_takesEvents
= formerTakesEvents
;
1480 return GSOCK_NOERROR
;
1484 socket
->m_takesEvents
= formerTakesEvents
;
1485 socket
->m_error
= GSOCK_TIMEDOUT
;
1486 return GSOCK_TIMEDOUT
;
1488 return GSOCK_NOERROR
;
1492 * There is data to be read in the input buffer. If, after a read
1493 * operation, there is still data available, the callback function will
1496 * The socket is available for writing. That is, the next write call
1497 * won't block. This event is generated only once, when the connection is
1498 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
1499 * when the output buffer empties again. This means that the app should
1500 * assume that it can write since the first OUTPUT event, and no more
1501 * OUTPUT events will be generated unless an error occurs.
1503 * Connection succesfully established, for client sockets, or incoming
1504 * client connection, for server sockets. Wait for this event (also watch
1505 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
1507 * The connection is lost (or a connection request failed); this could
1508 * be due to a failure, or due to the peer closing it gracefully.
1511 void _GSocket_Internal_Proc(unsigned long e
, void* d
)
1514 GSocket
* socket
= (GSocket
*) d
;
1515 OTEventCode ev
= (OTEventCode
) e
;
1517 GSocketEvent event2
;
1518 GSocketCallback cback
;
1520 GSocketCallback cback2
;
1525 event
= GSOCK_MAX_EVENT
;
1526 event2
= GSOCK_MAX_EVENT
;
1532 /* Check that the socket still exists (it has not been
1533 * destroyed) and for safety, check that the m_endpoint field
1534 * is what we expect it to be.
1536 if ((socket
!= NULL
) && (socket
->m_takesEvents
))
1541 event
= GSOCK_CONNECTION
;
1544 event
= GSOCK_CONNECTION
;
1545 event2
= GSOCK_OUTPUT
;
1549 retCall
.addr
.buf
= NULL
;
1550 retCall
.addr
.maxlen
= 0;
1551 retCall
.opt
.buf
= NULL
;
1552 retCall
.opt
.maxlen
= 0;
1553 retCall
.udata
.buf
= NULL
;
1554 retCall
.udata
.maxlen
= 0;
1555 OTRcvConnect( socket
->m_endpoint
, &retCall
) ;
1559 event
= GSOCK_LOST
;
1563 event
= GSOCK_OUTPUT
;
1566 event
= GSOCK_INPUT
;
1569 event
= GSOCK_INPUT
;
1572 if (event
!= GSOCK_MAX_EVENT
)
1574 cback
= socket
->m_cbacks
[event
];
1575 data
= socket
->m_data
[event
];
1577 if (event
== GSOCK_LOST
)
1578 socket
->m_detected
= GSOCK_LOST_FLAG
;
1580 socket
->m_detected
|= (1 << event
);
1582 if (event2
!= GSOCK_MAX_EVENT
)
1584 cback2
= socket
->m_cbacks
[event2
];
1585 data2
= socket
->m_data
[event2
];
1587 if (event2
== GSOCK_LOST
)
1588 socket
->m_detected
= GSOCK_LOST_FLAG
;
1590 socket
->m_detected
|= (1 << event2
);
1594 /* OK, we can now leave the critical section because we have
1595 * already obtained the callback address (we make no further
1596 * accesses to socket->whatever). However, the app should
1597 * be prepared to handle events from a socket that has just
1602 (cback
)(socket
, event
, data
);
1604 (cback2
)(socket
, event2
, data2
);
1608 /* Hack added for Mac OS X */
1609 GSocketError
GAddress_UNIX_GetPath(GAddress
*addr
, char *path
, size_t buf
)
1613 GSocketError
GAddress_UNIX_SetPath(GAddress
*addr
, const char *path
)
1617 #endif /* wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__) */