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 */
270 m_ok
= (GSocket_Verify_Inited() != FALSE
);
273 for (i
=0;i
<GSOCK_MAX_EVENT
;i
++)
280 m_error
= GSOCK_NOERROR
;
283 m_non_blocking
= FALSE
;
285 /* 10 sec * 1000 millisec */
286 m_takesEvents
= TRUE
;
287 m_mac_events
= wxMacGetNotifierTable() ;
294 /* Check that the socket is really shutdowned */
295 if (m_endpoint
!= kOTInvalidEndpointRef
)
299 /* Destroy private addresses */
301 GAddress_destroy(m_local
);
304 GAddress_destroy(m_peer
);
308 * Disallow further read/write operations on this socket, close
309 * the fd and disable all callbacks.
311 void GSocket::Shutdown()
318 /* If socket has been created, shutdown it */
319 if (m_endpoint
!= kOTInvalidEndpointRef
)
321 err
= OTSndOrderlyDisconnect( m_endpoint
) ;
322 if ( err
!= kOTNoError
)
326 err
= OTRcvOrderlyDisconnect( m_endpoint
) ;
327 err
= OTUnbind( m_endpoint
) ;
328 err
= OTCloseProvider( m_endpoint
) ;
329 m_endpoint
= kOTInvalidEndpointRef
;
332 /* Disable GUI callbacks */
333 for (evt
= 0; evt
< GSOCK_MAX_EVENT
; evt
++)
334 m_cbacks
[evt
] = NULL
;
338 wxMacRemoveAllNotifiersForData( wxMacGetNotifierTable() , this ) ;
342 /* Address handling */
348 * Set or get the local or peer address for this socket. The 'set'
349 * functions return GSOCK_NOERROR on success, an error code otherwise.
350 * The 'get' functions return a pointer to a GAddress object on success,
351 * or NULL otherwise, in which case they set the error code of the
352 * corresponding GSocket.
355 * GSOCK_INVSOCK - the socket is not valid.
356 * GSOCK_INVADDR - the address is not valid.
358 GSocketError
GSocket::SetLocal(GAddress
*address
)
362 /* the socket must be initialized, or it must be a server */
363 if ((m_endpoint
!= kOTInvalidEndpointRef
&& !m_server
))
365 m_error
= GSOCK_INVSOCK
;
366 return GSOCK_INVSOCK
;
370 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
372 m_error
= GSOCK_INVADDR
;
373 return GSOCK_INVADDR
;
377 GAddress_destroy(m_local
);
379 m_local
= GAddress_copy(address
);
381 return GSOCK_NOERROR
;
384 GSocketError
GSocket::SetPeer(GAddress
*address
)
389 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
391 m_error
= GSOCK_INVADDR
;
392 return GSOCK_INVADDR
;
396 GAddress_destroy(m_peer
);
398 m_peer
= GAddress_copy(address
);
400 return GSOCK_NOERROR
;
403 GAddress
*GSocket::GetLocal()
405 GAddress
*address
= NULL
;
411 /* try to get it from the m_local var first */
413 return GAddress_copy(m_local
);
415 /* else, if the socket is initialized, try getsockname */
416 if (m_endpoint
== kOTInvalidEndpointRef
)
418 m_error
= GSOCK_INVSOCK
;
423 /* we do not support multihoming with this code at the moment
424 OTGetProtAddress will have to be used then - but we don't have a handy
425 method to use right now
428 InetInterfaceInfo info
;
429 OTInetGetInterfaceInfo(&info
, kDefaultInetInterface
);
430 loc
.fHost
= info
.fAddress
;
432 loc
.fAddressType
= AF_INET
;
435 /* got a valid address from getsockname, create a GAddress object */
436 address
= GAddress_new();
439 m_error
= GSOCK_MEMERR
;
443 err
= _GAddress_translate_from(address
, &loc
);
444 if (err
!= GSOCK_NOERROR
)
446 GAddress_destroy(address
);
454 GAddress
*GSocket::GetPeer()
458 /* try to get it from the m_peer var */
460 return GAddress_copy(m_peer
);
465 /* Server specific parts */
467 /* GSocket_SetServer:
468 * Sets up this socket as a server. The local address must have been
469 * set with GSocket_SetLocal() before GSocket_SetServer() is called.
470 * Returns GSOCK_NOERROR on success, one of the following otherwise:
473 * GSOCK_INVSOCK - the socket is in use.
474 * GSOCK_INVADDR - the local address has not been set.
475 * GSOCK_IOERR - low-level error.
477 GSocketError
GSocket::SetServer()
481 /* must not be in use */
482 if (m_endpoint
!= kOTInvalidEndpointRef
)
484 m_error
= GSOCK_INVSOCK
;
485 return GSOCK_INVSOCK
;
488 /* the local addr must have been set */
491 m_error
= GSOCK_INVADDR
;
492 return GSOCK_INVADDR
;
495 /* Initialize all fields */
502 /* Create the socket */
503 m_endpoint
= socket(m_local
->m_realfamily
, SOCK_STREAM
, 0);
504 socket_set_ref( m_endpoint
, (unsigned long) &gMacNetEvents
, (unsigned long) this ) ;
505 if (m_endpoint
== kOTInvalidEndpointRef
)
507 m_error
= GSOCK_IOERR
;
511 ioctl(m_endpoint
, FIONBIO
, &arg
);
514 /* Bind to the local address,
515 * retrieve the actual address bound,
516 * and listen up to 5 connections.
518 if ((bind(m_endpoint
, m_local
->m_addr
, m_local
->m_len
) != 0) ||
519 (getsockname(m_endpoint
,
521 (SOCKLEN_T
*) &m_local
->m_len
) != 0) ||
522 (listen(m_endpoint
, 5) != 0))
526 m_error
= GSOCK_IOERR
;
530 return GSOCK_NOERROR
;
533 /* GSocket_WaitConnection:
534 * Waits for an incoming client connection. Returns a pointer to
535 * a GSocket object, or NULL if there was an error, in which case
536 * the last error field will be updated for the calling GSocket.
538 * Error codes (set in the calling GSocket)
539 * GSOCK_INVSOCK - the socket is not valid or not a server.
540 * GSOCK_TIMEDOUT - timeout, no incoming connections.
541 * GSOCK_WOULDBLOCK - the call would block and the socket is nonblocking.
542 * GSOCK_MEMERR - couldn't allocate memory.
543 * GSOCK_IOERR - low-level error.
545 GSocket
*GSocket::WaitConnection()
547 GSocket
*connection
= NULL
;
551 /* Reenable CONNECTION events */
552 m_detected
&= ~GSOCK_CONNECTION_FLAG
;
554 /* If the socket has already been created, we exit immediately */
555 if (m_endpoint
== kOTInvalidEndpointRef
|| !m_server
)
557 m_error
= GSOCK_INVSOCK
;
561 /* Create a GSocket object for the new connection */
562 connection
= GSocket_new();
566 m_error
= GSOCK_MEMERR
;
570 /* Wait for a connection (with timeout) */
571 if (Input_Timeout() == GSOCK_TIMEDOUT
)
574 /* m_error set by _GSocket_Input_Timeout */
580 connection
->m_endpoint
= accept(m_endpoint
, &from
, (SOCKLEN_T
*) &fromlen
);
583 if (connection
->m_endpoint
== kOTInvalidEndpointRef
)
585 if (errno
== EWOULDBLOCK
)
586 m_error
= GSOCK_WOULDBLOCK
;
588 m_error
= GSOCK_IOERR
;
594 /* Initialize all fields */
595 connection
->m_server
= FALSE
;
596 connection
->m_stream
= TRUE
;
597 connection
->m_oriented
= TRUE
;
599 /* Setup the peer address field */
600 connection
->m_peer
= GAddress_new();
601 if (!connection
->m_peer
)
604 m_error
= GSOCK_MEMERR
;
609 err
= _GAddress_translate_from(connection
->m_peer
, &from
, fromlen
);
610 if (err
!= GSOCK_NOERROR
)
612 GAddress_destroy(connection
->m_peer
);
613 GSocket_destroy(connection
);
618 ioctl(connection
->m_endpoint
, FIONBIO
, &arg
);
620 connection
->Enable_Events();
625 /* Datagram sockets */
627 /* GSocket_SetNonOriented:
628 * Sets up this socket as a non-connection oriented (datagram) socket.
629 * Before using this function, the local address must have been set
630 * with GSocket_SetLocal(), or the call will fail. Returns GSOCK_NOERROR
631 * on success, or one of the following otherwise.
634 * GSOCK_INVSOCK - the socket is in use.
635 * GSOCK_INVADDR - the local address has not been set.
636 * GSOCK_IOERR - low-level error.
638 GSocketError
GSocket::SetNonOriented()
642 if (m_endpoint
!= kOTInvalidEndpointRef
)
644 m_error
= GSOCK_INVSOCK
;
645 return GSOCK_INVSOCK
;
650 m_error
= GSOCK_INVADDR
;
651 return GSOCK_INVADDR
;
654 /* Initialize all fields */
659 /* Create the socket */
663 m_endpoint
= socket(m_local
->m_realfamily
, SOCK_DGRAM
, 0);
664 socket_set_ref( m_endpoint
, (unsigned long) &gMacNetEvents
, (unsigned long) this ) ;
666 if (m_endpoint
== kOTInvalidEndpointRef
)
668 m_error
= GSOCK_IOERR
;
674 ioctl(m_endpoint
, FIONBIO
, &arg
);
678 /* Bind to the local address,
679 * and retrieve the actual address bound.
683 if ((bind(m_endpoint
, m_local
->m_addr
, m_local
->m_len
) != 0) ||
684 (getsockname(m_endpoint
,
686 (SOCKLEN_T
*) &m_local
->m_len
) != 0))
690 m_error
= GSOCK_IOERR
;
694 return GSOCK_NOERROR
;
697 /* Client specific parts */
700 * For stream (connection oriented) sockets, GSocket_Connect() tries
701 * to establish a client connection to a server using the peer address
702 * as established with GSocket_SetPeer(). Returns GSOCK_NOERROR if the
703 * connection has been succesfully established, or one of the error
704 * codes listed below. Note that for nonblocking sockets, a return
705 * value of GSOCK_WOULDBLOCK doesn't mean a failure. The connection
706 * request can be completed later; you should use GSocket_Select()
707 * to poll for GSOCK_CONNECTION | GSOCK_LOST, or wait for the
708 * corresponding asynchronous events.
710 * For datagram (non connection oriented) sockets, GSocket_Connect()
711 * just sets the peer address established with GSocket_SetPeer() as
712 * default destination.
715 * GSOCK_INVSOCK - the socket is in use or not valid.
716 * GSOCK_INVADDR - the peer address has not been established.
717 * GSOCK_TIMEDOUT - timeout, the connection failed.
718 * GSOCK_WOULDBLOCK - connection in progress (nonblocking sockets only)
719 * GSOCK_MEMERR - couldn't allocate memory.
720 * GSOCK_IOERR - low-level error.
722 GSocketError
GSocket::Connect(GSocketStream stream
)
726 OSStatus err
= kOTNoError
;
731 /* Enable CONNECTION events (needed for nonblocking connections) */
732 m_detected
&= ~GSOCK_CONNECTION_FLAG
;
734 if (m_endpoint
!= kOTInvalidEndpointRef
)
736 m_error
= GSOCK_INVSOCK
;
737 return GSOCK_INVSOCK
;
742 m_error
= GSOCK_INVADDR
;
743 return GSOCK_INVADDR
;
746 /* Streamed or dgram socket? */
747 m_stream
= (stream
== GSOCK_STREAMED
);
751 /* Create the socket */
754 OTOpenEndpointInContext( OTCreateConfiguration( kTCPName
) , 0 , &info
, &err
, NULL
) ;
757 OTOpenEndpoint( OTCreateConfiguration( kTCPName
) , 0 , &info
, &err
) ;
759 if ( m_endpoint
== kOTInvalidEndpointRef
|| err
!= kOTNoError
)
761 m_endpoint
= kOTInvalidEndpointRef
;
762 m_error
= GSOCK_IOERR
;
765 err
= OTBind( m_endpoint
, nil
, nil
) ;
766 if ( err
!= kOTNoError
)
770 SetDefaultEndpointModes( m_endpoint
, this ) ;
773 ioctl(m_endpoint
, FIONBIO
, &arg
);
777 _GAddress_translate_to( m_peer
, &addr
) ;
778 memset( &peer
, 0 , sizeof( TCall
) ) ;
779 peer
.addr
.len
= sizeof( InetAddress
) ;
780 peer
.addr
.buf
= (unsigned char*) &addr
;
781 err
= OTConnect( m_endpoint
, &peer
, nil
) ;
784 /* If connect failed with EINPROGRESS and the GSocket object
785 * is in blocking mode, we select() for the specified timeout
786 * checking for writability to see if the connection request
790 if ((err
== kOTNoDataErr
) && (!m_non_blocking
))
792 if (Output_Timeout() == GSOCK_TIMEDOUT
)
794 OTSndOrderlyDisconnect( m_endpoint
) ;
795 m_endpoint
= kOTInvalidEndpointRef
;
796 /* m_error is set in _GSocket_Output_Timeout */
797 return GSOCK_TIMEDOUT
;
803 SOCKLEN_T len = sizeof(error);
805 getsockopt(m_endpoint, SOL_SOCKET, SO_ERROR, (void*) &error, &len);
809 return GSOCK_NOERROR
;
813 /* If connect failed with EINPROGRESS and the GSocket object
814 * is set to nonblocking, we set m_error to GSOCK_WOULDBLOCK
815 * (and return GSOCK_WOULDBLOCK) but we don't close the socket;
816 * this way if the connection completes, a GSOCK_CONNECTION
817 * event will be generated, if enabled.
819 if ((err
== kOTNoDataErr
) && (m_non_blocking
))
821 m_error
= GSOCK_WOULDBLOCK
;
822 return GSOCK_WOULDBLOCK
;
825 /* If connect failed with an error other than EINPROGRESS,
826 * then the call to GSocket_Connect has failed.
828 OTSndOrderlyDisconnect( m_endpoint
) ;
830 m_endpoint
= kOTInvalidEndpointRef
;
831 m_error
= GSOCK_IOERR
;
834 // OTInetEventHandler(this, T_CONNECT , kOTNoError , NULL ) ;
835 return GSOCK_NOERROR
;
840 /* Like recv(), send(), ... */
841 int GSocket::Read(char *buffer
, int size
)
847 /* Reenable INPUT events */
848 m_detected
&= ~GSOCK_INPUT_FLAG
;
850 if (m_endpoint
== kOTInvalidEndpointRef
|| m_server
)
852 m_error
= GSOCK_INVSOCK
;
856 /* If the socket is blocking, wait for data (with a timeout) */
857 if (Input_Timeout() == GSOCK_TIMEDOUT
)
862 ret
= Recv_Stream(buffer
, size
);
864 ret
= Recv_Dgram(buffer
, size
);
868 if (errno
== EWOULDBLOCK
)
869 m_error
= GSOCK_WOULDBLOCK
;
871 m_error
= GSOCK_IOERR
;
877 int GSocket::Write(const char *buffer
, int size
)
883 if (m_endpoint
== kOTInvalidEndpointRef
|| m_server
)
885 m_error
= GSOCK_INVSOCK
;
889 /* If the socket is blocking, wait for writability (with a timeout) */
890 if (Output_Timeout() == GSOCK_TIMEDOUT
)
895 ret
= Send_Stream(buffer
, size
);
897 ret
= Send_Dgram(buffer
, size
);
901 if (errno
== EWOULDBLOCK
)
902 m_error
= GSOCK_WOULDBLOCK
;
904 m_error
= GSOCK_IOERR
;
906 /* Only reenable OUTPUT events after an error (just like WSAAsyncSelect
907 * in MSW). Once the first OUTPUT event is received, users can assume
908 * that the socket is writable until a read operation fails. Only then
909 * will further OUTPUT events be posted.
911 m_detected
&= ~GSOCK_OUTPUT_FLAG
;
919 * Polls the socket to determine its status. This function will
920 * check for the events specified in the 'flags' parameter, and
921 * it will return a mask indicating which operations can be
922 * performed. This function won't block, regardless of the
923 * mode (blocking | nonblocking) of the socket.
925 GSocketEventFlags
GSocket::Select(GSocketEventFlags flags
)
928 wxMacProcessNotifierEvents() ;
930 state = OTGetEndpointState(m_endpoint);
932 if ( ( flags & GSOCK_INPUT_FLAG ) && ! ( m_detected & GSOCK_INPUT_FLAG ) )
935 OTCountDataBytes( m_endpoint , &sz ) ;
936 if ( state == T_INCON || sz > 0 )
938 m_detected |= GSOCK_INPUT_FLAG ;
939 (m_cbacks[GSOCK_INPUT])(this, GSOCK_INPUT, m_data[GSOCK_INPUT]);
942 if ( ( flags & GSOCK_INPUT_FLAG ) && ! ( m_detected & GSOCK_OUTPUT_FLAG ) )
944 if ( state == T_DATAXFER || state == T_INREL )
946 m_detected |=GSOCK_OUTPUT_FLAG ;
947 (m_cbacks[GSOCK_OUTPUT])(this, GSOCK_OUTPUT, m_data[GSOCK_OUTPUT]);
951 return ( flags
& m_detected
) ;
956 /* GSocket_SetNonBlocking:
957 * Sets the socket to non-blocking mode. All IO calls will return
960 void GSocket::SetNonBlocking(int non_block
)
964 m_non_blocking
= non_block
;
967 /* GSocket_SetTimeout:
968 * Sets the timeout for blocking calls. Time is expressed in
971 void GSocket::SetTimeout(unsigned long millisec
)
975 // this is usually set too high and we have not yet been able to detect a closed
976 // stream, thus we leave the 10 sec timeout
977 // m_timeout = millisec;
981 * Returns the last error occured for this socket. Note that successful
982 * operations do not clear this back to GSOCK_NOERROR, so use it only
985 GSocketError WXDLLIMPEXP_NET
GSocket::GetError()
995 * There is data to be read in the input buffer. If, after a read
996 * operation, there is still data available, the callback function will
999 * The socket is available for writing. That is, the next write call
1000 * won't block. This event is generated only once, when the connection is
1001 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
1002 * when the output buffer empties again. This means that the app should
1003 * assume that it can write since the first OUTPUT event, and no more
1004 * OUTPUT events will be generated unless an error occurs.
1006 * Connection succesfully established, for client sockets, or incoming
1007 * client connection, for server sockets. Wait for this event (also watch
1008 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
1010 * The connection is lost (or a connection request failed); this could
1011 * be due to a failure, or due to the peer closing it gracefully.
1014 /* GSocket_SetCallback:
1015 * Enables the callbacks specified by 'flags'. Note that 'flags'
1016 * may be a combination of flags OR'ed toghether, so the same
1017 * callback function can be made to accept different events.
1018 * The callback function must have the following prototype:
1020 * void function(GSocket *socket, GSocketEvent event, char *cdata)
1022 void GSocket::SetCallback(GSocketEventFlags flags
,
1023 GSocketCallback callback
, char *cdata
)
1029 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1031 if ((flags
& (1 << count
)) != 0)
1033 m_cbacks
[count
] = callback
;
1034 m_data
[count
] = cdata
;
1039 /* GSocket_UnsetCallback:
1040 * Disables all callbacks specified by 'flags', which may be a
1041 * combination of flags OR'ed toghether.
1043 void GSocket::UnsetCallback(GSocketEventFlags flags
)
1049 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1051 if ((flags
& (1 << count
)) != 0)
1053 m_cbacks
[count
] = NULL
;
1054 m_data
[count
] = NULL
;
1060 #define CALL_CALLBACK(socket, event) { \
1061 _GSocket_Disable(socket, event); \
1062 if (socket->m_cbacks[event]) \
1063 socket->m_cbacks[event](socket, event, socket->m_data[event]); \
1066 int GSocket::Recv_Stream(char *buffer
, int size
)
1070 OTByteCount sz
= 0 ;
1072 OTCountDataBytes( m_endpoint
, &sz
) ;
1073 if ( size
> (int)sz
)
1075 res
= OTRcv( m_endpoint
, buffer
, size
, &flags
) ;
1081 // we simulate another read event if there are still bytes
1082 if ( m_takesEvents
)
1084 OTByteCount sz
= 0 ;
1085 OTCountDataBytes( m_endpoint
, &sz
) ;
1088 m_detected
|= GSOCK_INPUT_FLAG
;
1089 (m_cbacks
[GSOCK_INPUT
])(this, GSOCK_INPUT
, m_data
[GSOCK_INPUT
]);
1095 int GSocket::Recv_Dgram(char *buffer
, int size
)
1100 struct sockaddr from
;
1101 SOCKLEN_T fromlen
= sizeof(from
);
1104 fromlen
= sizeof(from
);
1106 ret
= recvfrom(m_endpoint
, buffer
, size
, 0, &from
, (SOCKLEN_T
*) &fromlen
);
1111 /* Translate a system address into a GSocket address */
1114 m_peer
= GAddress_new();
1117 m_error
= GSOCK_MEMERR
;
1121 err
= _GAddress_translate_from(m_peer
, &from
, fromlen
);
1122 if (err
!= GSOCK_NOERROR
)
1124 GAddress_destroy(m_peer
);
1133 int GSocket::Send_Stream(const char *buffer
, int size
)
1138 res
= OTSnd( m_endpoint
, (void*) buffer
, size
, flags
) ;
1142 int GSocket::Send_Dgram(const char *buffer
, int size
)
1147 struct sockaddr
*addr
;
1153 m_error
= GSOCK_INVADDR
;
1157 err
= _GAddress_translate_to(m_peer
, &addr
, &len
);
1158 if (err
!= GSOCK_NOERROR
)
1164 ret
= sendto(m_endpoint
, buffer
, size
, 0, addr
, len
);
1166 /* Frees memory allocated from _GAddress_translate_to */
1174 * -------------------------------------------------------------------------
1176 * -------------------------------------------------------------------------
1179 /* CHECK_ADDRESS verifies that the current family is either GSOCK_NOFAMILY
1180 * or GSOCK_*family*, and if it is GSOCK_NOFAMILY, it initalizes address
1181 * to be a GSOCK_*family*. In other cases, it returns GSOCK_INVADDR.
1183 #define CHECK_ADDRESS(address, family, retval) \
1185 if (address->m_family == GSOCK_NOFAMILY) \
1186 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1187 return address->m_error; \
1188 if (address->m_family != GSOCK_##family) \
1190 address->m_error = GSOCK_INVADDR; \
1195 GAddress
*GAddress_new()
1199 if ((address
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1202 address
->m_family
= GSOCK_NOFAMILY
;
1203 address
->m_host
= INADDR_NONE
;
1204 address
->m_port
= 0 ;
1209 GAddress
*GAddress_copy(GAddress
*address
)
1213 assert(address
!= NULL
);
1215 if ((addr2
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1218 memcpy(addr2
, address
, sizeof(GAddress
));
1222 void GAddress_destroy(GAddress
*address
)
1224 assert(address
!= NULL
);
1229 void GAddress_SetFamily(GAddress
*address
, GAddressType type
)
1231 assert(address
!= NULL
);
1233 address
->m_family
= type
;
1236 GAddressType
GAddress_GetFamily(GAddress
*address
)
1238 assert(address
!= NULL
);
1240 return address
->m_family
;
1243 GSocketError
_GAddress_translate_from(GAddress
*address
,
1246 switch (addr
->fAddressType
)
1249 address
->m_family
= GSOCK_INET
;
1253 address
->m_family
= GSOCK_INET6
;
1258 address
->m_error
= GSOCK_INVOP
;
1262 address
->m_host
= addr
->fHost
;
1263 address
->m_port
= addr
->fPort
;
1264 return GSOCK_NOERROR
;
1267 GSocketError
_GAddress_translate_to(GAddress
*address
,
1270 if ( GSocket_Verify_Inited() == FALSE
)
1271 return GSOCK_IOERR
;
1272 memset(addr
, 0 , sizeof(struct InetAddress
));
1273 OTInitInetAddress( addr
, address
->m_port
, address
->m_host
) ;
1274 return GSOCK_NOERROR
;
1278 * -------------------------------------------------------------------------
1279 * Internet address family
1280 * -------------------------------------------------------------------------
1283 GSocketError
_GAddress_Init_INET(GAddress
*address
)
1285 address
->m_family
= GSOCK_INET
;
1286 address
->m_host
= kOTAnyInetAddress
;
1288 return GSOCK_NOERROR
;
1291 GSocketError
GAddress_INET_SetHostName(GAddress
*address
, const char *hostname
)
1293 InetHostInfo hinfo
;
1296 if ( GSocket_Verify_Inited() == FALSE
)
1297 return GSOCK_IOERR
;
1299 assert(address
!= NULL
);
1301 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1302 ret
= OTInetStringToAddress( gInetSvcRef
, (char*) hostname
, &hinfo
) ;
1303 if ( ret
!= kOTNoError
)
1305 address
->m_host
= INADDR_NONE
;
1306 address
->m_error
= GSOCK_NOHOST
;
1307 return GSOCK_NOHOST
;
1309 address
->m_host
= hinfo
.addrs
[0] ;
1310 return GSOCK_NOERROR
;
1313 GSocketError
GAddress_INET_SetAnyAddress(GAddress
*address
)
1315 return GAddress_INET_SetHostAddress(address
, INADDR_ANY
);
1318 GSocketError
GAddress_INET_SetHostAddress(GAddress
*address
,
1319 unsigned long hostaddr
)
1321 assert(address
!= NULL
);
1323 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1325 address
->m_host
= htonl(hostaddr
) ;
1327 return GSOCK_NOERROR
;
1330 struct service_entry
1333 unsigned short port
;
1336 typedef struct service_entry service_entry
;
1338 service_entry gServices
[] =
1340 { "http" , 80 , "tcp" }
1343 GSocketError
GAddress_INET_SetPortName(GAddress
*address
, const char *port
,
1344 const char *protocol
)
1348 assert(address
!= NULL
);
1349 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1353 address
->m_error
= GSOCK_INVPORT
;
1354 return GSOCK_INVPORT
;
1356 for ( i
= 0 ; i
< sizeof( gServices
) / sizeof( service_entry
) ; ++i
)
1358 if ( strcmp( port
, gServices
[i
].name
) == 0 )
1360 if ( protocol
== NULL
|| strcmp( protocol
, gServices
[i
].protocol
) )
1362 address
->m_port
= gServices
[i
].port
;
1363 return GSOCK_NOERROR
;
1368 if (isdigit(port
[0]))
1370 address
->m_port
= atoi(port
);
1371 return GSOCK_NOERROR
;
1374 address
->m_error
= GSOCK_INVPORT
;
1375 return GSOCK_INVPORT
;
1378 GSocketError
GAddress_INET_SetPort(GAddress
*address
, unsigned short port
)
1380 assert(address
!= NULL
);
1381 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1382 address
->m_port
= port
;
1384 return GSOCK_NOERROR
;
1387 GSocketError
GAddress_INET_GetHostName(GAddress
*address
, char *hostname
, size_t sbuf
)
1389 InetDomainName name
;
1390 if ( GSocket_Verify_Inited() == FALSE
)
1391 return GSOCK_IOERR
;
1393 assert(address
!= NULL
);
1394 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1396 OTInetAddressToName( gInetSvcRef
, address
->m_host
, name
) ;
1397 strncpy( hostname
, name
, sbuf
) ;
1398 return GSOCK_NOERROR
;
1401 unsigned long GAddress_INET_GetHostAddress(GAddress
*address
)
1403 assert(address
!= NULL
);
1404 CHECK_ADDRESS(address
, INET
, 0);
1406 return ntohl(address
->m_host
);
1409 unsigned short GAddress_INET_GetPort(GAddress
*address
)
1411 assert(address
!= NULL
);
1412 CHECK_ADDRESS(address
, INET
, 0);
1414 return address
->m_port
;
1417 void GSocket::Enable_Events()
1419 if ( m_takesEvents
)
1424 m_takesEvents
= TRUE
;
1425 state
= OTGetEndpointState(m_endpoint
);
1428 OTByteCount sz
= 0 ;
1429 OTCountDataBytes( m_endpoint
, &sz
) ;
1430 if ( state
== T_INCON
|| sz
> 0 )
1432 m_detected
|= GSOCK_INPUT_FLAG
;
1433 (m_cbacks
[GSOCK_INPUT
])(this, GSOCK_INPUT
, m_data
[GSOCK_INPUT
]);
1437 if ( state
== T_DATAXFER
|| state
== T_INREL
)
1439 m_detected
|=GSOCK_OUTPUT_FLAG
;
1440 (m_cbacks
[GSOCK_OUTPUT
])(this, GSOCK_OUTPUT
, m_data
[GSOCK_OUTPUT
]);
1446 void GSocket::Disable_Events()
1448 m_takesEvents
= FALSE
;
1451 /* _GSocket_Input_Timeout:
1452 * For blocking sockets, wait until data is available or
1453 * until timeout ellapses.
1455 GSocketError
GSocket::Input_Timeout()
1457 if ( !m_non_blocking
)
1459 UnsignedWide now
, start
;
1460 short formerTakesEvents
= m_takesEvents
;
1461 Microseconds(&start
);
1463 m_takesEvents
= FALSE
;
1465 while( (now
.hi
* 4294967296.0 + now
.lo
) - (start
.hi
* 4294967296.0 + start
.lo
) < m_timeout
* 1000.0 )
1468 OTByteCount sz
= 0 ;
1469 state
= OTGetEndpointState(m_endpoint
);
1471 OTCountDataBytes( m_endpoint
, &sz
) ;
1472 if ( state
== T_INCON
|| sz
> 0 )
1474 m_takesEvents
= formerTakesEvents
;
1475 return GSOCK_NOERROR
;
1479 m_takesEvents
= formerTakesEvents
;
1480 m_error
= GSOCK_TIMEDOUT
;
1481 return GSOCK_TIMEDOUT
;
1483 return GSOCK_NOERROR
;
1486 /* _GSocket_Output_Timeout:
1487 * For blocking sockets, wait until data can be sent without
1488 * blocking or until timeout ellapses.
1490 GSocketError
GSocket::Output_Timeout()
1492 if ( !m_non_blocking
)
1494 UnsignedWide now
, start
;
1495 short formerTakesEvents
= m_takesEvents
;
1496 Microseconds(&start
);
1498 m_takesEvents
= FALSE
;
1500 while( (now
.hi
* 4294967296.0 + now
.lo
) - (start
.hi
* 4294967296.0 + start
.lo
) < m_timeout
* 1000.0 )
1503 state
= OTGetEndpointState(m_endpoint
);
1505 if ( state
== T_DATAXFER
|| state
== T_INREL
)
1507 m_takesEvents
= formerTakesEvents
;
1508 return GSOCK_NOERROR
;
1512 m_takesEvents
= formerTakesEvents
;
1513 m_error
= GSOCK_TIMEDOUT
;
1514 return GSOCK_TIMEDOUT
;
1516 return GSOCK_NOERROR
;
1520 * There is data to be read in the input buffer. If, after a read
1521 * operation, there is still data available, the callback function will
1524 * The socket is available for writing. That is, the next write call
1525 * won't block. This event is generated only once, when the connection is
1526 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
1527 * when the output buffer empties again. This means that the app should
1528 * assume that it can write since the first OUTPUT event, and no more
1529 * OUTPUT events will be generated unless an error occurs.
1531 * Connection succesfully established, for client sockets, or incoming
1532 * client connection, for server sockets. Wait for this event (also watch
1533 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
1535 * The connection is lost (or a connection request failed); this could
1536 * be due to a failure, or due to the peer closing it gracefully.
1539 void _GSocket_Internal_Proc(unsigned long e
, void* d
)
1542 GSocket
* socket
= (GSocket
*) d
;
1543 OTEventCode ev
= (OTEventCode
) e
;
1545 GSocketEvent event2
;
1546 GSocketCallback cback
;
1548 GSocketCallback cback2
;
1553 event
= GSOCK_MAX_EVENT
;
1554 event2
= GSOCK_MAX_EVENT
;
1560 /* Check that the socket still exists (it has not been
1561 * destroyed) and for safety, check that the m_endpoint field
1562 * is what we expect it to be.
1564 if ((socket
!= NULL
) && (socket
->m_takesEvents
))
1569 event
= GSOCK_CONNECTION
;
1572 event
= GSOCK_CONNECTION
;
1573 event2
= GSOCK_OUTPUT
;
1577 retCall
.addr
.buf
= NULL
;
1578 retCall
.addr
.maxlen
= 0;
1579 retCall
.opt
.buf
= NULL
;
1580 retCall
.opt
.maxlen
= 0;
1581 retCall
.udata
.buf
= NULL
;
1582 retCall
.udata
.maxlen
= 0;
1583 OTRcvConnect( socket
->m_endpoint
, &retCall
) ;
1587 event
= GSOCK_LOST
;
1591 event
= GSOCK_OUTPUT
;
1594 event
= GSOCK_INPUT
;
1597 event
= GSOCK_INPUT
;
1600 if (event
!= GSOCK_MAX_EVENT
)
1602 cback
= socket
->m_cbacks
[event
];
1603 data
= socket
->m_data
[event
];
1605 if (event
== GSOCK_LOST
)
1606 socket
->m_detected
= GSOCK_LOST_FLAG
;
1608 socket
->m_detected
|= (1 << event
);
1610 if (event2
!= GSOCK_MAX_EVENT
)
1612 cback2
= socket
->m_cbacks
[event2
];
1613 data2
= socket
->m_data
[event2
];
1615 if (event2
== GSOCK_LOST
)
1616 socket
->m_detected
= GSOCK_LOST_FLAG
;
1618 socket
->m_detected
|= (1 << event2
);
1622 /* OK, we can now leave the critical section because we have
1623 * already obtained the callback address (we make no further
1624 * accesses to socket->whatever). However, the app should
1625 * be prepared to handle events from a socket that has just
1630 (cback
)(socket
, event
, data
);
1632 (cback2
)(socket
, event2
, data2
);
1636 /* Hack added for Mac OS X */
1637 GSocketError
GAddress_UNIX_GetPath(GAddress
*addr
, char *path
, size_t buf
)
1639 return GSOCK_INVADDR
;
1642 GSocketError
GAddress_UNIX_SetPath(GAddress
*addr
, const char *path
)
1644 return GSOCK_INVADDR
;
1647 #endif /* wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__) */