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);
195 /* run the command */
196 switch(cmdpid = rfork(RFPROC|RFFDG|RFNOTEG)){
198 sysfatal("rfork: %r");
201 if(mounter("/dev", MBEFORE, fd, exnum) < 0)
202 sysfatal("mounter: %r");
206 open("/dev/cons", OWRITE);
207 open("/dev/cons", OWRITE);
208 if(rfork(RFPROC|RFMEM|RFFDG) == 0){
209 exec(kbdfs[0], kbdfs);
214 rendezvous(&cmdpid, 0);
217 open("/dev/cons", OREAD);
219 fprint(2, "exec %s: %r\n", argv[0]);
226 rendezvous(&cmdpid, 0);
227 kbdin = open("/dev/kbdin", OWRITE);
228 unmount(nil, "/dev");
229 bind("#c", "/dev", MREPL);
231 /* run the service */
232 srvfd = vncannounce(net, display, adir, baseport);
234 sysfatal("announce failed");
236 fprint(2, "announced in %s\n", adir);
239 notify(noteshutdown);
242 cfd = listen(adir, ldir);
246 fprint(2, "call in %s\n", ldir);
247 fd = accept(cfd, ldir);
252 v = mallocz(sizeof(Vncs), 1);
262 getremote(ldir, v->remote);
263 strcpy(v->netpath, ldir);
265 v->next = clients.head;
274 parsedisplay(char *p)
282 n = strtol(p+1, &p, 10);
289 getremote(char *ldir, char *remote)
291 char buf[NETPATHLEN];
294 snprint(buf, sizeof buf, "%s/remote", ldir);
295 strcpy(remote, "<none>");
296 if((fd = open(buf, OREAD)) < 0)
298 n = readn(fd, remote, NETPATHLEN-1);
303 if(n>0 && remote[n-1] == '\n')
312 v = va_arg(fmt->args, Vncs*);
313 return fmtprint(fmt, "[%d] %s %s", getpid(), v->remote, v->netpath);
317 * We register exiting as an atexit handler in each proc, so that
318 * client procs need merely exit when something goes wrong.
325 /* remove self from client list if there */
327 for(l=&clients.head; *l; l=&(*l)->next)
334 /* if last proc, free v */
336 if(++v->ndead < v->nproc){
341 freerlist(&v->rlist);
348 freememimage(v->image);
362 fprint(2, "%V: hangup\n", (Vncs*)v);
363 exits(0); /* atexit and exiting() will take care of everything */
367 * Kill all clients except safe.
368 * Used to start a non-shared client and at shutdown.
371 killclients(Vncs *safe)
376 for(v=clients.head; v; v=v->next){
391 * Kill the executing command and then kill everyone else.
392 * Called to close up shop at the end of the day
393 * and also if we get an unexpected note.
395 static char killkin[] = "die vnc kin";
399 postnote(PNGROUP, cmdpid, "hangup");
406 postnote(PNGROUP, getpid(), killkin);
413 fprint(2, "vnc server shutdown\n");
418 noteshutdown(void*, char *msg)
420 if(strcmp(msg, killkin) == 0) /* already shutting down */
427 * Kill a specific instance of a server.
430 vnckill(char *net, int display, int baseport)
433 char buf[NETPATHLEN], *p;
436 snprint(buf, sizeof buf, "%s/tcp/%d/local", net, i);
437 if((fd = open(buf, OREAD)) < 0)
438 sysfatal("did not find display");
439 n = read(fd, buf, sizeof buf-1);
444 p = strchr(buf, '!');
448 if(port != display+baseport)
450 snprint(buf, sizeof buf, "%s/tcp/%d/ctl", net, i);
451 fd = open(buf, OWRITE);
453 sysfatal("cannot open %s: %r", buf);
454 if(write(fd, "hangup", 6) != 6)
455 sysfatal("cannot hangup %s: %r", buf);
462 * Look for a port on which to announce.
463 * If display != -1, we only try that one.
466 * Returns the announce fd.
469 vncannounce(char *net, int display, char *adir, int base)
472 char addr[NETPATHLEN];
482 for(; port<=eport; port++){
483 snprint(addr, sizeof addr, "%s/tcp!*!%d", net, port);
484 if((fd = announce(addr, adir)) >= 0){
485 fprint(2, "server started on display :%d\n", port-base);
490 fprint(2, "could not find any ports to announce\n");
492 fprint(2, "announce: %r\n");
497 * Handle a new connection.
499 static void clientreadproc(Vncs*);
500 static void clientwriteproc(Vncs*);
501 static void chan2fmt(Pixfmt*, ulong);
502 static ulong fmt2chan(Pixfmt*);
511 /* caller returns to listen */
512 switch(rfork(RFPROC|RFMEM|RFNAMEG)){
514 fprint(2, "%V: fork failed: %r\n", v);
524 if(!atexit(exiting)){
525 fprint(2, "%V: could not register atexit handler: %r; hanging up\n", v);
531 memset(&conn, 0, sizeof conn);
532 conn.cert = readcert(cert, &conn.certlen);
533 if(conn.cert == nil){
534 fprint(2, "%V: could not read cert %s: %r; hanging up\n", v, cert);
537 fd = tlsServer(v->datafd, &conn);
539 fprint(2, "%V: tlsServer: %r; hanging up\n", v);
542 free(conn.sessionID);
548 free(conn.sessionID);
550 vncinit(v->datafd, v->ctlfd, v);
553 fprint(2, "%V: handshake\n", v);
554 if(vncsrvhandshake(v) < 0){
555 fprint(2, "%V: handshake failed; hanging up\n", v);
559 fprint(2, "%V: auth\n", v);
560 if(vncsrvauth(v) < 0){
561 fprint(2, "%V: auth failed; hanging up\n", v);
565 shared = vncrdchar(v);
568 fprint(2, "%V: %sshared\n", v, shared ? "" : "not ");
572 v->dim = (Point){Dx(gscreen->r), Dy(gscreen->r)};
573 vncwrpoint(v, v->dim);
575 fprint(2, "%V: send screen size %P (rect %R)\n", v, v->dim, gscreen->r);
577 v->bpp = gscreen->depth;
578 v->depth = gscreen->depth;
581 chan2fmt(v, gscreen->chan);
583 fprint(2, "%V: bpp=%d, depth=%d, chan=%s\n", v,
584 v->bpp, v->depth, chantostr(buf, gscreen->chan));
587 vncwrbytes(v, "Plan9 Desktop", 14);
591 fprint(2, "%V: handshaking done\n", v);
593 switch(rfork(RFPROC|RFMEM)){
595 fprint(2, "%V: cannot fork: %r; hanging up\n", v);
603 if(atexit(exiting) == 0){
605 fprint(2, "%V: could not register atexit handler: %r; hanging up\n", v);
614 vncname(char *fmt, ...)
617 char name[64], buf[32];
621 vsnprint(name, sizeof name, fmt, arg);
624 sprint(buf, "/proc/%d/args", getpid());
625 if((fd = open(buf, OWRITE)) >= 0){
626 write(fd, name, strlen(name));
632 * Set the pixel format being sent. Can only happen once.
633 * (Maybe a client would send this again if the screen changed
634 * underneath it? If we want to support this we need a way to
635 * make sure the current image is no longer in use, so we can free it.
643 v->Pixfmt = vncrdpixfmt(v);
646 fprint(2, "%V: bad pixel format; hanging up\n", v);
653 * Set the preferred encoding list. Can only happen once.
654 * If we want to support changing this more than once then
655 * we need to put a lock around the encoding functions
656 * so as not to conflict with updateimage.
675 if(v->countrect != nil)
680 v->countrect = countraw;
681 v->sendrect = sendraw;
685 v->countrect = countrre;
686 v->sendrect = sendrre;
689 v->encname = "corre";
690 v->countrect = countcorre;
691 v->sendrect = sendcorre;
694 v->encname = "hextile";
695 v->countrect = counthextile;
696 v->sendrect = sendhextile;
701 if(v->countrect == nil){
703 v->countrect = countraw;
704 v->sendrect = sendraw;
708 fprint(2, "Encoding with %s%s%s\n", v->encname,
709 v->copyrect ? ", copyrect" : "",
710 v->canwarp ? ", canwarp" : "");
714 * Continually read updates from one client.
717 clientreadproc(Vncs *v)
719 int incremental, key, keydown, buttons, type, x, y, n;
723 vncname("read %V", v);
729 fprint(2, "%V: unknown vnc message type %d; hanging up\n", v, type);
732 /* set pixel format */
737 /* ignore color map changes */
744 /* set encoding list */
749 /* request image update in rectangle */
751 incremental = vncrdchar(v);
755 v->updaterequest = 1;
758 drawlock(); /* protects rlist */
759 vnclock(v); /* protects updaterequest */
760 v->updaterequest = 1;
761 addtorlist(&v->rlist, r);
769 keydown = vncrdchar(v);
772 vncputc(!keydown, key);
775 /* send mouse event */
777 buttons = vncrdchar(v);
780 mousetrack(x, y, buttons, nsec()/(1000*1000LL));
789 vncrdbytes(v, buf, n);
791 vnclock(v); /* for snarfvers */
792 setsnarf(buf, n, &v->snarfvers);
807 for(; mask; mask>>=1)
812 typedef struct Col Col;
820 fmt2chan(Pixfmt *fmt)
823 int i, j, depth, n, nc;
826 /* unpack the Pixfmt channels */
827 c[0] = (Col){CRed, nbits(fmt->red.max), fmt->red.shift};
828 c[1] = (Col){CGreen, nbits(fmt->green.max), fmt->green.shift};
829 c[2] = (Col){CBlue, nbits(fmt->blue.max), fmt->blue.shift};
832 /* add an ignore channel if necessary */
833 depth = c[0].nbits+c[1].nbits+c[2].nbits;
834 if(fmt->bpp != depth){
835 /* BUG: assumes only one run of ignored bits */
839 mask = (1<<fmt->bpp)-1;
840 mask ^= fmt->red.max << fmt->red.shift;
841 mask ^= fmt->green.max << fmt->green.shift;
842 mask ^= fmt->blue.max << fmt->blue.shift;
846 for(; !(mask&1); mask>>=1)
848 c[3] = (Col){CIgnore, nbits(mask), n};
852 /* sort the channels, largest shift (leftmost bits) first */
855 if(c[j].shift > c[j-1].shift){
861 /* build the channel descriptor */
865 u |= CHAN1(c[i].type, c[i].nbits);
872 chan2fmt(Pixfmt *fmt, ulong chan)
877 for(rc = chan; rc; rc >>=8){
881 fmt->red = (Colorfmt){(1<<NBITS(c))-1, shift};
884 fmt->blue = (Colorfmt){(1<<NBITS(c))-1, shift};
887 fmt->green = (Colorfmt){(1<<NBITS(c))-1, shift};
895 * Note that r has changed on the screen.
896 * Updating the rlists is okay because they are protected by drawlock.
899 flushmemscreen(Rectangle r)
903 if(!rectclip(&r, gscreen->r))
906 for(v=clients.head; v; v=v->next)
907 addtorlist(&v->rlist, r);
912 * Queue a mouse warp note for the next update to each client.
915 mousewarpnote(Point p)
920 for(v=clients.head; v; v=v->next){
932 * Send a client his changed screen image.
933 * v is locked on entrance, locked on exit, but released during.
938 int i, ncount, nsend, docursor, needwarp;
944 int (*count)(Vncs*, Rectangle);
945 int (*send)(Vncs*, Rectangle);
950 /* warping info and unlock v so that updates can proceed */
951 needwarp = v->canwarp && v->needwarp;
956 /* copy the screen bits and then unlock the screen so updates can proceed */
959 memset(&v->rlist, 0, sizeof v->rlist);
961 /* if the cursor has moved or changed shape, we need to redraw its square */
963 if(v->cursorver != cursorver || !eqpt(v->cursorpos, cursorpos)){
965 v->cursorver = cursorver;
966 v->cursorpos = cursorpos;
975 addtorlist(&rlist, v->cursorr);
976 if(!rectclip(&cr, gscreen->r))
978 addtorlist(&rlist, cr);
981 /* copy changed screen parts, also check for parts overlapping cursor location */
982 for(i=0; i<rlist.nrect; i++){
984 docursor = rectXrect(v->cursorr, rlist.rect[i]);
985 memimagedraw(v->image, rlist.rect[i], gscreen, rlist.rect[i].min, memopaque, ZP, S);
989 cursordraw(v->image, cr);
990 addtorlist(&rlist, v->cursorr);
996 ooffset = Boffset(&v->out);
997 /* no more locks are held; talk to the client */
999 if(rlist.nrect == 0 && needwarp == 0){
1004 count = v->countrect;
1006 if(count == nil || send == nil){
1012 for(i=0; i<rlist.nrect; i++)
1013 ncount += (*count)(v, rlist.rect[i]);
1016 fprint(2, "sendupdate: rlist.nrect=%d, ncount=%d", rlist.nrect, ncount);
1019 vncwrchar(v, MFrameUpdate);
1021 vncwrshort(v, ncount+needwarp);
1024 for(i=0; i<rlist.nrect; i++)
1025 nsend += (*send)(v, rlist.rect[i]);
1027 if(ncount != nsend){
1028 fprint(2, "%V: ncount=%d, nsend=%d; hanging up\n", v, ncount, nsend);
1033 vncwrrect(v, Rect(warppt.x, warppt.y, warppt.x+1, warppt.y+1));
1034 vncwrlong(v, EncMouseWarp);
1039 fprint(2, " in %lldms, %lld bytes\n", t1/1000000, Boffset(&v->out) - ooffset);
1047 * Update the snarf buffer if it has changed.
1050 updatesnarf(Vncs *v)
1055 if(v->snarfvers == snarf.vers)
1066 memmove(buf, snarf.buf, len);
1067 v->snarfvers = snarf.vers;
1070 vncwrchar(v, MSCut);
1071 vncwrbytes(v, "pad", 3);
1073 vncwrbytes(v, buf, len);
1079 * Continually update one client.
1082 clientwriteproc(Vncs *v)
1084 char buf[32], buf2[32];
1087 vncname("write %V", v);
1092 if((v->image == nil && v->imagechan!=0)
1093 || (v->image && v->image->chan != v->imagechan)){
1095 freememimage(v->image);
1096 v->image = allocmemimage(Rpt(ZP, v->dim), v->imagechan);
1097 if(v->image == nil){
1098 fprint(2, "%V: allocmemimage: %r; hanging up\n", v);
1102 fprint(2, "%V: translating image from chan=%s to chan=%s\n",
1103 v, chantostr(buf, gscreen->chan), chantostr(buf2, v->imagechan));
1106 if(v->updaterequest){
1107 v->updaterequest = 0;
1109 sent = updateimage(v);
1111 v->updaterequest = 1;