aboutsummaryrefslogtreecommitdiff
path: root/src/cmd/venti/writefile.c
blob: 2111712610830b5aadc8b3f964361ee2294cf791 (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
#include <u.h>
#include <libc.h>
#include <venti.h>
#include <libsec.h>
#include <thread.h>

enum
{
	Blocksize = 8192
};

int chatty;

void
usage(void)
{
	fprint(2, "usage: writefile [-v] [-h host] < data\n");
	threadexitsall("usage");
}

void
threadmain(int argc, char *argv[])
{
	int n;
	uchar score[VtScoreSize];
	uchar *buf;
	char *host;
	vlong off;
	VtEntry e;
	VtRoot root;
	VtCache *c;
	VtConn *z;
	VtFile *f;

	quotefmtinstall();
	fmtinstall('F', vtfcallfmt);
	fmtinstall('V', vtscorefmt);

	host = nil;
	ARGBEGIN{
	case 'V':
		chattyventi++;
		break;
	case 'h':
		host = EARGF(usage());
		break;
	case 'v':
		chatty++;
		break;
	default:
		usage();
		break;
	}ARGEND

	if(argc != 0)
		usage();

	buf = vtmallocz(Blocksize);

	z = vtdial(host);
	if(z == nil)
		sysfatal("could not connect to server: %r");

	if(vtconnect(z) < 0)
		sysfatal("vtconnect: %r");

	// write file
	c = vtcachealloc(z, Blocksize*32);
	if(c == nil)
		sysfatal("vtcachealloc: %r");
	f = vtfilecreateroot(c, Blocksize, Blocksize, VtDataType);
	if(f == nil)
		sysfatal("vtfilecreateroot: %r");
	off = 0;
	vtfilelock(f, VtOWRITE);
	while((n = read(0, buf, Blocksize)) > 0){
		if(vtfilewrite(f, buf, n, off) != n)
			sysfatal("vtfilewrite: %r");
		off += n;
		if(vtfileflushbefore(f, off) < 0)
			sysfatal("vtfileflushbefore: %r");
	}
	if(vtfileflush(f) < 0)
		sysfatal("vtfileflush: %r");
	if(vtfilegetentry(f, &e) < 0)
		sysfatal("vtfilegetentry: %r");
	vtfileunlock(f);
	
	// write directory entry
	memset(&root, 0, sizeof root);
	vtentrypack(&e, buf, 0);
	if(vtwrite(z, root.score, VtDirType, buf, VtEntrySize) < 0)
		sysfatal("vtwrite dir: %r");
	
	// write root
	strcpy(root.name, "data");
	strcpy(root.type, "file");
	root.blocksize = Blocksize;
	vtrootpack(&root, buf);
	if(vtwrite(z, score, VtRootType, buf, VtRootSize) < 0)
		sysfatal("vtwrite root: %r");
	
	print("file:%V\n", score);
	threadexitsall(0);
}