File Coverage

blib/lib/HTTP/Session2/Random.pm
Criterion Covered Total %
statement 29 30 96.6
branch 3 4 75.0
condition n/a
subroutine 8 8 100.0
pod 0 1 0.0
total 40 43 93.0


line stmt bran cond sub pod time code
1             package HTTP::Session2::Random;
2 11     11   29516 use strict;
  11         26  
  11         666  
3 11     11   71 use warnings;
  11         23  
  11         338  
4 11     11   6159 use utf8;
  11         36  
  11         89  
5 11     11   1427 use 5.008_001;
  11         44  
  11         556  
6              
7             # DO NOT USE THIS DIRECTLY.
8              
9 11     11   1921 use MIME::Base64 ();
  11         2037  
  11         248  
10 11     11   7872 use Digest::SHA ();
  11         33742  
  11         282  
11 11     11   13494 use Time::HiRes;
  11         30755  
  11         65  
12              
13             our $URANDOM_FH;
14              
15             # $URANDOM_FH is undef if there is no /dev/urandom
16             open $URANDOM_FH, '<:raw', '/dev/urandom'
17             or do {
18             undef $URANDOM_FH;
19             warn "Cannot open /dev/urandom: $!.";
20             };
21              
22             sub generate_session_id {
23 17 100   17 0 14731 if ($URANDOM_FH) {
24 15         27 my $length = 24;
25             # Generate session id from /dev/urandom.
26 15         6301 my $read = read($URANDOM_FH, my $buf, $length);
27 15 50       58 if ($read != $length) {
28 0         0 die "Cannot read bytes from /dev/urandom: $!";
29             }
30 15         118 my $result = MIME::Base64::encode_base64($buf, '');
31 15         46 $result =~ tr|+/=|\-_|d; # make it url safe
32 15         84 return substr($result, 0, 31);
33             } else {
34             # It's weaker than above. But it's portable.
35 2         152 substr(Digest::SHA::sha1_hex(rand() . $$ . {} . Time::HiRes::time()),int(rand(4)),31);
36             }
37             }
38              
39             1;