summaryrefslogtreecommitdiff
path: root/sys/src/ape/lib/ap/plan9/dirstat.c
blob: f054b4f6e920104db02cd3b8a31738ead1f10cb5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#include "lib.h"
#include <string.h>
#include <stdlib.h>
#include "sys9.h"
#include "dir.h"

enum
{
	DIRSIZE	= STATFIXLEN + 16 * 4		/* enough for encoded stat buf + some reasonable strings */
};

Dir*
_dirstat(char *name)
{
	Dir *d;
	uchar *buf;
	int n, nd, i;

	nd = DIRSIZE;
	for(i=0; i<2; i++){	/* should work by the second try */
		d = malloc(sizeof(Dir) + BIT16SZ +nd);
		if(d == nil)
			return nil;
		buf = (uchar*)&d[1];
		n = _STAT(name, buf, BIT16SZ+nd);
		if(n < BIT16SZ){
			free(d);
			return nil;
		}
		nd = GBIT16((uchar*)buf);	/* size needed to store whole stat buffer */
		if(nd <= n){
			_convM2D(buf, n, d, (char*)&d[1]);
			return d;
		}
		/* else sizeof(Dir)+BIT16SZ+nd is plenty */
		free(d);
	}
	return nil;
}

int
_dirwstat(char *name, Dir *d)
{
	uchar *buf;
	int r;

	r = _sizeD2M(d);
	buf = malloc(r);
	if(buf == nil)
		return -1;
	_convD2M(d, buf, r);
	r = _WSTAT(name, buf, r);
	free(buf);
	return r;
}

Dir*
_dirfstat(int fd)
{
	Dir *d;
	uchar *buf;
	int n, nd, i;

	nd = DIRSIZE;
	for(i=0; i<2; i++){	/* should work by the second try */
		d = malloc(sizeof(Dir) + nd);
		if(d == nil)
			return nil;
		buf = (uchar*)&d[1];
		n = _FSTAT(fd, buf, nd);
		if(n < BIT16SZ){
			free(d);
			return nil;
		}
		nd = GBIT16(buf);	/* size needed to store whole stat buffer */
		if(nd <= n){
			_convM2D(buf, n, d, (char*)&d[1]);
			return d;
		}
		/* else sizeof(Dir)+nd is plenty */
		free(d);
	}
	return nil;
}

int
_dirfwstat(int fd, Dir *d)
{
	uchar *buf;
	int r;

	r = _sizeD2M(d);
	buf = malloc(r);
	if(buf == nil)
		return -1;
	_convD2M(d, buf, r);
	r = _FWSTAT(fd, buf, r);
	free(buf);
	return r;
}

void
_nulldir(Dir *d)
{
	memset(d, ~0, sizeof(Dir));
	d->name = d->uid = d->gid = d->muid = "";
}