xref: /openbmc/qemu/ui/spice-core.c (revision c2387413)
1 /*
2  * Copyright (C) 2010 Red Hat, Inc.
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License as
6  * published by the Free Software Foundation; either version 2 or
7  * (at your option) version 3 of the License.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, see <http://www.gnu.org/licenses/>.
16  */
17 
18 #include "qemu/osdep.h"
19 #include <spice.h>
20 
21 #include "sysemu/sysemu.h"
22 #include "sysemu/runstate.h"
23 #include "ui/qemu-spice.h"
24 #include "qemu/error-report.h"
25 #include "qemu/main-loop.h"
26 #include "qemu/module.h"
27 #include "qemu/thread.h"
28 #include "qemu/timer.h"
29 #include "qemu/queue.h"
30 #include "qemu-x509.h"
31 #include "qemu/sockets.h"
32 #include "qapi/error.h"
33 #include "qapi/qapi-commands-ui.h"
34 #include "qapi/qapi-events-ui.h"
35 #include "qemu/notify.h"
36 #include "qemu/option.h"
37 #include "migration/misc.h"
38 #include "hw/pci/pci_bus.h"
39 #include "ui/spice-display.h"
40 
41 /* core bits */
42 
43 static SpiceServer *spice_server;
44 static Notifier migration_state;
45 static const char *auth = "spice";
46 static char *auth_passwd;
47 static time_t auth_expires = TIME_MAX;
48 static int spice_migration_completed;
49 static int spice_display_is_running;
50 static int spice_have_target_host;
51 
52 static QemuThread me;
53 
54 struct SpiceTimer {
55     QEMUTimer *timer;
56 };
57 
58 static SpiceTimer *timer_add(SpiceTimerFunc func, void *opaque)
59 {
60     SpiceTimer *timer;
61 
62     timer = g_malloc0(sizeof(*timer));
63     timer->timer = timer_new_ms(QEMU_CLOCK_REALTIME, func, opaque);
64     return timer;
65 }
66 
67 static void timer_start(SpiceTimer *timer, uint32_t ms)
68 {
69     timer_mod(timer->timer, qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + ms);
70 }
71 
72 static void timer_cancel(SpiceTimer *timer)
73 {
74     timer_del(timer->timer);
75 }
76 
77 static void timer_remove(SpiceTimer *timer)
78 {
79     timer_free(timer->timer);
80     g_free(timer);
81 }
82 
83 struct SpiceWatch {
84     int fd;
85     SpiceWatchFunc func;
86     void *opaque;
87 };
88 
89 static void watch_read(void *opaque)
90 {
91     SpiceWatch *watch = opaque;
92     watch->func(watch->fd, SPICE_WATCH_EVENT_READ, watch->opaque);
93 }
94 
95 static void watch_write(void *opaque)
96 {
97     SpiceWatch *watch = opaque;
98     watch->func(watch->fd, SPICE_WATCH_EVENT_WRITE, watch->opaque);
99 }
100 
101 static void watch_update_mask(SpiceWatch *watch, int event_mask)
102 {
103     IOHandler *on_read = NULL;
104     IOHandler *on_write = NULL;
105 
106     if (event_mask & SPICE_WATCH_EVENT_READ) {
107         on_read = watch_read;
108     }
109     if (event_mask & SPICE_WATCH_EVENT_WRITE) {
110         on_write = watch_write;
111     }
112     qemu_set_fd_handler(watch->fd, on_read, on_write, watch);
113 }
114 
115 static SpiceWatch *watch_add(int fd, int event_mask, SpiceWatchFunc func, void *opaque)
116 {
117     SpiceWatch *watch;
118 
119     watch = g_malloc0(sizeof(*watch));
120     watch->fd     = fd;
121     watch->func   = func;
122     watch->opaque = opaque;
123 
124     watch_update_mask(watch, event_mask);
125     return watch;
126 }
127 
128 static void watch_remove(SpiceWatch *watch)
129 {
130     qemu_set_fd_handler(watch->fd, NULL, NULL, NULL);
131     g_free(watch);
132 }
133 
134 typedef struct ChannelList ChannelList;
135 struct ChannelList {
136     SpiceChannelEventInfo *info;
137     QTAILQ_ENTRY(ChannelList) link;
138 };
139 static QTAILQ_HEAD(, ChannelList) channel_list = QTAILQ_HEAD_INITIALIZER(channel_list);
140 
141 static void channel_list_add(SpiceChannelEventInfo *info)
142 {
143     ChannelList *item;
144 
145     item = g_malloc0(sizeof(*item));
146     item->info = info;
147     QTAILQ_INSERT_TAIL(&channel_list, item, link);
148 }
149 
150 static void channel_list_del(SpiceChannelEventInfo *info)
151 {
152     ChannelList *item;
153 
154     QTAILQ_FOREACH(item, &channel_list, link) {
155         if (item->info != info) {
156             continue;
157         }
158         QTAILQ_REMOVE(&channel_list, item, link);
159         g_free(item);
160         return;
161     }
162 }
163 
164 static void add_addr_info(SpiceBasicInfo *info, struct sockaddr *addr, int len)
165 {
166     char host[NI_MAXHOST], port[NI_MAXSERV];
167 
168     getnameinfo(addr, len, host, sizeof(host), port, sizeof(port),
169                 NI_NUMERICHOST | NI_NUMERICSERV);
170 
171     info->host = g_strdup(host);
172     info->port = g_strdup(port);
173     info->family = inet_netfamily(addr->sa_family);
174 }
175 
176 static void add_channel_info(SpiceChannel *sc, SpiceChannelEventInfo *info)
177 {
178     int tls = info->flags & SPICE_CHANNEL_EVENT_FLAG_TLS;
179 
180     sc->connection_id = info->connection_id;
181     sc->channel_type = info->type;
182     sc->channel_id = info->id;
183     sc->tls = !!tls;
184 }
185 
186 static void channel_event(int event, SpiceChannelEventInfo *info)
187 {
188     SpiceServerInfo *server = g_malloc0(sizeof(*server));
189     SpiceChannel *client = g_malloc0(sizeof(*client));
190 
191     /*
192      * Spice server might have called us from spice worker thread
193      * context (happens on display channel disconnects).  Spice should
194      * not do that.  It isn't that easy to fix it in spice and even
195      * when it is fixed we still should cover the already released
196      * spice versions.  So detect that we've been called from another
197      * thread and grab the iothread lock if so before calling qemu
198      * functions.
199      */
200     bool need_lock = !qemu_thread_is_self(&me);
201     if (need_lock) {
202         qemu_mutex_lock_iothread();
203     }
204 
205     if (info->flags & SPICE_CHANNEL_EVENT_FLAG_ADDR_EXT) {
206         add_addr_info(qapi_SpiceChannel_base(client),
207                       (struct sockaddr *)&info->paddr_ext,
208                       info->plen_ext);
209         add_addr_info(qapi_SpiceServerInfo_base(server),
210                       (struct sockaddr *)&info->laddr_ext,
211                       info->llen_ext);
212     } else {
213         error_report("spice: %s, extended address is expected",
214                      __func__);
215     }
216 
217     switch (event) {
218     case SPICE_CHANNEL_EVENT_CONNECTED:
219         qapi_event_send_spice_connected(qapi_SpiceServerInfo_base(server),
220                                         qapi_SpiceChannel_base(client));
221         break;
222     case SPICE_CHANNEL_EVENT_INITIALIZED:
223         if (auth) {
224             server->has_auth = true;
225             server->auth = g_strdup(auth);
226         }
227         add_channel_info(client, info);
228         channel_list_add(info);
229         qapi_event_send_spice_initialized(server, client);
230         break;
231     case SPICE_CHANNEL_EVENT_DISCONNECTED:
232         channel_list_del(info);
233         qapi_event_send_spice_disconnected(qapi_SpiceServerInfo_base(server),
234                                            qapi_SpiceChannel_base(client));
235         break;
236     default:
237         break;
238     }
239 
240     if (need_lock) {
241         qemu_mutex_unlock_iothread();
242     }
243 
244     qapi_free_SpiceServerInfo(server);
245     qapi_free_SpiceChannel(client);
246 }
247 
248 static SpiceCoreInterface core_interface = {
249     .base.type          = SPICE_INTERFACE_CORE,
250     .base.description   = "qemu core services",
251     .base.major_version = SPICE_INTERFACE_CORE_MAJOR,
252     .base.minor_version = SPICE_INTERFACE_CORE_MINOR,
253 
254     .timer_add          = timer_add,
255     .timer_start        = timer_start,
256     .timer_cancel       = timer_cancel,
257     .timer_remove       = timer_remove,
258 
259     .watch_add          = watch_add,
260     .watch_update_mask  = watch_update_mask,
261     .watch_remove       = watch_remove,
262 
263     .channel_event      = channel_event,
264 };
265 
266 static void migrate_connect_complete_cb(SpiceMigrateInstance *sin);
267 static void migrate_end_complete_cb(SpiceMigrateInstance *sin);
268 
269 static const SpiceMigrateInterface migrate_interface = {
270     .base.type = SPICE_INTERFACE_MIGRATION,
271     .base.description = "migration",
272     .base.major_version = SPICE_INTERFACE_MIGRATION_MAJOR,
273     .base.minor_version = SPICE_INTERFACE_MIGRATION_MINOR,
274     .migrate_connect_complete = migrate_connect_complete_cb,
275     .migrate_end_complete = migrate_end_complete_cb,
276 };
277 
278 static SpiceMigrateInstance spice_migrate;
279 
280 static void migrate_connect_complete_cb(SpiceMigrateInstance *sin)
281 {
282     /* nothing, but libspice-server expects this cb being present. */
283 }
284 
285 static void migrate_end_complete_cb(SpiceMigrateInstance *sin)
286 {
287     qapi_event_send_spice_migrate_completed();
288     spice_migration_completed = true;
289 }
290 
291 /* config string parsing */
292 
293 static int name2enum(const char *string, const char *table[], int entries)
294 {
295     int i;
296 
297     if (string) {
298         for (i = 0; i < entries; i++) {
299             if (!table[i]) {
300                 continue;
301             }
302             if (strcmp(string, table[i]) != 0) {
303                 continue;
304             }
305             return i;
306         }
307     }
308     return -1;
309 }
310 
311 static int parse_name(const char *string, const char *optname,
312                       const char *table[], int entries)
313 {
314     int value = name2enum(string, table, entries);
315 
316     if (value != -1) {
317         return value;
318     }
319     error_report("spice: invalid %s: %s", optname, string);
320     exit(1);
321 }
322 
323 static const char *stream_video_names[] = {
324     [ SPICE_STREAM_VIDEO_OFF ]    = "off",
325     [ SPICE_STREAM_VIDEO_ALL ]    = "all",
326     [ SPICE_STREAM_VIDEO_FILTER ] = "filter",
327 };
328 #define parse_stream_video(_name) \
329     parse_name(_name, "stream video control", \
330                stream_video_names, ARRAY_SIZE(stream_video_names))
331 
332 static const char *compression_names[] = {
333     [ SPICE_IMAGE_COMPRESS_OFF ]      = "off",
334     [ SPICE_IMAGE_COMPRESS_AUTO_GLZ ] = "auto_glz",
335     [ SPICE_IMAGE_COMPRESS_AUTO_LZ ]  = "auto_lz",
336     [ SPICE_IMAGE_COMPRESS_QUIC ]     = "quic",
337     [ SPICE_IMAGE_COMPRESS_GLZ ]      = "glz",
338     [ SPICE_IMAGE_COMPRESS_LZ ]       = "lz",
339 };
340 #define parse_compression(_name)                                        \
341     parse_name(_name, "image compression",                              \
342                compression_names, ARRAY_SIZE(compression_names))
343 
344 static const char *wan_compression_names[] = {
345     [ SPICE_WAN_COMPRESSION_AUTO   ] = "auto",
346     [ SPICE_WAN_COMPRESSION_NEVER  ] = "never",
347     [ SPICE_WAN_COMPRESSION_ALWAYS ] = "always",
348 };
349 #define parse_wan_compression(_name)                                    \
350     parse_name(_name, "wan compression",                                \
351                wan_compression_names, ARRAY_SIZE(wan_compression_names))
352 
353 /* functions for the rest of qemu */
354 
355 static SpiceChannelList *qmp_query_spice_channels(void)
356 {
357     SpiceChannelList *head = NULL, **tail = &head;
358     ChannelList *item;
359 
360     QTAILQ_FOREACH(item, &channel_list, link) {
361         SpiceChannel *chan;
362         char host[NI_MAXHOST], port[NI_MAXSERV];
363         struct sockaddr *paddr;
364         socklen_t plen;
365 
366         assert(item->info->flags & SPICE_CHANNEL_EVENT_FLAG_ADDR_EXT);
367 
368         chan = g_malloc0(sizeof(*chan));
369 
370         paddr = (struct sockaddr *)&item->info->paddr_ext;
371         plen = item->info->plen_ext;
372         getnameinfo(paddr, plen,
373                     host, sizeof(host), port, sizeof(port),
374                     NI_NUMERICHOST | NI_NUMERICSERV);
375         chan->host = g_strdup(host);
376         chan->port = g_strdup(port);
377         chan->family = inet_netfamily(paddr->sa_family);
378 
379         chan->connection_id = item->info->connection_id;
380         chan->channel_type = item->info->type;
381         chan->channel_id = item->info->id;
382         chan->tls = item->info->flags & SPICE_CHANNEL_EVENT_FLAG_TLS;
383 
384         QAPI_LIST_APPEND(tail, chan);
385     }
386 
387     return head;
388 }
389 
390 static QemuOptsList qemu_spice_opts = {
391     .name = "spice",
392     .head = QTAILQ_HEAD_INITIALIZER(qemu_spice_opts.head),
393     .merge_lists = true,
394     .desc = {
395         {
396             .name = "port",
397             .type = QEMU_OPT_NUMBER,
398         },{
399             .name = "tls-port",
400             .type = QEMU_OPT_NUMBER,
401         },{
402             .name = "addr",
403             .type = QEMU_OPT_STRING,
404         },{
405             .name = "ipv4",
406             .type = QEMU_OPT_BOOL,
407         },{
408             .name = "ipv6",
409             .type = QEMU_OPT_BOOL,
410 #ifdef SPICE_ADDR_FLAG_UNIX_ONLY
411         },{
412             .name = "unix",
413             .type = QEMU_OPT_BOOL,
414 #endif
415         },{
416             .name = "password",
417             .type = QEMU_OPT_STRING,
418         },{
419             .name = "disable-ticketing",
420             .type = QEMU_OPT_BOOL,
421         },{
422             .name = "disable-copy-paste",
423             .type = QEMU_OPT_BOOL,
424         },{
425             .name = "disable-agent-file-xfer",
426             .type = QEMU_OPT_BOOL,
427         },{
428             .name = "sasl",
429             .type = QEMU_OPT_BOOL,
430         },{
431             .name = "x509-dir",
432             .type = QEMU_OPT_STRING,
433         },{
434             .name = "x509-key-file",
435             .type = QEMU_OPT_STRING,
436         },{
437             .name = "x509-key-password",
438             .type = QEMU_OPT_STRING,
439         },{
440             .name = "x509-cert-file",
441             .type = QEMU_OPT_STRING,
442         },{
443             .name = "x509-cacert-file",
444             .type = QEMU_OPT_STRING,
445         },{
446             .name = "x509-dh-key-file",
447             .type = QEMU_OPT_STRING,
448         },{
449             .name = "tls-ciphers",
450             .type = QEMU_OPT_STRING,
451         },{
452             .name = "tls-channel",
453             .type = QEMU_OPT_STRING,
454         },{
455             .name = "plaintext-channel",
456             .type = QEMU_OPT_STRING,
457         },{
458             .name = "image-compression",
459             .type = QEMU_OPT_STRING,
460         },{
461             .name = "jpeg-wan-compression",
462             .type = QEMU_OPT_STRING,
463         },{
464             .name = "zlib-glz-wan-compression",
465             .type = QEMU_OPT_STRING,
466         },{
467             .name = "streaming-video",
468             .type = QEMU_OPT_STRING,
469         },{
470             .name = "agent-mouse",
471             .type = QEMU_OPT_BOOL,
472         },{
473             .name = "playback-compression",
474             .type = QEMU_OPT_BOOL,
475         },{
476             .name = "seamless-migration",
477             .type = QEMU_OPT_BOOL,
478         },{
479             .name = "display",
480             .type = QEMU_OPT_STRING,
481         },{
482             .name = "head",
483             .type = QEMU_OPT_NUMBER,
484 #ifdef HAVE_SPICE_GL
485         },{
486             .name = "gl",
487             .type = QEMU_OPT_BOOL,
488         },{
489             .name = "rendernode",
490             .type = QEMU_OPT_STRING,
491 #endif
492         },
493         { /* end of list */ }
494     },
495 };
496 
497 static SpiceInfo *qmp_query_spice_real(Error **errp)
498 {
499     QemuOpts *opts = QTAILQ_FIRST(&qemu_spice_opts.head);
500     int port, tls_port;
501     const char *addr;
502     SpiceInfo *info;
503     unsigned int major;
504     unsigned int minor;
505     unsigned int micro;
506 
507     info = g_malloc0(sizeof(*info));
508 
509     if (!spice_server || !opts) {
510         info->enabled = false;
511         return info;
512     }
513 
514     info->enabled = true;
515     info->migrated = spice_migration_completed;
516 
517     addr = qemu_opt_get(opts, "addr");
518     port = qemu_opt_get_number(opts, "port", 0);
519     tls_port = qemu_opt_get_number(opts, "tls-port", 0);
520 
521     info->has_auth = true;
522     info->auth = g_strdup(auth);
523 
524     info->has_host = true;
525     info->host = g_strdup(addr ? addr : "*");
526 
527     info->has_compiled_version = true;
528     major = (SPICE_SERVER_VERSION & 0xff0000) >> 16;
529     minor = (SPICE_SERVER_VERSION & 0xff00) >> 8;
530     micro = SPICE_SERVER_VERSION & 0xff;
531     info->compiled_version = g_strdup_printf("%d.%d.%d", major, minor, micro);
532 
533     if (port) {
534         info->has_port = true;
535         info->port = port;
536     }
537     if (tls_port) {
538         info->has_tls_port = true;
539         info->tls_port = tls_port;
540     }
541 
542     info->mouse_mode = spice_server_is_server_mouse(spice_server) ?
543                        SPICE_QUERY_MOUSE_MODE_SERVER :
544                        SPICE_QUERY_MOUSE_MODE_CLIENT;
545 
546     /* for compatibility with the original command */
547     info->has_channels = true;
548     info->channels = qmp_query_spice_channels();
549 
550     return info;
551 }
552 
553 static void migration_state_notifier(Notifier *notifier, void *data)
554 {
555     MigrationState *s = data;
556 
557     if (!spice_have_target_host) {
558         return;
559     }
560 
561     if (migration_in_setup(s)) {
562         spice_server_migrate_start(spice_server);
563     } else if (migration_has_finished(s) ||
564                migration_in_postcopy_after_devices(s)) {
565         spice_server_migrate_end(spice_server, true);
566         spice_have_target_host = false;
567     } else if (migration_has_failed(s)) {
568         spice_server_migrate_end(spice_server, false);
569         spice_have_target_host = false;
570     }
571 }
572 
573 int qemu_spice_migrate_info(const char *hostname, int port, int tls_port,
574                             const char *subject)
575 {
576     int ret;
577 
578     ret = spice_server_migrate_connect(spice_server, hostname,
579                                        port, tls_port, subject);
580     spice_have_target_host = true;
581     return ret;
582 }
583 
584 static int add_channel(void *opaque, const char *name, const char *value,
585                        Error **errp)
586 {
587     int security = 0;
588     int rc;
589 
590     if (strcmp(name, "tls-channel") == 0) {
591         int *tls_port = opaque;
592         if (!*tls_port) {
593             error_setg(errp, "spice: tried to setup tls-channel"
594                        " without specifying a TLS port");
595             return -1;
596         }
597         security = SPICE_CHANNEL_SECURITY_SSL;
598     }
599     if (strcmp(name, "plaintext-channel") == 0) {
600         security = SPICE_CHANNEL_SECURITY_NONE;
601     }
602     if (security == 0) {
603         return 0;
604     }
605     if (strcmp(value, "default") == 0) {
606         rc = spice_server_set_channel_security(spice_server, NULL, security);
607     } else {
608         rc = spice_server_set_channel_security(spice_server, value, security);
609     }
610     if (rc != 0) {
611         error_setg(errp, "spice: failed to set channel security for %s",
612                    value);
613         return -1;
614     }
615     return 0;
616 }
617 
618 static void vm_change_state_handler(void *opaque, int running,
619                                     RunState state)
620 {
621     if (running) {
622         qemu_spice_display_start();
623     } else if (state != RUN_STATE_PAUSED) {
624         qemu_spice_display_stop();
625     }
626 }
627 
628 void qemu_spice_display_init_done(void)
629 {
630     if (runstate_is_running()) {
631         qemu_spice_display_start();
632     }
633     qemu_add_vm_change_state_handler(vm_change_state_handler, NULL);
634 }
635 
636 static void qemu_spice_init(void)
637 {
638     QemuOpts *opts = QTAILQ_FIRST(&qemu_spice_opts.head);
639     const char *password, *str, *x509_dir, *addr,
640         *x509_key_password = NULL,
641         *x509_dh_file = NULL,
642         *tls_ciphers = NULL;
643     char *x509_key_file = NULL,
644         *x509_cert_file = NULL,
645         *x509_cacert_file = NULL;
646     int port, tls_port, addr_flags;
647     spice_image_compression_t compression;
648     spice_wan_compression_t wan_compr;
649     bool seamless_migration;
650 
651     qemu_thread_get_self(&me);
652 
653     if (!opts) {
654         return;
655     }
656     port = qemu_opt_get_number(opts, "port", 0);
657     tls_port = qemu_opt_get_number(opts, "tls-port", 0);
658     if (port < 0 || port > 65535) {
659         error_report("spice port is out of range");
660         exit(1);
661     }
662     if (tls_port < 0 || tls_port > 65535) {
663         error_report("spice tls-port is out of range");
664         exit(1);
665     }
666     password = qemu_opt_get(opts, "password");
667 
668     if (tls_port) {
669         x509_dir = qemu_opt_get(opts, "x509-dir");
670         if (!x509_dir) {
671             x509_dir = ".";
672         }
673 
674         str = qemu_opt_get(opts, "x509-key-file");
675         if (str) {
676             x509_key_file = g_strdup(str);
677         } else {
678             x509_key_file = g_strdup_printf("%s/%s", x509_dir,
679                                             X509_SERVER_KEY_FILE);
680         }
681 
682         str = qemu_opt_get(opts, "x509-cert-file");
683         if (str) {
684             x509_cert_file = g_strdup(str);
685         } else {
686             x509_cert_file = g_strdup_printf("%s/%s", x509_dir,
687                                              X509_SERVER_CERT_FILE);
688         }
689 
690         str = qemu_opt_get(opts, "x509-cacert-file");
691         if (str) {
692             x509_cacert_file = g_strdup(str);
693         } else {
694             x509_cacert_file = g_strdup_printf("%s/%s", x509_dir,
695                                                X509_CA_CERT_FILE);
696         }
697 
698         x509_key_password = qemu_opt_get(opts, "x509-key-password");
699         x509_dh_file = qemu_opt_get(opts, "x509-dh-key-file");
700         tls_ciphers = qemu_opt_get(opts, "tls-ciphers");
701     }
702 
703     addr = qemu_opt_get(opts, "addr");
704     addr_flags = 0;
705     if (qemu_opt_get_bool(opts, "ipv4", 0)) {
706         addr_flags |= SPICE_ADDR_FLAG_IPV4_ONLY;
707     } else if (qemu_opt_get_bool(opts, "ipv6", 0)) {
708         addr_flags |= SPICE_ADDR_FLAG_IPV6_ONLY;
709 #ifdef SPICE_ADDR_FLAG_UNIX_ONLY
710     } else if (qemu_opt_get_bool(opts, "unix", 0)) {
711         addr_flags |= SPICE_ADDR_FLAG_UNIX_ONLY;
712 #endif
713     }
714 
715     spice_server = spice_server_new();
716     spice_server_set_addr(spice_server, addr ? addr : "", addr_flags);
717     if (port) {
718         spice_server_set_port(spice_server, port);
719     }
720     if (tls_port) {
721         spice_server_set_tls(spice_server, tls_port,
722                              x509_cacert_file,
723                              x509_cert_file,
724                              x509_key_file,
725                              x509_key_password,
726                              x509_dh_file,
727                              tls_ciphers);
728     }
729     if (password) {
730         qemu_spice.set_passwd(password, false, false);
731     }
732     if (qemu_opt_get_bool(opts, "sasl", 0)) {
733         if (spice_server_set_sasl(spice_server, 1) == -1) {
734             error_report("spice: failed to enable sasl");
735             exit(1);
736         }
737         auth = "sasl";
738     }
739     if (qemu_opt_get_bool(opts, "disable-ticketing", 0)) {
740         auth = "none";
741         spice_server_set_noauth(spice_server);
742     }
743 
744     if (qemu_opt_get_bool(opts, "disable-copy-paste", 0)) {
745         spice_server_set_agent_copypaste(spice_server, false);
746     }
747 
748     if (qemu_opt_get_bool(opts, "disable-agent-file-xfer", 0)) {
749         spice_server_set_agent_file_xfer(spice_server, false);
750     }
751 
752     compression = SPICE_IMAGE_COMPRESS_AUTO_GLZ;
753     str = qemu_opt_get(opts, "image-compression");
754     if (str) {
755         compression = parse_compression(str);
756     }
757     spice_server_set_image_compression(spice_server, compression);
758 
759     wan_compr = SPICE_WAN_COMPRESSION_AUTO;
760     str = qemu_opt_get(opts, "jpeg-wan-compression");
761     if (str) {
762         wan_compr = parse_wan_compression(str);
763     }
764     spice_server_set_jpeg_compression(spice_server, wan_compr);
765 
766     wan_compr = SPICE_WAN_COMPRESSION_AUTO;
767     str = qemu_opt_get(opts, "zlib-glz-wan-compression");
768     if (str) {
769         wan_compr = parse_wan_compression(str);
770     }
771     spice_server_set_zlib_glz_compression(spice_server, wan_compr);
772 
773     str = qemu_opt_get(opts, "streaming-video");
774     if (str) {
775         int streaming_video = parse_stream_video(str);
776         spice_server_set_streaming_video(spice_server, streaming_video);
777     } else {
778         spice_server_set_streaming_video(spice_server, SPICE_STREAM_VIDEO_OFF);
779     }
780 
781     spice_server_set_agent_mouse
782         (spice_server, qemu_opt_get_bool(opts, "agent-mouse", 1));
783     spice_server_set_playback_compression
784         (spice_server, qemu_opt_get_bool(opts, "playback-compression", 1));
785 
786     qemu_opt_foreach(opts, add_channel, &tls_port, &error_fatal);
787 
788     spice_server_set_name(spice_server, qemu_name ?: "QEMU " QEMU_VERSION);
789     spice_server_set_uuid(spice_server, (unsigned char *)&qemu_uuid);
790 
791     seamless_migration = qemu_opt_get_bool(opts, "seamless-migration", 0);
792     spice_server_set_seamless_migration(spice_server, seamless_migration);
793     spice_server_set_sasl_appname(spice_server, "qemu");
794     if (spice_server_init(spice_server, &core_interface) != 0) {
795         error_report("failed to initialize spice server");
796         exit(1);
797     };
798     using_spice = 1;
799 
800     migration_state.notify = migration_state_notifier;
801     add_migration_state_change_notifier(&migration_state);
802     spice_migrate.base.sif = &migrate_interface.base;
803     qemu_spice.add_interface(&spice_migrate.base);
804 
805     qemu_spice_input_init();
806 
807     qemu_spice_display_stop();
808 
809     g_free(x509_key_file);
810     g_free(x509_cert_file);
811     g_free(x509_cacert_file);
812 
813 #ifdef HAVE_SPICE_GL
814     if (qemu_opt_get_bool(opts, "gl", 0)) {
815         if ((port != 0) || (tls_port != 0)) {
816             error_report("SPICE GL support is local-only for now and "
817                          "incompatible with -spice port/tls-port");
818             exit(1);
819         }
820         if (egl_rendernode_init(qemu_opt_get(opts, "rendernode"),
821                                 DISPLAYGL_MODE_ON) != 0) {
822             error_report("Failed to initialize EGL render node for SPICE GL");
823             exit(1);
824         }
825         display_opengl = 1;
826         spice_opengl = 1;
827     }
828 #endif
829 }
830 
831 static int qemu_spice_add_interface(SpiceBaseInstance *sin)
832 {
833     if (!spice_server) {
834         if (QTAILQ_FIRST(&qemu_spice_opts.head) != NULL) {
835             error_report("Oops: spice configured but not active");
836             exit(1);
837         }
838         /*
839          * Create a spice server instance.
840          * It does *not* listen on the network.
841          * It handles QXL local rendering only.
842          *
843          * With a command line like '-vnc :0 -vga qxl' you'll end up here.
844          */
845         spice_server = spice_server_new();
846         spice_server_set_sasl_appname(spice_server, "qemu");
847         spice_server_init(spice_server, &core_interface);
848         qemu_add_vm_change_state_handler(vm_change_state_handler, NULL);
849     }
850 
851     return spice_server_add_interface(spice_server, sin);
852 }
853 
854 static GSList *spice_consoles;
855 
856 bool qemu_spice_have_display_interface(QemuConsole *con)
857 {
858     if (g_slist_find(spice_consoles, con)) {
859         return true;
860     }
861     return false;
862 }
863 
864 /*
865  * Recursively (in reverse order) appends addresses of PCI devices as it moves
866  * up in the PCI hierarchy.
867  *
868  * @returns true on success, false when the buffer wasn't large enough
869  */
870 static bool append_pci_address(char *buf, size_t buf_size, const PCIDevice *pci)
871 {
872     PCIBus *bus = pci_get_bus(pci);
873     /*
874      * equivalent to if (!pci_bus_is_root(bus)), but the function is not built
875      * with PCI_CONFIG=n, avoid using an #ifdef by checking directly
876      */
877     if (bus->parent_dev != NULL) {
878         append_pci_address(buf, buf_size, bus->parent_dev);
879     }
880 
881     size_t len = strlen(buf);
882     ssize_t written = snprintf(buf + len, buf_size - len, "/%02x.%x",
883         PCI_SLOT(pci->devfn), PCI_FUNC(pci->devfn));
884 
885     return written > 0 && written < buf_size - len;
886 }
887 
888 bool qemu_spice_fill_device_address(QemuConsole *con,
889                                     char *device_address,
890                                     size_t size)
891 {
892     DeviceState *dev = DEVICE(object_property_get_link(OBJECT(con),
893                                                        "device",
894                                                        &error_abort));
895     PCIDevice *pci = (PCIDevice *) object_dynamic_cast(OBJECT(dev),
896                                                        TYPE_PCI_DEVICE);
897 
898     if (pci == NULL) {
899         warn_report("Setting device address of a display device to SPICE: "
900                     "Not a PCI device.");
901         return false;
902     }
903 
904     strncpy(device_address, "pci/0000", size);
905     if (!append_pci_address(device_address, size, pci)) {
906         warn_report("Setting device address of a display device to SPICE: "
907             "Too many PCI devices in the chain.");
908         return false;
909     }
910 
911     return true;
912 }
913 
914 int qemu_spice_add_display_interface(QXLInstance *qxlin, QemuConsole *con)
915 {
916     if (g_slist_find(spice_consoles, con)) {
917         return -1;
918     }
919     qxlin->id = qemu_console_get_index(con);
920     spice_consoles = g_slist_append(spice_consoles, con);
921     return qemu_spice_add_interface(&qxlin->base);
922 }
923 
924 static int qemu_spice_set_ticket(bool fail_if_conn, bool disconnect_if_conn)
925 {
926     time_t lifetime, now = time(NULL);
927     char *passwd;
928 
929     if (now < auth_expires) {
930         passwd = auth_passwd;
931         lifetime = (auth_expires - now);
932         if (lifetime > INT_MAX) {
933             lifetime = INT_MAX;
934         }
935     } else {
936         passwd = NULL;
937         lifetime = 1;
938     }
939     return spice_server_set_ticket(spice_server, passwd, lifetime,
940                                    fail_if_conn, disconnect_if_conn);
941 }
942 
943 static int qemu_spice_set_passwd(const char *passwd,
944                                  bool fail_if_conn, bool disconnect_if_conn)
945 {
946     if (strcmp(auth, "spice") != 0) {
947         return -1;
948     }
949 
950     g_free(auth_passwd);
951     auth_passwd = g_strdup(passwd);
952     return qemu_spice_set_ticket(fail_if_conn, disconnect_if_conn);
953 }
954 
955 static int qemu_spice_set_pw_expire(time_t expires)
956 {
957     auth_expires = expires;
958     return qemu_spice_set_ticket(false, false);
959 }
960 
961 static int qemu_spice_display_add_client(int csock, int skipauth, int tls)
962 {
963     if (tls) {
964         return spice_server_add_ssl_client(spice_server, csock, skipauth);
965     } else {
966         return spice_server_add_client(spice_server, csock, skipauth);
967     }
968 }
969 
970 void qemu_spice_display_start(void)
971 {
972     if (spice_display_is_running) {
973         return;
974     }
975 
976     spice_display_is_running = true;
977     spice_server_vm_start(spice_server);
978 }
979 
980 void qemu_spice_display_stop(void)
981 {
982     if (!spice_display_is_running) {
983         return;
984     }
985 
986     spice_server_vm_stop(spice_server);
987     spice_display_is_running = false;
988 }
989 
990 int qemu_spice_display_is_running(SimpleSpiceDisplay *ssd)
991 {
992     return spice_display_is_running;
993 }
994 
995 static struct QemuSpiceOps real_spice_ops = {
996     .init         = qemu_spice_init,
997     .display_init = qemu_spice_display_init,
998     .migrate_info = qemu_spice_migrate_info,
999     .set_passwd   = qemu_spice_set_passwd,
1000     .set_pw_expire = qemu_spice_set_pw_expire,
1001     .display_add_client = qemu_spice_display_add_client,
1002     .add_interface = qemu_spice_add_interface,
1003     .qmp_query = qmp_query_spice_real,
1004 };
1005 
1006 static void spice_register_config(void)
1007 {
1008     qemu_spice = real_spice_ops;
1009     qemu_add_opts(&qemu_spice_opts);
1010 }
1011 opts_init(spice_register_config);
1012