12 extern Dev drawdevtab;
13 extern Dev mousedevtab;
14 extern Dev consdevtab;
24 static char *msgname[] = {
25 [MPixFmt] = "MPixFmt",
26 [MFixCmap] = "MFixCmap",
27 [MSetEnc] = "MSetEnc",
28 [MFrameReq] = "MFrameReq",
34 static char *encname[] = {
36 [EncCopyRect] = "copy rect",
39 [EncHextile] = "hextile",
41 [EncTight] = "zlibtight",
42 [EncZHextile] = "zhextile",
43 [EncMouseWarp] = "mousewarp",
48 * list head. used to hold the list, the lock, dim, and pixelfmt
61 char *pixchan = "r5g6b5";
65 static Vncs **vncpriv;
67 static int parsedisplay(char*);
68 static void vnckill(char*, int, int);
69 static int vncannounce(char *net, int display, char *adir, int base);
70 static void noteshutdown(void*, char*);
71 static void vncaccept(Vncs*);
72 static int vncsfmt(Fmt*);
73 static void getremote(char*, char*);
74 static void vncname(char*, ...);
75 #pragma varargck argpos vncname 1
77 #pragma varargck type "V" Vncs*
82 fprint(2, "usage: vncs [-v] [-c cert] [-d :display] [-g widthXheight] [-p pixelfmt] [cmd [args]...]\n");
83 fprint(2, "\tto kill a server: vncs [-v] -k :display\n");
88 main(int argc, char **argv)
90 int altnet, baseport, cfd, display, exnum, fd, h, killing, w;
91 char adir[NETPATHLEN], ldir[NETPATHLEN];
92 char net[NETPATHLEN], *p;
93 char *kbdfs[] = { "/bin/aux/kbdfs", "-dq", nil };
94 char *rc[] = { "/bin/rc", "-i", nil };
97 fmtinstall('V', vncsfmt);
104 setnetmtpt(net, sizeof net, nil);
109 cert = EARGF(usage());
115 display = parsedisplay(EARGF(usage()));
119 w = strtol(p, &p, 10);
120 if(*p != 'x' && *p != 'X' && *p != ' ' && *p != ' ')
122 h = strtol(p+1, &p, 10);
129 display = parsedisplay(EARGF(usage()));
133 pixchan = EARGF(usage());
137 sleeptime = atoi(EARGF(usage()));
145 setnetmtpt(net, sizeof net, p);
151 vnckill(net, display, baseport);
156 sysfatal("announcing on alternate network requires TLS (-c)");
162 if(access(argv[0], AEXEC) < 0)
163 sysfatal("access %s for exec: %r", argv[0]);
165 /* background ourselves */
166 switch(rfork(RFPROC|RFNAMEG|RFFDG|RFNOTEG)){
168 sysfatal("rfork: %r");
175 vncpriv = privalloc();
177 sysfatal("privalloc: %r");
182 sysfatal("screeninit %dx%d %s: %s", w, h, pixchan, up->error);
184 fprint(2, "geometry is %dx%d\n", w, h);
185 screeninit(w, h, pixchan);
188 /* start file system device slaves */
189 exnum = exporter(devtab, &fd, &exportfd);
191 /* rebuild /dev because the underlying connection might go away (ick) */
192 unmount(nil, "/dev");
193 bind("#c", "/dev", MREPL);
196 if(mounter("/dev", MBEFORE, fd, exnum) < 0)
197 sysfatal("mounter: %r");
200 cmdpid = rfork(RFPROC|RFMEM|RFFDG|RFNOTEG);
203 sysfatal("rfork: %r");
209 open("/dev/cons", OWRITE);
211 open("/dev/cons", OWRITE);
213 /* start and mount kbdfs */
214 cmdpid = rfork(RFPROC|RFMEM|RFFDG|RFREND);
217 sysfatal("rfork: %r");
220 exec(kbdfs[0], kbdfs);
221 fprint(2, "exec %s: %r\n", kbdfs[0]);
224 if(waitpid() != cmdpid){
225 rendezvous(&kbdin, nil);
226 sysfatal("%s: %r", kbdfs[0]);
228 rendezvous(&kbdin, nil);
230 rfork(RFNAMEG|RFREND);
233 open("/dev/cons", OREAD);
235 open("/dev/cons", OWRITE);
237 open("/dev/cons", OWRITE);
240 fprint(2, "exec %s: %r\n", argv[0]);
244 /* wait for kbdfs to get mounted */
245 rendezvous(&kbdin, nil);
246 if((kbdin = open("/dev/kbdin", OWRITE)) < 0)
247 sysfatal("open /dev/kbdin: %r");
249 /* run the service */
250 srvfd = vncannounce(net, display, adir, baseport);
252 sysfatal("announce failed");
254 fprint(2, "announced in %s\n", adir);
257 notify(noteshutdown);
260 cfd = listen(adir, ldir);
264 fprint(2, "call in %s\n", ldir);
265 fd = accept(cfd, ldir);
270 v = mallocz(sizeof(Vncs), 1);
280 getremote(ldir, v->remote);
281 strcpy(v->netpath, ldir);
283 v->next = clients.head;
292 parsedisplay(char *p)
300 n = strtol(p+1, &p, 10);
307 getremote(char *ldir, char *remote)
309 char buf[NETPATHLEN];
312 snprint(buf, sizeof buf, "%s/remote", ldir);
313 strcpy(remote, "<none>");
314 if((fd = open(buf, OREAD)) < 0)
316 n = readn(fd, remote, NETPATHLEN-1);
321 if(n>0 && remote[n-1] == '\n')
330 v = va_arg(fmt->args, Vncs*);
331 return fmtprint(fmt, "[%d] %s %s", getpid(), v->remote, v->netpath);
335 * We register exiting as an atexit handler in each proc, so that
336 * client procs need merely exit when something goes wrong.
343 /* remove self from client list if there */
345 for(l=&clients.head; *l; l=&(*l)->next)
352 /* if last proc, free v */
354 if(++v->ndead < v->nproc){
359 freerlist(&v->rlist);
366 freememimage(v->image);
380 fprint(2, "%V: hangup\n", (Vncs*)v);
381 exits(0); /* atexit and exiting() will take care of everything */
385 * Kill all clients except safe.
386 * Used to start a non-shared client and at shutdown.
389 killclients(Vncs *safe)
394 for(v=clients.head; v; v=v->next){
409 * Kill the executing command and then kill everyone else.
410 * Called to close up shop at the end of the day
411 * and also if we get an unexpected note.
413 static char killkin[] = "die vnc kin";
417 postnote(PNGROUP, cmdpid, "hangup");
424 postnote(PNGROUP, getpid(), killkin);
431 fprint(2, "vnc server shutdown\n");
436 noteshutdown(void*, char *msg)
438 if(strcmp(msg, killkin) == 0) /* already shutting down */
445 * Kill a specific instance of a server.
448 vnckill(char *net, int display, int baseport)
451 char buf[NETPATHLEN], *p;
454 snprint(buf, sizeof buf, "%s/tcp/%d/local", net, i);
455 if((fd = open(buf, OREAD)) < 0)
456 sysfatal("did not find display");
457 n = read(fd, buf, sizeof buf-1);
462 p = strchr(buf, '!');
466 if(port != display+baseport)
468 snprint(buf, sizeof buf, "%s/tcp/%d/ctl", net, i);
469 fd = open(buf, OWRITE);
471 sysfatal("cannot open %s: %r", buf);
472 if(write(fd, "hangup", 6) != 6)
473 sysfatal("cannot hangup %s: %r", buf);
480 * Look for a port on which to announce.
481 * If display != -1, we only try that one.
484 * Returns the announce fd.
487 vncannounce(char *net, int display, char *adir, int base)
490 char addr[NETPATHLEN];
500 for(; port<=eport; port++){
501 snprint(addr, sizeof addr, "%s/tcp!*!%d", net, port);
502 if((fd = announce(addr, adir)) >= 0){
503 fprint(2, "server started on display :%d\n", port-base);
508 fprint(2, "could not find any ports to announce\n");
510 fprint(2, "announce: %r\n");
515 * Handle a new connection.
517 static void clientreadproc(Vncs*);
518 static void clientwriteproc(Vncs*);
519 static void chan2fmt(Pixfmt*, ulong);
520 static ulong fmt2chan(Pixfmt*);
529 /* caller returns to listen */
530 switch(rfork(RFPROC|RFMEM|RFNAMEG)){
532 fprint(2, "%V: fork failed: %r\n", v);
542 if(!atexit(exiting)){
543 fprint(2, "%V: could not register atexit handler: %r; hanging up\n", v);
549 memset(&conn, 0, sizeof conn);
550 conn.cert = readcert(cert, &conn.certlen);
551 if(conn.cert == nil){
552 fprint(2, "%V: could not read cert %s: %r; hanging up\n", v, cert);
555 fd = tlsServer(v->datafd, &conn);
557 fprint(2, "%V: tlsServer: %r; hanging up\n", v);
560 free(conn.sessionID);
566 free(conn.sessionID);
568 vncinit(v->datafd, v->ctlfd, v);
571 fprint(2, "%V: handshake\n", v);
572 if(vncsrvhandshake(v) < 0){
573 fprint(2, "%V: handshake failed; hanging up\n", v);
577 fprint(2, "%V: auth\n", v);
578 if(vncsrvauth(v) < 0){
579 fprint(2, "%V: auth failed; hanging up\n", v);
583 shared = vncrdchar(v);
586 fprint(2, "%V: %sshared\n", v, shared ? "" : "not ");
590 v->dim = (Point){Dx(gscreen->r), Dy(gscreen->r)};
591 vncwrpoint(v, v->dim);
593 fprint(2, "%V: send screen size %P (rect %R)\n", v, v->dim, gscreen->r);
595 v->bpp = gscreen->depth;
596 v->depth = gscreen->depth;
599 chan2fmt(v, gscreen->chan);
601 fprint(2, "%V: bpp=%d, depth=%d, chan=%s\n", v,
602 v->bpp, v->depth, chantostr(buf, gscreen->chan));
605 vncwrbytes(v, "Plan9 Desktop", 14);
609 fprint(2, "%V: handshaking done\n", v);
611 switch(rfork(RFPROC|RFMEM)){
613 fprint(2, "%V: cannot fork: %r; hanging up\n", v);
621 if(atexit(exiting) == 0){
623 fprint(2, "%V: could not register atexit handler: %r; hanging up\n", v);
632 vncname(char *fmt, ...)
635 char name[64], buf[32];
639 vsnprint(name, sizeof name, fmt, arg);
642 sprint(buf, "/proc/%d/args", getpid());
643 if((fd = open(buf, OWRITE)) >= 0){
644 write(fd, name, strlen(name));
650 * Set the pixel format being sent. Can only happen once.
651 * (Maybe a client would send this again if the screen changed
652 * underneath it? If we want to support this we need a way to
653 * make sure the current image is no longer in use, so we can free it.
661 v->Pixfmt = vncrdpixfmt(v);
664 fprint(2, "%V: bad pixel format; hanging up\n", v);
671 * Set the preferred encoding list. Can only happen once.
672 * If we want to support changing this more than once then
673 * we need to put a lock around the encoding functions
674 * so as not to conflict with updateimage.
693 if(v->countrect != nil)
698 v->countrect = countraw;
699 v->sendrect = sendraw;
703 v->countrect = countrre;
704 v->sendrect = sendrre;
707 v->encname = "corre";
708 v->countrect = countcorre;
709 v->sendrect = sendcorre;
712 v->encname = "hextile";
713 v->countrect = counthextile;
714 v->sendrect = sendhextile;
719 if(v->countrect == nil){
721 v->countrect = countraw;
722 v->sendrect = sendraw;
726 fprint(2, "Encoding with %s%s%s\n", v->encname,
727 v->copyrect ? ", copyrect" : "",
728 v->canwarp ? ", canwarp" : "");
732 * Continually read updates from one client.
735 clientreadproc(Vncs *v)
737 int incremental, key, keydown, buttons, type, x, y, n;
741 vncname("read %V", v);
747 fprint(2, "%V: unknown vnc message type %d; hanging up\n", v, type);
750 /* set pixel format */
755 /* ignore color map changes */
762 /* set encoding list */
767 /* request image update in rectangle */
769 incremental = vncrdchar(v);
773 v->updaterequest = 1;
776 drawlock(); /* protects rlist */
777 vnclock(v); /* protects updaterequest */
778 v->updaterequest = 1;
779 addtorlist(&v->rlist, r);
787 keydown = vncrdchar(v);
790 vncputc(!keydown, key);
793 /* send mouse event */
795 buttons = vncrdchar(v);
798 mousetrack(x, y, buttons, nsec()/(1000*1000LL));
807 vncrdbytes(v, buf, n);
809 vnclock(v); /* for snarfvers */
810 setsnarf(buf, n, &v->snarfvers);
825 for(; mask; mask>>=1)
830 typedef struct Col Col;
838 fmt2chan(Pixfmt *fmt)
841 int i, j, depth, n, nc;
844 /* unpack the Pixfmt channels */
845 c[0] = (Col){CRed, nbits(fmt->red.max), fmt->red.shift};
846 c[1] = (Col){CGreen, nbits(fmt->green.max), fmt->green.shift};
847 c[2] = (Col){CBlue, nbits(fmt->blue.max), fmt->blue.shift};
850 /* add an ignore channel if necessary */
851 depth = c[0].nbits+c[1].nbits+c[2].nbits;
852 if(fmt->bpp != depth){
853 /* BUG: assumes only one run of ignored bits */
857 mask = (1<<fmt->bpp)-1;
858 mask ^= fmt->red.max << fmt->red.shift;
859 mask ^= fmt->green.max << fmt->green.shift;
860 mask ^= fmt->blue.max << fmt->blue.shift;
864 for(; !(mask&1); mask>>=1)
866 c[3] = (Col){CIgnore, nbits(mask), n};
870 /* sort the channels, largest shift (leftmost bits) first */
873 if(c[j].shift > c[j-1].shift){
879 /* build the channel descriptor */
883 u |= CHAN1(c[i].type, c[i].nbits);
890 chan2fmt(Pixfmt *fmt, ulong chan)
895 for(rc = chan; rc; rc >>=8){
899 fmt->red = (Colorfmt){(1<<NBITS(c))-1, shift};
902 fmt->blue = (Colorfmt){(1<<NBITS(c))-1, shift};
905 fmt->green = (Colorfmt){(1<<NBITS(c))-1, shift};
913 * Note that r has changed on the screen.
914 * Updating the rlists is okay because they are protected by drawlock.
917 flushmemscreen(Rectangle r)
921 if(!rectclip(&r, gscreen->r))
924 for(v=clients.head; v; v=v->next)
925 addtorlist(&v->rlist, r);
930 * Queue a mouse warp note for the next update to each client.
933 mousewarpnote(Point p)
938 for(v=clients.head; v; v=v->next){
950 * Send a client his changed screen image.
951 * v is locked on entrance, locked on exit, but released during.
956 int i, ncount, nsend, docursor, needwarp;
962 int (*count)(Vncs*, Rectangle);
963 int (*send)(Vncs*, Rectangle);
968 /* warping info and unlock v so that updates can proceed */
969 needwarp = v->canwarp && v->needwarp;
974 /* copy the screen bits and then unlock the screen so updates can proceed */
977 memset(&v->rlist, 0, sizeof v->rlist);
979 /* if the cursor has moved or changed shape, we need to redraw its square */
981 if(v->cursorver != cursorver || !eqpt(v->cursorpos, cursorpos)){
983 v->cursorver = cursorver;
984 v->cursorpos = cursorpos;
993 addtorlist(&rlist, v->cursorr);
994 if(!rectclip(&cr, gscreen->r))
996 addtorlist(&rlist, cr);
999 /* copy changed screen parts, also check for parts overlapping cursor location */
1000 for(i=0; i<rlist.nrect; i++){
1002 docursor = rectXrect(v->cursorr, rlist.rect[i]);
1003 memimagedraw(v->image, rlist.rect[i], gscreen, rlist.rect[i].min, memopaque, ZP, S);
1007 cursordraw(v->image, cr);
1008 addtorlist(&rlist, v->cursorr);
1014 ooffset = Boffset(&v->out);
1015 /* no more locks are held; talk to the client */
1017 if(rlist.nrect == 0 && needwarp == 0){
1022 count = v->countrect;
1024 if(count == nil || send == nil){
1030 for(i=0; i<rlist.nrect; i++)
1031 ncount += (*count)(v, rlist.rect[i]);
1034 fprint(2, "sendupdate: rlist.nrect=%d, ncount=%d", rlist.nrect, ncount);
1037 vncwrchar(v, MFrameUpdate);
1039 vncwrshort(v, ncount+needwarp);
1042 for(i=0; i<rlist.nrect; i++)
1043 nsend += (*send)(v, rlist.rect[i]);
1045 if(ncount != nsend){
1046 fprint(2, "%V: ncount=%d, nsend=%d; hanging up\n", v, ncount, nsend);
1051 vncwrrect(v, Rect(warppt.x, warppt.y, warppt.x+1, warppt.y+1));
1052 vncwrlong(v, EncMouseWarp);
1057 fprint(2, " in %lldms, %lld bytes\n", t1/1000000, Boffset(&v->out) - ooffset);
1065 * Update the snarf buffer if it has changed.
1068 updatesnarf(Vncs *v)
1073 if(v->snarfvers == snarf.vers)
1084 memmove(buf, snarf.buf, len);
1085 v->snarfvers = snarf.vers;
1088 vncwrchar(v, MSCut);
1089 vncwrbytes(v, "pad", 3);
1091 vncwrbytes(v, buf, len);
1097 * Continually update one client.
1100 clientwriteproc(Vncs *v)
1102 char buf[32], buf2[32];
1105 vncname("write %V", v);
1110 if((v->image == nil && v->imagechan!=0)
1111 || (v->image && v->image->chan != v->imagechan)){
1113 freememimage(v->image);
1114 v->image = allocmemimage(Rpt(ZP, v->dim), v->imagechan);
1115 if(v->image == nil){
1116 fprint(2, "%V: allocmemimage: %r; hanging up\n", v);
1120 fprint(2, "%V: translating image from chan=%s to chan=%s\n",
1121 v, chantostr(buf, gscreen->chan), chantostr(buf2, v->imagechan));
1124 if(v->updaterequest){
1125 v->updaterequest = 0;
1127 sent = updateimage(v);
1129 v->updaterequest = 1;