xref: /plan9/sys/src/ape/lib/ap/plan9/access.c (revision 781103c4074deb8af160e8a0da2742ba6b29dc2b)
1 #include "lib.h"
2 #include <string.h>
3 #include <sys/stat.h>
4 #include <fcntl.h>
5 #include <unistd.h>
6 #include <errno.h>
7 #include <stdlib.h>
8 #include "sys9.h"
9 #include "dir.h"
10 
11 int
access(const char * name,int mode)12 access(const char *name, int mode)
13 {
14 	int fd;
15 	Dir *db;
16 	struct stat st;
17 	static char omode[] = {
18 		0,
19 		3,
20 		1,
21 		2,
22 		0,
23 		2,
24 		2,
25 		2
26 	};
27 	char tname[1024];
28 
29 	if(mode == 0){
30 		db = _dirstat(name);
31 		if(db == nil){
32 			_syserrno();
33 			return -1;
34 		}
35 		free(db);
36 		return 0;
37 	}
38 	fd = open(name, omode[mode&7]);
39 	if(fd >= 0){
40 		close(fd);
41 		return 0;
42 	}
43 	else if(stat(name, &st)==0 && S_ISDIR(st.st_mode)){
44 		if(mode & (R_OK|X_OK)){
45 			fd = open(name, O_RDONLY);
46 			if(fd < 0)
47 				return -1;
48 			close(fd);
49 		}
50 		if(mode & W_OK){
51 			strncpy(tname, name, sizeof(tname)-9);
52 			strcat(tname, "/_AcChAcK");
53 			fd = creat(tname, 0666);
54 			if(fd < 0)
55 				return -1;
56 			close(fd);
57 			_REMOVE(tname);
58 		}
59 		return 0;
60 	}
61 	return -1;
62 }
63