1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <unistd.h>
4 #include <sys/types.h>
5 #include <sys/stat.h>
6 #include <sys/xattr.h>
7 #include <fcntl.h>
8 #include <errno.h>
9 #include <string.h>
10 #include <time.h>
11 #include <err.h>
12 
13 /* backward compat in case it's not defined */
14 #ifndef O_TMPFILE
15 #define	O_TMPFILE	(020000000|O_DIRECTORY)
16 #endif
17 
18 /*
19  * DESCRIPTION:
20  *	Verify we can create tmpfile.
21  *
22  * STRATEGY:
23  *	1. open(2) with O_TMPFILE.
24  *	2. write(2) random data to it, then read(2) and compare.
25  *	3. fsetxattr(2) random data, then fgetxattr(2) and compare.
26  *	4. Verify the above operations run successfully.
27  *
28  */
29 
30 #define	BSZ 64
31 
32 static void
33 fill_random(char *buf, int len)
34 {
35 	srand(time(NULL));
36 	for (int i = 0; i < len; i++)
37 		buf[i] = (char)(rand() % 0xFF);
38 }
39 
40 int
41 main(void)
42 {
43 	char buf1[BSZ], buf2[BSZ] = {0};
44 
45 	(void) fprintf(stdout, "Verify O_TMPFILE is working properly.\n");
46 
47 	const char *testdir = getenv("TESTDIR");
48 	if (testdir == NULL)
49 		errx(1, "getenv(\"TESTDIR\")");
50 
51 	fill_random(buf1, BSZ);
52 
53 	int fd = open(testdir, O_RDWR|O_TMPFILE, 0666);
54 	if (fd < 0)
55 		err(2, "open(%s)", testdir);
56 
57 	if (write(fd, buf1, BSZ) < 0)
58 		err(3, "write");
59 
60 	if (pread(fd, buf2, BSZ, 0) < 0)
61 		err(4, "pread");
62 
63 	if (memcmp(buf1, buf2, BSZ) != 0)
64 		errx(5, "data corrupted");
65 
66 	memset(buf2, 0, BSZ);
67 
68 	if (fsetxattr(fd, "user.test", buf1, BSZ, 0) < 0)
69 		err(6, "pread");
70 
71 	if (fgetxattr(fd, "user.test", buf2, BSZ) < 0)
72 		err(7, "fgetxattr");
73 
74 	if (memcmp(buf1, buf2, BSZ) != 0)
75 		errx(8, "xattr corrupted\n");
76 
77 	return (0);
78 }
79