Debian Codegraph @

Xpjproject/pjlib/src/pj/ioqueue_select.c

raw symbols SCIP
1 /*
2 * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
3 * Copyright (C) 2003-2008 Benny Prijono <[email protected]>
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
20 /*
21 * sock_select.c
22 *
23 * This is the implementation of IOQueue using pj_sock_select().
24 * It runs anywhere where pj_sock_select() is available (currently
25 * Win32, Linux, Linux kernel, etc.).
26 */
27
28 #include <pj/ioqueue.h>
29 #include <pj/os.h>
30 #include <pj/lock.h>
31 #include <pj/log.h>
32 #include <pj/list.h>
33 #include <pj/pool.h>
34 #include <pj/string.h>
35 #include <pj/assert.h>
36 #include <pj/sock.h>
37 #include <pj/compat/socket.h>
38 #include <pj/sock_select.h>
39 #include <pj/sock_qos.h>
40 #include <pj/errno.h>
41 #include <pj/rand.h>
42
43
44 /* Only build when the backend is using select(). */
45 #if PJ_IOQUEUE_IMP == PJ_IOQUEUE_IMP_SELECT
46
47
48 /* Now that we have access to OS'es <sys/select>, lets check again that
49 * PJ_IOQUEUE_MAX_HANDLES is not greater than FD_SETSIZE
50 */
51 #if PJ_IOQUEUE_MAX_HANDLES > FD_SETSIZE
52 # error "PJ_IOQUEUE_MAX_HANDLES cannot be greater than FD_SETSIZE"
53 #endif
54
55
56 /*
57 * Include declaration from common abstraction.
58 */
59 #include "ioqueue_common_abs.h"
60
61 /*
62 * ISSUES with ioqueue_select()
63 *
64 * EAGAIN/EWOULDBLOCK error in recv():
65 * - when multiple threads are working with the ioqueue, application
66 * may receive EAGAIN or EWOULDBLOCK in the receive callback.
67 * This error happens because more than one thread is watching for
68 * the same descriptor set, so when all of them call recv() or recvfrom()
69 * simultaneously, only one will succeed and the rest will get the error.
70 *
71 */
72 #define THIS_FILE "ioq_select"
73
74 /*
75 * The select ioqueue relies on socket functions (pj_sock_xxx()) to return
76 * the correct error code.
77 */
78 #if PJ_RETURN_OS_ERROR(100) != PJ_STATUS_FROM_OS(100)
79 # error "Error reporting must be enabled for this function to work!"
80 #endif
81
82 /*
83 * During debugging build, VALIDATE_FD_SET is set.
84 * This will check the validity of the fd_sets.
85 */
86 /*
87 #if defined(PJ_DEBUG) && PJ_DEBUG != 0
88 # define VALIDATE_FD_SET 1
89 #else
90 # define VALIDATE_FD_SET 0
91 #endif
92 */
93 #define VALIDATE_FD_SET 0
94
95 #if 0
96 # define TRACE__(args) PJ_LOG(3,args)
97 #else
98 # define TRACE__(args)
99 #endif
100
101 /*
102 * This describes each key.
103 */
104 struct pj_ioqueue_key_t
105 {
106 DECLARE_COMMON_KEY
107 };
108
109 /*
110 * This describes the I/O queue itself.
111 */
112 struct pj_ioqueue_t
113 {
114 DECLARE_COMMON_IOQUEUE
115
116 unsigned max, count; /* Max and current key count */
117 int nfds; /* The largest fd value (for select)*/
118 pj_ioqueue_key_t active_list; /* List of active keys. */
119 pj_fd_set_t rfdset;
120 pj_fd_set_t wfdset;
121 #if PJ_HAS_TCP
122 pj_fd_set_t xfdset;
123 #endif
124
125 #if PJ_IOQUEUE_HAS_SAFE_UNREG
126 pj_mutex_t *ref_cnt_mutex;
127 pj_ioqueue_key_t closing_list;
128 pj_ioqueue_key_t free_list;
129 #endif
130 };
131
132 /* Proto */
133 #if defined(PJ_IPHONE_OS_HAS_MULTITASKING_SUPPORT) && \
134 PJ_IPHONE_OS_HAS_MULTITASKING_SUPPORT!=0
135 static pj_status_t replace_udp_sock(pj_ioqueue_key_t *h);
136 #endif
137
138 #if defined(PJ_HAS_SSL_SOCK) && PJ_HAS_SSL_SOCK != 0 && \
139 (PJ_SSL_SOCK_IMP == PJ_SSL_SOCK_IMP_APPLE)
140 /* Call SSL Network framework poll */
141 pj_status_t ssl_network_event_poll();
142 #endif
143
144 /* Include implementation for common abstraction after we declare
145 * pj_ioqueue_key_t and pj_ioqueue_t.
146 */
147 #include "ioqueue_common_abs.c"
148
149 #if PJ_IOQUEUE_HAS_SAFE_UNREG
150 /* Scan closing keys to be put to free list again */
151 static void scan_closing_keys(pj_ioqueue_t *ioqueue);
152 #endif
153
154 /*
155 * pj_ioqueue_name()
156 */
157 PJ_DEF(const char*) pj_ioqueue_name(void)
158 {
159 return "select";
160 }
161
162 /*
163 * Scan the socket descriptor sets for the largest descriptor.
164 * This value is needed by select().
165 */
166 #if defined(PJ_SELECT_NEEDS_NFDS) && PJ_SELECT_NEEDS_NFDS!=0
167 static void rescan_fdset(pj_ioqueue_t *ioqueue)
168 {
169 pj_ioqueue_key_t *key = ioqueue->active_list.next;
170 int max = 0;
171
172 while (key != &ioqueue->active_list) {
173 if (key->fd > max)
174 max = key->fd;
175 key = key->next;
176 }
177
178 ioqueue->nfds = max;
179 }
180 #else
181 static void rescan_fdset(pj_ioqueue_t *ioqueue)
182 {
183 ioqueue->nfds = FD_SETSIZE-1;
184 }
185 #endif
186
187
188 /*
189 * pj_ioqueue_create()
190 *
191 * Create select ioqueue.
192 */
193 PJ_DEF(pj_status_t) pj_ioqueue_create( pj_pool_t *pool,
194 pj_size_t max_fd,
195 pj_ioqueue_t **p_ioqueue)
196 {
197 return pj_ioqueue_create2(pool, max_fd, NULL, p_ioqueue);
198 }
199
200
201 /*
202 * pj_ioqueue_create2()
203 *
204 * Create select ioqueue.
205 */
206 PJ_DEF(pj_status_t) pj_ioqueue_create2(pj_pool_t *pool,
207 pj_size_t max_fd,
208 const pj_ioqueue_cfg *cfg,
209 pj_ioqueue_t **p_ioqueue)
210 {
211 pj_ioqueue_t *ioqueue;
212 pj_lock_t *lock;
213 pj_size_t i;
214 pj_status_t rc;
215
216 /* Check that arguments are valid. */
217 PJ_ASSERT_RETURN(pool != NULL && p_ioqueue != NULL &&
218 max_fd > 0 && max_fd <= PJ_IOQUEUE_MAX_HANDLES,
219 PJ_EINVAL);
220
221 /* Check that size of pj_ioqueue_op_key_t is sufficient */
222 PJ_ASSERT_RETURN(sizeof(pj_ioqueue_op_key_t)-sizeof(void*) >=
223 sizeof(union operation_key), PJ_EBUG);
224
225 /* Create and init common ioqueue stuffs */
226 ioqueue = PJ_POOL_ZALLOC_T(pool, pj_ioqueue_t);
227 ioqueue_init(ioqueue);
228
229 if (cfg)
230 pj_memcpy(&ioqueue->cfg, cfg, sizeof(*cfg));
231 else
232 pj_ioqueue_cfg_default(&ioqueue->cfg);
233 ioqueue->max = (unsigned)max_fd;
234 ioqueue->count = 0;
235 PJ_FD_ZERO(&ioqueue->rfdset);
236 PJ_FD_ZERO(&ioqueue->wfdset);
237 #if PJ_HAS_TCP
238 PJ_FD_ZERO(&ioqueue->xfdset);
239 #endif
240 pj_list_init(&ioqueue->active_list);
241
242 rescan_fdset(ioqueue);
243
244 #if PJ_IOQUEUE_HAS_SAFE_UNREG
245 /* When safe unregistration is used (the default), we pre-create
246 * all keys and put them in the free list.
247 */
248
249 /* Mutex to protect key's reference counter
250 * We don't want to use key's mutex or ioqueue's mutex because
251 * that would create deadlock situation in some cases.
252 */
253 rc = pj_mutex_create_simple(pool, NULL, &ioqueue->ref_cnt_mutex);
254 if (rc != PJ_SUCCESS)
255 return rc;
256
257
258 /* Init key list */
259 pj_list_init(&ioqueue->free_list);
260 pj_list_init(&ioqueue->closing_list);
261
262
263 /* Pre-create all keys according to max_fd */
264 for (i=0; i<max_fd; ++i) {
265 pj_ioqueue_key_t *key;
266
267 key = PJ_POOL_ALLOC_T(pool, pj_ioqueue_key_t);
268 key->ref_count = 0;
269 rc = pj_lock_create_recursive_mutex(pool, NULL, &key->lock);
270 if (rc != PJ_SUCCESS) {
271 key = ioqueue->free_list.next;
272 while (key != &ioqueue->free_list) {
273 pj_lock_destroy(key->lock);
274 key = key->next;
275 }
276 pj_mutex_destroy(ioqueue->ref_cnt_mutex);
277 return rc;
278 }
279
280 pj_list_push_back(&ioqueue->free_list, key);
281 }
282 #endif
283
284 /* Create and init ioqueue mutex */
285 rc = pj_lock_create_simple_mutex(pool, "ioq%p", &lock);
286 if (rc != PJ_SUCCESS)
287 return rc;
288
289 rc = pj_ioqueue_set_lock(ioqueue, lock, PJ_TRUE);
290 if (rc != PJ_SUCCESS)
291 return rc;
292
293 PJ_LOG(4, ("pjlib", "select() I/O Queue created (%p)", ioqueue));
294
295 *p_ioqueue = ioqueue;
296 return PJ_SUCCESS;
297 }
298
299 /*
300 * pj_ioqueue_destroy()
301 *
302 * Destroy ioqueue.
303 */
304 PJ_DEF(pj_status_t) pj_ioqueue_destroy(pj_ioqueue_t *ioqueue)
305 {
306 pj_ioqueue_key_t *key;
307
308 PJ_ASSERT_RETURN(ioqueue, PJ_EINVAL);
309
310 pj_lock_acquire(ioqueue->lock);
311
312 #if PJ_IOQUEUE_HAS_SAFE_UNREG
313 /* Destroy reference counters */
314 key = ioqueue->active_list.next;
315 while (key != &ioqueue->active_list) {
316 pj_lock_destroy(key->lock);
317 key = key->next;
318 }
319
320 key = ioqueue->closing_list.next;
321 while (key != &ioqueue->closing_list) {
322 pj_lock_destroy(key->lock);
323 key = key->next;
324 }
325
326 key = ioqueue->free_list.next;
327 while (key != &ioqueue->free_list) {
328 pj_lock_destroy(key->lock);
329 key = key->next;
330 }
331
332 pj_mutex_destroy(ioqueue->ref_cnt_mutex);
333 #endif
334
335 return ioqueue_destroy(ioqueue);
336 }
337
338
339 /*
340 * pj_ioqueue_register_sock()
341 *
342 * Register socket handle to ioqueue.
343 */
344 PJ_DEF(pj_status_t) pj_ioqueue_register_sock2(pj_pool_t *pool,
345 pj_ioqueue_t *ioqueue,
346 pj_sock_t sock,
347 pj_grp_lock_t *grp_lock,
348 void *user_data,
349 const pj_ioqueue_callback *cb,
350 pj_ioqueue_key_t **p_key)
351 {
352 pj_ioqueue_key_t *key = NULL;
353 #if defined(PJ_WIN32) && PJ_WIN32!=0 || \
354 defined(PJ_WIN64) && PJ_WIN64 != 0 || \
355 defined(PJ_WIN32_WINCE) && PJ_WIN32_WINCE!=0
356 u_long value;
357 #else
358 pj_uint32_t value;
359 #endif
360 pj_status_t rc = PJ_SUCCESS;
361
362 PJ_ASSERT_RETURN(pool && ioqueue && sock != PJ_INVALID_SOCKET &&
363 cb && p_key, PJ_EINVAL);
364
365 /* On platforms with fd_set containing fd bitmap such as *nix family,
366 * avoid potential memory corruption caused by select() when given
367 * an fd that is higher than FD_SETSIZE.
368 */
369 if (sizeof(fd_set) < FD_SETSIZE && sock >= FD_SETSIZE) {
370 PJ_LOG(4, ("pjlib", "Failed to register socket to ioqueue because "
371 "socket fd is too big (fd=%ld/FD_SETSIZE=%d)",
372 sock, FD_SETSIZE));
373 return PJ_ETOOBIG;
374 }
375
376 pj_lock_acquire(ioqueue->lock);
377
378 if (ioqueue->count >= ioqueue->max) {
379 rc = PJ_ETOOMANY;
380 goto on_return;
381 }
382
383 /* If safe unregistration (PJ_IOQUEUE_HAS_SAFE_UNREG) is used, get
384 * the key from the free list. Otherwise allocate a new one.
385 */
386 #if PJ_IOQUEUE_HAS_SAFE_UNREG
387
388 /* Scan closing_keys first to let them come back to free_list */
389 scan_closing_keys(ioqueue);
390
391 pj_assert(!pj_list_empty(&ioqueue->free_list));
392 if (pj_list_empty(&ioqueue->free_list)) {
393 rc = PJ_ETOOMANY;
394 goto on_return;
395 }
396
397 key = ioqueue->free_list.next;
398 pj_list_erase(key);
399 #else
400 key = (pj_ioqueue_key_t*)pj_pool_zalloc(pool, sizeof(pj_ioqueue_key_t));
401 #endif
402
403 rc = ioqueue_init_key(pool, ioqueue, key, sock, grp_lock, user_data, cb);
404 if (rc != PJ_SUCCESS) {
405 key = NULL;
406 goto on_return;
407 }
408
409 /* Set socket to nonblocking. */
410 value = 1;
411 #if defined(PJ_WIN32) && PJ_WIN32!=0 || \
412 defined(PJ_WIN64) && PJ_WIN64 != 0 || \
413 defined(PJ_WIN32_WINCE) && PJ_WIN32_WINCE!=0
414 if (ioctlsocket(sock, FIONBIO, &value)) {
415 #else
416 if (ioctl(sock, FIONBIO, &value)) {
417 #endif
418 rc = pj_get_netos_error();
419 goto on_return;
420 }
421
422
423 /* Put in active list. */
424 pj_list_insert_before(&ioqueue->active_list, key);
425 ++ioqueue->count;
426
427 /* Rescan fdset to get max descriptor */
428 rescan_fdset(ioqueue);
429
430 on_return:
431 /* On error, socket may be left in non-blocking mode. */
432 if (rc != PJ_SUCCESS) {
433 if (key && key->grp_lock)
434 pj_grp_lock_dec_ref_dbg(key->grp_lock, "ioqueue", 0);
435 }
436 *p_key = key;
437 pj_lock_release(ioqueue->lock);
438
439 return rc;
440 }
441
442 PJ_DEF(pj_status_t) pj_ioqueue_register_sock( pj_pool_t *pool,
443 pj_ioqueue_t *ioqueue,
444 pj_sock_t sock,
445 void *user_data,
446 const pj_ioqueue_callback *cb,
447 pj_ioqueue_key_t **p_key)
448 {
449 return pj_ioqueue_register_sock2(pool, ioqueue, sock, NULL, user_data,
450 cb, p_key);
451 }
452
453 #if PJ_IOQUEUE_HAS_SAFE_UNREG
454 /* Increment key's reference counter */
455 static void increment_counter(pj_ioqueue_key_t *key)
456 {
457 pj_mutex_lock(key->ioqueue->ref_cnt_mutex);
458 ++key->ref_count;
459 pj_mutex_unlock(key->ioqueue->ref_cnt_mutex);
460 }
461
462 /* Decrement the key's reference counter, and when the counter reach zero,
463 * destroy the key.
464 *
465 * Note: MUST NOT CALL THIS FUNCTION WHILE HOLDING ioqueue's LOCK.
466 */
467 static void decrement_counter(pj_ioqueue_key_t *key)
468 {
469 pj_lock_acquire(key->ioqueue->lock);
470 pj_mutex_lock(key->ioqueue->ref_cnt_mutex);
471 --key->ref_count;
472 if (key->ref_count == 0) {
473
474 pj_assert(key->closing == 1);
475 pj_gettickcount(&key->free_time);
476 key->free_time.msec += PJ_IOQUEUE_KEY_FREE_DELAY;
477 pj_time_val_normalize(&key->free_time);
478
479 pj_list_erase(key);
480 pj_list_push_back(&key->ioqueue->closing_list, key);
481 /* Rescan fdset to get max descriptor */
482 rescan_fdset(key->ioqueue);
483 }
484 pj_mutex_unlock(key->ioqueue->ref_cnt_mutex);
485 pj_lock_release(key->ioqueue->lock);
486 }
487 #endif
488
489
490 /*
491 * pj_ioqueue_unregister()
492 *
493 * Unregister handle from ioqueue.
494 */
495 PJ_DEF(pj_status_t) pj_ioqueue_unregister( pj_ioqueue_key_t *key)
496 {
497 pj_ioqueue_t *ioqueue;
498
499 PJ_ASSERT_RETURN(key, PJ_EINVAL);
500
501 ioqueue = key->ioqueue;
502
503 /* Lock the key to make sure no callback is simultaneously modifying
504 * the key. We need to lock the key before ioqueue here to prevent
505 * deadlock.
506 */
507 pj_ioqueue_lock_key(key);
508
509 /* Best effort to avoid double key-unregistration */
510 if (IS_CLOSING(key)) {
511 pj_ioqueue_unlock_key(key);
512 return PJ_SUCCESS;
513 }
514
515 /* Also lock ioqueue */
516 pj_lock_acquire(ioqueue->lock);
517
518 /* Avoid "negative" ioqueue count */
519 if (ioqueue->count > 0) {
520 --ioqueue->count;
521 } else {
522 /* If this happens, very likely there is double unregistration
523 * of a key.
524 */
525 pj_assert(!"Bad ioqueue count in key unregistration!");
526 PJ_LOG(1,(THIS_FILE, "Bad ioqueue count in key unregistration!"));
527 }
528
529 #if !PJ_IOQUEUE_HAS_SAFE_UNREG
530 /* Ticket #520, key will be erased more than once */
531 pj_list_erase(key);
532 #endif
533
534 /* Remove socket from sets and close socket. */
535 if (key->fd != PJ_INVALID_SOCKET) {
536 PJ_FD_CLR(key->fd, &ioqueue->rfdset);
537 PJ_FD_CLR(key->fd, &ioqueue->wfdset);
538 #if PJ_HAS_TCP
539 PJ_FD_CLR(key->fd, &ioqueue->xfdset);
540 #endif
541
542 pj_sock_close(key->fd);
543 key->fd = PJ_INVALID_SOCKET;
544 }
545
546 /* Must release ioqueue lock first before decrementing counter, to
547 * prevent deadlock.
548 */
549 pj_lock_release(ioqueue->lock);
550
551 /* Mark key is closing. */
552 key->closing = 1;
553
554 pj_ioqueue_unlock_key(key);
555
556 #if PJ_IOQUEUE_HAS_SAFE_UNREG
557 /* Drain pending write callbacks. See #4864, #4878.
558 * Must be done before clearing callbacks below.
559 */
560 ioqueue_drain_pending_writes(key);
561 #endif
562
563 /* Clear callback */
564 key->cb.on_accept_complete = NULL;
565 key->cb.on_connect_complete = NULL;
566 key->cb.on_read_complete = NULL;
567 key->cb.on_write_complete = NULL;
568
569 #if PJ_IOQUEUE_HAS_SAFE_UNREG
570 /* Decrement counter. */
571 decrement_counter(key);
572 #else
573 /* Destroy the key lock */
574 pj_lock_destroy(key->lock);
575 #endif
576
577 /* Done. */
578 if (key->grp_lock) {
579 pj_grp_lock_dec_ref_dbg(key->grp_lock, "ioqueue", 0);
580 }
581
582 return PJ_SUCCESS;
583 }
584
585
586 /* This supposed to check whether the fd_set values are consistent
587 * with the operation currently set in each key.
588 */
589 #if VALIDATE_FD_SET
590 static void validate_sets(const pj_ioqueue_t *ioqueue,
591 const pj_fd_set_t *rfdset,
592 const pj_fd_set_t *wfdset,
593 const pj_fd_set_t *xfdset)
594 {
595 pj_ioqueue_key_t *key;
596
597 /*
598 * This basicly would not work anymore.
599 * We need to lock key before performing the check, but we can't do
600 * so because we're holding ioqueue mutex. If we acquire key's mutex
601 * now, the will cause deadlock.
602 */
603 pj_assert(0);
604
605 key = ioqueue->active_list.next;
606 while (key != &ioqueue->active_list) {
607 if (!pj_list_empty(&key->read_list)
608 #if defined(PJ_HAS_TCP) && PJ_HAS_TCP != 0
609 || !pj_list_empty(&key->accept_list)
610 #endif
611 )
612 {
613 pj_assert(PJ_FD_ISSET(key->fd, rfdset));
614 }
615 else {
616 pj_assert(PJ_FD_ISSET(key->fd, rfdset) == 0);
617 }
618 if (!pj_list_empty(&key->write_list)
619 #if defined(PJ_HAS_TCP) && PJ_HAS_TCP != 0
620 || key->connecting
621 #endif
622 )
623 {
624 pj_assert(PJ_FD_ISSET(key->fd, wfdset));
625 }
626 else {
627 pj_assert(PJ_FD_ISSET(key->fd, wfdset) == 0);
628 }
629 #if defined(PJ_HAS_TCP) && PJ_HAS_TCP != 0
630 if (key->connecting)
631 {
632 pj_assert(PJ_FD_ISSET(key->fd, xfdset));
633 }
634 else {
635 pj_assert(PJ_FD_ISSET(key->fd, xfdset) == 0);
636 }
637 #endif /* PJ_HAS_TCP */
638
639 key = key->next;
640 }
641 }
642 #endif /* VALIDATE_FD_SET */
643
644
645 /* ioqueue_remove_from_set()
646 * This function is called from ioqueue_dispatch_event() to instruct
647 * the ioqueue to remove the specified descriptor from ioqueue's descriptor
648 * set for the specified event.
649 */
650 static void ioqueue_remove_from_set( pj_ioqueue_t *ioqueue,
651 pj_ioqueue_key_t *key,
652 enum ioqueue_event_type event_type )
653 {
654 ioqueue_remove_from_set2(ioqueue, key, event_type);
655 }
656
657 static void ioqueue_remove_from_set2(pj_ioqueue_t *ioqueue,
658 pj_ioqueue_key_t *key,
659 unsigned event_types)
660 {
661 pj_lock_acquire(ioqueue->lock);
662
663 if (event_types & READABLE_EVENT)
664 PJ_FD_CLR((pj_sock_t)key->fd, &ioqueue->rfdset);
665 if (event_types & WRITEABLE_EVENT)
666 PJ_FD_CLR((pj_sock_t)key->fd, &ioqueue->wfdset);
667 #if defined(PJ_HAS_TCP) && PJ_HAS_TCP!=0
668 if (event_types & EXCEPTION_EVENT)
669 PJ_FD_CLR((pj_sock_t)key->fd, &ioqueue->xfdset);
670 #endif
671
672 pj_lock_release(ioqueue->lock);
673 }
674
675 /*
676 * ioqueue_add_to_set()
677 * This function is called from pj_ioqueue_recv(), pj_ioqueue_send() etc
678 * to instruct the ioqueue to add the specified handle to ioqueue's descriptor
679 * set for the specified event.
680 */
681 static void ioqueue_add_to_set( pj_ioqueue_t *ioqueue,
682 pj_ioqueue_key_t *key,
683 enum ioqueue_event_type event_type )
684 {
685 ioqueue_add_to_set2(ioqueue, key, event_type);
686 }
687
688 static void ioqueue_add_to_set2(pj_ioqueue_t *ioqueue,
689 pj_ioqueue_key_t *key,
690 unsigned event_types )
691 {
692 pj_lock_acquire(ioqueue->lock);
693
694 if (event_types & READABLE_EVENT)
695 PJ_FD_SET((pj_sock_t)key->fd, &ioqueue->rfdset);
696 if (event_types & WRITEABLE_EVENT)
697 PJ_FD_SET((pj_sock_t)key->fd, &ioqueue->wfdset);
698 #if defined(PJ_HAS_TCP) && PJ_HAS_TCP!=0
699 if (event_types & EXCEPTION_EVENT)
700 PJ_FD_SET((pj_sock_t)key->fd, &ioqueue->xfdset);
701 #endif
702
703 pj_lock_release(ioqueue->lock);
704 }
705
706 #if PJ_IOQUEUE_HAS_SAFE_UNREG
707 /* Scan closing keys to be put to free list again */
708 static void scan_closing_keys(pj_ioqueue_t *ioqueue)
709 {
710 pj_time_val now;
711 pj_ioqueue_key_t *h;
712
713 pj_gettickcount(&now);
714 h = ioqueue->closing_list.next;
715 while (h != &ioqueue->closing_list) {
716 pj_ioqueue_key_t *next = h->next;
717
718 pj_assert(h->closing != 0);
719
720 if (PJ_TIME_VAL_GTE(now, h->free_time)) {
721 pj_list_erase(h);
722 // Don't set grp_lock to NULL otherwise the other thread
723 // will crash. Just leave it as dangling pointer, but this
724 // should be safe
725 //h->grp_lock = NULL;
726 pj_list_push_back(&ioqueue->free_list, h);
727 }
728 h = next;
729 }
730 }
731 #endif
732
733 #if defined(PJ_IPHONE_OS_HAS_MULTITASKING_SUPPORT) && \
734 PJ_IPHONE_OS_HAS_MULTITASKING_SUPPORT!=0
735 static pj_status_t replace_udp_sock(pj_ioqueue_key_t *h)
736 {
737 enum flags {
738 HAS_PEER_ADDR = 1,
739 HAS_QOS = 2
740 };
741 pj_sock_t old_sock, new_sock = PJ_INVALID_SOCKET;
742 pj_sockaddr local_addr, rem_addr;
743 int val, addr_len;
744 pj_fd_set_t *fds[3];
745 unsigned i, fds_cnt, flags=0;
746 pj_qos_params qos_params;
747 unsigned msec, msec2;
748 pj_status_t status = PJ_EUNKNOWN;
749
750 pj_lock_acquire(h->ioqueue->lock);
751
752 old_sock = h->fd;
753
754 fds_cnt = 0;
755 fds[fds_cnt++] = &h->ioqueue->rfdset;
756 fds[fds_cnt++] = &h->ioqueue->wfdset;
757 #if PJ_HAS_TCP
758 fds[fds_cnt++] = &h->ioqueue->xfdset;
759 #endif
760
761 /* Can only replace UDP socket */
762 pj_assert(h->fd_type == pj_SOCK_DGRAM());
763
764 PJ_LOG(4,(THIS_FILE, "Attempting to replace UDP socket %ld", old_sock));
765
766 for (msec=20; (msec<1000 && status != PJ_SUCCESS); msec=msec*2)
767 {
768 if (msec > 20) {
769 PJ_LOG(4,(THIS_FILE, "Retry to replace UDP socket %ld", h->fd));
770 pj_thread_sleep(msec);
771 }
772
773 if (old_sock != PJ_INVALID_SOCKET) {
774 /* Investigate the old socket */
775 addr_len = sizeof(local_addr);
776 status = pj_sock_getsockname(old_sock, &local_addr, &addr_len);
777 if (status != PJ_SUCCESS) {
778 PJ_PERROR(5,(THIS_FILE, status, "Error get socket name"));
779 continue;
780 }
781
782 addr_len = sizeof(rem_addr);
783 status = pj_sock_getpeername(old_sock, &rem_addr, &addr_len);
784 if (status != PJ_SUCCESS) {
785 PJ_PERROR(5,(THIS_FILE, status, "Error get peer name"));
786 } else {
787 flags |= HAS_PEER_ADDR;
788 }
789
790 status = pj_sock_get_qos_params(old_sock, &qos_params);
791 if (status == PJ_STATUS_FROM_OS(EBADF) ||
792 status == PJ_STATUS_FROM_OS(EINVAL))
793 {
794 PJ_PERROR(5,(THIS_FILE, status, "Error get qos param"));
795 continue;
796 }
797
798 if (status != PJ_SUCCESS) {
799 PJ_PERROR(5,(THIS_FILE, status, "Error get qos param"));
800 } else {
801 flags |= HAS_QOS;
802 }
803
804 /* We're done with the old socket, close it otherwise we'll get
805 * error in bind()
806 */
807 status = pj_sock_close(old_sock);
808 if (status != PJ_SUCCESS) {
809 PJ_PERROR(5,(THIS_FILE, status, "Error closing socket"));
810 }
811
812 old_sock = PJ_INVALID_SOCKET;
813 }
814
815 /* Prepare the new socket */
816 status = pj_sock_socket(local_addr.addr.sa_family, PJ_SOCK_DGRAM, 0,
817 &new_sock);
818 if (status != PJ_SUCCESS) {
819 PJ_PERROR(5,(THIS_FILE, status, "Error create socket"));
820 continue;
821 }
822
823 /* Even after the socket is closed, we'll still get "Address in use"
824 * errors, so force it with SO_REUSEADDR
825 */
826 val = 1;
827 status = pj_sock_setsockopt(new_sock, SOL_SOCKET, SO_REUSEADDR,
828 &val, sizeof(val));
829 if (status == PJ_STATUS_FROM_OS(EBADF) ||
830 status == PJ_STATUS_FROM_OS(EINVAL))
831 {
832 PJ_PERROR(5,(THIS_FILE, status, "Error set socket option"));
833 continue;
834 }
835
836 /* The loop is silly, but what else can we do? */
837 addr_len = pj_sockaddr_get_len(&local_addr);
838 for (msec2=20; msec2<1000 ; msec2=msec2*2) {
839 status = pj_sock_bind(new_sock, &local_addr, addr_len);
840 if (status != PJ_STATUS_FROM_OS(EADDRINUSE))
841 break;
842 PJ_LOG(4,(THIS_FILE, "Address is still in use, retrying.."));
843 pj_thread_sleep(msec2);
844 }
845
846 if (status != PJ_SUCCESS)
847 continue;
848
849 if (flags & HAS_QOS) {
850 status = pj_sock_set_qos_params(new_sock, &qos_params);
851 if (status == PJ_STATUS_FROM_OS(EINVAL)) {
852 PJ_PERROR(5,(THIS_FILE, status, "Error set qos param"));
853 continue;
854 }
855 }
856
857 if (flags & HAS_PEER_ADDR) {
858 status = pj_sock_connect(new_sock, &rem_addr, addr_len);
859 if (status != PJ_SUCCESS) {
860 PJ_PERROR(5,(THIS_FILE, status, "Error connect socket"));
861 continue;
862 }
863 }
864 }
865
866 if (status != PJ_SUCCESS)
867 goto on_error;
868
869 /* Set socket to nonblocking. */
870 val = 1;
871 #if defined(PJ_WIN32) && PJ_WIN32!=0 || \
872 defined(PJ_WIN64) && PJ_WIN64 != 0 || \
873 defined(PJ_WIN32_WINCE) && PJ_WIN32_WINCE!=0
874 if (ioctlsocket(new_sock, FIONBIO, &val)) {
875 #else
876 if (ioctl(new_sock, FIONBIO, &val)) {
877 #endif
878 status = pj_get_netos_error();
879 goto on_error;
880 }
881
882 /* Replace the occurrence of old socket with new socket in the
883 * fd sets.
884 */
885 for (i=0; i<fds_cnt; ++i) {
886 if (PJ_FD_ISSET(h->fd, fds[i])) {
887 PJ_FD_CLR(h->fd, fds[i]);
888 PJ_FD_SET(new_sock, fds[i]);
889 }
890 }
891
892 /* And finally replace the fd in the key */
893 h->fd = new_sock;
894
895 PJ_LOG(4,(THIS_FILE, "UDP has been replaced successfully!"));
896
897 pj_lock_release(h->ioqueue->lock);
898
899 return PJ_SUCCESS;
900
901 on_error:
902 if (new_sock != PJ_INVALID_SOCKET)
903 pj_sock_close(new_sock);
904 if (old_sock != PJ_INVALID_SOCKET)
905 pj_sock_close(old_sock);
906
907 /* Clear the occurrence of old socket in the fd sets. */
908 for (i=0; i<fds_cnt; ++i) {
909 if (PJ_FD_ISSET(h->fd, fds[i])) {
910 PJ_FD_CLR(h->fd, fds[i]);
911 }
912 }
913
914 h->fd = PJ_INVALID_SOCKET;
915 PJ_PERROR(1,(THIS_FILE, status, "Error replacing socket %ld", old_sock));
916 pj_lock_release(h->ioqueue->lock);
917 return PJ_ESOCKETSTOP;
918 }
919 #endif
920
921
922 /*
923 * pj_ioqueue_poll()
924 *
925 * Few things worth written:
926 *
927 * - we used to do only one callback called per poll, but it didn't go
928 * very well. The reason is because on some situation, the write
929 * callback gets called all the time, thus doesn't give the read
930 * callback to get called. This happens, for example, when user
931 * submit write operation inside the write callback.
932 * As the result, we changed the behaviour so that now multiple
933 * callbacks are called in a single poll. It should be fast too,
934 * just that we need to be carefull with the ioqueue data structs.
935 *
936 * - to guarantee preemptiveness etc, the poll function must strictly
937 * work on fd_set copy of the ioqueue (not the original one).
938 */
939 PJ_DEF(int) pj_ioqueue_poll( pj_ioqueue_t *ioqueue, const pj_time_val *timeout)
940 {
941 pj_fd_set_t rfdset, wfdset, xfdset;
942 int nfds;
943 int i, count, event_cnt, processed_cnt;
944 pj_ioqueue_key_t *h;
945 enum { MAX_EVENTS = PJ_IOQUEUE_MAX_CAND_EVENTS };
946 struct event
947 {
948 pj_ioqueue_key_t *key;
949 enum ioqueue_event_type event_type;
950 } event[MAX_EVENTS];
951
952 PJ_ASSERT_RETURN(ioqueue, -PJ_EINVAL);
953
954 #if defined(PJ_HAS_SSL_SOCK) && PJ_HAS_SSL_SOCK != 0 && \
955 (PJ_SSL_SOCK_IMP == PJ_SSL_SOCK_IMP_APPLE)
956 /* Call SSL Network framework event poll */
957 ssl_network_event_poll();
958 #endif
959
960 /* Lock ioqueue before making fd_set copies */
961 pj_lock_acquire(ioqueue->lock);
962
963 /* We will only do select() when there are sockets to be polled.
964 * Otherwise select() will return error.
965 */
966 if (PJ_FD_COUNT(&ioqueue->rfdset)==0 &&
967 PJ_FD_COUNT(&ioqueue->wfdset)==0
968 #if defined(PJ_HAS_TCP) && PJ_HAS_TCP!=0
969 && PJ_FD_COUNT(&ioqueue->xfdset)==0
970 #endif
971 )
972 {
973 #if PJ_IOQUEUE_HAS_SAFE_UNREG
974 scan_closing_keys(ioqueue);
975 #endif
976 pj_lock_release(ioqueue->lock);
977 TRACE__((THIS_FILE, " poll: no fd is set"));
978 if (timeout)
979 pj_thread_sleep(PJ_TIME_VAL_MSEC(*timeout));
980 return 0;
981 }
982
983 /* Copy ioqueue's pj_fd_set_t to local variables. */
984 pj_memcpy(&rfdset, &ioqueue->rfdset, sizeof(pj_fd_set_t));
985 pj_memcpy(&wfdset, &ioqueue->wfdset, sizeof(pj_fd_set_t));
986 #if PJ_HAS_TCP
987 pj_memcpy(&xfdset, &ioqueue->xfdset, sizeof(pj_fd_set_t));
988 #else
989 PJ_FD_ZERO(&xfdset);
990 #endif
991
992 #if VALIDATE_FD_SET
993 validate_sets(ioqueue, &rfdset, &wfdset, &xfdset);
994 #endif
995
996 nfds = ioqueue->nfds;
997
998 /* Unlock ioqueue before select(). */
999 pj_lock_release(ioqueue->lock);
1000
1001 #if defined(PJ_WIN32_WINPHONE8) && PJ_WIN32_WINPHONE8
1002 count = 0;
1003 __try {
1004 #endif
1005
1006 count = pj_sock_select(nfds+1, &rfdset, &wfdset, &xfdset,
1007 timeout);
1008
1009 #if defined(PJ_WIN32_WINPHONE8) && PJ_WIN32_WINPHONE8
1010 /* Ignore Invalid Handle Exception raised by select().*/
1011 }
1012 __except (GetExceptionCode() == STATUS_INVALID_HANDLE ?
1013 EXCEPTION_CONTINUE_EXECUTION : EXCEPTION_CONTINUE_SEARCH) {
1014 }
1015 #endif
1016
1017 if (count == 0)
1018 return 0;
1019 else if (count < 0)
1020 return -pj_get_netos_error();
1021
1022 /* Scan descriptor sets for event and add the events in the event
1023 * array to be processed later in this function. We do this so that
1024 * events can be processed in parallel without holding ioqueue lock.
1025 */
1026 pj_lock_acquire(ioqueue->lock);
1027
1028 event_cnt = 0;
1029
1030 /* Scan for writable sockets first to handle piggy-back data
1031 * coming with accept().
1032 */
1033 for (h = ioqueue->active_list.next;
1034 h != &ioqueue->active_list && event_cnt < MAX_EVENTS;
1035 h = h->next)
1036 {
1037 if (h->fd == PJ_INVALID_SOCKET)
1038 continue;
1039
1040 if ( (key_has_pending_write(h) || key_has_pending_connect(h))
1041 && PJ_FD_ISSET(h->fd, &wfdset) && !IS_CLOSING(h))
1042 {
1043 #if PJ_IOQUEUE_HAS_SAFE_UNREG
1044 increment_counter(h);
1045 #endif
1046 event[event_cnt].key = h;
1047 event[event_cnt].event_type = WRITEABLE_EVENT;
1048 ++event_cnt;
1049 }
1050
1051 /* Scan for readable socket. */
1052 if ((key_has_pending_read(h) || key_has_pending_accept(h))
1053 && PJ_FD_ISSET(h->fd, &rfdset) && !IS_CLOSING(h) &&
1054 event_cnt < MAX_EVENTS)
1055 {
1056 #if PJ_IOQUEUE_HAS_SAFE_UNREG
1057 increment_counter(h);
1058 #endif
1059 event[event_cnt].key = h;
1060 event[event_cnt].event_type = READABLE_EVENT;
1061 ++event_cnt;
1062 }
1063
1064 #if PJ_HAS_TCP
1065 if (key_has_pending_connect(h) && PJ_FD_ISSET(h->fd, &xfdset) &&
1066 !IS_CLOSING(h) && event_cnt < MAX_EVENTS)
1067 {
1068 #if PJ_IOQUEUE_HAS_SAFE_UNREG
1069 increment_counter(h);
1070 #endif
1071 event[event_cnt].key = h;
1072 event[event_cnt].event_type = EXCEPTION_EVENT;
1073 ++event_cnt;
1074 }
1075 #endif
1076 }
1077
1078 for (i=0; i<event_cnt; ++i) {
1079 if (event[i].key->grp_lock)
1080 pj_grp_lock_add_ref_dbg(event[i].key->grp_lock, "ioqueue", 0);
1081 }
1082
1083 PJ_RACE_ME(5);
1084
1085 pj_lock_release(ioqueue->lock);
1086
1087 PJ_RACE_ME(5);
1088
1089 processed_cnt = 0;
1090
1091 /* Now process all events. The dispatch functions will take care
1092 * of locking in each of the key
1093 */
1094 for (i=0; i<event_cnt; ++i) {
1095
1096 /* Just do not exceed PJ_IOQUEUE_MAX_EVENTS_IN_SINGLE_POLL */
1097 if (processed_cnt < PJ_IOQUEUE_MAX_EVENTS_IN_SINGLE_POLL) {
1098 switch (event[i].event_type) {
1099 case READABLE_EVENT:
1100 if (ioqueue_dispatch_read_event(ioqueue, event[i].key))
1101 ++processed_cnt;
1102 break;
1103 case WRITEABLE_EVENT:
1104 if (ioqueue_dispatch_write_event(ioqueue, event[i].key))
1105 ++processed_cnt;
1106 break;
1107 case EXCEPTION_EVENT:
1108 if (ioqueue_dispatch_exception_event(ioqueue, event[i].key))
1109 ++processed_cnt;
1110 break;
1111 case NO_EVENT:
1112 pj_assert(!"Invalid event!");
1113 break;
1114 }
1115 }
1116
1117 #if PJ_IOQUEUE_HAS_SAFE_UNREG
1118 decrement_counter(event[i].key);
1119 #endif
1120
1121 if (event[i].key->grp_lock)
1122 pj_grp_lock_dec_ref_dbg(event[i].key->grp_lock,
1123 "ioqueue", 0);
1124 }
1125
1126 TRACE__((THIS_FILE, " poll: count=%d events=%d processed=%d",
1127 count, event_cnt, processed_cnt));
1128
1129 return processed_cnt;
1130 }
1131
1132 PJ_DEF(pj_oshandle_t) pj_ioqueue_get_os_handle( pj_ioqueue_t *ioqueue )
1133 {
1134 PJ_UNUSED_ARG(ioqueue);
1135 return NULL;
1136 }
1137
1138 #endif /* PJ_IOQUEUE_IMP == PJ_IOQUEUE_IMP_SELECT */