aboutsummaryrefslogtreecommitdiff
path: root/src/cmd/plumb/plumber.c
blob: c99282f02da0c4a939fb49ae3ec32c49b18fc5a5 (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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
#include <u.h>
#include <libc.h>
#include <regexp.h>
#include <thread.h>
#include <plumb.h>
#include <fcall.h>
#include "plumber.h"

int debug;
int foreground=0;
char	*plumbfile;
char *user;
char *home;
char *progname;
Ruleset **rules;
int	printerrors=1;
jmp_buf	parsejmp;
char	*lasterror;

void
makeports(Ruleset *rules[])
{
	int i;

	for(i=0; rules[i]; i++)
		addport(rules[i]->port);
}

void
threadmain(int argc, char *argv[])
{
	char buf[512];
	int fd;

	progname = "plumber";

	ARGBEGIN{
	case 'd':
		debug = 1;
		break;
	case 'f':
		foreground = 1;
		break;
	case 'p':
		plumbfile = ARGF();
		break;
	}ARGEND

	user = getuser();
	home = getenv("HOME");
	if(user==nil || home==nil)
		error("can't initialize $user or $home: %r");
	if(plumbfile == nil){
		sprint(buf, "%s/lib/plumbing", home);
		if(access(buf, 0) >= 0)
			plumbfile = estrdup(buf);
		else
			plumbfile = unsharp("#9/plumb/initial.plumbing");
	}

	fd = open(plumbfile, OREAD);
	if(fd < 0)
		error("can't open rules file %s: %r", plumbfile);
	if(setjmp(parsejmp))
		error("parse error");

	rules = readrules(plumbfile, fd);
	close(fd);

	/*
	 * Start all processes and threads from other proc
	 * so we (main pid) can return to user.
	 */
	printerrors = 0;
	makeports(rules);
	startfsys(foreground);
	threadexits(nil);
}

void
error(char *fmt, ...)
{
	char buf[512];
	va_list args;

	va_start(args, fmt);
	vseprint(buf, buf+sizeof buf, fmt, args);
	va_end(args);

	fprint(2, "%s: %s\n", progname, buf);
	threadexitsall("error");
}

void
parseerror(char *fmt, ...)
{
	char buf[512];
	va_list args;

	va_start(args, fmt);
	vseprint(buf, buf+sizeof buf, fmt, args);
	va_end(args);

	if(printerrors){
		printinputstack();
		fprint(2, "%s\n", buf);
	}
	do; while(popinput());
	lasterror = estrdup(buf);
	longjmp(parsejmp, 1);
}

void*
emalloc(long n)
{
	void *p;

	p = malloc(n);
	if(p == nil)
		error("malloc failed: %r");
	memset(p, 0, n);
	return p;
}

void*
erealloc(void *p, long n)
{
	p = realloc(p, n);
	if(p == nil)
		error("realloc failed: %r");
	return p;
}

char*
estrdup(char *s)
{
	char *t;

	t = strdup(s);
	if(t == nil)
		error("estrdup failed: %r");
	return t;
}