xref: /openbmc/qemu/ui/spice-core.c (revision 1cf9412b)
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 <spice.h>
19 #include <spice-experimental.h>
20 
21 #include <netdb.h>
22 #include "sysemu/sysemu.h"
23 
24 #include "qemu-common.h"
25 #include "ui/qemu-spice.h"
26 #include "qemu/thread.h"
27 #include "qemu/timer.h"
28 #include "qemu/queue.h"
29 #include "qemu-x509.h"
30 #include "qemu/sockets.h"
31 #include "qmp-commands.h"
32 #include "qapi/qmp/qint.h"
33 #include "qapi/qmp/qbool.h"
34 #include "qapi/qmp/qstring.h"
35 #include "qapi/qmp/qjson.h"
36 #include "qemu/notify.h"
37 #include "migration/migration.h"
38 #include "monitor/monitor.h"
39 #include "hw/hw.h"
40 #include "ui/spice-display.h"
41 
42 /* core bits */
43 
44 static SpiceServer *spice_server;
45 static Notifier migration_state;
46 static const char *auth = "spice";
47 static char *auth_passwd;
48 static time_t auth_expires = TIME_MAX;
49 static int spice_migration_completed;
50 int using_spice = 0;
51 int spice_displays;
52 
53 static QemuThread me;
54 
55 struct SpiceTimer {
56     QEMUTimer *timer;
57     QTAILQ_ENTRY(SpiceTimer) next;
58 };
59 static QTAILQ_HEAD(, SpiceTimer) timers = QTAILQ_HEAD_INITIALIZER(timers);
60 
61 static SpiceTimer *timer_add(SpiceTimerFunc func, void *opaque)
62 {
63     SpiceTimer *timer;
64 
65     timer = g_malloc0(sizeof(*timer));
66     timer->timer = timer_new_ms(QEMU_CLOCK_REALTIME, func, opaque);
67     QTAILQ_INSERT_TAIL(&timers, timer, next);
68     return timer;
69 }
70 
71 static void timer_start(SpiceTimer *timer, uint32_t ms)
72 {
73     timer_mod(timer->timer, qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + ms);
74 }
75 
76 static void timer_cancel(SpiceTimer *timer)
77 {
78     timer_del(timer->timer);
79 }
80 
81 static void timer_remove(SpiceTimer *timer)
82 {
83     timer_del(timer->timer);
84     timer_free(timer->timer);
85     QTAILQ_REMOVE(&timers, timer, next);
86     g_free(timer);
87 }
88 
89 struct SpiceWatch {
90     int fd;
91     int event_mask;
92     SpiceWatchFunc func;
93     void *opaque;
94     QTAILQ_ENTRY(SpiceWatch) next;
95 };
96 static QTAILQ_HEAD(, SpiceWatch) watches = QTAILQ_HEAD_INITIALIZER(watches);
97 
98 static void watch_read(void *opaque)
99 {
100     SpiceWatch *watch = opaque;
101     watch->func(watch->fd, SPICE_WATCH_EVENT_READ, watch->opaque);
102 }
103 
104 static void watch_write(void *opaque)
105 {
106     SpiceWatch *watch = opaque;
107     watch->func(watch->fd, SPICE_WATCH_EVENT_WRITE, watch->opaque);
108 }
109 
110 static void watch_update_mask(SpiceWatch *watch, int event_mask)
111 {
112     IOHandler *on_read = NULL;
113     IOHandler *on_write = NULL;
114 
115     watch->event_mask = event_mask;
116     if (watch->event_mask & SPICE_WATCH_EVENT_READ) {
117         on_read = watch_read;
118     }
119     if (watch->event_mask & SPICE_WATCH_EVENT_WRITE) {
120         on_write = watch_write;
121     }
122     qemu_set_fd_handler(watch->fd, on_read, on_write, watch);
123 }
124 
125 static SpiceWatch *watch_add(int fd, int event_mask, SpiceWatchFunc func, void *opaque)
126 {
127     SpiceWatch *watch;
128 
129     watch = g_malloc0(sizeof(*watch));
130     watch->fd     = fd;
131     watch->func   = func;
132     watch->opaque = opaque;
133     QTAILQ_INSERT_TAIL(&watches, watch, next);
134 
135     watch_update_mask(watch, event_mask);
136     return watch;
137 }
138 
139 static void watch_remove(SpiceWatch *watch)
140 {
141     qemu_set_fd_handler(watch->fd, NULL, NULL, NULL);
142     QTAILQ_REMOVE(&watches, watch, next);
143     g_free(watch);
144 }
145 
146 typedef struct ChannelList ChannelList;
147 struct ChannelList {
148     SpiceChannelEventInfo *info;
149     QTAILQ_ENTRY(ChannelList) link;
150 };
151 static QTAILQ_HEAD(, ChannelList) channel_list = QTAILQ_HEAD_INITIALIZER(channel_list);
152 
153 static void channel_list_add(SpiceChannelEventInfo *info)
154 {
155     ChannelList *item;
156 
157     item = g_malloc0(sizeof(*item));
158     item->info = info;
159     QTAILQ_INSERT_TAIL(&channel_list, item, link);
160 }
161 
162 static void channel_list_del(SpiceChannelEventInfo *info)
163 {
164     ChannelList *item;
165 
166     QTAILQ_FOREACH(item, &channel_list, link) {
167         if (item->info != info) {
168             continue;
169         }
170         QTAILQ_REMOVE(&channel_list, item, link);
171         g_free(item);
172         return;
173     }
174 }
175 
176 static void add_addr_info(QDict *dict, struct sockaddr *addr, int len)
177 {
178     char host[NI_MAXHOST], port[NI_MAXSERV];
179     const char *family;
180 
181     getnameinfo(addr, len, host, sizeof(host), port, sizeof(port),
182                 NI_NUMERICHOST | NI_NUMERICSERV);
183     family = inet_strfamily(addr->sa_family);
184 
185     qdict_put(dict, "host", qstring_from_str(host));
186     qdict_put(dict, "port", qstring_from_str(port));
187     qdict_put(dict, "family", qstring_from_str(family));
188 }
189 
190 static void add_channel_info(QDict *dict, SpiceChannelEventInfo *info)
191 {
192     int tls = info->flags & SPICE_CHANNEL_EVENT_FLAG_TLS;
193 
194     qdict_put(dict, "connection-id", qint_from_int(info->connection_id));
195     qdict_put(dict, "channel-type", qint_from_int(info->type));
196     qdict_put(dict, "channel-id", qint_from_int(info->id));
197     qdict_put(dict, "tls", qbool_from_int(tls));
198 }
199 
200 static void channel_event(int event, SpiceChannelEventInfo *info)
201 {
202     static const int qevent[] = {
203         [ SPICE_CHANNEL_EVENT_CONNECTED    ] = QEVENT_SPICE_CONNECTED,
204         [ SPICE_CHANNEL_EVENT_INITIALIZED  ] = QEVENT_SPICE_INITIALIZED,
205         [ SPICE_CHANNEL_EVENT_DISCONNECTED ] = QEVENT_SPICE_DISCONNECTED,
206     };
207     QDict *server, *client;
208     QObject *data;
209 
210     /*
211      * Spice server might have called us from spice worker thread
212      * context (happens on display channel disconnects).  Spice should
213      * not do that.  It isn't that easy to fix it in spice and even
214      * when it is fixed we still should cover the already released
215      * spice versions.  So detect that we've been called from another
216      * thread and grab the iothread lock if so before calling qemu
217      * functions.
218      */
219     bool need_lock = !qemu_thread_is_self(&me);
220     if (need_lock) {
221         qemu_mutex_lock_iothread();
222     }
223 
224     client = qdict_new();
225     server = qdict_new();
226 
227     if (info->flags & SPICE_CHANNEL_EVENT_FLAG_ADDR_EXT) {
228         add_addr_info(client, (struct sockaddr *)&info->paddr_ext,
229                       info->plen_ext);
230         add_addr_info(server, (struct sockaddr *)&info->laddr_ext,
231                       info->llen_ext);
232     } else {
233         error_report("spice: %s, extended address is expected",
234                      __func__);
235     }
236 
237     if (event == SPICE_CHANNEL_EVENT_INITIALIZED) {
238         qdict_put(server, "auth", qstring_from_str(auth));
239         add_channel_info(client, info);
240         channel_list_add(info);
241     }
242     if (event == SPICE_CHANNEL_EVENT_DISCONNECTED) {
243         channel_list_del(info);
244     }
245 
246     data = qobject_from_jsonf("{ 'client': %p, 'server': %p }",
247                               QOBJECT(client), QOBJECT(server));
248     monitor_protocol_event(qevent[event], data);
249     qobject_decref(data);
250 
251     if (need_lock) {
252         qemu_mutex_unlock_iothread();
253     }
254 }
255 
256 static SpiceCoreInterface core_interface = {
257     .base.type          = SPICE_INTERFACE_CORE,
258     .base.description   = "qemu core services",
259     .base.major_version = SPICE_INTERFACE_CORE_MAJOR,
260     .base.minor_version = SPICE_INTERFACE_CORE_MINOR,
261 
262     .timer_add          = timer_add,
263     .timer_start        = timer_start,
264     .timer_cancel       = timer_cancel,
265     .timer_remove       = timer_remove,
266 
267     .watch_add          = watch_add,
268     .watch_update_mask  = watch_update_mask,
269     .watch_remove       = watch_remove,
270 
271     .channel_event      = channel_event,
272 };
273 
274 typedef struct SpiceMigration {
275     SpiceMigrateInstance sin;
276     struct {
277         MonitorCompletion *cb;
278         void *opaque;
279     } connect_complete;
280 } SpiceMigration;
281 
282 static void migrate_connect_complete_cb(SpiceMigrateInstance *sin);
283 static void migrate_end_complete_cb(SpiceMigrateInstance *sin);
284 
285 static const SpiceMigrateInterface migrate_interface = {
286     .base.type = SPICE_INTERFACE_MIGRATION,
287     .base.description = "migration",
288     .base.major_version = SPICE_INTERFACE_MIGRATION_MAJOR,
289     .base.minor_version = SPICE_INTERFACE_MIGRATION_MINOR,
290     .migrate_connect_complete = migrate_connect_complete_cb,
291     .migrate_end_complete = migrate_end_complete_cb,
292 };
293 
294 static SpiceMigration spice_migrate;
295 
296 static void migrate_connect_complete_cb(SpiceMigrateInstance *sin)
297 {
298     SpiceMigration *sm = container_of(sin, SpiceMigration, sin);
299     if (sm->connect_complete.cb) {
300         sm->connect_complete.cb(sm->connect_complete.opaque, NULL);
301     }
302     sm->connect_complete.cb = NULL;
303 }
304 
305 static void migrate_end_complete_cb(SpiceMigrateInstance *sin)
306 {
307     monitor_protocol_event(QEVENT_SPICE_MIGRATE_COMPLETED, NULL);
308     spice_migration_completed = true;
309 }
310 
311 /* config string parsing */
312 
313 static int name2enum(const char *string, const char *table[], int entries)
314 {
315     int i;
316 
317     if (string) {
318         for (i = 0; i < entries; i++) {
319             if (!table[i]) {
320                 continue;
321             }
322             if (strcmp(string, table[i]) != 0) {
323                 continue;
324             }
325             return i;
326         }
327     }
328     return -1;
329 }
330 
331 static int parse_name(const char *string, const char *optname,
332                       const char *table[], int entries)
333 {
334     int value = name2enum(string, table, entries);
335 
336     if (value != -1) {
337         return value;
338     }
339     error_report("spice: invalid %s: %s", optname, string);
340     exit(1);
341 }
342 
343 static const char *stream_video_names[] = {
344     [ SPICE_STREAM_VIDEO_OFF ]    = "off",
345     [ SPICE_STREAM_VIDEO_ALL ]    = "all",
346     [ SPICE_STREAM_VIDEO_FILTER ] = "filter",
347 };
348 #define parse_stream_video(_name) \
349     parse_name(_name, "stream video control", \
350                stream_video_names, ARRAY_SIZE(stream_video_names))
351 
352 static const char *compression_names[] = {
353     [ SPICE_IMAGE_COMPRESS_OFF ]      = "off",
354     [ SPICE_IMAGE_COMPRESS_AUTO_GLZ ] = "auto_glz",
355     [ SPICE_IMAGE_COMPRESS_AUTO_LZ ]  = "auto_lz",
356     [ SPICE_IMAGE_COMPRESS_QUIC ]     = "quic",
357     [ SPICE_IMAGE_COMPRESS_GLZ ]      = "glz",
358     [ SPICE_IMAGE_COMPRESS_LZ ]       = "lz",
359 };
360 #define parse_compression(_name)                                        \
361     parse_name(_name, "image compression",                              \
362                compression_names, ARRAY_SIZE(compression_names))
363 
364 static const char *wan_compression_names[] = {
365     [ SPICE_WAN_COMPRESSION_AUTO   ] = "auto",
366     [ SPICE_WAN_COMPRESSION_NEVER  ] = "never",
367     [ SPICE_WAN_COMPRESSION_ALWAYS ] = "always",
368 };
369 #define parse_wan_compression(_name)                                    \
370     parse_name(_name, "wan compression",                                \
371                wan_compression_names, ARRAY_SIZE(wan_compression_names))
372 
373 /* functions for the rest of qemu */
374 
375 static SpiceChannelList *qmp_query_spice_channels(void)
376 {
377     SpiceChannelList *cur_item = NULL, *head = NULL;
378     ChannelList *item;
379 
380     QTAILQ_FOREACH(item, &channel_list, link) {
381         SpiceChannelList *chan;
382         char host[NI_MAXHOST], port[NI_MAXSERV];
383         struct sockaddr *paddr;
384         socklen_t plen;
385 
386         chan = g_malloc0(sizeof(*chan));
387         chan->value = g_malloc0(sizeof(*chan->value));
388 
389         if (item->info->flags & SPICE_CHANNEL_EVENT_FLAG_ADDR_EXT) {
390             paddr = (struct sockaddr *)&item->info->paddr_ext;
391             plen = item->info->plen_ext;
392         } else {
393             paddr = &item->info->paddr;
394             plen = item->info->plen;
395         }
396 
397         getnameinfo(paddr, plen,
398                     host, sizeof(host), port, sizeof(port),
399                     NI_NUMERICHOST | NI_NUMERICSERV);
400         chan->value->host = g_strdup(host);
401         chan->value->port = g_strdup(port);
402         chan->value->family = g_strdup(inet_strfamily(paddr->sa_family));
403 
404         chan->value->connection_id = item->info->connection_id;
405         chan->value->channel_type = item->info->type;
406         chan->value->channel_id = item->info->id;
407         chan->value->tls = item->info->flags & SPICE_CHANNEL_EVENT_FLAG_TLS;
408 
409        /* XXX: waiting for the qapi to support GSList */
410         if (!cur_item) {
411             head = cur_item = chan;
412         } else {
413             cur_item->next = chan;
414             cur_item = chan;
415         }
416     }
417 
418     return head;
419 }
420 
421 static QemuOptsList qemu_spice_opts = {
422     .name = "spice",
423     .head = QTAILQ_HEAD_INITIALIZER(qemu_spice_opts.head),
424     .desc = {
425         {
426             .name = "port",
427             .type = QEMU_OPT_NUMBER,
428         },{
429             .name = "tls-port",
430             .type = QEMU_OPT_NUMBER,
431         },{
432             .name = "addr",
433             .type = QEMU_OPT_STRING,
434         },{
435             .name = "ipv4",
436             .type = QEMU_OPT_BOOL,
437         },{
438             .name = "ipv6",
439             .type = QEMU_OPT_BOOL,
440         },{
441             .name = "password",
442             .type = QEMU_OPT_STRING,
443         },{
444             .name = "disable-ticketing",
445             .type = QEMU_OPT_BOOL,
446         },{
447             .name = "disable-copy-paste",
448             .type = QEMU_OPT_BOOL,
449         },{
450             .name = "disable-agent-file-xfer",
451             .type = QEMU_OPT_BOOL,
452         },{
453             .name = "sasl",
454             .type = QEMU_OPT_BOOL,
455         },{
456             .name = "x509-dir",
457             .type = QEMU_OPT_STRING,
458         },{
459             .name = "x509-key-file",
460             .type = QEMU_OPT_STRING,
461         },{
462             .name = "x509-key-password",
463             .type = QEMU_OPT_STRING,
464         },{
465             .name = "x509-cert-file",
466             .type = QEMU_OPT_STRING,
467         },{
468             .name = "x509-cacert-file",
469             .type = QEMU_OPT_STRING,
470         },{
471             .name = "x509-dh-key-file",
472             .type = QEMU_OPT_STRING,
473         },{
474             .name = "tls-ciphers",
475             .type = QEMU_OPT_STRING,
476         },{
477             .name = "tls-channel",
478             .type = QEMU_OPT_STRING,
479         },{
480             .name = "plaintext-channel",
481             .type = QEMU_OPT_STRING,
482         },{
483             .name = "image-compression",
484             .type = QEMU_OPT_STRING,
485         },{
486             .name = "jpeg-wan-compression",
487             .type = QEMU_OPT_STRING,
488         },{
489             .name = "zlib-glz-wan-compression",
490             .type = QEMU_OPT_STRING,
491         },{
492             .name = "streaming-video",
493             .type = QEMU_OPT_STRING,
494         },{
495             .name = "agent-mouse",
496             .type = QEMU_OPT_BOOL,
497         },{
498             .name = "playback-compression",
499             .type = QEMU_OPT_BOOL,
500         }, {
501             .name = "seamless-migration",
502             .type = QEMU_OPT_BOOL,
503         },
504         { /* end of list */ }
505     },
506 };
507 
508 SpiceInfo *qmp_query_spice(Error **errp)
509 {
510     QemuOpts *opts = QTAILQ_FIRST(&qemu_spice_opts.head);
511     int port, tls_port;
512     const char *addr;
513     SpiceInfo *info;
514     unsigned int major;
515     unsigned int minor;
516     unsigned int micro;
517 
518     info = g_malloc0(sizeof(*info));
519 
520     if (!spice_server || !opts) {
521         info->enabled = false;
522         return info;
523     }
524 
525     info->enabled = true;
526     info->migrated = spice_migration_completed;
527 
528     addr = qemu_opt_get(opts, "addr");
529     port = qemu_opt_get_number(opts, "port", 0);
530     tls_port = qemu_opt_get_number(opts, "tls-port", 0);
531 
532     info->has_auth = true;
533     info->auth = g_strdup(auth);
534 
535     info->has_host = true;
536     info->host = g_strdup(addr ? addr : "0.0.0.0");
537 
538     info->has_compiled_version = true;
539     major = (SPICE_SERVER_VERSION & 0xff0000) >> 16;
540     minor = (SPICE_SERVER_VERSION & 0xff00) >> 8;
541     micro = SPICE_SERVER_VERSION & 0xff;
542     info->compiled_version = g_strdup_printf("%d.%d.%d", major, minor, micro);
543 
544     if (port) {
545         info->has_port = true;
546         info->port = port;
547     }
548     if (tls_port) {
549         info->has_tls_port = true;
550         info->tls_port = tls_port;
551     }
552 
553     info->mouse_mode = spice_server_is_server_mouse(spice_server) ?
554                        SPICE_QUERY_MOUSE_MODE_SERVER :
555                        SPICE_QUERY_MOUSE_MODE_CLIENT;
556 
557     /* for compatibility with the original command */
558     info->has_channels = true;
559     info->channels = qmp_query_spice_channels();
560 
561     return info;
562 }
563 
564 static void migration_state_notifier(Notifier *notifier, void *data)
565 {
566     MigrationState *s = data;
567 
568     if (migration_in_setup(s)) {
569         spice_server_migrate_start(spice_server);
570     } else if (migration_has_finished(s)) {
571         spice_server_migrate_end(spice_server, true);
572     } else if (migration_has_failed(s)) {
573         spice_server_migrate_end(spice_server, false);
574     }
575 }
576 
577 int qemu_spice_migrate_info(const char *hostname, int port, int tls_port,
578                             const char *subject,
579                             MonitorCompletion *cb, void *opaque)
580 {
581     int ret;
582 
583     spice_migrate.connect_complete.cb = cb;
584     spice_migrate.connect_complete.opaque = opaque;
585     ret = spice_server_migrate_connect(spice_server, hostname,
586                                        port, tls_port, subject);
587     return ret;
588 }
589 
590 static int add_channel(const char *name, const char *value, void *opaque)
591 {
592     int security = 0;
593     int rc;
594 
595     if (strcmp(name, "tls-channel") == 0) {
596         int *tls_port = opaque;
597         if (!*tls_port) {
598             error_report("spice: tried to setup tls-channel"
599                          " without specifying a TLS port");
600             exit(1);
601         }
602         security = SPICE_CHANNEL_SECURITY_SSL;
603     }
604     if (strcmp(name, "plaintext-channel") == 0) {
605         security = SPICE_CHANNEL_SECURITY_NONE;
606     }
607     if (security == 0) {
608         return 0;
609     }
610     if (strcmp(value, "default") == 0) {
611         rc = spice_server_set_channel_security(spice_server, NULL, security);
612     } else {
613         rc = spice_server_set_channel_security(spice_server, value, security);
614     }
615     if (rc != 0) {
616         error_report("spice: failed to set channel security for %s", value);
617         exit(1);
618     }
619     return 0;
620 }
621 
622 static void vm_change_state_handler(void *opaque, int running,
623                                     RunState state)
624 {
625     if (running) {
626         qemu_spice_display_start();
627         spice_server_vm_start(spice_server);
628     } else {
629         spice_server_vm_stop(spice_server);
630         qemu_spice_display_stop();
631     }
632 }
633 
634 void qemu_spice_init(void)
635 {
636     QemuOpts *opts = QTAILQ_FIRST(&qemu_spice_opts.head);
637     const char *password, *str, *x509_dir, *addr,
638         *x509_key_password = NULL,
639         *x509_dh_file = NULL,
640         *tls_ciphers = NULL;
641     char *x509_key_file = NULL,
642         *x509_cert_file = NULL,
643         *x509_cacert_file = NULL;
644     int port, tls_port, addr_flags;
645     spice_image_compression_t compression;
646     spice_wan_compression_t wan_compr;
647     bool seamless_migration;
648 
649     qemu_thread_get_self(&me);
650 
651     if (!opts) {
652         return;
653     }
654     port = qemu_opt_get_number(opts, "port", 0);
655     tls_port = qemu_opt_get_number(opts, "tls-port", 0);
656     if (!port && !tls_port) {
657         error_report("neither port nor tls-port specified for spice");
658         exit(1);
659     }
660     if (port < 0 || port > 65535) {
661         error_report("spice port is out of range");
662         exit(1);
663     }
664     if (tls_port < 0 || tls_port > 65535) {
665         error_report("spice tls-port is out of range");
666         exit(1);
667     }
668     password = qemu_opt_get(opts, "password");
669 
670     if (tls_port) {
671         x509_dir = qemu_opt_get(opts, "x509-dir");
672         if (NULL == x509_dir) {
673             x509_dir = ".";
674         }
675 
676         str = qemu_opt_get(opts, "x509-key-file");
677         if (str) {
678             x509_key_file = g_strdup(str);
679         } else {
680             x509_key_file = g_strdup_printf("%s/%s", x509_dir,
681                                             X509_SERVER_KEY_FILE);
682         }
683 
684         str = qemu_opt_get(opts, "x509-cert-file");
685         if (str) {
686             x509_cert_file = g_strdup(str);
687         } else {
688             x509_cert_file = g_strdup_printf("%s/%s", x509_dir,
689                                              X509_SERVER_CERT_FILE);
690         }
691 
692         str = qemu_opt_get(opts, "x509-cacert-file");
693         if (str) {
694             x509_cacert_file = g_strdup(str);
695         } else {
696             x509_cacert_file = g_strdup_printf("%s/%s", x509_dir,
697                                                X509_CA_CERT_FILE);
698         }
699 
700         x509_key_password = qemu_opt_get(opts, "x509-key-password");
701         x509_dh_file = qemu_opt_get(opts, "x509-dh-key-file");
702         tls_ciphers = qemu_opt_get(opts, "tls-ciphers");
703     }
704 
705     addr = qemu_opt_get(opts, "addr");
706     addr_flags = 0;
707     if (qemu_opt_get_bool(opts, "ipv4", 0)) {
708         addr_flags |= SPICE_ADDR_FLAG_IPV4_ONLY;
709     } else if (qemu_opt_get_bool(opts, "ipv6", 0)) {
710         addr_flags |= SPICE_ADDR_FLAG_IPV6_ONLY;
711     }
712 
713     spice_server = spice_server_new();
714     spice_server_set_addr(spice_server, addr ? addr : "", addr_flags);
715     if (port) {
716         spice_server_set_port(spice_server, port);
717     }
718     if (tls_port) {
719         spice_server_set_tls(spice_server, tls_port,
720                              x509_cacert_file,
721                              x509_cert_file,
722                              x509_key_file,
723                              x509_key_password,
724                              x509_dh_file,
725                              tls_ciphers);
726     }
727     if (password) {
728         spice_server_set_ticket(spice_server, password, 0, 0, 0);
729     }
730     if (qemu_opt_get_bool(opts, "sasl", 0)) {
731         if (spice_server_set_sasl_appname(spice_server, "qemu") == -1 ||
732             spice_server_set_sasl(spice_server, 1) == -1) {
733             error_report("spice: failed to enable sasl");
734             exit(1);
735         }
736     }
737     if (qemu_opt_get_bool(opts, "disable-ticketing", 0)) {
738         auth = "none";
739         spice_server_set_noauth(spice_server);
740     }
741 
742     if (qemu_opt_get_bool(opts, "disable-copy-paste", 0)) {
743         spice_server_set_agent_copypaste(spice_server, false);
744     }
745 
746     if (qemu_opt_get_bool(opts, "disable-agent-file-xfer", 0)) {
747 #if SPICE_SERVER_VERSION >= 0x000c04
748         spice_server_set_agent_file_xfer(spice_server, false);
749 #else
750         error_report("this qemu build does not support the "
751                      "\"disable-agent-file-xfer\" option");
752         exit(1);
753 #endif
754     }
755 
756     compression = SPICE_IMAGE_COMPRESS_AUTO_GLZ;
757     str = qemu_opt_get(opts, "image-compression");
758     if (str) {
759         compression = parse_compression(str);
760     }
761     spice_server_set_image_compression(spice_server, compression);
762 
763     wan_compr = SPICE_WAN_COMPRESSION_AUTO;
764     str = qemu_opt_get(opts, "jpeg-wan-compression");
765     if (str) {
766         wan_compr = parse_wan_compression(str);
767     }
768     spice_server_set_jpeg_compression(spice_server, wan_compr);
769 
770     wan_compr = SPICE_WAN_COMPRESSION_AUTO;
771     str = qemu_opt_get(opts, "zlib-glz-wan-compression");
772     if (str) {
773         wan_compr = parse_wan_compression(str);
774     }
775     spice_server_set_zlib_glz_compression(spice_server, wan_compr);
776 
777     str = qemu_opt_get(opts, "streaming-video");
778     if (str) {
779         int streaming_video = parse_stream_video(str);
780         spice_server_set_streaming_video(spice_server, streaming_video);
781     }
782 
783     spice_server_set_agent_mouse
784         (spice_server, qemu_opt_get_bool(opts, "agent-mouse", 1));
785     spice_server_set_playback_compression
786         (spice_server, qemu_opt_get_bool(opts, "playback-compression", 1));
787 
788     qemu_opt_foreach(opts, add_channel, &tls_port, 0);
789 
790     spice_server_set_name(spice_server, qemu_name);
791     spice_server_set_uuid(spice_server, qemu_uuid);
792 
793     seamless_migration = qemu_opt_get_bool(opts, "seamless-migration", 0);
794     spice_server_set_seamless_migration(spice_server, seamless_migration);
795     if (0 != spice_server_init(spice_server, &core_interface)) {
796         error_report("failed to initialize spice server");
797         exit(1);
798     };
799     using_spice = 1;
800 
801     migration_state.notify = migration_state_notifier;
802     add_migration_state_change_notifier(&migration_state);
803     spice_migrate.sin.base.sif = &migrate_interface.base;
804     spice_migrate.connect_complete.cb = NULL;
805     qemu_spice_add_interface(&spice_migrate.sin.base);
806 
807     qemu_spice_input_init();
808     qemu_spice_audio_init();
809 
810     qemu_add_vm_change_state_handler(vm_change_state_handler, NULL);
811 
812     g_free(x509_key_file);
813     g_free(x509_cert_file);
814     g_free(x509_cacert_file);
815 
816 #if SPICE_SERVER_VERSION >= 0x000c02
817     qemu_spice_register_ports();
818 #endif
819 }
820 
821 int qemu_spice_add_interface(SpiceBaseInstance *sin)
822 {
823     if (!spice_server) {
824         if (QTAILQ_FIRST(&qemu_spice_opts.head) != NULL) {
825             error_report("Oops: spice configured but not active");
826             exit(1);
827         }
828         /*
829          * Create a spice server instance.
830          * It does *not* listen on the network.
831          * It handles QXL local rendering only.
832          *
833          * With a command line like '-vnc :0 -vga qxl' you'll end up here.
834          */
835         spice_server = spice_server_new();
836         spice_server_init(spice_server, &core_interface);
837         qemu_add_vm_change_state_handler(vm_change_state_handler, NULL);
838     }
839 
840     if (strcmp(sin->sif->type, SPICE_INTERFACE_QXL) == 0) {
841         spice_displays++;
842     }
843 
844     return spice_server_add_interface(spice_server, sin);
845 }
846 
847 static int qemu_spice_set_ticket(bool fail_if_conn, bool disconnect_if_conn)
848 {
849     time_t lifetime, now = time(NULL);
850     char *passwd;
851 
852     if (now < auth_expires) {
853         passwd = auth_passwd;
854         lifetime = (auth_expires - now);
855         if (lifetime > INT_MAX) {
856             lifetime = INT_MAX;
857         }
858     } else {
859         passwd = NULL;
860         lifetime = 1;
861     }
862     return spice_server_set_ticket(spice_server, passwd, lifetime,
863                                    fail_if_conn, disconnect_if_conn);
864 }
865 
866 int qemu_spice_set_passwd(const char *passwd,
867                           bool fail_if_conn, bool disconnect_if_conn)
868 {
869     g_free(auth_passwd);
870     auth_passwd = g_strdup(passwd);
871     return qemu_spice_set_ticket(fail_if_conn, disconnect_if_conn);
872 }
873 
874 int qemu_spice_set_pw_expire(time_t expires)
875 {
876     auth_expires = expires;
877     return qemu_spice_set_ticket(false, false);
878 }
879 
880 int qemu_spice_display_add_client(int csock, int skipauth, int tls)
881 {
882     if (tls) {
883         return spice_server_add_ssl_client(spice_server, csock, skipauth);
884     } else {
885         return spice_server_add_client(spice_server, csock, skipauth);
886     }
887 }
888 
889 static void spice_register_config(void)
890 {
891     qemu_add_opts(&qemu_spice_opts);
892 }
893 machine_init(spice_register_config);
894