2 * Copyright (c) 2015 Tycho Nightingale <tycho.nightingale@pluribusnetworks.com>
3 * Copyright (c) 2015 Leon Dang
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND
16 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD$");
31 #include <sys/param.h>
32 #include <sys/socket.h>
33 #include <sys/select.h>
35 #include <arpa/inet.h>
36 #include <machine/cpufunc.h>
37 #include <machine/specialreg.h>
38 #include <netinet/in.h>
42 #include <pthread_np.h>
55 #include "sockstream.h"
57 static int rfb_debug = 0;
58 #define DPRINTF(params) if (rfb_debug) printf params
59 #define WPRINTF(params) printf params
83 uint32_t *crc; /* WxH crc cells */
84 uint32_t *crc_tmp; /* buffer to store single crc row */
85 int crc_width, crc_height;
102 struct rfb_srvr_info {
105 struct rfb_pixfmt pixfmt;
109 struct rfb_pixfmt_msg {
112 struct rfb_pixfmt pixfmt;
115 #define RFB_ENCODING_RAW 0
116 #define RFB_ENCODING_ZLIB 6
117 #define RFB_ENCODING_RESIZE -223
119 #define RFB_MAX_WIDTH 2000
120 #define RFB_MAX_HEIGHT 1200
121 #define RFB_ZLIB_BUFSZ RFB_MAX_WIDTH*RFB_MAX_HEIGHT*4
123 /* percentage changes to screen before sending the entire screen */
124 #define RFB_SEND_ALL_THRESH 25
132 struct rfb_updt_msg {
155 struct rfb_srvr_updt_msg {
161 struct rfb_srvr_rect_hdr {
169 struct rfb_cuttext_msg {
177 rfb_send_server_init_msg(int cfd)
179 struct bhyvegc_image *gc_image;
180 struct rfb_srvr_info sinfo;
182 gc_image = console_get_image();
184 sinfo.width = htons(gc_image->width);
185 sinfo.height = htons(gc_image->height);
186 sinfo.pixfmt.bpp = 32;
187 sinfo.pixfmt.depth = 32;
188 sinfo.pixfmt.bigendian = 0;
189 sinfo.pixfmt.truecolor = 1;
190 sinfo.pixfmt.red_max = htons(255);
191 sinfo.pixfmt.green_max = htons(255);
192 sinfo.pixfmt.blue_max = htons(255);
193 sinfo.pixfmt.red_shift = 16;
194 sinfo.pixfmt.green_shift = 8;
195 sinfo.pixfmt.blue_shift = 0;
196 sinfo.namelen = htonl(strlen("bhyve"));
197 (void)stream_write(cfd, &sinfo, sizeof(sinfo));
198 (void)stream_write(cfd, "bhyve", strlen("bhyve"));
202 rfb_send_resize_update_msg(struct rfb_softc *rc, int cfd)
204 struct rfb_srvr_updt_msg supdt_msg;
205 struct rfb_srvr_rect_hdr srect_hdr;
207 /* Number of rectangles: 1 */
210 supdt_msg.numrects = htons(1);
211 stream_write(cfd, &supdt_msg, sizeof(struct rfb_srvr_updt_msg));
213 /* Rectangle header */
214 srect_hdr.x = htons(0);
215 srect_hdr.y = htons(0);
216 srect_hdr.width = htons(rc->width);
217 srect_hdr.height = htons(rc->height);
218 srect_hdr.encoding = htonl(RFB_ENCODING_RESIZE);
219 stream_write(cfd, &srect_hdr, sizeof(struct rfb_srvr_rect_hdr));
223 rfb_recv_set_pixfmt_msg(struct rfb_softc *rc, int cfd)
225 struct rfb_pixfmt_msg pixfmt_msg;
227 (void)stream_read(cfd, ((void *)&pixfmt_msg)+1, sizeof(pixfmt_msg)-1);
232 rfb_recv_set_encodings_msg(struct rfb_softc *rc, int cfd)
234 struct rfb_enc_msg enc_msg;
238 assert((sizeof(enc_msg) - 1) == 3);
239 (void)stream_read(cfd, ((void *)&enc_msg)+1, sizeof(enc_msg)-1);
241 for (i = 0; i < htons(enc_msg.numencs); i++) {
242 (void)stream_read(cfd, &encoding, sizeof(encoding));
243 switch (htonl(encoding)) {
244 case RFB_ENCODING_RAW:
245 rc->enc_raw_ok = true;
247 case RFB_ENCODING_ZLIB:
248 rc->enc_zlib_ok = true;
249 deflateInit(&rc->zstream, Z_BEST_SPEED);
251 case RFB_ENCODING_RESIZE:
252 rc->enc_resize_ok = true;
259 * Calculate CRC32 using SSE4.2; Intel or AMD Bulldozer+ CPUs only
261 static __inline uint32_t
262 fast_crc32(void *buf, int len, uint32_t crcval)
264 uint32_t q = len / sizeof(uint32_t);
265 uint32_t *p = (uint32_t *)buf;
269 ".byte 0xf2, 0xf, 0x38, 0xf1, 0xf1;"
271 :"0" (crcval), "c" (*p)
281 rfb_send_rect(struct rfb_softc *rc, int cfd, struct bhyvegc_image *gc,
282 int x, int y, int w, int h)
284 struct rfb_srvr_updt_msg supdt_msg;
285 struct rfb_srvr_rect_hdr srect_hdr;
287 ssize_t nwrite, total;
293 * Send a single rectangle of the given x, y, w h dimensions.
296 /* Number of rectangles: 1 */
299 supdt_msg.numrects = htons(1);
300 nwrite = stream_write(cfd, &supdt_msg,
301 sizeof(struct rfb_srvr_updt_msg));
306 /* Rectangle header */
307 srect_hdr.x = htons(x);
308 srect_hdr.y = htons(y);
309 srect_hdr.width = htons(w);
310 srect_hdr.height = htons(h);
313 w *= sizeof(uint32_t);
314 if (rc->enc_zlib_ok) {
316 rc->zstream.total_in = 0;
317 rc->zstream.total_out = 0;
318 for (p = &gc->data[y * gc->width + x]; y < h; y++) {
319 rc->zstream.next_in = (Bytef *)p;
320 rc->zstream.avail_in = w;
321 rc->zstream.next_out = (Bytef *)zbufp;
322 rc->zstream.avail_out = RFB_ZLIB_BUFSZ + 16 -
323 rc->zstream.total_out;
324 rc->zstream.data_type = Z_BINARY;
326 /* Compress with zlib */
327 err = deflate(&rc->zstream, Z_SYNC_FLUSH);
329 WPRINTF(("zlib[rect] deflate err: %d\n", err));
330 rc->enc_zlib_ok = false;
331 deflateEnd(&rc->zstream);
334 zbufp = rc->zbuf + rc->zstream.total_out;
337 srect_hdr.encoding = htonl(RFB_ENCODING_ZLIB);
338 nwrite = stream_write(cfd, &srect_hdr,
339 sizeof(struct rfb_srvr_rect_hdr));
343 zlen = htonl(rc->zstream.total_out);
344 nwrite = stream_write(cfd, &zlen, sizeof(uint32_t));
347 return (stream_write(cfd, rc->zbuf, rc->zstream.total_out));
354 for (p = &gc->data[y * gc->width + x]; y < h; y++) {
361 srect_hdr.encoding = htonl(RFB_ENCODING_RAW);
362 nwrite = stream_write(cfd, &srect_hdr,
363 sizeof(struct rfb_srvr_rect_hdr));
367 total = stream_write(cfd, rc->zbuf, total);
373 rfb_send_all(struct rfb_softc *rc, int cfd, struct bhyvegc_image *gc)
375 struct rfb_srvr_updt_msg supdt_msg;
376 struct rfb_srvr_rect_hdr srect_hdr;
382 * Send the whole thing
385 /* Number of rectangles: 1 */
388 supdt_msg.numrects = htons(1);
389 nwrite = stream_write(cfd, &supdt_msg,
390 sizeof(struct rfb_srvr_updt_msg));
394 /* Rectangle header */
397 srect_hdr.width = htons(gc->width);
398 srect_hdr.height = htons(gc->height);
399 if (rc->enc_zlib_ok) {
400 rc->zstream.next_in = (Bytef *)gc->data;
401 rc->zstream.avail_in = gc->width * gc->height *
403 rc->zstream.next_out = (Bytef *)rc->zbuf;
404 rc->zstream.avail_out = RFB_ZLIB_BUFSZ + 16;
405 rc->zstream.data_type = Z_BINARY;
407 rc->zstream.total_in = 0;
408 rc->zstream.total_out = 0;
410 /* Compress with zlib */
411 err = deflate(&rc->zstream, Z_SYNC_FLUSH);
413 WPRINTF(("zlib deflate err: %d\n", err));
414 rc->enc_zlib_ok = false;
415 deflateEnd(&rc->zstream);
419 srect_hdr.encoding = htonl(RFB_ENCODING_ZLIB);
420 nwrite = stream_write(cfd, &srect_hdr,
421 sizeof(struct rfb_srvr_rect_hdr));
425 zlen = htonl(rc->zstream.total_out);
426 nwrite = stream_write(cfd, &zlen, sizeof(uint32_t));
429 return (stream_write(cfd, rc->zbuf, rc->zstream.total_out));
433 srect_hdr.encoding = htonl(RFB_ENCODING_RAW);
434 nwrite = stream_write(cfd, &srect_hdr,
435 sizeof(struct rfb_srvr_rect_hdr));
439 nwrite = stream_write(cfd, gc->data,
440 gc->width * gc->height * sizeof(uint32_t));
445 #define PIX_PER_CELL 32
446 #define PIXCELL_SHIFT 5
447 #define PIXCELL_MASK 0x1F
450 rfb_send_screen(struct rfb_softc *rc, int cfd, int all)
452 struct bhyvegc_image *gc_image;
455 int celly, cellwidth;
459 int rem_x, rem_y; /* remainder for resolutions not x32 pixels ratio */
461 uint32_t *crc_p, *orig_crc;
465 gc_image = console_get_image();
467 pthread_mutex_lock(&rc->mtx);
469 pthread_mutex_unlock(&rc->mtx);
473 pthread_mutex_unlock(&rc->mtx);
478 retval = rfb_send_all(rc, cfd, gc_image);
483 * Calculate the checksum for each 32x32 cell. Send each that
484 * has changed since the last scan.
487 /* Resolution changed */
489 rc->crc_width = gc_image->width;
490 rc->crc_height = gc_image->height;
494 xcells = howmany(rc->crc_width, PIX_PER_CELL);
495 ycells = howmany(rc->crc_height, PIX_PER_CELL);
497 rem_x = w & PIXCELL_MASK;
499 rem_y = h & PIXCELL_MASK;
501 rem_y = PIX_PER_CELL;
506 * Go through all cells and calculate crc. If significant number
507 * of changes, then send entire screen.
508 * crc_tmp is dual purpose: to store the new crc and to flag as
509 * a cell that has changed.
511 crc_p = rc->crc_tmp - xcells;
512 orig_crc = rc->crc - xcells;
514 memset(rc->crc_tmp, 0, sizeof(uint32_t) * xcells * ycells);
515 for (y = 0; y < h; y++) {
516 if ((y & PIXCELL_MASK) == 0) {
521 for (x = 0; x < xcells; x++) {
523 crc_p[x] = fast_crc32(p,
524 PIX_PER_CELL * sizeof(uint32_t),
527 crc_p[x] = (uint32_t)crc32(crc_p[x],
529 PIX_PER_CELL * sizeof(uint32_t));
533 /* check for crc delta if last row in cell */
534 if ((y & PIXCELL_MASK) == PIXCELL_MASK || y == (h-1)) {
535 if (orig_crc[x] != crc_p[x]) {
536 orig_crc[x] = crc_p[x];
547 crc_p[x] = fast_crc32(p,
548 rem_x * sizeof(uint32_t),
551 crc_p[x] = (uint32_t)crc32(crc_p[x],
553 rem_x * sizeof(uint32_t));
556 if ((y & PIXCELL_MASK) == PIXCELL_MASK || y == (h-1)) {
557 if (orig_crc[x] != crc_p[x]) {
558 orig_crc[x] = crc_p[x];
568 /* If number of changes is > THRESH percent, send the whole screen */
569 if (((changes * 100) / (xcells * ycells)) >= RFB_SEND_ALL_THRESH) {
570 retval = rfb_send_all(rc, cfd, gc_image);
574 /* Go through all cells, and send only changed ones */
576 for (y = 0; y < h; y += PIX_PER_CELL) {
577 /* previous cell's row */
578 celly = (y >> PIXCELL_SHIFT);
580 /* Delta check crc to previous set */
581 for (x = 0; x < xcells; x++) {
585 if (x == (xcells - 1) && rem_x > 0)
588 cellwidth = PIX_PER_CELL;
589 nwrite = rfb_send_rect(rc, cfd,
592 celly * PIX_PER_CELL,
594 y + PIX_PER_CELL >= h ? rem_y : PIX_PER_CELL);
604 pthread_mutex_lock(&rc->mtx);
606 pthread_mutex_unlock(&rc->mtx);
613 rfb_recv_update_msg(struct rfb_softc *rc, int cfd, int discardonly)
615 struct rfb_updt_msg updt_msg;
616 struct bhyvegc_image *gc_image;
618 (void)stream_read(cfd, ((void *)&updt_msg) + 1 , sizeof(updt_msg) - 1);
621 gc_image = console_get_image();
623 updt_msg.x = htons(updt_msg.x);
624 updt_msg.y = htons(updt_msg.y);
625 updt_msg.width = htons(updt_msg.width);
626 updt_msg.height = htons(updt_msg.height);
628 if (updt_msg.width != gc_image->width ||
629 updt_msg.height != gc_image->height) {
630 rc->width = gc_image->width;
631 rc->height = gc_image->height;
632 if (rc->enc_resize_ok)
633 rfb_send_resize_update_msg(rc, cfd);
639 rfb_send_screen(rc, cfd, 1);
643 rfb_recv_key_msg(struct rfb_softc *rc, int cfd)
645 struct rfb_key_msg key_msg;
647 (void)stream_read(cfd, ((void *)&key_msg) + 1, sizeof(key_msg) - 1);
649 console_key_event(key_msg.down, htonl(key_msg.code));
653 rfb_recv_ptr_msg(struct rfb_softc *rc, int cfd)
655 struct rfb_ptr_msg ptr_msg;
657 (void)stream_read(cfd, ((void *)&ptr_msg) + 1, sizeof(ptr_msg) - 1);
659 console_ptr_event(ptr_msg.button, htons(ptr_msg.x), htons(ptr_msg.y));
663 rfb_recv_cuttext_msg(struct rfb_softc *rc, int cfd)
665 struct rfb_cuttext_msg ct_msg;
666 unsigned char buf[32];
669 len = stream_read(cfd, ((void *)&ct_msg) + 1, sizeof(ct_msg) - 1);
670 ct_msg.length = htonl(ct_msg.length);
671 while (ct_msg.length > 0) {
672 len = stream_read(cfd, buf, ct_msg.length > sizeof(buf) ?
673 sizeof(buf) : ct_msg.length);
674 ct_msg.length -= len;
679 timeval_delta(struct timeval *prev, struct timeval *now)
682 n1 = now->tv_sec * 1000000 + now->tv_usec;
683 n2 = prev->tv_sec * 1000000 + prev->tv_usec;
688 rfb_wr_thr(void *arg)
690 struct rfb_softc *rc;
693 struct timeval prev_tv;
703 while (rc->cfd >= 0) {
709 err = select(cfd+1, &rfds, NULL, NULL, &tv);
713 /* Determine if its time to push screen; ~24hz */
714 gettimeofday(&tv, NULL);
715 tdiff = timeval_delta(&prev_tv, &tv);
717 prev_tv.tv_sec = tv.tv_sec;
718 prev_tv.tv_usec = tv.tv_usec;
719 if (rfb_send_screen(rc, cfd, 0) <= 0) {
724 usleep(40000 - tdiff);
732 rfb_handle(struct rfb_softc *rc, int cfd)
734 const char *vbuf = "RFB 003.008\n";
735 unsigned char buf[80];
742 /* 1a. Send server version */
743 stream_write(cfd, vbuf, strlen(vbuf));
745 /* 1b. Read client version */
746 len = read(cfd, buf, sizeof(buf));
748 /* 2a. Send security type 'none' */
750 buf[1] = 1; /* none */
751 stream_write(cfd, buf, 2);
754 /* 2b. Read agreed security type */
755 len = stream_read(cfd, buf, 1);
757 /* 2c. Write back a status of 0 */
759 stream_write(cfd, &sres, 4);
761 /* 3a. Read client shared-flag byte */
762 len = stream_read(cfd, buf, 1);
764 /* 4a. Write server-init info */
765 rfb_send_server_init_msg(cfd);
768 rc->zbuf = malloc(RFB_ZLIB_BUFSZ + 16);
769 assert(rc->zbuf != NULL);
772 rfb_send_screen(rc, cfd, 1);
774 pthread_create(&tid, NULL, rfb_wr_thr, rc);
775 pthread_set_name_np(tid, "rfbout");
777 /* Now read in client requests. 1st byte identifies type */
779 len = read(cfd, buf, 1);
781 DPRINTF(("rfb client exiting\r\n"));
787 rfb_recv_set_pixfmt_msg(rc, cfd);
790 rfb_recv_set_encodings_msg(rc, cfd);
793 rfb_recv_update_msg(rc, cfd, 1);
796 rfb_recv_key_msg(rc, cfd);
799 rfb_recv_ptr_msg(rc, cfd);
802 rfb_recv_cuttext_msg(rc, cfd);
805 WPRINTF(("rfb unknown cli-code %d!\n", buf[0] & 0xff));
811 pthread_join(tid, NULL);
813 deflateEnd(&rc->zstream);
819 struct rfb_softc *rc;
827 sigaddset(&set, SIGPIPE);
828 if (pthread_sigmask(SIG_BLOCK, &set, NULL) != 0) {
829 perror("pthread_sigmask");
834 rc->enc_raw_ok = false;
835 rc->enc_zlib_ok = false;
836 rc->enc_resize_ok = false;
838 cfd = accept(rc->sfd, NULL, NULL);
840 pthread_mutex_lock(&rc->mtx);
841 pthread_cond_signal(&rc->cond);
842 pthread_mutex_unlock(&rc->mtx);
854 sse42_supported(void)
856 u_int cpu_registers[4], ecx;
858 do_cpuid(1, cpu_registers);
860 ecx = cpu_registers[2];
862 return ((ecx & CPUID2_SSE42) != 0);
866 rfb_init(char *hostname, int port, int wait)
868 struct rfb_softc *rc;
869 struct sockaddr_in sin;
872 rc = calloc(1, sizeof(struct rfb_softc));
874 rc->crc = calloc(howmany(RFB_MAX_WIDTH * RFB_MAX_HEIGHT, 32),
876 rc->crc_tmp = calloc(howmany(RFB_MAX_WIDTH * RFB_MAX_HEIGHT, 32),
878 rc->crc_width = RFB_MAX_WIDTH;
879 rc->crc_height = RFB_MAX_HEIGHT;
881 rc->sfd = socket(AF_INET, SOCK_STREAM, 0);
887 setsockopt(rc->sfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
889 sin.sin_len = sizeof(sin);
890 sin.sin_family = AF_INET;
891 sin.sin_port = htons(port);
892 if (hostname && strlen(hostname) > 0)
893 inet_pton(AF_INET, hostname, &(sin.sin_addr));
895 sin.sin_addr.s_addr = htonl(INADDR_ANY);
897 if (bind(rc->sfd, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
902 if (listen(rc->sfd, 1) < 0) {
907 rc->hw_crc = sse42_supported();
909 rc->conn_wait = wait;
911 pthread_mutex_init(&rc->mtx, NULL);
912 pthread_cond_init(&rc->cond, NULL);
915 pthread_create(&rc->tid, NULL, rfb_thr, rc);
916 pthread_set_name_np(rc->tid, "rfb");
919 DPRINTF(("Waiting for rfb client...\n"));
920 pthread_mutex_lock(&rc->mtx);
921 pthread_cond_wait(&rc->cond, &rc->mtx);
922 pthread_mutex_unlock(&rc->mtx);