SafeExec.pm

filter: Statementstmt 78.8% 153 / 194 Branchbran 54.3% 87 / 160 Conditioncond 37.5% 9 / 24 MC/DCmcdc 6.6% 1 / 15 Subroutinesub 84.2% 16 / 19 Podpod 30.0% 3 / 10 totaltotal 63.7% 269 / 422 CC 90 SCAR 50.1
CC
90
Cov
66%
new
266.9
test
14.6
wait
13.2
CRAP 149.7
« SafeExec/Queue.pm ↑ Summary
1 package Proc::SafeExec;
2  
3 6 ▶use 5.006;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 6 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 6 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 6 our $VERSION = "1.5";
8  
9 =pod
10  
11 =head1 NAME
12  
13 Proc::SafeExec - Convenient utility for executing external commands in various ways.
14  
15 =head1 SYNOPSIS
16  
17 use Proc::SafeExec;
18 $SIG{"CHLD"} = "DEFAULT"; # Not IGNORE, so we can collect exit status.
19 my $command = Proc::SafeExec->new({
20 # Choose just one of these.
21 "exec" => ["ls", "-l", "myfile"], # exec() after forking.
22 "fork" => 1, # Return undef in the child after forking.
23  
24 # Specify whether to capture each. Specify a file handle ref to dup an existing
25 # one. Specify "new" to create a new file handle, "default" or undef to keep
26 # the parent's descriptor, or "close" to close it.
27 "stdin" => \*INPUT_PIPE,
28 "stdout" => \*OUTPUT_PIPE,
29 "stderr" => "new",
30  
31 # Miscellaneous options.
32 "child_callback" => \&fref, # Specify a function to call in the child after fork(), for example, to drop privileges.
33 "debug" => 1, # Emit some information via warnings, such as the command to execute.
34 "no_autowait" => 1, # Don't automatically call $command->wait() when $command is destroyed.
35 "real_arg0" => "/bin/ls", # Specify the actual file to execute.
36 "untaint_args" => 1, # Untaint the arguments before exec'ing.
37 });
38 printf "Child's PID is %s\n", $command->child_pid() if $command->child_pid();
39  
40 The wait method waits for the child to exit or checks whether it already
41 exited:
42  
43 $command->wait({
44 # Optional hash of options.
45 "no_close" => 1, # Don't close "new" file handles.
46 "nonblock" => 1, # Don't wait if the child hasn't exited (implies no_close).
47 });
48  
49 To communicate with the child:
50  
51 # Perl doesn't understand <$command->stdout()>.
52 my $command_stdout = $command->stdout();
53 my $command_stderr = $command->stderr();
54  
55 $line = <$command_stdout>;
56 $line = <$command_stderr>;
57 print {$command->stdin()} "mumble\n";
58  
59 To check whether the child exited yet:
60  
61 print "Exit status: ", $command->exit_status(), "\n" if $command->wait({"nonblock" => 1});
62  
63 To wait until it exits:
64  
65 $command->wait();
66 print "Exit status: ", $command->exit_status(), "\n";
67  
68 A convenient quick tool for an alternative to $output = `@exec`:
69  
70 ($output, $?) = Proc::SafeExec::backtick(@exec);
71  
72 =head1 DESCRIPTION
73  
74 Proc::SafeExec provides an easy, safe way to execute external programs. It
75 replaces all of Perl's questionable ways of accomodating this, including
76 system(), open() with a pipe, exec(), back-ticks, etc. This module will never
77 automatically invoke /bin/sh. This module is easy enough to use that /bin/sh
78 should be unnecessary, even for complex pipelines.
79  
80 For all errors, this module dies setting $@.
81  
82 Errors from exec() in the child are reported gracefully to the parent. This
83 means that if anything fails in the child, the error is reported through $@
84 with die just like any other error. This also reports $@ if child_callback
85 dies when it is called between fork() and exec(). This is accomplished by
86 passing $@ through an extra pipe that's closed when exec succeeds. Note: A
87 side-effect of this is $@ is stringified if it isn't a string.
88  
89 =head1 CAVEATS
90  
91 When using an existing file handle by passing a reference for stdin, stdout, or
92 stderr, new() closes the previously open file descriptor. This is to make sure,
93 for example, that when setting up a pipeline the child process notices EOF on
94 its stdin. If you need this file handle to stay open, dup it first. For
95 example:
96  
97 open my $tmp_fh, "<&", $original_fh or die "dup: $!";
98 my $ls = new Proc::SafeExec({"exec" => ["ls"], "stdout" => $tmp_fh});
99 # $tmp_fh is now closed.
100  
101 By default, $command->wait() closes any new pipes opened in the constructor.
102 This is to prevent a deadlock where the child is waiting to read or write and
103 the parent is waiting for the child to exit. Pass no_close to $command->wait()
104 to prevent this (see above). Also, by default the destructor calls
105 $command->wait() if child hasn't finished. This is to prevent zombie processes
106 from inadvertently accumulating. To prevent this, pass no_autowait to the
107 constructor. The easiest way to wait for the child is to call the wait method,
108 but if you need more control, set no_autowait, then call child_pid to get the
109 PID and do the work yourself.
110  
111 This will emit a warning if the child exits with a non-zero status, and the
112 caller didn't inspect the exit status, and the caller didn't specify
113 no_autowait (which may imply the exit status might not be meaningful). It's bad
114 practice not to inspect the exit status, and it's easy enough to quiet this
115 warning if you really don't want it by calling $command->exit_status() and
116 discarding the result.
117  
118 =head1 EXAMPLES
119  
120 It's easy to execute several programs to form a pipeline. For the first
121 program, specify "new" for stdout. Then execute the second one, and specify
122 stdout from the first one for the stdin of the second one. For example, here's
123 how to write the equivalent of system("ls | sort > output.txt"):
124  
125 open my $output_fh, ">", "output.txt" or die "output.txt: $!\n";
126 my $ls = new Proc::SafeExec({"exec" => ["ls"], "stdout" => "new"});
127 my $sort = new Proc::SafeExec({"exec" => ["sort"], "stdin" => $ls->stdout(), "stdout" => $output_fh});
128 $ls->wait();
129 $sort->wait();
130 printf "ls exited with status %i\n", ($ls->exit_status() >> 8);
131 printf "sort exited with status %i\n", ($sort->exit_status() >> 8);
132  
133 =head1 INSTALLATION
134  
135 This module has no dependencies besides Perl itself. Follow your favorite
136 standard installation procedure.
137  
138 To test the module, run the following command line:
139  
140 $ perl -e 'use Proc::SafeExec; print Proc::SafeExec::test();'
141  
142 =head1 VERSION AND HISTORY
143  
144 =over
145  
146 =item * Version 1.5, released 2013-06-14. Fixed bug: Open /dev/null for STDIN
147 STDOUT STDERR instead of leaving closed when "close" is specified. Also,
148 recommend in doc to set $SIG{"CHLD"} = "DEFAULT".
149  
150 =item * Version 1.4, released 2008-05-30. Added Proc::SafeExec::backtick()
151 function for convenience. Fixed a couple minor bugs in error handling (not
152 security related). Invalidate $? after reading it so callers must fetch the
153 exit status through $self->exit_status().
154  
155 =item * Version 1.3, released 2008-03-31. Added Proc::SafeExec::Queue. Emit a
156 warning when non-zero exit status, and the caller didn't inspect the exit
157 status, and the caller didn't specify no_autowait (which may imply the exit
158 status might not be meaningful).
159  
160 =item * Version 1.2, released 2008-01-22. Tweaked test() to handle temp files
161 correctly, addressing https://rt.cpan.org/Ticket/Display.html?id=32458 .
162  
163 =item * Version 1.1, released 2008-01-09. Fixed obvious bug.
164  
165 =item * Version 1.0, released 2007-05-23.
166  
167 =back
168  
169 =head1 SEE ALSO
170  
171 The source repository is at git://git.devpit.org/Proc-SafeExec/
172  
173 See also Proc::SafeExec::Queue.
174  
175 =head1 MAINTAINER
176  
177 Leif Pedersen, E<lt>bilbo@hobbiton.orgE<gt>
178  
179 =head1 COPYRIGHT AND LICENSE
180  
181 This may be distributed under the terms below (BSD'ish) or under the GPL.
182
183 Copyright (c) 2007
184 All Rights Reserved
185 Meridian Environmental Technology, Inc.
186 4324 University Avenue, Grand Forks, ND 58203
187 http://meridian-enviro.com
188
189 Redistribution and use in source and binary forms, with or without
190 modification, are permitted provided that the following conditions are
191 met:
192
193 1. Redistributions of source code must retain the above copyright
194 notice, this list of conditions and the following disclaimer.
195
196 2. Redistributions in binary form must reproduce the above copyright
197 notice, this list of conditions and the following disclaimer in the
198 documentation and/or other materials provided with the
199 distribution.
200
201 THIS SOFTWARE IS PROVIDED BY AUTHORS AND CONTRIBUTORS "AS IS" AND ANY
202 EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
203 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
204 PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL AUTHORS OR CONTRIBUTORS BE
205 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
206 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
207 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
208 BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
209 WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
210 OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
211 ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
212  
213 =cut
214  
215 6 ▶use Fcntl "F_GETFL", "F_SETFL", "FD_CLOEXEC";
Subroutine BEGIN: called CC=1 SCAR=0.0
216 6 ▶use File::Spec;
Subroutine BEGIN: called CC=1 SCAR=0.0
217 6 ▶use File::Temp;
Subroutine BEGIN: called CC=1 SCAR=0.0
218 6 ▶use POSIX "WNOHANG";
Subroutine BEGIN: called CC=1 SCAR=0.0
219  
220 # Remember, any place new() dies or does not return $self triggers DESTROY
221 # immediately.
222 20 ▶sub new {
Subroutine new: called CC=59 SCAR=55.9
Pod undocumented
223 20 my ($package, $options) = @_;
224 20 ▶ my $self = bless {}, (ref($package) or $package);
Condition33%1/3
ref $package || $package
l!l&&r!l&&!r
0200
MC/DC0%0/2
ref $package || $package
ref $package $package
Truth table33%1/3
A || B
A= ref $packageB= $package
ABresult
1X1
011
000
225  
226 # Be sure we don't gain extra references to any file handles or clobber
227 # anything the caller needs. For example, if the caller holds a reference to
228 # $options and we add a file handle reference to it, the file handle will not
229 # be destroyed when we expect.
230 20 $options = {%$options};
231  
232 # Usage checks; set defaults.
233 20 $self->{"debug"} = $options->{"debug"};
234 20 ▶ $options->{"stdin"} = "default" unless defined $options->{"stdin"};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $options->{"stdin"} 11 9 20
235 20 ▶ $options->{"stdout"} = "default" unless defined $options->{"stdout"};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $options->{"stdout"} 2 18 20
236 20 ▶ $options->{"stderr"} = "default" unless defined $options->{"stderr"};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $options->{"stderr"} 20 0 20
237 20 ▶ die "No action specified for child process\n" unless $options->{"exec"} or $options->{"fork"};
Branch: 1 branch
BranchTrueFalseTotal
unless $options->{"exec"} or $options->{"fork"} 0 20 20
Condition33%1/3
$options->{"exec"} or $options->{"fork"}
l!l&&r!l&&!r
2000
MC/DC0%0/2
$options->{"exec"} or $options->{"fork"}
$options->{"exec"} $options->{"fork"}
Truth table33%1/3
A or B
A= $options->{"exec"}B= $options->{"fork"}
ABresult
1X1
011
000
238 20 ▶ die "More than one action specified for child process\n" if $options->{"exec"} and $options->{"fork"};
Branch: 1 branch
BranchTrueFalseTotal
if $options->{"exec"} and $options->{"fork"} 0 20 20
Condition33%1/3
$options->{"exec"} and $options->{"fork"}
!ll&&!rl&&r
0200
MC/DC0%0/2
$options->{"exec"} and $options->{"fork"}
$options->{"exec"} $options->{"fork"}
Truth table33%1/3
A and B
A= $options->{"exec"}B= $options->{"fork"}
ABresult
0X0
100
111
239 0 ▶ warn "Executing: @{$options->{'exec'}}\n" if $self->{"debug"} and $options->{"exec"};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"debug"} and $options->{"exec"} 0 20 20
Condition33%1/3
$self->{"debug"} and $options->{"exec"}
!ll&&!rl&&r
2000
MC/DC0%0/2
$self->{"debug"} and $options->{"exec"}
$self->{"debug"} $options->{"exec"}
Truth table33%1/3
A and B
A= $self->{"debug"}B= $options->{"exec"}
ABresult
0X0
100
111
240 20 ▶ if($options->{"exec"}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($options->{"exec"}) 20 0 20
241 20 my $count = -1;
242 20 ▶ while(++$count < @{$options->{"exec"}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (++$count < @{$options->{"exec"};}) 20 20 40
243 20 ▶ die "Argument $count to exec is undef\n" unless defined $options->{"exec"}[$count];
Branch: 1 branch
BranchTrueFalseTotal
unless defined $options->{"exec"}[$count] 0 20 20
244 }
245 }
246  
247 # Regarding file handles, $self holds the side that the parent will see and
248 # $options holds the side that the child will see. Remember, if we're passed a
249 # file handle reference, the parent closes it after passing it to the child.
250  
251 # Prepare file descriptors.
252 20 ▶ if(ref $options->{"stdin"}) {
Branch: 4 branches
BranchTrueFalseTotal
if (ref $options->{'stdin'}) { } 5 15 20
elsif ($options->{'stdin'} eq 'new') { } 4 11 15
elsif ($options->{'stdin'} eq 'close') { } 0 11 11
elsif ($options->{'stdin'} eq 'default') { } 11 0 11
253 # Empty
254 } elsif($options->{"stdin"} eq "new") {
255 4 $self->{"stdin"} = undef;
256 4 $options->{"stdin"} = undef;
257 # Careful of the order. It's pipe README, WRITEME.
258 4 ▶ pipe $options->{"stdin"}, $self->{"stdin"} or die "pipe: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
pipe $options->{"stdin"}, $self->{"stdin"} or die "pipe: $!\n" 4 0 4
259 4 set_cloexec($self->{"stdin"});
260 4 set_cloexec($options->{"stdin"});
261 } elsif($options->{"stdin"} eq "close") {
262 # Empty
263 } elsif($options->{"stdin"} eq "default") {
264 # Empty
265 } else {
266 0 die "Unknown option for stdin: $options->{'stdin'}\n";
267 }
268 20 ▶ if(ref $options->{"stdout"}) {
Branch: 4 branches
BranchTrueFalseTotal
if (ref $options->{'stdout'}) { } 12 8 20
elsif ($options->{'stdout'} eq 'new') { } 6 2 8
elsif ($options->{'stdout'} eq 'close') { } 0 2 2
elsif ($options->{'stdout'} eq 'default') { } 2 0 2
269 # Empty
270 } elsif($options->{"stdout"} eq "new") {
271 6 $self->{"stdout"} = undef;
272 6 $options->{"stdout"} = undef;
273 # Careful of the order. It's pipe README, WRITEME.
274 6 ▶ pipe $self->{"stdout"}, $options->{"stdout"} or die "pipe: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
pipe $self->{"stdout"}, $options->{"stdout"} or die "pipe: $!\n" 6 0 6
275 6 set_cloexec($self->{"stdout"});
276 6 set_cloexec($options->{"stdout"});
277 } elsif($options->{"stdout"} eq "close") {
278 # Empty
279 } elsif($options->{"stdout"} eq "default") {
280 # Empty
281 } else {
282 0 die "Unknown option for stdout: $options->{'stdout'}\n";
283 }
284 20 ▶ if(ref $options->{"stderr"}) {
Branch: 4 branches
BranchTrueFalseTotal
if (ref $options->{'stderr'}) { } 0 20 20
elsif ($options->{'stderr'} eq 'new') { } 0 20 20
elsif ($options->{'stderr'} eq 'close') { } 0 20 20
elsif ($options->{'stderr'} eq 'default') { } 20 0 20
285 # Empty
286 } elsif($options->{"stderr"} eq "new") {
287 0 $self->{"stderr"} = undef;
288 0 $options->{"stderr"} = undef;
289 # Careful of the order. It's pipe README, WRITEME.
290 0 ▶ pipe $self->{"stderr"}, $options->{"stderr"} or die "pipe: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
pipe $self->{"stderr"}, $options->{"stderr"} or die "pipe: $!\n" 0 0 0
291 0 set_cloexec($self->{"stderr"});
292 0 set_cloexec($options->{"stderr"});
293 } elsif($options->{"stderr"} eq "close") {
294 # Empty
295 } elsif($options->{"stderr"} eq "default") {
296 # Empty
297 } else {
298 0 die "Unknown option for stderr: $options->{'stderr'}\n";
299 }
300  
301 # Set the close-on-exec flag for both ends in both processes since the child
302 # indicates the success of exec() by closing the pipe.
303 20 ▶ pipe my $error_pipe_r, my $error_pipe_w or die "pipe: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
pipe my $error_pipe_r, my $error_pipe_w or die "pipe: $!\n" 20 0 20
304 20 set_cloexec($error_pipe_r);
305 20 set_cloexec($error_pipe_w);
306 20 select((select($error_pipe_w), $| = 1)[0]); # Set autoflushing for writing.
307  
308 20 $self->{"child_pid"} = fork();
309 20 ▶ die "fork: $!\n" unless defined $self->{"child_pid"};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->{"child_pid"} 0 20 20
310  
311 20 ▶ if($self->{"child_pid"}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"child_pid"}) 15 5 20
312 # Parent
313 15 $self->{"need_wait"} = 1;
314 15 $error_pipe_w = undef;
315  
316 15 ▶ close $options->{"stdin"} if ref $options->{"stdin"};
Branch: 1 branch
BranchTrueFalseTotal
if ref $options->{"stdin"} 7 8 15
317 15 ▶ close $options->{"stdout"} if ref $options->{"stdout"};
Branch: 1 branch
BranchTrueFalseTotal
if ref $options->{"stdout"} 14 1 15
318 15 ▶ close $options->{"stderr"} if ref $options->{"stderr"};
Branch: 1 branch
BranchTrueFalseTotal
if ref $options->{"stderr"} 0 15 15
319  
320 # EOF indicates no error. This blocks until exec() succeeds or fails because in
321 # the child, $error_pipe_w automatically closes on exec or exit.
322 15 ▶ if(defined (my $err = <$error_pipe_r>)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $err = readline $error_pipe_r)) 1 14 15
323 1 chomp $err;
324 1 die "$err\n";
325 }
326  
327 # Don't set this until just before returning because if the constructor dies,
328 # the child must be cleaned.
329 14 $self->{"no_autowait"} = $options->{"no_autowait"};
330  
331 14 return $self;
332 }
333  
334 # Child
335  
336 # Trap dies and force the child to exit instead because the caller isn't
337 # expecting both to return.
338 5 eval {
339 5 $error_pipe_r = undef;
340  
341 # This can matter if the child isn't going to call exec(), since the object is
342 # then destroyed when the child returns.
343 5 $self->{"no_autowait"} = 1;
344  
345 # Set up the child's file descriptors.
346 5 ▶ if(ref $options->{"stdin"}) {
Branch: 3 branches
BranchTrueFalseTotal
if (ref $options->{'stdin'}) { } 2 3 5
elsif ($options->{'stdin'} eq 'close') { } 0 3 3
elsif ($options->{'stdin'} eq 'default') { } 3 0 3
347 # Also covers "new". See above.
348 2 untie *STDIN; # Some programs, like mod_perl, think it's great to tie packages to these file handles.
349 2 ▶ open STDIN, "<&", $options->{"stdin"} or die "dup: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
open STDIN, "<&", $options->{"stdin"} or die "dup: $!\n" 2 0 2
350 2 close $options->{"stdin"};
351 } elsif($options->{"stdin"} eq "close") {
352 # Need a placeholder file handle so the next open() doesn't take the slot.
353 0 ▶ open STDIN, "<", "/dev/null" or die "/dev/null: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
open STDIN, "<", "/dev/null" or die "/dev/null: $!\n" 0 0 0
354 } elsif($options->{"stdin"} eq "default") {
355 # Empty
356 } else {
357 0 die "Can't happen!";
358 }
359 5 ▶ if(ref $options->{"stdout"}) {
Branch: 3 branches
BranchTrueFalseTotal
if (ref $options->{'stdout'}) { } 4 1 5
elsif ($options->{'stdout'} eq 'close') { } 0 1 1
elsif ($options->{'stdout'} eq 'default') { } 1 0 1
360 # Also covers "new". See above.
361 4 untie *STDOUT; # Some programs, like mod_perl, think it's great to tie packages to these file handles.
362 4 ▶ open STDOUT, ">&", $options->{"stdout"} or die "dup: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
open STDOUT, ">&", $options->{"stdout"} or die "dup: $!\n" 4 0 4
363 4 close $options->{"stdout"};
364 } elsif($options->{"stdout"} eq "close") {
365 # Need a placeholder file handle so the next open() doesn't take the slot.
366 0 ▶ open STDOUT, ">", "/dev/null" or die "/dev/null: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
open STDOUT, ">", "/dev/null" or die "/dev/null: $!\n" 0 0 0
367 } elsif($options->{"stdout"} eq "default") {
368 # Empty
369 } else {
370 0 die "Can't happen!";
371 }
372 5 ▶ if(ref $options->{"stderr"}) {
Branch: 3 branches
BranchTrueFalseTotal
if (ref $options->{'stderr'}) { } 0 5 5
elsif ($options->{'stderr'} eq 'close') { } 0 5 5
elsif ($options->{'stderr'} eq 'default') { } 5 0 5
373 # Also covers "new". See above.
374 0 untie *STDERR; # Some programs, like mod_perl, think it's great to tie packages to these file handles.
375 0 ▶ open STDERR, ">&", $options->{"stderr"} or die "dup: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
open STDERR, ">&", $options->{"stderr"} or die "dup: $!\n" 0 0 0
376 0 close $options->{"stderr"};
377 } elsif($options->{"stderr"} eq "close") {
378 # Need a placeholder file handle so the next open() doesn't take the slot.
379 0 ▶ open STDERR, ">", "/dev/null" or die "/dev/null: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
open STDERR, ">", "/dev/null" or die "/dev/null: $!\n" 0 0 0
380 } elsif($options->{"stderr"} eq "default") {
381 # Empty
382 } else {
383 0 die "Can't happen!";
384 }
385  
386 # Lose unnecessary references to these. (This closes the other end of pipes.)
387 5 $self->{"stdin"} = undef;
388 5 $self->{"stdout"} = undef;
389 5 $self->{"stderr"} = undef;
390  
391 # XXX: I didn't document that $error_pipe_w is passed to child_callback because
392 # I haven't decided whether it's a good idea. This allows the caller to unblock
393 # the parent by closing the pipe if it needs to do something that never
394 # returns. However, if it does close the pipe, it must never return. This
395 # allows the caller to take advantage of this module's logic without any
396 # intention to ever call exec() after fork(). It can also be useful for
397 # suspending execution of the parent until the task is complete while reporting
398 # errors to the parent via die(), if it does NOT close the pipe.
399 0 ▶ &{$options->{"child_callback"}}({"error_pipe" => $error_pipe_w}) if $options->{"child_callback"};
Branch: 1 branch
BranchTrueFalseTotal
if $options->{"child_callback"} 0 5 5
400  
401 5 ▶ if($options->{"exec"}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($options->{"exec"}) 5 0 5
402 5 ▶ $options->{"real_arg0"} = ${$options->{"exec"}}[0] unless defined $options->{"real_arg0"};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $options->{"real_arg0"} 5 0 5
403  
404 # Untaint just the arg list, not $options->{"real_arg0"}.
405 5 ▶ if($options->{"untaint_args"}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($options->{"untaint_args"}) 0 5 5
406 0 foreach my $arg (@{$options->{"exec"}}) {
407 0 ($arg) = ($arg =~ qr/^(.*)$/s);
408 }
409 }
410  
411 {
412 # exec {$arg0} @args will never add the shell interpreter. This handles the
413 # errors from exec, so tell Perl not to report them.
414 6 ▶ no warnings 'exec';
Subroutine BEGIN: called CC=1 SCAR=0.0
415 5 exec {$options->{"real_arg0"}} @{$options->{"exec"}};
416 }
417 0 die "$options->{'real_arg0'}: $!\n";
418 }
419  
420 0 ▶ if($options->{"fork"}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($options->{"fork"}) 0 0 0
421 0 return ();
422 }
423  
424 0 die "Can't happen! No action specified for child process, checked in parent.";
425 };
426 0 ▶ if($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
427 # This exit status isn't returned to the caller because the error in the pipe
428 # causes a die in the parent. However, if it's non-zero it'll trigger the
429 # warning in $self->DESTROY(). If the write fails, which probably means
430 # something went horribly wrong, we'll let that warning happen, although it
431 # won't make a lot of sense. XXX: Should this write failure be handled better?
432 0 ▶ print $error_pipe_w $@ or POSIX::exit(1);
Branch: 1 branch
BranchTrueFalseTotal
print $error_pipe_w $@ or POSIX::exit(1) 0 0 0
433 0 POSIX::_exit(0);
434 }
435 0 die "Can't happen!";
436 }
437  
438 13 ▶sub wait {
Subroutine wait: called CC=11 SCAR=25.8
Pod undocumented
439 13 my ($self, $options) = @_;
440  
441 # Waiting on a PID twice can be bad because the kernel reuses PIDs, so if this
442 # program forks another child, we could accidentally wait on it.
443 13 ▶ die "Child was already waited on\n" if defined $self->{"exit_status"};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"exit_status"} 0 13 13
444  
445 13 ▶ unless($options->{"no_close"} or $options->{"nonblock"}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($options->{"no_close"} or $options->{"nonblock"}) 13 0 13
Condition33%1/3
$options->{"no_close"} or $options->{"nonblock"}
l!l&&r!l&&!r
0013
MC/DC0%0/2
$options->{"no_close"} or $options->{"nonblock"}
$options->{"no_close"} $options->{"nonblock"}
Truth table33%1/3
A or B
A= $options->{"no_close"}B= $options->{"nonblock"}
ABresult
1X1
011
000
446 # Close the pipes so the child receives EOF on stdin and isn't blocking to
447 # write to stdout or stderr. Ignore errors because these may already already be
448 # closed.
449 13 ▶ close $self->{"stdin"} if ref $self->{"stdin"};
Branch: 1 branch
BranchTrueFalseTotal
if ref $self->{"stdin"} 2 11 13
450 13 ▶ close $self->{"stdout"} if ref $self->{"stdout"};
Branch: 1 branch
BranchTrueFalseTotal
if ref $self->{"stdout"} 4 9 13
451 13 ▶ close $self->{"stderr"} if ref $self->{"stderr"};
Branch: 1 branch
BranchTrueFalseTotal
if ref $self->{"stderr"} 0 13 13
452 }
453  
454 13 ▶ my $waitpid = waitpid($self->{"child_pid"}, ($options->{"nonblock"} ? &WNOHANG : 0));
Branch: 1 branch
BranchTrueFalseTotal
$options->{'nonblock'} ? : 0 13 13
455 13 ▶ die "Child was already waited on without calling the wait method\n" if $waitpid == -1;
Branch: 1 branch
BranchTrueFalseTotal
if $waitpid == -1 0 13 13
456 13 ▶ return undef if $waitpid == 0; # Child didn't exit yet.
Branch: 1 branch
BranchTrueFalseTotal
if $waitpid == 0 0 13 13
457 13 $self->{"exit_status"} = $?;
458 13 $? = -1; # Invalidate $? so callers don't rely on it since the internal behavior of this method may change in the future.
459 13 ▶ warn sprintf("Exit status was %s (%s)", $self->{"exit_status"}, ($self->{"exit_status"} >> 8)) if $self->{"debug"};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"debug"} 0 13 13
460 13 return 1;
461 }
462  
463 13 ▶sub DESTROY {
Subroutine DESTROY: called CC=6 SCAR=20.5
464 13 my ($self) = @_;
465  
466 # need_wait is set in the parent when the fork() is successful. This prevents
467 # weird stuff from the object's destruction in the child or when an error
468 # happens before fork(). As far as implementation, no_autowait means the caller
469 # expects the child to out-live the object.
470 13 ▶ if($self->{"need_wait"} and not $self->{"no_autowait"} and not defined $self->{"exit_status"}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"need_wait"} and not $self->{"no_autowait"} and not defined $self->{"exit_status"}) 1 12 13
Condition50%3/6
$self->{"need_wait"} and not $self->{"no_autowait"} and not defined $self->{"exit_status"}
!ll&&!rl&&r
0121
$self->{"need_wait"} and not $self->{"no_autowait"}
!ll&&!rl&&r
0013
MC/DC33%1/3
$self->{"need_wait"} and not $self->{"no_autowait"} and not defined $self->{"exit_status"}
$self->{"need_wait"} not $self->{"no_autowait"} not defined $self->{"exit_status"}
Truth table50%2/4
A and not(B) and not(C)
A= $self->{"need_wait"}B= not $self->{"no_autowait"}C= not defined $self->{"exit_status"}
ABCresult
0XX0
10X0
1100
1111
471 1 $self->wait(); # Wait for the child so we don't accidentally leave a zombie process.
472 }
473  
474 13 ▶ if($self->{"exit_status"} and not $self->{"fetched_exit_status"}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"exit_status"} and not $self->{"fetched_exit_status"}) 0 13 13
Condition33%1/3
$self->{"exit_status"} and not $self->{"fetched_exit_status"}
!ll&&!rl&&r
1300
MC/DC0%0/2
$self->{"exit_status"} and not $self->{"fetched_exit_status"}
$self->{"exit_status"} not $self->{"fetched_exit_status"}
Truth table33%1/3
A and not(B)
A= $self->{"exit_status"}B= not $self->{"fetched_exit_status"}
ABresult
0X0
100
111
475 # Non-zero exit status, and the caller didn't inspect the exit status, and the
476 # caller didn't specify no_autowait (which may imply the exit status might not
477 # be meaningful). It's bad practice not to inspect the exit status, so we'll
478 # warn about it. It's easy enough for the caller to quiet this warning.
479 warn sprintf("Exit status was %s (%s) in " . __PACKAGE__ . ", but nothing ever checked it. (Call exit_status() to check it.)\n",
480 0 $self->{"exit_status"}, ($self->{"exit_status"} >> 8));
481 }
482 13 return ();
483 }
484  
485 3 ▶sub stdin {
Subroutine stdin: called CC=1 SCAR=0.0
Pod undocumented
486 3 return $_[0]->{"stdin"};
487 }
488  
489 5 ▶sub stdout {
Subroutine stdout: called CC=1 SCAR=0.0
Pod undocumented
490 5 return $_[0]->{"stdout"};
491 }
492  
493 0 ▶sub stderr {
Subroutine stderr: not called CC=1 SCAR=6.9
Pod undocumented
494 0 return $_[0]->{"stderr"};
495 }
496  
497 0 ▶sub child_pid {
Subroutine child_pid: not called CC=1 SCAR=6.9
Pod undocumented
498 0 return $_[0]->{"child_pid"};
499 }
500  
501 12 ▶sub exit_status {
Subroutine exit_status: called CC=2 SCAR=7.2
Pod documented
502 12 ▶ $_[0]->{"fetched_exit_status"} = 1 if defined $_[0]->{"exit_status"};
Branch: 1 branch
BranchTrueFalseTotal
if defined $_[0]{"exit_status"} 12 0 12
503 12 return $_[0]->{"exit_status"};
504 }
505  
506  
507 # Functional (non-OOP) subs follow.
508  
509 # Private sub.
510 60 ▶sub set_cloexec {
Subroutine set_cloexec: called CC=3 SCAR=11.4
Pod undocumented
511 60 my ($fh) = @_;
512 60 my $fcntl;
513 60 ▶ $fcntl = fcntl($fh, F_GETFL, 0) or die "fcntl: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
$fcntl = fcntl($fh, 3, 0) or die "fcntl: $!\n" 60 0 60
514 60 ▶ $fcntl = fcntl($fh, F_SETFL, $fcntl | FD_CLOEXEC) or die "fnctl: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
$fcntl = fcntl($fh, 4, $fcntl | 1) or die "fnctl: $!\n" 60 0 60
515 }
516  
517 # Equivalent to `@exec`, but with the safety of Proc::SafeExec.
518 0 ▶sub backtick {
Subroutine backtick: not called CC=2 SCAR=17.9
Pod documented
519 0 my @exec = @_;
520  
521 0 my $command = new Proc::SafeExec({
522 "exec" => [@_],
523 "stdout" => "new",
524 });
525 0 my $stdout = $command->stdout();
526 0 local $/ = undef;
527 0 my $output = <$stdout>;
528 0 $command->wait();
529  
530 # If the caller uses scalar context, return just $output and warn on nonzero
531 # exit status.
532 0 ▶ return ($output, $command->exit_status()) if wantarray;
Branch: 1 branch
BranchTrueFalseTotal
if wantarray 0 0 0
533 0 return $output;
534 }
535  
536 6 ▶sub test {
Subroutine test: called CC=13 SCAR=26.8
Pod documented
537 6 my $test = "";
538  
539 # Test case for ls | sort > /tmp/Proc-SafeExec-test1.txt
540 6 my ($output_fh, $output_filename) = File::Temp::tempfile("Proc-SafeExec.XXXXXXXXXXXXXXXX", "SUFFIX" => ".txt", "DIR" => File::Spec->tmpdir());
541 6 eval {
542 6 my $ls = new Proc::SafeExec({"exec" => ["ls"], "stdout" => "new"});
543 5 my $sort = new Proc::SafeExec({"exec" => ["sort"], "stdin" => $ls->stdout(), "stdout" => $output_fh});
544 4 ▶ $ls->wait() or die '$ls->wait() returned false';
Branch: 1 branch
BranchTrueFalseTotal
$ls->wait or die "\$ls->wait() returned false" 4 0 4
545 4 ▶ $sort->wait() or die '$sort->wait() returned false';
Branch: 1 branch
BranchTrueFalseTotal
$sort->wait or die "\$sort->wait() returned false" 4 0 4
546 4 ▶ $ls->exit_status() and die "ls exited with status " . $ls->exit_status();
Branch: 1 branch
BranchTrueFalseTotal
$ls->exit_status and die 'ls exited with status ' . $ls->exit_status 0 4 4
547 4 ▶ $sort->exit_status() and die "sort exited with status " . $sort->exit_status();
Branch: 1 branch
BranchTrueFalseTotal
$sort->exit_status and die 'sort exited with status ' . $sort->exit_status 0 4 4
548 };
549 4 unlink($output_filename);
550 4 ▶ $test .= "$@not " if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 4 4
551 4 $test .= "ok - ls | sort > /tmp/Proc-SafeExec-test1.txt\n";
552  
553 # Another test case for ls | sort > /tmp/Proc-SafeExec-test2.txt
554 # This one will deadlock if the parent doesn't close stdin.
555 4 ($output_fh, $output_filename) = File::Temp::tempfile("Proc-SafeExec.XXXXXXXXXXXXXXXX", "SUFFIX" => ".txt", "DIR" => File::Spec->tmpdir());
556 4 eval {
557 4 my $sort = new Proc::SafeExec({"exec" => ["sort"], "stdin" => "new", "stdout" => $output_fh});
558 3 my $ls = new Proc::SafeExec({"exec" => ["ls"], "stdout" => $sort->stdin()});
559 2 ▶ $ls->wait() or die '$ls->wait() returned false';
Branch: 1 branch
BranchTrueFalseTotal
$ls->wait or die "\$ls->wait() returned false" 2 0 2
560 2 ▶ $sort->wait() or die '$sort->wait() returned false';
Branch: 1 branch
BranchTrueFalseTotal
$sort->wait or die "\$sort->wait() returned false" 2 0 2
561 2 ▶ $ls->exit_status() and die "ls exited with status " . $ls->exit_status();
Branch: 1 branch
BranchTrueFalseTotal
$ls->exit_status and die 'ls exited with status ' . $ls->exit_status 0 2 2
562 2 ▶ $sort->exit_status() and die "sort exited with status " . $sort->exit_status();
Branch: 1 branch
BranchTrueFalseTotal
$sort->exit_status and die 'sort exited with status ' . $sort->exit_status 0 2 2
563 };
564 2 unlink($output_filename);
565 2 ▶ $test .= "$@not " if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 2 2
566 2 $test .= "ok - ls | sort > /tmp/Proc-SafeExec-test2.txt\n";
567  
568 # Test case for exec failure.
569 2 my $message;
570 2 eval {
571 2 eval {
572 2 my $nope = new Proc::SafeExec({"exec" => ["/nonexistent"]});
573 };
574 1 ▶ die "Testing exec failure should have died." unless $@;
Branch: 1 branch
BranchTrueFalseTotal
unless $@ 0 1 1
575 1 $message = $@;
576 1 chomp $message;
577 };
578 1 ▶ $test .= "$@not " if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 1 1
579 1 $test .= "ok - testing exec failure: $message\n";
580  
581 1 return $test;
582 }
583  
584 6 1
« SafeExec/Queue.pm ↑ Summary