6de80fe50ee0cec61eda64c3517f3715abbf7da0
[platform/upstream/coreutils.git] / tests / priv-check
1 # -*- sh -*-
2 # Source this file at the beginning of a test that works
3 # only when run as root or as non-root.
4
5 case "$PRIV_CHECK_ARG" in
6   require-root) who='as root';;
7   require-non-root) who='by an unprivileged user';;
8   *) echo "Usage: PRIV_CHECK_ARG={require-root|require-non-root} . priv-check"\
9      1>&2; exit 1;;
10 esac
11
12 # Make sure id -u succeeds.
13 my_uid=`id -u`
14 test $? = 0 || {
15   echo "$0: cannot run \`id -u'" 1>&2
16   (exit 1); exit 1
17 }
18
19 # Make sure it gives valid output.
20 case $my_uid in
21   *[!0-9]*)
22     echo "$0: invalid output (\`$my_uid') from \`id -u'" 1>&2
23     (exit 1); exit 1
24     ;;
25   *) ;;
26 esac
27
28 test $my_uid = 0 && \
29 {
30   # When running as root, always ensure that we have a valid non-root username.
31   # As non-root, don't do anything, since we won't be running setuidgid.
32   : ${NON_ROOT_USERNAME=nobody}
33
34   # Ensure that the supplied username is valid and with UID != 0.
35   coreutils_non_root_uid=`id -u $NON_ROOT_USERNAME`
36   test $? = 0 || \
37     {
38       echo "$0: This command failed: \`id -u $NON_ROOT_USERNAME'" 1>&2
39       echo "$0: Skipping this test.  To enable it, set the envvar" 1>&2
40       echo "$0: NON_ROOT_USERNAME to a non-root user name." 1>&2
41       (exit 77); exit 77
42     }
43   test "$coreutils_non_root_uid" = 0 && \
44     {
45       echo "$0: The specified NON_ROOT_USERNAME ($NON_ROOT_USERNAME)" 1>&2
46       echo "$0: is invalid because its UID is 0." 1>&2
47       (exit 1); exit 1
48     }
49 }
50
51 give_msg=no
52 case $PRIV_CHECK_ARG:$my_uid in
53   require-root:0) ;;
54   require-root:*) give_msg=yes ;;
55   require-non-root:0)
56     # `.' must be writable by $NON_ROOT_USERNAME
57     setuidgid $NON_ROOT_USERNAME test -w . ||
58       {
59         echo "$0: `pwd`: not writable by user \`$NON_ROOT_USERNAME'" 1>&2
60         echo "$0: skipping this test" 1>&2
61         (exit 77); exit 77
62       }
63     exec setuidgid $NON_ROOT_USERNAME env PATH="$PATH" $0
64     ;;
65   require-non-root:*) ;;
66 esac
67
68 test $give_msg = yes && {
69   cat <<EOF
70 ***************************
71 NOTICE:
72 $0: This test is being skipped, since it works only
73 when run $who.
74 ***************************
75 EOF
76   (exit 77); exit 77
77 }