1 /* -------------------------------------------------------------------------
2 * Project: GSocket (Generic Socket) for WX
4 * Copyright: (c) Guilhem Lavaux
5 * Licence: wxWindows Licence
6 * Authors: Guilhem Lavaux,
7 * Guillermo Rodriguez Garcia <guille@iies.es> (maintainer)
9 * Purpose: GSocket main mac file
11 * -------------------------------------------------------------------------
15 * PLEASE don't put C++ comments here - this is a C source file.
18 #ifndef __GSOCKET_STANDALONE__
20 #include "wx/platform.h"
23 #if wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__)
26 #include <CoreServices/CoreServices.h>
29 #include <MacHeaders.c>
30 #define OTUNIXERRORS 1
31 #include <OpenTransport.h>
32 #include <OpenTransportProviders.h>
33 #include <OpenTptInternet.h>
35 #if TARGET_CARBON && !defined(OTAssert)
36 #define OTAssert( str , cond ) /* does not exists in Carbon */
50 * INADDR_BROADCAST is identical to INADDR_NONE which is not defined
51 * on all unices. INADDR_BROADCAST should be fine to indicate an error.
53 #ifndef INADDR_BROADCAST
54 #define INADDR_BROADCAST 0xFFFFFFFFUL
57 #define INADDR_NONE INADDR_BROADCAST
60 #define INADDR_ANY 0x0UL
62 #ifndef __GSOCKET_STANDALONE__
64 #include "wx/mac/macnotfy.h"
65 #include "wx/mac/gsockmac.h"
66 #include "wx/gsocket.h"
73 #endif /* __GSOCKET_STANDALONE__ */
86 extern pascal void OTDebugStr(const char* str
);
91 InetSvcRef gInetSvcRef
= 0 ;
93 OTNotifyUPP gOTNotifierUPP
= NULL
;
95 OSStatus
DoNegotiateIPReuseAddrOption(EndpointRef ep
, Boolean enableReuseIPMode
);
97 /* Input: ep - endpointref on which to negotiate the option
98 enableReuseIPMode - desired option setting - true/false
99 Return: kOTNoError indicates that the option was successfully negotiated
100 OSStatus is an error if < 0, otherwise, the status field is
103 IMPORTANT NOTE: The endpoint is assumed to be in synchronous more, otherwise
104 this code will not function as desired
108 OSStatus
DoNegotiateIPReuseAddrOption(EndpointRef ep
, Boolean enableReuseIPMode
)
111 UInt8 buf
[kOTFourByteOptionSize
]; // define buffer for fourByte Option size
112 TOption
* opt
; // option ptr to make items easier to access
117 if (!OTIsSynchronous(ep
))
121 opt
= (TOption
*)buf
; // set option ptr to buffer
123 req
.opt
.len
= sizeof(buf
);
124 req
.flags
= T_NEGOTIATE
; // negotiate for option
127 ret
.opt
.maxlen
= kOTFourByteOptionSize
;
129 opt
->level
= INET_IP
; // dealing with an IP Level function
131 opt
->name
= kIP_REUSEADDR
;
133 opt
->name
= IP_REUSEADDR
;
135 opt
->len
= kOTFourByteOptionSize
;
137 *(UInt32
*)opt
->value
= enableReuseIPMode
; // set the desired option level, true or false
139 err
= OTOptionManagement(ep
, &req
, &ret
);
141 // if no error then return the option status value
142 if (err
== kOTNoError
)
144 if (opt
->status
!= T_SUCCESS
)
154 pascal void OTInetEventHandler(void*s
, OTEventCode event
, OTResult
, void *cookie
) ;
155 pascal void OTInetEventHandler(void*s
, OTEventCode event
, OTResult result
, void *cookie
)
158 GSocket
* sock
= (GSocket
*) s
;
160 if ( event
== kOTSyncIdleEvent
)
167 wxMacAddEvent( sock
->m_mac_events
, _GSocket_Internal_Proc
, event
, s
, wakeUp
) ;
173 static void SetDefaultEndpointModes(EndpointRef ep
, void *data
)
174 // This routine sets the supplied endpoint into the default
175 // mode used in this application. The specifics are:
176 // blocking, synchronous, and using synch idle events with
177 // the standard YieldingNotifier.
179 OSStatus junk
= kOTNoError
;
180 OTAssert ("SetDefaultEndpointModes:invalid ref", ep
!= kOTInvalidEndpointRef
) ;
181 junk
= OTSetAsynchronous(ep
);
182 OTAssert("SetDefaultEndpointModes: Could not set asynchronous", junk
== noErr
);
184 junk = OTSetBlocking(ep);
185 OTAssert("SetDefaultEndpointModes: Could not set blocking", junk == noErr);
186 junk = OTSetSynchronous(ep);
187 OTAssert("SetDefaultEndpointModes: Could not set synchronous", junk == noErr);
188 junk = OTSetBlocking(ep);
189 OTAssert("SetDefaultEndpointModes: Could not set blocking", junk == noErr);
191 junk
= OTInstallNotifier(ep
, gOTNotifierUPP
, data
);
192 OTAssert("SetDefaultEndpointModes: Could not install notifier", junk
== noErr
);
194 junk = OTUseSyncIdleEvents(ep, true);
195 OTAssert("SetDefaultEndpointModes: Could not use sync idle events", junk == noErr);
199 /* Global initialisers */
201 void GSocket_SetGUIFunctions(GSocketGUIFunctionsTable
*table
)
203 // do nothing, wxMac doesn't have wxBase-GUI separation yet
211 bool GSocket_Verify_Inited() ;
212 bool GSocket_Verify_Inited()
216 // Marc Newsam: added the clientcontext variable
217 // however, documentation is unclear how this works
218 OTClientContextPtr clientcontext
;
223 InitOpenTransportInContext(kInitOTForApplicationMask
, &clientcontext
);
225 gInetSvcRef
= OTOpenInternetServicesInContext(kDefaultInternetServicesPath
,
226 NULL
, &err
, clientcontext
);
231 InitOpenTransport() ;
233 gInetSvcRef
= OTOpenInternetServices(kDefaultInternetServicesPath
, NULL
, &err
);
235 if ( gInetSvcRef
== NULL
|| err
!= kOTNoError
)
237 OTAssert("Could not open Inet Services", err
== noErr
);
240 gOTNotifierUPP
= NewOTNotifyUPP( OTInetEventHandler
) ;
244 void GSocket_Cleanup()
246 if ( gOTInited
!= 0 )
248 if ( gInetSvcRef
!= NULL
)
249 OTCloseProvider( gInetSvcRef
);
251 CloseOpenTransportInContext( NULL
) ;
253 CloseOpenTransport() ;
255 if ( gOTNotifierUPP
)
256 DisposeOTNotifyUPP( gOTNotifierUPP
) ;
260 /* Constructors / Destructors for GSocket */
266 m_ok
= GSocket_Verify_Inited();
269 for (i
=0;i
<GSOCK_MAX_EVENT
;i
++)
276 m_error
= GSOCK_NOERROR
;
279 m_non_blocking
= false;
281 /* 10 sec * 1000 millisec */
282 m_takesEvents
= true ;
283 m_mac_events
= wxMacGetNotifierTable() ;
290 /* Check that the socket is really shutdowned */
291 if (m_endpoint
!= kOTInvalidEndpointRef
)
295 /* Destroy private addresses */
297 GAddress_destroy(m_local
);
300 GAddress_destroy(m_peer
);
304 * Disallow further read/write operations on this socket, close
305 * the fd and disable all callbacks.
307 void GSocket::Shutdown()
314 /* If socket has been created, shutdown it */
315 if (m_endpoint
!= kOTInvalidEndpointRef
)
317 err
= OTSndOrderlyDisconnect( m_endpoint
) ;
318 if ( err
!= kOTNoError
)
322 err
= OTRcvOrderlyDisconnect( m_endpoint
) ;
323 err
= OTUnbind( m_endpoint
) ;
324 err
= OTCloseProvider( m_endpoint
) ;
325 m_endpoint
= kOTInvalidEndpointRef
;
328 /* Disable GUI callbacks */
329 for (evt
= 0; evt
< GSOCK_MAX_EVENT
; evt
++)
330 m_cbacks
[evt
] = NULL
;
334 wxMacRemoveAllNotifiersForData( wxMacGetNotifierTable() , this ) ;
338 /* Address handling */
344 * Set or get the local or peer address for this socket. The 'set'
345 * functions return GSOCK_NOERROR on success, an error code otherwise.
346 * The 'get' functions return a pointer to a GAddress object on success,
347 * or NULL otherwise, in which case they set the error code of the
348 * corresponding GSocket.
351 * GSOCK_INVSOCK - the socket is not valid.
352 * GSOCK_INVADDR - the address is not valid.
354 GSocketError
GSocket::SetLocal(GAddress
*address
)
358 /* the socket must be initialized, or it must be a server */
359 if ((m_endpoint
!= kOTInvalidEndpointRef
&& !m_server
))
361 m_error
= GSOCK_INVSOCK
;
362 return GSOCK_INVSOCK
;
366 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
368 m_error
= GSOCK_INVADDR
;
369 return GSOCK_INVADDR
;
373 GAddress_destroy(m_local
);
375 m_local
= GAddress_copy(address
);
377 return GSOCK_NOERROR
;
380 GSocketError
GSocket::SetPeer(GAddress
*address
)
385 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
387 m_error
= GSOCK_INVADDR
;
388 return GSOCK_INVADDR
;
392 GAddress_destroy(m_peer
);
394 m_peer
= GAddress_copy(address
);
396 return GSOCK_NOERROR
;
399 GAddress
*GSocket::GetLocal()
401 GAddress
*address
= NULL
;
407 /* try to get it from the m_local var first */
409 return GAddress_copy(m_local
);
411 /* else, if the socket is initialized, try getsockname */
412 if (m_endpoint
== kOTInvalidEndpointRef
)
414 m_error
= GSOCK_INVSOCK
;
419 /* we do not support multihoming with this code at the moment
420 OTGetProtAddress will have to be used then - but we don't have a handy
421 method to use right now
424 InetInterfaceInfo info
;
425 OTInetGetInterfaceInfo(&info
, kDefaultInetInterface
);
426 loc
.fHost
= info
.fAddress
;
428 loc
.fAddressType
= AF_INET
;
431 /* got a valid address from getsockname, create a GAddress object */
432 address
= GAddress_new();
435 m_error
= GSOCK_MEMERR
;
439 err
= _GAddress_translate_from(address
, &loc
);
440 if (err
!= GSOCK_NOERROR
)
442 GAddress_destroy(address
);
450 GAddress
*GSocket::GetPeer()
454 /* try to get it from the m_peer var */
456 return GAddress_copy(m_peer
);
461 /* Server specific parts */
463 /* GSocket_SetServer:
464 * Sets up this socket as a server. The local address must have been
465 * set with GSocket_SetLocal() before GSocket_SetServer() is called.
466 * Returns GSOCK_NOERROR on success, one of the following otherwise:
469 * GSOCK_INVSOCK - the socket is in use.
470 * GSOCK_INVADDR - the local address has not been set.
471 * GSOCK_IOERR - low-level error.
473 GSocketError
GSocket::SetServer()
477 /* must not be in use */
478 if (m_endpoint
!= kOTInvalidEndpointRef
)
480 m_error
= GSOCK_INVSOCK
;
481 return GSOCK_INVSOCK
;
484 /* the local addr must have been set */
487 m_error
= GSOCK_INVADDR
;
488 return GSOCK_INVADDR
;
491 /* Initialize all fields */
498 /* Create the socket */
499 m_endpoint
= socket(m_local
->m_realfamily
, SOCK_STREAM
, 0);
500 socket_set_ref( m_endpoint
, (unsigned long) &gMacNetEvents
, (unsigned long) this ) ;
501 if (m_endpoint
== kOTInvalidEndpointRef
)
503 m_error
= GSOCK_IOERR
;
507 ioctl(m_endpoint
, FIONBIO
, &arg
);
510 /* Bind to the local address,
511 * retrieve the actual address bound,
512 * and listen up to 5 connections.
514 if ((bind(m_endpoint
, m_local
->m_addr
, m_local
->m_len
) != 0) ||
515 (getsockname(m_endpoint
,
517 (SOCKLEN_T
*) &m_local
->m_len
) != 0) ||
518 (listen(m_endpoint
, 5) != 0))
522 m_error
= GSOCK_IOERR
;
526 return GSOCK_NOERROR
;
529 /* GSocket_WaitConnection:
530 * Waits for an incoming client connection. Returns a pointer to
531 * a GSocket object, or NULL if there was an error, in which case
532 * the last error field will be updated for the calling GSocket.
534 * Error codes (set in the calling GSocket)
535 * GSOCK_INVSOCK - the socket is not valid or not a server.
536 * GSOCK_TIMEDOUT - timeout, no incoming connections.
537 * GSOCK_WOULDBLOCK - the call would block and the socket is nonblocking.
538 * GSOCK_MEMERR - couldn't allocate memory.
539 * GSOCK_IOERR - low-level error.
541 GSocket
*GSocket::WaitConnection()
543 GSocket
*connection
= NULL
;
547 /* Reenable CONNECTION events */
548 m_detected
&= ~GSOCK_CONNECTION_FLAG
;
550 /* If the socket has already been created, we exit immediately */
551 if (m_endpoint
== kOTInvalidEndpointRef
|| !m_server
)
553 m_error
= GSOCK_INVSOCK
;
557 /* Create a GSocket object for the new connection */
558 connection
= GSocket_new();
562 m_error
= GSOCK_MEMERR
;
566 /* Wait for a connection (with timeout) */
567 if (Input_Timeout() == GSOCK_TIMEDOUT
)
570 /* m_error set by _GSocket_Input_Timeout */
576 connection
->m_endpoint
= accept(m_endpoint
, &from
, (SOCKLEN_T
*) &fromlen
);
579 if (connection
->m_endpoint
== kOTInvalidEndpointRef
)
581 if (errno
== EWOULDBLOCK
)
582 m_error
= GSOCK_WOULDBLOCK
;
584 m_error
= GSOCK_IOERR
;
590 /* Initialize all fields */
591 connection
->m_server
= false;
592 connection
->m_stream
= true;
593 connection
->m_oriented
= true;
595 /* Setup the peer address field */
596 connection
->m_peer
= GAddress_new();
597 if (!connection
->m_peer
)
600 m_error
= GSOCK_MEMERR
;
605 err
= _GAddress_translate_from(connection
->m_peer
, &from
, fromlen
);
606 if (err
!= GSOCK_NOERROR
)
608 GAddress_destroy(connection
->m_peer
);
609 GSocket_destroy(connection
);
614 ioctl(connection
->m_endpoint
, FIONBIO
, &arg
);
616 connection
->Enable_Events();
621 /* Datagram sockets */
623 /* GSocket_SetNonOriented:
624 * Sets up this socket as a non-connection oriented (datagram) socket.
625 * Before using this function, the local address must have been set
626 * with GSocket_SetLocal(), or the call will fail. Returns GSOCK_NOERROR
627 * on success, or one of the following otherwise.
630 * GSOCK_INVSOCK - the socket is in use.
631 * GSOCK_INVADDR - the local address has not been set.
632 * GSOCK_IOERR - low-level error.
634 GSocketError
GSocket::SetNonOriented()
638 if (m_endpoint
!= kOTInvalidEndpointRef
)
640 m_error
= GSOCK_INVSOCK
;
641 return GSOCK_INVSOCK
;
646 m_error
= GSOCK_INVADDR
;
647 return GSOCK_INVADDR
;
650 /* Initialize all fields */
655 /* Create the socket */
659 m_endpoint
= socket(m_local
->m_realfamily
, SOCK_DGRAM
, 0);
660 socket_set_ref( m_endpoint
, (unsigned long) &gMacNetEvents
, (unsigned long) this ) ;
662 if (m_endpoint
== kOTInvalidEndpointRef
)
664 m_error
= GSOCK_IOERR
;
670 ioctl(m_endpoint
, FIONBIO
, &arg
);
674 /* Bind to the local address,
675 * and retrieve the actual address bound.
679 if ((bind(m_endpoint
, m_local
->m_addr
, m_local
->m_len
) != 0) ||
680 (getsockname(m_endpoint
,
682 (SOCKLEN_T
*) &m_local
->m_len
) != 0))
686 m_error
= GSOCK_IOERR
;
690 return GSOCK_NOERROR
;
693 /* Client specific parts */
696 * For stream (connection oriented) sockets, GSocket_Connect() tries
697 * to establish a client connection to a server using the peer address
698 * as established with GSocket_SetPeer(). Returns GSOCK_NOERROR if the
699 * connection has been successfully established, or one of the error
700 * codes listed below. Note that for nonblocking sockets, a return
701 * value of GSOCK_WOULDBLOCK doesn't mean a failure. The connection
702 * request can be completed later; you should use GSocket_Select()
703 * to poll for GSOCK_CONNECTION | GSOCK_LOST, or wait for the
704 * corresponding asynchronous events.
706 * For datagram (non connection oriented) sockets, GSocket_Connect()
707 * just sets the peer address established with GSocket_SetPeer() as
708 * default destination.
711 * GSOCK_INVSOCK - the socket is in use or not valid.
712 * GSOCK_INVADDR - the peer address has not been established.
713 * GSOCK_TIMEDOUT - timeout, the connection failed.
714 * GSOCK_WOULDBLOCK - connection in progress (nonblocking sockets only)
715 * GSOCK_MEMERR - couldn't allocate memory.
716 * GSOCK_IOERR - low-level error.
718 GSocketError
GSocket::Connect(GSocketStream stream
)
722 OSStatus err
= kOTNoError
;
727 /* Enable CONNECTION events (needed for nonblocking connections) */
728 m_detected
&= ~GSOCK_CONNECTION_FLAG
;
730 if (m_endpoint
!= kOTInvalidEndpointRef
)
732 m_error
= GSOCK_INVSOCK
;
733 return GSOCK_INVSOCK
;
738 m_error
= GSOCK_INVADDR
;
739 return GSOCK_INVADDR
;
742 /* Streamed or dgram socket? */
743 m_stream
= (stream
== GSOCK_STREAMED
);
747 /* Create the socket */
750 OTOpenEndpointInContext( OTCreateConfiguration( kTCPName
) , 0 , &info
, &err
, NULL
) ;
753 OTOpenEndpoint( OTCreateConfiguration( kTCPName
) , 0 , &info
, &err
) ;
755 if ( m_endpoint
== kOTInvalidEndpointRef
|| err
!= kOTNoError
)
757 m_endpoint
= kOTInvalidEndpointRef
;
758 m_error
= GSOCK_IOERR
;
761 err
= OTBind( m_endpoint
, nil
, nil
) ;
762 if ( err
!= kOTNoError
)
766 SetDefaultEndpointModes( m_endpoint
, this ) ;
769 ioctl(m_endpoint
, FIONBIO
, &arg
);
773 _GAddress_translate_to( m_peer
, &addr
) ;
774 memset( &peer
, 0 , sizeof( TCall
) ) ;
775 peer
.addr
.len
= sizeof( InetAddress
) ;
776 peer
.addr
.buf
= (unsigned char*) &addr
;
777 err
= OTConnect( m_endpoint
, &peer
, nil
) ;
780 /* If connect failed with EINPROGRESS and the GSocket object
781 * is in blocking mode, we select() for the specified timeout
782 * checking for writability to see if the connection request
786 if ((err
== kOTNoDataErr
) && (!m_non_blocking
))
788 if (Output_Timeout() == GSOCK_TIMEDOUT
)
790 OTSndOrderlyDisconnect( m_endpoint
) ;
791 m_endpoint
= kOTInvalidEndpointRef
;
792 /* m_error is set in _GSocket_Output_Timeout */
793 return GSOCK_TIMEDOUT
;
799 SOCKLEN_T len = sizeof(error);
801 getsockopt(m_endpoint, SOL_SOCKET, SO_ERROR, (void*) &error, &len);
805 return GSOCK_NOERROR
;
809 /* If connect failed with EINPROGRESS and the GSocket object
810 * is set to nonblocking, we set m_error to GSOCK_WOULDBLOCK
811 * (and return GSOCK_WOULDBLOCK) but we don't close the socket;
812 * this way if the connection completes, a GSOCK_CONNECTION
813 * event will be generated, if enabled.
815 if ((err
== kOTNoDataErr
) && (m_non_blocking
))
817 m_error
= GSOCK_WOULDBLOCK
;
818 return GSOCK_WOULDBLOCK
;
821 /* If connect failed with an error other than EINPROGRESS,
822 * then the call to GSocket_Connect has failed.
824 OTSndOrderlyDisconnect( m_endpoint
) ;
826 m_endpoint
= kOTInvalidEndpointRef
;
827 m_error
= GSOCK_IOERR
;
830 // OTInetEventHandler(this, T_CONNECT , kOTNoError , NULL ) ;
831 return GSOCK_NOERROR
;
836 /* Like recv(), send(), ... */
837 int GSocket::Read(char *buffer
, int size
)
843 /* Reenable INPUT events */
844 m_detected
&= ~GSOCK_INPUT_FLAG
;
846 if (m_endpoint
== kOTInvalidEndpointRef
|| m_server
)
848 m_error
= GSOCK_INVSOCK
;
852 /* If the socket is blocking, wait for data (with a timeout) */
853 if (Input_Timeout() == GSOCK_TIMEDOUT
)
858 ret
= Recv_Stream(buffer
, size
);
860 ret
= Recv_Dgram(buffer
, size
);
864 if (errno
== EWOULDBLOCK
)
865 m_error
= GSOCK_WOULDBLOCK
;
867 m_error
= GSOCK_IOERR
;
873 int GSocket::Write(const char *buffer
, int size
)
879 if (m_endpoint
== kOTInvalidEndpointRef
|| m_server
)
881 m_error
= GSOCK_INVSOCK
;
885 /* If the socket is blocking, wait for writability (with a timeout) */
886 if (Output_Timeout() == GSOCK_TIMEDOUT
)
891 ret
= Send_Stream(buffer
, size
);
893 ret
= Send_Dgram(buffer
, size
);
897 if (errno
== EWOULDBLOCK
)
898 m_error
= GSOCK_WOULDBLOCK
;
900 m_error
= GSOCK_IOERR
;
902 /* Only reenable OUTPUT events after an error (just like WSAAsyncSelect
903 * in MSW). Once the first OUTPUT event is received, users can assume
904 * that the socket is writable until a read operation fails. Only then
905 * will further OUTPUT events be posted.
907 m_detected
&= ~GSOCK_OUTPUT_FLAG
;
915 * Polls the socket to determine its status. This function will
916 * check for the events specified in the 'flags' parameter, and
917 * it will return a mask indicating which operations can be
918 * performed. This function won't block, regardless of the
919 * mode (blocking | nonblocking) of the socket.
921 GSocketEventFlags
GSocket::Select(GSocketEventFlags flags
)
924 wxMacProcessNotifierEvents() ;
926 state = OTGetEndpointState(m_endpoint);
928 if ( ( flags & GSOCK_INPUT_FLAG ) && ! ( m_detected & GSOCK_INPUT_FLAG ) )
931 OTCountDataBytes( m_endpoint , &sz ) ;
932 if ( state == T_INCON || sz > 0 )
934 m_detected |= GSOCK_INPUT_FLAG ;
935 (m_cbacks[GSOCK_INPUT])(this, GSOCK_INPUT, m_data[GSOCK_INPUT]);
938 if ( ( flags & GSOCK_INPUT_FLAG ) && ! ( m_detected & GSOCK_OUTPUT_FLAG ) )
940 if ( state == T_DATAXFER || state == T_INREL )
942 m_detected |=GSOCK_OUTPUT_FLAG ;
943 (m_cbacks[GSOCK_OUTPUT])(this, GSOCK_OUTPUT, m_data[GSOCK_OUTPUT]);
947 return ( flags
& m_detected
) ;
952 /* GSocket_SetNonBlocking:
953 * Sets the socket to non-blocking mode. All IO calls will return
956 void GSocket::SetNonBlocking(bool non_block
)
960 m_non_blocking
= non_block
;
963 /* GSocket_SetTimeout:
964 * Sets the timeout for blocking calls. Time is expressed in
967 void GSocket::SetTimeout(unsigned long millisec
)
971 // this is usually set too high and we have not yet been able to detect a closed
972 // stream, thus we leave the 10 sec timeout
973 // m_timeout = millisec;
977 * Returns the last error which occurred for this socket. Note that successful
978 * operations do not clear this back to GSOCK_NOERROR, so use it only
981 GSocketError WXDLLIMPEXP_NET
GSocket::GetError()
991 * There is data to be read in the input buffer. If, after a read
992 * operation, there is still data available, the callback function will
995 * The socket is available for writing. That is, the next write call
996 * won't block. This event is generated only once, when the connection is
997 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
998 * when the output buffer empties again. This means that the app should
999 * assume that it can write since the first OUTPUT event, and no more
1000 * OUTPUT events will be generated unless an error occurs.
1002 * Connection successfully established, for client sockets, or incoming
1003 * client connection, for server sockets. Wait for this event (also watch
1004 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
1006 * The connection is lost (or a connection request failed); this could
1007 * be due to a failure, or due to the peer closing it gracefully.
1010 /* GSocket_SetCallback:
1011 * Enables the callbacks specified by 'flags'. Note that 'flags'
1012 * may be a combination of flags OR'ed toghether, so the same
1013 * callback function can be made to accept different events.
1014 * The callback function must have the following prototype:
1016 * void function(GSocket *socket, GSocketEvent event, char *cdata)
1018 void GSocket::SetCallback(GSocketEventFlags flags
,
1019 GSocketCallback callback
, char *cdata
)
1025 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1027 if ((flags
& (1 << count
)) != 0)
1029 m_cbacks
[count
] = callback
;
1030 m_data
[count
] = cdata
;
1035 /* GSocket_UnsetCallback:
1036 * Disables all callbacks specified by 'flags', which may be a
1037 * combination of flags OR'ed toghether.
1039 void GSocket::UnsetCallback(GSocketEventFlags flags
)
1045 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1047 if ((flags
& (1 << count
)) != 0)
1049 m_cbacks
[count
] = NULL
;
1050 m_data
[count
] = NULL
;
1056 #define CALL_CALLBACK(socket, event) { \
1057 _GSocket_Disable(socket, event); \
1058 if (socket->m_cbacks[event]) \
1059 socket->m_cbacks[event](socket, event, socket->m_data[event]); \
1062 int GSocket::Recv_Stream(char *buffer
, int size
)
1066 OTByteCount sz
= 0 ;
1068 OTCountDataBytes( m_endpoint
, &sz
) ;
1069 if ( size
> (int)sz
)
1071 res
= OTRcv( m_endpoint
, buffer
, size
, &flags
) ;
1077 // we simulate another read event if there are still bytes
1078 if ( m_takesEvents
)
1080 OTByteCount sz
= 0 ;
1081 OTCountDataBytes( m_endpoint
, &sz
) ;
1084 m_detected
|= GSOCK_INPUT_FLAG
;
1085 (m_cbacks
[GSOCK_INPUT
])(this, GSOCK_INPUT
, m_data
[GSOCK_INPUT
]);
1091 int GSocket::Recv_Dgram(char *buffer
, int size
)
1096 struct sockaddr from
;
1097 SOCKLEN_T fromlen
= sizeof(from
);
1100 fromlen
= sizeof(from
);
1102 ret
= recvfrom(m_endpoint
, buffer
, size
, 0, &from
, (SOCKLEN_T
*) &fromlen
);
1107 /* Translate a system address into a GSocket address */
1110 m_peer
= GAddress_new();
1113 m_error
= GSOCK_MEMERR
;
1117 err
= _GAddress_translate_from(m_peer
, &from
, fromlen
);
1118 if (err
!= GSOCK_NOERROR
)
1120 GAddress_destroy(m_peer
);
1129 int GSocket::Send_Stream(const char *buffer
, int size
)
1134 res
= OTSnd( m_endpoint
, (void*) buffer
, size
, flags
) ;
1138 int GSocket::Send_Dgram(const char *buffer
, int size
)
1143 struct sockaddr
*addr
;
1149 m_error
= GSOCK_INVADDR
;
1153 err
= _GAddress_translate_to(m_peer
, &addr
, &len
);
1154 if (err
!= GSOCK_NOERROR
)
1160 ret
= sendto(m_endpoint
, buffer
, size
, 0, addr
, len
);
1162 /* Frees memory allocated from _GAddress_translate_to */
1168 /* Compatibility functions for GSocket */
1169 GSocket
*GSocket_new(void)
1171 GSocket
*newsocket
= new GSocket();
1172 if(newsocket
->IsOk())
1180 * -------------------------------------------------------------------------
1182 * -------------------------------------------------------------------------
1185 /* CHECK_ADDRESS verifies that the current family is either GSOCK_NOFAMILY
1186 * or GSOCK_*family*, and if it is GSOCK_NOFAMILY, it initalizes address
1187 * to be a GSOCK_*family*. In other cases, it returns GSOCK_INVADDR.
1189 #define CHECK_ADDRESS(address, family, retval) \
1191 if (address->m_family == GSOCK_NOFAMILY) \
1192 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1193 return address->m_error; \
1194 if (address->m_family != GSOCK_##family) \
1196 address->m_error = GSOCK_INVADDR; \
1201 GAddress
*GAddress_new()
1205 if ((address
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1208 address
->m_family
= GSOCK_NOFAMILY
;
1209 address
->m_host
= INADDR_NONE
;
1210 address
->m_port
= 0 ;
1215 GAddress
*GAddress_copy(GAddress
*address
)
1219 assert(address
!= NULL
);
1221 if ((addr2
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1224 memcpy(addr2
, address
, sizeof(GAddress
));
1228 void GAddress_destroy(GAddress
*address
)
1230 assert(address
!= NULL
);
1235 void GAddress_SetFamily(GAddress
*address
, GAddressType type
)
1237 assert(address
!= NULL
);
1239 address
->m_family
= type
;
1242 GAddressType
GAddress_GetFamily(GAddress
*address
)
1244 assert(address
!= NULL
);
1246 return address
->m_family
;
1249 GSocketError
_GAddress_translate_from(GAddress
*address
,
1252 switch (addr
->fAddressType
)
1255 address
->m_family
= GSOCK_INET
;
1259 address
->m_family
= GSOCK_INET6
;
1264 address
->m_error
= GSOCK_INVOP
;
1268 address
->m_host
= addr
->fHost
;
1269 address
->m_port
= addr
->fPort
;
1270 return GSOCK_NOERROR
;
1273 GSocketError
_GAddress_translate_to(GAddress
*address
,
1276 if ( !GSocket_Verify_Inited() )
1277 return GSOCK_IOERR
;
1278 memset(addr
, 0 , sizeof(struct InetAddress
));
1279 OTInitInetAddress( addr
, address
->m_port
, address
->m_host
) ;
1280 return GSOCK_NOERROR
;
1284 * -------------------------------------------------------------------------
1285 * Internet address family
1286 * -------------------------------------------------------------------------
1289 GSocketError
_GAddress_Init_INET(GAddress
*address
)
1291 address
->m_family
= GSOCK_INET
;
1292 address
->m_host
= kOTAnyInetAddress
;
1294 return GSOCK_NOERROR
;
1297 GSocketError
GAddress_INET_SetHostName(GAddress
*address
, const char *hostname
)
1299 InetHostInfo hinfo
;
1302 if ( !GSocket_Verify_Inited() )
1303 return GSOCK_IOERR
;
1305 assert(address
!= NULL
);
1307 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1308 ret
= OTInetStringToAddress( gInetSvcRef
, (char*) hostname
, &hinfo
) ;
1309 if ( ret
!= kOTNoError
)
1311 address
->m_host
= INADDR_NONE
;
1312 address
->m_error
= GSOCK_NOHOST
;
1313 return GSOCK_NOHOST
;
1315 address
->m_host
= hinfo
.addrs
[0] ;
1316 return GSOCK_NOERROR
;
1319 GSocketError
GAddress_INET_SetAnyAddress(GAddress
*address
)
1321 return GAddress_INET_SetHostAddress(address
, INADDR_ANY
);
1324 GSocketError
GAddress_INET_SetHostAddress(GAddress
*address
,
1325 unsigned long hostaddr
)
1327 assert(address
!= NULL
);
1329 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1331 address
->m_host
= htonl(hostaddr
) ;
1333 return GSOCK_NOERROR
;
1336 struct service_entry
1339 unsigned short port
;
1340 const char * protocol
;
1342 typedef struct service_entry service_entry
;
1344 service_entry gServices
[] =
1346 { "http" , 80 , "tcp" }
1349 GSocketError
GAddress_INET_SetPortName(GAddress
*address
, const char *port
,
1350 const char *protocol
)
1354 assert(address
!= NULL
);
1355 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1359 address
->m_error
= GSOCK_INVPORT
;
1360 return GSOCK_INVPORT
;
1362 for ( i
= 0 ; i
< sizeof( gServices
) / sizeof( service_entry
) ; ++i
)
1364 if ( strcmp( port
, gServices
[i
].name
) == 0 )
1366 if ( protocol
== NULL
|| strcmp( protocol
, gServices
[i
].protocol
) )
1368 address
->m_port
= gServices
[i
].port
;
1369 return GSOCK_NOERROR
;
1374 if (isdigit(port
[0]))
1376 address
->m_port
= atoi(port
);
1377 return GSOCK_NOERROR
;
1380 address
->m_error
= GSOCK_INVPORT
;
1381 return GSOCK_INVPORT
;
1384 GSocketError
GAddress_INET_SetPort(GAddress
*address
, unsigned short port
)
1386 assert(address
!= NULL
);
1387 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1388 address
->m_port
= port
;
1390 return GSOCK_NOERROR
;
1393 GSocketError
GAddress_INET_GetHostName(GAddress
*address
, char *hostname
, size_t sbuf
)
1395 InetDomainName name
;
1396 if ( !GSocket_Verify_Inited() )
1397 return GSOCK_IOERR
;
1399 assert(address
!= NULL
);
1400 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1402 OTInetAddressToName( gInetSvcRef
, address
->m_host
, name
) ;
1403 strncpy( hostname
, name
, sbuf
) ;
1404 return GSOCK_NOERROR
;
1407 unsigned long GAddress_INET_GetHostAddress(GAddress
*address
)
1409 assert(address
!= NULL
);
1410 CHECK_ADDRESS(address
, INET
, 0);
1412 return ntohl(address
->m_host
);
1415 unsigned short GAddress_INET_GetPort(GAddress
*address
)
1417 assert(address
!= NULL
);
1418 CHECK_ADDRESS(address
, INET
, 0);
1420 return address
->m_port
;
1423 void GSocket::Enable_Events()
1425 if ( m_takesEvents
)
1430 m_takesEvents
= true ;
1431 state
= OTGetEndpointState(m_endpoint
);
1434 OTByteCount sz
= 0 ;
1435 OTCountDataBytes( m_endpoint
, &sz
) ;
1436 if ( state
== T_INCON
|| sz
> 0 )
1438 m_detected
|= GSOCK_INPUT_FLAG
;
1439 (m_cbacks
[GSOCK_INPUT
])(this, GSOCK_INPUT
, m_data
[GSOCK_INPUT
]);
1443 if ( state
== T_DATAXFER
|| state
== T_INREL
)
1445 m_detected
|=GSOCK_OUTPUT_FLAG
;
1446 (m_cbacks
[GSOCK_OUTPUT
])(this, GSOCK_OUTPUT
, m_data
[GSOCK_OUTPUT
]);
1452 void GSocket::Disable_Events()
1454 m_takesEvents
= false ;
1457 /* _GSocket_Input_Timeout:
1458 * For blocking sockets, wait until data is available or
1459 * until timeout ellapses.
1461 GSocketError
GSocket::Input_Timeout()
1463 if ( !m_non_blocking
)
1465 UnsignedWide now
, start
;
1466 bool formerTakesEvents
= m_takesEvents
;
1467 Microseconds(&start
);
1469 m_takesEvents
= false ;
1471 while( (now
.hi
* 4294967296.0 + now
.lo
) - (start
.hi
* 4294967296.0 + start
.lo
) < m_timeout
* 1000.0 )
1474 OTByteCount sz
= 0 ;
1475 state
= OTGetEndpointState(m_endpoint
);
1477 OTCountDataBytes( m_endpoint
, &sz
) ;
1478 if ( state
== T_INCON
|| sz
> 0 )
1480 m_takesEvents
= formerTakesEvents
;
1481 return GSOCK_NOERROR
;
1485 m_takesEvents
= formerTakesEvents
;
1486 m_error
= GSOCK_TIMEDOUT
;
1487 return GSOCK_TIMEDOUT
;
1489 return GSOCK_NOERROR
;
1492 /* _GSocket_Output_Timeout:
1493 * For blocking sockets, wait until data can be sent without
1494 * blocking or until timeout ellapses.
1496 GSocketError
GSocket::Output_Timeout()
1498 if ( !m_non_blocking
)
1500 UnsignedWide now
, start
;
1501 bool formerTakesEvents
= m_takesEvents
;
1502 Microseconds(&start
);
1504 m_takesEvents
= false ;
1506 while( (now
.hi
* 4294967296.0 + now
.lo
) - (start
.hi
* 4294967296.0 + start
.lo
) < m_timeout
* 1000.0 )
1509 state
= OTGetEndpointState(m_endpoint
);
1511 if ( state
== T_DATAXFER
|| state
== T_INREL
)
1513 m_takesEvents
= formerTakesEvents
;
1514 return GSOCK_NOERROR
;
1518 m_takesEvents
= formerTakesEvents
;
1519 m_error
= GSOCK_TIMEDOUT
;
1520 return GSOCK_TIMEDOUT
;
1522 return GSOCK_NOERROR
;
1526 * There is data to be read in the input buffer. If, after a read
1527 * operation, there is still data available, the callback function will
1530 * The socket is available for writing. That is, the next write call
1531 * won't block. This event is generated only once, when the connection is
1532 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
1533 * when the output buffer empties again. This means that the app should
1534 * assume that it can write since the first OUTPUT event, and no more
1535 * OUTPUT events will be generated unless an error occurs.
1537 * Connection successfully established, for client sockets, or incoming
1538 * client connection, for server sockets. Wait for this event (also watch
1539 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
1541 * The connection is lost (or a connection request failed); this could
1542 * be due to a failure, or due to the peer closing it gracefully.
1545 void _GSocket_Internal_Proc(unsigned long e
, void* d
)
1548 GSocket
* socket
= (GSocket
*) d
;
1549 OTEventCode ev
= (OTEventCode
) e
;
1551 GSocketEvent event2
;
1552 GSocketCallback cback
;
1554 GSocketCallback cback2
;
1559 event
= GSOCK_MAX_EVENT
;
1560 event2
= GSOCK_MAX_EVENT
;
1566 /* Check that the socket still exists (it has not been
1567 * destroyed) and for safety, check that the m_endpoint field
1568 * is what we expect it to be.
1570 if ((socket
!= NULL
) && (socket
->m_takesEvents
))
1575 event
= GSOCK_CONNECTION
;
1578 event
= GSOCK_CONNECTION
;
1579 event2
= GSOCK_OUTPUT
;
1583 retCall
.addr
.buf
= NULL
;
1584 retCall
.addr
.maxlen
= 0;
1585 retCall
.opt
.buf
= NULL
;
1586 retCall
.opt
.maxlen
= 0;
1587 retCall
.udata
.buf
= NULL
;
1588 retCall
.udata
.maxlen
= 0;
1589 OTRcvConnect( socket
->m_endpoint
, &retCall
) ;
1593 event
= GSOCK_LOST
;
1597 event
= GSOCK_OUTPUT
;
1600 event
= GSOCK_INPUT
;
1603 event
= GSOCK_INPUT
;
1606 if (event
!= GSOCK_MAX_EVENT
)
1608 cback
= socket
->m_cbacks
[event
];
1609 data
= socket
->m_data
[event
];
1611 if (event
== GSOCK_LOST
)
1612 socket
->m_detected
= GSOCK_LOST_FLAG
;
1614 socket
->m_detected
|= (1 << event
);
1616 if (event2
!= GSOCK_MAX_EVENT
)
1618 cback2
= socket
->m_cbacks
[event2
];
1619 data2
= socket
->m_data
[event2
];
1621 if (event2
== GSOCK_LOST
)
1622 socket
->m_detected
= GSOCK_LOST_FLAG
;
1624 socket
->m_detected
|= (1 << event2
);
1628 /* OK, we can now leave the critical section because we have
1629 * already obtained the callback address (we make no further
1630 * accesses to socket->whatever). However, the app should
1631 * be prepared to handle events from a socket that has just
1636 (cback
)(socket
, event
, data
);
1638 (cback2
)(socket
, event2
, data2
);
1642 /* Hack added for Mac OS X */
1643 GSocketError
GAddress_UNIX_GetPath(GAddress
*addr
, char *path
, size_t buf
)
1645 return GSOCK_INVADDR
;
1648 GSocketError
GAddress_UNIX_SetPath(GAddress
*addr
, const char *path
)
1650 return GSOCK_INVADDR
;
1653 #endif /* wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__) */