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__ */
83 extern pascal void OTDebugStr(const char* str
);
88 InetSvcRef gInetSvcRef
= 0 ;
90 OTNotifyUPP gOTNotifierUPP
= NULL
;
92 OSStatus
DoNegotiateIPReuseAddrOption(EndpointRef ep
, Boolean enableReuseIPMode
);
94 /* Input: ep - endpointref on which to negotiate the option
95 enableReuseIPMode - desired option setting - true/false
96 Return: kOTNoError indicates that the option was successfully negotiated
97 OSStatus is an error if < 0, otherwise, the status field is
100 IMPORTANT NOTE: The endpoint is assumed to be in synchronous more, otherwise
101 this code will not function as desired
105 OSStatus
DoNegotiateIPReuseAddrOption(EndpointRef ep
, Boolean enableReuseIPMode
)
108 UInt8 buf
[kOTFourByteOptionSize
]; // define buffer for fourByte Option size
109 TOption
* opt
; // option ptr to make items easier to access
114 if (!OTIsSynchronous(ep
))
118 opt
= (TOption
*)buf
; // set option ptr to buffer
120 req
.opt
.len
= sizeof(buf
);
121 req
.flags
= T_NEGOTIATE
; // negotiate for option
124 ret
.opt
.maxlen
= kOTFourByteOptionSize
;
126 opt
->level
= INET_IP
; // dealing with an IP Level function
128 opt
->name
= kIP_REUSEADDR
;
130 opt
->name
= IP_REUSEADDR
;
132 opt
->len
= kOTFourByteOptionSize
;
134 *(UInt32
*)opt
->value
= enableReuseIPMode
; // set the desired option level, true or false
136 err
= OTOptionManagement(ep
, &req
, &ret
);
138 // if no error then return the option status value
139 if (err
== kOTNoError
)
141 if (opt
->status
!= T_SUCCESS
)
151 pascal void OTInetEventHandler(void*s
, OTEventCode event
, OTResult
, void *cookie
) ;
152 pascal void OTInetEventHandler(void*s
, OTEventCode event
, OTResult result
, void *cookie
)
155 GSocket
* sock
= (GSocket
*) s
;
157 if ( event
== kOTSyncIdleEvent
)
165 wxMacAddEvent( sock
->m_mac_events
, _GSocket_Internal_Proc
, event
, s
, wakeUp
) ;
171 static void SetDefaultEndpointModes(EndpointRef ep
, void *data
)
172 // This routine sets the supplied endpoint into the default
173 // mode used in this application. The specifics are:
174 // blocking, synchronous, and using synch idle events with
175 // the standard YieldingNotifier.
177 OSStatus junk
= kOTNoError
;
178 OTAssert ("SetDefaultEndpointModes:invalid ref", ep
!= kOTInvalidEndpointRef
) ;
179 junk
= OTSetAsynchronous(ep
);
180 OTAssert("SetDefaultEndpointModes: Could not set asynchronous", junk
== noErr
);
182 junk = OTSetBlocking(ep);
183 OTAssert("SetDefaultEndpointModes: Could not set blocking", junk == noErr);
184 junk = OTSetSynchronous(ep);
185 OTAssert("SetDefaultEndpointModes: Could not set synchronous", junk == noErr);
186 junk = OTSetBlocking(ep);
187 OTAssert("SetDefaultEndpointModes: Could not set blocking", junk == noErr);
189 junk
= OTInstallNotifier(ep
, gOTNotifierUPP
, data
);
190 OTAssert("SetDefaultEndpointModes: Could not install notifier", junk
== noErr
);
192 junk = OTUseSyncIdleEvents(ep, true);
193 OTAssert("SetDefaultEndpointModes: Could not use sync idle events", junk == noErr);
197 /* Global initialisers */
204 int GSocket_Verify_Inited() ;
205 int GSocket_Verify_Inited()
209 // Marc Newsam: added the clientcontext variable
210 // however, documentation is unclear how this works
211 OTClientContextPtr clientcontext
;
216 InitOpenTransportInContext(kInitOTForApplicationMask
, &clientcontext
);
218 gInetSvcRef
= OTOpenInternetServicesInContext(kDefaultInternetServicesPath
,
219 NULL
, &err
, clientcontext
);
224 InitOpenTransport() ;
226 gInetSvcRef
= OTOpenInternetServices(kDefaultInternetServicesPath
, NULL
, &err
);
228 if ( gInetSvcRef
== NULL
|| err
!= kOTNoError
)
230 OTAssert("Could not open Inet Services", err
== noErr
);
233 gOTNotifierUPP
= NewOTNotifyUPP( OTInetEventHandler
) ;
237 void GSocket_Cleanup()
239 if ( gOTInited
!= 0 )
241 if ( gInetSvcRef
!= NULL
)
242 OTCloseProvider( gInetSvcRef
);
244 CloseOpenTransportInContext( NULL
) ;
246 CloseOpenTransport() ;
248 if ( gOTNotifierUPP
)
249 DisposeOTNotifyUPP( gOTNotifierUPP
) ;
253 /* Constructors / Destructors for GSocket */
255 GSocket
*GSocket_new()
261 if ( GSocket_Verify_Inited() == FALSE
)
264 socket
= (GSocket
*)malloc(sizeof(GSocket
));
269 socket
->m_endpoint
= NULL
;
270 for (i
=0;i
<GSOCK_MAX_EVENT
;i
++)
272 socket
->m_cbacks
[i
] = NULL
;
274 socket
->m_detected
= 0;
275 socket
->m_local
= NULL
;
276 socket
->m_peer
= NULL
;
277 socket
->m_error
= GSOCK_NOERROR
;
278 socket
->m_server
= FALSE
;
279 socket
->m_stream
= TRUE
;
280 socket
->m_non_blocking
= FALSE
;
281 socket
->m_timeout
= 1*1000;
282 /* 10 sec * 1000 millisec */
283 socket
->m_takesEvents
= TRUE
;
284 socket
->m_mac_events
= wxMacGetNotifierTable() ;
288 void GSocket_destroy(GSocket
*socket
)
290 assert(socket
!= NULL
);
292 /* Check that the socket is really shutdowned */
293 if (socket
->m_endpoint
!= kOTInvalidEndpointRef
)
294 GSocket_Shutdown(socket
);
297 /* Destroy private addresses */
299 GAddress_destroy(socket
->m_local
);
302 GAddress_destroy(socket
->m_peer
);
304 /* Destroy the socket itself */
309 * Disallow further read/write operations on this socket, close
310 * the fd and disable all callbacks.
312 void GSocket_Shutdown(GSocket
*socket
)
317 assert(socket
!= NULL
);
319 /* If socket has been created, shutdown it */
320 if (socket
->m_endpoint
!= kOTInvalidEndpointRef
)
322 err
= OTSndOrderlyDisconnect( socket
->m_endpoint
) ;
323 if ( err
!= kOTNoError
)
327 err
= OTRcvOrderlyDisconnect( socket
->m_endpoint
) ;
328 err
= OTUnbind( socket
->m_endpoint
) ;
329 err
= OTCloseProvider( socket
->m_endpoint
) ;
330 socket
->m_endpoint
= kOTInvalidEndpointRef
;
333 /* Disable GUI callbacks */
334 for (evt
= 0; evt
< GSOCK_MAX_EVENT
; evt
++)
335 socket
->m_cbacks
[evt
] = NULL
;
337 socket
->m_detected
= 0;
338 _GSocket_Disable_Events(socket
);
339 wxMacRemoveAllNotifiersForData( wxMacGetNotifierTable() , socket
) ;
343 /* Address handling */
349 * Set or get the local or peer address for this socket. The 'set'
350 * functions return GSOCK_NOERROR on success, an error code otherwise.
351 * The 'get' functions return a pointer to a GAddress object on success,
352 * or NULL otherwise, in which case they set the error code of the
353 * corresponding GSocket.
356 * GSOCK_INVSOCK - the socket is not valid.
357 * GSOCK_INVADDR - the address is not valid.
359 GSocketError
GSocket_SetLocal(GSocket
*socket
, GAddress
*address
)
361 assert(socket
!= NULL
);
363 /* the socket must be initialized, or it must be a server */
364 if ((socket
->m_endpoint
!= kOTInvalidEndpointRef
&& !socket
->m_server
))
366 socket
->m_error
= GSOCK_INVSOCK
;
367 return GSOCK_INVSOCK
;
371 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
373 socket
->m_error
= GSOCK_INVADDR
;
374 return GSOCK_INVADDR
;
378 GAddress_destroy(socket
->m_local
);
380 socket
->m_local
= GAddress_copy(address
);
382 return GSOCK_NOERROR
;
385 GSocketError
GSocket_SetPeer(GSocket
*socket
, GAddress
*address
)
387 assert(socket
!= NULL
);
390 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
392 socket
->m_error
= GSOCK_INVADDR
;
393 return GSOCK_INVADDR
;
397 GAddress_destroy(socket
->m_peer
);
399 socket
->m_peer
= GAddress_copy(address
);
401 return GSOCK_NOERROR
;
404 GAddress
*GSocket_GetLocal(GSocket
*socket
)
406 GAddress
*address
= NULL
;
410 assert(socket
!= NULL
);
412 /* try to get it from the m_local var first */
414 return GAddress_copy(socket
->m_local
);
416 /* else, if the socket is initialized, try getsockname */
417 if (socket
->m_endpoint
== kOTInvalidEndpointRef
)
419 socket
->m_error
= GSOCK_INVSOCK
;
424 /* we do not support multihoming with this code at the moment
425 OTGetProtAddress will have to be used then - but we don't have a handy
426 method to use right now
429 InetInterfaceInfo info
;
430 OTInetGetInterfaceInfo(&info
, kDefaultInetInterface
);
431 loc
.fHost
= info
.fAddress
;
433 loc
.fAddressType
= AF_INET
;
436 /* got a valid address from getsockname, create a GAddress object */
437 address
= GAddress_new();
440 socket
->m_error
= GSOCK_MEMERR
;
444 err
= _GAddress_translate_from(address
, &loc
);
445 if (err
!= GSOCK_NOERROR
)
447 GAddress_destroy(address
);
448 socket
->m_error
= err
;
455 GAddress
*GSocket_GetPeer(GSocket
*socket
)
457 assert(socket
!= NULL
);
459 /* try to get it from the m_peer var */
461 return GAddress_copy(socket
->m_peer
);
466 /* Server specific parts */
468 /* GSocket_SetServer:
469 * Sets up this socket as a server. The local address must have been
470 * set with GSocket_SetLocal() before GSocket_SetServer() is called.
471 * Returns GSOCK_NOERROR on success, one of the following otherwise:
474 * GSOCK_INVSOCK - the socket is in use.
475 * GSOCK_INVADDR - the local address has not been set.
476 * GSOCK_IOERR - low-level error.
478 GSocketError
GSocket_SetServer(GSocket
*sck
)
482 /* must not be in use */
483 if (sck
->m_endpoint
!= kOTInvalidEndpointRef
)
485 sck
->m_error
= GSOCK_INVSOCK
;
486 return GSOCK_INVSOCK
;
489 /* the local addr must have been set */
492 sck
->m_error
= GSOCK_INVADDR
;
493 return GSOCK_INVADDR
;
496 /* Initialize all fields */
497 sck
->m_stream
= TRUE
;
498 sck
->m_server
= TRUE
;
499 sck
->m_oriented
= TRUE
;
503 /* Create the socket */
504 sck
->m_endpoint
= socket(sck
->m_local
->m_realfamily
, SOCK_STREAM
, 0);
505 socket_set_ref( sck
->m_endpoint
, (unsigned long) &gMacNetEvents
, (unsigned long) sck
) ;
506 if (sck
->m_endpoint
== kOTInvalidEndpointRef
)
508 sck
->m_error
= GSOCK_IOERR
;
512 ioctl(sck
->m_endpoint
, FIONBIO
, &arg
);
513 _GSocket_Enable_Events(sck
);
515 /* Bind to the local address,
516 * retrieve the actual address bound,
517 * and listen up to 5 connections.
519 if ((bind(sck
->m_endpoint
, sck
->m_local
->m_addr
, sck
->m_local
->m_len
) != 0) ||
520 (getsockname(sck
->m_endpoint
,
521 sck
->m_local
->m_addr
,
522 (SOCKLEN_T
*) &sck
->m_local
->m_len
) != 0) ||
523 (listen(sck
->m_endpoint
, 5) != 0))
525 close(sck
->m_endpoint
);
526 sck
->m_endpoint
= -1;
527 sck
->m_error
= GSOCK_IOERR
;
531 return GSOCK_NOERROR
;
534 /* GSocket_WaitConnection:
535 * Waits for an incoming client connection. Returns a pointer to
536 * a GSocket object, or NULL if there was an error, in which case
537 * the last error field will be updated for the calling GSocket.
539 * Error codes (set in the calling GSocket)
540 * GSOCK_INVSOCK - the socket is not valid or not a server.
541 * GSOCK_TIMEDOUT - timeout, no incoming connections.
542 * GSOCK_WOULDBLOCK - the call would block and the socket is nonblocking.
543 * GSOCK_MEMERR - couldn't allocate memory.
544 * GSOCK_IOERR - low-level error.
546 GSocket
*GSocket_WaitConnection(GSocket
*socket
)
548 GSocket
*connection
= NULL
;
550 assert(socket
!= NULL
);
552 /* Reenable CONNECTION events */
553 socket
->m_detected
&= ~GSOCK_CONNECTION_FLAG
;
555 /* If the socket has already been created, we exit immediately */
556 if (socket
->m_endpoint
== kOTInvalidEndpointRef
|| !socket
->m_server
)
558 socket
->m_error
= GSOCK_INVSOCK
;
562 /* Create a GSocket object for the new connection */
563 connection
= GSocket_new();
567 socket
->m_error
= GSOCK_MEMERR
;
571 /* Wait for a connection (with timeout) */
572 if (_GSocket_Input_Timeout(socket
) == GSOCK_TIMEDOUT
)
574 GSocket_destroy(connection
);
575 /* socket->m_error set by _GSocket_Input_Timeout */
581 connection
->m_endpoint
= accept(socket
->m_endpoint
, &from
, (SOCKLEN_T
*) &fromlen
);
584 if (connection
->m_endpoint
== kOTInvalidEndpointRef
)
586 if (errno
== EWOULDBLOCK
)
587 socket
->m_error
= GSOCK_WOULDBLOCK
;
589 socket
->m_error
= GSOCK_IOERR
;
591 GSocket_destroy(connection
);
595 /* Initialize all fields */
596 connection
->m_server
= FALSE
;
597 connection
->m_stream
= TRUE
;
598 connection
->m_oriented
= TRUE
;
600 /* Setup the peer address field */
601 connection
->m_peer
= GAddress_new();
602 if (!connection
->m_peer
)
604 GSocket_destroy(connection
);
605 socket
->m_error
= GSOCK_MEMERR
;
610 err
= _GAddress_translate_from(connection
->m_peer
, &from
, fromlen
);
611 if (err
!= GSOCK_NOERROR
)
613 GAddress_destroy(connection
->m_peer
);
614 GSocket_destroy(connection
);
615 socket
->m_error
= err
;
619 ioctl(connection
->m_endpoint
, FIONBIO
, &arg
);
621 _GSocket_Enable_Events(connection
);
626 /* Datagram sockets */
628 /* GSocket_SetNonOriented:
629 * Sets up this socket as a non-connection oriented (datagram) socket.
630 * Before using this function, the local address must have been set
631 * with GSocket_SetLocal(), or the call will fail. Returns GSOCK_NOERROR
632 * on success, or one of the following otherwise.
635 * GSOCK_INVSOCK - the socket is in use.
636 * GSOCK_INVADDR - the local address has not been set.
637 * GSOCK_IOERR - low-level error.
639 GSocketError
GSocket_SetNonOriented(GSocket
*sck
)
643 if (sck
->m_endpoint
!= kOTInvalidEndpointRef
)
645 sck
->m_error
= GSOCK_INVSOCK
;
646 return GSOCK_INVSOCK
;
651 sck
->m_error
= GSOCK_INVADDR
;
652 return GSOCK_INVADDR
;
655 /* Initialize all fields */
656 sck
->m_stream
= FALSE
;
657 sck
->m_server
= FALSE
;
658 sck
->m_oriented
= FALSE
;
660 /* Create the socket */
664 sck
->m_endpoint
= socket(sck
->m_local
->m_realfamily
, SOCK_DGRAM
, 0);
665 socket_set_ref( sck
->m_endpoint
, (unsigned long) &gMacNetEvents
, (unsigned long) sck
) ;
667 if (sck
->m_endpoint
== kOTInvalidEndpointRef
)
669 sck
->m_error
= GSOCK_IOERR
;
675 ioctl(sck
->m_endpoint
, FIONBIO
, &arg
);
677 _GSocket_Enable_Events(sck
);
679 /* Bind to the local address,
680 * and retrieve the actual address bound.
684 if ((bind(sck
->m_endpoint
, sck
->m_local
->m_addr
, sck
->m_local
->m_len
) != 0) ||
685 (getsockname(sck
->m_endpoint
,
686 sck
->m_local
->m_addr
,
687 (SOCKLEN_T
*) &sck
->m_local
->m_len
) != 0))
689 close(sck
->m_endpoint
);
690 sck
->m_endpoint
= -1;
691 sck
->m_error
= GSOCK_IOERR
;
695 return GSOCK_NOERROR
;
698 /* Client specific parts */
701 * For stream (connection oriented) sockets, GSocket_Connect() tries
702 * to establish a client connection to a server using the peer address
703 * as established with GSocket_SetPeer(). Returns GSOCK_NOERROR if the
704 * connection has been succesfully established, or one of the error
705 * codes listed below. Note that for nonblocking sockets, a return
706 * value of GSOCK_WOULDBLOCK doesn't mean a failure. The connection
707 * request can be completed later; you should use GSocket_Select()
708 * to poll for GSOCK_CONNECTION | GSOCK_LOST, or wait for the
709 * corresponding asynchronous events.
711 * For datagram (non connection oriented) sockets, GSocket_Connect()
712 * just sets the peer address established with GSocket_SetPeer() as
713 * default destination.
716 * GSOCK_INVSOCK - the socket is in use or not valid.
717 * GSOCK_INVADDR - the peer address has not been established.
718 * GSOCK_TIMEDOUT - timeout, the connection failed.
719 * GSOCK_WOULDBLOCK - connection in progress (nonblocking sockets only)
720 * GSOCK_MEMERR - couldn't allocate memory.
721 * GSOCK_IOERR - low-level error.
723 GSocketError
GSocket_Connect(GSocket
*sck
, GSocketStream stream
)
727 OSStatus err
= kOTNoError
;
732 /* Enable CONNECTION events (needed for nonblocking connections) */
733 sck
->m_detected
&= ~GSOCK_CONNECTION_FLAG
;
735 if (sck
->m_endpoint
!= kOTInvalidEndpointRef
)
737 sck
->m_error
= GSOCK_INVSOCK
;
738 return GSOCK_INVSOCK
;
743 sck
->m_error
= GSOCK_INVADDR
;
744 return GSOCK_INVADDR
;
747 /* Streamed or dgram socket? */
748 sck
->m_stream
= (stream
== GSOCK_STREAMED
);
749 sck
->m_oriented
= TRUE
;
750 sck
->m_server
= FALSE
;
752 /* Create the socket */
755 OTOpenEndpointInContext( OTCreateConfiguration( kTCPName
) , 0 , &info
, &err
, NULL
) ;
758 OTOpenEndpoint( OTCreateConfiguration( kTCPName
) , 0 , &info
, &err
) ;
760 if ( sck
->m_endpoint
== kOTInvalidEndpointRef
|| err
!= kOTNoError
)
762 sck
->m_endpoint
= kOTInvalidEndpointRef
;
763 sck
->m_error
= GSOCK_IOERR
;
766 err
= OTBind( sck
->m_endpoint
, nil
, nil
) ;
767 if ( err
!= kOTNoError
)
771 SetDefaultEndpointModes( sck
->m_endpoint
, sck
) ;
774 ioctl(sck
->m_endpoint
, FIONBIO
, &arg
);
776 _GSocket_Enable_Events(sck
);
778 _GAddress_translate_to( sck
->m_peer
, &addr
) ;
779 memset( &peer
, 0 , sizeof( TCall
) ) ;
780 peer
.addr
.len
= sizeof( InetAddress
) ;
781 peer
.addr
.buf
= (unsigned char*) &addr
;
782 err
= OTConnect( sck
->m_endpoint
, &peer
, nil
) ;
785 /* If connect failed with EINPROGRESS and the GSocket object
786 * is in blocking mode, we select() for the specified timeout
787 * checking for writability to see if the connection request
791 if ((err
== kOTNoDataErr
) && (!sck
->m_non_blocking
))
793 if (_GSocket_Output_Timeout(sck
) == GSOCK_TIMEDOUT
)
795 OTSndOrderlyDisconnect( sck
->m_endpoint
) ;
796 sck
->m_endpoint
= kOTInvalidEndpointRef
;
797 /* sck->m_error is set in _GSocket_Output_Timeout */
798 return GSOCK_TIMEDOUT
;
804 SOCKLEN_T len = sizeof(error);
806 getsockopt(sck->m_endpoint, SOL_SOCKET, SO_ERROR, (void*) &error, &len);
810 return GSOCK_NOERROR
;
814 /* If connect failed with EINPROGRESS and the GSocket object
815 * is set to nonblocking, we set m_error to GSOCK_WOULDBLOCK
816 * (and return GSOCK_WOULDBLOCK) but we don't close the socket;
817 * this way if the connection completes, a GSOCK_CONNECTION
818 * event will be generated, if enabled.
820 if ((err
== kOTNoDataErr
) && (sck
->m_non_blocking
))
822 sck
->m_error
= GSOCK_WOULDBLOCK
;
823 return GSOCK_WOULDBLOCK
;
826 /* If connect failed with an error other than EINPROGRESS,
827 * then the call to GSocket_Connect has failed.
829 OTSndOrderlyDisconnect( sck
->m_endpoint
) ;
831 sck
->m_endpoint
= kOTInvalidEndpointRef
;
832 sck
->m_error
= GSOCK_IOERR
;
835 // OTInetEventHandler(sck, T_CONNECT , kOTNoError , NULL ) ;
836 return GSOCK_NOERROR
;
841 /* Like recv(), send(), ... */
842 int GSocket_Read(GSocket
*socket
, char *buffer
, int size
)
846 assert(socket
!= NULL
);
848 /* Reenable INPUT events */
849 socket
->m_detected
&= ~GSOCK_INPUT_FLAG
;
851 if (socket
->m_endpoint
== kOTInvalidEndpointRef
|| socket
->m_server
)
853 socket
->m_error
= GSOCK_INVSOCK
;
857 /* If the socket is blocking, wait for data (with a timeout) */
858 if (_GSocket_Input_Timeout(socket
) == GSOCK_TIMEDOUT
)
862 if (socket
->m_stream
)
863 ret
= _GSocket_Recv_Stream(socket
, buffer
, size
);
865 ret
= _GSocket_Recv_Dgram(socket
, buffer
, size
);
869 if (errno
== EWOULDBLOCK
)
870 socket
->m_error
= GSOCK_WOULDBLOCK
;
872 socket
->m_error
= GSOCK_IOERR
;
878 int GSocket_Write(GSocket
*socket
, const char *buffer
, int size
)
882 assert(socket
!= NULL
);
884 if (socket
->m_endpoint
== kOTInvalidEndpointRef
|| socket
->m_server
)
886 socket
->m_error
= GSOCK_INVSOCK
;
890 /* If the socket is blocking, wait for writability (with a timeout) */
891 if (_GSocket_Output_Timeout(socket
) == GSOCK_TIMEDOUT
)
895 if (socket
->m_stream
)
896 ret
= _GSocket_Send_Stream(socket
, buffer
, size
);
898 ret
= _GSocket_Send_Dgram(socket
, buffer
, size
);
902 if (errno
== EWOULDBLOCK
)
903 socket
->m_error
= GSOCK_WOULDBLOCK
;
905 socket
->m_error
= GSOCK_IOERR
;
907 /* Only reenable OUTPUT events after an error (just like WSAAsyncSelect
908 * in MSW). Once the first OUTPUT event is received, users can assume
909 * that the socket is writable until a read operation fails. Only then
910 * will further OUTPUT events be posted.
912 socket
->m_detected
&= ~GSOCK_OUTPUT_FLAG
;
920 * Polls the socket to determine its status. This function will
921 * check for the events specified in the 'flags' parameter, and
922 * it will return a mask indicating which operations can be
923 * performed. This function won't block, regardless of the
924 * mode (blocking | nonblocking) of the socket.
926 GSocketEventFlags
GSocket_Select(GSocket
*socket
, GSocketEventFlags flags
)
928 assert(socket
!= NULL
);
929 wxMacProcessNotifierEvents() ;
931 state = OTGetEndpointState(socket->m_endpoint);
933 if ( ( flags & GSOCK_INPUT_FLAG ) && ! ( socket->m_detected & GSOCK_INPUT_FLAG ) )
936 OTCountDataBytes( socket->m_endpoint , &sz ) ;
937 if ( state == T_INCON || sz > 0 )
939 socket->m_detected |= GSOCK_INPUT_FLAG ;
940 (socket->m_cbacks[GSOCK_INPUT])(socket, GSOCK_INPUT, socket->m_data[GSOCK_INPUT]);
943 if ( ( flags & GSOCK_INPUT_FLAG ) && ! ( socket->m_detected & GSOCK_OUTPUT_FLAG ) )
945 if ( state == T_DATAXFER || state == T_INREL )
947 socket->m_detected |=GSOCK_OUTPUT_FLAG ;
948 (socket->m_cbacks[GSOCK_OUTPUT])(socket, GSOCK_OUTPUT, socket->m_data[GSOCK_OUTPUT]);
952 return ( flags
& socket
->m_detected
) ;
957 /* GSocket_SetNonBlocking:
958 * Sets the socket to non-blocking mode. All IO calls will return
961 void GSocket_SetNonBlocking(GSocket
*socket
, int non_block
)
963 assert(socket
!= NULL
);
965 socket
->m_non_blocking
= non_block
;
968 /* GSocket_SetTimeout:
969 * Sets the timeout for blocking calls. Time is expressed in
972 void GSocket_SetTimeout(GSocket
*socket
, unsigned long millisec
)
974 assert(socket
!= NULL
);
976 // this is usually set too high and we have not yet been able to detect a closed
977 // stream, thus we leave the 10 sec timeout
978 // socket->m_timeout = millisec;
982 * Returns the last error occured for this socket. Note that successful
983 * operations do not clear this back to GSOCK_NOERROR, so use it only
986 GSocketError
GSocket_GetError(GSocket
*socket
)
988 assert(socket
!= NULL
);
990 return socket
->m_error
;
996 * There is data to be read in the input buffer. If, after a read
997 * operation, there is still data available, the callback function will
1000 * The socket is available for writing. That is, the next write call
1001 * won't block. This event is generated only once, when the connection is
1002 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
1003 * when the output buffer empties again. This means that the app should
1004 * assume that it can write since the first OUTPUT event, and no more
1005 * OUTPUT events will be generated unless an error occurs.
1007 * Connection succesfully established, for client sockets, or incoming
1008 * client connection, for server sockets. Wait for this event (also watch
1009 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
1011 * The connection is lost (or a connection request failed); this could
1012 * be due to a failure, or due to the peer closing it gracefully.
1015 /* GSocket_SetCallback:
1016 * Enables the callbacks specified by 'flags'. Note that 'flags'
1017 * may be a combination of flags OR'ed toghether, so the same
1018 * callback function can be made to accept different events.
1019 * The callback function must have the following prototype:
1021 * void function(GSocket *socket, GSocketEvent event, char *cdata)
1023 void GSocket_SetCallback(GSocket
*socket
, GSocketEventFlags flags
,
1024 GSocketCallback callback
, char *cdata
)
1028 assert(socket
!= NULL
);
1030 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1032 if ((flags
& (1 << count
)) != 0)
1034 socket
->m_cbacks
[count
] = callback
;
1035 socket
->m_data
[count
] = cdata
;
1040 /* GSocket_UnsetCallback:
1041 * Disables all callbacks specified by 'flags', which may be a
1042 * combination of flags OR'ed toghether.
1044 void GSocket_UnsetCallback(GSocket
*socket
, GSocketEventFlags flags
)
1048 assert(socket
!= NULL
);
1050 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1052 if ((flags
& (1 << count
)) != 0)
1054 socket
->m_cbacks
[count
] = NULL
;
1055 socket
->m_data
[count
] = NULL
;
1061 #define CALL_CALLBACK(socket, event) { \
1062 _GSocket_Disable(socket, event); \
1063 if (socket->m_cbacks[event]) \
1064 socket->m_cbacks[event](socket, event, socket->m_data[event]); \
1067 int _GSocket_Recv_Stream(GSocket
*socket
, char *buffer
, int size
)
1071 OTByteCount sz
= 0 ;
1073 OTCountDataBytes( socket
->m_endpoint
, &sz
) ;
1076 res
= OTRcv( socket
->m_endpoint
, buffer
, size
, &flags
) ;
1082 // we simulate another read event if there are still bytes
1083 if ( socket
->m_takesEvents
)
1085 OTByteCount sz
= 0 ;
1086 OTCountDataBytes( socket
->m_endpoint
, &sz
) ;
1089 socket
->m_detected
|= GSOCK_INPUT_FLAG
;
1090 (socket
->m_cbacks
[GSOCK_INPUT
])(socket
, GSOCK_INPUT
, socket
->m_data
[GSOCK_INPUT
]);
1096 int _GSocket_Recv_Dgram(GSocket
*socket
, char *buffer
, int size
)
1101 struct sockaddr from
;
1102 SOCKLEN_T fromlen
= sizeof(from
);
1105 fromlen
= sizeof(from
);
1107 ret
= recvfrom(socket
->m_endpoint
, buffer
, size
, 0, &from
, (SOCKLEN_T
*) &fromlen
);
1112 /* Translate a system address into a GSocket address */
1113 if (!socket
->m_peer
)
1115 socket
->m_peer
= GAddress_new();
1116 if (!socket
->m_peer
)
1118 socket
->m_error
= GSOCK_MEMERR
;
1122 err
= _GAddress_translate_from(socket
->m_peer
, &from
, fromlen
);
1123 if (err
!= GSOCK_NOERROR
)
1125 GAddress_destroy(socket
->m_peer
);
1126 socket
->m_peer
= NULL
;
1127 socket
->m_error
= err
;
1134 int _GSocket_Send_Stream(GSocket
*socket
, const char *buffer
, int size
)
1139 res
= OTSnd( socket
->m_endpoint
, (void*) buffer
, size
, flags
) ;
1143 int _GSocket_Send_Dgram(GSocket
*socket
, const char *buffer
, int size
)
1148 struct sockaddr
*addr
;
1152 if (!socket
->m_peer
)
1154 socket
->m_error
= GSOCK_INVADDR
;
1158 err
= _GAddress_translate_to(socket
->m_peer
, &addr
, &len
);
1159 if (err
!= GSOCK_NOERROR
)
1161 socket
->m_error
= err
;
1165 ret
= sendto(socket
->m_endpoint
, buffer
, size
, 0, addr
, len
);
1167 /* Frees memory allocated from _GAddress_translate_to */
1175 * -------------------------------------------------------------------------
1177 * -------------------------------------------------------------------------
1180 /* CHECK_ADDRESS verifies that the current family is either GSOCK_NOFAMILY
1181 * or GSOCK_*family*, and if it is GSOCK_NOFAMILY, it initalizes address
1182 * to be a GSOCK_*family*. In other cases, it returns GSOCK_INVADDR.
1184 #define CHECK_ADDRESS(address, family, retval) \
1186 if (address->m_family == GSOCK_NOFAMILY) \
1187 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1188 return address->m_error; \
1189 if (address->m_family != GSOCK_##family) \
1191 address->m_error = GSOCK_INVADDR; \
1196 GAddress
*GAddress_new()
1200 if ((address
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1203 address
->m_family
= GSOCK_NOFAMILY
;
1204 address
->m_host
= INADDR_NONE
;
1205 address
->m_port
= 0 ;
1210 GAddress
*GAddress_copy(GAddress
*address
)
1214 assert(address
!= NULL
);
1216 if ((addr2
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1219 memcpy(addr2
, address
, sizeof(GAddress
));
1223 void GAddress_destroy(GAddress
*address
)
1225 assert(address
!= NULL
);
1230 void GAddress_SetFamily(GAddress
*address
, GAddressType type
)
1232 assert(address
!= NULL
);
1234 address
->m_family
= type
;
1237 GAddressType
GAddress_GetFamily(GAddress
*address
)
1239 assert(address
!= NULL
);
1241 return address
->m_family
;
1244 GSocketError
_GAddress_translate_from(GAddress
*address
,
1247 switch (addr
->fAddressType
)
1250 address
->m_family
= GSOCK_INET
;
1254 address
->m_family
= GSOCK_INET6
;
1259 address
->m_error
= GSOCK_INVOP
;
1263 address
->m_host
= addr
->fHost
;
1264 address
->m_port
= addr
->fPort
;
1265 return GSOCK_NOERROR
;
1268 GSocketError
_GAddress_translate_to(GAddress
*address
,
1271 if ( GSocket_Verify_Inited() == FALSE
)
1272 return GSOCK_IOERR
;
1273 memset(addr
, 0 , sizeof(struct InetAddress
));
1274 OTInitInetAddress( addr
, address
->m_port
, address
->m_host
) ;
1275 return GSOCK_NOERROR
;
1279 * -------------------------------------------------------------------------
1280 * Internet address family
1281 * -------------------------------------------------------------------------
1284 GSocketError
_GAddress_Init_INET(GAddress
*address
)
1286 address
->m_family
= GSOCK_INET
;
1287 address
->m_host
= kOTAnyInetAddress
;
1289 return GSOCK_NOERROR
;
1292 GSocketError
GAddress_INET_SetHostName(GAddress
*address
, const char *hostname
)
1294 InetHostInfo hinfo
;
1297 if ( GSocket_Verify_Inited() == FALSE
)
1298 return GSOCK_IOERR
;
1300 assert(address
!= NULL
);
1302 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1303 ret
= OTInetStringToAddress( gInetSvcRef
, (char*) hostname
, &hinfo
) ;
1304 if ( ret
!= kOTNoError
)
1306 address
->m_host
= INADDR_NONE
;
1307 address
->m_error
= GSOCK_NOHOST
;
1308 return GSOCK_NOHOST
;
1310 address
->m_host
= hinfo
.addrs
[0] ;
1311 return GSOCK_NOERROR
;
1314 GSocketError
GAddress_INET_SetAnyAddress(GAddress
*address
)
1316 return GAddress_INET_SetHostAddress(address
, INADDR_ANY
);
1319 GSocketError
GAddress_INET_SetHostAddress(GAddress
*address
,
1320 unsigned long hostaddr
)
1322 assert(address
!= NULL
);
1324 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1326 address
->m_host
= hostaddr
;
1328 return GSOCK_NOERROR
;
1331 struct service_entry
1334 unsigned short port
;
1337 typedef struct service_entry service_entry
;
1339 service_entry gServices
[] =
1341 { "http" , 80 , "tcp" }
1344 GSocketError
GAddress_INET_SetPortName(GAddress
*address
, const char *port
,
1345 const char *protocol
)
1349 assert(address
!= NULL
);
1350 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1354 address
->m_error
= GSOCK_INVPORT
;
1355 return GSOCK_INVPORT
;
1357 for ( i
= 0 ; i
< sizeof( gServices
) / sizeof( service_entry
) ; ++i
)
1359 if ( strcmp( port
, gServices
[i
].name
) == 0 )
1361 if ( protocol
== NULL
|| strcmp( protocol
, gServices
[i
].protocol
) )
1363 address
->m_port
= gServices
[i
].port
;
1364 return GSOCK_NOERROR
;
1369 if (isdigit(port
[0]))
1371 address
->m_port
= atoi(port
);
1372 return GSOCK_NOERROR
;
1375 address
->m_error
= GSOCK_INVPORT
;
1376 return GSOCK_INVPORT
;
1379 GSocketError
GAddress_INET_SetPort(GAddress
*address
, unsigned short port
)
1381 assert(address
!= NULL
);
1382 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1383 address
->m_port
= port
;
1385 return GSOCK_NOERROR
;
1388 GSocketError
GAddress_INET_GetHostName(GAddress
*address
, char *hostname
, size_t sbuf
)
1390 InetDomainName name
;
1391 if ( GSocket_Verify_Inited() == FALSE
)
1392 return GSOCK_IOERR
;
1394 assert(address
!= NULL
);
1395 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1397 OTInetAddressToName( gInetSvcRef
, address
->m_host
, name
) ;
1398 strncpy( hostname
, name
, sbuf
) ;
1399 return GSOCK_NOERROR
;
1402 unsigned long GAddress_INET_GetHostAddress(GAddress
*address
)
1404 assert(address
!= NULL
);
1405 CHECK_ADDRESS(address
, INET
, 0);
1407 return address
->m_host
;
1410 unsigned short GAddress_INET_GetPort(GAddress
*address
)
1412 assert(address
!= NULL
);
1413 CHECK_ADDRESS(address
, INET
, 0);
1415 return address
->m_port
;
1418 void _GSocket_Enable_Events(GSocket
*socket
)
1420 if ( socket
->m_takesEvents
)
1425 socket
->m_takesEvents
= TRUE
;
1426 state
= OTGetEndpointState(socket
->m_endpoint
);
1429 OTByteCount sz
= 0 ;
1430 OTCountDataBytes( socket
->m_endpoint
, &sz
) ;
1431 if ( state
== T_INCON
|| sz
> 0 )
1433 socket
->m_detected
|= GSOCK_INPUT_FLAG
;
1434 (socket
->m_cbacks
[GSOCK_INPUT
])(socket
, GSOCK_INPUT
, socket
->m_data
[GSOCK_INPUT
]);
1438 if ( state
== T_DATAXFER
|| state
== T_INREL
)
1440 socket
->m_detected
|=GSOCK_OUTPUT_FLAG
;
1441 (socket
->m_cbacks
[GSOCK_OUTPUT
])(socket
, GSOCK_OUTPUT
, socket
->m_data
[GSOCK_OUTPUT
]);
1447 void _GSocket_Disable_Events(GSocket
*socket
)
1449 socket
->m_takesEvents
= FALSE
;
1452 /* _GSocket_Input_Timeout:
1453 * For blocking sockets, wait until data is available or
1454 * until timeout ellapses.
1456 GSocketError
_GSocket_Input_Timeout(GSocket
*socket
)
1458 if ( !socket
->m_non_blocking
)
1460 UnsignedWide now
, start
;
1461 short formerTakesEvents
= socket
->m_takesEvents
;
1462 Microseconds(&start
);
1464 socket
->m_takesEvents
= FALSE
;
1466 while( (now
.hi
* 4294967296.0 + now
.lo
) - (start
.hi
* 4294967296.0 + start
.lo
) < socket
->m_timeout
* 1000.0 )
1469 OTByteCount sz
= 0 ;
1470 state
= OTGetEndpointState(socket
->m_endpoint
);
1472 OTCountDataBytes( socket
->m_endpoint
, &sz
) ;
1473 if ( state
== T_INCON
|| sz
> 0 )
1475 socket
->m_takesEvents
= formerTakesEvents
;
1476 return GSOCK_NOERROR
;
1480 socket
->m_takesEvents
= formerTakesEvents
;
1481 socket
->m_error
= GSOCK_TIMEDOUT
;
1482 return GSOCK_TIMEDOUT
;
1484 return GSOCK_NOERROR
;
1487 /* _GSocket_Output_Timeout:
1488 * For blocking sockets, wait until data can be sent without
1489 * blocking or until timeout ellapses.
1491 GSocketError
_GSocket_Output_Timeout(GSocket
*socket
)
1493 if ( !socket
->m_non_blocking
)
1495 UnsignedWide now
, start
;
1496 short formerTakesEvents
= socket
->m_takesEvents
;
1497 Microseconds(&start
);
1499 socket
->m_takesEvents
= FALSE
;
1501 while( (now
.hi
* 4294967296.0 + now
.lo
) - (start
.hi
* 4294967296.0 + start
.lo
) < socket
->m_timeout
* 1000.0 )
1504 state
= OTGetEndpointState(socket
->m_endpoint
);
1506 if ( state
== T_DATAXFER
|| state
== T_INREL
)
1508 socket
->m_takesEvents
= formerTakesEvents
;
1509 return GSOCK_NOERROR
;
1513 socket
->m_takesEvents
= formerTakesEvents
;
1514 socket
->m_error
= GSOCK_TIMEDOUT
;
1515 return GSOCK_TIMEDOUT
;
1517 return GSOCK_NOERROR
;
1521 * There is data to be read in the input buffer. If, after a read
1522 * operation, there is still data available, the callback function will
1525 * The socket is available for writing. That is, the next write call
1526 * won't block. This event is generated only once, when the connection is
1527 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
1528 * when the output buffer empties again. This means that the app should
1529 * assume that it can write since the first OUTPUT event, and no more
1530 * OUTPUT events will be generated unless an error occurs.
1532 * Connection succesfully established, for client sockets, or incoming
1533 * client connection, for server sockets. Wait for this event (also watch
1534 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
1536 * The connection is lost (or a connection request failed); this could
1537 * be due to a failure, or due to the peer closing it gracefully.
1540 void _GSocket_Internal_Proc(unsigned long e
, void* d
)
1543 GSocket
* socket
= (GSocket
*) d
;
1544 OTEventCode ev
= (OTEventCode
) e
;
1546 GSocketEvent event2
;
1547 GSocketCallback cback
;
1549 GSocketCallback cback2
;
1554 event
= GSOCK_MAX_EVENT
;
1555 event2
= GSOCK_MAX_EVENT
;
1561 /* Check that the socket still exists (it has not been
1562 * destroyed) and for safety, check that the m_endpoint field
1563 * is what we expect it to be.
1565 if ((socket
!= NULL
) && (socket
->m_takesEvents
))
1570 event
= GSOCK_CONNECTION
;
1573 event
= GSOCK_CONNECTION
;
1574 event2
= GSOCK_OUTPUT
;
1578 retCall
.addr
.buf
= NULL
;
1579 retCall
.addr
.maxlen
= 0;
1580 retCall
.opt
.buf
= NULL
;
1581 retCall
.opt
.maxlen
= 0;
1582 retCall
.udata
.buf
= NULL
;
1583 retCall
.udata
.maxlen
= 0;
1584 OTRcvConnect( socket
->m_endpoint
, &retCall
) ;
1588 event
= GSOCK_LOST
;
1592 event
= GSOCK_OUTPUT
;
1595 event
= GSOCK_INPUT
;
1598 event
= GSOCK_INPUT
;
1601 if (event
!= GSOCK_MAX_EVENT
)
1603 cback
= socket
->m_cbacks
[event
];
1604 data
= socket
->m_data
[event
];
1606 if (event
== GSOCK_LOST
)
1607 socket
->m_detected
= GSOCK_LOST_FLAG
;
1609 socket
->m_detected
|= (1 << event
);
1611 if (event2
!= GSOCK_MAX_EVENT
)
1613 cback2
= socket
->m_cbacks
[event2
];
1614 data2
= socket
->m_data
[event2
];
1616 if (event2
== GSOCK_LOST
)
1617 socket
->m_detected
= GSOCK_LOST_FLAG
;
1619 socket
->m_detected
|= (1 << event2
);
1623 /* OK, we can now leave the critical section because we have
1624 * already obtained the callback address (we make no further
1625 * accesses to socket->whatever). However, the app should
1626 * be prepared to handle events from a socket that has just
1631 (cback
)(socket
, event
, data
);
1633 (cback2
)(socket
, event2
, data2
);
1637 /* Hack added for Mac OS X */
1638 GSocketError
GAddress_UNIX_GetPath(GAddress
*addr
, char *path
, size_t buf
)
1640 return GSOCK_INVADDR
;
1643 GSocketError
GAddress_UNIX_SetPath(GAddress
*addr
, const char *path
)
1645 return GSOCK_INVADDR
;
1648 #endif /* wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__) */