File::Save::Home(3)

NAME
File::Save::Home - Place file safely under user home directory

VERSION
This document refers to version 0.12, released January 03 2026.

SYNOPSIS
    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
    );

DESCRIPTION
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.

  Limitations
The preceding description was written in 2005. Experience has shown that any claim that one can make about the safety of the creation or deletion of directories and files underneath a user's home directory must be qualified. File::Save::Home is satisfactory for the use case for which it was originally designed, but there are other situations where it falls short.

The original use case for which File::Save::Home was designed was to support the placement of personal preference files in a user's home directory. Such personal preference files are often referred to as dot-rc files because their names typically start with a "." character to render them hidden from commands like "ls" and end in "rc" much like ".bashrc" or <.shrc>. A developer using CPAN::Mini, for example, often makes use of ".minicpanrc" to store the developer's preferred CPAN mirror. File::Save::Home was created specifically to support the creation of a ".modulemakerrc" file by users of ExtUtils::ModuleMaker and a ".podmultirc" file by users of Pod::Multi. (ExtUtils::ModuleMaker and Pod::Multi are maintained by the author of File::Save::Home.) These libraries are developer's tools, i.e., they are intended to assist individual humans in software development rather than being used "in production." As such, their use of dot-rc files implicitly assumes:

•   Only one user is concerned with the status of the directories and files, including dot-rc files, underneath the user's home directory.

•   Only one user has permissions to create, modify or remove directories and files underneath the user's home directory -- an assumption that is easily violated by a superuser such as "root".

•   The user is running processes to create, modify or remove directories and files underneath the user's home directory one-at-a-time, "i.e.," the user is not running such processes in parallel. Running such processes in parallel would raise the possibility, for example, of process trying to rename a dot-rc file that a second, parallel process had already deleted.

When either the second or third assumption above is violated, we have the possibility of race conditions (<https://en.wikipedia.org/wiki/Race_condition>) and time of check to time of use (TOCTTOU) errors (<https://en.wikipedia.org/wiki/Time_of_check_to_time_of_use>). Such conditions may lead to either spurious testing failures (e.g., when CPANtesteers run tests in parallel on libraries using File::Save::Home) or to security violations.

USAGE

  get_home_directory()
Analyzes environmental information to determine whether there exists on the system a 'HOME' or 'home-equivalent' directory. Takes no arguments. Returns that directory if it exists; "croak"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 "SEE ALSO".)

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.

  get_subhome_directory_status()
Single argument version

Takes as argument a string holding the name of a directory, either single-level ("mydir") or multi-level ("path/to/mydir"). Determines whether that directory already exists underneath the user's home or home-equivalent directory. Calls get_home_directory() 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 get_home_directory(). Suppose, for example, that you're on Win32 and want to use the my_home() method supplied by CPAN distribution File::HomeDir -- a method which returns a different result from that of our get_home_directory() -- but you still want to use those File::Save::Home functions which normally call get_home_directory() internally. Or, suppose you want to supply an arbitrary path.

You can now do so by supplying an optional second argument to "get_subhome_directory_status". This argument should be a valid path name for a directory to which you have write privileges. "get_subhome_directory_status" 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, "get_subhome_directory_status" returns a reference to a four-element hash whose keys are:

home
    The absolute path of the home directory.

abs The absolute path of the directory specified as first argument to the function.

flag
    A Boolean value indicating whether the desired directory already exists (a true value) or not ("undef").

top The uppermost subdirectory passed as the argument to this function.

  make_subhome_directory()
Takes as argument the hash reference returned by get_subhome_directory_status(). Examines the first element in that array -- the directory name -- and creates the directory if it doesn't already exist. The function "croak"s if the directory cannot be created.

  restore_subhome_directory_status()
Undoes make_subhome_directory(), 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.

  make_subhome_temp_directory()
Regular version: no arguments

Creates a randomly named temporary directory underneath the home or home-equivalent directory returned by get_home_directory().

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 version of "get_subhome_directory_status()" above. You could use it if, for example, you wanted to use "File::HomeDir-"my_home()> to supply a value for the user's home directory instead of our get_home_directory().

Both versions

In both versions, the temporary subdirectory is created by calling "File::Temp::tempdir (DIR =" $home, CLEANUP => 1)>. The function returns the directory path if successful; "croak"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.

  conceal_target_file()
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:

dir The directory in which the file is presumed to exist.

file
    The targeted file, i.e., the file to be temporarily hidden if it already exists.

test
    Boolean value which, if turned on (1), will cause the function, when called, to run two Test::More::ok() tests. Defaults to off (0).

Returns a reference to a hash with these keys:

full
    The absolute path to the target file.

hidden
    The absolute path to the now-hidden file.

atime
    The last access time to the target file ("(stat($file{full}))[8]").

modtime
    The last modification time to the target file ("(stat($file{full}))[9]").

test
    The value of the key "test" in the hash passed by reference as an argument to this function.

  reveal_target_file()
Used in conjunction with conceal_target_file() to restore the original status of the file targeted by conceal_target_file(), 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. "croak"s if the hidden file cannot be renamed. Takes as argument the hash reference returned by conceal_target_file(). If the value for the "test" key in the hash passed as an argument to conceal_target_file() was true, then a call to "reveal_target_file" will run three Test::More::ok() tests.

BUGS AND TODO
So far tested only on Unix-like systems and Win32.

SEE ALSO
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 CPAN. They and the ExtUtils::ModuleMaker test suite provide examples of the use of File::Save::Home.

One other CPAN distribution, File::HomeDir can also be used to locate a suitable value for a user's home directory. It should be noted, however, that this module and File::Save::Home take different approaches 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; YMMV.

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, "get_home_directory", 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, "File::Save::Home->get_home_directory" gave the same result as "File::HomeDir->my_data", not, as I might have expected, the same result as "File::HomeDir->my_home".

These results can be explained by peeking behind the curtains and looking at the source code for each module.

  File::HomeDir
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. "File::HomeDir::Windows->my_home()" 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 CSIDL_LOCAL_APPDATA (<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 CSIDL values in general and CSIDL_LOCAL_APPDATA() in particular:

•   CSIDL 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.

•   CSIDL_LOCAL_APPDATA (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>. 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, my_documents() and my_data() both rely on using a Win32 module to peer into the registry, albeit in a slightly different manner from "File::Save::Home->get_home_directory". TIMTOWTDI.

In an event, File::Save::Home has a number of useful methods besides get_home_directory() 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 "get_home_directory" internally.

AUTHOR
        James E Keenan
        CPAN ID: JKEENAN
        jkeenan@cpan.org
    https://metacpan.org/pod/File::Save::Home

ACKNOWLEDGMENTS
File::Save::Home has its origins in the maintenance revisions I was doing on CPAN 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 SEE ALSO section and to Adam Kennedy for responding to questions about File::HomeDir.

Thanks to Damyan Ivanov, Xavier Guimard and Gregor Herrman of Debian Perl Group for patches.

COPYRIGHT
Copyright (c) 2005-2026 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 LICENSE file included with this module.

DISCLAIMER OF WARRANTY
BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE SOFTWARE ''AS IS'' WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR, OR CORRECTION.

IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.