]>
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.
212 m_internal
->FinalizeSocket();
216 // Unregister from the handler database.
218 m_handler
->UnRegister(this);
220 // Destroy all saved states.
221 m_states
.DeleteContents(TRUE
);
223 // Destroy the socket manager.
227 bool wxSocketBase::Close()
229 if (m_fd
!= INVALID_SOCKET
)
231 // Pause all running socket thread.
232 m_internal
->PauseSocket();
234 // Shutdown the connection.
237 m_fd
= INVALID_SOCKET
;
244 // --------------------------------------------------------------
245 // wxSocketBase base IO function
246 // --------------------------------------------------------------
248 wxSocketBase
& wxSocketBase::Read(char* buffer
, size_t nbytes
)
250 m_lcount
= GetPushback(buffer
, nbytes
, FALSE
);
254 // If we have got the whole needed buffer or if we don't want to
255 // wait then it returns immediately.
256 if (!nbytes
|| (m_lcount
&& !(m_flags
& WAITALL
)) ) {
260 WantBuffer(buffer
, nbytes
, EVT_READ
);
265 wxSocketBase
& wxSocketBase::Peek(char* buffer
, size_t nbytes
)
267 m_lcount
= GetPushback(buffer
, nbytes
, TRUE
);
268 if (nbytes
-m_lcount
== 0)
275 WantBuffer(buffer
, nbytes
, EVT_PEEK
);
280 wxSocketBase
& wxSocketBase::Write(const char *buffer
, size_t nbytes
)
283 WantBuffer((char *)buffer
, nbytes
, EVT_WRITE
);
287 wxSocketBase
& wxSocketBase::Unread(const char *buffer
, size_t nbytes
)
289 CreatePushbackAfter(buffer
, nbytes
);
293 bool wxSocketBase::IsData() const
303 m_internal
->AcquireFD();
308 FD_SET(m_fd
, &sock_set
);
309 select(FD_SETSIZE
, &sock_set
, NULL
, NULL
, &tv
);
311 m_internal
->ReleaseFD();
313 return (FD_ISSET(m_fd
, &sock_set
) != 0);
316 // ---------------------------------------------------------------------
317 // --------- wxSocketBase Discard(): deletes all byte in the input queue
318 // ---------------------------------------------------------------------
319 void wxSocketBase::Discard()
321 #define MAX_BUFSIZE (10*1024)
322 char *my_data
= new char[MAX_BUFSIZE
];
323 size_t recv_size
= MAX_BUFSIZE
;
326 SetFlags((wxSockFlags
)(NOWAIT
| SPEED
));
328 while (recv_size
== MAX_BUFSIZE
)
330 recv_size
= Read(my_data
, MAX_BUFSIZE
).LastCount();
339 // If what? Who seems to need unsigned int?
340 // BTW uint isn't even defined on wxMSW for VC++ for some reason. Even if it
341 // were, getpeername/getsockname don't take unsigned int*, they take int*.
343 // Under glibc 2.0.7, socketbits.h declares socklen_t to be unsigned int
344 // and it uses *socklen_t as the 3rd parameter. Robert.
346 // JACS - How can we detect this?
347 // Meanwhile, if your compiler complains about socklen_t,
348 // switch lines below.
351 # define wxSOCKET_INT socklen_t
353 # define wxSOCKET_INT int
356 // --------------------------------------------------------------
357 // wxSocketBase socket info functions
358 // --------------------------------------------------------------
360 bool wxSocketBase::GetPeer(wxSockAddress
& addr_man
) const
362 struct sockaddr my_addr
;
363 wxSOCKET_INT len_addr
= sizeof(my_addr
);
368 m_internal
->AcquireFD();
370 if (getpeername(m_fd
, (struct sockaddr
*)&my_addr
, &len_addr
) < 0) {
371 m_internal
->ReleaseFD();
375 m_internal
->ReleaseFD();
376 addr_man
.Disassemble(&my_addr
, len_addr
);
380 bool wxSocketBase::GetLocal(wxSockAddress
& addr_man
) const
382 struct sockaddr my_addr
;
383 wxSOCKET_INT len_addr
= sizeof(my_addr
);
388 m_internal
->AcquireFD();
390 if (getsockname(m_fd
, (struct sockaddr
*)&my_addr
, &len_addr
) < 0) {
391 m_internal
->ReleaseFD();
394 m_internal
->ReleaseFD();
396 addr_man
.Disassemble(&my_addr
, len_addr
);
400 // --------------------------------------------------------------
401 // wxSocketBase wait functions
402 // --------------------------------------------------------------
404 void wxSocketBase::SaveState()
406 SocketState
*state
= new SocketState
;
408 state
->notify_state
= m_notify_state
;
409 state
->evt_notify_state
= m_neededreq
;
410 state
->socket_flags
= m_flags
;
411 state
->c_callback
= m_cbk
;
412 state
->c_callback_data
= m_cdata
;
414 m_states
.Append((wxObject
*)state
);
417 void wxSocketBase::RestoreState()
422 node
= m_states
.Last();
426 state
= (SocketState
*)node
->Data();
428 SetFlags(state
->socket_flags
);
429 m_neededreq
= state
->evt_notify_state
;
430 m_cbk
= state
->c_callback
;
431 m_cdata
= state
->c_callback_data
;
432 Notify(state
->notify_state
);
438 // --------------------------------------------------------------
439 // --------- wxSocketBase callback functions --------------------
440 // --------------------------------------------------------------
442 wxSocketBase::wxSockCbk
wxSocketBase::Callback(wxSockCbk cbk_
)
444 wxSockCbk old_cbk
= cbk_
;
450 char *wxSocketBase::CallbackData(char *data
)
452 char *old_data
= m_cdata
;
458 // --------------------------------------------------------------
459 // --------- wxSocketBase wait functions ------------------------
460 // --------------------------------------------------------------
462 bool wxSocketBase::_Wait(long seconds
, long milliseconds
, int type
)
466 if ((!m_connected
&& !m_connecting
) || m_fd
< 0)
469 req
= new SockRequest
;
471 req
->type
= REQ_WAIT
| type
;
472 req
->timeout
= seconds
* 1000 + milliseconds
;
478 m_internal
->QueueRequest(req
, TRUE
);
480 return (req
->io_nbytes
!= 0);
483 bool wxSocketBase::Wait(long seconds
, long milliseconds
)
485 return _Wait(seconds
, milliseconds
, REQ_ACCEPT
| REQ_CONNECT
|
486 REQ_READ
| REQ_WRITE
| REQ_LOST
);
489 bool wxSocketBase::WaitForRead(long seconds
, long milliseconds
)
491 return _Wait(seconds
, milliseconds
, REQ_READ
| REQ_LOST
);
494 bool wxSocketBase::WaitForWrite(long seconds
, long milliseconds
)
496 return _Wait(seconds
, milliseconds
, REQ_WRITE
);
499 bool wxSocketBase::WaitForLost(long seconds
, long milliseconds
)
501 return _Wait(seconds
, milliseconds
, REQ_LOST
);
504 // --------------------------------------------------------------
505 // --------- wxSocketBase callback management -------------------
506 // --------------------------------------------------------------
508 wxSocketBase::wxRequestNotify
wxSocketBase::EventToNotify(wxRequestEvent evt
)
528 void wxSocketBase::SetFlags(wxSockFlags _flags
)
531 if (_flags
& SPEED
) {
532 // SPEED and WAITALL are antagonists.
533 m_flags
= (wxSockFlags
)(m_flags
& ~WAITALL
);
537 wxSocketBase::wxSockFlags
wxSocketBase::GetFlags() const
542 void wxSocketBase::SetNotify(wxRequestNotify flags
)
544 /* Check if server */
545 if (m_type
!= SOCK_SERVER
)
546 flags
&= ~REQ_ACCEPT
;
549 if (m_neededreq
== 0)
550 m_internal
->DisableWaiter();
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
->EnableWaiter();
564 m_internal
->DisableWaiter();
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 SetNotify(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
->DisableWaiter();
686 buf
->buffer
= buffer
;
689 buf
->type
= EventToNotify(evt
);
694 buf_timed_out
= FALSE
;
697 m_internal
->QueueRequest(buf
, FALSE
);
699 if (m_flags
& NOWAIT
)
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
->InitializeSocket();
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
->InitializeSocket();
777 wxSocketBase
*wxSocketServer::Accept()
779 wxSocketBase
* sock
= new wxSocketBase();
781 sock
->SetFlags((wxSockFlags
)m_flags
);
783 if (!AcceptWith(*sock
))
787 m_handler
->Register(sock
);
792 // --------------------------------------------------------------
794 // --------------------------------------------------------------
796 // --------- wxSocketClient CONSTRUCTOR -------------------------
797 // --------------------------------------------------------------
798 wxSocketClient::wxSocketClient(wxSockFlags _flags
) :
799 wxSocketBase(_flags
, SOCK_CLIENT
)
803 // --------------------------------------------------------------
804 // --------- wxSocketClient DESTRUCTOR --------------------------
805 // --------------------------------------------------------------
806 wxSocketClient::~wxSocketClient()
810 // --------------------------------------------------------------
811 // --------- wxSocketClient Connect functions -------------------
812 // --------------------------------------------------------------
813 bool wxSocketClient::Connect(wxSockAddress
& addr_man
, bool WXUNUSED(wait
) )
815 struct linger linger
;
820 // Initializes all socket stuff ...
821 // --------------------------------
822 m_fd
= socket(addr_man
.GetFamily(), SOCK_STREAM
, 0);
831 setsockopt(m_fd
, SOL_SOCKET
, SO_LINGER
, (char*)&linger
, sizeof(linger
));
833 // Stay in touch with the state of things...
835 unsigned long flag
= 1;
836 setsockopt(m_fd
, SOL_SOCKET
, SO_KEEPALIVE
, (char*)&flag
, sizeof(int));
838 // Disable the nagle algorithm, which delays sends till the
839 // buffer is full (or a certain time period has passed?)...
841 #if defined(__WINDOWS__) || (defined(IPPROTO_TCP) && defined(TCP_NODELAY))
843 setsockopt(m_fd
, IPPROTO_TCP
, TCP_NODELAY
, (char*)&flag
, sizeof(int));
846 struct sockaddr
*remote
;
849 addr_man
.Build(remote
, len
);
851 if (connect(m_fd
, remote
, len
) != 0)
854 // Initializes the background threads ...
855 // --------------------------------------
856 m_internal
->InitializeSocket();
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 SetNotify(m_neededreq
& ~REQ_CONNECT
);
886 OldOnNotify(EVT_CONNECT
);
889 wxSocketBase::OnRequest(evt
);
892 /////////////////////////////////////////////////////////////////
893 // wxSocketHandler ///////////////////////////////////////////////
894 /////////////////////////////////////////////////////////////////
896 wxSocketHandler
*wxSocketHandler::master
= NULL
;
897 #if defined(__WINDOWS__)
898 static int win_initialized
= 0;
901 // --------------------------------------------------------------
902 // --------- wxSocketHandler CONSTRUCTOR ------------------------
903 // --------------------------------------------------------------
904 wxSocketHandler::wxSocketHandler()
906 #if defined(__WINDOWS__)
907 if (!win_initialized
)
911 WSAStartup((1 << 8) | 1, &wsaData
);
919 signal(SIGPIPE
, SIG_IGN
);
923 // --------------------------------------------------------------
924 // --------- wxSocketHandler DESTRUCTOR -------------------------
925 // --------------------------------------------------------------
926 wxSocketHandler::~wxSocketHandler()
928 wxNode
*next_node
, *node
= socks
->First();
932 wxSocketBase
* sock
= (wxSocketBase
*)node
->Data();
935 next_node
= node
->Next();
948 // --------------------------------------------------------------
949 // --------- wxSocketHandler registering functions --------------
950 // --------------------------------------------------------------
952 void wxSocketHandler::Register(wxSocketBase
* sock
)
956 for (node
= socks
->First(); node
!= NULL
; node
= node
->Next())
958 wxSocketBase
* s
= (wxSocketBase
*)node
->Data();
967 sock
->SetHandler(this);
971 void wxSocketHandler::UnRegister(wxSocketBase
* sock
)
975 for (node
= socks
->First(); node
; node
= node
->Next())
977 wxSocketBase
* s
= (wxSocketBase
*)node
->Data();
982 sock
->SetHandler(NULL
);
988 unsigned long wxSocketHandler::Count() const
990 return socks
->Number();
993 // --------------------------------------------------------------
994 // --------- wxSocketHandler "big" wait functions ---------------
995 // --------------------------------------------------------------
997 int wxSocketHandler::Wait(long seconds
, long microseconds
)
999 // TODO Needs the completely asynchronous notifier.
1005 for (node = socks->First(), i=0; node; node = node->Next(), i++)
1007 wxSocketBase *sock = (wxSocketBase *)node->Data();
1011 sock->SetupCallbacks();
1013 sock->Callback(handler_cbk);
1014 sock->CallbackData((char *)&on_wait);
1018 s_wake.Start((seconds*1000) + (microseconds/1000), TRUE);
1023 for (node = socks->First(), i=0; node; node = node->Next(), i++)
1025 wxSocketBase *sock = (wxSocketBase *)node->Data();
1027 sock->RestoreState();
1038 void wxSocketHandler::YieldSock()
1042 // Nothing to do anymore here except waiting for the queue emptying.
1043 for (node
= socks
->First(); node
; node
=node
->Next()) {
1044 wxSocketBase
*sock
= (wxSocketBase
*)node
->Data();
1046 sock
->m_internal
->WaitForEnd(NULL
);
1050 // --------------------------------------------------------------
1051 // --------- wxSocketHandler: create and register the socket ----
1052 // --------------------------------------------------------------
1053 wxSocketServer
*wxSocketHandler::CreateServer(wxSockAddress
& addr
,
1054 wxSocketBase::wxSockFlags flags
)
1056 wxSocketServer
*serv
= new wxSocketServer(addr
, flags
);
1062 wxSocketClient
*wxSocketHandler::CreateClient(wxSocketBase::wxSockFlags flags
)
1064 wxSocketClient
*client
= new wxSocketClient(flags
);
1070 bool wxSocketModule::OnInit()
1072 wxSocketHandler::master
= new wxSocketHandler();
1076 void wxSocketModule::OnExit()
1078 delete wxSocketHandler::master
;
1079 wxSocketHandler::master
= NULL
;