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 ...]'
19 void fatal(char*, ...);
20 void lclnoteproc(int);
21 void rmtnoteproc(void);
22 void catcher(void*, char*);
24 void writestr(int, char*, char*, int);
25 int readstr(int, char*, int);
26 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 /* authentication mechanisms */
47 static int netkeyauth(int);
48 static int netkeysrvauth(int, char*);
49 static int p9auth(int);
50 static int srvp9auth(int, char*);
51 static int noauth(int);
52 static int srvnoauth(int, char*);
54 typedef struct AuthMethod AuthMethod;
56 char *name; /* name of method */
57 int (*cf)(int); /* client side authentication */
58 int (*sf)(int, char*); /* server side authentication */
61 { "p9", p9auth, srvp9auth,},
62 { "netkey", netkeyauth, netkeysrvauth,},
63 // { "none", noauth, srvnoauth,},
66 AuthMethod *am = authmethod; /* default is p9 */
68 char *p9authproto = "p9any";
72 char *aan = "/bin/aan";
73 char *anstring = "tcp!*!0";
76 int filter(int fd, char *host);
81 fprint(2, "usage: cpu [-p] [-h system] [-u user] [-a authmethod] "
82 "[-e 'crypt hash'] [-k keypattern] [-P patternfile] "
83 "[-c cmd arg ...]\n");
88 * reading /proc/pid/args yields either "name args" or "name [display args]",
89 * so return only args or display args.
98 snprint(buf, sizeof buf, "#p/%d/args", getpid());
99 if((fd = open(buf, OREAD)) < 0)
102 n = read(fd, buf, sizeof buf-1);
106 if ((lp = strchr(buf, '[')) == nil || (rp = strrchr(buf, ']')) == nil) {
107 lp = strchr(buf, ' ');
118 * based on libthread's threadsetname, but drags in less library code.
119 * actually just sets the arguments displayed.
122 procsetname(char *fmt, ...)
130 cmdname = vsmprint(fmt, arg);
134 snprint(buf, sizeof buf, "#p/%d/args", getpid());
135 if((fd = open(buf, OWRITE)) >= 0){
136 write(fd, cmdname, strlen(cmdname)+1);
143 main(int argc, char **argv)
145 char dat[MaxStr], buf[MaxStr], cmd[MaxStr], *p, *s, *err;
146 int ac, fd, ms, data;
150 origargs = procgetname();
151 /* see if we should use a larger message size */
152 fd = open("/dev/draw", OREAD);
155 if(msgsize < ms+IOHDRSZ)
156 msgsize = ms+IOHDRSZ;
162 fatal("can't read user name: %r");
167 fatal("unknown auth method %s", p);
170 ealgs = EARGF(usage());
171 if(*ealgs == 0 || strcmp(ealgs, "clear") == 0)
178 /* ignored but accepted for compatibility */
181 anstring = EARGF(usage());
184 p9authproto = "p9sk2";
185 remoteside(1); /* From listen */
187 case 'R': /* From listen */
191 system = EARGF(usage());
199 s = seprint(s, cmd+sizeof(cmd), " %s", p);
202 keyspec = smprint("%s %s", keyspec, EARGF(usage()));
205 patternfile = EARGF(usage());
208 user = EARGF(usage());
209 keyspec = smprint("%s user=%s", keyspec, user);
229 if(err = rexcall(&data, system, srvname))
230 fatal("%s: %s: %r", err, system);
232 procsetname("%s", origargs);
233 /* Tell the remote side the command to execute and where our working directory is */
235 writestr(data, cmd, "command", 0);
236 if(getwd(dat, sizeof(dat)) == 0)
237 writestr(data, "NO", "dir", 0);
239 writestr(data, dat, "dir", 0);
241 /* start up a process to pass along notes */
245 * Wait for the other end to execute and start our file service
248 if(readstr(data, buf, sizeof(buf)) < 0)
249 fatal("waiting for FS: %r");
250 if(strncmp("FS", buf, 2) != 0) {
251 print("remote cpu: %s", buf);
255 /* Begin serving the gnot namespace */
260 sprint(buf, "%d", msgsize);
267 if(patternfile != nil){
269 av[ac++] = patternfile;
273 fatal("starting exportfs: %r");
277 fatal(char *fmt, ...)
283 vsnprint(buf, sizeof(buf), fmt, arg);
285 fprint(2, "cpu: %s\n", buf);
286 syslog(0, "cpu", "%s", buf);
290 char *negstr = "negotiating authentication method";
300 switch(rfork(RFPROC|RFMEM|RFFDG|RFNAMEG)) {
302 fatal("rfork srvold9p: %r");
314 fd = open("/sys/log/cpu", OWRITE);
319 execl("/bin/srvold9p", "srvold9p", "-ds", nil);
321 execl("/bin/srvold9p", "srvold9p", "-s", nil);
322 fatal("exec srvold9p: %r");
330 /* Invoked with stdin, stdout and stderr connected to the network connection */
334 char user[MaxStr], home[MaxStr], buf[MaxStr], xdir[MaxStr], cmd[MaxStr];
335 int i, n, fd, badchdir, gotcmd;
338 putenv("service", "cpu");
341 /* negotiate authentication mechanism */
342 n = readstr(fd, cmd, sizeof(cmd));
344 fatal("authenticating: %r");
346 if(!old && strcmp(cmd, "aan") == 0){
348 writestr(fd, "", nil, 1);
349 n = readstr(fd, cmd, sizeof(cmd));
351 fatal("authenticating: %r");
353 if(setamalg(cmd) < 0){
354 writestr(fd, "unsupported auth method", nil, 0);
355 fatal("bad auth method %s: %r", cmd);
357 writestr(fd, "", "", 1);
359 fd = (*am->sf)(fd, user);
361 fatal("srvauth: %r");
363 /* Set environment values for the user */
364 putenv("user", user);
365 snprint(home, sizeof(home), "/usr/%s", user);
366 putenv("home", home);
368 /* Now collect invoking cpu's current directory or possibly a command */
370 if(readstr(fd, xdir, sizeof(xdir)) < 0)
371 fatal("dir/cmd: %r");
373 strcpy(cmd, &xdir[1]);
375 if(readstr(fd, xdir, sizeof(xdir)) < 0)
379 /* Establish the new process at the current working directory of the
382 if(strcmp(xdir, "NO") == 0)
384 else if(chdir(xdir) < 0) {
389 /* Start the gnot serving its namespace */
390 writestr(fd, "FS", "FS", 0);
391 writestr(fd, "/", "exportfs dir", 0);
393 n = read(fd, buf, sizeof(buf));
394 if(n != 2 || buf[0] != 'O' || buf[1] != 'K')
395 exits("remote tree");
400 /* make sure buffers are big by doing fversion explicitly; pick a huge number; other side will trim */
401 strcpy(buf, VERSION9P);
402 if(fversion(fd, 64*1024, buf, sizeof buf) < 0)
403 exits("fversion failed");
404 if(mount(fd, -1, "/mnt/term", MCREATE|MREPL, "") < 0)
405 exits("mount failed");
409 /* the remote noteproc uses the mount so it must follow it */
412 for(i = 0; i < 3; i++)
415 if(open("/mnt/term/dev/cons", OREAD) != 0)
417 if(open("/mnt/term/dev/cons", OWRITE) != 1)
418 exits("open stdout");
422 print("cpu: failed to chdir to '%s'\n", xdir);
425 execl("/bin/rc", "rc", "-lc", cmd, nil);
427 execl("/bin/rc", "rc", "-li", nil);
428 fatal("exec shell: %r");
432 rexcall(int *fd, char *host, char *service)
440 na = netmkaddr(host, 0, service);
441 procsetname("dialing %s", na);
442 if((*fd = dial(na, 0, dir, 0)) < 0)
445 /* negotiate aan filter extension */
447 writestr(*fd, "aan", "negotiating aan", 0);
448 n = readstr(*fd, err, sizeof err);
450 return "negotiating aan";
457 /* negotiate authentication mechanism */
459 snprint(msg, sizeof(msg), "%s %s", am->name, ealgs);
461 snprint(msg, sizeof(msg), "%s", am->name);
462 procsetname("writing %s", msg);
463 writestr(*fd, msg, negstr, 0);
464 procsetname("awaiting auth method");
465 n = readstr(*fd, err, sizeof err);
474 procsetname("%s: auth via %s", origargs, am->name);
475 *fd = (*am->cf)(*fd);
477 return "can't authenticate";
482 writestr(int fd, char *str, char *thing, int ignore)
487 n = write(fd, str, l+1);
489 fatal("writing network: %s: %r", thing);
493 readstr(int fd, char *str, int len)
498 n = read(fd, str, 1);
510 readln(char *buf, int n)
515 n--; /* room for \0 */
518 if(read(0, p, 1) != 1)
520 if(*p == '\n' || *p == '\r')
529 * user level challenge/response
537 strecpy(chall, chall+sizeof chall, getuser());
538 print("user[%s]: ", chall);
539 if(readln(resp, sizeof(resp)) < 0)
543 writestr(fd, chall, "challenge/response", 1);
546 if(readstr(fd, chall, sizeof chall) < 0)
549 return filter(fd, system);
550 print("challenge: %s\nresponse: ", chall);
551 if(readln(resp, sizeof(resp)) < 0)
553 writestr(fd, resp, "challenge/response", 1);
559 netkeysrvauth(int fd, char *user)
566 if(readstr(fd, user, MaxStr) < 0)
571 for(tries = 0; tries < 10; tries++){
572 if((ch = auth_challenge("proto=p9cr role=server user=%q", user)) == nil)
574 writestr(fd, ch->chal, "challenge", 1);
575 if(readstr(fd, response, sizeof response) < 0)
578 ch->nresp = strlen(response);
579 if((ai = auth_response(ch)) != nil)
585 writestr(fd, "", "challenge", 1);
586 if(auth_chuid(ai, 0) < 0)
589 return filter(fd, nil);
593 mksecret(char *t, uchar *f)
595 sprint(t, "%2.2ux%2.2ux%2.2ux%2.2ux%2.2ux%2.2ux%2.2ux%2.2ux%2.2ux%2.2ux",
596 f[0], f[1], f[2], f[3], f[4], f[5], f[6], f[7], f[8], f[9]);
600 * plan9 authentication followed by rc4 encryption
605 uchar key[16], digest[SHA1dlen];
606 char fromclientsecret[21];
607 char fromserversecret[21];
611 procsetname("%s: auth_proxy proto=%q role=client %s",
612 origargs, p9authproto, keyspec);
613 ai = auth_proxy(fd, auth_getkey, "proto=%q role=client %s", p9authproto, keyspec);
620 assert(ai->nsecret <= sizeof(key)-4);
621 memmove(key+4, ai->secret, ai->nsecret);
624 /* exchange random numbers */
626 for(i = 0; i < 4; i++)
628 procsetname("writing p9 key");
629 if(write(fd, key, 4) != 4)
631 procsetname("reading p9 key");
632 if(readn(fd, key+12, 4) != 4)
635 /* scramble into two secrets */
636 sha1(key, sizeof(key), digest, nil);
637 mksecret(fromclientsecret, digest);
638 mksecret(fromserversecret, digest+10);
640 if((fd = filter(fd, system)) < 0)
643 /* set up encryption */
644 procsetname("pushssl");
645 fd = pushssl(fd, ealgs, fromclientsecret, fromserversecret, nil);
647 werrstr("can't establish ssl connection: %r");
659 srvnoauth(int fd, char *user)
661 strecpy(user, user+MaxStr, getuser());
668 loghex(uchar *p, int n)
673 for(i = 0; i < n; i++)
674 sprint(buf+2*i, "%2.2ux", p[i]);
675 syslog(0, "cpu", "%s", buf);
679 srvp9auth(int fd, char *user)
681 uchar key[16], digest[SHA1dlen];
682 char fromclientsecret[21];
683 char fromserversecret[21];
687 ai = auth_proxy(fd, nil, "proto=%q role=server %s", p9authproto, keyspec);
690 if(auth_chuid(ai, nil) < 0)
692 snprint(user, MaxStr, "%s", ai->cuid);
697 assert(ai->nsecret <= sizeof(key)-4);
698 memmove(key+4, ai->secret, ai->nsecret);
701 /* exchange random numbers */
703 for(i = 0; i < 4; i++)
705 if(readn(fd, key, 4) != 4)
707 if(write(fd, key+12, 4) != 4)
710 /* scramble into two secrets */
711 sha1(key, sizeof(key), digest, nil);
712 mksecret(fromclientsecret, digest);
713 mksecret(fromserversecret, digest+10);
715 if((fd = filter(fd, nil)) < 0)
718 /* set up encryption */
719 fd = pushssl(fd, ealgs, fromserversecret, fromclientsecret, nil);
721 werrstr("can't establish ssl connection: %r");
726 * set authentication mechanism
731 for(am = authmethod; am->name != nil; am++)
732 if(strcmp(am->name, name) == 0)
739 * set authentication mechanism and encryption/hash algs
744 ealgs = strchr(s, ' ');
751 filter(int fd, char *host)
753 char addr[128], buf[256], *s, *file, *argv[16];
754 int p[2], lfd, flags, len, argc;
758 procsetname("filter %s", filterp);
759 flags = RFNOWAIT|RFPROC|RFMEM|RFFDG;
762 if(announce(anstring, addr) < 0)
763 fatal("filter: Cannot announce %s: %r", anstring);
764 snprint(buf, sizeof(buf), "%s/local", addr);
765 if((lfd = open(buf, OREAD)) < 0)
766 fatal("filter: Cannot open %s: %r", buf);
767 if((len = read(lfd, buf, sizeof buf - 1)) < 0)
768 fatal("filter: Cannot read %s: %r", buf);
771 if(s = strchr(buf, '\n'))
773 if(write(fd, buf, len) != len)
774 fatal("filter: cannot write port; %r");
778 if((len = read(fd, buf, sizeof buf - 1)) < 0)
779 fatal("filter: cannot read port; %r");
781 if((s = strrchr(buf, '!')) == nil)
782 fatal("filter: malformed remote port: %s", buf);
783 snprint(addr, sizeof(addr), "%s", netmkaddr(host, "tcp", s+1));
786 snprint(buf, sizeof(buf), "%s", filterp);
787 if((argc = tokenize(buf, argv, nelem(argv)-3)) <= 0)
788 fatal("filter: empty command");
794 if(s = strrchr(argv[0], '/'))
798 fatal("filter: pipe; %r");
800 switch(rfork(flags)) {
802 fatal("filter: rfork; %r\n");
804 if (dup(p[0], 1) < 0)
805 fatal("filter: Cannot dup to 1; %r");
806 if (dup(p[0], 0) < 0)
807 fatal("filter: Cannot dup to 0; %r");
811 fatal("filter: exec; %r");
819 char *rmtnotefile = "/mnt/term/dev/cpunote";
822 * loop reading /mnt/term/dev/note looking for notes.
823 * The child returns to start the shell.
828 int n, fd, pid, notepid;
831 /* new proc returns to start shell */
832 pid = rfork(RFPROC|RFFDG|RFNOTEG|RFNAMEG|RFMEM);
835 syslog(0, "cpu", "cpu -R: can't start noteproc: %r");
841 /* new proc reads notes from other side and posts them to shell */
842 switch(notepid = rfork(RFPROC|RFFDG|RFMEM)){
844 syslog(0, "cpu", "cpu -R: can't start wait proc: %r");
847 fd = open(rmtnotefile, OREAD);
849 syslog(0, "cpu", "cpu -R: can't open %s", rmtnotefile);
854 n = read(fd, buf, sizeof(buf)-1);
856 postnote(PNGROUP, pid, "hangup");
860 postnote(PNGROUP, pid, buf);
864 /* original proc waits for shell proc to die and kills note proc */
867 if(n < 0 || n == pid)
870 postnote(PNPROC, notepid, "kill");
888 [Qdir] { ".", {Qdir, 0, QTDIR}, DMDIR|0555 },
889 [Qcpunote] { "cpunote", {Qcpunote, 0}, 0444 },
892 typedef struct Note Note;
899 typedef struct Request Request;
906 typedef struct Fid Fid;
917 Note *nfirst, *nlast;
918 Request *rfirst, *rlast;
922 fsreply(int fd, Fcall *f)
924 uchar buf[IOHDRSZ+Maxfdata];
928 fprint(2, "notefs: <-%F\n", f);
929 n = convS2M(f, buf, sizeof buf);
931 if(write(fd, buf, n) != n){
939 /* match a note read request with a note, reply to the request */
951 if(rp == nil || np == nil){
955 nfs.rfirst = rp->next;
956 nfs.nfirst = np->next;
960 rp->f.count = strlen(np->msg);
961 rp->f.data = np->msg;
962 rv = fsreply(fd, &rp->f);
977 for(l = &nfs.rfirst; *l != nil; l = &(*l)->next){
979 if(rp->f.tag == tag){
995 for(i = 0; i < Nfid; i++){
996 if(freefid < 0 && fids[i].file < 0)
998 if(fids[i].fid == fid)
1002 fids[freefid].fid = fid;
1003 return &fids[freefid];
1009 fsstat(int fd, Fid *fid, Fcall *f)
1014 memset(&d, 0, sizeof(d));
1015 d.name = fstab[fid->file].name;
1019 d.qid = fstab[fid->file].qid;
1020 d.mode = fstab[fid->file].perm;
1021 d.atime = d.mtime = time(0);
1023 f->nstat = convD2M(&d, statbuf, sizeof statbuf);
1024 return fsreply(fd, f);
1028 fsread(int fd, Fid *fid, Fcall *f)
1038 if(f->offset == 0 && f->count >0){
1039 memset(&d, 0, sizeof(d));
1040 d.name = fstab[Qcpunote].name;
1044 d.qid = fstab[Qcpunote].qid;
1045 d.mode = fstab[Qcpunote].perm;
1046 d.atime = d.mtime = time(0);
1047 f->count = convD2M(&d, buf, sizeof buf);
1048 f->data = (char*)buf;
1051 return fsreply(fd, f);
1053 rp = mallocz(sizeof(*rp), 1);
1058 if(nfs.rfirst == nil)
1061 nfs.rlast->next = rp;
1068 char Eperm[] = "permission denied";
1069 char Enofile[] = "out of files";
1070 char Enotdir[] = "not a directory";
1075 uchar buf[IOHDRSZ+Maxfdata];
1083 fmtinstall('F', fcallfmt);
1085 for(n = 0; n < Nfid; n++){
1092 n = read9pmsg(fd, buf, sizeof(buf));
1095 fprint(2, "read9pmsg(%d) returns %d: %r\n", fd, n);
1098 if(convM2S(buf, n, &f) <= BIT16SZ)
1101 fprint(2, "notefs: ->%F\n", &f);
1103 fid = getfid(f.fid);
1114 f.ename = "unknown type";
1120 if(f.msize > IOHDRSZ+Maxfdata)
1121 f.msize = IOHDRSZ+Maxfdata;
1125 f.ename = "authentication not required";
1128 f.qid = fstab[Qdir].qid;
1133 if(f.newfid != f.fid){
1134 nfid = getfid(f.newfid);
1137 nfid->file = fid->file;
1140 for(i=0; i<f.nwname && i<MAXWELEM; i++){
1141 if(fid->file != Qdir){
1146 if(strcmp(f.wname[i], "..") == 0){
1147 wqid[i] = fstab[Qdir].qid;
1150 if(strcmp(f.wname[i], "cpunote") != 0){
1153 f.ename = "file does not exist";
1157 fid->file = Qcpunote;
1158 wqid[i] = fstab[Qcpunote].qid;
1160 if(nfid != nil && (f.type == Rerror || i < f.nwname))
1162 if(f.type != Rerror){
1164 for(i=0; i<f.nwqid; i++)
1165 f.wqid[i] = wqid[i];
1169 if(f.mode != OREAD){
1174 fid->omode = f.mode;
1175 if(fid->file == Qcpunote)
1177 f.qid = fstab[fid->file].qid;
1181 if(fsread(fd, fid, &f) < 0)
1186 if(fid->omode != -1 && fid->file == Qcpunote){
1188 if(ncpunote == 0) /* remote side is done */
1195 if(fsstat(fd, fid, &f) < 0)
1208 if(fsreply(fd, &f) < 0)
1213 fprint(2, "notefs exiting: %r\n");
1215 postnote(PNGROUP, exportpid, "kill");
1217 fprint(2, "postnote PNGROUP %d: %r\n", exportpid);
1221 char notebuf[ERRMAX];
1224 catcher(void*, char *text)
1229 if(n >= sizeof(notebuf))
1230 n = sizeof(notebuf)-1;
1231 memmove(notebuf, text, n);
1237 * mount in /dev a note file for the remote side to read.
1240 lclnoteproc(int netfd)
1248 fprint(2, "cpu: can't start note proc: pipe: %r\n");
1252 /* new proc mounts and returns to start exportfs */
1253 switch(pid = rfork(RFPROC|RFNAMEG|RFFDG|RFMEM)){
1258 fprint(2, "cpu: can't start note proc: rfork: %r\n");
1262 if(mount(pfd[1], -1, "/dev", MBEFORE, "") < 0)
1263 fprint(2, "cpu: can't mount note proc: %r\n");
1271 /* new proc listens for note file system rpc's */
1272 switch(rfork(RFPROC|RFNAMEG|RFMEM)){
1274 fprint(2, "cpu: can't start note proc: rfork1: %r\n");
1281 /* original proc waits for notes */
1291 np = mallocz(sizeof(Note), 1);
1293 strcpy(np->msg, notebuf);
1295 if(nfs.nfirst == nil)
1298 nfs.nlast->next = np;
1304 } else if(w->pid == exportpid)
1311 /* exits(w->msg); */