9 #include <support/xunistd.h>
11 static void prepare (void);
12 #define PREPARE(argc, argv) prepare ()
14 static int do_test (void);
15 #define TEST_FUNCTION do_test ()
17 #include "../test-skeleton.c"
24 #if _POSIX_CHOWN_RESTRICTED == 0
25 if (pathconf (test_dir
, _PC_CHOWN_RESTRICTED
) != 0)
28 uid_t uid
= getuid ();
31 puts ("need root privileges");
36 size_t test_dir_len
= strlen (test_dir
);
37 static const char dir_name
[] = "/tst-fchownat.XXXXXX";
39 size_t dirbuflen
= test_dir_len
+ sizeof (dir_name
);
40 char *dirbuf
= malloc (dirbuflen
);
43 puts ("out of memory");
47 snprintf (dirbuf
, dirbuflen
, "%s%s", test_dir
, dir_name
);
48 if (mkdtemp (dirbuf
) == NULL
)
50 puts ("cannot create temporary directory");
54 add_temp_file (dirbuf
);
56 dir_fd
= open (dirbuf
, O_RDONLY
| O_DIRECTORY
);
59 puts ("cannot open directory");
68 /* fdopendir takes over the descriptor, make a copy. */
69 int dupfd
= dup (dir_fd
);
75 if (lseek (dupfd
, 0, SEEK_SET
) != 0)
77 puts ("1st lseek failed");
81 /* The directory should be empty safe the . and .. files. */
82 DIR *dir
= fdopendir (dupfd
);
85 puts ("fdopendir failed");
89 while ((d
= readdir64 (dir
)) != NULL
)
90 if (strcmp (d
->d_name
, ".") != 0 && strcmp (d
->d_name
, "..") != 0)
92 printf ("temp directory contains file \"%s\"\n", d
->d_name
);
97 /* Try to create a file. */
98 int fd
= openat (dir_fd
, "some-file", O_CREAT
|O_RDWR
|O_EXCL
, 0666);
103 puts ("*at functions not supported");
107 puts ("file creation failed");
110 xwrite (fd
, "hello", 5);
111 puts ("file created");
114 if (fstat64 (fd
, &st1
) != 0)
116 puts ("fstat64 failed");
120 /* Before closing the file, try using this file descriptor to open
121 another file. This must fail. */
122 if (fchownat (fd
, "some-file", 1, 1, 0) != -1)
124 puts ("fchownat using descriptor for normal file worked");
127 if (errno
!= ENOTDIR
)
130 error for fchownat using descriptor for normal file not ENOTDIR ");
136 if (fchownat (dir_fd
, "some-file", st1
.st_uid
+ 1, st1
.st_gid
+ 1, 0) != 0)
138 puts ("fchownat failed");
143 if (fstatat64 (dir_fd
, "some-file", &st2
, 0) != 0)
145 puts ("fstatat64 failed");
149 if (st1
.st_uid
+ 1 != st2
.st_uid
|| st1
.st_gid
+ 1 != st2
.st_gid
)
151 puts ("owner change failed");
155 if (unlinkat (dir_fd
, "some-file", 0) != 0)
157 puts ("unlinkat failed");
161 /* Create a file descriptor which is closed again right away. */
162 int dir_fd2
= dup (dir_fd
);
170 if (fchownat (dir_fd2
, "some-file", 1, 1, 0) != -1)
172 puts ("fchownat using closed descriptor worked");
177 puts ("error for fchownat using closed descriptor not EBADF ");
183 if (fchownat (-1, "some-file", 1, 1, 0) != -1)
185 puts ("fchownat using invalid descriptor worked");
190 puts ("error for fchownat using invalid descriptor not EBADF ");