]> git.saurik.com Git - wxWidgets.git/blob - src/msw/gsocket.cpp
Take src x, y into account when blitting with alpha
[wxWidgets.git] / src / msw / gsocket.cpp
1 /* -------------------------------------------------------------------------
2 * Project: GSocket (Generic Socket)
3 * Name: gsocket.cpp
4 * Copyright: (c) Guilhem Lavaux
5 * Licence: wxWindows Licence
6 * Author: Guillermo Rodriguez Garcia <guille@iies.es>
7 * Purpose: GSocket main MSW file
8 * Licence: The wxWindows licence
9 * CVSID: $Id$
10 * -------------------------------------------------------------------------
11 */
12
13 // For compilers that support precompilation, includes "wx.h".
14 #include "wx/wxprec.h"
15
16 #ifdef __BORLANDC__
17 #pragma hdrstop
18 #endif
19
20 #ifdef _MSC_VER
21 /* RPCNOTIFICATION_ROUTINE in rasasync.h (included from winsock.h),
22 * warning: conditional expression is constant.
23 */
24 # pragma warning(disable:4115)
25 /* FD_SET,
26 * warning: named type definition in parentheses.
27 */
28 # pragma warning(disable:4127)
29 /* GAddress_UNIX_GetPath,
30 * warning: unreferenced formal parameter.
31 */
32 # pragma warning(disable:4100)
33
34 #ifdef __WXWINCE__
35 /* windows.h results in tons of warnings at max warning level */
36 # ifdef _MSC_VER
37 # pragma warning(push, 1)
38 # endif
39 # include <windows.h>
40 # ifdef _MSC_VER
41 # pragma warning(pop)
42 # pragma warning(disable:4514)
43 # endif
44 #endif
45
46 #endif /* _MSC_VER */
47
48 #if defined(__CYGWIN__)
49 //CYGWIN gives annoying warning about runtime stuff if we don't do this
50 # define USE_SYS_TYPES_FD_SET
51 # include <sys/types.h>
52 #endif
53
54 #include <winsock.h>
55
56 #ifndef __GSOCKET_STANDALONE__
57 # include "wx/platform.h"
58 # include "wx/setup.h"
59 #endif
60
61 #if wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__)
62
63 #ifndef __GSOCKET_STANDALONE__
64 # include "wx/msw/gsockmsw.h"
65 # include "wx/gsocket.h"
66 #else
67 # include "gsockmsw.h"
68 # include "gsocket.h"
69 #endif /* __GSOCKET_STANDALONE__ */
70
71 #ifndef __WXWINCE__
72 #include <assert.h>
73 #else
74 #define assert(x)
75 #ifndef isdigit
76 #define isdigit(x) (x > 47 && x < 58)
77 #endif
78 #include "wx/msw/wince/net.h"
79 #endif
80
81 #include <string.h>
82 #include <stdio.h>
83 #include <stdlib.h>
84 #include <stddef.h>
85 #include <ctype.h>
86
87 /* if we use configure for MSW SOCKLEN_T will be already defined */
88 #ifndef SOCKLEN_T
89 # define SOCKLEN_T int
90 #endif
91
92 /* Table of GUI-related functions. We must call them indirectly because
93 * of wxBase and GUI separation: */
94
95 static GSocketGUIFunctionsTable *gs_gui_functions;
96
97 class GSocketGUIFunctionsTableNull: public GSocketGUIFunctionsTable
98 {
99 public:
100 virtual bool OnInit();
101 virtual void OnExit();
102 virtual bool CanUseEventLoop();
103 virtual bool Init_Socket(GSocket *socket);
104 virtual void Destroy_Socket(GSocket *socket);
105 virtual void Enable_Events(GSocket *socket);
106 virtual void Disable_Events(GSocket *socket);
107 };
108
109 bool GSocketGUIFunctionsTableNull::OnInit()
110 { return true; }
111 void GSocketGUIFunctionsTableNull::OnExit()
112 {}
113 bool GSocketGUIFunctionsTableNull::CanUseEventLoop()
114 { return false; }
115 bool GSocketGUIFunctionsTableNull::Init_Socket(GSocket *WXUNUSED(socket))
116 { return true; }
117 void GSocketGUIFunctionsTableNull::Destroy_Socket(GSocket *WXUNUSED(socket))
118 {}
119 void GSocketGUIFunctionsTableNull::Enable_Events(GSocket *WXUNUSED(socket))
120 {}
121 void GSocketGUIFunctionsTableNull::Disable_Events(GSocket *WXUNUSED(socket))
122 {}
123 /* Global initialisers */
124
125 void GSocket_SetGUIFunctions(GSocketGUIFunctionsTable *guifunc)
126 {
127 gs_gui_functions = guifunc;
128 }
129
130 int GSocket_Init(void)
131 {
132 WSADATA wsaData;
133
134 if (!gs_gui_functions)
135 {
136 static GSocketGUIFunctionsTableNull table;
137 gs_gui_functions = &table;
138 }
139 if ( !gs_gui_functions->OnInit() )
140 {
141 return 0;
142 }
143
144 /* Initialize WinSocket */
145 return (WSAStartup((1 << 8) | 1, &wsaData) == 0);
146 }
147
148 void GSocket_Cleanup(void)
149 {
150 if (gs_gui_functions)
151 {
152 gs_gui_functions->OnExit();
153 }
154
155 /* Cleanup WinSocket */
156 WSACleanup();
157 }
158
159 /* Constructors / Destructors for GSocket */
160
161 GSocket::GSocket()
162 {
163 int i;
164
165 m_fd = INVALID_SOCKET;
166 for (i = 0; i < GSOCK_MAX_EVENT; i++)
167 {
168 m_cbacks[i] = NULL;
169 }
170 m_detected = 0;
171 m_local = NULL;
172 m_peer = NULL;
173 m_error = GSOCK_NOERROR;
174 m_server = false;
175 m_stream = true;
176 m_non_blocking = false;
177 m_timeout.tv_sec = 10 * 60; /* 10 minutes */
178 m_timeout.tv_usec = 0;
179 m_establishing = false;
180 m_reusable = false;
181
182 assert(gs_gui_functions);
183 /* Per-socket GUI-specific initialization */
184 m_ok = gs_gui_functions->Init_Socket(this);
185 }
186
187 void GSocket::Close()
188 {
189 gs_gui_functions->Disable_Events(this);
190 closesocket(m_fd);
191 m_fd = INVALID_SOCKET;
192 }
193
194 GSocket::~GSocket()
195 {
196 assert(this);
197
198 /* Per-socket GUI-specific cleanup */
199 gs_gui_functions->Destroy_Socket(this);
200
201 /* Check that the socket is really shutdowned */
202 if (m_fd != INVALID_SOCKET)
203 Shutdown();
204
205 /* Destroy private addresses */
206 if (m_local)
207 GAddress_destroy(m_local);
208
209 if (m_peer)
210 GAddress_destroy(m_peer);
211 }
212
213 /* GSocket_Shutdown:
214 * Disallow further read/write operations on this socket, close
215 * the fd and disable all callbacks.
216 */
217 void GSocket::Shutdown()
218 {
219 int evt;
220
221 assert(this);
222
223 /* If socket has been created, shutdown it */
224 if (m_fd != INVALID_SOCKET)
225 {
226 shutdown(m_fd, 2);
227 Close();
228 }
229
230 /* Disable GUI callbacks */
231 for (evt = 0; evt < GSOCK_MAX_EVENT; evt++)
232 m_cbacks[evt] = NULL;
233
234 m_detected = GSOCK_LOST_FLAG;
235 }
236
237 /* Address handling */
238
239 /* GSocket_SetLocal:
240 * GSocket_GetLocal:
241 * GSocket_SetPeer:
242 * GSocket_GetPeer:
243 * Set or get the local or peer address for this socket. The 'set'
244 * functions return GSOCK_NOERROR on success, an error code otherwise.
245 * The 'get' functions return a pointer to a GAddress object on success,
246 * or NULL otherwise, in which case they set the error code of the
247 * corresponding GSocket.
248 *
249 * Error codes:
250 * GSOCK_INVSOCK - the socket is not valid.
251 * GSOCK_INVADDR - the address is not valid.
252 */
253 GSocketError GSocket::SetLocal(GAddress *address)
254 {
255 assert(this);
256
257 /* the socket must be initialized, or it must be a server */
258 if (m_fd != INVALID_SOCKET && !m_server)
259 {
260 m_error = GSOCK_INVSOCK;
261 return GSOCK_INVSOCK;
262 }
263
264 /* check address */
265 if (address == NULL || address->m_family == GSOCK_NOFAMILY)
266 {
267 m_error = GSOCK_INVADDR;
268 return GSOCK_INVADDR;
269 }
270
271 if (m_local)
272 GAddress_destroy(m_local);
273
274 m_local = GAddress_copy(address);
275
276 return GSOCK_NOERROR;
277 }
278
279 GSocketError GSocket::SetPeer(GAddress *address)
280 {
281 assert(this);
282
283 /* check address */
284 if (address == NULL || address->m_family == GSOCK_NOFAMILY)
285 {
286 m_error = GSOCK_INVADDR;
287 return GSOCK_INVADDR;
288 }
289
290 if (m_peer)
291 GAddress_destroy(m_peer);
292
293 m_peer = GAddress_copy(address);
294
295 return GSOCK_NOERROR;
296 }
297
298 GAddress *GSocket::GetLocal()
299 {
300 GAddress *address;
301 struct sockaddr addr;
302 SOCKLEN_T size = sizeof(addr);
303 GSocketError err;
304
305 assert(this);
306
307 /* try to get it from the m_local var first */
308 if (m_local)
309 return GAddress_copy(m_local);
310
311 /* else, if the socket is initialized, try getsockname */
312 if (m_fd == INVALID_SOCKET)
313 {
314 m_error = GSOCK_INVSOCK;
315 return NULL;
316 }
317
318 if (getsockname(m_fd, &addr, &size) == SOCKET_ERROR)
319 {
320 m_error = GSOCK_IOERR;
321 return NULL;
322 }
323
324 /* got a valid address from getsockname, create a GAddress object */
325 if ((address = GAddress_new()) == NULL)
326 {
327 m_error = GSOCK_MEMERR;
328 return NULL;
329 }
330
331 if ((err = _GAddress_translate_from(address, &addr, size)) != GSOCK_NOERROR)
332 {
333 GAddress_destroy(address);
334 m_error = err;
335 return NULL;
336 }
337
338 return address;
339 }
340
341 GAddress *GSocket::GetPeer()
342 {
343 assert(this);
344
345 /* try to get it from the m_peer var */
346 if (m_peer)
347 return GAddress_copy(m_peer);
348
349 return NULL;
350 }
351
352 /* Server specific parts */
353
354 /* GSocket_SetServer:
355 * Sets up this socket as a server. The local address must have been
356 * set with GSocket_SetLocal() before GSocket_SetServer() is called.
357 * Returns GSOCK_NOERROR on success, one of the following otherwise:
358 *
359 * Error codes:
360 * GSOCK_INVSOCK - the socket is in use.
361 * GSOCK_INVADDR - the local address has not been set.
362 * GSOCK_IOERR - low-level error.
363 */
364 GSocketError GSocket::SetServer()
365 {
366 u_long arg = 1;
367
368 assert(this);
369
370 /* must not be in use */
371 if (m_fd != INVALID_SOCKET)
372 {
373 m_error = GSOCK_INVSOCK;
374 return GSOCK_INVSOCK;
375 }
376
377 /* the local addr must have been set */
378 if (!m_local)
379 {
380 m_error = GSOCK_INVADDR;
381 return GSOCK_INVADDR;
382 }
383
384 /* Initialize all fields */
385 m_server = true;
386 m_stream = true;
387
388 /* Create the socket */
389 m_fd = socket(m_local->m_realfamily, SOCK_STREAM, 0);
390
391 if (m_fd == INVALID_SOCKET)
392 {
393 m_error = GSOCK_IOERR;
394 return GSOCK_IOERR;
395 }
396
397 ioctlsocket(m_fd, FIONBIO, (u_long FAR *) &arg);
398 gs_gui_functions->Enable_Events(this);
399
400 /* allow a socket to re-bind if the socket is in the TIME_WAIT
401 state after being previously closed.
402 */
403 if (m_reusable) {
404 setsockopt(m_fd, SOL_SOCKET, SO_REUSEADDR, (const char*)&arg, sizeof(u_long));
405 }
406
407 /* Bind to the local address,
408 * retrieve the actual address bound,
409 * and listen up to 5 connections.
410 */
411 if ((bind(m_fd, m_local->m_addr, m_local->m_len) != 0) ||
412 (getsockname(m_fd,
413 m_local->m_addr,
414 (SOCKLEN_T *)&m_local->m_len) != 0) ||
415 (listen(m_fd, 5) != 0))
416 {
417 Close();
418 m_error = GSOCK_IOERR;
419 return GSOCK_IOERR;
420 }
421
422 return GSOCK_NOERROR;
423 }
424
425 /* GSocket_WaitConnection:
426 * Waits for an incoming client connection. Returns a pointer to
427 * a GSocket object, or NULL if there was an error, in which case
428 * the last error field will be updated for the calling GSocket.
429 *
430 * Error codes (set in the calling GSocket)
431 * GSOCK_INVSOCK - the socket is not valid or not a server.
432 * GSOCK_TIMEDOUT - timeout, no incoming connections.
433 * GSOCK_WOULDBLOCK - the call would block and the socket is nonblocking.
434 * GSOCK_MEMERR - couldn't allocate memory.
435 * GSOCK_IOERR - low-level error.
436 */
437 GSocket *GSocket::WaitConnection()
438 {
439 GSocket *connection;
440 struct sockaddr from;
441 SOCKLEN_T fromlen = sizeof(from);
442 GSocketError err;
443 u_long arg = 1;
444
445 assert(this);
446
447 /* Reenable CONNECTION events */
448 m_detected &= ~GSOCK_CONNECTION_FLAG;
449
450 /* If the socket has already been created, we exit immediately */
451 if (m_fd == INVALID_SOCKET || !m_server)
452 {
453 m_error = GSOCK_INVSOCK;
454 return NULL;
455 }
456
457 /* Create a GSocket object for the new connection */
458 connection = GSocket_new();
459
460 if (!connection)
461 {
462 m_error = GSOCK_MEMERR;
463 return NULL;
464 }
465
466 /* Wait for a connection (with timeout) */
467 if (Input_Timeout() == GSOCK_TIMEDOUT)
468 {
469 delete connection;
470 /* m_error set by _GSocket_Input_Timeout */
471 return NULL;
472 }
473
474 connection->m_fd = accept(m_fd, &from, &fromlen);
475
476 if (connection->m_fd == INVALID_SOCKET)
477 {
478 if (WSAGetLastError() == WSAEWOULDBLOCK)
479 m_error = GSOCK_WOULDBLOCK;
480 else
481 m_error = GSOCK_IOERR;
482
483 delete connection;
484 return NULL;
485 }
486
487 /* Initialize all fields */
488 connection->m_server = false;
489 connection->m_stream = true;
490
491 /* Setup the peer address field */
492 connection->m_peer = GAddress_new();
493 if (!connection->m_peer)
494 {
495 delete connection;
496 m_error = GSOCK_MEMERR;
497 return NULL;
498 }
499 err = _GAddress_translate_from(connection->m_peer, &from, fromlen);
500 if (err != GSOCK_NOERROR)
501 {
502 GAddress_destroy(connection->m_peer);
503 delete connection;
504 m_error = err;
505 return NULL;
506 }
507
508 ioctlsocket(connection->m_fd, FIONBIO, (u_long FAR *) &arg);
509 gs_gui_functions->Enable_Events(connection);
510
511 return connection;
512 }
513
514 /* GSocket_SetReusable:
515 * Simply sets the m_resuable flag on the socket. GSocket_SetServer will
516 * make the appropriate setsockopt() call.
517 * Implemented as a GSocket function because clients (ie, wxSocketServer)
518 * don't have access to the GSocket struct information.
519 * Returns true if the flag was set correctly, false if an error occured
520 * (ie, if the parameter was NULL)
521 */
522 bool GSocket::SetReusable()
523 {
524 /* socket must not be null, and must not be in use/already bound */
525 if (this && m_fd == INVALID_SOCKET) {
526 m_reusable = true;
527 return true;
528 }
529 return false;
530 }
531
532 /* Client specific parts */
533
534 /* GSocket_Connect:
535 * For stream (connection oriented) sockets, GSocket_Connect() tries
536 * to establish a client connection to a server using the peer address
537 * as established with GSocket_SetPeer(). Returns GSOCK_NOERROR if the
538 * connection has been succesfully established, or one of the error
539 * codes listed below. Note that for nonblocking sockets, a return
540 * value of GSOCK_WOULDBLOCK doesn't mean a failure. The connection
541 * request can be completed later; you should use GSocket_Select()
542 * to poll for GSOCK_CONNECTION | GSOCK_LOST, or wait for the
543 * corresponding asynchronous events.
544 *
545 * For datagram (non connection oriented) sockets, GSocket_Connect()
546 * just sets the peer address established with GSocket_SetPeer() as
547 * default destination.
548 *
549 * Error codes:
550 * GSOCK_INVSOCK - the socket is in use or not valid.
551 * GSOCK_INVADDR - the peer address has not been established.
552 * GSOCK_TIMEDOUT - timeout, the connection failed.
553 * GSOCK_WOULDBLOCK - connection in progress (nonblocking sockets only)
554 * GSOCK_MEMERR - couldn't allocate memory.
555 * GSOCK_IOERR - low-level error.
556 */
557 GSocketError GSocket::Connect(GSocketStream stream)
558 {
559 int ret, err;
560 u_long arg = 1;
561
562 assert(this);
563
564 /* Enable CONNECTION events (needed for nonblocking connections) */
565 m_detected &= ~GSOCK_CONNECTION_FLAG;
566
567 if (m_fd != INVALID_SOCKET)
568 {
569 m_error = GSOCK_INVSOCK;
570 return GSOCK_INVSOCK;
571 }
572
573 if (!m_peer)
574 {
575 m_error = GSOCK_INVADDR;
576 return GSOCK_INVADDR;
577 }
578
579 /* Streamed or dgram socket? */
580 m_stream = (stream == GSOCK_STREAMED);
581 m_server = false;
582 m_establishing = false;
583
584 /* Create the socket */
585 m_fd = socket(m_peer->m_realfamily,
586 m_stream? SOCK_STREAM : SOCK_DGRAM, 0);
587
588 if (m_fd == INVALID_SOCKET)
589 {
590 m_error = GSOCK_IOERR;
591 return GSOCK_IOERR;
592 }
593
594 ioctlsocket(m_fd, FIONBIO, (u_long FAR *) &arg);
595 gs_gui_functions->Enable_Events(this);
596
597 /* Connect it to the peer address, with a timeout (see below) */
598 ret = connect(m_fd, m_peer->m_addr, m_peer->m_len);
599
600 if (ret == SOCKET_ERROR)
601 {
602 err = WSAGetLastError();
603
604 /* If connect failed with EWOULDBLOCK and the GSocket object
605 * is in blocking mode, we select() for the specified timeout
606 * checking for writability to see if the connection request
607 * completes.
608 */
609 if ((err == WSAEWOULDBLOCK) && (!m_non_blocking))
610 {
611 err = Connect_Timeout();
612
613 if (err != GSOCK_NOERROR)
614 {
615 Close();
616 /* m_error is set in _GSocket_Connect_Timeout */
617 }
618
619 return (GSocketError) err;
620 }
621
622 /* If connect failed with EWOULDBLOCK and the GSocket object
623 * is set to nonblocking, we set m_error to GSOCK_WOULDBLOCK
624 * (and return GSOCK_WOULDBLOCK) but we don't close the socket;
625 * this way if the connection completes, a GSOCK_CONNECTION
626 * event will be generated, if enabled.
627 */
628 if ((err == WSAEWOULDBLOCK) && (m_non_blocking))
629 {
630 m_establishing = true;
631 m_error = GSOCK_WOULDBLOCK;
632 return GSOCK_WOULDBLOCK;
633 }
634
635 /* If connect failed with an error other than EWOULDBLOCK,
636 * then the call to GSocket_Connect() has failed.
637 */
638 Close();
639 m_error = GSOCK_IOERR;
640 return GSOCK_IOERR;
641 }
642
643 return GSOCK_NOERROR;
644 }
645
646 /* Datagram sockets */
647
648 /* GSocket_SetNonOriented:
649 * Sets up this socket as a non-connection oriented (datagram) socket.
650 * Before using this function, the local address must have been set
651 * with GSocket_SetLocal(), or the call will fail. Returns GSOCK_NOERROR
652 * on success, or one of the following otherwise.
653 *
654 * Error codes:
655 * GSOCK_INVSOCK - the socket is in use.
656 * GSOCK_INVADDR - the local address has not been set.
657 * GSOCK_IOERR - low-level error.
658 */
659 GSocketError GSocket::SetNonOriented()
660 {
661 u_long arg = 1;
662
663 assert(this);
664
665 if (m_fd != INVALID_SOCKET)
666 {
667 m_error = GSOCK_INVSOCK;
668 return GSOCK_INVSOCK;
669 }
670
671 if (!m_local)
672 {
673 m_error = GSOCK_INVADDR;
674 return GSOCK_INVADDR;
675 }
676
677 /* Initialize all fields */
678 m_stream = false;
679 m_server = false;
680
681 /* Create the socket */
682 m_fd = socket(m_local->m_realfamily, SOCK_DGRAM, 0);
683
684 if (m_fd == INVALID_SOCKET)
685 {
686 m_error = GSOCK_IOERR;
687 return GSOCK_IOERR;
688 }
689
690 ioctlsocket(m_fd, FIONBIO, (u_long FAR *) &arg);
691 gs_gui_functions->Enable_Events(this);
692
693 /* Bind to the local address,
694 * and retrieve the actual address bound.
695 */
696 if ((bind(m_fd, m_local->m_addr, m_local->m_len) != 0) ||
697 (getsockname(m_fd,
698 m_local->m_addr,
699 (SOCKLEN_T *)&m_local->m_len) != 0))
700 {
701 Close();
702 m_error = GSOCK_IOERR;
703 return GSOCK_IOERR;
704 }
705
706 return GSOCK_NOERROR;
707 }
708
709 /* Generic IO */
710
711 /* Like recv(), send(), ... */
712 int GSocket::Read(char *buffer, int size)
713 {
714 int ret;
715
716 assert(this);
717
718 /* Reenable INPUT events */
719 m_detected &= ~GSOCK_INPUT_FLAG;
720
721 if (m_fd == INVALID_SOCKET || m_server)
722 {
723 m_error = GSOCK_INVSOCK;
724 return -1;
725 }
726
727 /* If the socket is blocking, wait for data (with a timeout) */
728 if (Input_Timeout() == GSOCK_TIMEDOUT)
729 return -1;
730
731 /* Read the data */
732 if (m_stream)
733 ret = Recv_Stream(buffer, size);
734 else
735 ret = Recv_Dgram(buffer, size);
736
737 if (ret == SOCKET_ERROR)
738 {
739 if (WSAGetLastError() != WSAEWOULDBLOCK)
740 m_error = GSOCK_IOERR;
741 else
742 m_error = GSOCK_WOULDBLOCK;
743 return -1;
744 }
745
746 return ret;
747 }
748
749 int GSocket::Write(const char *buffer, int size)
750 {
751 int ret;
752
753 assert(this);
754
755 if (m_fd == INVALID_SOCKET || m_server)
756 {
757 m_error = GSOCK_INVSOCK;
758 return -1;
759 }
760
761 /* If the socket is blocking, wait for writability (with a timeout) */
762 if (Output_Timeout() == GSOCK_TIMEDOUT)
763 return -1;
764
765 /* Write the data */
766 if (m_stream)
767 ret = Send_Stream(buffer, size);
768 else
769 ret = Send_Dgram(buffer, size);
770
771 if (ret == SOCKET_ERROR)
772 {
773 if (WSAGetLastError() != WSAEWOULDBLOCK)
774 m_error = GSOCK_IOERR;
775 else
776 m_error = GSOCK_WOULDBLOCK;
777
778 /* Only reenable OUTPUT events after an error (just like WSAAsyncSelect
779 * does). Once the first OUTPUT event is received, users can assume
780 * that the socket is writable until a read operation fails. Only then
781 * will further OUTPUT events be posted.
782 */
783 m_detected &= ~GSOCK_OUTPUT_FLAG;
784 return -1;
785 }
786
787 return ret;
788 }
789
790 /* GSocket_Select:
791 * Polls the socket to determine its status. This function will
792 * check for the events specified in the 'flags' parameter, and
793 * it will return a mask indicating which operations can be
794 * performed. This function won't block, regardless of the
795 * mode (blocking | nonblocking) of the socket.
796 */
797 GSocketEventFlags GSocket::Select(GSocketEventFlags flags)
798 {
799 if (!gs_gui_functions->CanUseEventLoop())
800 {
801 GSocketEventFlags result = 0;
802 fd_set readfds;
803 fd_set writefds;
804 fd_set exceptfds;
805
806 assert(this);
807
808 FD_ZERO(&readfds);
809 FD_ZERO(&writefds);
810 FD_ZERO(&exceptfds);
811 FD_SET(m_fd, &readfds);
812 if (flags & GSOCK_OUTPUT_FLAG || flags & GSOCK_CONNECTION_FLAG)
813 FD_SET(m_fd, &writefds);
814 FD_SET(m_fd, &exceptfds);
815
816 /* Check 'sticky' CONNECTION flag first */
817 result |= (GSOCK_CONNECTION_FLAG & m_detected);
818
819 /* If we have already detected a LOST event, then don't try
820 * to do any further processing.
821 */
822 if ((m_detected & GSOCK_LOST_FLAG) != 0)
823 {
824 m_establishing = false;
825
826 return (GSOCK_LOST_FLAG & flags);
827 }
828
829 /* Try select now */
830 if (select(m_fd + 1, &readfds, &writefds, &exceptfds,
831 &m_timeout) <= 0)
832 {
833 /* What to do here? */
834 return (result & flags);
835 }
836
837 /* Check for readability */
838 if (FD_ISSET(m_fd, &readfds))
839 {
840 char c;
841
842 if (!m_stream || recv(m_fd, &c, 1, MSG_PEEK) > 0)
843 {
844 result |= GSOCK_INPUT_FLAG;
845 }
846 else
847 {
848 if (m_server && m_stream)
849 {
850 result |= GSOCK_CONNECTION_FLAG;
851 m_detected |= GSOCK_CONNECTION_FLAG;
852 }
853 else
854 {
855 m_detected = GSOCK_LOST_FLAG;
856 m_establishing = false;
857
858 /* LOST event: Abort any further processing */
859 return (GSOCK_LOST_FLAG & flags);
860 }
861 }
862 }
863
864 /* Check for writability */
865 if (FD_ISSET(m_fd, &writefds))
866 {
867 if (m_establishing && !m_server)
868 {
869 int error;
870 SOCKLEN_T len = sizeof(error);
871
872 m_establishing = false;
873
874 getsockopt(m_fd, SOL_SOCKET, SO_ERROR, (char*)&error, &len);
875
876 if (error)
877 {
878 m_detected = GSOCK_LOST_FLAG;
879
880 /* LOST event: Abort any further processing */
881 return (GSOCK_LOST_FLAG & flags);
882 }
883 else
884 {
885 result |= GSOCK_CONNECTION_FLAG;
886 m_detected |= GSOCK_CONNECTION_FLAG;
887 }
888 }
889 else
890 {
891 result |= GSOCK_OUTPUT_FLAG;
892 }
893 }
894
895 /* Check for exceptions and errors (is this useful in Unices?) */
896 if (FD_ISSET(m_fd, &exceptfds))
897 {
898 m_establishing = false;
899 m_detected = GSOCK_LOST_FLAG;
900
901 /* LOST event: Abort any further processing */
902 return (GSOCK_LOST_FLAG & flags);
903 }
904
905 return (result & flags);
906 }
907 else /* USE_GUI() */
908 {
909 assert(this);
910 return flags & m_detected;
911 }
912 }
913
914 /* Attributes */
915
916 /* GSocket_SetNonBlocking:
917 * Sets the socket to non-blocking mode. All IO calls will return
918 * immediately.
919 */
920 void GSocket::SetNonBlocking(bool non_block)
921 {
922 assert(this);
923
924 m_non_blocking = non_block;
925 }
926
927 /* GSocket_SetTimeout:
928 * Sets the timeout for blocking calls. Time is expressed in
929 * milliseconds.
930 */
931 void GSocket::SetTimeout(unsigned long millis)
932 {
933 assert(this);
934
935 m_timeout.tv_sec = (millis / 1000);
936 m_timeout.tv_usec = (millis % 1000) * 1000;
937 }
938
939 /* GSocket_GetError:
940 * Returns the last error occured for this socket. Note that successful
941 * operations do not clear this back to GSOCK_NOERROR, so use it only
942 * after an error.
943 */
944 GSocketError WXDLLIMPEXP_NET GSocket::GetError()
945 {
946 assert(this);
947
948 return m_error;
949 }
950
951 /* Callbacks */
952
953 /* GSOCK_INPUT:
954 * There is data to be read in the input buffer. If, after a read
955 * operation, there is still data available, the callback function will
956 * be called again.
957 * GSOCK_OUTPUT:
958 * The socket is available for writing. That is, the next write call
959 * won't block. This event is generated only once, when the connection is
960 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
961 * when the output buffer empties again. This means that the app should
962 * assume that it can write since the first OUTPUT event, and no more
963 * OUTPUT events will be generated unless an error occurs.
964 * GSOCK_CONNECTION:
965 * Connection succesfully established, for client sockets, or incoming
966 * client connection, for server sockets. Wait for this event (also watch
967 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
968 * GSOCK_LOST:
969 * The connection is lost (or a connection request failed); this could
970 * be due to a failure, or due to the peer closing it gracefully.
971 */
972
973 /* GSocket_SetCallback:
974 * Enables the callbacks specified by 'flags'. Note that 'flags'
975 * may be a combination of flags OR'ed toghether, so the same
976 * callback function can be made to accept different events.
977 * The callback function must have the following prototype:
978 *
979 * void function(GSocket *socket, GSocketEvent event, char *cdata)
980 */
981 void GSocket::SetCallback(GSocketEventFlags flags,
982 GSocketCallback callback, char *cdata)
983 {
984 int count;
985
986 assert(this);
987
988 for (count = 0; count < GSOCK_MAX_EVENT; count++)
989 {
990 if ((flags & (1 << count)) != 0)
991 {
992 m_cbacks[count] = callback;
993 m_data[count] = cdata;
994 }
995 }
996 }
997
998 /* GSocket_UnsetCallback:
999 * Disables all callbacks specified by 'flags', which may be a
1000 * combination of flags OR'ed toghether.
1001 */
1002 void GSocket::UnsetCallback(GSocketEventFlags flags)
1003 {
1004 int count;
1005
1006 assert(this);
1007
1008 for (count = 0; count < GSOCK_MAX_EVENT; count++)
1009 {
1010 if ((flags & (1 << count)) != 0)
1011 {
1012 m_cbacks[count] = NULL;
1013 m_data[count] = NULL;
1014 }
1015 }
1016 }
1017
1018 GSocketError GSocket::GetSockOpt(int level, int optname,
1019 void *optval, int *optlen)
1020 {
1021 if (getsockopt(m_fd, level, optname, (char*)optval, optlen) == 0)
1022 {
1023 return GSOCK_NOERROR;
1024 }
1025 return GSOCK_OPTERR;
1026 }
1027
1028 GSocketError GSocket::SetSockOpt(int level, int optname,
1029 const void *optval, int optlen)
1030 {
1031 if (setsockopt(m_fd, level, optname, (char*)optval, optlen) == 0)
1032 {
1033 return GSOCK_NOERROR;
1034 }
1035 return GSOCK_OPTERR;
1036 }
1037
1038 /* Internals (IO) */
1039
1040 /* _GSocket_Input_Timeout:
1041 * For blocking sockets, wait until data is available or
1042 * until timeout ellapses.
1043 */
1044 GSocketError GSocket::Input_Timeout()
1045 {
1046 fd_set readfds;
1047
1048 if (!m_non_blocking)
1049 {
1050 FD_ZERO(&readfds);
1051 FD_SET(m_fd, &readfds);
1052 if (select(0, &readfds, NULL, NULL, &m_timeout) == 0)
1053 {
1054 m_error = GSOCK_TIMEDOUT;
1055 return GSOCK_TIMEDOUT;
1056 }
1057 }
1058 return GSOCK_NOERROR;
1059 }
1060
1061 /* _GSocket_Output_Timeout:
1062 * For blocking sockets, wait until data can be sent without
1063 * blocking or until timeout ellapses.
1064 */
1065 GSocketError GSocket::Output_Timeout()
1066 {
1067 fd_set writefds;
1068
1069 if (!m_non_blocking)
1070 {
1071 FD_ZERO(&writefds);
1072 FD_SET(m_fd, &writefds);
1073 if (select(0, NULL, &writefds, NULL, &m_timeout) == 0)
1074 {
1075 m_error = GSOCK_TIMEDOUT;
1076 return GSOCK_TIMEDOUT;
1077 }
1078 }
1079 return GSOCK_NOERROR;
1080 }
1081
1082 /* _GSocket_Connect_Timeout:
1083 * For blocking sockets, wait until the connection is
1084 * established or fails, or until timeout ellapses.
1085 */
1086 GSocketError GSocket::Connect_Timeout()
1087 {
1088 fd_set writefds;
1089 fd_set exceptfds;
1090
1091 FD_ZERO(&writefds);
1092 FD_ZERO(&exceptfds);
1093 FD_SET(m_fd, &writefds);
1094 FD_SET(m_fd, &exceptfds);
1095 if (select(0, NULL, &writefds, &exceptfds, &m_timeout) == 0)
1096 {
1097 m_error = GSOCK_TIMEDOUT;
1098 return GSOCK_TIMEDOUT;
1099 }
1100 if (!FD_ISSET(m_fd, &writefds))
1101 {
1102 m_error = GSOCK_IOERR;
1103 return GSOCK_IOERR;
1104 }
1105
1106 return GSOCK_NOERROR;
1107 }
1108
1109 int GSocket::Recv_Stream(char *buffer, int size)
1110 {
1111 return recv(m_fd, buffer, size, 0);
1112 }
1113
1114 int GSocket::Recv_Dgram(char *buffer, int size)
1115 {
1116 struct sockaddr from;
1117 SOCKLEN_T fromlen = sizeof(from);
1118 int ret;
1119 GSocketError err;
1120
1121 ret = recvfrom(m_fd, buffer, size, 0, &from, &fromlen);
1122
1123 if (ret == SOCKET_ERROR)
1124 return SOCKET_ERROR;
1125
1126 /* Translate a system address into a GSocket address */
1127 if (!m_peer)
1128 {
1129 m_peer = GAddress_new();
1130 if (!m_peer)
1131 {
1132 m_error = GSOCK_MEMERR;
1133 return -1;
1134 }
1135 }
1136 err = _GAddress_translate_from(m_peer, &from, fromlen);
1137 if (err != GSOCK_NOERROR)
1138 {
1139 GAddress_destroy(m_peer);
1140 m_peer = NULL;
1141 m_error = err;
1142 return -1;
1143 }
1144
1145 return ret;
1146 }
1147
1148 int GSocket::Send_Stream(const char *buffer, int size)
1149 {
1150 return send(m_fd, buffer, size, 0);
1151 }
1152
1153 int GSocket::Send_Dgram(const char *buffer, int size)
1154 {
1155 struct sockaddr *addr;
1156 int len, ret;
1157 GSocketError err;
1158
1159 if (!m_peer)
1160 {
1161 m_error = GSOCK_INVADDR;
1162 return -1;
1163 }
1164
1165 err = _GAddress_translate_to(m_peer, &addr, &len);
1166 if (err != GSOCK_NOERROR)
1167 {
1168 m_error = err;
1169 return -1;
1170 }
1171
1172 ret = sendto(m_fd, buffer, size, 0, addr, len);
1173
1174 /* Frees memory allocated by _GAddress_translate_to */
1175 free(addr);
1176
1177 return ret;
1178 }
1179
1180 /* Compatibility functions for GSocket */
1181 GSocket *GSocket_new(void)
1182 {
1183 GSocket *newsocket = new GSocket();
1184 if(newsocket->IsOk())
1185 return newsocket;
1186 delete newsocket;
1187 return NULL;
1188 }
1189
1190
1191 /*
1192 * -------------------------------------------------------------------------
1193 * GAddress
1194 * -------------------------------------------------------------------------
1195 */
1196
1197 /* CHECK_ADDRESS verifies that the current address family is either
1198 * GSOCK_NOFAMILY or GSOCK_*family*, and if it is GSOCK_NOFAMILY, it
1199 * initalizes it to be a GSOCK_*family*. In other cases, it returns
1200 * an appropiate error code.
1201 *
1202 * CHECK_ADDRESS_RETVAL does the same but returning 'retval' on error.
1203 */
1204 #define CHECK_ADDRESS(address, family) \
1205 { \
1206 if (address->m_family == GSOCK_NOFAMILY) \
1207 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1208 return address->m_error; \
1209 if (address->m_family != GSOCK_##family) \
1210 { \
1211 address->m_error = GSOCK_INVADDR; \
1212 return GSOCK_INVADDR; \
1213 } \
1214 }
1215
1216 #define CHECK_ADDRESS_RETVAL(address, family, retval) \
1217 { \
1218 if (address->m_family == GSOCK_NOFAMILY) \
1219 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1220 return retval; \
1221 if (address->m_family != GSOCK_##family) \
1222 { \
1223 address->m_error = GSOCK_INVADDR; \
1224 return retval; \
1225 } \
1226 }
1227
1228
1229 GAddress *GAddress_new(void)
1230 {
1231 GAddress *address;
1232
1233 if ((address = (GAddress *) malloc(sizeof(GAddress))) == NULL)
1234 return NULL;
1235
1236 address->m_family = GSOCK_NOFAMILY;
1237 address->m_addr = NULL;
1238 address->m_len = 0;
1239
1240 return address;
1241 }
1242
1243 GAddress *GAddress_copy(GAddress *address)
1244 {
1245 GAddress *addr2;
1246
1247 assert(address != NULL);
1248
1249 if ((addr2 = (GAddress *) malloc(sizeof(GAddress))) == NULL)
1250 return NULL;
1251
1252 memcpy(addr2, address, sizeof(GAddress));
1253
1254 if (address->m_addr)
1255 {
1256 addr2->m_addr = (struct sockaddr *) malloc(addr2->m_len);
1257 if (addr2->m_addr == NULL)
1258 {
1259 free(addr2);
1260 return NULL;
1261 }
1262 memcpy(addr2->m_addr, address->m_addr, addr2->m_len);
1263 }
1264
1265 return addr2;
1266 }
1267
1268 void GAddress_destroy(GAddress *address)
1269 {
1270 assert(address != NULL);
1271
1272 if (address->m_addr)
1273 free(address->m_addr);
1274
1275 free(address);
1276 }
1277
1278 void GAddress_SetFamily(GAddress *address, GAddressType type)
1279 {
1280 assert(address != NULL);
1281
1282 address->m_family = type;
1283 }
1284
1285 GAddressType GAddress_GetFamily(GAddress *address)
1286 {
1287 assert(address != NULL);
1288
1289 return address->m_family;
1290 }
1291
1292 GSocketError _GAddress_translate_from(GAddress *address,
1293 struct sockaddr *addr, int len)
1294 {
1295 address->m_realfamily = addr->sa_family;
1296 switch (addr->sa_family)
1297 {
1298 case AF_INET:
1299 address->m_family = GSOCK_INET;
1300 break;
1301 case AF_UNIX:
1302 address->m_family = GSOCK_UNIX;
1303 break;
1304 #ifdef AF_INET6
1305 case AF_INET6:
1306 address->m_family = GSOCK_INET6;
1307 break;
1308 #endif
1309 default:
1310 {
1311 address->m_error = GSOCK_INVOP;
1312 return GSOCK_INVOP;
1313 }
1314 }
1315
1316 if (address->m_addr)
1317 free(address->m_addr);
1318
1319 address->m_len = len;
1320 address->m_addr = (struct sockaddr *) malloc(len);
1321
1322 if (address->m_addr == NULL)
1323 {
1324 address->m_error = GSOCK_MEMERR;
1325 return GSOCK_MEMERR;
1326 }
1327 memcpy(address->m_addr, addr, len);
1328
1329 return GSOCK_NOERROR;
1330 }
1331
1332 GSocketError _GAddress_translate_to(GAddress *address,
1333 struct sockaddr **addr, int *len)
1334 {
1335 if (!address->m_addr)
1336 {
1337 address->m_error = GSOCK_INVADDR;
1338 return GSOCK_INVADDR;
1339 }
1340
1341 *len = address->m_len;
1342 *addr = (struct sockaddr *) malloc(address->m_len);
1343 if (*addr == NULL)
1344 {
1345 address->m_error = GSOCK_MEMERR;
1346 return GSOCK_MEMERR;
1347 }
1348
1349 memcpy(*addr, address->m_addr, address->m_len);
1350 return GSOCK_NOERROR;
1351 }
1352
1353 /*
1354 * -------------------------------------------------------------------------
1355 * Internet address family
1356 * -------------------------------------------------------------------------
1357 */
1358
1359 GSocketError _GAddress_Init_INET(GAddress *address)
1360 {
1361 address->m_len = sizeof(struct sockaddr_in);
1362 address->m_addr = (struct sockaddr *) malloc(address->m_len);
1363 if (address->m_addr == NULL)
1364 {
1365 address->m_error = GSOCK_MEMERR;
1366 return GSOCK_MEMERR;
1367 }
1368
1369 address->m_family = GSOCK_INET;
1370 address->m_realfamily = AF_INET;
1371 ((struct sockaddr_in *)address->m_addr)->sin_family = AF_INET;
1372 ((struct sockaddr_in *)address->m_addr)->sin_addr.s_addr = INADDR_ANY;
1373
1374 return GSOCK_NOERROR;
1375 }
1376
1377 GSocketError GAddress_INET_SetHostName(GAddress *address, const char *hostname)
1378 {
1379 struct hostent *he;
1380 struct in_addr *addr;
1381
1382 assert(address != NULL);
1383
1384 CHECK_ADDRESS(address, INET);
1385
1386 addr = &(((struct sockaddr_in *)address->m_addr)->sin_addr);
1387
1388 addr->s_addr = inet_addr(hostname);
1389
1390 /* If it is a numeric host name, convert it now */
1391 if (addr->s_addr == INADDR_NONE)
1392 {
1393 struct in_addr *array_addr;
1394
1395 /* It is a real name, we solve it */
1396 if ((he = gethostbyname(hostname)) == NULL)
1397 {
1398 /* addr->s_addr = INADDR_NONE just done by inet_addr() above */
1399 address->m_error = GSOCK_NOHOST;
1400 return GSOCK_NOHOST;
1401 }
1402 array_addr = (struct in_addr *) *(he->h_addr_list);
1403 addr->s_addr = array_addr[0].s_addr;
1404 }
1405 return GSOCK_NOERROR;
1406 }
1407
1408 GSocketError GAddress_INET_SetAnyAddress(GAddress *address)
1409 {
1410 return GAddress_INET_SetHostAddress(address, INADDR_ANY);
1411 }
1412
1413 GSocketError GAddress_INET_SetHostAddress(GAddress *address,
1414 unsigned long hostaddr)
1415 {
1416 struct in_addr *addr;
1417
1418 assert(address != NULL);
1419
1420 CHECK_ADDRESS(address, INET);
1421
1422 addr = &(((struct sockaddr_in *)address->m_addr)->sin_addr);
1423 addr->s_addr = htonl(hostaddr);;
1424
1425 return GSOCK_NOERROR;
1426 }
1427
1428 GSocketError GAddress_INET_SetPortName(GAddress *address, const char *port,
1429 const char *protocol)
1430 {
1431 struct servent *se;
1432 struct sockaddr_in *addr;
1433
1434 assert(address != NULL);
1435 CHECK_ADDRESS(address, INET);
1436
1437 if (!port)
1438 {
1439 address->m_error = GSOCK_INVPORT;
1440 return GSOCK_INVPORT;
1441 }
1442
1443 se = getservbyname(port, protocol);
1444 if (!se)
1445 {
1446 if (isdigit(port[0]))
1447 {
1448 int port_int;
1449
1450 port_int = atoi(port);
1451 addr = (struct sockaddr_in *)address->m_addr;
1452 addr->sin_port = htons((u_short) port_int);
1453 return GSOCK_NOERROR;
1454 }
1455
1456 address->m_error = GSOCK_INVPORT;
1457 return GSOCK_INVPORT;
1458 }
1459
1460 addr = (struct sockaddr_in *)address->m_addr;
1461 addr->sin_port = se->s_port;
1462
1463 return GSOCK_NOERROR;
1464 }
1465
1466 GSocketError GAddress_INET_SetPort(GAddress *address, unsigned short port)
1467 {
1468 struct sockaddr_in *addr;
1469
1470 assert(address != NULL);
1471 CHECK_ADDRESS(address, INET);
1472
1473 addr = (struct sockaddr_in *)address->m_addr;
1474 addr->sin_port = htons(port);
1475
1476 return GSOCK_NOERROR;
1477 }
1478
1479 GSocketError GAddress_INET_GetHostName(GAddress *address, char *hostname, size_t sbuf)
1480 {
1481 struct hostent *he;
1482 char *addr_buf;
1483 struct sockaddr_in *addr;
1484
1485 assert(address != NULL);
1486 CHECK_ADDRESS(address, INET);
1487
1488 addr = (struct sockaddr_in *)address->m_addr;
1489 addr_buf = (char *)&(addr->sin_addr);
1490
1491 he = gethostbyaddr(addr_buf, sizeof(addr->sin_addr), AF_INET);
1492 if (he == NULL)
1493 {
1494 address->m_error = GSOCK_NOHOST;
1495 return GSOCK_NOHOST;
1496 }
1497
1498 strncpy(hostname, he->h_name, sbuf);
1499
1500 return GSOCK_NOERROR;
1501 }
1502
1503 unsigned long GAddress_INET_GetHostAddress(GAddress *address)
1504 {
1505 struct sockaddr_in *addr;
1506
1507 assert(address != NULL);
1508 CHECK_ADDRESS_RETVAL(address, INET, 0);
1509
1510 addr = (struct sockaddr_in *)address->m_addr;
1511
1512 return ntohl(addr->sin_addr.s_addr);
1513 }
1514
1515 unsigned short GAddress_INET_GetPort(GAddress *address)
1516 {
1517 struct sockaddr_in *addr;
1518
1519 assert(address != NULL);
1520 CHECK_ADDRESS_RETVAL(address, INET, 0);
1521
1522 addr = (struct sockaddr_in *)address->m_addr;
1523 return ntohs(addr->sin_port);
1524 }
1525
1526 /*
1527 * -------------------------------------------------------------------------
1528 * Unix address family
1529 * -------------------------------------------------------------------------
1530 */
1531
1532 GSocketError _GAddress_Init_UNIX(GAddress *address)
1533 {
1534 assert (address != NULL);
1535 address->m_error = GSOCK_INVADDR;
1536 return GSOCK_INVADDR;
1537 }
1538
1539 GSocketError GAddress_UNIX_SetPath(GAddress *address, const char *WXUNUSED(path))
1540 {
1541 assert (address != NULL);
1542 address->m_error = GSOCK_INVADDR;
1543 return GSOCK_INVADDR;
1544 }
1545
1546 GSocketError GAddress_UNIX_GetPath(GAddress *address, char *WXUNUSED(path), size_t WXUNUSED(sbuf))
1547 {
1548 assert (address != NULL);
1549 address->m_error = GSOCK_INVADDR;
1550 return GSOCK_INVADDR;
1551 }
1552
1553 #else /* !wxUSE_SOCKETS */
1554
1555 /*
1556 * Translation unit shouldn't be empty, so include this typedef to make the
1557 * compiler (VC++ 6.0, for example) happy
1558 */
1559 typedef void (*wxDummy)();
1560
1561 #endif /* wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__) */
1562