[Melbourne-pm] how to pass a filehandle to an external binary

David Dick david_dick at iprimus.com.au
Sat Feb 12 23:54:58 PST 2005


I've got a perl program that needs to call external binaries to apply a 
transformation, namely, htmldoc and compress or bzip.  I've also been 
reading the secure programming for linux and unix howto at 
http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/index.html 
and hence am now massively (and probably over) paranoid about race 
conditions on tmp files involving setuid bits, SIGSTOP and SIGCONT and 
tmp directory cleaners.

however, on reading the doco for File::Temp i came across a good trick 
for linux / unix boxes, namely, how to pass a file handle to an external 
binary that is expecting a file name.  The following code works well for 
me and seems to work for everything on my machine.

anyone know a more secure way / different secure way of interacting with 
external binaries? or any issues with this approach?

uru
-dave

#! /usr/bin/perl -w

use FileHandle();
use File::Temp();
use Fcntl();
use strict;

my $tmpFileHandle = File::Temp::tempfile();
unless ($tmpFileHandle) {
         die("Failed to open tmp file:$!\n");
}
unless ($tmpFileHandle->print("Sample data for bzip")) {
         die("Failed to write to temp file:$!\n");
}
# stop tmpFileHandle being closed during the exec of bzip
unless (fcntl($tmpFileHandle, Fcntl::F_SETFD(), 0)) {
         die("Failed to set close-on-exec flag:$!\n");
}
my ($bzipHandle) = new FileHandle("bzip2 --stdout /dev/fd/" . 
$tmpFileHandle->fileno() . " |");
unless ($bzipHandle) {
         die("Failed to start bzip:$!\n");
}
# can close tmpFileHandle here
while(<$bzipHandle>) {
}
# close bzipHandle, check $?, etc




More information about the Melbourne-pm mailing list