UdpServer.cpp 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231
  1. /*
  2. * Copyright: JessMA Open Source (ldcsaa@gmail.com)
  3. *
  4. * Author : Bruce Liang
  5. * Website : https://github.com/ldcsaa
  6. * Project : https://github.com/ldcsaa/HP-Socket
  7. * Blog : http://www.cnblogs.com/ldcsaa
  8. * Wiki : http://www.oschina.net/p/hp-socket
  9. * QQ Group : 44636872, 75375912
  10. *
  11. * Licensed under the Apache License, Version 2.0 (the "License");
  12. * you may not use this file except in compliance with the License.
  13. * You may obtain a copy of the License at
  14. *
  15. * http://www.apache.org/licenses/LICENSE-2.0
  16. *
  17. * Unless required by applicable law or agreed to in writing, software
  18. * distributed under the License is distributed on an "AS IS" BASIS,
  19. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20. * See the License for the specific language governing permissions and
  21. * limitations under the License.
  22. */
  23. #include "UdpServer.h"
  24. #ifdef _UDP_SUPPORT
  25. EnHandleResult CUdpServer::TriggerFireAccept(TUdpSocketObj* pSocketObj)
  26. {
  27. EnHandleResult rs = TRIGGER(FireAccept(pSocketObj));
  28. return rs;
  29. }
  30. BOOL CUdpServer::Start(LPCTSTR lpszBindAddress, USHORT usPort)
  31. {
  32. if(!CheckParams() || !CheckStarting())
  33. return FALSE;
  34. PrepareStart();
  35. if(CreateListenSocket(lpszBindAddress, usPort))
  36. if(CreateWorkerThreads())
  37. if(StartAccept())
  38. {
  39. m_enState = SS_STARTED;
  40. return TRUE;
  41. }
  42. EXECUTE_RESTORE_ERROR(Stop());
  43. return FALSE;
  44. }
  45. void CUdpServer::SetLastError(EnSocketError code, LPCSTR func, int ec)
  46. {
  47. m_enLastError = code;
  48. ::SetLastError(ec);
  49. }
  50. BOOL CUdpServer::CheckParams()
  51. {
  52. if ((m_enSendPolicy >= SP_PACK && m_enSendPolicy <= SP_DIRECT) &&
  53. (m_enOnSendSyncPolicy >= OSSP_NONE && m_enOnSendSyncPolicy <= OSSP_RECEIVE) &&
  54. ((int)m_dwMaxConnectionCount > 0 && m_dwMaxConnectionCount <= MAX_CONNECTION_COUNT) &&
  55. ((int)m_dwWorkerThreadCount > 0 && m_dwWorkerThreadCount <= MAX_WORKER_THREAD_COUNT) &&
  56. ((int)m_dwFreeSocketObjLockTime >= 1000) &&
  57. ((int)m_dwFreeSocketObjPool >= 0) &&
  58. ((int)m_dwFreeBufferObjPool >= 0) &&
  59. ((int)m_dwFreeSocketObjHold >= 0) &&
  60. ((int)m_dwFreeBufferObjHold >= 0) &&
  61. ((int)m_dwMaxDatagramSize > 0 && m_dwMaxDatagramSize <= MAXIMUM_UDP_MAX_DATAGRAM_SIZE) &&
  62. ((int)m_dwPostReceiveCount > 0) &&
  63. ((int)m_dwDetectAttempts >= 0) &&
  64. ((int)m_dwDetectInterval >= 1000 || m_dwDetectInterval == 0) )
  65. return TRUE;
  66. SetLastError(SE_INVALID_PARAM, __FUNCTION__, ERROR_INVALID_PARAMETER);
  67. return FALSE;
  68. }
  69. void CUdpServer::PrepareStart()
  70. {
  71. m_bfActiveSockets.Reset(m_dwMaxConnectionCount);
  72. m_lsFreeSocket.Reset(m_dwFreeSocketObjPool);
  73. m_bfObjPool.SetItemCapacity(m_dwMaxDatagramSize);
  74. m_bfObjPool.SetPoolSize(m_dwFreeBufferObjPool);
  75. m_bfObjPool.SetPoolHold(m_dwFreeBufferObjHold);
  76. m_bfObjPool.Prepare();
  77. m_quSends = make_unique<CSendQueue[]>(m_dwWorkerThreadCount);
  78. m_rcBuffers = make_unique<CBufferPtr[]>(m_dwWorkerThreadCount);
  79. for_each(m_rcBuffers.get(), m_rcBuffers.get() + m_dwWorkerThreadCount, [this](CBufferPtr& buff) {buff.Malloc(m_dwMaxDatagramSize);});
  80. m_soListens = make_unique<SOCKET[]>(m_dwWorkerThreadCount);
  81. for_each(m_soListens.get(), m_soListens.get() + m_dwWorkerThreadCount, [](SOCKET& sock) {sock = INVALID_FD;});
  82. }
  83. BOOL CUdpServer::CheckStarting()
  84. {
  85. CSpinLock locallock(m_csState);
  86. if(m_enState == SS_STOPPED)
  87. m_enState = SS_STARTING;
  88. else
  89. {
  90. SetLastError(SE_ILLEGAL_STATE, __FUNCTION__, ERROR_INVALID_STATE);
  91. return FALSE;
  92. }
  93. return TRUE;
  94. }
  95. BOOL CUdpServer::CheckStoping()
  96. {
  97. if(m_enState != SS_STOPPED)
  98. {
  99. CSpinLock locallock(m_csState);
  100. if(HasStarted())
  101. {
  102. m_enState = SS_STOPPING;
  103. return TRUE;
  104. }
  105. }
  106. SetLastError(SE_ILLEGAL_STATE, __FUNCTION__, ERROR_INVALID_STATE);
  107. return FALSE;
  108. }
  109. BOOL CUdpServer::CreateListenSocket(LPCTSTR lpszBindAddress, USHORT usPort)
  110. {
  111. if(::IsStrEmpty(lpszBindAddress))
  112. lpszBindAddress = DEFAULT_IPV4_BIND_ADDRESS;
  113. HP_SOCKADDR addr;
  114. if(!::sockaddr_A_2_IN(lpszBindAddress, usPort, addr))
  115. {
  116. SetLastError(SE_SOCKET_CREATE, __FUNCTION__, ::WSAGetLastError());
  117. return FALSE;
  118. }
  119. for(DWORD i = 0; i < m_dwWorkerThreadCount; i++)
  120. {
  121. m_soListens[i] = socket(addr.family, SOCK_DGRAM, IPPROTO_UDP);
  122. SOCKET soListen = m_soListens[i];
  123. if(IS_INVALID_FD(soListen))
  124. {
  125. SetLastError(SE_SOCKET_CREATE, __FUNCTION__, ::WSAGetLastError());
  126. return FALSE;
  127. }
  128. ::fcntl_SETFL(soListen, O_NOATIME | O_NONBLOCK | O_CLOEXEC);
  129. VERIFY(IS_NO_ERROR(::SSO_ReuseAddress(soListen, m_enReusePolicy)));
  130. if(IS_HAS_ERROR(::bind(soListen, addr.Addr(), addr.AddrSize())))
  131. {
  132. SetLastError(SE_SOCKET_BIND, __FUNCTION__, ::WSAGetLastError());
  133. return FALSE;
  134. }
  135. if(TRIGGER(FirePrepareListen(soListen)) == HR_ERROR)
  136. {
  137. SetLastError(SE_SOCKET_PREPARE, __FUNCTION__, ENSURE_ERROR_CANCELLED);
  138. return FALSE;
  139. }
  140. }
  141. return TRUE;
  142. }
  143. BOOL CUdpServer::CreateWorkerThreads()
  144. {
  145. DWORD dwWorkerThreadCount = m_dwWorkerThreadCount
  146. #ifdef USE_EXTERNAL_GC
  147. + 1
  148. #endif
  149. ;
  150. if(!m_ioDispatcher.Start(this, m_dwPostReceiveCount, dwWorkerThreadCount))
  151. {
  152. SetLastError(SE_WORKER_THREAD_CREATE, __FUNCTION__, ::WSAGetLastError());
  153. return FALSE;
  154. }
  155. #ifdef USE_EXTERNAL_GC
  156. m_fdGCTimer = m_ioDispatcher.AddTimer(m_dwWorkerThreadCount, GC_CHECK_INTERVAL, this);
  157. if(IS_INVALID_FD(m_fdGCTimer))
  158. {
  159. SetLastError(SE_GC_START, __FUNCTION__, ::WSAGetLastError());
  160. return FALSE;
  161. }
  162. #endif
  163. return TRUE;
  164. }
  165. BOOL CUdpServer::StartAccept()
  166. {
  167. for(int i = 0; i < (int)m_dwWorkerThreadCount; i++)
  168. {
  169. SOCKET& soListen = m_soListens[i];
  170. if(!m_ioDispatcher.AddFD(i, soListen, EPOLLIN | EPOLLOUT | EPOLLET, TO_PVOID(&soListen)))
  171. {
  172. SetLastError(SE_SOCKE_ATTACH_TO_CP, __FUNCTION__, ::WSAGetLastError());
  173. return FALSE;
  174. }
  175. }
  176. #ifdef USE_EXTERNAL_GC
  177. m_fdGCTimer = m_ioDispatcher.AddTimer(m_dwWorkerThreadCount, GC_CHECK_INTERVAL, this);
  178. if(IS_INVALID_FD(m_fdGCTimer))
  179. {
  180. SetLastError(SE_GC_START, __FUNCTION__, ::WSAGetLastError());
  181. return FALSE;
  182. }
  183. #endif
  184. return TRUE;
  185. }
  186. BOOL CUdpServer::Stop()
  187. {
  188. if(!CheckStoping())
  189. return FALSE;
  190. SendCloseNotify();
  191. CloseListenSocket();
  192. DisconnectClientSocket();
  193. WaitForClientSocketClose();
  194. WaitForWorkerThreadEnd();
  195. ReleaseClientSocket();
  196. FireShutdown();
  197. ReleaseFreeSocket();
  198. ClearSendQueues();
  199. Reset();
  200. return TRUE;
  201. }
  202. void CUdpServer::SendCloseNotify()
  203. {
  204. if(!m_soListens)
  205. return;
  206. if(m_bfActiveSockets.Elements() == 0)
  207. return;
  208. TUdpSocketObjPtrPool::IndexSet indexes;
  209. m_bfActiveSockets.CopyIndexes(indexes);
  210. for(auto it = indexes.begin(), end = indexes.end(); it != end; ++it)
  211. {
  212. CONNID connID = *it;
  213. TUdpSocketObj* pSocketObj = FindSocketObj(connID);
  214. if(TUdpSocketObj::IsValid(pSocketObj))
  215. ::SendUdpCloseNotify(m_soListens[pSocketObj->index], pSocketObj->remoteAddr);
  216. }
  217. ::WaitFor(30);
  218. }
  219. void CUdpServer::CloseListenSocket()
  220. {
  221. if(m_soListens)
  222. {
  223. for_each(m_soListens.get(), m_soListens.get() + m_dwWorkerThreadCount, [](SOCKET& sock)
  224. {
  225. if(sock != INVALID_FD)
  226. {
  227. ::ManualCloseSocket(sock);
  228. sock = INVALID_FD;
  229. }
  230. });
  231. ::WaitFor(70);
  232. }
  233. }
  234. void CUdpServer::DisconnectClientSocket()
  235. {
  236. if(m_bfActiveSockets.Elements() == 0)
  237. return;
  238. TUdpSocketObjPtrPool::IndexSet indexes;
  239. m_bfActiveSockets.CopyIndexes(indexes);
  240. for(auto it = indexes.begin(), end = indexes.end(); it != end; ++it)
  241. Disconnect(*it);
  242. }
  243. void CUdpServer::WaitForClientSocketClose()
  244. {
  245. while(m_bfActiveSockets.Elements() > 0)
  246. ::WaitFor(50);
  247. }
  248. void CUdpServer::WaitForWorkerThreadEnd()
  249. {
  250. m_ioDispatcher.Stop();
  251. }
  252. void CUdpServer::ReleaseClientSocket()
  253. {
  254. VERIFY(m_bfActiveSockets.IsEmpty());
  255. m_bfActiveSockets.Reset();
  256. CWriteLock locallock(m_csClientSocket);
  257. m_mpClientAddr.clear();
  258. }
  259. void CUdpServer::ReleaseFreeSocket()
  260. {
  261. m_lsFreeSocket.Clear();
  262. #ifdef USE_EXTERNAL_GC
  263. if(IS_VALID_FD(m_fdGCTimer))
  264. {
  265. close(m_fdGCTimer);
  266. m_fdGCTimer = INVALID_FD;
  267. }
  268. #endif
  269. ReleaseGCSocketObj(TRUE);
  270. VERIFY(m_lsGCSocket.IsEmpty());
  271. }
  272. void CUdpServer::ClearSendQueues()
  273. {
  274. if(m_quSends) for_each(m_quSends.get(), m_quSends.get() + m_dwWorkerThreadCount, [](CSendQueue& queue) {queue.UnsafeClear();});
  275. }
  276. void CUdpServer::Reset()
  277. {
  278. m_phSocket.Reset();
  279. m_bfObjPool.Clear();
  280. m_soListens = nullptr;
  281. m_rcBuffers = nullptr;
  282. m_quSends = nullptr;
  283. m_enState = SS_STOPPED;
  284. m_evWait.SyncNotifyAll();
  285. }
  286. TUdpSocketObj* CUdpServer::GetFreeSocketObj(CONNID dwConnID)
  287. {
  288. DWORD dwIndex;
  289. TUdpSocketObj* pSocketObj = nullptr;
  290. if(m_lsFreeSocket.TryLock(&pSocketObj, dwIndex))
  291. {
  292. if(::GetTimeGap32(pSocketObj->freeTime) >= m_dwFreeSocketObjLockTime)
  293. VERIFY(m_lsFreeSocket.ReleaseLock(nullptr, dwIndex));
  294. else
  295. {
  296. VERIFY(m_lsFreeSocket.ReleaseLock(pSocketObj, dwIndex));
  297. pSocketObj = nullptr;
  298. }
  299. }
  300. if(!pSocketObj) pSocketObj = CreateSocketObj();
  301. pSocketObj->Reset(dwConnID);
  302. return pSocketObj;
  303. }
  304. TUdpSocketObj* CUdpServer::CreateSocketObj()
  305. {
  306. return TUdpSocketObj::Construct(m_phSocket, m_bfObjPool);
  307. }
  308. void CUdpServer::DeleteSocketObj(TUdpSocketObj* pSocketObj)
  309. {
  310. TUdpSocketObj::Destruct(pSocketObj);
  311. }
  312. void CUdpServer::AddFreeSocketObj(TUdpSocketObj* pSocketObj, EnSocketCloseFlag enFlag, EnSocketOperation enOperation, int iErrorCode, BOOL bNotify)
  313. {
  314. if(!InvalidSocketObj(pSocketObj))
  315. return;
  316. CloseClientSocketObj(pSocketObj, enFlag, enOperation, iErrorCode, bNotify);
  317. {
  318. m_bfActiveSockets.Remove(pSocketObj->connID);
  319. CWriteLock locallock(m_csClientSocket);
  320. m_mpClientAddr.erase(&pSocketObj->remoteAddr);
  321. }
  322. m_ioDispatcher.DelTimer(pSocketObj->index, pSocketObj->fdTimer);
  323. TUdpSocketObj::Release(pSocketObj);
  324. #ifndef USE_EXTERNAL_GC
  325. ReleaseGCSocketObj();
  326. #endif
  327. if(!m_lsFreeSocket.TryPut(pSocketObj))
  328. m_lsGCSocket.PushBack(pSocketObj);
  329. }
  330. void CUdpServer::ReleaseGCSocketObj(BOOL bForce)
  331. {
  332. ::ReleaseGCObj(m_lsGCSocket, m_dwFreeSocketObjLockTime, bForce);
  333. }
  334. BOOL CUdpServer::InvalidSocketObj(TUdpSocketObj* pSocketObj)
  335. {
  336. return TUdpSocketObj::InvalidSocketObj(pSocketObj);
  337. }
  338. void CUdpServer::AddClientSocketObj(int idx, CONNID dwConnID, TUdpSocketObj* pSocketObj, const HP_SOCKADDR& remoteAddr)
  339. {
  340. ASSERT(FindSocketObj(dwConnID) == nullptr);
  341. pSocketObj->index = idx;
  342. pSocketObj->pHolder = this;
  343. pSocketObj->connTime = ::TimeGetTime();
  344. pSocketObj->activeTime = pSocketObj->connTime;
  345. if(IsNeedDetectConnection())
  346. pSocketObj->fdTimer = m_ioDispatcher.AddTimer(pSocketObj->index, m_dwDetectInterval, pSocketObj);
  347. remoteAddr.Copy(pSocketObj->remoteAddr);
  348. pSocketObj->SetConnected();
  349. VERIFY(m_bfActiveSockets.ReleaseLock(dwConnID, pSocketObj));
  350. CWriteLock locallock(m_csClientSocket);
  351. m_mpClientAddr[&pSocketObj->remoteAddr] = dwConnID;
  352. }
  353. TUdpSocketObj* CUdpServer::FindSocketObj(CONNID dwConnID)
  354. {
  355. TUdpSocketObj* pSocketObj = nullptr;
  356. if(m_bfActiveSockets.Get(dwConnID, &pSocketObj) != TUdpSocketObjPtrPool::GR_VALID)
  357. pSocketObj = nullptr;
  358. return pSocketObj;
  359. }
  360. CONNID CUdpServer::FindConnectionID(const HP_SOCKADDR* pAddr)
  361. {
  362. CONNID dwConnID = 0;
  363. CReadLock locallock(m_csClientSocket);
  364. TSockAddrMapCI it = m_mpClientAddr.find(pAddr);
  365. if(it != m_mpClientAddr.end())
  366. dwConnID = it->second;
  367. return dwConnID;
  368. }
  369. void CUdpServer::CloseClientSocketObj(TUdpSocketObj* pSocketObj, EnSocketCloseFlag enFlag, EnSocketOperation enOperation, int iErrorCode, BOOL bNotify)
  370. {
  371. ASSERT(TUdpSocketObj::IsExist(pSocketObj));
  372. SOCKET soListen = m_soListens[pSocketObj->index];
  373. if(bNotify && soListen != INVALID_SOCKET)
  374. ::SendUdpCloseNotify(soListen, pSocketObj->remoteAddr);
  375. if(enFlag == SCF_CLOSE)
  376. FireClose(pSocketObj, SO_CLOSE, SE_OK);
  377. else if(enFlag == SCF_ERROR)
  378. FireClose(pSocketObj, enOperation, iErrorCode);
  379. }
  380. BOOL CUdpServer::GetListenAddress(TCHAR lpszAddress[], int& iAddressLen, USHORT& usPort)
  381. {
  382. ASSERT(lpszAddress != nullptr && iAddressLen > 0);
  383. if(!HasStarted())
  384. {
  385. ::SetLastError(ERROR_INVALID_STATE);
  386. return FALSE;
  387. }
  388. return ::GetSocketLocalAddress(m_soListens[0], lpszAddress, iAddressLen, usPort);
  389. }
  390. BOOL CUdpServer::GetLocalAddress(CONNID dwConnID, TCHAR lpszAddress[], int& iAddressLen, USHORT& usPort)
  391. {
  392. ASSERT(lpszAddress != nullptr && iAddressLen > 0);
  393. TUdpSocketObj* pSocketObj = FindSocketObj(dwConnID);
  394. if(!TUdpSocketObj::IsValid(pSocketObj))
  395. {
  396. ::SetLastError(ERROR_OBJECT_NOT_FOUND);
  397. return FALSE;
  398. }
  399. return ::GetSocketLocalAddress(m_soListens[pSocketObj->index], lpszAddress, iAddressLen, usPort);
  400. }
  401. BOOL CUdpServer::GetRemoteAddress(CONNID dwConnID, TCHAR lpszAddress[], int& iAddressLen, USHORT& usPort)
  402. {
  403. ASSERT(lpszAddress != nullptr && iAddressLen > 0);
  404. TUdpSocketObj* pSocketObj = FindSocketObj(dwConnID);
  405. if(!TUdpSocketObj::IsExist(pSocketObj))
  406. {
  407. ::SetLastError(ERROR_OBJECT_NOT_FOUND);
  408. return FALSE;
  409. }
  410. ADDRESS_FAMILY usFamily;
  411. return ::sockaddr_IN_2_A(pSocketObj->remoteAddr, usFamily, lpszAddress, iAddressLen, usPort);
  412. }
  413. BOOL CUdpServer::SetConnectionExtra(CONNID dwConnID, PVOID pExtra)
  414. {
  415. TUdpSocketObj* pSocketObj = FindSocketObj(dwConnID);
  416. return SetConnectionExtra(pSocketObj, pExtra);
  417. }
  418. BOOL CUdpServer::SetConnectionExtra(TUdpSocketObj* pSocketObj, PVOID pExtra)
  419. {
  420. if(!TUdpSocketObj::IsExist(pSocketObj))
  421. ::SetLastError(ERROR_OBJECT_NOT_FOUND);
  422. else
  423. {
  424. pSocketObj->extra = pExtra;
  425. return TRUE;
  426. }
  427. return FALSE;
  428. }
  429. BOOL CUdpServer::GetConnectionExtra(CONNID dwConnID, PVOID* ppExtra)
  430. {
  431. TUdpSocketObj* pSocketObj = FindSocketObj(dwConnID);
  432. return GetConnectionExtra(pSocketObj, ppExtra);
  433. }
  434. BOOL CUdpServer::GetConnectionExtra(TUdpSocketObj* pSocketObj, PVOID* ppExtra)
  435. {
  436. ASSERT(ppExtra != nullptr);
  437. if(!TUdpSocketObj::IsExist(pSocketObj))
  438. ::SetLastError(ERROR_OBJECT_NOT_FOUND);
  439. else
  440. {
  441. *ppExtra = pSocketObj->extra;
  442. return TRUE;
  443. }
  444. return FALSE;
  445. }
  446. BOOL CUdpServer::SetConnectionReserved(CONNID dwConnID, PVOID pReserved)
  447. {
  448. TUdpSocketObj* pSocketObj = FindSocketObj(dwConnID);
  449. return SetConnectionReserved(pSocketObj, pReserved);
  450. }
  451. BOOL CUdpServer::SetConnectionReserved(TUdpSocketObj* pSocketObj, PVOID pReserved)
  452. {
  453. if(!TUdpSocketObj::IsExist(pSocketObj))
  454. ::SetLastError(ERROR_OBJECT_NOT_FOUND);
  455. else
  456. {
  457. pSocketObj->reserved = pReserved;
  458. return TRUE;
  459. }
  460. return FALSE;
  461. }
  462. BOOL CUdpServer::GetConnectionReserved(CONNID dwConnID, PVOID* ppReserved)
  463. {
  464. TUdpSocketObj* pSocketObj = FindSocketObj(dwConnID);
  465. return GetConnectionReserved(pSocketObj, ppReserved);
  466. }
  467. BOOL CUdpServer::GetConnectionReserved(TUdpSocketObj* pSocketObj, PVOID* ppReserved)
  468. {
  469. ASSERT(ppReserved != nullptr);
  470. if(!TUdpSocketObj::IsExist(pSocketObj))
  471. ::SetLastError(ERROR_OBJECT_NOT_FOUND);
  472. else
  473. {
  474. *ppReserved = pSocketObj->reserved;
  475. return TRUE;
  476. }
  477. return FALSE;
  478. }
  479. BOOL CUdpServer::SetConnectionReserved2(CONNID dwConnID, PVOID pReserved2)
  480. {
  481. TUdpSocketObj* pSocketObj = FindSocketObj(dwConnID);
  482. return SetConnectionReserved2(pSocketObj, pReserved2);
  483. }
  484. BOOL CUdpServer::SetConnectionReserved2(TUdpSocketObj* pSocketObj, PVOID pReserved2)
  485. {
  486. if(!TUdpSocketObj::IsExist(pSocketObj))
  487. ::SetLastError(ERROR_OBJECT_NOT_FOUND);
  488. else
  489. {
  490. pSocketObj->reserved2 = pReserved2;
  491. return TRUE;
  492. }
  493. return FALSE;
  494. }
  495. BOOL CUdpServer::GetConnectionReserved2(CONNID dwConnID, PVOID* ppReserved2)
  496. {
  497. TUdpSocketObj* pSocketObj = FindSocketObj(dwConnID);
  498. return GetConnectionReserved2(pSocketObj, ppReserved2);
  499. }
  500. BOOL CUdpServer::GetConnectionReserved2(TUdpSocketObj* pSocketObj, PVOID* ppReserved2)
  501. {
  502. ASSERT(ppReserved2 != nullptr);
  503. if(!TUdpSocketObj::IsExist(pSocketObj))
  504. ::SetLastError(ERROR_OBJECT_NOT_FOUND);
  505. else
  506. {
  507. *ppReserved2 = pSocketObj->reserved2;
  508. return TRUE;
  509. }
  510. return FALSE;
  511. }
  512. BOOL CUdpServer::IsPauseReceive(CONNID dwConnID, BOOL& bPaused)
  513. {
  514. ::SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
  515. bPaused = FALSE;
  516. return FALSE;
  517. }
  518. BOOL CUdpServer::IsConnected(CONNID dwConnID)
  519. {
  520. TUdpSocketObj* pSocketObj = FindSocketObj(dwConnID);
  521. if(!TUdpSocketObj::IsValid(pSocketObj))
  522. {
  523. ::SetLastError(ERROR_OBJECT_NOT_FOUND);
  524. return FALSE;
  525. }
  526. return pSocketObj->HasConnected();
  527. }
  528. BOOL CUdpServer::GetPendingDataLength(CONNID dwConnID, int& iPending)
  529. {
  530. TUdpSocketObj* pSocketObj = FindSocketObj(dwConnID);
  531. if(!TUdpSocketObj::IsValid(pSocketObj))
  532. ::SetLastError(ERROR_OBJECT_NOT_FOUND);
  533. else
  534. {
  535. iPending = pSocketObj->Pending();
  536. return TRUE;
  537. }
  538. return FALSE;
  539. }
  540. DWORD CUdpServer::GetConnectionCount()
  541. {
  542. return m_bfActiveSockets.Elements();
  543. }
  544. BOOL CUdpServer::GetAllConnectionIDs(CONNID pIDs[], DWORD& dwCount)
  545. {
  546. return m_bfActiveSockets.GetAllElementIndexes(pIDs, dwCount);
  547. }
  548. BOOL CUdpServer::GetConnectPeriod(CONNID dwConnID, DWORD& dwPeriod)
  549. {
  550. BOOL isOK = TRUE;
  551. TUdpSocketObj* pSocketObj = FindSocketObj(dwConnID);
  552. if(TUdpSocketObj::IsValid(pSocketObj))
  553. dwPeriod = ::GetTimeGap32(pSocketObj->connTime);
  554. else
  555. {
  556. ::SetLastError(ERROR_OBJECT_NOT_FOUND);
  557. isOK = FALSE;
  558. }
  559. return isOK;
  560. }
  561. BOOL CUdpServer::GetSilencePeriod(CONNID dwConnID, DWORD& dwPeriod)
  562. {
  563. if(!m_bMarkSilence)
  564. return FALSE;
  565. BOOL isOK = TRUE;
  566. TUdpSocketObj* pSocketObj = FindSocketObj(dwConnID);
  567. if(TUdpSocketObj::IsValid(pSocketObj))
  568. dwPeriod = ::GetTimeGap32(pSocketObj->activeTime);
  569. else
  570. {
  571. ::SetLastError(ERROR_OBJECT_NOT_FOUND);
  572. isOK = FALSE;
  573. }
  574. return isOK;
  575. }
  576. BOOL CUdpServer::Disconnect(CONNID dwConnID, BOOL bForce)
  577. {
  578. TUdpSocketObj* pSocketObj = FindSocketObj(dwConnID);
  579. if(!TUdpSocketObj::IsValid(pSocketObj))
  580. {
  581. ::SetLastError(ERROR_OBJECT_NOT_FOUND);
  582. return FALSE;
  583. }
  584. return m_ioDispatcher.SendCommandByIndex(pSocketObj->index, DISP_CMD_DISCONNECT, dwConnID, bForce);
  585. }
  586. BOOL CUdpServer::DisconnectLongConnections(DWORD dwPeriod, BOOL bForce)
  587. {
  588. if(dwPeriod > MAX_CONNECTION_PERIOD)
  589. return FALSE;
  590. if(m_bfActiveSockets.Elements() == 0)
  591. return TRUE;
  592. DWORD now = ::TimeGetTime();
  593. TUdpSocketObjPtrPool::IndexSet indexes;
  594. m_bfActiveSockets.CopyIndexes(indexes);
  595. for(auto it = indexes.begin(), end = indexes.end(); it != end; ++it)
  596. {
  597. CONNID connID = *it;
  598. TUdpSocketObj* pSocketObj = FindSocketObj(connID);
  599. if(TUdpSocketObj::IsValid(pSocketObj) && (int)(now - pSocketObj->connTime) >= (int)dwPeriod)
  600. Disconnect(connID, bForce);
  601. }
  602. return TRUE;
  603. }
  604. BOOL CUdpServer::DisconnectSilenceConnections(DWORD dwPeriod, BOOL bForce)
  605. {
  606. if(!m_bMarkSilence)
  607. return FALSE;
  608. if(dwPeriod > MAX_CONNECTION_PERIOD)
  609. return FALSE;
  610. if(m_bfActiveSockets.Elements() == 0)
  611. return TRUE;
  612. DWORD now = ::TimeGetTime();
  613. TUdpSocketObjPtrPool::IndexSet indexes;
  614. m_bfActiveSockets.CopyIndexes(indexes);
  615. for(auto it = indexes.begin(), end = indexes.end(); it != end; ++it)
  616. {
  617. CONNID connID = *it;
  618. TUdpSocketObj* pSocketObj = FindSocketObj(connID);
  619. if(TUdpSocketObj::IsValid(pSocketObj) && (int)(now - pSocketObj->activeTime) >= (int)dwPeriod)
  620. Disconnect(connID, bForce);
  621. }
  622. return TRUE;
  623. }
  624. BOOL CUdpServer::PauseReceive(CONNID dwConnID, BOOL bPause)
  625. {
  626. ::SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
  627. return FALSE;
  628. }
  629. BOOL CUdpServer::OnBeforeProcessIo(const TDispContext* pContext, PVOID pv, UINT events)
  630. {
  631. if(pv == &m_soListens[pContext->GetIndex()])
  632. return TRUE;
  633. else if(pv == this)
  634. {
  635. ReleaseGCSocketObj(FALSE);
  636. ::ReadTimer(m_fdGCTimer);
  637. return FALSE;
  638. }
  639. if(!(events & _EPOLL_ALL_ERROR_EVENTS))
  640. DetectConnection(pv);
  641. return FALSE;
  642. }
  643. VOID CUdpServer::OnAfterProcessIo(const TDispContext* pContext, PVOID pv, UINT events, BOOL rs)
  644. {
  645. }
  646. VOID CUdpServer::OnCommand(const TDispContext* pContext, TDispCommand* pCmd)
  647. {
  648. CONNID dwConnID = (CONNID)(pCmd->wParam);
  649. switch(pCmd->type)
  650. {
  651. case DISP_CMD_SEND:
  652. HandleCmdSend(dwConnID, (int)(pCmd->lParam));
  653. break;
  654. case DISP_CMD_DISCONNECT:
  655. HandleCmdDisconnect(dwConnID, (BOOL)pCmd->lParam);
  656. break;
  657. case DISP_CMD_TIMEOUT:
  658. HandleCmdTimeout(dwConnID);
  659. break;
  660. }
  661. }
  662. VOID CUdpServer::HandleCmdDisconnect(CONNID dwConnID, BOOL bForce)
  663. {
  664. AddFreeSocketObj(FindSocketObj(dwConnID), SCF_CLOSE);
  665. }
  666. VOID CUdpServer::HandleCmdTimeout(CONNID dwConnID)
  667. {
  668. AddFreeSocketObj(FindSocketObj(dwConnID), SCF_CLOSE, SO_UNKNOWN, 0, FALSE);
  669. }
  670. BOOL CUdpServer::OnReadyRead(const TDispContext* pContext, PVOID pv, UINT events)
  671. {
  672. return HandleReceive(pContext, RETRIVE_EVENT_FLAG_H(events));
  673. }
  674. BOOL CUdpServer::OnReadyWrite(const TDispContext* pContext, PVOID pv, UINT events)
  675. {
  676. return HandleSend(pContext, RETRIVE_EVENT_FLAG_H(events));
  677. }
  678. BOOL CUdpServer::OnHungUp(const TDispContext* pContext, PVOID pv, UINT events)
  679. {
  680. return HandleClose(nullptr, SO_CLOSE, 0);
  681. }
  682. BOOL CUdpServer::OnError(const TDispContext* pContext, PVOID pv, UINT events)
  683. {
  684. return HandleClose(nullptr, SO_CLOSE, -1);
  685. }
  686. VOID CUdpServer::OnDispatchThreadStart(THR_ID tid)
  687. {
  688. OnWorkerThreadStart(tid);
  689. }
  690. VOID CUdpServer::OnDispatchThreadEnd(THR_ID tid)
  691. {
  692. OnWorkerThreadEnd(tid);
  693. }
  694. BOOL CUdpServer::HandleClose(TUdpSocketObj* pSocketObj, EnSocketOperation enOperation, int iErrorCode)
  695. {
  696. if(!HasStarted())
  697. return FALSE;
  698. else if(pSocketObj == nullptr)
  699. {
  700. TRACE("HandleClose() -> OP: %d, EC: %d", enOperation, iErrorCode);
  701. return TRUE;
  702. }
  703. if(iErrorCode == -1)
  704. iErrorCode = ::SSO_GetError(m_soListens[pSocketObj->index]);
  705. EnSocketCloseFlag enFlag = IS_NO_ERROR(iErrorCode) ? SCF_CLOSE : SCF_ERROR;
  706. AddFreeSocketObj(pSocketObj, enFlag, enOperation, iErrorCode);
  707. return FALSE;
  708. }
  709. BOOL CUdpServer::HandleReceive(const TDispContext* pContext, int flag)
  710. {
  711. int idx = pContext->GetIndex();
  712. CBufferPtr& buffer = m_rcBuffers[idx];
  713. int iBufferLen = (int)buffer.Size();
  714. while(TRUE)
  715. {
  716. HP_SOCKADDR addr;
  717. socklen_t dwAddrLen = (socklen_t)addr.AddrSize();
  718. int rc = (int)recvfrom(m_soListens[idx], buffer.Ptr(), iBufferLen, MSG_TRUNC, addr.Addr(), &dwAddrLen);
  719. if(rc >= 0)
  720. {
  721. CONNID dwConnID = FindConnectionID(&addr);
  722. if(dwConnID == 0)
  723. {
  724. if(rc > iBufferLen)
  725. continue;
  726. if((dwConnID = HandleAccept(pContext, addr)) == 0)
  727. continue;
  728. }
  729. TUdpSocketObj* pSocketObj = FindSocketObj(dwConnID);
  730. ASSERT(pSocketObj->index == idx);
  731. if(!TUdpSocketObj::IsValid(pSocketObj))
  732. continue;
  733. if(rc == 0)
  734. {
  735. HandleZeroBytes(pSocketObj);
  736. continue;
  737. }
  738. if(rc > iBufferLen)
  739. {
  740. AddFreeSocketObj(pSocketObj, SCF_ERROR, SO_RECEIVE, ERROR_BAD_LENGTH);
  741. continue;
  742. }
  743. if(::IsUdpCloseNotify(buffer.Ptr(), rc))
  744. {
  745. AddFreeSocketObj(pSocketObj, SCF_CLOSE, SO_CLOSE, SE_OK, FALSE);
  746. continue;
  747. }
  748. if(TRIGGER(FireReceive(pSocketObj, buffer.Ptr(), rc)) == HR_ERROR)
  749. {
  750. TRACE("<S-CNNID: %zu> OnReceive() event return 'HR_ERROR', connection will be closed !", dwConnID);
  751. AddFreeSocketObj(pSocketObj, SCF_ERROR, SO_RECEIVE, ENSURE_ERROR_CANCELLED);;
  752. continue;
  753. }
  754. }
  755. else if(rc == SOCKET_ERROR)
  756. {
  757. int code = ::WSAGetLastError();
  758. if(code == ERROR_WOULDBLOCK)
  759. break;
  760. else if(!HandleClose(nullptr, SO_RECEIVE, code))
  761. return FALSE;
  762. }
  763. else
  764. {
  765. ASSERT(FALSE);
  766. }
  767. }
  768. return TRUE;
  769. }
  770. CONNID CUdpServer::HandleAccept(const TDispContext* pContext, HP_SOCKADDR& addr)
  771. {
  772. int idx = pContext->GetIndex();
  773. CONNID dwConnID = 0;
  774. TUdpSocketObj* pSocketObj = nullptr;
  775. if(!m_bfActiveSockets.AcquireLock(dwConnID))
  776. {
  777. ::SendUdpCloseNotify(m_soListens[idx], addr);
  778. return 0;
  779. }
  780. pSocketObj = GetFreeSocketObj(dwConnID);
  781. AddClientSocketObj(idx, dwConnID, pSocketObj, addr);
  782. if(TriggerFireAccept(pSocketObj) == HR_ERROR)
  783. {
  784. AddFreeSocketObj(pSocketObj);
  785. dwConnID = 0;
  786. }
  787. return dwConnID;
  788. }
  789. void CUdpServer::HandleZeroBytes(TUdpSocketObj* pSocketObj)
  790. {
  791. TRACE("<S-CNNID: %zu> recv 0 bytes (detect package)", pSocketObj->connID);
  792. pSocketObj->detectFails = 0;
  793. #if defined(DEBUG_TRACE)
  794. int rc = (int)
  795. #endif
  796. sendto(m_soListens[pSocketObj->index], nullptr, 0, 0, pSocketObj->remoteAddr.Addr(), pSocketObj->remoteAddr.AddrSize());
  797. TRACE("<S-CNNID: %zu> send 0 bytes (detect ack package - %s)", pSocketObj->connID, IS_HAS_ERROR(rc) ? "fail" : "succ");
  798. }
  799. BOOL CUdpServer::HandleSend(const TDispContext* pContext, int flag)
  800. {
  801. CSendQueue& quSend = m_quSends[pContext->GetIndex()];
  802. CONNID dwConnID = 0;
  803. while(quSend.PopFront(&dwConnID))
  804. HandleCmdSend(dwConnID, flag);
  805. return TRUE;
  806. }
  807. VOID CUdpServer::HandleCmdSend(CONNID dwConnID, int flag)
  808. {
  809. TUdpSocketObj* pSocketObj = FindSocketObj(dwConnID);
  810. if(!TUdpSocketObj::IsValid(pSocketObj) || !pSocketObj->IsPending())
  811. return;
  812. BOOL bBlocked = FALSE;
  813. int writes = flag ? -1 : MAX_CONTINUE_WRITES;
  814. TBufferObjList& sndBuff = pSocketObj->sndBuff;
  815. TItemPtr itPtr(sndBuff);
  816. for(int i = 0; i < writes || writes < 0; i++)
  817. {
  818. {
  819. CReentrantCriSecLock locallock(pSocketObj->csSend);
  820. itPtr = sndBuff.PopFront();
  821. }
  822. if(!itPtr.IsValid())
  823. break;
  824. ASSERT(!itPtr->IsEmpty());
  825. if(!SendItem(pSocketObj, itPtr, bBlocked))
  826. return;
  827. if(bBlocked)
  828. {
  829. {
  830. CReentrantCriSecLock locallock(pSocketObj->csSend);
  831. sndBuff.PushFront(itPtr.Detach());
  832. }
  833. m_quSends[pSocketObj->index].PushBack(dwConnID);
  834. break;
  835. }
  836. }
  837. if(!bBlocked && pSocketObj->IsPending())
  838. VERIFY(m_ioDispatcher.SendCommandByIndex(pSocketObj->index, DISP_CMD_SEND, dwConnID));
  839. }
  840. BOOL CUdpServer::SendItem(TUdpSocketObj* pSocketObj, TItem* pItem, BOOL& bBlocked)
  841. {
  842. int rc = (int)sendto(m_soListens[pSocketObj->index], pItem->Ptr(), pItem->Size(), 0, pSocketObj->remoteAddr.Addr(), pSocketObj->remoteAddr.AddrSize());
  843. if(rc > 0)
  844. {
  845. ASSERT(rc == pItem->Size());
  846. if(TRIGGER(FireSend(pSocketObj, pItem->Ptr(), rc)) == HR_ERROR)
  847. {
  848. TRACE("<S-CNNID: %zu> OnSend() event should not return 'HR_ERROR' !!", pSocketObj->connID);
  849. ASSERT(FALSE);
  850. }
  851. }
  852. else if(rc == SOCKET_ERROR)
  853. {
  854. int code = ::WSAGetLastError();
  855. if(code == ERROR_WOULDBLOCK)
  856. bBlocked = TRUE;
  857. else if(!HandleClose(pSocketObj, SO_SEND, code))
  858. return FALSE;
  859. }
  860. else
  861. ASSERT(FALSE);
  862. return TRUE;
  863. }
  864. BOOL CUdpServer::Send(CONNID dwConnID, const BYTE* pBuffer, int iLength, int iOffset)
  865. {
  866. ASSERT(pBuffer && iLength > 0 && iLength <= (int)m_dwMaxDatagramSize);
  867. TUdpSocketObj* pSocketObj = FindSocketObj(dwConnID);
  868. return DoSend(pSocketObj, pBuffer, iLength, iOffset);
  869. }
  870. BOOL CUdpServer::DoSend(TUdpSocketObj* pSocketObj, const BYTE* pBuffer, int iLength, int iOffset)
  871. {
  872. int result = NO_ERROR;
  873. if(TUdpSocketObj::IsValid(pSocketObj))
  874. {
  875. if(pBuffer && iLength > 0 && iLength <= (int)m_dwMaxDatagramSize)
  876. {
  877. if(iOffset != 0) pBuffer += iOffset;
  878. TItemPtr itPtr(m_bfObjPool, m_bfObjPool.PickFreeItem());
  879. itPtr->Cat(pBuffer, iLength);
  880. result = SendInternal(pSocketObj, itPtr);
  881. }
  882. else
  883. result = ERROR_INVALID_PARAMETER;
  884. }
  885. else
  886. result = ERROR_OBJECT_NOT_FOUND;
  887. if(result != NO_ERROR)
  888. ::SetLastError(result);
  889. return (result == NO_ERROR);
  890. }
  891. BOOL CUdpServer::SendPackets(CONNID dwConnID, const WSABUF pBuffers[], int iCount)
  892. {
  893. ASSERT(pBuffers && iCount > 0);
  894. if(!pBuffers || iCount <= 0)
  895. return ERROR_INVALID_PARAMETER;
  896. TUdpSocketObj* pSocketObj = FindSocketObj(dwConnID);
  897. if(!TUdpSocketObj::IsValid(pSocketObj))
  898. {
  899. ::SetLastError(ERROR_OBJECT_NOT_FOUND);
  900. return FALSE;
  901. }
  902. int result = NO_ERROR;
  903. int iLength = 0;
  904. int iMaxLen = (int)m_dwMaxDatagramSize;
  905. TItemPtr itPtr(m_bfObjPool, m_bfObjPool.PickFreeItem());
  906. for(int i = 0; i < iCount; i++)
  907. {
  908. int iBufLen = pBuffers[i].len;
  909. if(iBufLen > 0)
  910. {
  911. BYTE* pBuffer = (BYTE*)pBuffers[i].buf;
  912. ASSERT(pBuffer);
  913. iLength += iBufLen;
  914. if(iLength <= iMaxLen)
  915. itPtr->Cat(pBuffer, iBufLen);
  916. else
  917. break;
  918. }
  919. }
  920. if(iLength > 0 && iLength <= iMaxLen)
  921. result = SendInternal(pSocketObj, itPtr);
  922. else
  923. result = ERROR_INCORRECT_SIZE;
  924. if(result != NO_ERROR)
  925. ::SetLastError(result);
  926. return (result == NO_ERROR);
  927. }
  928. int CUdpServer::SendInternal(TUdpSocketObj* pSocketObj, TItemPtr& itPtr)
  929. {
  930. BOOL bPending;
  931. {
  932. CLocalSafeCounter localcounter(*pSocketObj);
  933. CReentrantCriSecLock locallock(pSocketObj->csSend);
  934. if(!TUdpSocketObj::IsValid(pSocketObj))
  935. return ERROR_OBJECT_NOT_FOUND;
  936. bPending = pSocketObj->IsPending();
  937. pSocketObj->sndBuff.PushBack(itPtr.Detach());
  938. ASSERT(pSocketObj->sndBuff.Length() > 0);
  939. }
  940. if(!bPending && pSocketObj->IsPending())
  941. VERIFY(m_ioDispatcher.SendCommandByIndex(pSocketObj->index, DISP_CMD_SEND, pSocketObj->connID));
  942. return NO_ERROR;
  943. }
  944. void CUdpServer::DetectConnection(PVOID pv)
  945. {
  946. TUdpSocketObj* pSocketObj = (TUdpSocketObj*)pv;
  947. if(TUdpSocketObj::IsValid(pSocketObj))
  948. {
  949. CUdpServer* pServer = (CUdpServer*)pSocketObj->pHolder;
  950. if(pSocketObj->detectFails >= pServer->m_dwDetectAttempts)
  951. VERIFY(m_ioDispatcher.SendCommandByIndex(pSocketObj->index, DISP_CMD_TIMEOUT, pSocketObj->connID));
  952. else
  953. ::InterlockedIncrement(&pSocketObj->detectFails);
  954. ::ReadTimer(pSocketObj->fdTimer);
  955. }
  956. }
  957. #endif