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