Blob


1 #include <u.h>
2 #include <libc.h>
3 #include <regexp.h>
4 #include <thread.h>
5 #include <plumb.h>
6 #include <fcall.h>
7 #include "plumber.h"
9 int debug;
10 char *plumbfile;
11 char *user;
12 char *home;
13 char *progname;
14 Ruleset **rules;
15 int printerrors=1;
16 jmp_buf parsejmp;
17 char *lasterror;
19 void
20 makeports(Ruleset *rules[])
21 {
22 int i;
24 for(i=0; rules[i]; i++)
25 addport(rules[i]->port);
26 }
28 void
29 threadmain(int argc, char *argv[])
30 {
31 char buf[512];
32 int fd;
34 progname = "plumber";
36 ARGBEGIN{
37 case 'd':
38 debug = 1;
39 break;
40 case 'p':
41 plumbfile = ARGF();
42 break;
43 }ARGEND
45 user = getuser();
46 home = getenv("home");
47 if(home == nil)
48 home = getenv("HOME");
49 if(user==nil || home==nil)
50 error("can't initialize $user or $home: %r");
51 if(plumbfile == nil){
52 sprint(buf, "%s/lib/plumbing", home);
53 if(access(buf, 0) >= 0)
54 plumbfile = estrdup(buf);
55 else
56 plumbfile = unsharp("#9/plumb/initial.plumbing");
57 }
59 fd = open(plumbfile, OREAD);
60 if(fd < 0)
61 error("can't open rules file %s: %r", plumbfile);
62 if(setjmp(parsejmp))
63 error("parse error");
65 rules = readrules(plumbfile, fd);
66 close(fd);
68 /*
69 * Start all processes and threads from other proc
70 * so we (main pid) can return to user.
71 */
72 printerrors = 0;
73 makeports(rules);
74 startfsys();
75 threadexits(nil);
76 }
78 void
79 error(char *fmt, ...)
80 {
81 char buf[512];
82 va_list args;
84 va_start(args, fmt);
85 vseprint(buf, buf+sizeof buf, fmt, args);
86 va_end(args);
88 fprint(2, "%s: %s\n", progname, buf);
89 threadexitsall("error");
90 }
92 void
93 parseerror(char *fmt, ...)
94 {
95 char buf[512];
96 va_list args;
98 va_start(args, fmt);
99 vseprint(buf, buf+sizeof buf, fmt, args);
100 va_end(args);
102 if(printerrors){
103 printinputstack();
104 fprint(2, "%s\n", buf);
106 do; while(popinput());
107 lasterror = estrdup(buf);
108 longjmp(parsejmp, 1);
111 void*
112 emalloc(long n)
114 void *p;
116 p = malloc(n);
117 if(p == nil)
118 error("malloc failed: %r");
119 memset(p, 0, n);
120 return p;
123 void*
124 erealloc(void *p, long n)
126 p = realloc(p, n);
127 if(p == nil)
128 error("realloc failed: %r");
129 return p;
132 char*
133 estrdup(char *s)
135 char *t;
137 t = strdup(s);
138 if(t == nil)
139 error("estrdup failed: %r");
140 return t;