| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221 |
- /*
- * Copyright: JessMA Open Source (ldcsaa@gmail.com)
- *
- * Author : Bruce Liang
- * Website : https://github.com/ldcsaa
- * Project : https://github.com/ldcsaa/HP-Socket
- * Blog : http://www.cnblogs.com/ldcsaa
- * Wiki : http://www.oschina.net/p/hp-socket
- * QQ Group : 44636872, 75375912
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
- #include "UdpServer.h"
- #ifdef _UDP_SUPPORT
- EnHandleResult CUdpServer::TriggerFireAccept(TUdpSocketObj* pSocketObj)
- {
- EnHandleResult rs = TRIGGER(FireAccept(pSocketObj));
- return rs;
- }
- BOOL CUdpServer::Start(LPCTSTR lpszBindAddress, USHORT usPort)
- {
- if(!CheckParams() || !CheckStarting())
- return FALSE;
- PrepareStart();
- if(CreateListenSocket(lpszBindAddress, usPort))
- if(CreateWorkerThreads())
- if(StartAccept())
- {
- m_enState = SS_STARTED;
- return TRUE;
- }
- EXECUTE_RESTORE_ERROR(Stop());
- return FALSE;
- }
- void CUdpServer::SetLastError(EnSocketError code, LPCSTR func, int ec)
- {
- m_enLastError = code;
- ::SetLastError(ec);
- }
- BOOL CUdpServer::CheckParams()
- {
- if ((m_enSendPolicy >= SP_PACK && m_enSendPolicy <= SP_DIRECT) &&
- (m_enOnSendSyncPolicy >= OSSP_NONE && m_enOnSendSyncPolicy <= OSSP_CLOSE) &&
- ((int)m_dwMaxConnectionCount > 0 && m_dwMaxConnectionCount <= MAX_CONNECTION_COUNT) &&
- ((int)m_dwWorkerThreadCount > 0 && m_dwWorkerThreadCount <= MAX_WORKER_THREAD_COUNT) &&
- ((int)m_dwFreeSocketObjLockTime >= 1000) &&
- ((int)m_dwFreeSocketObjPool >= 0) &&
- ((int)m_dwFreeBufferObjPool >= 0) &&
- ((int)m_dwFreeSocketObjHold >= 0) &&
- ((int)m_dwFreeBufferObjHold >= 0) &&
- ((int)m_dwMaxDatagramSize > 0 && m_dwMaxDatagramSize <= MAXIMUM_UDP_MAX_DATAGRAM_SIZE) &&
- ((int)m_dwPostReceiveCount > 0) &&
- ((int)m_dwDetectAttempts >= 0) &&
- ((int)m_dwDetectInterval >= 1000 || m_dwDetectInterval == 0) )
- return TRUE;
- SetLastError(SE_INVALID_PARAM, __FUNCTION__, ERROR_INVALID_PARAMETER);
- return FALSE;
- }
- void CUdpServer::PrepareStart()
- {
- m_bfActiveSockets.Reset(m_dwMaxConnectionCount);
- m_lsFreeSocket.Reset(m_dwFreeSocketObjPool);
- m_bfObjPool.SetItemCapacity(m_dwMaxDatagramSize);
- m_bfObjPool.SetPoolSize(m_dwFreeBufferObjPool);
- m_bfObjPool.SetPoolHold(m_dwFreeBufferObjHold);
- m_bfObjPool.Prepare();
- }
- BOOL CUdpServer::CheckStarting()
- {
- CSpinLock locallock(m_csState);
- if(m_enState == SS_STOPPED)
- m_enState = SS_STARTING;
- else
- {
- SetLastError(SE_ILLEGAL_STATE, __FUNCTION__, ERROR_INVALID_STATE);
- return FALSE;
- }
- return TRUE;
- }
- BOOL CUdpServer::CheckStoping()
- {
- if(m_enState != SS_STOPPED)
- {
- CSpinLock locallock(m_csState);
- if(HasStarted())
- {
- m_enState = SS_STOPPING;
- return TRUE;
- }
- }
- SetLastError(SE_ILLEGAL_STATE, __FUNCTION__, ERROR_INVALID_STATE);
- return FALSE;
- }
- BOOL CUdpServer::CreateListenSocket(LPCTSTR lpszBindAddress, USHORT usPort)
- {
- BOOL isOK = FALSE;
- if(::IsStrEmpty(lpszBindAddress))
- lpszBindAddress = DEFAULT_IPV4_BIND_ADDRESS;
- HP_SOCKADDR addr;
- if(::sockaddr_A_2_IN(lpszBindAddress, usPort, addr))
- {
- m_soListen = socket(addr.family, SOCK_DGRAM, IPPROTO_UDP);
- if(m_soListen != INVALID_SOCKET)
- {
- ::fcntl_SETFL(m_soListen, O_NOATIME | O_NONBLOCK | O_CLOEXEC);
- VERIFY(IS_NO_ERROR(::SSO_ReuseAddress(m_soListen, m_enReusePolicy)));
- if(::bind(m_soListen, addr.Addr(), addr.AddrSize()) != SOCKET_ERROR)
- {
- if(TRIGGER(FirePrepareListen(m_soListen)) != HR_ERROR)
- isOK = TRUE;
- else
- SetLastError(SE_SOCKET_PREPARE, __FUNCTION__, ENSURE_ERROR_CANCELLED);
- }
- else
- SetLastError(SE_SOCKET_BIND, __FUNCTION__, ::WSAGetLastError());
- }
- else
- SetLastError(SE_SOCKET_CREATE, __FUNCTION__, ::WSAGetLastError());
- }
- else
- SetLastError(SE_SOCKET_CREATE, __FUNCTION__, ::WSAGetLastError());
- return isOK;
- }
- BOOL CUdpServer::CreateWorkerThreads()
- {
- return m_ioDispatcher.Start(this, m_dwPostReceiveCount, m_dwWorkerThreadCount);
- }
- BOOL CUdpServer::StartAccept()
- {
- return m_ioDispatcher.AddFD(m_soListen, _EPOLL_READ_EVENTS | EPOLLET, TO_PVOID(&m_soListen));
- }
- BOOL CUdpServer::Stop()
- {
- if(!CheckStoping())
- return FALSE;
- SendCloseNotify();
- CloseListenSocket();
- DisconnectClientSocket();
- WaitForClientSocketClose();
- WaitForWorkerThreadEnd();
-
- ReleaseClientSocket();
- FireShutdown();
- ReleaseFreeSocket();
- Reset();
- return TRUE;
- }
- void CUdpServer::SendCloseNotify()
- {
- if(m_soListen == INVALID_SOCKET)
- return;
- if(m_bfActiveSockets.Elements() == 0)
- return;
- TUdpSocketObjPtrPool::IndexSet indexes;
- m_bfActiveSockets.CopyIndexes(indexes);
- for(auto it = indexes.begin(), end = indexes.end(); it != end; ++it)
- {
- CONNID connID = *it;
- TUdpSocketObj* pSocketObj = FindSocketObj(connID);
- if(TUdpSocketObj::IsValid(pSocketObj))
- ::SendUdpCloseNotify(m_soListen, pSocketObj->remoteAddr);
- }
- ::WaitFor(30);
- }
- void CUdpServer::CloseListenSocket()
- {
- if(m_soListen == INVALID_SOCKET)
- return;
- ::ManualCloseSocket(m_soListen);
- m_soListen = INVALID_SOCKET;
- ::WaitFor(70);
- }
- void CUdpServer::DisconnectClientSocket()
- {
- if(m_bfActiveSockets.Elements() == 0)
- return;
- TUdpSocketObjPtrPool::IndexSet indexes;
- m_bfActiveSockets.CopyIndexes(indexes);
- for(auto it = indexes.begin(), end = indexes.end(); it != end; ++it)
- Disconnect(*it);
- }
- void CUdpServer::WaitForClientSocketClose()
- {
- while(m_bfActiveSockets.Elements() > 0)
- ::WaitFor(50);
- }
- void CUdpServer::WaitForWorkerThreadEnd()
- {
- m_ioDispatcher.Stop();
- }
- void CUdpServer::ReleaseClientSocket()
- {
- VERIFY(m_bfActiveSockets.IsEmpty());
- m_bfActiveSockets.Reset();
- CWriteLock locallock(m_csClientSocket);
- m_mpClientAddr.clear();
- }
- void CUdpServer::ReleaseFreeSocket()
- {
- m_lsFreeSocket.Clear();
- ReleaseGCSocketObj(TRUE);
- VERIFY(m_lsGCSocket.IsEmpty());
- }
- void CUdpServer::Reset()
- {
- m_phSocket.Reset();
- m_bfObjPool.Clear();
- m_quSend.UnsafeClear();
- m_enState = SS_STOPPED;
- m_evWait.SyncNotifyAll();
- }
- TUdpSocketObj* CUdpServer::GetFreeSocketObj(CONNID dwConnID)
- {
- DWORD dwIndex;
- TUdpSocketObj* pSocketObj = nullptr;
- if(m_lsFreeSocket.TryLock(&pSocketObj, dwIndex))
- {
- if(::GetTimeGap32(pSocketObj->freeTime) >= m_dwFreeSocketObjLockTime)
- VERIFY(m_lsFreeSocket.ReleaseLock(nullptr, dwIndex));
- else
- {
- VERIFY(m_lsFreeSocket.ReleaseLock(pSocketObj, dwIndex));
- pSocketObj = nullptr;
- }
- }
- if(!pSocketObj) pSocketObj = CreateSocketObj();
- pSocketObj->Reset(dwConnID);
- return pSocketObj;
- }
- TUdpSocketObj* CUdpServer::CreateSocketObj()
- {
- return TUdpSocketObj::Construct(m_phSocket, m_bfObjPool);
- }
- void CUdpServer::DeleteSocketObj(TUdpSocketObj* pSocketObj)
- {
- TUdpSocketObj::Destruct(pSocketObj);
- }
- void CUdpServer::AddFreeSocketObj(TUdpSocketObj* pSocketObj, EnSocketCloseFlag enFlag, EnSocketOperation enOperation, int iErrorCode, BOOL bNotify)
- {
- if(!InvalidSocketObj(pSocketObj))
- return;
- CloseClientSocketObj(pSocketObj, enFlag, enOperation, iErrorCode, bNotify);
- {
- m_bfActiveSockets.Remove(pSocketObj->connID);
- CWriteLock locallock(m_csClientSocket);
- m_mpClientAddr.erase(&pSocketObj->remoteAddr);
- }
- m_ioDispatcher.DelTimer(pSocketObj->fdTimer);
- TUdpSocketObj::Release(pSocketObj);
- ReleaseGCSocketObj();
- if(!m_lsFreeSocket.TryPut(pSocketObj))
- m_lsGCSocket.PushBack(pSocketObj);
- }
- void CUdpServer::ReleaseGCSocketObj(BOOL bForce)
- {
- ::ReleaseGCObj(m_lsGCSocket, m_dwFreeSocketObjLockTime, bForce);
- }
- BOOL CUdpServer::InvalidSocketObj(TUdpSocketObj* pSocketObj)
- {
- return TUdpSocketObj::InvalidSocketObj(pSocketObj);
- }
- void CUdpServer::AddClientSocketObj(CONNID dwConnID, TUdpSocketObj* pSocketObj, const HP_SOCKADDR& remoteAddr)
- {
- ASSERT(FindSocketObj(dwConnID) == nullptr);
- if(IsNeedDetectConnection())
- pSocketObj->fdTimer = m_ioDispatcher.AddTimer(m_dwDetectInterval, pSocketObj);
- pSocketObj->pHolder = this;
- pSocketObj->connTime = ::TimeGetTime();
- pSocketObj->activeTime = pSocketObj->connTime;
- remoteAddr.Copy(pSocketObj->remoteAddr);
- pSocketObj->SetConnected();
- VERIFY(m_bfActiveSockets.ReleaseLock(dwConnID, pSocketObj));
- CWriteLock locallock(m_csClientSocket);
- m_mpClientAddr[&pSocketObj->remoteAddr] = dwConnID;
- }
- TUdpSocketObj* CUdpServer::FindSocketObj(CONNID dwConnID)
- {
- TUdpSocketObj* pSocketObj = nullptr;
- if(m_bfActiveSockets.Get(dwConnID, &pSocketObj) != TUdpSocketObjPtrPool::GR_VALID)
- pSocketObj = nullptr;
- return pSocketObj;
- }
- CONNID CUdpServer::FindConnectionID(const HP_SOCKADDR* pAddr)
- {
- CONNID dwConnID = 0;
- CReadLock locallock(m_csClientSocket);
- TSockAddrMapCI it = m_mpClientAddr.find(pAddr);
- if(it != m_mpClientAddr.end())
- dwConnID = it->second;
- return dwConnID;
- }
- void CUdpServer::CloseClientSocketObj(TUdpSocketObj* pSocketObj, EnSocketCloseFlag enFlag, EnSocketOperation enOperation, int iErrorCode, BOOL bNotify)
- {
- ASSERT(TUdpSocketObj::IsExist(pSocketObj));
- if(bNotify && m_soListen != INVALID_SOCKET)
- ::SendUdpCloseNotify(m_soListen, pSocketObj->remoteAddr);
- if(enFlag == SCF_CLOSE)
- FireClose(pSocketObj, SO_CLOSE, SE_OK);
- else if(enFlag == SCF_ERROR)
- FireClose(pSocketObj, enOperation, iErrorCode);
- }
- BOOL CUdpServer::GetListenAddress(TCHAR lpszAddress[], int& iAddressLen, USHORT& usPort)
- {
- ASSERT(lpszAddress != nullptr && iAddressLen > 0);
- return ::GetSocketLocalAddress(m_soListen, lpszAddress, iAddressLen, usPort);
- }
- BOOL CUdpServer::GetLocalAddress(CONNID dwConnID, TCHAR lpszAddress[], int& iAddressLen, USHORT& usPort)
- {
- ASSERT(lpszAddress != nullptr && iAddressLen > 0);
- TUdpSocketObj* pSocketObj = FindSocketObj(dwConnID);
- if(!TUdpSocketObj::IsValid(pSocketObj))
- {
- ::SetLastError(ERROR_OBJECT_NOT_FOUND);
- return FALSE;
- }
- return ::GetSocketLocalAddress(m_soListen, lpszAddress, iAddressLen, usPort);
- }
- BOOL CUdpServer::GetRemoteAddress(CONNID dwConnID, TCHAR lpszAddress[], int& iAddressLen, USHORT& usPort)
- {
- ASSERT(lpszAddress != nullptr && iAddressLen > 0);
- TUdpSocketObj* pSocketObj = FindSocketObj(dwConnID);
- if(!TUdpSocketObj::IsExist(pSocketObj))
- {
- ::SetLastError(ERROR_OBJECT_NOT_FOUND);
- return FALSE;
- }
- ADDRESS_FAMILY usFamily;
- return ::sockaddr_IN_2_A(pSocketObj->remoteAddr, usFamily, lpszAddress, iAddressLen, usPort);
- }
- BOOL CUdpServer::SetConnectionExtra(CONNID dwConnID, PVOID pExtra)
- {
- TUdpSocketObj* pSocketObj = FindSocketObj(dwConnID);
- return SetConnectionExtra(pSocketObj, pExtra);
- }
- BOOL CUdpServer::SetConnectionExtra(TUdpSocketObj* pSocketObj, PVOID pExtra)
- {
- if(!TUdpSocketObj::IsExist(pSocketObj))
- ::SetLastError(ERROR_OBJECT_NOT_FOUND);
- else
- {
- pSocketObj->extra = pExtra;
- return TRUE;
- }
- return FALSE;
- }
- BOOL CUdpServer::GetConnectionExtra(CONNID dwConnID, PVOID* ppExtra)
- {
- TUdpSocketObj* pSocketObj = FindSocketObj(dwConnID);
- return GetConnectionExtra(pSocketObj, ppExtra);
- }
- BOOL CUdpServer::GetConnectionExtra(TUdpSocketObj* pSocketObj, PVOID* ppExtra)
- {
- ASSERT(ppExtra != nullptr);
- if(!TUdpSocketObj::IsExist(pSocketObj))
- ::SetLastError(ERROR_OBJECT_NOT_FOUND);
- else
- {
- *ppExtra = pSocketObj->extra;
- return TRUE;
- }
- return FALSE;
- }
- BOOL CUdpServer::SetConnectionReserved(CONNID dwConnID, PVOID pReserved)
- {
- TUdpSocketObj* pSocketObj = FindSocketObj(dwConnID);
- return SetConnectionReserved(pSocketObj, pReserved);
- }
- BOOL CUdpServer::SetConnectionReserved(TUdpSocketObj* pSocketObj, PVOID pReserved)
- {
- if(!TUdpSocketObj::IsExist(pSocketObj))
- ::SetLastError(ERROR_OBJECT_NOT_FOUND);
- else
- {
- pSocketObj->reserved = pReserved;
- return TRUE;
- }
- return FALSE;
- }
- BOOL CUdpServer::GetConnectionReserved(CONNID dwConnID, PVOID* ppReserved)
- {
- TUdpSocketObj* pSocketObj = FindSocketObj(dwConnID);
- return GetConnectionReserved(pSocketObj, ppReserved);
- }
- BOOL CUdpServer::GetConnectionReserved(TUdpSocketObj* pSocketObj, PVOID* ppReserved)
- {
- ASSERT(ppReserved != nullptr);
- if(!TUdpSocketObj::IsExist(pSocketObj))
- ::SetLastError(ERROR_OBJECT_NOT_FOUND);
- else
- {
- *ppReserved = pSocketObj->reserved;
- return TRUE;
- }
- return FALSE;
- }
- BOOL CUdpServer::SetConnectionReserved2(CONNID dwConnID, PVOID pReserved2)
- {
- TUdpSocketObj* pSocketObj = FindSocketObj(dwConnID);
- return SetConnectionReserved2(pSocketObj, pReserved2);
- }
- BOOL CUdpServer::SetConnectionReserved2(TUdpSocketObj* pSocketObj, PVOID pReserved2)
- {
- if(!TUdpSocketObj::IsExist(pSocketObj))
- ::SetLastError(ERROR_OBJECT_NOT_FOUND);
- else
- {
- pSocketObj->reserved2 = pReserved2;
- return TRUE;
- }
- return FALSE;
- }
- BOOL CUdpServer::GetConnectionReserved2(CONNID dwConnID, PVOID* ppReserved2)
- {
- TUdpSocketObj* pSocketObj = FindSocketObj(dwConnID);
- return GetConnectionReserved2(pSocketObj, ppReserved2);
- }
- BOOL CUdpServer::GetConnectionReserved2(TUdpSocketObj* pSocketObj, PVOID* ppReserved2)
- {
- ASSERT(ppReserved2 != nullptr);
- if(!TUdpSocketObj::IsExist(pSocketObj))
- ::SetLastError(ERROR_OBJECT_NOT_FOUND);
- else
- {
- *ppReserved2 = pSocketObj->reserved2;
- return TRUE;
- }
- return FALSE;
- }
- BOOL CUdpServer::IsPauseReceive(CONNID dwConnID, BOOL& bPaused)
- {
- ::SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
- bPaused = FALSE;
- return FALSE;
- }
- BOOL CUdpServer::IsConnected(CONNID dwConnID)
- {
- TUdpSocketObj* pSocketObj = FindSocketObj(dwConnID);
- if(!TUdpSocketObj::IsValid(pSocketObj))
- {
- ::SetLastError(ERROR_OBJECT_NOT_FOUND);
- return FALSE;
- }
- return pSocketObj->HasConnected();
- }
- BOOL CUdpServer::GetPendingDataLength(CONNID dwConnID, int& iPending)
- {
- TUdpSocketObj* pSocketObj = FindSocketObj(dwConnID);
- if(!TUdpSocketObj::IsValid(pSocketObj))
- ::SetLastError(ERROR_OBJECT_NOT_FOUND);
- else
- {
- iPending = pSocketObj->Pending();
- return TRUE;
- }
- return FALSE;
- }
- DWORD CUdpServer::GetConnectionCount()
- {
- return m_bfActiveSockets.Elements();
- }
- BOOL CUdpServer::GetAllConnectionIDs(CONNID pIDs[], DWORD& dwCount)
- {
- return m_bfActiveSockets.GetAllElementIndexes(pIDs, dwCount);
- }
- BOOL CUdpServer::GetConnectPeriod(CONNID dwConnID, DWORD& dwPeriod)
- {
- BOOL isOK = TRUE;
- TUdpSocketObj* pSocketObj = FindSocketObj(dwConnID);
- if(TUdpSocketObj::IsValid(pSocketObj))
- dwPeriod = ::GetTimeGap32(pSocketObj->connTime);
- else
- {
- ::SetLastError(ERROR_OBJECT_NOT_FOUND);
- isOK = FALSE;
- }
- return isOK;
- }
- BOOL CUdpServer::GetSilencePeriod(CONNID dwConnID, DWORD& dwPeriod)
- {
- if(!m_bMarkSilence)
- return FALSE;
- BOOL isOK = TRUE;
- TUdpSocketObj* pSocketObj = FindSocketObj(dwConnID);
- if(TUdpSocketObj::IsValid(pSocketObj))
- dwPeriod = ::GetTimeGap32(pSocketObj->activeTime);
- else
- {
- ::SetLastError(ERROR_OBJECT_NOT_FOUND);
- isOK = FALSE;
- }
- return isOK;
- }
- BOOL CUdpServer::Disconnect(CONNID dwConnID, BOOL bForce)
- {
- TUdpSocketObj* pSocketObj = FindSocketObj(dwConnID);
- if(!TUdpSocketObj::IsValid(pSocketObj))
- {
- ::SetLastError(ERROR_OBJECT_NOT_FOUND);
- return FALSE;
- }
- return m_ioDispatcher.SendCommand(DISP_CMD_DISCONNECT, dwConnID, bForce);
- }
- BOOL CUdpServer::DisconnectLongConnections(DWORD dwPeriod, BOOL bForce)
- {
- if(dwPeriod > MAX_CONNECTION_PERIOD)
- return FALSE;
- if(m_bfActiveSockets.Elements() == 0)
- return TRUE;
- DWORD now = ::TimeGetTime();
- TUdpSocketObjPtrPool::IndexSet indexes;
- m_bfActiveSockets.CopyIndexes(indexes);
- for(auto it = indexes.begin(), end = indexes.end(); it != end; ++it)
- {
- CONNID connID = *it;
- TUdpSocketObj* pSocketObj = FindSocketObj(connID);
- if(TUdpSocketObj::IsValid(pSocketObj) && (int)(now - pSocketObj->connTime) >= (int)dwPeriod)
- Disconnect(connID, bForce);
- }
- return TRUE;
- }
- BOOL CUdpServer::DisconnectSilenceConnections(DWORD dwPeriod, BOOL bForce)
- {
- if(!m_bMarkSilence)
- return FALSE;
- if(dwPeriod > MAX_CONNECTION_PERIOD)
- return FALSE;
- if(m_bfActiveSockets.Elements() == 0)
- return TRUE;
- DWORD now = ::TimeGetTime();
- TUdpSocketObjPtrPool::IndexSet indexes;
- m_bfActiveSockets.CopyIndexes(indexes);
- for(auto it = indexes.begin(), end = indexes.end(); it != end; ++it)
- {
- CONNID connID = *it;
- TUdpSocketObj* pSocketObj = FindSocketObj(connID);
- if(TUdpSocketObj::IsValid(pSocketObj) && (int)(now - pSocketObj->activeTime) >= (int)dwPeriod)
- Disconnect(connID, bForce);
- }
- return TRUE;
- }
- BOOL CUdpServer::PauseReceive(CONNID dwConnID, BOOL bPause)
- {
- ::SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
- return FALSE;
- }
- BOOL CUdpServer::OnBeforeProcessIo(PVOID pv, UINT events)
- {
- if(pv == &m_soListen)
- return TRUE;
- if(!(events & _EPOLL_ALL_ERROR_EVENTS))
- DetectConnection(pv);
- return FALSE;
- }
- VOID CUdpServer::OnAfterProcessIo(PVOID pv, UINT events, BOOL rs)
- {
- }
- VOID CUdpServer::OnCommand(TDispCommand* pCmd)
- {
- switch(pCmd->type)
- {
- case DISP_CMD_SEND:
- HandleCmdSend((CONNID)(pCmd->wParam), (int)(pCmd->lParam));
- break;
- case DISP_CMD_RECEIVE:
- HandleCmdReceive((CONNID)(pCmd->wParam), (int)(pCmd->lParam));
- break;
- case DISP_CMD_DISCONNECT:
- HandleCmdDisconnect((CONNID)(pCmd->wParam), (BOOL)pCmd->lParam);
- break;
- case DISP_CMD_TIMEOUT:
- HandleCmdTimeout((CONNID)(pCmd->wParam));
- break;
- }
- }
- VOID CUdpServer::HandleCmdDisconnect(CONNID dwConnID, BOOL bForce)
- {
- AddFreeSocketObj(FindSocketObj(dwConnID), SCF_CLOSE);
- }
- VOID CUdpServer::HandleCmdTimeout(CONNID dwConnID)
- {
- AddFreeSocketObj(FindSocketObj(dwConnID), SCF_CLOSE, SO_UNKNOWN, 0, FALSE);
- }
- BOOL CUdpServer::OnReadyRead(PVOID pv, UINT events)
- {
- return HandleReceive(RETRIVE_EVENT_FLAG_H(events));
- }
- BOOL CUdpServer::OnReadyWrite(PVOID pv, UINT events)
- {
- return HandleSend(RETRIVE_EVENT_FLAG_H(events));
- }
- BOOL CUdpServer::OnHungUp(PVOID pv, UINT events)
- {
- return HandleClose(nullptr, SO_CLOSE, 0);
- }
- BOOL CUdpServer::OnError(PVOID pv, UINT events)
- {
- return HandleClose(nullptr, SO_CLOSE, -1);
- }
- VOID CUdpServer::OnDispatchThreadStart(THR_ID tid)
- {
- OnWorkerThreadStart(tid);
- }
- VOID CUdpServer::OnDispatchThreadEnd(THR_ID tid)
- {
- OnWorkerThreadEnd(tid);
- }
- BOOL CUdpServer::HandleClose(TUdpSocketObj* pSocketObj, EnSocketOperation enOperation, int iErrorCode)
- {
- if(!HasStarted())
- return FALSE;
- else if(pSocketObj == nullptr)
- {
- TRACE("HandleClose() -> OP: %d, EC: %d", enOperation, iErrorCode);
- return TRUE;
- }
- if(iErrorCode == -1)
- iErrorCode = ::SSO_GetError(m_soListen);
- EnSocketCloseFlag enFlag = IS_NO_ERROR(iErrorCode) ? SCF_CLOSE : SCF_ERROR;
- AddFreeSocketObj(pSocketObj, enFlag, enOperation, iErrorCode);
- return FALSE;
- }
- BOOL CUdpServer::HandleReceive(int flag)
- {
- while(TRUE)
- {
- HP_SOCKADDR addr;
- socklen_t dwAddrLen = (socklen_t)addr.AddrSize();
- TItemPtr itPtr(m_bfObjPool, m_bfObjPool.PickFreeItem());
- int iBufferLen = itPtr->Capacity();
- int rc = (int)recvfrom(m_soListen, itPtr->Ptr(), iBufferLen, MSG_TRUNC, addr.Addr(), &dwAddrLen);
- if(rc >= 0)
- {
- CONNID dwConnID = FindConnectionID(&addr);
- if(dwConnID == 0)
- {
- if(rc > iBufferLen)
- continue;
- if((dwConnID = HandleAccept(addr)) == 0)
- continue;
- }
- TUdpSocketObj* pSocketObj = FindSocketObj(dwConnID);
- if(!TUdpSocketObj::IsValid(pSocketObj))
- continue;
- if(rc == 0)
- {
- HandleZeroBytes(pSocketObj);
- continue;
- }
- if(rc > iBufferLen)
- {
- AddFreeSocketObj(pSocketObj, SCF_ERROR, SO_RECEIVE, ERROR_BAD_LENGTH);
- continue;
- }
- if(::IsUdpCloseNotify(itPtr->Ptr(), rc))
- {
- AddFreeSocketObj(pSocketObj, SCF_CLOSE, SO_CLOSE, SE_OK, FALSE);
- continue;
- }
- itPtr->Increase(rc);
-
- {
- CLocalSafeCounter localcounter(*pSocketObj);
- CReentrantReadLock locallock(pSocketObj->lcIo);
- if(!TUdpSocketObj::IsValid(pSocketObj))
- continue;
- pSocketObj->recvQueue.PushBack(itPtr.Detach());
- }
- VERIFY(m_ioDispatcher.SendCommand(DISP_CMD_RECEIVE, dwConnID, flag));
- }
- else if(rc == SOCKET_ERROR)
- {
- int code = ::WSAGetLastError();
- if(code == ERROR_WOULDBLOCK)
- break;
- else if(!HandleClose(nullptr, SO_RECEIVE, code))
- return FALSE;
- }
- else
- {
- ASSERT(FALSE);
- }
- }
- return TRUE;
- }
- CONNID CUdpServer::HandleAccept(HP_SOCKADDR& addr)
- {
- CONNID dwConnID = 0;
- TUdpSocketObj* pSocketObj = nullptr;
- {
- CCriSecLock locallock(m_csAccept);
- dwConnID = FindConnectionID(&addr);
- if(dwConnID != 0)
- return dwConnID;
- else
- {
- if(!m_bfActiveSockets.AcquireLock(dwConnID))
- {
- ::SendUdpCloseNotify(m_soListen, addr);
- return 0;
- }
- pSocketObj = GetFreeSocketObj(dwConnID);
- pSocketObj->lcIo.WaitToWrite();
- AddClientSocketObj(dwConnID, pSocketObj, addr);
- }
- }
- if(TriggerFireAccept(pSocketObj) == HR_ERROR)
- {
- AddFreeSocketObj(pSocketObj);
- dwConnID = 0;
- }
- pSocketObj->lcIo.WriteDone();
- return dwConnID;
- }
- void CUdpServer::HandleZeroBytes(TUdpSocketObj* pSocketObj)
- {
- TRACE("<S-CNNID: %zu> recv 0 bytes (detect package)", pSocketObj->connID);
- pSocketObj->detectFails = 0;
- #if defined(DEBUG_TRACE)
- int rc = (int)
- #endif
- sendto(m_soListen, nullptr, 0, 0, pSocketObj->remoteAddr.Addr(), pSocketObj->remoteAddr.AddrSize());
- TRACE("<S-CNNID: %zu> send 0 bytes (detect ack package - %s)", pSocketObj->connID, IS_HAS_ERROR(rc) ? "fail" : "succ");
- }
- VOID CUdpServer::HandleCmdReceive(CONNID dwConnID, int flag)
- {
- TUdpSocketObj* pSocketObj = FindSocketObj(dwConnID);
- if(!TUdpSocketObj::IsValid(pSocketObj))
- return;
- if(pSocketObj->recvQueue.IsEmpty())
- return;
- BOOL bCancel = FALSE;
- {
- CLocalSafeCounter localcounter(*pSocketObj);
- CReentrantReadLock locallock(pSocketObj->lcIo);
- if(!TUdpSocketObj::IsValid(pSocketObj))
- return;
- if(pSocketObj->recvQueue.IsEmpty())
- return;
- pSocketObj->detectFails = 0;
- if(m_bMarkSilence) pSocketObj->activeTime = ::TimeGetTime();
- int reads = flag ? -1 : MAX_CONTINUE_READS;
- for(int i = 0; i < reads || reads < 0; i++)
- {
- TItemPtr itPtr(m_bfObjPool);
- if(!pSocketObj->recvQueue.PopFront(&itPtr.PtrRef()))
- break;
- if(TRIGGER(FireReceive(pSocketObj, itPtr->Ptr(), itPtr->Size())) == HR_ERROR)
- {
- TRACE("<S-CNNID: %zu> OnReceive() event return 'HR_ERROR', connection will be closed !", dwConnID);
- bCancel = TRUE;
- break;
- }
- }
- }
- if(bCancel)
- AddFreeSocketObj(pSocketObj, SCF_ERROR, SO_RECEIVE, ENSURE_ERROR_CANCELLED);
- else
- {
- if(TUdpSocketObj::IsValid(pSocketObj) && pSocketObj->HasRecvData())
- VERIFY(m_ioDispatcher.SendCommand(DISP_CMD_RECEIVE, dwConnID, flag));
- }
- }
- BOOL CUdpServer::HandleSend(int flag)
- {
- m_ioDispatcher.ModFD(m_soListen, _EPOLL_READ_EVENTS | EPOLLET, TO_PVOID(&m_soListen));
- CONNID dwConnID = 0;
- while(m_quSend.PopFront(&dwConnID))
- VERIFY(m_ioDispatcher.SendCommand(DISP_CMD_SEND, dwConnID));
- return TRUE;
- }
- VOID CUdpServer::HandleCmdSend(CONNID dwConnID, int flag)
- {
- TUdpSocketObj* pSocketObj = FindSocketObj(dwConnID);
- if(!TUdpSocketObj::IsValid(pSocketObj) || !pSocketObj->IsPending())
- return;
- BOOL bClose = FALSE;
- BOOL bBlocked = FALSE;
- int writes = flag ? -1 : MAX_CONTINUE_WRITES;
- TBufferObjList& sndBuff = pSocketObj->sndBuff;
- TItemPtr itPtr(sndBuff);
- {
- CLocalSafeCounter localcounter(*pSocketObj);
- CReentrantReadLock locallock(pSocketObj->lcSend);
- if(!TUdpSocketObj::IsValid(pSocketObj) || !pSocketObj->IsPending())
- return;
- for(int i = 0; i < writes || writes < 0; i++)
- {
- {
- CCriSecLock locallock(pSocketObj->csSend);
- itPtr = sndBuff.PopFront();
- }
- if(!itPtr.IsValid())
- break;
- ASSERT(!itPtr->IsEmpty());
- if(!SendItem(pSocketObj, itPtr, bBlocked))
- {
- bClose = TRUE;
- break;
- }
- if(bBlocked)
- {
- {
- CCriSecLock locallock(pSocketObj->csSend);
- sndBuff.PushFront(itPtr.Detach());
- }
- m_quSend.PushBack(dwConnID);
- m_ioDispatcher.ModFD(m_soListen, EPOLLOUT | _EPOLL_READ_EVENTS | EPOLLET, TO_PVOID(&m_soListen));
- break;
- }
- }
- }
- if(bClose)
- HandleClose(pSocketObj, SO_SEND, ::WSAGetLastError());
- else if(!bBlocked && pSocketObj->IsPending())
- VERIFY(m_ioDispatcher.SendCommand(DISP_CMD_SEND, dwConnID));
- }
- BOOL CUdpServer::SendItem(TUdpSocketObj* pSocketObj, TItem* pItem, BOOL& bBlocked)
- {
- int rc = (int)sendto(m_soListen, pItem->Ptr(), pItem->Size(), 0, pSocketObj->remoteAddr.Addr(), pSocketObj->remoteAddr.AddrSize());
- if(rc > 0)
- {
- ASSERT(rc == pItem->Size());
- if(TRIGGER(FireSend(pSocketObj, pItem->Ptr(), rc)) == HR_ERROR)
- {
- TRACE("<S-CNNID: %zu> OnSend() event should not return 'HR_ERROR' !!", pSocketObj->connID);
- ASSERT(FALSE);
- }
- }
- else if(rc == SOCKET_ERROR)
- {
- int code = ::WSAGetLastError();
- if(code == ERROR_WOULDBLOCK)
- bBlocked = TRUE;
- else
- return FALSE;
- }
- else
- ASSERT(FALSE);
- return TRUE;
- }
- BOOL CUdpServer::Send(CONNID dwConnID, const BYTE* pBuffer, int iLength, int iOffset)
- {
- ASSERT(pBuffer && iLength > 0 && iLength <= (int)m_dwMaxDatagramSize);
- TUdpSocketObj* pSocketObj = FindSocketObj(dwConnID);
- return DoSend(pSocketObj, pBuffer, iLength, iOffset);
- }
- BOOL CUdpServer::DoSend(TUdpSocketObj* pSocketObj, const BYTE* pBuffer, int iLength, int iOffset)
- {
- int result = NO_ERROR;
- if(TUdpSocketObj::IsValid(pSocketObj))
- {
- if(pBuffer && iLength > 0 && iLength <= (int)m_dwMaxDatagramSize)
- {
- if(iOffset != 0) pBuffer += iOffset;
- TItemPtr itPtr(m_bfObjPool, m_bfObjPool.PickFreeItem());
- itPtr->Cat(pBuffer, iLength);
- result = SendInternal(pSocketObj, itPtr);
- }
- else
- result = ERROR_INVALID_PARAMETER;
- }
- else
- result = ERROR_OBJECT_NOT_FOUND;
- if(result != NO_ERROR)
- ::SetLastError(result);
- return (result == NO_ERROR);
- }
- BOOL CUdpServer::SendPackets(CONNID dwConnID, const WSABUF pBuffers[], int iCount)
- {
- ASSERT(pBuffers && iCount > 0);
- if(!pBuffers || iCount <= 0)
- return ERROR_INVALID_PARAMETER;
- TUdpSocketObj* pSocketObj = FindSocketObj(dwConnID);
- if(!TUdpSocketObj::IsValid(pSocketObj))
- {
- ::SetLastError(ERROR_OBJECT_NOT_FOUND);
- return FALSE;
- }
- int result = NO_ERROR;
- int iLength = 0;
- int iMaxLen = (int)m_dwMaxDatagramSize;
-
- TItemPtr itPtr(m_bfObjPool, m_bfObjPool.PickFreeItem());
- for(int i = 0; i < iCount; i++)
- {
- int iBufLen = pBuffers[i].len;
- if(iBufLen > 0)
- {
- BYTE* pBuffer = (BYTE*)pBuffers[i].buf;
- ASSERT(pBuffer);
- iLength += iBufLen;
- if(iLength <= iMaxLen)
- itPtr->Cat(pBuffer, iBufLen);
- else
- break;
- }
- }
- if(iLength > 0 && iLength <= iMaxLen)
- result = SendInternal(pSocketObj, itPtr);
- else
- result = ERROR_INCORRECT_SIZE;
- if(result != NO_ERROR)
- ::SetLastError(result);
- return (result == NO_ERROR);
- }
- int CUdpServer::SendInternal(TUdpSocketObj* pSocketObj, TItemPtr& itPtr)
- {
- BOOL bPending;
- {
- CLocalSafeCounter localcounter(*pSocketObj);
- CCriSecLock locallock(pSocketObj->csSend);
- if(!TUdpSocketObj::IsValid(pSocketObj))
- return ERROR_OBJECT_NOT_FOUND;
- bPending = pSocketObj->IsPending();
- pSocketObj->sndBuff.PushBack(itPtr.Detach());
- ASSERT(pSocketObj->sndBuff.Length() > 0);
- }
- if(!bPending)
- VERIFY(m_ioDispatcher.SendCommand(DISP_CMD_SEND, pSocketObj->connID));
- return NO_ERROR;
- }
- void CUdpServer::DetectConnection(PVOID pv)
- {
- TUdpSocketObj* pSocketObj = (TUdpSocketObj*)pv;
- if(TUdpSocketObj::IsValid(pSocketObj))
- {
- CUdpServer* pServer = (CUdpServer*)pSocketObj->pHolder;
- if(pSocketObj->detectFails >= pServer->m_dwDetectAttempts)
- VERIFY(m_ioDispatcher.SendCommand(DISP_CMD_TIMEOUT, pSocketObj->connID));
- else
- ::InterlockedIncrement(&pSocketObj->detectFails);
- ::ReadTimer(pSocketObj->fdTimer);
- }
- }
- #endif
|