]> git.saurik.com Git - wxWidgets.git/blame - src/mac/carbon/gsocket.cpp
cleanup - reformat
[wxWidgets.git] / src / mac / carbon / gsocket.cpp
CommitLineData
e6f2ec14 1/* -------------------------------------------------------------------------
99d80019
JS
2 * Project: GSocket (Generic Socket) for WX
3 * Name: gsocket.cpp
4 * Copyright: (c) Guilhem Lavaux
5 * Licence: wxWindows Licence
6 * Authors: Guilhem Lavaux,
7 * Guillermo Rodriguez Garcia <guille@iies.es> (maintainer)
8 * Stefan CSomor
9 * Purpose: GSocket main mac file
10 * CVSID: $Id$
e6f2ec14
DE
11 * -------------------------------------------------------------------------
12 */
13
14/*
15 * PLEASE don't put C++ comments here - this is a C source file.
16 */
17
18#ifndef __GSOCKET_STANDALONE__
19#include "wx/setup.h"
20#include "wx/platform.h"
21#endif
22
23#if wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__)
24
25#ifdef __DARWIN__
902725ee 26 #include <CoreServices/CoreServices.h>
e6f2ec14 27#else
902725ee
WS
28 #include <MacHeaders.c>
29 #define OTUNIXERRORS 1
30 #include <OpenTransport.h>
31 #include <OpenTransportProviders.h>
32 #include <OpenTptInternet.h>
e6f2ec14
DE
33#endif
34#if TARGET_CARBON && !defined(OTAssert)
902725ee 35 #define OTAssert( str , cond ) /* does not exists in Carbon */
e6f2ec14
DE
36#endif
37
38#include <assert.h>
39#include <errno.h>
40#include <string.h>
41#include <unistd.h>
42#include <stdio.h>
43#include <stdlib.h>
44#include <stddef.h>
45#include <ctype.h>
46#include <utime.h>
47
48/*
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.
51 */
52#ifndef INADDR_BROADCAST
53#define INADDR_BROADCAST 0xFFFFFFFFUL
54#endif
55#ifndef INADDR_NONE
56#define INADDR_NONE INADDR_BROADCAST
57#endif
58#ifndef INADDR_ANY
59#define INADDR_ANY 0x0UL
60#endif
61#ifndef __GSOCKET_STANDALONE__
62
902725ee
WS
63 #include "wx/mac/macnotfy.h"
64 #include "wx/mac/gsockmac.h"
65 #include "wx/gsocket.h"
e6f2ec14
DE
66
67#else
68
902725ee
WS
69 #include "gsockmac.h"
70 #include "gsocket.h"
e6f2ec14
DE
71
72#endif /* __GSOCKET_STANDALONE__ */
73
74#ifndef ntohl
902725ee
WS
75 #define ntohl(x) (x)
76 #define ntohs(x) (x)
77 #define htonl(x) (x)
78 #define htons(x) (x)
e6f2ec14
DE
79#endif
80
81void wxCYield() ;
82#ifdef __WXDEBUG__
83#define qDebug 1
84#define qDebug2 1
85extern pascal void OTDebugStr(const char* str);
86#endif
87#ifndef __DARWIN__
88 #include <OTDebug.h>
89#endif
90InetSvcRef gInetSvcRef = 0 ;
91int gOTInited = 0 ;
92OTNotifyUPP gOTNotifierUPP = NULL ;
93
94OSStatus DoNegotiateIPReuseAddrOption(EndpointRef ep, Boolean enableReuseIPMode);
95
96/* Input: ep - endpointref on which to negotiate the option
902725ee 97 enableReuseIPMode - desired option setting - true/false
e6f2ec14 98 Return: kOTNoError indicates that the option was successfully negotiated
902725ee
WS
99 OSStatus is an error if < 0, otherwise, the status field is
100 returned and is > 0.
101
102 IMPORTANT NOTE: The endpoint is assumed to be in synchronous more, otherwise
103 this code will not function as desired
e6f2ec14
DE
104*/
105
106
107OSStatus DoNegotiateIPReuseAddrOption(EndpointRef ep, Boolean enableReuseIPMode)
108
109{
902725ee
WS
110 UInt8 buf[kOTFourByteOptionSize]; // define buffer for fourByte Option size
111 TOption* opt; // option ptr to make items easier to access
112 TOptMgmt req;
113 TOptMgmt ret;
114 OSStatus err;
e6f2ec14 115
902725ee
WS
116 if (!OTIsSynchronous(ep))
117 {
118 return (-1);
119 }
120 opt = (TOption*)buf; // set option ptr to buffer
121 req.opt.buf = buf;
122 req.opt.len = sizeof(buf);
123 req.flags = T_NEGOTIATE; // negotiate for option
e6f2ec14 124
902725ee
WS
125 ret.opt.buf = buf;
126 ret.opt.maxlen = kOTFourByteOptionSize;
127
128 opt->level = INET_IP; // dealing with an IP Level function
e6f2ec14 129#ifdef __DARWIN__
902725ee 130 opt->name = kIP_REUSEADDR;
e6f2ec14 131#else
902725ee 132 opt->name = IP_REUSEADDR;
e6f2ec14 133#endif
902725ee
WS
134 opt->len = kOTFourByteOptionSize;
135 opt->status = 0;
136 *(UInt32*)opt->value = enableReuseIPMode; // set the desired option level, true or false
137
138 err = OTOptionManagement(ep, &req, &ret);
139
140 // if no error then return the option status value
141 if (err == kOTNoError)
142 {
143 if (opt->status != T_SUCCESS)
144 err = opt->status;
145 else
146 err = kOTNoError;
147 }
148
149 return err;
e6f2ec14
DE
150}
151
152
153pascal void OTInetEventHandler(void*s, OTEventCode event, OTResult, void *cookie) ;
154pascal void OTInetEventHandler(void*s, OTEventCode event, OTResult result, void *cookie)
155{
902725ee
WS
156 int wakeUp = true ;
157 GSocket* sock = (GSocket*) s ;
e6f2ec14 158
902725ee
WS
159 if ( event == kOTSyncIdleEvent )
160 {
161 return ;
162 }
e6f2ec14 163
902725ee
WS
164 if ( s )
165 {
166 wxMacAddEvent( sock->m_mac_events , _GSocket_Internal_Proc , event , s , wakeUp ) ;
167 }
168
169 return;
e6f2ec14
DE
170}
171
172static void SetDefaultEndpointModes(EndpointRef ep , void *data )
902725ee
WS
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.
e6f2ec14 177{
902725ee
WS
178 OSStatus junk = kOTNoError ;
179 OTAssert ("SetDefaultEndpointModes:invalid ref", ep != kOTInvalidEndpointRef ) ;
180 junk = OTSetAsynchronous(ep);
181 OTAssert("SetDefaultEndpointModes: Could not set asynchronous", junk == noErr);
e6f2ec14 182/*
902725ee
WS
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);
e6f2ec14 189*/
902725ee
WS
190 junk = OTInstallNotifier(ep, gOTNotifierUPP, data);
191 OTAssert("SetDefaultEndpointModes: Could not install notifier", junk == noErr);
e6f2ec14 192/*
902725ee
WS
193 junk = OTUseSyncIdleEvents(ep, true);
194 OTAssert("SetDefaultEndpointModes: Could not use sync idle events", junk == noErr);
e6f2ec14
DE
195*/
196}
197
198/* Global initialisers */
199
3e1400ac 200void GSocket_SetGUIFunctions(GSocketGUIFunctionsTable *table)
e6f2ec14
DE
201{
202 // do nothing, wxMac doesn't have wxBase-GUI separation yet
203}
204
205int GSocket_Init()
206{
948c96ef 207 return 1;
e6f2ec14
DE
208}
209
948c96ef
DE
210bool GSocket_Verify_Inited() ;
211bool GSocket_Verify_Inited()
e6f2ec14
DE
212{
213 OSStatus err ;
214#if TARGET_CARBON
215 // Marc Newsam: added the clientcontext variable
216 // however, documentation is unclear how this works
217 OTClientContextPtr clientcontext;
218
219 if ( gInetSvcRef )
948c96ef 220 return true ;
e6f2ec14
DE
221
222 InitOpenTransportInContext(kInitOTForApplicationMask, &clientcontext);
223 gOTInited = 1 ;
224 gInetSvcRef = OTOpenInternetServicesInContext(kDefaultInternetServicesPath,
902725ee
WS
225 NULL, &err, clientcontext);
226#else
e6f2ec14 227 if ( gInetSvcRef )
948c96ef 228 return true ;
902725ee 229
e6f2ec14
DE
230 InitOpenTransport() ;
231 gOTInited = 1 ;
232 gInetSvcRef = OTOpenInternetServices(kDefaultInternetServicesPath, NULL, &err);
233#endif
234 if ( gInetSvcRef == NULL || err != kOTNoError )
235 {
902725ee
WS
236 OTAssert("Could not open Inet Services", err == noErr);
237 return false ;
e6f2ec14
DE
238 }
239 gOTNotifierUPP = NewOTNotifyUPP( OTInetEventHandler ) ;
948c96ef 240 return true ;
e6f2ec14
DE
241}
242
243void GSocket_Cleanup()
244{
245 if ( gOTInited != 0 )
246 {
902725ee
WS
247 if ( gInetSvcRef != NULL )
248 OTCloseProvider( gInetSvcRef );
e6f2ec14
DE
249 #if TARGET_CARBON
250 CloseOpenTransportInContext( NULL ) ;
251 #else
252 CloseOpenTransport() ;
253 #endif
254 if ( gOTNotifierUPP )
255 DisposeOTNotifyUPP( gOTNotifierUPP ) ;
256 }
257}
258
259/* Constructors / Destructors for GSocket */
260
c5602b4a 261GSocket::GSocket()
e6f2ec14 262{
e6f2ec14 263 int i;
e6f2ec14 264
948c96ef 265 m_ok = GSocket_Verify_Inited();
e6f2ec14 266
c5602b4a 267 m_endpoint = NULL ;
e6f2ec14
DE
268 for (i=0;i<GSOCK_MAX_EVENT;i++)
269 {
c5602b4a 270 m_cbacks[i] = NULL;
e6f2ec14 271 }
c5602b4a
DE
272 m_detected = 0;
273 m_local = NULL;
274 m_peer = NULL;
275 m_error = GSOCK_NOERROR;
948c96ef
DE
276 m_server = false;
277 m_stream = true;
278 m_non_blocking = false;
c5602b4a 279 m_timeout = 1*1000;
e6f2ec14 280 /* 10 sec * 1000 millisec */
902725ee
WS
281 m_takesEvents = true ;
282 m_mac_events = wxMacGetNotifierTable() ;
e6f2ec14
DE
283}
284
c5602b4a 285GSocket::~GSocket()
e6f2ec14 286{
902725ee 287 assert(this);
e6f2ec14 288
902725ee
WS
289 /* Check that the socket is really shutdowned */
290 if (m_endpoint != kOTInvalidEndpointRef)
291 Shutdown();
e6f2ec14
DE
292
293
902725ee
WS
294 /* Destroy private addresses */
295 if (m_local)
296 GAddress_destroy(m_local);
e6f2ec14 297
902725ee
WS
298 if (m_peer)
299 GAddress_destroy(m_peer);
e6f2ec14
DE
300}
301
302/* GSocket_Shutdown:
303 * Disallow further read/write operations on this socket, close
304 * the fd and disable all callbacks.
305 */
c5602b4a 306void GSocket::Shutdown()
e6f2ec14 307{
902725ee
WS
308 OSStatus err ;
309 int evt;
e6f2ec14 310
902725ee 311 assert(this);
e6f2ec14 312
902725ee
WS
313 /* If socket has been created, shutdown it */
314 if (m_endpoint != kOTInvalidEndpointRef )
315 {
316 err = OTSndOrderlyDisconnect( m_endpoint ) ;
317 if ( err != kOTNoError )
318 {
319 }
320
321 err = OTRcvOrderlyDisconnect( m_endpoint ) ;
322 err = OTUnbind( m_endpoint ) ;
323 err = OTCloseProvider( m_endpoint ) ;
324 m_endpoint = kOTInvalidEndpointRef ;
325 }
e6f2ec14 326
902725ee
WS
327 /* Disable GUI callbacks */
328 for (evt = 0; evt < GSOCK_MAX_EVENT; evt++)
329 m_cbacks[evt] = NULL;
e6f2ec14 330
902725ee
WS
331 m_detected = 0;
332 Disable_Events();
333 wxMacRemoveAllNotifiersForData( wxMacGetNotifierTable() , this ) ;
e6f2ec14
DE
334}
335
336
337/* Address handling */
338
339/* GSocket_SetLocal:
340 * GSocket_GetLocal:
341 * GSocket_SetPeer:
342 * GSocket_GetPeer:
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.
348 *
349 * Error codes:
350 * GSOCK_INVSOCK - the socket is not valid.
351 * GSOCK_INVADDR - the address is not valid.
352 */
c5602b4a 353GSocketError GSocket::SetLocal(GAddress *address)
e6f2ec14 354{
902725ee 355 assert(this);
e6f2ec14 356
902725ee
WS
357 /* the socket must be initialized, or it must be a server */
358 if ((m_endpoint != kOTInvalidEndpointRef && !m_server))
359 {
360 m_error = GSOCK_INVSOCK;
361 return GSOCK_INVSOCK;
362 }
e6f2ec14 363
902725ee
WS
364 /* check address */
365 if (address == NULL || address->m_family == GSOCK_NOFAMILY)
366 {
367 m_error = GSOCK_INVADDR;
368 return GSOCK_INVADDR;
369 }
e6f2ec14 370
902725ee
WS
371 if (m_local)
372 GAddress_destroy(m_local);
e6f2ec14 373
902725ee 374 m_local = GAddress_copy(address);
e6f2ec14 375
902725ee 376 return GSOCK_NOERROR;
e6f2ec14
DE
377}
378
c5602b4a 379GSocketError GSocket::SetPeer(GAddress *address)
e6f2ec14 380{
902725ee 381 assert(this);
e6f2ec14 382
902725ee
WS
383 /* check address */
384 if (address == NULL || address->m_family == GSOCK_NOFAMILY)
385 {
386 m_error = GSOCK_INVADDR;
387 return GSOCK_INVADDR;
388 }
e6f2ec14 389
902725ee
WS
390 if (m_peer)
391 GAddress_destroy(m_peer);
e6f2ec14 392
902725ee 393 m_peer = GAddress_copy(address);
e6f2ec14 394
902725ee 395 return GSOCK_NOERROR;
e6f2ec14
DE
396}
397
c5602b4a 398GAddress *GSocket::GetLocal()
e6f2ec14 399{
902725ee
WS
400 GAddress *address = NULL ;
401 GSocketError err;
402 InetAddress loc ;
e6f2ec14 403
902725ee 404 assert(this);
e6f2ec14 405
902725ee
WS
406 /* try to get it from the m_local var first */
407 if (m_local)
408 return GAddress_copy(m_local);
409
410 /* else, if the socket is initialized, try getsockname */
411 if (m_endpoint == kOTInvalidEndpointRef)
412 {
413 m_error = GSOCK_INVSOCK;
414 return NULL;
415 }
e6f2ec14 416
e6f2ec14 417
e6f2ec14 418/* we do not support multihoming with this code at the moment
902725ee 419 OTGetProtAddress will have to be used then - but we don't have a handy
e6f2ec14
DE
420 method to use right now
421*/
902725ee
WS
422 {
423 InetInterfaceInfo info;
424 OTInetGetInterfaceInfo(&info, kDefaultInetInterface);
425 loc.fHost = info.fAddress ;
426 loc.fPort = 0 ;
427 loc.fAddressType = AF_INET ;
428 }
e6f2ec14 429
902725ee
WS
430 /* got a valid address from getsockname, create a GAddress object */
431 address = GAddress_new();
432 if (address == NULL)
433 {
434 m_error = GSOCK_MEMERR;
435 return NULL;
436 }
e6f2ec14 437
902725ee
WS
438 err = _GAddress_translate_from(address, &loc);
439 if (err != GSOCK_NOERROR)
440 {
441 GAddress_destroy(address);
442 m_error = err;
443 return NULL;
444 }
e6f2ec14 445
902725ee 446 return address;
e6f2ec14
DE
447}
448
c5602b4a 449GAddress *GSocket::GetPeer()
e6f2ec14 450{
902725ee 451 assert(this);
e6f2ec14 452
902725ee
WS
453 /* try to get it from the m_peer var */
454 if (m_peer)
455 return GAddress_copy(m_peer);
e6f2ec14 456
902725ee 457 return NULL;
e6f2ec14
DE
458}
459
460/* Server specific parts */
461
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:
902725ee 466 *
e6f2ec14
DE
467 * Error codes:
468 * GSOCK_INVSOCK - the socket is in use.
469 * GSOCK_INVADDR - the local address has not been set.
902725ee 470 * GSOCK_IOERR - low-level error.
e6f2ec14 471 */
c5602b4a 472GSocketError GSocket::SetServer()
e6f2ec14 473{
c5602b4a 474 assert(this);
e6f2ec14
DE
475
476 /* must not be in use */
c5602b4a 477 if (m_endpoint != kOTInvalidEndpointRef )
e6f2ec14 478 {
c5602b4a 479 m_error = GSOCK_INVSOCK;
e6f2ec14
DE
480 return GSOCK_INVSOCK;
481 }
482
483 /* the local addr must have been set */
c5602b4a 484 if (!m_local)
e6f2ec14 485 {
c5602b4a 486 m_error = GSOCK_INVADDR;
e6f2ec14
DE
487 return GSOCK_INVADDR;
488 }
489
490 /* Initialize all fields */
948c96ef
DE
491 m_stream = true;
492 m_server = true;
493 m_oriented = true;
e6f2ec14
DE
494
495// TODO
496#if 0
497 /* Create the socket */
c5602b4a
DE
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)
e6f2ec14 501 {
c5602b4a 502 m_error = GSOCK_IOERR;
e6f2ec14
DE
503 return GSOCK_IOERR;
504 }
505
c5602b4a
DE
506 ioctl(m_endpoint, FIONBIO, &arg);
507 Enable_Events();
e6f2ec14
DE
508
509 /* Bind to the local address,
510 * retrieve the actual address bound,
511 * and listen up to 5 connections.
512 */
c5602b4a
DE
513 if ((bind(m_endpoint, m_local->m_addr, m_local->m_len) != 0) ||
514 (getsockname(m_endpoint,
515 m_local->m_addr,
9e03e02d 516 (WX_SOCKLEN_T *) &m_local->m_len) != 0) ||
c5602b4a 517 (listen(m_endpoint, 5) != 0))
e6f2ec14 518 {
c5602b4a
DE
519 close(m_endpoint);
520 m_endpoint = -1;
521 m_error = GSOCK_IOERR;
e6f2ec14
DE
522 return GSOCK_IOERR;
523 }
524#endif
525 return GSOCK_NOERROR;
526}
527
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.
532 *
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.
902725ee 538 * GSOCK_IOERR - low-level error.
e6f2ec14 539 */
c5602b4a 540GSocket *GSocket::WaitConnection()
e6f2ec14
DE
541{
542 GSocket *connection = NULL ;
543
c5602b4a 544 assert(this);
e6f2ec14
DE
545
546 /* Reenable CONNECTION events */
c5602b4a 547 m_detected &= ~GSOCK_CONNECTION_FLAG;
e6f2ec14
DE
548
549 /* If the socket has already been created, we exit immediately */
c5602b4a 550 if (m_endpoint == kOTInvalidEndpointRef || !m_server)
e6f2ec14 551 {
c5602b4a 552 m_error = GSOCK_INVSOCK;
e6f2ec14
DE
553 return NULL;
554 }
555
556 /* Create a GSocket object for the new connection */
557 connection = GSocket_new();
558
559 if (!connection)
560 {
c5602b4a 561 m_error = GSOCK_MEMERR;
e6f2ec14
DE
562 return NULL;
563 }
564
565 /* Wait for a connection (with timeout) */
c5602b4a 566 if (Input_Timeout() == GSOCK_TIMEDOUT)
e6f2ec14 567 {
c5602b4a
DE
568 delete connection;
569 /* m_error set by _GSocket_Input_Timeout */
e6f2ec14
DE
570 return NULL;
571 }
572
573// TODO
574#if 0
9e03e02d 575 connection->m_endpoint = accept(m_endpoint, &from, (WX_SOCKLEN_T *) &fromlen);
e6f2ec14
DE
576#endif
577
578 if (connection->m_endpoint == kOTInvalidEndpointRef )
579 {
580 if (errno == EWOULDBLOCK)
c5602b4a 581 m_error = GSOCK_WOULDBLOCK;
e6f2ec14 582 else
c5602b4a 583 m_error = GSOCK_IOERR;
e6f2ec14 584
c5602b4a 585 delete connection;
e6f2ec14
DE
586 return NULL;
587 }
588
589 /* Initialize all fields */
948c96ef
DE
590 connection->m_server = false;
591 connection->m_stream = true;
592 connection->m_oriented = true;
e6f2ec14
DE
593
594 /* Setup the peer address field */
595 connection->m_peer = GAddress_new();
596 if (!connection->m_peer)
597 {
c5602b4a
DE
598 delete connection;
599 m_error = GSOCK_MEMERR;
e6f2ec14
DE
600 return NULL;
601 }
602 // TODO
603 #if 0
604 err = _GAddress_translate_from(connection->m_peer, &from, fromlen);
605 if (err != GSOCK_NOERROR)
606 {
607 GAddress_destroy(connection->m_peer);
608 GSocket_destroy(connection);
c5602b4a 609 m_error = err;
e6f2ec14
DE
610 return NULL;
611 }
612
613 ioctl(connection->m_endpoint, FIONBIO, &arg);
614#endif
c5602b4a 615 connection->Enable_Events();
e6f2ec14
DE
616
617 return connection;
618}
619
620/* Datagram sockets */
621
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.
627 *
628 * Error codes:
629 * GSOCK_INVSOCK - the socket is in use.
630 * GSOCK_INVADDR - the local address has not been set.
631 * GSOCK_IOERR - low-level error.
632 */
c5602b4a 633GSocketError GSocket::SetNonOriented()
e6f2ec14 634{
c5602b4a 635 assert(this);
e6f2ec14 636
c5602b4a 637 if (m_endpoint != kOTInvalidEndpointRef )
e6f2ec14 638 {
c5602b4a 639 m_error = GSOCK_INVSOCK;
e6f2ec14
DE
640 return GSOCK_INVSOCK;
641 }
642
c5602b4a 643 if (!m_local)
e6f2ec14 644 {
c5602b4a 645 m_error = GSOCK_INVADDR;
e6f2ec14
DE
646 return GSOCK_INVADDR;
647 }
648
649 /* Initialize all fields */
948c96ef
DE
650 m_stream = false;
651 m_server = false;
652 m_oriented = false;
e6f2ec14
DE
653
654 /* Create the socket */
902725ee 655
e6f2ec14
DE
656// TODO
657#if 0
c5602b4a
DE
658 m_endpoint = socket(m_local->m_realfamily, SOCK_DGRAM, 0);
659 socket_set_ref( m_endpoint , (unsigned long) &gMacNetEvents , (unsigned long) this ) ;
e6f2ec14 660#endif
c5602b4a 661 if (m_endpoint == kOTInvalidEndpointRef )
e6f2ec14 662 {
c5602b4a 663 m_error = GSOCK_IOERR;
e6f2ec14
DE
664 return GSOCK_IOERR;
665 }
666
667// TODO
668#if 0
c5602b4a 669 ioctl(m_endpoint, FIONBIO, &arg);
e6f2ec14 670#endif
c5602b4a 671 Enable_Events();
e6f2ec14
DE
672
673 /* Bind to the local address,
674 * and retrieve the actual address bound.
675 */
676// TODO
677#if 0
c5602b4a
DE
678 if ((bind(m_endpoint, m_local->m_addr, m_local->m_len) != 0) ||
679 (getsockname(m_endpoint,
680 m_local->m_addr,
9e03e02d 681 (WX_SOCKLEN_T *) &m_local->m_len) != 0))
e6f2ec14 682 {
c5602b4a
DE
683 close(m_endpoint);
684 m_endpoint = -1;
685 m_error = GSOCK_IOERR;
e6f2ec14
DE
686 return GSOCK_IOERR;
687 }
688#endif
689 return GSOCK_NOERROR;
690}
691
692/* Client specific parts */
693
694/* GSocket_Connect:
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
3103e8a9 698 * connection has been successfully established, or one of the error
e6f2ec14
DE
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.
704 *
705 * For datagram (non connection oriented) sockets, GSocket_Connect()
706 * just sets the peer address established with GSocket_SetPeer() as
707 * default destination.
708 *
709 * Error codes:
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.
902725ee 715 * GSOCK_IOERR - low-level error.
e6f2ec14 716 */
c5602b4a 717GSocketError GSocket::Connect(GSocketStream stream)
e6f2ec14
DE
718{
719 InetAddress addr ;
3dee36ae
WS
720 TEndpointInfo info;
721 OSStatus err = kOTNoError;
e6f2ec14
DE
722 TCall peer ;
723
c5602b4a 724 assert(this);
e6f2ec14
DE
725
726 /* Enable CONNECTION events (needed for nonblocking connections) */
c5602b4a 727 m_detected &= ~GSOCK_CONNECTION_FLAG;
e6f2ec14 728
c5602b4a 729 if (m_endpoint != kOTInvalidEndpointRef )
e6f2ec14 730 {
c5602b4a 731 m_error = GSOCK_INVSOCK;
e6f2ec14
DE
732 return GSOCK_INVSOCK;
733 }
734
c5602b4a 735 if (!m_peer)
e6f2ec14 736 {
c5602b4a 737 m_error = GSOCK_INVADDR;
e6f2ec14
DE
738 return GSOCK_INVADDR;
739 }
740
741 /* Streamed or dgram socket? */
c5602b4a 742 m_stream = (stream == GSOCK_STREAMED);
948c96ef
DE
743 m_oriented = true;
744 m_server = false;
e6f2ec14
DE
745
746 /* Create the socket */
747#if TARGET_CARBON
902725ee 748 m_endpoint =
3dee36ae 749 OTOpenEndpointInContext( OTCreateConfiguration( kTCPName) , 0 , &info , &err , NULL ) ;
e6f2ec14 750#else
902725ee 751 m_endpoint =
3dee36ae 752 OTOpenEndpoint( OTCreateConfiguration( kTCPName) , 0 , &info , &err ) ;
e6f2ec14 753#endif
c5602b4a 754 if ( m_endpoint == kOTInvalidEndpointRef || err != kOTNoError )
e6f2ec14 755 {
3dee36ae
WS
756 m_endpoint = kOTInvalidEndpointRef ;
757 m_error = GSOCK_IOERR;
758 return GSOCK_IOERR;
e6f2ec14 759 }
c5602b4a 760 err = OTBind( m_endpoint , nil , nil ) ;
e6f2ec14
DE
761 if ( err != kOTNoError )
762 {
3dee36ae 763 return GSOCK_IOERR;
e6f2ec14 764 }
c5602b4a 765 SetDefaultEndpointModes( m_endpoint , this ) ;
e6f2ec14
DE
766// TODO
767#if 0
c5602b4a 768 ioctl(m_endpoint, FIONBIO, &arg);
e6f2ec14 769#endif
c5602b4a 770 Enable_Events();
e6f2ec14 771
c5602b4a 772 _GAddress_translate_to( m_peer , &addr ) ;
e6f2ec14
DE
773 memset( &peer , 0 , sizeof( TCall ) ) ;
774 peer.addr.len = sizeof( InetAddress ) ;
775 peer.addr.buf = (unsigned char*) &addr ;
c5602b4a 776 err = OTConnect( m_endpoint , &peer , nil ) ;
e6f2ec14
DE
777 if ( err != noErr )
778 {
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
782 * completes.
902725ee
WS
783 */
784
c5602b4a 785 if ((err == kOTNoDataErr ) && (!m_non_blocking))
e6f2ec14 786 {
c5602b4a 787 if (Output_Timeout() == GSOCK_TIMEDOUT)
e6f2ec14 788 {
3dee36ae 789 OTSndOrderlyDisconnect( m_endpoint ) ;
c5602b4a
DE
790 m_endpoint = kOTInvalidEndpointRef ;
791 /* m_error is set in _GSocket_Output_Timeout */
e6f2ec14
DE
792 return GSOCK_TIMEDOUT;
793 }
794 else
795 {
796/*
797 int error;
9e03e02d 798 WX_SOCKLEN_T len = sizeof(error);
e6f2ec14 799
c5602b4a 800 getsockopt(m_endpoint, SOL_SOCKET, SO_ERROR, (void*) &error, &len);
e6f2ec14
DE
801
802 if (!error)
803*/
804 return GSOCK_NOERROR;
805 }
806 }
807
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.
813 */
c5602b4a 814 if ((err == kOTNoDataErr) && (m_non_blocking))
e6f2ec14 815 {
c5602b4a 816 m_error = GSOCK_WOULDBLOCK;
e6f2ec14
DE
817 return GSOCK_WOULDBLOCK;
818 }
819
820 /* If connect failed with an error other than EINPROGRESS,
821 * then the call to GSocket_Connect has failed.
822 */
c5602b4a 823 OTSndOrderlyDisconnect( m_endpoint ) ;
e6f2ec14 824
c5602b4a
DE
825 m_endpoint = kOTInvalidEndpointRef ;
826 m_error = GSOCK_IOERR;
e6f2ec14
DE
827 return GSOCK_IOERR;
828 }
c5602b4a 829// OTInetEventHandler(this, T_CONNECT , kOTNoError , NULL ) ;
e6f2ec14
DE
830 return GSOCK_NOERROR;
831}
832
833/* Generic IO */
834
835/* Like recv(), send(), ... */
c5602b4a 836int GSocket::Read(char *buffer, int size)
e6f2ec14
DE
837{
838 int ret = 0 ;
839
c5602b4a 840 assert(this);
e6f2ec14
DE
841
842 /* Reenable INPUT events */
c5602b4a 843 m_detected &= ~GSOCK_INPUT_FLAG;
e6f2ec14 844
c5602b4a 845 if (m_endpoint == kOTInvalidEndpointRef || m_server)
e6f2ec14 846 {
c5602b4a 847 m_error = GSOCK_INVSOCK;
e6f2ec14
DE
848 return -1;
849 }
850
851 /* If the socket is blocking, wait for data (with a timeout) */
c5602b4a 852 if (Input_Timeout() == GSOCK_TIMEDOUT)
e6f2ec14
DE
853 return -1;
854
855 /* Read the data */
c5602b4a
DE
856 if (m_stream)
857 ret = Recv_Stream(buffer, size);
e6f2ec14 858 else
c5602b4a 859 ret = Recv_Dgram(buffer, size);
902725ee 860
e6f2ec14
DE
861 if (ret == -1)
862 {
863 if (errno == EWOULDBLOCK)
c5602b4a 864 m_error = GSOCK_WOULDBLOCK;
e6f2ec14 865 else
c5602b4a 866 m_error = GSOCK_IOERR;
e6f2ec14 867 }
902725ee 868
e6f2ec14
DE
869 return ret;
870}
871
c5602b4a 872int GSocket::Write(const char *buffer, int size)
902725ee 873{
e6f2ec14
DE
874 int ret;
875
c5602b4a 876 assert(this);
e6f2ec14 877
c5602b4a 878 if (m_endpoint == kOTInvalidEndpointRef || m_server)
e6f2ec14 879 {
c5602b4a 880 m_error = GSOCK_INVSOCK;
e6f2ec14
DE
881 return -1;
882 }
883
884 /* If the socket is blocking, wait for writability (with a timeout) */
c5602b4a 885 if (Output_Timeout() == GSOCK_TIMEDOUT)
e6f2ec14
DE
886 return -1;
887
888 /* Write the data */
c5602b4a
DE
889 if (m_stream)
890 ret = Send_Stream(buffer, size);
e6f2ec14 891 else
c5602b4a 892 ret = Send_Dgram(buffer, size);
902725ee 893
e6f2ec14
DE
894 if (ret == -1)
895 {
896 if (errno == EWOULDBLOCK)
c5602b4a 897 m_error = GSOCK_WOULDBLOCK;
e6f2ec14 898 else
c5602b4a 899 m_error = GSOCK_IOERR;
e6f2ec14
DE
900
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.
905 */
c5602b4a 906 m_detected &= ~GSOCK_OUTPUT_FLAG;
e6f2ec14
DE
907 return -1;
908 }
902725ee 909
e6f2ec14
DE
910 return ret;
911}
912
913/* GSocket_Select:
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.
919 */
c5602b4a 920GSocketEventFlags GSocket::Select(GSocketEventFlags flags)
e6f2ec14 921{
c5602b4a 922 assert(this);
e6f2ec14
DE
923 wxMacProcessNotifierEvents() ;
924 /*
c5602b4a 925 state = OTGetEndpointState(m_endpoint);
902725ee 926
c5602b4a 927 if ( ( flags & GSOCK_INPUT_FLAG ) && ! ( m_detected & GSOCK_INPUT_FLAG ) )
e6f2ec14 928 {
3dee36ae
WS
929 size_t sz = 0 ;
930 OTCountDataBytes( m_endpoint , &sz ) ;
931 if ( state == T_INCON || sz > 0 )
932 {
933 m_detected |= GSOCK_INPUT_FLAG ;
934 (m_cbacks[GSOCK_INPUT])(this, GSOCK_INPUT, m_data[GSOCK_INPUT]);
935 }
e6f2ec14 936 }
c5602b4a 937 if ( ( flags & GSOCK_INPUT_FLAG ) && ! ( m_detected & GSOCK_OUTPUT_FLAG ) )
e6f2ec14 938 {
3dee36ae
WS
939 if ( state == T_DATAXFER || state == T_INREL )
940 {
941 m_detected |=GSOCK_OUTPUT_FLAG ;
942 (m_cbacks[GSOCK_OUTPUT])(this, GSOCK_OUTPUT, m_data[GSOCK_OUTPUT]);
943 }
e6f2ec14
DE
944 }
945 */
c5602b4a 946 return ( flags & m_detected ) ;
e6f2ec14
DE
947}
948
949/* Flags */
950
951/* GSocket_SetNonBlocking:
952 * Sets the socket to non-blocking mode. All IO calls will return
953 * immediately.
954 */
948c96ef 955void GSocket::SetNonBlocking(bool non_block)
e6f2ec14 956{
c5602b4a 957 assert(this);
e6f2ec14 958
c5602b4a 959 m_non_blocking = non_block;
e6f2ec14
DE
960}
961
962/* GSocket_SetTimeout:
963 * Sets the timeout for blocking calls. Time is expressed in
964 * milliseconds.
965 */
c5602b4a 966void GSocket::SetTimeout(unsigned long millisec)
e6f2ec14 967{
c5602b4a 968 assert(this);
e6f2ec14
DE
969
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
c5602b4a 972// m_timeout = millisec;
e6f2ec14
DE
973}
974
975/* GSocket_GetError:
3103e8a9 976 * Returns the last error which occurred for this socket. Note that successful
e6f2ec14
DE
977 * operations do not clear this back to GSOCK_NOERROR, so use it only
978 * after an error.
979 */
c5602b4a 980GSocketError WXDLLIMPEXP_NET GSocket::GetError()
e6f2ec14 981{
c5602b4a 982 assert(this);
e6f2ec14 983
c5602b4a 984 return m_error;
e6f2ec14
DE
985}
986
987/* Callbacks */
988
989/* GSOCK_INPUT:
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
992 * be called again.
993 * GSOCK_OUTPUT:
902725ee 994 * The socket is available for writing. That is, the next write call
e6f2ec14
DE
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.
1000 * GSOCK_CONNECTION:
3103e8a9 1001 * Connection successfully established, for client sockets, or incoming
e6f2ec14
DE
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.
1004 * GSOCK_LOST:
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.
1007 */
1008
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:
1014 *
1015 * void function(GSocket *socket, GSocketEvent event, char *cdata)
1016 */
c5602b4a 1017void GSocket::SetCallback(GSocketEventFlags flags,
e6f2ec14
DE
1018 GSocketCallback callback, char *cdata)
1019{
1020 int count;
1021
c5602b4a 1022 assert(this);
e6f2ec14
DE
1023
1024 for (count = 0; count < GSOCK_MAX_EVENT; count++)
1025 {
1026 if ((flags & (1 << count)) != 0)
1027 {
c5602b4a
DE
1028 m_cbacks[count] = callback;
1029 m_data[count] = cdata;
e6f2ec14
DE
1030 }
1031 }
1032}
1033
1034/* GSocket_UnsetCallback:
1035 * Disables all callbacks specified by 'flags', which may be a
1036 * combination of flags OR'ed toghether.
1037 */
c5602b4a 1038void GSocket::UnsetCallback(GSocketEventFlags flags)
e6f2ec14
DE
1039{
1040 int count;
1041
c5602b4a 1042 assert(this);
e6f2ec14
DE
1043
1044 for (count = 0; count < GSOCK_MAX_EVENT; count++)
1045 {
1046 if ((flags & (1 << count)) != 0)
1047 {
c5602b4a
DE
1048 m_cbacks[count] = NULL;
1049 m_data[count] = NULL;
e6f2ec14
DE
1050 }
1051 }
1052}
1053
1054
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]); \
1059}
1060
c5602b4a 1061int GSocket::Recv_Stream(char *buffer, int size)
e6f2ec14 1062{
3dee36ae
WS
1063 OTFlags flags ;
1064 OTResult res ;
1065 OTByteCount sz = 0 ;
1066
1067 OTCountDataBytes( m_endpoint , &sz ) ;
1068 if ( size > (int)sz )
1069 size = sz ;
1070 res = OTRcv( m_endpoint , buffer , size , &flags ) ;
1071 if ( res < 0 )
1072 {
1073 return -1 ;
1074 }
1075
1076 // we simulate another read event if there are still bytes
1077 if ( m_takesEvents )
1078 {
1079 OTByteCount sz = 0 ;
1080 OTCountDataBytes( m_endpoint , &sz ) ;
1081 if ( sz > 0 )
1082 {
1083 m_detected |= GSOCK_INPUT_FLAG ;
1084 (m_cbacks[GSOCK_INPUT])(this, GSOCK_INPUT, m_data[GSOCK_INPUT]);
1085 }
1086 }
1087 return res ;
e6f2ec14
DE
1088}
1089
c5602b4a 1090int GSocket::Recv_Dgram(char *buffer, int size)
e6f2ec14
DE
1091{
1092// TODO
1093 int ret = -1;
1094#if 0
1095 struct sockaddr from;
9e03e02d 1096 WX_SOCKLEN_T fromlen = sizeof(from);
e6f2ec14
DE
1097 GSocketError err;
1098
1099 fromlen = sizeof(from);
1100
9e03e02d 1101 ret = recvfrom(m_endpoint, buffer, size, 0, &from, (WX_SOCKLEN_T *) &fromlen);
e6f2ec14
DE
1102
1103 if (ret == -1)
1104 return -1;
1105
1106 /* Translate a system address into a GSocket address */
c5602b4a 1107 if (!m_peer)
e6f2ec14 1108 {
c5602b4a
DE
1109 m_peer = GAddress_new();
1110 if (!m_peer)
e6f2ec14 1111 {
c5602b4a 1112 m_error = GSOCK_MEMERR;
e6f2ec14
DE
1113 return -1;
1114 }
1115 }
c5602b4a 1116 err = _GAddress_translate_from(m_peer, &from, fromlen);
e6f2ec14
DE
1117 if (err != GSOCK_NOERROR)
1118 {
c5602b4a
DE
1119 GAddress_destroy(m_peer);
1120 m_peer = NULL;
1121 m_error = err;
e6f2ec14
DE
1122 return -1;
1123 }
1124#endif
1125 return ret;
1126}
1127
c5602b4a 1128int GSocket::Send_Stream(const char *buffer, int size)
e6f2ec14 1129{
3dee36ae
WS
1130 OTFlags flags = 0 ;
1131 OTResult res ;
e6f2ec14 1132
3dee36ae
WS
1133 res = OTSnd( m_endpoint , (void*) buffer , size , flags ) ;
1134 return res ;
e6f2ec14
DE
1135}
1136
c5602b4a 1137int GSocket::Send_Dgram(const char *buffer, int size)
e6f2ec14
DE
1138{
1139 int ret = -1 ;
1140// TODO
1141#if 0
1142 struct sockaddr *addr;
1143 int len ;
1144 GSocketError err;
1145
c5602b4a 1146 if (!m_peer)
e6f2ec14 1147 {
c5602b4a 1148 m_error = GSOCK_INVADDR;
e6f2ec14
DE
1149 return -1;
1150 }
1151
c5602b4a 1152 err = _GAddress_translate_to(m_peer, &addr, &len);
e6f2ec14
DE
1153 if (err != GSOCK_NOERROR)
1154 {
c5602b4a 1155 m_error = err;
e6f2ec14
DE
1156 return -1;
1157 }
1158
c5602b4a 1159 ret = sendto(m_endpoint, buffer, size, 0, addr, len);
e6f2ec14
DE
1160
1161 /* Frees memory allocated from _GAddress_translate_to */
1162 free(addr);
1163#endif
1164 return ret;
1165}
1166
f5d5bd1d
DE
1167/* Compatibility functions for GSocket */
1168GSocket *GSocket_new(void)
1169{
1170 GSocket *newsocket = new GSocket();
1171 if(newsocket->IsOk())
1172 return newsocket;
1173 delete newsocket;
1174 return NULL;
1175}
1176
e6f2ec14
DE
1177
1178/*
1179 * -------------------------------------------------------------------------
1180 * GAddress
1181 * -------------------------------------------------------------------------
1182 */
1183
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.
1187 */
1188#define CHECK_ADDRESS(address, family, retval) \
1189{ \
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) \
1194 { \
1195 address->m_error = GSOCK_INVADDR; \
1196 return retval; \
1197 } \
1198}
1199
1200GAddress *GAddress_new()
1201{
1202 GAddress *address;
1203
1204 if ((address = (GAddress *) malloc(sizeof(GAddress))) == NULL)
1205 return NULL;
1206
1207 address->m_family = GSOCK_NOFAMILY;
1208 address->m_host = INADDR_NONE ;
1209 address->m_port = 0 ;
1210
1211 return address;
1212}
1213
1214GAddress *GAddress_copy(GAddress *address)
1215{
1216 GAddress *addr2;
1217
1218 assert(address != NULL);
1219
1220 if ((addr2 = (GAddress *) malloc(sizeof(GAddress))) == NULL)
1221 return NULL;
1222
1223 memcpy(addr2, address, sizeof(GAddress));
1224 return addr2;
1225}
1226
1227void GAddress_destroy(GAddress *address)
1228{
1229 assert(address != NULL);
1230
1231 free(address);
1232}
1233
1234void GAddress_SetFamily(GAddress *address, GAddressType type)
1235{
1236 assert(address != NULL);
1237
1238 address->m_family = type;
1239}
1240
1241GAddressType GAddress_GetFamily(GAddress *address)
1242{
1243 assert(address != NULL);
1244
1245 return address->m_family;
1246}
1247
1248GSocketError _GAddress_translate_from(GAddress *address,
1249 InetAddress *addr)
1250{
1251 switch (addr->fAddressType)
1252 {
1253 case AF_INET:
1254 address->m_family = GSOCK_INET;
1255 break;
1256#ifdef AF_INET6
1257 case AF_INET6:
1258 address->m_family = GSOCK_INET6;
1259 break;
1260#endif
1261 default:
1262 {
1263 address->m_error = GSOCK_INVOP;
1264 return GSOCK_INVOP;
1265 }
1266 }
1267 address->m_host = addr->fHost ;
1268 address->m_port = addr->fPort ;
1269 return GSOCK_NOERROR;
1270}
1271
1272GSocketError _GAddress_translate_to(GAddress *address,
1273 InetAddress *addr)
1274{
3dee36ae 1275 if ( !GSocket_Verify_Inited() )
e6f2ec14
DE
1276 return GSOCK_IOERR ;
1277 memset(addr, 0 , sizeof(struct InetAddress));
1278 OTInitInetAddress( addr , address->m_port , address->m_host ) ;
1279 return GSOCK_NOERROR;
1280}
1281
1282/*
1283 * -------------------------------------------------------------------------
1284 * Internet address family
1285 * -------------------------------------------------------------------------
1286 */
1287
1288GSocketError _GAddress_Init_INET(GAddress *address)
1289{
1290 address->m_family = GSOCK_INET;
1291 address->m_host = kOTAnyInetAddress ;
902725ee 1292
e6f2ec14
DE
1293 return GSOCK_NOERROR;
1294}
1295
1296GSocketError GAddress_INET_SetHostName(GAddress *address, const char *hostname)
1297{
1298 InetHostInfo hinfo ;
1299 OSStatus ret ;
1300
948c96ef 1301 if ( !GSocket_Verify_Inited() )
e6f2ec14
DE
1302 return GSOCK_IOERR ;
1303
1304 assert(address != NULL);
1305
1306 CHECK_ADDRESS(address, INET, GSOCK_INVADDR);
1307 ret = OTInetStringToAddress( gInetSvcRef , (char*) hostname , &hinfo ) ;
1308 if ( ret != kOTNoError )
1309 {
3dee36ae 1310 address->m_host = INADDR_NONE ;
e6f2ec14
DE
1311 address->m_error = GSOCK_NOHOST;
1312 return GSOCK_NOHOST;
902725ee 1313 }
e6f2ec14
DE
1314 address->m_host = hinfo.addrs[0] ;
1315 return GSOCK_NOERROR;
1316}
1317
1318GSocketError GAddress_INET_SetAnyAddress(GAddress *address)
1319{
1320 return GAddress_INET_SetHostAddress(address, INADDR_ANY);
1321}
1322
1323GSocketError GAddress_INET_SetHostAddress(GAddress *address,
1324 unsigned long hostaddr)
1325{
1326 assert(address != NULL);
1327
1328 CHECK_ADDRESS(address, INET, GSOCK_INVADDR);
1329
1330 address->m_host = htonl(hostaddr) ;
1331
1332 return GSOCK_NOERROR;
1333}
1334
902725ee 1335struct service_entry
e6f2ec14 1336{
3dee36ae
WS
1337 const char * name ;
1338 unsigned short port ;
1339 const char * protocol ;
e6f2ec14
DE
1340} ;
1341typedef struct service_entry service_entry ;
1342
1343service_entry gServices[] =
1344{
3dee36ae 1345 { "http" , 80 , "tcp" }
e6f2ec14
DE
1346} ;
1347
1348GSocketError GAddress_INET_SetPortName(GAddress *address, const char *port,
1349 const char *protocol)
1350{
1351 size_t i ;
1352
1353 assert(address != NULL);
1354 CHECK_ADDRESS(address, INET, GSOCK_INVADDR);
1355
1356 if (!port)
1357 {
1358 address->m_error = GSOCK_INVPORT;
1359 return GSOCK_INVPORT;
1360 }
1361 for ( i = 0 ; i < sizeof( gServices) / sizeof( service_entry ) ; ++i )
1362 {
3dee36ae
WS
1363 if ( strcmp( port , gServices[i].name ) == 0 )
1364 {
1365 if ( protocol == NULL || strcmp( protocol , gServices[i].protocol ) )
1366 {
1367 address->m_port = gServices[i].port ;
1368 return GSOCK_NOERROR;
1369 }
1370 }
e6f2ec14
DE
1371 }
1372
1373 if (isdigit(port[0]))
1374 {
1375 address->m_port = atoi(port);
1376 return GSOCK_NOERROR;
1377 }
1378
1379 address->m_error = GSOCK_INVPORT;
1380 return GSOCK_INVPORT;
1381}
1382
1383GSocketError GAddress_INET_SetPort(GAddress *address, unsigned short port)
1384{
1385 assert(address != NULL);
1386 CHECK_ADDRESS(address, INET, GSOCK_INVADDR);
1387 address->m_port = port ;
902725ee 1388
e6f2ec14
DE
1389 return GSOCK_NOERROR;
1390}
1391
1392GSocketError GAddress_INET_GetHostName(GAddress *address, char *hostname, size_t sbuf)
1393{
1394 InetDomainName name ;
3dee36ae 1395 if ( !GSocket_Verify_Inited() )
e6f2ec14 1396 return GSOCK_IOERR ;
902725ee
WS
1397
1398 assert(address != NULL);
e6f2ec14
DE
1399 CHECK_ADDRESS(address, INET, GSOCK_INVADDR);
1400
1401 OTInetAddressToName( gInetSvcRef , address->m_host , name ) ;
1402 strncpy( hostname , name , sbuf ) ;
1403 return GSOCK_NOERROR;
1404}
1405
1406unsigned long GAddress_INET_GetHostAddress(GAddress *address)
1407{
902725ee
WS
1408 assert(address != NULL);
1409 CHECK_ADDRESS(address, INET, 0);
e6f2ec14
DE
1410
1411 return ntohl(address->m_host);
1412}
1413
1414unsigned short GAddress_INET_GetPort(GAddress *address)
1415{
902725ee
WS
1416 assert(address != NULL);
1417 CHECK_ADDRESS(address, INET, 0);
e6f2ec14
DE
1418
1419 return address->m_port;
1420}
1421
c5602b4a 1422void GSocket::Enable_Events()
e6f2ec14 1423{
3dee36ae
WS
1424 if ( m_takesEvents )
1425 return ;
902725ee 1426
3dee36ae
WS
1427 {
1428 OTResult state ;
1429 m_takesEvents = true ;
1430 state = OTGetEndpointState(m_endpoint);
1431
1432 {
1433 OTByteCount sz = 0 ;
1434 OTCountDataBytes( m_endpoint , &sz ) ;
1435 if ( state == T_INCON || sz > 0 )
1436 {
1437 m_detected |= GSOCK_INPUT_FLAG ;
1438 (m_cbacks[GSOCK_INPUT])(this, GSOCK_INPUT, m_data[GSOCK_INPUT]);
1439 }
1440 }
1441 {
1442 if ( state == T_DATAXFER || state == T_INREL )
1443 {
1444 m_detected |=GSOCK_OUTPUT_FLAG ;
1445 (m_cbacks[GSOCK_OUTPUT])(this, GSOCK_OUTPUT, m_data[GSOCK_OUTPUT]);
1446 }
1447 }
1448 }
e6f2ec14
DE
1449}
1450
c5602b4a 1451void GSocket::Disable_Events()
e6f2ec14 1452{
3dee36ae 1453 m_takesEvents = false ;
e6f2ec14
DE
1454}
1455
1456/* _GSocket_Input_Timeout:
1457 * For blocking sockets, wait until data is available or
1458 * until timeout ellapses.
1459 */
c5602b4a 1460GSocketError GSocket::Input_Timeout()
e6f2ec14 1461{
c5602b4a 1462 if ( !m_non_blocking )
e6f2ec14
DE
1463 {
1464 UnsignedWide now , start ;
948c96ef 1465 bool formerTakesEvents = m_takesEvents ;
e6f2ec14
DE
1466 Microseconds(&start);
1467 now = start ;
948c96ef 1468 m_takesEvents = false ;
902725ee 1469
c5602b4a 1470 while( (now.hi * 4294967296.0 + now.lo) - (start.hi * 4294967296.0 + start.lo) < m_timeout * 1000.0 )
e6f2ec14 1471 {
3dee36ae
WS
1472 OTResult state ;
1473 OTByteCount sz = 0 ;
1474 state = OTGetEndpointState(m_endpoint);
1475
1476 OTCountDataBytes( m_endpoint , &sz ) ;
1477 if ( state == T_INCON || sz > 0 )
1478 {
1479 m_takesEvents = formerTakesEvents ;
1480 return GSOCK_NOERROR;
1481 }
1482 Microseconds(&now);
e6f2ec14 1483 }
c5602b4a
DE
1484 m_takesEvents = formerTakesEvents ;
1485 m_error = GSOCK_TIMEDOUT;
e6f2ec14
DE
1486 return GSOCK_TIMEDOUT;
1487 }
1488 return GSOCK_NOERROR;
1489}
1490
1491/* _GSocket_Output_Timeout:
1492 * For blocking sockets, wait until data can be sent without
1493 * blocking or until timeout ellapses.
1494 */
c5602b4a 1495GSocketError GSocket::Output_Timeout()
e6f2ec14 1496{
c5602b4a 1497 if ( !m_non_blocking )
e6f2ec14
DE
1498 {
1499 UnsignedWide now , start ;
948c96ef 1500 bool formerTakesEvents = m_takesEvents ;
e6f2ec14
DE
1501 Microseconds(&start);
1502 now = start ;
948c96ef 1503 m_takesEvents = false ;
902725ee 1504
c5602b4a 1505 while( (now.hi * 4294967296.0 + now.lo) - (start.hi * 4294967296.0 + start.lo) < m_timeout * 1000.0 )
e6f2ec14 1506 {
3dee36ae
WS
1507 OTResult state ;
1508 state = OTGetEndpointState(m_endpoint);
1509
1510 if ( state == T_DATAXFER || state == T_INREL )
1511 {
1512 m_takesEvents = formerTakesEvents ;
1513 return GSOCK_NOERROR;
1514 }
1515 Microseconds(&now);
e6f2ec14 1516 }
c5602b4a
DE
1517 m_takesEvents = formerTakesEvents ;
1518 m_error = GSOCK_TIMEDOUT;
e6f2ec14
DE
1519 return GSOCK_TIMEDOUT;
1520 }
1521 return GSOCK_NOERROR;
1522}
1523
1524/* GSOCK_INPUT:
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
1527 * be called again.
1528 * GSOCK_OUTPUT:
902725ee 1529 * The socket is available for writing. That is, the next write call
e6f2ec14
DE
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.
1535 * GSOCK_CONNECTION:
3103e8a9 1536 * Connection successfully established, for client sockets, or incoming
e6f2ec14
DE
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.
1539 * GSOCK_LOST:
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.
1542 */
1543
1544void _GSocket_Internal_Proc(unsigned long e , void* d )
1545{
902725ee
WS
1546 GSocket *socket = (GSocket*) d ;
1547
1548 if ( !socket )
1549 return ;
1550
1551 OTEventCode ev = (OTEventCode) e ;
1552 GSocketEvent event;
1553 GSocketEvent event2;
1554 GSocketCallback cback;
1555 char *data;
1556 GSocketCallback cback2;
1557 char *data2;
1558
e6f2ec14
DE
1559 event = GSOCK_MAX_EVENT ;
1560 event2 = GSOCK_MAX_EVENT ;
1561 cback = NULL;
1562 data = NULL;
1563 cback2 = NULL;
1564 data2 = NULL;
1565
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.
1569 */
902725ee 1570 if ( /* (socket != NULL) && */ (socket->m_takesEvents))
e6f2ec14 1571 {
3dee36ae
WS
1572 switch (ev)
1573 {
1574 case T_LISTEN :
1575 event = GSOCK_CONNECTION ;
1576 break ;
1577 case T_CONNECT :
1578 event = GSOCK_CONNECTION ;
1579 event2 = GSOCK_OUTPUT ;
1580 {
1581 TCall retCall;
1582
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 ) ;
1590 }
1591 break ;
1592 case T_DISCONNECT :
1593 event = GSOCK_LOST ;
1594 break ;
1595 case T_GODATA :
1596 case T_GOEXDATA :
1597 event = GSOCK_OUTPUT ;
1598 break ;
1599 case T_DATA :
1600 event = GSOCK_INPUT ;
1601 break ;
1602 case T_EXDATA :
1603 event = GSOCK_INPUT ;
1604 break ;
e6f2ec14
DE
1605 }
1606 if (event != GSOCK_MAX_EVENT)
1607 {
1608 cback = socket->m_cbacks[event];
1609 data = socket->m_data[event];
1610
1611 if (event == GSOCK_LOST)
1612 socket->m_detected = GSOCK_LOST_FLAG;
1613 else
1614 socket->m_detected |= (1 << event);
1615 }
1616 if (event2 != GSOCK_MAX_EVENT)
1617 {
1618 cback2 = socket->m_cbacks[event2];
1619 data2 = socket->m_data[event2];
1620
1621 if (event2 == GSOCK_LOST)
1622 socket->m_detected = GSOCK_LOST_FLAG;
1623 else
1624 socket->m_detected |= (1 << event2);
1625 }
1626 }
1627
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
1632 * been closed!
1633 */
1634
1635 if (cback != NULL)
1636 (cback)(socket, event, data);
1637 if (cback2 != NULL)
1638 (cback2)(socket, event2, data2);
1639
1640}
1641
1642/* Hack added for Mac OS X */
1643GSocketError GAddress_UNIX_GetPath(GAddress *addr, char *path, size_t buf)
1644{
1645 return GSOCK_INVADDR;
1646}
1647
1648GSocketError GAddress_UNIX_SetPath(GAddress *addr, const char *path)
1649{
1650 return GSOCK_INVADDR;
1651}
1652
1653#endif /* wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__) */