2 * cpu.c - Make a connection to a cpu server
4 * Invoked by listen as 'cpu -R | -N service net netdir'
5 * by users as 'cpu [-h system] [-c cmd args ...]'
17 void remoteside(void);
18 void fatal(char*, ...);
19 void lclnoteproc(int);
20 void rmtnoteproc(void);
21 void catcher(void*, char*);
23 void writestr(int, char*, char*, int);
24 int readstr(int, char*, int);
25 char *rexcall(int*, char*, char*);
39 char *srvname = "ncpu";
40 char *exportfs = "/bin/exportfs";
41 char *ealgs = "rc4_256 sha1";
43 /* message size for exportfs; may be larger so we can do big graphics in CPU window */
44 int msgsize = Maxfdata+IOHDRSZ;
46 /* encryption mechanisms */
47 static int clear(int);
49 int (*encryption)(int) = clear;
51 /* authentication mechanisms */
52 static int netkeyauth(int);
53 static int netkeysrvauth(int, char*);
54 static int p9auth(int);
55 static int srvp9auth(int, char*);
56 static int noauth(int);
57 static int srvnoauth(int, char*);
59 typedef struct AuthMethod AuthMethod;
61 char *name; /* name of method */
62 int (*cf)(int); /* client side authentication */
63 int (*sf)(int, char*); /* server side authentication */
65 { "p9", p9auth, srvp9auth,},
66 { "netkey", netkeyauth, netkeysrvauth,},
67 { "none", noauth, srvnoauth,},
70 AuthMethod *am = authmethod; /* default is p9 */
74 char *aan = "/bin/aan";
75 char *anstring = "tcp!*!0";
78 int filter(int fd, char *host);
83 fprint(2, "usage: cpu [-p] [-h system] [-u user] [-a authmethod] "
84 "[-e 'crypt hash'] [-k keypattern] [-P patternfile] "
85 "[-c cmd arg ...]\n");
90 * reading /proc/pid/args yields either "name args" or "name [display args]",
91 * so return only args or display args.
100 snprint(buf, sizeof buf, "#p/%d/args", getpid());
101 if((fd = open(buf, OREAD)) < 0)
104 n = read(fd, buf, sizeof buf-1);
108 if ((lp = strchr(buf, '[')) == nil || (rp = strrchr(buf, ']')) == nil) {
109 lp = strchr(buf, ' ');
120 * based on libthread's threadsetname, but drags in less library code.
121 * actually just sets the arguments displayed.
124 procsetname(char *fmt, ...)
132 cmdname = vsmprint(fmt, arg);
136 snprint(buf, sizeof buf, "#p/%d/args", getpid());
137 if((fd = open(buf, OWRITE)) >= 0){
138 write(fd, cmdname, strlen(cmdname)+1);
145 main(int argc, char **argv)
147 char dat[MaxStr], buf[MaxStr], cmd[MaxStr], *p, *s, *err;
148 int ac, fd, ms, data;
152 origargs = procgetname();
153 /* see if we should use a larger message size */
154 fd = open("/dev/draw", OREAD);
157 if(msgsize < ms+IOHDRSZ)
158 msgsize = ms+IOHDRSZ;
164 fatal("can't read user name: %r");
169 fatal("unknown auth method %s", p);
172 ealgs = EARGF(usage());
173 if(*ealgs == 0 || strcmp(ealgs, "clear") == 0)
180 /* ignored but accepted for compatibility */
183 /* must be specified before -R/-O */
187 anstring = EARGF(usage());
189 case 'R': /* From listen */
193 system = EARGF(usage());
201 s = seprint(s, cmd+sizeof(cmd), " %q", p);
204 keyspec = smprint("%s %s", keyspec, EARGF(usage()));
207 patternfile = EARGF(usage());
210 user = EARGF(usage());
211 keyspec = smprint("%s user=%s", keyspec, user);
231 if(err = rexcall(&data, system, srvname))
232 fatal("%s: %s: %r", err, system);
234 procsetname("%s", origargs);
235 /* Tell the remote side the command to execute and where our working directory is */
237 writestr(data, cmd, "command", 0);
238 if(getwd(dat, sizeof(dat)) == 0)
239 writestr(data, "NO", "dir", 0);
241 writestr(data, dat, "dir", 0);
243 /* start up a process to pass along notes */
247 * Wait for the other end to execute and start our file service
250 if(readstr(data, buf, sizeof(buf)) < 0)
251 fatal("waiting for FS: %r");
252 if(strncmp("FS", buf, 2) != 0) {
253 print("remote cpu: %s", buf);
257 /* Begin serving the gnot namespace */
262 sprint(buf, "%d", msgsize);
269 if(patternfile != nil){
271 av[ac++] = patternfile;
275 fatal("starting exportfs: %r");
279 fatal(char *fmt, ...)
285 vsnprint(buf, sizeof(buf), fmt, arg);
287 fprint(2, "cpu: %s\n", buf);
288 syslog(0, "cpu", "%s", buf);
292 char *negstr = "negotiating authentication method";
294 /* Invoked with stdin and stdout connected to the network connection */
298 char user[MaxStr], buf[MaxStr], xdir[MaxStr], cmd[MaxStr];
299 int i, n, fd, badchdir, gotcmd;
302 putenv("service", "cpu");
305 /* negotiate authentication mechanism */
306 n = readstr(fd, cmd, sizeof(cmd));
308 fatal("authenticating: %r");
310 if(strcmp(cmd, "aan") == 0){
312 writestr(fd, "", nil, 1);
313 n = readstr(fd, cmd, sizeof(cmd));
315 fatal("authenticating: %r");
317 if(setamalg(cmd) < 0 || (nflag == 0 && am->sf == srvnoauth)) {
318 writestr(fd, "unsupported auth method", nil, 0);
319 fatal("bad auth method %s", cmd);
321 writestr(fd, "", "", 1);
323 if((fd = (*am->sf)(fd, user)) < 0)
324 fatal("srvauth: %r");
325 if((fd = filter(fd, nil)) < 0)
327 if((fd = encryption(fd)) < 0)
328 fatal("encrypt: %r");
330 /* Now collect invoking cpu's current directory or possibly a command */
332 if(readstr(fd, xdir, sizeof(xdir)) < 0)
333 fatal("dir/cmd: %r");
335 strcpy(cmd, &xdir[1]);
337 if(readstr(fd, xdir, sizeof(xdir)) < 0)
341 /* Establish the new process at the current working directory of the gnot */
343 if(strcmp(xdir, "NO") != 0)
347 /* Start the gnot serving its namespace */
348 writestr(fd, "FS", "FS", 0);
349 writestr(fd, "/", "exportfs dir", 0);
351 n = read(fd, buf, sizeof(buf));
352 if(n != 2 || buf[0] != 'O' || buf[1] != 'K')
353 exits("remote tree");
355 /* make sure buffers are big by doing fversion explicitly; pick a huge number; other side will trim */
356 strcpy(buf, VERSION9P);
357 if(fversion(fd, 64*1024, buf, sizeof buf) < 0)
358 exits("fversion failed");
359 if(mount(fd, -1, "/mnt/term", MCREATE|MREPL, "") < 0)
360 exits("mount failed");
364 /* the remote noteproc uses the mount so it must follow it */
367 for(i = 0; i < 3; i++)
370 if(open("/mnt/term/dev/cons", OREAD) != 0)
372 if(open("/mnt/term/dev/cons", OWRITE) != 1)
373 exits("open stdout");
377 print("cpu: failed to chdir to '%s'\n", xdir);
380 execl("/bin/rc", "rc", "-lc", cmd, nil);
382 execl("/bin/rc", "rc", "-li", nil);
383 fatal("exec shell: %r");
387 rexcall(int *fd, char *host, char *service)
394 na = netmkaddr(host, 0, service);
395 procsetname("dialing %s", na);
396 if((*fd = dial(na, 0, 0, 0)) < 0)
399 /* negotiate aan filter extension */
401 writestr(*fd, "aan", "negotiating aan", 0);
402 n = readstr(*fd, err, sizeof err);
404 return "negotiating aan";
406 errstr(err, sizeof err);
411 /* negotiate authentication mechanism */
413 snprint(msg, sizeof(msg), "%s %s", am->name, ealgs);
415 snprint(msg, sizeof(msg), "%s", am->name);
416 procsetname("writing %s", msg);
417 writestr(*fd, msg, negstr, 0);
418 procsetname("awaiting auth method");
419 n = readstr(*fd, err, sizeof err);
423 errstr(err, sizeof err);
428 procsetname("%s: auth via %s", origargs, am->name);
429 if((*fd = (*am->cf)(*fd)) < 0)
430 return "can't authenticate";
431 if((*fd = filter(*fd, system)) < 0)
432 return "can't filter";
433 if((*fd = encryption(*fd)) < 0)
434 return "can't encrypt";
439 writestr(int fd, char *str, char *thing, int ignore)
444 n = write(fd, str, l+1);
446 fatal("writing network: %s: %r", thing);
450 readstr(int fd, char *str, int len)
455 n = read(fd, str, 1);
467 readln(char *buf, int n)
472 n--; /* room for \0 */
475 if(read(0, p, 1) != 1)
477 if(*p == '\n' || *p == '\r')
486 * user level challenge/response
494 strecpy(chall, chall+sizeof chall, getuser());
495 print("user[%s]: ", chall);
496 if(readln(resp, sizeof(resp)) < 0)
500 writestr(fd, chall, "challenge/response", 1);
503 if(readstr(fd, chall, sizeof chall) < 0)
507 print("challenge: %s\nresponse: ", chall);
508 if(readln(resp, sizeof(resp)) < 0)
510 writestr(fd, resp, "challenge/response", 1);
516 netkeysrvauth(int fd, char *user)
523 if(readstr(fd, user, MaxStr) < 0)
528 for(tries = 0; tries < 10; tries++){
529 if((ch = auth_challenge("proto=p9cr role=server user=%q", user)) == nil)
531 writestr(fd, ch->chal, "challenge", 1);
532 if(readstr(fd, response, sizeof response) < 0)
535 ch->nresp = strlen(response);
536 if((ai = auth_response(ch)) != nil)
542 writestr(fd, "", "challenge", 1);
543 if(auth_chuid(ai, 0) < 0)
555 static char sslsecret[2][21];
560 return pushssl(fd, ealgs, sslsecret[0], sslsecret[1], nil);
564 mksecret(char *t, uchar *f)
566 sprint(t, "%2.2ux%2.2ux%2.2ux%2.2ux%2.2ux%2.2ux%2.2ux%2.2ux%2.2ux%2.2ux",
567 f[0], f[1], f[2], f[3], f[4], f[5], f[6], f[7], f[8], f[9]);
571 sslsetup(int fd, uchar *secret, int nsecret, int isclient)
573 uchar key[16], digest[SHA1dlen];
580 werrstr("secret too small to ssl");
583 memmove(key+4, secret, 8);
585 /* exchange random numbers */
589 for(i = 0; i < 4; i++)
591 if(write(fd, key, 4) != 4)
593 if(readn(fd, key+12, 4) != 4)
596 for(i = 0; i < 4; i++)
598 if(readn(fd, key, 4) != 4)
600 if(write(fd, key+12, 4) != 4)
604 /* scramble into two secrets */
605 sha1(key, sizeof(key), digest, nil);
606 mksecret(sslsecret[isclient == 0], digest);
607 mksecret(sslsecret[isclient != 0], digest+10);
609 encryption = sslencrypt;
615 * plan9 authentication followed by rc4 encryption
622 ai = auth_proxy(fd, auth_getkey, "proto=p9any role=client %s", keyspec);
625 fd = sslsetup(fd, ai->secret, ai->nsecret, 1);
638 srvnoauth(int fd, char *user)
640 strecpy(user, user+MaxStr, getuser());
647 srvp9auth(int fd, char *user)
651 ai = auth_proxy(fd, nil, "proto=p9any role=server %s", keyspec);
654 if(auth_chuid(ai, nil) < 0)
656 snprint(user, MaxStr, "%s", ai->cuid);
657 fd = sslsetup(fd, ai->secret, ai->nsecret, 0);
663 * set authentication mechanism
668 for(am = authmethod; am->name != nil; am++)
669 if(strcmp(am->name, name) == 0)
676 * set authentication mechanism and encryption/hash algs
681 ealgs = strchr(s, ' ');
688 filter(int fd, char *host)
690 char addr[128], buf[256], *s, *file, *argv[16];
691 int p[2], lfd, flags, len, argc;
695 procsetname("filter %s", filterp);
696 flags = RFNOWAIT|RFPROC|RFMEM|RFFDG|RFREND;
699 if(announce(anstring, addr) < 0)
700 fatal("filter: Cannot announce %s: %r", anstring);
701 snprint(buf, sizeof(buf), "%s/local", addr);
702 if((lfd = open(buf, OREAD)) < 0)
703 fatal("filter: Cannot open %s: %r", buf);
704 if((len = read(lfd, buf, sizeof buf - 1)) < 0)
705 fatal("filter: Cannot read %s: %r", buf);
708 if(s = strchr(buf, '\n'))
710 if(write(fd, buf, len) != len)
711 fatal("filter: cannot write port; %r");
715 if((len = read(fd, buf, sizeof buf - 1)) < 0)
716 fatal("filter: cannot read port; %r");
718 if((s = strrchr(buf, '!')) == nil)
719 fatal("filter: malformed remote port: %s", buf);
720 strecpy(addr, addr+sizeof(addr), netmkaddr(host, "tcp", s+1));
721 strecpy(strrchr(addr, '!'), addr+sizeof(addr), s);
724 snprint(buf, sizeof(buf), "%s", filterp);
725 if((argc = tokenize(buf, argv, nelem(argv)-3)) <= 0)
726 fatal("filter: empty command");
732 if(s = strrchr(argv[0], '/'))
736 fatal("filter: pipe; %r");
738 switch(rfork(flags)) {
740 fatal("filter: rfork; %r\n");
742 if (dup(p[0], 1) < 0)
743 fatal("filter: Cannot dup to 1; %r");
744 if (dup(p[0], 0) < 0)
745 fatal("filter: Cannot dup to 0; %r");
749 fatal("filter: exec; %r");
757 char *rmtnotefile = "/mnt/term/dev/cpunote";
760 * loop reading /mnt/term/dev/note looking for notes.
761 * The child returns to start the shell.
766 int n, fd, pid, notepid;
769 /* new proc returns to start shell */
770 pid = rfork(RFPROC|RFFDG|RFNOTEG|RFNAMEG|RFMEM);
773 syslog(0, "cpu", "cpu -R: can't start noteproc: %r");
779 /* new proc reads notes from other side and posts them to shell */
780 switch(notepid = rfork(RFPROC|RFFDG|RFMEM)){
782 syslog(0, "cpu", "cpu -R: can't start wait proc: %r");
785 fd = open(rmtnotefile, OREAD);
790 n = read(fd, buf, sizeof(buf)-1);
792 postnote(PNGROUP, pid, "hangup");
796 postnote(PNGROUP, pid, buf);
800 /* original proc waits for shell proc to die and kills note proc */
803 if(n < 0 || n == pid)
806 postnote(PNPROC, notepid, "kill");
824 [Qdir] { ".", {Qdir, 0, QTDIR}, DMDIR|0555 },
825 [Qcpunote] { "cpunote", {Qcpunote, 0}, 0444 },
828 typedef struct Note Note;
835 typedef struct Request Request;
842 typedef struct Fid Fid;
853 Note *nfirst, *nlast;
854 Request *rfirst, *rlast;
858 fsreply(int fd, Fcall *f)
860 uchar buf[IOHDRSZ+Maxfdata];
864 fprint(2, "notefs: <-%F\n", f);
865 n = convS2M(f, buf, sizeof buf);
867 if(write(fd, buf, n) != n){
875 /* match a note read request with a note, reply to the request */
887 if(rp == nil || np == nil){
891 nfs.rfirst = rp->next;
892 nfs.nfirst = np->next;
896 rp->f.count = strlen(np->msg);
897 rp->f.data = np->msg;
898 rv = fsreply(fd, &rp->f);
913 for(l = &nfs.rfirst; *l != nil; l = &(*l)->next){
915 if(rp->f.tag == tag){
931 for(i = 0; i < Nfid; i++){
932 if(freefid < 0 && fids[i].file < 0)
934 if(fids[i].fid == fid)
938 fids[freefid].fid = fid;
939 return &fids[freefid];
945 fsstat(int fd, Fid *fid, Fcall *f)
950 memset(&d, 0, sizeof(d));
951 d.name = fstab[fid->file].name;
955 d.qid = fstab[fid->file].qid;
956 d.mode = fstab[fid->file].perm;
957 d.atime = d.mtime = time(0);
959 f->nstat = convD2M(&d, statbuf, sizeof statbuf);
960 return fsreply(fd, f);
964 fsread(int fd, Fid *fid, Fcall *f)
974 if(f->offset == 0 && f->count >0){
975 memset(&d, 0, sizeof(d));
976 d.name = fstab[Qcpunote].name;
980 d.qid = fstab[Qcpunote].qid;
981 d.mode = fstab[Qcpunote].perm;
982 d.atime = d.mtime = time(0);
983 f->count = convD2M(&d, buf, sizeof buf);
984 f->data = (char*)buf;
987 return fsreply(fd, f);
989 rp = mallocz(sizeof(*rp), 1);
994 if(nfs.rfirst == nil)
997 nfs.rlast->next = rp;
1004 char Eperm[] = "permission denied";
1005 char Enofile[] = "out of files";
1006 char Enotdir[] = "not a directory";
1011 uchar buf[IOHDRSZ+Maxfdata];
1019 fmtinstall('F', fcallfmt);
1021 for(n = 0; n < Nfid; n++){
1028 n = read9pmsg(fd, buf, sizeof(buf));
1029 if(n <= 0 || convM2S(buf, n, &f) != n)
1032 fprint(2, "notefs: ->%F\n", &f);
1034 fid = getfid(f.fid);
1045 f.ename = "unknown type";
1051 if(f.msize > IOHDRSZ+Maxfdata)
1052 f.msize = IOHDRSZ+Maxfdata;
1056 f.ename = "authentication not required";
1059 f.qid = fstab[Qdir].qid;
1064 if(f.newfid != f.fid){
1065 nfid = getfid(f.newfid);
1068 nfid->file = fid->file;
1071 for(i=0; i<f.nwname && i<MAXWELEM; i++){
1072 if(fid->file != Qdir){
1077 if(strcmp(f.wname[i], "..") == 0){
1078 wqid[i] = fstab[Qdir].qid;
1081 if(strcmp(f.wname[i], "cpunote") != 0){
1084 f.ename = "file does not exist";
1088 fid->file = Qcpunote;
1089 wqid[i] = fstab[Qcpunote].qid;
1091 if(nfid != nil && (f.type == Rerror || i < f.nwname))
1093 if(f.type != Rerror){
1095 for(i=0; i<f.nwqid; i++)
1096 f.wqid[i] = wqid[i];
1100 if(f.mode != OREAD){
1105 fid->omode = f.mode;
1106 if(fid->file == Qcpunote)
1108 f.qid = fstab[fid->file].qid;
1112 if(fsread(fd, fid, &f) < 0)
1117 if(fid->omode != -1 && fid->file == Qcpunote){
1119 if(ncpunote == 0) /* remote side is done */
1126 if(fsstat(fd, fid, &f) < 0)
1139 if(fsreply(fd, &f) < 0)
1144 fprint(2, "notefs exiting: %r\n");
1146 postnote(PNGROUP, exportpid, "kill");
1148 fprint(2, "postnote PNGROUP %d: %r\n", exportpid);
1152 char notebuf[ERRMAX];
1155 catcher(void*, char *text)
1160 if(n >= sizeof(notebuf))
1161 n = sizeof(notebuf)-1;
1162 memmove(notebuf, text, n);
1168 * mount in /dev a note file for the remote side to read.
1171 lclnoteproc(int netfd)
1179 fprint(2, "cpu: can't start note proc: pipe: %r\n");
1183 /* new proc mounts and returns to start exportfs */
1184 switch(pid = rfork(RFPROC|RFNAMEG|RFFDG|RFMEM)){
1189 fprint(2, "cpu: can't start note proc: rfork: %r\n");
1193 if(mount(pfd[1], -1, "/dev", MBEFORE, "") < 0)
1194 fprint(2, "cpu: can't mount note proc: %r\n");
1202 /* new proc listens for note file system rpc's */
1203 switch(rfork(RFPROC|RFNAMEG|RFMEM)){
1205 fprint(2, "cpu: can't start note proc: rfork1: %r\n");
1212 /* original proc waits for notes */
1222 np = mallocz(sizeof(Note), 1);
1224 strcpy(np->msg, notebuf);
1226 if(nfs.nfirst == nil)
1229 nfs.nlast->next = np;
1235 } else if(w->pid == exportpid)
1242 /* exits(w->msg); */