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 /* 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 */
72 char *p9authproto = "p9any";
76 char *aan = "/bin/aan";
77 char *anstring = "tcp!*!0";
80 int filter(int fd, char *host);
85 fprint(2, "usage: cpu [-p] [-h system] [-u user] [-a authmethod] "
86 "[-e 'crypt hash'] [-k keypattern] [-P patternfile] "
87 "[-c cmd arg ...]\n");
92 * reading /proc/pid/args yields either "name args" or "name [display args]",
93 * so return only args or display args.
102 snprint(buf, sizeof buf, "#p/%d/args", getpid());
103 if((fd = open(buf, OREAD)) < 0)
106 n = read(fd, buf, sizeof buf-1);
110 if ((lp = strchr(buf, '[')) == nil || (rp = strrchr(buf, ']')) == nil) {
111 lp = strchr(buf, ' ');
122 * based on libthread's threadsetname, but drags in less library code.
123 * actually just sets the arguments displayed.
126 procsetname(char *fmt, ...)
134 cmdname = vsmprint(fmt, arg);
138 snprint(buf, sizeof buf, "#p/%d/args", getpid());
139 if((fd = open(buf, OWRITE)) >= 0){
140 write(fd, cmdname, strlen(cmdname)+1);
147 main(int argc, char **argv)
149 char dat[MaxStr], buf[MaxStr], cmd[MaxStr], *p, *s, *err;
150 int ac, fd, ms, data;
154 origargs = procgetname();
155 /* see if we should use a larger message size */
156 fd = open("/dev/draw", OREAD);
159 if(msgsize < ms+IOHDRSZ)
160 msgsize = ms+IOHDRSZ;
166 fatal("can't read user name: %r");
171 fatal("unknown auth method %s", p);
174 ealgs = EARGF(usage());
175 if(*ealgs == 0 || strcmp(ealgs, "clear") == 0)
182 /* ignored but accepted for compatibility */
185 /* must be specified before -R/-O */
189 anstring = EARGF(usage());
192 p9authproto = "p9sk2";
193 remoteside(1); /* From listen */
195 case 'R': /* From listen */
199 system = EARGF(usage());
207 s = seprint(s, cmd+sizeof(cmd), " %s", p);
210 keyspec = smprint("%s %s", keyspec, EARGF(usage()));
213 patternfile = EARGF(usage());
216 user = EARGF(usage());
217 keyspec = smprint("%s user=%s", keyspec, user);
237 if(err = rexcall(&data, system, srvname))
238 fatal("%s: %s: %r", err, system);
240 procsetname("%s", origargs);
241 /* Tell the remote side the command to execute and where our working directory is */
243 writestr(data, cmd, "command", 0);
244 if(getwd(dat, sizeof(dat)) == 0)
245 writestr(data, "NO", "dir", 0);
247 writestr(data, dat, "dir", 0);
249 /* start up a process to pass along notes */
253 * Wait for the other end to execute and start our file service
256 if(readstr(data, buf, sizeof(buf)) < 0)
257 fatal("waiting for FS: %r");
258 if(strncmp("FS", buf, 2) != 0) {
259 print("remote cpu: %s", buf);
263 /* Begin serving the gnot namespace */
268 sprint(buf, "%d", msgsize);
275 if(patternfile != nil){
277 av[ac++] = patternfile;
281 fatal("starting exportfs: %r");
285 fatal(char *fmt, ...)
291 vsnprint(buf, sizeof(buf), fmt, arg);
293 fprint(2, "cpu: %s\n", buf);
294 syslog(0, "cpu", "%s", buf);
298 char *negstr = "negotiating authentication method";
308 switch(rfork(RFPROC|RFMEM|RFFDG|RFNAMEG|RFREND)) {
310 fatal("rfork srvold9p: %r");
322 fd = open("/sys/log/cpu", OWRITE);
327 execl("/bin/srvold9p", "srvold9p", "-ds", nil);
329 execl("/bin/srvold9p", "srvold9p", "-s", nil);
330 fatal("exec srvold9p: %r");
338 /* Invoked with stdin and stdout connected to the network connection */
342 char user[MaxStr], buf[MaxStr], xdir[MaxStr], cmd[MaxStr];
343 int i, n, fd, badchdir, gotcmd;
346 putenv("service", "cpu");
349 /* negotiate authentication mechanism */
350 n = readstr(fd, cmd, sizeof(cmd));
352 fatal("authenticating: %r");
354 if(!old && strcmp(cmd, "aan") == 0){
356 writestr(fd, "", nil, 1);
357 n = readstr(fd, cmd, sizeof(cmd));
359 fatal("authenticating: %r");
361 if(setamalg(cmd) < 0 || (nflag == 0 && am->sf == srvnoauth)) {
362 writestr(fd, "unsupported auth method", nil, 0);
363 fatal("bad auth method %s", cmd);
365 writestr(fd, "", "", 1);
367 if((fd = (*am->sf)(fd, user)) < 0)
368 fatal("srvauth: %r");
369 if((fd = filter(fd, nil)) < 0)
371 if((fd = encryption(fd)) < 0)
372 fatal("encrypt: %r");
374 /* Now collect invoking cpu's current directory or possibly a command */
376 if(readstr(fd, xdir, sizeof(xdir)) < 0)
377 fatal("dir/cmd: %r");
379 strcpy(cmd, &xdir[1]);
381 if(readstr(fd, xdir, sizeof(xdir)) < 0)
385 /* Establish the new process at the current working directory of the gnot */
387 if(strcmp(xdir, "NO") != 0)
391 /* Start the gnot serving its namespace */
392 writestr(fd, "FS", "FS", 0);
393 writestr(fd, "/", "exportfs dir", 0);
395 n = read(fd, buf, sizeof(buf));
396 if(n != 2 || buf[0] != 'O' || buf[1] != 'K')
397 exits("remote tree");
402 /* make sure buffers are big by doing fversion explicitly; pick a huge number; other side will trim */
403 strcpy(buf, VERSION9P);
404 if(fversion(fd, 64*1024, buf, sizeof buf) < 0)
405 exits("fversion failed");
406 if(mount(fd, -1, "/mnt/term", MCREATE|MREPL, "") < 0)
407 exits("mount failed");
411 /* the remote noteproc uses the mount so it must follow it */
414 for(i = 0; i < 3; i++)
417 if(open("/mnt/term/dev/cons", OREAD) != 0)
419 if(open("/mnt/term/dev/cons", OWRITE) != 1)
420 exits("open stdout");
424 print("cpu: failed to chdir to '%s'\n", xdir);
427 execl("/bin/rc", "rc", "-lc", cmd, nil);
429 execl("/bin/rc", "rc", "-li", nil);
430 fatal("exec shell: %r");
434 rexcall(int *fd, char *host, char *service)
441 na = netmkaddr(host, 0, service);
442 procsetname("dialing %s", na);
443 if((*fd = dial(na, 0, 0, 0)) < 0)
446 /* negotiate aan filter extension */
448 writestr(*fd, "aan", "negotiating aan", 0);
449 n = readstr(*fd, err, sizeof err);
451 return "negotiating aan";
453 errstr(err, sizeof err);
458 /* negotiate authentication mechanism */
460 snprint(msg, sizeof(msg), "%s %s", am->name, ealgs);
462 snprint(msg, sizeof(msg), "%s", am->name);
463 procsetname("writing %s", msg);
464 writestr(*fd, msg, negstr, 0);
465 procsetname("awaiting auth method");
466 n = readstr(*fd, err, sizeof err);
470 errstr(err, sizeof err);
475 procsetname("%s: auth via %s", origargs, am->name);
476 if((*fd = (*am->cf)(*fd)) < 0)
477 return "can't authenticate";
478 if((*fd = filter(*fd, system)) < 0)
479 return "can't filter";
480 if((*fd = encryption(*fd)) < 0)
481 return "can't encrypt";
486 writestr(int fd, char *str, char *thing, int ignore)
491 n = write(fd, str, l+1);
493 fatal("writing network: %s: %r", thing);
497 readstr(int fd, char *str, int len)
502 n = read(fd, str, 1);
514 readln(char *buf, int n)
519 n--; /* room for \0 */
522 if(read(0, p, 1) != 1)
524 if(*p == '\n' || *p == '\r')
533 * user level challenge/response
541 strecpy(chall, chall+sizeof chall, getuser());
542 print("user[%s]: ", chall);
543 if(readln(resp, sizeof(resp)) < 0)
547 writestr(fd, chall, "challenge/response", 1);
550 if(readstr(fd, chall, sizeof chall) < 0)
554 print("challenge: %s\nresponse: ", chall);
555 if(readln(resp, sizeof(resp)) < 0)
557 writestr(fd, resp, "challenge/response", 1);
563 netkeysrvauth(int fd, char *user)
570 if(readstr(fd, user, MaxStr) < 0)
575 for(tries = 0; tries < 10; tries++){
576 if((ch = auth_challenge("proto=p9cr role=server user=%q", user)) == nil)
578 writestr(fd, ch->chal, "challenge", 1);
579 if(readstr(fd, response, sizeof response) < 0)
582 ch->nresp = strlen(response);
583 if((ai = auth_response(ch)) != nil)
589 writestr(fd, "", "challenge", 1);
590 if(auth_chuid(ai, 0) < 0)
602 static char sslsecret[2][21];
607 return pushssl(fd, ealgs, sslsecret[0], sslsecret[1], nil);
611 mksecret(char *t, uchar *f)
613 sprint(t, "%2.2ux%2.2ux%2.2ux%2.2ux%2.2ux%2.2ux%2.2ux%2.2ux%2.2ux%2.2ux",
614 f[0], f[1], f[2], f[3], f[4], f[5], f[6], f[7], f[8], f[9]);
618 sslsetup(int fd, uchar *secret, int nsecret, int isclient)
620 uchar key[16], digest[SHA1dlen];
627 werrstr("secret too small to ssl");
630 memmove(key+4, secret, 8);
632 /* exchange random numbers */
636 for(i = 0; i < 4; i++)
638 if(write(fd, key, 4) != 4)
640 if(readn(fd, key+12, 4) != 4)
643 for(i = 0; i < 4; i++)
645 if(readn(fd, key, 4) != 4)
647 if(write(fd, key+12, 4) != 4)
651 /* scramble into two secrets */
652 sha1(key, sizeof(key), digest, nil);
653 mksecret(sslsecret[isclient == 0], digest);
654 mksecret(sslsecret[isclient != 0], digest+10);
656 encryption = sslencrypt;
662 * plan9 authentication followed by rc4 encryption
669 ai = auth_proxy(fd, auth_getkey, "proto=%q role=client %s", p9authproto, keyspec);
672 fd = sslsetup(fd, ai->secret, ai->nsecret, 1);
685 srvnoauth(int fd, char *user)
687 strecpy(user, user+MaxStr, getuser());
694 srvp9auth(int fd, char *user)
698 ai = auth_proxy(fd, nil, "proto=%q role=server %s", p9authproto, keyspec);
701 if(auth_chuid(ai, nil) < 0)
703 snprint(user, MaxStr, "%s", ai->cuid);
704 fd = sslsetup(fd, ai->secret, ai->nsecret, 0);
710 * set authentication mechanism
715 for(am = authmethod; am->name != nil; am++)
716 if(strcmp(am->name, name) == 0)
723 * set authentication mechanism and encryption/hash algs
728 ealgs = strchr(s, ' ');
735 filter(int fd, char *host)
737 char addr[128], buf[256], *s, *file, *argv[16];
738 int p[2], lfd, flags, len, argc;
742 procsetname("filter %s", filterp);
743 flags = RFNOWAIT|RFPROC|RFMEM|RFFDG|RFREND;
746 if(announce(anstring, addr) < 0)
747 fatal("filter: Cannot announce %s: %r", anstring);
748 snprint(buf, sizeof(buf), "%s/local", addr);
749 if((lfd = open(buf, OREAD)) < 0)
750 fatal("filter: Cannot open %s: %r", buf);
751 if((len = read(lfd, buf, sizeof buf - 1)) < 0)
752 fatal("filter: Cannot read %s: %r", buf);
755 if(s = strchr(buf, '\n'))
757 if(write(fd, buf, len) != len)
758 fatal("filter: cannot write port; %r");
762 if((len = read(fd, buf, sizeof buf - 1)) < 0)
763 fatal("filter: cannot read port; %r");
765 if((s = strrchr(buf, '!')) == nil)
766 fatal("filter: malformed remote port: %s", buf);
767 strecpy(addr, addr+sizeof(addr), netmkaddr(host, "tcp", s+1));
768 strecpy(strrchr(addr, '!'), addr+sizeof(addr), s);
771 snprint(buf, sizeof(buf), "%s", filterp);
772 if((argc = tokenize(buf, argv, nelem(argv)-3)) <= 0)
773 fatal("filter: empty command");
779 if(s = strrchr(argv[0], '/'))
783 fatal("filter: pipe; %r");
785 switch(rfork(flags)) {
787 fatal("filter: rfork; %r\n");
789 if (dup(p[0], 1) < 0)
790 fatal("filter: Cannot dup to 1; %r");
791 if (dup(p[0], 0) < 0)
792 fatal("filter: Cannot dup to 0; %r");
796 fatal("filter: exec; %r");
804 char *rmtnotefile = "/mnt/term/dev/cpunote";
807 * loop reading /mnt/term/dev/note looking for notes.
808 * The child returns to start the shell.
813 int n, fd, pid, notepid;
816 /* new proc returns to start shell */
817 pid = rfork(RFPROC|RFFDG|RFNOTEG|RFNAMEG|RFMEM);
820 syslog(0, "cpu", "cpu -R: can't start noteproc: %r");
826 /* new proc reads notes from other side and posts them to shell */
827 switch(notepid = rfork(RFPROC|RFFDG|RFMEM)){
829 syslog(0, "cpu", "cpu -R: can't start wait proc: %r");
832 fd = open(rmtnotefile, OREAD);
834 syslog(0, "cpu", "cpu -R: can't open %s", rmtnotefile);
839 n = read(fd, buf, sizeof(buf)-1);
841 postnote(PNGROUP, pid, "hangup");
845 postnote(PNGROUP, pid, buf);
849 /* original proc waits for shell proc to die and kills note proc */
852 if(n < 0 || n == pid)
855 postnote(PNPROC, notepid, "kill");
873 [Qdir] { ".", {Qdir, 0, QTDIR}, DMDIR|0555 },
874 [Qcpunote] { "cpunote", {Qcpunote, 0}, 0444 },
877 typedef struct Note Note;
884 typedef struct Request Request;
891 typedef struct Fid Fid;
902 Note *nfirst, *nlast;
903 Request *rfirst, *rlast;
907 fsreply(int fd, Fcall *f)
909 uchar buf[IOHDRSZ+Maxfdata];
913 fprint(2, "notefs: <-%F\n", f);
914 n = convS2M(f, buf, sizeof buf);
916 if(write(fd, buf, n) != n){
924 /* match a note read request with a note, reply to the request */
936 if(rp == nil || np == nil){
940 nfs.rfirst = rp->next;
941 nfs.nfirst = np->next;
945 rp->f.count = strlen(np->msg);
946 rp->f.data = np->msg;
947 rv = fsreply(fd, &rp->f);
962 for(l = &nfs.rfirst; *l != nil; l = &(*l)->next){
964 if(rp->f.tag == tag){
980 for(i = 0; i < Nfid; i++){
981 if(freefid < 0 && fids[i].file < 0)
983 if(fids[i].fid == fid)
987 fids[freefid].fid = fid;
988 return &fids[freefid];
994 fsstat(int fd, Fid *fid, Fcall *f)
999 memset(&d, 0, sizeof(d));
1000 d.name = fstab[fid->file].name;
1004 d.qid = fstab[fid->file].qid;
1005 d.mode = fstab[fid->file].perm;
1006 d.atime = d.mtime = time(0);
1008 f->nstat = convD2M(&d, statbuf, sizeof statbuf);
1009 return fsreply(fd, f);
1013 fsread(int fd, Fid *fid, Fcall *f)
1023 if(f->offset == 0 && f->count >0){
1024 memset(&d, 0, sizeof(d));
1025 d.name = fstab[Qcpunote].name;
1029 d.qid = fstab[Qcpunote].qid;
1030 d.mode = fstab[Qcpunote].perm;
1031 d.atime = d.mtime = time(0);
1032 f->count = convD2M(&d, buf, sizeof buf);
1033 f->data = (char*)buf;
1036 return fsreply(fd, f);
1038 rp = mallocz(sizeof(*rp), 1);
1043 if(nfs.rfirst == nil)
1046 nfs.rlast->next = rp;
1053 char Eperm[] = "permission denied";
1054 char Enofile[] = "out of files";
1055 char Enotdir[] = "not a directory";
1060 uchar buf[IOHDRSZ+Maxfdata];
1068 fmtinstall('F', fcallfmt);
1070 for(n = 0; n < Nfid; n++){
1077 n = read9pmsg(fd, buf, sizeof(buf));
1080 fprint(2, "read9pmsg(%d) returns %d: %r\n", fd, n);
1085 if(convM2S(buf, n, &f) <= BIT16SZ)
1088 fprint(2, "notefs: ->%F\n", &f);
1090 fid = getfid(f.fid);
1101 f.ename = "unknown type";
1107 if(f.msize > IOHDRSZ+Maxfdata)
1108 f.msize = IOHDRSZ+Maxfdata;
1112 f.ename = "authentication not required";
1115 f.qid = fstab[Qdir].qid;
1120 if(f.newfid != f.fid){
1121 nfid = getfid(f.newfid);
1124 nfid->file = fid->file;
1127 for(i=0; i<f.nwname && i<MAXWELEM; i++){
1128 if(fid->file != Qdir){
1133 if(strcmp(f.wname[i], "..") == 0){
1134 wqid[i] = fstab[Qdir].qid;
1137 if(strcmp(f.wname[i], "cpunote") != 0){
1140 f.ename = "file does not exist";
1144 fid->file = Qcpunote;
1145 wqid[i] = fstab[Qcpunote].qid;
1147 if(nfid != nil && (f.type == Rerror || i < f.nwname))
1149 if(f.type != Rerror){
1151 for(i=0; i<f.nwqid; i++)
1152 f.wqid[i] = wqid[i];
1156 if(f.mode != OREAD){
1161 fid->omode = f.mode;
1162 if(fid->file == Qcpunote)
1164 f.qid = fstab[fid->file].qid;
1168 if(fsread(fd, fid, &f) < 0)
1173 if(fid->omode != -1 && fid->file == Qcpunote){
1175 if(ncpunote == 0) /* remote side is done */
1182 if(fsstat(fd, fid, &f) < 0)
1195 if(fsreply(fd, &f) < 0)
1200 fprint(2, "notefs exiting: %r\n");
1202 postnote(PNGROUP, exportpid, "kill");
1204 fprint(2, "postnote PNGROUP %d: %r\n", exportpid);
1208 char notebuf[ERRMAX];
1211 catcher(void*, char *text)
1216 if(n >= sizeof(notebuf))
1217 n = sizeof(notebuf)-1;
1218 memmove(notebuf, text, n);
1224 * mount in /dev a note file for the remote side to read.
1227 lclnoteproc(int netfd)
1235 fprint(2, "cpu: can't start note proc: pipe: %r\n");
1239 /* new proc mounts and returns to start exportfs */
1240 switch(pid = rfork(RFPROC|RFNAMEG|RFFDG|RFMEM)){
1245 fprint(2, "cpu: can't start note proc: rfork: %r\n");
1249 if(mount(pfd[1], -1, "/dev", MBEFORE, "") < 0)
1250 fprint(2, "cpu: can't mount note proc: %r\n");
1258 /* new proc listens for note file system rpc's */
1259 switch(rfork(RFPROC|RFNAMEG|RFMEM)){
1261 fprint(2, "cpu: can't start note proc: rfork1: %r\n");
1268 /* original proc waits for notes */
1278 np = mallocz(sizeof(Note), 1);
1280 strcpy(np->msg, notebuf);
1282 if(nfs.nfirst == nil)
1285 nfs.nlast->next = np;
1291 } else if(w->pid == exportpid)
1298 /* exits(w->msg); */