blob: b6c94fa4efb5c6d8af67a67cc33a27bd65ad0686 [file] [log] [blame]
Brian Waters13d96012017-12-08 16:53:31 -06001/*********************************************************************************************************
2* Software License Agreement (BSD License) *
3* Author: Sebastien Decugis <sdecugis@freediameter.net> *
4* *
5* Copyright (c) 2013, WIDE Project and NICT *
6* All rights reserved. *
7* *
8* Redistribution and use of this software in source and binary forms, with or without modification, are *
9* permitted provided that the following conditions are met: *
10* *
11* * Redistributions of source code must retain the above *
12* copyright notice, this list of conditions and the *
13* following disclaimer. *
14* *
15* * Redistributions in binary form must reproduce the above *
16* copyright notice, this list of conditions and the *
17* following disclaimer in the documentation and/or other *
18* materials provided with the distribution. *
19* *
20* * Neither the name of the WIDE Project or NICT nor the *
21* names of its contributors may be used to endorse or *
22* promote products derived from this software without *
23* specific prior written permission of WIDE Project and *
24* NICT. *
25* *
26* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED *
27* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A *
28* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR *
29* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT *
30* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS *
31* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR *
32* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF *
33* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *
34*********************************************************************************************************/
35
36/* Sessions module.
37 *
38 * Basic functionalities to help implementing User sessions state machines from RFC3588.
39 */
40
41#include "fdproto-internal.h"
42
43/*********************** Parameters **********************/
44
45/* Size of the hash table containing the session objects (pow of 2. ex: 6 => 2^6 = 64). must be between 0 and 31. */
46#ifndef SESS_HASH_SIZE
47#define SESS_HASH_SIZE 6
48#endif /* SESS_HASH_SIZE */
49
50/* Default lifetime of a session, in seconds. (31 days = 2678400 seconds) */
51#ifndef SESS_DEFAULT_LIFETIME
52#define SESS_DEFAULT_LIFETIME 2678400
53#endif /* SESS_DEFAULT_LIFETIME */
54
55/********************** /Parameters **********************/
56
57/* Eyescatchers definitions */
58#define SH_EYEC 0x53554AD1
59#define SD_EYEC 0x5355D474
60#define SI_EYEC 0x53551D
61
62/* Macro to check an object is valid */
63#define VALIDATE_SH( _obj ) ( ((_obj) != NULL) && ( ((struct session_handler *)(_obj))->eyec == SH_EYEC) )
64#define VALIDATE_SI( _obj ) ( ((_obj) != NULL) && ( ((struct session *)(_obj))->eyec == SI_EYEC) )
65
66
67/* Handlers registered by users of the session module */
68struct session_handler {
69 int eyec; /* An eye catcher also used to ensure the object is valid, must be SH_EYEC */
70 int id; /* A unique integer to identify this handler */
71 void (*cleanup)(struct sess_state *, os0_t, void *); /* The cleanup function to be called for cleaning a state */
72 session_state_dump state_dump; /* dumper function */
73 void *opaque; /* a value that is passed as is to the cleanup callback */
74};
75
76static int hdl_id = 0; /* A global counter to initialize the id field */
77static pthread_mutex_t hdl_lock = PTHREAD_MUTEX_INITIALIZER; /* lock to protect hdl_id; we could use atomic operations otherwise (less portable) */
78
79
80/* Data structures linked from the sessions, containing the applications states */
81struct state {
82 int eyec; /* Must be SD_EYEC */
83 struct sess_state *state; /* The state registered by the application, never NULL (or the whole object is deleted) */
84 struct fd_list chain; /* Chaining in the list of session's states ordered by hdl->id */
85 union {
86 struct session_handler *hdl; /* The handler for which this state was registered */
87 os0_t sid; /* For deleted state, the sid of the session it belong to */
88 };
89};
90
91/* Session object, one for each value of Session-Id AVP */
92struct session {
93 int eyec; /* Eyecatcher, SI_EYEC */
94
95 os0_t sid; /* The \0-terminated Session-Id */
96 size_t sidlen; /* cached length of sid */
97 uint32_t hash; /* computed hash of sid */
98 struct fd_list chain_h;/* chaining in the hash table of sessions. */
99
100 struct timespec timeout;/* Timeout date for the session */
101 struct fd_list expire; /* List of expiring sessions, ordered by timeouts. */
102
103 pthread_mutex_t stlock; /* A lock to protect the list of states associated with this session */
104 struct fd_list states; /* Sentinel for the list of states of this session. */
105 int msg_cnt;/* Reference counter for the messages pointing to this session */
106 int is_destroyed; /* boolean telling if fd_sess_detroy has been called on this */
107};
108
109/* Sessions hash table, to allow fast sid to session retrieval */
110static struct {
111 struct fd_list sentinel; /* sentinel element for this sublist. The sublist is ordered by hash value, then fd_os_cmp(sid). */
112 pthread_mutex_t lock; /* the mutex for this sublist -- we might probably change it to rwlock for a little optimization */
113} sess_hash [ 1 << SESS_HASH_SIZE ] ;
114#define H_MASK( __hash ) ((__hash) & (( 1 << SESS_HASH_SIZE ) - 1))
115#define H_LIST( _hash ) (&(sess_hash[H_MASK(_hash)].sentinel))
116#define H_LOCK( _hash ) (&(sess_hash[H_MASK(_hash)].lock ))
117
118static uint32_t sess_cnt = 0; /* counts all active session (that are in the expiry list) */
119
120/* The following are used to generate sid values that are eternaly unique */
121static uint32_t sid_h; /* initialized to the current time in fd_sess_init */
122static uint32_t sid_l; /* incremented each time a session id is created */
123static pthread_mutex_t sid_lock = PTHREAD_MUTEX_INITIALIZER;
124
125/* Expiring sessions management */
126static struct fd_list exp_sentinel = FD_LIST_INITIALIZER(exp_sentinel); /* list of sessions ordered by their timeout date */
127static pthread_mutex_t exp_lock = PTHREAD_MUTEX_INITIALIZER; /* lock protecting the list. */
128static pthread_cond_t exp_cond = PTHREAD_COND_INITIALIZER; /* condvar used by the expiry mecahinsm. */
129static pthread_t exp_thr = (pthread_t)NULL; /* The expiry thread that handles cleanup of expired sessions */
130
131/* Hierarchy of the locks, to avoid deadlocks:
132 * hash lock > state lock > expiry lock
133 * i.e. state lock can be taken while holding the hash lock, but not while holding the expiry lock.
134 * As well, the hash lock cannot be taken while holding a state lock.
135 */
136
137/********************************************************************************************************/
138
139/* Initialize a session object. It is not linked now. sid must be already malloc'ed. The hash has already been computed. */
140static struct session * new_session(os0_t sid, size_t sidlen, uint32_t hash)
141{
142 struct session * sess;
143
144 TRACE_ENTRY("%p %zd", sid, sidlen);
145 CHECK_PARAMS_DO( sid && sidlen, return NULL );
146
147 CHECK_MALLOC_DO( sess = malloc(sizeof(struct session)), return NULL );
148 memset(sess, 0, sizeof(struct session));
149
150 sess->eyec = SI_EYEC;
151
152 sess->sid = sid;
153 sess->sidlen = sidlen;
154 sess->hash = hash;
155 fd_list_init(&sess->chain_h, sess);
156
157 CHECK_SYS_DO( clock_gettime(CLOCK_REALTIME, &sess->timeout), return NULL );
158 sess->timeout.tv_sec += SESS_DEFAULT_LIFETIME;
159 fd_list_init(&sess->expire, sess);
160
161 CHECK_POSIX_DO( pthread_mutex_init(&sess->stlock, NULL), return NULL );
162 fd_list_init(&sess->states, sess);
163
164 return sess;
165}
166
167/* destroy the session object. It should really be already unlinked... */
168static void del_session(struct session * s)
169{
170 ASSERT(FD_IS_LIST_EMPTY(&s->states));
171 free(s->sid);
172 fd_list_unlink(&s->chain_h);
173 fd_list_unlink(&s->expire);
174 CHECK_POSIX_DO( pthread_mutex_destroy(&s->stlock), /* continue */ );
175 free(s);
176}
177
178/* The expiry thread */
179static void * exp_fct(void * arg)
180{
181 fd_log_threadname ( "Session/expire" );
182 TRACE_ENTRY( "" );
183
184
185 do {
186 struct timespec now;
187 struct session * first;
188
189 CHECK_POSIX_DO( pthread_mutex_lock(&exp_lock), break );
190 pthread_cleanup_push( fd_cleanup_mutex, &exp_lock );
191again:
192 /* Check if there are expiring sessions available */
193 if (FD_IS_LIST_EMPTY(&exp_sentinel)) {
194 /* Just wait for a change or cancelation */
195 CHECK_POSIX_DO( pthread_cond_wait( &exp_cond, &exp_lock ), break /* this might not pop the cleanup handler, but since we ASSERT(0), it is not the big issue... */ );
196 /* Restart the loop on wakeup */
197 goto again;
198 }
199
200 /* Get the pointer to the session that expires first */
201 first = (struct session *)(exp_sentinel.next->o);
202 ASSERT( VALIDATE_SI(first) );
203
204 /* Get the current time */
205 CHECK_SYS_DO( clock_gettime(CLOCK_REALTIME, &now), break );
206
207 /* If first session is not expired, we just wait until it happens */
208 if ( TS_IS_INFERIOR( &now, &first->timeout ) ) {
209
210 CHECK_POSIX_DO2( pthread_cond_timedwait( &exp_cond, &exp_lock, &first->timeout ),
211 ETIMEDOUT, /* ETIMEDOUT is a normal error, continue */,
212 /* on other error, */ break );
213
214 /* on wakeup, loop */
215 goto again;
216 }
217
218 /* Now, the first session in the list is expired; destroy it */
219 pthread_cleanup_pop( 0 );
220 CHECK_POSIX_DO( pthread_mutex_unlock(&exp_lock), break );
221
222 CHECK_FCT_DO( fd_sess_destroy( &first ), break );
223
224 } while (1);
225
226 TRACE_DEBUG(INFO, "A system error occurred in session module! Expiry thread is terminating...");
227 ASSERT(0);
228 return NULL;
229}
230
231
232
233/********************************************************************************************************/
234
235/* Initialize the session module */
236int fd_sess_init(void)
237{
238 int i;
239
240 TRACE_ENTRY( "" );
241
242 /* Initialize the global counters */
243 sid_h = (uint32_t) time(NULL);
244 sid_l = 0;
245
246 /* Initialize the hash table */
247 for (i = 0; i < sizeof(sess_hash) / sizeof(sess_hash[0]); i++) {
248 fd_list_init( &sess_hash[i].sentinel, NULL );
249 CHECK_POSIX( pthread_mutex_init(&sess_hash[i].lock, NULL) );
250 }
251
252 return 0;
253}
254
255/* Run this when initializations are complete. */
256int fd_sess_start(void)
257{
258 /* Start session garbage collector (expiry) */
259 CHECK_POSIX( pthread_create(&exp_thr, NULL, exp_fct, NULL) );
260
261 return 0;
262}
263
264/* Terminate */
265void fd_sess_fini(void)
266{
267 TRACE_ENTRY("");
268 CHECK_FCT_DO( fd_thr_term(&exp_thr), /* continue */ );
269
270 /* Destroy all sessions in the hash table, and the hash table itself? -- How to do it without a race condition ? */
271
272 return;
273}
274
275/* Create a new handler */
276int fd_sess_handler_create ( struct session_handler ** handler, void (*cleanup)(struct sess_state *, os0_t, void *), session_state_dump dumper, void * opaque )
277{
278 struct session_handler *new;
279
280 TRACE_ENTRY("%p %p", handler, cleanup);
281
282 CHECK_PARAMS( handler && cleanup );
283
284 CHECK_MALLOC( new = malloc(sizeof(struct session_handler)) );
285 memset(new, 0, sizeof(struct session_handler));
286
287 CHECK_POSIX( pthread_mutex_lock(&hdl_lock) );
288 new->id = ++hdl_id;
289 CHECK_POSIX( pthread_mutex_unlock(&hdl_lock) );
290
291 new->eyec = SH_EYEC;
292 new->cleanup = cleanup;
293 new->state_dump = dumper;
294 new->opaque = opaque;
295
296 *handler = new;
297 return 0;
298}
299
300/* Destroy a handler, and all states attached to this handler. This operation is very slow but we don't care since it's rarely used.
301 * Note that it's better to call this function after all sessions have been deleted... */
302int fd_sess_handler_destroy ( struct session_handler ** handler, void ** opaque )
303{
304 struct session_handler * del;
305 /* place to save the list of states to be cleaned up. We do it after finding them to avoid deadlocks. the "o" field becomes a copy of the sid. */
306 struct fd_list deleted_states = FD_LIST_INITIALIZER( deleted_states );
307 int i;
308
309 TRACE_ENTRY("%p", handler);
310 CHECK_PARAMS( handler && VALIDATE_SH(*handler) );
311
312 del = *handler;
313 *handler = NULL;
314
315 del->eyec = 0xdead; /* The handler is not valid anymore for any other operation */
316
317 /* Now find all sessions with data registered for this handler, and move this data to the deleted_states list. */
318 for (i = 0; i < sizeof(sess_hash) / sizeof(sess_hash[0]); i++) {
319 struct fd_list * li_si;
320 CHECK_POSIX( pthread_mutex_lock(&sess_hash[i].lock) );
321
322 for (li_si = sess_hash[i].sentinel.next; li_si != &sess_hash[i].sentinel; li_si = li_si->next) { /* for each session in the hash line */
323 struct fd_list * li_st;
324 struct session * sess = (struct session *)(li_si->o);
325 CHECK_POSIX( pthread_mutex_lock(&sess->stlock) );
326 for (li_st = sess->states.next; li_st != &sess->states; li_st = li_st->next) { /* for each state in this session */
327 struct state * st = (struct state *)(li_st->o);
328 /* The list is ordered */
329 if (st->hdl->id < del->id)
330 continue;
331 if (st->hdl->id == del->id) {
332 /* This state belongs to the handler we are deleting, move the item to the deleted_states list */
333 fd_list_unlink(&st->chain);
334 st->sid = sess->sid;
335 fd_list_insert_before(&deleted_states, &st->chain);
336 }
337 break;
338 }
339 CHECK_POSIX( pthread_mutex_unlock(&sess->stlock) );
340 }
341 CHECK_POSIX( pthread_mutex_unlock(&sess_hash[i].lock) );
342 }
343
344 /* Now, delete all states after calling their cleanup handler */
345 while (!FD_IS_LIST_EMPTY(&deleted_states)) {
346 struct state * st = (struct state *)(deleted_states.next->o);
347 TRACE_DEBUG(FULL, "Calling cleanup handler for session '%s' and data %p", st->sid, st->state);
348 (*del->cleanup)(st->state, st->sid, del->opaque);
349 fd_list_unlink(&st->chain);
350 free(st);
351 }
352
353 if (opaque)
354 *opaque = del->opaque;
355
356 /* Free the handler */
357 free(del);
358
359 return 0;
360}
361
362
363
364/* Create a new session object with the default timeout value, and link it. The refcount is increased by 1, whether the session existed or not */
365int fd_sess_new ( struct session ** session, DiamId_t diamid, size_t diamidlen, uint8_t * opt, size_t optlen )
366{
367 os0_t sid = NULL;
368 size_t sidlen;
369 uint32_t hash;
370 struct session * sess;
371 struct fd_list * li;
372 int found = 0;
373 int ret = 0;
374
375 TRACE_ENTRY("%p %p %zd %p %zd", session, diamid, diamidlen, opt, optlen);
376 CHECK_PARAMS( session && (diamid || opt) );
377
378 if (diamid) {
379 if (!diamidlen) {
380 diamidlen = strlen(diamid);
381 }
382 /* We check if the string is a valid DiameterIdentity */
383 CHECK_PARAMS( fd_os_is_valid_DiameterIdentity((uint8_t *)diamid, diamidlen) );
384 } else {
385 diamidlen = 0;
386 }
387 if (opt) {
388 if (!optlen) {
389 optlen = strlen((char *)opt);
390 } else {
391 CHECK_PARAMS( fd_os_is_valid_os0(opt, optlen) );
392 }
393 } else {
394 optlen = 0;
395 }
396
397 /* Ok, first create the identifier for the string */
398 if (diamid == NULL) {
399 /* opt is the full string */
400 CHECK_MALLOC( sid = os0dup(opt, optlen) );
401 sidlen = optlen;
402 } else {
403 uint32_t sid_h_cpy;
404 uint32_t sid_l_cpy;
405 /* "<diamId>;<high32>;<low32>[;opt]" */
406 sidlen = diamidlen;
407 sidlen += 22; /* max size of ';<high32>;<low32>' */
408 if (opt)
409 sidlen += 1 + optlen; /* ';opt' */
410 sidlen++; /* space for the final \0 also */
411 CHECK_MALLOC( sid = malloc(sidlen) );
412
413 CHECK_POSIX( pthread_mutex_lock(&sid_lock) );
414 if ( ++sid_l == 0 ) /* overflow */
415 ++sid_h;
416 sid_h_cpy = sid_h;
417 sid_l_cpy = sid_l;
418 CHECK_POSIX( pthread_mutex_unlock(&sid_lock) );
419
420 if (opt) {
421 sidlen = snprintf((char*)sid, sidlen, "%.*s;%u;%u;%.*s", (int)diamidlen, diamid, sid_h_cpy, sid_l_cpy, (int)optlen, opt);
422 } else {
423 sidlen = snprintf((char*)sid, sidlen, "%.*s;%u;%u", (int)diamidlen, diamid, sid_h_cpy, sid_l_cpy);
424 }
425 }
426
427 hash = fd_os_hash(sid, sidlen);
428
429 /* Now find the place to add this object in the hash table. */
430 CHECK_POSIX( pthread_mutex_lock( H_LOCK(hash) ) );
431 pthread_cleanup_push( fd_cleanup_mutex, H_LOCK(hash) );
432
433 for (li = H_LIST(hash)->next; li != H_LIST(hash); li = li->next) {
434 int cmp;
435 struct session * s = (struct session *)(li->o);
436
437 /* The list is ordered by hash and sid (in case of collisions) */
438 if (s->hash < hash)
439 continue;
440 if (s->hash > hash)
441 break;
442
443 cmp = fd_os_cmp(s->sid, s->sidlen, sid, sidlen);
444 if (cmp < 0)
445 continue;
446 if (cmp > 0)
447 break;
448
449 /* A session with the same sid was already in the hash table */
450 found = 1;
451 *session = s;
452 break;
453 }
454
455 /* If the session did not exist, we can create it & link it in global tables */
456 if (!found) {
457 CHECK_MALLOC_DO(sess = new_session(sid, sidlen, hash),
458 {
459 ret = ENOMEM;
460 free(sid);
461 goto out;
462 } );
463
464 fd_list_insert_before(li, &sess->chain_h); /* hash table */
465 sess->msg_cnt++;
466 } else {
467 free(sid);
468
469 CHECK_POSIX( pthread_mutex_lock(&(*session)->stlock) );
470 (*session)->msg_cnt++;
471 CHECK_POSIX( pthread_mutex_unlock(&(*session)->stlock) );
472
473 /* it was found: was it previously destroyed? */
474 if ((*session)->is_destroyed == 0) {
475 ret = EALREADY;
476 goto out;
477 } else {
478 /* the session was marked destroyed, let's re-activate it. */
479 sess = *session;
480 sess->is_destroyed = 0;
481
482 /* update the expiry time */
483 CHECK_SYS_DO( clock_gettime(CLOCK_REALTIME, &sess->timeout), { ASSERT(0); } );
484 sess->timeout.tv_sec += SESS_DEFAULT_LIFETIME;
485 }
486 }
487
488 /* We must insert in the expiry list */
489 CHECK_POSIX( pthread_mutex_lock( &exp_lock ) );
490 pthread_cleanup_push( fd_cleanup_mutex, &exp_lock );
491
492 /* Find the position in that list. We take it in reverse order */
493 for (li = exp_sentinel.prev; li != &exp_sentinel; li = li->prev) {
494 struct session * s = (struct session *)(li->o);
495 if (TS_IS_INFERIOR( &s->timeout, &sess->timeout ) )
496 break;
497 }
498 fd_list_insert_after( li, &sess->expire );
499 sess_cnt++;
500
501 /* We added a new expiring element, we must signal */
502 if (li == &exp_sentinel) {
503 CHECK_POSIX_DO( pthread_cond_signal(&exp_cond), { ASSERT(0); } ); /* if it fails, we might not pop the cleanup handlers, but this should not happen -- and we'd have a serious problem otherwise */
504 }
505
506 /* We're done with the locked part */
507 pthread_cleanup_pop(0);
508 CHECK_POSIX_DO( pthread_mutex_unlock( &exp_lock ), { ASSERT(0); } ); /* if it fails, we might not pop the cleanup handler, but this should not happen -- and we'd have a serious problem otherwise */
509
510out:
511 ;
512 pthread_cleanup_pop(0);
513 CHECK_POSIX( pthread_mutex_unlock( H_LOCK(hash) ) );
514
515 if (ret) /* in case of error */
516 return ret;
517
518 *session = sess;
519 return 0;
520}
521
522/* Find or create a session -- the msg refcount is increased */
523int fd_sess_fromsid_msg ( uint8_t * sid, size_t len, struct session ** session, int * new)
524{
525 int ret;
526
527 TRACE_ENTRY("%p %zd %p %p", sid, len, session, new);
528 CHECK_PARAMS( sid && session );
529
530 if (!fd_os_is_valid_os0(sid,len)) {
531 TRACE_DEBUG(INFO, "Warning: a Session-Id value contains \\0 chars... (len:%zd, begin:'%.*s') => Debug messages may be truncated.", len, (int)len, sid);
532 }
533
534 /* All the work is done in sess_new */
535 ret = fd_sess_new ( session, NULL, 0, sid, len );
536 switch (ret) {
537 case 0:
538 case EALREADY:
539 break;
540
541 default:
542 CHECK_FCT(ret);
543 }
544
545 if (new)
546 *new = ret ? 0 : 1;
547
548 return 0;
549}
550
551/* Get the sid of a session */
552int fd_sess_getsid ( struct session * session, os0_t * sid, size_t * sidlen )
553{
554 TRACE_ENTRY("%p %p", session, sid);
555
556 CHECK_PARAMS( VALIDATE_SI(session) && sid );
557
558 *sid = session->sid;
559 if (sidlen)
560 *sidlen = session->sidlen;
561
562 return 0;
563}
564
565/* Change the timeout value of a session */
566int fd_sess_settimeout( struct session * session, const struct timespec * timeout )
567{
568 struct fd_list * li;
569
570 TRACE_ENTRY("%p %p", session, timeout);
571 CHECK_PARAMS( VALIDATE_SI(session) && timeout );
572
573 /* Lock -- do we need to lock the hash table as well? I don't think so... */
574 CHECK_POSIX( pthread_mutex_lock( &exp_lock ) );
575 pthread_cleanup_push( fd_cleanup_mutex, &exp_lock );
576
577 /* Update the timeout */
578 fd_list_unlink(&session->expire);
579 memcpy(&session->timeout, timeout, sizeof(struct timespec));
580
581 /* Find the new position in expire list. We take it in normal order */
582 for (li = exp_sentinel.next; li != &exp_sentinel; li = li->next) {
583 struct session * s = (struct session *)(li->o);
584
585 if (TS_IS_INFERIOR( &s->timeout, &session->timeout ) )
586 continue;
587
588 break;
589 }
590 fd_list_insert_before( li, &session->expire );
591
592 /* We added a new expiring element, we must signal if it was in first position */
593 if (session->expire.prev == &exp_sentinel) {
594 CHECK_POSIX_DO( pthread_cond_signal(&exp_cond), { ASSERT(0); /* so that we don't have a pending cancellation handler */ } );
595 }
596
597 /* We're done */
598 pthread_cleanup_pop(0);
599 CHECK_POSIX( pthread_mutex_unlock( &exp_lock ) );
600
601 return 0;
602}
603
604/* Destroy the states associated to a session, and mark it destroyed. */
605int fd_sess_destroy ( struct session ** session )
606{
607 struct session * sess;
608 int destroy_now;
609 os0_t sid;
610 int ret = 0;
611
612 /* place to save the list of states to be cleaned up. We do it after finding them to avoid deadlocks. the "o" field becomes a copy of the sid. */
613 struct fd_list deleted_states = FD_LIST_INITIALIZER( deleted_states );
614
615 TRACE_ENTRY("%p", session);
616 CHECK_PARAMS( session && VALIDATE_SI(*session) );
617
618 sess = *session;
619 *session = NULL;
620
621 /* Lock the hash line */
622 CHECK_POSIX( pthread_mutex_lock( H_LOCK(sess->hash) ) );
623 pthread_cleanup_push( fd_cleanup_mutex, H_LOCK(sess->hash) );
624
625 /* Unlink from the expiry list */
626 CHECK_POSIX_DO( pthread_mutex_lock( &exp_lock ), { ASSERT(0); /* otherwise cleanup handler is not pop'd */ } );
627 if (!FD_IS_LIST_EMPTY(&sess->expire)) {
628 sess_cnt--;
629 fd_list_unlink( &sess->expire ); /* no need to signal the condition here */
630 }
631 CHECK_POSIX_DO( pthread_mutex_unlock( &exp_lock ), { ASSERT(0); /* otherwise cleanup handler is not pop'd */ } );
632
633 /* Now move all states associated to this session into deleted_states */
634 CHECK_POSIX_DO( pthread_mutex_lock( &sess->stlock ), { ASSERT(0); /* otherwise cleanup handler is not pop'd */ } );
635 while (!FD_IS_LIST_EMPTY(&sess->states)) {
636 struct state * st = (struct state *)(sess->states.next->o);
637 fd_list_unlink(&st->chain);
638 fd_list_insert_before(&deleted_states, &st->chain);
639 }
640 CHECK_POSIX_DO( pthread_mutex_unlock( &sess->stlock ), { ASSERT(0); /* otherwise cleanup handler is not pop'd */ } );
641
642 /* Mark the session as destroyed */
643 destroy_now = (sess->msg_cnt == 0);
644 if (destroy_now) {
645 fd_list_unlink( &sess->chain_h );
646 sid = sess->sid;
647 } else {
648 sess->is_destroyed = 1;
649 CHECK_MALLOC_DO( sid = os0dup(sess->sid, sess->sidlen), ret = ENOMEM );
650 }
651 pthread_cleanup_pop(0);
652 CHECK_POSIX( pthread_mutex_unlock( H_LOCK(sess->hash) ) );
653
654 if (ret)
655 return ret;
656
657 /* Now, really delete the states */
658 while (!FD_IS_LIST_EMPTY(&deleted_states)) {
659 struct state * st = (struct state *)(deleted_states.next->o);
660 fd_list_unlink(&st->chain);
661 TRACE_DEBUG(FULL, "Calling handler %p cleanup for state %p registered with session '%s'", st->hdl, st, sid);
662 (*st->hdl->cleanup)(st->state, sid, st->hdl->opaque);
663 free(st);
664 }
665
666 /* Finally, destroy the session itself, if it is not referrenced by any message anymore */
667 if (destroy_now) {
668 del_session(sess);
669 } else {
670 free(sid);
671 }
672
673 return 0;
674}
675
676/* Destroy a session if it is not used */
677int fd_sess_reclaim ( struct session ** session )
678{
679 struct session * sess;
680 uint32_t hash;
681 int destroy_now = 0;
682
683 TRACE_ENTRY("%p", session);
684 CHECK_PARAMS( session && VALIDATE_SI(*session) );
685
686 sess = *session;
687 hash = sess->hash;
688 *session = NULL;
689
690 CHECK_POSIX( pthread_mutex_lock( H_LOCK(hash) ) );
691 pthread_cleanup_push( fd_cleanup_mutex, H_LOCK(hash) );
692 CHECK_POSIX_DO( pthread_mutex_lock( &sess->stlock ), { ASSERT(0); /* otherwise, cleanup not poped on FreeBSD */ } );
693 pthread_cleanup_push( fd_cleanup_mutex, &sess->stlock );
694 CHECK_POSIX_DO( pthread_mutex_lock( &exp_lock ), { ASSERT(0); /* otherwise, cleanup not poped on FreeBSD */ } );
695
696 /* We only do something if the states list is empty */
697 if (FD_IS_LIST_EMPTY(&sess->states)) {
698 /* In this case, we do as in destroy */
699 fd_list_unlink( &sess->expire );
700 destroy_now = (sess->msg_cnt == 0);
701 if (destroy_now) {
702 fd_list_unlink(&sess->chain_h);
703 } else {
704 /* just mark it as destroyed, it will be freed when the last message stops referencing it */
705 sess->is_destroyed = 1;
706 }
707 }
708
709 CHECK_POSIX_DO( pthread_mutex_unlock( &exp_lock ), { ASSERT(0); /* otherwise, cleanup not poped on FreeBSD */ } );
710 pthread_cleanup_pop(0);
711 CHECK_POSIX_DO( pthread_mutex_unlock( &sess->stlock ), { ASSERT(0); /* otherwise, cleanup not poped on FreeBSD */ } );
712 pthread_cleanup_pop(0);
713 CHECK_POSIX( pthread_mutex_unlock( H_LOCK(hash) ) );
714
715 if (destroy_now)
716 del_session(sess);
717
718 return 0;
719}
720
721/* Save a state information with a session */
722int fd_sess_state_store ( struct session_handler * handler, struct session * session, struct sess_state ** state )
723{
724 struct state *new;
725 struct fd_list * li;
726 int already = 0;
727 int ret = 0;
728
729 TRACE_ENTRY("%p %p %p", handler, session, state);
730 CHECK_PARAMS( handler && VALIDATE_SH(handler) && session && VALIDATE_SI(session) && (!session->is_destroyed) && state );
731
732 /* Lock the session state list */
733 CHECK_POSIX( pthread_mutex_lock(&session->stlock) );
734 pthread_cleanup_push( fd_cleanup_mutex, &session->stlock );
735
736 /* Create the new state object */
737 CHECK_MALLOC_DO(new = malloc(sizeof(struct state)), { ret = ENOMEM; goto out; } );
738 memset(new, 0, sizeof(struct state));
739
740 new->eyec = SD_EYEC;
741 new->state= *state;
742 fd_list_init(&new->chain, new);
743 new->hdl = handler;
744
745 /* find place for this state in the list */
746 for (li = session->states.next; li != &session->states; li = li->next) {
747 struct state * st = (struct state *)(li->o);
748 /* The list is ordered by handler's id */
749 if (st->hdl->id < handler->id)
750 continue;
751
752 if (st->hdl->id == handler->id) {
753 TRACE_DEBUG(INFO, "A state was already stored for session '%s' and handler '%p', at location %p", session->sid, st->hdl, st->state);
754 already = EALREADY;
755 }
756
757 break;
758 }
759
760 if (!already) {
761 fd_list_insert_before(li, &new->chain);
762 *state = NULL;
763 } else {
764 free(new);
765 }
766out:
767 ;
768 pthread_cleanup_pop(0);
769 CHECK_POSIX( pthread_mutex_unlock(&session->stlock) );
770
771 return ret ?: already;
772}
773
774/* Get the data back */
775int fd_sess_state_retrieve ( struct session_handler * handler, struct session * session, struct sess_state ** state )
776{
777 struct fd_list * li;
778 struct state * st = NULL;
779
780 TRACE_ENTRY("%p %p %p", handler, session, state);
781 CHECK_PARAMS( handler && VALIDATE_SH(handler) && session && VALIDATE_SI(session) && state );
782
783 *state = NULL;
784
785 /* Lock the session state list */
786 CHECK_POSIX( pthread_mutex_lock(&session->stlock) );
787 pthread_cleanup_push( fd_cleanup_mutex, &session->stlock );
788
789 /* find the state in the list */
790 for (li = session->states.next; li != &session->states; li = li->next) {
791 st = (struct state *)(li->o);
792
793 /* The list is ordered by handler's id */
794 if (st->hdl->id > handler->id)
795 break;
796 }
797
798 /* If we found the state */
799 if (st && (st->hdl == handler)) {
800 fd_list_unlink(&st->chain);
801 *state = st->state;
802 free(st);
803 }
804
805 pthread_cleanup_pop(0);
806 CHECK_POSIX( pthread_mutex_unlock(&session->stlock) );
807
808 return 0;
809}
810
811/* For the messages module */
812int fd_sess_fromsid ( uint8_t * sid, size_t len, struct session ** session, int * new)
813{
814 TRACE_ENTRY("%p %zd %p %p", sid, len, session, new);
815 CHECK_PARAMS( sid && len && session );
816
817 /* Get the session object */
818 CHECK_FCT( fd_sess_fromsid_msg ( sid, len, session, new) );
819
820 /* Decrease the refcount */
821 CHECK_POSIX( pthread_mutex_lock(&(*session)->stlock) );
822 (*session)->msg_cnt--; /* was increased in fd_sess_new */
823 CHECK_POSIX( pthread_mutex_unlock(&(*session)->stlock) );
824
825 /* Done */
826 return 0;
827}
828
829int fd_sess_ref_msg ( struct session * session )
830{
831 TRACE_ENTRY("%p", session);
832 CHECK_PARAMS( VALIDATE_SI(session) );
833
834 /* Update the msg refcount */
835 CHECK_POSIX( pthread_mutex_lock(&session->stlock) );
836 session->msg_cnt++;
837 CHECK_POSIX( pthread_mutex_unlock(&session->stlock) );
838
839 return 0;
840}
841
842int fd_sess_reclaim_msg ( struct session ** session )
843{
844 int reclaim;
845 uint32_t hash;
846
847 TRACE_ENTRY("%p", session);
848 CHECK_PARAMS( session && VALIDATE_SI(*session) );
849
850 /* Lock the hash line to avoid possibility that session is freed while we are reclaiming */
851 hash = (*session)->hash;
852 CHECK_POSIX( pthread_mutex_lock( H_LOCK(hash)) );
853 pthread_cleanup_push( fd_cleanup_mutex, H_LOCK(hash) );
854
855 /* Update the msg refcount */
856 CHECK_POSIX( pthread_mutex_lock(&(*session)->stlock) );
857 reclaim = (*session)->msg_cnt;
858 (*session)->msg_cnt = reclaim - 1;
859 CHECK_POSIX( pthread_mutex_unlock(&(*session)->stlock) );
860
861 /* Ok, now unlock the hash line */
862 pthread_cleanup_pop( 0 );
863 CHECK_POSIX( pthread_mutex_unlock( H_LOCK(hash) ) );
864
865 /* and reclaim if no message references the session anymore */
866 if (reclaim == 1) {
867 CHECK_FCT(fd_sess_reclaim ( session ));
868 } else {
869 *session = NULL;
870 }
871 return 0;
872}
873
874
875
876/* Dump functions */
877DECLARE_FD_DUMP_PROTOTYPE(fd_sess_dump, struct session * session, int with_states)
878{
879 FD_DUMP_HANDLE_OFFSET();
880
881 CHECK_MALLOC_DO( fd_dump_extend( FD_DUMP_STD_PARAMS, "{session}(@%p): ", session), return NULL);
882
883 if (!VALIDATE_SI(session)) {
884 CHECK_MALLOC_DO( fd_dump_extend( FD_DUMP_STD_PARAMS, "INVALID/NULL"), return NULL);
885 } else {
886 char timebuf[30];
887 struct tm tm;
888
889 strftime(timebuf, sizeof(timebuf), "%D,%T", localtime_r( &session->timeout.tv_sec , &tm ));
890 CHECK_MALLOC_DO( fd_dump_extend( FD_DUMP_STD_PARAMS, "'%s'(%zd) h:%x m:%d d:%d to:%s.%06ld",
891 session->sid, session->sidlen, session->hash, session->msg_cnt, session->is_destroyed,
892 timebuf, session->timeout.tv_nsec/1000),
893 return NULL);
894
895 if (with_states) {
896 struct fd_list * li;
897 CHECK_POSIX_DO( pthread_mutex_lock(&session->stlock), /* ignore */ );
898 pthread_cleanup_push( fd_cleanup_mutex, &session->stlock );
899
900 for (li = session->states.next; li != &session->states; li = li->next) {
901 struct state * st = (struct state *)(li->o);
902 CHECK_MALLOC_DO( fd_dump_extend( FD_DUMP_STD_PARAMS, "\n {state i:%d}(@%p): ", st->hdl->id, st), return NULL);
903 if (st->hdl->state_dump) {
904 CHECK_MALLOC_DO( (*st->hdl->state_dump)( FD_DUMP_STD_PARAMS, st->state),
905 fd_dump_extend( FD_DUMP_STD_PARAMS, "[dumper error]"));
906 } else {
907 CHECK_MALLOC_DO( fd_dump_extend( FD_DUMP_STD_PARAMS, "<%p>", st->state), return NULL);
908 }
909 }
910
911 pthread_cleanup_pop(0);
912 CHECK_POSIX_DO( pthread_mutex_unlock(&session->stlock), /* ignore */ );
913 }
914 }
915
916 return *buf;
917}
918
919DECLARE_FD_DUMP_PROTOTYPE(fd_sess_dump_hdl, struct session_handler * handler)
920{
921 FD_DUMP_HANDLE_OFFSET();
922
923 CHECK_MALLOC_DO( fd_dump_extend( FD_DUMP_STD_PARAMS, "{sesshdl}(@%p): ", handler), return NULL);
924
925 if (!VALIDATE_SH(handler)) {
926 CHECK_MALLOC_DO( fd_dump_extend( FD_DUMP_STD_PARAMS, "INVALID/NULL"), return NULL);
927 } else {
928 CHECK_MALLOC_DO( fd_dump_extend( FD_DUMP_STD_PARAMS, "i:%d cl:%p d:%p o:%p", handler->id, handler->cleanup, handler->state_dump, handler->opaque), return NULL);
929 }
930 return *buf;
931}
932
933int fd_sess_getcount(uint32_t *cnt)
934{
935 CHECK_PARAMS(cnt);
936 CHECK_POSIX( pthread_mutex_lock( &exp_lock ) );
937 *cnt = sess_cnt;
938 CHECK_POSIX( pthread_mutex_unlock( &exp_lock ) );
939 return 0;
940}