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";
75 fprint(2, "usage: cpu [-h system] [-u user] [-a authmethod] "
76 "[-e 'crypt hash'] [-k keypattern] [-P patternfile] "
77 "[-c cmd arg ...]\n");
82 * reading /proc/pid/args yields either "name args" or "name [display args]",
83 * so return only args or display args.
92 snprint(buf, sizeof buf, "#p/%d/args", getpid());
93 if((fd = open(buf, OREAD)) < 0)
96 n = read(fd, buf, sizeof buf-1);
100 if ((lp = strchr(buf, '[')) == nil || (rp = strrchr(buf, ']')) == nil) {
101 lp = strchr(buf, ' ');
112 * based on libthread's threadsetname, but drags in less library code.
113 * actually just sets the arguments displayed.
116 procsetname(char *fmt, ...)
124 cmdname = vsmprint(fmt, arg);
128 snprint(buf, sizeof buf, "#p/%d/args", getpid());
129 if((fd = open(buf, OWRITE)) >= 0){
130 write(fd, cmdname, strlen(cmdname)+1);
137 main(int argc, char **argv)
139 char dat[MaxStr], buf[MaxStr], cmd[MaxStr], *p, *err;
140 int ac, fd, ms, data;
144 origargs = procgetname();
145 /* see if we should use a larger message size */
146 fd = open("/dev/draw", OREAD);
149 if(msgsize < ms+IOHDRSZ)
150 msgsize = ms+IOHDRSZ;
156 fatal("can't read user name: %r");
161 fatal("unknown auth method %s", p);
164 ealgs = EARGF(usage());
165 if(*ealgs == 0 || strcmp(ealgs, "clear") == 0)
172 /* ignored but accepted for compatibility */
175 p9authproto = "p9sk2";
176 remoteside(1); /* From listen */
178 case 'R': /* From listen */
182 system = EARGF(usage());
194 keyspec = smprint("%s %s", keyspec, EARGF(usage()));
197 patternfile = EARGF(usage());
200 user = EARGF(usage());
201 keyspec = smprint("%s user=%s", keyspec, user);
218 if(err = rexcall(&data, system, srvname))
219 fatal("%s: %s: %r", err, system);
221 procsetname("%s", origargs);
222 /* Tell the remote side the command to execute and where our working directory is */
224 writestr(data, cmd, "command", 0);
225 if(getwd(dat, sizeof(dat)) == 0)
226 writestr(data, "NO", "dir", 0);
228 writestr(data, dat, "dir", 0);
230 /* start up a process to pass along notes */
234 * Wait for the other end to execute and start our file service
237 if(readstr(data, buf, sizeof(buf)) < 0)
238 fatal("waiting for FS: %r");
239 if(strncmp("FS", buf, 2) != 0) {
240 print("remote cpu: %s", buf);
244 /* Begin serving the gnot namespace */
249 sprint(buf, "%d", msgsize);
256 if(patternfile != nil){
258 av[ac++] = patternfile;
262 fatal("starting exportfs: %r");
266 fatal(char *fmt, ...)
272 vsnprint(buf, sizeof(buf), fmt, arg);
274 fprint(2, "cpu: %s\n", buf);
275 syslog(0, "cpu", "%s", buf);
279 char *negstr = "negotiating authentication method";
289 switch(rfork(RFPROC|RFFDG|RFNAMEG)) {
291 fatal("rfork srvold9p: %r");
303 fd = open("/sys/log/cpu", OWRITE);
308 execl("/bin/srvold9p", "srvold9p", "-ds", nil);
310 execl("/bin/srvold9p", "srvold9p", "-s", nil);
311 fatal("exec srvold9p: %r");
319 /* Invoked with stdin, stdout and stderr connected to the network connection */
323 char user[MaxStr], home[MaxStr], buf[MaxStr], xdir[MaxStr], cmd[MaxStr];
324 int i, n, fd, badchdir, gotcmd;
327 putenv("service", "cpu");
330 /* negotiate authentication mechanism */
331 n = readstr(fd, cmd, sizeof(cmd));
333 fatal("authenticating: %r");
334 if(setamalg(cmd) < 0){
335 writestr(fd, "unsupported auth method", nil, 0);
336 fatal("bad auth method %s: %r", cmd);
338 writestr(fd, "", "", 1);
340 fd = (*am->sf)(fd, user);
342 fatal("srvauth: %r");
344 /* Set environment values for the user */
345 putenv("user", user);
346 sprint(home, "/usr/%s", user);
347 putenv("home", home);
349 /* Now collect invoking cpu's current directory or possibly a command */
351 if(readstr(fd, xdir, sizeof(xdir)) < 0)
352 fatal("dir/cmd: %r");
354 strcpy(cmd, &xdir[1]);
356 if(readstr(fd, xdir, sizeof(xdir)) < 0)
360 /* Establish the new process at the current working directory of the
363 if(strcmp(xdir, "NO") == 0)
365 else if(chdir(xdir) < 0) {
370 /* Start the gnot serving its namespace */
371 writestr(fd, "FS", "FS", 0);
372 writestr(fd, "/", "exportfs dir", 0);
374 n = read(fd, buf, sizeof(buf));
375 if(n != 2 || buf[0] != 'O' || buf[1] != 'K')
376 exits("remote tree");
381 /* make sure buffers are big by doing fversion explicitly; pick a huge number; other side will trim */
382 strcpy(buf, VERSION9P);
383 if(fversion(fd, 64*1024, buf, sizeof buf) < 0)
384 exits("fversion failed");
385 if(mount(fd, -1, "/mnt/term", MCREATE|MREPL, "") < 0)
386 exits("mount failed");
390 /* the remote noteproc uses the mount so it must follow it */
393 for(i = 0; i < 3; i++)
396 if(open("/mnt/term/dev/cons", OREAD) != 0)
398 if(open("/mnt/term/dev/cons", OWRITE) != 1)
399 exits("open stdout");
403 print("cpu: failed to chdir to '%s'\n", xdir);
406 execl("/bin/rc", "rc", "-lc", cmd, nil);
408 execl("/bin/rc", "rc", "-li", nil);
409 fatal("exec shell: %r");
413 rexcall(int *fd, char *host, char *service)
421 na = netmkaddr(host, 0, service);
422 procsetname("dialing %s", na);
423 if((*fd = dial(na, 0, dir, 0)) < 0)
426 /* negotiate authentication mechanism */
428 snprint(msg, sizeof(msg), "%s %s", am->name, ealgs);
430 snprint(msg, sizeof(msg), "%s", am->name);
431 procsetname("writing %s", msg);
432 writestr(*fd, msg, negstr, 0);
433 procsetname("awaiting auth method");
434 n = readstr(*fd, err, sizeof err);
443 procsetname("%s: auth via %s", origargs, am->name);
444 *fd = (*am->cf)(*fd);
446 return "can't authenticate";
451 writestr(int fd, char *str, char *thing, int ignore)
456 n = write(fd, str, l+1);
458 fatal("writing network: %s: %r", thing);
462 readstr(int fd, char *str, int len)
467 n = read(fd, str, 1);
479 readln(char *buf, int n)
484 n--; /* room for \0 */
487 if(read(0, p, 1) != 1)
489 if(*p == '\n' || *p == '\r')
498 * user level challenge/response
506 strecpy(chall, chall+sizeof chall, getuser());
507 print("user[%s]: ", chall);
508 if(readln(resp, sizeof(resp)) < 0)
512 writestr(fd, chall, "challenge/response", 1);
515 if(readstr(fd, chall, sizeof chall) < 0)
519 print("challenge: %s\nresponse: ", chall);
520 if(readln(resp, sizeof(resp)) < 0)
522 writestr(fd, resp, "challenge/response", 1);
528 netkeysrvauth(int fd, char *user)
535 if(readstr(fd, user, 32) < 0)
540 for(tries = 0; tries < 10; tries++){
541 if((ch = auth_challenge("proto=p9cr role=server user=%q", user)) == nil)
543 writestr(fd, ch->chal, "challenge", 1);
544 if(readstr(fd, response, sizeof response) < 0)
547 ch->nresp = strlen(response);
548 if((ai = auth_response(ch)) != nil)
554 writestr(fd, "", "challenge", 1);
555 if(auth_chuid(ai, 0) < 0)
562 mksecret(char *t, uchar *f)
564 sprint(t, "%2.2ux%2.2ux%2.2ux%2.2ux%2.2ux%2.2ux%2.2ux%2.2ux%2.2ux%2.2ux",
565 f[0], f[1], f[2], f[3], f[4], f[5], f[6], f[7], f[8], f[9]);
569 * plan9 authentication followed by rc4 encryption
575 uchar digest[SHA1dlen];
576 char fromclientsecret[21];
577 char fromserversecret[21];
581 procsetname("%s: auth_proxy proto=%q role=client %s",
582 origargs, p9authproto, keyspec);
583 ai = auth_proxy(fd, auth_getkey, "proto=%q role=client %s", p9authproto, keyspec);
586 memmove(key+4, ai->secret, ai->nsecret);
590 /* exchange random numbers */
592 for(i = 0; i < 4; i++)
594 procsetname("writing p9 key");
595 if(write(fd, key, 4) != 4)
597 procsetname("reading p9 key");
598 if(readn(fd, key+12, 4) != 4)
601 /* scramble into two secrets */
602 sha1(key, sizeof(key), digest, nil);
603 mksecret(fromclientsecret, digest);
604 mksecret(fromserversecret, digest+10);
606 /* set up encryption */
607 procsetname("pushssl");
608 i = pushssl(fd, ealgs, fromclientsecret, fromserversecret, nil);
610 werrstr("can't establish ssl connection: %r");
622 srvnoauth(int fd, char *user)
624 strecpy(user, user+MaxStr, getuser());
631 loghex(uchar *p, int n)
636 for(i = 0; i < n; i++)
637 sprint(buf+2*i, "%2.2ux", p[i]);
638 syslog(0, "cpu", "%s", buf);
642 srvp9auth(int fd, char *user)
645 uchar digest[SHA1dlen];
646 char fromclientsecret[21];
647 char fromserversecret[21];
651 ai = auth_proxy(0, nil, "proto=%q role=server %s", p9authproto, keyspec);
654 if(auth_chuid(ai, nil) < 0)
656 strecpy(user, user+MaxStr, ai->cuid);
657 memmove(key+4, ai->secret, ai->nsecret);
662 /* exchange random numbers */
664 for(i = 0; i < 4; i++)
666 if(readn(fd, key, 4) != 4)
668 if(write(fd, key+12, 4) != 4)
671 /* scramble into two secrets */
672 sha1(key, sizeof(key), digest, nil);
673 mksecret(fromclientsecret, digest);
674 mksecret(fromserversecret, digest+10);
676 /* set up encryption */
677 i = pushssl(fd, ealgs, fromserversecret, fromclientsecret, nil);
679 werrstr("can't establish ssl connection: %r");
684 * set authentication mechanism
689 for(am = authmethod; am->name != nil; am++)
690 if(strcmp(am->name, name) == 0)
697 * set authentication mechanism and encryption/hash algs
702 ealgs = strchr(s, ' ');
708 char *rmtnotefile = "/mnt/term/dev/cpunote";
711 * loop reading /mnt/term/dev/note looking for notes.
712 * The child returns to start the shell.
717 int n, fd, pid, notepid;
720 /* new proc returns to start shell */
721 pid = rfork(RFPROC|RFFDG|RFNOTEG|RFNAMEG|RFMEM);
724 syslog(0, "cpu", "cpu -R: can't start noteproc: %r");
730 /* new proc reads notes from other side and posts them to shell */
731 switch(notepid = rfork(RFPROC|RFFDG|RFMEM)){
733 syslog(0, "cpu", "cpu -R: can't start wait proc: %r");
736 fd = open(rmtnotefile, OREAD);
738 syslog(0, "cpu", "cpu -R: can't open %s", rmtnotefile);
743 n = read(fd, buf, sizeof(buf)-1);
745 postnote(PNGROUP, pid, "hangup");
749 postnote(PNGROUP, pid, buf);
753 /* original proc waits for shell proc to die and kills note proc */
756 if(n < 0 || n == pid)
759 postnote(PNPROC, notepid, "kill");
777 [Qdir] { ".", {Qdir, 0, QTDIR}, DMDIR|0555 },
778 [Qcpunote] { "cpunote", {Qcpunote, 0}, 0444 },
781 typedef struct Note Note;
788 typedef struct Request Request;
795 typedef struct Fid Fid;
806 Note *nfirst, *nlast;
807 Request *rfirst, *rlast;
811 fsreply(int fd, Fcall *f)
813 uchar buf[IOHDRSZ+Maxfdata];
817 fprint(2, "notefs: <-%F\n", f);
818 n = convS2M(f, buf, sizeof buf);
820 if(write(fd, buf, n) != n){
828 /* match a note read request with a note, reply to the request */
840 if(rp == nil || np == nil){
844 nfs.rfirst = rp->next;
845 nfs.nfirst = np->next;
849 rp->f.count = strlen(np->msg);
850 rp->f.data = np->msg;
851 rv = fsreply(fd, &rp->f);
866 for(l = &nfs.rfirst; *l != nil; l = &(*l)->next){
868 if(rp->f.tag == tag){
884 for(i = 0; i < Nfid; i++){
885 if(freefid < 0 && fids[i].file < 0)
887 if(fids[i].fid == fid)
891 fids[freefid].fid = fid;
892 return &fids[freefid];
898 fsstat(int fd, Fid *fid, Fcall *f)
903 memset(&d, 0, sizeof(d));
904 d.name = fstab[fid->file].name;
908 d.qid = fstab[fid->file].qid;
909 d.mode = fstab[fid->file].perm;
910 d.atime = d.mtime = time(0);
912 f->nstat = convD2M(&d, statbuf, sizeof statbuf);
913 return fsreply(fd, f);
917 fsread(int fd, Fid *fid, Fcall *f)
927 if(f->offset == 0 && f->count >0){
928 memset(&d, 0, sizeof(d));
929 d.name = fstab[Qcpunote].name;
933 d.qid = fstab[Qcpunote].qid;
934 d.mode = fstab[Qcpunote].perm;
935 d.atime = d.mtime = time(0);
936 f->count = convD2M(&d, buf, sizeof buf);
937 f->data = (char*)buf;
940 return fsreply(fd, f);
942 rp = mallocz(sizeof(*rp), 1);
947 if(nfs.rfirst == nil)
950 nfs.rlast->next = rp;
957 char Eperm[] = "permission denied";
958 char Enofile[] = "out of files";
959 char Enotdir[] = "not a directory";
964 uchar buf[IOHDRSZ+Maxfdata];
972 fmtinstall('F', fcallfmt);
974 for(n = 0; n < Nfid; n++){
981 n = read9pmsg(fd, buf, sizeof(buf));
984 fprint(2, "read9pmsg(%d) returns %d: %r\n", fd, n);
987 if(convM2S(buf, n, &f) <= BIT16SZ)
990 fprint(2, "notefs: ->%F\n", &f);
1003 f.ename = "unknown type";
1009 if(f.msize > IOHDRSZ+Maxfdata)
1010 f.msize = IOHDRSZ+Maxfdata;
1014 f.ename = "authentication not required";
1017 f.qid = fstab[Qdir].qid;
1022 if(f.newfid != f.fid){
1023 nfid = getfid(f.newfid);
1026 nfid->file = fid->file;
1029 for(i=0; i<f.nwname && i<MAXWELEM; i++){
1030 if(fid->file != Qdir){
1035 if(strcmp(f.wname[i], "..") == 0){
1036 wqid[i] = fstab[Qdir].qid;
1039 if(strcmp(f.wname[i], "cpunote") != 0){
1042 f.ename = "file does not exist";
1046 fid->file = Qcpunote;
1047 wqid[i] = fstab[Qcpunote].qid;
1049 if(nfid != nil && (f.type == Rerror || i < f.nwname))
1051 if(f.type != Rerror){
1053 for(i=0; i<f.nwqid; i++)
1054 f.wqid[i] = wqid[i];
1058 if(f.mode != OREAD){
1063 fid->omode = f.mode;
1064 if(fid->file == Qcpunote)
1066 f.qid = fstab[fid->file].qid;
1070 if(fsread(fd, fid, &f) < 0)
1075 if(fid->omode != -1 && fid->file == Qcpunote){
1077 if(ncpunote == 0) /* remote side is done */
1084 if(fsstat(fd, fid, &f) < 0)
1097 if(fsreply(fd, &f) < 0)
1102 fprint(2, "notefs exiting: %r\n");
1104 postnote(PNGROUP, exportpid, "kill");
1106 fprint(2, "postnote PNGROUP %d: %r\n", exportpid);
1110 char notebuf[ERRMAX];
1113 catcher(void*, char *text)
1118 if(n >= sizeof(notebuf))
1119 n = sizeof(notebuf)-1;
1120 memmove(notebuf, text, n);
1126 * mount in /dev a note file for the remote side to read.
1129 lclnoteproc(int netfd)
1137 fprint(2, "cpu: can't start note proc: pipe: %r\n");
1141 /* new proc mounts and returns to start exportfs */
1142 switch(pid = rfork(RFPROC|RFNAMEG|RFFDG|RFMEM)){
1147 fprint(2, "cpu: can't start note proc: rfork: %r\n");
1151 if(mount(pfd[1], -1, "/dev", MBEFORE, "") < 0)
1152 fprint(2, "cpu: can't mount note proc: %r\n");
1160 /* new proc listens for note file system rpc's */
1161 switch(rfork(RFPROC|RFNAMEG|RFMEM)){
1163 fprint(2, "cpu: can't start note proc: rfork1: %r\n");
1170 /* original proc waits for notes */
1180 np = mallocz(sizeof(Note), 1);
1182 strcpy(np->msg, notebuf);
1184 if(nfs.nfirst == nil)
1187 nfs.nlast->next = np;
1193 } else if(w->pid == exportpid)
1200 /* exits(w->msg); */