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 int
30 threadmaybackground(void)
31 {
32 return 1;
33 }
35 void
36 threadmain(int argc, char *argv[])
37 {
38 char buf[512];
39 int fd;
41 progname = "plumber";
43 ARGBEGIN{
44 case 'd':
45 debug = 1;
46 break;
47 case 'f':
48 foreground = 1;
49 break;
50 case 'p':
51 plumbfile = ARGF();
52 break;
53 }ARGEND
55 user = getuser();
56 home = getenv("HOME");
57 if(user==nil || home==nil)
58 error("can't initialize $user or $home: %r");
59 if(plumbfile == nil){
60 sprint(buf, "%s/lib/plumbing", home);
61 if(access(buf, 0) >= 0)
62 plumbfile = estrdup(buf);
63 else
64 plumbfile = unsharp("#9/plumb/initial.plumbing");
65 }
67 fd = open(plumbfile, OREAD);
68 if(fd < 0)
69 error("can't open rules file %s: %r", plumbfile);
70 if(setjmp(parsejmp))
71 error("parse error");
73 rules = readrules(plumbfile, fd);
74 close(fd);
76 /*
77 * Start all processes and threads from other proc
78 * so we (main pid) can return to user.
79 */
80 printerrors = 0;
81 makeports(rules);
82 startfsys(foreground);
83 threadexits(nil);
84 }
86 void
87 error(char *fmt, ...)
88 {
89 char buf[512];
90 va_list args;
92 va_start(args, fmt);
93 vseprint(buf, buf+sizeof buf, fmt, args);
94 va_end(args);
96 fprint(2, "%s: %s\n", progname, buf);
97 threadexitsall("error");
98 }
100 void
101 parseerror(char *fmt, ...)
103 char buf[512];
104 va_list args;
106 va_start(args, fmt);
107 vseprint(buf, buf+sizeof buf, fmt, args);
108 va_end(args);
110 if(printerrors){
111 printinputstack();
112 fprint(2, "%s\n", buf);
114 do; while(popinput());
115 lasterror = estrdup(buf);
116 longjmp(parsejmp, 1);
119 void*
120 emalloc(long n)
122 void *p;
124 p = malloc(n);
125 if(p == nil)
126 error("malloc failed: %r");
127 memset(p, 0, n);
128 return p;
131 void*
132 erealloc(void *p, long n)
134 p = realloc(p, n);
135 if(p == nil)
136 error("realloc failed: %r");
137 return p;
140 char*
141 estrdup(char *s)
143 char *t;
145 t = strdup(s);
146 if(t == nil)
147 error("estrdup failed: %r");
148 return t;