• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright © 2013 Hardening <rdp.effort@gmail.com>
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining
5  * a copy of this software and associated documentation files (the
6  * "Software"), to deal in the Software without restriction, including
7  * without limitation the rights to use, copy, modify, merge, publish,
8  * distribute, sublicense, and/or sell copies of the Software, and to
9  * permit persons to whom the Software is furnished to do so, subject to
10  * the following conditions:
11  *
12  * The above copyright notice and this permission notice (including the
13  * next paragraph) shall be included in all copies or substantial
14  * portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19  * NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
20  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
21  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
22  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23  * SOFTWARE.
24  */
25 
26 #include "config.h"
27 
28 #include <assert.h>
29 #include <stdint.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <errno.h>
33 #include <linux/input.h>
34 
35 #if HAVE_FREERDP_VERSION_H
36 #include <freerdp/version.h>
37 #else
38 /* assume it's a early 1.1 version */
39 #define FREERDP_VERSION_MAJOR 1
40 #define FREERDP_VERSION_MINOR 1
41 #define FREERDP_VERSION_REVISION 0
42 #endif
43 
44 #define FREERDP_VERSION_NUMBER ((FREERDP_VERSION_MAJOR * 0x10000) + \
45 		(FREERDP_VERSION_MINOR * 0x100) + FREERDP_VERSION_REVISION)
46 
47 
48 #if FREERDP_VERSION_NUMBER >= 0x10201
49 #define HAVE_SKIP_COMPRESSION
50 #endif
51 
52 #if FREERDP_VERSION_NUMBER < 0x10202
53 #	define FREERDP_CB_RET_TYPE void
54 #	define FREERDP_CB_RETURN(V) return
55 #	define NSC_RESET(C, W, H)
56 #	define RFX_RESET(C, W, H) do { rfx_context_reset(C); C->width = W; C->height = H; } while(0)
57 #else
58 #if FREERDP_VERSION_MAJOR >= 2
59 #	define NSC_RESET(C, W, H) nsc_context_reset(C, W, H)
60 #	define RFX_RESET(C, W, H) rfx_context_reset(C, W, H)
61 #else
62 #	define NSC_RESET(C, W, H) do { nsc_context_reset(C); C->width = W; C->height = H; } while(0)
63 #	define RFX_RESET(C, W, H) do { rfx_context_reset(C); C->width = W; C->height = H; } while(0)
64 #endif
65 #define FREERDP_CB_RET_TYPE BOOL
66 #define FREERDP_CB_RETURN(V) return TRUE
67 #endif
68 
69 #ifdef HAVE_SURFACE_BITS_BMP
70 #define SURFACE_BPP(cmd) cmd.bmp.bpp
71 #define SURFACE_CODECID(cmd) cmd.bmp.codecID
72 #define SURFACE_WIDTH(cmd) cmd.bmp.width
73 #define SURFACE_HEIGHT(cmd) cmd.bmp.height
74 #define SURFACE_BITMAP_DATA(cmd) cmd.bmp.bitmapData
75 #define SURFACE_BITMAP_DATA_LEN(cmd) cmd.bmp.bitmapDataLength
76 #else
77 #define SURFACE_BPP(cmd) cmd.bpp
78 #define SURFACE_CODECID(cmd) cmd.codecID
79 #define SURFACE_WIDTH(cmd) cmd.width
80 #define SURFACE_HEIGHT(cmd) cmd.height
81 #define SURFACE_BITMAP_DATA(cmd) cmd.bitmapData
82 #define SURFACE_BITMAP_DATA_LEN(cmd) cmd.bitmapDataLength
83 #endif
84 
85 #include <freerdp/freerdp.h>
86 #include <freerdp/listener.h>
87 #include <freerdp/update.h>
88 #include <freerdp/input.h>
89 #include <freerdp/codec/color.h>
90 #include <freerdp/codec/rfx.h>
91 #include <freerdp/codec/nsc.h>
92 #include <freerdp/locale/keyboard.h>
93 #include <winpr/input.h>
94 
95 #if FREERDP_VERSION_MAJOR >= 2
96 #include <winpr/ssl.h>
97 #endif
98 
99 #include "shared/helpers.h"
100 #include "shared/timespec-util.h"
101 #include <libweston/libweston.h>
102 #include <libweston/backend-rdp.h>
103 #include "pixman-renderer.h"
104 
105 #define MAX_FREERDP_FDS 32
106 #define DEFAULT_AXIS_STEP_DISTANCE 10
107 #define RDP_MODE_FREQ 60 * 1000
108 
109 #if FREERDP_VERSION_MAJOR >= 2 && defined(PIXEL_FORMAT_BGRA32) && !defined(PIXEL_FORMAT_B8G8R8A8)
110 	/* The RDP API is truly wonderful: the pixel format definition changed
111 	 * from BGRA32 to B8G8R8A8, but some versions ship with a definition of
112 	 * PIXEL_FORMAT_BGRA32 which doesn't actually build. Try really, really,
113 	 * hard to find one which does. */
114 #	define DEFAULT_PIXEL_FORMAT PIXEL_FORMAT_BGRA32
115 #else
116 #	define DEFAULT_PIXEL_FORMAT RDP_PIXEL_FORMAT_B8G8R8A8
117 #endif
118 
119 struct rdp_output;
120 
121 struct rdp_backend {
122 	struct weston_backend base;
123 	struct weston_compositor *compositor;
124 
125 	freerdp_listener *listener;
126 	struct wl_event_source *listener_events[MAX_FREERDP_FDS];
127 	struct rdp_output *output;
128 
129 	char *server_cert;
130 	char *server_key;
131 	char *rdp_key;
132 	int tls_enabled;
133 	int no_clients_resize;
134 	int force_no_compression;
135 };
136 
137 enum peer_item_flags {
138 	RDP_PEER_ACTIVATED      = (1 << 0),
139 	RDP_PEER_OUTPUT_ENABLED = (1 << 1),
140 };
141 
142 struct rdp_peers_item {
143 	int flags;
144 	freerdp_peer *peer;
145 	struct weston_seat *seat;
146 
147 	struct wl_list link;
148 };
149 
150 struct rdp_head {
151 	struct weston_head base;
152 };
153 
154 struct rdp_output {
155 	struct weston_output base;
156 	struct wl_event_source *finish_frame_timer;
157 	pixman_image_t *shadow_surface;
158 
159 	struct wl_list peers;
160 };
161 
162 struct rdp_peer_context {
163 	rdpContext _p;
164 
165 	struct rdp_backend *rdpBackend;
166 	struct wl_event_source *events[MAX_FREERDP_FDS];
167 	RFX_CONTEXT *rfx_context;
168 	wStream *encode_stream;
169 	RFX_RECT *rfx_rects;
170 	NSC_CONTEXT *nsc_context;
171 
172 	struct rdp_peers_item item;
173 };
174 typedef struct rdp_peer_context RdpPeerContext;
175 
176 static inline struct rdp_head *
to_rdp_head(struct weston_head * base)177 to_rdp_head(struct weston_head *base)
178 {
179 	return container_of(base, struct rdp_head, base);
180 }
181 
182 static inline struct rdp_output *
to_rdp_output(struct weston_output * base)183 to_rdp_output(struct weston_output *base)
184 {
185 	return container_of(base, struct rdp_output, base);
186 }
187 
188 static inline struct rdp_backend *
to_rdp_backend(struct weston_compositor * base)189 to_rdp_backend(struct weston_compositor *base)
190 {
191 	return container_of(base->backend, struct rdp_backend, base);
192 }
193 
194 static void
rdp_peer_refresh_rfx(pixman_region32_t * damage,pixman_image_t * image,freerdp_peer * peer)195 rdp_peer_refresh_rfx(pixman_region32_t *damage, pixman_image_t *image, freerdp_peer *peer)
196 {
197 	int width, height, nrects, i;
198 	pixman_box32_t *region, *rects;
199 	uint32_t *ptr;
200 	RFX_RECT *rfxRect;
201 	rdpUpdate *update = peer->update;
202 	SURFACE_BITS_COMMAND cmd;
203 	RdpPeerContext *context = (RdpPeerContext *)peer->context;
204 
205 	Stream_Clear(context->encode_stream);
206 	Stream_SetPosition(context->encode_stream, 0);
207 
208 	width = (damage->extents.x2 - damage->extents.x1);
209 	height = (damage->extents.y2 - damage->extents.y1);
210 
211 #ifdef HAVE_SKIP_COMPRESSION
212 	cmd.skipCompression = TRUE;
213 #else
214 	memset(&cmd, 0, sizeof(*cmd));
215 #endif
216 #ifdef HAVE_SURFCMD_CMDTYPE
217 	cmd.cmdType = CMDTYPE_STREAM_SURFACE_BITS;
218 #endif
219 	cmd.destLeft = damage->extents.x1;
220 	cmd.destTop = damage->extents.y1;
221 	cmd.destRight = damage->extents.x2;
222 	cmd.destBottom = damage->extents.y2;
223 	SURFACE_BPP(cmd) = 32;
224 	SURFACE_CODECID(cmd) = peer->settings->RemoteFxCodecId;
225 	SURFACE_WIDTH(cmd) = width;
226 	SURFACE_HEIGHT(cmd) = height;
227 
228 	ptr = pixman_image_get_data(image) + damage->extents.x1 +
229 				damage->extents.y1 * (pixman_image_get_stride(image) / sizeof(uint32_t));
230 
231 	rects = pixman_region32_rectangles(damage, &nrects);
232 	context->rfx_rects = realloc(context->rfx_rects, nrects * sizeof *rfxRect);
233 
234 	for (i = 0; i < nrects; i++) {
235 		region = &rects[i];
236 		rfxRect = &context->rfx_rects[i];
237 
238 		rfxRect->x = (region->x1 - damage->extents.x1);
239 		rfxRect->y = (region->y1 - damage->extents.y1);
240 		rfxRect->width = (region->x2 - region->x1);
241 		rfxRect->height = (region->y2 - region->y1);
242 	}
243 
244 	rfx_compose_message(context->rfx_context, context->encode_stream, context->rfx_rects, nrects,
245 			(BYTE *)ptr, width, height,
246 			pixman_image_get_stride(image)
247 	);
248 
249 	SURFACE_BITMAP_DATA_LEN(cmd) = Stream_GetPosition(context->encode_stream);
250 	SURFACE_BITMAP_DATA(cmd) = Stream_Buffer(context->encode_stream);
251 
252 	update->SurfaceBits(update->context, &cmd);
253 }
254 
255 
256 static void
rdp_peer_refresh_nsc(pixman_region32_t * damage,pixman_image_t * image,freerdp_peer * peer)257 rdp_peer_refresh_nsc(pixman_region32_t *damage, pixman_image_t *image, freerdp_peer *peer)
258 {
259 	int width, height;
260 	uint32_t *ptr;
261 	rdpUpdate *update = peer->update;
262 	SURFACE_BITS_COMMAND cmd;
263 	RdpPeerContext *context = (RdpPeerContext *)peer->context;
264 
265 	Stream_Clear(context->encode_stream);
266 	Stream_SetPosition(context->encode_stream, 0);
267 
268 	width = (damage->extents.x2 - damage->extents.x1);
269 	height = (damage->extents.y2 - damage->extents.y1);
270 
271 #ifdef HAVE_SKIP_COMPRESSION
272 	cmd.skipCompression = TRUE;
273 #else
274 	memset(cmd, 0, sizeof(*cmd));
275 #endif
276 #ifdef HAVE_SURFCMD_CMDTYPE
277 	cmd.cmdType = CMDTYPE_SET_SURFACE_BITS;
278 #endif
279 	cmd.destLeft = damage->extents.x1;
280 	cmd.destTop = damage->extents.y1;
281 	cmd.destRight = damage->extents.x2;
282 	cmd.destBottom = damage->extents.y2;
283 	SURFACE_BPP(cmd) = 32;
284 	SURFACE_CODECID(cmd) = peer->settings->NSCodecId;
285 	SURFACE_WIDTH(cmd) = width;
286 	SURFACE_HEIGHT(cmd) = height;
287 
288 	ptr = pixman_image_get_data(image) + damage->extents.x1 +
289 				damage->extents.y1 * (pixman_image_get_stride(image) / sizeof(uint32_t));
290 
291 	nsc_compose_message(context->nsc_context, context->encode_stream, (BYTE *)ptr,
292 			width, height,
293 			pixman_image_get_stride(image));
294 
295 	SURFACE_BITMAP_DATA_LEN(cmd) = Stream_GetPosition(context->encode_stream);
296 	SURFACE_BITMAP_DATA(cmd) = Stream_Buffer(context->encode_stream);
297 
298 	update->SurfaceBits(update->context, &cmd);
299 }
300 
301 static void
pixman_image_flipped_subrect(const pixman_box32_t * rect,pixman_image_t * img,BYTE * dest)302 pixman_image_flipped_subrect(const pixman_box32_t *rect, pixman_image_t *img, BYTE *dest)
303 {
304 	int stride = pixman_image_get_stride(img);
305 	int h;
306 	int toCopy = (rect->x2 - rect->x1) * 4;
307 	int height = (rect->y2 - rect->y1);
308 	const BYTE *src = (const BYTE *)pixman_image_get_data(img);
309 	src += ((rect->y2-1) * stride) + (rect->x1 * 4);
310 
311 	for (h = 0; h < height; h++, src -= stride, dest += toCopy)
312 		   memcpy(dest, src, toCopy);
313 }
314 
315 static void
rdp_peer_refresh_raw(pixman_region32_t * region,pixman_image_t * image,freerdp_peer * peer)316 rdp_peer_refresh_raw(pixman_region32_t *region, pixman_image_t *image, freerdp_peer *peer)
317 {
318 	rdpUpdate *update = peer->update;
319 	SURFACE_BITS_COMMAND cmd;
320 	SURFACE_FRAME_MARKER marker;
321 	pixman_box32_t *rect, subrect;
322 	int nrects, i;
323 	int heightIncrement, remainingHeight, top;
324 
325 	rect = pixman_region32_rectangles(region, &nrects);
326 	if (!nrects)
327 		return;
328 
329 	marker.frameId++;
330 	marker.frameAction = SURFACECMD_FRAMEACTION_BEGIN;
331 	update->SurfaceFrameMarker(peer->context, &marker);
332 
333 	memset(&cmd, 0, sizeof(cmd));
334 #ifdef HAVE_SURFCMD_CMDTYPE
335 	cmd.cmdType = CMDTYPE_SET_SURFACE_BITS;
336 #endif
337 	SURFACE_BPP(cmd) = 32;
338 	SURFACE_CODECID(cmd) = 0;
339 
340 	for (i = 0; i < nrects; i++, rect++) {
341 		/*weston_log("rect(%d,%d, %d,%d)\n", rect->x1, rect->y1, rect->x2, rect->y2);*/
342 		cmd.destLeft = rect->x1;
343 		cmd.destRight = rect->x2;
344 		SURFACE_WIDTH(cmd) = rect->x2 - rect->x1;
345 
346 		heightIncrement = peer->settings->MultifragMaxRequestSize / (16 + SURFACE_WIDTH(cmd) * 4);
347 		remainingHeight = rect->y2 - rect->y1;
348 		top = rect->y1;
349 
350 		subrect.x1 = rect->x1;
351 		subrect.x2 = rect->x2;
352 
353 		while (remainingHeight) {
354 			   SURFACE_HEIGHT(cmd) = (remainingHeight > heightIncrement) ? heightIncrement : remainingHeight;
355 			   cmd.destTop = top;
356 			   cmd.destBottom = top + SURFACE_HEIGHT(cmd);
357 			   SURFACE_BITMAP_DATA_LEN(cmd) = SURFACE_WIDTH(cmd) * SURFACE_HEIGHT(cmd) * 4;
358 			   SURFACE_BITMAP_DATA(cmd) = (BYTE *)realloc(SURFACE_BITMAP_DATA(cmd), SURFACE_BITMAP_DATA_LEN(cmd));
359 
360 			   subrect.y1 = top;
361 			   subrect.y2 = top + SURFACE_HEIGHT(cmd);
362 			   pixman_image_flipped_subrect(&subrect, image, SURFACE_BITMAP_DATA(cmd));
363 
364 			   /*weston_log("*  sending (%d,%d, %d,%d)\n", subrect.x1, subrect.y1, subrect.x2, subrect.y2); */
365 			   update->SurfaceBits(peer->context, &cmd);
366 
367 			   remainingHeight -= SURFACE_HEIGHT(cmd);
368 			   top += SURFACE_HEIGHT(cmd);
369 		}
370 	}
371 
372 	free(SURFACE_BITMAP_DATA(cmd));
373 
374 	marker.frameAction = SURFACECMD_FRAMEACTION_END;
375 	update->SurfaceFrameMarker(peer->context, &marker);
376 }
377 
378 static void
rdp_peer_refresh_region(pixman_region32_t * region,freerdp_peer * peer)379 rdp_peer_refresh_region(pixman_region32_t *region, freerdp_peer *peer)
380 {
381 	RdpPeerContext *context = (RdpPeerContext *)peer->context;
382 	struct rdp_output *output = context->rdpBackend->output;
383 	rdpSettings *settings = peer->settings;
384 
385 	if (settings->RemoteFxCodec)
386 		rdp_peer_refresh_rfx(region, output->shadow_surface, peer);
387 	else if (settings->NSCodec)
388 		rdp_peer_refresh_nsc(region, output->shadow_surface, peer);
389 	else
390 		rdp_peer_refresh_raw(region, output->shadow_surface, peer);
391 }
392 
393 static int
rdp_output_start_repaint_loop(struct weston_output * output)394 rdp_output_start_repaint_loop(struct weston_output *output)
395 {
396 	struct timespec ts;
397 
398 	weston_compositor_read_presentation_clock(output->compositor, &ts);
399 	weston_output_finish_frame(output, &ts, WP_PRESENTATION_FEEDBACK_INVALID);
400 
401 	return 0;
402 }
403 
404 static int
rdp_output_repaint(struct weston_output * output_base,pixman_region32_t * damage,void * repaint_data)405 rdp_output_repaint(struct weston_output *output_base, pixman_region32_t *damage,
406 		   void *repaint_data)
407 {
408 	struct rdp_output *output = container_of(output_base, struct rdp_output, base);
409 	struct weston_compositor *ec = output->base.compositor;
410 	struct rdp_peers_item *outputPeer;
411 
412 	pixman_renderer_output_set_buffer(output_base, output->shadow_surface);
413 	ec->renderer->repaint_output(&output->base, damage);
414 
415 	if (pixman_region32_not_empty(damage)) {
416 		wl_list_for_each(outputPeer, &output->peers, link) {
417 			if ((outputPeer->flags & RDP_PEER_ACTIVATED) &&
418 					(outputPeer->flags & RDP_PEER_OUTPUT_ENABLED))
419 			{
420 				rdp_peer_refresh_region(damage, outputPeer->peer);
421 			}
422 		}
423 	}
424 
425 	pixman_region32_subtract(&ec->primary_plane.damage,
426 				 &ec->primary_plane.damage, damage);
427 
428 	wl_event_source_timer_update(output->finish_frame_timer, 16);
429 	return 0;
430 }
431 
432 static int
finish_frame_handler(void * data)433 finish_frame_handler(void *data)
434 {
435 	struct rdp_output *output = data;
436 	struct timespec ts;
437 
438 	weston_compositor_read_presentation_clock(output->base.compositor, &ts);
439 	weston_output_finish_frame(&output->base, &ts, 0);
440 
441 	return 1;
442 }
443 
444 static struct weston_mode *
rdp_insert_new_mode(struct weston_output * output,int width,int height,int rate)445 rdp_insert_new_mode(struct weston_output *output, int width, int height, int rate)
446 {
447 	struct weston_mode *ret;
448 	ret = zalloc(sizeof *ret);
449 	if (!ret)
450 		return NULL;
451 	ret->width = width;
452 	ret->height = height;
453 	ret->refresh = rate;
454 	wl_list_insert(&output->mode_list, &ret->link);
455 	return ret;
456 }
457 
458 static struct weston_mode *
ensure_matching_mode(struct weston_output * output,struct weston_mode * target)459 ensure_matching_mode(struct weston_output *output, struct weston_mode *target)
460 {
461 	struct weston_mode *local;
462 
463 	wl_list_for_each(local, &output->mode_list, link) {
464 		if ((local->width == target->width) && (local->height == target->height))
465 			return local;
466 	}
467 
468 	return rdp_insert_new_mode(output, target->width, target->height, RDP_MODE_FREQ);
469 }
470 
471 static int
rdp_switch_mode(struct weston_output * output,struct weston_mode * target_mode)472 rdp_switch_mode(struct weston_output *output, struct weston_mode *target_mode)
473 {
474 	struct rdp_output *rdpOutput = container_of(output, struct rdp_output, base);
475 	struct rdp_peers_item *rdpPeer;
476 	rdpSettings *settings;
477 	pixman_image_t *new_shadow_buffer;
478 	struct weston_mode *local_mode;
479 	const struct pixman_renderer_output_options options = { };
480 
481 	local_mode = ensure_matching_mode(output, target_mode);
482 	if (!local_mode) {
483 		weston_log("mode %dx%d not available\n", target_mode->width, target_mode->height);
484 		return -ENOENT;
485 	}
486 
487 	if (local_mode == output->current_mode)
488 		return 0;
489 
490 	output->current_mode->flags &= ~WL_OUTPUT_MODE_CURRENT;
491 
492 	output->current_mode = local_mode;
493 	output->current_mode->flags |= WL_OUTPUT_MODE_CURRENT;
494 
495 	pixman_renderer_output_destroy(output);
496 	pixman_renderer_output_create(output, &options);
497 
498 	new_shadow_buffer = pixman_image_create_bits(PIXMAN_x8r8g8b8, target_mode->width,
499 			target_mode->height, 0, target_mode->width * 4);
500 	pixman_image_composite32(PIXMAN_OP_SRC, rdpOutput->shadow_surface, 0, new_shadow_buffer,
501 			0, 0, 0, 0, 0, 0, target_mode->width, target_mode->height);
502 	pixman_image_unref(rdpOutput->shadow_surface);
503 	rdpOutput->shadow_surface = new_shadow_buffer;
504 
505 	wl_list_for_each(rdpPeer, &rdpOutput->peers, link) {
506 		settings = rdpPeer->peer->settings;
507 		if (settings->DesktopWidth == (UINT32)target_mode->width &&
508 				settings->DesktopHeight == (UINT32)target_mode->height)
509 			continue;
510 
511 		if (!settings->DesktopResize) {
512 			/* too bad this peer does not support desktop resize */
513 			rdpPeer->peer->Close(rdpPeer->peer);
514 		} else {
515 			settings->DesktopWidth = target_mode->width;
516 			settings->DesktopHeight = target_mode->height;
517 			rdpPeer->peer->update->DesktopResize(rdpPeer->peer->context);
518 		}
519 	}
520 	return 0;
521 }
522 
523 static int
rdp_output_set_size(struct weston_output * base,int width,int height)524 rdp_output_set_size(struct weston_output *base,
525 		    int width, int height)
526 {
527 	struct rdp_output *output = to_rdp_output(base);
528 	struct weston_head *head;
529 	struct weston_mode *currentMode;
530 	struct weston_mode initMode;
531 
532 	/* We can only be called once. */
533 	assert(!output->base.current_mode);
534 
535 	wl_list_for_each(head, &output->base.head_list, output_link) {
536 		weston_head_set_monitor_strings(head, "weston", "rdp", NULL);
537 
538 		/* This is a virtual output, so report a zero physical size.
539 		 * It's better to let frontends/clients use their defaults. */
540 		weston_head_set_physical_size(head, 0, 0);
541 	}
542 
543 	wl_list_init(&output->peers);
544 
545 	initMode.flags = WL_OUTPUT_MODE_CURRENT | WL_OUTPUT_MODE_PREFERRED;
546 	initMode.width = width;
547 	initMode.height = height;
548 	initMode.refresh = RDP_MODE_FREQ;
549 
550 	currentMode = ensure_matching_mode(&output->base, &initMode);
551 	if (!currentMode)
552 		return -1;
553 
554 	output->base.current_mode = output->base.native_mode = currentMode;
555 
556 	output->base.start_repaint_loop = rdp_output_start_repaint_loop;
557 	output->base.repaint = rdp_output_repaint;
558 	output->base.assign_planes = NULL;
559 	output->base.set_backlight = NULL;
560 	output->base.set_dpms = NULL;
561 	output->base.switch_mode = rdp_switch_mode;
562 
563 	return 0;
564 }
565 
566 static int
rdp_output_enable(struct weston_output * base)567 rdp_output_enable(struct weston_output *base)
568 {
569 	struct rdp_output *output = to_rdp_output(base);
570 	struct rdp_backend *b = to_rdp_backend(base->compositor);
571 	struct wl_event_loop *loop;
572 	const struct pixman_renderer_output_options options = {
573 		.use_shadow = true,
574 	};
575 
576 	output->shadow_surface = pixman_image_create_bits(PIXMAN_x8r8g8b8,
577 							  output->base.current_mode->width,
578 							  output->base.current_mode->height,
579 							  NULL,
580 							  output->base.current_mode->width * 4);
581 	if (output->shadow_surface == NULL) {
582 		weston_log("Failed to create surface for frame buffer.\n");
583 		return -1;
584 	}
585 
586 	if (pixman_renderer_output_create(&output->base, &options) < 0) {
587 		pixman_image_unref(output->shadow_surface);
588 		return -1;
589 	}
590 
591 	loop = wl_display_get_event_loop(b->compositor->wl_display);
592 	output->finish_frame_timer = wl_event_loop_add_timer(loop, finish_frame_handler, output);
593 
594 	b->output = output;
595 
596 	return 0;
597 }
598 
599 static int
rdp_output_disable(struct weston_output * base)600 rdp_output_disable(struct weston_output *base)
601 {
602 	struct rdp_output *output = to_rdp_output(base);
603 	struct rdp_backend *b = to_rdp_backend(base->compositor);
604 
605 	if (!output->base.enabled)
606 		return 0;
607 
608 	pixman_image_unref(output->shadow_surface);
609 	pixman_renderer_output_destroy(&output->base);
610 
611 	wl_event_source_remove(output->finish_frame_timer);
612 	b->output = NULL;
613 
614 	return 0;
615 }
616 
617 static void
rdp_output_destroy(struct weston_output * base)618 rdp_output_destroy(struct weston_output *base)
619 {
620 	struct rdp_output *output = to_rdp_output(base);
621 
622 	rdp_output_disable(&output->base);
623 	weston_output_release(&output->base);
624 
625 	free(output);
626 }
627 
628 static struct weston_output *
rdp_output_create(struct weston_compositor * compositor,const char * name)629 rdp_output_create(struct weston_compositor *compositor, const char *name)
630 {
631 	struct rdp_output *output;
632 
633 	output = zalloc(sizeof *output);
634 	if (output == NULL)
635 		return NULL;
636 
637 	weston_output_init(&output->base, compositor, name);
638 
639 	output->base.destroy = rdp_output_destroy;
640 	output->base.disable = rdp_output_disable;
641 	output->base.enable = rdp_output_enable;
642 	output->base.attach_head = NULL;
643 
644 	weston_compositor_add_pending_output(&output->base, compositor);
645 
646 	return &output->base;
647 }
648 
649 static int
rdp_head_create(struct weston_compositor * compositor,const char * name)650 rdp_head_create(struct weston_compositor *compositor, const char *name)
651 {
652 	struct rdp_head *head;
653 
654 	head = zalloc(sizeof *head);
655 	if (!head)
656 		return -1;
657 
658 	weston_head_init(&head->base, name);
659 	weston_head_set_connection_status(&head->base, true);
660 	weston_compositor_add_head(compositor, &head->base);
661 
662 	return 0;
663 }
664 
665 static void
rdp_head_destroy(struct rdp_head * head)666 rdp_head_destroy(struct rdp_head *head)
667 {
668 	weston_head_release(&head->base);
669 	free(head);
670 }
671 
672 static void
rdp_destroy(struct weston_compositor * ec)673 rdp_destroy(struct weston_compositor *ec)
674 {
675 	struct rdp_backend *b = to_rdp_backend(ec);
676 	struct weston_head *base, *next;
677 	struct rdp_peers_item *rdp_peer, *tmp;
678 	int i;
679 
680 	wl_list_for_each_safe(rdp_peer, tmp, &b->output->peers, link) {
681 		freerdp_peer* client = rdp_peer->peer;
682 
683 		client->Disconnect(client);
684 		freerdp_peer_context_free(client);
685 		freerdp_peer_free(client);
686 	}
687 
688 	for (i = 0; i < MAX_FREERDP_FDS; i++)
689 		if (b->listener_events[i])
690 			wl_event_source_remove(b->listener_events[i]);
691 
692 	weston_compositor_shutdown(ec);
693 
694 	wl_list_for_each_safe(base, next, &ec->head_list, compositor_link)
695 		rdp_head_destroy(to_rdp_head(base));
696 
697 	freerdp_listener_free(b->listener);
698 
699 	free(b->server_cert);
700 	free(b->server_key);
701 	free(b->rdp_key);
702 	free(b);
703 }
704 
705 static
rdp_listener_activity(int fd,uint32_t mask,void * data)706 int rdp_listener_activity(int fd, uint32_t mask, void *data)
707 {
708 	freerdp_listener* instance = (freerdp_listener *)data;
709 
710 	if (!(mask & WL_EVENT_READABLE))
711 		return 0;
712 	if (!instance->CheckFileDescriptor(instance)) {
713 		weston_log("failed to check FreeRDP file descriptor\n");
714 		return -1;
715 	}
716 	return 0;
717 }
718 
719 static
rdp_implant_listener(struct rdp_backend * b,freerdp_listener * instance)720 int rdp_implant_listener(struct rdp_backend *b, freerdp_listener* instance)
721 {
722 	int i, fd;
723 	int rcount = 0;
724 	void* rfds[MAX_FREERDP_FDS];
725 	struct wl_event_loop *loop;
726 
727 	if (!instance->GetFileDescriptor(instance, rfds, &rcount)) {
728 		weston_log("Failed to get FreeRDP file descriptor\n");
729 		return -1;
730 	}
731 
732 	loop = wl_display_get_event_loop(b->compositor->wl_display);
733 	for (i = 0; i < rcount; i++) {
734 		fd = (int)(long)(rfds[i]);
735 		b->listener_events[i] = wl_event_loop_add_fd(loop, fd, WL_EVENT_READABLE,
736 				rdp_listener_activity, instance);
737 	}
738 
739 	for ( ; i < MAX_FREERDP_FDS; i++)
740 		b->listener_events[i] = 0;
741 	return 0;
742 }
743 
744 
745 static FREERDP_CB_RET_TYPE
rdp_peer_context_new(freerdp_peer * client,RdpPeerContext * context)746 rdp_peer_context_new(freerdp_peer* client, RdpPeerContext* context)
747 {
748 	context->item.peer = client;
749 	context->item.flags = RDP_PEER_OUTPUT_ENABLED;
750 
751 #if FREERDP_VERSION_MAJOR == 1 && FREERDP_VERSION_MINOR == 1
752 	context->rfx_context = rfx_context_new();
753 #else
754 	context->rfx_context = rfx_context_new(TRUE);
755 #endif
756 	if (!context->rfx_context) {
757 		FREERDP_CB_RETURN(FALSE);
758 	}
759 
760 	context->rfx_context->mode = RLGR3;
761 	context->rfx_context->width = client->settings->DesktopWidth;
762 	context->rfx_context->height = client->settings->DesktopHeight;
763 	rfx_context_set_pixel_format(context->rfx_context, DEFAULT_PIXEL_FORMAT);
764 
765 	context->nsc_context = nsc_context_new();
766 	if (!context->nsc_context)
767 		goto out_error_nsc;
768 
769 #ifdef HAVE_NSC_CONTEXT_SET_PARAMETERS
770 	nsc_context_set_parameters(context->nsc_context, NSC_COLOR_FORMAT, DEFAULT_PIXEL_FORMAT);
771 #else
772 	nsc_context_set_pixel_format(context->nsc_context, DEFAULT_PIXEL_FORMAT);
773 #endif
774 	context->encode_stream = Stream_New(NULL, 65536);
775 	if (!context->encode_stream)
776 		goto out_error_stream;
777 
778 	FREERDP_CB_RETURN(TRUE);
779 
780 out_error_nsc:
781 	rfx_context_free(context->rfx_context);
782 out_error_stream:
783 	nsc_context_free(context->nsc_context);
784 	FREERDP_CB_RETURN(FALSE);
785 }
786 
787 static void
rdp_peer_context_free(freerdp_peer * client,RdpPeerContext * context)788 rdp_peer_context_free(freerdp_peer* client, RdpPeerContext* context)
789 {
790 	int i;
791 	if (!context)
792 		return;
793 
794 	wl_list_remove(&context->item.link);
795 	for (i = 0; i < MAX_FREERDP_FDS; i++) {
796 		if (context->events[i])
797 			wl_event_source_remove(context->events[i]);
798 	}
799 
800 	if (context->item.flags & RDP_PEER_ACTIVATED) {
801 		weston_seat_release_keyboard(context->item.seat);
802 		weston_seat_release_pointer(context->item.seat);
803 		/* XXX we should weston_seat_release(context->item.seat); here
804 		 * but it would crash on reconnect */
805 	}
806 
807 	Stream_Free(context->encode_stream, TRUE);
808 	nsc_context_free(context->nsc_context);
809 	rfx_context_free(context->rfx_context);
810 	free(context->rfx_rects);
811 }
812 
813 
814 static int
rdp_client_activity(int fd,uint32_t mask,void * data)815 rdp_client_activity(int fd, uint32_t mask, void *data)
816 {
817 	freerdp_peer* client = (freerdp_peer *)data;
818 
819 	if (!client->CheckFileDescriptor(client)) {
820 		weston_log("unable to checkDescriptor for %p\n", client);
821 		goto out_clean;
822 	}
823 	return 0;
824 
825 out_clean:
826 	freerdp_peer_context_free(client);
827 	freerdp_peer_free(client);
828 	return 0;
829 }
830 
831 static BOOL
xf_peer_capabilities(freerdp_peer * client)832 xf_peer_capabilities(freerdp_peer* client)
833 {
834 	return TRUE;
835 }
836 
837 struct rdp_to_xkb_keyboard_layout {
838 	UINT32 rdpLayoutCode;
839 	const char *xkbLayout;
840 	const char *xkbVariant;
841 };
842 
843 /* table reversed from
844 	https://github.com/awakecoding/FreeRDP/blob/master/libfreerdp/locale/xkb_layout_ids.c#L811 */
845 static const
846 struct rdp_to_xkb_keyboard_layout rdp_keyboards[] = {
847 	{KBD_ARABIC_101, "ara", 0},
848 	{KBD_BULGARIAN, 0, 0},
849 	{KBD_CHINESE_TRADITIONAL_US, 0},
850 	{KBD_CZECH, "cz", 0},
851 	{KBD_CZECH_PROGRAMMERS, "cz", "bksl"},
852 	{KBD_CZECH_QWERTY, "cz", "qwerty"},
853 	{KBD_DANISH, "dk", 0},
854 	{KBD_GERMAN, "de", 0},
855 	{KBD_GERMAN_NEO, "de", "neo"},
856 	{KBD_GERMAN_IBM, "de", "qwerty"},
857 	{KBD_GREEK, "gr", 0},
858 	{KBD_GREEK_220, "gr", "simple"},
859 	{KBD_GREEK_319, "gr", "extended"},
860 	{KBD_GREEK_POLYTONIC, "gr", "polytonic"},
861 	{KBD_US, "us", 0},
862 	{KBD_US_ENGLISH_TABLE_FOR_IBM_ARABIC_238_L, "ara", "buckwalter"},
863 	{KBD_SPANISH, "es", 0},
864 	{KBD_SPANISH_VARIATION, "es", "nodeadkeys"},
865 	{KBD_FINNISH, "fi", 0},
866 	{KBD_FRENCH, "fr", 0},
867 	{KBD_HEBREW, "il", 0},
868 	{KBD_HUNGARIAN, "hu", 0},
869 	{KBD_HUNGARIAN_101_KEY, "hu", "standard"},
870 	{KBD_ICELANDIC, "is", 0},
871 	{KBD_ITALIAN, "it", 0},
872 	{KBD_ITALIAN_142, "it", "nodeadkeys"},
873 	{KBD_JAPANESE, "jp", 0},
874 	{KBD_JAPANESE_INPUT_SYSTEM_MS_IME2002, "jp", "kana"},
875 	{KBD_KOREAN, "kr", 0},
876 	{KBD_KOREAN_INPUT_SYSTEM_IME_2000, "kr", "kr104"},
877 	{KBD_DUTCH, "nl", 0},
878 	{KBD_NORWEGIAN, "no", 0},
879 	{KBD_POLISH_PROGRAMMERS, "pl", 0},
880 	{KBD_POLISH_214, "pl", "qwertz"},
881 	{KBD_ROMANIAN, "ro", 0},
882 	{KBD_RUSSIAN, "ru", 0},
883 	{KBD_RUSSIAN_TYPEWRITER, "ru", "typewriter"},
884 	{KBD_CROATIAN, "hr", 0},
885 	{KBD_SLOVAK, "sk", 0},
886 	{KBD_SLOVAK_QWERTY, "sk", "qwerty"},
887 	{KBD_ALBANIAN, 0, 0},
888 	{KBD_SWEDISH, "se", 0},
889 	{KBD_THAI_KEDMANEE, "th", 0},
890 	{KBD_THAI_KEDMANEE_NON_SHIFTLOCK, "th", "tis"},
891 	{KBD_TURKISH_Q, "tr", 0},
892 	{KBD_TURKISH_F, "tr", "f"},
893 	{KBD_URDU, "in", "urd-phonetic3"},
894 	{KBD_UKRAINIAN, "ua", 0},
895 	{KBD_BELARUSIAN, "by", 0},
896 	{KBD_SLOVENIAN, "si", 0},
897 	{KBD_ESTONIAN, "ee", 0},
898 	{KBD_LATVIAN, "lv", 0},
899 	{KBD_LITHUANIAN_IBM, "lt", "ibm"},
900 	{KBD_FARSI, "af", 0},
901 	{KBD_VIETNAMESE, "vn", 0},
902 	{KBD_ARMENIAN_EASTERN, "am", 0},
903 	{KBD_AZERI_LATIN, 0, 0},
904 	{KBD_FYRO_MACEDONIAN, "mk", 0},
905 	{KBD_GEORGIAN, "ge", 0},
906 	{KBD_FAEROESE, 0, 0},
907 	{KBD_DEVANAGARI_INSCRIPT, 0, 0},
908 	{KBD_MALTESE_47_KEY, 0, 0},
909 	{KBD_NORWEGIAN_WITH_SAMI, "no", "smi"},
910 	{KBD_KAZAKH, "kz", 0},
911 	{KBD_KYRGYZ_CYRILLIC, "kg", "phonetic"},
912 	{KBD_TATAR, "ru", "tt"},
913 	{KBD_BENGALI, "bd", 0},
914 	{KBD_BENGALI_INSCRIPT, "bd", "probhat"},
915 	{KBD_PUNJABI, 0, 0},
916 	{KBD_GUJARATI, "in", "guj"},
917 	{KBD_TAMIL, "in", "tam"},
918 	{KBD_TELUGU, "in", "tel"},
919 	{KBD_KANNADA, "in", "kan"},
920 	{KBD_MALAYALAM, "in", "mal"},
921 	{KBD_HINDI_TRADITIONAL, "in", 0},
922 	{KBD_MARATHI, 0, 0},
923 	{KBD_MONGOLIAN_CYRILLIC, "mn", 0},
924 	{KBD_UNITED_KINGDOM_EXTENDED, "gb", "intl"},
925 	{KBD_SYRIAC, "syc", 0},
926 	{KBD_SYRIAC_PHONETIC, "syc", "syc_phonetic"},
927 	{KBD_NEPALI, "np", 0},
928 	{KBD_PASHTO, "af", "ps"},
929 	{KBD_DIVEHI_PHONETIC, 0, 0},
930 	{KBD_LUXEMBOURGISH, 0, 0},
931 	{KBD_MAORI, "mao", 0},
932 	{KBD_CHINESE_SIMPLIFIED_US, 0, 0},
933 	{KBD_SWISS_GERMAN, "ch", "de_nodeadkeys"},
934 	{KBD_UNITED_KINGDOM, "gb", 0},
935 	{KBD_LATIN_AMERICAN, "latam", 0},
936 	{KBD_BELGIAN_FRENCH, "be", 0},
937 	{KBD_BELGIAN_PERIOD, "be", "oss_sundeadkeys"},
938 	{KBD_PORTUGUESE, "pt", 0},
939 	{KBD_SERBIAN_LATIN, "rs", 0},
940 	{KBD_AZERI_CYRILLIC, "az", "cyrillic"},
941 	{KBD_SWEDISH_WITH_SAMI, "se", "smi"},
942 	{KBD_UZBEK_CYRILLIC, "af", "uz"},
943 	{KBD_INUKTITUT_LATIN, "ca", "ike"},
944 	{KBD_CANADIAN_FRENCH_LEGACY, "ca", "fr-legacy"},
945 	{KBD_SERBIAN_CYRILLIC, "rs", 0},
946 	{KBD_CANADIAN_FRENCH, "ca", "fr-legacy"},
947 	{KBD_SWISS_FRENCH, "ch", "fr"},
948 	{KBD_BOSNIAN, "ba", 0},
949 	{KBD_IRISH, 0, 0},
950 	{KBD_BOSNIAN_CYRILLIC, "ba", "us"},
951 	{KBD_UNITED_STATES_DVORAK, "us", "dvorak"},
952 	{KBD_PORTUGUESE_BRAZILIAN_ABNT2, "br", "nativo"},
953 	{KBD_CANADIAN_MULTILINGUAL_STANDARD, "ca", "multix"},
954 	{KBD_GAELIC, "ie", "CloGaelach"},
955 
956 	{0x00000000, 0, 0},
957 };
958 
959 /* taken from 2.2.7.1.6 Input Capability Set (TS_INPUT_CAPABILITYSET) */
960 static const char *rdp_keyboard_types[] = {
961 	"",	/* 0: unused */
962 	"", /* 1: IBM PC/XT or compatible (83-key) keyboard */
963 	"", /* 2: Olivetti "ICO" (102-key) keyboard */
964 	"", /* 3: IBM PC/AT (84-key) or similar keyboard */
965 	"pc102",/* 4: IBM enhanced (101- or 102-key) keyboard */
966 	"", /* 5: Nokia 1050 and similar keyboards */
967 	"",	/* 6: Nokia 9140 and similar keyboards */
968 	""	/* 7: Japanese keyboard */
969 };
970 
971 static BOOL
xf_peer_activate(freerdp_peer * client)972 xf_peer_activate(freerdp_peer* client)
973 {
974 	RdpPeerContext *peerCtx;
975 	struct rdp_backend *b;
976 	struct rdp_output *output;
977 	rdpSettings *settings;
978 	rdpPointerUpdate *pointer;
979 	struct rdp_peers_item *peersItem;
980 	struct xkb_rule_names xkbRuleNames;
981 	struct xkb_keymap *keymap;
982 	struct weston_output *weston_output;
983 	int i;
984 	pixman_box32_t box;
985 	pixman_region32_t damage;
986 	char seat_name[50];
987 	POINTER_SYSTEM_UPDATE pointer_system;
988 
989 	peerCtx = (RdpPeerContext *)client->context;
990 	b = peerCtx->rdpBackend;
991 	peersItem = &peerCtx->item;
992 	output = b->output;
993 	settings = client->settings;
994 
995 	if (!settings->SurfaceCommandsEnabled) {
996 		weston_log("client doesn't support required SurfaceCommands\n");
997 		return FALSE;
998 	}
999 
1000 	if (b->force_no_compression && settings->CompressionEnabled) {
1001 		weston_log("Forcing compression off\n");
1002 		settings->CompressionEnabled = FALSE;
1003 	}
1004 
1005 	if (output->base.width != (int)settings->DesktopWidth ||
1006 			output->base.height != (int)settings->DesktopHeight)
1007 	{
1008 		if (b->no_clients_resize) {
1009 			/* RDP peers don't dictate their resolution to weston */
1010 			if (!settings->DesktopResize) {
1011 				/* peer does not support desktop resize */
1012 				weston_log("%s: client doesn't support resizing, closing connection\n", __FUNCTION__);
1013 				return FALSE;
1014 			} else {
1015 				settings->DesktopWidth = output->base.width;
1016 				settings->DesktopHeight = output->base.height;
1017 				client->update->DesktopResize(client->context);
1018 			}
1019 		} else {
1020 			/* ask weston to adjust size */
1021 			struct weston_mode new_mode;
1022 			struct weston_mode *target_mode;
1023 			new_mode.width = (int)settings->DesktopWidth;
1024 			new_mode.height = (int)settings->DesktopHeight;
1025 			target_mode = ensure_matching_mode(&output->base, &new_mode);
1026 			if (!target_mode) {
1027 				weston_log("client mode not found\n");
1028 				return FALSE;
1029 			}
1030 			weston_output_mode_set_native(&output->base, target_mode, 1);
1031 			output->base.width = new_mode.width;
1032 			output->base.height = new_mode.height;
1033 		}
1034 	}
1035 
1036 	weston_output = &output->base;
1037 	RFX_RESET(peerCtx->rfx_context, weston_output->width, weston_output->height);
1038 	NSC_RESET(peerCtx->nsc_context, weston_output->width, weston_output->height);
1039 
1040 	if (peersItem->flags & RDP_PEER_ACTIVATED)
1041 		return TRUE;
1042 
1043 	/* when here it's the first reactivation, we need to setup a little more */
1044 	weston_log("kbd_layout:0x%x kbd_type:0x%x kbd_subType:0x%x kbd_functionKeys:0x%x\n",
1045 			settings->KeyboardLayout, settings->KeyboardType, settings->KeyboardSubType,
1046 			settings->KeyboardFunctionKey);
1047 
1048 	memset(&xkbRuleNames, 0, sizeof(xkbRuleNames));
1049 	if (settings->KeyboardType <= 7)
1050 		xkbRuleNames.model = rdp_keyboard_types[settings->KeyboardType];
1051 	for (i = 0; rdp_keyboards[i].rdpLayoutCode; i++) {
1052 		if (rdp_keyboards[i].rdpLayoutCode == settings->KeyboardLayout) {
1053 			xkbRuleNames.layout = rdp_keyboards[i].xkbLayout;
1054 			xkbRuleNames.variant = rdp_keyboards[i].xkbVariant;
1055 			weston_log("%s: matching layout=%s variant=%s\n", __FUNCTION__,
1056 					xkbRuleNames.layout, xkbRuleNames.variant);
1057 			break;
1058 		}
1059 	}
1060 
1061 	keymap = NULL;
1062 	if (xkbRuleNames.layout) {
1063 		keymap = xkb_keymap_new_from_names(b->compositor->xkb_context,
1064 						   &xkbRuleNames, 0);
1065 	}
1066 
1067 	if (settings->ClientHostname)
1068 		snprintf(seat_name, sizeof(seat_name), "RDP %s", settings->ClientHostname);
1069 	else
1070 		snprintf(seat_name, sizeof(seat_name), "RDP peer @%s", settings->ClientAddress);
1071 
1072 	peersItem->seat = zalloc(sizeof(*peersItem->seat));
1073 	if (!peersItem->seat) {
1074 		xkb_keymap_unref(keymap);
1075 		weston_log("unable to create a weston_seat\n");
1076 		return FALSE;
1077 	}
1078 
1079 	weston_seat_init(peersItem->seat, b->compositor, seat_name);
1080 	weston_seat_init_keyboard(peersItem->seat, keymap);
1081 	xkb_keymap_unref(keymap);
1082 	weston_seat_init_pointer(peersItem->seat);
1083 
1084 	peersItem->flags |= RDP_PEER_ACTIVATED;
1085 
1086 	/* disable pointer on the client side */
1087 	pointer = client->update->pointer;
1088 	pointer_system.type = SYSPTR_NULL;
1089 	pointer->PointerSystem(client->context, &pointer_system);
1090 
1091 	/* sends a full refresh */
1092 	box.x1 = 0;
1093 	box.y1 = 0;
1094 	box.x2 = output->base.width;
1095 	box.y2 = output->base.height;
1096 	pixman_region32_init_with_extents(&damage, &box);
1097 
1098 	rdp_peer_refresh_region(&damage, client);
1099 
1100 	pixman_region32_fini(&damage);
1101 
1102 	return TRUE;
1103 }
1104 
1105 static BOOL
xf_peer_post_connect(freerdp_peer * client)1106 xf_peer_post_connect(freerdp_peer *client)
1107 {
1108 	return TRUE;
1109 }
1110 
1111 static FREERDP_CB_RET_TYPE
xf_mouseEvent(rdpInput * input,UINT16 flags,UINT16 x,UINT16 y)1112 xf_mouseEvent(rdpInput *input, UINT16 flags, UINT16 x, UINT16 y)
1113 {
1114 	RdpPeerContext *peerContext = (RdpPeerContext *)input->context;
1115 	struct rdp_output *output;
1116 	uint32_t button = 0;
1117 	bool need_frame = false;
1118 	struct timespec time;
1119 
1120 	if (flags & PTR_FLAGS_MOVE) {
1121 		output = peerContext->rdpBackend->output;
1122 		if (x < output->base.width && y < output->base.height) {
1123 			weston_compositor_get_time(&time);
1124 			notify_motion_absolute(peerContext->item.seat, &time,
1125 					x, y);
1126 			need_frame = true;
1127 		}
1128 	}
1129 
1130 	if (flags & PTR_FLAGS_BUTTON1)
1131 		button = BTN_LEFT;
1132 	else if (flags & PTR_FLAGS_BUTTON2)
1133 		button = BTN_RIGHT;
1134 	else if (flags & PTR_FLAGS_BUTTON3)
1135 		button = BTN_MIDDLE;
1136 
1137 	if (button) {
1138 		weston_compositor_get_time(&time);
1139 		notify_button(peerContext->item.seat, &time, button,
1140 			(flags & PTR_FLAGS_DOWN) ? WL_POINTER_BUTTON_STATE_PRESSED : WL_POINTER_BUTTON_STATE_RELEASED
1141 		);
1142 		need_frame = true;
1143 	}
1144 
1145 	if (flags & PTR_FLAGS_WHEEL) {
1146 		struct weston_pointer_axis_event weston_event;
1147 		double value;
1148 
1149 		/* DEFAULT_AXIS_STEP_DISTANCE is stolen from compositor-x11.c
1150 		 * The RDP specs says the lower bits of flags contains the "the number of rotation
1151 		 * units the mouse wheel was rotated".
1152 		 *
1153 		 * https://blogs.msdn.microsoft.com/oldnewthing/20130123-00/?p=5473 explains the 120 value
1154 		 */
1155 		value = -(flags & 0xff) / 120.0;
1156 		if (flags & PTR_FLAGS_WHEEL_NEGATIVE)
1157 			value = -value;
1158 
1159 		weston_event.axis = WL_POINTER_AXIS_VERTICAL_SCROLL;
1160 		weston_event.value = DEFAULT_AXIS_STEP_DISTANCE * value;
1161 		weston_event.discrete = (int)value;
1162 		weston_event.has_discrete = true;
1163 
1164 		weston_compositor_get_time(&time);
1165 
1166 		notify_axis(peerContext->item.seat, &time, &weston_event);
1167 		need_frame = true;
1168 	}
1169 
1170 	if (need_frame)
1171 		notify_pointer_frame(peerContext->item.seat);
1172 
1173 	FREERDP_CB_RETURN(TRUE);
1174 }
1175 
1176 static FREERDP_CB_RET_TYPE
xf_extendedMouseEvent(rdpInput * input,UINT16 flags,UINT16 x,UINT16 y)1177 xf_extendedMouseEvent(rdpInput *input, UINT16 flags, UINT16 x, UINT16 y)
1178 {
1179 	RdpPeerContext *peerContext = (RdpPeerContext *)input->context;
1180 	struct rdp_output *output;
1181 	struct timespec time;
1182 
1183 	output = peerContext->rdpBackend->output;
1184 	if (x < output->base.width && y < output->base.height) {
1185 		weston_compositor_get_time(&time);
1186 		notify_motion_absolute(peerContext->item.seat, &time, x, y);
1187 	}
1188 
1189 	FREERDP_CB_RETURN(TRUE);
1190 }
1191 
1192 
1193 static FREERDP_CB_RET_TYPE
xf_input_synchronize_event(rdpInput * input,UINT32 flags)1194 xf_input_synchronize_event(rdpInput *input, UINT32 flags)
1195 {
1196 	freerdp_peer *client = input->context->peer;
1197 	RdpPeerContext *peerCtx = (RdpPeerContext *)input->context;
1198 	struct rdp_output *output = peerCtx->rdpBackend->output;
1199 	pixman_box32_t box;
1200 	pixman_region32_t damage;
1201 
1202 	/* sends a full refresh */
1203 	box.x1 = 0;
1204 	box.y1 = 0;
1205 	box.x2 = output->base.width;
1206 	box.y2 = output->base.height;
1207 	pixman_region32_init_with_extents(&damage, &box);
1208 
1209 	rdp_peer_refresh_region(&damage, client);
1210 
1211 	pixman_region32_fini(&damage);
1212 	FREERDP_CB_RETURN(TRUE);
1213 }
1214 
1215 
1216 static FREERDP_CB_RET_TYPE
xf_input_keyboard_event(rdpInput * input,UINT16 flags,UINT16 code)1217 xf_input_keyboard_event(rdpInput *input, UINT16 flags, UINT16 code)
1218 {
1219 	uint32_t scan_code, vk_code, full_code;
1220 	enum wl_keyboard_key_state keyState;
1221 	RdpPeerContext *peerContext = (RdpPeerContext *)input->context;
1222 	int notify = 0;
1223 	struct timespec time;
1224 
1225 	if (!(peerContext->item.flags & RDP_PEER_ACTIVATED))
1226 		FREERDP_CB_RETURN(TRUE);
1227 
1228 	if (flags & KBD_FLAGS_DOWN) {
1229 		keyState = WL_KEYBOARD_KEY_STATE_PRESSED;
1230 		notify = 1;
1231 	} else if (flags & KBD_FLAGS_RELEASE) {
1232 		keyState = WL_KEYBOARD_KEY_STATE_RELEASED;
1233 		notify = 1;
1234 	}
1235 
1236 	if (notify) {
1237 		full_code = code;
1238 		if (flags & KBD_FLAGS_EXTENDED)
1239 			full_code |= KBD_FLAGS_EXTENDED;
1240 
1241 		vk_code = GetVirtualKeyCodeFromVirtualScanCode(full_code, 4);
1242 		if (flags & KBD_FLAGS_EXTENDED)
1243 			vk_code |= KBDEXT;
1244 
1245 		scan_code = GetKeycodeFromVirtualKeyCode(vk_code, KEYCODE_TYPE_EVDEV);
1246 
1247 		/*weston_log("code=%x ext=%d vk_code=%x scan_code=%x\n", code, (flags & KBD_FLAGS_EXTENDED) ? 1 : 0,
1248 				vk_code, scan_code);*/
1249 		weston_compositor_get_time(&time);
1250 		notify_key(peerContext->item.seat, &time,
1251 					scan_code - 8, keyState, STATE_UPDATE_AUTOMATIC);
1252 	}
1253 
1254 	FREERDP_CB_RETURN(TRUE);
1255 }
1256 
1257 static FREERDP_CB_RET_TYPE
xf_input_unicode_keyboard_event(rdpInput * input,UINT16 flags,UINT16 code)1258 xf_input_unicode_keyboard_event(rdpInput *input, UINT16 flags, UINT16 code)
1259 {
1260 	weston_log("Client sent a unicode keyboard event (flags:0x%X code:0x%X)\n", flags, code);
1261 	FREERDP_CB_RETURN(TRUE);
1262 }
1263 
1264 
1265 static FREERDP_CB_RET_TYPE
xf_suppress_output(rdpContext * context,BYTE allow,const RECTANGLE_16 * area)1266 xf_suppress_output(rdpContext *context, BYTE allow, const RECTANGLE_16 *area)
1267 {
1268 	RdpPeerContext *peerContext = (RdpPeerContext *)context;
1269 
1270 	if (allow)
1271 		peerContext->item.flags |= RDP_PEER_OUTPUT_ENABLED;
1272 	else
1273 		peerContext->item.flags &= (~RDP_PEER_OUTPUT_ENABLED);
1274 
1275 	FREERDP_CB_RETURN(TRUE);
1276 }
1277 
1278 static int
rdp_peer_init(freerdp_peer * client,struct rdp_backend * b)1279 rdp_peer_init(freerdp_peer *client, struct rdp_backend *b)
1280 {
1281 	int rcount = 0;
1282 	void *rfds[MAX_FREERDP_FDS];
1283 	int i, fd;
1284 	struct wl_event_loop *loop;
1285 	rdpSettings	*settings;
1286 	rdpInput *input;
1287 	RdpPeerContext *peerCtx;
1288 
1289 	client->ContextSize = sizeof(RdpPeerContext);
1290 	client->ContextNew = (psPeerContextNew)rdp_peer_context_new;
1291 	client->ContextFree = (psPeerContextFree)rdp_peer_context_free;
1292 	freerdp_peer_context_new(client);
1293 
1294 	peerCtx = (RdpPeerContext *) client->context;
1295 	peerCtx->rdpBackend = b;
1296 
1297 	settings = client->settings;
1298 	/* configure security settings */
1299 	if (b->rdp_key)
1300 		settings->RdpKeyFile = strdup(b->rdp_key);
1301 	if (b->tls_enabled) {
1302 		settings->CertificateFile = strdup(b->server_cert);
1303 		settings->PrivateKeyFile = strdup(b->server_key);
1304 	} else {
1305 		settings->TlsSecurity = FALSE;
1306 	}
1307 	settings->NlaSecurity = FALSE;
1308 
1309 	if (!client->Initialize(client)) {
1310 		weston_log("peer initialization failed\n");
1311 		goto error_initialize;
1312 	}
1313 
1314 	settings->OsMajorType = OSMAJORTYPE_UNIX;
1315 	settings->OsMinorType = OSMINORTYPE_PSEUDO_XSERVER;
1316 	settings->ColorDepth = 32;
1317 	settings->RefreshRect = TRUE;
1318 	settings->RemoteFxCodec = TRUE;
1319 	settings->NSCodec = TRUE;
1320 	settings->FrameMarkerCommandEnabled = TRUE;
1321 	settings->SurfaceFrameMarkerEnabled = TRUE;
1322 
1323 	client->Capabilities = xf_peer_capabilities;
1324 	client->PostConnect = xf_peer_post_connect;
1325 	client->Activate = xf_peer_activate;
1326 
1327 	client->update->SuppressOutput = (pSuppressOutput)xf_suppress_output;
1328 
1329 	input = client->input;
1330 	input->SynchronizeEvent = xf_input_synchronize_event;
1331 	input->MouseEvent = xf_mouseEvent;
1332 	input->ExtendedMouseEvent = xf_extendedMouseEvent;
1333 	input->KeyboardEvent = xf_input_keyboard_event;
1334 	input->UnicodeKeyboardEvent = xf_input_unicode_keyboard_event;
1335 
1336 	if (!client->GetFileDescriptor(client, rfds, &rcount)) {
1337 		weston_log("unable to retrieve client fds\n");
1338 		goto error_initialize;
1339 	}
1340 
1341 	loop = wl_display_get_event_loop(b->compositor->wl_display);
1342 	for (i = 0; i < rcount; i++) {
1343 		fd = (int)(long)(rfds[i]);
1344 
1345 		peerCtx->events[i] = wl_event_loop_add_fd(loop, fd, WL_EVENT_READABLE,
1346 				rdp_client_activity, client);
1347 	}
1348 	for ( ; i < MAX_FREERDP_FDS; i++)
1349 		peerCtx->events[i] = 0;
1350 
1351 	wl_list_insert(&b->output->peers, &peerCtx->item.link);
1352 	return 0;
1353 
1354 error_initialize:
1355 	client->Close(client);
1356 	return -1;
1357 }
1358 
1359 
1360 static FREERDP_CB_RET_TYPE
rdp_incoming_peer(freerdp_listener * instance,freerdp_peer * client)1361 rdp_incoming_peer(freerdp_listener *instance, freerdp_peer *client)
1362 {
1363 	struct rdp_backend *b = (struct rdp_backend *)instance->param4;
1364 	if (rdp_peer_init(client, b) < 0) {
1365 		weston_log("error when treating incoming peer\n");
1366 		FREERDP_CB_RETURN(FALSE);
1367 	}
1368 
1369 	FREERDP_CB_RETURN(TRUE);
1370 }
1371 
1372 static const struct weston_rdp_output_api api = {
1373 	rdp_output_set_size,
1374 };
1375 
1376 static struct rdp_backend *
rdp_backend_create(struct weston_compositor * compositor,struct weston_rdp_backend_config * config)1377 rdp_backend_create(struct weston_compositor *compositor,
1378 		   struct weston_rdp_backend_config *config)
1379 {
1380 	struct rdp_backend *b;
1381 	char *fd_str;
1382 	char *fd_tail;
1383 	int fd, ret;
1384 
1385 	b = zalloc(sizeof *b);
1386 	if (b == NULL)
1387 		return NULL;
1388 
1389 	b->compositor = compositor;
1390 	b->base.destroy = rdp_destroy;
1391 	b->base.create_output = rdp_output_create;
1392 	b->rdp_key = config->rdp_key ? strdup(config->rdp_key) : NULL;
1393 	b->no_clients_resize = config->no_clients_resize;
1394 	b->force_no_compression = config->force_no_compression;
1395 
1396 	compositor->backend = &b->base;
1397 
1398 	/* activate TLS only if certificate/key are available */
1399 	if (config->server_cert && config->server_key) {
1400 		weston_log("TLS support activated\n");
1401 		b->server_cert = strdup(config->server_cert);
1402 		b->server_key = strdup(config->server_key);
1403 		if (!b->server_cert || !b->server_key)
1404 			goto err_free_strings;
1405 		b->tls_enabled = 1;
1406 	}
1407 
1408 	if (weston_compositor_set_presentation_clock_software(compositor) < 0)
1409 		goto err_compositor;
1410 
1411 	if (pixman_renderer_init(compositor) < 0)
1412 		goto err_compositor;
1413 
1414 	if (rdp_head_create(compositor, "rdp") < 0)
1415 		goto err_compositor;
1416 
1417 	compositor->capabilities |= WESTON_CAP_ARBITRARY_MODES;
1418 
1419 	if (!config->env_socket) {
1420 		b->listener = freerdp_listener_new();
1421 		b->listener->PeerAccepted = rdp_incoming_peer;
1422 		b->listener->param4 = b;
1423 		if (!b->listener->Open(b->listener, config->bind_address, config->port)) {
1424 			weston_log("unable to bind rdp socket\n");
1425 			goto err_listener;
1426 		}
1427 
1428 		if (rdp_implant_listener(b, b->listener) < 0)
1429 			goto err_compositor;
1430 	} else {
1431 		/* get the socket from RDP_FD var */
1432 		fd_str = getenv("RDP_FD");
1433 		if (!fd_str) {
1434 			weston_log("RDP_FD env variable not set\n");
1435 			goto err_output;
1436 		}
1437 
1438 		fd = strtoul(fd_str, &fd_tail, 10);
1439 		if (errno != 0 || fd_tail == fd_str || *fd_tail != '\0'
1440 		    || rdp_peer_init(freerdp_peer_new(fd), b))
1441 			goto err_output;
1442 	}
1443 
1444 	ret = weston_plugin_api_register(compositor, WESTON_RDP_OUTPUT_API_NAME,
1445 					 &api, sizeof(api));
1446 
1447 	if (ret < 0) {
1448 		weston_log("Failed to register output API.\n");
1449 		goto err_output;
1450 	}
1451 
1452 	return b;
1453 
1454 err_listener:
1455 	freerdp_listener_free(b->listener);
1456 err_output:
1457 	weston_output_release(&b->output->base);
1458 err_compositor:
1459 	weston_compositor_shutdown(compositor);
1460 err_free_strings:
1461 	free(b->rdp_key);
1462 	free(b->server_cert);
1463 	free(b->server_key);
1464 	free(b);
1465 	return NULL;
1466 }
1467 
1468 static void
config_init_to_defaults(struct weston_rdp_backend_config * config)1469 config_init_to_defaults(struct weston_rdp_backend_config *config)
1470 {
1471 	config->bind_address = NULL;
1472 	config->port = 3389;
1473 	config->rdp_key = NULL;
1474 	config->server_cert = NULL;
1475 	config->server_key = NULL;
1476 	config->env_socket = 0;
1477 	config->no_clients_resize = 0;
1478 	config->force_no_compression = 0;
1479 }
1480 
1481 WL_EXPORT int
weston_backend_init(struct weston_compositor * compositor,struct weston_backend_config * config_base)1482 weston_backend_init(struct weston_compositor *compositor,
1483 		    struct weston_backend_config *config_base)
1484 {
1485 	struct rdp_backend *b;
1486 	struct weston_rdp_backend_config config = {{ 0, }};
1487 	int major, minor, revision;
1488 
1489 #if FREERDP_VERSION_MAJOR >= 2
1490 	winpr_InitializeSSL(0);
1491 #endif
1492 	freerdp_get_version(&major, &minor, &revision);
1493 	weston_log("using FreeRDP version %d.%d.%d\n", major, minor, revision);
1494 
1495 	if (config_base == NULL ||
1496 	    config_base->struct_version != WESTON_RDP_BACKEND_CONFIG_VERSION ||
1497 	    config_base->struct_size > sizeof(struct weston_rdp_backend_config)) {
1498 		weston_log("RDP backend config structure is invalid\n");
1499 		return -1;
1500 	}
1501 
1502 	config_init_to_defaults(&config);
1503 	memcpy(&config, config_base, config_base->struct_size);
1504 
1505 	if (!config.rdp_key && (!config.server_cert || !config.server_key)) {
1506 		weston_log("the RDP compositor requires keys and an optional certificate for RDP or TLS security ("
1507 				"--rdp4-key or --rdp-tls-cert/--rdp-tls-key)\n");
1508 		return -1;
1509 	}
1510 
1511 	b = rdp_backend_create(compositor, &config);
1512 	if (b == NULL)
1513 		return -1;
1514 	return 0;
1515 }
1516