File Coverage

blib/lib/HTTP/Session/ID/Urandom.pm
Criterion Covered Total %
statement 24 25 96.0
branch 1 2 50.0
condition n/a
subroutine 7 7 100.0
pod 0 1 0.0
total 32 35 91.4


line stmt bran cond sub pod time code
1             package HTTP::Session::ID::Urandom;
2 1     1   367151 use strict;
  1         2  
  1         50  
3 1     1   6 use warnings;
  1         2  
  1         95  
4 1     1   556 use utf8;
  1         338  
  1         7  
5 1     1   51 use 5.008_001;
  1         4  
6 1     1   689 use MIME::Base64;
  1         1064  
  1         93  
7 1     1   584 use POSIX;
  1         8939  
  1         6  
8              
9             our $URANDOM_FH;
10              
11             # $URANDOM_FH is undef if there is no /dev/urandom
12             open $URANDOM_FH, '<:raw', '/dev/urandom'
13             or die "Cannot open /dev/urandom: $!.";
14              
15             sub generate_id {
16 3     3 0 20 my ($class, $sid_length) = @_;
17 3         35 my $src_len = POSIX::ceil($sid_length/3.0*4.0);
18             # Generate session id from /dev/urandom.
19 3         81 my $read = read($URANDOM_FH, my $buf, $src_len);
20 3 50       9 if ($read != $src_len) {
21 0         0 die "Cannot read bytes from /dev/urandom: $!";
22             }
23 3         11 my $result = MIME::Base64::encode_base64($buf, '');
24 3         7 $result =~ tr|+/=|\-_|d; # make it url safe
25 3         20 return substr($result, 0, $sid_length);
26             }
27              
28             1;
29