ioqueue_winnt.c 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514
  1. /*
  2. * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
  3. * Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 2 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program; if not, write to the Free Software
  17. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  18. */
  19. #include <pj/ioqueue.h>
  20. #include <pj/os.h>
  21. #include <pj/lock.h>
  22. #include <pj/pool.h>
  23. #include <pj/string.h>
  24. #include <pj/sock.h>
  25. #include <pj/array.h>
  26. #include <pj/log.h>
  27. #include <pj/assert.h>
  28. #include <pj/errno.h>
  29. #include <pj/compat/socket.h>
  30. #if defined(PJ_HAS_WINSOCK2_H) && PJ_HAS_WINSOCK2_H != 0
  31. # include <winsock2.h>
  32. #elif defined(PJ_HAS_WINSOCK_H) && PJ_HAS_WINSOCK_H != 0
  33. # include <winsock.h>
  34. #endif
  35. #if defined(PJ_HAS_MSWSOCK_H) && PJ_HAS_MSWSOCK_H != 0
  36. # include <mswsock.h>
  37. #endif
  38. /* The address specified in AcceptEx() must be 16 more than the size of
  39. * SOCKADDR (source: MSDN).
  40. */
  41. #define ACCEPT_ADDR_LEN (sizeof(pj_sockaddr_in)+16)
  42. typedef struct generic_overlapped
  43. {
  44. WSAOVERLAPPED overlapped;
  45. pj_ioqueue_operation_e operation;
  46. } generic_overlapped;
  47. /*
  48. * OVERLAPPPED structure for send and receive.
  49. */
  50. typedef struct ioqueue_overlapped
  51. {
  52. WSAOVERLAPPED overlapped;
  53. pj_ioqueue_operation_e operation;
  54. WSABUF wsabuf;
  55. pj_sockaddr_in dummy_addr;
  56. int dummy_addrlen;
  57. } ioqueue_overlapped;
  58. #if PJ_HAS_TCP
  59. /*
  60. * OVERLAP structure for accept.
  61. */
  62. typedef struct ioqueue_accept_rec
  63. {
  64. WSAOVERLAPPED overlapped;
  65. pj_ioqueue_operation_e operation;
  66. pj_sock_t newsock;
  67. pj_sock_t *newsock_ptr;
  68. int *addrlen;
  69. void *remote;
  70. void *local;
  71. char accept_buf[2 * ACCEPT_ADDR_LEN];
  72. } ioqueue_accept_rec;
  73. #endif
  74. /*
  75. * Structure to hold pending operation key.
  76. */
  77. union operation_key
  78. {
  79. generic_overlapped generic;
  80. ioqueue_overlapped overlapped;
  81. #if PJ_HAS_TCP
  82. ioqueue_accept_rec accept;
  83. #endif
  84. };
  85. /* Type of handle in the key. */
  86. enum handle_type
  87. {
  88. HND_IS_UNKNOWN,
  89. HND_IS_FILE,
  90. HND_IS_SOCKET,
  91. };
  92. enum { POST_QUIT_LEN = 0xFFFFDEADUL };
  93. /*
  94. * Structure for individual socket.
  95. */
  96. struct pj_ioqueue_key_t
  97. {
  98. PJ_DECL_LIST_MEMBER(struct pj_ioqueue_key_t);
  99. pj_ioqueue_t *ioqueue;
  100. HANDLE hnd;
  101. void *user_data;
  102. enum handle_type hnd_type;
  103. pj_ioqueue_callback cb;
  104. pj_bool_t allow_concurrent;
  105. pj_grp_lock_t *grp_lock;
  106. #if PJ_HAS_TCP
  107. int connecting;
  108. #endif
  109. #if PJ_IOQUEUE_HAS_SAFE_UNREG
  110. pj_atomic_t *ref_count;
  111. pj_bool_t closing;
  112. pj_time_val free_time;
  113. pj_mutex_t *mutex;
  114. #endif
  115. };
  116. /*
  117. * IO Queue structure.
  118. */
  119. struct pj_ioqueue_t
  120. {
  121. pj_ioqueue_cfg cfg;
  122. HANDLE iocp;
  123. pj_lock_t *lock;
  124. pj_bool_t auto_delete_lock;
  125. pj_bool_t default_concurrency;
  126. #if PJ_IOQUEUE_HAS_SAFE_UNREG
  127. pj_ioqueue_key_t active_list;
  128. pj_ioqueue_key_t free_list;
  129. pj_ioqueue_key_t closing_list;
  130. #endif
  131. /* These are to keep track of connecting sockets */
  132. #if PJ_HAS_TCP
  133. unsigned event_count;
  134. HANDLE event_pool[MAXIMUM_WAIT_OBJECTS+1];
  135. unsigned connecting_count;
  136. HANDLE connecting_handles[MAXIMUM_WAIT_OBJECTS+1];
  137. pj_ioqueue_key_t *connecting_keys[MAXIMUM_WAIT_OBJECTS+1];
  138. #endif
  139. };
  140. #if PJ_IOQUEUE_HAS_SAFE_UNREG
  141. /* Prototype */
  142. static void scan_closing_keys(pj_ioqueue_t *ioqueue);
  143. #endif
  144. #if PJ_HAS_TCP
  145. /*
  146. * Process the socket when the overlapped accept() completed.
  147. */
  148. static void ioqueue_on_accept_complete(pj_ioqueue_key_t *key,
  149. ioqueue_accept_rec *accept_overlapped)
  150. {
  151. struct sockaddr *local;
  152. struct sockaddr *remote;
  153. int locallen, remotelen;
  154. pj_status_t status;
  155. PJ_CHECK_STACK();
  156. /* On WinXP or later, use SO_UPDATE_ACCEPT_CONTEXT so that socket
  157. * addresses can be obtained with getsockname() and getpeername().
  158. */
  159. status = setsockopt(accept_overlapped->newsock, SOL_SOCKET,
  160. SO_UPDATE_ACCEPT_CONTEXT,
  161. (char*)&key->hnd,
  162. sizeof(SOCKET));
  163. /* SO_UPDATE_ACCEPT_CONTEXT is for WinXP or later.
  164. * So ignore the error status.
  165. */
  166. /* Operation complete immediately. */
  167. if (accept_overlapped->addrlen) {
  168. GetAcceptExSockaddrs( accept_overlapped->accept_buf,
  169. 0,
  170. ACCEPT_ADDR_LEN,
  171. ACCEPT_ADDR_LEN,
  172. &local,
  173. &locallen,
  174. &remote,
  175. &remotelen);
  176. if (*accept_overlapped->addrlen >= locallen) {
  177. if (accept_overlapped->local)
  178. pj_memcpy(accept_overlapped->local, local, locallen);
  179. if (accept_overlapped->remote)
  180. pj_memcpy(accept_overlapped->remote, remote, locallen);
  181. } else {
  182. if (accept_overlapped->local)
  183. pj_bzero(accept_overlapped->local,
  184. *accept_overlapped->addrlen);
  185. if (accept_overlapped->remote)
  186. pj_bzero(accept_overlapped->remote,
  187. *accept_overlapped->addrlen);
  188. }
  189. *accept_overlapped->addrlen = locallen;
  190. }
  191. if (accept_overlapped->newsock_ptr)
  192. *accept_overlapped->newsock_ptr = accept_overlapped->newsock;
  193. accept_overlapped->operation = 0;
  194. }
  195. static void erase_connecting_socket( pj_ioqueue_t *ioqueue, unsigned pos)
  196. {
  197. pj_ioqueue_key_t *key = ioqueue->connecting_keys[pos];
  198. HANDLE hEvent = ioqueue->connecting_handles[pos];
  199. /* Remove key from array of connecting handles. */
  200. pj_array_erase(ioqueue->connecting_keys, sizeof(key),
  201. ioqueue->connecting_count, pos);
  202. pj_array_erase(ioqueue->connecting_handles, sizeof(HANDLE),
  203. ioqueue->connecting_count, pos);
  204. --ioqueue->connecting_count;
  205. /* Disassociate the socket from the event. */
  206. WSAEventSelect((pj_sock_t)key->hnd, hEvent, 0);
  207. /* Put event object to pool. */
  208. if (ioqueue->event_count < MAXIMUM_WAIT_OBJECTS) {
  209. ioqueue->event_pool[ioqueue->event_count++] = hEvent;
  210. } else {
  211. /* Shouldn't happen. There should be no more pending connections
  212. * than max.
  213. */
  214. pj_assert(0);
  215. CloseHandle(hEvent);
  216. }
  217. }
  218. /*
  219. * Poll for the completion of non-blocking connect().
  220. * If there's a completion, the function return the key of the completed
  221. * socket, and 'result' argument contains the connect() result. If connect()
  222. * succeeded, 'result' will have value zero, otherwise will have the error
  223. * code.
  224. */
  225. static int check_connecting( pj_ioqueue_t *ioqueue )
  226. {
  227. if (ioqueue->connecting_count) {
  228. int i, count;
  229. struct
  230. {
  231. pj_ioqueue_key_t *key;
  232. pj_status_t status;
  233. } events[PJ_IOQUEUE_MAX_EVENTS_IN_SINGLE_POLL-1];
  234. pj_lock_acquire(ioqueue->lock);
  235. for (count=0; count<PJ_IOQUEUE_MAX_EVENTS_IN_SINGLE_POLL-1; ++count) {
  236. DWORD result;
  237. result = WaitForMultipleObjects(ioqueue->connecting_count,
  238. ioqueue->connecting_handles,
  239. FALSE, 0);
  240. if (result >= WAIT_OBJECT_0 &&
  241. result < WAIT_OBJECT_0+ioqueue->connecting_count)
  242. {
  243. WSANETWORKEVENTS net_events;
  244. /* Got completed connect(). */
  245. unsigned pos = result - WAIT_OBJECT_0;
  246. events[count].key = ioqueue->connecting_keys[pos];
  247. /* See whether connect has succeeded. */
  248. WSAEnumNetworkEvents((pj_sock_t)events[count].key->hnd,
  249. ioqueue->connecting_handles[pos],
  250. &net_events);
  251. events[count].status =
  252. PJ_STATUS_FROM_OS(net_events.iErrorCode[FD_CONNECT_BIT]);
  253. /* Erase socket from pending connect. */
  254. erase_connecting_socket(ioqueue, pos);
  255. } else {
  256. /* No more events */
  257. break;
  258. }
  259. }
  260. pj_lock_release(ioqueue->lock);
  261. /* Call callbacks. */
  262. for (i=0; i<count; ++i) {
  263. if (events[i].key->cb.on_connect_complete) {
  264. events[i].key->cb.on_connect_complete(events[i].key,
  265. events[i].status);
  266. }
  267. }
  268. return count;
  269. }
  270. return 0;
  271. }
  272. #endif
  273. /*
  274. * pj_ioqueue_name()
  275. */
  276. PJ_DEF(const char*) pj_ioqueue_name(void)
  277. {
  278. return "iocp";
  279. }
  280. PJ_DEF(void) pj_ioqueue_cfg_default(pj_ioqueue_cfg *cfg)
  281. {
  282. pj_bzero(cfg, sizeof(*cfg));
  283. cfg->epoll_flags = PJ_IOQUEUE_DEFAULT_EPOLL_FLAGS;
  284. cfg->default_concurrency = PJ_IOQUEUE_DEFAULT_ALLOW_CONCURRENCY;
  285. }
  286. PJ_DEF(pj_status_t) pj_ioqueue_clear_key( pj_ioqueue_key_t *key )
  287. {
  288. PJ_ASSERT_RETURN(key, PJ_EINVAL);
  289. pj_ioqueue_lock_key(key);
  290. key->connecting = 0;
  291. pj_ioqueue_unlock_key(key);
  292. return PJ_SUCCESS;
  293. }
  294. /*
  295. * pj_ioqueue_create()
  296. */
  297. PJ_DEF(pj_status_t) pj_ioqueue_create( pj_pool_t *pool,
  298. pj_size_t max_fd,
  299. pj_ioqueue_t **p_ioqueue)
  300. {
  301. return pj_ioqueue_create2(pool, max_fd, NULL, p_ioqueue);
  302. }
  303. /*
  304. * pj_ioqueue_create2()
  305. */
  306. PJ_DEF(pj_status_t) pj_ioqueue_create2(pj_pool_t *pool,
  307. pj_size_t max_fd,
  308. const pj_ioqueue_cfg *cfg,
  309. pj_ioqueue_t **p_ioqueue)
  310. {
  311. pj_ioqueue_t *ioqueue;
  312. pj_size_t i;
  313. pj_status_t rc;
  314. PJ_UNUSED_ARG(max_fd);
  315. PJ_ASSERT_RETURN(pool && p_ioqueue, PJ_EINVAL);
  316. rc = sizeof(union operation_key);
  317. /* Check that sizeof(pj_ioqueue_op_key_t) makes sense. */
  318. PJ_ASSERT_RETURN(sizeof(pj_ioqueue_op_key_t)-sizeof(void*) >=
  319. sizeof(union operation_key), PJ_EBUG);
  320. /* Create IOCP */
  321. ioqueue = pj_pool_zalloc(pool, sizeof(*ioqueue));
  322. if (cfg)
  323. pj_memcpy(&ioqueue->cfg, cfg, sizeof(*cfg));
  324. else
  325. pj_ioqueue_cfg_default(&ioqueue->cfg);
  326. ioqueue->iocp = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 0);
  327. if (ioqueue->iocp == NULL)
  328. return PJ_RETURN_OS_ERROR(GetLastError());
  329. /* Create IOCP mutex */
  330. rc = pj_lock_create_recursive_mutex(pool, NULL, &ioqueue->lock);
  331. if (rc != PJ_SUCCESS) {
  332. CloseHandle(ioqueue->iocp);
  333. return rc;
  334. }
  335. ioqueue->auto_delete_lock = PJ_TRUE;
  336. ioqueue->default_concurrency = PJ_IOQUEUE_DEFAULT_ALLOW_CONCURRENCY;
  337. #if PJ_IOQUEUE_HAS_SAFE_UNREG
  338. /*
  339. * Create and initialize key pools.
  340. */
  341. pj_list_init(&ioqueue->active_list);
  342. pj_list_init(&ioqueue->free_list);
  343. pj_list_init(&ioqueue->closing_list);
  344. /* Preallocate keys according to max_fd setting, and put them
  345. * in free_list.
  346. */
  347. for (i=0; i<max_fd; ++i) {
  348. pj_ioqueue_key_t *key;
  349. key = pj_pool_alloc(pool, sizeof(pj_ioqueue_key_t));
  350. rc = pj_atomic_create(pool, 0, &key->ref_count);
  351. if (rc != PJ_SUCCESS) {
  352. key = ioqueue->free_list.next;
  353. while (key != &ioqueue->free_list) {
  354. pj_atomic_destroy(key->ref_count);
  355. pj_mutex_destroy(key->mutex);
  356. key = key->next;
  357. }
  358. CloseHandle(ioqueue->iocp);
  359. return rc;
  360. }
  361. rc = pj_mutex_create_recursive(pool, "ioqkey", &key->mutex);
  362. if (rc != PJ_SUCCESS) {
  363. pj_atomic_destroy(key->ref_count);
  364. key = ioqueue->free_list.next;
  365. while (key != &ioqueue->free_list) {
  366. pj_atomic_destroy(key->ref_count);
  367. pj_mutex_destroy(key->mutex);
  368. key = key->next;
  369. }
  370. CloseHandle(ioqueue->iocp);
  371. return rc;
  372. }
  373. pj_list_push_back(&ioqueue->free_list, key);
  374. }
  375. #endif
  376. *p_ioqueue = ioqueue;
  377. PJ_LOG(4, ("pjlib", "WinNT IOCP I/O Queue created (%p)", ioqueue));
  378. return PJ_SUCCESS;
  379. }
  380. /*
  381. * pj_ioqueue_destroy()
  382. */
  383. PJ_DEF(pj_status_t) pj_ioqueue_destroy( pj_ioqueue_t *ioqueue )
  384. {
  385. #if PJ_HAS_TCP
  386. unsigned i;
  387. #endif
  388. pj_ioqueue_key_t *key;
  389. PJ_CHECK_STACK();
  390. PJ_ASSERT_RETURN(ioqueue, PJ_EINVAL);
  391. pj_lock_acquire(ioqueue->lock);
  392. #if PJ_HAS_TCP
  393. /* Destroy events in the pool */
  394. for (i=0; i<ioqueue->event_count; ++i) {
  395. CloseHandle(ioqueue->event_pool[i]);
  396. }
  397. ioqueue->event_count = 0;
  398. #endif
  399. if (CloseHandle(ioqueue->iocp) != TRUE)
  400. return PJ_RETURN_OS_ERROR(GetLastError());
  401. #if PJ_IOQUEUE_HAS_SAFE_UNREG
  402. /* Destroy reference counters */
  403. key = ioqueue->active_list.next;
  404. while (key != &ioqueue->active_list) {
  405. pj_atomic_destroy(key->ref_count);
  406. pj_mutex_destroy(key->mutex);
  407. key = key->next;
  408. }
  409. key = ioqueue->closing_list.next;
  410. while (key != &ioqueue->closing_list) {
  411. pj_atomic_destroy(key->ref_count);
  412. pj_mutex_destroy(key->mutex);
  413. key = key->next;
  414. }
  415. key = ioqueue->free_list.next;
  416. while (key != &ioqueue->free_list) {
  417. pj_atomic_destroy(key->ref_count);
  418. pj_mutex_destroy(key->mutex);
  419. key = key->next;
  420. }
  421. #endif
  422. pj_lock_release(ioqueue->lock);
  423. if (ioqueue->auto_delete_lock)
  424. pj_lock_destroy(ioqueue->lock);
  425. return PJ_SUCCESS;
  426. }
  427. PJ_DEF(pj_status_t) pj_ioqueue_set_default_concurrency(pj_ioqueue_t *ioqueue,
  428. pj_bool_t allow)
  429. {
  430. PJ_ASSERT_RETURN(ioqueue != NULL, PJ_EINVAL);
  431. ioqueue->default_concurrency = allow;
  432. return PJ_SUCCESS;
  433. }
  434. /*
  435. * pj_ioqueue_set_lock()
  436. */
  437. PJ_DEF(pj_status_t) pj_ioqueue_set_lock( pj_ioqueue_t *ioqueue,
  438. pj_lock_t *lock,
  439. pj_bool_t auto_delete )
  440. {
  441. PJ_ASSERT_RETURN(ioqueue && lock, PJ_EINVAL);
  442. if (ioqueue->auto_delete_lock) {
  443. pj_lock_destroy(ioqueue->lock);
  444. }
  445. ioqueue->lock = lock;
  446. ioqueue->auto_delete_lock = auto_delete;
  447. return PJ_SUCCESS;
  448. }
  449. /*
  450. * pj_ioqueue_register_sock2()
  451. */
  452. PJ_DEF(pj_status_t) pj_ioqueue_register_sock2(pj_pool_t *pool,
  453. pj_ioqueue_t *ioqueue,
  454. pj_sock_t sock,
  455. pj_grp_lock_t *grp_lock,
  456. void *user_data,
  457. const pj_ioqueue_callback *cb,
  458. pj_ioqueue_key_t **key )
  459. {
  460. HANDLE hioq;
  461. pj_ioqueue_key_t *rec;
  462. u_long value;
  463. int rc;
  464. PJ_ASSERT_RETURN(pool && ioqueue && cb && key, PJ_EINVAL);
  465. pj_lock_acquire(ioqueue->lock);
  466. #if PJ_IOQUEUE_HAS_SAFE_UNREG
  467. /* Scan closing list first to release unused keys.
  468. * Must do this with lock acquired.
  469. */
  470. scan_closing_keys(ioqueue);
  471. /* If safe unregistration is used, then get the key record from
  472. * the free list.
  473. */
  474. pj_assert(!pj_list_empty(&ioqueue->free_list));
  475. if (pj_list_empty(&ioqueue->free_list)) {
  476. pj_lock_release(ioqueue->lock);
  477. return PJ_ETOOMANY;
  478. }
  479. rec = ioqueue->free_list.next;
  480. pj_list_erase(rec);
  481. /* Set initial reference count to 1 */
  482. pj_assert(pj_atomic_get(rec->ref_count) == 0);
  483. pj_atomic_inc(rec->ref_count);
  484. rec->closing = 0;
  485. #else
  486. rec = (pj_ioqueue_key_t *)pj_pool_zalloc(pool, sizeof(pj_ioqueue_key_t));
  487. #endif
  488. /* Build the key for this socket. */
  489. rec->ioqueue = ioqueue;
  490. rec->hnd = (HANDLE)sock;
  491. rec->hnd_type = HND_IS_SOCKET;
  492. rec->user_data = user_data;
  493. pj_memcpy(&rec->cb, cb, sizeof(pj_ioqueue_callback));
  494. /* Set concurrency for this handle */
  495. rc = pj_ioqueue_set_concurrency(rec, ioqueue->default_concurrency);
  496. if (rc != PJ_SUCCESS) {
  497. pj_lock_release(ioqueue->lock);
  498. return rc;
  499. }
  500. #if PJ_HAS_TCP
  501. rec->connecting = 0;
  502. #endif
  503. /* Set socket to nonblocking. */
  504. value = 1;
  505. rc = ioctlsocket(sock, FIONBIO, &value);
  506. if (rc != 0) {
  507. pj_lock_release(ioqueue->lock);
  508. return PJ_RETURN_OS_ERROR(WSAGetLastError());
  509. }
  510. /* Associate with IOCP */
  511. hioq = CreateIoCompletionPort((HANDLE)sock, ioqueue->iocp, (DWORD)rec, 0);
  512. if (!hioq) {
  513. pj_lock_release(ioqueue->lock);
  514. return PJ_RETURN_OS_ERROR(GetLastError());
  515. }
  516. /* Group lock */
  517. rec->grp_lock = grp_lock;
  518. if (rec->grp_lock) {
  519. /* IOCP backend doesn't have group lock functionality, so
  520. * you should not use it other than for experimental purposes.
  521. */
  522. PJ_TODO(INTEGRATE_GROUP_LOCK);
  523. // pj_grp_lock_add_ref_dbg(rec->grp_lock, "ioqueue", 0);
  524. }
  525. *key = rec;
  526. #if PJ_IOQUEUE_HAS_SAFE_UNREG
  527. pj_list_push_back(&ioqueue->active_list, rec);
  528. #endif
  529. pj_lock_release(ioqueue->lock);
  530. return PJ_SUCCESS;
  531. }
  532. /*
  533. * pj_ioqueue_register_sock()
  534. */
  535. PJ_DEF(pj_status_t) pj_ioqueue_register_sock( pj_pool_t *pool,
  536. pj_ioqueue_t *ioqueue,
  537. pj_sock_t sock,
  538. void *user_data,
  539. const pj_ioqueue_callback *cb,
  540. pj_ioqueue_key_t **key )
  541. {
  542. return pj_ioqueue_register_sock2(pool, ioqueue, sock, NULL, user_data, cb,
  543. key);
  544. }
  545. /*
  546. * pj_ioqueue_get_user_data()
  547. */
  548. PJ_DEF(void*) pj_ioqueue_get_user_data( pj_ioqueue_key_t *key )
  549. {
  550. PJ_ASSERT_RETURN(key, NULL);
  551. return key->user_data;
  552. }
  553. /*
  554. * pj_ioqueue_set_user_data()
  555. */
  556. PJ_DEF(pj_status_t) pj_ioqueue_set_user_data( pj_ioqueue_key_t *key,
  557. void *user_data,
  558. void **old_data )
  559. {
  560. PJ_ASSERT_RETURN(key, PJ_EINVAL);
  561. if (old_data)
  562. *old_data = key->user_data;
  563. key->user_data = user_data;
  564. return PJ_SUCCESS;
  565. }
  566. #if PJ_IOQUEUE_HAS_SAFE_UNREG
  567. /* Decrement the key's reference counter, and when the counter reach zero,
  568. * destroy the key.
  569. */
  570. static void decrement_counter(pj_ioqueue_key_t *key)
  571. {
  572. if (pj_atomic_dec_and_get(key->ref_count) == 0) {
  573. pj_lock_acquire(key->ioqueue->lock);
  574. pj_assert(key->closing == 1);
  575. pj_gettickcount(&key->free_time);
  576. key->free_time.msec += PJ_IOQUEUE_KEY_FREE_DELAY;
  577. pj_time_val_normalize(&key->free_time);
  578. pj_list_erase(key);
  579. pj_list_push_back(&key->ioqueue->closing_list, key);
  580. pj_lock_release(key->ioqueue->lock);
  581. }
  582. }
  583. #endif
  584. /*
  585. * Poll the I/O Completion Port, execute callback,
  586. * and return the key and bytes transferred of the last operation.
  587. */
  588. static pj_bool_t poll_iocp( HANDLE hIocp, DWORD dwTimeout,
  589. pj_ssize_t *p_bytes, pj_ioqueue_key_t **p_key )
  590. {
  591. DWORD dwBytesTransferred, dwKey;
  592. generic_overlapped *pOv;
  593. pj_ioqueue_key_t *key;
  594. pj_ssize_t size_status = -1;
  595. BOOL rcGetQueued;
  596. /* Poll for completion status. */
  597. rcGetQueued = GetQueuedCompletionStatus(hIocp, &dwBytesTransferred,
  598. &dwKey, (OVERLAPPED**)&pOv,
  599. dwTimeout);
  600. /* The return value is:
  601. * - nonzero if event was dequeued.
  602. * - zero and pOv==NULL if no event was dequeued.
  603. * - zero and pOv!=NULL if event for failed I/O was dequeued.
  604. */
  605. if (pOv) {
  606. pj_bool_t has_lock;
  607. /* Event was dequeued for either successfull or failed I/O */
  608. key = (pj_ioqueue_key_t*)dwKey;
  609. size_status = dwBytesTransferred;
  610. /* Report to caller regardless */
  611. if (p_bytes)
  612. *p_bytes = size_status;
  613. if (p_key)
  614. *p_key = key;
  615. #if PJ_IOQUEUE_HAS_SAFE_UNREG
  616. /* We shouldn't call callbacks if key is quitting. */
  617. if (key->closing)
  618. return PJ_TRUE;
  619. /* If concurrency is disabled, lock the key
  620. * (and save the lock status to local var since app may change
  621. * concurrency setting while in the callback) */
  622. if (key->allow_concurrent == PJ_FALSE) {
  623. pj_mutex_lock(key->mutex);
  624. has_lock = PJ_TRUE;
  625. } else {
  626. has_lock = PJ_FALSE;
  627. }
  628. /* Now that we get the lock, check again that key is not closing */
  629. if (key->closing) {
  630. if (has_lock) {
  631. pj_mutex_unlock(key->mutex);
  632. }
  633. return PJ_TRUE;
  634. }
  635. /* Increment reference counter to prevent this key from being
  636. * deleted
  637. */
  638. pj_atomic_inc(key->ref_count);
  639. #else
  640. PJ_UNUSED_ARG(has_lock);
  641. #endif
  642. /* Carry out the callback */
  643. switch (pOv->operation) {
  644. case PJ_IOQUEUE_OP_READ:
  645. case PJ_IOQUEUE_OP_RECV:
  646. case PJ_IOQUEUE_OP_RECV_FROM:
  647. pOv->operation = 0;
  648. if (key->cb.on_read_complete)
  649. key->cb.on_read_complete(key, (pj_ioqueue_op_key_t*)pOv,
  650. size_status);
  651. break;
  652. case PJ_IOQUEUE_OP_WRITE:
  653. case PJ_IOQUEUE_OP_SEND:
  654. case PJ_IOQUEUE_OP_SEND_TO:
  655. pOv->operation = 0;
  656. if (key->cb.on_write_complete)
  657. key->cb.on_write_complete(key, (pj_ioqueue_op_key_t*)pOv,
  658. size_status);
  659. break;
  660. #if PJ_HAS_TCP
  661. case PJ_IOQUEUE_OP_ACCEPT:
  662. /* special case for accept. */
  663. ioqueue_on_accept_complete(key, (ioqueue_accept_rec*)pOv);
  664. if (key->cb.on_accept_complete) {
  665. ioqueue_accept_rec *accept_rec = (ioqueue_accept_rec*)pOv;
  666. pj_status_t status = PJ_SUCCESS;
  667. pj_sock_t newsock;
  668. newsock = accept_rec->newsock;
  669. accept_rec->newsock = PJ_INVALID_SOCKET;
  670. if (newsock == PJ_INVALID_SOCKET) {
  671. int dwError = WSAGetLastError();
  672. if (dwError == 0) dwError = OSERR_ENOTCONN;
  673. status = PJ_RETURN_OS_ERROR(dwError);
  674. }
  675. key->cb.on_accept_complete(key, (pj_ioqueue_op_key_t*)pOv,
  676. newsock, status);
  677. }
  678. break;
  679. case PJ_IOQUEUE_OP_CONNECT:
  680. #endif
  681. case PJ_IOQUEUE_OP_NONE:
  682. pj_assert(0);
  683. break;
  684. }
  685. #if PJ_IOQUEUE_HAS_SAFE_UNREG
  686. decrement_counter(key);
  687. if (has_lock)
  688. pj_mutex_unlock(key->mutex);
  689. #endif
  690. return PJ_TRUE;
  691. }
  692. /* No event was queued. */
  693. return PJ_FALSE;
  694. }
  695. /*
  696. * pj_ioqueue_unregister()
  697. */
  698. PJ_DEF(pj_status_t) pj_ioqueue_unregister( pj_ioqueue_key_t *key )
  699. {
  700. unsigned i;
  701. pj_bool_t has_lock;
  702. enum { RETRY = 10 };
  703. PJ_ASSERT_RETURN(key, PJ_EINVAL);
  704. #if PJ_HAS_TCP
  705. if (key->connecting) {
  706. unsigned pos;
  707. pj_ioqueue_t *ioqueue;
  708. ioqueue = key->ioqueue;
  709. /* Erase from connecting_handles */
  710. pj_lock_acquire(ioqueue->lock);
  711. for (pos=0; pos < ioqueue->connecting_count; ++pos) {
  712. if (ioqueue->connecting_keys[pos] == key) {
  713. erase_connecting_socket(ioqueue, pos);
  714. break;
  715. }
  716. }
  717. key->connecting = 0;
  718. pj_lock_release(ioqueue->lock);
  719. }
  720. #endif
  721. #if PJ_IOQUEUE_HAS_SAFE_UNREG
  722. /* Mark key as closing before closing handle. */
  723. key->closing = 1;
  724. /* If concurrency is disabled, wait until the key has finished
  725. * processing the callback
  726. */
  727. if (key->allow_concurrent == PJ_FALSE) {
  728. pj_mutex_lock(key->mutex);
  729. has_lock = PJ_TRUE;
  730. } else {
  731. has_lock = PJ_FALSE;
  732. }
  733. #else
  734. PJ_UNUSED_ARG(has_lock);
  735. #endif
  736. /* Close handle (the only way to disassociate handle from IOCP).
  737. * We also need to close handle to make sure that no further events
  738. * will come to the handle.
  739. */
  740. /* Update 2008/07/18 (https://github.com/pjsip/pjproject/issues/575):
  741. * - It seems that CloseHandle() in itself does not actually close
  742. * the socket (i.e. it will still appear in "netstat" output). Also
  743. * if we only use CloseHandle(), an "Invalid Handle" exception will
  744. * be raised in WSACleanup().
  745. * - MSDN documentation says that CloseHandle() must be called after
  746. * closesocket() call (see
  747. * http://msdn.microsoft.com/en-us/library/ms724211(VS.85).aspx).
  748. * But turns out that this will raise "Invalid Handle" exception
  749. * in debug mode.
  750. * So because of this, we replaced CloseHandle() with closesocket()
  751. * instead. These was tested on WinXP SP2.
  752. */
  753. //CloseHandle(key->hnd);
  754. pj_sock_close((pj_sock_t)key->hnd);
  755. /* Reset callbacks */
  756. key->cb.on_accept_complete = NULL;
  757. key->cb.on_connect_complete = NULL;
  758. key->cb.on_read_complete = NULL;
  759. key->cb.on_write_complete = NULL;
  760. #if PJ_IOQUEUE_HAS_SAFE_UNREG
  761. /* Even after handle is closed, I suspect that IOCP may still try to
  762. * do something with the handle, causing memory corruption when pool
  763. * debugging is enabled.
  764. *
  765. * Forcing context switch seems to have fixed that, but this is quite
  766. * an ugly solution..
  767. *
  768. * Update 2008/02/13:
  769. * This should not happen if concurrency is disallowed for the key.
  770. * So at least application has a solution for this (i.e. by disallowing
  771. * concurrency in the key).
  772. */
  773. //This will loop forever if unregistration is done on the callback.
  774. //Doing this with RETRY I think should solve the IOCP setting the
  775. //socket signalled, without causing the deadlock.
  776. //while (pj_atomic_get(key->ref_count) != 1)
  777. // pj_thread_sleep(0);
  778. for (i=0; pj_atomic_get(key->ref_count) != 1 && i<RETRY; ++i)
  779. pj_thread_sleep(0);
  780. /* Decrement reference counter to destroy the key. */
  781. decrement_counter(key);
  782. if (has_lock)
  783. pj_mutex_unlock(key->mutex);
  784. #endif
  785. return PJ_SUCCESS;
  786. }
  787. #if PJ_IOQUEUE_HAS_SAFE_UNREG
  788. /* Scan the closing list, and put pending closing keys to free list.
  789. * Must do this with ioqueue mutex held.
  790. */
  791. static void scan_closing_keys(pj_ioqueue_t *ioqueue)
  792. {
  793. if (!pj_list_empty(&ioqueue->closing_list)) {
  794. pj_time_val now;
  795. pj_ioqueue_key_t *key;
  796. pj_gettickcount(&now);
  797. /* Move closing keys to free list when they've finished the closing
  798. * idle time.
  799. */
  800. key = ioqueue->closing_list.next;
  801. while (key != &ioqueue->closing_list) {
  802. pj_ioqueue_key_t *next = key->next;
  803. pj_assert(key->closing != 0);
  804. if (PJ_TIME_VAL_GTE(now, key->free_time)) {
  805. pj_list_erase(key);
  806. pj_list_push_back(&ioqueue->free_list, key);
  807. }
  808. key = next;
  809. }
  810. }
  811. }
  812. #endif
  813. /*
  814. * pj_ioqueue_poll()
  815. *
  816. * Poll for events.
  817. */
  818. PJ_DEF(int) pj_ioqueue_poll( pj_ioqueue_t *ioqueue, const pj_time_val *timeout)
  819. {
  820. DWORD dwMsec;
  821. #if PJ_HAS_TCP
  822. int connect_count = 0;
  823. #endif
  824. int event_count = 0;
  825. PJ_ASSERT_RETURN(ioqueue, -PJ_EINVAL);
  826. /* Calculate miliseconds timeout for GetQueuedCompletionStatus */
  827. dwMsec = timeout ? timeout->sec*1000 + timeout->msec : INFINITE;
  828. /* Poll for completion status. */
  829. event_count = poll_iocp(ioqueue->iocp, dwMsec, NULL, NULL);
  830. #if PJ_HAS_TCP
  831. /* Check the connecting array, only when there's no activity. */
  832. if (event_count == 0) {
  833. connect_count = check_connecting(ioqueue);
  834. if (connect_count > 0)
  835. event_count += connect_count;
  836. }
  837. #endif
  838. #if PJ_IOQUEUE_HAS_SAFE_UNREG
  839. /* Check the closing keys only when there's no activity and when there are
  840. * pending closing keys.
  841. */
  842. if (event_count == 0 && !pj_list_empty(&ioqueue->closing_list)) {
  843. pj_lock_acquire(ioqueue->lock);
  844. scan_closing_keys(ioqueue);
  845. pj_lock_release(ioqueue->lock);
  846. }
  847. #endif
  848. /* Return number of events. */
  849. return event_count;
  850. }
  851. /*
  852. * pj_ioqueue_recv()
  853. *
  854. * Initiate overlapped WSARecv() operation.
  855. */
  856. PJ_DEF(pj_status_t) pj_ioqueue_recv( pj_ioqueue_key_t *key,
  857. pj_ioqueue_op_key_t *op_key,
  858. void *buffer,
  859. pj_ssize_t *length,
  860. pj_uint32_t flags )
  861. {
  862. /*
  863. * Ideally we should just call pj_ioqueue_recvfrom() with NULL addr and
  864. * addrlen here. But unfortunately it generates EINVAL... :-(
  865. * -bennylp
  866. */
  867. int rc;
  868. DWORD bytesRead;
  869. DWORD dwFlags = 0;
  870. union operation_key *op_key_rec;
  871. PJ_CHECK_STACK();
  872. PJ_ASSERT_RETURN(key && op_key && buffer && length, PJ_EINVAL);
  873. #if PJ_IOQUEUE_HAS_SAFE_UNREG
  874. /* Check key is not closing */
  875. if (key->closing)
  876. return PJ_ECANCELLED;
  877. #endif
  878. op_key_rec = (union operation_key*)op_key->internal__;
  879. op_key_rec->overlapped.wsabuf.buf = buffer;
  880. op_key_rec->overlapped.wsabuf.len = *length;
  881. dwFlags = flags;
  882. /* Try non-overlapped received first to see if data is
  883. * immediately available.
  884. */
  885. if ((flags & PJ_IOQUEUE_ALWAYS_ASYNC) == 0) {
  886. rc = WSARecv((SOCKET)key->hnd, &op_key_rec->overlapped.wsabuf, 1,
  887. &bytesRead, &dwFlags, NULL, NULL);
  888. if (rc == 0) {
  889. *length = bytesRead;
  890. return PJ_SUCCESS;
  891. } else {
  892. DWORD dwError = WSAGetLastError();
  893. if (dwError != WSAEWOULDBLOCK) {
  894. *length = -1;
  895. return PJ_RETURN_OS_ERROR(dwError);
  896. }
  897. }
  898. }
  899. dwFlags &= ~(PJ_IOQUEUE_ALWAYS_ASYNC);
  900. /*
  901. * No immediate data available.
  902. * Register overlapped Recv() operation.
  903. */
  904. pj_bzero( &op_key_rec->overlapped.overlapped,
  905. sizeof(op_key_rec->overlapped.overlapped));
  906. op_key_rec->overlapped.operation = PJ_IOQUEUE_OP_RECV;
  907. rc = WSARecv((SOCKET)key->hnd, &op_key_rec->overlapped.wsabuf, 1,
  908. &bytesRead, &dwFlags,
  909. &op_key_rec->overlapped.overlapped, NULL);
  910. if (rc == SOCKET_ERROR) {
  911. DWORD dwStatus = WSAGetLastError();
  912. if (dwStatus!=WSA_IO_PENDING) {
  913. *length = -1;
  914. return PJ_STATUS_FROM_OS(dwStatus);
  915. }
  916. }
  917. /* Pending operation has been scheduled. */
  918. return PJ_EPENDING;
  919. }
  920. /*
  921. * pj_ioqueue_recvfrom()
  922. *
  923. * Initiate overlapped RecvFrom() operation.
  924. */
  925. PJ_DEF(pj_status_t) pj_ioqueue_recvfrom( pj_ioqueue_key_t *key,
  926. pj_ioqueue_op_key_t *op_key,
  927. void *buffer,
  928. pj_ssize_t *length,
  929. pj_uint32_t flags,
  930. pj_sockaddr_t *addr,
  931. int *addrlen)
  932. {
  933. int rc;
  934. DWORD bytesRead;
  935. DWORD dwFlags = 0;
  936. union operation_key *op_key_rec;
  937. PJ_CHECK_STACK();
  938. PJ_ASSERT_RETURN(key && op_key && buffer, PJ_EINVAL);
  939. #if PJ_IOQUEUE_HAS_SAFE_UNREG
  940. /* Check key is not closing */
  941. if (key->closing)
  942. return PJ_ECANCELLED;
  943. #endif
  944. op_key_rec = (union operation_key*)op_key->internal__;
  945. op_key_rec->overlapped.wsabuf.buf = buffer;
  946. op_key_rec->overlapped.wsabuf.len = *length;
  947. dwFlags = flags;
  948. /* Try non-overlapped received first to see if data is
  949. * immediately available.
  950. */
  951. if ((flags & PJ_IOQUEUE_ALWAYS_ASYNC) == 0) {
  952. rc = WSARecvFrom((SOCKET)key->hnd, &op_key_rec->overlapped.wsabuf, 1,
  953. &bytesRead, &dwFlags, addr, addrlen, NULL, NULL);
  954. if (rc == 0) {
  955. *length = bytesRead;
  956. return PJ_SUCCESS;
  957. } else {
  958. DWORD dwError = WSAGetLastError();
  959. if (dwError != WSAEWOULDBLOCK) {
  960. *length = -1;
  961. return PJ_RETURN_OS_ERROR(dwError);
  962. }
  963. }
  964. }
  965. dwFlags &= ~(PJ_IOQUEUE_ALWAYS_ASYNC);
  966. /*
  967. * No immediate data available.
  968. * Register overlapped Recv() operation.
  969. */
  970. pj_bzero( &op_key_rec->overlapped.overlapped,
  971. sizeof(op_key_rec->overlapped.overlapped));
  972. op_key_rec->overlapped.operation = PJ_IOQUEUE_OP_RECV;
  973. rc = WSARecvFrom((SOCKET)key->hnd, &op_key_rec->overlapped.wsabuf, 1,
  974. &bytesRead, &dwFlags, addr, addrlen,
  975. &op_key_rec->overlapped.overlapped, NULL);
  976. if (rc == SOCKET_ERROR) {
  977. DWORD dwStatus = WSAGetLastError();
  978. if (dwStatus!=WSA_IO_PENDING) {
  979. *length = -1;
  980. return PJ_STATUS_FROM_OS(dwStatus);
  981. }
  982. }
  983. /* Pending operation has been scheduled. */
  984. return PJ_EPENDING;
  985. }
  986. /*
  987. * pj_ioqueue_send()
  988. *
  989. * Initiate overlapped Send operation.
  990. */
  991. PJ_DEF(pj_status_t) pj_ioqueue_send( pj_ioqueue_key_t *key,
  992. pj_ioqueue_op_key_t *op_key,
  993. const void *data,
  994. pj_ssize_t *length,
  995. pj_uint32_t flags )
  996. {
  997. return pj_ioqueue_sendto(key, op_key, data, length, flags, NULL, 0);
  998. }
  999. /*
  1000. * pj_ioqueue_sendto()
  1001. *
  1002. * Initiate overlapped SendTo operation.
  1003. */
  1004. PJ_DEF(pj_status_t) pj_ioqueue_sendto( pj_ioqueue_key_t *key,
  1005. pj_ioqueue_op_key_t *op_key,
  1006. const void *data,
  1007. pj_ssize_t *length,
  1008. pj_uint32_t flags,
  1009. const pj_sockaddr_t *addr,
  1010. int addrlen)
  1011. {
  1012. int rc;
  1013. DWORD bytesWritten;
  1014. DWORD dwFlags;
  1015. union operation_key *op_key_rec;
  1016. PJ_CHECK_STACK();
  1017. PJ_ASSERT_RETURN(key && op_key && data, PJ_EINVAL);
  1018. #if PJ_IOQUEUE_HAS_SAFE_UNREG
  1019. /* Check key is not closing */
  1020. if (key->closing)
  1021. return PJ_ECANCELLED;
  1022. #endif
  1023. op_key_rec = (union operation_key*)op_key->internal__;
  1024. /*
  1025. * First try blocking write.
  1026. */
  1027. op_key_rec->overlapped.wsabuf.buf = (void*)data;
  1028. op_key_rec->overlapped.wsabuf.len = *length;
  1029. dwFlags = flags;
  1030. if ((flags & PJ_IOQUEUE_ALWAYS_ASYNC) == 0) {
  1031. rc = WSASendTo((SOCKET)key->hnd, &op_key_rec->overlapped.wsabuf, 1,
  1032. &bytesWritten, dwFlags, addr, addrlen,
  1033. NULL, NULL);
  1034. if (rc == 0) {
  1035. *length = bytesWritten;
  1036. return PJ_SUCCESS;
  1037. } else {
  1038. DWORD dwStatus = WSAGetLastError();
  1039. if (dwStatus != WSAEWOULDBLOCK) {
  1040. *length = -1;
  1041. return PJ_RETURN_OS_ERROR(dwStatus);
  1042. }
  1043. }
  1044. }
  1045. dwFlags &= ~(PJ_IOQUEUE_ALWAYS_ASYNC);
  1046. /*
  1047. * Data can't be sent immediately.
  1048. * Schedule asynchronous WSASend().
  1049. */
  1050. pj_bzero( &op_key_rec->overlapped.overlapped,
  1051. sizeof(op_key_rec->overlapped.overlapped));
  1052. op_key_rec->overlapped.operation = PJ_IOQUEUE_OP_SEND;
  1053. rc = WSASendTo((SOCKET)key->hnd, &op_key_rec->overlapped.wsabuf, 1,
  1054. &bytesWritten, dwFlags, addr, addrlen,
  1055. &op_key_rec->overlapped.overlapped, NULL);
  1056. if (rc == SOCKET_ERROR) {
  1057. DWORD dwStatus = WSAGetLastError();
  1058. if (dwStatus!=WSA_IO_PENDING)
  1059. return PJ_STATUS_FROM_OS(dwStatus);
  1060. }
  1061. /* Asynchronous operation successfully submitted. */
  1062. return PJ_EPENDING;
  1063. }
  1064. #if PJ_HAS_TCP
  1065. /*
  1066. * pj_ioqueue_accept()
  1067. *
  1068. * Initiate overlapped accept() operation.
  1069. */
  1070. PJ_DEF(pj_status_t) pj_ioqueue_accept( pj_ioqueue_key_t *key,
  1071. pj_ioqueue_op_key_t *op_key,
  1072. pj_sock_t *new_sock,
  1073. pj_sockaddr_t *local,
  1074. pj_sockaddr_t *remote,
  1075. int *addrlen)
  1076. {
  1077. BOOL rc;
  1078. DWORD bytesReceived;
  1079. pj_status_t status;
  1080. union operation_key *op_key_rec;
  1081. SOCKET sock;
  1082. PJ_CHECK_STACK();
  1083. PJ_ASSERT_RETURN(key && op_key && new_sock, PJ_EINVAL);
  1084. #if PJ_IOQUEUE_HAS_SAFE_UNREG
  1085. /* Check key is not closing */
  1086. if (key->closing)
  1087. return PJ_ECANCELLED;
  1088. #endif
  1089. /*
  1090. * See if there is a new connection immediately available.
  1091. */
  1092. sock = WSAAccept((SOCKET)key->hnd, remote, addrlen, NULL, 0);
  1093. if (sock != INVALID_SOCKET) {
  1094. /* Yes! New socket is available! */
  1095. if (local && addrlen) {
  1096. int status_;
  1097. /* On WinXP or later, use SO_UPDATE_ACCEPT_CONTEXT so that socket
  1098. * addresses can be obtained with getsockname() and getpeername().
  1099. */
  1100. status_ = setsockopt(sock, SOL_SOCKET, SO_UPDATE_ACCEPT_CONTEXT,
  1101. (char*)&key->hnd, sizeof(SOCKET));
  1102. /* SO_UPDATE_ACCEPT_CONTEXT is for WinXP or later.
  1103. * So ignore the error status.
  1104. */
  1105. status_ = getsockname(sock, local, addrlen);
  1106. if (status_ != 0) {
  1107. DWORD dwError = WSAGetLastError();
  1108. closesocket(sock);
  1109. return PJ_RETURN_OS_ERROR(dwError);
  1110. }
  1111. }
  1112. *new_sock = sock;
  1113. return PJ_SUCCESS;
  1114. } else {
  1115. DWORD dwError = WSAGetLastError();
  1116. if (dwError != WSAEWOULDBLOCK) {
  1117. return PJ_RETURN_OS_ERROR(dwError);
  1118. }
  1119. }
  1120. /*
  1121. * No connection is immediately available.
  1122. * Must schedule an asynchronous operation.
  1123. */
  1124. op_key_rec = (union operation_key*)op_key->internal__;
  1125. status = pj_sock_socket(pj_AF_INET(), pj_SOCK_STREAM(), 0,
  1126. &op_key_rec->accept.newsock);
  1127. if (status != PJ_SUCCESS)
  1128. return status;
  1129. op_key_rec->accept.operation = PJ_IOQUEUE_OP_ACCEPT;
  1130. op_key_rec->accept.addrlen = addrlen;
  1131. op_key_rec->accept.local = local;
  1132. op_key_rec->accept.remote = remote;
  1133. op_key_rec->accept.newsock_ptr = new_sock;
  1134. pj_bzero( &op_key_rec->accept.overlapped,
  1135. sizeof(op_key_rec->accept.overlapped));
  1136. rc = AcceptEx( (SOCKET)key->hnd, (SOCKET)op_key_rec->accept.newsock,
  1137. op_key_rec->accept.accept_buf,
  1138. 0, ACCEPT_ADDR_LEN, ACCEPT_ADDR_LEN,
  1139. &bytesReceived,
  1140. &op_key_rec->accept.overlapped );
  1141. if (rc == TRUE) {
  1142. ioqueue_on_accept_complete(key, &op_key_rec->accept);
  1143. return PJ_SUCCESS;
  1144. } else {
  1145. DWORD dwStatus = WSAGetLastError();
  1146. if (dwStatus!=WSA_IO_PENDING)
  1147. return PJ_STATUS_FROM_OS(dwStatus);
  1148. }
  1149. /* Asynchronous Accept() has been submitted. */
  1150. return PJ_EPENDING;
  1151. }
  1152. /*
  1153. * pj_ioqueue_connect()
  1154. *
  1155. * Initiate overlapped connect() operation (well, it's non-blocking actually,
  1156. * since there's no overlapped version of connect()).
  1157. */
  1158. PJ_DEF(pj_status_t) pj_ioqueue_connect( pj_ioqueue_key_t *key,
  1159. const pj_sockaddr_t *addr,
  1160. int addrlen )
  1161. {
  1162. HANDLE hEvent;
  1163. pj_ioqueue_t *ioqueue;
  1164. PJ_CHECK_STACK();
  1165. PJ_ASSERT_RETURN(key && addr && addrlen, PJ_EINVAL);
  1166. #if PJ_IOQUEUE_HAS_SAFE_UNREG
  1167. /* Check key is not closing */
  1168. if (key->closing)
  1169. return PJ_ECANCELLED;
  1170. #endif
  1171. /* Initiate connect() */
  1172. if (connect((pj_sock_t)key->hnd, addr, addrlen) != 0) {
  1173. DWORD dwStatus;
  1174. dwStatus = WSAGetLastError();
  1175. if (dwStatus != WSAEWOULDBLOCK) {
  1176. return PJ_RETURN_OS_ERROR(dwStatus);
  1177. }
  1178. } else {
  1179. /* Connect has completed immediately! */
  1180. return PJ_SUCCESS;
  1181. }
  1182. ioqueue = key->ioqueue;
  1183. /* Add to the array of connecting socket to be polled */
  1184. pj_lock_acquire(ioqueue->lock);
  1185. if (ioqueue->connecting_count >= MAXIMUM_WAIT_OBJECTS) {
  1186. pj_lock_release(ioqueue->lock);
  1187. return PJ_ETOOMANYCONN;
  1188. }
  1189. /* Get or create event object. */
  1190. if (ioqueue->event_count) {
  1191. hEvent = ioqueue->event_pool[ioqueue->event_count - 1];
  1192. --ioqueue->event_count;
  1193. } else {
  1194. hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
  1195. if (hEvent == NULL) {
  1196. DWORD dwStatus = GetLastError();
  1197. pj_lock_release(ioqueue->lock);
  1198. return PJ_STATUS_FROM_OS(dwStatus);
  1199. }
  1200. }
  1201. /* Mark key as connecting.
  1202. * We can't use array index since key can be removed dynamically.
  1203. */
  1204. key->connecting = 1;
  1205. /* Associate socket events to the event object. */
  1206. if (WSAEventSelect((pj_sock_t)key->hnd, hEvent, FD_CONNECT) != 0) {
  1207. CloseHandle(hEvent);
  1208. pj_lock_release(ioqueue->lock);
  1209. return PJ_RETURN_OS_ERROR(WSAGetLastError());
  1210. }
  1211. /* Add to array. */
  1212. ioqueue->connecting_keys[ ioqueue->connecting_count ] = key;
  1213. ioqueue->connecting_handles[ ioqueue->connecting_count ] = hEvent;
  1214. ioqueue->connecting_count++;
  1215. pj_lock_release(ioqueue->lock);
  1216. return PJ_EPENDING;
  1217. }
  1218. #endif /* #if PJ_HAS_TCP */
  1219. PJ_DEF(void) pj_ioqueue_op_key_init( pj_ioqueue_op_key_t *op_key,
  1220. pj_size_t size )
  1221. {
  1222. pj_bzero(op_key, size);
  1223. }
  1224. PJ_DEF(pj_bool_t) pj_ioqueue_is_pending( pj_ioqueue_key_t *key,
  1225. pj_ioqueue_op_key_t *op_key )
  1226. {
  1227. BOOL rc;
  1228. DWORD bytesTransferred;
  1229. rc = GetOverlappedResult( key->hnd, (LPOVERLAPPED)op_key,
  1230. &bytesTransferred, FALSE );
  1231. if (rc == FALSE) {
  1232. return GetLastError()==ERROR_IO_INCOMPLETE;
  1233. }
  1234. return FALSE;
  1235. }
  1236. PJ_DEF(pj_status_t) pj_ioqueue_post_completion( pj_ioqueue_key_t *key,
  1237. pj_ioqueue_op_key_t *op_key,
  1238. pj_ssize_t bytes_status )
  1239. {
  1240. BOOL rc;
  1241. rc = PostQueuedCompletionStatus(key->ioqueue->iocp, bytes_status,
  1242. (long)key, (OVERLAPPED*)op_key );
  1243. if (rc == FALSE) {
  1244. return PJ_RETURN_OS_ERROR(GetLastError());
  1245. }
  1246. return PJ_SUCCESS;
  1247. }
  1248. PJ_DEF(pj_status_t) pj_ioqueue_set_concurrency(pj_ioqueue_key_t *key,
  1249. pj_bool_t allow)
  1250. {
  1251. PJ_ASSERT_RETURN(key, PJ_EINVAL);
  1252. /* PJ_IOQUEUE_HAS_SAFE_UNREG must be enabled if concurrency is
  1253. * disabled.
  1254. */
  1255. PJ_ASSERT_RETURN(allow || PJ_IOQUEUE_HAS_SAFE_UNREG, PJ_EINVAL);
  1256. key->allow_concurrent = allow;
  1257. return PJ_SUCCESS;
  1258. }
  1259. PJ_DEF(pj_status_t) pj_ioqueue_lock_key(pj_ioqueue_key_t *key)
  1260. {
  1261. #if PJ_IOQUEUE_HAS_SAFE_UNREG
  1262. return pj_mutex_lock(key->mutex);
  1263. #else
  1264. PJ_ASSERT_RETURN(!"PJ_IOQUEUE_HAS_SAFE_UNREG is disabled", PJ_EINVALIDOP);
  1265. #endif
  1266. }
  1267. PJ_DEF(pj_status_t) pj_ioqueue_unlock_key(pj_ioqueue_key_t *key)
  1268. {
  1269. #if PJ_IOQUEUE_HAS_SAFE_UNREG
  1270. return pj_mutex_unlock(key->mutex);
  1271. #else
  1272. PJ_ASSERT_RETURN(!"PJ_IOQUEUE_HAS_SAFE_UNREG is disabled", PJ_EINVALIDOP);
  1273. #endif
  1274. }
  1275. PJ_DEF(pj_oshandle_t) pj_ioqueue_get_os_handle( pj_ioqueue_t *ioqueue )
  1276. {
  1277. return ioqueue ? (pj_oshandle_t)ioqueue->iocp : NULL;
  1278. }