]>
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
;
547 if (m_neededreq
== 0)
548 m_internal
->StopWaiter();
550 Notify(m_notify_state
);
553 void wxSocketBase::Notify(bool notify
)
555 m_notify_state
= notify
;
556 if (m_fd
== INVALID_SOCKET
)
560 m_internal
->ResumeWaiter();
562 m_internal
->StopWaiter();
565 void wxSocketBase::OnRequest(wxRequestEvent req_evt
)
567 wxSocketEvent
event(m_id
);
568 wxRequestNotify notify
= EventToNotify(req_evt
);
570 if ((m_neededreq
& notify
) == notify
) {
571 event
.m_socket
= this;
572 event
.m_skevt
= req_evt
;
575 // OldOnNotify(req_evt);
577 // We disable the event reporting.
578 m_neededreq
&= ~notify
;
582 wxSocketEvent::wxSocketEvent(int id
)
585 wxEventType type
= (wxEventType
)wxEVT_SOCKET
;
590 void wxSocketEvent::CopyObject(wxObject
& obj_d
) const
592 wxSocketEvent
*event
= (wxSocketEvent
*)&obj_d
;
594 wxEvent::CopyObject(obj_d
);
596 event
->m_skevt
= m_skevt
;
597 event
->m_socket
= m_socket
;
600 void wxSocketBase::OldOnNotify(wxRequestEvent evt
)
604 // --------------------------------------------------------------
605 // --------- wxSocketBase functions [Callback, CallbackData] ----
606 // --------------------------------------------------------------
608 void wxSocketBase::SetEventHandler(wxEvtHandler
& h_evt
, int id
)
610 SetNextHandler(&h_evt
);
614 // --------------------------------------------------------------
615 // --------- wxSocketBase pushback library ----------------------
616 // --------------------------------------------------------------
618 void wxSocketBase::CreatePushbackAfter(const char *buffer
, size_t size
)
622 if (m_unread
!= NULL
)
623 m_unread
= (char *) realloc(m_unread
, m_unrd_size
+size
);
625 m_unread
= (char *) malloc(size
);
626 curr_pos
= m_unread
+ m_unrd_size
;
628 memcpy(curr_pos
, buffer
, size
);
632 void wxSocketBase::CreatePushbackBefore(const char *buffer
, size_t size
)
634 char *curr_pos
, *new_buf
;
636 new_buf
= (char *) malloc(m_unrd_size
+size
);
637 curr_pos
= new_buf
+ size
;
639 memcpy(new_buf
, buffer
, size
);
640 if (m_unrd_size
!= 0) {
641 memcpy(curr_pos
, m_unread
, m_unrd_size
);
648 size_t wxSocketBase::GetPushback(char *buffer
, size_t size
, bool peek
)
653 if (size
> m_unrd_size
)
655 memcpy(buffer
, m_unread
, size
);
659 if (m_unrd_size
== 0) {
668 // --------------------------------------------------------------
669 // --------- wxSocketBase buffer core requester -----------------
670 // --------------------------------------------------------------
672 void wxSocketBase::WantBuffer(char *buffer
, size_t nbytes
,
677 if (m_fd
== INVALID_SOCKET
|| !m_handler
|| !m_connected
)
680 SockRequest
*buf
= new SockRequest
;
683 m_internal
->StopWaiter();
684 buf
->buffer
= buffer
;
687 buf
->type
= EventToNotify(evt
);
692 buf_timed_out
= FALSE
;
695 m_internal
->QueueRequest(buf
, FALSE
);
697 if (m_flags
& NOWAIT
)
698 m_internal
->QueueRequest(buf
, TRUE
);
700 m_internal
->QueueRequest(buf
, TRUE
);
701 m_lcount
+= buf
->io_nbytes
;
705 m_error
= buf
->error
;
711 // --------------------------------------------------------------
713 // --------------------------------------------------------------
715 wxSocketServer::wxSocketServer(wxSockAddress
& addr_man
,
717 wxSocketBase(flags
, SOCK_SERVER
)
719 m_fd
= socket(addr_man
.GetFamily(), SOCK_STREAM
, 0);
721 if (m_fd
== INVALID_SOCKET
)
725 setsockopt(m_fd
, SOL_SOCKET
, SO_REUSEADDR
, (char*)&flag
, sizeof(int));
727 struct sockaddr
*myaddr
;
730 addr_man
.Build(myaddr
, len
);
731 if (bind(m_fd
, myaddr
, addr_man
.SockAddrLen()) < 0)
734 if (listen(m_fd
, 5) < 0) {
735 m_fd
= INVALID_SOCKET
;
739 m_internal
->SetFD(m_fd
);
744 // --------------------------------------------------------------
745 // wxSocketServer Accept
746 // --------------------------------------------------------------
748 bool wxSocketServer::AcceptWith(wxSocketBase
& sock
)
752 m_internal
->AcquireFD();
753 if ((fd2
= accept(m_fd
, 0, 0)) < 0) {
754 m_internal
->ReleaseFD();
757 m_internal
->ReleaseFD();
759 struct linger linger
;
763 setsockopt(fd2
, SOL_SOCKET
, SO_LINGER
, (char*)&linger
, sizeof(linger
));
766 setsockopt(fd2
, SOL_SOCKET
, SO_KEEPALIVE
, (char*)&flag
, sizeof(int));
768 sock
.m_type
= SOCK_INTERNAL
;
770 sock
.m_connected
= TRUE
;
772 sock
.m_internal
->SetFD(fd2
);
774 sock
.m_internal
->ResumeWaiter();
779 wxSocketBase
*wxSocketServer::Accept()
781 wxSocketBase
* sock
= new wxSocketBase();
783 sock
->SetFlags((wxSockFlags
)m_flags
);
785 if (!AcceptWith(*sock
))
789 m_handler
->Register(sock
);
794 // --------------------------------------------------------------
796 // --------------------------------------------------------------
798 // --------- wxSocketClient CONSTRUCTOR -------------------------
799 // --------------------------------------------------------------
800 wxSocketClient::wxSocketClient(wxSockFlags _flags
) :
801 wxSocketBase(_flags
, SOCK_CLIENT
)
805 // --------------------------------------------------------------
806 // --------- wxSocketClient DESTRUCTOR --------------------------
807 // --------------------------------------------------------------
808 wxSocketClient::~wxSocketClient()
812 // --------------------------------------------------------------
813 // --------- wxSocketClient Connect functions -------------------
814 // --------------------------------------------------------------
815 bool wxSocketClient::Connect(wxSockAddress
& addr_man
, bool WXUNUSED(wait
) )
817 struct linger linger
;
822 // Initializes all socket stuff ...
823 // --------------------------------
824 m_fd
= socket(addr_man
.GetFamily(), SOCK_STREAM
, 0);
833 setsockopt(m_fd
, SOL_SOCKET
, SO_LINGER
, (char*)&linger
, sizeof(linger
));
835 // Stay in touch with the state of things...
837 unsigned long flag
= 1;
838 setsockopt(m_fd
, SOL_SOCKET
, SO_KEEPALIVE
, (char*)&flag
, sizeof(int));
840 // Disable the nagle algorithm, which delays sends till the
841 // buffer is full (or a certain time period has passed?)...
843 #if defined(__WINDOWS__) || (defined(IPPROTO_TCP) && defined(TCP_NODELAY))
845 setsockopt(m_fd
, IPPROTO_TCP
, TCP_NODELAY
, (char*)&flag
, sizeof(int));
848 struct sockaddr
*remote
;
851 addr_man
.Build(remote
, len
);
853 if (connect(m_fd
, remote
, len
) != 0)
856 m_internal
->SetFD(m_fd
);
858 // Enables bg events.
859 // ------------------
866 bool wxSocketClient::WaitOnConnect(long seconds
, long microseconds
)
868 int ret
= _Wait(seconds
, microseconds
, REQ_CONNECT
| REQ_LOST
);
876 void wxSocketClient::OnRequest(wxRequestEvent evt
)
878 if (evt
== EVT_CONNECT
)
882 m_neededreq
&= ~REQ_CONNECT
;
888 wxSocketBase::OnRequest(evt
);
891 /////////////////////////////////////////////////////////////////
892 // wxSocketHandler ///////////////////////////////////////////////
893 /////////////////////////////////////////////////////////////////
895 wxSocketHandler
*wxSocketHandler::master
= NULL
;
896 #if defined(__WINDOWS__)
897 static int win_initialized
= 0;
900 // --------------------------------------------------------------
901 // --------- wxSocketHandler CONSTRUCTOR ------------------------
902 // --------------------------------------------------------------
903 wxSocketHandler::wxSocketHandler()
905 #if defined(__WINDOWS__)
906 if (!win_initialized
)
910 WSAStartup((1 << 8) | 1, &wsaData
);
918 signal(SIGPIPE
, SIG_IGN
);
922 // --------------------------------------------------------------
923 // --------- wxSocketHandler DESTRUCTOR -------------------------
924 // --------------------------------------------------------------
925 wxSocketHandler::~wxSocketHandler()
927 wxNode
*next_node
, *node
= socks
->First();
931 wxSocketBase
* sock
= (wxSocketBase
*)node
->Data();
934 next_node
= node
->Next();
947 // --------------------------------------------------------------
948 // --------- wxSocketHandler registering functions --------------
949 // --------------------------------------------------------------
951 void wxSocketHandler::Register(wxSocketBase
* sock
)
955 for (node
= socks
->First(); node
!= NULL
; node
= node
->Next())
957 wxSocketBase
* s
= (wxSocketBase
*)node
->Data();
966 sock
->SetHandler(this);
970 void wxSocketHandler::UnRegister(wxSocketBase
* sock
)
974 for (node
= socks
->First(); node
; node
= node
->Next())
976 wxSocketBase
* s
= (wxSocketBase
*)node
->Data();
981 sock
->SetHandler(NULL
);
987 unsigned long wxSocketHandler::Count() const
989 return socks
->Number();
992 // --------------------------------------------------------------
993 // --------- wxSocketHandler "big" wait functions ---------------
994 // --------------------------------------------------------------
996 int wxSocketHandler::Wait(long seconds
, long microseconds
)
998 // TODO Needs the completely asynchronous notifier.
1004 for (node = socks->First(), i=0; node; node = node->Next(), i++)
1006 wxSocketBase *sock = (wxSocketBase *)node->Data();
1010 sock->SetupCallbacks();
1012 sock->Callback(handler_cbk);
1013 sock->CallbackData((char *)&on_wait);
1017 s_wake.Start((seconds*1000) + (microseconds/1000), TRUE);
1022 for (node = socks->First(), i=0; node; node = node->Next(), i++)
1024 wxSocketBase *sock = (wxSocketBase *)node->Data();
1026 sock->RestoreState();
1037 void wxSocketHandler::YieldSock()
1041 // Nothing to do anymore here except waiting for the queue emptying.
1042 for (node
= socks
->First(); node
; node
=node
->Next()) {
1043 wxSocketBase
*sock
= (wxSocketBase
*)node
->Data();
1045 sock
->m_internal
->WaitForEnd(NULL
);
1049 // --------------------------------------------------------------
1050 // --------- wxSocketHandler: create and register the socket ----
1051 // --------------------------------------------------------------
1052 wxSocketServer
*wxSocketHandler::CreateServer(wxSockAddress
& addr
,
1053 wxSocketBase::wxSockFlags flags
)
1055 wxSocketServer
*serv
= new wxSocketServer(addr
, flags
);
1061 wxSocketClient
*wxSocketHandler::CreateClient(wxSocketBase::wxSockFlags flags
)
1063 wxSocketClient
*client
= new wxSocketClient(flags
);
1069 bool wxSocketModule::OnInit()
1071 wxSocketHandler::master
= new wxSocketHandler();
1075 void wxSocketModule::OnExit()
1077 delete wxSocketHandler::master
;
1078 wxSocketHandler::master
= NULL
;