Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Problems getting session management to work: is_expired seems to lie to me

by ted.byers (Scribe)
on May 06, 2013 at 18:43 UTC ( #1032369=perlquestion: print w/ replies, xml ) Need Help??
ted.byers has asked for the wisdom of the Perl Monks concerning the following question:

Here is some test code that I constructed to both test session management functions and error handling in a package used by a CGI script. First the package:

package pkgerr; use strict; use Exporter; use Exception::Class::TryCatch; use vars qw ($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS); $VERSION = 1.00; @ISA = qw (Exporter); @EXPORT = (); @EXPORT_OK = qw(good_func bad_func uid ut); %EXPORT_TAGS = (All => [qw(&good_func &bad_func &uid &ut)]); my $class_data = { idusers => "", user_type_id => "", }; sub new { my $class = shift; my $self = {}; my $uid = shift; my $ut = shift; $self->{'idusers'} = $uid; $self->{'user_type_id'} = $ut; bless($self, $class); return $self; } sub good_func { my $self = shift; print "I'm a good function\n"; } sub bad_func { my $self = shift; die "I'm a bad function\n"; } sub uid { my $self = shift; return $self->{'idusers'}; } sub ut { my $self = shift; return $self->{'user_type_id'}; } sub check { my $self = shift; my $dummy; try eval { $dummy = uid($self); bad_func($self); }; if (catch my $err) { print "We set \$dummy to $dummy, and then invoked a bad function\n +"; print $err->error,"\n"; } } 1;

And now the trivial CGI script:

#!perl use strict; use CGI; use CGI::Session; use Exception::Class::TryCatch; $| = 1; use lib './REJBlib'; use pkgerr; # NB: Iff all works right, he debug screen ought never be seen! use CGI::Carp::DebugScreen ( engine => 'TT', debug => 1, lines => 5, modules => 1, environment => 1, raw_error => 1, overload => 1, ); my $query = new CGI; my $url = $query->url(-path_info=>1); my $cnt = $query->param('cnt'); my $session; if (defined $cnt) { $cnt += 1; $session = CGI::Session->load('driver:mysql',$query,{ DataSource => + 'dbi:mysql:profitorius', User => 'rejbyers', Password => 'Didr39Qcab' }); my $extest = $session->is_expired; my $emptest = $session->is_empty; if ($extest) { print $query->header; print $query->start_html(-title=>'Secrets of SESSIONS',); print $query->end_html; } else { print $session->header; my $pref = $session->dataref; my %ph = %$pref; print $query->start_html(-title=>'Secrets of SESSIONS',); print "<p>The session has not expired.</p>"; if ($emptest) { print "<p>The session is empty.</p>"; } else { print "<p>The session is NOT empty.</p>"; print "<p>The following are the known session parameters.</p><ta +ble><thead><tr><th>Parameter</th><th>Value</th></tr></thead><tbaody>" +; foreach my $k (keys %ph) { print "<tr><td>$k</td><td>$ph{$k}</td></tr>"; } print "</table>"; print "<a href=\"$url?cnt=$cnt\">Click me</a>"; } print "<pre>"; print "</pre>"; print $query->end_html; } } else { $session = CGI::Session->new('driver:mysql',$query,{ DataSource => +'dbi:mysql:profitorius', User => 'rejbyers', Password => 'Didr39Qcab' }); $session->expire("5m"); $session->param('qwerty',12345); $session->param('zxcvb',98765); print $session->header; print $query->start_html(-title=>'Secrets of SESSIONS',); print "<a href=\"$url?cnt=1\">Click me</a>"; print "<pre>"; my $tobj = pkgerr->new(3,5); print "Checking if package was properly created:\n\tuid = ",$tobj->u +id,"\n\tut = ",$tobj->ut,"\n\n"; print "\nCalling check function.\n"; $tobj->check; print "Calling a good function\n\t"; $tobj->good_func; print "\nCalling a bad function within a try/catch block\n"; try eval { $tobj->bad_func; }; if ( catch my $err) { print "We caught a fatal error from the calling code\n\t",$err->er +ror,"\n\n"; } print "</pre>"; print $query->end_html; }

Now, just about everything in these scripts works as anticipated, except for the conditional block that tests whether or not an existing session is empty. NB: Given how the session is first created, it should never happen that a session that has not expired is empty (I was considering adding a random variate, as a CGI parameter, that empties the session of parameters say, 20% of the time, and of course, any empty session that has not expired would, on the next access, be populated, but that part of the experiment got pre-empted by the current behaviour).

What I see happening is the session data being displayed as expected when the session has not expired, but when the session has expired, I see the following output (copied from MS IE and pasted below):

The session has not expired. The session is empty.

Why is this? Did I make a mistake on how I used is_expired (it IS, in fact, used only after a call to load)?

Obviously load did not return NULL after the session expired, as otherwise the call to is_expired should be expected to fail. But the value returned by is_expired is clearly wrong. This is with both Activestate Perl 5.12 and Activestate Perl 5.16, both running on The latest Windows build of Apache's httpd server (2.4.3?). As a work-around, I can check for an expired session by checking whether or not my session is empty (as I ALWAYS create several session parameters), but this seems like a kludge, and the problem that session's is_expired function lies remains unfixed. Any ideas?

Thanks.

Ted

Comment on Problems getting session management to work: is_expired seems to lie to me
Select or Download Code
Re: Problems getting session management to work: is_expired seems to lie to me
by Anonymous Monk on May 06, 2013 at 19:47 UTC

      Yes, yes, you point to trivial programs that run from the commandline, but those specific scripts will not work as CGI programs as they do not write the usual suite of headers, or valid HTML, to standard out. The fact is that in a number of cases, I have found the behaviour of certain code snippets differing based on whether executed from a commandline script or from within a CGI script. This is why I included all that was necessary to have apache use perl to create the output page, and also why code of the sort you recommend can not answer the question. The code I posted is trivially simple (about 60 lines in the package and about 30 in the cgi script, hardly qualifies as much unrelated code - and in fact most of the code in the pl script is what is necessary to create a valid CGI script - and yes, you need not look at the code in the package unless you're interested in error handling in that context - but it makes the output of the CGI script more interesting), but it is sufficient to provide a trivially simple context in which the value returned by is_expired is wrong. The code in the posts you provided illustrates how is_expired is supposed to work, and that is something I already understood. What I did not understand, and the specific question you ignored, is why it did not work that way when applied in a more realistic context.

      To see the code I posted in action, all that need be done is put it in the cgi directory for your web browser, request the page using your favourite browser, and then request once, in less than 5 minutes, to see what ought to happen when the session ought not have timed out, and then wait a little over 5 minutes (something that the impatient can adjust without difficulty) to see what happens when the session ought to have expired.

      And yes, I am familiar with the notion of small, self contained, programs that illustrate the problem, and the code I posted IS small, self contained, and shows the problem where the code you recommend, while small and self contained, is not adequate to illustrate the problem because they would have to be singificantly altered in order to be executed as a CGI script. The relevant criterion that makes the code I posted applicable is that it shows the problem. Now, as I do not know why the problem exists, it could be anything from some peculiarity in the Activestate distributions, or running it on Windows, or anything else that I can't yet imagine, but information that will tell me what is the cause is what is needed here; nothing else.

      Do you have any information that might actually address the real problem?

      thanks

      Ted

Re: Problems getting session management to work: is_expired seems to lie to me
by Corion (Pope) on May 06, 2013 at 21:13 UTC

    I don't see a call to ->flush() in your code. I don't use CGI::Session, but the documentation recommends doing so.

      Thanks, good catch. Alas, adding that to the end of my script changed nothing.

      Out of curiousity, is you do not use CGI::Session, what do you use for session management?

      Thanks

      Ted

        Currently I use Dancer with Dancer::Session.

        Also, your script is still very long and includes lots of unrelated stuff, like that try/catch stuff and HTML generation. I recommend ripping all that out to make the structure more obvious.

Re: Problems getting session management to work: is_expired seems to lie to me
by sundialsvc4 (Abbot) on May 06, 2013 at 22:04 UTC

    Looking at the source-code of CGI::Session using the CPAN link, we can confirm that yes, the value of is_expired() is useful only after a load() call, since it is setting several bit-flags using the (alas, “thawed” and therefore not so easily readable) database data, viz:

    # checking for expiration ticker if ( $self->{_DATA}->{_SESSION_ETIME} ) { if ( ($self->{_DATA}->{_SESSION_ATIME} + $self->{_DATA}->{_SES +SION_ETIME}) <= time() ) { $self->_set_status( STATUS_EXPIRED | # <-- so client ca +n detect expired sessions STATUS_DELETED ); # <-- session shou +ld be removed from database $self->flush(); # <-- flush() will + do the actual removal! return $self; } }

    flush() is visibly a very-important call, responsible for creating, updating, and removing the underlying database record.

    Now, we notice that this code is acting upon information that has been saved previously in the database, in the “frozen” blob of data ... if it is there!   But, as Corion probably already intuited, there is a very good chance that it isn’t.

    The POD documentation says (in the second sentence of “a warning about auto-flushing,” that:   Explicit flushing after key session updates is recommended.   And this is precisely what I would now suggest that you do.   In the } else { part, after you have created the session, set its expiration-time and two parameters, flush() now.   Don’t just add a line at the end of the module and hope for the best.   As soon as you have made any changes that you want to be permanently fixed in the database, flush.   Do this as-needed in both the “session found“ and the “new session” cases, erring as-needed on the side of caution, and I suspect that your troubles will vanish.   (And if I’m right, Corion beat me to it.)

      Thanks, this is actually helpful, and leads to a couple other questions.

      The code where the session has been created has now been changed to:

      $session = CGI::Session->new('driver:mysql',$query,{ DataSource => +'dbi:mysql:profitorius', User => 'rejbyers', Password => 'Didr39Qcab' }); $session->expire("5m"); $session->param('qwerty',12345); $session->param('zxcvb',98765); $session->flush;

      That is the only place in my code where the session data is actually changed, except when load updates the time when the session will next expire, if not accessed before that time. Alas, this change did not change the behaviour I see, implying your first guess, and Corion's, is incorrect. I do, and have always, seen the session parameters I'd set when I accessed the page before the session timed out, so I know that that data had been stored, and thus I am not especially surprised that adding the fluch earlier in the call sequence didn't change anything.

      But, my first question to you, since you have gone through that code, is, "Is the code you quoted responsible for the fact that I see the session empty in the call to is_empty, as I had suspected all along (an expection that should also be inferable from the code you quoted)? Second, and more importantly, is there any chance that the lines that set the status to 'STATUS_DELETED', followed by a flush, could have unintentionally removed the 'STATUS_EXPIRED ' status (I am thinking maybe in the call to flush, but I haven't dug into the bowels of that code).

      Thanks

      Ted

        I did some digging of my own. Here is what I found.

        Function load begins:

        sub load { my $class = shift; return $class->set_error( "called as instance method") if ref $ +class; return $class->set_error( "Too many arguments provided to load()") + if @_ > 5; my $self = bless { _DATA => { _SESSION_ID => undef, _SESSION_CTIME => undef, _SESSION_ATIME => undef, _SESSION_REMOTE_ADDR => $ENV{REMOTE_ADDR} || "", # # Following two attributes may not exist in every single s +ession, and declaring # them now will force these to get serialized into databas +e, wasting space. But they # are here to remind the coder of their purpose # # _SESSION_ETIME => undef, # _SESSION_EXPIRE_LIST => {} }, # session data _DSN => {}, # parsed DSN params _OBJECTS => {}, # keeps necessary objects _DRIVER_ARGS=> {}, # arguments to be passed to driver _CLAIMED_ID => undef, # id **claimed** by client _STATUS => STATUS_UNSET,# status of the session object _QUERY => undef # query object }, $class;

        Here we see that _STATUS is part of _DATA. Then, a little further on in load, where it checks for whether or not the session has timed out, we have:

        # checking for expiration ticker if ( $self->{_DATA}->{_SESSION_ETIME} ) { if ( ($self->{_DATA}->{_SESSION_ATIME} + $self->{_DATA}->{_SES +SION_ETIME}) <= time() ) { $self->_set_status( STATUS_EXPIRED | # <-- so client ca +n detect expired sessions STATUS_DELETED ); # <-- session shou +ld be removed from database $self->flush(); # <-- flush() will + do the actual removal! return $self; } }

        Which, I believe you quoted. But then in flush, we have:

        sub flush { my $self = shift; # Would it be better to die or err if something very basic is wron +g here? # I'm trying to address the DESTROY related warning # from: http://rt.cpan.org/Ticket/Display.html?id=17541 # return unless defined $self; return unless $self->id; # <-- empty session # neither new, nor deleted nor modified return if !defined($self->{_STATUS}) or $self->{_STATUS} == STATUS +_UNSET; if ( $self->_test_status(STATUS_NEW) && $self->_test_status(STATUS +_DELETED) ) { $self->{_DATA} = {}; return $self->_unset_status(STATUS_NEW | STATUS_DELETED); } my $driver = $self->_driver(); my $serializer = $self->_serializer(); if ( $self->_test_status(STATUS_DELETED) ) { defined($driver->remove($self->id)) or return $self->set_error( "flush(): couldn't remove session + data: " . $driver->errstr ); $self->{_DATA} = {}; # <-- removing all + the data, making sure # it won't be acce +ssible after flush() return $self->_unset_status(STATUS_DELETED); } if ( $self->_test_status(STATUS_NEW | STATUS_MODIFIED) ) { my $datastr = $serializer->freeze( $self->dataref ); unless ( defined $datastr ) { return $self->set_error( "flush(): couldn't freeze data: " + . $serializer->errstr ); } defined( $driver->store($self->id, $datastr) ) or return $self->set_error( "flush(): couldn't store datastr: + " . $driver->errstr); $self->_unset_status(STATUS_NEW | STATUS_MODIFIED); } return 1; }

        In the block that begins with "if ( $self->_test_status(STATUS_DELETED) ) {", we have "$self->{_DATA} = {};". Doesn't this have the effect of blowing away the "STATUS_EXPIRED" status, resulting in a false value being returned by is_expired because it is checking against a member in the hash that does not exist after the flush when the status has been given a status of DELETED?

        Thanks

        Ted

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1032369]
Approved by marto
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (11)
As of 2014-10-02 13:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    What is your favourite meta-syntactic variable name?














    Results (60 votes), past polls