-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdebase
More file actions
executable file
·87 lines (80 loc) · 2.4 KB
/
debase
File metadata and controls
executable file
·87 lines (80 loc) · 2.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#!/usr/bin/env perl
use warnings;
use strict;
use MIME::Base64 qw(encode_base64);
use Getopt::Std;
$Getopt::Std::STANDARD_HELP_VERSION = "true";
$main::VERSION = "0.2";
sub HELP_MESSAGE {
my $fh = shift || \*STDERR;
print $fh "Usage: debase input.file\n";
}
# I plan to extend this later so that it will
# transparently use File::MimeInfo or the mimetype command
# depending on what is available
sub getMimeType {
my $filename = shift;
return undef if ($filename eq "");
my $mimetype = `mimetype -b $filename`;
chomp $mimetype;
return undef if ($mimetype eq "");
return $mimetype;
}
sub runTests {
print "Running unit tests.\n";
getMimeType("/usr/bin/env") eq 'application/x-executable' || die ("/usr/bin/env should have type application/x-executable\n");
!defined getMimeType("") || die ("Empty filename should have failed\n");
!defined getMimeType("/home/unlikelyusername/nosuchfile") || die ("Non-existant file should have failed.\n");
print "All tests passed.\n";
}
sub getMimeChunker {
my $filename = shift;
my $chunkSize = shift || 30;
my $buf;
open(my $fh, "<", $filename) or return undef;
return sub {
if (read($fh, $buf, $chunkSize)) {
my $section = encode_base64($buf);
chomp $section;
return $section;
} else {
close($fh);
return undef;
}
}
}
# Chunker should be a code reference that returns strings when called
# until there are no more chunks, then returns a false value
sub printFile {
my $mimeType = shift;
my $chunker = shift;
print qq(<!DOCTYPE html>\n);
print qq(<html>\n);
print qq(<body>\n);
print qq(<p>Encoded Data Follows. To automatically decode, please enable JavaScript.<br />\n);
print qq(MIME type: $mimeType</p>\n);
print qq(<pre id="encoded_data">\n);
while (my $chunk = $chunker->()) {
print qq($chunk\n);
}
print qq(</pre>\n);
print qq(<script type="text/javascript">\n);
print qq(location.href="data:$mimeType;base64,"+\n);
print qq(document.getElementById("encoded_data").innerHTML;\n);
print qq(</script>\n);
print qq(</body>\n);
print qq(</html>\n);
}
my %opts;
getopts('t', \%opts);
if (exists $opts{t}) {
runTests();
exit(0);
}
if (!defined $ARGV[0]) {
HELP_MESSAGE();
exit(1);
}
my $mimeType = getMimeType($ARGV[0]) or die(qq(Could not determine type of file "$ARGV[0]"));
my $chunker = getMimeChunker($ARGV[0]) or die(qq(Could not open file "$ARGV[0]"));
printFile($mimeType, $chunker);