]>
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
)
558 m_internal
->EnableWaiter();
560 m_internal
->DisableWaiter();
561 m_notify_state
= notify
;
564 void wxSocketBase::OnRequest(wxRequestEvent req_evt
)
566 wxSocketEvent
event(m_id
);
567 wxRequestNotify notify
= EventToNotify(req_evt
);
569 if ((m_neededreq
& notify
) == notify
) {
570 event
.m_socket
= this;
571 event
.m_skevt
= req_evt
;
574 // OldOnNotify(req_evt);
576 // We disable the event reporting.
577 SetNotify(m_neededreq
& ~notify
);
581 wxSocketEvent::wxSocketEvent(int id
)
584 wxEventType type
= (wxEventType
)wxEVT_SOCKET
;
589 wxObject
*wxSocketEvent::Clone() const
591 wxSocketEvent
*event
= (wxSocketEvent
*)wxEvent::Clone();
593 event
->m_skevt
= m_skevt
;
594 event
->m_socket
= m_socket
;
599 void wxSocketBase::OldOnNotify(wxRequestEvent evt
)
603 // --------------------------------------------------------------
604 // --------- wxSocketBase functions [Callback, CallbackData] ----
605 // --------------------------------------------------------------
607 void wxSocketBase::SetEventHandler(wxEvtHandler
& h_evt
, int id
)
609 SetNextHandler(&h_evt
);
613 // --------------------------------------------------------------
614 // --------- wxSocketBase pushback library ----------------------
615 // --------------------------------------------------------------
617 void wxSocketBase::CreatePushbackAfter(const char *buffer
, size_t size
)
621 if (m_unread
!= NULL
)
622 m_unread
= (char *) realloc(m_unread
, m_unrd_size
+size
);
624 m_unread
= (char *) malloc(size
);
625 curr_pos
= m_unread
+ m_unrd_size
;
627 memcpy(curr_pos
, buffer
, size
);
631 void wxSocketBase::CreatePushbackBefore(const char *buffer
, size_t size
)
633 char *curr_pos
, *new_buf
;
635 new_buf
= (char *) malloc(m_unrd_size
+size
);
636 curr_pos
= new_buf
+ size
;
638 memcpy(new_buf
, buffer
, size
);
639 if (m_unrd_size
!= 0) {
640 memcpy(curr_pos
, m_unread
, m_unrd_size
);
647 size_t wxSocketBase::GetPushback(char *buffer
, size_t size
, bool peek
)
652 if (size
> m_unrd_size
)
654 memcpy(buffer
, m_unread
, size
);
658 if (m_unrd_size
== 0) {
667 // --------------------------------------------------------------
668 // --------- wxSocketBase buffer core requester -----------------
669 // --------------------------------------------------------------
671 void wxSocketBase::WantBuffer(char *buffer
, size_t nbytes
,
676 if (m_fd
== INVALID_SOCKET
|| !m_handler
|| !m_connected
)
679 SockRequest
*buf
= new SockRequest
;
682 m_internal
->DisableWaiter();
683 buf
->buffer
= buffer
;
686 buf
->type
= EventToNotify(evt
);
691 buf_timed_out
= FALSE
;
694 m_internal
->QueueRequest(buf
, FALSE
);
696 if (m_flags
& NOWAIT
)
697 m_internal
->QueueRequest(buf
, TRUE
);
699 m_internal
->QueueRequest(buf
, TRUE
);
700 m_lcount
+= buf
->io_nbytes
;
704 m_error
= buf
->error
;
710 // --------------------------------------------------------------
712 // --------------------------------------------------------------
714 wxSocketServer::wxSocketServer(wxSockAddress
& addr_man
,
716 wxSocketBase(flags
, SOCK_SERVER
)
718 m_fd
= socket(addr_man
.GetFamily(), SOCK_STREAM
, 0);
720 if (m_fd
== INVALID_SOCKET
)
724 setsockopt(m_fd
, SOL_SOCKET
, SO_REUSEADDR
, (char*)&flag
, sizeof(int));
726 struct sockaddr
*myaddr
;
729 addr_man
.Build(myaddr
, len
);
730 if (bind(m_fd
, myaddr
, addr_man
.SockAddrLen()) < 0)
733 if (listen(m_fd
, 5) < 0) {
734 m_fd
= INVALID_SOCKET
;
738 m_internal
->InitializeSocket();
741 // --------------------------------------------------------------
742 // wxSocketServer Accept
743 // --------------------------------------------------------------
745 bool wxSocketServer::AcceptWith(wxSocketBase
& sock
)
749 if ((fd2
= accept(m_fd
, 0, 0)) < 0)
752 struct linger linger
;
756 setsockopt(fd2
, SOL_SOCKET
, SO_LINGER
, (char*)&linger
, sizeof(linger
));
759 setsockopt(fd2
, SOL_SOCKET
, SO_KEEPALIVE
, (char*)&flag
, sizeof(int));
761 sock
.m_type
= SOCK_INTERNAL
;
763 sock
.m_connected
= TRUE
;
765 sock
.m_internal
->InitializeSocket();
770 wxSocketBase
*wxSocketServer::Accept()
772 wxSocketBase
* sock
= new wxSocketBase();
774 sock
->SetFlags((wxSockFlags
)m_flags
);
776 if (!AcceptWith(*sock
))
780 m_handler
->Register(sock
);
785 // --------------------------------------------------------------
787 // --------------------------------------------------------------
789 // --------- wxSocketClient CONSTRUCTOR -------------------------
790 // --------------------------------------------------------------
791 wxSocketClient::wxSocketClient(wxSockFlags _flags
) :
792 wxSocketBase(_flags
, SOCK_CLIENT
)
796 // --------------------------------------------------------------
797 // --------- wxSocketClient DESTRUCTOR --------------------------
798 // --------------------------------------------------------------
799 wxSocketClient::~wxSocketClient()
803 // --------------------------------------------------------------
804 // --------- wxSocketClient Connect functions -------------------
805 // --------------------------------------------------------------
806 bool wxSocketClient::Connect(wxSockAddress
& addr_man
, bool WXUNUSED(wait
) )
808 struct linger linger
;
813 // Initializes all socket stuff ...
814 // --------------------------------
815 m_fd
= socket(addr_man
.GetFamily(), SOCK_STREAM
, 0);
824 setsockopt(m_fd
, SOL_SOCKET
, SO_LINGER
, (char*)&linger
, sizeof(linger
));
826 // Stay in touch with the state of things...
828 unsigned long flag
= 1;
829 setsockopt(m_fd
, SOL_SOCKET
, SO_KEEPALIVE
, (char*)&flag
, sizeof(int));
831 // Disable the nagle algorithm, which delays sends till the
832 // buffer is full (or a certain time period has passed?)...
834 #if defined(__WINDOWS__) || (defined(IPPROTO_TCP) && defined(TCP_NODELAY))
836 setsockopt(m_fd
, IPPROTO_TCP
, TCP_NODELAY
, (char*)&flag
, sizeof(int));
839 struct sockaddr
*remote
;
842 addr_man
.Build(remote
, len
);
844 if (connect(m_fd
, remote
, len
) != 0)
847 // Initializes the background threads ...
848 // --------------------------------------
849 m_internal
->InitializeSocket();
851 // Enables bg events.
852 // ------------------
859 bool wxSocketClient::WaitOnConnect(long seconds
, long microseconds
)
861 int ret
= _Wait(seconds
, microseconds
, REQ_CONNECT
| REQ_LOST
);
869 void wxSocketClient::OnRequest(wxRequestEvent evt
)
871 if (evt
== EVT_CONNECT
)
875 SetNotify(m_neededreq
& ~REQ_CONNECT
);
879 OldOnNotify(EVT_CONNECT
);
882 wxSocketBase::OnRequest(evt
);
885 /////////////////////////////////////////////////////////////////
886 // wxSocketHandler ///////////////////////////////////////////////
887 /////////////////////////////////////////////////////////////////
889 wxSocketHandler
*wxSocketHandler::master
= NULL
;
890 #if defined(__WINDOWS__)
891 static int win_initialized
= 0;
894 // --------------------------------------------------------------
895 // --------- wxSocketHandler CONSTRUCTOR ------------------------
896 // --------------------------------------------------------------
897 wxSocketHandler::wxSocketHandler()
899 #if defined(__WINDOWS__)
900 if (!win_initialized
)
904 WSAStartup((1 << 8) | 1, &wsaData
);
912 signal(SIGPIPE
, SIG_IGN
);
916 // --------------------------------------------------------------
917 // --------- wxSocketHandler DESTRUCTOR -------------------------
918 // --------------------------------------------------------------
919 wxSocketHandler::~wxSocketHandler()
921 wxNode
*next_node
, *node
= socks
->First();
925 wxSocketBase
* sock
= (wxSocketBase
*)node
->Data();
928 next_node
= node
->Next();
941 // --------------------------------------------------------------
942 // --------- wxSocketHandler registering functions --------------
943 // --------------------------------------------------------------
945 void wxSocketHandler::Register(wxSocketBase
* sock
)
949 for (node
= socks
->First(); node
!= NULL
; node
= node
->Next())
951 wxSocketBase
* s
= (wxSocketBase
*)node
->Data();
960 sock
->SetHandler(this);
964 void wxSocketHandler::UnRegister(wxSocketBase
* sock
)
968 for (node
= socks
->First(); node
; node
= node
->Next())
970 wxSocketBase
* s
= (wxSocketBase
*)node
->Data();
975 sock
->SetHandler(NULL
);
981 unsigned long wxSocketHandler::Count() const
983 return socks
->Number();
986 // --------------------------------------------------------------
987 // --------- wxSocketHandler "big" wait functions ---------------
988 // --------------------------------------------------------------
990 int wxSocketHandler::Wait(long seconds
, long microseconds
)
992 // TODO Needs the completely asynchronous notifier.
998 for (node = socks->First(), i=0; node; node = node->Next(), i++)
1000 wxSocketBase *sock = (wxSocketBase *)node->Data();
1004 sock->SetupCallbacks();
1006 sock->Callback(handler_cbk);
1007 sock->CallbackData((char *)&on_wait);
1011 s_wake.Start((seconds*1000) + (microseconds/1000), TRUE);
1016 for (node = socks->First(), i=0; node; node = node->Next(), i++)
1018 wxSocketBase *sock = (wxSocketBase *)node->Data();
1020 sock->RestoreState();
1031 void wxSocketHandler::YieldSock()
1035 // Nothing to do anymore here except waiting for the queue emptying.
1036 for (node
= socks
->First(); node
; node
=node
->Next()) {
1037 wxSocketBase
*sock
= (wxSocketBase
*)node
->Data();
1039 sock
->m_internal
->WaitForEnd(NULL
);
1043 // --------------------------------------------------------------
1044 // --------- wxSocketHandler: create and register the socket ----
1045 // --------------------------------------------------------------
1046 wxSocketServer
*wxSocketHandler::CreateServer(wxSockAddress
& addr
,
1047 wxSocketBase::wxSockFlags flags
)
1049 wxSocketServer
*serv
= new wxSocketServer(addr
, flags
);
1055 wxSocketClient
*wxSocketHandler::CreateClient(wxSocketBase::wxSockFlags flags
)
1057 wxSocketClient
*client
= new wxSocketClient(flags
);
1064 // --------------------------------------------------------------
1065 // --------- wxSocketHandler: Windows specific methods ----------
1066 // --------------------------------------------------------------
1068 UINT
wxSocketHandler::NewMessage(wxSocketBase
*sock
)
1070 internal
->firstAvailableMsg
++;
1071 smsg_list
->Append(internal
->firstAvailableMsg
, sock
);
1072 return internal
->firstAvailableMsg
;
1075 void wxSocketHandler::DestroyMessage(UINT msg
)
1077 wxNode
*node
= smsg_list
->Find(msg
);
1081 HWND
wxSocketHandler::GetHWND() const
1083 return internal
->sockWin
;
1088 bool wxSocketModule::OnInit()
1090 wxSocketHandler::master
= new wxSocketHandler();
1094 void wxSocketModule::OnExit()
1096 delete wxSocketHandler::master
;
1097 wxSocketHandler::master
= NULL
;