btrfs-progs: fsck-test: Add check_sudo to check valid root/sudo privilege
[platform/upstream/btrfs-progs.git] / tests / common
1 #!/bin/bash
2 #
3 # Common routines for all tests
4 #
5
6 _fail()
7 {
8         echo "$*" | tee -a $RESULT
9         exit 1
10 }
11
12 _not_run()
13 {
14         echo "    [NOTRUN] $*"
15         exit 0
16 }
17
18 run_check()
19 {
20         echo "############### $@" >> $RESULT 2>&1
21         "$@" >> $RESULT 2>&1 || _fail "failed: $@"
22 }
23
24 check_prereq()
25 {
26         if ! [ -f $top/$1 ]; then
27                 _fail "Failed prerequisities: $1";
28         fi
29 }
30
31 check_image()
32 {
33         image=$1
34         echo "testing image $(basename $image)" >> $RESULT
35         $top/btrfs check $image >> $RESULT 2>&1
36         [ $? -eq 0 ] && _fail "btrfs check should have detected corruption"
37
38         run_check $top/btrfs check --repair $image
39         run_check $top/btrfs check $image
40 }
41
42 check_all_images()
43 {
44         dir=$1
45         for i in $(find $dir -iname '*.img')
46         do
47                 echo "extracting image $(basename $i)" >> $RESULT
48                 $top/btrfs-image -r $i $i.restored || \
49                         _fail "failed to extract image $i"
50
51                 check_image $i.restored
52
53                 rm $i.restored
54         done
55 }
56
57 # some tests need to mount the recovered image and do verifications call
58 # 'setup_root_helper' and then check for have_root_helper == 1 if the test
59 # needs to fail otherwise; using sudo by default for now
60 _sudo=
61 need_validate=-1
62 export _sudo
63 export need_validate
64 root_helper()
65 {
66         if [ $UID -eq 0 ]; then
67                 $*
68         else
69                 if [ $need_validate -eq 1 ]; then
70                         sudo -v -n &> /dev/null || \
71                                 _not_run "Need validate sudo credential"
72                         sudo -n $*
73                 elif [ $need_validate -eq 0 ]; then
74                         sudo -n true  &> /dev/null || \
75                                 _not_run "Need validate sudo user setting"
76                         sudo -n $*
77                 else
78                         # should not happen
79                         _not_run "Need validate root privilege"
80                 fi
81         fi
82 }
83
84 setup_root_helper()
85 {
86         if [ $UID -eq 0 ]; then
87                 return
88         fi
89         # Test for old sudo or special setting, which makes sudo -v fails even
90         # user is set NOPASSWD
91         sudo -n true &> /dev/null && need_validate=0
92
93         # Newer sudo or default sudo setting
94         sudo -v -n &> /dev/null && need_validate=1
95
96         if [ $need_validate -eq -1 ]; then
97                 _not_run "Need validate root privilege"
98         fi
99         _sudo=root_helper
100 }