2 # Create a temporary directory, sort of like mktemp -d does.
4 # Copyright (C) 2007 Red Hat, Inc. All rights reserved.
6 # This copyrighted material is made available to anyone wishing to use,
7 # modify, copy, or redistribute it subject to the terms and conditions
8 # of the GNU General Public License v.2.
10 # You should have received a copy of the GNU General Public License
11 # along with this program; if not, write to the Free Software Foundation,
12 # Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
14 # Written by Jim Meyering.
16 # Usage: mkdtemp /tmp phoey.XXXXXXXXXX
18 # First, try to use the mktemp program.
19 # Failing that, we'll roll our own mktemp-like function:
20 # - try to get random bytes from /dev/urandom
21 # - failing that, generate output from a combination of quickly-varying
22 # sources and gzip. Ignore non-varying gzip header, and extract
23 # "random" bits from there.
24 # - given those bits, map to file-name bytes using tr, and try to create
25 # the desired directory.
26 # - make only $MAX_TRIES attempts
29 die
() { echo >&2 "$ME: $@"; exit 1; }
37 chars
=abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
40 if test -r "$dev_rand"; then
41 # Note: 256-length($chars) == 194; 3 copies of $chars is 186 + 8 = 194.
42 head -c$n "$dev_rand" |
tr -c $chars 01234567$chars$chars$chars
46 cmds
='date; date +%N; free; who -a; w; ps auxww; ps ef; netstat -n'
47 data
=$
( (eval "$cmds") 2>&1 |
gzip )
49 n_plus_50
=$
(expr $n + 50)
51 # Ensure that $data has length at least 50+$n
53 len
=$
(echo "$data"|
wc -c)
54 test $n_plus_50 -le $len && break;
55 data
=$
( (echo "$data"; eval "$cmds") 2>&1 |
gzip )
59 |
dd bs
=1 skip
=50 count
=$n 2>/dev
/null \
60 |
tr -c $chars 01234567$chars$chars$chars
67 *) die
"Usage: $ME DIR TEMPLATE";;
75 *) die
"invalid template: $template (must have a suffix of at least 4 X's)";;
80 # First, try to use mktemp.
81 d
=$
(env
-u TMPDIR mktemp
-d -t -p "$destdir" "$template" 2>/dev
/null
) \
84 # The resulting name must be in the specified directory.
85 case $d in "$destdir"*);; *) fail
=1;; esac
87 # It must have created the directory.
88 test -d "$d" || fail
=1
90 # It must have 0700 permissions.
91 perms
=$
(ls -dgo "$d" 2>/dev
/null
) || fail
=1
92 case $perms in drwx------
*) ;; *) fail
=1;; esac
99 # If we reach this point, we'll have to create a directory manually.
101 # Get a copy of the template without its suffix of X's.
102 base_template
=$
(echo "$template"|
sed 's/XX*$//')
104 # Calculate how many X's we've just removed.
105 nx
=$
(expr length
"$template" - length
"$base_template")
111 candidate_dir
="$destdir/$base_template$X"
112 err
=$
(mkdir
-m 0700 "$candidate_dir" 2>&1) \
113 && { echo "$candidate_dir"; return; }
114 test $MAX_TRIES -le $i && break;