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 int foreground=0;
11 char *plumbfile;
12 char *user;
13 char *home;
14 char *progname;
15 Ruleset **rules;
16 int printerrors=1;
17 jmp_buf parsejmp;
18 char *lasterror;
20 void
21 makeports(Ruleset *rules[])
22 {
23 int i;
25 for(i=0; rules[i]; i++)
26 addport(rules[i]->port);
27 }
29 void
30 threadmain(int argc, char *argv[])
31 {
32 char buf[512];
33 int fd;
35 progname = "plumber";
37 ARGBEGIN{
38 case 'd':
39 debug = 1;
40 break;
41 case 'f':
42 foreground = 1;
43 break;
44 case 'p':
45 plumbfile = ARGF();
46 break;
47 }ARGEND
49 user = getuser();
50 home = getenv("HOME");
51 if(user==nil || home==nil)
52 error("can't initialize $user or $home: %r");
53 if(plumbfile == nil){
54 sprint(buf, "%s/lib/plumbing", home);
55 if(access(buf, 0) >= 0)
56 plumbfile = estrdup(buf);
57 else
58 plumbfile = unsharp("#9/plumb/initial.plumbing");
59 }
61 fd = open(plumbfile, OREAD);
62 if(fd < 0)
63 error("can't open rules file %s: %r", plumbfile);
64 if(setjmp(parsejmp))
65 error("parse error");
67 rules = readrules(plumbfile, fd);
68 close(fd);
70 /*
71 * Start all processes and threads from other proc
72 * so we (main pid) can return to user.
73 */
74 printerrors = 0;
75 makeports(rules);
76 startfsys(foreground);
77 threadexits(nil);
78 }
80 void
81 error(char *fmt, ...)
82 {
83 char buf[512];
84 va_list args;
86 va_start(args, fmt);
87 vseprint(buf, buf+sizeof buf, fmt, args);
88 va_end(args);
90 fprint(2, "%s: %s\n", progname, buf);
91 threadexitsall("error");
92 }
94 void
95 parseerror(char *fmt, ...)
96 {
97 char buf[512];
98 va_list args;
100 va_start(args, fmt);
101 vseprint(buf, buf+sizeof buf, fmt, args);
102 va_end(args);
104 if(printerrors){
105 printinputstack();
106 fprint(2, "%s\n", buf);
108 do; while(popinput());
109 lasterror = estrdup(buf);
110 longjmp(parsejmp, 1);
113 void*
114 emalloc(long n)
116 void *p;
118 p = malloc(n);
119 if(p == nil)
120 error("malloc failed: %r");
121 memset(p, 0, n);
122 return p;
125 void*
126 erealloc(void *p, long n)
128 p = realloc(p, n);
129 if(p == nil)
130 error("realloc failed: %r");
131 return p;
134 char*
135 estrdup(char *s)
137 char *t;
139 t = strdup(s);
140 if(t == nil)
141 error("estrdup failed: %r");
142 return t;