UdpServer.cpp 27 KB

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