Navigation


source: freeDiameter/libfdproto/sessions.c @ 786:d3fc443dae36

Last change on this file since 786:d3fc443dae36 was 786:d3fc443dae36, checked in by Sebastien Decugis <sdecugis@nict.go.jp>, 14 months ago

Added information in session dump

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