Place file safely under user home directory
This document refers to version 0.09, released December 14, 2012.
use File::Save::Home qw( get_home_directory get_subhome_directory_status make_subhome_directory restore_subhome_directory_status conceal_target_file reveal_target_file make_subhome_temp_directory ); $home_dir = get_home_directory(); $desired_dir_ref = get_subhome_directory_status("desired/directory"); $desired_dir_ref = get_subhome_directory_status( "desired/directory", "pseudohome/directory", # two-argument version ); $desired_dir = make_subhome_directory($desired_dir_ref); restore_subhome_directory_status($desired_dir_ref); $target_ref = conceal_target_file( { dir => $desired_dir, file => 'file_to_be_checked', test => 0, } ); reveal_target_file($target_ref); $tmpdir = make_subhome_temp_directory(); $tmpdir = make_subhome_temp_directory( "pseudohome/directory", # optional argument version );
In the course of deploying an application on another user's system, you sometimes need to place a file in or underneath that user's home directory. Can you do so safely?
This Perl extension provides several functions which try to determine whether you can, indeed, safely create directories and files underneath a user's home directory. Among other things, if you are placing a file in such a location only temporarily \*(-- say, for testing purposes \*(-- you can temporarily hide any already existing file with the same name and restore it to its original name and timestamps when you are done.
Analyzes environmental information to determine whether there exists on the system a '\s-1HOME\s0' or 'home-equivalent' directory. Takes no arguments. Returns that directory if it exists; \*(C`croak\*(C's otherwise.
On Win32, this directory is the one returned by the following function from the Win32module:
Win32->import( qw(CSIDL_LOCAL_APPDATA) ); $realhome = Win32::GetFolderPath( CSIDL_LOCAL_APPDATA() );
... which translates to something like C:\Documents and Settings\localuser\Local Settings\Application Data. (For a further discussion of Win32, see below \*(L"\s-1SEE\s0 \s-1ALSO\s0\*(R".)
On Unix-like systems, things are much simpler. We simply check the value of $ENV{HOME}. We cannot do that on Win32 because $ENV{HOME} is not defined there. Single argument version
Takes as argument a string holding the name of a directory, either single-level (\*(C`mydir\*(C') or multi-level (\*(C`path/to/mydir\*(C'). Determines whether that directory already exists underneath the user's home or home-equivalent directory. Calls \*(C`get_home_directory()\*(C' internally, then tacks on the path passed as argument.
Two-argument version
Suppose you want to determine the name of a user's home directory by some other route than \*(C`get_home_directory()\*(C'. Suppose, for example, that you're on Win32 and want to use the \*(C`my_home()\*(C' method supplied by \s-1CPAN\s0 distribution File::HomeDir \*(-- a method which returns a different result from that of our \*(C`get_home_directory()\*(C' \*(-- but you still want to use those File::Save::Home functions which normally call \*(C`get_home_directory()\*(C' internally. Or, suppose you want to supply an arbitrary path.
You can now do so by supplying an optional second argument to \*(C`get_subhome_directory_status\*(C'. This argument should be a valid path name for a directory to which you have write privileges. \*(C`get_subhome_directory_status\*(C' will determine if the directory exists and, if so, determine whether the first argument is a subdirectory of the second argument.
Both versions
Whether you use the single argument version or the two-argument version, \*(C`get_subhome_directory_status\*(C' returns a reference to a four-element hash whose keys are:
The absolute path of the home directory.
The absolute path of the specified directory.
A Boolean value indicating whether that directory already exists (a true value) or not (\*(C`undef\*(C').
The uppermost subdirectory passed as the argument to this function. Takes as argument the hash reference returned by \*(C`get_subhome_directory_status()\*(C'. Examines the first element in that array \*(-- the directory name \*(-- and creates the directory if it doesn't already exist. The function \*(C`croak\*(C's if the directory cannot be created. Undoes \*(C`make_subhome_directory()\*(C', i.e., if there was no specified directory under the user's home directory on the user's system before testing, any such directory created during testing is removed. On the other hand, if there was such a directory present before testing, it is left unchanged. Regular version: no arguments
Creates a randomly named temporary directory underneath the home or home-equivalent directory returned by \*(C`get_home_directory()\*(C'.
Optional argument version
Creates a randomly named temporary directory underneath the directory supplied as the single argument. This version is analogous to the two-argument verion of \*(L"get_subhome_directory_status()\*(R" above. You could use it if, for example, you wanted to use \*(C`File::HomeDir-\*(C'my_home()> to supply a value for the user's home directory instead of our \*(C`get_home_directory()\*(C'.
Both versions
In both versions, the temporary subdirectory is created by calling \*(C`File::Temp::tempdir (DIR =\*(C' $home, \s-1CLEANUP\s0 => 1)>. The function returns the directory path if successful; \*(C`croak\*(C's otherwise.
Note: Any temporary directory so created remains in existence for the duration of the program, but is deleted (along with all its contents) when the program exits. Determines whether file with specified name already exists in specified directory and, if so, temporarily hides it by renaming it with a .hidden suffix and storing away its last access and modification times. Takes as argument a reference to a hash with these keys:
The directory in which the file is presumed to exist.
The targeted file, i.e., the file to be temporarily hidden if it already exists.
Boolean value which, if turned on (1), will cause the function, when called, to run two \*(C`Test::More::ok()\*(C' tests. Defaults to off (0).
Returns a reference to a hash with these keys:
The absolute path to the target file.
The absolute path to the now-hidden file.
The last access time to the target file (\*(C`(stat($file{full}))[8]\*(C').
The last modification time to the target file (\*(C`(stat($file{full}))[9]\*(C').
The value of the key \*(C`test\*(C' in the hash passed by reference as an argument to this function. Used in conjunction with \*(C`conceal_target_file()\*(C' to restore the original status of the file targeted by \*(C`conceal_target_file()\*(C', i.e., renames the hidden file to its original name by removing the .hidden suffix, thereby deleting any other file with the original name created between the calls tothe two functions. \*(C`croak\*(C's if the hidden file cannot be renamed. Takes as argument the hash reference returned by \*(C`conceal_target_file()\*(C'. If the value for the \*(C`test\*(C' key in the hash passed as an argument to \*(C`conceal_target_file()\*(C' was true, then a call to \*(C`reveal_target_file\*(C' will run three \*(C`Test::More::ok()\*(C' tests.
So far tested only on Unix-like systems and Win32.
perl\|(1). ExtUtils::ModuleMaker::Auxiliary. ExtUtils::ModuleMaker::Utility. The latter two packages are part of the ExtUtils::ModuleMaker distribution available from the same author on \s-1CPAN\s0. They and the ExtUtils::ModuleMaker test suite provide examples of the use of File::Save::Home.
Two other distributions located on \s-1CPAN\s0, File::HomeDir and File::HomeDir::Win32, may also be used to locate a suitable value for a user's home directory. It should be noted, however, that those modules and File::Save::Home each take a different approach to defining a home directory on Win32 systems. Hence, each may deliver a different result on a given system. I cannot say that one distribution's approach is any more or less correct than the other two's approaches. The following comments should be viewed as my subjective impressions; \s-1YMMV\s0.
File::HomeDir was originally written by Sean M Burke and is now maintained by Adam Kennedy. As of version 0.52 its interface provides three methods for the ''current user'':
$home = File::HomeDir->my_home; $docs = File::HomeDir->my_documents; $data = File::HomeDir->my_data;
When I ran these three methods on a Win2K Pro system running ActivePerl 8, I got these results:
C:\WINNT\system32>perl -MFile::HomeDir -e "print File::HomeDir->my_home" C:\Documents and Settings\localuser
C:\WINNT\system32>perl -MFile::HomeDir -e "print File::HomeDir->my_documents" C:\Documents and Settings\localuser\My Documents
C:\WINNT\system32>perl -MFile::HomeDir -e "print File::HomeDir->my_data" C:\Documents and Settings\localuser\Local Settings\Application Data
In contrast, when I ran the closest equivalent method in File::Save::Home, \*(C`get_home_directory\*(C', I got this result:
C:\WINNT\system32>perl -MFile::Save::Home -e "print File::Save::Home->get_home_directory" C:\Documents and Settings\localuser\Local Settings\Application Data
In other words, \*(C`File::Save::Home->get_home_directory\*(C' gave the same result as \*(C`File::HomeDir->my_data\*(C', not, as I might have expected, the same result as \*(C`File::HomeDir->my_home\*(C'.
These results can be explained by peeking behind the curtains and looking at the source code for each module.
File::HomeDir's objective is to provide a value for a user's home directory on a wide variety of operating systems. When invoked, it detects the operating system you're on and calls a subclassed module. When used on a Win32 system, that subclass is called File::HomeDir::Windows (not to be confused with the separate \s-1CPAN\s0 distribution File::HomeDir::Win32). \*(C`File::HomeDir::Windows->my_home()\*(C' looks like this:
sub my_home { my $class = shift; if ( $ENV{USERPROFILE} ) { return $ENV{USERPROFILE}; } if ( $ENV{HOMEDRIVE} and $ENV{HOMEPATH} ) { return File::Spec->catpath( $ENV{HOMEDRIVE}, $ENV{HOMEPATH}, '',); } Carp::croak("Could not locate current user's home directory"); }
In other words, determine the current user's home directory simply by checking environmental variables analogous to the $ENV{HOME} on Unix-like systems. A very straightforward approach!
As mentioned above, File::Save::Home takes a different approach. It uses the Win32 module to, in effect, check a particular key in the registry.
Win32->import( qw(CSIDL_LOCAL_APPDATA) ); $realhome = Win32::GetFolderPath( CSIDL_LOCAL_APPDATA() );
This approach was suggested to me in August 2005 by several members of Perlmonks. (See threads Installing a config file during module operation (<http://perlmonks.org/?node_id=481690>) and Win32 \s-1CSIDL_LOCAL_APPDATA\s0 (<http://perlmonks.org/?node_id=485902>).) I adopted this approach in part because the people recommending it knew more about Windows than I did, and in part because File::HomeDir was not quite as mature as it has since become.
But don't trust me; trust Microsoft! Here's their explanation for the use of \s-1CSIDL\s0 values in general and \s-1CSIDL_LOCAL_APPDATA\s0() in particular:
\s-1CSIDL\s0 values provide a unique system-independent way to identify special folders used frequently by applications, but which may not have the same name or location on any given system. For example, the system folder may be ''C:\Windows'' on one system and ''C:\Winnt'' on another. These constants are defined in Shlobj.h and Shfolder.h.
\s-1CSIDL_LOCAL_APPDATA\s0 (0x001c) Version 5.0. The file system directory that serves as a data repository for local (nonroaming) applications. A typical path is C:\Documents and Settings\username\Local Settings\Application Data.
(Source: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/shellcc/platform/shell/reference/enums/csidl.asp <http://msdn.microsoft.com/library/default.asp?url=/library/en-us/shellcc/platform/shell/reference/enums/csidl.asp>. Link valid as of Feb 18 2006. Thanks to Soren Andersen for reminding me of this citation.)
It is interesting that the other two File::HomeDir methods listed above, \*(C`my_documents()\*(C' and \*(C`my_data()\*(C' both rely on using a Win32 module to peer into the registry, albeit in a slightly different manner from \*(C`File::Save::Home->get_home_directory\*(C'. \s-1TIMTOWTDI\s0.
In an event, File::Save::Home has a number of useful methods besides \*(C`get_home_directory()\*(C' which merit your consideration. And, as noted above, you can supply any valid directory as an optional additional argument to the two File::Save::Home functions which normally default to calling \*(C`get_home_directory\*(C' internally.
File::HomeDir::Win32 was originally written by Rob Rothenberg and is now maintained by Randy Kobes. According to Adam Kennedy (http://annocpan.org/~JKEENAN/File-Save-Home-0.07/lib/File/Save/Home.pm#note_636 <http://annocpan.org/~JKEENAN/File-Save-Home-0.07/lib/File/Save/Home.pm#note_636>), ''The functionality in File::HomeDir::Win32 is gradually being merged into File::HomeDir over time and will eventually be deprecated (although left in place for compatibility purposes).'' Because I have not yet fully installed File::HomeDir::Win32, I will defer further comparison between it and File::Save::Home to a later date.
James E Keenan CPAN ID: JKEENAN [email protected] http://search.cpan.org/~jkeenan
File::Save::Home has its origins in the maintenance revisions I was doing on \s-1CPAN\s0 distribution ExtUtils::ModuleMaker in the summer of 2005. After I made a presentation about that distribution to the Toronto Perlmongers on October 27, 2005, Michael Graham suggested that certain utility functions could be extracted to a separate Perl extension for more general applicability. This module is the implementation of Michael's suggestion.
While I was developing those utility functions for ExtUtils::ModuleMaker, I turned to the Perlmonks for assistance with the problem of determining a suitable value for the user's home directory on Win32 systems. In the Perlmonks discussion threads referred to above I received helpful suggestions from monks CountZero, Tanktalus, xdg and holli, among others.
Thanks to Rob Rothenberg for prodding me to expand the \s-1SEE\s0 \s-1ALSO\s0 section and to Adam Kennedy for responding to questions about File::HomeDir.
Copyright (c) 2005-06 James E. Keenan. United States. All rights reserved.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
The full text of the license can be found in the \s-1LICENSE\s0 file included with this module.
\s-1BECAUSE\s0 \s-1THIS\s0 \s-1SOFTWARE\s0 \s-1IS\s0 \s-1LICENSED\s0 \s-1FREE\s0 \s-1OF\s0 \s-1CHARGE\s0, \s-1THERE\s0 \s-1IS\s0 \s-1NO\s0 \s-1WARRANTY\s0 \s-1FOR\s0 \s-1THE\s0 \s-1SOFTWARE\s0, \s-1TO\s0 \s-1THE\s0 \s-1EXTENT\s0 \s-1PERMITTED\s0 \s-1BY\s0 \s-1APPLICABLE\s0 \s-1LAW\s0. \s-1EXCEPT\s0 \s-1WHEN\s0 \s-1OTHERWISE\s0 \s-1STATED\s0 \s-1IN\s0 \s-1WRITING\s0 \s-1THE\s0 \s-1COPYRIGHT\s0 \s-1HOLDERS\s0 \s-1AND/OR\s0 \s-1OTHER\s0 \s-1PARTIES\s0 \s-1PROVIDE\s0 \s-1THE\s0 \s-1SOFTWARE\s0 ''\s-1AS\s0 \s-1IS\s0'' \s-1WITHOUT\s0 \s-1WARRANTY\s0 \s-1OF\s0 \s-1ANY\s0 \s-1KIND\s0, \s-1EITHER\s0 \s-1EXPRESSED\s0 \s-1OR\s0 \s-1IMPLIED\s0, \s-1INCLUDING\s0, \s-1BUT\s0 \s-1NOT\s0 \s-1LIMITED\s0 \s-1TO\s0, \s-1THE\s0 \s-1IMPLIED\s0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