File Coverage

blib/lib/HTTP/Session2/Random.pm
Criterion Covered Total %
statement 28 29 96.5
branch 3 4 75.0
condition n/a
subroutine 8 8 100.0
pod 0 1 0.0
total 39 42 92.8


line stmt bran cond sub pod time code
1             package HTTP::Session2::Random;
2 12     12   57330 use strict;
  12         28  
  12         312  
3 12     12   61 use warnings;
  12         19  
  12         280  
4 12     12   486 use utf8;
  12         28  
  12         58  
5 12     12   457 use 5.008_001;
  12         31  
6              
7             # DO NOT USE THIS DIRECTLY.
8              
9 12     12   1045 use MIME::Base64 ();
  12         1535  
  12         205  
10 12     12   2056 use Digest::SHA ();
  12         11457  
  12         229  
11 12     12   5205 use Time::HiRes;
  12         12072  
  12         42  
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 28 100   28 0 3051 if ($URANDOM_FH) {
24 26         50 my $length = 24;
25             # Generate session id from /dev/urandom.
26 26         5251 my $read = read($URANDOM_FH, my $buf, $length);
27 26 50       83 if ($read != $length) {
28 0         0 die "Cannot read bytes from /dev/urandom: $!";
29             }
30 26         133 my $result = MIME::Base64::encode_base64($buf, '');
31 26         56 $result =~ tr|+/=|\-_|d; # make it url safe
32 26         120 return substr($result, 0, 31);
33             } else {
34             # It's weaker than above. But it's portable.
35 2         69 substr(Digest::SHA::sha1_hex(rand() . $$ . {} . Time::HiRes::time()),int(rand(4)),31);
36             }
37             }
38              
39             1;