1 /* -------------------------------------------------------------------------
2 * Project: GSocket (Generic Socket) for WX
4 * Authors: Guilhem Lavaux,
5 * Guillermo Rodriguez Garcia <guille@iies.es> (maintainer)
7 * Purpose: GSocket main mac file
9 * -------------------------------------------------------------------------
13 * PLEASE don't put C++ comments here - this is a C source file.
16 #ifndef __GSOCKET_STANDALONE__
18 #include "wx/platform.h"
21 #if wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__)
24 #include <CoreServices/CoreServices.h>
33 #include <MacHeaders.c>
34 #define OTUNIXERRORS 1
35 #include <OpenTransport.h>
36 #include <OpenTransportProviders.h>
37 #include <OpenTptInternet.h>
39 #if TARGET_CARBON && !defined(OTAssert)
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__ */
90 extern pascal void OTDebugStr(const char* str
);
95 InetSvcRef gInetSvcRef
= 0 ;
97 OTNotifyUPP gOTNotifierUPP
= NULL
;
99 OSStatus
DoNegotiateIPReuseAddrOption(EndpointRef ep
, Boolean enableReuseIPMode
);
101 /* Input: ep - endpointref on which to negotiate the option
102 enableReuseIPMode - desired option setting - true/false
103 Return: kOTNoError indicates that the option was successfully negotiated
104 OSStatus is an error if < 0, otherwise, the status field is
107 IMPORTANT NOTE: The endpoint is assumed to be in synchronous more, otherwise
108 this code will not function as desired
112 OSStatus
DoNegotiateIPReuseAddrOption(EndpointRef ep
, Boolean enableReuseIPMode
)
115 UInt8 buf
[kOTFourByteOptionSize
]; // define buffer for fourByte Option size
116 TOption
* opt
; // option ptr to make items easier to access
121 if (!OTIsSynchronous(ep
))
125 opt
= (TOption
*)buf
; // set option ptr to buffer
127 req
.opt
.len
= sizeof(buf
);
128 req
.flags
= T_NEGOTIATE
; // negotiate for option
131 ret
.opt
.maxlen
= kOTFourByteOptionSize
;
133 opt
->level
= INET_IP
; // dealing with an IP Level function
135 opt
->name
= kIP_REUSEADDR
;
137 opt
->name
= IP_REUSEADDR
;
139 opt
->len
= kOTFourByteOptionSize
;
141 *(UInt32
*)opt
->value
= enableReuseIPMode
; // set the desired option level, true or false
143 err
= OTOptionManagement(ep
, &req
, &ret
);
145 // if no error then return the option status value
146 if (err
== kOTNoError
)
148 if (opt
->status
!= T_SUCCESS
)
158 pascal void OTInetEventHandler(void*s
, OTEventCode event
, OTResult
, void *cookie
) ;
159 pascal void OTInetEventHandler(void*s
, OTEventCode event
, OTResult result
, void *cookie
)
162 GSocket
* sock
= (GSocket
*) s
;
164 if ( event
== kOTSyncIdleEvent
)
171 wxMacAddEvent( sock
->m_mac_events
, _GSocket_Internal_Proc
, event
, s
, wakeUp
) ;
177 static void SetDefaultEndpointModes(EndpointRef ep
, void *data
)
178 // This routine sets the supplied endpoint into the default
179 // mode used in this application. The specifics are:
180 // blocking, synchronous, and using synch idle events with
181 // the standard YieldingNotifier.
183 OSStatus junk
= kOTNoError
;
184 OTAssert ("SetDefaultEndpointModes:invalid ref", ep
!= kOTInvalidEndpointRef
) ;
185 junk
= OTSetAsynchronous(ep
);
186 OTAssert("SetDefaultEndpointModes: Could not set asynchronous", junk
== noErr
);
188 junk = OTSetBlocking(ep);
189 OTAssert("SetDefaultEndpointModes: Could not set blocking", junk == noErr);
190 junk = OTSetSynchronous(ep);
191 OTAssert("SetDefaultEndpointModes: Could not set synchronous", junk == noErr);
192 junk = OTSetBlocking(ep);
193 OTAssert("SetDefaultEndpointModes: Could not set blocking", junk == noErr);
195 junk
= OTInstallNotifier(ep
, gOTNotifierUPP
, data
);
196 OTAssert("SetDefaultEndpointModes: Could not install notifier", junk
== noErr
);
198 junk = OTUseSyncIdleEvents(ep, true);
199 OTAssert("SetDefaultEndpointModes: Could not use sync idle events", junk == noErr);
203 /* Global initialisers */
205 void GSocket_SetGUIFunctions(struct GSocketGUIFunctionsTable
*table
)
207 // do nothing, wxMac doesn't have wxBase-GUI separation yet
215 int GSocket_Verify_Inited() ;
216 int GSocket_Verify_Inited()
220 // Marc Newsam: added the clientcontext variable
221 // however, documentation is unclear how this works
222 OTClientContextPtr clientcontext
;
227 InitOpenTransportInContext(kInitOTForApplicationMask
, &clientcontext
);
229 gInetSvcRef
= OTOpenInternetServicesInContext(kDefaultInternetServicesPath
,
230 NULL
, &err
, clientcontext
);
235 InitOpenTransport() ;
237 gInetSvcRef
= OTOpenInternetServices(kDefaultInternetServicesPath
, NULL
, &err
);
239 if ( gInetSvcRef
== NULL
|| err
!= kOTNoError
)
241 OTAssert("Could not open Inet Services", err
== noErr
);
244 gOTNotifierUPP
= NewOTNotifyUPP( OTInetEventHandler
) ;
248 void GSocket_Cleanup()
250 if ( gOTInited
!= 0 )
252 if ( gInetSvcRef
!= NULL
)
253 OTCloseProvider( gInetSvcRef
);
255 CloseOpenTransportInContext( NULL
) ;
257 CloseOpenTransport() ;
259 if ( gOTNotifierUPP
)
260 DisposeOTNotifyUPP( gOTNotifierUPP
) ;
264 /* Constructors / Destructors for GSocket */
266 GSocket
*GSocket_new()
272 if ( GSocket_Verify_Inited() == FALSE
)
275 socket
= (GSocket
*)malloc(sizeof(GSocket
));
280 socket
->m_endpoint
= NULL
;
281 for (i
=0;i
<GSOCK_MAX_EVENT
;i
++)
283 socket
->m_cbacks
[i
] = NULL
;
285 socket
->m_detected
= 0;
286 socket
->m_local
= NULL
;
287 socket
->m_peer
= NULL
;
288 socket
->m_error
= GSOCK_NOERROR
;
289 socket
->m_server
= FALSE
;
290 socket
->m_stream
= TRUE
;
291 socket
->m_non_blocking
= FALSE
;
292 socket
->m_timeout
= 1*1000;
293 /* 10 sec * 1000 millisec */
294 socket
->m_takesEvents
= TRUE
;
295 socket
->m_mac_events
= wxMacGetNotifierTable() ;
299 void GSocket_destroy(GSocket
*socket
)
301 assert(socket
!= NULL
);
303 /* Check that the socket is really shutdowned */
304 if (socket
->m_endpoint
!= kOTInvalidEndpointRef
)
305 GSocket_Shutdown(socket
);
308 /* Destroy private addresses */
310 GAddress_destroy(socket
->m_local
);
313 GAddress_destroy(socket
->m_peer
);
315 /* Destroy the socket itself */
320 * Disallow further read/write operations on this socket, close
321 * the fd and disable all callbacks.
323 void GSocket_Shutdown(GSocket
*socket
)
328 assert(socket
!= NULL
);
330 /* If socket has been created, shutdown it */
331 if (socket
->m_endpoint
!= kOTInvalidEndpointRef
)
333 err
= OTSndOrderlyDisconnect( socket
->m_endpoint
) ;
334 if ( err
!= kOTNoError
)
338 err
= OTRcvOrderlyDisconnect( socket
->m_endpoint
) ;
339 err
= OTUnbind( socket
->m_endpoint
) ;
340 err
= OTCloseProvider( socket
->m_endpoint
) ;
341 socket
->m_endpoint
= kOTInvalidEndpointRef
;
344 /* Disable GUI callbacks */
345 for (evt
= 0; evt
< GSOCK_MAX_EVENT
; evt
++)
346 socket
->m_cbacks
[evt
] = NULL
;
348 socket
->m_detected
= 0;
349 _GSocket_Disable_Events(socket
);
350 wxMacRemoveAllNotifiersForData( wxMacGetNotifierTable() , socket
) ;
354 /* Address handling */
360 * Set or get the local or peer address for this socket. The 'set'
361 * functions return GSOCK_NOERROR on success, an error code otherwise.
362 * The 'get' functions return a pointer to a GAddress object on success,
363 * or NULL otherwise, in which case they set the error code of the
364 * corresponding GSocket.
367 * GSOCK_INVSOCK - the socket is not valid.
368 * GSOCK_INVADDR - the address is not valid.
370 GSocketError
GSocket_SetLocal(GSocket
*socket
, GAddress
*address
)
372 assert(socket
!= NULL
);
374 /* the socket must be initialized, or it must be a server */
375 if ((socket
->m_endpoint
!= kOTInvalidEndpointRef
&& !socket
->m_server
))
377 socket
->m_error
= GSOCK_INVSOCK
;
378 return GSOCK_INVSOCK
;
382 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
384 socket
->m_error
= GSOCK_INVADDR
;
385 return GSOCK_INVADDR
;
389 GAddress_destroy(socket
->m_local
);
391 socket
->m_local
= GAddress_copy(address
);
393 return GSOCK_NOERROR
;
396 GSocketError
GSocket_SetPeer(GSocket
*socket
, GAddress
*address
)
398 assert(socket
!= NULL
);
401 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
403 socket
->m_error
= GSOCK_INVADDR
;
404 return GSOCK_INVADDR
;
408 GAddress_destroy(socket
->m_peer
);
410 socket
->m_peer
= GAddress_copy(address
);
412 return GSOCK_NOERROR
;
415 GAddress
*GSocket_GetLocal(GSocket
*socket
)
417 GAddress
*address
= NULL
;
421 assert(socket
!= NULL
);
423 /* try to get it from the m_local var first */
425 return GAddress_copy(socket
->m_local
);
427 /* else, if the socket is initialized, try getsockname */
428 if (socket
->m_endpoint
== kOTInvalidEndpointRef
)
430 socket
->m_error
= GSOCK_INVSOCK
;
435 /* we do not support multihoming with this code at the moment
436 OTGetProtAddress will have to be used then - but we don't have a handy
437 method to use right now
440 InetInterfaceInfo info
;
441 OTInetGetInterfaceInfo(&info
, kDefaultInetInterface
);
442 loc
.fHost
= info
.fAddress
;
444 loc
.fAddressType
= AF_INET
;
447 /* got a valid address from getsockname, create a GAddress object */
448 address
= GAddress_new();
451 socket
->m_error
= GSOCK_MEMERR
;
455 err
= _GAddress_translate_from(address
, &loc
);
456 if (err
!= GSOCK_NOERROR
)
458 GAddress_destroy(address
);
459 socket
->m_error
= err
;
466 GAddress
*GSocket_GetPeer(GSocket
*socket
)
468 assert(socket
!= NULL
);
470 /* try to get it from the m_peer var */
472 return GAddress_copy(socket
->m_peer
);
477 /* Server specific parts */
479 /* GSocket_SetServer:
480 * Sets up this socket as a server. The local address must have been
481 * set with GSocket_SetLocal() before GSocket_SetServer() is called.
482 * Returns GSOCK_NOERROR on success, one of the following otherwise:
485 * GSOCK_INVSOCK - the socket is in use.
486 * GSOCK_INVADDR - the local address has not been set.
487 * GSOCK_IOERR - low-level error.
489 GSocketError
GSocket_SetServer(GSocket
*sck
)
493 /* must not be in use */
494 if (sck
->m_endpoint
!= kOTInvalidEndpointRef
)
496 sck
->m_error
= GSOCK_INVSOCK
;
497 return GSOCK_INVSOCK
;
500 /* the local addr must have been set */
503 sck
->m_error
= GSOCK_INVADDR
;
504 return GSOCK_INVADDR
;
507 /* Initialize all fields */
508 sck
->m_stream
= TRUE
;
509 sck
->m_server
= TRUE
;
510 sck
->m_oriented
= TRUE
;
514 /* Create the socket */
515 sck
->m_endpoint
= socket(sck
->m_local
->m_realfamily
, SOCK_STREAM
, 0);
516 socket_set_ref( sck
->m_endpoint
, (unsigned long) &gMacNetEvents
, (unsigned long) sck
) ;
517 if (sck
->m_endpoint
== kOTInvalidEndpointRef
)
519 sck
->m_error
= GSOCK_IOERR
;
523 ioctl(sck
->m_endpoint
, FIONBIO
, &arg
);
524 _GSocket_Enable_Events(sck
);
526 /* Bind to the local address,
527 * retrieve the actual address bound,
528 * and listen up to 5 connections.
530 if ((bind(sck
->m_endpoint
, sck
->m_local
->m_addr
, sck
->m_local
->m_len
) != 0) ||
531 (getsockname(sck
->m_endpoint
,
532 sck
->m_local
->m_addr
,
533 (SOCKLEN_T
*) &sck
->m_local
->m_len
) != 0) ||
534 (listen(sck
->m_endpoint
, 5) != 0))
536 close(sck
->m_endpoint
);
537 sck
->m_endpoint
= -1;
538 sck
->m_error
= GSOCK_IOERR
;
542 return GSOCK_NOERROR
;
545 /* GSocket_WaitConnection:
546 * Waits for an incoming client connection. Returns a pointer to
547 * a GSocket object, or NULL if there was an error, in which case
548 * the last error field will be updated for the calling GSocket.
550 * Error codes (set in the calling GSocket)
551 * GSOCK_INVSOCK - the socket is not valid or not a server.
552 * GSOCK_TIMEDOUT - timeout, no incoming connections.
553 * GSOCK_WOULDBLOCK - the call would block and the socket is nonblocking.
554 * GSOCK_MEMERR - couldn't allocate memory.
555 * GSOCK_IOERR - low-level error.
557 GSocket
*GSocket_WaitConnection(GSocket
*socket
)
559 GSocket
*connection
= NULL
;
561 assert(socket
!= NULL
);
563 /* Reenable CONNECTION events */
564 socket
->m_detected
&= ~GSOCK_CONNECTION_FLAG
;
566 /* If the socket has already been created, we exit immediately */
567 if (socket
->m_endpoint
== kOTInvalidEndpointRef
|| !socket
->m_server
)
569 socket
->m_error
= GSOCK_INVSOCK
;
573 /* Create a GSocket object for the new connection */
574 connection
= GSocket_new();
578 socket
->m_error
= GSOCK_MEMERR
;
582 /* Wait for a connection (with timeout) */
583 if (_GSocket_Input_Timeout(socket
) == GSOCK_TIMEDOUT
)
585 GSocket_destroy(connection
);
586 /* socket->m_error set by _GSocket_Input_Timeout */
592 connection
->m_endpoint
= accept(socket
->m_endpoint
, &from
, (SOCKLEN_T
*) &fromlen
);
595 if (connection
->m_endpoint
== kOTInvalidEndpointRef
)
597 if (errno
== EWOULDBLOCK
)
598 socket
->m_error
= GSOCK_WOULDBLOCK
;
600 socket
->m_error
= GSOCK_IOERR
;
602 GSocket_destroy(connection
);
606 /* Initialize all fields */
607 connection
->m_server
= FALSE
;
608 connection
->m_stream
= TRUE
;
609 connection
->m_oriented
= TRUE
;
611 /* Setup the peer address field */
612 connection
->m_peer
= GAddress_new();
613 if (!connection
->m_peer
)
615 GSocket_destroy(connection
);
616 socket
->m_error
= GSOCK_MEMERR
;
621 err
= _GAddress_translate_from(connection
->m_peer
, &from
, fromlen
);
622 if (err
!= GSOCK_NOERROR
)
624 GAddress_destroy(connection
->m_peer
);
625 GSocket_destroy(connection
);
626 socket
->m_error
= err
;
630 ioctl(connection
->m_endpoint
, FIONBIO
, &arg
);
632 _GSocket_Enable_Events(connection
);
637 /* Datagram sockets */
639 /* GSocket_SetNonOriented:
640 * Sets up this socket as a non-connection oriented (datagram) socket.
641 * Before using this function, the local address must have been set
642 * with GSocket_SetLocal(), or the call will fail. Returns GSOCK_NOERROR
643 * on success, or one of the following otherwise.
646 * GSOCK_INVSOCK - the socket is in use.
647 * GSOCK_INVADDR - the local address has not been set.
648 * GSOCK_IOERR - low-level error.
650 GSocketError
GSocket_SetNonOriented(GSocket
*sck
)
654 if (sck
->m_endpoint
!= kOTInvalidEndpointRef
)
656 sck
->m_error
= GSOCK_INVSOCK
;
657 return GSOCK_INVSOCK
;
662 sck
->m_error
= GSOCK_INVADDR
;
663 return GSOCK_INVADDR
;
666 /* Initialize all fields */
667 sck
->m_stream
= FALSE
;
668 sck
->m_server
= FALSE
;
669 sck
->m_oriented
= FALSE
;
671 /* Create the socket */
675 sck
->m_endpoint
= socket(sck
->m_local
->m_realfamily
, SOCK_DGRAM
, 0);
676 socket_set_ref( sck
->m_endpoint
, (unsigned long) &gMacNetEvents
, (unsigned long) sck
) ;
678 if (sck
->m_endpoint
== kOTInvalidEndpointRef
)
680 sck
->m_error
= GSOCK_IOERR
;
686 ioctl(sck
->m_endpoint
, FIONBIO
, &arg
);
688 _GSocket_Enable_Events(sck
);
690 /* Bind to the local address,
691 * and retrieve the actual address bound.
695 if ((bind(sck
->m_endpoint
, sck
->m_local
->m_addr
, sck
->m_local
->m_len
) != 0) ||
696 (getsockname(sck
->m_endpoint
,
697 sck
->m_local
->m_addr
,
698 (SOCKLEN_T
*) &sck
->m_local
->m_len
) != 0))
700 close(sck
->m_endpoint
);
701 sck
->m_endpoint
= -1;
702 sck
->m_error
= GSOCK_IOERR
;
706 return GSOCK_NOERROR
;
709 /* Client specific parts */
712 * For stream (connection oriented) sockets, GSocket_Connect() tries
713 * to establish a client connection to a server using the peer address
714 * as established with GSocket_SetPeer(). Returns GSOCK_NOERROR if the
715 * connection has been succesfully established, or one of the error
716 * codes listed below. Note that for nonblocking sockets, a return
717 * value of GSOCK_WOULDBLOCK doesn't mean a failure. The connection
718 * request can be completed later; you should use GSocket_Select()
719 * to poll for GSOCK_CONNECTION | GSOCK_LOST, or wait for the
720 * corresponding asynchronous events.
722 * For datagram (non connection oriented) sockets, GSocket_Connect()
723 * just sets the peer address established with GSocket_SetPeer() as
724 * default destination.
727 * GSOCK_INVSOCK - the socket is in use or not valid.
728 * GSOCK_INVADDR - the peer address has not been established.
729 * GSOCK_TIMEDOUT - timeout, the connection failed.
730 * GSOCK_WOULDBLOCK - connection in progress (nonblocking sockets only)
731 * GSOCK_MEMERR - couldn't allocate memory.
732 * GSOCK_IOERR - low-level error.
734 GSocketError
GSocket_Connect(GSocket
*sck
, GSocketStream stream
)
738 OSStatus err
= kOTNoError
;
743 /* Enable CONNECTION events (needed for nonblocking connections) */
744 sck
->m_detected
&= ~GSOCK_CONNECTION_FLAG
;
746 if (sck
->m_endpoint
!= kOTInvalidEndpointRef
)
748 sck
->m_error
= GSOCK_INVSOCK
;
749 return GSOCK_INVSOCK
;
754 sck
->m_error
= GSOCK_INVADDR
;
755 return GSOCK_INVADDR
;
758 /* Streamed or dgram socket? */
759 sck
->m_stream
= (stream
== GSOCK_STREAMED
);
760 sck
->m_oriented
= TRUE
;
761 sck
->m_server
= FALSE
;
763 /* Create the socket */
766 OTOpenEndpointInContext( OTCreateConfiguration( kTCPName
) , 0 , &info
, &err
, NULL
) ;
769 OTOpenEndpoint( OTCreateConfiguration( kTCPName
) , 0 , &info
, &err
) ;
771 if ( sck
->m_endpoint
== kOTInvalidEndpointRef
|| err
!= kOTNoError
)
773 sck
->m_endpoint
= kOTInvalidEndpointRef
;
774 sck
->m_error
= GSOCK_IOERR
;
777 err
= OTBind( sck
->m_endpoint
, nil
, nil
) ;
778 if ( err
!= kOTNoError
)
782 SetDefaultEndpointModes( sck
->m_endpoint
, sck
) ;
785 ioctl(sck
->m_endpoint
, FIONBIO
, &arg
);
787 _GSocket_Enable_Events(sck
);
789 _GAddress_translate_to( sck
->m_peer
, &addr
) ;
790 memset( &peer
, 0 , sizeof( TCall
) ) ;
791 peer
.addr
.len
= sizeof( InetAddress
) ;
792 peer
.addr
.buf
= (unsigned char*) &addr
;
793 err
= OTConnect( sck
->m_endpoint
, &peer
, nil
) ;
796 /* If connect failed with EINPROGRESS and the GSocket object
797 * is in blocking mode, we select() for the specified timeout
798 * checking for writability to see if the connection request
802 if ((err
== kOTNoDataErr
) && (!sck
->m_non_blocking
))
804 if (_GSocket_Output_Timeout(sck
) == GSOCK_TIMEDOUT
)
806 OTSndOrderlyDisconnect( sck
->m_endpoint
) ;
807 sck
->m_endpoint
= kOTInvalidEndpointRef
;
808 /* sck->m_error is set in _GSocket_Output_Timeout */
809 return GSOCK_TIMEDOUT
;
815 SOCKLEN_T len = sizeof(error);
817 getsockopt(sck->m_endpoint, SOL_SOCKET, SO_ERROR, (void*) &error, &len);
821 return GSOCK_NOERROR
;
825 /* If connect failed with EINPROGRESS and the GSocket object
826 * is set to nonblocking, we set m_error to GSOCK_WOULDBLOCK
827 * (and return GSOCK_WOULDBLOCK) but we don't close the socket;
828 * this way if the connection completes, a GSOCK_CONNECTION
829 * event will be generated, if enabled.
831 if ((err
== kOTNoDataErr
) && (sck
->m_non_blocking
))
833 sck
->m_error
= GSOCK_WOULDBLOCK
;
834 return GSOCK_WOULDBLOCK
;
837 /* If connect failed with an error other than EINPROGRESS,
838 * then the call to GSocket_Connect has failed.
840 OTSndOrderlyDisconnect( sck
->m_endpoint
) ;
842 sck
->m_endpoint
= kOTInvalidEndpointRef
;
843 sck
->m_error
= GSOCK_IOERR
;
846 // OTInetEventHandler(sck, T_CONNECT , kOTNoError , NULL ) ;
847 return GSOCK_NOERROR
;
852 /* Like recv(), send(), ... */
853 int GSocket_Read(GSocket
*socket
, char *buffer
, int size
)
857 assert(socket
!= NULL
);
859 /* Reenable INPUT events */
860 socket
->m_detected
&= ~GSOCK_INPUT_FLAG
;
862 if (socket
->m_endpoint
== kOTInvalidEndpointRef
|| socket
->m_server
)
864 socket
->m_error
= GSOCK_INVSOCK
;
868 /* If the socket is blocking, wait for data (with a timeout) */
869 if (_GSocket_Input_Timeout(socket
) == GSOCK_TIMEDOUT
)
873 if (socket
->m_stream
)
874 ret
= _GSocket_Recv_Stream(socket
, buffer
, size
);
876 ret
= _GSocket_Recv_Dgram(socket
, buffer
, size
);
880 if (errno
== EWOULDBLOCK
)
881 socket
->m_error
= GSOCK_WOULDBLOCK
;
883 socket
->m_error
= GSOCK_IOERR
;
889 int GSocket_Write(GSocket
*socket
, const char *buffer
, int size
)
893 assert(socket
!= NULL
);
895 if (socket
->m_endpoint
== kOTInvalidEndpointRef
|| socket
->m_server
)
897 socket
->m_error
= GSOCK_INVSOCK
;
901 /* If the socket is blocking, wait for writability (with a timeout) */
902 if (_GSocket_Output_Timeout(socket
) == GSOCK_TIMEDOUT
)
906 if (socket
->m_stream
)
907 ret
= _GSocket_Send_Stream(socket
, buffer
, size
);
909 ret
= _GSocket_Send_Dgram(socket
, buffer
, size
);
913 if (errno
== EWOULDBLOCK
)
914 socket
->m_error
= GSOCK_WOULDBLOCK
;
916 socket
->m_error
= GSOCK_IOERR
;
918 /* Only reenable OUTPUT events after an error (just like WSAAsyncSelect
919 * in MSW). Once the first OUTPUT event is received, users can assume
920 * that the socket is writable until a read operation fails. Only then
921 * will further OUTPUT events be posted.
923 socket
->m_detected
&= ~GSOCK_OUTPUT_FLAG
;
931 * Polls the socket to determine its status. This function will
932 * check for the events specified in the 'flags' parameter, and
933 * it will return a mask indicating which operations can be
934 * performed. This function won't block, regardless of the
935 * mode (blocking | nonblocking) of the socket.
937 GSocketEventFlags
GSocket_Select(GSocket
*socket
, GSocketEventFlags flags
)
939 assert(socket
!= NULL
);
940 wxMacProcessNotifierEvents() ;
942 state = OTGetEndpointState(socket->m_endpoint);
944 if ( ( flags & GSOCK_INPUT_FLAG ) && ! ( socket->m_detected & GSOCK_INPUT_FLAG ) )
947 OTCountDataBytes( socket->m_endpoint , &sz ) ;
948 if ( state == T_INCON || sz > 0 )
950 socket->m_detected |= GSOCK_INPUT_FLAG ;
951 (socket->m_cbacks[GSOCK_INPUT])(socket, GSOCK_INPUT, socket->m_data[GSOCK_INPUT]);
954 if ( ( flags & GSOCK_INPUT_FLAG ) && ! ( socket->m_detected & GSOCK_OUTPUT_FLAG ) )
956 if ( state == T_DATAXFER || state == T_INREL )
958 socket->m_detected |=GSOCK_OUTPUT_FLAG ;
959 (socket->m_cbacks[GSOCK_OUTPUT])(socket, GSOCK_OUTPUT, socket->m_data[GSOCK_OUTPUT]);
963 return ( flags
& socket
->m_detected
) ;
968 /* GSocket_SetNonBlocking:
969 * Sets the socket to non-blocking mode. All IO calls will return
972 void GSocket_SetNonBlocking(GSocket
*socket
, int non_block
)
974 assert(socket
!= NULL
);
976 socket
->m_non_blocking
= non_block
;
979 /* GSocket_SetTimeout:
980 * Sets the timeout for blocking calls. Time is expressed in
983 void GSocket_SetTimeout(GSocket
*socket
, unsigned long millisec
)
985 assert(socket
!= NULL
);
987 // this is usually set too high and we have not yet been able to detect a closed
988 // stream, thus we leave the 10 sec timeout
989 // socket->m_timeout = millisec;
993 * Returns the last error occured for this socket. Note that successful
994 * operations do not clear this back to GSOCK_NOERROR, so use it only
997 GSocketError
GSocket_GetError(GSocket
*socket
)
999 assert(socket
!= NULL
);
1001 return socket
->m_error
;
1007 * There is data to be read in the input buffer. If, after a read
1008 * operation, there is still data available, the callback function will
1011 * The socket is available for writing. That is, the next write call
1012 * won't block. This event is generated only once, when the connection is
1013 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
1014 * when the output buffer empties again. This means that the app should
1015 * assume that it can write since the first OUTPUT event, and no more
1016 * OUTPUT events will be generated unless an error occurs.
1018 * Connection succesfully established, for client sockets, or incoming
1019 * client connection, for server sockets. Wait for this event (also watch
1020 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
1022 * The connection is lost (or a connection request failed); this could
1023 * be due to a failure, or due to the peer closing it gracefully.
1026 /* GSocket_SetCallback:
1027 * Enables the callbacks specified by 'flags'. Note that 'flags'
1028 * may be a combination of flags OR'ed toghether, so the same
1029 * callback function can be made to accept different events.
1030 * The callback function must have the following prototype:
1032 * void function(GSocket *socket, GSocketEvent event, char *cdata)
1034 void GSocket_SetCallback(GSocket
*socket
, GSocketEventFlags flags
,
1035 GSocketCallback callback
, char *cdata
)
1039 assert(socket
!= NULL
);
1041 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1043 if ((flags
& (1 << count
)) != 0)
1045 socket
->m_cbacks
[count
] = callback
;
1046 socket
->m_data
[count
] = cdata
;
1051 /* GSocket_UnsetCallback:
1052 * Disables all callbacks specified by 'flags', which may be a
1053 * combination of flags OR'ed toghether.
1055 void GSocket_UnsetCallback(GSocket
*socket
, GSocketEventFlags flags
)
1059 assert(socket
!= NULL
);
1061 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1063 if ((flags
& (1 << count
)) != 0)
1065 socket
->m_cbacks
[count
] = NULL
;
1066 socket
->m_data
[count
] = NULL
;
1072 #define CALL_CALLBACK(socket, event) { \
1073 _GSocket_Disable(socket, event); \
1074 if (socket->m_cbacks[event]) \
1075 socket->m_cbacks[event](socket, event, socket->m_data[event]); \
1078 int _GSocket_Recv_Stream(GSocket
*socket
, char *buffer
, int size
)
1082 OTByteCount sz
= 0 ;
1084 OTCountDataBytes( socket
->m_endpoint
, &sz
) ;
1085 if ( size
> (int)sz
)
1087 res
= OTRcv( socket
->m_endpoint
, buffer
, size
, &flags
) ;
1093 // we simulate another read event if there are still bytes
1094 if ( socket
->m_takesEvents
)
1096 OTByteCount sz
= 0 ;
1097 OTCountDataBytes( socket
->m_endpoint
, &sz
) ;
1100 socket
->m_detected
|= GSOCK_INPUT_FLAG
;
1101 (socket
->m_cbacks
[GSOCK_INPUT
])(socket
, GSOCK_INPUT
, socket
->m_data
[GSOCK_INPUT
]);
1107 int _GSocket_Recv_Dgram(GSocket
*socket
, char *buffer
, int size
)
1112 struct sockaddr from
;
1113 SOCKLEN_T fromlen
= sizeof(from
);
1116 fromlen
= sizeof(from
);
1118 ret
= recvfrom(socket
->m_endpoint
, buffer
, size
, 0, &from
, (SOCKLEN_T
*) &fromlen
);
1123 /* Translate a system address into a GSocket address */
1124 if (!socket
->m_peer
)
1126 socket
->m_peer
= GAddress_new();
1127 if (!socket
->m_peer
)
1129 socket
->m_error
= GSOCK_MEMERR
;
1133 err
= _GAddress_translate_from(socket
->m_peer
, &from
, fromlen
);
1134 if (err
!= GSOCK_NOERROR
)
1136 GAddress_destroy(socket
->m_peer
);
1137 socket
->m_peer
= NULL
;
1138 socket
->m_error
= err
;
1145 int _GSocket_Send_Stream(GSocket
*socket
, const char *buffer
, int size
)
1150 res
= OTSnd( socket
->m_endpoint
, (void*) buffer
, size
, flags
) ;
1154 int _GSocket_Send_Dgram(GSocket
*socket
, const char *buffer
, int size
)
1159 struct sockaddr
*addr
;
1163 if (!socket
->m_peer
)
1165 socket
->m_error
= GSOCK_INVADDR
;
1169 err
= _GAddress_translate_to(socket
->m_peer
, &addr
, &len
);
1170 if (err
!= GSOCK_NOERROR
)
1172 socket
->m_error
= err
;
1176 ret
= sendto(socket
->m_endpoint
, buffer
, size
, 0, addr
, len
);
1178 /* Frees memory allocated from _GAddress_translate_to */
1186 * -------------------------------------------------------------------------
1188 * -------------------------------------------------------------------------
1191 /* CHECK_ADDRESS verifies that the current family is either GSOCK_NOFAMILY
1192 * or GSOCK_*family*, and if it is GSOCK_NOFAMILY, it initalizes address
1193 * to be a GSOCK_*family*. In other cases, it returns GSOCK_INVADDR.
1195 #define CHECK_ADDRESS(address, family, retval) \
1197 if (address->m_family == GSOCK_NOFAMILY) \
1198 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1199 return address->m_error; \
1200 if (address->m_family != GSOCK_##family) \
1202 address->m_error = GSOCK_INVADDR; \
1207 GAddress
*GAddress_new()
1211 if ((address
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1214 address
->m_family
= GSOCK_NOFAMILY
;
1215 address
->m_host
= INADDR_NONE
;
1216 address
->m_port
= 0 ;
1221 GAddress
*GAddress_copy(GAddress
*address
)
1225 assert(address
!= NULL
);
1227 if ((addr2
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1230 memcpy(addr2
, address
, sizeof(GAddress
));
1234 void GAddress_destroy(GAddress
*address
)
1236 assert(address
!= NULL
);
1241 void GAddress_SetFamily(GAddress
*address
, GAddressType type
)
1243 assert(address
!= NULL
);
1245 address
->m_family
= type
;
1248 GAddressType
GAddress_GetFamily(GAddress
*address
)
1250 assert(address
!= NULL
);
1252 return address
->m_family
;
1255 GSocketError
_GAddress_translate_from(GAddress
*address
,
1258 switch (addr
->fAddressType
)
1261 address
->m_family
= GSOCK_INET
;
1265 address
->m_family
= GSOCK_INET6
;
1270 address
->m_error
= GSOCK_INVOP
;
1274 address
->m_host
= addr
->fHost
;
1275 address
->m_port
= addr
->fPort
;
1276 return GSOCK_NOERROR
;
1279 GSocketError
_GAddress_translate_to(GAddress
*address
,
1282 if ( GSocket_Verify_Inited() == FALSE
)
1283 return GSOCK_IOERR
;
1284 memset(addr
, 0 , sizeof(struct InetAddress
));
1285 OTInitInetAddress( addr
, address
->m_port
, address
->m_host
) ;
1286 return GSOCK_NOERROR
;
1290 * -------------------------------------------------------------------------
1291 * Internet address family
1292 * -------------------------------------------------------------------------
1295 GSocketError
_GAddress_Init_INET(GAddress
*address
)
1297 address
->m_family
= GSOCK_INET
;
1298 address
->m_host
= kOTAnyInetAddress
;
1300 return GSOCK_NOERROR
;
1303 GSocketError
GAddress_INET_SetHostName(GAddress
*address
, const char *hostname
)
1305 InetHostInfo hinfo
;
1308 if ( GSocket_Verify_Inited() == FALSE
)
1309 return GSOCK_IOERR
;
1311 assert(address
!= NULL
);
1313 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1314 ret
= OTInetStringToAddress( gInetSvcRef
, (char*) hostname
, &hinfo
) ;
1315 if ( ret
!= kOTNoError
)
1317 address
->m_host
= INADDR_NONE
;
1318 address
->m_error
= GSOCK_NOHOST
;
1319 return GSOCK_NOHOST
;
1321 address
->m_host
= hinfo
.addrs
[0] ;
1322 return GSOCK_NOERROR
;
1325 GSocketError
GAddress_INET_SetAnyAddress(GAddress
*address
)
1327 return GAddress_INET_SetHostAddress(address
, INADDR_ANY
);
1330 GSocketError
GAddress_INET_SetHostAddress(GAddress
*address
,
1331 unsigned long hostaddr
)
1333 assert(address
!= NULL
);
1335 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1337 address
->m_host
= htonl(hostaddr
) ;
1339 return GSOCK_NOERROR
;
1342 struct service_entry
1345 unsigned short port
;
1348 typedef struct service_entry service_entry
;
1350 service_entry gServices
[] =
1352 { "http" , 80 , "tcp" }
1355 GSocketError
GAddress_INET_SetPortName(GAddress
*address
, const char *port
,
1356 const char *protocol
)
1360 assert(address
!= NULL
);
1361 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1365 address
->m_error
= GSOCK_INVPORT
;
1366 return GSOCK_INVPORT
;
1368 for ( i
= 0 ; i
< sizeof( gServices
) / sizeof( service_entry
) ; ++i
)
1370 if ( strcmp( port
, gServices
[i
].name
) == 0 )
1372 if ( protocol
== NULL
|| strcmp( protocol
, gServices
[i
].protocol
) )
1374 address
->m_port
= gServices
[i
].port
;
1375 return GSOCK_NOERROR
;
1380 if (isdigit(port
[0]))
1382 address
->m_port
= atoi(port
);
1383 return GSOCK_NOERROR
;
1386 address
->m_error
= GSOCK_INVPORT
;
1387 return GSOCK_INVPORT
;
1390 GSocketError
GAddress_INET_SetPort(GAddress
*address
, unsigned short port
)
1392 assert(address
!= NULL
);
1393 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1394 address
->m_port
= port
;
1396 return GSOCK_NOERROR
;
1399 GSocketError
GAddress_INET_GetHostName(GAddress
*address
, char *hostname
, size_t sbuf
)
1401 InetDomainName name
;
1402 if ( GSocket_Verify_Inited() == FALSE
)
1403 return GSOCK_IOERR
;
1405 assert(address
!= NULL
);
1406 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1408 OTInetAddressToName( gInetSvcRef
, address
->m_host
, name
) ;
1409 strncpy( hostname
, name
, sbuf
) ;
1410 return GSOCK_NOERROR
;
1413 unsigned long GAddress_INET_GetHostAddress(GAddress
*address
)
1415 assert(address
!= NULL
);
1416 CHECK_ADDRESS(address
, INET
, 0);
1418 return ntohl(address
->m_host
);
1421 unsigned short GAddress_INET_GetPort(GAddress
*address
)
1423 assert(address
!= NULL
);
1424 CHECK_ADDRESS(address
, INET
, 0);
1426 return address
->m_port
;
1429 void _GSocket_Enable_Events(GSocket
*socket
)
1431 if ( socket
->m_takesEvents
)
1436 socket
->m_takesEvents
= TRUE
;
1437 state
= OTGetEndpointState(socket
->m_endpoint
);
1440 OTByteCount sz
= 0 ;
1441 OTCountDataBytes( socket
->m_endpoint
, &sz
) ;
1442 if ( state
== T_INCON
|| sz
> 0 )
1444 socket
->m_detected
|= GSOCK_INPUT_FLAG
;
1445 (socket
->m_cbacks
[GSOCK_INPUT
])(socket
, GSOCK_INPUT
, socket
->m_data
[GSOCK_INPUT
]);
1449 if ( state
== T_DATAXFER
|| state
== T_INREL
)
1451 socket
->m_detected
|=GSOCK_OUTPUT_FLAG
;
1452 (socket
->m_cbacks
[GSOCK_OUTPUT
])(socket
, GSOCK_OUTPUT
, socket
->m_data
[GSOCK_OUTPUT
]);
1458 void _GSocket_Disable_Events(GSocket
*socket
)
1460 socket
->m_takesEvents
= FALSE
;
1463 /* _GSocket_Input_Timeout:
1464 * For blocking sockets, wait until data is available or
1465 * until timeout ellapses.
1467 GSocketError
_GSocket_Input_Timeout(GSocket
*socket
)
1469 if ( !socket
->m_non_blocking
)
1471 UnsignedWide now
, start
;
1472 short formerTakesEvents
= socket
->m_takesEvents
;
1473 Microseconds(&start
);
1475 socket
->m_takesEvents
= FALSE
;
1477 while( (now
.hi
* 4294967296.0 + now
.lo
) - (start
.hi
* 4294967296.0 + start
.lo
) < socket
->m_timeout
* 1000.0 )
1480 OTByteCount sz
= 0 ;
1481 state
= OTGetEndpointState(socket
->m_endpoint
);
1483 OTCountDataBytes( socket
->m_endpoint
, &sz
) ;
1484 if ( state
== T_INCON
|| sz
> 0 )
1486 socket
->m_takesEvents
= formerTakesEvents
;
1487 return GSOCK_NOERROR
;
1491 socket
->m_takesEvents
= formerTakesEvents
;
1492 socket
->m_error
= GSOCK_TIMEDOUT
;
1493 return GSOCK_TIMEDOUT
;
1495 return GSOCK_NOERROR
;
1498 /* _GSocket_Output_Timeout:
1499 * For blocking sockets, wait until data can be sent without
1500 * blocking or until timeout ellapses.
1502 GSocketError
_GSocket_Output_Timeout(GSocket
*socket
)
1504 if ( !socket
->m_non_blocking
)
1506 UnsignedWide now
, start
;
1507 short formerTakesEvents
= socket
->m_takesEvents
;
1508 Microseconds(&start
);
1510 socket
->m_takesEvents
= FALSE
;
1512 while( (now
.hi
* 4294967296.0 + now
.lo
) - (start
.hi
* 4294967296.0 + start
.lo
) < socket
->m_timeout
* 1000.0 )
1515 state
= OTGetEndpointState(socket
->m_endpoint
);
1517 if ( state
== T_DATAXFER
|| state
== T_INREL
)
1519 socket
->m_takesEvents
= formerTakesEvents
;
1520 return GSOCK_NOERROR
;
1524 socket
->m_takesEvents
= formerTakesEvents
;
1525 socket
->m_error
= GSOCK_TIMEDOUT
;
1526 return GSOCK_TIMEDOUT
;
1528 return GSOCK_NOERROR
;
1532 * There is data to be read in the input buffer. If, after a read
1533 * operation, there is still data available, the callback function will
1536 * The socket is available for writing. That is, the next write call
1537 * won't block. This event is generated only once, when the connection is
1538 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
1539 * when the output buffer empties again. This means that the app should
1540 * assume that it can write since the first OUTPUT event, and no more
1541 * OUTPUT events will be generated unless an error occurs.
1543 * Connection succesfully established, for client sockets, or incoming
1544 * client connection, for server sockets. Wait for this event (also watch
1545 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
1547 * The connection is lost (or a connection request failed); this could
1548 * be due to a failure, or due to the peer closing it gracefully.
1551 void _GSocket_Internal_Proc(unsigned long e
, void* d
)
1554 GSocket
* socket
= (GSocket
*) d
;
1555 OTEventCode ev
= (OTEventCode
) e
;
1557 GSocketEvent event2
;
1558 GSocketCallback cback
;
1560 GSocketCallback cback2
;
1565 event
= GSOCK_MAX_EVENT
;
1566 event2
= GSOCK_MAX_EVENT
;
1572 /* Check that the socket still exists (it has not been
1573 * destroyed) and for safety, check that the m_endpoint field
1574 * is what we expect it to be.
1576 if ((socket
!= NULL
) && (socket
->m_takesEvents
))
1581 event
= GSOCK_CONNECTION
;
1584 event
= GSOCK_CONNECTION
;
1585 event2
= GSOCK_OUTPUT
;
1589 retCall
.addr
.buf
= NULL
;
1590 retCall
.addr
.maxlen
= 0;
1591 retCall
.opt
.buf
= NULL
;
1592 retCall
.opt
.maxlen
= 0;
1593 retCall
.udata
.buf
= NULL
;
1594 retCall
.udata
.maxlen
= 0;
1595 OTRcvConnect( socket
->m_endpoint
, &retCall
) ;
1599 event
= GSOCK_LOST
;
1603 event
= GSOCK_OUTPUT
;
1606 event
= GSOCK_INPUT
;
1609 event
= GSOCK_INPUT
;
1612 if (event
!= GSOCK_MAX_EVENT
)
1614 cback
= socket
->m_cbacks
[event
];
1615 data
= socket
->m_data
[event
];
1617 if (event
== GSOCK_LOST
)
1618 socket
->m_detected
= GSOCK_LOST_FLAG
;
1620 socket
->m_detected
|= (1 << event
);
1622 if (event2
!= GSOCK_MAX_EVENT
)
1624 cback2
= socket
->m_cbacks
[event2
];
1625 data2
= socket
->m_data
[event2
];
1627 if (event2
== GSOCK_LOST
)
1628 socket
->m_detected
= GSOCK_LOST_FLAG
;
1630 socket
->m_detected
|= (1 << event2
);
1634 /* OK, we can now leave the critical section because we have
1635 * already obtained the callback address (we make no further
1636 * accesses to socket->whatever). However, the app should
1637 * be prepared to handle events from a socket that has just
1642 (cback
)(socket
, event
, data
);
1644 (cback2
)(socket
, event2
, data2
);
1648 /* Hack added for Mac OS X */
1649 GSocketError
GAddress_UNIX_GetPath(GAddress
*addr
, char *path
, size_t buf
)
1651 return GSOCK_INVADDR
;
1654 GSocketError
GAddress_UNIX_SetPath(GAddress
*addr
, const char *path
)
1656 return GSOCK_INVADDR
;
1659 #endif /* wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__) */