aboutsummaryrefslogtreecommitdiff
path: root/src/cmd/plumb/plumb.c
blob: d693ed58442318bc5d33c3f588126471e326c6c5 (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
108
109
110
111
112
113
114
115
116
117
118
119
120
#include <u.h>
#include <libc.h>
#include <plumb.h>
#include <thread.h>

char *plumbfile = nil;
Plumbmsg m;

void
usage(void)
{
	fprint(2, "usage: plumb [-p plumbfile] [-a 'attr=value ...'] [-s src] [-d dst] [-t type] [-w wdir] -i | data1\n");
	exits("usage");
}

void
gather(void)
{
	char buf[8192];
	int n;

	m.ndata = 0;
	m.data = nil;
	while((n = read(0, buf, sizeof buf)) > 0){
		m.data = realloc(m.data, m.ndata+n);
		if(m.data == nil){
			fprint(2, "plumb: alloc failed: %r\n");
			exits("alloc");
		}
		memmove(m.data+m.ndata, buf, n);
		m.ndata += n;
	}
	if(n < 0){
		fprint(2, "plumb: i/o error on input: %r\n");
		exits("read");
	}
}

void
threadmain(int argc, char *argv[])
{
	char buf[1024], *p;
	int fd, i, input;

	input = 0;
	m.src = "plumb";
	m.dst = nil;
	m.wdir = getwd(buf, sizeof buf);
	m.type = "text";
	m.attr = nil;
	ARGBEGIN{
	case 'a':
		p = ARGF();
		if(p == nil)
			usage();
		m.attr = plumbaddattr(m.attr, plumbunpackattr(p));
		break;
	case 'd':
		m.dst = ARGF();
		if(m.dst == nil)
			usage();
		break;
	case 'i':
		input++;
		break;
	case 't':
	case 'k':	/* for backwards compatibility */
		m.type = ARGF();
		if(m.type == nil)
			usage();
		break;
	case 'p':
		plumbfile = ARGF();
		if(plumbfile == nil)
			usage();
		break;
	case 's':
		m.src = ARGF();
		if(m.src == nil)
			usage();
		break;
	case 'w':
		m.wdir = ARGF();
		if(m.wdir == nil)
			usage();
		break;
	}ARGEND

	if((input && argc>0) || (!input && argc<1))
		usage();
	if(plumbfile != nil)
		fd = open(plumbfile, OWRITE);
	else
		fd = plumbopen("send", OWRITE);
	if(fd < 0){
		fprint(2, "plumb: can't open plumb file: %r\n");
		exits("open");
	}
	if(input){
		gather();
		if(plumblookup(m.attr, "action") == nil)
			m.attr = plumbaddattr(m.attr, plumbunpackattr("action=showdata"));
		if(plumbsend(fd, &m) < 0){
			fprint(2, "plumb: can't send message: %r\n");
			exits("error");
		}
		exits(nil);
	}
	for(i=0; i<argc; i++){
		if(input == 0){
			m.data = argv[i];
			m.ndata = -1;
		}
		if(plumbsend(fd, &m) < 0){
			fprint(2, "plumb: can't send message: %r\n");
			exits("error");
		}
	}
	threadexitsall(nil);
}