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 ...]'
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 /* 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 /* must be specified before -R/-O */
185 anstring = EARGF(usage());
188 p9authproto = "p9sk2";
189 remoteside(1); /* From listen */
191 case 'R': /* From listen */
195 system = EARGF(usage());
203 s = seprint(s, cmd+sizeof(cmd), " %s", p);
206 keyspec = smprint("%s %s", keyspec, EARGF(usage()));
209 patternfile = EARGF(usage());
212 user = EARGF(usage());
213 keyspec = smprint("%s user=%s", keyspec, user);
233 if(err = rexcall(&data, system, srvname))
234 fatal("%s: %s: %r", err, system);
236 procsetname("%s", origargs);
237 /* Tell the remote side the command to execute and where our working directory is */
239 writestr(data, cmd, "command", 0);
240 if(getwd(dat, sizeof(dat)) == 0)
241 writestr(data, "NO", "dir", 0);
243 writestr(data, dat, "dir", 0);
245 /* start up a process to pass along notes */
249 * Wait for the other end to execute and start our file service
252 if(readstr(data, buf, sizeof(buf)) < 0)
253 fatal("waiting for FS: %r");
254 if(strncmp("FS", buf, 2) != 0) {
255 print("remote cpu: %s", buf);
259 /* Begin serving the gnot namespace */
264 sprint(buf, "%d", msgsize);
271 if(patternfile != nil){
273 av[ac++] = patternfile;
277 fatal("starting exportfs: %r");
281 fatal(char *fmt, ...)
287 vsnprint(buf, sizeof(buf), fmt, arg);
289 fprint(2, "cpu: %s\n", buf);
290 syslog(0, "cpu", "%s", buf);
294 char *negstr = "negotiating authentication method";
304 switch(rfork(RFPROC|RFMEM|RFFDG|RFNAMEG|RFREND)) {
306 fatal("rfork srvold9p: %r");
318 fd = open("/sys/log/cpu", OWRITE);
323 execl("/bin/srvold9p", "srvold9p", "-ds", nil);
325 execl("/bin/srvold9p", "srvold9p", "-s", nil);
326 fatal("exec srvold9p: %r");
334 /* Invoked with stdin and stdout connected to the network connection */
338 char user[MaxStr], buf[MaxStr], xdir[MaxStr], cmd[MaxStr];
339 int i, n, fd, badchdir, gotcmd;
342 putenv("service", "cpu");
345 /* negotiate authentication mechanism */
346 n = readstr(fd, cmd, sizeof(cmd));
348 fatal("authenticating: %r");
350 if(!old && strcmp(cmd, "aan") == 0){
352 writestr(fd, "", nil, 1);
353 n = readstr(fd, cmd, sizeof(cmd));
355 fatal("authenticating: %r");
357 if(setamalg(cmd) < 0 || (nflag == 0 && am->sf == srvnoauth)) {
358 writestr(fd, "unsupported auth method", nil, 0);
359 fatal("bad auth method %s", cmd);
361 writestr(fd, "", "", 1);
363 fd = (*am->sf)(fd, user);
365 fatal("srvauth: %r");
367 /* Now collect invoking cpu's current directory or possibly a command */
369 if(readstr(fd, xdir, sizeof(xdir)) < 0)
370 fatal("dir/cmd: %r");
372 strcpy(cmd, &xdir[1]);
374 if(readstr(fd, xdir, sizeof(xdir)) < 0)
378 /* Establish the new process at the current working directory of the gnot */
380 if(strcmp(xdir, "NO") != 0)
384 /* Start the gnot serving its namespace */
385 writestr(fd, "FS", "FS", 0);
386 writestr(fd, "/", "exportfs dir", 0);
388 n = read(fd, buf, sizeof(buf));
389 if(n != 2 || buf[0] != 'O' || buf[1] != 'K')
390 exits("remote tree");
395 /* make sure buffers are big by doing fversion explicitly; pick a huge number; other side will trim */
396 strcpy(buf, VERSION9P);
397 if(fversion(fd, 64*1024, buf, sizeof buf) < 0)
398 exits("fversion failed");
399 if(mount(fd, -1, "/mnt/term", MCREATE|MREPL, "") < 0)
400 exits("mount failed");
404 /* the remote noteproc uses the mount so it must follow it */
407 for(i = 0; i < 3; i++)
410 if(open("/mnt/term/dev/cons", OREAD) != 0)
412 if(open("/mnt/term/dev/cons", OWRITE) != 1)
413 exits("open stdout");
417 print("cpu: failed to chdir to '%s'\n", xdir);
420 execl("/bin/rc", "rc", "-lc", cmd, nil);
422 execl("/bin/rc", "rc", "-li", nil);
423 fatal("exec shell: %r");
427 rexcall(int *fd, char *host, char *service)
434 na = netmkaddr(host, 0, service);
435 procsetname("dialing %s", na);
436 if((*fd = dial(na, 0, 0, 0)) < 0)
439 /* negotiate aan filter extension */
441 writestr(*fd, "aan", "negotiating aan", 0);
442 n = readstr(*fd, err, sizeof err);
444 return "negotiating aan";
446 errstr(err, sizeof err);
451 /* negotiate authentication mechanism */
453 snprint(msg, sizeof(msg), "%s %s", am->name, ealgs);
455 snprint(msg, sizeof(msg), "%s", am->name);
456 procsetname("writing %s", msg);
457 writestr(*fd, msg, negstr, 0);
458 procsetname("awaiting auth method");
459 n = readstr(*fd, err, sizeof err);
463 errstr(err, sizeof err);
468 procsetname("%s: auth via %s", origargs, am->name);
469 *fd = (*am->cf)(*fd);
471 return "can't authenticate";
476 writestr(int fd, char *str, char *thing, int ignore)
481 n = write(fd, str, l+1);
483 fatal("writing network: %s: %r", thing);
487 readstr(int fd, char *str, int len)
492 n = read(fd, str, 1);
504 readln(char *buf, int n)
509 n--; /* room for \0 */
512 if(read(0, p, 1) != 1)
514 if(*p == '\n' || *p == '\r')
523 * user level challenge/response
531 strecpy(chall, chall+sizeof chall, getuser());
532 print("user[%s]: ", chall);
533 if(readln(resp, sizeof(resp)) < 0)
537 writestr(fd, chall, "challenge/response", 1);
540 if(readstr(fd, chall, sizeof chall) < 0)
543 return filter(fd, system);
544 print("challenge: %s\nresponse: ", chall);
545 if(readln(resp, sizeof(resp)) < 0)
547 writestr(fd, resp, "challenge/response", 1);
553 netkeysrvauth(int fd, char *user)
560 if(readstr(fd, user, MaxStr) < 0)
565 for(tries = 0; tries < 10; tries++){
566 if((ch = auth_challenge("proto=p9cr role=server user=%q", user)) == nil)
568 writestr(fd, ch->chal, "challenge", 1);
569 if(readstr(fd, response, sizeof response) < 0)
572 ch->nresp = strlen(response);
573 if((ai = auth_response(ch)) != nil)
579 writestr(fd, "", "challenge", 1);
580 if(auth_chuid(ai, 0) < 0)
583 return filter(fd, nil);
587 mksecret(char *t, uchar *f)
589 sprint(t, "%2.2ux%2.2ux%2.2ux%2.2ux%2.2ux%2.2ux%2.2ux%2.2ux%2.2ux%2.2ux",
590 f[0], f[1], f[2], f[3], f[4], f[5], f[6], f[7], f[8], f[9]);
594 * plan9 authentication followed by rc4 encryption
599 uchar key[16], digest[SHA1dlen];
600 char fromclientsecret[21];
601 char fromserversecret[21];
605 procsetname("%s: auth_proxy proto=%q role=client %s",
606 origargs, p9authproto, keyspec);
607 ai = auth_proxy(fd, auth_getkey, "proto=%q role=client %s", p9authproto, keyspec);
614 assert(ai->nsecret <= sizeof(key)-4);
615 memmove(key+4, ai->secret, ai->nsecret);
618 /* exchange random numbers */
620 for(i = 0; i < 4; i++)
622 procsetname("writing p9 key");
623 if(write(fd, key, 4) != 4)
625 procsetname("reading p9 key");
626 if(readn(fd, key+12, 4) != 4)
629 /* scramble into two secrets */
630 sha1(key, sizeof(key), digest, nil);
631 mksecret(fromclientsecret, digest);
632 mksecret(fromserversecret, digest+10);
634 if((fd = filter(fd, system)) < 0)
637 /* set up encryption */
638 procsetname("pushssl");
639 fd = pushssl(fd, ealgs, fromclientsecret, fromserversecret, nil);
641 werrstr("can't establish ssl connection: %r");
653 srvnoauth(int fd, char *user)
655 strecpy(user, user+MaxStr, getuser());
662 loghex(uchar *p, int n)
667 for(i = 0; i < n; i++)
668 sprint(buf+2*i, "%2.2ux", p[i]);
669 syslog(0, "cpu", "%s", buf);
673 srvp9auth(int fd, char *user)
675 uchar key[16], digest[SHA1dlen];
676 char fromclientsecret[21];
677 char fromserversecret[21];
681 ai = auth_proxy(fd, nil, "proto=%q role=server %s", p9authproto, keyspec);
684 if(auth_chuid(ai, nil) < 0)
686 snprint(user, MaxStr, "%s", ai->cuid);
691 assert(ai->nsecret <= sizeof(key)-4);
692 memmove(key+4, ai->secret, ai->nsecret);
695 /* exchange random numbers */
697 for(i = 0; i < 4; i++)
699 if(readn(fd, key, 4) != 4)
701 if(write(fd, key+12, 4) != 4)
704 /* scramble into two secrets */
705 sha1(key, sizeof(key), digest, nil);
706 mksecret(fromclientsecret, digest);
707 mksecret(fromserversecret, digest+10);
709 if((fd = filter(fd, nil)) < 0)
712 /* set up encryption */
713 fd = pushssl(fd, ealgs, fromserversecret, fromclientsecret, nil);
715 werrstr("can't establish ssl connection: %r");
720 * set authentication mechanism
725 for(am = authmethod; am->name != nil; am++)
726 if(strcmp(am->name, name) == 0)
733 * set authentication mechanism and encryption/hash algs
738 ealgs = strchr(s, ' ');
745 filter(int fd, char *host)
747 char addr[128], buf[256], *s, *file, *argv[16];
748 int p[2], lfd, flags, len, argc;
752 procsetname("filter %s", filterp);
753 flags = RFNOWAIT|RFPROC|RFMEM|RFFDG|RFREND;
756 if(announce(anstring, addr) < 0)
757 fatal("filter: Cannot announce %s: %r", anstring);
758 snprint(buf, sizeof(buf), "%s/local", addr);
759 if((lfd = open(buf, OREAD)) < 0)
760 fatal("filter: Cannot open %s: %r", buf);
761 if((len = read(lfd, buf, sizeof buf - 1)) < 0)
762 fatal("filter: Cannot read %s: %r", buf);
765 if(s = strchr(buf, '\n'))
767 if(write(fd, buf, len) != len)
768 fatal("filter: cannot write port; %r");
772 if((len = read(fd, buf, sizeof buf - 1)) < 0)
773 fatal("filter: cannot read port; %r");
775 if((s = strrchr(buf, '!')) == nil)
776 fatal("filter: malformed remote port: %s", buf);
777 strecpy(addr, addr+sizeof(addr), netmkaddr(host, "tcp", s+1));
778 strecpy(strrchr(addr, '!'), addr+sizeof(addr), s);
781 snprint(buf, sizeof(buf), "%s", filterp);
782 if((argc = tokenize(buf, argv, nelem(argv)-3)) <= 0)
783 fatal("filter: empty command");
789 if(s = strrchr(argv[0], '/'))
793 fatal("filter: pipe; %r");
795 switch(rfork(flags)) {
797 fatal("filter: rfork; %r\n");
799 if (dup(p[0], 1) < 0)
800 fatal("filter: Cannot dup to 1; %r");
801 if (dup(p[0], 0) < 0)
802 fatal("filter: Cannot dup to 0; %r");
806 fatal("filter: exec; %r");
814 char *rmtnotefile = "/mnt/term/dev/cpunote";
817 * loop reading /mnt/term/dev/note looking for notes.
818 * The child returns to start the shell.
823 int n, fd, pid, notepid;
826 /* new proc returns to start shell */
827 pid = rfork(RFPROC|RFFDG|RFNOTEG|RFNAMEG|RFMEM);
830 syslog(0, "cpu", "cpu -R: can't start noteproc: %r");
836 /* new proc reads notes from other side and posts them to shell */
837 switch(notepid = rfork(RFPROC|RFFDG|RFMEM)){
839 syslog(0, "cpu", "cpu -R: can't start wait proc: %r");
842 fd = open(rmtnotefile, OREAD);
844 syslog(0, "cpu", "cpu -R: can't open %s", rmtnotefile);
849 n = read(fd, buf, sizeof(buf)-1);
851 postnote(PNGROUP, pid, "hangup");
855 postnote(PNGROUP, pid, buf);
859 /* original proc waits for shell proc to die and kills note proc */
862 if(n < 0 || n == pid)
865 postnote(PNPROC, notepid, "kill");
883 [Qdir] { ".", {Qdir, 0, QTDIR}, DMDIR|0555 },
884 [Qcpunote] { "cpunote", {Qcpunote, 0}, 0444 },
887 typedef struct Note Note;
894 typedef struct Request Request;
901 typedef struct Fid Fid;
912 Note *nfirst, *nlast;
913 Request *rfirst, *rlast;
917 fsreply(int fd, Fcall *f)
919 uchar buf[IOHDRSZ+Maxfdata];
923 fprint(2, "notefs: <-%F\n", f);
924 n = convS2M(f, buf, sizeof buf);
926 if(write(fd, buf, n) != n){
934 /* match a note read request with a note, reply to the request */
946 if(rp == nil || np == nil){
950 nfs.rfirst = rp->next;
951 nfs.nfirst = np->next;
955 rp->f.count = strlen(np->msg);
956 rp->f.data = np->msg;
957 rv = fsreply(fd, &rp->f);
972 for(l = &nfs.rfirst; *l != nil; l = &(*l)->next){
974 if(rp->f.tag == tag){
990 for(i = 0; i < Nfid; i++){
991 if(freefid < 0 && fids[i].file < 0)
993 if(fids[i].fid == fid)
997 fids[freefid].fid = fid;
998 return &fids[freefid];
1004 fsstat(int fd, Fid *fid, Fcall *f)
1009 memset(&d, 0, sizeof(d));
1010 d.name = fstab[fid->file].name;
1014 d.qid = fstab[fid->file].qid;
1015 d.mode = fstab[fid->file].perm;
1016 d.atime = d.mtime = time(0);
1018 f->nstat = convD2M(&d, statbuf, sizeof statbuf);
1019 return fsreply(fd, f);
1023 fsread(int fd, Fid *fid, Fcall *f)
1033 if(f->offset == 0 && f->count >0){
1034 memset(&d, 0, sizeof(d));
1035 d.name = fstab[Qcpunote].name;
1039 d.qid = fstab[Qcpunote].qid;
1040 d.mode = fstab[Qcpunote].perm;
1041 d.atime = d.mtime = time(0);
1042 f->count = convD2M(&d, buf, sizeof buf);
1043 f->data = (char*)buf;
1046 return fsreply(fd, f);
1048 rp = mallocz(sizeof(*rp), 1);
1053 if(nfs.rfirst == nil)
1056 nfs.rlast->next = rp;
1063 char Eperm[] = "permission denied";
1064 char Enofile[] = "out of files";
1065 char Enotdir[] = "not a directory";
1070 uchar buf[IOHDRSZ+Maxfdata];
1078 fmtinstall('F', fcallfmt);
1080 for(n = 0; n < Nfid; n++){
1087 n = read9pmsg(fd, buf, sizeof(buf));
1090 fprint(2, "read9pmsg(%d) returns %d: %r\n", fd, n);
1095 if(convM2S(buf, n, &f) <= BIT16SZ)
1098 fprint(2, "notefs: ->%F\n", &f);
1100 fid = getfid(f.fid);
1111 f.ename = "unknown type";
1117 if(f.msize > IOHDRSZ+Maxfdata)
1118 f.msize = IOHDRSZ+Maxfdata;
1122 f.ename = "authentication not required";
1125 f.qid = fstab[Qdir].qid;
1130 if(f.newfid != f.fid){
1131 nfid = getfid(f.newfid);
1134 nfid->file = fid->file;
1137 for(i=0; i<f.nwname && i<MAXWELEM; i++){
1138 if(fid->file != Qdir){
1143 if(strcmp(f.wname[i], "..") == 0){
1144 wqid[i] = fstab[Qdir].qid;
1147 if(strcmp(f.wname[i], "cpunote") != 0){
1150 f.ename = "file does not exist";
1154 fid->file = Qcpunote;
1155 wqid[i] = fstab[Qcpunote].qid;
1157 if(nfid != nil && (f.type == Rerror || i < f.nwname))
1159 if(f.type != Rerror){
1161 for(i=0; i<f.nwqid; i++)
1162 f.wqid[i] = wqid[i];
1166 if(f.mode != OREAD){
1171 fid->omode = f.mode;
1172 if(fid->file == Qcpunote)
1174 f.qid = fstab[fid->file].qid;
1178 if(fsread(fd, fid, &f) < 0)
1183 if(fid->omode != -1 && fid->file == Qcpunote){
1185 if(ncpunote == 0) /* remote side is done */
1192 if(fsstat(fd, fid, &f) < 0)
1205 if(fsreply(fd, &f) < 0)
1210 fprint(2, "notefs exiting: %r\n");
1212 postnote(PNGROUP, exportpid, "kill");
1214 fprint(2, "postnote PNGROUP %d: %r\n", exportpid);
1218 char notebuf[ERRMAX];
1221 catcher(void*, char *text)
1226 if(n >= sizeof(notebuf))
1227 n = sizeof(notebuf)-1;
1228 memmove(notebuf, text, n);
1234 * mount in /dev a note file for the remote side to read.
1237 lclnoteproc(int netfd)
1245 fprint(2, "cpu: can't start note proc: pipe: %r\n");
1249 /* new proc mounts and returns to start exportfs */
1250 switch(pid = rfork(RFPROC|RFNAMEG|RFFDG|RFMEM)){
1255 fprint(2, "cpu: can't start note proc: rfork: %r\n");
1259 if(mount(pfd[1], -1, "/dev", MBEFORE, "") < 0)
1260 fprint(2, "cpu: can't mount note proc: %r\n");
1268 /* new proc listens for note file system rpc's */
1269 switch(rfork(RFPROC|RFNAMEG|RFMEM)){
1271 fprint(2, "cpu: can't start note proc: rfork1: %r\n");
1278 /* original proc waits for notes */
1288 np = mallocz(sizeof(Note), 1);
1290 strcpy(np->msg, notebuf);
1292 if(nfs.nfirst == nil)
1295 nfs.nlast->next = np;
1301 } else if(w->pid == exportpid)
1308 /* exits(w->msg); */