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>
28 #include <MacHeaders.c>
29 #define OTUNIXERRORS 1
30 #include <OpenTransport.h>
31 #include <OpenTransportProviders.h>
32 #include <OpenTptInternet.h>
34 #if TARGET_CARBON && !defined(OTAssert)
35 #define OTAssert( str , cond ) /* does not exists in Carbon */
49 * INADDR_BROADCAST is identical to INADDR_NONE which is not defined
50 * on all unices. INADDR_BROADCAST should be fine to indicate an error.
52 #ifndef INADDR_BROADCAST
53 #define INADDR_BROADCAST 0xFFFFFFFFUL
56 #define INADDR_NONE INADDR_BROADCAST
59 #define INADDR_ANY 0x0UL
61 #ifndef __GSOCKET_STANDALONE__
63 #include "wx/mac/macnotfy.h"
64 #include "wx/mac/gsockmac.h"
65 #include "wx/gsocket.h"
72 #endif /* __GSOCKET_STANDALONE__ */
85 extern pascal void OTDebugStr(const char* str
);
90 InetSvcRef gInetSvcRef
= 0 ;
92 OTNotifyUPP gOTNotifierUPP
= NULL
;
94 OSStatus
DoNegotiateIPReuseAddrOption(EndpointRef ep
, Boolean enableReuseIPMode
);
96 /* Input: ep - endpointref on which to negotiate the option
97 enableReuseIPMode - desired option setting - true/false
98 Return: kOTNoError indicates that the option was successfully negotiated
99 OSStatus is an error if < 0, otherwise, the status field is
102 IMPORTANT NOTE: The endpoint is assumed to be in synchronous more, otherwise
103 this code will not function as desired
107 OSStatus
DoNegotiateIPReuseAddrOption(EndpointRef ep
, Boolean enableReuseIPMode
)
110 UInt8 buf
[kOTFourByteOptionSize
]; // define buffer for fourByte Option size
111 TOption
* opt
; // option ptr to make items easier to access
116 if (!OTIsSynchronous(ep
))
120 opt
= (TOption
*)buf
; // set option ptr to buffer
122 req
.opt
.len
= sizeof(buf
);
123 req
.flags
= T_NEGOTIATE
; // negotiate for option
126 ret
.opt
.maxlen
= kOTFourByteOptionSize
;
128 opt
->level
= INET_IP
; // dealing with an IP Level function
130 opt
->name
= kIP_REUSEADDR
;
132 opt
->name
= IP_REUSEADDR
;
134 opt
->len
= kOTFourByteOptionSize
;
136 *(UInt32
*)opt
->value
= enableReuseIPMode
; // set the desired option level, true or false
138 err
= OTOptionManagement(ep
, &req
, &ret
);
140 // if no error then return the option status value
141 if (err
== kOTNoError
)
143 if (opt
->status
!= T_SUCCESS
)
153 pascal void OTInetEventHandler(void*s
, OTEventCode event
, OTResult
, void *cookie
) ;
154 pascal void OTInetEventHandler(void*s
, OTEventCode event
, OTResult result
, void *cookie
)
157 GSocket
* sock
= (GSocket
*) s
;
159 if ( event
== kOTSyncIdleEvent
)
166 wxMacAddEvent( sock
->m_mac_events
, _GSocket_Internal_Proc
, event
, s
, wakeUp
) ;
172 static void SetDefaultEndpointModes(EndpointRef ep
, void *data
)
173 // This routine sets the supplied endpoint into the default
174 // mode used in this application. The specifics are:
175 // blocking, synchronous, and using synch idle events with
176 // the standard YieldingNotifier.
178 OSStatus junk
= kOTNoError
;
179 OTAssert ("SetDefaultEndpointModes:invalid ref", ep
!= kOTInvalidEndpointRef
) ;
180 junk
= OTSetAsynchronous(ep
);
181 OTAssert("SetDefaultEndpointModes: Could not set asynchronous", junk
== noErr
);
183 junk = OTSetBlocking(ep);
184 OTAssert("SetDefaultEndpointModes: Could not set blocking", junk == noErr);
185 junk = OTSetSynchronous(ep);
186 OTAssert("SetDefaultEndpointModes: Could not set synchronous", junk == noErr);
187 junk = OTSetBlocking(ep);
188 OTAssert("SetDefaultEndpointModes: Could not set blocking", junk == noErr);
190 junk
= OTInstallNotifier(ep
, gOTNotifierUPP
, data
);
191 OTAssert("SetDefaultEndpointModes: Could not install notifier", junk
== noErr
);
193 junk = OTUseSyncIdleEvents(ep, true);
194 OTAssert("SetDefaultEndpointModes: Could not use sync idle events", junk == noErr);
198 /* Global initialisers */
200 void GSocket_SetGUIFunctions(GSocketGUIFunctionsTable
*table
)
202 // do nothing, wxMac doesn't have wxBase-GUI separation yet
210 bool GSocket_Verify_Inited() ;
211 bool GSocket_Verify_Inited()
215 // Marc Newsam: added the clientcontext variable
216 // however, documentation is unclear how this works
217 OTClientContextPtr clientcontext
;
222 InitOpenTransportInContext(kInitOTForApplicationMask
, &clientcontext
);
224 gInetSvcRef
= OTOpenInternetServicesInContext(kDefaultInternetServicesPath
,
225 NULL
, &err
, clientcontext
);
230 InitOpenTransport() ;
232 gInetSvcRef
= OTOpenInternetServices(kDefaultInternetServicesPath
, NULL
, &err
);
234 if ( gInetSvcRef
== NULL
|| err
!= kOTNoError
)
236 OTAssert("Could not open Inet Services", err
== noErr
);
239 gOTNotifierUPP
= NewOTNotifyUPP( OTInetEventHandler
) ;
243 void GSocket_Cleanup()
245 if ( gOTInited
!= 0 )
247 if ( gInetSvcRef
!= NULL
)
248 OTCloseProvider( gInetSvcRef
);
250 CloseOpenTransportInContext( NULL
) ;
252 CloseOpenTransport() ;
254 if ( gOTNotifierUPP
)
255 DisposeOTNotifyUPP( gOTNotifierUPP
) ;
259 /* Constructors / Destructors for GSocket */
265 m_ok
= GSocket_Verify_Inited();
268 for (i
=0;i
<GSOCK_MAX_EVENT
;i
++)
275 m_error
= GSOCK_NOERROR
;
278 m_non_blocking
= false;
280 /* 10 sec * 1000 millisec */
281 m_takesEvents
= true ;
282 m_mac_events
= wxMacGetNotifierTable() ;
289 /* Check that the socket is really shutdowned */
290 if (m_endpoint
!= kOTInvalidEndpointRef
)
294 /* Destroy private addresses */
296 GAddress_destroy(m_local
);
299 GAddress_destroy(m_peer
);
303 * Disallow further read/write operations on this socket, close
304 * the fd and disable all callbacks.
306 void GSocket::Shutdown()
313 /* If socket has been created, shutdown it */
314 if (m_endpoint
!= kOTInvalidEndpointRef
)
316 err
= OTSndOrderlyDisconnect( m_endpoint
) ;
317 if ( err
!= kOTNoError
)
321 err
= OTRcvOrderlyDisconnect( m_endpoint
) ;
322 err
= OTUnbind( m_endpoint
) ;
323 err
= OTCloseProvider( m_endpoint
) ;
324 m_endpoint
= kOTInvalidEndpointRef
;
327 /* Disable GUI callbacks */
328 for (evt
= 0; evt
< GSOCK_MAX_EVENT
; evt
++)
329 m_cbacks
[evt
] = NULL
;
333 wxMacRemoveAllNotifiersForData( wxMacGetNotifierTable() , this ) ;
337 /* Address handling */
343 * Set or get the local or peer address for this socket. The 'set'
344 * functions return GSOCK_NOERROR on success, an error code otherwise.
345 * The 'get' functions return a pointer to a GAddress object on success,
346 * or NULL otherwise, in which case they set the error code of the
347 * corresponding GSocket.
350 * GSOCK_INVSOCK - the socket is not valid.
351 * GSOCK_INVADDR - the address is not valid.
353 GSocketError
GSocket::SetLocal(GAddress
*address
)
357 /* the socket must be initialized, or it must be a server */
358 if ((m_endpoint
!= kOTInvalidEndpointRef
&& !m_server
))
360 m_error
= GSOCK_INVSOCK
;
361 return GSOCK_INVSOCK
;
365 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
367 m_error
= GSOCK_INVADDR
;
368 return GSOCK_INVADDR
;
372 GAddress_destroy(m_local
);
374 m_local
= GAddress_copy(address
);
376 return GSOCK_NOERROR
;
379 GSocketError
GSocket::SetPeer(GAddress
*address
)
384 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
386 m_error
= GSOCK_INVADDR
;
387 return GSOCK_INVADDR
;
391 GAddress_destroy(m_peer
);
393 m_peer
= GAddress_copy(address
);
395 return GSOCK_NOERROR
;
398 GAddress
*GSocket::GetLocal()
400 GAddress
*address
= NULL
;
406 /* try to get it from the m_local var first */
408 return GAddress_copy(m_local
);
410 /* else, if the socket is initialized, try getsockname */
411 if (m_endpoint
== kOTInvalidEndpointRef
)
413 m_error
= GSOCK_INVSOCK
;
418 /* we do not support multihoming with this code at the moment
419 OTGetProtAddress will have to be used then - but we don't have a handy
420 method to use right now
423 InetInterfaceInfo info
;
424 OTInetGetInterfaceInfo(&info
, kDefaultInetInterface
);
425 loc
.fHost
= info
.fAddress
;
427 loc
.fAddressType
= AF_INET
;
430 /* got a valid address from getsockname, create a GAddress object */
431 address
= GAddress_new();
434 m_error
= GSOCK_MEMERR
;
438 err
= _GAddress_translate_from(address
, &loc
);
439 if (err
!= GSOCK_NOERROR
)
441 GAddress_destroy(address
);
449 GAddress
*GSocket::GetPeer()
453 /* try to get it from the m_peer var */
455 return GAddress_copy(m_peer
);
460 /* Server specific parts */
462 /* GSocket_SetServer:
463 * Sets up this socket as a server. The local address must have been
464 * set with GSocket_SetLocal() before GSocket_SetServer() is called.
465 * Returns GSOCK_NOERROR on success, one of the following otherwise:
468 * GSOCK_INVSOCK - the socket is in use.
469 * GSOCK_INVADDR - the local address has not been set.
470 * GSOCK_IOERR - low-level error.
472 GSocketError
GSocket::SetServer()
476 /* must not be in use */
477 if (m_endpoint
!= kOTInvalidEndpointRef
)
479 m_error
= GSOCK_INVSOCK
;
480 return GSOCK_INVSOCK
;
483 /* the local addr must have been set */
486 m_error
= GSOCK_INVADDR
;
487 return GSOCK_INVADDR
;
490 /* Initialize all fields */
497 /* Create the socket */
498 m_endpoint
= socket(m_local
->m_realfamily
, SOCK_STREAM
, 0);
499 socket_set_ref( m_endpoint
, (unsigned long) &gMacNetEvents
, (unsigned long) this ) ;
500 if (m_endpoint
== kOTInvalidEndpointRef
)
502 m_error
= GSOCK_IOERR
;
506 ioctl(m_endpoint
, FIONBIO
, &arg
);
509 /* Bind to the local address,
510 * retrieve the actual address bound,
511 * and listen up to 5 connections.
513 if ((bind(m_endpoint
, m_local
->m_addr
, m_local
->m_len
) != 0) ||
514 (getsockname(m_endpoint
,
516 (SOCKLEN_T
*) &m_local
->m_len
) != 0) ||
517 (listen(m_endpoint
, 5) != 0))
521 m_error
= GSOCK_IOERR
;
525 return GSOCK_NOERROR
;
528 /* GSocket_WaitConnection:
529 * Waits for an incoming client connection. Returns a pointer to
530 * a GSocket object, or NULL if there was an error, in which case
531 * the last error field will be updated for the calling GSocket.
533 * Error codes (set in the calling GSocket)
534 * GSOCK_INVSOCK - the socket is not valid or not a server.
535 * GSOCK_TIMEDOUT - timeout, no incoming connections.
536 * GSOCK_WOULDBLOCK - the call would block and the socket is nonblocking.
537 * GSOCK_MEMERR - couldn't allocate memory.
538 * GSOCK_IOERR - low-level error.
540 GSocket
*GSocket::WaitConnection()
542 GSocket
*connection
= NULL
;
546 /* Reenable CONNECTION events */
547 m_detected
&= ~GSOCK_CONNECTION_FLAG
;
549 /* If the socket has already been created, we exit immediately */
550 if (m_endpoint
== kOTInvalidEndpointRef
|| !m_server
)
552 m_error
= GSOCK_INVSOCK
;
556 /* Create a GSocket object for the new connection */
557 connection
= GSocket_new();
561 m_error
= GSOCK_MEMERR
;
565 /* Wait for a connection (with timeout) */
566 if (Input_Timeout() == GSOCK_TIMEDOUT
)
569 /* m_error set by _GSocket_Input_Timeout */
575 connection
->m_endpoint
= accept(m_endpoint
, &from
, (SOCKLEN_T
*) &fromlen
);
578 if (connection
->m_endpoint
== kOTInvalidEndpointRef
)
580 if (errno
== EWOULDBLOCK
)
581 m_error
= GSOCK_WOULDBLOCK
;
583 m_error
= GSOCK_IOERR
;
589 /* Initialize all fields */
590 connection
->m_server
= false;
591 connection
->m_stream
= true;
592 connection
->m_oriented
= true;
594 /* Setup the peer address field */
595 connection
->m_peer
= GAddress_new();
596 if (!connection
->m_peer
)
599 m_error
= GSOCK_MEMERR
;
604 err
= _GAddress_translate_from(connection
->m_peer
, &from
, fromlen
);
605 if (err
!= GSOCK_NOERROR
)
607 GAddress_destroy(connection
->m_peer
);
608 GSocket_destroy(connection
);
613 ioctl(connection
->m_endpoint
, FIONBIO
, &arg
);
615 connection
->Enable_Events();
620 /* Datagram sockets */
622 /* GSocket_SetNonOriented:
623 * Sets up this socket as a non-connection oriented (datagram) socket.
624 * Before using this function, the local address must have been set
625 * with GSocket_SetLocal(), or the call will fail. Returns GSOCK_NOERROR
626 * on success, or one of the following otherwise.
629 * GSOCK_INVSOCK - the socket is in use.
630 * GSOCK_INVADDR - the local address has not been set.
631 * GSOCK_IOERR - low-level error.
633 GSocketError
GSocket::SetNonOriented()
637 if (m_endpoint
!= kOTInvalidEndpointRef
)
639 m_error
= GSOCK_INVSOCK
;
640 return GSOCK_INVSOCK
;
645 m_error
= GSOCK_INVADDR
;
646 return GSOCK_INVADDR
;
649 /* Initialize all fields */
654 /* Create the socket */
658 m_endpoint
= socket(m_local
->m_realfamily
, SOCK_DGRAM
, 0);
659 socket_set_ref( m_endpoint
, (unsigned long) &gMacNetEvents
, (unsigned long) this ) ;
661 if (m_endpoint
== kOTInvalidEndpointRef
)
663 m_error
= GSOCK_IOERR
;
669 ioctl(m_endpoint
, FIONBIO
, &arg
);
673 /* Bind to the local address,
674 * and retrieve the actual address bound.
678 if ((bind(m_endpoint
, m_local
->m_addr
, m_local
->m_len
) != 0) ||
679 (getsockname(m_endpoint
,
681 (SOCKLEN_T
*) &m_local
->m_len
) != 0))
685 m_error
= GSOCK_IOERR
;
689 return GSOCK_NOERROR
;
692 /* Client specific parts */
695 * For stream (connection oriented) sockets, GSocket_Connect() tries
696 * to establish a client connection to a server using the peer address
697 * as established with GSocket_SetPeer(). Returns GSOCK_NOERROR if the
698 * connection has been successfully established, or one of the error
699 * codes listed below. Note that for nonblocking sockets, a return
700 * value of GSOCK_WOULDBLOCK doesn't mean a failure. The connection
701 * request can be completed later; you should use GSocket_Select()
702 * to poll for GSOCK_CONNECTION | GSOCK_LOST, or wait for the
703 * corresponding asynchronous events.
705 * For datagram (non connection oriented) sockets, GSocket_Connect()
706 * just sets the peer address established with GSocket_SetPeer() as
707 * default destination.
710 * GSOCK_INVSOCK - the socket is in use or not valid.
711 * GSOCK_INVADDR - the peer address has not been established.
712 * GSOCK_TIMEDOUT - timeout, the connection failed.
713 * GSOCK_WOULDBLOCK - connection in progress (nonblocking sockets only)
714 * GSOCK_MEMERR - couldn't allocate memory.
715 * GSOCK_IOERR - low-level error.
717 GSocketError
GSocket::Connect(GSocketStream stream
)
721 OSStatus err
= kOTNoError
;
726 /* Enable CONNECTION events (needed for nonblocking connections) */
727 m_detected
&= ~GSOCK_CONNECTION_FLAG
;
729 if (m_endpoint
!= kOTInvalidEndpointRef
)
731 m_error
= GSOCK_INVSOCK
;
732 return GSOCK_INVSOCK
;
737 m_error
= GSOCK_INVADDR
;
738 return GSOCK_INVADDR
;
741 /* Streamed or dgram socket? */
742 m_stream
= (stream
== GSOCK_STREAMED
);
746 /* Create the socket */
749 OTOpenEndpointInContext( OTCreateConfiguration( kTCPName
) , 0 , &info
, &err
, NULL
) ;
752 OTOpenEndpoint( OTCreateConfiguration( kTCPName
) , 0 , &info
, &err
) ;
754 if ( m_endpoint
== kOTInvalidEndpointRef
|| err
!= kOTNoError
)
756 m_endpoint
= kOTInvalidEndpointRef
;
757 m_error
= GSOCK_IOERR
;
760 err
= OTBind( m_endpoint
, nil
, nil
) ;
761 if ( err
!= kOTNoError
)
765 SetDefaultEndpointModes( m_endpoint
, this ) ;
768 ioctl(m_endpoint
, FIONBIO
, &arg
);
772 _GAddress_translate_to( m_peer
, &addr
) ;
773 memset( &peer
, 0 , sizeof( TCall
) ) ;
774 peer
.addr
.len
= sizeof( InetAddress
) ;
775 peer
.addr
.buf
= (unsigned char*) &addr
;
776 err
= OTConnect( m_endpoint
, &peer
, nil
) ;
779 /* If connect failed with EINPROGRESS and the GSocket object
780 * is in blocking mode, we select() for the specified timeout
781 * checking for writability to see if the connection request
785 if ((err
== kOTNoDataErr
) && (!m_non_blocking
))
787 if (Output_Timeout() == GSOCK_TIMEDOUT
)
789 OTSndOrderlyDisconnect( m_endpoint
) ;
790 m_endpoint
= kOTInvalidEndpointRef
;
791 /* m_error is set in _GSocket_Output_Timeout */
792 return GSOCK_TIMEDOUT
;
798 SOCKLEN_T len = sizeof(error);
800 getsockopt(m_endpoint, SOL_SOCKET, SO_ERROR, (void*) &error, &len);
804 return GSOCK_NOERROR
;
808 /* If connect failed with EINPROGRESS and the GSocket object
809 * is set to nonblocking, we set m_error to GSOCK_WOULDBLOCK
810 * (and return GSOCK_WOULDBLOCK) but we don't close the socket;
811 * this way if the connection completes, a GSOCK_CONNECTION
812 * event will be generated, if enabled.
814 if ((err
== kOTNoDataErr
) && (m_non_blocking
))
816 m_error
= GSOCK_WOULDBLOCK
;
817 return GSOCK_WOULDBLOCK
;
820 /* If connect failed with an error other than EINPROGRESS,
821 * then the call to GSocket_Connect has failed.
823 OTSndOrderlyDisconnect( m_endpoint
) ;
825 m_endpoint
= kOTInvalidEndpointRef
;
826 m_error
= GSOCK_IOERR
;
829 // OTInetEventHandler(this, T_CONNECT , kOTNoError , NULL ) ;
830 return GSOCK_NOERROR
;
835 /* Like recv(), send(), ... */
836 int GSocket::Read(char *buffer
, int size
)
842 /* Reenable INPUT events */
843 m_detected
&= ~GSOCK_INPUT_FLAG
;
845 if (m_endpoint
== kOTInvalidEndpointRef
|| m_server
)
847 m_error
= GSOCK_INVSOCK
;
851 /* If the socket is blocking, wait for data (with a timeout) */
852 if (Input_Timeout() == GSOCK_TIMEDOUT
)
857 ret
= Recv_Stream(buffer
, size
);
859 ret
= Recv_Dgram(buffer
, size
);
863 if (errno
== EWOULDBLOCK
)
864 m_error
= GSOCK_WOULDBLOCK
;
866 m_error
= GSOCK_IOERR
;
872 int GSocket::Write(const char *buffer
, int size
)
878 if (m_endpoint
== kOTInvalidEndpointRef
|| m_server
)
880 m_error
= GSOCK_INVSOCK
;
884 /* If the socket is blocking, wait for writability (with a timeout) */
885 if (Output_Timeout() == GSOCK_TIMEDOUT
)
890 ret
= Send_Stream(buffer
, size
);
892 ret
= Send_Dgram(buffer
, size
);
896 if (errno
== EWOULDBLOCK
)
897 m_error
= GSOCK_WOULDBLOCK
;
899 m_error
= GSOCK_IOERR
;
901 /* Only reenable OUTPUT events after an error (just like WSAAsyncSelect
902 * in MSW). Once the first OUTPUT event is received, users can assume
903 * that the socket is writable until a read operation fails. Only then
904 * will further OUTPUT events be posted.
906 m_detected
&= ~GSOCK_OUTPUT_FLAG
;
914 * Polls the socket to determine its status. This function will
915 * check for the events specified in the 'flags' parameter, and
916 * it will return a mask indicating which operations can be
917 * performed. This function won't block, regardless of the
918 * mode (blocking | nonblocking) of the socket.
920 GSocketEventFlags
GSocket::Select(GSocketEventFlags flags
)
923 wxMacProcessNotifierEvents() ;
925 state = OTGetEndpointState(m_endpoint);
927 if ( ( flags & GSOCK_INPUT_FLAG ) && ! ( m_detected & GSOCK_INPUT_FLAG ) )
930 OTCountDataBytes( m_endpoint , &sz ) ;
931 if ( state == T_INCON || sz > 0 )
933 m_detected |= GSOCK_INPUT_FLAG ;
934 (m_cbacks[GSOCK_INPUT])(this, GSOCK_INPUT, m_data[GSOCK_INPUT]);
937 if ( ( flags & GSOCK_INPUT_FLAG ) && ! ( m_detected & GSOCK_OUTPUT_FLAG ) )
939 if ( state == T_DATAXFER || state == T_INREL )
941 m_detected |=GSOCK_OUTPUT_FLAG ;
942 (m_cbacks[GSOCK_OUTPUT])(this, GSOCK_OUTPUT, m_data[GSOCK_OUTPUT]);
946 return ( flags
& m_detected
) ;
951 /* GSocket_SetNonBlocking:
952 * Sets the socket to non-blocking mode. All IO calls will return
955 void GSocket::SetNonBlocking(bool non_block
)
959 m_non_blocking
= non_block
;
962 /* GSocket_SetTimeout:
963 * Sets the timeout for blocking calls. Time is expressed in
966 void GSocket::SetTimeout(unsigned long millisec
)
970 // this is usually set too high and we have not yet been able to detect a closed
971 // stream, thus we leave the 10 sec timeout
972 // m_timeout = millisec;
976 * Returns the last error which occurred for this socket. Note that successful
977 * operations do not clear this back to GSOCK_NOERROR, so use it only
980 GSocketError WXDLLIMPEXP_NET
GSocket::GetError()
990 * There is data to be read in the input buffer. If, after a read
991 * operation, there is still data available, the callback function will
994 * The socket is available for writing. That is, the next write call
995 * won't block. This event is generated only once, when the connection is
996 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
997 * when the output buffer empties again. This means that the app should
998 * assume that it can write since the first OUTPUT event, and no more
999 * OUTPUT events will be generated unless an error occurs.
1001 * Connection successfully established, for client sockets, or incoming
1002 * client connection, for server sockets. Wait for this event (also watch
1003 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
1005 * The connection is lost (or a connection request failed); this could
1006 * be due to a failure, or due to the peer closing it gracefully.
1009 /* GSocket_SetCallback:
1010 * Enables the callbacks specified by 'flags'. Note that 'flags'
1011 * may be a combination of flags OR'ed toghether, so the same
1012 * callback function can be made to accept different events.
1013 * The callback function must have the following prototype:
1015 * void function(GSocket *socket, GSocketEvent event, char *cdata)
1017 void GSocket::SetCallback(GSocketEventFlags flags
,
1018 GSocketCallback callback
, char *cdata
)
1024 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1026 if ((flags
& (1 << count
)) != 0)
1028 m_cbacks
[count
] = callback
;
1029 m_data
[count
] = cdata
;
1034 /* GSocket_UnsetCallback:
1035 * Disables all callbacks specified by 'flags', which may be a
1036 * combination of flags OR'ed toghether.
1038 void GSocket::UnsetCallback(GSocketEventFlags flags
)
1044 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1046 if ((flags
& (1 << count
)) != 0)
1048 m_cbacks
[count
] = NULL
;
1049 m_data
[count
] = NULL
;
1055 #define CALL_CALLBACK(socket, event) { \
1056 _GSocket_Disable(socket, event); \
1057 if (socket->m_cbacks[event]) \
1058 socket->m_cbacks[event](socket, event, socket->m_data[event]); \
1061 int GSocket::Recv_Stream(char *buffer
, int size
)
1065 OTByteCount sz
= 0 ;
1067 OTCountDataBytes( m_endpoint
, &sz
) ;
1068 if ( size
> (int)sz
)
1070 res
= OTRcv( m_endpoint
, buffer
, size
, &flags
) ;
1076 // we simulate another read event if there are still bytes
1077 if ( m_takesEvents
)
1079 OTByteCount sz
= 0 ;
1080 OTCountDataBytes( m_endpoint
, &sz
) ;
1083 m_detected
|= GSOCK_INPUT_FLAG
;
1084 (m_cbacks
[GSOCK_INPUT
])(this, GSOCK_INPUT
, m_data
[GSOCK_INPUT
]);
1090 int GSocket::Recv_Dgram(char *buffer
, int size
)
1095 struct sockaddr from
;
1096 SOCKLEN_T fromlen
= sizeof(from
);
1099 fromlen
= sizeof(from
);
1101 ret
= recvfrom(m_endpoint
, buffer
, size
, 0, &from
, (SOCKLEN_T
*) &fromlen
);
1106 /* Translate a system address into a GSocket address */
1109 m_peer
= GAddress_new();
1112 m_error
= GSOCK_MEMERR
;
1116 err
= _GAddress_translate_from(m_peer
, &from
, fromlen
);
1117 if (err
!= GSOCK_NOERROR
)
1119 GAddress_destroy(m_peer
);
1128 int GSocket::Send_Stream(const char *buffer
, int size
)
1133 res
= OTSnd( m_endpoint
, (void*) buffer
, size
, flags
) ;
1137 int GSocket::Send_Dgram(const char *buffer
, int size
)
1142 struct sockaddr
*addr
;
1148 m_error
= GSOCK_INVADDR
;
1152 err
= _GAddress_translate_to(m_peer
, &addr
, &len
);
1153 if (err
!= GSOCK_NOERROR
)
1159 ret
= sendto(m_endpoint
, buffer
, size
, 0, addr
, len
);
1161 /* Frees memory allocated from _GAddress_translate_to */
1167 /* Compatibility functions for GSocket */
1168 GSocket
*GSocket_new(void)
1170 GSocket
*newsocket
= new GSocket();
1171 if(newsocket
->IsOk())
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() )
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() )
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
= htonl(hostaddr
) ;
1332 return GSOCK_NOERROR
;
1335 struct service_entry
1338 unsigned short port
;
1339 const char * protocol
;
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() )
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 ntohl(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()
1424 if ( m_takesEvents
)
1429 m_takesEvents
= true ;
1430 state
= OTGetEndpointState(m_endpoint
);
1433 OTByteCount sz
= 0 ;
1434 OTCountDataBytes( m_endpoint
, &sz
) ;
1435 if ( state
== T_INCON
|| sz
> 0 )
1437 m_detected
|= GSOCK_INPUT_FLAG
;
1438 (m_cbacks
[GSOCK_INPUT
])(this, GSOCK_INPUT
, m_data
[GSOCK_INPUT
]);
1442 if ( state
== T_DATAXFER
|| state
== T_INREL
)
1444 m_detected
|=GSOCK_OUTPUT_FLAG
;
1445 (m_cbacks
[GSOCK_OUTPUT
])(this, GSOCK_OUTPUT
, m_data
[GSOCK_OUTPUT
]);
1451 void GSocket::Disable_Events()
1453 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()
1462 if ( !m_non_blocking
)
1464 UnsignedWide now
, start
;
1465 bool formerTakesEvents
= m_takesEvents
;
1466 Microseconds(&start
);
1468 m_takesEvents
= false ;
1470 while( (now
.hi
* 4294967296.0 + now
.lo
) - (start
.hi
* 4294967296.0 + start
.lo
) < m_timeout
* 1000.0 )
1473 OTByteCount sz
= 0 ;
1474 state
= OTGetEndpointState(m_endpoint
);
1476 OTCountDataBytes( m_endpoint
, &sz
) ;
1477 if ( state
== T_INCON
|| sz
> 0 )
1479 m_takesEvents
= formerTakesEvents
;
1480 return GSOCK_NOERROR
;
1484 m_takesEvents
= formerTakesEvents
;
1485 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()
1497 if ( !m_non_blocking
)
1499 UnsignedWide now
, start
;
1500 bool formerTakesEvents
= m_takesEvents
;
1501 Microseconds(&start
);
1503 m_takesEvents
= false ;
1505 while( (now
.hi
* 4294967296.0 + now
.lo
) - (start
.hi
* 4294967296.0 + start
.lo
) < m_timeout
* 1000.0 )
1508 state
= OTGetEndpointState(m_endpoint
);
1510 if ( state
== T_DATAXFER
|| state
== T_INREL
)
1512 m_takesEvents
= formerTakesEvents
;
1513 return GSOCK_NOERROR
;
1517 m_takesEvents
= formerTakesEvents
;
1518 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
)
1546 GSocket
*socket
= (GSocket
*) d
;
1551 OTEventCode ev
= (OTEventCode
) e
;
1553 GSocketEvent event2
;
1554 GSocketCallback cback
;
1556 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__) */