Skip to content

Commit

Permalink
Merge pull request #202 from mknos/base64-dir
Browse files Browse the repository at this point in the history
base64: fail early for directory argument
  • Loading branch information
briandfoy authored Jul 13, 2023
2 parents 9ef966a + 27cf8e2 commit 7f186d9
Showing 1 changed file with 28 additions and 10 deletions.
38 changes: 28 additions & 10 deletions bin/base64
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
#!/usr/bin/perl

=encoding utf8
=begin metadata
Name: base64
Description: encode and decode base64 data
Author: Michael Mikonos
License: perl
License: artistic2
=end metadata
Expand All @@ -14,32 +16,45 @@ License: perl
use strict;
use warnings;

use constant EX_SUCCESS => 0;
use constant EX_FAILURE => 1;

use File::Basename qw(basename);
use Getopt::Std qw(getopts);
use MIME::Base64 qw(decode_base64 encode_base64);

my $VERSION = '1.0';

my $Program = basename($0);

my (%opt, $bufsz, $in, $out);
getopts('do:v', \%opt) or usage();
if (scalar(@ARGV) > 1) {
warn "$0 too many arguments\n";
warn "$Program: too many arguments\n";
usage();
}
if ($opt{'v'}) {
die "$0 version $VERSION\n";
print "$Program version $VERSION\n";
exit EX_SUCCESS;
}
$bufsz = $opt{'d'} ? 76 : 57;
$bufsz *= 20;
if (defined $opt{'o'}) {
unless (open $out, '>', $opt{'o'}) {
die "$0: $opt{o}: $!\n";
warn "$Program: cannot open '$opt{o}': $!\n";
exit EX_FAILURE;
}
} else {
$out = *STDOUT;
}
if (defined $ARGV[0] && $ARGV[0] ne '-') {
if (-d $ARGV[0]) {
warn "$Program: '$ARGV[0]' is a directory\n";
exit EX_FAILURE;
}
unless (open $in, '<', $ARGV[0]) {
die "$0: $ARGV[0]: $!\n";
warn "$Program: cannot open '$ARGV[0]': $!\n";
exit EX_FAILURE;
}
} else {
$in = *STDIN;
Expand All @@ -48,12 +63,16 @@ if (defined $ARGV[0] && $ARGV[0] ne '-') {
$opt{'d'} ? decode() : encode();
close $in;
close $out;
exit EX_SUCCESS;

sub decode {
my $buf = '';
while (readline $in) {
s/\s//g;
die("$0: bad input\n") if m/[^A-Za-z0-9\+\/\=]/;
if (m/[^A-Za-z0-9\+\/\=]/) {
warn "$Program: bad input\n";
exit EX_FAILURE;
}
$buf .= $_;
if (length($buf) >= $bufsz) {
my $chunk = substr($buf, 0, $bufsz);
Expand All @@ -74,7 +93,8 @@ sub encode {
}

sub usage {
die "usage: $0 [-dv] [-o FILE] [FILE]\n";
warn "usage: $Program [-dv] [-o FILE] [FILE]\n";
exit EX_FAILURE;
}

__END__
Expand Down Expand Up @@ -140,6 +160,4 @@ Written by Michael Mikonos.
Copyright (c) 2023 Michael Mikonos.
This program is free software; you can redistribute it and/or modify it under
the same terms as Perl itself.
This code is licensed under the Artistic License 2.

0 comments on commit 7f186d9

Please sign in to comment.