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)) {
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], home[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 /* Set environment values for the user */
368 putenv("user", user);
369 snprint(home, sizeof(home), "/usr/%s", user);
370 putenv("home", home);
372 /* Now collect invoking cpu's current directory or possibly a command */
374 if(readstr(fd, xdir, sizeof(xdir)) < 0)
375 fatal("dir/cmd: %r");
377 strcpy(cmd, &xdir[1]);
379 if(readstr(fd, xdir, sizeof(xdir)) < 0)
383 /* Establish the new process at the current working directory of the
386 if(strcmp(xdir, "NO") == 0)
388 else if(chdir(xdir) < 0) {
393 /* Start the gnot serving its namespace */
394 writestr(fd, "FS", "FS", 0);
395 writestr(fd, "/", "exportfs dir", 0);
397 n = read(fd, buf, sizeof(buf));
398 if(n != 2 || buf[0] != 'O' || buf[1] != 'K')
399 exits("remote tree");
404 /* make sure buffers are big by doing fversion explicitly; pick a huge number; other side will trim */
405 strcpy(buf, VERSION9P);
406 if(fversion(fd, 64*1024, buf, sizeof buf) < 0)
407 exits("fversion failed");
408 if(mount(fd, -1, "/mnt/term", MCREATE|MREPL, "") < 0)
409 exits("mount failed");
413 /* the remote noteproc uses the mount so it must follow it */
416 for(i = 0; i < 3; i++)
419 if(open("/mnt/term/dev/cons", OREAD) != 0)
421 if(open("/mnt/term/dev/cons", OWRITE) != 1)
422 exits("open stdout");
426 print("cpu: failed to chdir to '%s'\n", xdir);
429 execl("/bin/rc", "rc", "-lc", cmd, nil);
431 execl("/bin/rc", "rc", "-li", nil);
432 fatal("exec shell: %r");
436 rexcall(int *fd, char *host, char *service)
444 na = netmkaddr(host, 0, service);
445 procsetname("dialing %s", na);
446 if((*fd = dial(na, 0, dir, 0)) < 0)
449 /* negotiate aan filter extension */
451 writestr(*fd, "aan", "negotiating aan", 0);
452 n = readstr(*fd, err, sizeof err);
454 return "negotiating aan";
461 /* negotiate authentication mechanism */
463 snprint(msg, sizeof(msg), "%s %s", am->name, ealgs);
465 snprint(msg, sizeof(msg), "%s", am->name);
466 procsetname("writing %s", msg);
467 writestr(*fd, msg, negstr, 0);
468 procsetname("awaiting auth method");
469 n = readstr(*fd, err, sizeof err);
478 procsetname("%s: auth via %s", origargs, am->name);
479 *fd = (*am->cf)(*fd);
481 return "can't authenticate";
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)
553 return filter(fd, system);
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)
593 return filter(fd, nil);
597 mksecret(char *t, uchar *f)
599 sprint(t, "%2.2ux%2.2ux%2.2ux%2.2ux%2.2ux%2.2ux%2.2ux%2.2ux%2.2ux%2.2ux",
600 f[0], f[1], f[2], f[3], f[4], f[5], f[6], f[7], f[8], f[9]);
604 * plan9 authentication followed by rc4 encryption
609 uchar key[16], digest[SHA1dlen];
610 char fromclientsecret[21];
611 char fromserversecret[21];
615 procsetname("%s: auth_proxy proto=%q role=client %s",
616 origargs, p9authproto, keyspec);
617 ai = auth_proxy(fd, auth_getkey, "proto=%q role=client %s", p9authproto, keyspec);
624 assert(ai->nsecret <= sizeof(key)-4);
625 memmove(key+4, ai->secret, ai->nsecret);
628 /* exchange random numbers */
630 for(i = 0; i < 4; i++)
632 procsetname("writing p9 key");
633 if(write(fd, key, 4) != 4)
635 procsetname("reading p9 key");
636 if(readn(fd, key+12, 4) != 4)
639 /* scramble into two secrets */
640 sha1(key, sizeof(key), digest, nil);
641 mksecret(fromclientsecret, digest);
642 mksecret(fromserversecret, digest+10);
644 if((fd = filter(fd, system)) < 0)
647 /* set up encryption */
648 procsetname("pushssl");
649 fd = pushssl(fd, ealgs, fromclientsecret, fromserversecret, nil);
651 werrstr("can't establish ssl connection: %r");
663 srvnoauth(int fd, char *user)
665 strecpy(user, user+MaxStr, getuser());
672 loghex(uchar *p, int n)
677 for(i = 0; i < n; i++)
678 sprint(buf+2*i, "%2.2ux", p[i]);
679 syslog(0, "cpu", "%s", buf);
683 srvp9auth(int fd, char *user)
685 uchar key[16], digest[SHA1dlen];
686 char fromclientsecret[21];
687 char fromserversecret[21];
691 ai = auth_proxy(fd, nil, "proto=%q role=server %s", p9authproto, keyspec);
694 if(auth_chuid(ai, nil) < 0)
696 snprint(user, MaxStr, "%s", ai->cuid);
701 assert(ai->nsecret <= sizeof(key)-4);
702 memmove(key+4, ai->secret, ai->nsecret);
705 /* exchange random numbers */
707 for(i = 0; i < 4; i++)
709 if(readn(fd, key, 4) != 4)
711 if(write(fd, key+12, 4) != 4)
714 /* scramble into two secrets */
715 sha1(key, sizeof(key), digest, nil);
716 mksecret(fromclientsecret, digest);
717 mksecret(fromserversecret, digest+10);
719 if((fd = filter(fd, nil)) < 0)
722 /* set up encryption */
723 fd = pushssl(fd, ealgs, fromserversecret, fromclientsecret, nil);
725 werrstr("can't establish ssl connection: %r");
730 * set authentication mechanism
735 for(am = authmethod; am->name != nil; am++)
736 if(strcmp(am->name, name) == 0)
743 * set authentication mechanism and encryption/hash algs
748 ealgs = strchr(s, ' ');
755 filter(int fd, char *host)
757 char addr[128], buf[256], *s, *file, *argv[16];
758 int p[2], lfd, flags, len, argc;
762 procsetname("filter %s", filterp);
763 flags = RFNOWAIT|RFPROC|RFMEM|RFFDG;
766 if(announce(anstring, addr) < 0)
767 fatal("filter: Cannot announce %s: %r", anstring);
768 snprint(buf, sizeof(buf), "%s/local", addr);
769 if((lfd = open(buf, OREAD)) < 0)
770 fatal("filter: Cannot open %s: %r", buf);
771 if((len = read(lfd, buf, sizeof buf - 1)) < 0)
772 fatal("filter: Cannot read %s: %r", buf);
775 if(s = strchr(buf, '\n'))
777 if(write(fd, buf, len) != len)
778 fatal("filter: cannot write port; %r");
782 if((len = read(fd, buf, sizeof buf - 1)) < 0)
783 fatal("filter: cannot read port; %r");
785 if((s = strrchr(buf, '!')) == nil)
786 fatal("filter: malformed remote port: %s", buf);
787 snprint(addr, sizeof(addr), "%s", netmkaddr(host, "tcp", s+1));
790 snprint(buf, sizeof(buf), "%s", filterp);
791 if((argc = tokenize(buf, argv, nelem(argv)-3)) <= 0)
792 fatal("filter: empty command");
798 if(s = strrchr(argv[0], '/'))
802 fatal("filter: pipe; %r");
804 switch(rfork(flags)) {
806 fatal("filter: rfork; %r\n");
808 if (dup(p[0], 1) < 0)
809 fatal("filter: Cannot dup to 1; %r");
810 if (dup(p[0], 0) < 0)
811 fatal("filter: Cannot dup to 0; %r");
815 fatal("filter: exec; %r");
823 char *rmtnotefile = "/mnt/term/dev/cpunote";
826 * loop reading /mnt/term/dev/note looking for notes.
827 * The child returns to start the shell.
832 int n, fd, pid, notepid;
835 /* new proc returns to start shell */
836 pid = rfork(RFPROC|RFFDG|RFNOTEG|RFNAMEG|RFMEM);
839 syslog(0, "cpu", "cpu -R: can't start noteproc: %r");
845 /* new proc reads notes from other side and posts them to shell */
846 switch(notepid = rfork(RFPROC|RFFDG|RFMEM)){
848 syslog(0, "cpu", "cpu -R: can't start wait proc: %r");
851 fd = open(rmtnotefile, OREAD);
853 syslog(0, "cpu", "cpu -R: can't open %s", rmtnotefile);
858 n = read(fd, buf, sizeof(buf)-1);
860 postnote(PNGROUP, pid, "hangup");
864 postnote(PNGROUP, pid, buf);
868 /* original proc waits for shell proc to die and kills note proc */
871 if(n < 0 || n == pid)
874 postnote(PNPROC, notepid, "kill");
892 [Qdir] { ".", {Qdir, 0, QTDIR}, DMDIR|0555 },
893 [Qcpunote] { "cpunote", {Qcpunote, 0}, 0444 },
896 typedef struct Note Note;
903 typedef struct Request Request;
910 typedef struct Fid Fid;
921 Note *nfirst, *nlast;
922 Request *rfirst, *rlast;
926 fsreply(int fd, Fcall *f)
928 uchar buf[IOHDRSZ+Maxfdata];
932 fprint(2, "notefs: <-%F\n", f);
933 n = convS2M(f, buf, sizeof buf);
935 if(write(fd, buf, n) != n){
943 /* match a note read request with a note, reply to the request */
955 if(rp == nil || np == nil){
959 nfs.rfirst = rp->next;
960 nfs.nfirst = np->next;
964 rp->f.count = strlen(np->msg);
965 rp->f.data = np->msg;
966 rv = fsreply(fd, &rp->f);
981 for(l = &nfs.rfirst; *l != nil; l = &(*l)->next){
983 if(rp->f.tag == tag){
999 for(i = 0; i < Nfid; i++){
1000 if(freefid < 0 && fids[i].file < 0)
1002 if(fids[i].fid == fid)
1006 fids[freefid].fid = fid;
1007 return &fids[freefid];
1013 fsstat(int fd, Fid *fid, Fcall *f)
1018 memset(&d, 0, sizeof(d));
1019 d.name = fstab[fid->file].name;
1023 d.qid = fstab[fid->file].qid;
1024 d.mode = fstab[fid->file].perm;
1025 d.atime = d.mtime = time(0);
1027 f->nstat = convD2M(&d, statbuf, sizeof statbuf);
1028 return fsreply(fd, f);
1032 fsread(int fd, Fid *fid, Fcall *f)
1042 if(f->offset == 0 && f->count >0){
1043 memset(&d, 0, sizeof(d));
1044 d.name = fstab[Qcpunote].name;
1048 d.qid = fstab[Qcpunote].qid;
1049 d.mode = fstab[Qcpunote].perm;
1050 d.atime = d.mtime = time(0);
1051 f->count = convD2M(&d, buf, sizeof buf);
1052 f->data = (char*)buf;
1055 return fsreply(fd, f);
1057 rp = mallocz(sizeof(*rp), 1);
1062 if(nfs.rfirst == nil)
1065 nfs.rlast->next = rp;
1072 char Eperm[] = "permission denied";
1073 char Enofile[] = "out of files";
1074 char Enotdir[] = "not a directory";
1079 uchar buf[IOHDRSZ+Maxfdata];
1087 fmtinstall('F', fcallfmt);
1089 for(n = 0; n < Nfid; n++){
1096 n = read9pmsg(fd, buf, sizeof(buf));
1099 fprint(2, "read9pmsg(%d) returns %d: %r\n", fd, n);
1104 if(convM2S(buf, n, &f) <= BIT16SZ)
1107 fprint(2, "notefs: ->%F\n", &f);
1109 fid = getfid(f.fid);
1120 f.ename = "unknown type";
1126 if(f.msize > IOHDRSZ+Maxfdata)
1127 f.msize = IOHDRSZ+Maxfdata;
1131 f.ename = "authentication not required";
1134 f.qid = fstab[Qdir].qid;
1139 if(f.newfid != f.fid){
1140 nfid = getfid(f.newfid);
1143 nfid->file = fid->file;
1146 for(i=0; i<f.nwname && i<MAXWELEM; i++){
1147 if(fid->file != Qdir){
1152 if(strcmp(f.wname[i], "..") == 0){
1153 wqid[i] = fstab[Qdir].qid;
1156 if(strcmp(f.wname[i], "cpunote") != 0){
1159 f.ename = "file does not exist";
1163 fid->file = Qcpunote;
1164 wqid[i] = fstab[Qcpunote].qid;
1166 if(nfid != nil && (f.type == Rerror || i < f.nwname))
1168 if(f.type != Rerror){
1170 for(i=0; i<f.nwqid; i++)
1171 f.wqid[i] = wqid[i];
1175 if(f.mode != OREAD){
1180 fid->omode = f.mode;
1181 if(fid->file == Qcpunote)
1183 f.qid = fstab[fid->file].qid;
1187 if(fsread(fd, fid, &f) < 0)
1192 if(fid->omode != -1 && fid->file == Qcpunote){
1194 if(ncpunote == 0) /* remote side is done */
1201 if(fsstat(fd, fid, &f) < 0)
1214 if(fsreply(fd, &f) < 0)
1219 fprint(2, "notefs exiting: %r\n");
1221 postnote(PNGROUP, exportpid, "kill");
1223 fprint(2, "postnote PNGROUP %d: %r\n", exportpid);
1227 char notebuf[ERRMAX];
1230 catcher(void*, char *text)
1235 if(n >= sizeof(notebuf))
1236 n = sizeof(notebuf)-1;
1237 memmove(notebuf, text, n);
1243 * mount in /dev a note file for the remote side to read.
1246 lclnoteproc(int netfd)
1254 fprint(2, "cpu: can't start note proc: pipe: %r\n");
1258 /* new proc mounts and returns to start exportfs */
1259 switch(pid = rfork(RFPROC|RFNAMEG|RFFDG|RFMEM)){
1264 fprint(2, "cpu: can't start note proc: rfork: %r\n");
1268 if(mount(pfd[1], -1, "/dev", MBEFORE, "") < 0)
1269 fprint(2, "cpu: can't mount note proc: %r\n");
1277 /* new proc listens for note file system rpc's */
1278 switch(rfork(RFPROC|RFNAMEG|RFMEM)){
1280 fprint(2, "cpu: can't start note proc: rfork1: %r\n");
1287 /* original proc waits for notes */
1297 np = mallocz(sizeof(Note), 1);
1299 strcpy(np->msg, notebuf);
1301 if(nfs.nfirst == nil)
1304 nfs.nlast->next = np;
1310 } else if(w->pid == exportpid)
1317 /* exits(w->msg); */