Blob


1 #include <u.h>
2 #include <libc.h>
3 #include <ctype.h>
5 static int
6 isme(char *uid)
7 {
8 int n;
9 char *p;
11 n = strtol(uid, &p, 10);
12 if(*p == 0 && p > uid)
13 return n == getuid();
14 return strcmp(getuser(), uid) == 0;
15 }
16 /*
17 * Absent other hints, it works reasonably well to use
18 * the X11 display name as the name space identifier.
19 * This is how sam's B has worked since the early days.
20 * Since most programs using name spaces are also using X,
21 * this still seems reasonable. Terminal-only sessions
22 * can set $NAMESPACE.
23 */
24 static char*
25 nsfromdisplay(void)
26 {
27 int fd;
28 Dir *d;
29 char *disp, *p;
31 if((disp = getenv("DISPLAY")) == nil){
32 werrstr("$DISPLAY not set");
33 return nil;
34 }
36 /* canonicalize: xxx:0.0 => xxx:0 */
37 p = strrchr(disp, ':');
38 if(p){
39 p++;
40 while(isdigit((uchar)*p))
41 p++;
42 if(strcmp(p, ".0") == 0)
43 *p = 0;
44 }
46 p = smprint("/tmp/ns.%s.%s", getuser(), disp);
47 free(disp);
48 if(p == nil){
49 werrstr("out of memory");
50 return p;
51 }
52 if((fd=create(p, OREAD, DMDIR|0700)) >= 0){
53 close(fd);
54 return p;
55 }
56 if((d = dirstat(p)) == nil){
57 free(d);
58 werrstr("stat %s: %r", p);
59 free(p);
60 return nil;
61 }
62 if((d->mode&0777) != 0700 || !isme(d->uid)){
63 werrstr("bad name space dir %s", p);
64 free(p);
65 free(d);
66 return nil;
67 }
68 free(d);
69 return p;
70 }
72 char*
73 getns(void)
74 {
75 char *ns;
77 ns = getenv("NAMESPACE");
78 if(ns == nil)
79 ns = nsfromdisplay();
80 if(ns == nil){
81 werrstr("$NAMESPACE not set, %r");
82 return nil;
83 }
84 return ns;
85 }