📄 api.cpp
字号:
/*****************************************************************************Copyright (c) 2001 - 2009, The Board of Trustees of the University of Illinois.All rights reserved.Redistribution and use in source and binary forms, with or withoutmodification, are permitted provided that the following conditions aremet:* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.* Neither the name of the University of Illinois nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "ASIS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULARPURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER ORCONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, ORPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OFLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDINGNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THISSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.*****************************************************************************//*****************************************************************************written by Yunhong Gu, last updated 01/22/2009*****************************************************************************/#ifdef WIN32 #include <winsock2.h> #include <ws2tcpip.h> #include <wspiapi.h>#else #include <unistd.h>#endif#include <cstring>#include "api.h"#include "core.h"using namespace std;CUDTSocket::CUDTSocket():m_pSelfAddr(NULL),m_pPeerAddr(NULL),m_pUDT(NULL),m_pQueuedSockets(NULL),m_pAcceptSockets(NULL){ #ifndef WIN32 pthread_mutex_init(&m_AcceptLock, NULL); pthread_cond_init(&m_AcceptCond, NULL); #else m_AcceptLock = CreateMutex(NULL, false, NULL); m_AcceptCond = CreateEvent(NULL, false, false, NULL); #endif}CUDTSocket::~CUDTSocket(){ if (AF_INET == m_iIPversion) { delete (sockaddr_in*)m_pSelfAddr; delete (sockaddr_in*)m_pPeerAddr; } else { delete (sockaddr_in6*)m_pSelfAddr; delete (sockaddr_in6*)m_pPeerAddr; } delete m_pUDT; delete m_pQueuedSockets; delete m_pAcceptSockets; #ifndef WIN32 pthread_mutex_destroy(&m_AcceptLock); pthread_cond_destroy(&m_AcceptCond); #else CloseHandle(m_AcceptLock); CloseHandle(m_AcceptCond); #endif}////////////////////////////////////////////////////////////////////////////////CUDTUnited::CUDTUnited(){ srand((unsigned int)CTimer::getTime()); m_SocketID = 1 + (int)((1 << 30) * (rand()/(RAND_MAX + 1.0))); #ifndef WIN32 pthread_mutex_init(&m_ControlLock, NULL); pthread_mutex_init(&m_IDLock, NULL); pthread_mutex_init(&m_InitLock, NULL); #else m_ControlLock = CreateMutex(NULL, false, NULL); m_IDLock = CreateMutex(NULL, false, NULL); m_InitLock = CreateMutex(NULL, false, NULL); #endif #ifndef WIN32 pthread_key_create(&m_TLSError, TLSDestroy); #else m_TLSError = TlsAlloc(); m_TLSLock = CreateMutex(NULL, false, NULL); #endif // Global initialization code #ifdef WIN32 WORD wVersionRequested; WSADATA wsaData; wVersionRequested = MAKEWORD(2, 2); if (0 != WSAStartup(wVersionRequested, &wsaData)) throw CUDTException(1, 0, WSAGetLastError()); #endif m_vMultiplexer.clear(); m_pController = new CControl; m_bGCStatus = false;}CUDTUnited::~CUDTUnited(){ #ifndef WIN32 pthread_mutex_destroy(&m_ControlLock); pthread_mutex_destroy(&m_IDLock); pthread_mutex_destroy(&m_InitLock); #else CloseHandle(m_ControlLock); CloseHandle(m_IDLock); CloseHandle(m_InitLock); #endif #ifndef WIN32 pthread_key_delete(m_TLSError); #else TlsFree(m_TLSError); CloseHandle(m_TLSLock); #endif m_vMultiplexer.clear(); delete m_pController; // Global destruction code #ifdef WIN32 WSACleanup(); #endif}int CUDTUnited::startup(){ CGuard gcinit(m_InitLock); if (m_bGCStatus) return true; m_bClosing = false; #ifndef WIN32 pthread_mutex_init(&m_GCStopLock, NULL); pthread_cond_init(&m_GCStopCond, NULL); pthread_create(&m_GCThread, NULL, garbageCollect, this); #else m_GCStopLock = CreateMutex(NULL, false, NULL); m_GCStopCond = CreateEvent(NULL, false, false, NULL); DWORD ThreadID; m_GCThread = CreateThread(NULL, 0, garbageCollect, this, NULL, &ThreadID); #endif m_bGCStatus = true; return 0;}int CUDTUnited::cleanup(){ CGuard gcinit(m_InitLock); if (!m_bGCStatus) return 0; m_bClosing = true; #ifndef WIN32 pthread_cond_signal(&m_GCStopCond); pthread_join(m_GCThread, NULL); pthread_mutex_destroy(&m_GCStopLock); pthread_cond_destroy(&m_GCStopCond); #else SetEvent(m_GCStopCond); WaitForSingleObject(m_GCThread, INFINITE); CloseHandle(m_GCThread); CloseHandle(m_GCStopLock); CloseHandle(m_GCStopCond); #endif m_bGCStatus = false; return 0;}UDTSOCKET CUDTUnited::newSocket(const int& af, const int& type){ if ((type != SOCK_STREAM) && (type != SOCK_DGRAM)) throw CUDTException(5, 3, 0); CUDTSocket* ns = NULL; try { ns = new CUDTSocket; ns->m_pUDT = new CUDT; if (AF_INET == af) { ns->m_pSelfAddr = (sockaddr*)(new sockaddr_in); ((sockaddr_in*)(ns->m_pSelfAddr))->sin_port = 0; } else { ns->m_pSelfAddr = (sockaddr*)(new sockaddr_in6); ((sockaddr_in6*)(ns->m_pSelfAddr))->sin6_port = 0; } } catch (...) { delete ns; throw CUDTException(3, 2, 0); } CGuard::enterCS(m_IDLock); ns->m_SocketID = -- m_SocketID; CGuard::leaveCS(m_IDLock); ns->m_Status = CUDTSocket::INIT; ns->m_ListenSocket = 0; ns->m_pUDT->m_SocketID = ns->m_SocketID; ns->m_pUDT->m_iSockType = (SOCK_STREAM == type) ? UDT_STREAM : UDT_DGRAM; ns->m_pUDT->m_iIPversion = ns->m_iIPversion = af; ns->m_pUDT->m_pController = m_pController; // protect the m_Sockets structure. CGuard::enterCS(m_ControlLock); try { m_Sockets[ns->m_SocketID] = ns; } catch (...) { //failure and rollback delete ns; ns = NULL; } CGuard::leaveCS(m_ControlLock); if (NULL == ns) throw CUDTException(3, 2, 0); return ns->m_SocketID;}int CUDTUnited::newConnection(const UDTSOCKET listen, const sockaddr* peer, CHandShake* hs){ CUDTSocket* ns = NULL; CUDTSocket* ls = locate(listen); // if this connection has already been processed if (NULL != (ns = locate(listen, peer, hs->m_iID, hs->m_iISN))) { if (ns->m_pUDT->m_bBroken) { // last connection from the "peer" address has been broken ns->m_Status = CUDTSocket::CLOSED; ns->m_TimeStamp = CTimer::getTime(); CGuard::enterCS(ls->m_AcceptLock); ls->m_pQueuedSockets->erase(ns->m_SocketID); ls->m_pAcceptSockets->erase(ns->m_SocketID); CGuard::leaveCS(ls->m_AcceptLock); } else { // connection already exist, this is a repeated connection request // respond with existing HS information hs->m_iISN = ns->m_pUDT->m_iISN; hs->m_iMSS = ns->m_pUDT->m_iMSS; hs->m_iFlightFlagSize = ns->m_pUDT->m_iFlightFlagSize; hs->m_iReqType = -1; hs->m_iID = ns->m_SocketID; return 0; //except for this situation a new connection should be started } } // exceeding backlog, refuse the connection request if (ls->m_pQueuedSockets->size() >= ls->m_uiBackLog) return -1; try { ns = new CUDTSocket; ns->m_pUDT = new CUDT(*(ls->m_pUDT)); if (AF_INET == ls->m_iIPversion) { ns->m_pSelfAddr = (sockaddr*)(new sockaddr_in); ((sockaddr_in*)(ns->m_pSelfAddr))->sin_port = 0; ns->m_pPeerAddr = (sockaddr*)(new sockaddr_in); memcpy(ns->m_pPeerAddr, peer, sizeof(sockaddr_in)); } else { ns->m_pSelfAddr = (sockaddr*)(new sockaddr_in6); ((sockaddr_in6*)(ns->m_pSelfAddr))->sin6_port = 0; ns->m_pPeerAddr = (sockaddr*)(new sockaddr_in6); memcpy(ns->m_pPeerAddr, peer, sizeof(sockaddr_in6)); } } catch (...) { delete ns; return -1; } CGuard::enterCS(m_IDLock); ns->m_SocketID = -- m_SocketID; CGuard::leaveCS(m_IDLock); ns->m_ListenSocket = listen; ns->m_iIPversion = ls->m_iIPversion; ns->m_pUDT->m_SocketID = ns->m_SocketID; ns->m_PeerID = hs->m_iID; ns->m_iISN = hs->m_iISN; int error = 0; try { // bind to the same addr of listening socket ns->m_pUDT->open(); updateMux(ns->m_pUDT, ls); ns->m_pUDT->connect(peer, hs); } catch (...) { error = 1; goto ERR_ROLLBACK; } ns->m_Status = CUDTSocket::CONNECTED; // copy address information of local node ns->m_pUDT->m_pSndQueue->m_pChannel->getSockAddr(ns->m_pSelfAddr); // protect the m_Sockets structure. CGuard::enterCS(m_ControlLock); try { m_Sockets[ns->m_SocketID] = ns; } catch (...) { error = 2; } CGuard::leaveCS(m_ControlLock); CGuard::enterCS(ls->m_AcceptLock); try { ls->m_pQueuedSockets->insert(ns->m_SocketID); } catch (...) { error = 3; } CGuard::leaveCS(ls->m_AcceptLock); CTimer::triggerEvent(); ERR_ROLLBACK: if (error > 0) { ns->m_pUDT->close(); ns->m_Status = CUDTSocket::CLOSED; ns->m_TimeStamp = CTimer::getTime(); return -1; } // wake up a waiting accept() call #ifndef WIN32 pthread_cond_signal(&(ls->m_AcceptCond)); #else SetEvent(ls->m_AcceptCond); #endif return 1;}CUDT* CUDTUnited::lookup(const UDTSOCKET u){ // protects the m_Sockets structure CGuard cg(m_ControlLock); map<UDTSOCKET, CUDTSocket*>::iterator i = m_Sockets.find(u); if ((i == m_Sockets.end()) || (i->second->m_Status == CUDTSocket::CLOSED)) throw CUDTException(5, 4, 0); return i->second->m_pUDT;}CUDTSocket::UDTSTATUS CUDTUnited::getStatus(const UDTSOCKET u){ // protects the m_Sockets structure CGuard cg(m_ControlLock); map<UDTSOCKET, CUDTSocket*>::iterator i = m_Sockets.find(u); if (i == m_Sockets.end()) return CUDTSocket::INIT; if (i->second->m_pUDT->m_bBroken) return CUDTSocket::BROKEN; return i->second->m_Status; }int CUDTUnited::bind(const UDTSOCKET u, const sockaddr* name, const int& namelen){ CUDTSocket* s = locate(u); if (NULL == s) throw CUDTException(5, 4, 0); // cannot bind a socket more than once if (CUDTSocket::INIT != s->m_Status) throw CUDTException(5, 0, 0); // check the size of SOCKADDR structure if (AF_INET == s->m_iIPversion) { if (namelen != sizeof(sockaddr_in)) throw CUDTException(5, 3, 0); } else { if (namelen != sizeof(sockaddr_in6)) throw CUDTException(5, 3, 0); } s->m_pUDT->open(); updateMux(s->m_pUDT, name); s->m_Status = CUDTSocket::OPENED; // copy address information of local node s->m_pUDT->m_pSndQueue->m_pChannel->getSockAddr(s->m_pSelfAddr); return 0;}int CUDTUnited::bind(UDTSOCKET u, UDPSOCKET udpsock){ CUDTSocket* s = locate(u); if (NULL == s) throw CUDTException(5, 4, 0); // cannot bind a socket more than once if (CUDTSocket::INIT != s->m_Status) throw CUDTException(5, 0, 0); sockaddr_in name4; sockaddr_in6 name6; sockaddr* name; socklen_t namelen; if (AF_INET == s->m_iIPversion) { namelen = sizeof(sockaddr_in); name = (sockaddr*)&name4; } else { namelen = sizeof(sockaddr_in6); name = (sockaddr*)&name6; } if (-1 == ::getsockname(udpsock, name, &namelen)) throw CUDTException(5, 3); s->m_pUDT->open(); updateMux(s->m_pUDT, name, &udpsock); s->m_Status = CUDTSocket::OPENED; // copy address information of local node s->m_pUDT->m_pSndQueue->m_pChannel->getSockAddr(s->m_pSelfAddr); return 0;}int CUDTUnited::listen(const UDTSOCKET u, const int& backlog){ CUDTSocket* s = locate(u); if (NULL == s) throw CUDTException(5, 4, 0); // do nothing if the socket is already listening if (CUDTSocket::LISTENING == s->m_Status) return 0; // a socket can listen only if is in OPENED status if (CUDTSocket::OPENED != s->m_Status) throw CUDTException(5, 5, 0); // listen is not supported in rendezvous connection setup if (s->m_pUDT->m_bRendezvous) throw CUDTException(5, 7, 0); if (backlog <= 0) throw CUDTException(5, 3, 0); s->m_uiBackLog = backlog; try { s->m_pQueuedSockets = new set<UDTSOCKET>; s->m_pAcceptSockets = new set<UDTSOCKET>; } catch (...) { delete s->m_pQueuedSockets; throw CUDTException(3, 2, 0); } s->m_pUDT->listen(); s->m_Status = CUDTSocket::LISTENING; return 0;}UDTSOCKET CUDTUnited::accept(const UDTSOCKET listen, sockaddr* addr, int* addrlen){ if ((NULL != addr) && (NULL == addrlen)) throw CUDTException(5, 3, 0); CUDTSocket* ls = locate(listen); if (ls == NULL) throw CUDTException(5, 4, 0); // the "listen" socket must be in LISTENING status if (CUDTSocket::LISTENING != ls->m_Status) throw CUDTException(5, 6, 0); // no "accept" in rendezvous connection setup if (ls->m_pUDT->m_bRendezvous) throw CUDTException(5, 7, 0); UDTSOCKET u = CUDT::INVALID_SOCK; bool accepted = false; // !!only one conection can be set up each time!! #ifndef WIN32 while (!accepted) { pthread_mutex_lock(&(ls->m_AcceptLock)); if (ls->m_pQueuedSockets->size() > 0) { u = *(ls->m_pQueuedSockets->begin()); ls->m_pAcceptSockets->insert(ls->m_pAcceptSockets->end(), u); ls->m_pQueuedSockets->erase(ls->m_pQueuedSockets->begin()); accepted = true; } else if (!ls->m_pUDT->m_bSynRecving) accepted = true; else if (CUDTSocket::LISTENING == ls->m_Status) pthread_cond_wait(&(ls->m_AcceptCond), &(ls->m_AcceptLock)); if (CUDTSocket::LISTENING != ls->m_Status) accepted = true; pthread_mutex_unlock(&(ls->m_AcceptLock)); } #else while (!accepted) { WaitForSingleObject(ls->m_AcceptLock, INFINITE);
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -