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 void20 makeports(Ruleset *rules[])21 {22 int i;24 for(i=0; rules[i]; i++)25 addport(rules[i]->port);26 }28 void29 threadmain(int argc, char *argv[])30 {31 char buf[512];32 int fd, dofork;34 progname = "plumber";35 dofork = 1;37 ARGBEGIN{38 case 'd':39 debug = 1;40 break;41 case 'f':42 dofork = 0;43 break;44 case 'p':45 plumbfile = ARGF();46 break;47 }ARGEND49 user = getuser();50 home = getenv("home");51 if(home == nil)52 home = getenv("HOME");53 if(user==nil || home==nil)54 error("can't initialize $user or $home: %r");55 if(plumbfile == nil){56 sprint(buf, "%s/lib/plumbing", home);57 plumbfile = estrdup(buf);58 }60 fd = open(plumbfile, OREAD);61 if(fd < 0)62 error("can't open rules file %s: %r", plumbfile);63 if(setjmp(parsejmp))64 error("parse error");66 rules = readrules(plumbfile, fd);67 close(fd);69 /*70 * Start all processes and threads from other proc71 * so we (main pid) can return to user.72 */73 if(dofork)74 switch(fork()){75 case -1:76 sysfatal("fork: %r");77 case 0:78 break;79 default:80 _exit(0);81 }83 printerrors = 0;84 makeports(rules);85 startfsys();86 }88 void89 error(char *fmt, ...)90 {91 char buf[512];92 va_list args;94 va_start(args, fmt);95 vseprint(buf, buf+sizeof buf, fmt, args);96 va_end(args);98 fprint(2, "%s: %s\n", progname, buf);99 threadexitsall("error");100 }102 void103 parseerror(char *fmt, ...)104 {105 char buf[512];106 va_list args;108 va_start(args, fmt);109 vseprint(buf, buf+sizeof buf, fmt, args);110 va_end(args);112 if(printerrors){113 printinputstack();114 fprint(2, "%s\n", buf);115 }116 do; while(popinput());117 lasterror = estrdup(buf);118 longjmp(parsejmp, 1);119 }121 void*122 emalloc(long n)123 {124 void *p;126 p = malloc(n);127 if(p == nil)128 error("malloc failed: %r");129 memset(p, 0, n);130 return p;131 }133 void*134 erealloc(void *p, long n)135 {136 p = realloc(p, n);137 if(p == nil)138 error("realloc failed: %r");139 return p;140 }142 char*143 estrdup(char *s)144 {145 char *t;147 t = strdup(s);148 if(t == nil)149 error("estrdup failed: %r");150 return t;151 }