]>
git.saurik.com Git - wxWidgets.git/blob - src/common/socket.cpp
1 ////////////////////////////////////////////////////////////////////////////////
3 // Purpose: Socket handler classes
4 // Authors: Guilhem Lavaux (completely rewritten from a basic API of Andrew
5 // Davidson(1995) in wxWeb)
8 // Copyright: (C) 1999 1998, 1997, Guilhem Lavaux
10 // License: see wxWindows license
11 ////////////////////////////////////////////////////////////////////////////////
13 #pragma implementation "socket.h"
17 typedef int socklen_t
;
20 // For compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
29 /////////////////////////////////////////////////////////////////////////////
31 /////////////////////////////////////////////////////////////////////////////
33 #include <wx/object.h>
34 #include <wx/string.h>
38 // Not enough OS behaviour defined for wxStubs
45 /////////////////////////////////////////////////////////////////////////////
46 // System specific headers
47 /////////////////////////////////////////////////////////////////////////////
49 // in order to avoid problems with our c library and double definitions
50 #define close closesocket
51 #define ioctl ioctlsocket
53 #include <wx/mac/macsock.h>
57 #if defined(__WINDOWS__)
66 #include <sys/socket.h>
68 #include <sys/ioctl.h>
74 #include <sys/filio.h>
86 /////////////////////////////////////////////////////////////////////////////
88 /////////////////////////////////////////////////////////////////////////////
89 #include <wx/module.h>
90 #define WXSOCK_INTERNAL
91 #include <wx/sckaddr.h>
92 #include <wx/socket.h>
93 #include <wx/sckint.h>
95 // ----------------------
96 // Some patch ----- BEGIN
97 // ----------------------
99 #define close closesocket
100 #define ioctl ioctlsocket
104 #define errno WSAGetLastError()
108 #define EWOULDBLOCK WSAEWOULDBLOCK
109 #define ETIMEDOUT WSAETIMEDOUT
111 #define EINTR WSAEINTR
115 #define INVALID_SOCKET -1
119 // This is an MS TCP/IP routine and is not needed here. Some WinSock
120 // implementations (such as PC-NFS) will require you to include this
121 // or a similar routine (see appendix in WinSock doc or help file).
123 #if defined( NEED_WSAFDIsSet ) || defined( __VISUALC__ )
124 int PASCAL FAR
__WSAFDIsSet(SOCKET fd
, fd_set FAR
*set
)
126 int i
= set
->fd_count
;
130 if (set
->fd_array
[i
] == fd
)
139 // -------------------
140 // Some patch ---- END
141 // -------------------
147 // --------------------------------------------------------------
149 // --------------------------------------------------------------
150 class wxSocketModule
: public wxModule
152 DECLARE_DYNAMIC_CLASS(wxSocketModule
)
159 // --------------------------------------------------------------
161 // --------------------------------------------------------------
162 #if !USE_SHARED_LIBRARY
163 IMPLEMENT_CLASS(wxSocketBase
, wxObject
)
164 IMPLEMENT_CLASS(wxSocketServer
, wxSocketBase
)
165 IMPLEMENT_CLASS(wxSocketClient
, wxSocketBase
)
166 IMPLEMENT_CLASS(wxSocketHandler
, wxObject
)
167 IMPLEMENT_DYNAMIC_CLASS(wxSocketEvent
, wxEvent
)
168 IMPLEMENT_DYNAMIC_CLASS(wxSocketModule
, wxModule
)
171 // --------------------------------------------------------------
172 // --------- wxSocketBase CONSTRUCTOR ---------------------------
173 // --------------------------------------------------------------
174 wxSocketBase::wxSocketBase(wxSocketBase::wxSockFlags _flags
,
175 wxSocketBase::wxSockType _type
) :
177 m_flags(_flags
), m_type(_type
), m_connected(FALSE
), m_connecting(FALSE
),
178 m_fd(INVALID_SOCKET
), m_id(-1),
180 m_neededreq((wxRequestNotify
)(REQ_READ
| REQ_LOST
)),
182 m_unread(NULL
), m_unrd_size(0),
183 m_cbk(NULL
), m_cdata(NULL
),
184 m_notify_state(FALSE
)
186 m_internal
= new wxSocketInternal(this);
189 wxSocketBase::wxSocketBase() :
191 m_flags(WAITALL
), m_type(SOCK_UNINIT
), m_connected(FALSE
),
192 m_connecting(FALSE
), m_fd(INVALID_SOCKET
),
193 m_id(-1), m_handler(0),
194 m_neededreq((wxRequestNotify
)(REQ_READ
| REQ_LOST
)),
196 m_unread(NULL
), m_unrd_size(0),
197 m_cbk(NULL
), m_cdata(NULL
),
198 m_notify_state(FALSE
)
200 m_internal
= new wxSocketInternal(this);
203 // --------------------------------------------------------------
205 // --------------------------------------------------------------
207 wxSocketBase::~wxSocketBase()
209 // First, close the file descriptor.
214 // Unregister from the handler database.
216 m_handler
->UnRegister(this);
218 // Destroy all saved states.
219 m_states
.DeleteContents(TRUE
);
221 // Destroy the socket manager.
225 bool wxSocketBase::Close()
227 if (m_fd
!= INVALID_SOCKET
)
229 if (m_notify_state
== TRUE
)
232 // Shutdown the connection.
235 m_fd
= INVALID_SOCKET
;
242 // --------------------------------------------------------------
243 // wxSocketBase base IO function
244 // --------------------------------------------------------------
246 wxSocketBase
& wxSocketBase::Read(char* buffer
, size_t nbytes
)
248 m_lcount
= GetPushback(buffer
, nbytes
, FALSE
);
252 // If we have got the whole needed buffer or if we don't want to
253 // wait then it returns immediately.
254 if (!nbytes
|| (m_lcount
&& !(m_flags
& WAITALL
)) ) {
258 WantBuffer(buffer
, nbytes
, EVT_READ
);
263 wxSocketBase
& wxSocketBase::Peek(char* buffer
, size_t nbytes
)
265 m_lcount
= GetPushback(buffer
, nbytes
, TRUE
);
266 if (nbytes
-m_lcount
== 0)
273 WantBuffer(buffer
, nbytes
, EVT_PEEK
);
278 wxSocketBase
& wxSocketBase::Write(const char *buffer
, size_t nbytes
)
281 WantBuffer((char *)buffer
, nbytes
, EVT_WRITE
);
285 wxSocketBase
& wxSocketBase::Unread(const char *buffer
, size_t nbytes
)
287 CreatePushbackAfter(buffer
, nbytes
);
291 bool wxSocketBase::IsData() const
301 m_internal
->AcquireFD();
306 FD_SET(m_fd
, &sock_set
);
307 select(FD_SETSIZE
, &sock_set
, NULL
, NULL
, &tv
);
309 m_internal
->ReleaseFD();
311 return (FD_ISSET(m_fd
, &sock_set
) != 0);
314 // ---------------------------------------------------------------------
315 // --------- wxSocketBase Discard(): deletes all byte in the input queue
316 // ---------------------------------------------------------------------
317 void wxSocketBase::Discard()
319 #define MAX_BUFSIZE (10*1024)
320 char *my_data
= new char[MAX_BUFSIZE
];
321 size_t recv_size
= MAX_BUFSIZE
;
324 SetFlags((wxSockFlags
)(NOWAIT
| SPEED
));
326 while (recv_size
== MAX_BUFSIZE
)
328 recv_size
= Read(my_data
, MAX_BUFSIZE
).LastCount();
337 // If what? Who seems to need unsigned int?
338 // BTW uint isn't even defined on wxMSW for VC++ for some reason. Even if it
339 // were, getpeername/getsockname don't take unsigned int*, they take int*.
341 // Under glibc 2.0.7, socketbits.h declares socklen_t to be unsigned int
342 // and it uses *socklen_t as the 3rd parameter. Robert.
344 // JACS - How can we detect this?
345 // Meanwhile, if your compiler complains about socklen_t,
346 // switch lines below.
349 # define wxSOCKET_INT socklen_t
351 # define wxSOCKET_INT int
354 // --------------------------------------------------------------
355 // wxSocketBase socket info functions
356 // --------------------------------------------------------------
358 bool wxSocketBase::GetPeer(wxSockAddress
& addr_man
) const
360 struct sockaddr my_addr
;
361 wxSOCKET_INT len_addr
= sizeof(my_addr
);
366 m_internal
->AcquireFD();
368 if (getpeername(m_fd
, (struct sockaddr
*)&my_addr
, &len_addr
) < 0) {
369 m_internal
->ReleaseFD();
373 m_internal
->ReleaseFD();
374 addr_man
.Disassemble(&my_addr
, len_addr
);
378 bool wxSocketBase::GetLocal(wxSockAddress
& addr_man
) const
380 struct sockaddr my_addr
;
381 wxSOCKET_INT len_addr
= sizeof(my_addr
);
386 m_internal
->AcquireFD();
388 if (getsockname(m_fd
, (struct sockaddr
*)&my_addr
, &len_addr
) < 0) {
389 m_internal
->ReleaseFD();
392 m_internal
->ReleaseFD();
394 addr_man
.Disassemble(&my_addr
, len_addr
);
398 // --------------------------------------------------------------
399 // wxSocketBase wait functions
400 // --------------------------------------------------------------
402 void wxSocketBase::SaveState()
404 SocketState
*state
= new SocketState
;
406 state
->notify_state
= m_notify_state
;
407 state
->evt_notify_state
= m_neededreq
;
408 state
->socket_flags
= m_flags
;
409 state
->c_callback
= m_cbk
;
410 state
->c_callback_data
= m_cdata
;
412 m_states
.Append((wxObject
*)state
);
415 void wxSocketBase::RestoreState()
420 node
= m_states
.Last();
424 state
= (SocketState
*)node
->Data();
426 SetFlags(state
->socket_flags
);
427 m_neededreq
= state
->evt_notify_state
;
428 m_cbk
= state
->c_callback
;
429 m_cdata
= state
->c_callback_data
;
430 Notify(state
->notify_state
);
436 // --------------------------------------------------------------
437 // --------- wxSocketBase callback functions --------------------
438 // --------------------------------------------------------------
440 wxSocketBase::wxSockCbk
wxSocketBase::Callback(wxSockCbk cbk_
)
442 wxSockCbk old_cbk
= cbk_
;
448 char *wxSocketBase::CallbackData(char *data
)
450 char *old_data
= m_cdata
;
456 // --------------------------------------------------------------
457 // --------- wxSocketBase wait functions ------------------------
458 // --------------------------------------------------------------
460 bool wxSocketBase::_Wait(long seconds
, long milliseconds
, int type
)
464 if ((!m_connected
&& !m_connecting
) || m_fd
< 0)
467 req
= new SockRequest
;
469 req
->type
= REQ_WAIT
| type
;
470 req
->timeout
= seconds
* 1000 + milliseconds
;
476 m_internal
->QueueRequest(req
, TRUE
);
478 return (req
->io_nbytes
!= 0);
481 bool wxSocketBase::Wait(long seconds
, long milliseconds
)
483 return _Wait(seconds
, milliseconds
, REQ_ACCEPT
| REQ_CONNECT
|
484 REQ_READ
| REQ_WRITE
| REQ_LOST
);
487 bool wxSocketBase::WaitForRead(long seconds
, long milliseconds
)
489 return _Wait(seconds
, milliseconds
, REQ_READ
| REQ_LOST
);
492 bool wxSocketBase::WaitForWrite(long seconds
, long milliseconds
)
494 return _Wait(seconds
, milliseconds
, REQ_WRITE
);
497 bool wxSocketBase::WaitForLost(long seconds
, long milliseconds
)
499 return _Wait(seconds
, milliseconds
, REQ_LOST
);
502 // --------------------------------------------------------------
503 // --------- wxSocketBase callback management -------------------
504 // --------------------------------------------------------------
506 wxSocketBase::wxRequestNotify
wxSocketBase::EventToNotify(wxRequestEvent evt
)
526 void wxSocketBase::SetFlags(wxSockFlags _flags
)
529 if (_flags
& SPEED
) {
530 // SPEED and WAITALL are antagonists.
531 m_flags
= (wxSockFlags
)(m_flags
& ~WAITALL
);
535 wxSocketBase::wxSockFlags
wxSocketBase::GetFlags() const
540 void wxSocketBase::SetNotify(wxRequestNotify flags
)
542 /* Check if server */
543 if (m_type
!= SOCK_SERVER
)
544 flags
&= ~REQ_ACCEPT
;
546 m_internal
->AcquireData();
548 m_internal
->ReleaseData();
549 if (m_neededreq
== 0)
550 m_internal
->StopWaiter();
552 Notify(m_notify_state
);
555 void wxSocketBase::Notify(bool notify
)
557 m_notify_state
= notify
;
558 if (m_fd
== INVALID_SOCKET
)
562 m_internal
->ResumeWaiter();
564 m_internal
->StopWaiter();
567 void wxSocketBase::OnRequest(wxRequestEvent req_evt
)
569 wxSocketEvent
event(m_id
);
570 wxRequestNotify notify
= EventToNotify(req_evt
);
572 if ((m_neededreq
& notify
) == notify
) {
573 event
.m_socket
= this;
574 event
.m_skevt
= req_evt
;
577 // OldOnNotify(req_evt);
579 // We disable the event reporting.
580 m_neededreq
&= ~notify
;
584 wxSocketEvent::wxSocketEvent(int id
)
587 wxEventType type
= (wxEventType
)wxEVT_SOCKET
;
592 void wxSocketEvent::CopyObject(wxObject
& obj_d
) const
594 wxSocketEvent
*event
= (wxSocketEvent
*)&obj_d
;
596 wxEvent::CopyObject(obj_d
);
598 event
->m_skevt
= m_skevt
;
599 event
->m_socket
= m_socket
;
602 void wxSocketBase::OldOnNotify(wxRequestEvent evt
)
606 // --------------------------------------------------------------
607 // --------- wxSocketBase functions [Callback, CallbackData] ----
608 // --------------------------------------------------------------
610 void wxSocketBase::SetEventHandler(wxEvtHandler
& h_evt
, int id
)
612 SetNextHandler(&h_evt
);
616 // --------------------------------------------------------------
617 // --------- wxSocketBase pushback library ----------------------
618 // --------------------------------------------------------------
620 void wxSocketBase::CreatePushbackAfter(const char *buffer
, size_t size
)
624 if (m_unread
!= NULL
)
625 m_unread
= (char *) realloc(m_unread
, m_unrd_size
+size
);
627 m_unread
= (char *) malloc(size
);
628 curr_pos
= m_unread
+ m_unrd_size
;
630 memcpy(curr_pos
, buffer
, size
);
634 void wxSocketBase::CreatePushbackBefore(const char *buffer
, size_t size
)
636 char *curr_pos
, *new_buf
;
638 new_buf
= (char *) malloc(m_unrd_size
+size
);
639 curr_pos
= new_buf
+ size
;
641 memcpy(new_buf
, buffer
, size
);
642 if (m_unrd_size
!= 0) {
643 memcpy(curr_pos
, m_unread
, m_unrd_size
);
650 size_t wxSocketBase::GetPushback(char *buffer
, size_t size
, bool peek
)
655 if (size
> m_unrd_size
)
657 memcpy(buffer
, m_unread
, size
);
661 if (m_unrd_size
== 0) {
670 // --------------------------------------------------------------
671 // --------- wxSocketBase buffer core requester -----------------
672 // --------------------------------------------------------------
674 void wxSocketBase::WantBuffer(char *buffer
, size_t nbytes
,
679 if (m_fd
== INVALID_SOCKET
|| !m_handler
|| !m_connected
)
682 SockRequest
*buf
= new SockRequest
;
685 m_internal
->StopWaiter();
686 buf
->buffer
= buffer
;
689 buf
->type
= EventToNotify(evt
);
694 buf_timed_out
= FALSE
;
696 if ((m_flags
& SPEED
) != 0)
697 m_internal
->QueueRequest(buf
, FALSE
);
699 if ((m_flags
& NOWAIT
) != 0)
700 m_internal
->QueueRequest(buf
, TRUE
);
702 m_internal
->QueueRequest(buf
, TRUE
);
703 m_lcount
+= buf
->io_nbytes
;
707 m_error
= buf
->error
;
713 // --------------------------------------------------------------
715 // --------------------------------------------------------------
717 wxSocketServer::wxSocketServer(wxSockAddress
& addr_man
,
719 wxSocketBase(flags
, SOCK_SERVER
)
721 m_fd
= socket(addr_man
.GetFamily(), SOCK_STREAM
, 0);
723 if (m_fd
== INVALID_SOCKET
)
727 setsockopt(m_fd
, SOL_SOCKET
, SO_REUSEADDR
, (char*)&flag
, sizeof(int));
729 struct sockaddr
*myaddr
;
732 addr_man
.Build(myaddr
, len
);
733 if (bind(m_fd
, myaddr
, addr_man
.SockAddrLen()) < 0)
736 if (listen(m_fd
, 5) < 0) {
737 m_fd
= INVALID_SOCKET
;
741 m_internal
->SetFD(m_fd
);
746 // --------------------------------------------------------------
747 // wxSocketServer Accept
748 // --------------------------------------------------------------
750 bool wxSocketServer::AcceptWith(wxSocketBase
& sock
)
754 m_internal
->AcquireFD();
755 if ((fd2
= accept(m_fd
, 0, 0)) < 0) {
756 m_internal
->ReleaseFD();
759 m_internal
->ReleaseFD();
761 struct linger linger
;
765 setsockopt(fd2
, SOL_SOCKET
, SO_LINGER
, (char*)&linger
, sizeof(linger
));
768 setsockopt(fd2
, SOL_SOCKET
, SO_KEEPALIVE
, (char*)&flag
, sizeof(int));
770 sock
.m_type
= SOCK_INTERNAL
;
772 sock
.m_connected
= TRUE
;
774 sock
.m_internal
->SetFD(fd2
);
776 sock
.m_internal
->ResumeWaiter();
781 wxSocketBase
*wxSocketServer::Accept()
783 wxSocketBase
* sock
= new wxSocketBase();
785 sock
->SetFlags((wxSockFlags
)m_flags
);
787 if (!AcceptWith(*sock
))
791 m_handler
->Register(sock
);
796 // --------------------------------------------------------------
798 // --------------------------------------------------------------
800 // --------- wxSocketClient CONSTRUCTOR -------------------------
801 // --------------------------------------------------------------
802 wxSocketClient::wxSocketClient(wxSockFlags _flags
) :
803 wxSocketBase(_flags
, SOCK_CLIENT
)
807 // --------------------------------------------------------------
808 // --------- wxSocketClient DESTRUCTOR --------------------------
809 // --------------------------------------------------------------
810 wxSocketClient::~wxSocketClient()
814 // --------------------------------------------------------------
815 // --------- wxSocketClient Connect functions -------------------
816 // --------------------------------------------------------------
817 bool wxSocketClient::Connect(wxSockAddress
& addr_man
, bool WXUNUSED(wait
) )
819 struct linger linger
;
824 // Initializes all socket stuff ...
825 // --------------------------------
826 m_fd
= socket(addr_man
.GetFamily(), SOCK_STREAM
, 0);
835 setsockopt(m_fd
, SOL_SOCKET
, SO_LINGER
, (char*)&linger
, sizeof(linger
));
837 // Stay in touch with the state of things...
839 unsigned long flag
= 1;
840 setsockopt(m_fd
, SOL_SOCKET
, SO_KEEPALIVE
, (char*)&flag
, sizeof(int));
842 // Disable the nagle algorithm, which delays sends till the
843 // buffer is full (or a certain time period has passed?)...
845 #if defined(__WINDOWS__) || (defined(IPPROTO_TCP) && defined(TCP_NODELAY))
847 setsockopt(m_fd
, IPPROTO_TCP
, TCP_NODELAY
, (char*)&flag
, sizeof(int));
850 struct sockaddr
*remote
;
853 addr_man
.Build(remote
, len
);
855 if (connect(m_fd
, remote
, len
) != 0)
858 m_internal
->SetFD(m_fd
);
860 // Enables bg events.
861 // ------------------
868 bool wxSocketClient::WaitOnConnect(long seconds
, long microseconds
)
870 int ret
= _Wait(seconds
, microseconds
, REQ_CONNECT
| REQ_LOST
);
878 void wxSocketClient::OnRequest(wxRequestEvent evt
)
880 if (evt
== EVT_CONNECT
)
884 m_neededreq
&= ~REQ_CONNECT
;
890 wxSocketBase::OnRequest(evt
);
893 /////////////////////////////////////////////////////////////////
894 // wxSocketHandler ///////////////////////////////////////////////
895 /////////////////////////////////////////////////////////////////
897 wxSocketHandler
*wxSocketHandler::master
= NULL
;
898 #if defined(__WINDOWS__)
899 static int win_initialized
= 0;
902 // --------------------------------------------------------------
903 // --------- wxSocketHandler CONSTRUCTOR ------------------------
904 // --------------------------------------------------------------
905 wxSocketHandler::wxSocketHandler()
907 #if defined(__WINDOWS__)
908 if (!win_initialized
)
912 WSAStartup((1 << 8) | 1, &wsaData
);
920 signal(SIGPIPE
, SIG_IGN
);
924 // --------------------------------------------------------------
925 // --------- wxSocketHandler DESTRUCTOR -------------------------
926 // --------------------------------------------------------------
927 wxSocketHandler::~wxSocketHandler()
929 wxNode
*next_node
, *node
= socks
->First();
933 wxSocketBase
* sock
= (wxSocketBase
*)node
->Data();
936 next_node
= node
->Next();
949 // --------------------------------------------------------------
950 // --------- wxSocketHandler registering functions --------------
951 // --------------------------------------------------------------
953 void wxSocketHandler::Register(wxSocketBase
* sock
)
957 for (node
= socks
->First(); node
!= NULL
; node
= node
->Next())
959 wxSocketBase
* s
= (wxSocketBase
*)node
->Data();
968 sock
->SetHandler(this);
972 void wxSocketHandler::UnRegister(wxSocketBase
* sock
)
976 for (node
= socks
->First(); node
; node
= node
->Next())
978 wxSocketBase
* s
= (wxSocketBase
*)node
->Data();
983 sock
->SetHandler(NULL
);
989 unsigned long wxSocketHandler::Count() const
991 return socks
->Number();
994 // --------------------------------------------------------------
995 // --------- wxSocketHandler "big" wait functions ---------------
996 // --------------------------------------------------------------
998 int wxSocketHandler::Wait(long seconds
, long microseconds
)
1000 // TODO Needs the completely asynchronous notifier.
1006 for (node = socks->First(), i=0; node; node = node->Next(), i++)
1008 wxSocketBase *sock = (wxSocketBase *)node->Data();
1012 sock->SetupCallbacks();
1014 sock->Callback(handler_cbk);
1015 sock->CallbackData((char *)&on_wait);
1019 s_wake.Start((seconds*1000) + (microseconds/1000), TRUE);
1024 for (node = socks->First(), i=0; node; node = node->Next(), i++)
1026 wxSocketBase *sock = (wxSocketBase *)node->Data();
1028 sock->RestoreState();
1039 void wxSocketHandler::YieldSock()
1043 // Nothing to do anymore here except waiting for the queue emptying.
1044 for (node
= socks
->First(); node
; node
=node
->Next()) {
1045 wxSocketBase
*sock
= (wxSocketBase
*)node
->Data();
1047 sock
->m_internal
->WaitForEnd(NULL
);
1051 // --------------------------------------------------------------
1052 // --------- wxSocketHandler: create and register the socket ----
1053 // --------------------------------------------------------------
1054 wxSocketServer
*wxSocketHandler::CreateServer(wxSockAddress
& addr
,
1055 wxSocketBase::wxSockFlags flags
)
1057 wxSocketServer
*serv
= new wxSocketServer(addr
, flags
);
1063 wxSocketClient
*wxSocketHandler::CreateClient(wxSocketBase::wxSockFlags flags
)
1065 wxSocketClient
*client
= new wxSocketClient(flags
);
1071 bool wxSocketModule::OnInit()
1073 wxSocketHandler::master
= new wxSocketHandler();
1077 void wxSocketModule::OnExit()
1079 delete wxSocketHandler::master
;
1080 wxSocketHandler::master
= NULL
;