Blob


1 #!/usr/bin/env perl
2 #
3 # Copyright (c) 2022 Omar Polo <op@omarpolo.com>
4 #
5 # Permission to use, copy, modify, and distribute this software for any
6 # purpose with or without fee is hereby granted, provided that the above
7 # copyright notice and this permission notice appear in all copies.
8 #
9 # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10 # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11 # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12 # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13 # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14 # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15 # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 use strict;
18 use warnings;
19 use v5.32;
21 use open ":std", ":encoding(UTF-8)";
23 use Getopt::Long qw(:config bundling require_order);
24 use File::Basename;
25 use File::Find;
27 my $store = $ENV{'PLASS_STORE'} // $ENV{'HOME'}.'/.password-store';
29 my $got = $ENV{'PLASS_GOT'} // 'got';
31 my $gpg = $ENV{'PLASS_GPG'} // 'gpg';
32 my @gpg_flags = qw(--quiet --compress-algo=none --no-encrypt-to --use-agent);
34 my $default_chars = $ENV{'PLASS_CHARS'} // '!-~';
35 my $default_length = $ENV{'PLASS_LENGTH'};
36 if (!defined($default_length) || $default_length <= 0) {
37 $default_length = 32;
38 }
40 my %subcmd = (
41 cat => [\&cmd_cat, "entries..."],
42 find => [\&cmd_find, "[pattern]"],
43 gen => [\&cmd_gen, "[-nq] [-c chars] [-l length] entry"],
44 mv => [\&cmd_mv, "from to"],
45 rm => [\&cmd_rm, "entries..."],
46 tee => [\&cmd_tee, "[-q] entry"],
47 );
49 my $usage = "[-h] command [argument ...]";
50 my $cmd;
51 sub usage {
52 my $prog = basename $0;
53 if (defined($cmd) and defined($subcmd{$cmd})) {
54 say STDERR "Usage: $prog $cmd $usage";
55 } else {
56 say STDERR "Usage: $prog $usage";
57 say STDERR "unknown command $cmd" if defined($cmd);
58 say STDERR "commands: ", join(' ', sort(keys %subcmd));
59 }
60 exit 1;
61 }
63 GetOptions("h|?" => \&usage) or usage();
65 $cmd = shift // 'find';
66 usage() unless defined $subcmd{$cmd};
67 my $fn;
68 ($fn, $usage) = @{$subcmd{$cmd}};
69 chdir $store;
70 $fn->();
71 exit 0;
74 # utils
76 sub name2file {
77 my $f = shift;
78 $f .= ".gpg" unless $f =~ m,\.gpg$,;
79 return $f;
80 }
82 # tr -cd -- $chars < /dev/random | dd bs=$len count=1 status=none
83 sub gen {
84 my ($chars, $length) = @_;
85 my $pass = "";
87 open(my $fh, '<:raw', '/dev/random')
88 or die "can't open /dev/random: $!";
89 my $l = $length;
90 while ($l >= 0) {
91 read($fh, my $t, $length * 4)
92 or die "failed to read /dev/random: $!";
93 $t =~ s/[^$chars]//g;
94 $l -= length($t);
95 $pass .= $t;
96 }
97 close($fh);
99 return substr($pass, 0, $length);
102 sub mkdirs {
103 my $dir = shift;
104 my $parent = dirname $dir;
105 mkdirs($parent) unless -d $parent || $parent eq '/';
106 mkdir $dir or die "mkdir $dir: $!"
107 unless -d $dir;
110 sub writepass {
111 my ($file, $pass) = @_;
113 mkdirs(dirname $file);
115 # temporary redirect stdout to $file
116 open(my $stdout, '>&', STDOUT);
117 open(STDOUT, '>', $file);
119 my @args = ($gpg, @gpg_flags, '-e', '-r', recipient(),
120 '-o', '-');
121 open my $fh, '|-', @args;
122 print $fh "$pass";
123 close($fh);
124 my $ok = !$?;
126 open(STDOUT, '>&', $stdout); # restore stdout
128 die "failed to run $gpg\n" unless $ok;
131 sub recipient {
132 open my $fh, '<', "$store/.gpg-id"
133 or die "can't open recipient file";
134 my $r = <$fh>;
135 chomp $r;
136 close($fh);
137 return $r;
140 sub passfind {
141 my $pattern = shift;
142 my @entries;
144 find({
145 wanted => sub {
146 if (m,/.git$, || m,/.got$,) {
147 $File::Find::prune = 1;
148 return;
151 return if defined($pattern) && ! m/$pattern/;
152 return unless -f && m,.gpg$,;
154 s,^$store/*,,;
155 s,.gpg$,,;
156 push @entries, $_;
157 },
158 no_chdir => 1,
159 follow_fast => 1,
160 }, ($store));
161 return sort(@entries);
164 sub got {
165 # discard stdout
166 open my $fh, '-|', ($got, @_);
167 close($fh);
168 return !$?;
171 sub got_add {
172 return got 'add', '-I', shift;
175 sub got_rm {
176 got 'remove', '-f', shift
177 or exit(1);
180 sub got_ci {
181 my $pid = fork;
182 die "failed to fork: $!" unless defined $pid;
184 if ($pid != 0) {
185 wait;
186 die "failed to commit changes" if $?;
187 return;
190 open (STDOUT, ">&", \*STDERR)
191 or die "can't redirect stdout to stderr";
192 exec ($got, 'commit', '-m', shift)
193 or die "failed to exec $got: $!";
197 # cmds
199 sub cmd_cat {
200 GetOptions('h|?' => \&usage) or usage;
201 usage unless @ARGV;
203 while (@ARGV) {
204 my $file = name2file(shift @ARGV);
205 system ($gpg, @gpg_flags, '-d', $file);
206 die "failed to exec $gpg: $!" if $? == -1;
210 sub cmd_find {
211 GetOptions('h|?' => \&usage) or usage;
212 usage if @ARGV > 1;
214 map { say $_ } passfind(shift @ARGV);
217 sub cmd_gen {
218 my $chars = $default_chars;
219 my $length = $default_length;
220 my $nop;
221 my $q;
223 GetOptions(
224 'c=s' => sub { $chars = $_[1] },
225 'h|?' => \&usage,
226 'l=i' => sub { $length = $_[1] },
227 'n' => \$nop,
228 'q' => \$q,
229 ) or usage;
231 my $pass = gen($chars, $length) . "\n";
232 if ($nop) {
233 say $pass;
234 return;
237 usage if @ARGV != 1;
239 my $name = shift @ARGV;
240 my $file = name2file $name;
241 my $renamed = -f $file;
243 writepass($file, $pass);
244 got_add $file;
245 got_ci($renamed ? "update $name" : "+$name");
246 say $pass unless $q;
249 # TODO: handle moving directories?
250 sub cmd_mv {
251 GetOptions('h|?' => \&usage) or usage;
252 usage if @ARGV != 2;
254 my $a = shift @ARGV;
255 my $b = shift @ARGV;
257 my $pa = name2file $a;
258 my $pb = name2file $b;
260 die "source password doesn't exist" unless -f $pa;
261 die "target password exists" if -f $pb;
263 mkdirs(dirname $pb);
264 rename $pa, $pb or die "can't rename $a to $b: $!";
266 got_rm $pa;
267 got_add $pb or die "can't add $pb\n";
268 got_ci "mv $a $b";
271 sub cmd_rm {
272 GetOptions('h|?' => \&usage) or usage;
273 usage unless @ARGV;
275 while (@ARGV) {
276 my $name = shift @ARGV;
277 my $file = name2file $name;
279 got_rm $file;
280 got_ci "-$name";
284 sub cmd_tee {
285 my $q;
286 GetOptions(
287 'h|?' => \&usage,
288 'q' => \$q,
289 ) or usage;
290 usage if @ARGV != 1;
292 my $name = shift @ARGV;
293 my $file = name2file $name;
295 my $msg = -f $file ? "update $name" : "+$name";
297 my $pass = "";
298 $pass .= $_ while <STDIN>;
299 die "No content!\n" if $pass eq "";
301 writepass($file, $pass);
303 got_add $file;
304 got_ci $msg;
305 print $pass unless $q;