9base

revived minimalist port of Plan 9 userland to Unix
git clone git://git.suckless.org/9base
Log | Files | Refs | README | LICENSE

listen1.c (1652B)


      1 #include <u.h>
      2 #include <libc.h>
      3 #include <auth.h>
      4 
      5 int verbose;
      6 int trusted;
      7 
      8 void
      9 usage(void)
     10 {
     11 	fprint(2, "usage: listen1 [-v] address cmd args...\n");
     12 	exits("usage");
     13 }
     14 
     15 char*
     16 remoteaddr(char *dir)
     17 {
     18 	static char buf[128];
     19 	char *p;
     20 	int n, fd;
     21 
     22 	snprint(buf, sizeof buf, "%s/remote", dir);
     23 	fd = open(buf, OREAD);
     24 	if(fd < 0)
     25 		return "";
     26 	n = read(fd, buf, sizeof(buf));
     27 	close(fd);
     28 	if(n > 0){
     29 		buf[n] = 0;
     30 		p = strchr(buf, '!');
     31 		if(p)
     32 			*p = 0;
     33 		return buf;
     34 	}
     35 	return "";
     36 }
     37 
     38 void
     39 main(int argc, char **argv)
     40 {
     41 	char dir[40], ndir[40];
     42 	int ctl, nctl, fd;
     43 
     44 	ARGBEGIN{
     45 	default:
     46 		usage();
     47 	case 't':
     48 		trusted = 1;
     49 		break;
     50 	case 'v':
     51 		verbose = 1;
     52 		break;
     53 	}ARGEND
     54 
     55 	if(argc < 2)
     56 		usage();
     57 
     58 	if(!verbose){
     59 		close(1);
     60 		fd = open("/dev/null", OWRITE);
     61 		if(fd != 1){
     62 			dup(fd, 1);
     63 			close(fd);
     64 		}
     65 	}
     66 
     67 	print("listen started\n");
     68 	ctl = announce(argv[0], dir);
     69 	if(ctl < 0)
     70 		sysfatal("announce %s: %r", argv[0]);
     71 
     72 	for(;;){
     73 		nctl = listen(dir, ndir);
     74 		if(nctl < 0)
     75 			sysfatal("listen %s: %r", argv[0]);
     76 
     77 		switch(rfork(RFFDG|RFPROC|RFNOWAIT|RFNOTEG)){
     78 		case -1:
     79 			close(nctl);
     80 			continue;
     81 		case 0:
     82 			fd = accept(nctl, ndir);
     83 			if(fd < 0){
     84 				fprint(2, "accept %s: can't open  %s/data: %r", argv[0], ndir);
     85 				_exits(0);
     86 			}
     87 			print("incoming call for %s from %s in %s\n", argv[0], remoteaddr(ndir), ndir);
     88 			close(ctl);
     89 			close(nctl);
     90 			/*putenv("net", ndir); */
     91 			/*sprint(data, "%s/data", ndir); */
     92 			/*bind(data, "/dev/cons", MREPL); */
     93 			dup(fd, 0);
     94 			dup(fd, 1);
     95 			dup(fd, 2);
     96 			close(fd);
     97 			exec(argv[1], argv+1);
     98 			fprint(2, "exec: %r");
     99 			exits(nil);
    100 		default:
    101 			close(nctl);
    102 			break;
    103 		}
    104 	}
    105 }