xref: /openbmc/qemu/ui/vdagent.c (revision 7ae71462)
1 #include "qemu/osdep.h"
2 #include "qapi/error.h"
3 #include "chardev/char.h"
4 #include "qemu/buffer.h"
5 #include "qemu/option.h"
6 #include "qemu/units.h"
7 #include "hw/qdev-core.h"
8 #include "migration/blocker.h"
9 #include "ui/clipboard.h"
10 #include "ui/console.h"
11 #include "ui/input.h"
12 #include "trace.h"
13 
14 #include "qapi/qapi-types-char.h"
15 #include "qapi/qapi-types-ui.h"
16 
17 #include "spice/vd_agent.h"
18 
19 #define CHECK_SPICE_PROTOCOL_VERSION(major, minor, micro) \
20     (CONFIG_SPICE_PROTOCOL_MAJOR > (major) ||             \
21      (CONFIG_SPICE_PROTOCOL_MAJOR == (major) &&           \
22       CONFIG_SPICE_PROTOCOL_MINOR > (minor)) ||           \
23      (CONFIG_SPICE_PROTOCOL_MAJOR == (major) &&           \
24       CONFIG_SPICE_PROTOCOL_MINOR == (minor) &&           \
25       CONFIG_SPICE_PROTOCOL_MICRO >= (micro)))
26 
27 #define VDAGENT_BUFFER_LIMIT (1 * MiB)
28 #define VDAGENT_MOUSE_DEFAULT true
29 #define VDAGENT_CLIPBOARD_DEFAULT false
30 
31 struct VDAgentChardev {
32     Chardev parent;
33 
34     /* TODO: migration isn't yet supported */
35     Error *migration_blocker;
36 
37     /* config */
38     bool mouse;
39     bool clipboard;
40 
41     /* guest vdagent */
42     uint32_t caps;
43     VDIChunkHeader chunk;
44     uint32_t chunksize;
45     uint8_t *msgbuf;
46     uint32_t msgsize;
47     uint8_t *xbuf;
48     uint32_t xoff, xsize;
49     Buffer outbuf;
50 
51     /* mouse */
52     DeviceState mouse_dev;
53     uint32_t mouse_x;
54     uint32_t mouse_y;
55     uint32_t mouse_btn;
56     uint32_t mouse_display;
57     QemuInputHandlerState *mouse_hs;
58 
59     /* clipboard */
60     QemuClipboardPeer cbpeer;
61     uint32_t last_serial[QEMU_CLIPBOARD_SELECTION__COUNT];
62     uint32_t cbpending[QEMU_CLIPBOARD_SELECTION__COUNT];
63 };
64 typedef struct VDAgentChardev VDAgentChardev;
65 
66 #define TYPE_CHARDEV_QEMU_VDAGENT "chardev-qemu-vdagent"
67 
68 DECLARE_INSTANCE_CHECKER(VDAgentChardev, QEMU_VDAGENT_CHARDEV,
69                          TYPE_CHARDEV_QEMU_VDAGENT);
70 
71 /* ------------------------------------------------------------------ */
72 /* names, for debug logging                                           */
73 
74 static const char *cap_name[] = {
75     [VD_AGENT_CAP_MOUSE_STATE]                    = "mouse-state",
76     [VD_AGENT_CAP_MONITORS_CONFIG]                = "monitors-config",
77     [VD_AGENT_CAP_REPLY]                          = "reply",
78     [VD_AGENT_CAP_CLIPBOARD]                      = "clipboard",
79     [VD_AGENT_CAP_DISPLAY_CONFIG]                 = "display-config",
80     [VD_AGENT_CAP_CLIPBOARD_BY_DEMAND]            = "clipboard-by-demand",
81     [VD_AGENT_CAP_CLIPBOARD_SELECTION]            = "clipboard-selection",
82     [VD_AGENT_CAP_SPARSE_MONITORS_CONFIG]         = "sparse-monitors-config",
83     [VD_AGENT_CAP_GUEST_LINEEND_LF]               = "guest-lineend-lf",
84     [VD_AGENT_CAP_GUEST_LINEEND_CRLF]             = "guest-lineend-crlf",
85     [VD_AGENT_CAP_MAX_CLIPBOARD]                  = "max-clipboard",
86     [VD_AGENT_CAP_AUDIO_VOLUME_SYNC]              = "audio-volume-sync",
87     [VD_AGENT_CAP_MONITORS_CONFIG_POSITION]       = "monitors-config-position",
88     [VD_AGENT_CAP_FILE_XFER_DISABLED]             = "file-xfer-disabled",
89     [VD_AGENT_CAP_FILE_XFER_DETAILED_ERRORS]      = "file-xfer-detailed-errors",
90     [VD_AGENT_CAP_GRAPHICS_DEVICE_INFO]           = "graphics-device-info",
91 #if CHECK_SPICE_PROTOCOL_VERSION(0, 14, 1)
92     [VD_AGENT_CAP_CLIPBOARD_NO_RELEASE_ON_REGRAB] = "clipboard-no-release-on-regrab",
93     [VD_AGENT_CAP_CLIPBOARD_GRAB_SERIAL]          = "clipboard-grab-serial",
94 #endif
95 };
96 
97 static const char *msg_name[] = {
98     [VD_AGENT_MOUSE_STATE]           = "mouse-state",
99     [VD_AGENT_MONITORS_CONFIG]       = "monitors-config",
100     [VD_AGENT_REPLY]                 = "reply",
101     [VD_AGENT_CLIPBOARD]             = "clipboard",
102     [VD_AGENT_DISPLAY_CONFIG]        = "display-config",
103     [VD_AGENT_ANNOUNCE_CAPABILITIES] = "announce-capabilities",
104     [VD_AGENT_CLIPBOARD_GRAB]        = "clipboard-grab",
105     [VD_AGENT_CLIPBOARD_REQUEST]     = "clipboard-request",
106     [VD_AGENT_CLIPBOARD_RELEASE]     = "clipboard-release",
107     [VD_AGENT_FILE_XFER_START]       = "file-xfer-start",
108     [VD_AGENT_FILE_XFER_STATUS]      = "file-xfer-status",
109     [VD_AGENT_FILE_XFER_DATA]        = "file-xfer-data",
110     [VD_AGENT_CLIENT_DISCONNECTED]   = "client-disconnected",
111     [VD_AGENT_MAX_CLIPBOARD]         = "max-clipboard",
112     [VD_AGENT_AUDIO_VOLUME_SYNC]     = "audio-volume-sync",
113     [VD_AGENT_GRAPHICS_DEVICE_INFO]  = "graphics-device-info",
114 };
115 
116 static const char *sel_name[] = {
117     [VD_AGENT_CLIPBOARD_SELECTION_CLIPBOARD] = "clipboard",
118     [VD_AGENT_CLIPBOARD_SELECTION_PRIMARY]   = "primary",
119     [VD_AGENT_CLIPBOARD_SELECTION_SECONDARY] = "secondary",
120 };
121 
122 static const char *type_name[] = {
123     [VD_AGENT_CLIPBOARD_NONE]       = "none",
124     [VD_AGENT_CLIPBOARD_UTF8_TEXT]  = "text",
125     [VD_AGENT_CLIPBOARD_IMAGE_PNG]  = "png",
126     [VD_AGENT_CLIPBOARD_IMAGE_BMP]  = "bmp",
127     [VD_AGENT_CLIPBOARD_IMAGE_TIFF] = "tiff",
128     [VD_AGENT_CLIPBOARD_IMAGE_JPG]  = "jpg",
129 #if CHECK_SPICE_PROTOCOL_VERSION(0, 14, 3)
130     [VD_AGENT_CLIPBOARD_FILE_LIST]  = "files",
131 #endif
132 };
133 
134 #define GET_NAME(_m, _v) \
135     (((_v) < ARRAY_SIZE(_m) && (_m[_v])) ? (_m[_v]) : "???")
136 
137 /* ------------------------------------------------------------------ */
138 /* send messages                                                      */
139 
140 static void vdagent_send_buf(VDAgentChardev *vd)
141 {
142     uint32_t len;
143 
144     while (!buffer_empty(&vd->outbuf)) {
145         len = qemu_chr_be_can_write(CHARDEV(vd));
146         if (len == 0) {
147             return;
148         }
149         if (len > vd->outbuf.offset) {
150             len = vd->outbuf.offset;
151         }
152         qemu_chr_be_write(CHARDEV(vd), vd->outbuf.buffer, len);
153         buffer_advance(&vd->outbuf, len);
154     }
155 }
156 
157 static void vdagent_send_msg(VDAgentChardev *vd, VDAgentMessage *msg)
158 {
159     uint8_t *msgbuf = (void *)msg;
160     uint32_t msgsize = sizeof(VDAgentMessage) + msg->size;
161     uint32_t msgoff = 0;
162     VDIChunkHeader chunk;
163 
164     trace_vdagent_send(GET_NAME(msg_name, msg->type));
165 
166     msg->protocol = VD_AGENT_PROTOCOL;
167 
168     if (vd->outbuf.offset + msgsize > VDAGENT_BUFFER_LIMIT) {
169         error_report("buffer full, dropping message");
170         return;
171     }
172 
173     while (msgoff < msgsize) {
174         chunk.port = VDP_CLIENT_PORT;
175         chunk.size = msgsize - msgoff;
176         if (chunk.size > 1024) {
177             chunk.size = 1024;
178         }
179         buffer_reserve(&vd->outbuf, sizeof(chunk) + chunk.size);
180         buffer_append(&vd->outbuf, &chunk, sizeof(chunk));
181         buffer_append(&vd->outbuf, msgbuf + msgoff, chunk.size);
182         msgoff += chunk.size;
183     }
184     vdagent_send_buf(vd);
185 }
186 
187 static void vdagent_send_caps(VDAgentChardev *vd)
188 {
189     g_autofree VDAgentMessage *msg = g_malloc0(sizeof(VDAgentMessage) +
190                                                sizeof(VDAgentAnnounceCapabilities) +
191                                                sizeof(uint32_t));
192     VDAgentAnnounceCapabilities *caps = (void *)msg->data;
193 
194     msg->type = VD_AGENT_ANNOUNCE_CAPABILITIES;
195     msg->size = sizeof(VDAgentAnnounceCapabilities) + sizeof(uint32_t);
196     if (vd->mouse) {
197         caps->caps[0] |= (1 << VD_AGENT_CAP_MOUSE_STATE);
198     }
199     if (vd->clipboard) {
200         caps->caps[0] |= (1 << VD_AGENT_CAP_CLIPBOARD_BY_DEMAND);
201         caps->caps[0] |= (1 << VD_AGENT_CAP_CLIPBOARD_SELECTION);
202 #if CHECK_SPICE_PROTOCOL_VERSION(0, 14, 1)
203         caps->caps[0] |= (1 << VD_AGENT_CAP_CLIPBOARD_GRAB_SERIAL);
204 #endif
205     }
206 
207     vdagent_send_msg(vd, msg);
208 }
209 
210 /* ------------------------------------------------------------------ */
211 /* mouse events                                                       */
212 
213 static bool have_mouse(VDAgentChardev *vd)
214 {
215     return vd->mouse &&
216         (vd->caps & (1 << VD_AGENT_CAP_MOUSE_STATE));
217 }
218 
219 static void vdagent_send_mouse(VDAgentChardev *vd)
220 {
221     g_autofree VDAgentMessage *msg = g_malloc0(sizeof(VDAgentMessage) +
222                                                sizeof(VDAgentMouseState));
223     VDAgentMouseState *mouse = (void *)msg->data;
224 
225     msg->type = VD_AGENT_MOUSE_STATE;
226     msg->size = sizeof(VDAgentMouseState);
227 
228     mouse->x          = vd->mouse_x;
229     mouse->y          = vd->mouse_y;
230     mouse->buttons    = vd->mouse_btn;
231     mouse->display_id = vd->mouse_display;
232 
233     vdagent_send_msg(vd, msg);
234 }
235 
236 static void vdagent_pointer_event(DeviceState *dev, QemuConsole *src,
237                                   InputEvent *evt)
238 {
239     static const int bmap[INPUT_BUTTON__MAX] = {
240         [INPUT_BUTTON_LEFT]        = VD_AGENT_LBUTTON_MASK,
241         [INPUT_BUTTON_RIGHT]       = VD_AGENT_RBUTTON_MASK,
242         [INPUT_BUTTON_MIDDLE]      = VD_AGENT_MBUTTON_MASK,
243         [INPUT_BUTTON_WHEEL_UP]    = VD_AGENT_UBUTTON_MASK,
244         [INPUT_BUTTON_WHEEL_DOWN]  = VD_AGENT_DBUTTON_MASK,
245 #ifdef VD_AGENT_EBUTTON_MASK
246         [INPUT_BUTTON_SIDE]        = VD_AGENT_SBUTTON_MASK,
247         [INPUT_BUTTON_EXTRA]       = VD_AGENT_EBUTTON_MASK,
248 #endif
249     };
250 
251     VDAgentChardev *vd = container_of(dev, struct VDAgentChardev, mouse_dev);
252     InputMoveEvent *move;
253     InputBtnEvent *btn;
254     uint32_t xres, yres;
255 
256     switch (evt->type) {
257     case INPUT_EVENT_KIND_ABS:
258         move = evt->u.abs.data;
259         xres = qemu_console_get_width(src, 1024);
260         yres = qemu_console_get_height(src, 768);
261         if (move->axis == INPUT_AXIS_X) {
262             vd->mouse_x = qemu_input_scale_axis(move->value,
263                                                 INPUT_EVENT_ABS_MIN,
264                                                 INPUT_EVENT_ABS_MAX,
265                                                 0, xres);
266         } else if (move->axis == INPUT_AXIS_Y) {
267             vd->mouse_y = qemu_input_scale_axis(move->value,
268                                                 INPUT_EVENT_ABS_MIN,
269                                                 INPUT_EVENT_ABS_MAX,
270                                                 0, yres);
271         }
272         vd->mouse_display = qemu_console_get_index(src);
273         break;
274 
275     case INPUT_EVENT_KIND_BTN:
276         btn = evt->u.btn.data;
277         if (btn->down) {
278             vd->mouse_btn |= bmap[btn->button];
279         } else {
280             vd->mouse_btn &= ~bmap[btn->button];
281         }
282         break;
283 
284     default:
285         /* keep gcc happy */
286         break;
287     }
288 }
289 
290 static void vdagent_pointer_sync(DeviceState *dev)
291 {
292     VDAgentChardev *vd = container_of(dev, struct VDAgentChardev, mouse_dev);
293 
294     if (vd->caps & (1 << VD_AGENT_CAP_MOUSE_STATE)) {
295         vdagent_send_mouse(vd);
296     }
297 }
298 
299 static QemuInputHandler vdagent_mouse_handler = {
300     .name  = "vdagent mouse",
301     .mask  = INPUT_EVENT_MASK_BTN | INPUT_EVENT_MASK_ABS,
302     .event = vdagent_pointer_event,
303     .sync  = vdagent_pointer_sync,
304 };
305 
306 /* ------------------------------------------------------------------ */
307 /* clipboard                                                          */
308 
309 static bool have_clipboard(VDAgentChardev *vd)
310 {
311     return vd->clipboard &&
312         (vd->caps & (1 << VD_AGENT_CAP_CLIPBOARD_BY_DEMAND));
313 }
314 
315 static bool have_selection(VDAgentChardev *vd)
316 {
317     return vd->caps & (1 << VD_AGENT_CAP_CLIPBOARD_SELECTION);
318 }
319 
320 static uint32_t type_qemu_to_vdagent(enum QemuClipboardType type)
321 {
322     switch (type) {
323     case QEMU_CLIPBOARD_TYPE_TEXT:
324         return VD_AGENT_CLIPBOARD_UTF8_TEXT;
325     default:
326         return VD_AGENT_CLIPBOARD_NONE;
327     }
328 }
329 
330 static void vdagent_send_clipboard_grab(VDAgentChardev *vd,
331                                         QemuClipboardInfo *info)
332 {
333     g_autofree VDAgentMessage *msg =
334         g_malloc0(sizeof(VDAgentMessage) +
335                   sizeof(uint32_t) * (QEMU_CLIPBOARD_TYPE__COUNT + 1) +
336                   sizeof(uint32_t));
337     uint8_t *s = msg->data;
338     uint32_t *data = (uint32_t *)msg->data;
339     uint32_t q, type;
340 
341     if (have_selection(vd)) {
342         *s = info->selection;
343         data++;
344         msg->size += sizeof(uint32_t);
345     } else if (info->selection != QEMU_CLIPBOARD_SELECTION_CLIPBOARD) {
346         return;
347     }
348 
349 #if CHECK_SPICE_PROTOCOL_VERSION(0, 14, 1)
350     if (vd->caps & (1 << VD_AGENT_CAP_CLIPBOARD_GRAB_SERIAL)) {
351         if (!info->has_serial) {
352             /* client should win */
353             info->serial = vd->last_serial[info->selection]++;
354             info->has_serial = true;
355         }
356         *data = info->serial;
357         data++;
358         msg->size += sizeof(uint32_t);
359     }
360 #endif
361 
362     for (q = 0; q < QEMU_CLIPBOARD_TYPE__COUNT; q++) {
363         type = type_qemu_to_vdagent(q);
364         if (type != VD_AGENT_CLIPBOARD_NONE && info->types[q].available) {
365             *data = type;
366             data++;
367             msg->size += sizeof(uint32_t);
368         }
369     }
370 
371     msg->type = VD_AGENT_CLIPBOARD_GRAB;
372     vdagent_send_msg(vd, msg);
373 }
374 
375 static void vdagent_send_clipboard_release(VDAgentChardev *vd,
376                                            QemuClipboardInfo *info)
377 {
378     g_autofree VDAgentMessage *msg = g_malloc0(sizeof(VDAgentMessage) +
379                                                sizeof(uint32_t));
380 
381     if (have_selection(vd)) {
382         uint8_t *s = msg->data;
383         *s = info->selection;
384         msg->size += sizeof(uint32_t);
385     } else if (info->selection != QEMU_CLIPBOARD_SELECTION_CLIPBOARD) {
386         return;
387     }
388 
389     msg->type = VD_AGENT_CLIPBOARD_RELEASE;
390     vdagent_send_msg(vd, msg);
391 }
392 
393 static void vdagent_send_clipboard_data(VDAgentChardev *vd,
394                                         QemuClipboardInfo *info,
395                                         QemuClipboardType type)
396 {
397     g_autofree VDAgentMessage *msg = g_malloc0(sizeof(VDAgentMessage) +
398                                                sizeof(uint32_t) * 2 +
399                                                info->types[type].size);
400 
401     uint8_t *s = msg->data;
402     uint32_t *data = (uint32_t *)msg->data;
403 
404     if (have_selection(vd)) {
405         *s = info->selection;
406         data++;
407         msg->size += sizeof(uint32_t);
408     } else if (info->selection != QEMU_CLIPBOARD_SELECTION_CLIPBOARD) {
409         return;
410     }
411 
412     *data = type_qemu_to_vdagent(type);
413     data++;
414     msg->size += sizeof(uint32_t);
415 
416     memcpy(data, info->types[type].data, info->types[type].size);
417     msg->size += info->types[type].size;
418 
419     msg->type = VD_AGENT_CLIPBOARD;
420     vdagent_send_msg(vd, msg);
421 }
422 
423 static void vdagent_send_empty_clipboard_data(VDAgentChardev *vd,
424                                               QemuClipboardSelection selection,
425                                               QemuClipboardType type)
426 {
427     g_autoptr(QemuClipboardInfo) info = qemu_clipboard_info_new(&vd->cbpeer, selection);
428 
429     trace_vdagent_send_empty_clipboard();
430     vdagent_send_clipboard_data(vd, info, type);
431 }
432 
433 static void vdagent_clipboard_update_info(VDAgentChardev *vd,
434                                           QemuClipboardInfo *info)
435 {
436     QemuClipboardSelection s = info->selection;
437     QemuClipboardType type;
438     bool self_update = info->owner == &vd->cbpeer;
439 
440     if (info != qemu_clipboard_info(s)) {
441         vd->cbpending[s] = 0;
442         if (!self_update) {
443             if (info->owner) {
444                 vdagent_send_clipboard_grab(vd, info);
445             } else {
446                 vdagent_send_clipboard_release(vd, info);
447             }
448         }
449         return;
450     }
451 
452     if (self_update) {
453         return;
454     }
455 
456     for (type = 0; type < QEMU_CLIPBOARD_TYPE__COUNT; type++) {
457         if (vd->cbpending[s] & (1 << type)) {
458             vd->cbpending[s] &= ~(1 << type);
459             vdagent_send_clipboard_data(vd, info, type);
460         }
461     }
462 }
463 
464 static void vdagent_clipboard_reset_serial(VDAgentChardev *vd)
465 {
466     Chardev *chr = CHARDEV(vd);
467 
468     /* reopen the agent connection to reset the serial state */
469     qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
470     /* OPENED again after the guest disconnected, see set_fe_open */
471 }
472 
473 static void vdagent_clipboard_notify(Notifier *notifier, void *data)
474 {
475     VDAgentChardev *vd =
476         container_of(notifier, VDAgentChardev, cbpeer.notifier);
477     QemuClipboardNotify *notify = data;
478 
479     switch (notify->type) {
480     case QEMU_CLIPBOARD_UPDATE_INFO:
481         vdagent_clipboard_update_info(vd, notify->info);
482         return;
483     case QEMU_CLIPBOARD_RESET_SERIAL:
484         vdagent_clipboard_reset_serial(vd);
485         return;
486     }
487 }
488 
489 static void vdagent_clipboard_request(QemuClipboardInfo *info,
490                                       QemuClipboardType qtype)
491 {
492     VDAgentChardev *vd = container_of(info->owner, VDAgentChardev, cbpeer);
493     g_autofree VDAgentMessage *msg = g_malloc0(sizeof(VDAgentMessage) +
494                                                sizeof(uint32_t) * 2);
495     uint32_t type = type_qemu_to_vdagent(qtype);
496     uint8_t *s = msg->data;
497     uint32_t *data = (uint32_t *)msg->data;
498 
499     if (type == VD_AGENT_CLIPBOARD_NONE) {
500         return;
501     }
502 
503     if (have_selection(vd)) {
504         *s = info->selection;
505         data++;
506         msg->size += sizeof(uint32_t);
507     }
508 
509     *data = type;
510     msg->size += sizeof(uint32_t);
511 
512     msg->type = VD_AGENT_CLIPBOARD_REQUEST;
513     vdagent_send_msg(vd, msg);
514 }
515 
516 static void vdagent_clipboard_recv_grab(VDAgentChardev *vd, uint8_t s, uint32_t size, void *data)
517 {
518     g_autoptr(QemuClipboardInfo) info = NULL;
519 
520     trace_vdagent_cb_grab_selection(GET_NAME(sel_name, s));
521     info = qemu_clipboard_info_new(&vd->cbpeer, s);
522 #if CHECK_SPICE_PROTOCOL_VERSION(0, 14, 1)
523     if (vd->caps & (1 << VD_AGENT_CAP_CLIPBOARD_GRAB_SERIAL)) {
524         if (size < sizeof(uint32_t)) {
525             /* this shouldn't happen! */
526             return;
527         }
528 
529         info->has_serial = true;
530         info->serial = *(uint32_t *)data;
531         if (info->serial < vd->last_serial[s]) {
532             trace_vdagent_cb_grab_discard(GET_NAME(sel_name, s),
533                                           vd->last_serial[s], info->serial);
534             /* discard lower-ordering guest grab */
535             return;
536         }
537         vd->last_serial[s] = info->serial;
538         data += sizeof(uint32_t);
539         size -= sizeof(uint32_t);
540     }
541 #endif
542     if (size > sizeof(uint32_t) * 10) {
543         /*
544          * spice has 6 types as of 2021. Limiting to 10 entries
545          * so we have some wiggle room.
546          */
547         return;
548     }
549     while (size >= sizeof(uint32_t)) {
550         trace_vdagent_cb_grab_type(GET_NAME(type_name, *(uint32_t *)data));
551         switch (*(uint32_t *)data) {
552         case VD_AGENT_CLIPBOARD_UTF8_TEXT:
553             info->types[QEMU_CLIPBOARD_TYPE_TEXT].available = true;
554             break;
555         default:
556             break;
557         }
558         data += sizeof(uint32_t);
559         size -= sizeof(uint32_t);
560     }
561     qemu_clipboard_update(info);
562 }
563 
564 static void vdagent_clipboard_recv_request(VDAgentChardev *vd, uint8_t s, uint32_t size, void *data)
565 {
566     QemuClipboardType type;
567     QemuClipboardInfo *info;
568 
569     if (size < sizeof(uint32_t)) {
570         return;
571     }
572     switch (*(uint32_t *)data) {
573     case VD_AGENT_CLIPBOARD_UTF8_TEXT:
574         type = QEMU_CLIPBOARD_TYPE_TEXT;
575         break;
576     default:
577         return;
578     }
579 
580     info = qemu_clipboard_info(s);
581     if (info && info->types[type].available && info->owner != &vd->cbpeer) {
582         if (info->types[type].data) {
583             vdagent_send_clipboard_data(vd, info, type);
584         } else {
585             vd->cbpending[s] |= (1 << type);
586             qemu_clipboard_request(info, type);
587         }
588     } else {
589         vdagent_send_empty_clipboard_data(vd, s, type);
590     }
591 }
592 
593 static void vdagent_clipboard_recv_data(VDAgentChardev *vd, uint8_t s, uint32_t size, void *data)
594 {
595     QemuClipboardType type;
596 
597     if (size < sizeof(uint32_t)) {
598         return;
599     }
600     switch (*(uint32_t *)data) {
601     case VD_AGENT_CLIPBOARD_UTF8_TEXT:
602         type = QEMU_CLIPBOARD_TYPE_TEXT;
603         break;
604     default:
605         return;
606     }
607     data += 4;
608     size -= 4;
609 
610     if (qemu_clipboard_peer_owns(&vd->cbpeer, s)) {
611         qemu_clipboard_set_data(&vd->cbpeer, qemu_clipboard_info(s),
612                                 type, size, data, true);
613     }
614 }
615 
616 static void vdagent_clipboard_recv_release(VDAgentChardev *vd, uint8_t s)
617 {
618     qemu_clipboard_peer_release(&vd->cbpeer, s);
619 }
620 
621 static void vdagent_chr_recv_clipboard(VDAgentChardev *vd, VDAgentMessage *msg)
622 {
623     uint8_t s = VD_AGENT_CLIPBOARD_SELECTION_CLIPBOARD;
624     uint32_t size = msg->size;
625     void *data = msg->data;
626 
627     if (have_selection(vd)) {
628         if (size < 4) {
629             return;
630         }
631         s = *(uint8_t *)data;
632         if (s >= QEMU_CLIPBOARD_SELECTION__COUNT) {
633             return;
634         }
635         data += 4;
636         size -= 4;
637     }
638 
639     switch (msg->type) {
640     case VD_AGENT_CLIPBOARD_GRAB:
641         return vdagent_clipboard_recv_grab(vd, s, size, data);
642     case VD_AGENT_CLIPBOARD_REQUEST:
643         return vdagent_clipboard_recv_request(vd, s, size, data);
644     case VD_AGENT_CLIPBOARD: /* data */
645         return vdagent_clipboard_recv_data(vd, s, size, data);
646     case VD_AGENT_CLIPBOARD_RELEASE:
647         return vdagent_clipboard_recv_release(vd, s);
648     default:
649         g_assert_not_reached();
650     }
651 }
652 
653 /* ------------------------------------------------------------------ */
654 /* chardev backend                                                    */
655 
656 static void vdagent_chr_open(Chardev *chr,
657                              ChardevBackend *backend,
658                              bool *be_opened,
659                              Error **errp)
660 {
661     VDAgentChardev *vd = QEMU_VDAGENT_CHARDEV(chr);
662     ChardevQemuVDAgent *cfg = backend->u.qemu_vdagent.data;
663 
664 #if HOST_BIG_ENDIAN
665     /*
666      * TODO: vdagent protocol is defined to be LE,
667      * so we have to byteswap everything on BE hosts.
668      */
669     error_setg(errp, "vdagent is not supported on bigendian hosts");
670     return;
671 #endif
672 
673     if (migrate_add_blocker(vd->migration_blocker, errp) != 0) {
674         return;
675     }
676 
677     vd->mouse = VDAGENT_MOUSE_DEFAULT;
678     if (cfg->has_mouse) {
679         vd->mouse = cfg->mouse;
680     }
681 
682     vd->clipboard = VDAGENT_CLIPBOARD_DEFAULT;
683     if (cfg->has_clipboard) {
684         vd->clipboard = cfg->clipboard;
685     }
686 
687     if (vd->mouse) {
688         vd->mouse_hs = qemu_input_handler_register(&vd->mouse_dev,
689                                                    &vdagent_mouse_handler);
690     }
691 
692     *be_opened = true;
693 }
694 
695 static void vdagent_chr_recv_caps(VDAgentChardev *vd, VDAgentMessage *msg)
696 {
697     VDAgentAnnounceCapabilities *caps = (void *)msg->data;
698     int i;
699 
700     if (msg->size < (sizeof(VDAgentAnnounceCapabilities) +
701                      sizeof(uint32_t))) {
702         return;
703     }
704 
705     for (i = 0; i < ARRAY_SIZE(cap_name); i++) {
706         if (caps->caps[0] & (1 << i)) {
707             trace_vdagent_peer_cap(GET_NAME(cap_name, i));
708         }
709     }
710 
711     vd->caps = caps->caps[0];
712     if (caps->request) {
713         vdagent_send_caps(vd);
714     }
715     if (have_mouse(vd) && vd->mouse_hs) {
716         qemu_input_handler_activate(vd->mouse_hs);
717     }
718 
719     memset(vd->last_serial, 0, sizeof(vd->last_serial));
720 
721     if (have_clipboard(vd) && vd->cbpeer.notifier.notify == NULL) {
722         vd->cbpeer.name = "vdagent";
723         vd->cbpeer.notifier.notify = vdagent_clipboard_notify;
724         vd->cbpeer.request = vdagent_clipboard_request;
725         qemu_clipboard_peer_register(&vd->cbpeer);
726     }
727 }
728 
729 static void vdagent_chr_recv_msg(VDAgentChardev *vd, VDAgentMessage *msg)
730 {
731     trace_vdagent_recv_msg(GET_NAME(msg_name, msg->type), msg->size);
732 
733     switch (msg->type) {
734     case VD_AGENT_ANNOUNCE_CAPABILITIES:
735         vdagent_chr_recv_caps(vd, msg);
736         break;
737     case VD_AGENT_CLIPBOARD:
738     case VD_AGENT_CLIPBOARD_GRAB:
739     case VD_AGENT_CLIPBOARD_REQUEST:
740     case VD_AGENT_CLIPBOARD_RELEASE:
741         if (have_clipboard(vd)) {
742             vdagent_chr_recv_clipboard(vd, msg);
743         }
744         break;
745     default:
746         break;
747     }
748 }
749 
750 static void vdagent_reset_xbuf(VDAgentChardev *vd)
751 {
752     g_clear_pointer(&vd->xbuf, g_free);
753     vd->xoff = 0;
754     vd->xsize = 0;
755 }
756 
757 static void vdagent_chr_recv_chunk(VDAgentChardev *vd)
758 {
759     VDAgentMessage *msg = (void *)vd->msgbuf;
760 
761     if (!vd->xsize) {
762         if (vd->msgsize < sizeof(*msg)) {
763             error_report("%s: message too small: %d < %zd", __func__,
764                          vd->msgsize, sizeof(*msg));
765             return;
766         }
767         if (vd->msgsize == msg->size + sizeof(*msg)) {
768             vdagent_chr_recv_msg(vd, msg);
769             return;
770         }
771     }
772 
773     if (!vd->xsize) {
774         vd->xsize = msg->size + sizeof(*msg);
775         vd->xbuf = g_malloc0(vd->xsize);
776     }
777 
778     if (vd->xoff + vd->msgsize > vd->xsize) {
779         error_report("%s: Oops: %d+%d > %d", __func__,
780                      vd->xoff, vd->msgsize, vd->xsize);
781         vdagent_reset_xbuf(vd);
782         return;
783     }
784 
785     memcpy(vd->xbuf + vd->xoff, vd->msgbuf, vd->msgsize);
786     vd->xoff += vd->msgsize;
787     if (vd->xoff < vd->xsize) {
788         return;
789     }
790 
791     msg = (void *)vd->xbuf;
792     vdagent_chr_recv_msg(vd, msg);
793     vdagent_reset_xbuf(vd);
794 }
795 
796 static void vdagent_reset_bufs(VDAgentChardev *vd)
797 {
798     memset(&vd->chunk, 0, sizeof(vd->chunk));
799     vd->chunksize = 0;
800     g_free(vd->msgbuf);
801     vd->msgbuf = NULL;
802     vd->msgsize = 0;
803 }
804 
805 static int vdagent_chr_write(Chardev *chr, const uint8_t *buf, int len)
806 {
807     VDAgentChardev *vd = QEMU_VDAGENT_CHARDEV(chr);
808     uint32_t copy, ret = len;
809 
810     while (len) {
811         if (vd->chunksize < sizeof(vd->chunk)) {
812             copy = sizeof(vd->chunk) - vd->chunksize;
813             if (copy > len) {
814                 copy = len;
815             }
816             memcpy((void *)(&vd->chunk) + vd->chunksize, buf, copy);
817             vd->chunksize += copy;
818             buf += copy;
819             len -= copy;
820             if (vd->chunksize < sizeof(vd->chunk)) {
821                 break;
822             }
823 
824             assert(vd->msgbuf == NULL);
825             vd->msgbuf = g_malloc0(vd->chunk.size);
826         }
827 
828         copy = vd->chunk.size - vd->msgsize;
829         if (copy > len) {
830             copy = len;
831         }
832         memcpy(vd->msgbuf + vd->msgsize, buf, copy);
833         vd->msgsize += copy;
834         buf += copy;
835         len -= copy;
836 
837         if (vd->msgsize == vd->chunk.size) {
838             trace_vdagent_recv_chunk(vd->chunk.size);
839             vdagent_chr_recv_chunk(vd);
840             vdagent_reset_bufs(vd);
841         }
842     }
843 
844     return ret;
845 }
846 
847 static void vdagent_chr_accept_input(Chardev *chr)
848 {
849     VDAgentChardev *vd = QEMU_VDAGENT_CHARDEV(chr);
850 
851     vdagent_send_buf(vd);
852 }
853 
854 static void vdagent_disconnect(VDAgentChardev *vd)
855 {
856     trace_vdagent_disconnect();
857 
858     buffer_reset(&vd->outbuf);
859     vdagent_reset_bufs(vd);
860     vd->caps = 0;
861     if (vd->mouse_hs) {
862         qemu_input_handler_deactivate(vd->mouse_hs);
863     }
864     if (vd->cbpeer.notifier.notify) {
865         qemu_clipboard_peer_unregister(&vd->cbpeer);
866         memset(&vd->cbpeer, 0, sizeof(vd->cbpeer));
867     }
868 }
869 
870 static void vdagent_chr_set_fe_open(struct Chardev *chr, int fe_open)
871 {
872     if (!fe_open) {
873         trace_vdagent_close();
874         /* To reset_serial, we CLOSED our side. Make sure the other end knows we
875          * are ready again. */
876         qemu_chr_be_event(chr, CHR_EVENT_OPENED);
877         return;
878     }
879 
880     trace_vdagent_open();
881 }
882 
883 static void vdagent_chr_parse(QemuOpts *opts, ChardevBackend *backend,
884                               Error **errp)
885 {
886     ChardevQemuVDAgent *cfg;
887 
888     backend->type = CHARDEV_BACKEND_KIND_QEMU_VDAGENT;
889     cfg = backend->u.qemu_vdagent.data = g_new0(ChardevQemuVDAgent, 1);
890     qemu_chr_parse_common(opts, qapi_ChardevQemuVDAgent_base(cfg));
891     cfg->has_mouse = true;
892     cfg->mouse = qemu_opt_get_bool(opts, "mouse", VDAGENT_MOUSE_DEFAULT);
893     cfg->has_clipboard = true;
894     cfg->clipboard = qemu_opt_get_bool(opts, "clipboard", VDAGENT_CLIPBOARD_DEFAULT);
895 }
896 
897 /* ------------------------------------------------------------------ */
898 
899 static void vdagent_chr_class_init(ObjectClass *oc, void *data)
900 {
901     ChardevClass *cc = CHARDEV_CLASS(oc);
902 
903     cc->parse            = vdagent_chr_parse;
904     cc->open             = vdagent_chr_open;
905     cc->chr_write        = vdagent_chr_write;
906     cc->chr_set_fe_open  = vdagent_chr_set_fe_open;
907     cc->chr_accept_input = vdagent_chr_accept_input;
908 }
909 
910 static void vdagent_chr_init(Object *obj)
911 {
912     VDAgentChardev *vd = QEMU_VDAGENT_CHARDEV(obj);
913 
914     buffer_init(&vd->outbuf, "vdagent-outbuf");
915     error_setg(&vd->migration_blocker,
916                "The vdagent chardev doesn't yet support migration");
917 }
918 
919 static void vdagent_chr_fini(Object *obj)
920 {
921     VDAgentChardev *vd = QEMU_VDAGENT_CHARDEV(obj);
922 
923     migrate_del_blocker(vd->migration_blocker);
924     vdagent_disconnect(vd);
925     buffer_free(&vd->outbuf);
926     error_free(vd->migration_blocker);
927 }
928 
929 static const TypeInfo vdagent_chr_type_info = {
930     .name = TYPE_CHARDEV_QEMU_VDAGENT,
931     .parent = TYPE_CHARDEV,
932     .instance_size = sizeof(VDAgentChardev),
933     .instance_init = vdagent_chr_init,
934     .instance_finalize = vdagent_chr_fini,
935     .class_init = vdagent_chr_class_init,
936 };
937 
938 static void register_types(void)
939 {
940     type_register_static(&vdagent_chr_type_info);
941 }
942 
943 type_init(register_types);
944