summaryrefslogtreecommitdiff
path: root/server/smartcard.c
blob: b9b89670bec3b61560b8801920abed462e1b3038 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
/* -*- Mode: C; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
   Copyright (C) 2010-2016 Red Hat, Inc.

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public
   License along with this library; if not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <arpa/inet.h>
#ifdef USE_SMARTCARD_012
#include <vscard_common.h>
#else
#ifdef USE_SMARTCARD
#include <libcacard.h>
#endif
#endif

#include "reds.h"
#include "char-device.h"
#include "red-channel.h"
#include "smartcard.h"
#include "migration-protocol.h"

/*
 * TODO: the code doesn't really support multiple readers.
 * For example: smartcard_char_device_add_to_readers calls smartcard_init,
 * which can be called only once.
 * We should allow different readers, at least one reader per client.
 * In addition the implementation should be changed: instead of one channel for
 * all readers, we need to have different channles for different readers,
 * similarly to spicevmc.
 *
 */
#define SMARTCARD_MAX_READERS 10

// Maximal length of APDU
#define APDUBufSize 270

typedef struct SmartCardChannelClient {
    RedChannelClient base;
    RedCharDeviceSmartcard *smartcard;

    /* read_from_client/write_to_device buffer.
     * The beginning of the buffer should always be VSCMsgHeader*/
    RedCharDeviceWriteBuffer *write_buf;
    int msg_in_write_buf; /* was the client msg received into a RedCharDeviceWriteBuffer
                           * or was it explicitly malloced */
} SmartCardChannelClient;

G_DEFINE_TYPE(RedCharDeviceSmartcard, red_char_device_smartcard, RED_TYPE_CHAR_DEVICE)

#define RED_CHAR_DEVICE_SMARTCARD_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), RED_TYPE_CHAR_DEVICE_SMARTCARD, RedCharDeviceSmartcardPrivate))

struct RedCharDeviceSmartcardPrivate {
    uint32_t             reader_id;
    /* read_from_device buffer */
    uint8_t             *buf;
    uint32_t             buf_size;
    uint8_t             *buf_pos;
    uint32_t             buf_used;

    SmartCardChannelClient    *scc; // client providing the remote card
    int                  reader_added; // has reader_add been sent to the device
};

enum {
    PIPE_ITEM_TYPE_ERROR = PIPE_ITEM_TYPE_CHANNEL_BASE,
    PIPE_ITEM_TYPE_SMARTCARD_DATA,
    PIPE_ITEM_TYPE_SMARTCARD_MIGRATE_DATA,
};

typedef struct ErrorItem {
    PipeItem base;
    VSCMsgHeader vheader;
    VSCMsgError  error;
} ErrorItem;

typedef struct MsgItem {
    PipeItem base;

    VSCMsgHeader* vheader;
} MsgItem;

static MsgItem *smartcard_get_vsc_msg_item(RedChannelClient *rcc, VSCMsgHeader *vheader);
static void smartcard_channel_client_pipe_add_push(RedChannelClient *rcc, PipeItem *item);

typedef struct SmartCardChannel {
    RedChannel base;
} SmartCardChannel;

static struct Readers {
    uint32_t num;
    SpiceCharDeviceInstance* sin[SMARTCARD_MAX_READERS];
} g_smartcard_readers = {0, {NULL}};

static SpiceCharDeviceInstance* smartcard_readers_get_unattached(void);
static SpiceCharDeviceInstance* smartcard_readers_get(uint32_t reader_id);
static int smartcard_char_device_add_to_readers(RedsState *reds, SpiceCharDeviceInstance *sin);
static void smartcard_char_device_attach_client(
    SpiceCharDeviceInstance *char_device, SmartCardChannelClient *scc);
static void smartcard_channel_write_to_reader(RedCharDeviceWriteBuffer *write_buf);

static MsgItem *smartcard_char_device_on_message_from_device(
    RedCharDeviceSmartcard *dev, VSCMsgHeader *header);
static RedCharDeviceSmartcard *smartcard_device_new(RedsState *reds, SpiceCharDeviceInstance *sin);
static void smartcard_init(RedsState *reds);

static void smartcard_read_buf_prepare(RedCharDeviceSmartcard *dev, VSCMsgHeader *vheader)
{
    uint32_t msg_len;

    msg_len = ntohl(vheader->length);
    if (msg_len > dev->priv->buf_size) {
        dev->priv->buf_size = MAX(dev->priv->buf_size * 2, msg_len + sizeof(VSCMsgHeader));
        dev->priv->buf = spice_realloc(dev->priv->buf, dev->priv->buf_size);
    }
}

static PipeItem *smartcard_read_msg_from_device(SpiceCharDeviceInstance *sin,
                                                void *opaque)
{
    RedCharDeviceSmartcard *dev = opaque;
    SpiceCharDeviceInterface *sif = spice_char_device_get_interface(sin);
    VSCMsgHeader *vheader = (VSCMsgHeader*)dev->priv->buf;
    int n;
    int remaining;
    int actual_length;

    while ((n = sif->read(sin, dev->priv->buf_pos, dev->priv->buf_size - dev->priv->buf_used)) > 0) {
        MsgItem *msg_to_client;

        dev->priv->buf_pos += n;
        dev->priv->buf_used += n;
        if (dev->priv->buf_used < sizeof(VSCMsgHeader)) {
            continue;
        }
        smartcard_read_buf_prepare(dev, vheader);
        actual_length = ntohl(vheader->length);
        if (dev->priv->buf_used - sizeof(VSCMsgHeader) < actual_length) {
            continue;
        }
        msg_to_client = smartcard_char_device_on_message_from_device(dev, vheader);
        remaining = dev->priv->buf_used - sizeof(VSCMsgHeader) - actual_length;
        if (remaining > 0) {
            memcpy(dev->priv->buf, dev->priv->buf_pos, remaining);
        }
        dev->priv->buf_pos = dev->priv->buf;
        dev->priv->buf_used = remaining;
        if (msg_to_client) {
            return (PipeItem *)msg_to_client;
        }
    }
    return NULL;
}

static void smartcard_send_msg_to_client(PipeItem *msg,
                                         RedClient *client,
                                         void *opaque)
{
    RedCharDeviceSmartcard *dev = opaque;
    spice_assert(dev->priv->scc && dev->priv->scc->base.client == client);
    smartcard_channel_client_pipe_add_push(&dev->priv->scc->base, (PipeItem *)msg);

}

static void smartcard_send_tokens_to_client(RedClient *client, uint32_t tokens, void *opaque)
{
    spice_error("not implemented");
}

static void smartcard_remove_client(RedClient *client, void *opaque)
{
    RedCharDeviceSmartcard *dev = opaque;

    spice_printerr("smartcard  dev %p, client %p", dev, client);
    spice_assert(dev->priv->scc && dev->priv->scc->base.client == client);
    red_channel_client_shutdown(&dev->priv->scc->base);
}

MsgItem *smartcard_char_device_on_message_from_device(RedCharDeviceSmartcard *dev,
                                                      VSCMsgHeader *vheader)
{
    VSCMsgHeader *sent_header;

    vheader->type = ntohl(vheader->type);
    vheader->length = ntohl(vheader->length);
    vheader->reader_id = ntohl(vheader->reader_id);

    switch (vheader->type) {
        case VSC_Init:
            return NULL;
        default:
            break;
    }
    /* We pass any VSC_Error right now - might need to ignore some? */
    if (dev->priv->reader_id == VSCARD_UNDEFINED_READER_ID && vheader->type != VSC_Init) {
        spice_printerr("error: reader_id not assigned for message of type %d", vheader->type);
    }
    if (dev->priv->scc) {
        sent_header = spice_memdup(vheader, sizeof(*vheader) + vheader->length);
        /* We patch the reader_id, since the device only knows about itself, and
         * we know about the sum of readers. */
        sent_header->reader_id = dev->priv->reader_id;
        return smartcard_get_vsc_msg_item(&dev->priv->scc->base, sent_header);
    }
    return NULL;
}

static int smartcard_char_device_add_to_readers(RedsState *reds, SpiceCharDeviceInstance *char_device)
{
    RedCharDeviceSmartcard *dev = red_char_device_opaque_get(char_device->st);

    if (g_smartcard_readers.num >= SMARTCARD_MAX_READERS) {
        return -1;
    }
    dev->priv->reader_id = g_smartcard_readers.num;
    g_smartcard_readers.sin[g_smartcard_readers.num++] = char_device;
    smartcard_init(reds);
    return 0;
}

static SpiceCharDeviceInstance *smartcard_readers_get(uint32_t reader_id)
{
    spice_assert(reader_id < g_smartcard_readers.num);
    return g_smartcard_readers.sin[reader_id];
}

/* TODO: fix implementation for multiple readers. Each reader should have a separated
 * channel */
static SpiceCharDeviceInstance *smartcard_readers_get_unattached(void)
{
    int i;
    RedCharDeviceSmartcard* dev;

    for (i = 0; i < g_smartcard_readers.num; ++i) {
        dev = red_char_device_opaque_get(g_smartcard_readers.sin[i]->st);
        if (!dev->priv->scc) {
            return g_smartcard_readers.sin[i];
        }
    }
    return NULL;
}

static RedCharDeviceSmartcard *smartcard_device_new(RedsState *reds, SpiceCharDeviceInstance *sin)
{
    RedCharDevice *char_dev;

    char_dev = g_object_new(RED_TYPE_CHAR_DEVICE_SMARTCARD,
                            "sin", sin,
                            "spice-server", reds,
                            "client-tokens-interval", 0ULL,
                            "self-tokens", ~0ULL,
                            NULL);

    g_object_set(char_dev, "opaque", char_dev, NULL);

    return RED_CHAR_DEVICE_SMARTCARD(char_dev);
}

void smartcard_device_disconnect(SpiceCharDeviceInstance *char_device)
{
    g_return_if_fail(RED_IS_CHAR_DEVICE_SMARTCARD(char_device->st));

    g_object_unref(char_device);
}

RedCharDevice *smartcard_device_connect(RedsState *reds, SpiceCharDeviceInstance *char_device)
{
    RedCharDeviceSmartcard *dev;

    dev = smartcard_device_new(reds, char_device);
    if (smartcard_char_device_add_to_readers(reds, char_device) == -1) {
        g_object_unref(dev);
        return NULL;
    }
    return RED_CHAR_DEVICE(dev);
}

static void smartcard_char_device_notify_reader_add(RedCharDeviceSmartcard *dev)
{
    RedCharDeviceWriteBuffer *write_buf;
    VSCMsgHeader *vheader;

    write_buf = red_char_device_write_buffer_get(RED_CHAR_DEVICE(dev), NULL, sizeof(vheader));
    if (!write_buf) {
        spice_error("failed to allocate write buffer");
        return;
    }
    dev->priv->reader_added = TRUE;
    vheader = (VSCMsgHeader *)write_buf->buf;
    vheader->type = VSC_ReaderAdd;
    vheader->reader_id = dev->priv->reader_id;
    vheader->length = 0;
    smartcard_channel_write_to_reader(write_buf);
}

static void smartcard_char_device_attach_client(SpiceCharDeviceInstance *char_device,
                                                SmartCardChannelClient *scc)
{
    RedCharDeviceSmartcard *dev = red_char_device_opaque_get(char_device->st);
    int client_added;

    spice_assert(!scc->smartcard && !dev->priv->scc);
    dev->priv->scc = scc;
    scc->smartcard = dev;
    client_added = red_char_device_client_add(RED_CHAR_DEVICE(dev),
                                              scc->base.client,
                                              FALSE, /* no flow control yet */
                                              0, /* send queue size */
                                              ~0,
                                              ~0,
                                              red_channel_client_is_waiting_for_migrate_data(
                                                  &scc->base));
    if (!client_added) {
        spice_warning("failed");
        dev->priv->scc = NULL;
        scc->smartcard = NULL;
        red_channel_client_disconnect(&scc->base);
    }
}

static void smartcard_char_device_notify_reader_remove(RedCharDeviceSmartcard *dev)
{
    RedCharDeviceWriteBuffer *write_buf;
    VSCMsgHeader *vheader;

    if (!dev->priv->reader_added) {
        spice_debug("reader add was never sent to the device");
        return;
    }
    write_buf = red_char_device_write_buffer_get(RED_CHAR_DEVICE(dev), NULL, sizeof(vheader));
    if (!write_buf) {
        spice_error("failed to allocate write buffer");
        return;
    }
    dev->priv->reader_added = FALSE;
    vheader = (VSCMsgHeader *)write_buf->buf;
    vheader->type = VSC_ReaderRemove;
    vheader->reader_id = dev->priv->reader_id;
    vheader->length = 0;
    smartcard_channel_write_to_reader(write_buf);
}

static void smartcard_char_device_detach_client(SmartCardChannelClient *scc)
{
    RedCharDeviceSmartcard *dev;

    if (!scc->smartcard) {
        return;
    }
    dev = scc->smartcard;
    spice_assert(dev->priv->scc == scc);
    red_char_device_client_remove(RED_CHAR_DEVICE(dev), scc->base.client);
    scc->smartcard = NULL;
    dev->priv->scc = NULL;
}

static int smartcard_channel_client_config_socket(RedChannelClient *rcc)
{
    return TRUE;
}

static uint8_t *smartcard_channel_alloc_msg_rcv_buf(RedChannelClient *rcc,
                                                    uint16_t type,
                                                    uint32_t size)
{
    SmartCardChannelClient *scc = SPICE_CONTAINEROF(rcc, SmartCardChannelClient, base);

    /* todo: only one reader is actually supported. When we fix the code to support
     * multiple readers, we will porbably associate different devices to
     * differenc channels */
    if (!scc->smartcard) {
        scc->msg_in_write_buf = FALSE;
        return spice_malloc(size);
    } else {
        RedCharDeviceSmartcard *dev;

        spice_assert(g_smartcard_readers.num == 1);
        dev = scc->smartcard;
        spice_assert(dev->priv->scc || scc->smartcard);
        spice_assert(!scc->write_buf);
        scc->write_buf = red_char_device_write_buffer_get(RED_CHAR_DEVICE(dev), rcc->client, size);

        if (!scc->write_buf) {
            spice_error("failed to allocate write buffer");
            return NULL;
        }
        scc->msg_in_write_buf = TRUE;
        return scc->write_buf->buf;
    }
}

static void smartcard_channel_release_msg_rcv_buf(RedChannelClient *rcc,
                                                  uint16_t type,
                                                  uint32_t size,
                                                  uint8_t *msg)
{
    SmartCardChannelClient *scc = SPICE_CONTAINEROF(rcc, SmartCardChannelClient, base);

    /* todo: only one reader is actually supported. When we fix the code to support
     * multiple readers, we will porbably associate different devices to
     * differenc channels */

    if (!scc->msg_in_write_buf) {
        spice_assert(!scc->write_buf);
        free(msg);
    } else {
        if (scc->write_buf) { /* msg hasn't been pushed to the guest */
            spice_assert(scc->write_buf->buf == msg);
            red_char_device_write_buffer_release(RED_CHAR_DEVICE(scc->smartcard), scc->write_buf);
            scc->write_buf = NULL;
        }
    }
}

static void smartcard_channel_send_data(RedChannelClient *rcc, SpiceMarshaller *m,
                                        PipeItem *item, VSCMsgHeader *vheader)
{
    spice_assert(rcc);
    spice_assert(vheader);
    red_channel_client_init_send_data(rcc, SPICE_MSG_SMARTCARD_DATA, item);
    spice_marshaller_add_ref(m, (uint8_t*)vheader, sizeof(VSCMsgHeader));
    if (vheader->length > 0) {
        spice_marshaller_add_ref(m, (uint8_t*)(vheader+1), vheader->length);
    }
}

static void smartcard_channel_send_error(
    RedChannelClient *rcc, SpiceMarshaller *m, PipeItem *item)
{
    ErrorItem* error_item = (ErrorItem*)item;

    smartcard_channel_send_data(rcc, m, item, &error_item->vheader);
}

static void smartcard_channel_send_msg(RedChannelClient *rcc,
                                       SpiceMarshaller *m, PipeItem *item)
{
    MsgItem* msg_item = (MsgItem*)item;

    smartcard_channel_send_data(rcc, m, item, msg_item->vheader);
}

static void smartcard_channel_send_migrate_data(RedChannelClient *rcc,
                                                SpiceMarshaller *m, PipeItem *item)
{
    SmartCardChannelClient *scc;
    RedCharDeviceSmartcard *dev;
    SpiceMarshaller *m2;

    scc = SPICE_CONTAINEROF(rcc, SmartCardChannelClient, base);
    dev = scc->smartcard;
    red_channel_client_init_send_data(rcc, SPICE_MSG_MIGRATE_DATA, item);
    spice_marshaller_add_uint32(m, SPICE_MIGRATE_DATA_SMARTCARD_MAGIC);
    spice_marshaller_add_uint32(m, SPICE_MIGRATE_DATA_SMARTCARD_VERSION);

    if (!dev) {
        red_char_device_migrate_data_marshall_empty(m);
        spice_marshaller_add_uint8(m, 0);
        spice_marshaller_add_uint32(m, 0);
        spice_marshaller_add_uint32(m, 0);
        spice_debug("null char dev");
    } else {
        red_char_device_migrate_data_marshall(RED_CHAR_DEVICE(dev), m);
        spice_marshaller_add_uint8(m, dev->priv->reader_added);
        spice_marshaller_add_uint32(m, dev->priv->buf_used);
        m2 = spice_marshaller_get_ptr_submarshaller(m, 0);
        spice_marshaller_add(m2, dev->priv->buf, dev->priv->buf_used);
        spice_debug("reader added %d partial read size %u", dev->priv->reader_added, dev->priv->buf_used);
    }
}

static void smartcard_channel_send_item(RedChannelClient *rcc, PipeItem *item)
{
    SpiceMarshaller *m = red_channel_client_get_marshaller(rcc);

    switch (item->type) {
    case PIPE_ITEM_TYPE_ERROR:
        smartcard_channel_send_error(rcc, m, item);
        break;
    case PIPE_ITEM_TYPE_SMARTCARD_DATA:
        smartcard_channel_send_msg(rcc, m, item);
        break;
    case PIPE_ITEM_TYPE_SMARTCARD_MIGRATE_DATA:
        smartcard_channel_send_migrate_data(rcc, m, item);
        break;
    default:
        spice_error("bad pipe item %d", item->type);
        free(item);
        return;
    }
    red_channel_client_begin_send_message(rcc);
}

static void smartcard_channel_release_pipe_item(RedChannelClient *rcc,
                                      PipeItem *item, int item_pushed)
{
    if (item->type == PIPE_ITEM_TYPE_SMARTCARD_DATA) {
        pipe_item_unref(item);
    } else {
        free(item);
    }
}

static void smartcard_channel_on_disconnect(RedChannelClient *rcc)
{
    SmartCardChannelClient *scc = SPICE_CONTAINEROF(rcc, SmartCardChannelClient, base);

    if (scc->smartcard) {
        RedCharDeviceSmartcard *dev = scc->smartcard;

        smartcard_char_device_detach_client(scc);
        smartcard_char_device_notify_reader_remove(dev);
    }
}

/* this is called from both device input and client input. since the device is
 * a usb device, the context is still the main thread (kvm_main_loop, timers)
 * so no mutex is required. */
static void smartcard_channel_client_pipe_add_push(RedChannelClient *rcc, PipeItem *item)
{
    red_channel_client_pipe_add_push(rcc, item);
}

static void smartcard_push_error(RedChannelClient *rcc, uint32_t reader_id, VSCErrorCode error)
{
    ErrorItem *error_item = spice_new0(ErrorItem, 1);

    pipe_item_init(&error_item->base, PIPE_ITEM_TYPE_ERROR);

    error_item->base.type = PIPE_ITEM_TYPE_ERROR;
    error_item->vheader.reader_id = reader_id;
    error_item->vheader.type = VSC_Error;
    error_item->vheader.length = sizeof(error_item->error);
    error_item->error.code = error;
    smartcard_channel_client_pipe_add_push(rcc, &error_item->base);
}

static void smartcard_free_vsc_msg_item(MsgItem *item)
{
    free(item->vheader);
    free(item);
}

static MsgItem *smartcard_get_vsc_msg_item(RedChannelClient *rcc, VSCMsgHeader *vheader)
{
    MsgItem *msg_item = spice_new0(MsgItem, 1);

    pipe_item_init_full(&msg_item->base, PIPE_ITEM_TYPE_SMARTCARD_DATA,
                        (GDestroyNotify)smartcard_free_vsc_msg_item);
    msg_item->vheader = vheader;
    return msg_item;
}

static void smartcard_remove_reader(SmartCardChannelClient *scc, uint32_t reader_id)
{
    SpiceCharDeviceInstance *char_device = smartcard_readers_get(reader_id);
    RedCharDeviceSmartcard *dev;

    if (char_device == NULL) {
        smartcard_push_error(&scc->base, reader_id,
            VSC_GENERAL_ERROR);
        return;
    }

    dev = red_char_device_opaque_get(char_device->st);
    if (dev->priv->reader_added == FALSE) {
        smartcard_push_error(&scc->base, reader_id,
            VSC_GENERAL_ERROR);
        return;
    }
    spice_assert(scc->smartcard == dev);
    smartcard_char_device_notify_reader_remove(dev);
}

static void smartcard_add_reader(SmartCardChannelClient *scc, uint8_t *name)
{
    if (!scc->smartcard) { /* we already tried to attach a reader to the client
                                    when it connected */
        SpiceCharDeviceInstance *char_device = smartcard_readers_get_unattached();

        if (!char_device) {
            smartcard_push_error(&scc->base, VSCARD_UNDEFINED_READER_ID,
                                VSC_CANNOT_ADD_MORE_READERS);
            return;
        }
        smartcard_char_device_attach_client(char_device, scc);
    }
    smartcard_char_device_notify_reader_add(scc->smartcard);
    // The device sends a VSC_Error message, we will let it through, no
    // need to send our own. We already set the correct reader_id, from
    // our RedCharDeviceSmartcard.
}

static void smartcard_channel_write_to_reader(RedCharDeviceWriteBuffer *write_buf)
{
    SpiceCharDeviceInstance *sin;
    RedCharDeviceSmartcard *dev;
    VSCMsgHeader *vheader;
    uint32_t actual_length;

    vheader = (VSCMsgHeader *)write_buf->buf;
    actual_length = vheader->length;

    spice_assert(vheader->reader_id <= g_smartcard_readers.num);
    sin = g_smartcard_readers.sin[vheader->reader_id];
    dev = (RedCharDeviceSmartcard *)red_char_device_opaque_get(sin->st);
    spice_assert(!dev->priv->scc || dev == dev->priv->scc->smartcard);
    /* protocol requires messages to be in network endianess */
    vheader->type = htonl(vheader->type);
    vheader->length = htonl(vheader->length);
    vheader->reader_id = htonl(vheader->reader_id);
    write_buf->buf_used = actual_length + sizeof(VSCMsgHeader);
    /* pushing the buffer to the write queue; It will be released
     * when it will be fully consumed by the device */
    red_char_device_write_buffer_add(sin->st, write_buf);
    if (dev->priv->scc && write_buf == dev->priv->scc->write_buf) {
        dev->priv->scc->write_buf = NULL;
    }
}

static int smartcard_channel_client_handle_migrate_flush_mark(RedChannelClient *rcc)
{
    red_channel_client_pipe_add_type(rcc, PIPE_ITEM_TYPE_SMARTCARD_MIGRATE_DATA);
    return TRUE;
}

static void smartcard_device_restore_partial_read(RedCharDeviceSmartcard *dev,
                                                  SpiceMigrateDataSmartcard *mig_data)
{
    uint8_t *read_data;

    spice_debug("read_size  %u", mig_data->read_size);
    read_data = (uint8_t *)mig_data + mig_data->read_data_ptr - sizeof(SpiceMigrateDataHeader);
    if (mig_data->read_size < sizeof(VSCMsgHeader)) {
        spice_assert(dev->priv->buf_size >= mig_data->read_size);
    } else {
        smartcard_read_buf_prepare(dev, (VSCMsgHeader *)read_data);
    }
    memcpy(dev->priv->buf, read_data, mig_data->read_size);
    dev->priv->buf_used = mig_data->read_size;
    dev->priv->buf_pos = dev->priv->buf + mig_data->read_size;
}

static int smartcard_channel_client_handle_migrate_data(RedChannelClient *rcc,
                                                        uint32_t size, void *message)
{
    SmartCardChannelClient *scc;
    SpiceMigrateDataHeader *header;
    SpiceMigrateDataSmartcard *mig_data;

    scc = SPICE_CONTAINEROF(rcc, SmartCardChannelClient, base);
    header = (SpiceMigrateDataHeader *)message;
    mig_data = (SpiceMigrateDataSmartcard *)(header + 1);
    if (size < sizeof(SpiceMigrateDataHeader) + sizeof(SpiceMigrateDataSmartcard)) {
        spice_error("bad message size");
        return FALSE;
    }
    if (!migration_protocol_validate_header(header,
                                            SPICE_MIGRATE_DATA_SMARTCARD_MAGIC,
                                            SPICE_MIGRATE_DATA_SMARTCARD_VERSION)) {
        spice_error("bad header");
        return FALSE;
    }

    if (!mig_data->base.connected) { /* client wasn't attached to a smartcard */
        return TRUE;
    }

    if (!scc->smartcard) {
        SpiceCharDeviceInstance *char_device = smartcard_readers_get_unattached();

        if (!char_device) {
            spice_warning("no unattached device available");
            return TRUE;
        } else {
            smartcard_char_device_attach_client(char_device, scc);
        }
    }
    spice_debug("reader added %d partial read_size %u", mig_data->reader_added, mig_data->read_size);
    scc->smartcard->priv->reader_added = mig_data->reader_added;

    smartcard_device_restore_partial_read(scc->smartcard, mig_data);
    return red_char_device_restore(RED_CHAR_DEVICE(scc->smartcard), &mig_data->base);
}

static int smartcard_channel_handle_message(RedChannelClient *rcc,
                                            uint16_t type,
                                            uint32_t size,
                                            uint8_t *msg)
{
    VSCMsgHeader* vheader = (VSCMsgHeader*)msg;
    SmartCardChannelClient *scc = SPICE_CONTAINEROF(rcc, SmartCardChannelClient, base);

    if (type != SPICE_MSGC_SMARTCARD_DATA) {
        /* Handles seamless migration protocol. Also handles ack's,
         * spicy sends them while spicec does not */
        return red_channel_client_handle_message(rcc, size, type, msg);
    }

    spice_assert(size == vheader->length + sizeof(VSCMsgHeader));
    switch (vheader->type) {
        case VSC_ReaderAdd:
            smartcard_add_reader(scc, msg + sizeof(VSCMsgHeader));
            return TRUE;
            break;
        case VSC_ReaderRemove:
            smartcard_remove_reader(scc, vheader->reader_id);
            return TRUE;
            break;
        case VSC_Init:
            // ignore - we should never get this anyway
            return TRUE;
            break;
        case VSC_Error:
        case VSC_ATR:
        case VSC_CardRemove:
        case VSC_APDU:
            break; // passed on to device
        default:
            printf("ERROR: unexpected message on smartcard channel\n");
            return TRUE;
    }

    /* todo: fix */
    if (vheader->reader_id >= g_smartcard_readers.num) {
        spice_printerr("ERROR: received message for non existing reader: %d, %d, %d", vheader->reader_id,
            vheader->type, vheader->length);
        return FALSE;
    }
    spice_assert(scc->write_buf->buf == msg);
    smartcard_channel_write_to_reader(scc->write_buf);

    return TRUE;
}

static void smartcard_channel_hold_pipe_item(RedChannelClient *rcc, PipeItem *item)
{
}

static void smartcard_connect_client(RedChannel *channel, RedClient *client,
                                     RedsStream *stream, int migration,
                                     int num_common_caps, uint32_t *common_caps,
                                     int num_caps, uint32_t *caps)
{
    SpiceCharDeviceInstance *char_device =
            smartcard_readers_get_unattached();

    SmartCardChannelClient *scc;

    scc = (SmartCardChannelClient *)red_channel_client_create(sizeof(SmartCardChannelClient),
                                                              channel,
                                                              client,
                                                              stream,
                                                              FALSE,
                                                              num_common_caps, common_caps,
                                                              num_caps, caps);

    if (!scc) {
        return;
    }
    red_channel_client_ack_zero_messages_window(&scc->base);

    if (char_device) {
        smartcard_char_device_attach_client(char_device, scc);
    } else {
        spice_printerr("char dev unavailable");
    }
}

SmartCardChannel *g_smartcard_channel;

static void smartcard_init(RedsState *reds)
{
    ChannelCbs channel_cbs = { NULL, };
    ClientCbs client_cbs = { NULL, };
    uint32_t migration_flags = SPICE_MIGRATE_NEED_FLUSH | SPICE_MIGRATE_NEED_DATA_TRANSFER;

    spice_assert(!g_smartcard_channel);

    channel_cbs.config_socket = smartcard_channel_client_config_socket;
    channel_cbs.on_disconnect = smartcard_channel_on_disconnect;
    channel_cbs.send_item = smartcard_channel_send_item;
    channel_cbs.hold_item = smartcard_channel_hold_pipe_item;
    channel_cbs.release_item = smartcard_channel_release_pipe_item;
    channel_cbs.alloc_recv_buf = smartcard_channel_alloc_msg_rcv_buf;
    channel_cbs.release_recv_buf = smartcard_channel_release_msg_rcv_buf;
    channel_cbs.handle_migrate_flush_mark = smartcard_channel_client_handle_migrate_flush_mark;
    channel_cbs.handle_migrate_data = smartcard_channel_client_handle_migrate_data;

    g_smartcard_channel = (SmartCardChannel*)red_channel_create(sizeof(SmartCardChannel),
                                             reds,
                                             reds_get_core_interface(reds),
                                             SPICE_CHANNEL_SMARTCARD, 0,
                                             FALSE /* handle_acks */,
                                             smartcard_channel_handle_message,
                                             &channel_cbs,
                                             migration_flags);

    if (!g_smartcard_channel) {
        spice_error("failed to allocate Smartcard Channel");
    }

    client_cbs.connect = smartcard_connect_client;
    red_channel_register_client_cbs(&g_smartcard_channel->base, &client_cbs, NULL);

    reds_register_channel(reds, &g_smartcard_channel->base);
}


static void
red_char_device_smartcard_finalize(GObject *object)
{
    RedCharDeviceSmartcard *self = RED_CHAR_DEVICE_SMARTCARD(object);

    free(self->priv->buf);
    if (self->priv->scc) {
        self->priv->scc->smartcard = NULL;
    }

    G_OBJECT_CLASS(red_char_device_smartcard_parent_class)->finalize(object);
}

static void
red_char_device_smartcard_class_init(RedCharDeviceSmartcardClass *klass)
{
    GObjectClass *object_class = G_OBJECT_CLASS(klass);
    RedCharDeviceClass *char_dev_class = RED_CHAR_DEVICE_CLASS(klass);

    g_type_class_add_private(klass, sizeof (RedCharDeviceSmartcardPrivate));

    object_class->finalize = red_char_device_smartcard_finalize;

    char_dev_class->read_one_msg_from_device = smartcard_read_msg_from_device;
    char_dev_class->send_msg_to_client = smartcard_send_msg_to_client;
    char_dev_class->send_tokens_to_client = smartcard_send_tokens_to_client;
    char_dev_class->remove_client = smartcard_remove_client;
}

static void
red_char_device_smartcard_init(RedCharDeviceSmartcard *self)
{
    self->priv = RED_CHAR_DEVICE_SMARTCARD_PRIVATE(self);

    self->priv->reader_id = VSCARD_UNDEFINED_READER_ID;
    self->priv->buf_size = APDUBufSize + sizeof(VSCMsgHeader);
    self->priv->buf = spice_malloc(self->priv->buf_size);
    self->priv->buf_pos = self->priv->buf;
}