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
59 char *pixchan = "r5g6b5";
63 static Vncs **vncpriv;
65 static int parsedisplay(char*);
66 static void vnckill(char*, int, int);
67 static int vncannounce(char *net, int display, char *adir, int base);
68 static void noteshutdown(void*, char*);
69 static void vncaccept(Vncs*);
70 static int vncsfmt(Fmt*);
71 static void getremote(char*, char*);
72 static void vncname(char*, ...);
73 #pragma varargck argpos vncname 1
75 #pragma varargck type "V" Vncs*
80 fprint(2, "usage: vncs [-v] [-c cert] [-d :display] [-g widthXheight] [-p pixelfmt] [cmd [args]...]\n");
81 fprint(2, "\tto kill a server: vncs [-v] -k :display\n");
86 main(int argc, char **argv)
88 int altnet, baseport, cfd, display, exnum, fd, h, killing, w;
89 char adir[NETPATHLEN], ldir[NETPATHLEN];
90 char net[NETPATHLEN], *p;
91 char *rc[] = { "/bin/rc", "-i", nil };
94 fmtinstall('V', vncsfmt);
101 setnetmtpt(net, sizeof net, nil);
106 cert = EARGF(usage());
112 display = parsedisplay(EARGF(usage()));
116 w = strtol(p, &p, 10);
117 if(*p != 'x' && *p != 'X' && *p != ' ' && *p != ' ')
119 h = strtol(p+1, &p, 10);
126 display = parsedisplay(EARGF(usage()));
130 pixchan = EARGF(usage());
134 sleeptime = atoi(EARGF(usage()));
142 setnetmtpt(net, sizeof net, p);
148 vnckill(net, display, baseport);
153 sysfatal("announcing on alternate network requires TLS (-c)");
159 if(access(argv[0], AEXEC) < 0)
160 sysfatal("access %s for exec: %r", argv[0]);
162 /* background ourselves */
163 switch(rfork(RFPROC|RFNAMEG|RFFDG|RFNOTEG)){
165 sysfatal("rfork: %r");
172 vncpriv = privalloc();
174 sysfatal("privalloc: %r");
179 sysfatal("screeninit %dx%d %s: %s", w, h, pixchan, up->error);
181 fprint(2, "geometry is %dx%d\n", w, h);
182 screeninit(w, h, pixchan);
185 /* start file system device slaves */
186 exnum = exporter(devtab, &fd, &exportfd);
188 /* rebuild /dev because the underlying connection might go away (ick) */
189 unmount(nil, "/dev");
190 bind("#c", "/dev", MREPL);
192 /* run the command */
193 switch(cmdpid = rfork(RFPROC|RFFDG|RFNOTEG|RFNAMEG|RFREND)){
195 sysfatal("rfork: %r");
198 if(mounter("/dev", MBEFORE, fd, exnum) < 0)
199 sysfatal("mounter: %r");
204 open("/dev/cons", OREAD);
205 open("/dev/cons", OWRITE);
206 open("/dev/cons", OWRITE);
208 fprint(2, "exec %s: %r\n", argv[0]);
215 /* run the service */
216 srvfd = vncannounce(net, display, adir, baseport);
218 sysfatal("announce failed");
220 fprint(2, "announced in %s\n", adir);
223 notify(noteshutdown);
226 cfd = listen(adir, ldir);
230 fprint(2, "call in %s\n", ldir);
231 fd = accept(cfd, ldir);
236 v = mallocz(sizeof(Vncs), 1);
246 getremote(ldir, v->remote);
247 strcpy(v->netpath, ldir);
249 v->next = clients.head;
258 parsedisplay(char *p)
266 n = strtol(p+1, &p, 10);
273 getremote(char *ldir, char *remote)
275 char buf[NETPATHLEN];
278 snprint(buf, sizeof buf, "%s/remote", ldir);
279 strcpy(remote, "<none>");
280 if((fd = open(buf, OREAD)) < 0)
282 n = readn(fd, remote, NETPATHLEN-1);
287 if(n>0 && remote[n-1] == '\n')
296 v = va_arg(fmt->args, Vncs*);
297 return fmtprint(fmt, "[%d] %s %s", getpid(), v->remote, v->netpath);
301 * We register exiting as an atexit handler in each proc, so that
302 * client procs need merely exit when something goes wrong.
309 /* remove self from client list if there */
311 for(l=&clients.head; *l; l=&(*l)->next)
318 /* if last proc, free v */
320 if(++v->ndead < v->nproc){
325 freerlist(&v->rlist);
332 freememimage(v->image);
346 fprint(2, "%V: hangup\n", (Vncs*)v);
347 exits(0); /* atexit and exiting() will take care of everything */
351 * Kill all clients except safe.
352 * Used to start a non-shared client and at shutdown.
355 killclients(Vncs *safe)
360 for(v=clients.head; v; v=v->next){
375 * Kill the executing command and then kill everyone else.
376 * Called to close up shop at the end of the day
377 * and also if we get an unexpected note.
379 static char killkin[] = "die vnc kin";
383 postnote(PNGROUP, cmdpid, "hangup");
388 postnote(PNGROUP, getpid(), killkin);
395 fprint(2, "vnc server shutdown\n");
400 noteshutdown(void*, char *msg)
402 if(strcmp(msg, killkin) == 0) /* already shutting down */
409 * Kill a specific instance of a server.
412 vnckill(char *net, int display, int baseport)
415 char buf[NETPATHLEN], *p;
418 snprint(buf, sizeof buf, "%s/tcp/%d/local", net, i);
419 if((fd = open(buf, OREAD)) < 0)
420 sysfatal("did not find display");
421 n = read(fd, buf, sizeof buf-1);
426 p = strchr(buf, '!');
430 if(port != display+baseport)
432 snprint(buf, sizeof buf, "%s/tcp/%d/ctl", net, i);
433 fd = open(buf, OWRITE);
435 sysfatal("cannot open %s: %r", buf);
436 if(write(fd, "hangup", 6) != 6)
437 sysfatal("cannot hangup %s: %r", buf);
444 * Look for a port on which to announce.
445 * If display != -1, we only try that one.
448 * Returns the announce fd.
451 vncannounce(char *net, int display, char *adir, int base)
454 char addr[NETPATHLEN];
464 for(; port<=eport; port++){
465 snprint(addr, sizeof addr, "%s/tcp!*!%d", net, port);
466 if((fd = announce(addr, adir)) >= 0){
467 fprint(2, "server started on display :%d\n", port-base);
472 fprint(2, "could not find any ports to announce\n");
474 fprint(2, "announce: %r\n");
479 * Handle a new connection.
481 static void clientreadproc(Vncs*);
482 static void clientwriteproc(Vncs*);
483 static void chan2fmt(Pixfmt*, ulong);
484 static ulong fmt2chan(Pixfmt*);
493 /* caller returns to listen */
494 switch(rfork(RFPROC|RFMEM|RFNAMEG)){
496 fprint(2, "%V: fork failed: %r\n", v);
506 if(!atexit(exiting)){
507 fprint(2, "%V: could not register atexit handler: %r; hanging up\n", v);
513 memset(&conn, 0, sizeof conn);
514 conn.cert = readcert(cert, &conn.certlen);
515 if(conn.cert == nil){
516 fprint(2, "%V: could not read cert %s: %r; hanging up\n", v, cert);
519 fd = tlsServer(v->datafd, &conn);
521 fprint(2, "%V: tlsServer: %r; hanging up\n", v);
524 free(conn.sessionID);
530 free(conn.sessionID);
532 vncinit(v->datafd, v->ctlfd, v);
535 fprint(2, "%V: handshake\n", v);
536 if(vncsrvhandshake(v) < 0){
537 fprint(2, "%V: handshake failed; hanging up\n", v);
541 fprint(2, "%V: auth\n", v);
542 if(vncsrvauth(v) < 0){
543 fprint(2, "%V: auth failed; hanging up\n", v);
547 shared = vncrdchar(v);
550 fprint(2, "%V: %sshared\n", v, shared ? "" : "not ");
554 v->dim = (Point){Dx(gscreen->r), Dy(gscreen->r)};
555 vncwrpoint(v, v->dim);
557 fprint(2, "%V: send screen size %P (rect %R)\n", v, v->dim, gscreen->r);
559 v->bpp = gscreen->depth;
560 v->depth = gscreen->depth;
563 chan2fmt(v, gscreen->chan);
565 fprint(2, "%V: bpp=%d, depth=%d, chan=%s\n", v,
566 v->bpp, v->depth, chantostr(buf, gscreen->chan));
569 vncwrbytes(v, "Plan9 Desktop", 14);
573 fprint(2, "%V: handshaking done\n", v);
575 switch(rfork(RFPROC|RFMEM)){
577 fprint(2, "%V: cannot fork: %r; hanging up\n", v);
585 if(atexit(exiting) == 0){
587 fprint(2, "%V: could not register atexit handler: %r; hanging up\n", v);
596 vncname(char *fmt, ...)
599 char name[64], buf[32];
603 vsnprint(name, sizeof name, fmt, arg);
606 sprint(buf, "/proc/%d/args", getpid());
607 if((fd = open(buf, OWRITE)) >= 0){
608 write(fd, name, strlen(name));
614 * Set the pixel format being sent. Can only happen once.
615 * (Maybe a client would send this again if the screen changed
616 * underneath it? If we want to support this we need a way to
617 * make sure the current image is no longer in use, so we can free it.
625 v->Pixfmt = vncrdpixfmt(v);
628 fprint(2, "%V: bad pixel format; hanging up\n", v);
635 * Set the preferred encoding list. Can only happen once.
636 * If we want to support changing this more than once then
637 * we need to put a lock around the encoding functions
638 * so as not to conflict with updateimage.
657 if(v->countrect != nil)
662 v->countrect = countraw;
663 v->sendrect = sendraw;
667 v->countrect = countrre;
668 v->sendrect = sendrre;
671 v->encname = "corre";
672 v->countrect = countcorre;
673 v->sendrect = sendcorre;
676 v->encname = "hextile";
677 v->countrect = counthextile;
678 v->sendrect = sendhextile;
683 if(v->countrect == nil){
685 v->countrect = countraw;
686 v->sendrect = sendraw;
690 fprint(2, "Encoding with %s%s%s\n", v->encname,
691 v->copyrect ? ", copyrect" : "",
692 v->canwarp ? ", canwarp" : "");
696 * Continually read updates from one client.
699 clientreadproc(Vncs *v)
701 int incremental, key, keydown, buttons, type, x, y, n;
705 vncname("read %V", v);
711 fprint(2, "%V: unknown vnc message type %d; hanging up\n", v, type);
714 /* set pixel format */
719 /* ignore color map changes */
726 /* set encoding list */
731 /* request image update in rectangle */
733 incremental = vncrdchar(v);
737 v->updaterequest = 1;
740 drawlock(); /* protects rlist */
741 vnclock(v); /* protects updaterequest */
742 v->updaterequest = 1;
743 addtorlist(&v->rlist, r);
751 keydown = vncrdchar(v);
754 vncputc(!keydown, key);
757 /* send mouse event */
759 buttons = vncrdchar(v);
762 mousetrack(x, y, buttons, nsec()/(1000*1000LL));
771 vncrdbytes(v, buf, n);
773 vnclock(v); /* for snarfvers */
774 setsnarf(buf, n, &v->snarfvers);
789 for(; mask; mask>>=1)
794 typedef struct Col Col;
802 fmt2chan(Pixfmt *fmt)
805 int i, j, depth, n, nc;
808 /* unpack the Pixfmt channels */
809 c[0] = (Col){CRed, nbits(fmt->red.max), fmt->red.shift};
810 c[1] = (Col){CGreen, nbits(fmt->green.max), fmt->green.shift};
811 c[2] = (Col){CBlue, nbits(fmt->blue.max), fmt->blue.shift};
814 /* add an ignore channel if necessary */
815 depth = c[0].nbits+c[1].nbits+c[2].nbits;
816 if(fmt->bpp != depth){
817 /* BUG: assumes only one run of ignored bits */
821 mask = (1<<fmt->bpp)-1;
822 mask ^= fmt->red.max << fmt->red.shift;
823 mask ^= fmt->green.max << fmt->green.shift;
824 mask ^= fmt->blue.max << fmt->blue.shift;
828 for(; !(mask&1); mask>>=1)
830 c[3] = (Col){CIgnore, nbits(mask), n};
834 /* sort the channels, largest shift (leftmost bits) first */
837 if(c[j].shift > c[j-1].shift){
843 /* build the channel descriptor */
847 u |= CHAN1(c[i].type, c[i].nbits);
854 chan2fmt(Pixfmt *fmt, ulong chan)
859 for(rc = chan; rc; rc >>=8){
863 fmt->red = (Colorfmt){(1<<NBITS(c))-1, shift};
866 fmt->blue = (Colorfmt){(1<<NBITS(c))-1, shift};
869 fmt->green = (Colorfmt){(1<<NBITS(c))-1, shift};
877 * Note that r has changed on the screen.
878 * Updating the rlists is okay because they are protected by drawlock.
881 flushmemscreen(Rectangle r)
885 if(!rectclip(&r, gscreen->r))
888 for(v=clients.head; v; v=v->next)
889 addtorlist(&v->rlist, r);
894 * Queue a mouse warp note for the next update to each client.
897 mousewarpnote(Point p)
902 for(v=clients.head; v; v=v->next){
914 * Send a client his changed screen image.
915 * v is locked on entrance, locked on exit, but released during.
920 int i, ncount, nsend, docursor, needwarp;
926 int (*count)(Vncs*, Rectangle);
927 int (*send)(Vncs*, Rectangle);
932 /* warping info and unlock v so that updates can proceed */
933 needwarp = v->canwarp && v->needwarp;
938 /* copy the screen bits and then unlock the screen so updates can proceed */
941 memset(&v->rlist, 0, sizeof v->rlist);
943 /* if the cursor has moved or changed shape, we need to redraw its square */
945 if(v->cursorver != cursorver || !eqpt(v->cursorpos, cursorpos)){
947 v->cursorver = cursorver;
948 v->cursorpos = cursorpos;
957 addtorlist(&rlist, v->cursorr);
958 if(!rectclip(&cr, gscreen->r))
960 addtorlist(&rlist, cr);
963 /* copy changed screen parts, also check for parts overlapping cursor location */
964 for(i=0; i<rlist.nrect; i++){
966 docursor = rectXrect(v->cursorr, rlist.rect[i]);
967 memimagedraw(v->image, rlist.rect[i], gscreen, rlist.rect[i].min, memopaque, ZP, S);
971 cursordraw(v->image, cr);
972 addtorlist(&rlist, v->cursorr);
978 ooffset = Boffset(&v->out);
979 /* no more locks are held; talk to the client */
981 if(rlist.nrect == 0 && needwarp == 0){
986 count = v->countrect;
988 if(count == nil || send == nil){
994 for(i=0; i<rlist.nrect; i++)
995 ncount += (*count)(v, rlist.rect[i]);
998 fprint(2, "sendupdate: rlist.nrect=%d, ncount=%d", rlist.nrect, ncount);
1001 vncwrchar(v, MFrameUpdate);
1003 vncwrshort(v, ncount+needwarp);
1006 for(i=0; i<rlist.nrect; i++)
1007 nsend += (*send)(v, rlist.rect[i]);
1009 if(ncount != nsend){
1010 fprint(2, "%V: ncount=%d, nsend=%d; hanging up\n", v, ncount, nsend);
1015 vncwrrect(v, Rect(warppt.x, warppt.y, warppt.x+1, warppt.y+1));
1016 vncwrlong(v, EncMouseWarp);
1021 fprint(2, " in %lldms, %lld bytes\n", t1/1000000, Boffset(&v->out) - ooffset);
1029 * Update the snarf buffer if it has changed.
1032 updatesnarf(Vncs *v)
1037 if(v->snarfvers == snarf.vers)
1048 memmove(buf, snarf.buf, len);
1049 v->snarfvers = snarf.vers;
1052 vncwrchar(v, MSCut);
1053 vncwrbytes(v, "pad", 3);
1055 vncwrbytes(v, buf, len);
1061 * Continually update one client.
1064 clientwriteproc(Vncs *v)
1066 char buf[32], buf2[32];
1069 vncname("write %V", v);
1074 if((v->image == nil && v->imagechan!=0)
1075 || (v->image && v->image->chan != v->imagechan)){
1077 freememimage(v->image);
1078 v->image = allocmemimage(Rpt(ZP, v->dim), v->imagechan);
1079 if(v->image == nil){
1080 fprint(2, "%V: allocmemimage: %r; hanging up\n", v);
1084 fprint(2, "%V: translating image from chan=%s to chan=%s\n",
1085 v, chantostr(buf, gscreen->chan), chantostr(buf2, v->imagechan));
1088 if(v->updaterequest){
1089 v->updaterequest = 0;
1091 sent = updateimage(v);
1093 v->updaterequest = 1;