xref: /freebsd-14.2/usr.sbin/bhyve/rfb.c (revision f9e09dc5)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2015 Tycho Nightingale <[email protected]>
5  * Copyright (c) 2015 Leon Dang
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 #include <sys/cdefs.h>
31 #include <sys/param.h>
32 #ifndef WITHOUT_CAPSICUM
33 #include <sys/capsicum.h>
34 #endif
35 #include <sys/endian.h>
36 #include <sys/socket.h>
37 #include <sys/select.h>
38 #include <sys/time.h>
39 #include <arpa/inet.h>
40 #include <stdatomic.h>
41 #include <machine/cpufunc.h>
42 #include <machine/specialreg.h>
43 #include <netinet/in.h>
44 #include <netdb.h>
45 
46 #include <assert.h>
47 #ifndef WITHOUT_CAPSICUM
48 #include <capsicum_helpers.h>
49 #endif
50 #include <err.h>
51 #include <errno.h>
52 #include <pthread.h>
53 #include <pthread_np.h>
54 #include <signal.h>
55 #include <stdbool.h>
56 #include <stdlib.h>
57 #include <stdio.h>
58 #include <string.h>
59 #include <sysexits.h>
60 #include <unistd.h>
61 
62 #include <zlib.h>
63 
64 #include "bhyvegc.h"
65 #include "debug.h"
66 #include "console.h"
67 #include "rfb.h"
68 #include "sockstream.h"
69 
70 #ifndef NO_OPENSSL
71 #include <openssl/des.h>
72 #endif
73 
74 /* Delays in microseconds */
75 #define	CFD_SEL_DELAY	10000
76 #define	SCREEN_REFRESH_DELAY	33300	/* 30Hz */
77 #define	SCREEN_POLL_DELAY	(SCREEN_REFRESH_DELAY / 2)
78 
79 static int rfb_debug = 0;
80 #define	DPRINTF(params) if (rfb_debug) PRINTLN params
81 #define	WPRINTF(params) PRINTLN params
82 
83 #define VERSION_LENGTH	12
84 #define AUTH_LENGTH	16
85 #define PASSWD_LENGTH	8
86 
87 /* Protocol versions */
88 #define CVERS_3_3	'3'
89 #define CVERS_3_7	'7'
90 #define CVERS_3_8	'8'
91 
92 /* Client-to-server msg types */
93 #define CS_SET_PIXEL_FORMAT	0
94 #define CS_SET_ENCODINGS	2
95 #define CS_UPDATE_MSG		3
96 #define CS_KEY_EVENT		4
97 #define CS_POINTER_EVENT	5
98 #define CS_CUT_TEXT		6
99 #define CS_MSG_CLIENT_QEMU	255
100 
101 #define SECURITY_TYPE_NONE	1
102 #define SECURITY_TYPE_VNC_AUTH	2
103 
104 #define AUTH_FAILED_UNAUTH	1
105 #define AUTH_FAILED_ERROR	2
106 
107 struct pixfmt {
108 	bool		adjust_pixels;
109 	uint8_t		red_shift;
110 	uint8_t		green_shift;
111 	uint8_t		blue_shift;
112 };
113 
114 struct rfb_softc {
115 	int		sfd;
116 	pthread_t	tid;
117 
118 	int		cfd;
119 
120 	int		width, height;
121 
122 	const char	*password;
123 
124 	bool		enc_raw_ok;
125 	bool		enc_zlib_ok;
126 	bool		enc_resize_ok;
127 	bool		enc_extkeyevent_ok;
128 
129 	bool		enc_extkeyevent_send;
130 
131 	z_stream	zstream;
132 	uint8_t		*zbuf;
133 	int		zbuflen;
134 
135 	int		conn_wait;
136 	int		wrcount;
137 
138 	atomic_bool	sending;
139 	atomic_bool	pending;
140 	atomic_bool	update_all;
141 	atomic_bool	input_detected;
142 	atomic_bool	update_pixfmt;
143 
144 	pthread_mutex_t mtx;
145 	pthread_mutex_t pixfmt_mtx;
146 	pthread_cond_t  cond;
147 
148 	int		hw_crc;
149 	uint32_t	*crc;		/* WxH crc cells */
150 	uint32_t	*crc_tmp;	/* buffer to store single crc row */
151 	int		crc_width, crc_height;
152 
153 	struct pixfmt	pixfmt;		/* owned by the write thread */
154 	struct pixfmt	new_pixfmt;	/* managed with pixfmt_mtx */
155 	uint32_t	*pixrow;
156 };
157 
158 struct rfb_pixfmt {
159 	uint8_t		bpp;
160 	uint8_t		depth;
161 	uint8_t		bigendian;
162 	uint8_t		truecolor;
163 	uint16_t	red_max;
164 	uint16_t	green_max;
165 	uint16_t	blue_max;
166 	uint8_t		red_shift;
167 	uint8_t		green_shift;
168 	uint8_t		blue_shift;
169 	uint8_t		pad[3];
170 };
171 
172 struct rfb_srvr_info {
173 	uint16_t		width;
174 	uint16_t		height;
175 	struct rfb_pixfmt	pixfmt;
176 	uint32_t		namelen;
177 };
178 
179 struct rfb_pixfmt_msg {
180 	uint8_t			type;
181 	uint8_t			pad[3];
182 	struct rfb_pixfmt	pixfmt;
183 };
184 
185 #define	RFB_ENCODING_RAW		0
186 #define	RFB_ENCODING_ZLIB		6
187 #define	RFB_ENCODING_RESIZE		-223
188 #define	RFB_ENCODING_EXT_KEYEVENT	-258
189 
190 #define	RFB_CLIENTMSG_EXT_KEYEVENT	0
191 
192 #define	RFB_MAX_WIDTH			2000
193 #define	RFB_MAX_HEIGHT			1200
194 #define	RFB_ZLIB_BUFSZ			RFB_MAX_WIDTH*RFB_MAX_HEIGHT*4
195 
196 #define PIXEL_RED_SHIFT		16
197 #define PIXEL_GREEN_SHIFT	8
198 #define PIXEL_BLUE_SHIFT	0
199 
200 /* percentage changes to screen before sending the entire screen */
201 #define	RFB_SEND_ALL_THRESH		25
202 
203 struct rfb_enc_msg {
204 	uint8_t		type;
205 	uint8_t		pad;
206 	uint16_t	numencs;
207 };
208 
209 struct rfb_updt_msg {
210 	uint8_t		type;
211 	uint8_t		incremental;
212 	uint16_t	x;
213 	uint16_t	y;
214 	uint16_t	width;
215 	uint16_t	height;
216 };
217 
218 struct rfb_key_msg {
219 	uint8_t		type;
220 	uint8_t		down;
221 	uint16_t	pad;
222 	uint32_t	sym;
223 };
224 
225 struct rfb_client_msg {
226 	uint8_t		type;
227 	uint8_t		subtype;
228 };
229 
230 struct rfb_extended_key_msg {
231 	uint8_t		type;
232 	uint8_t		subtype;
233 	uint16_t	down;
234 	uint32_t	sym;
235 	uint32_t	code;
236 };
237 
238 struct rfb_ptr_msg {
239 	uint8_t		type;
240 	uint8_t		button;
241 	uint16_t	x;
242 	uint16_t	y;
243 };
244 
245 struct rfb_srvr_updt_msg {
246 	uint8_t		type;
247 	uint8_t		pad;
248 	uint16_t	numrects;
249 };
250 
251 struct rfb_srvr_rect_hdr {
252 	uint16_t	x;
253 	uint16_t	y;
254 	uint16_t	width;
255 	uint16_t	height;
256 	uint32_t	encoding;
257 };
258 
259 struct rfb_cuttext_msg {
260 	uint8_t		type;
261 	uint8_t		padding[3];
262 	uint32_t	length;
263 };
264 
265 static void
rfb_send_server_init_msg(int cfd)266 rfb_send_server_init_msg(int cfd)
267 {
268 	struct bhyvegc_image *gc_image;
269 	struct rfb_srvr_info sinfo;
270 
271 	gc_image = console_get_image();
272 
273 	sinfo.width = htons(gc_image->width);
274 	sinfo.height = htons(gc_image->height);
275 	sinfo.pixfmt.bpp = 32;
276 	sinfo.pixfmt.depth = 32;
277 	sinfo.pixfmt.bigendian = 0;
278 	sinfo.pixfmt.truecolor = 1;
279 	sinfo.pixfmt.red_max = htons(255);
280 	sinfo.pixfmt.green_max = htons(255);
281 	sinfo.pixfmt.blue_max = htons(255);
282 	sinfo.pixfmt.red_shift = PIXEL_RED_SHIFT;
283 	sinfo.pixfmt.green_shift = PIXEL_GREEN_SHIFT;
284 	sinfo.pixfmt.blue_shift = PIXEL_BLUE_SHIFT;
285 	sinfo.pixfmt.pad[0] = 0;
286 	sinfo.pixfmt.pad[1] = 0;
287 	sinfo.pixfmt.pad[2] = 0;
288 	sinfo.namelen = htonl(strlen("bhyve"));
289 	(void)stream_write(cfd, &sinfo, sizeof(sinfo));
290 	(void)stream_write(cfd, "bhyve", strlen("bhyve"));
291 }
292 
293 static void
rfb_send_resize_update_msg(struct rfb_softc * rc,int cfd)294 rfb_send_resize_update_msg(struct rfb_softc *rc, int cfd)
295 {
296 	struct rfb_srvr_updt_msg supdt_msg;
297 	struct rfb_srvr_rect_hdr srect_hdr;
298 
299 	/* Number of rectangles: 1 */
300 	supdt_msg.type = 0;
301 	supdt_msg.pad = 0;
302 	supdt_msg.numrects = htons(1);
303 	stream_write(cfd, &supdt_msg, sizeof(struct rfb_srvr_updt_msg));
304 
305 	/* Rectangle header */
306 	srect_hdr.x = htons(0);
307 	srect_hdr.y = htons(0);
308 	srect_hdr.width = htons(rc->width);
309 	srect_hdr.height = htons(rc->height);
310 	srect_hdr.encoding = htonl(RFB_ENCODING_RESIZE);
311 	stream_write(cfd, &srect_hdr, sizeof(struct rfb_srvr_rect_hdr));
312 }
313 
314 static void
rfb_send_extended_keyevent_update_msg(struct rfb_softc * rc,int cfd)315 rfb_send_extended_keyevent_update_msg(struct rfb_softc *rc, int cfd)
316 {
317 	struct rfb_srvr_updt_msg supdt_msg;
318 	struct rfb_srvr_rect_hdr srect_hdr;
319 
320 	/* Number of rectangles: 1 */
321 	supdt_msg.type = 0;
322 	supdt_msg.pad = 0;
323 	supdt_msg.numrects = htons(1);
324 	stream_write(cfd, &supdt_msg, sizeof(struct rfb_srvr_updt_msg));
325 
326 	/* Rectangle header */
327 	srect_hdr.x = htons(0);
328 	srect_hdr.y = htons(0);
329 	srect_hdr.width = htons(rc->width);
330 	srect_hdr.height = htons(rc->height);
331 	srect_hdr.encoding = htonl(RFB_ENCODING_EXT_KEYEVENT);
332 	stream_write(cfd, &srect_hdr, sizeof(struct rfb_srvr_rect_hdr));
333 }
334 
335 static void
rfb_recv_set_pixfmt_msg(struct rfb_softc * rc __unused,int cfd)336 rfb_recv_set_pixfmt_msg(struct rfb_softc *rc __unused, int cfd)
337 {
338 	struct rfb_pixfmt_msg pixfmt_msg;
339 	uint8_t red_shift, green_shift, blue_shift;
340 	uint16_t red_max, green_max, blue_max;
341 	bool adjust_pixels = true;
342 
343 	(void)stream_read(cfd, (uint8_t *)&pixfmt_msg + 1,
344 	    sizeof(pixfmt_msg) - 1);
345 
346 	/*
347 	 * The framebuffer is fixed at 32 bit and orders the colors
348 	 * as RGB bytes. However, some VNC clients request a different
349 	 * ordering. We will still require the same bit depth and size
350 	 * but allow the colors to be shifted when sent to the client.
351 	 */
352 	if (pixfmt_msg.pixfmt.bpp != 32 || pixfmt_msg.pixfmt.truecolor != 1) {
353 		WPRINTF(("rfb: pixfmt unsupported bitdepth bpp: %d "
354 			 "truecolor: %d",
355 			 pixfmt_msg.pixfmt.bpp, pixfmt_msg.pixfmt.truecolor));
356 		return;
357 	}
358 
359 	red_max = ntohs(pixfmt_msg.pixfmt.red_max);
360 	green_max = ntohs(pixfmt_msg.pixfmt.green_max);
361 	blue_max = ntohs(pixfmt_msg.pixfmt.blue_max);
362 
363 	/* Check for valid max values */
364 	if (red_max != 255 || green_max != 255 || blue_max != 255) {
365 		WPRINTF(("rfb: pixfmt unsupported max values "
366 			 "r: %d g: %d b: %d",
367 			 red_max, green_max, blue_max));
368 		return;
369 	}
370 
371 	red_shift = pixfmt_msg.pixfmt.red_shift;
372 	green_shift = pixfmt_msg.pixfmt.green_shift;
373 	blue_shift = pixfmt_msg.pixfmt.blue_shift;
374 
375 	/* Check shifts are 8 bit aligned */
376 	if ((red_shift & 0x7) != 0 ||
377 	    (green_shift & 0x7) != 0 ||
378 	    (blue_shift & 0x7) != 0) {
379 		WPRINTF(("rfb: pixfmt unsupported shift values "
380 			 "r: %d g: %d b: %d",
381 			 red_shift, green_shift, blue_shift));
382 		return;
383 	}
384 
385 	if (red_shift == PIXEL_RED_SHIFT &&
386 	    green_shift == PIXEL_GREEN_SHIFT &&
387 	    blue_shift == PIXEL_BLUE_SHIFT) {
388 		adjust_pixels = false;
389 	}
390 
391 	pthread_mutex_lock(&rc->pixfmt_mtx);
392 	rc->new_pixfmt.red_shift = red_shift;
393 	rc->new_pixfmt.green_shift = green_shift;
394 	rc->new_pixfmt.blue_shift = blue_shift;
395 	rc->new_pixfmt.adjust_pixels = adjust_pixels;
396 	pthread_mutex_unlock(&rc->pixfmt_mtx);
397 
398 	/* Notify the write thread to update */
399 	rc->update_pixfmt = true;
400 }
401 
402 static void
rfb_recv_set_encodings_msg(struct rfb_softc * rc,int cfd)403 rfb_recv_set_encodings_msg(struct rfb_softc *rc, int cfd)
404 {
405 	struct rfb_enc_msg enc_msg;
406 	int i;
407 	uint32_t encoding;
408 
409 	(void)stream_read(cfd, (uint8_t *)&enc_msg + 1, sizeof(enc_msg) - 1);
410 
411 	for (i = 0; i < htons(enc_msg.numencs); i++) {
412 		(void)stream_read(cfd, &encoding, sizeof(encoding));
413 		switch (htonl(encoding)) {
414 		case RFB_ENCODING_RAW:
415 			rc->enc_raw_ok = true;
416 			break;
417 		case RFB_ENCODING_ZLIB:
418 			if (!rc->enc_zlib_ok) {
419 				deflateInit(&rc->zstream, Z_BEST_SPEED);
420 				rc->enc_zlib_ok = true;
421 			}
422 			break;
423 		case RFB_ENCODING_RESIZE:
424 			rc->enc_resize_ok = true;
425 			break;
426 		case RFB_ENCODING_EXT_KEYEVENT:
427 			rc->enc_extkeyevent_ok = true;
428 			break;
429 		}
430 	}
431 }
432 
433 /*
434  * Calculate CRC32 using SSE4.2; Intel or AMD Bulldozer+ CPUs only
435  */
436 static __inline uint32_t
fast_crc32(void * buf,int len,uint32_t crcval)437 fast_crc32(void *buf, int len, uint32_t crcval)
438 {
439 	uint32_t q = len / sizeof(uint32_t);
440 	uint32_t *p = (uint32_t *)buf;
441 
442 	while (q--) {
443 		asm volatile (
444 			".byte 0xf2, 0xf, 0x38, 0xf1, 0xf1;"
445 			:"=S" (crcval)
446 			:"0" (crcval), "c" (*p)
447 		);
448 		p++;
449 	}
450 
451 	return (crcval);
452 }
453 
454 static int
rfb_send_update_header(struct rfb_softc * rc __unused,int cfd,int numrects)455 rfb_send_update_header(struct rfb_softc *rc __unused, int cfd, int numrects)
456 {
457 	struct rfb_srvr_updt_msg supdt_msg;
458 
459 	supdt_msg.type = 0;
460 	supdt_msg.pad = 0;
461 	supdt_msg.numrects = htons(numrects);
462 
463 	return stream_write(cfd, &supdt_msg,
464 	    sizeof(struct rfb_srvr_updt_msg));
465 }
466 
467 static uint32_t *
rfb_adjust_pixels(struct rfb_softc * rc,uint32_t * gcptr,int width)468 rfb_adjust_pixels(struct rfb_softc *rc, uint32_t *gcptr, int width)
469 {
470 	uint32_t *pixelp;
471 	uint32_t red, green, blue;
472 	int i;
473 
474 	/* If no pixel adjustment needed, send in server format */
475 	if (!rc->pixfmt.adjust_pixels) {
476 		return (gcptr);
477 	}
478 
479 	for (i = 0, pixelp = rc->pixrow; i < width; i++, pixelp++, gcptr++) {
480 		red = (*gcptr >> 16) & 0xFF;
481 		green = (*gcptr >> 8) & 0xFF;
482 		blue = (*gcptr & 0xFF);
483 		*pixelp = (red << rc->pixfmt.red_shift) |
484 			  (green << rc->pixfmt.green_shift) |
485 			  (blue << rc->pixfmt.blue_shift);
486 	}
487 
488 	return (rc->pixrow);
489 }
490 
491 static int
rfb_send_rect(struct rfb_softc * rc,int cfd,struct bhyvegc_image * gc,int x,int y,int w,int h)492 rfb_send_rect(struct rfb_softc *rc, int cfd, struct bhyvegc_image *gc,
493               int x, int y, int w, int h)
494 {
495 	struct rfb_srvr_rect_hdr srect_hdr;
496 	unsigned long zlen;
497 	ssize_t nwrite, total;
498 	int err, width;
499 	uint32_t *p, *pixelp;
500 	uint8_t *zbufp;
501 
502 	/*
503 	 * Send a single rectangle of the given x, y, w h dimensions.
504 	 */
505 
506 	/* Rectangle header */
507 	srect_hdr.x = htons(x);
508 	srect_hdr.y = htons(y);
509 	srect_hdr.width = htons(w);
510 	srect_hdr.height = htons(h);
511 
512 	width = w;
513 	h = y + h;
514 	w *= sizeof(uint32_t);
515 	if (rc->enc_zlib_ok) {
516 		zbufp = rc->zbuf;
517 		rc->zstream.total_in = 0;
518 		rc->zstream.total_out = 0;
519 		for (p = &gc->data[y * gc->width + x]; y < h; y++) {
520 			pixelp = rfb_adjust_pixels(rc, p, width);
521 			rc->zstream.next_in = (Bytef *)pixelp;
522 			rc->zstream.avail_in = w;
523 			rc->zstream.next_out = (Bytef *)zbufp;
524 			rc->zstream.avail_out = RFB_ZLIB_BUFSZ + 16 -
525 			                        rc->zstream.total_out;
526 			rc->zstream.data_type = Z_BINARY;
527 
528 			/* Compress with zlib */
529 			err = deflate(&rc->zstream, Z_SYNC_FLUSH);
530 			if (err != Z_OK) {
531 				WPRINTF(("zlib[rect] deflate err: %d", err));
532 				rc->enc_zlib_ok = false;
533 				deflateEnd(&rc->zstream);
534 				goto doraw;
535 			}
536 			zbufp = rc->zbuf + rc->zstream.total_out;
537 			p += gc->width;
538 		}
539 		srect_hdr.encoding = htonl(RFB_ENCODING_ZLIB);
540 		nwrite = stream_write(cfd, &srect_hdr,
541 		                      sizeof(struct rfb_srvr_rect_hdr));
542 		if (nwrite <= 0)
543 			return (nwrite);
544 
545 		zlen = htonl(rc->zstream.total_out);
546 		nwrite = stream_write(cfd, &zlen, sizeof(uint32_t));
547 		if (nwrite <= 0)
548 			return (nwrite);
549 		return (stream_write(cfd, rc->zbuf, rc->zstream.total_out));
550 	}
551 
552 doraw:
553 
554 	total = 0;
555 	zbufp = rc->zbuf;
556 	for (p = &gc->data[y * gc->width + x]; y < h; y++) {
557 		pixelp = rfb_adjust_pixels(rc, p, width);
558 		memcpy(zbufp, pixelp, w);
559 		zbufp += w;
560 		total += w;
561 		p += gc->width;
562 	}
563 
564 	srect_hdr.encoding = htonl(RFB_ENCODING_RAW);
565 	nwrite = stream_write(cfd, &srect_hdr,
566 	                      sizeof(struct rfb_srvr_rect_hdr));
567 	if (nwrite <= 0)
568 		return (nwrite);
569 
570 	total = stream_write(cfd, rc->zbuf, total);
571 
572 	return (total);
573 }
574 
575 static int
rfb_send_all(struct rfb_softc * rc,int cfd,struct bhyvegc_image * gc)576 rfb_send_all(struct rfb_softc *rc, int cfd, struct bhyvegc_image *gc)
577 {
578 	struct rfb_srvr_updt_msg supdt_msg;
579         struct rfb_srvr_rect_hdr srect_hdr;
580 	ssize_t nwrite;
581 	unsigned long zlen;
582 	int err;
583 
584 	/*
585 	 * Send the whole thing
586 	 */
587 
588 	/* Number of rectangles: 1 */
589 	supdt_msg.type = 0;
590 	supdt_msg.pad = 0;
591 	supdt_msg.numrects = htons(1);
592 	nwrite = stream_write(cfd, &supdt_msg,
593 	                      sizeof(struct rfb_srvr_updt_msg));
594 	if (nwrite <= 0)
595 		return (nwrite);
596 
597 	if (rc->pixfmt.adjust_pixels) {
598 		return (rfb_send_rect(rc, cfd, gc, 0, 0,
599 				gc->width, gc->height));
600 	}
601 
602 	/* Rectangle header */
603 	srect_hdr.x = 0;
604 	srect_hdr.y = 0;
605 	srect_hdr.width = htons(gc->width);
606 	srect_hdr.height = htons(gc->height);
607 	if (rc->enc_zlib_ok) {
608 		rc->zstream.next_in = (Bytef *)gc->data;
609 		rc->zstream.avail_in = gc->width * gc->height *
610 		                   sizeof(uint32_t);
611 		rc->zstream.next_out = (Bytef *)rc->zbuf;
612 		rc->zstream.avail_out = RFB_ZLIB_BUFSZ + 16;
613 		rc->zstream.data_type = Z_BINARY;
614 
615 		rc->zstream.total_in = 0;
616 		rc->zstream.total_out = 0;
617 
618 		/* Compress with zlib */
619 		err = deflate(&rc->zstream, Z_SYNC_FLUSH);
620 		if (err != Z_OK) {
621 			WPRINTF(("zlib deflate err: %d", err));
622 			rc->enc_zlib_ok = false;
623 			deflateEnd(&rc->zstream);
624 			goto doraw;
625 		}
626 
627 		srect_hdr.encoding = htonl(RFB_ENCODING_ZLIB);
628 		nwrite = stream_write(cfd, &srect_hdr,
629 		                      sizeof(struct rfb_srvr_rect_hdr));
630 		if (nwrite <= 0)
631 			return (nwrite);
632 
633 		zlen = htonl(rc->zstream.total_out);
634 		nwrite = stream_write(cfd, &zlen, sizeof(uint32_t));
635 		if (nwrite <= 0)
636 			return (nwrite);
637 		return (stream_write(cfd, rc->zbuf, rc->zstream.total_out));
638 	}
639 
640 doraw:
641 	srect_hdr.encoding = htonl(RFB_ENCODING_RAW);
642 	nwrite = stream_write(cfd, &srect_hdr,
643 	                      sizeof(struct rfb_srvr_rect_hdr));
644 	if (nwrite <= 0)
645 		return (nwrite);
646 
647 	nwrite = stream_write(cfd, gc->data,
648 	               gc->width * gc->height * sizeof(uint32_t));
649 
650 	return (nwrite);
651 }
652 
653 #define	PIX_PER_CELL	32
654 #define	PIXCELL_SHIFT	5
655 #define	PIXCELL_MASK	0x1F
656 
657 static void
rfb_set_pixel_adjustment(struct rfb_softc * rc)658 rfb_set_pixel_adjustment(struct rfb_softc *rc)
659 {
660 	pthread_mutex_lock(&rc->pixfmt_mtx);
661 	rc->pixfmt = rc->new_pixfmt;
662 	pthread_mutex_unlock(&rc->pixfmt_mtx);
663 }
664 
665 static int
rfb_send_screen(struct rfb_softc * rc,int cfd)666 rfb_send_screen(struct rfb_softc *rc, int cfd)
667 {
668 	struct bhyvegc_image *gc_image;
669 	ssize_t nwrite;
670 	int x, y;
671 	int celly, cellwidth;
672 	int xcells, ycells;
673 	int w, h;
674 	uint32_t *p;
675 	int rem_x, rem_y;   /* remainder for resolutions not x32 pixels ratio */
676 	int retval;
677 	uint32_t *crc_p, *orig_crc;
678 	int changes;
679 	bool expected;
680 
681 	/* Return if another thread sending */
682 	expected = false;
683 	if (atomic_compare_exchange_strong(&rc->sending, &expected, true) == false)
684 		return (1);
685 
686 	retval = 1;
687 
688 	/* Updates require a preceding update request */
689 	if (atomic_exchange(&rc->pending, false) == false)
690 		goto done;
691 
692 	if (atomic_exchange(&rc->update_pixfmt, false) == true) {
693 		rfb_set_pixel_adjustment(rc);
694 	}
695 
696 	console_refresh();
697 	gc_image = console_get_image();
698 
699 	/* Clear old CRC values when the size changes */
700 	if (rc->crc_width != gc_image->width ||
701 	    rc->crc_height != gc_image->height) {
702 		memset(rc->crc, 0, sizeof(uint32_t) *
703 		    howmany(RFB_MAX_WIDTH, PIX_PER_CELL) *
704 		    howmany(RFB_MAX_HEIGHT, PIX_PER_CELL));
705 		rc->crc_width = gc_image->width;
706 		rc->crc_height = gc_image->height;
707 	}
708 
709        /* A size update counts as an update in itself */
710        if (rc->width != gc_image->width ||
711            rc->height != gc_image->height) {
712                rc->width = gc_image->width;
713                rc->height = gc_image->height;
714                if (rc->enc_resize_ok) {
715                        rfb_send_resize_update_msg(rc, cfd);
716 		       rc->update_all = true;
717                        goto done;
718                }
719        }
720 
721        if (atomic_exchange(&rc->update_all, false) == true) {
722 	       retval = rfb_send_all(rc, cfd, gc_image);
723 	       goto done;
724        }
725 
726 	/*
727 	 * Calculate the checksum for each 32x32 cell. Send each that
728 	 * has changed since the last scan.
729 	 */
730 
731 	w = rc->crc_width;
732 	h = rc->crc_height;
733 	xcells = howmany(rc->crc_width, PIX_PER_CELL);
734 	ycells = howmany(rc->crc_height, PIX_PER_CELL);
735 
736 	rem_x = w & PIXCELL_MASK;
737 
738 	rem_y = h & PIXCELL_MASK;
739 	if (!rem_y)
740 		rem_y = PIX_PER_CELL;
741 
742 	p = gc_image->data;
743 
744 	/*
745 	 * Go through all cells and calculate crc. If significant number
746 	 * of changes, then send entire screen.
747 	 * crc_tmp is dual purpose: to store the new crc and to flag as
748 	 * a cell that has changed.
749 	 */
750 	crc_p = rc->crc_tmp - xcells;
751 	orig_crc = rc->crc - xcells;
752 	changes = 0;
753 	memset(rc->crc_tmp, 0, sizeof(uint32_t) * xcells * ycells);
754 	for (y = 0; y < h; y++) {
755 		if ((y & PIXCELL_MASK) == 0) {
756 			crc_p += xcells;
757 			orig_crc += xcells;
758 		}
759 
760 		for (x = 0; x < xcells; x++) {
761 			if (x == (xcells - 1) && rem_x > 0)
762 				cellwidth = rem_x;
763 			else
764 				cellwidth = PIX_PER_CELL;
765 
766 			if (rc->hw_crc)
767 				crc_p[x] = fast_crc32(p,
768 				             cellwidth * sizeof(uint32_t),
769 				             crc_p[x]);
770 			else
771 				crc_p[x] = (uint32_t)crc32(crc_p[x],
772 				             (Bytef *)p,
773 				             cellwidth * sizeof(uint32_t));
774 
775 			p += cellwidth;
776 
777 			/* check for crc delta if last row in cell */
778 			if ((y & PIXCELL_MASK) == PIXCELL_MASK || y == (h-1)) {
779 				if (orig_crc[x] != crc_p[x]) {
780 					orig_crc[x] = crc_p[x];
781 					crc_p[x] = 1;
782 					changes++;
783 				} else {
784 					crc_p[x] = 0;
785 				}
786 			}
787 		}
788 	}
789 
790        /*
791 	* We only send the update if there are changes.
792 	* Restore the pending flag since it was unconditionally cleared
793 	* above.
794 	*/
795 	if (!changes) {
796 		rc->pending = true;
797 		goto done;
798 	}
799 
800 	/* If number of changes is > THRESH percent, send the whole screen */
801 	if (((changes * 100) / (xcells * ycells)) >= RFB_SEND_ALL_THRESH) {
802 		retval = rfb_send_all(rc, cfd, gc_image);
803 		goto done;
804 	}
805 
806 	rfb_send_update_header(rc, cfd, changes);
807 
808 	/* Go through all cells, and send only changed ones */
809 	crc_p = rc->crc_tmp;
810 	for (y = 0; y < h; y += PIX_PER_CELL) {
811 		/* previous cell's row */
812 		celly = (y >> PIXCELL_SHIFT);
813 
814 		/* Delta check crc to previous set */
815 		for (x = 0; x < xcells; x++) {
816 			if (*crc_p++ == 0)
817 				continue;
818 
819 			if (x == (xcells - 1) && rem_x > 0)
820 				cellwidth = rem_x;
821 			else
822 				cellwidth = PIX_PER_CELL;
823 			nwrite = rfb_send_rect(rc, cfd,
824 				gc_image,
825 				x * PIX_PER_CELL,
826 				celly * PIX_PER_CELL,
827 			        cellwidth,
828 				y + PIX_PER_CELL >= h ? rem_y : PIX_PER_CELL);
829 			if (nwrite <= 0) {
830 				retval = nwrite;
831 				goto done;
832 			}
833 		}
834 	}
835 
836 done:
837 	rc->sending = false;
838 
839 	return (retval);
840 }
841 
842 
843 static void
rfb_recv_update_msg(struct rfb_softc * rc,int cfd)844 rfb_recv_update_msg(struct rfb_softc *rc, int cfd)
845 {
846 	struct rfb_updt_msg updt_msg;
847 
848 	(void)stream_read(cfd, (uint8_t *)&updt_msg + 1 , sizeof(updt_msg) - 1);
849 
850 	if (rc->enc_extkeyevent_ok && (!rc->enc_extkeyevent_send)) {
851 		rfb_send_extended_keyevent_update_msg(rc, cfd);
852 		rc->enc_extkeyevent_send = true;
853 	}
854 
855 	rc->pending = true;
856 	if (!updt_msg.incremental)
857 		rc->update_all = true;
858 }
859 
860 static void
rfb_recv_key_msg(struct rfb_softc * rc,int cfd)861 rfb_recv_key_msg(struct rfb_softc *rc, int cfd)
862 {
863 	struct rfb_key_msg key_msg;
864 
865 	(void)stream_read(cfd, (uint8_t *)&key_msg + 1, sizeof(key_msg) - 1);
866 
867 	console_key_event(key_msg.down, htonl(key_msg.sym), htonl(0));
868 	rc->input_detected = true;
869 }
870 
871 static void
rfb_recv_client_msg(struct rfb_softc * rc,int cfd)872 rfb_recv_client_msg(struct rfb_softc *rc, int cfd)
873 {
874 	struct rfb_client_msg client_msg;
875 	struct rfb_extended_key_msg extkey_msg;
876 
877 	(void)stream_read(cfd, (uint8_t *)&client_msg + 1,
878 	    sizeof(client_msg) - 1);
879 
880 	if (client_msg.subtype == RFB_CLIENTMSG_EXT_KEYEVENT) {
881 		(void)stream_read(cfd, (uint8_t *)&extkey_msg + 2,
882 		    sizeof(extkey_msg) - 2);
883 		console_key_event((int)extkey_msg.down, htonl(extkey_msg.sym), htonl(extkey_msg.code));
884 		rc->input_detected = true;
885 	}
886 }
887 
888 static void
rfb_recv_ptr_msg(struct rfb_softc * rc,int cfd)889 rfb_recv_ptr_msg(struct rfb_softc *rc, int cfd)
890 {
891 	struct rfb_ptr_msg ptr_msg;
892 
893 	(void)stream_read(cfd, (uint8_t *)&ptr_msg + 1, sizeof(ptr_msg) - 1);
894 
895 	console_ptr_event(ptr_msg.button, htons(ptr_msg.x), htons(ptr_msg.y));
896 	rc->input_detected = true;
897 }
898 
899 static void
rfb_recv_cuttext_msg(struct rfb_softc * rc __unused,int cfd)900 rfb_recv_cuttext_msg(struct rfb_softc *rc __unused, int cfd)
901 {
902 	struct rfb_cuttext_msg ct_msg;
903 	unsigned char buf[32];
904 	int len;
905 
906 	len = stream_read(cfd, (uint8_t *)&ct_msg + 1, sizeof(ct_msg) - 1);
907 	ct_msg.length = htonl(ct_msg.length);
908 	while (ct_msg.length > 0) {
909 		len = stream_read(cfd, buf, ct_msg.length > sizeof(buf) ?
910 			sizeof(buf) : ct_msg.length);
911 		ct_msg.length -= len;
912 	}
913 }
914 
915 static int64_t
timeval_delta(struct timeval * prev,struct timeval * now)916 timeval_delta(struct timeval *prev, struct timeval *now)
917 {
918 	int64_t n1, n2;
919 	n1 = now->tv_sec * 1000000 + now->tv_usec;
920 	n2 = prev->tv_sec * 1000000 + prev->tv_usec;
921 	return (n1 - n2);
922 }
923 
924 static void *
rfb_wr_thr(void * arg)925 rfb_wr_thr(void *arg)
926 {
927 	struct rfb_softc *rc;
928 	fd_set rfds;
929 	struct timeval tv;
930 	struct timeval prev_tv;
931 	int64_t tdiff;
932 	int cfd;
933 	int err;
934 
935 	rc = arg;
936 	cfd = rc->cfd;
937 
938 	prev_tv.tv_sec = 0;
939 	prev_tv.tv_usec = 0;
940 	while (rc->cfd >= 0) {
941 		FD_ZERO(&rfds);
942 		FD_SET(cfd, &rfds);
943 		tv.tv_sec = 0;
944 		tv.tv_usec = CFD_SEL_DELAY;
945 
946 		err = select(cfd+1, &rfds, NULL, NULL, &tv);
947 		if (err < 0)
948 			return (NULL);
949 
950 		/* Determine if its time to push screen; ~24hz */
951 		gettimeofday(&tv, NULL);
952 		tdiff = timeval_delta(&prev_tv, &tv);
953 		if (tdiff >= SCREEN_POLL_DELAY) {
954 			bool input;
955 			prev_tv.tv_sec = tv.tv_sec;
956 			prev_tv.tv_usec = tv.tv_usec;
957 			input = atomic_exchange(&rc->input_detected, false);
958 			/*
959 			 * Refresh the screen on every second trip through the loop,
960 			 * or if keyboard/mouse input has been detected.
961 			 */
962 			if ((++rc->wrcount & 1) || input) {
963 				if (rfb_send_screen(rc, cfd) <= 0) {
964 					return (NULL);
965 				}
966 			}
967 		} else {
968 			/* sleep */
969 			usleep(SCREEN_POLL_DELAY - tdiff);
970 		}
971 	}
972 
973 	return (NULL);
974 }
975 
976 static void
rfb_handle(struct rfb_softc * rc,int cfd)977 rfb_handle(struct rfb_softc *rc, int cfd)
978 {
979 	const char *vbuf = "RFB 003.008\n";
980 	unsigned char buf[80];
981 	unsigned const char *message;
982 
983 #ifndef NO_OPENSSL
984 	unsigned char challenge[AUTH_LENGTH];
985 	unsigned char keystr[PASSWD_LENGTH];
986 	unsigned char crypt_expected[AUTH_LENGTH];
987 
988 	DES_key_schedule ks;
989 	int i;
990 #endif
991 	uint8_t client_ver;
992 	uint8_t auth_type;
993 	pthread_t tid;
994 	uint32_t sres = 0;
995 	int len;
996 	int perror = 1;
997 
998 	rc->cfd = cfd;
999 
1000 	/* 1a. Send server version */
1001 	stream_write(cfd, vbuf, strlen(vbuf));
1002 
1003 	/* 1b. Read client version */
1004 	len = stream_read(cfd, buf, VERSION_LENGTH);
1005 	if (len != VERSION_LENGTH ||
1006 	    strncmp(vbuf, buf, VERSION_LENGTH - 2) != 0) {
1007 		goto done;
1008 	}
1009 
1010 	client_ver = buf[VERSION_LENGTH - 2];
1011 	if (client_ver != CVERS_3_8 && client_ver != CVERS_3_7) {
1012 		/* only recognize 3.3, 3.7 & 3.8. Others dflt to 3.3 */
1013 		client_ver = CVERS_3_3;
1014 	}
1015 
1016 	/* 2a. Send security type */
1017 	buf[0] = 1;
1018 
1019 	/* In versions 3.7 & 3.8, it's 2-way handshake */
1020 	/* For version 3.3, server says what the authentication type must be */
1021 #ifndef NO_OPENSSL
1022 	if (rc->password) {
1023 		auth_type = SECURITY_TYPE_VNC_AUTH;
1024 	} else {
1025 		auth_type = SECURITY_TYPE_NONE;
1026 	}
1027 #else
1028 	auth_type = SECURITY_TYPE_NONE;
1029 #endif
1030 
1031 	switch (client_ver) {
1032 	case CVERS_3_7:
1033 	case CVERS_3_8:
1034 		buf[0] = 1;
1035 		buf[1] = auth_type;
1036 		stream_write(cfd, buf, 2);
1037 
1038 		/* 2b. Read agreed security type */
1039 		len = stream_read(cfd, buf, 1);
1040 		if (buf[0] != auth_type) {
1041 			/* deny */
1042 			sres = htonl(1);
1043 			message = "Auth failed: authentication type mismatch";
1044 			goto report_and_done;
1045 		}
1046 		break;
1047 	case CVERS_3_3:
1048 	default:
1049 		be32enc(buf, auth_type);
1050 		stream_write(cfd, buf, 4);
1051 		break;
1052 	}
1053 
1054 	/* 2c. Do VNC authentication */
1055 	switch (auth_type) {
1056 	case SECURITY_TYPE_NONE:
1057 		break;
1058 	case SECURITY_TYPE_VNC_AUTH:
1059 		/*
1060 		 * The client encrypts the challenge with DES, using a password
1061 		 * supplied by the user as the key.
1062 		 * To form the key, the password is truncated to
1063 		 * eight characters, or padded with null bytes on the right.
1064 		 * The client then sends the resulting 16-bytes response.
1065 		 */
1066 #ifndef NO_OPENSSL
1067 		strncpy(keystr, rc->password, PASSWD_LENGTH);
1068 
1069 		/* VNC clients encrypts the challenge with all the bit fields
1070 		 * in each byte of the password mirrored.
1071 		 * Here we flip each byte of the keystr.
1072 		 */
1073 		for (i = 0; i < PASSWD_LENGTH; i++) {
1074 			keystr[i] = (keystr[i] & 0xF0) >> 4
1075 				  | (keystr[i] & 0x0F) << 4;
1076 			keystr[i] = (keystr[i] & 0xCC) >> 2
1077 				  | (keystr[i] & 0x33) << 2;
1078 			keystr[i] = (keystr[i] & 0xAA) >> 1
1079 				  | (keystr[i] & 0x55) << 1;
1080 		}
1081 
1082 		/* Initialize a 16-byte random challenge */
1083 		arc4random_buf(challenge, sizeof(challenge));
1084 		stream_write(cfd, challenge, AUTH_LENGTH);
1085 
1086 		/* Receive the 16-byte challenge response */
1087 		stream_read(cfd, buf, AUTH_LENGTH);
1088 
1089 		memcpy(crypt_expected, challenge, AUTH_LENGTH);
1090 
1091 		/* Encrypt the Challenge with DES */
1092 		DES_set_key((const_DES_cblock *)keystr, &ks);
1093 		DES_ecb_encrypt((const_DES_cblock *)challenge,
1094 				(const_DES_cblock *)crypt_expected,
1095 				&ks, DES_ENCRYPT);
1096 		DES_ecb_encrypt((const_DES_cblock *)(challenge + PASSWD_LENGTH),
1097 				(const_DES_cblock *)(crypt_expected +
1098 				PASSWD_LENGTH),
1099 				&ks, DES_ENCRYPT);
1100 
1101 		if (memcmp(crypt_expected, buf, AUTH_LENGTH) != 0) {
1102 			message = "Auth Failed: Invalid Password.";
1103 			sres = htonl(1);
1104 		} else {
1105 			sres = 0;
1106 		}
1107 #else
1108 		sres = htonl(1);
1109 		WPRINTF(("Auth not supported, no OpenSSL in your system"));
1110 #endif
1111 
1112 		break;
1113 	}
1114 
1115 	switch (client_ver) {
1116 	case CVERS_3_7:
1117 	case CVERS_3_8:
1118 report_and_done:
1119 		/* 2d. Write back a status */
1120 		stream_write(cfd, &sres, 4);
1121 
1122 		if (sres) {
1123 			/* 3.7 does not want string explaining cause */
1124 			if (client_ver == CVERS_3_8) {
1125 				be32enc(buf, strlen(message));
1126 				stream_write(cfd, buf, 4);
1127 				stream_write(cfd, message, strlen(message));
1128 			}
1129 			goto done;
1130 		}
1131 		break;
1132 	case CVERS_3_3:
1133 	default:
1134 		/* for VNC auth case send status */
1135 		if (auth_type == SECURITY_TYPE_VNC_AUTH) {
1136 			/* 2d. Write back a status */
1137 			stream_write(cfd, &sres, 4);
1138 		}
1139 		if (sres) {
1140 			goto done;
1141 		}
1142 		break;
1143 	}
1144 	/* 3a. Read client shared-flag byte */
1145 	len = stream_read(cfd, buf, 1);
1146 
1147 	/* 4a. Write server-init info */
1148 	rfb_send_server_init_msg(cfd);
1149 
1150 	if (!rc->zbuf) {
1151 		rc->zbuf = malloc(RFB_ZLIB_BUFSZ + 16);
1152 		assert(rc->zbuf != NULL);
1153 	}
1154 
1155 	perror = pthread_create(&tid, NULL, rfb_wr_thr, rc);
1156 	if (perror == 0)
1157 		pthread_set_name_np(tid, "rfbout");
1158 
1159         /* Now read in client requests. 1st byte identifies type */
1160 	for (;;) {
1161 		len = read(cfd, buf, 1);
1162 		if (len <= 0) {
1163 			DPRINTF(("rfb client exiting"));
1164 			break;
1165 		}
1166 
1167 		switch (buf[0]) {
1168 		case CS_SET_PIXEL_FORMAT:
1169 			rfb_recv_set_pixfmt_msg(rc, cfd);
1170 			break;
1171 		case CS_SET_ENCODINGS:
1172 			rfb_recv_set_encodings_msg(rc, cfd);
1173 			break;
1174 		case CS_UPDATE_MSG:
1175 			rfb_recv_update_msg(rc, cfd);
1176 			break;
1177 		case CS_KEY_EVENT:
1178 			rfb_recv_key_msg(rc, cfd);
1179 			break;
1180 		case CS_POINTER_EVENT:
1181 			rfb_recv_ptr_msg(rc, cfd);
1182 			break;
1183 		case CS_CUT_TEXT:
1184 			rfb_recv_cuttext_msg(rc, cfd);
1185 			break;
1186 		case CS_MSG_CLIENT_QEMU:
1187 			rfb_recv_client_msg(rc, cfd);
1188 			break;
1189 		default:
1190 			WPRINTF(("rfb unknown cli-code %d!", buf[0] & 0xff));
1191 			goto done;
1192 		}
1193 	}
1194 done:
1195 	rc->cfd = -1;
1196 	if (perror == 0)
1197 		pthread_join(tid, NULL);
1198 	if (rc->enc_zlib_ok)
1199 		deflateEnd(&rc->zstream);
1200 }
1201 
1202 static void *
rfb_thr(void * arg)1203 rfb_thr(void *arg)
1204 {
1205 	struct rfb_softc *rc;
1206 	sigset_t set;
1207 
1208 	int cfd;
1209 
1210 	rc = arg;
1211 
1212 	sigemptyset(&set);
1213 	sigaddset(&set, SIGPIPE);
1214 	if (pthread_sigmask(SIG_BLOCK, &set, NULL) != 0) {
1215 		perror("pthread_sigmask");
1216 		return (NULL);
1217 	}
1218 
1219 	for (;;) {
1220 		rc->enc_raw_ok = false;
1221 		rc->enc_zlib_ok = false;
1222 		rc->enc_resize_ok = false;
1223 		rc->enc_extkeyevent_ok = false;
1224 
1225 		rc->enc_extkeyevent_send = false;
1226 
1227 		cfd = accept(rc->sfd, NULL, NULL);
1228 		if (rc->conn_wait) {
1229 			pthread_mutex_lock(&rc->mtx);
1230 			pthread_cond_signal(&rc->cond);
1231 			pthread_mutex_unlock(&rc->mtx);
1232 			rc->conn_wait = 0;
1233 		}
1234 		rfb_handle(rc, cfd);
1235 		close(cfd);
1236 	}
1237 
1238 	/* NOTREACHED */
1239 	return (NULL);
1240 }
1241 
1242 static int
sse42_supported(void)1243 sse42_supported(void)
1244 {
1245 	u_int cpu_registers[4], ecx;
1246 
1247 	do_cpuid(1, cpu_registers);
1248 
1249 	ecx = cpu_registers[2];
1250 
1251 	return ((ecx & CPUID2_SSE42) != 0);
1252 }
1253 
1254 int
rfb_init(const char * hostname,int port,int wait,const char * password)1255 rfb_init(const char *hostname, int port, int wait, const char *password)
1256 {
1257 	int e;
1258 	char servname[6];
1259 	struct rfb_softc *rc;
1260 	struct addrinfo *ai = NULL;
1261 	struct addrinfo hints;
1262 	int on = 1;
1263 	int cnt;
1264 #ifndef WITHOUT_CAPSICUM
1265 	cap_rights_t rights;
1266 #endif
1267 
1268 	rc = calloc(1, sizeof(struct rfb_softc));
1269 
1270 	cnt = howmany(RFB_MAX_WIDTH, PIX_PER_CELL) *
1271 	    howmany(RFB_MAX_HEIGHT, PIX_PER_CELL);
1272 	rc->crc = calloc(cnt, sizeof(uint32_t));
1273 	rc->crc_tmp = calloc(cnt, sizeof(uint32_t));
1274 	rc->crc_width = RFB_MAX_WIDTH;
1275 	rc->crc_height = RFB_MAX_HEIGHT;
1276 	rc->sfd = -1;
1277 
1278 	rc->password = password;
1279 
1280 	rc->pixrow = malloc(RFB_MAX_WIDTH * sizeof(uint32_t));
1281 	if (rc->pixrow == NULL) {
1282 		EPRINTLN("rfb: failed to allocate memory for pixrow buffer");
1283 		goto error;
1284 	}
1285 
1286 	snprintf(servname, sizeof(servname), "%d", port ? port : 5900);
1287 
1288 	if (!hostname || strlen(hostname) == 0)
1289 #if defined(INET)
1290 		hostname = "127.0.0.1";
1291 #elif defined(INET6)
1292 		hostname = "[::1]";
1293 #endif
1294 
1295 	memset(&hints, 0, sizeof(hints));
1296 	hints.ai_family = AF_UNSPEC;
1297 	hints.ai_socktype = SOCK_STREAM;
1298 	hints.ai_flags = AI_NUMERICHOST | AI_NUMERICSERV | AI_PASSIVE;
1299 
1300 	if ((e = getaddrinfo(hostname, servname, &hints, &ai)) != 0) {
1301 		EPRINTLN("getaddrinfo: %s", gai_strerror(e));
1302 		goto error;
1303 	}
1304 
1305 	rc->sfd = socket(ai->ai_family, ai->ai_socktype, 0);
1306 	if (rc->sfd < 0) {
1307 		perror("socket");
1308 		goto error;
1309 	}
1310 
1311 	setsockopt(rc->sfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
1312 
1313 	if (bind(rc->sfd, ai->ai_addr, ai->ai_addrlen) < 0) {
1314 		perror("bind");
1315 		goto error;
1316 	}
1317 
1318 	if (listen(rc->sfd, 1) < 0) {
1319 		perror("listen");
1320 		goto error;
1321 	}
1322 
1323 #ifndef WITHOUT_CAPSICUM
1324 	cap_rights_init(&rights, CAP_ACCEPT, CAP_EVENT, CAP_READ, CAP_WRITE);
1325 	if (caph_rights_limit(rc->sfd, &rights) == -1)
1326 		errx(EX_OSERR, "Unable to apply rights for sandbox");
1327 #endif
1328 
1329 	rc->hw_crc = sse42_supported();
1330 
1331 	rc->conn_wait = wait;
1332 	if (wait) {
1333 		pthread_mutex_init(&rc->mtx, NULL);
1334 		pthread_cond_init(&rc->cond, NULL);
1335 	}
1336 
1337 	pthread_mutex_init(&rc->pixfmt_mtx, NULL);
1338 	pthread_create(&rc->tid, NULL, rfb_thr, rc);
1339 	pthread_set_name_np(rc->tid, "rfb");
1340 
1341 	if (wait) {
1342 		DPRINTF(("Waiting for rfb client..."));
1343 		pthread_mutex_lock(&rc->mtx);
1344 		pthread_cond_wait(&rc->cond, &rc->mtx);
1345 		pthread_mutex_unlock(&rc->mtx);
1346 		DPRINTF(("rfb client connected"));
1347 	}
1348 
1349 	freeaddrinfo(ai);
1350 	return (0);
1351 
1352  error:
1353 	if (rc->pixfmt_mtx)
1354 		pthread_mutex_destroy(&rc->pixfmt_mtx);
1355 	if (ai != NULL)
1356 		freeaddrinfo(ai);
1357 	if (rc->sfd != -1)
1358 		close(rc->sfd);
1359 	free(rc->crc);
1360 	free(rc->crc_tmp);
1361 	free(rc->pixrow);
1362 	free(rc);
1363 	return (-1);
1364 }
1365