1 /* -------------------------------------------------------------------------
2 * Project: GSocket (Generic Socket) for WX
3 * Name: src/mac/classic/gsocket.c
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__
17 #include "wx/platform.h"
20 #if wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__)
23 #include <CoreServices/CoreServices.h>
32 #include <MacHeaders.c>
33 #define OTUNIXERRORS 1
34 #include <OpenTransport.h>
35 #include <OpenTransportProviders.h>
36 #include <OpenTptInternet.h>
38 #if TARGET_CARBON && !defined(OTAssert)
39 #define OTAssert( str , cond ) /* does not exists in Carbon */
53 * INADDR_BROADCAST is identical to INADDR_NONE which is not defined
54 * on all unices. INADDR_BROADCAST should be fine to indicate an error.
56 #ifndef INADDR_BROADCAST
57 #define INADDR_BROADCAST 0xFFFFFFFFUL
60 #define INADDR_NONE INADDR_BROADCAST
63 #define INADDR_ANY 0x0UL
65 #ifndef __GSOCKET_STANDALONE__
67 #include "wx/mac/macnotfy.h"
68 #include "wx/mac/gsockmac.h"
69 #include "wx/gsocket.h"
76 #endif /* __GSOCKET_STANDALONE__ */
82 extern pascal void OTDebugStr(const char* str
);
87 InetSvcRef gInetSvcRef
= 0 ;
89 OTNotifyUPP gOTNotifierUPP
= NULL
;
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
127 opt
->name
= kIP_REUSEADDR
;
129 opt
->name
= IP_REUSEADDR
;
131 opt
->len
= kOTFourByteOptionSize
;
133 *(UInt32
*)opt
->value
= enableReuseIPMode
; // set the desired option level, true or false
135 err
= OTOptionManagement(ep
, &req
, &ret
);
137 // if no error then return the option status value
138 if (err
== kOTNoError
)
140 if (opt
->status
!= T_SUCCESS
)
150 pascal void OTInetEventHandler(void*s
, OTEventCode event
, OTResult
, void *cookie
) ;
151 pascal void OTInetEventHandler(void*s
, OTEventCode event
, OTResult result
, void *cookie
)
154 GSocket
* sock
= (GSocket
*) s
;
156 if ( event
== kOTSyncIdleEvent
)
164 wxMacAddEvent( sock
->m_mac_events
, _GSocket_Internal_Proc
, event
, s
, wakeUp
) ;
170 static void SetDefaultEndpointModes(EndpointRef ep
, void *data
)
171 // This routine sets the supplied endpoint into the default
172 // mode used in this application. The specifics are:
173 // blocking, synchronous, and using synch idle events with
174 // the standard YieldingNotifier.
176 OSStatus junk
= kOTNoError
;
177 OTAssert ("SetDefaultEndpointModes:invalid ref", ep
!= kOTInvalidEndpointRef
) ;
178 junk
= OTSetAsynchronous(ep
);
179 OTAssert("SetDefaultEndpointModes: Could not set asynchronous", junk
== noErr
);
181 junk = OTSetBlocking(ep);
182 OTAssert("SetDefaultEndpointModes: Could not set blocking", junk == noErr);
183 junk = OTSetSynchronous(ep);
184 OTAssert("SetDefaultEndpointModes: Could not set synchronous", junk == noErr);
185 junk = OTSetBlocking(ep);
186 OTAssert("SetDefaultEndpointModes: Could not set blocking", junk == noErr);
188 junk
= OTInstallNotifier(ep
, gOTNotifierUPP
, data
);
189 OTAssert("SetDefaultEndpointModes: Could not install notifier", junk
== noErr
);
191 junk = OTUseSyncIdleEvents(ep, true);
192 OTAssert("SetDefaultEndpointModes: Could not use sync idle events", junk == noErr);
196 /* Global initialisers */
198 void GSocket_SetGUIFunctions(struct GSocketGUIFunctionsTable
*table
)
200 // do nothing, wxMac doesn't have wxBase-GUI separation yet
208 int GSocket_Verify_Inited() ;
209 int GSocket_Verify_Inited()
213 // Marc Newsam: added the clientcontext variable
214 // however, documentation is unclear how this works
215 OTClientContextPtr clientcontext
;
220 InitOpenTransportInContext(kInitOTForApplicationMask
, &clientcontext
);
222 gInetSvcRef
= OTOpenInternetServicesInContext(kDefaultInternetServicesPath
,
223 NULL
, &err
, clientcontext
);
228 InitOpenTransport() ;
230 gInetSvcRef
= OTOpenInternetServices(kDefaultInternetServicesPath
, NULL
, &err
);
232 if ( gInetSvcRef
== NULL
|| err
!= kOTNoError
)
234 OTAssert("Could not open Inet Services", err
== noErr
);
237 gOTNotifierUPP
= NewOTNotifyUPP( OTInetEventHandler
) ;
241 void GSocket_Cleanup()
243 if ( gOTInited
!= 0 )
245 if ( gInetSvcRef
!= NULL
)
246 OTCloseProvider( gInetSvcRef
);
248 CloseOpenTransportInContext( NULL
) ;
250 CloseOpenTransport() ;
252 if ( gOTNotifierUPP
)
253 DisposeOTNotifyUPP( gOTNotifierUPP
) ;
257 /* Constructors / Destructors for GSocket */
259 GSocket
*GSocket_new()
265 if ( GSocket_Verify_Inited() == FALSE
)
268 socket
= (GSocket
*)malloc(sizeof(GSocket
));
273 socket
->m_endpoint
= NULL
;
274 for (i
=0;i
<GSOCK_MAX_EVENT
;i
++)
276 socket
->m_cbacks
[i
] = NULL
;
278 socket
->m_detected
= 0;
279 socket
->m_local
= NULL
;
280 socket
->m_peer
= NULL
;
281 socket
->m_error
= GSOCK_NOERROR
;
282 socket
->m_server
= FALSE
;
283 socket
->m_stream
= TRUE
;
284 socket
->m_non_blocking
= FALSE
;
285 socket
->m_timeout
= 1*1000;
286 /* 10 sec * 1000 millisec */
287 socket
->m_takesEvents
= TRUE
;
288 socket
->m_mac_events
= wxMacGetNotifierTable() ;
292 void GSocket_destroy(GSocket
*socket
)
294 assert(socket
!= NULL
);
296 /* Check that the socket is really shutdowned */
297 if (socket
->m_endpoint
!= kOTInvalidEndpointRef
)
298 GSocket_Shutdown(socket
);
301 /* Destroy private addresses */
303 GAddress_destroy(socket
->m_local
);
306 GAddress_destroy(socket
->m_peer
);
308 /* Destroy the socket itself */
313 * Disallow further read/write operations on this socket, close
314 * the fd and disable all callbacks.
316 void GSocket_Shutdown(GSocket
*socket
)
321 assert(socket
!= NULL
);
323 /* If socket has been created, shutdown it */
324 if (socket
->m_endpoint
!= kOTInvalidEndpointRef
)
326 err
= OTSndOrderlyDisconnect( socket
->m_endpoint
) ;
327 if ( err
!= kOTNoError
)
331 err
= OTRcvOrderlyDisconnect( socket
->m_endpoint
) ;
332 err
= OTUnbind( socket
->m_endpoint
) ;
333 err
= OTCloseProvider( socket
->m_endpoint
) ;
334 socket
->m_endpoint
= kOTInvalidEndpointRef
;
337 /* Disable GUI callbacks */
338 for (evt
= 0; evt
< GSOCK_MAX_EVENT
; evt
++)
339 socket
->m_cbacks
[evt
] = NULL
;
341 socket
->m_detected
= 0;
342 _GSocket_Disable_Events(socket
);
343 wxMacRemoveAllNotifiersForData( wxMacGetNotifierTable() , socket
) ;
347 /* Address handling */
353 * Set or get the local or peer address for this socket. The 'set'
354 * functions return GSOCK_NOERROR on success, an error code otherwise.
355 * The 'get' functions return a pointer to a GAddress object on success,
356 * or NULL otherwise, in which case they set the error code of the
357 * corresponding GSocket.
360 * GSOCK_INVSOCK - the socket is not valid.
361 * GSOCK_INVADDR - the address is not valid.
363 GSocketError
GSocket_SetLocal(GSocket
*socket
, GAddress
*address
)
365 assert(socket
!= NULL
);
367 /* the socket must be initialized, or it must be a server */
368 if ((socket
->m_endpoint
!= kOTInvalidEndpointRef
&& !socket
->m_server
))
370 socket
->m_error
= GSOCK_INVSOCK
;
371 return GSOCK_INVSOCK
;
375 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
377 socket
->m_error
= GSOCK_INVADDR
;
378 return GSOCK_INVADDR
;
382 GAddress_destroy(socket
->m_local
);
384 socket
->m_local
= GAddress_copy(address
);
386 return GSOCK_NOERROR
;
389 GSocketError
GSocket_SetPeer(GSocket
*socket
, GAddress
*address
)
391 assert(socket
!= NULL
);
394 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
396 socket
->m_error
= GSOCK_INVADDR
;
397 return GSOCK_INVADDR
;
401 GAddress_destroy(socket
->m_peer
);
403 socket
->m_peer
= GAddress_copy(address
);
405 return GSOCK_NOERROR
;
408 GAddress
*GSocket_GetLocal(GSocket
*socket
)
410 GAddress
*address
= NULL
;
414 assert(socket
!= NULL
);
416 /* try to get it from the m_local var first */
418 return GAddress_copy(socket
->m_local
);
420 /* else, if the socket is initialized, try getsockname */
421 if (socket
->m_endpoint
== kOTInvalidEndpointRef
)
423 socket
->m_error
= GSOCK_INVSOCK
;
428 /* we do not support multihoming with this code at the moment
429 OTGetProtAddress will have to be used then - but we don't have a handy
430 method to use right now
433 InetInterfaceInfo info
;
434 OTInetGetInterfaceInfo(&info
, kDefaultInetInterface
);
435 loc
.fHost
= info
.fAddress
;
437 loc
.fAddressType
= AF_INET
;
440 /* got a valid address from getsockname, create a GAddress object */
441 address
= GAddress_new();
444 socket
->m_error
= GSOCK_MEMERR
;
448 err
= _GAddress_translate_from(address
, &loc
);
449 if (err
!= GSOCK_NOERROR
)
451 GAddress_destroy(address
);
452 socket
->m_error
= err
;
459 GAddress
*GSocket_GetPeer(GSocket
*socket
)
461 assert(socket
!= NULL
);
463 /* try to get it from the m_peer var */
465 return GAddress_copy(socket
->m_peer
);
470 /* Server specific parts */
472 /* GSocket_SetServer:
473 * Sets up this socket as a server. The local address must have been
474 * set with GSocket_SetLocal() before GSocket_SetServer() is called.
475 * Returns GSOCK_NOERROR on success, one of the following otherwise:
478 * GSOCK_INVSOCK - the socket is in use.
479 * GSOCK_INVADDR - the local address has not been set.
480 * GSOCK_IOERR - low-level error.
482 GSocketError
GSocket_SetServer(GSocket
*sck
)
486 /* must not be in use */
487 if (sck
->m_endpoint
!= kOTInvalidEndpointRef
)
489 sck
->m_error
= GSOCK_INVSOCK
;
490 return GSOCK_INVSOCK
;
493 /* the local addr must have been set */
496 sck
->m_error
= GSOCK_INVADDR
;
497 return GSOCK_INVADDR
;
500 /* Initialize all fields */
501 sck
->m_stream
= TRUE
;
502 sck
->m_server
= TRUE
;
503 sck
->m_oriented
= TRUE
;
507 /* Create the socket */
508 sck
->m_endpoint
= socket(sck
->m_local
->m_realfamily
, SOCK_STREAM
, 0);
509 socket_set_ref( sck
->m_endpoint
, (unsigned long) &gMacNetEvents
, (unsigned long) sck
) ;
510 if (sck
->m_endpoint
== kOTInvalidEndpointRef
)
512 sck
->m_error
= GSOCK_IOERR
;
516 ioctl(sck
->m_endpoint
, FIONBIO
, &arg
);
517 _GSocket_Enable_Events(sck
);
519 /* Bind to the local address,
520 * retrieve the actual address bound,
521 * and listen up to 5 connections.
523 if ((bind(sck
->m_endpoint
, sck
->m_local
->m_addr
, sck
->m_local
->m_len
) != 0) ||
524 (getsockname(sck
->m_endpoint
,
525 sck
->m_local
->m_addr
,
526 (WX_SOCKLEN_T
*) &sck
->m_local
->m_len
) != 0) ||
527 (listen(sck
->m_endpoint
, 5) != 0))
529 close(sck
->m_endpoint
);
530 sck
->m_endpoint
= -1;
531 sck
->m_error
= GSOCK_IOERR
;
535 return GSOCK_NOERROR
;
538 /* GSocket_WaitConnection:
539 * Waits for an incoming client connection. Returns a pointer to
540 * a GSocket object, or NULL if there was an error, in which case
541 * the last error field will be updated for the calling GSocket.
543 * Error codes (set in the calling GSocket)
544 * GSOCK_INVSOCK - the socket is not valid or not a server.
545 * GSOCK_TIMEDOUT - timeout, no incoming connections.
546 * GSOCK_WOULDBLOCK - the call would block and the socket is nonblocking.
547 * GSOCK_MEMERR - couldn't allocate memory.
548 * GSOCK_IOERR - low-level error.
550 GSocket
*GSocket_WaitConnection(GSocket
*socket
)
552 GSocket
*connection
= NULL
;
554 assert(socket
!= NULL
);
556 /* Reenable CONNECTION events */
557 socket
->m_detected
&= ~GSOCK_CONNECTION_FLAG
;
559 /* If the socket has already been created, we exit immediately */
560 if (socket
->m_endpoint
== kOTInvalidEndpointRef
|| !socket
->m_server
)
562 socket
->m_error
= GSOCK_INVSOCK
;
566 /* Create a GSocket object for the new connection */
567 connection
= GSocket_new();
571 socket
->m_error
= GSOCK_MEMERR
;
575 /* Wait for a connection (with timeout) */
576 if (_GSocket_Input_Timeout(socket
) == GSOCK_TIMEDOUT
)
578 GSocket_destroy(connection
);
579 /* socket->m_error set by _GSocket_Input_Timeout */
585 connection
->m_endpoint
= accept(socket
->m_endpoint
, &from
, (WX_SOCKLEN_T
*) &fromlen
);
588 if (connection
->m_endpoint
== kOTInvalidEndpointRef
)
590 if (errno
== EWOULDBLOCK
)
591 socket
->m_error
= GSOCK_WOULDBLOCK
;
593 socket
->m_error
= GSOCK_IOERR
;
595 GSocket_destroy(connection
);
599 /* Initialize all fields */
600 connection
->m_server
= FALSE
;
601 connection
->m_stream
= TRUE
;
602 connection
->m_oriented
= TRUE
;
604 /* Setup the peer address field */
605 connection
->m_peer
= GAddress_new();
606 if (!connection
->m_peer
)
608 GSocket_destroy(connection
);
609 socket
->m_error
= GSOCK_MEMERR
;
614 err
= _GAddress_translate_from(connection
->m_peer
, &from
, fromlen
);
615 if (err
!= GSOCK_NOERROR
)
617 GAddress_destroy(connection
->m_peer
);
618 GSocket_destroy(connection
);
619 socket
->m_error
= err
;
623 ioctl(connection
->m_endpoint
, FIONBIO
, &arg
);
625 _GSocket_Enable_Events(connection
);
630 /* Datagram sockets */
632 /* GSocket_SetNonOriented:
633 * Sets up this socket as a non-connection oriented (datagram) socket.
634 * Before using this function, the local address must have been set
635 * with GSocket_SetLocal(), or the call will fail. Returns GSOCK_NOERROR
636 * on success, or one of the following otherwise.
639 * GSOCK_INVSOCK - the socket is in use.
640 * GSOCK_INVADDR - the local address has not been set.
641 * GSOCK_IOERR - low-level error.
643 GSocketError
GSocket_SetNonOriented(GSocket
*sck
)
647 if (sck
->m_endpoint
!= kOTInvalidEndpointRef
)
649 sck
->m_error
= GSOCK_INVSOCK
;
650 return GSOCK_INVSOCK
;
655 sck
->m_error
= GSOCK_INVADDR
;
656 return GSOCK_INVADDR
;
659 /* Initialize all fields */
660 sck
->m_stream
= FALSE
;
661 sck
->m_server
= FALSE
;
662 sck
->m_oriented
= FALSE
;
664 /* Create the socket */
668 sck
->m_endpoint
= socket(sck
->m_local
->m_realfamily
, SOCK_DGRAM
, 0);
669 socket_set_ref( sck
->m_endpoint
, (unsigned long) &gMacNetEvents
, (unsigned long) sck
) ;
671 if (sck
->m_endpoint
== kOTInvalidEndpointRef
)
673 sck
->m_error
= GSOCK_IOERR
;
679 ioctl(sck
->m_endpoint
, FIONBIO
, &arg
);
681 _GSocket_Enable_Events(sck
);
683 /* Bind to the local address,
684 * and retrieve the actual address bound.
688 if ((bind(sck
->m_endpoint
, sck
->m_local
->m_addr
, sck
->m_local
->m_len
) != 0) ||
689 (getsockname(sck
->m_endpoint
,
690 sck
->m_local
->m_addr
,
691 (WX_SOCKLEN_T
*) &sck
->m_local
->m_len
) != 0))
693 close(sck
->m_endpoint
);
694 sck
->m_endpoint
= -1;
695 sck
->m_error
= GSOCK_IOERR
;
699 return GSOCK_NOERROR
;
702 /* Client specific parts */
705 * For stream (connection oriented) sockets, GSocket_Connect() tries
706 * to establish a client connection to a server using the peer address
707 * as established with GSocket_SetPeer(). Returns GSOCK_NOERROR if the
708 * connection has been successfully established, or one of the error
709 * codes listed below. Note that for nonblocking sockets, a return
710 * value of GSOCK_WOULDBLOCK doesn't mean a failure. The connection
711 * request can be completed later; you should use GSocket_Select()
712 * to poll for GSOCK_CONNECTION | GSOCK_LOST, or wait for the
713 * corresponding asynchronous events.
715 * For datagram (non connection oriented) sockets, GSocket_Connect()
716 * just sets the peer address established with GSocket_SetPeer() as
717 * default destination.
720 * GSOCK_INVSOCK - the socket is in use or not valid.
721 * GSOCK_INVADDR - the peer address has not been established.
722 * GSOCK_TIMEDOUT - timeout, the connection failed.
723 * GSOCK_WOULDBLOCK - connection in progress (nonblocking sockets only)
724 * GSOCK_MEMERR - couldn't allocate memory.
725 * GSOCK_IOERR - low-level error.
727 GSocketError
GSocket_Connect(GSocket
*sck
, GSocketStream stream
)
731 OSStatus err
= kOTNoError
;
736 /* Enable CONNECTION events (needed for nonblocking connections) */
737 sck
->m_detected
&= ~GSOCK_CONNECTION_FLAG
;
739 if (sck
->m_endpoint
!= kOTInvalidEndpointRef
)
741 sck
->m_error
= GSOCK_INVSOCK
;
742 return GSOCK_INVSOCK
;
747 sck
->m_error
= GSOCK_INVADDR
;
748 return GSOCK_INVADDR
;
751 /* Streamed or dgram socket? */
752 sck
->m_stream
= (stream
== GSOCK_STREAMED
);
753 sck
->m_oriented
= TRUE
;
754 sck
->m_server
= FALSE
;
756 /* Create the socket */
759 OTOpenEndpointInContext( OTCreateConfiguration( kTCPName
) , 0 , &info
, &err
, NULL
) ;
762 OTOpenEndpoint( OTCreateConfiguration( kTCPName
) , 0 , &info
, &err
) ;
764 if ( sck
->m_endpoint
== kOTInvalidEndpointRef
|| err
!= kOTNoError
)
766 sck
->m_endpoint
= kOTInvalidEndpointRef
;
767 sck
->m_error
= GSOCK_IOERR
;
770 err
= OTBind( sck
->m_endpoint
, nil
, nil
) ;
771 if ( err
!= kOTNoError
)
775 SetDefaultEndpointModes( sck
->m_endpoint
, sck
) ;
778 ioctl(sck
->m_endpoint
, FIONBIO
, &arg
);
780 _GSocket_Enable_Events(sck
);
782 _GAddress_translate_to( sck
->m_peer
, &addr
) ;
783 memset( &peer
, 0 , sizeof( TCall
) ) ;
784 peer
.addr
.len
= sizeof( InetAddress
) ;
785 peer
.addr
.buf
= (unsigned char*) &addr
;
786 err
= OTConnect( sck
->m_endpoint
, &peer
, nil
) ;
789 /* If connect failed with EINPROGRESS and the GSocket object
790 * is in blocking mode, we select() for the specified timeout
791 * checking for writability to see if the connection request
795 if ((err
== kOTNoDataErr
) && (!sck
->m_non_blocking
))
797 if (_GSocket_Output_Timeout(sck
) == GSOCK_TIMEDOUT
)
799 OTSndOrderlyDisconnect( sck
->m_endpoint
) ;
800 sck
->m_endpoint
= kOTInvalidEndpointRef
;
801 /* sck->m_error is set in _GSocket_Output_Timeout */
802 return GSOCK_TIMEDOUT
;
808 WX_SOCKLEN_T len = sizeof(error);
810 getsockopt(sck->m_endpoint, SOL_SOCKET, SO_ERROR, (void*) &error, &len);
814 return GSOCK_NOERROR
;
818 /* If connect failed with EINPROGRESS and the GSocket object
819 * is set to nonblocking, we set m_error to GSOCK_WOULDBLOCK
820 * (and return GSOCK_WOULDBLOCK) but we don't close the socket;
821 * this way if the connection completes, a GSOCK_CONNECTION
822 * event will be generated, if enabled.
824 if ((err
== kOTNoDataErr
) && (sck
->m_non_blocking
))
826 sck
->m_error
= GSOCK_WOULDBLOCK
;
827 return GSOCK_WOULDBLOCK
;
830 /* If connect failed with an error other than EINPROGRESS,
831 * then the call to GSocket_Connect has failed.
833 OTSndOrderlyDisconnect( sck
->m_endpoint
) ;
835 sck
->m_endpoint
= kOTInvalidEndpointRef
;
836 sck
->m_error
= GSOCK_IOERR
;
839 // OTInetEventHandler(sck, T_CONNECT , kOTNoError , NULL ) ;
840 return GSOCK_NOERROR
;
845 /* Like recv(), send(), ... */
846 int GSocket_Read(GSocket
*socket
, char *buffer
, int size
)
850 assert(socket
!= NULL
);
852 /* Reenable INPUT events */
853 socket
->m_detected
&= ~GSOCK_INPUT_FLAG
;
855 if (socket
->m_endpoint
== kOTInvalidEndpointRef
|| socket
->m_server
)
857 socket
->m_error
= GSOCK_INVSOCK
;
861 /* If the socket is blocking, wait for data (with a timeout) */
862 if (_GSocket_Input_Timeout(socket
) == GSOCK_TIMEDOUT
)
866 if (socket
->m_stream
)
867 ret
= _GSocket_Recv_Stream(socket
, buffer
, size
);
869 ret
= _GSocket_Recv_Dgram(socket
, buffer
, size
);
873 if (errno
== EWOULDBLOCK
)
874 socket
->m_error
= GSOCK_WOULDBLOCK
;
876 socket
->m_error
= GSOCK_IOERR
;
882 int GSocket_Write(GSocket
*socket
, const char *buffer
, int size
)
886 assert(socket
!= NULL
);
888 if (socket
->m_endpoint
== kOTInvalidEndpointRef
|| socket
->m_server
)
890 socket
->m_error
= GSOCK_INVSOCK
;
894 /* If the socket is blocking, wait for writability (with a timeout) */
895 if (_GSocket_Output_Timeout(socket
) == GSOCK_TIMEDOUT
)
899 if (socket
->m_stream
)
900 ret
= _GSocket_Send_Stream(socket
, buffer
, size
);
902 ret
= _GSocket_Send_Dgram(socket
, buffer
, size
);
906 if (errno
== EWOULDBLOCK
)
907 socket
->m_error
= GSOCK_WOULDBLOCK
;
909 socket
->m_error
= GSOCK_IOERR
;
911 /* Only reenable OUTPUT events after an error (just like WSAAsyncSelect
912 * in MSW). Once the first OUTPUT event is received, users can assume
913 * that the socket is writable until a read operation fails. Only then
914 * will further OUTPUT events be posted.
916 socket
->m_detected
&= ~GSOCK_OUTPUT_FLAG
;
924 * Polls the socket to determine its status. This function will
925 * check for the events specified in the 'flags' parameter, and
926 * it will return a mask indicating which operations can be
927 * performed. This function won't block, regardless of the
928 * mode (blocking | nonblocking) of the socket.
930 GSocketEventFlags
GSocket_Select(GSocket
*socket
, GSocketEventFlags flags
)
932 assert(socket
!= NULL
);
933 wxMacProcessNotifierEvents() ;
935 state = OTGetEndpointState(socket->m_endpoint);
937 if ( ( flags & GSOCK_INPUT_FLAG ) && ! ( socket->m_detected & GSOCK_INPUT_FLAG ) )
940 OTCountDataBytes( socket->m_endpoint , &sz ) ;
941 if ( state == T_INCON || sz > 0 )
943 socket->m_detected |= GSOCK_INPUT_FLAG ;
944 (socket->m_cbacks[GSOCK_INPUT])(socket, GSOCK_INPUT, socket->m_data[GSOCK_INPUT]);
947 if ( ( flags & GSOCK_INPUT_FLAG ) && ! ( socket->m_detected & GSOCK_OUTPUT_FLAG ) )
949 if ( state == T_DATAXFER || state == T_INREL )
951 socket->m_detected |=GSOCK_OUTPUT_FLAG ;
952 (socket->m_cbacks[GSOCK_OUTPUT])(socket, GSOCK_OUTPUT, socket->m_data[GSOCK_OUTPUT]);
956 return ( flags
& socket
->m_detected
) ;
961 /* GSocket_SetNonBlocking:
962 * Sets the socket to non-blocking mode. All IO calls will return
965 void GSocket_SetNonBlocking(GSocket
*socket
, int non_block
)
967 assert(socket
!= NULL
);
969 socket
->m_non_blocking
= non_block
;
972 /* GSocket_SetTimeout:
973 * Sets the timeout for blocking calls. Time is expressed in
976 void GSocket_SetTimeout(GSocket
*socket
, unsigned long millisec
)
978 assert(socket
!= NULL
);
980 // this is usually set too high and we have not yet been able to detect a closed
981 // stream, thus we leave the 10 sec timeout
982 // socket->m_timeout = millisec;
986 * Returns the last error which occurred for this socket. Note that successful
987 * operations do not clear this back to GSOCK_NOERROR, so use it only
990 GSocketError
GSocket_GetError(GSocket
*socket
)
992 assert(socket
!= NULL
);
994 return socket
->m_error
;
1000 * There is data to be read in the input buffer. If, after a read
1001 * operation, there is still data available, the callback function will
1004 * The socket is available for writing. That is, the next write call
1005 * won't block. This event is generated only once, when the connection is
1006 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
1007 * when the output buffer empties again. This means that the app should
1008 * assume that it can write since the first OUTPUT event, and no more
1009 * OUTPUT events will be generated unless an error occurs.
1011 * Connection successfully established, for client sockets, or incoming
1012 * client connection, for server sockets. Wait for this event (also watch
1013 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
1015 * The connection is lost (or a connection request failed); this could
1016 * be due to a failure, or due to the peer closing it gracefully.
1019 /* GSocket_SetCallback:
1020 * Enables the callbacks specified by 'flags'. Note that 'flags'
1021 * may be a combination of flags OR'ed toghether, so the same
1022 * callback function can be made to accept different events.
1023 * The callback function must have the following prototype:
1025 * void function(GSocket *socket, GSocketEvent event, char *cdata)
1027 void GSocket_SetCallback(GSocket
*socket
, GSocketEventFlags flags
,
1028 GSocketCallback callback
, char *cdata
)
1032 assert(socket
!= NULL
);
1034 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1036 if ((flags
& (1 << count
)) != 0)
1038 socket
->m_cbacks
[count
] = callback
;
1039 socket
->m_data
[count
] = cdata
;
1044 /* GSocket_UnsetCallback:
1045 * Disables all callbacks specified by 'flags', which may be a
1046 * combination of flags OR'ed toghether.
1048 void GSocket_UnsetCallback(GSocket
*socket
, GSocketEventFlags flags
)
1052 assert(socket
!= NULL
);
1054 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1056 if ((flags
& (1 << count
)) != 0)
1058 socket
->m_cbacks
[count
] = NULL
;
1059 socket
->m_data
[count
] = NULL
;
1065 #define CALL_CALLBACK(socket, event) { \
1066 _GSocket_Disable(socket, event); \
1067 if (socket->m_cbacks[event]) \
1068 socket->m_cbacks[event](socket, event, socket->m_data[event]); \
1071 int _GSocket_Recv_Stream(GSocket
*socket
, char *buffer
, int size
)
1075 OTByteCount sz
= 0 ;
1077 OTCountDataBytes( socket
->m_endpoint
, &sz
) ;
1078 if ( size
> (int)sz
)
1080 res
= OTRcv( socket
->m_endpoint
, buffer
, size
, &flags
) ;
1086 // we simulate another read event if there are still bytes
1087 if ( socket
->m_takesEvents
)
1089 OTByteCount sz
= 0 ;
1090 OTCountDataBytes( socket
->m_endpoint
, &sz
) ;
1093 socket
->m_detected
|= GSOCK_INPUT_FLAG
;
1094 (socket
->m_cbacks
[GSOCK_INPUT
])(socket
, GSOCK_INPUT
, socket
->m_data
[GSOCK_INPUT
]);
1100 int _GSocket_Recv_Dgram(GSocket
*socket
, char *buffer
, int size
)
1105 struct sockaddr from
;
1106 WX_SOCKLEN_T fromlen
= sizeof(from
);
1109 fromlen
= sizeof(from
);
1111 ret
= recvfrom(socket
->m_endpoint
, buffer
, size
, 0, &from
, (WX_SOCKLEN_T
*) &fromlen
);
1116 /* Translate a system address into a GSocket address */
1117 if (!socket
->m_peer
)
1119 socket
->m_peer
= GAddress_new();
1120 if (!socket
->m_peer
)
1122 socket
->m_error
= GSOCK_MEMERR
;
1126 err
= _GAddress_translate_from(socket
->m_peer
, &from
, fromlen
);
1127 if (err
!= GSOCK_NOERROR
)
1129 GAddress_destroy(socket
->m_peer
);
1130 socket
->m_peer
= NULL
;
1131 socket
->m_error
= err
;
1138 int _GSocket_Send_Stream(GSocket
*socket
, const char *buffer
, int size
)
1143 res
= OTSnd( socket
->m_endpoint
, (void*) buffer
, size
, flags
) ;
1147 int _GSocket_Send_Dgram(GSocket
*socket
, const char *buffer
, int size
)
1152 struct sockaddr
*addr
;
1156 if (!socket
->m_peer
)
1158 socket
->m_error
= GSOCK_INVADDR
;
1162 err
= _GAddress_translate_to(socket
->m_peer
, &addr
, &len
);
1163 if (err
!= GSOCK_NOERROR
)
1165 socket
->m_error
= err
;
1169 ret
= sendto(socket
->m_endpoint
, buffer
, size
, 0, addr
, len
);
1171 /* Frees memory allocated from _GAddress_translate_to */
1179 * -------------------------------------------------------------------------
1181 * -------------------------------------------------------------------------
1184 /* CHECK_ADDRESS verifies that the current family is either GSOCK_NOFAMILY
1185 * or GSOCK_*family*, and if it is GSOCK_NOFAMILY, it initalizes address
1186 * to be a GSOCK_*family*. In other cases, it returns GSOCK_INVADDR.
1188 #define CHECK_ADDRESS(address, family, retval) \
1190 if (address->m_family == GSOCK_NOFAMILY) \
1191 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1192 return address->m_error; \
1193 if (address->m_family != GSOCK_##family) \
1195 address->m_error = GSOCK_INVADDR; \
1200 GAddress
*GAddress_new()
1204 if ((address
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1207 address
->m_family
= GSOCK_NOFAMILY
;
1208 address
->m_host
= INADDR_NONE
;
1209 address
->m_port
= 0 ;
1214 GAddress
*GAddress_copy(GAddress
*address
)
1218 assert(address
!= NULL
);
1220 if ((addr2
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1223 memcpy(addr2
, address
, sizeof(GAddress
));
1227 void GAddress_destroy(GAddress
*address
)
1229 assert(address
!= NULL
);
1234 void GAddress_SetFamily(GAddress
*address
, GAddressType type
)
1236 assert(address
!= NULL
);
1238 address
->m_family
= type
;
1241 GAddressType
GAddress_GetFamily(GAddress
*address
)
1243 assert(address
!= NULL
);
1245 return address
->m_family
;
1248 GSocketError
_GAddress_translate_from(GAddress
*address
,
1251 switch (addr
->fAddressType
)
1254 address
->m_family
= GSOCK_INET
;
1258 address
->m_family
= GSOCK_INET6
;
1263 address
->m_error
= GSOCK_INVOP
;
1267 address
->m_host
= addr
->fHost
;
1268 address
->m_port
= addr
->fPort
;
1269 return GSOCK_NOERROR
;
1272 GSocketError
_GAddress_translate_to(GAddress
*address
,
1275 if ( GSocket_Verify_Inited() == FALSE
)
1276 return GSOCK_IOERR
;
1277 memset(addr
, 0 , sizeof(struct InetAddress
));
1278 OTInitInetAddress( addr
, address
->m_port
, address
->m_host
) ;
1279 return GSOCK_NOERROR
;
1283 * -------------------------------------------------------------------------
1284 * Internet address family
1285 * -------------------------------------------------------------------------
1288 GSocketError
_GAddress_Init_INET(GAddress
*address
)
1290 address
->m_family
= GSOCK_INET
;
1291 address
->m_host
= kOTAnyInetAddress
;
1293 return GSOCK_NOERROR
;
1296 GSocketError
GAddress_INET_SetHostName(GAddress
*address
, const char *hostname
)
1298 InetHostInfo hinfo
;
1301 if ( GSocket_Verify_Inited() == FALSE
)
1302 return GSOCK_IOERR
;
1304 assert(address
!= NULL
);
1306 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1307 ret
= OTInetStringToAddress( gInetSvcRef
, (char*) hostname
, &hinfo
) ;
1308 if ( ret
!= kOTNoError
)
1310 address
->m_host
= INADDR_NONE
;
1311 address
->m_error
= GSOCK_NOHOST
;
1312 return GSOCK_NOHOST
;
1314 address
->m_host
= hinfo
.addrs
[0] ;
1315 return GSOCK_NOERROR
;
1318 GSocketError
GAddress_INET_SetAnyAddress(GAddress
*address
)
1320 return GAddress_INET_SetHostAddress(address
, INADDR_ANY
);
1323 GSocketError
GAddress_INET_SetHostAddress(GAddress
*address
,
1324 unsigned long hostaddr
)
1326 assert(address
!= NULL
);
1328 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1330 address
->m_host
= hostaddr
;
1332 return GSOCK_NOERROR
;
1335 struct service_entry
1338 unsigned short port
;
1341 typedef struct service_entry service_entry
;
1343 service_entry gServices
[] =
1345 { "http" , 80 , "tcp" }
1348 GSocketError
GAddress_INET_SetPortName(GAddress
*address
, const char *port
,
1349 const char *protocol
)
1353 assert(address
!= NULL
);
1354 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1358 address
->m_error
= GSOCK_INVPORT
;
1359 return GSOCK_INVPORT
;
1361 for ( i
= 0 ; i
< sizeof( gServices
) / sizeof( service_entry
) ; ++i
)
1363 if ( strcmp( port
, gServices
[i
].name
) == 0 )
1365 if ( protocol
== NULL
|| strcmp( protocol
, gServices
[i
].protocol
) )
1367 address
->m_port
= gServices
[i
].port
;
1368 return GSOCK_NOERROR
;
1373 if (isdigit(port
[0]))
1375 address
->m_port
= atoi(port
);
1376 return GSOCK_NOERROR
;
1379 address
->m_error
= GSOCK_INVPORT
;
1380 return GSOCK_INVPORT
;
1383 GSocketError
GAddress_INET_SetPort(GAddress
*address
, unsigned short port
)
1385 assert(address
!= NULL
);
1386 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1387 address
->m_port
= port
;
1389 return GSOCK_NOERROR
;
1392 GSocketError
GAddress_INET_GetHostName(GAddress
*address
, char *hostname
, size_t sbuf
)
1394 InetDomainName name
;
1395 if ( GSocket_Verify_Inited() == FALSE
)
1396 return GSOCK_IOERR
;
1398 assert(address
!= NULL
);
1399 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1401 OTInetAddressToName( gInetSvcRef
, address
->m_host
, name
) ;
1402 strncpy( hostname
, name
, sbuf
) ;
1403 return GSOCK_NOERROR
;
1406 unsigned long GAddress_INET_GetHostAddress(GAddress
*address
)
1408 assert(address
!= NULL
);
1409 CHECK_ADDRESS(address
, INET
, 0);
1411 return address
->m_host
;
1414 unsigned short GAddress_INET_GetPort(GAddress
*address
)
1416 assert(address
!= NULL
);
1417 CHECK_ADDRESS(address
, INET
, 0);
1419 return address
->m_port
;
1422 void _GSocket_Enable_Events(GSocket
*socket
)
1424 if ( socket
->m_takesEvents
)
1429 socket
->m_takesEvents
= TRUE
;
1430 state
= OTGetEndpointState(socket
->m_endpoint
);
1433 OTByteCount sz
= 0 ;
1434 OTCountDataBytes( socket
->m_endpoint
, &sz
) ;
1435 if ( state
== T_INCON
|| sz
> 0 )
1437 socket
->m_detected
|= GSOCK_INPUT_FLAG
;
1438 (socket
->m_cbacks
[GSOCK_INPUT
])(socket
, GSOCK_INPUT
, socket
->m_data
[GSOCK_INPUT
]);
1442 if ( state
== T_DATAXFER
|| state
== T_INREL
)
1444 socket
->m_detected
|=GSOCK_OUTPUT_FLAG
;
1445 (socket
->m_cbacks
[GSOCK_OUTPUT
])(socket
, GSOCK_OUTPUT
, socket
->m_data
[GSOCK_OUTPUT
]);
1451 void _GSocket_Disable_Events(GSocket
*socket
)
1453 socket
->m_takesEvents
= FALSE
;
1456 /* _GSocket_Input_Timeout:
1457 * For blocking sockets, wait until data is available or
1458 * until timeout ellapses.
1460 GSocketError
_GSocket_Input_Timeout(GSocket
*socket
)
1462 if ( !socket
->m_non_blocking
)
1464 UnsignedWide now
, start
;
1465 short formerTakesEvents
= socket
->m_takesEvents
;
1466 Microseconds(&start
);
1468 socket
->m_takesEvents
= FALSE
;
1470 while( (now
.hi
* 4294967296.0 + now
.lo
) - (start
.hi
* 4294967296.0 + start
.lo
) < socket
->m_timeout
* 1000.0 )
1473 OTByteCount sz
= 0 ;
1474 state
= OTGetEndpointState(socket
->m_endpoint
);
1476 OTCountDataBytes( socket
->m_endpoint
, &sz
) ;
1477 if ( state
== T_INCON
|| sz
> 0 )
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
;
1491 /* _GSocket_Output_Timeout:
1492 * For blocking sockets, wait until data can be sent without
1493 * blocking or until timeout ellapses.
1495 GSocketError
_GSocket_Output_Timeout(GSocket
*socket
)
1497 if ( !socket
->m_non_blocking
)
1499 UnsignedWide now
, start
;
1500 short formerTakesEvents
= socket
->m_takesEvents
;
1501 Microseconds(&start
);
1503 socket
->m_takesEvents
= FALSE
;
1505 while( (now
.hi
* 4294967296.0 + now
.lo
) - (start
.hi
* 4294967296.0 + start
.lo
) < socket
->m_timeout
* 1000.0 )
1508 state
= OTGetEndpointState(socket
->m_endpoint
);
1510 if ( state
== T_DATAXFER
|| state
== T_INREL
)
1512 socket
->m_takesEvents
= formerTakesEvents
;
1513 return GSOCK_NOERROR
;
1517 socket
->m_takesEvents
= formerTakesEvents
;
1518 socket
->m_error
= GSOCK_TIMEDOUT
;
1519 return GSOCK_TIMEDOUT
;
1521 return GSOCK_NOERROR
;
1525 * There is data to be read in the input buffer. If, after a read
1526 * operation, there is still data available, the callback function will
1529 * The socket is available for writing. That is, the next write call
1530 * won't block. This event is generated only once, when the connection is
1531 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
1532 * when the output buffer empties again. This means that the app should
1533 * assume that it can write since the first OUTPUT event, and no more
1534 * OUTPUT events will be generated unless an error occurs.
1536 * Connection successfully established, for client sockets, or incoming
1537 * client connection, for server sockets. Wait for this event (also watch
1538 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
1540 * The connection is lost (or a connection request failed); this could
1541 * be due to a failure, or due to the peer closing it gracefully.
1544 void _GSocket_Internal_Proc(unsigned long e
, void* d
)
1547 GSocket
* socket
= (GSocket
*) d
;
1548 OTEventCode ev
= (OTEventCode
) e
;
1550 GSocketEvent event2
;
1551 GSocketCallback cback
;
1553 GSocketCallback cback2
;
1558 event
= GSOCK_MAX_EVENT
;
1559 event2
= GSOCK_MAX_EVENT
;
1565 /* Check that the socket still exists (it has not been
1566 * destroyed) and for safety, check that the m_endpoint field
1567 * is what we expect it to be.
1569 if ((socket
!= NULL
) && (socket
->m_takesEvents
))
1574 event
= GSOCK_CONNECTION
;
1577 event
= GSOCK_CONNECTION
;
1578 event2
= GSOCK_OUTPUT
;
1582 retCall
.addr
.buf
= NULL
;
1583 retCall
.addr
.maxlen
= 0;
1584 retCall
.opt
.buf
= NULL
;
1585 retCall
.opt
.maxlen
= 0;
1586 retCall
.udata
.buf
= NULL
;
1587 retCall
.udata
.maxlen
= 0;
1588 OTRcvConnect( socket
->m_endpoint
, &retCall
) ;
1592 event
= GSOCK_LOST
;
1596 event
= GSOCK_OUTPUT
;
1599 event
= GSOCK_INPUT
;
1602 event
= GSOCK_INPUT
;
1605 if (event
!= GSOCK_MAX_EVENT
)
1607 cback
= socket
->m_cbacks
[event
];
1608 data
= socket
->m_data
[event
];
1610 if (event
== GSOCK_LOST
)
1611 socket
->m_detected
= GSOCK_LOST_FLAG
;
1613 socket
->m_detected
|= (1 << event
);
1615 if (event2
!= GSOCK_MAX_EVENT
)
1617 cback2
= socket
->m_cbacks
[event2
];
1618 data2
= socket
->m_data
[event2
];
1620 if (event2
== GSOCK_LOST
)
1621 socket
->m_detected
= GSOCK_LOST_FLAG
;
1623 socket
->m_detected
|= (1 << event2
);
1627 /* OK, we can now leave the critical section because we have
1628 * already obtained the callback address (we make no further
1629 * accesses to socket->whatever). However, the app should
1630 * be prepared to handle events from a socket that has just
1635 (cback
)(socket
, event
, data
);
1637 (cback2
)(socket
, event2
, data2
);
1641 /* Hack added for Mac OS X */
1642 GSocketError
GAddress_UNIX_GetPath(GAddress
*addr
, char *path
, size_t buf
)
1644 return GSOCK_INVADDR
;
1647 GSocketError
GAddress_UNIX_SetPath(GAddress
*addr
, const char *path
)
1649 return GSOCK_INVADDR
;
1652 #endif /* wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__) */