summaryrefslogtreecommitdiffstats
path: root/server/reds.c
blob: 108ade3e8a42b4fd128f4961a72bc9b75c5799db (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
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
/*
   Copyright (C) 2009 Red Hat, Inc.

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

   This program 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 General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <stdint.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <limits.h>
#include <time.h>
#include <pthread.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <errno.h>
#include <ctype.h>

#include <openssl/bio.h>
#include <openssl/pem.h>
#include <openssl/bn.h>
#include <openssl/rsa.h>
#include <openssl/ssl.h>
#include <openssl/err.h>

#include "spice.h"
#include "reds.h"
#include "red.h"
#include "vd_agent.h"

#include "red_common.h"
#include "red_dispatcher.h"
#include "snd_worker.h"
#include "reds_stat.h"
#include "stat.h"
#include "ring.h"
#include "config.h"

CoreInterface *core = NULL;
static MigrationInterface *mig = NULL;
static KeyboardInterface *keyboard = NULL;
static MouseInterface *mouse = NULL;
static TabletInterface *tablet = NULL;
static VDIPortInterface *vdagent = NULL;

#define MIGRATION_NOTIFY_SPICE_KEY "spice_mig_ext"

#define REDS_MIG_VERSION 3
#define REDS_MIG_CONTINUE 1
#define REDS_MIG_ABORT 2
#define REDS_MIG_DIFF_VERSION 3

#define REDS_AGENT_WINDOW_SIZE 10
#define REDS_TOKENS_TO_SEND 5
#define REDS_NUM_INTERNAL_AGENT_MESSAGES 1
#define REDS_VDI_PORT_NUM_RECIVE_BUFFS 5
#define REDS_MAX_SEND_IOVEC 100

#define NET_TEST_WARMUP_BYTES 0
#define NET_TEST_BYTES (1024 * 250)

static int spice_port = -1;
static int spice_secure_port = -1;
static char spice_addr[256];
static int spice_family = PF_UNSPEC;
static char *default_renderer = "cairo";

static int ticketing_enabled = 1; //Ticketing is enabled by default
static pthread_mutex_t *lock_cs;
static long *lock_count;
uint32_t streaming_video = STREAM_VIDEO_FILTER;
spice_image_compression_t image_compression = SPICE_IMAGE_COMPRESS_AUTO_GLZ;
int agent_mouse = TRUE;

static void openssl_init();

#define MIGRATE_TIMEOUT (1000 * 10) /* 10sec */
#define PING_INTERVAL (1000 * 10)
#define KEY_MODIFIERS_TTL (1000 * 2) /*2sec*/
#define MM_TIMER_GRANULARITY_MS (1000 / 30)
#define MM_TIME_DELTA 400 /*ms*/

// approximate max recive message size
#define RECIVE_BUF_SIZE \
    (4096 + (REDS_AGENT_WINDOW_SIZE + REDS_NUM_INTERNAL_AGENT_MESSAGES) * RED_AGENT_MAX_DATA_SIZE)

#define SEND_BUF_SIZE 4096

#define SCROLL_LOCK_SCAN_CODE 0x46
#define NUM_LOCK_SCAN_CODE 0x45
#define CAPS_LOCK_SCAN_CODE 0x3a

typedef struct IncomingHandler {
    void *opaque;
    int shut;
    uint8_t buf[RECIVE_BUF_SIZE];
    uint32_t end_pos;
    void (*handle_message)(void *opaque, RedDataHeader *message);
} IncomingHandler;

typedef struct OutgoingHandler {
    void *opaque;
    uint8_t buf[SEND_BUF_SIZE];
    uint8_t *now;
    uint32_t length;
    void (*select)(void *opaque, int select);
    void (*may_write)(void *opaque);
} OutgoingHandler;

typedef struct TicketAuthentication {
    char password[RED_MAX_PASSWORD_LENGTH];
    time_t expiration_time;
} TicketAuthentication;

static TicketAuthentication taTicket;

typedef struct TicketInfo {
    RSA *rsa;
    int rsa_size;
    BIGNUM *bn;
    RedLinkEncryptedTicket encrypted_ticket;
} TicketInfo;

typedef struct MonitorMode {
    uint32_t x_res;
    uint32_t y_res;
} MonitorMode;

typedef struct RedsOutItem RedsOutItem;
struct RedsOutItem {
    RingItem link;
    void (*prepare)(RedsOutItem *item, struct iovec* vec, int *len);
    void (*release)(RedsOutItem *item);
};

typedef struct VDIReadBuf {
    RedsOutItem out_item;
    int len;
    RedDataHeader header;
    uint8_t data[RED_AGENT_MAX_DATA_SIZE];
} VDIReadBuf;

enum {
    VDI_PORT_READ_STATE_READ_HADER,
    VDI_PORT_READ_STATE_GET_BUFF,
    VDI_PORT_READ_STATE_READ_DATA,
};

enum {
    VDP_CLIENT_PORT = 1,
    VDP_SERVER_PORT,
};

typedef struct __attribute__ ((__packed__)) VDIChunkHeader {
    uint32_t port;
    uint32_t size;
} VDIChunkHeader;

typedef struct VDIPortState {
    VDIPortPlug plug;
    VDObjectRef plug_ref;
    uint32_t plug_generation;

    uint32_t num_tokens;
    uint32_t num_client_tokens;
    Ring external_bufs;
    Ring internal_bufs;
    Ring write_queue;

    Ring read_bufs;
    uint32_t read_state;
    uint32_t message_recive_len;
    uint8_t *recive_pos;
    uint32_t recive_len;
    VDIReadBuf *current_read_buf;

    VDIChunkHeader vdi_chunk_header;

    int client_agent_started;
    uint32_t send_tokens;
} VDIPortState;

typedef struct InputsState {
    Channel *channel;
    RedsStreamContext *peer;
    uint8_t buf[RECIVE_BUF_SIZE];
    uint32_t end_pos;
    IncomingHandler in_handler;
    OutgoingHandler out_handler;
    VDAgentMouseState mouse_state;
    int pending_mouse_event;
    uint32_t motion_count;
    uint64_t serial; //migrate me
} InputsState;

typedef struct RedsOutgoingData {
    Ring pipe;
    RedsOutItem *item;
    int vec_size;
    struct iovec vec_buf[REDS_MAX_SEND_IOVEC];
    struct iovec *vec;
} RedsOutgoingData;

enum NetTestStage {
    NET_TEST_STAGE_INVALID,
    NET_TEST_STAGE_WARMUP,
    NET_TEST_STAGE_LATENCY,
    NET_TEST_STAGE_RATE,
};

#ifdef RED_STATISTICS

#define REDS_MAX_STAT_NODES 100
#define REDS_STAT_SHM_SIZE (sizeof(RedsStat) + REDS_MAX_STAT_NODES * sizeof(StatNode))

typedef struct RedsStatValue {
    uint32_t value;
    uint32_t min;
    uint32_t max;
    uint32_t average;
    uint32_t count;
} RedsStatValue;

#endif

typedef struct RedsState {
    int listen_socket;
    int secure_listen_socket;
    RedsStreamContext *peer;
    int disconnecting;
    uint32_t link_id;
    uint64_t serial; //migrate me
    VDIPortState agent_state;
    InputsState *inputs_state;

    VDObjectRef mig_notifier;
    int mig_wait_connect;
    int mig_wait_disconnect;
    int mig_inprogress;
    int mig_target;
    int num_of_channels;
    IncomingHandler in_handler;
    RedsOutgoingData outgoing;
    Channel *channels;
    int mouse_mode;
    int is_client_mouse_allowed;
    int dispatcher_allows_client_mouse;
    MonitorMode monitor_mode;
    VDObjectRef mig_timer;
    VDObjectRef key_modifiers_timer;
    VDObjectRef mm_timer;

    TicketAuthentication taTicket;
    SSL_CTX *ctx;

#ifdef RED_STATISTICS
    char *stat_shm_name;
    RedsStat *stat;
    pthread_mutex_t stat_lock;
    RedsStatValue roundtrip_stat;
    VDObjectRef ping_timer;
    int ping_interval;
#endif
    uint32_t ping_id;
    uint32_t net_test_id;
    int net_test_stage;
    int peer_minor_version;
} RedsState;

uint64_t bitrate_per_sec = ~0;
static uint64_t letancy = 0;

static RedsState *reds = NULL;

typedef struct AsyncRead {
    RedsStreamContext *peer;
    void *opaque;
    uint8_t *now;
    uint8_t *end;
    int active_file_handlers;
    void (*done)(void *opaque);
    void (*error)(void *opaque, int err);
} AsyncRead;

typedef struct RedLinkInfo {
    RedsStreamContext *peer;
    AsyncRead asyc_read;
    RedLinkHeader link_header;
    RedLinkMess *link_mess;
    int mess_pos;
    TicketInfo tiTicketing;
} RedLinkInfo;

typedef struct VDIPortBuf VDIPortBuf;
struct  __attribute__ ((__packed__)) VDIPortBuf {
    RingItem link;
    uint8_t *now;
    int write_len;
    void (*free)(VDIPortBuf *buf);
    VDIChunkHeader chunk_header; //start send from &chunk_header
};

typedef struct __attribute__ ((__packed__)) VDAgentExtBuf {
    VDIPortBuf base;
    uint8_t buf[RED_AGENT_MAX_DATA_SIZE];
    VDIChunkHeader migrate_overflow;
} VDAgentExtBuf;

typedef struct __attribute__ ((__packed__)) VDInternalBuf {
    VDIPortBuf base;
    VDAgentMessage header;
    union {
        VDAgentMouseState mouse_state;
    }
    u;
    VDIChunkHeader migrate_overflow;
} VDInternalBuf;

typedef struct RedSSLParameters {
    char keyfile_password[256];
    char certs_file[256];
    char private_key_file[256];
    char ca_certificate_file[256];
    char dh_key_file[256];
    char ciphersuite[256];
} RedSSLParameters;

typedef struct ChannelSecurityOptions ChannelSecurityOptions;
struct ChannelSecurityOptions {
    uint32_t channel_id;
    uint32_t options;
    ChannelSecurityOptions *next;
};

typedef struct PingItem {
    RedsOutItem base;
    RedDataHeader header;
    RedPing ping;
    int size;
} PingItem;


#define ZERO_BUF_SIZE 4096

static uint8_t zero_page[ZERO_BUF_SIZE] = {0};

static void reds_main_write(void *data);
static void reds_push();

static ChannelSecurityOptions *channels_security = NULL;
static int default_channel_security =
    SPICE_CHANNEL_SECURITY_NON | SPICE_CHANNEL_SECURITY_SSL;

static RedSSLParameters ssl_parameters;


void (*log_proc)(CoreInterface *core, LogLevel level, const char* component,
                 const char* format, ...) = NULL;

#define LOG_MESSAGE(level, format, ...) {                           \
    if (log_proc) {                                                 \
        log_proc(core, level, "spice", format, ## __VA_ARGS__ );    \
    }                                                               \
}

static int args_is_empty(const VDICmdArg* args)
{
    return !args || args[0].descriptor.type == ARG_TYPE_INVALID;
}

const int args_is_string(const VDICmdArg* args)
{
    return !args_is_empty(args) && args->descriptor.type == ARG_TYPE_STRING;
}

const int args_is_int(const VDICmdArg* args)
{
    return !args_is_empty(args) && args->descriptor.type == ARG_TYPE_INT;
}

static ChannelSecurityOptions *find_channel_security(int id)
{
    ChannelSecurityOptions *now = channels_security;
    while (now && now->channel_id != id) {
        now = now->next;
    }
    return now;
}

static int reds_write(void *ctx, void *buf, size_t size)
{
    int return_code;
    int sock = (long)ctx;
    size_t count = size;

    return_code = write(sock, buf, count);

    return (return_code);
}

static int reds_read(void *ctx, void *buf, size_t size)
{
    int return_code;
    int sock = (long)ctx;
    size_t count = size;

    return_code = read(sock, buf, count);

    return (return_code);
}

static int reds_free(RedsStreamContext *peer)
{
    close(peer->socket);
    free(peer);
    return 0;
}

static int reds_ssl_write(void *ctx, void *buf, size_t size)
{
    int return_code;
    int ssl_error;
    SSL *ssl = ctx;

    return_code = SSL_write(ssl, buf, size);

    if (return_code < 0) {
        ssl_error = SSL_get_error(ssl, return_code);
    }

    return (return_code);
}

static int reds_ssl_read(void *ctx, void *buf, size_t size)
{
    int return_code;
    int ssl_error;
    SSL *ssl = ctx;

    return_code = SSL_read(ssl, buf, size);

    if (return_code < 0) {
        ssl_error = SSL_get_error(ssl, return_code);
    }

    return (return_code);
}

static int reds_ssl_writev(void *ctx, const struct iovec *vector, int count)
{
    int i;
    int n;
    int return_code = 0;
    int ssl_error;
    SSL *ssl = ctx;

    for (i = 0; i < count; ++i) {
        n = SSL_write(ssl, vector[i].iov_base, vector[i].iov_len);
        if (n <= 0) {
            ssl_error = SSL_get_error(ssl, n);
            if (return_code <= 0) {
                return n;
            } else {
                break;
            }
        } else {
            return_code += n;
        }
    }

    return return_code;
}

static int reds_ssl_free(RedsStreamContext *peer)
{
    SSL_free(peer->ssl);
    close(peer->socket);
    free(peer);
    return 0;
}

static void __reds_release_link(RedLinkInfo *link)
{
    ASSERT(link->peer);
    core->set_file_handlers(core, link->peer->socket, NULL, NULL, NULL);
    free(link->link_mess);
    BN_free(link->tiTicketing.bn);
    if (link->tiTicketing.rsa) {
        RSA_free(link->tiTicketing.rsa);
    }
    free(link);
}

static inline void reds_release_link(RedLinkInfo *link)
{
    RedsStreamContext *peer = link->peer;
    __reds_release_link(link);
    peer->cb_free(peer);
}

static void reds_do_disable_ticketing(void)
{
    ticketing_enabled = 0;
    memset(taTicket.password, 0, sizeof(taTicket.password));
    core->term_printf(core, "Ticketing is now disabled.\n");
}

static void reds_do_disable_ticketing_2(const VDICmdArg* args)
{
    if (!args_is_empty(args)) {
        red_printf("invalid args");
        return;
    }

    reds_do_disable_ticketing();
}

static char *base64decode(const char *input, int length)
{
    BIO *b64;
    BIO *bmem;
    int n;
    char *buffer = (char *)malloc(length);
    memset(buffer, 0, length);

    char *inbuffer = (char *)malloc(length + 1);
    memset(inbuffer, 0, length + 1);
    memcpy(inbuffer, input, length);
    inbuffer[length] = '\n';

    b64 = BIO_new(BIO_f_base64());
    bmem = BIO_new_mem_buf(inbuffer, length + 1);

    if (b64 != NULL && bmem != NULL) {
        bmem = BIO_push(b64, bmem);

        n = BIO_read(bmem, buffer, length);

        if (n != 0) {
            buffer[n - 1] = '\0';
        } else {
            free(buffer);
            buffer = NULL;
        }
    } else {
        free(buffer);
        buffer = NULL;
    }

    BIO_free_all(bmem);

    return buffer;
}

static void reds_do_info_ticket(void)
{
    core->term_printf(core, "Ticket Information:");
    if (ticketing_enabled) {
        if (strlen(taTicket.password) == 0) {
            core->term_printf(core, " blocked\n");
        } else {
            if (taTicket.expiration_time == INT_MAX) {
                core->term_printf(core, " expiration NEVER\n");
            } else {
                time_t now;

                time(&now);
                int expired = taTicket.expiration_time < now;
                if (expired) {
                    core->term_printf(core, " expiration EXPIRED\n");
                } else {
                    core->term_printf(core, " expiration %s\n",
                                      ctime((time_t *)&(taTicket.expiration_time)));
                }
            }
        }
    } else {
        core->term_printf(core, " disabled\n");
    }
}

static struct iovec *reds_iovec_skip(struct iovec vec[], int skip, int *vec_size)
{
    struct iovec *now = vec;

    while (skip && skip >= now->iov_len) {
        skip -= now->iov_len;
        --*vec_size;
        now++;
    }
    now->iov_base = (uint8_t *)now->iov_base + skip;
    now->iov_len -= skip;
    return now;
}

#ifdef RED_STATISTICS

#define STAT_TAB_LEN 4
#define STAT_VALUE_TABS 7

static void print_stat_tree(uint32_t node_index, int depth)
{
    StatNode *node = &reds->stat->nodes[node_index];

    if ((node->flags & STAT_NODE_MASK_SHOW) == STAT_NODE_MASK_SHOW) {
        core->term_printf(core, "%*s%s", depth * STAT_TAB_LEN, "", node->name);
        if (node->flags & STAT_NODE_FLAG_VALUE) {
            core->term_printf(core, ":%*s%llu\n",
                              (STAT_VALUE_TABS - depth) * STAT_TAB_LEN - strlen(node->name) - 1, "",
                              node->value);
        } else {
            core->term_printf(core, "\n");
            if (node->first_child_index != INVALID_STAT_REF) {
                print_stat_tree(node->first_child_index, depth + 1);
            }
        }
    }
    if (node->next_sibling_index != INVALID_STAT_REF) {
        print_stat_tree(node->next_sibling_index, depth);
    }
}

static void do_info_statistics()
{
    core->term_printf(core, "Spice Statistics:\n");
    print_stat_tree(reds->stat->root_index, 0);
}

static void do_reset_statistics()
{
    StatNode *node;
    int i;

    for (i = 0; i <= REDS_MAX_STAT_NODES; i++) {
        node = &reds->stat->nodes[i];
        if (node->flags & STAT_NODE_FLAG_VALUE) {
            node->value = 0;
        }
    }
}

static void do_reset_statistics_2(const VDICmdArg* args)
{
    if (!args_is_empty(args)) {
        red_printf("invalid args");
        return;
    }

    do_reset_statistics();
}

void insert_stat_node(StatNodeRef parent, StatNodeRef ref)
{
    StatNode *node = &reds->stat->nodes[ref];
    uint32_t pos = INVALID_STAT_REF;
    uint32_t node_index;
    uint32_t *head;
    StatNode *n;

    node->first_child_index = INVALID_STAT_REF;
    head = (parent == INVALID_STAT_REF ? &reds->stat->root_index :
                                         &reds->stat->nodes[parent].first_child_index);
    node_index = *head;
    while (node_index != INVALID_STAT_REF && (n = &reds->stat->nodes[node_index]) &&
                                                     strcmp(node->name, n->name) > 0) {
        pos = node_index;
        node_index = n->next_sibling_index;
    }
    if (pos == INVALID_STAT_REF) {
        node->next_sibling_index = *head;
        *head = ref;
    } else {
        n = &reds->stat->nodes[pos];
        node->next_sibling_index = n->next_sibling_index;
        n->next_sibling_index = ref;
    }
}

StatNodeRef stat_add_node(StatNodeRef parent, const char *name, int visible)
{
    StatNodeRef ref;
    StatNode *node;

    ASSERT(name && strlen(name) > 0);
    if (strlen(name) >= sizeof(node->name)) {
        return INVALID_STAT_REF;
    }
    pthread_mutex_lock(&reds->stat_lock);
    ref = (parent == INVALID_STAT_REF ? reds->stat->root_index :
                                        reds->stat->nodes[parent].first_child_index);
    while (ref != INVALID_STAT_REF) {
        node = &reds->stat->nodes[ref];
        if (strcmp(name, node->name)) {
            ref = node->next_sibling_index;
        } else {
            pthread_mutex_unlock(&reds->stat_lock);
            return ref;
        }
    }
    if (reds->stat->num_of_nodes >= REDS_MAX_STAT_NODES || reds->stat == NULL) {
        pthread_mutex_unlock(&reds->stat_lock);
        return INVALID_STAT_REF;
    }
    reds->stat->generation++;
    reds->stat->num_of_nodes++;
    for (ref = 0; ref <= REDS_MAX_STAT_NODES; ref++) {
        node = &reds->stat->nodes[ref];
        if (!(node->flags & STAT_NODE_FLAG_ENABLED)) {
            break;
        }
    }
    ASSERT(!(node->flags & STAT_NODE_FLAG_ENABLED));
    node->value = 0;
    node->flags = STAT_NODE_FLAG_ENABLED | (visible ? STAT_NODE_FLAG_VISIBLE : 0);
    strncpy(node->name, name, sizeof(node->name));
    insert_stat_node(parent, ref);
    pthread_mutex_unlock(&reds->stat_lock);
    return ref;
}

void stat_remove(StatNode *node)
{
    pthread_mutex_lock(&reds->stat_lock);
    node->flags &= ~STAT_NODE_FLAG_ENABLED;
    reds->stat->generation++;
    reds->stat->num_of_nodes--;
    pthread_mutex_unlock(&reds->stat_lock);
}

void stat_remove_node(StatNodeRef ref)
{
    stat_remove(&reds->stat->nodes[ref]);
}

uint64_t *stat_add_counter(StatNodeRef parent, const char *name, int visible)
{
    StatNodeRef ref = stat_add_node(parent, name, visible);
    StatNode *node;

    if (ref == INVALID_STAT_REF) {
        return NULL;
    }
    node = &reds->stat->nodes[ref];
    node->flags |= STAT_NODE_FLAG_VALUE;
    return &node->value;
}

void stat_remove_counter(uint64_t *counter)
{
    stat_remove((StatNode *)(counter - offsetof(StatNode, value)));
}

static void reds_update_stat_value(RedsStatValue* stat_value, uint32_t value)
{
    stat_value->value = value;
    stat_value->min = (stat_value->count ? MIN(stat_value->min, value) : value);
    stat_value->max = MAX(stat_value->max, value);
    stat_value->average = (stat_value->average * stat_value->count + value) /
                          (stat_value->count + 1);
    stat_value->count++;
}

#endif

void reds_register_channel(Channel *channel)
{
    ASSERT(reds);
    channel->next = reds->channels;
    reds->channels = channel;
    reds->num_of_channels++;
}

void reds_unregister_channel(Channel *channel)
{
    Channel **now = &reds->channels;

    while (*now) {
        if (*now == channel) {
            *now = channel->next;
            reds->num_of_channels--;
            return;
        }
        now = &(*now)->next;
    }
    red_printf("not found");
}

static Channel *reds_find_channel(uint32_t type, uint32_t id)
{
    Channel *channel = reds->channels;
    while (channel && !(channel->type == type && channel->id == id)) {
        channel = channel->next;
    }
    return channel;
}

static void reds_shatdown_channels()
{
    Channel *channel = reds->channels;
    while (channel) {
        channel->shutdown(channel);
        channel = channel->next;
    }
}

static void reds_mig_cleanup()
{
    if (reds->mig_inprogress) {
        reds->mig_inprogress = FALSE;
        reds->mig_wait_connect = FALSE;
        reds->mig_wait_disconnect = FALSE;
        core->disarm_timer(core, reds->mig_timer);
        mig->notifier_done(mig, reds->mig_notifier);
    }
}

static void reds_reset_vdp()
{
    VDIPortState *state = &reds->agent_state;

    while (!ring_is_empty(&state->write_queue)) {
        VDIPortBuf *buf;
        RingItem *item;

        item = ring_get_tail(&state->write_queue);
        ring_remove(item);
        buf = (VDIPortBuf *)item;
        buf->free(buf);
    }
    state->read_state = VDI_PORT_READ_STATE_READ_HADER;
    state->recive_pos = (uint8_t *)&state->vdi_chunk_header;
    state->recive_len = sizeof(state->vdi_chunk_header);
    state->message_recive_len = 0;
    if (state->current_read_buf) {
        ring_add(&state->read_bufs, &state->current_read_buf->out_item.link);
        state->current_read_buf = NULL;
    }
    state->client_agent_started = FALSE;
    state->send_tokens = 0;
}

static void reds_reset_outgoing()
{
    RedsOutgoingData *outgoing = &reds->outgoing;
    RingItem *ring_item;

    if (outgoing->item) {
        outgoing->item->release(outgoing->item);
        outgoing->item = NULL;
    }
    while ((ring_item = ring_get_tail(&outgoing->pipe))) {
        RedsOutItem *out_item = (RedsOutItem *)ring_item;
        ring_remove(ring_item);
        out_item->release(out_item);
    }
    outgoing->vec_size = 0;
    outgoing->vec = outgoing->vec_buf;
}

static void reds_disconnect()
{
    if (!reds->peer || reds->disconnecting) {
        return;
    }

    red_printf("");
    LOG_MESSAGE(VD_LOG_INFO, "user disconnected");
    reds->disconnecting = TRUE;
    reds_reset_outgoing();

    if (reds->agent_state.plug_ref != INVALID_VD_OBJECT_REF) {
        ASSERT(vdagent);
        vdagent->unplug(vdagent, reds->agent_state.plug_ref);
        reds->agent_state.plug_ref = INVALID_VD_OBJECT_REF;
        reds_reset_vdp();
    }

    reds_shatdown_channels();
    core->set_file_handlers(core, reds->peer->socket, NULL, NULL, NULL);
    reds->peer->cb_free(reds->peer);
    reds->peer = NULL;
    reds->in_handler.shut = TRUE;
    reds->link_id = 0;
    reds->serial = 0;
    reds->ping_id = 0;
    reds->net_test_id = 0;
    reds->net_test_stage = NET_TEST_STAGE_INVALID;
    reds->in_handler.end_pos = 0;

    bitrate_per_sec = ~0;
    letancy = 0;

    reds_mig_cleanup();
    reds->disconnecting = FALSE;
}

static void reds_mig_disconnect()
{
    if (reds->peer) {
        reds_disconnect();
    } else {
        reds_mig_cleanup();
    }
}

static int handle_incoming(RedsStreamContext *peer, IncomingHandler *handler)
{
    for (;;) {
        uint8_t *buf = handler->buf;
        uint32_t pos = handler->end_pos;
        uint8_t *end = buf + pos;
        RedDataHeader *header;
        int n;
        n = peer->cb_read(peer->ctx, buf + pos, RECIVE_BUF_SIZE - pos);
        if (n <= 0) {
            if (n == 0) {
                return -1;
            }
            switch (errno) {
            case EAGAIN:
                return 0;
            case EINTR:
                break;
            case EPIPE:
                return -1;
            default:
                red_printf("%s", strerror(errno));
                return -1;
            }
        } else {
            pos += n;
            end = buf + pos;
            while (buf + sizeof(RedDataHeader) <= end &&
                   buf + sizeof(RedDataHeader) + (header = (RedDataHeader *)buf)->size <= end) {
                buf += sizeof(RedDataHeader) + header->size;
                handler->handle_message(handler->opaque, header);

                if (handler->shut) {
                    return -1;
                }
            }
            memmove(handler->buf, buf, (handler->end_pos = end - buf));
        }
    }
}

static int handle_outgoing(RedsStreamContext *peer, OutgoingHandler *handler)
{
    if (!handler->length) {
        return 0;
    }

    while (handler->length) {
        int n;

        n = peer->cb_write(peer->ctx, handler->now, handler->length);
        if (n <= 0) {
            if (n == 0) {
                return -1;
            }
            switch (errno) {
            case EAGAIN:
                return 0;
            case EINTR:
                break;
            case EPIPE:
                return -1;
            default:
                red_printf("%s", strerror(errno));
                return -1;
            }
        } else {
            handler->now += n;
            handler->length -= n;
        }
    }
    handler->select(handler->opaque, FALSE);
    handler->may_write(handler->opaque);
    return 0;
}

#define OUTGOING_OK 0
#define OUTGOING_FAILED -1
#define OUTGOING_BLOCKED 1

static int outgoing_write(RedsStreamContext *peer, OutgoingHandler *handler, void *in_data,
                          int length)
{
    uint8_t *data = in_data;
    ASSERT(length <= SEND_BUF_SIZE);
    if (handler->length) {
        return OUTGOING_BLOCKED;
    }

    while (length) {
        int n = peer->cb_write(peer->ctx, data, length);
        if (n < 0) {
            switch (errno) {
            case EAGAIN:
                handler->length = length;
                memcpy(handler->buf, data, length);
                handler->select(handler->opaque, TRUE);
                return OUTGOING_OK;
            case EINTR:
                break;
            case EPIPE:
                return OUTGOING_FAILED;
            default:
                red_printf("%s", strerror(errno));
                return OUTGOING_FAILED;
            }
        } else {
            data += n;
            length -= n;
        }
    }
    return OUTGOING_OK;
}

typedef struct SimpleOutItem {
    RedsOutItem base;
    RedDataHeader header;
    uint8_t data[0];
} SimpleOutItem;

static void reds_prepare_basic_out_item(RedsOutItem *in_item, struct iovec* vec, int *len)
{
    SimpleOutItem *item = (SimpleOutItem *)in_item;

    vec[0].iov_base = &item->header;
    vec[0].iov_len = sizeof(item->header);
    if (item->header.size) {
        vec[1].iov_base = item->data;
        vec[1].iov_len = item->header.size;
        *len = 2;
    } else {
        *len = 1;
    }
}

static void reds_free_basic_out_item(RedsOutItem *item)
{
    free(item);
}

static SimpleOutItem *new_simple_out_item(uint32_t type, int message_size)
{
    SimpleOutItem *item;

    if (!(item = (SimpleOutItem *)malloc(sizeof(*item) + message_size))) {
        return NULL;
    }
    ring_item_init(&item->base.link);
    item->base.prepare = reds_prepare_basic_out_item;
    item->base.release = reds_free_basic_out_item;

    item->header.serial = ++reds->serial;
    item->header.type = type;
    item->header.size = message_size;
    item->header.sub_list = 0;

    return item;
}

static void reds_push_pipe_item(RedsOutItem *item)
{
    ring_add(&reds->outgoing.pipe, &item->link);
    reds_push();
}

static void reds_send_channels()
{
    RedChannels* channels_info;
    SimpleOutItem *item;
    int message_size;
    Channel *channel;
    int i;

    message_size = sizeof(RedChannels) + reds->num_of_channels * sizeof(RedChannelInit);
    if (!(item = new_simple_out_item(RED_CHANNELS_LIST, message_size))) {
        red_printf("alloc item failed");
        reds_disconnect();
        return;
    }
    channels_info = (RedChannels *)item->data;
    channels_info->num_of_channels = reds->num_of_channels;
    channel = reds->channels;

    for (i = 0; i < reds->num_of_channels; i++) {
        ASSERT(channel);
        channels_info->channels[i].type = channel->type;
        channels_info->channels[i].id = channel->id;
        channel = channel->next;
    }
    reds_push_pipe_item(&item->base);
}

static void reds_prepare_ping_item(RedsOutItem *in_item, struct iovec* vec, int *len)
{
    PingItem *item = (PingItem *)in_item;

    vec[0].iov_base = &item->header;
    vec[0].iov_len = sizeof(item->header);
    vec[1].iov_base = &item->ping;
    vec[1].iov_len = sizeof(item->ping);
    int size = item->size;
    int pos = 2;
    while (size) {
        ASSERT(pos < REDS_MAX_SEND_IOVEC);
        int now = MIN(ZERO_BUF_SIZE, size);
        size -= now;
        vec[pos].iov_base = zero_page;
        vec[pos].iov_len = now;
        pos++;
    }
    *len = pos;
}

static void reds_free_ping_item(RedsOutItem *item)
{
    free(item);
}

static int send_ping(int size)
{
    struct timespec time_space;
    PingItem *item;

    if (!reds->peer || !(item = (PingItem *)malloc(sizeof(*item)))) {
        return FALSE;
    }
    ring_item_init(&item->base.link);
    item->base.prepare = reds_prepare_ping_item;
    item->base.release = reds_free_ping_item;

    item->header.serial = ++reds->serial;
    item->header.type = RED_PING;
    item->header.size = sizeof(item->ping) + size;
    item->header.sub_list = 0;

    item->ping.id = ++reds->ping_id;
    clock_gettime(CLOCK_MONOTONIC, &time_space);
    item->ping.timestamp = time_space.tv_sec * 1000000LL + time_space.tv_nsec / 1000LL;

    item->size = size;
    reds_push_pipe_item(&item->base);
    return TRUE;
}

#ifdef RED_STATISTICS

static void do_ping_client(const char *opt, int has_interval, int interval)
{
    if (!reds->peer) {
        red_printf("not connected to peer");
        return;
    }

    if (!opt) {
        send_ping(0);
    } else if (!strcmp(opt, "on")) {
        if (has_interval && interval > 0) {
            reds->ping_interval = interval * 1000;
        }
        core->arm_timer(core, reds->ping_timer, reds->ping_interval);
        core->term_printf(core, "ping on, interval %u s\n", reds->ping_interval / 1000);
    } else if (!strcmp(opt, "off")) {
        core->disarm_timer(core, reds->ping_timer);
        core->term_printf(core, "ping off\n");
    } else {
        core->term_printf(core, "ping invalid option: %s\n", opt);
        return;
    }
}

static void do_ping_client_2(const VDICmdArg* args)
{
    if (args_is_empty(args)) {
        do_ping_client(NULL, FALSE, 0);
        return;
    }

    if (!args_is_string(args)) {
        red_printf("invalid args");
        return;
    }

    if (args_is_empty(&args[1])) {
        do_ping_client(args[0].string_val, FALSE, 0);
        return;
    }

    if (!args_is_int(&args[1])) {
        red_printf("invalid args");
        return;
    }

    do_ping_client(args[0].string_val, TRUE, args[1].int_val);
}

static void ping_timer_cb()
{
    if (!reds->peer) {
        red_printf("not connected to peer, ping off");
        core->disarm_timer(core, reds->ping_timer);
        return;
    }
    do_ping_client(NULL, 0, 0);
    core->arm_timer(core, reds->ping_timer, reds->ping_interval);
}

static void do_info_rtt_client()
{
    core->term_printf(core, "rtt=%uus, min/max/avg=%u/%u/%uus\n", reds->roundtrip_stat.value,
                      reds->roundtrip_stat.min, reds->roundtrip_stat.max,
                      reds->roundtrip_stat.average);
}

#endif

static void reds_send_mouse_mode()
{
    RedMouseMode *mouse_mode;
    SimpleOutItem *item;

    if (!reds->peer) {
        return;
    }

    if (!(item = new_simple_out_item(RED_MOUSE_MODE, sizeof(RedMouseMode)))) {
        red_printf("alloc item failed");
        reds_disconnect();
        return;
    }
    mouse_mode = (RedMouseMode *)item->data;
    mouse_mode->supported_modes = RED_MOUSE_MODE_SERVER;
    if (reds->is_client_mouse_allowed) {
        mouse_mode->supported_modes |= RED_MOUSE_MODE_CLIENT;
    }
    mouse_mode->current_mode = reds->mouse_mode;
    reds_push_pipe_item(&item->base);
}

static void reds_set_mouse_mode(uint32_t mode)
{
    if (reds->mouse_mode == mode) {
        return;
    }
    reds->mouse_mode = mode;
    red_dispatcher_set_mouse_mode(reds->mouse_mode);
    reds_send_mouse_mode();
}

static void reds_update_mouse_mode()
{
    int allowed = 0;
    int qxl_count = red_dispatcher_qxl_count();

    if ((agent_mouse && vdagent) || (tablet && qxl_count == 1)) {
        allowed = reds->dispatcher_allows_client_mouse;
    }
    if (allowed == reds->is_client_mouse_allowed) {
        return;
    }
    reds->is_client_mouse_allowed = allowed;
    if (reds->mouse_mode == RED_MOUSE_MODE_CLIENT && !allowed) {
        reds_set_mouse_mode(RED_MOUSE_MODE_SERVER);
        return;
    }
    reds_send_mouse_mode();
}

static void reds_send_agent_connected()
{
    SimpleOutItem *item;
    if (!(item = new_simple_out_item(RED_AGENT_CONNECTED, 0))) {
        PANIC("alloc item failed");
    }
    reds_push_pipe_item(&item->base);
}

static void reds_send_agent_disconnected()
{
    RedAgentDisconnect *disconnect;
    SimpleOutItem *item;

    if (!(item = new_simple_out_item(RED_AGENT_DISCONNECTED, sizeof(RedAgentDisconnect)))) {
        PANIC("alloc item failed");
    }
    disconnect = (RedAgentDisconnect *)item->data;
    disconnect->error_code = RED_ERR_OK;
    reds_push_pipe_item(&item->base);
}

static void reds_agent_remove()
{
    VDIPortInterface *interface = vdagent;

    vdagent = NULL;
    reds_update_mouse_mode();

    if (!reds->peer || !interface) {
        return;
    }

    ASSERT(reds->agent_state.plug_ref != INVALID_VD_OBJECT_REF);
    interface->unplug(interface, reds->agent_state.plug_ref);
    reds->agent_state.plug_ref = INVALID_VD_OBJECT_REF;

    if (reds->mig_target) {
        return;
    }

    reds_reset_vdp();
    reds_send_agent_disconnected();
}

static void reds_send_tokens()
{
    RedAgentTokens *tokens;
    SimpleOutItem *item;

    if (!reds->peer) {
        return;
    }

    if (!(item = new_simple_out_item(RED_AGENT_TOKEN, sizeof(RedAgentTokens)))) {
        red_printf("alloc item failed");
        reds_disconnect();
        return;
    }
    tokens = (RedAgentTokens *)item->data;
    tokens->num_tokens = reds->agent_state.num_tokens;
    reds->agent_state.num_client_tokens += tokens->num_tokens;
    ASSERT(reds->agent_state.num_client_tokens <= REDS_AGENT_WINDOW_SIZE);
    reds->agent_state.num_tokens = 0;
    reds_push_pipe_item(&item->base);
}

static int write_to_vdi_port()
{
    VDIPortState *state = &reds->agent_state;
    RingItem *ring_item;
    VDIPortBuf *buf;
    int total = 0;
    int n;

    if (reds->agent_state.plug_ref == INVALID_VD_OBJECT_REF || reds->mig_target) {
        return 0;
    }

    for (;;) {
        if (!(ring_item = ring_get_tail(&state->write_queue))) {
            break;
        }
        buf = (VDIPortBuf *)ring_item;
        n = vdagent->write(vdagent, state->plug_ref, buf->now, buf->write_len);
        if (n == 0) {
            break;
        }
        total += n;
        buf->write_len -= n;
        if (!buf->write_len) {
            ring_remove(ring_item);
            buf->free(buf);
            continue;
        }
        buf->now += n;
    }
    return total;
}

static void dispatch_vdi_port_data(int port, VDIReadBuf *buf)
{
    VDIPortState *state = &reds->agent_state;
    switch (port) {
    case VDP_CLIENT_PORT: {
        buf->header.serial = ++reds->serial;
        buf->header.size = buf->len;
        reds_push_pipe_item(&buf->out_item);
        break;
    }
    case VDP_SERVER_PORT:
        ring_add(&state->read_bufs, &buf->out_item.link);
        break;
    default:
        ring_add(&state->read_bufs, &buf->out_item.link);
        red_printf("invalid port");
        reds_agent_remove();
    }
}

static int read_from_vdi_port()
{
    VDIPortState *state = &reds->agent_state;
    VDIReadBuf *dispatch_buf;
    int total = 0;
    int n;

    if (reds->mig_target) {
        return 0;
    }

    while (reds->agent_state.plug_ref != INVALID_VD_OBJECT_REF) {
        switch (state->read_state) {
        case VDI_PORT_READ_STATE_READ_HADER:
            n = vdagent->read(vdagent, state->plug_ref, state->recive_pos, state->recive_len);
            if (!n) {
                return total;
            }
            total += n;
            if ((state->recive_len -= n)) {
                state->recive_pos += n;
                break;
            }
            state->message_recive_len = state->vdi_chunk_header.size;
            state->read_state = VDI_PORT_READ_STATE_GET_BUFF;
        case VDI_PORT_READ_STATE_GET_BUFF: {
            RingItem *item;

            if (!(item = ring_get_head(&state->read_bufs))) {
                return total;
            }

            if (state->vdi_chunk_header.port == VDP_CLIENT_PORT) {
                if (!state->send_tokens) {
                    return total;
                }
                --state->send_tokens;
            }
            ring_remove(item);
            state->current_read_buf = (VDIReadBuf *)item;
            state->recive_pos = state->current_read_buf->data;
            state->recive_len = MIN(state->message_recive_len,
                                    sizeof(state->current_read_buf->data));
            state->current_read_buf->len = state->recive_len;
            state->message_recive_len -= state->recive_len;
            state->read_state = VDI_PORT_READ_STATE_READ_DATA;
        }
        case VDI_PORT_READ_STATE_READ_DATA:
            n = vdagent->read(vdagent, state->plug_ref, state->recive_pos, state->recive_len);
            if (!n) {
                return total;
            }
            total += n;
            if ((state->recive_len -= n)) {
                state->recive_pos += n;
                break;
            }
            dispatch_buf = state->current_read_buf;
            state->current_read_buf = NULL;
            state->recive_pos = NULL;
            if (state->message_recive_len == 0) {
                state->read_state = VDI_PORT_READ_STATE_READ_HADER;
                state->recive_pos = (uint8_t *)&state->vdi_chunk_header;
                state->recive_len = sizeof(state->vdi_chunk_header);
            } else {
                state->read_state = VDI_PORT_READ_STATE_GET_BUFF;
            }
            dispatch_vdi_port_data(state->vdi_chunk_header.port, dispatch_buf);
        }
    }
    return total;
}

static void reds_agent_wakeup(VDIPortPlug *plug)
{
    while (write_to_vdi_port() || read_from_vdi_port());
}

static void reds_handle_agent_mouse_event()
{
    RingItem *ring_item;
    VDInternalBuf *buf;

    if (!reds->inputs_state) {
        return;
    }
    if (reds->mig_target || !(ring_item = ring_get_head(&reds->agent_state.internal_bufs))) {
        reds->inputs_state->pending_mouse_event = TRUE;
        return;
    }
    reds->inputs_state->pending_mouse_event = FALSE;
    ring_remove(ring_item);
    buf = (VDInternalBuf *)ring_item;
    buf->base.now = (uint8_t *)&buf->base.chunk_header;
    buf->base.write_len = sizeof(VDIChunkHeader) + sizeof(VDAgentMessage) +
                          sizeof(VDAgentMouseState);
    buf->u.mouse_state = reds->inputs_state->mouse_state;
    ring_add(&reds->agent_state.write_queue, &buf->base.link);
    write_to_vdi_port();
}

static void add_token()
{
    VDIPortState *state = &reds->agent_state;

    if (++state->num_tokens == REDS_TOKENS_TO_SEND) {
        reds_send_tokens();
    }
}

typedef struct MainMigrateData {
    uint32_t version;
    uint32_t serial;
    uint32_t ping_id;

    uint32_t agent_connected;
    uint32_t client_agent_started;
    uint32_t num_client_tokens;
    uint32_t send_tokens;

    uint32_t read_state;
    VDIChunkHeader vdi_chunk_header;
    uint32_t recive_len;
    uint32_t message_recive_len;
    uint32_t read_buf_len;

    uint32_t write_queue_size;
} MainMigrateData;

#define MAIN_CHANNEL_MIG_DATA_VERSION 1

typedef struct WriteQueueInfo {
    uint32_t port;
    uint32_t len;
} WriteQueueInfo;

typedef struct SendMainMigrateItem {
    RedsOutItem base;
    RedDataHeader header;
    MainMigrateData data;
    WriteQueueInfo queue_info[REDS_AGENT_WINDOW_SIZE + REDS_NUM_INTERNAL_AGENT_MESSAGES];
} SendMainMigrateItem;

static void main_channel_send_migrate_data_item(RedsOutItem *in_item, struct iovec* vec_start,
                                                int *len)
{
    SendMainMigrateItem *item = (SendMainMigrateItem *)in_item;
    VDIPortState *state = &reds->agent_state;
    struct iovec* vec;
    int buf_index;
    RingItem *now;

    vec = vec_start;

    item->header.serial = ++reds->serial;
    item->header.type = RED_MIGRATE_DATA;
    item->header.size = sizeof(item->data);
    item->header.sub_list = 0;

    vec[0].iov_base = &item->header;
    vec[0].iov_len = sizeof(item->header);
    vec[1].iov_base = &item->data;
    vec[1].iov_len = sizeof(item->data);

    vec += 2;
    *len = 2;

    item->data.version = MAIN_CHANNEL_MIG_DATA_VERSION;
    item->data.serial = reds->serial;
    item->data.ping_id = reds->ping_id;

    item->data.agent_connected = !!state->plug_ref;
    item->data.client_agent_started = state->client_agent_started;
    item->data.num_client_tokens = state->num_client_tokens;
    item->data.send_tokens = state->send_tokens;

    item->data.read_state = state->read_state;
    item->data.vdi_chunk_header = state->vdi_chunk_header;
    item->data.recive_len = state->recive_len;
    item->data.message_recive_len = state->message_recive_len;


    if (state->current_read_buf) {
        item->data.read_buf_len = state->current_read_buf->len;
        if ((vec->iov_len = item->data.read_buf_len - item->data.recive_len)) {
            vec->iov_base = state->current_read_buf->data;
            item->header.size += vec->iov_len;
            vec++;
            (*len)++;
        }
    } else {
        item->data.read_buf_len = 0;
    }

    now = &state->write_queue;
    item->data.write_queue_size = 0;
    while ((now = ring_prev(&state->write_queue, now))) {
        item->data.write_queue_size++;
    }
    if (!item->data.write_queue_size) {
        return;
    }
    ASSERT(item->data.write_queue_size <= sizeof(item->queue_info) / sizeof(item->queue_info[0]));
    vec->iov_base = item->queue_info;
    vec->iov_len = item->data.write_queue_size * sizeof(item->queue_info[0]);
    item->header.size += vec->iov_len;
    vec++;
    (*len)++;

    buf_index = 0;
    now = &state->write_queue;
    while ((now = ring_prev(&state->write_queue, now))) {
        VDIPortBuf *buf = (VDIPortBuf *)now;
        item->queue_info[buf_index].port = buf->chunk_header.port;
        item->queue_info[buf_index++].len = buf->write_len;
        ASSERT(vec - vec_start < REDS_MAX_SEND_IOVEC);
        vec->iov_base = buf->now;
        vec->iov_len = buf->write_len;
        item->header.size += vec->iov_len;
        vec++;
        (*len)++;
    }
}

static void main_channelrelease_migrate_data_item(RedsOutItem *in_item)
{
    SendMainMigrateItem *item = (SendMainMigrateItem *)in_item;
    free(item);
}

static void main_channel_push_migrate_data_item()
{
    SendMainMigrateItem *item;

    if (!(item = (SendMainMigrateItem *)malloc(sizeof(*item)))) {
        PANIC("malloc failed");
    }
    memset(item, 0, sizeof(*item));
    ring_item_init(&item->base.link);
    item->base.prepare = main_channel_send_migrate_data_item;
    item->base.release = main_channelrelease_migrate_data_item;

    reds_push_pipe_item((RedsOutItem *)item);
}

static int main_channel_restore_vdi_read_state(MainMigrateData *data, uint8_t **in_pos,
                                               uint8_t *end)
{
    VDIPortState *state = &reds->agent_state;
    uint8_t *pos = *in_pos;
    RingItem *ring_item;

    state->read_state = data->read_state;
    state->vdi_chunk_header = data->vdi_chunk_header;
    state->recive_len = data->recive_len;
    state->message_recive_len = data->message_recive_len;

    switch (state->read_state) {
    case VDI_PORT_READ_STATE_READ_HADER:
        if (data->read_buf_len) {
            red_printf("unexpected recive buf");
            reds_disconnect();
            return FALSE;
        }
        state->recive_pos = (uint8_t *)(&state->vdi_chunk_header + 1) - state->recive_len;
        break;
    case VDI_PORT_READ_STATE_GET_BUFF:
        if (state->message_recive_len > state->vdi_chunk_header.size) {
            red_printf("invalid message recive len");
            reds_disconnect();
            return FALSE;
        }

        if (data->read_buf_len) {
            red_printf("unexpected recive buf");
            reds_disconnect();
            return FALSE;
        }
        break;
    case VDI_PORT_READ_STATE_READ_DATA: {
        VDIReadBuf *buff;
        uint32_t n;

        if (!data->read_buf_len) {
            red_printf("read state and read_buf_len == 0");
            reds_disconnect();
            return FALSE;
        }

        if (state->message_recive_len > state->vdi_chunk_header.size) {
            red_printf("invalid message recive len");
            reds_disconnect();
            return FALSE;
        }


        if (!(ring_item = ring_get_head(&state->read_bufs))) {
            red_printf("get read buf failed");
            reds_disconnect();
            return FALSE;
        }

        ring_remove(ring_item);
        buff = state->current_read_buf = (VDIReadBuf *)ring_item;
        buff->len = data->read_buf_len;
        n = buff->len - state->recive_len;
        if (buff->len > RED_AGENT_MAX_DATA_SIZE || n > RED_AGENT_MAX_DATA_SIZE) {
            red_printf("bad read position");
            reds_disconnect();
            return FALSE;
        }
        memcpy(buff->data, pos, n);
        pos += n;
        state->recive_pos = buff->data + n;
        break;
    }
    default:
        red_printf("invalid read state");
        reds_disconnect();
        return FALSE;
    }
    *in_pos = pos;
    return TRUE;
}

static void free_tmp_internal_buf(VDIPortBuf *buf)
{
    free(buf);
}

static int main_channel_restore_vdi_wqueue(MainMigrateData *data, uint8_t *pos, uint8_t *end)
{
    VDIPortState *state = &reds->agent_state;
    WriteQueueInfo *inf;
    WriteQueueInfo *inf_end;
    RingItem *ring_item;

    if (!data->write_queue_size) {
        return TRUE;
    }

    inf = (WriteQueueInfo *)pos;
    inf_end = inf + data->write_queue_size;
    pos = (uint8_t *)inf_end;
    if (pos > end) {
        red_printf("access violation");
        reds_disconnect();
        return FALSE;
    }

    for (; inf < inf_end; inf++) {
        if (pos + inf->len > end) {
            red_printf("access violation");
            reds_disconnect();
            return FALSE;
        }
        if (inf->port == VDP_SERVER_PORT) {
            VDInternalBuf *buf;

            if (inf->len > sizeof(*buf) - OFFSETOF(VDInternalBuf, header)) {
                red_printf("bad buffer len");
                reds_disconnect();
                return FALSE;
            }
            if (!(buf = malloc(sizeof(VDInternalBuf)))) {
                red_printf("no internal buff");
                reds_disconnect();
                return FALSE;
            }
            ring_item_init(&buf->base.link);
            buf->base.free = free_tmp_internal_buf;
            buf->base.now = (uint8_t *)&buf->base.chunk_header;
            buf->base.write_len = inf->len;
            memcpy(buf->base.now, pos, buf->base.write_len);
            ring_add(&reds->agent_state.write_queue, &buf->base.link);
        } else if (inf->port == VDP_CLIENT_PORT) {
            VDAgentExtBuf *buf;

            state->num_tokens--;
            if (inf->len > sizeof(*buf) - OFFSETOF(VDAgentExtBuf, buf)) {
                red_printf("bad buffer len");
                reds_disconnect();
                return FALSE;
            }
            if (!(ring_item = ring_get_head(&reds->agent_state.external_bufs))) {
                red_printf("no external buff");
                reds_disconnect();
                return FALSE;
            }
            ring_remove(ring_item);
            buf = (VDAgentExtBuf *)ring_item;
            memcpy(&buf->buf, pos, inf->len);
            buf->base.now = (uint8_t *)buf->buf;
            buf->base.write_len = inf->len;
            ring_add(&reds->agent_state.write_queue, &buf->base.link);
        } else {
            red_printf("invalid data");
            reds_disconnect();
            return FALSE;
        }
        pos += inf->len;
    }
    return TRUE;
}

static void main_channel_recive_migrate_data(MainMigrateData *data, uint8_t *end)
{
    VDIPortState *state = &reds->agent_state;
    uint8_t *pos;

    if (data->version != MAIN_CHANNEL_MIG_DATA_VERSION) {
        red_printf("version mismatch");
        reds_disconnect();
        return;
    }

    reds->serial = data->serial;
    reds->ping_id = data->ping_id;

    state->num_client_tokens = data->num_client_tokens;
    ASSERT(state->num_client_tokens + data->write_queue_size <= REDS_AGENT_WINDOW_SIZE +
                                                                REDS_NUM_INTERNAL_AGENT_MESSAGES);
    state->num_tokens = REDS_AGENT_WINDOW_SIZE - state->num_client_tokens;
    state->send_tokens = data->send_tokens;


    if (!data->agent_connected) {
        if (state->plug_ref) {
            reds_send_agent_connected();
        }
        return;
    }

    if (state->plug_ref == INVALID_VD_OBJECT_REF) {
        reds_send_agent_disconnected();
        return;
    }

    if (state->plug_generation > 1) {
        reds_send_agent_disconnected();
        reds_send_agent_connected();
        return;
    }

    state->client_agent_started = data->client_agent_started;

    pos = (uint8_t *)(data + 1);

    if (!main_channel_restore_vdi_read_state(data, &pos, end)) {
        return;
    }

    main_channel_restore_vdi_wqueue(data, pos, end);
    ASSERT(state->num_client_tokens + state->num_tokens == REDS_AGENT_WINDOW_SIZE);
}

static void reds_main_handle_message(void *opaque, RedDataHeader *message)
{
    switch (message->type) {
    case REDC_AGENT_START: {
        RedcAgentTokens *agent_start;

        red_printf("agent start");
        if (!reds->peer) {
            return;
        }
        agent_start = (RedcAgentTokens *)(message + 1);
        reds->agent_state.client_agent_started = TRUE;
        reds->agent_state.send_tokens = agent_start->num_tokens;
        read_from_vdi_port();
        break;
    }
    case REDC_AGENT_DATA: {
        RingItem *ring_item;
        VDAgentExtBuf *buf;

        if (!reds->agent_state.num_client_tokens) {
            red_printf("token vailoation");
            reds_disconnect();
            break;
        }
        --reds->agent_state.num_client_tokens;

        if (!vdagent) {
            add_token();
            break;
        }

        if (!reds->agent_state.client_agent_started) {
            red_printf("REDC_AGENT_DATA race");
            add_token();
            break;
        }

        if (message->size > RED_AGENT_MAX_DATA_SIZE) {
            red_printf("invalid agent message");
            reds_disconnect();
            break;
        }

        if (!(ring_item = ring_get_head(&reds->agent_state.external_bufs))) {
            red_printf("no agent free bufs");
            reds_disconnect();
            break;
        }
        ring_remove(ring_item);
        buf = (VDAgentExtBuf *)ring_item;
        buf->base.now = (uint8_t *)&buf->base.chunk_header.port;
        buf->base.write_len = message->size + sizeof(VDIChunkHeader);
        buf->base.chunk_header.size = message->size;
        memcpy(buf->buf, message + 1, message->size);
        ring_add(&reds->agent_state.write_queue, ring_item);
        write_to_vdi_port();
        break;
    }
    case REDC_AGENT_TOKEN: {
        RedcAgentTokens *token;

        if (!reds->agent_state.client_agent_started) {
            red_printf("REDC_AGENT_TOKEN race");
            break;
        }

        token = (RedcAgentTokens *)(message + 1);
        reds->agent_state.send_tokens += token->num_tokens;
        read_from_vdi_port();
        break;
    }
    case REDC_ATTACH_CHANNELS:
        reds_send_channels();
        break;
    case REDC_MIGRATE_CONNECTED:
        red_printf("connected");
        if (reds->mig_wait_connect) {
            reds_mig_cleanup();
        }
        break;
    case REDC_MIGRATE_CONNECT_ERROR:
        red_printf("mig connect error");
        if (reds->mig_wait_connect) {
            reds_mig_cleanup();
        }
        break;
    case REDC_MOUSE_MODE_REQUEST: {
        switch (((RedcMouseModeRequest *)(message + 1))->mode) {
        case RED_MOUSE_MODE_CLIENT:
            if (reds->is_client_mouse_allowed) {
                reds_set_mouse_mode(RED_MOUSE_MODE_CLIENT);
            } else {
                red_printf("client mouse is disabled");
            }
            break;
        case RED_MOUSE_MODE_SERVER:
            reds_set_mouse_mode(RED_MOUSE_MODE_SERVER);
            break;
        default:
            red_printf("unsupported mouse mode");
        }
        break;
    }
    case REDC_PONG: {
        RedPing *ping = (RedPing *)(message + 1);
        uint64_t roundtrip;
        struct timespec ts;

        clock_gettime(CLOCK_MONOTONIC, &ts);
        roundtrip = ts.tv_sec * 1000000LL + ts.tv_nsec / 1000LL - ping->timestamp;

        if (ping->id == reds->net_test_id) {
            switch (reds->net_test_stage) {
            case NET_TEST_STAGE_WARMUP:
                reds->net_test_id++;
                reds->net_test_stage = NET_TEST_STAGE_LATENCY;
                break;
            case NET_TEST_STAGE_LATENCY:
                reds->net_test_id++;
                reds->net_test_stage = NET_TEST_STAGE_RATE;
                letancy = roundtrip;
                break;
            case NET_TEST_STAGE_RATE:
                reds->net_test_id = 0;
                if (roundtrip <= letancy) {
                    // probably high load on client or server result with incorrect values
                    letancy = 0;
                    red_printf("net test: invalid values, letancy %lu roundtrip %lu. assuming high"
                               "bendwidth", letancy, roundtrip);
                    break;
                }
                bitrate_per_sec = (uint64_t)(NET_TEST_BYTES * 8) * 1000000 / (roundtrip - letancy);
                red_printf("net test: letancy %f ms, bitrate %lu bps (%f Mbps)%s",
                           (double)letancy / 1000,
                           bitrate_per_sec,
                           (double)bitrate_per_sec / 1024 / 1024,
                           IS_LOW_BANDWIDTH() ? " LOW BANDWIDTH" : "");
                reds->net_test_stage = NET_TEST_STAGE_INVALID;
                break;
            default:
                red_printf("invalid net test stage, ping id %d test id %d stage %d",
                           ping->id,
                           reds->net_test_id,
                           reds->net_test_stage);
            }
            break;
        }
#ifdef RED_STATISTICS
        reds_update_stat_value(&reds->roundtrip_stat, roundtrip);
        do_info_rtt_client();
#endif
        break;
    }
    case REDC_MIGRATE_FLUSH_MARK:
        main_channel_push_migrate_data_item();
        break;
    case REDC_MIGRATE_DATA:
        main_channel_recive_migrate_data((MainMigrateData *)(message + 1),
                                         (uint8_t *)(message + 1) + message->size);
        reds->mig_target = FALSE;
        while (write_to_vdi_port() || read_from_vdi_port());
        break;
    case REDC_DISCONNECTING:
        break;
    default:
        red_printf("unexpected type %d", message->type);
    }
}

static void reds_main_read(void *data)
{
    if (handle_incoming(reds->peer, &reds->in_handler)) {
        reds_disconnect();
    }
}

static int reds_send_data()
{
    RedsOutgoingData *outgoing = &reds->outgoing;
    int n;

    if (!outgoing->item) {
        return TRUE;
    }

    ASSERT(outgoing->vec_size);
    for (;;) {
        if ((n = reds->peer->cb_writev(reds->peer->ctx, outgoing->vec, outgoing->vec_size)) == -1) {
            switch (errno) {
            case EAGAIN:
                core->set_file_handlers(core, reds->peer->socket, reds_main_read, reds_main_write,
                                        NULL);
                return FALSE;
            case EINTR:
                break;
            case EPIPE:
                reds_disconnect();
                return FALSE;
            default:
                red_printf("%s", strerror(errno));
                reds_disconnect();
                return FALSE;
            }
        } else {
            outgoing->vec = reds_iovec_skip(outgoing->vec, n, &outgoing->vec_size);
            if (!outgoing->vec_size) {
                outgoing->item->release(outgoing->item);
                outgoing->item = NULL;
                outgoing->vec = outgoing->vec_buf;
                return TRUE;
            }
        }
    }
}

static void reds_push()
{
    RedsOutgoingData *outgoing = &reds->outgoing;
    RingItem *item;

    for (;;) {
        if (!reds->peer || outgoing->item || !(item = ring_get_tail(&outgoing->pipe))) {
            return;
        }
        ring_remove(item);
        outgoing->item = (RedsOutItem *)item;
        outgoing->item->prepare(outgoing->item, outgoing->vec_buf, &outgoing->vec_size);
        reds_send_data();
    }
}

static void reds_main_write(void *data)
{
    RedsOutgoingData *outgoing = &reds->outgoing;

    if (reds_send_data()) {
        reds_push();
        if (!outgoing->item) {
            core->set_file_handlers(core, reds->peer->socket, reds_main_read, NULL, NULL);
        }
    }
}

static int sync_write(RedsStreamContext *peer, void *in_buf, size_t n)
{
    uint8_t *buf = (uint8_t *)in_buf;
    while (n) {
        int now = peer->cb_write(peer->ctx, buf, n);
        if (now <= 0) {
            if (now == -1 && (errno == EINTR || errno == EAGAIN)) {
                continue;
            }
            return FALSE;
        }
        n -= now;
        buf += now;
    }
    return TRUE;
}

static int reds_send_link_ack(RedLinkInfo *link)
{
    RedLinkHeader header;
    RedLinkReply ack;
    Channel *channel;
    BUF_MEM *bmBuf;
    BIO *bio;
    int ret;

    header.magic = RED_MAGIC;
    header.size = sizeof(ack);
    header.major_version = RED_VERSION_MAJOR;
    header.minor_version = RED_VERSION_MINOR;

    ack.error = RED_ERR_OK;

    if ((channel = reds_find_channel(link->link_mess->channel_type, 0))) {
        ack.num_common_caps = channel->num_common_caps;
        ack.num_channel_caps = channel->num_caps;
        header.size += (ack.num_common_caps + ack.num_channel_caps) * sizeof(uint32_t);
    } else {
        ack.num_common_caps = 0;
        ack.num_channel_caps = 0;
    }
    ack.caps_offset = sizeof(RedLinkReply);

    if (!(link->tiTicketing.rsa = RSA_new())) {
        red_printf("RSA nes failed");
        return FALSE;
    }

    if (!(bio = BIO_new(BIO_s_mem()))) {
        red_printf("BIO new failed");
        return FALSE;
    }

    RSA_generate_key_ex(link->tiTicketing.rsa, RED_TICKET_KEY_PAIR_LENGTH, link->tiTicketing.bn,
                        NULL);
    link->tiTicketing.rsa_size = RSA_size(link->tiTicketing.rsa);

    i2d_RSA_PUBKEY_bio(bio, link->tiTicketing.rsa);
    BIO_get_mem_ptr(bio, &bmBuf);
    memcpy(ack.pub_key, bmBuf->data, sizeof(ack.pub_key));

    ret = sync_write(link->peer, &header, sizeof(header)) && sync_write(link->peer, &ack,
                                                                        sizeof(ack));
    if (channel) {
        ret = ret && sync_write(link->peer, channel->common_caps,
                                channel->num_common_caps * sizeof(uint32_t)) &&
              sync_write(link->peer, channel->caps, channel->num_caps * sizeof(uint32_t));
    }
    BIO_free(bio);
    return ret;
}

static int reds_send_link_error(RedLinkInfo *link, uint32_t error)
{
    RedLinkHeader header;
    RedLinkReply reply;

    header.magic = RED_MAGIC;
    header.size = sizeof(reply);
    header.major_version = RED_VERSION_MAJOR;
    header.minor_version = RED_VERSION_MINOR;
    memset(&reply, 0, sizeof(reply));
    reply.error = error;
    return sync_write(link->peer, &header, sizeof(header)) && sync_write(link->peer, &reply,
                                                                         sizeof(reply));
}

static void reds_show_new_channel(RedLinkInfo *link)
{
    red_printf("channel %d:%d, connected sucessfully, over %s link",
               link->link_mess->channel_type,
               link->link_mess->channel_id,
               link->peer->ssl == NULL ? "Non Secure" : "Secure");
}

static void reds_send_link_result(RedLinkInfo *link, uint32_t error)
{
    sync_write(link->peer, &error, sizeof(error));
}

static void reds_start_net_test()
{
    if (!reds->peer || reds->net_test_id) {
        return;
    }

    if (send_ping(NET_TEST_WARMUP_BYTES) && send_ping(0) && send_ping(NET_TEST_BYTES)) {
        reds->net_test_id = reds->ping_id - 2;
        reds->net_test_stage = NET_TEST_STAGE_WARMUP;
    }
}

static void reds_handle_main_link(RedLinkInfo *link)
{
    uint32_t connection_id;

    red_printf("");

    reds_disconnect();

    if (!link->link_mess->connection_id) {
        reds_send_link_result(link, RED_ERR_OK);
        while((connection_id = rand()) == 0);
        reds->agent_state.num_tokens = 0;
        reds->agent_state.send_tokens = 0;
        memcpy(&(reds->taTicket), &taTicket, sizeof(reds->taTicket));
        reds->mig_target = FALSE;
    } else {
        if (link->link_mess->connection_id != reds->link_id) {
            reds_send_link_result(link, RED_ERR_BAD_CONNECTION_ID);
            reds_release_link(link);
            return;
        }
        reds_send_link_result(link, RED_ERR_OK);
        connection_id = link->link_mess->connection_id;
        reds->mig_target = TRUE;
    }

    reds->link_id = connection_id;
    reds->mig_inprogress = FALSE;
    reds->mig_wait_connect = FALSE;
    reds->mig_wait_disconnect = FALSE;
    reds->peer = link->peer;
    reds->in_handler.shut = FALSE;
    if (reds->mig_target) {
        LOG_MESSAGE(VD_LOG_INFO, "migrate connection");
    } else {
        LOG_MESSAGE(VD_LOG_INFO, "new user connection");
    }

    reds_show_new_channel(link);
    __reds_release_link(link);
    if (vdagent) {
        reds->agent_state.plug_ref = vdagent->plug(vdagent, &reds->agent_state.plug);
        if (reds->agent_state.plug_ref == INVALID_VD_OBJECT_REF) {
            PANIC("vdagent plug failed");
        }
        reds->agent_state.plug_generation++;
    }
    core->set_file_handlers(core, reds->peer->socket, reds_main_read, NULL, NULL);

    if (!reds->mig_target) {
        SimpleOutItem *item;
        RedInit *init;

        if (!(item = new_simple_out_item(RED_INIT, sizeof(RedInit)))) {
            red_printf("alloc item failed");
            reds_disconnect();
            return;
        }
        init = (RedInit *)item->data;
        init->session_id = connection_id;
        init->display_channels_hint = red_dispatcher_count();
        init->current_mouse_mode = reds->mouse_mode;
        init->supported_mouse_modes = RED_MOUSE_MODE_SERVER;
        if (reds->is_client_mouse_allowed) {
            init->supported_mouse_modes |= RED_MOUSE_MODE_CLIENT;
        }
        init->agent_connected = !!vdagent;
        init->agent_tokens = REDS_AGENT_WINDOW_SIZE;
        reds->agent_state.num_client_tokens = REDS_AGENT_WINDOW_SIZE;
        init->multi_media_time = reds_get_mm_time() - MM_TIME_DELTA;
        init->ram_hint = red_dispatcher_qxl_ram_size();
        reds_push_pipe_item(&item->base);
        reds_start_net_test();
    }
}

#define RED_MOUSE_STATE_TO_LOCAL(state)     \
    ((state & REDC_LBUTTON_MASK) |          \
     ((state & REDC_MBUTTON_MASK) << 1) |   \
     ((state & REDC_RBUTTON_MASK) >> 1))

#define RED_MOUSE_BUTTON_STATE_TO_AGENT(state)                      \
    (((state & REDC_LBUTTON_MASK) ? VD_AGENT_LBUTTON_MASK : 0) |    \
     ((state & REDC_MBUTTON_MASK) ? VD_AGENT_MBUTTON_MASK : 0) |    \
     ((state & REDC_RBUTTON_MASK) ? VD_AGENT_RBUTTON_MASK : 0))

static void activate_modifiers_watch()
{
    core->arm_timer(core, reds->key_modifiers_timer, KEY_MODIFIERS_TTL);
}

static void push_key_scan(uint8_t scan)
{
    if (!keyboard) {
        return;
    }
    keyboard->push_scan_freg(keyboard, scan);
}

static void inputs_handle_input(void *opaque, RedDataHeader *header)
{
    InputsState *state = (InputsState *)opaque;
    uint8_t *buf = (uint8_t *)(header + 1);

    switch (header->type) {
    case REDC_INPUTS_KEY_DOWN: {
        RedcKeyDown *key_up = (RedcKeyDown *)buf;
        if (key_up->code == CAPS_LOCK_SCAN_CODE || key_up->code == NUM_LOCK_SCAN_CODE ||
            key_up->code == SCROLL_LOCK_SCAN_CODE) {
            activate_modifiers_watch();
        }
    }
    case REDC_INPUTS_KEY_UP: {
        RedcKeyDown *key_down = (RedcKeyDown *)buf;
        uint8_t *now = (uint8_t *)&key_down->code;
        uint8_t *end = now + sizeof(key_down->code);
        for (; now < end && *now; now++) {
            push_key_scan(*now);
        }
        break;
    }
    case REDC_INPUTS_MOUSE_MOTION: {
        RedcMouseMotion *mouse_motion = (RedcMouseMotion *)buf;

        if (++state->motion_count % RED_MOTION_ACK_BUNCH == 0) {
            RedDataHeader header;

            header.serial = ++state->serial;
            header.type = RED_INPUTS_MOUSE_MOTION_ACK;
            header.size = 0;
            header.sub_list = 0;
            if (outgoing_write(state->peer, &state->out_handler, &header, sizeof(RedDataHeader))
                                                                                != OUTGOING_OK) {
                red_printf("motion ack failed");
                reds_disconnect();
            }
        }
        if (mouse && reds->mouse_mode == RED_MOUSE_MODE_SERVER) {
            mouse->moution(mouse, mouse_motion->dx, mouse_motion->dy, 0,
                           RED_MOUSE_STATE_TO_LOCAL(mouse_motion->buttons_state));
        }
        break;
    }
    case REDC_INPUTS_MOUSE_POSITION: {
        RedcMousePosition *pos = (RedcMousePosition *)buf;

        if (++state->motion_count % RED_MOTION_ACK_BUNCH == 0) {
            RedDataHeader header;

            header.serial = ++state->serial;
            header.type = RED_INPUTS_MOUSE_MOTION_ACK;
            header.size = 0;
            header.sub_list = 0;
            if (outgoing_write(state->peer, &state->out_handler, &header, sizeof(RedDataHeader))
                                                                                != OUTGOING_OK) {
                red_printf("position ack failed");
                reds_disconnect();
            }
        }
        if (reds->mouse_mode != RED_MOUSE_MODE_CLIENT) {
            break;
        }
        ASSERT((agent_mouse && vdagent) || tablet);
        if (!agent_mouse || !vdagent) {
            tablet->position(tablet, pos->x, pos->y, RED_MOUSE_STATE_TO_LOCAL(pos->buttons_state));
            break;
        }
        VDAgentMouseState *mouse_state = &state->mouse_state;
        mouse_state->x = pos->x;
        mouse_state->y = pos->y;
        mouse_state->buttons = RED_MOUSE_BUTTON_STATE_TO_AGENT(pos->buttons_state);
        mouse_state->display_id = pos->display_id;
        reds_handle_agent_mouse_event();
        break;
    }
    case REDC_INPUTS_MOUSE_PRESS: {
        RedcMousePress *mouse_press = (RedcMousePress *)buf;
        int dz = 0;
        if (mouse_press->button == REDC_MOUSE_UBUTTON) {
            dz = -1;
        } else if (mouse_press->button == REDC_MOUSE_DBUTTON) {
            dz = 1;
        }
        if (reds->mouse_mode == RED_MOUSE_MODE_CLIENT) {
            if (agent_mouse && vdagent) {
                reds->inputs_state->mouse_state.buttons =
                    RED_MOUSE_BUTTON_STATE_TO_AGENT(mouse_press->buttons_state) |
                    (dz == -1 ? VD_AGENT_UBUTTON_MASK : 0) |
                    (dz == 1 ? VD_AGENT_DBUTTON_MASK : 0);
                reds_handle_agent_mouse_event();
            } else if (tablet) {
                tablet->wheel(tablet, dz, RED_MOUSE_STATE_TO_LOCAL(mouse_press->buttons_state));
            }
        } else if (mouse) {
            mouse->moution(mouse, 0, 0, dz, RED_MOUSE_STATE_TO_LOCAL(mouse_press->buttons_state));
        }
        break;
    }
    case REDC_INPUTS_MOUSE_RELEASE: {
        RedcMouseRelease *mouse_release = (RedcMouseRelease *)buf;
        if (reds->mouse_mode == RED_MOUSE_MODE_CLIENT) {
            if (agent_mouse && vdagent) {
                reds->inputs_state->mouse_state.buttons =
                    RED_MOUSE_BUTTON_STATE_TO_AGENT(mouse_release->buttons_state);
                reds_handle_agent_mouse_event();
            } else if (tablet) {
                tablet->buttons(tablet, RED_MOUSE_STATE_TO_LOCAL(mouse_release->buttons_state));
            }
        } else if (mouse) {
            mouse->buttons(mouse, RED_MOUSE_STATE_TO_LOCAL(mouse_release->buttons_state));
        }
        break;
    }
    case REDC_INPUTS_KEY_MODIFAIERS: {
        RedcKeyModifiers *modifiers = (RedcKeyModifiers *)buf;
        if (!keyboard) {
            break;
        }
        uint8_t leds = keyboard->get_leds(keyboard);
        if ((modifiers->modifiers & RED_SCROLL_LOCK_MODIFIER) !=
                                                                (leds & RED_SCROLL_LOCK_MODIFIER)) {
            push_key_scan(SCROLL_LOCK_SCAN_CODE);
            push_key_scan(SCROLL_LOCK_SCAN_CODE | 0x80);
        }
        if ((modifiers->modifiers & RED_NUM_LOCK_MODIFIER) != (leds & RED_NUM_LOCK_MODIFIER)) {
            push_key_scan(NUM_LOCK_SCAN_CODE);
            push_key_scan(NUM_LOCK_SCAN_CODE | 0x80);
        }
        if ((modifiers->modifiers & RED_CAPS_LOCK_MODIFIER) != (leds & RED_CAPS_LOCK_MODIFIER)) {
            push_key_scan(CAPS_LOCK_SCAN_CODE);
            push_key_scan(CAPS_LOCK_SCAN_CODE | 0x80);
        }
        activate_modifiers_watch();
        break;
    }
    case REDC_DISCONNECTING:
        break;
    default:
        red_printf("unexpected type %d", header->type);
    }
}

void reds_set_client_mouse_allowed(int is_client_mouse_allowed, int x_res, int y_res)
{
    reds->monitor_mode.x_res = x_res;
    reds->monitor_mode.y_res = y_res;
    reds->dispatcher_allows_client_mouse = is_client_mouse_allowed;
    reds_update_mouse_mode();
    if (reds->is_client_mouse_allowed && tablet) {
        tablet->set_logical_size(tablet, reds->monitor_mode.x_res, reds->monitor_mode.y_res);
    }
}

static void inputs_relase_keys(void)
{
    push_key_scan(0x2a | 0x80); //LSHIFT
    push_key_scan(0x36 | 0x80); //RSHIFT
    push_key_scan(0xe0); push_key_scan(0x1d | 0x80); //RCTRL
    push_key_scan(0x1d | 0x80); //LCTRL
    push_key_scan(0xe0); push_key_scan(0x38 | 0x80); //RALT
    push_key_scan(0x38 | 0x80); //LALT
}

static void inputs_read(void *data)
{
    InputsState *inputs_state = (InputsState *)data;
    if (handle_incoming(inputs_state->peer, &inputs_state->in_handler)) {
        inputs_relase_keys();
        core->set_file_handlers(core, inputs_state->peer->socket, NULL, NULL, NULL);
        if (inputs_state->channel) {
            inputs_state->channel->data = NULL;
            reds->inputs_state = NULL;
        }
        inputs_state->peer->cb_free(inputs_state->peer);
        free(inputs_state);
    }
}

static void inputs_write(void *data)
{
    InputsState *inputs_state = (InputsState *)data;

    red_printf("");
    if (handle_outgoing(inputs_state->peer, &inputs_state->out_handler)) {
        reds_disconnect();
    }
}

static void inputs_shutdown(Channel *channel)
{
    InputsState *state = (InputsState *)channel->data;
    if (state) {
        state->in_handler.shut = TRUE;
        shutdown(state->peer->socket, SHUT_RDWR);
        channel->data = NULL;
        state->channel = NULL;
        reds->inputs_state = NULL;
    }
}

static void inputs_migrate(Channel *channel)
{
    InputsState *state = (InputsState *)channel->data;
    RedDataHeader header;
    RedMigrate migrate;

    red_printf("");
    header.serial = ++state->serial;
    header.type = RED_MIGRATE;
    header.size = sizeof(migrate);
    header.sub_list = 0;
    migrate.flags = 0;
    if (outgoing_write(state->peer, &state->out_handler, &header, sizeof(header))
                                                                            != OUTGOING_OK ||
        outgoing_write(state->peer, &state->out_handler, &migrate, sizeof(migrate))
                                                                            != OUTGOING_OK) {
        red_printf("write failed");
    }
}

static void inputs_select(void *opaque, int select)
{
    InputsState *inputs_state;
    red_printf("");

    inputs_state = (InputsState *)opaque;
    if (select) {
        core->set_file_handlers(core, inputs_state->peer->socket, inputs_read, inputs_write,
                                inputs_state);
    } else {
        core->set_file_handlers(core, inputs_state->peer->socket, inputs_read, NULL, inputs_state);
    }
}

static void inputs_may_write(void *opaque)
{
    red_printf("");
}

static void inputs_link(Channel *channel, RedsStreamContext *peer, int migration,
                        int num_common_caps, uint32_t *common_caps, int num_caps,
                        uint32_t *caps)
{
    InputsState *inputs_state;
    int delay_val;
    int flags;

    red_printf("");
    ASSERT(channel->data == NULL);

    if (!(inputs_state = malloc(sizeof(InputsState)))) {
        red_printf("alloc input state failed");
        close(peer->socket);
        return;
    }

    delay_val = 1;
    if (setsockopt(peer->socket, IPPROTO_TCP, TCP_NODELAY, &delay_val, sizeof(delay_val)) == -1) {
        red_printf("setsockopt failed, %s", strerror(errno));
    }

    if ((flags = fcntl(peer->socket, F_GETFL)) == -1 ||
                                            fcntl(peer->socket, F_SETFL, flags | O_ASYNC) == -1) {
        red_printf("fcntl failed, %s", strerror(errno));
    }

    memset(inputs_state, 0, sizeof(*inputs_state));
    inputs_state->peer = peer;
    inputs_state->end_pos = 0;
    inputs_state->channel = channel;
    inputs_state->in_handler.opaque = inputs_state;
    inputs_state->in_handler.handle_message = inputs_handle_input;
    inputs_state->out_handler.length = 0;
    inputs_state->out_handler.opaque = inputs_state;
    inputs_state->out_handler.select = inputs_select;
    inputs_state->out_handler.may_write = inputs_may_write;
    inputs_state->pending_mouse_event = FALSE;
    channel->data = inputs_state;
    reds->inputs_state = inputs_state;
    core->set_file_handlers(core, peer->socket, inputs_read, NULL, inputs_state);

    RedDataHeader header;
    RedInputsInit inputs_init;
    header.serial = ++inputs_state->serial;
    header.type = RED_INPUTS_INIT;
    header.size = sizeof(RedInputsInit);
    header.sub_list = 0;
    inputs_init.keyboard_modifiers = keyboard ? keyboard->get_leds(keyboard) : 0;
    if (outgoing_write(inputs_state->peer, &inputs_state->out_handler, &header,
                       sizeof(RedDataHeader)) != OUTGOING_OK ||
        outgoing_write(inputs_state->peer, &inputs_state->out_handler, &inputs_init,
                       sizeof(RedInputsInit)) != OUTGOING_OK) {
        red_printf("failed to send modifiers state");
        reds_disconnect();
    }
}

static void reds_send_keyborad_modifiers(uint8_t modifiers)
{
    Channel *channel = reds_find_channel(RED_CHANNEL_INPUTS, 0);
    InputsState *state;

    if (!channel || !(state = (InputsState *)channel->data)) {
        return;
    }
    ASSERT(state->peer);
    RedDataHeader header;
    RedKeyModifiers key_modifiers;
    header.serial = ++state->serial;
    header.type = RED_INPUTS_KEY_MODIFAIERS;
    header.size = sizeof(RedKeyModifiers);
    header.sub_list = 0;
    key_modifiers.modifiers = modifiers;

    if (outgoing_write(state->peer, &state->out_handler, &header, sizeof(RedDataHeader))
                                                                                != OUTGOING_OK ||
        outgoing_write(state->peer, &state->out_handler, &key_modifiers, sizeof(RedKeyModifiers))
                                                                                != OUTGOING_OK) {
        red_printf("failed to send modifiers state");
        reds_disconnect();
    }
}

static void reds_on_keyborad_leads_change(void *opaque, uint8_t leds)
{
    reds_send_keyborad_modifiers(leds);
}

static void openssl_init(RedLinkInfo *link)
{
    unsigned long f4 = RSA_F4;
    link->tiTicketing.bn = BN_new();

    if (!link->tiTicketing.bn) {
        red_error("OpenSSL BIGNUMS alloc failed");
    }

    BN_set_word(link->tiTicketing.bn, f4);
}

static void inputs_init()
{
    Channel *channel;
    if (!(channel = malloc(sizeof(Channel)))) {
        red_error("alloc inputs chanel failed");
    }
    memset(channel, 0, sizeof(Channel));
    channel->type = RED_CHANNEL_INPUTS;
    channel->link = inputs_link;
    channel->shutdown = inputs_shutdown;
    channel->migrate = inputs_migrate;
    reds_register_channel(channel);
}

static void reds_handle_other_links(RedLinkInfo *link)
{
    Channel *channel;
    RedsStreamContext *peer;
    RedLinkMess *link_mess;
    uint32_t *caps;

    link_mess = link->link_mess;

    if (!reds->link_id || reds->link_id != link_mess->connection_id) {
        reds_send_link_result(link, RED_ERR_BAD_CONNECTION_ID);
        reds_release_link(link);
        return;
    }

    if (!(channel = reds_find_channel(link_mess->channel_type,
                                      link_mess->channel_id))) {
        reds_send_link_result(link, RED_ERR_CHANNEL_NOT_AVAILABLE);
        reds_release_link(link);
        return;
    }

    reds_send_link_result(link, RED_ERR_OK);
    reds_show_new_channel(link);
    if (link_mess->channel_type == RED_CHANNEL_INPUTS && !link->peer->ssl) {
        SimpleOutItem *item;
        RedNotify *notify;
        char *mess = "keybord channel is unsecure";
        const int mess_len = strlen(mess);

        LOG_MESSAGE(VD_LOG_WARN, "%s", mess);

        if (!(item = new_simple_out_item(RED_NOTIFY, sizeof(RedNotify) + mess_len + 1))) {
            red_printf("alloc item failed");
            reds_disconnect();
            return;
        }

        notify = (RedNotify *)item->data;
        notify->time_stamp = get_time_stamp();
        notify->severty = RED_NOTIFY_SEVERITY_WARN;
        notify->visibilty = RED_NOTIFY_VISIBILITY_HIGH;
        notify->what = RED_WARN_GENERAL;
        notify->message_len = mess_len;
        memcpy(notify->message, mess, mess_len + 1);
        reds_push_pipe_item(&item->base);
    }
    peer = link->peer;
    link->link_mess = NULL;
    __reds_release_link(link);
    caps = (uint32_t *)((uint8_t *)link_mess + link_mess->caps_offset);
    channel->link(channel, peer, reds->mig_target, link_mess->num_common_caps,
                  link_mess->num_common_caps ? caps : NULL, link_mess->num_channel_caps,
                  link_mess->num_channel_caps ? caps + link_mess->num_common_caps : NULL);
    free(link_mess);
}

static void reds_handle_ticket(void *opaque)
{
    RedLinkInfo *link = (RedLinkInfo *)opaque;
    char password[RED_MAX_PASSWORD_LENGTH];
    time_t ltime;

    //todo: use monotonic time
    time(&ltime);
    RSA_private_decrypt(link->tiTicketing.rsa_size,
                        link->tiTicketing.encrypted_ticket.encrypted_data,
                        (unsigned char *)password, link->tiTicketing.rsa, RSA_PKCS1_OAEP_PADDING);

    if (ticketing_enabled) {
        int expired = !link->link_mess->connection_id && taTicket.expiration_time < ltime;
        char *actual_sever_pass = link->link_mess->connection_id ? reds->taTicket.password :
                                                                   taTicket.password;
        if (strlen(actual_sever_pass) == 0) {
            reds_send_link_result(link, RED_ERR_PERMISSION_DENIED);
            red_printf("Ticketing is enabled, but no password is set. "
                       "please set a ticket first");
            reds_release_link(link);
            return;
        }

        if (expired || strncmp(password, actual_sever_pass, RED_MAX_PASSWORD_LENGTH) != 0) {
            reds_send_link_result(link, RED_ERR_PERMISSION_DENIED);
            LOG_MESSAGE(VD_LOG_WARN, "bad connection password or time expired");
            reds_release_link(link);
            return;
        }
    }
    if (link->link_mess->channel_type == RED_CHANNEL_MAIN) {
        reds_handle_main_link(link);
    } else {
        reds_handle_other_links(link);
    }
}

static inline void async_read_clear_handlers(AsyncRead *obj)
{
    if (!obj->active_file_handlers) {
        return;
    }
    obj->active_file_handlers = FALSE;
    core->set_file_handlers(core, obj->peer->socket, NULL, NULL, NULL);
}

static void async_read_handler(void *data)
{
    AsyncRead *obj = (AsyncRead *)data;

    for (;;) {
        int n = obj->end - obj->now;

        ASSERT(n > 0);
        if ((n = obj->peer->cb_read(obj->peer->ctx, obj->now, n)) <= 0) {
            if (n < 0) {
                switch (errno) {
                case EAGAIN:
                    if (!obj->active_file_handlers) {
                        obj->active_file_handlers = TRUE;
                        core->set_file_handlers(core, obj->peer->socket, async_read_handler, NULL,
                                                obj);
                    }
                    return;
                case EINTR:
                    break;
                default:
                    async_read_clear_handlers(obj);
                    obj->error(obj->opaque, errno);
                    return;
                }
            } else {
                async_read_clear_handlers(obj);
                obj->error(obj->opaque, 0);
                return;
            }
        } else {
            obj->now += n;
            if (obj->now == obj->end) {
                async_read_clear_handlers(obj);
                obj->done(obj->opaque);
                return;
            }
        }
    }
}

static int reds_security_check(RedLinkInfo *link)
{
    ChannelSecurityOptions *security_option = find_channel_security(link->link_mess->channel_type);
    uint32_t security = security_option ? security_option->options : default_channel_security;
    return (link->peer->ssl && (security & SPICE_CHANNEL_SECURITY_SSL)) ||
        (!link->peer->ssl && (security & SPICE_CHANNEL_SECURITY_NON));
}

static void reds_handle_read_link_done(void *opaque)
{
    RedLinkInfo *link = (RedLinkInfo *)opaque;
    RedLinkMess *link_mess = link->link_mess;
    AsyncRead *obj = &link->asyc_read;
    uint32_t num_caps = link_mess->num_common_caps + link_mess->num_channel_caps;

    if (num_caps && (num_caps * sizeof(uint32_t) + link_mess->caps_offset >
                                                   link->link_header.size ||
                                                     link_mess->caps_offset < sizeof(*link_mess))) {
        reds_send_link_error(link, RED_ERR_INVALID_DATA);
        reds_release_link(link);
        return;
    }

    if (!reds_security_check(link)) {
        if (link->peer->ssl) {
            LOG_MESSAGE(VD_LOG_INFO, "channels of type %d should connect only over "
                                     "a non secure link", link_mess->channel_type);
            red_printf("spice channels %d should not be encrypted", link_mess->channel_type);
            reds_send_link_error(link, RED_ERR_NEED_UNSECURED);
        } else {
            LOG_MESSAGE(VD_LOG_INFO, "channels of type %d should connect only over "
                                     "a secure link", link_mess->channel_type);
            red_printf("spice channels %d should be encrypted", link_mess->channel_type);
            reds_send_link_error(link, RED_ERR_NEED_SECURED);
        }
        reds_release_link(link);
        return;
    }

    if (!reds_send_link_ack(link)) {
        reds_release_link(link);
        return;
    }

    obj->now = (uint8_t *)&link->tiTicketing.encrypted_ticket.encrypted_data;
    obj->end = obj->now + link->tiTicketing.rsa_size;
    obj->done = reds_handle_ticket;
    async_read_handler(&link->asyc_read);
}

static void reds_handle_link_error(void *opaque, int err)
{
    RedLinkInfo *link = (RedLinkInfo *)opaque;
    switch (err) {
    case 0:
    case EPIPE:
        break;
    default:
        red_printf("%s", strerror(errno));
        break;
    }
    reds_release_link(link);
}

static void reds_handle_read_header_done(void *opaque)
{
    RedLinkInfo *link = (RedLinkInfo *)opaque;
    RedLinkHeader *header = &link->link_header;
    AsyncRead *obj = &link->asyc_read;

    if (header->magic != RED_MAGIC) {
        reds_send_link_error(link, RED_ERR_INVALID_MAGIC);
        LOG_MESSAGE(VD_LOG_ERROR, "bad magic %u", header->magic);
        reds_release_link(link);
        return;
    }

    if (header->major_version != RED_VERSION_MAJOR) {
        if (header->major_version > 0) {
            reds_send_link_error(link, RED_ERR_VERSION_MISMATCH);
        }
        LOG_MESSAGE(VD_LOG_INFO, "version mismatch client %u.%u server %u.%u",
                    header->major_version,
                    header->minor_version,
                    RED_VERSION_MAJOR,
                    RED_VERSION_MINOR);

        red_printf("version mismatch");
        reds_release_link(link);
        return;
    }

    reds->peer_minor_version = header->minor_version;

    if (header->size < sizeof(RedLinkMess)) {
        reds_send_link_error(link, RED_ERR_INVALID_DATA);
        red_printf("bad size %u", header->size);
        reds_release_link(link);
        return;
    }

    if (!(link->link_mess = malloc(header->size))) {
        red_printf("malloc failed %u", header->size);
        reds_release_link(link);
        return;
    }

    obj->now = (uint8_t *)link->link_mess;
    obj->end = obj->now + header->size;
    obj->done = reds_handle_read_link_done;
    async_read_handler(&link->asyc_read);
}

static void reds_handle_new_link(RedLinkInfo *link)
{
    AsyncRead *obj = &link->asyc_read;
    obj->opaque = link;
    obj->peer = link->peer;
    obj->now = (uint8_t *)&link->link_header;
    obj->end = (uint8_t *)((RedLinkHeader *)&link->link_header + 1);
    obj->active_file_handlers = FALSE;
    obj->done = reds_handle_read_header_done;
    obj->error = reds_handle_link_error;
    async_read_handler(&link->asyc_read);
}

static void reds_handle_ssl_accept(void *data)
{
    RedLinkInfo *link = (RedLinkInfo *)data;
    int return_code;

    if ((return_code = SSL_accept(link->peer->ssl)) != 1) {
        int ssl_error = SSL_get_error(link->peer->ssl, return_code);

        if (ssl_error != SSL_ERROR_WANT_READ && ssl_error != SSL_ERROR_WANT_WRITE) {
            red_printf("SSL_accept failed, error=%d", ssl_error);
            reds_release_link(link);
        }
        return;
    }
    reds_handle_new_link(link);
}

static RedLinkInfo *__reds_accept_connection(int listen_socket)
{
    RedLinkInfo *link;
    RedsStreamContext *peer;
    int delay_val = 1;
    int flags;
    int socket;

    if ((socket = accept(listen_socket, NULL, 0)) == -1) {
        red_printf("accept failed, %s", strerror(errno));
        return NULL;
    }

    if ((flags = fcntl(socket, F_GETFL)) == -1) {
        red_printf("accept failed, %s", strerror(errno));
        goto error1;
    }

    if (fcntl(socket, F_SETFL, flags | O_NONBLOCK) == -1) {
        red_printf("accept failed, %s", strerror(errno));
        goto error1;
    }

    if (setsockopt(socket, IPPROTO_TCP, TCP_NODELAY, &delay_val, sizeof(delay_val)) == -1) {
        red_printf("setsockopt failed, %s", strerror(errno));
    }

    if (!(link = malloc(sizeof(RedLinkInfo)))) {
        red_printf("malloc failed");
        goto error1;
    }

    if (!(peer = malloc(sizeof(RedsStreamContext)))) {
        red_printf("malloc failed");
        goto error2;
    }

    memset(link, 0, sizeof(RedLinkInfo));
    memset(peer, 0, sizeof(RedsStreamContext));
    link->peer = peer;
    peer->socket = socket;
    openssl_init(link);

    return link;

error2:
    free(link);

error1:
    close(socket);

    return NULL;
}

static RedLinkInfo *reds_accept_connection(int listen_socket)
{
    RedLinkInfo *link;
    RedsStreamContext *peer;

    if (!(link = __reds_accept_connection(listen_socket))) {
        return NULL;
    }
    peer = link->peer;
    peer->ctx = (void *)((unsigned long)link->peer->socket);
    peer->cb_read = (int (*)(void *, void *, int))reds_read;
    peer->cb_write = (int (*)(void *, void *, int))reds_write;
    peer->cb_readv = (int (*)(void *, const struct iovec *vector, int count))readv;
    peer->cb_writev = (int (*)(void *, const struct iovec *vector, int count))writev;
    peer->cb_free = (int (*)(RedsStreamContext *))reds_free;

    return link;
}

static void reds_accept_ssl_connection(void *data)
{
    RedLinkInfo *link;
    int return_code;
    int ssl_error;
    BIO *sbio;

    link = __reds_accept_connection(reds->secure_listen_socket);
    if (link == NULL) {
        return;
    }

    // Handle SSL handshaking
    if (!(sbio = BIO_new_socket(link->peer->socket, BIO_NOCLOSE))) {
        red_printf("could not allocate ssl bio socket");
        goto error;
    }

    link->peer->ssl = SSL_new(reds->ctx);
    if (!link->peer->ssl) {
        red_printf("could not allocate ssl context");
        BIO_free(sbio);
        goto error;
    }

    SSL_set_bio(link->peer->ssl, sbio, sbio);

    link->peer->ctx = (void *)(link->peer->ssl);
    link->peer->cb_write = (int (*)(void *, void *, int))reds_ssl_write;
    link->peer->cb_read = (int (*)(void *, void *, int))reds_ssl_read;
    link->peer->cb_readv = NULL;
    link->peer->cb_writev = reds_ssl_writev;
    link->peer->cb_free = (int (*)(RedsStreamContext *))reds_ssl_free;

    return_code = SSL_accept(link->peer->ssl);
    if (return_code == 1) {
        reds_handle_new_link(link);
        return;
    }

    ssl_error = SSL_get_error(link->peer->ssl, return_code);
    if (return_code == -1 && (ssl_error == SSL_ERROR_WANT_READ ||
                              ssl_error == SSL_ERROR_WANT_WRITE)) {
        core->set_file_handlers(core, link->peer->socket, reds_handle_ssl_accept,
                                reds_handle_ssl_accept, link);
        return;
    }

    ERR_print_errors_fp(stderr);
    red_printf("SSL_accept failed, error=%d", ssl_error);
    SSL_free(link->peer->ssl);

error:
    close(link->peer->socket);
    free(link->peer);
    BN_free(link->tiTicketing.bn);
    free(link);
}

static void reds_accept(void *data)
{
    RedLinkInfo *link;

    link = reds_accept_connection(reds->listen_socket);
    if (link == NULL) {
        red_printf("accept failed");
        return;
    }
    reds_handle_new_link(link);
}

static int reds_init_socket(const char *addr, int portnr, int family)
{
    static const int on=1, off=0;
    struct addrinfo ai,*res,*e;
    char port[33];
    char uaddr[INET6_ADDRSTRLEN+1];
    char uport[33];
    int slisten,rc;

    memset(&ai,0, sizeof(ai));
    ai.ai_flags = AI_PASSIVE | AI_ADDRCONFIG;
    ai.ai_socktype = SOCK_STREAM;
    ai.ai_family = family;

    snprintf(port, sizeof(port), "%d", portnr);
    rc = getaddrinfo(strlen(addr) ? addr : NULL, port, &ai, &res);
    if (rc != 0) {
        red_error("getaddrinfo(%s,%s): %s\n", addr, port,
                  gai_strerror(rc));
    }

    for (e = res; e != NULL; e = e->ai_next) {
        getnameinfo((struct sockaddr*)e->ai_addr,e->ai_addrlen,
                    uaddr,INET6_ADDRSTRLEN, uport,32,
                    NI_NUMERICHOST | NI_NUMERICSERV);
        slisten = socket(e->ai_family, e->ai_socktype, e->ai_protocol);
        if (slisten < 0) {
            continue;
        }

        setsockopt(slisten,SOL_SOCKET,SO_REUSEADDR,(void*)&on,sizeof(on));
#ifdef IPV6_V6ONLY
        if (e->ai_family == PF_INET6) {
            /* listen on both ipv4 and ipv6 */
            setsockopt(slisten,IPPROTO_IPV6,IPV6_V6ONLY,(void*)&off,
                       sizeof(off));
        }
#endif
        if (bind(slisten, e->ai_addr, e->ai_addrlen) == 0) {
            goto listen;
        }
        close(slisten);
    }
    red_error("%s: binding socket to %s:%d failed\n", __FUNCTION__,
              addr, portnr);
    freeaddrinfo(res);
    return -1;

listen:
    freeaddrinfo(res);
    if (listen(slisten,1) != 0) {
        red_error("%s: listen: %s", __FUNCTION__, strerror(errno));
        close(slisten);
        return -1;
    }
    return slisten;
}

static void reds_init_net()
{
    if (spice_port != -1) {
        reds->listen_socket = reds_init_socket(spice_addr, spice_port, spice_family);
        if (core->set_file_handlers(core, reds->listen_socket, reds_accept, NULL, NULL)) {
            red_error("set fd handle failed");
        }
    }

    if (spice_secure_port != -1) {
        reds->secure_listen_socket = reds_init_socket(spice_addr, spice_secure_port,
                                                      spice_family);
        if (core->set_file_handlers(core, reds->secure_listen_socket,
                                    reds_accept_ssl_connection, NULL, NULL)) {
            red_error("set fd handle failed");
        }
    }
}

static void load_dh_params(SSL_CTX *ctx, char *file)
{
    DH *ret = 0;
    BIO *bio;

    if ((bio = BIO_new_file(file, "r")) == NULL) {
        red_error("Could not open DH file");
    }

    ret = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
    if (ret == 0) {
        red_error("Could not read DH params");
    }

    BIO_free(bio);

    if (SSL_CTX_set_tmp_dh(ctx, ret) < 0) {
        red_error("Could not set DH params");
    }
}

/*The password code is not thread safe*/
static int ssl_password_cb(char *buf, int size, int flags, void *userdata)
{
    char *pass = ssl_parameters.keyfile_password;
    if (size < strlen(pass) + 1) {
        return (0);
    }

    strcpy(buf, pass);
    return (strlen(pass));
}

static unsigned long pthreads_thread_id(void)
{
    unsigned long ret;

    ret = (unsigned long)pthread_self();
    return (ret);
}

static void pthreads_locking_callback(int mode, int type, char *file, int line)
{
    if (mode & CRYPTO_LOCK) {
        pthread_mutex_lock(&(lock_cs[type]));
        lock_count[type]++;
    } else {
        pthread_mutex_unlock(&(lock_cs[type]));
    }
}

static void openssl_thread_setup()
{
    int i;

    lock_cs = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
    lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));

    for (i = 0; i < CRYPTO_num_locks(); i++) {
        lock_count[i] = 0;
        pthread_mutex_init(&(lock_cs[i]), NULL);
    }

    CRYPTO_set_id_callback((unsigned long (*)())pthreads_thread_id);
    CRYPTO_set_locking_callback((void (*)())pthreads_locking_callback);
}

static void reds_init_ssl()
{
#if OPENSSL_VERSION_NUMBER >= 0x10000000L
    const SSL_METHOD *ssl_method;
#else
    SSL_METHOD *ssl_method;
#endif
    int return_code;
    long ssl_options = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3;

    /* Global system initialization*/
    SSL_library_init();
    SSL_load_error_strings();

    /* Create our context*/
    ssl_method = TLSv1_method();
    reds->ctx = SSL_CTX_new(ssl_method);
    if (!reds->ctx) {
        red_error("Could not allocate new SSL context");
    }

    /* Limit connection to TLSv1 only */
#ifdef SSL_OP_NO_COMPRESSION
    ssl_options |= SSL_OP_NO_COMPRESSION;
#endif
    SSL_CTX_set_options(reds->ctx, ssl_options);

    /* Load our keys and certificates*/
    return_code = SSL_CTX_use_certificate_chain_file(reds->ctx, ssl_parameters.certs_file);
    if (return_code != 1) {
        red_error("Could not load certificates from %s", ssl_parameters.certs_file);
    }

    SSL_CTX_set_default_passwd_cb(reds->ctx, ssl_password_cb);

    return_code = SSL_CTX_use_PrivateKey_file(reds->ctx, ssl_parameters.private_key_file,
                                              SSL_FILETYPE_PEM);
    if (return_code != 1) {
        red_error("Could not user private key file");
    }

    /* Load the CAs we trust*/
    return_code = SSL_CTX_load_verify_locations(reds->ctx, ssl_parameters.ca_certificate_file, 0);
    if (return_code != 1) {
        red_error("Could not use ca file");
    }

#if (OPENSSL_VERSION_NUMBER < 0x00905100L)
    SSL_CTX_set_verify_depth(reds->ctx, 1);
#endif

    if (strlen(ssl_parameters.dh_key_file) > 0) {
        load_dh_params(reds->ctx, ssl_parameters.dh_key_file);
    }

    SSL_CTX_set_session_id_context(reds->ctx, (const unsigned char *)"SPICE", 5);
    if (strlen(ssl_parameters.ciphersuite) > 0) {
        SSL_CTX_set_cipher_list(reds->ctx, ssl_parameters.ciphersuite);
    }

    openssl_thread_setup();

#ifndef SSL_OP_NO_COMPRESSION
    STACK *cmp_stack = SSL_COMP_get_compression_methods();
    sk_zero(cmp_stack);
#endif
}

static void reds_exit()
{
    if (reds->peer) {
        close(reds->peer->socket);
    }
#ifdef RED_STATISTICS
    shm_unlink(reds->stat_shm_name);
    free(reds->stat_shm_name);
#endif
    unsetenv("QEMU_AUDIO_DRV");
}

enum {
    SPICE_OPTION_INVALID,
    SPICE_OPTION_PORT,
    SPICE_OPTION_SPORT,
    SPICE_OPTION_HOST,
    SPICE_OPTION_IMAGE_COMPRESSION,
    SPICE_OPTION_PASSWORD,
    SPICE_OPTION_DISABLE_TICKET,
    SPICE_OPTION_RENDERER,
    SPICE_OPTION_SSLKEY,
    SPICE_OPTION_SSLCERTS,
    SPICE_OPTION_SSLCAFILE,
    SPICE_OPTION_SSLDHFILE,
    SPICE_OPTION_SSLPASSWORD,
    SPICE_OPTION_SSLCIPHERSUITE,
    SPICE_SECURED_CHANNELS,
    SPICE_UNSECURED_CHANNELS,
    SPICE_OPTION_STREAMING_VIDEO,
    SPICE_OPTION_AGENT_MOUSE,
    SPICE_OPTION_PLAYBACK_COMPRESSION,
};

typedef struct OptionsMap {
    const char *name;
    int val;
} OptionsMap;

static int find_option(const char *str, OptionsMap *options_map)
{
    int i = 0;

    for (i = 0; options_map[i].name != NULL; i++) {
        if (strcmp(str, options_map[i].name) == 0) {
            return options_map[i].val;
        }
    }
    return SPICE_OPTION_INVALID;
}

static void clear_blanks(char **ptr)
{
    char *str = *ptr;
    while (isspace(*str)) {
        str++;
    }
    while (isspace(str[strlen(str) - 1])) {
        str[strlen(str) - 1] = 0;
    }
    *ptr = str;
}

static int get_option(char **args, char **out_val, OptionsMap *map, char seperator)
{
    char *p;
    char *next;
    char *val;

    ASSERT(args && out_val);

    p = *args;
    if ((next = strchr(p, seperator))) {
        *next = 0;
        *args = next + 1;
    } else {
        *args = NULL;
    }

    if ((val = strchr(p, '='))) {
        *(val++) = 0;
        clear_blanks(&val);
        *out_val = (strlen(val) == 0) ? NULL : val;
    } else {
        *out_val = NULL;
    }

    clear_blanks(&p);
    return find_option(p, map);
}

enum {
    SPICE_TICKET_OPTION_INVALID,
    SPICE_TICKET_OPTION_EXPIRATION,
    SPICE_TICKET_OPTION_CONNECTED,
};

static OptionsMap _spice_ticket_options[] = {
    {"expiration", SPICE_TICKET_OPTION_EXPIRATION},
    {"connected", SPICE_TICKET_OPTION_CONNECTED},
    {NULL, 0},
};

static inline void on_activating_ticketing()
{
    if (!ticketing_enabled && reds->peer) {
        red_printf("disconnecting");
        reds_disconnect();
    }
}

static void reds_reset_ticketing()
{
    on_activating_ticketing();
    ticketing_enabled = 1;
    taTicket.expiration_time = 0;
    memset(taTicket.password, 0, sizeof(taTicket.password));
}

static void reds_set_ticketing(const char *pass, long expiration)
{
    ASSERT(expiration >= 0);
    on_activating_ticketing();
    ticketing_enabled = 1;
    if (expiration == 0) {
        taTicket.expiration_time = INT_MAX;
    } else {
        time_t ltime;

        time(&ltime);
        taTicket.expiration_time = ltime + expiration;
    }
    strncpy(taTicket.password, pass, sizeof(taTicket.password));
}

static void reds_do_set_ticket(const char *password, const char *args)
{
    long expiration = 0;
    char *local_args = NULL;
    const char *term_str = "invalid args";
    int disconnect = FALSE;
    int fail = FALSE;

    if (!password) {
        term_str = "unexpected NULL password";
        goto error;
    }

    if (args) {
        char *in_args;
        int option;
        char *val;

        in_args = local_args = malloc(strlen(args) + 1);
        strcpy(local_args, args);
        do {
            switch (option = get_option(&in_args, &val, _spice_ticket_options, ',')) {
            case SPICE_TICKET_OPTION_EXPIRATION: {
                char *endptr;

                if (!val) {
                    goto error;
                }
                expiration = strtol(val, &endptr, 0);
                if (endptr != val + strlen(val) || expiration < 0) {
                    term_str = "invalid expiration";
                    goto error;
                }
                break;
            }
            case SPICE_TICKET_OPTION_CONNECTED:
                if (!val) {
                    goto error;
                }

                if (strcmp(val, "disconnect") == 0) {
                    disconnect = TRUE;
                    fail = FALSE;
                } else if (strcmp(val, "fail") == 0) {
                    fail = TRUE;
                    disconnect = FALSE;
                } else if (strcmp(val, "keep") == 0) {
                    fail = FALSE;
                    disconnect = FALSE;
                } else {
                    goto error;
                }
                break;
            default:
                goto error;
            }
        } while (in_args);
    }

    if (fail && reds->peer) {
        term_str = "Ticket set failed";
    } else {
        if (disconnect) {
            reds_disconnect();
        }
        reds_set_ticketing(password, expiration);
        term_str = "Ticket set successfully";
    }
    core->term_printf(core, "%s\n", term_str);
    free(local_args);
    return;

error:
    reds_reset_ticketing();
    core->term_printf(core, "%s\n", term_str);
    free(local_args);
}

static void reds_do_set_ticket_2(const VDICmdArg *args)
{
    const char *arg2 = NULL;

    if (!args_is_string(args)) {
        red_printf("invalid args");
        return;
    }

    if (!args_is_empty(&args[1])) {
        if (!args_is_string(&args[1])) {
            red_printf("invalid args");
            return;
        }
        arg2 = args[1].string_val;
    }

    reds_do_set_ticket(args[0].string_val, arg2);
}

static void reds_do_set_ticket64(const char *password64, const char *args)
{
    char *password;

    if (!password64) {
        reds_reset_ticketing();
        core->term_printf(core, "unexpected NULL password\n");
        return;
    }

    if (!(password = base64decode(password64, strlen(password64)))) {
        reds_reset_ticketing();
        core->term_printf(core, "set_ticket64 failed!\n");
        return;
    }
    reds_do_set_ticket(password, args);
    free(password);
}

static void reds_do_set_ticket64_2(const VDICmdArg *args)
{
    const char *arg2 = NULL;

    if (!args_is_string(args)) {
        red_printf("invalid args");
        return;
    }

    if (!args_is_empty(&args[1])) {
        if (!args_is_string(&args[1])) {
            red_printf("invalid args");
            return;
        }
        arg2 = args[1].string_val;
    }

    reds_do_set_ticket64(args[0].string_val, arg2);
}

static void reds_do_info_spice()
{
    core->term_printf(core, "spice info:");
    if (reds->peer) {
        char *ip = NULL;
        struct sockaddr_in sock_addr;
        socklen_t len = sizeof(sock_addr);
        if (getpeername(reds->peer->socket, (struct sockaddr *)&sock_addr, &len) != -1) {
            ip = inet_ntoa(sock_addr.sin_addr);
        }
        core->term_printf(core, " client=%s", ip);
    } else {
        core->term_printf(core, " disconnected");
    }
    core->term_printf(core, " ticketing=%s", ticketing_enabled ? "on" : "off");
    switch (image_compression) {
    case SPICE_IMAGE_COMPRESS_AUTO_GLZ:
        core->term_printf(core, " ic=auto_glz");
        break;
    case SPICE_IMAGE_COMPRESS_AUTO_LZ:
        core->term_printf(core, " ic=auto_lz");
        break;
    case SPICE_IMAGE_COMPRESS_QUIC:
        core->term_printf(core, " ic=quic");
        break;
    case SPICE_IMAGE_COMPRESS_LZ:
        core->term_printf(core, " ic=lz");
        break;
    case SPICE_IMAGE_COMPRESS_GLZ:
        core->term_printf(core, " ic=glz");
        break;
    case SPICE_IMAGE_COMPRESS_OFF:
        core->term_printf(core, " ic=off");
        break;
    case SPICE_IMAGE_COMPRESS_INVALID:
    default:
        core->term_printf(core, " ic=invalid");
    }

    switch (streaming_video) {
        case STREAM_VIDEO_ALL:
            core->term_printf(core, " sv=all");
            break;
        case STREAM_VIDEO_FILTER:
            core->term_printf(core, " sv=filter");
            break;
        case STREAM_VIDEO_OFF:
            core->term_printf(core, " sv=off");
            break;
        case STREAM_VIDEO_INVALID:
        default:
            core->term_printf(core, " sv=invalid");

    }
    core->term_printf(core, " playback-compression=%s\n",
                      snd_get_playback_compression() ? "on" : "off");
}

static void set_image_compression(spice_image_compression_t val)
{
    if (val == image_compression) {
        return;
    }
    image_compression = val;
    red_dispatcher_on_ic_change();
}

static spice_image_compression_t reds_get_image_compression(const char *val)
{
    if ((strcmp(val, "on") == 0) || (strcmp(val, "auto_glz") == 0)) {
        return SPICE_IMAGE_COMPRESS_AUTO_GLZ;
    } else if (strcmp(val, "auto_lz") == 0) {
        return SPICE_IMAGE_COMPRESS_AUTO_LZ;
    } else if (strcmp(val, "quic") == 0) {
        return SPICE_IMAGE_COMPRESS_QUIC;
    } else if (strcmp(val, "glz") == 0) {
        return SPICE_IMAGE_COMPRESS_GLZ;
    } else if (strcmp(val, "lz") == 0) {
        return SPICE_IMAGE_COMPRESS_LZ;
    } else if (strcmp(val, "off") == 0) {
        return SPICE_IMAGE_COMPRESS_OFF;
    }
    return SPICE_IMAGE_COMPRESS_INVALID;
}

static void reds_do_set_image_compression(const char *val)
{
    spice_image_compression_t real_val = reds_get_image_compression(val);
    if (real_val == SPICE_IMAGE_COMPRESS_INVALID) {
        core->term_printf(core, "bad image compression arg\n");
        return;
    }
    set_image_compression(real_val);
}

static void reds_do_set_image_compression_2(const VDICmdArg *args)
{
    if (!args_is_string(args)) {
        red_printf("invalid args");
        return;
    }

    reds_do_set_image_compression(args[0].string_val);
}

static int reds_get_streaming_video(const char *val)
{
    if (strcmp(val, "on") == 0) {
        return STREAM_VIDEO_FILTER;
    } else if (strcmp(val, "filter") == 0) {
        return STREAM_VIDEO_FILTER;
    } else if (strcmp(val, "all") == 0) {
        return STREAM_VIDEO_ALL;
    } else if (strcmp(val, "off") == 0){
        return STREAM_VIDEO_OFF;
    } else {
        return STREAM_VIDEO_INVALID;
    }
}

static void reds_do_set_streaming_video(const char *val)
{
    uint32_t new_val = reds_get_streaming_video(val);
    if (new_val == STREAM_VIDEO_INVALID) {
        core->term_printf(core, "bad streaming video arg\n");
        return;
    }

    if (new_val == streaming_video) {
        return;
    }
    streaming_video = new_val;
    red_dispatcher_on_sv_change();
}

static void reds_do_set_streaming_video_2(const VDICmdArg *args)
{
    if (!args_is_string(args)) {
        red_printf("invalid args");
        return;
    }

    reds_do_set_streaming_video(args[0].string_val);
}

static void reds_do_set_agent_mouse(const char *val)
{
    int new_val;
    if (strcmp(val, "on") == 0) {
        new_val = TRUE;
    } else if (strcmp(val, "off") == 0) {
        new_val = FALSE;
    } else {
        core->term_printf(core, "bad agent mouse arg\n");
        return;
    }
    if (new_val == agent_mouse) {
        return;
    }
    agent_mouse = new_val;
    reds_update_mouse_mode();
}

static void reds_do_set_agent_mouse_2(const VDICmdArg *args)
{
    if (!args_is_string(args)) {
        red_printf("invalid args");
        return;
    }

    reds_do_set_agent_mouse(args[0].string_val);
}

static void reds_do_set_playback_compression(const char *val)
{
    int on;
    if (strcmp(val, "on") == 0) {
        on = TRUE;
    } else if (strcmp(val, "off") == 0) {
        on = FALSE;
    } else {
        core->term_printf(core, "bad playback compression arg\n");
        return;
    }
    snd_set_playback_compression(on);
}

static void reds_do_set_playback_compression_2(const VDICmdArg *args)
{
    if (!args_is_string(args)) {
        red_printf("invalid args");
        return;
    }

    reds_do_set_playback_compression(args[0].string_val);
}

static OptionsMap _spice_options[] = {
    {"port", SPICE_OPTION_PORT},
    {"sport", SPICE_OPTION_SPORT},
    {"host", SPICE_OPTION_HOST},
    {"ic", SPICE_OPTION_IMAGE_COMPRESSION},
    {"password", SPICE_OPTION_PASSWORD},
    {"disable-ticketing", SPICE_OPTION_DISABLE_TICKET},
    {"renderer", SPICE_OPTION_RENDERER},
    {"sslkey", SPICE_OPTION_SSLKEY},
    {"sslcert", SPICE_OPTION_SSLCERTS},
    {"sslcafile", SPICE_OPTION_SSLCAFILE},
    {"ssldhfile", SPICE_OPTION_SSLDHFILE},
    {"sslpassword", SPICE_OPTION_SSLPASSWORD},
    {"sslciphersuite", SPICE_OPTION_SSLCIPHERSUITE},
    {"secure-channels", SPICE_SECURED_CHANNELS},
    {"unsecure-channels", SPICE_UNSECURED_CHANNELS},
    {"sv", SPICE_OPTION_STREAMING_VIDEO},
    {"agent-mouse", SPICE_OPTION_AGENT_MOUSE},
    {"playback-compression", SPICE_OPTION_PLAYBACK_COMPRESSION},
    {NULL, 0},
};

static OptionsMap _channel_map[] = {
    {"all", SPICE_CHANNEL_ALL},
    {"main", SPICE_CHANNEL_MAIN},
    {"display", SPICE_CHANNEL_DISPLAY},
    {"inputs", SPICE_CHANNEL_INPUTS},
    {"cursor", SPICE_CHANNEL_CURSOR},
    {"playback", SPICE_CHANNEL_PLAYBACK},
    {"record", SPICE_CHANNEL_RECORD},
    {NULL, 0},
};

static void set_all_channels_security(uint32_t security)
{
    while (channels_security) {
        ChannelSecurityOptions *temp = channels_security;
        channels_security = channels_security->next;
        free(temp);
    }
    default_channel_security = security;
}

static void set_one_channel_security(int id, uint32_t security)
{
    ChannelSecurityOptions *security_options;

    if ((security_options = find_channel_security(id))) {
        security_options->options = security;
        return;
    }
    security_options = (ChannelSecurityOptions *)malloc(sizeof(*security_options));
    if (!security_options) {
        red_error("malloc failed");
    }
    security_options->channel_id = id;
    security_options->options = security;
    security_options->next = channels_security;
    channels_security = security_options;
}

static int set_channels_security(const char *channels, uint32_t security)
{
    char *local_str = malloc(strlen(channels) + 1);
    int channel_name;
    char *str;
    char *val;
    int all = 0;
    int specific = 0;

    if (!local_str) {
        red_error("malloc failed");
    }
    strcpy(local_str, channels);
    str = local_str;
    do {
        switch (channel_name = get_option(&str, &val, _channel_map, '+')) {
        case SPICE_CHANNEL_ALL:
            all++;
            break;
        case SPICE_CHANNEL_MAIN:
            specific++;
            set_one_channel_security(RED_CHANNEL_MAIN, security);
            break;
        case SPICE_CHANNEL_DISPLAY:
            specific++;
            set_one_channel_security(RED_CHANNEL_DISPLAY, security);
            break;
        case SPICE_CHANNEL_INPUTS:
            specific++;
            set_one_channel_security(RED_CHANNEL_INPUTS, security);
            break;
        case SPICE_CHANNEL_CURSOR:
            specific++;
            set_one_channel_security(RED_CHANNEL_CURSOR, security);
            break;
        case SPICE_CHANNEL_PLAYBACK:
            specific++;
            set_one_channel_security(RED_CHANNEL_PLAYBACK, security);
            break;
        case SPICE_CHANNEL_RECORD:
            specific++;
            set_one_channel_security(RED_CHANNEL_RECORD, security);
            break;
        default:
            goto error;
        }
        if (val) {
            goto error;
        }
    } while (str);

    if (all) {
        if (specific || all > 1) {
            goto error;
        }
        set_all_channels_security(security);
        return TRUE;
    }
    return TRUE;

error:
    free(local_str);
    return FALSE;
}

int __attribute__ ((visibility ("default"))) spice_parse_args(const char *in_args)
{
    char *local_args;
    char *args;
    int option;
    char *val;
    int renderers_opt = FALSE;

    int ssl_port = FALSE;
    int ssl_key = FALSE;
    int ssl_certs = FALSE;
    int ssl_ciphersuite = FALSE;
    int ssl_cafile = FALSE;
    int ssl_dhfile = FALSE;

    memset(&ssl_parameters, 0, sizeof(ssl_parameters));

    local_args = malloc(strlen(in_args) + 1);
    strcpy(local_args, in_args);

    args = local_args;
    do {
        switch (option = get_option(&args, &val, _spice_options, ',')) {
        case SPICE_OPTION_PORT: {
            char *endptr;
            long int port;

            if (!val) {
                goto error;
            }
            port = strtol(val, &endptr, 0);
            if (endptr != val + strlen(val) || port < 0 || port > 0xffff) {
                goto error;
            }
            spice_port = port;
            break;
        }
        case SPICE_OPTION_SPORT: {
            char *endptr;
            long int port;

            if (!val) {
                goto error;
            }
            port = strtol(val, &endptr, 0);
            if (endptr != val + strlen(val) || port < 0 || port > 0xffff) {
                goto error;
            }

            ssl_port = TRUE;
            spice_secure_port = port;
            break;
        }
        case SPICE_OPTION_HOST: {
            if (val) {
                strncpy(spice_addr, val, sizeof(spice_addr));
                /* force ipv4 here for backward compatibility */
                spice_family = PF_INET;
            }
            break;
        }
        case SPICE_OPTION_IMAGE_COMPRESSION:
            if (!val) {
                goto error;
            }
            image_compression = reds_get_image_compression(val);
            if (image_compression == SPICE_IMAGE_COMPRESS_INVALID) {
                goto error;
            }
            break;
        case SPICE_OPTION_PASSWORD:
            ticketing_enabled = 1;

            if (val) {
                strncpy(taTicket.password, val, sizeof taTicket.password);
                //todo: add expiration option
                taTicket.expiration_time = INT_MAX;
            }

            break;
        case SPICE_OPTION_DISABLE_TICKET:
            ticketing_enabled = 0;
            break;
        case SPICE_OPTION_RENDERER:
            renderers_opt = TRUE;
            if (!val) {
                goto error;
            }
            while (val) {
                char *now = val;
                if ((val = strchr(now, '+'))) {
                    *val++ = 0;
                }
                if (!red_dispatcher_add_renderer(now)) {
                    goto error;
                }
            }

            break;
        case SPICE_OPTION_SSLCIPHERSUITE:
            ssl_ciphersuite = TRUE;

            if (val) {
                strncpy(ssl_parameters.ciphersuite, val, sizeof(ssl_parameters.ciphersuite));
            }

            break;
        case SPICE_OPTION_SSLPASSWORD:
            if (val) {
                strncpy(ssl_parameters.keyfile_password, val,
                        sizeof(ssl_parameters.keyfile_password));
            }
            break;
        case SPICE_OPTION_SSLKEY:
            ssl_key = TRUE;

            if (val) {
                strncpy(ssl_parameters.private_key_file, val,
                        sizeof(ssl_parameters.private_key_file));
            }
            break;
        case SPICE_OPTION_SSLCERTS:
            ssl_certs = TRUE;

            if (val) {
                strncpy(ssl_parameters.certs_file, val, sizeof(ssl_parameters.certs_file));
            }
            break;
        case SPICE_OPTION_SSLCAFILE:
            ssl_cafile = TRUE;

            if (val) {
                strncpy(ssl_parameters.ca_certificate_file, val,
                        sizeof(ssl_parameters.ca_certificate_file));
            }
            break;
        case SPICE_OPTION_SSLDHFILE:
            ssl_dhfile = TRUE;

            if (val) {
                strncpy(ssl_parameters.dh_key_file, val, sizeof(ssl_parameters.dh_key_file));
            }
            break;
        case SPICE_SECURED_CHANNELS:
            if (!val || !set_channels_security(val, SPICE_CHANNEL_SECURITY_SSL)) {
                goto error;
            }
            break;
        case SPICE_UNSECURED_CHANNELS:
            if (!val || !set_channels_security(val, SPICE_CHANNEL_SECURITY_NON)) {
                goto error;
            }
            break;
        case SPICE_OPTION_STREAMING_VIDEO:
            if (!val) {
                goto error;
            }
            streaming_video = reds_get_streaming_video(val);
            if (streaming_video == STREAM_VIDEO_INVALID) {
                goto error;
            }
            break;
        case SPICE_OPTION_PLAYBACK_COMPRESSION:
            if (!val) {
                goto error;
            }
            if (strcmp(val, "on") == 0) {
                snd_set_playback_compression(TRUE);
            } else if (strcmp(val, "off") == 0) {
                snd_set_playback_compression(FALSE);
            } else {
                goto error;
            }
            break;
        case SPICE_OPTION_AGENT_MOUSE:
            if (!val) {
                goto error;
            }
            if (strcmp(val, "on") == 0) {
                agent_mouse = TRUE;
            } else if (strcmp(val, "off") == 0) {
                agent_mouse = FALSE;
            } else {
                goto error;
            }
            break;
        default:
            goto error;
        }
    } while (args);

    if (!renderers_opt && !red_dispatcher_add_renderer("cairo")) {
        goto error;
    }

    // All SSL parameters should be either on or off.
    if (ssl_port != ssl_key || ssl_key != ssl_certs || ssl_certs != ssl_cafile ||
        ssl_cafile != ssl_dhfile || ssl_dhfile != ssl_ciphersuite) {

        goto error;
    }
    free(local_args);
    return TRUE;

error:
    free(local_args);
    return FALSE;
}

const char *spice_usage_str[] __attribute__ ((visibility ("default"))) = {
    "[port=<port>][,sport=<port>][,host=<host>]",
    "[,ic=on|auto_glz|auto_lz|quic|glz|lz|off]",
    "[,playback-compression=on|off]",
    "[,password=password][,disable-ticketing]",
    "[,renderer=oglpbuf+oglpixmap+cairo]",
    "[,sslkeys=key directory,sslcerts=certs directory,sslpassword=pem password,",
    "                                              sslciphersuite=cipher suite]",
    "[,secure-channels=all|channel+channel+...]",
    "[,unsecure-channels=all|channel+channel+...]",
    "[,vs=on|off] [,ac=on|off]",
    "    listen on interface address <host> port <port> and/or sport <port>",
    "    setting ticket password using \"ticket\" option",
    "    setting image compression using \"ic\" option [default=auto_local]",
    "    setting playback compression using \"playback-compression\" option [default=on]",
    "    select renderers using \"renderer\" option",
    "    sslkeys - set directory where ssl key file resides.",
    "    sslcerts - set directory where ssl cert file resides.",
    "    sslpassword - set the password to open the private key file.",
    "    sslciphersuite - set the cipher suite to use.",
    "    setting streaming video using \"sv\" option [default=on]",
    "    setting audio compression codec using \"ac\" option [default=off]",
    "    secure-channels - force secure connection on all/specific chnnels.",
    "                       channels names: main, inputs, display, cursor,",
    "                                       playback and record.",
    "    unsecure-channels - force unsecure connection on all/specific chnnels.",
    "                         channels names as in secure-channels.",
    NULL,
};

#define REDS_SAVE_VERSION 1

static OptionsMap spice_mig_options[] = {
    {"spicesport", SPICE_OPTION_SPORT},
    {"spiceport", SPICE_OPTION_PORT},
    {"spicehost", SPICE_OPTION_HOST},
    {NULL, 0},
};

struct RedsMigSpice;

typedef struct RedsMigRead {
    uint8_t buf[RECIVE_BUF_SIZE];
    uint32_t end_pos;
    uint32_t size;

    void (*handle_data)(struct RedsMigSpice *message);
} RedsMigRead;

typedef struct RedsMigWrite {
    uint8_t buf[SEND_BUF_SIZE];
    uint8_t *now;
    uint32_t length;

    void (*handle_done)(struct RedsMigSpice *s);
} RedsMigWrite;

typedef struct RedsMigSpice {
    int fd;
    RedsMigWrite write;
    RedsMigRead read;

    char pub_key[RED_TICKET_PUBKEY_BYTES];
    uint32_t mig_key;

    char *local_args;
    char *host;
    int port;
    int sport;
    uint16_t cert_pub_key_type;
    uint32_t cert_pub_key_len;
    uint8_t* cert_pub_key;
} RedsMigSpice;

typedef struct RedsMigSpiceMessage {
    uint32_t link_id;
} RedsMigSpiceMessage;

typedef struct RedsMigCertPubKeyInfo {
    uint16_t type;
    uint32_t len;
} RedsMigCertPubKeyInfo;

static int reds_mig_actual_read(RedsMigSpice *s)
{
    for (;;) {
        uint8_t *buf = s->read.buf;
        uint32_t pos = s->read.end_pos;
        int n;
        n = read(s->fd, buf + pos, s->read.size - pos);
        if (n <= 0) {
            if (n == 0) {
                return -1;
            }
            switch (errno) {
            case EAGAIN:
                return 0;
            case EINTR:
                break;
            case EPIPE:
                return -1;
            default:
                red_printf("%s", strerror(errno));
                return -1;
            }
        } else {
            s->read.end_pos += n;
            if (s->read.end_pos == s->read.size) {
                s->read.handle_data(s);
                return 0;
            }
        }
    }
}

static int reds_mig_actual_write(RedsMigSpice *s)
{
    if (!s->write.length) {
        return 0;
    }

    while (s->write.length) {
        int n;

        n = write(s->fd, s->write.now, s->write.length);
        if (n <= 0) {
            if (n == 0) {
                return -1;
            }
            switch (errno) {
            case EAGAIN:
                return 0;
            case EINTR:
                break;
            case EPIPE:
                return -1;
            default:
                red_printf("%s", strerror(errno));
                return -1;
            }
        } else {
            s->write.now += n;
            s->write.length -= n;
        }
    }

    s->write.handle_done(s);
    return 0;
}

static void reds_mig_failed(RedsMigSpice *s)
{
    red_printf("");
    core->set_file_handlers(core, s->fd, NULL, NULL, NULL);
    if (s->local_args) {
        free(s->local_args);
    }
    free(s);

    reds_mig_disconnect();
}

static void reds_mig_write(void *data)
{
    RedsMigSpice *s = data;

    if (reds_mig_actual_write((RedsMigSpice *)data)) {
        red_printf("write error cannot continue spice migration");
        reds_mig_failed(s);
    }
}

static void reds_mig_read(void *data)
{
    RedsMigSpice *s = data;

    if (reds_mig_actual_read((RedsMigSpice *)data)) {
        red_printf("read error cannot continue spice migration");
        reds_mig_failed(s);
    }
}

static void reds_mig_continue(RedsMigSpice *s)
{
    RedMigrationBegin *migrate;
    SimpleOutItem *item;
    int host_len;

    red_printf("");
    core->set_file_handlers(core, s->fd, NULL, NULL, NULL);
    host_len = strlen(s->host) + 1;
    item = new_simple_out_item(RED_MIGRATE_BEGIN,
                               sizeof(RedMigrationBegin) + host_len + s->cert_pub_key_len);
    if (!(item)) {
        red_printf("alloc item failed");
        reds_disconnect();
        return;
    }
    migrate = (RedMigrationBegin *)item->data;
    migrate->port = s->port;
    migrate->sport = s->sport;
    migrate->host_offset = sizeof(RedMigrationBegin);
    migrate->host_size = host_len;
    migrate->pub_key_type = s->cert_pub_key_type;
    migrate->pub_key_offset = sizeof(RedMigrationBegin) + host_len;
    migrate->pub_key_size = s->cert_pub_key_len;
    memcpy((uint8_t*)(migrate) + migrate->host_offset , s->host, host_len);
    memcpy((uint8_t*)(migrate) + migrate->pub_key_offset, s->cert_pub_key, s->cert_pub_key_len);
    reds_push_pipe_item(&item->base);

    free(s->local_args);
    free(s);
    reds->mig_wait_connect = TRUE;
    core->arm_timer(core, reds->mig_timer, MIGRATE_TIMEOUT);
}

static void reds_mig_receive_ack(RedsMigSpice *s)
{
    s->read.size = sizeof(uint32_t);
    s->read.end_pos = 0;
    s->read.handle_data = reds_mig_continue;

    core->set_file_handlers(core, s->fd, reds_mig_read, NULL, s);
}

static void reds_mig_send_link_id(RedsMigSpice *s)
{
    RedsMigSpiceMessage *data = (RedsMigSpiceMessage *)s->write.buf;

    memcpy(&data->link_id, &reds->link_id, sizeof(reds->link_id));

    s->write.now = s->write.buf;
    s->write.length = sizeof(RedsMigSpiceMessage);
    s->write.handle_done = reds_mig_receive_ack;

    core->set_file_handlers(core, s->fd, reds_mig_write, reds_mig_write, s);
}

static void reds_mig_send_ticket(RedsMigSpice *s)
{
    EVP_PKEY *pubkey = NULL;
    BIO *bio_key;
    RSA *rsa;
    int rsa_size = 0;

    red_printf("");

    bio_key = BIO_new(BIO_s_mem());
    if (bio_key != NULL) {
        BIO_write(bio_key, s->read.buf, RED_TICKET_PUBKEY_BYTES);
        pubkey = d2i_PUBKEY_bio(bio_key, NULL);
        rsa = pubkey->pkey.rsa;
        rsa_size = RSA_size(rsa);
        if (RSA_public_encrypt(strlen(reds->taTicket.password) + 1,
                               (unsigned char *)reds->taTicket.password,
                               (uint8_t *)(s->write.buf),
                               rsa, RSA_PKCS1_OAEP_PADDING) > 0) {
            s->write.length = RSA_size(rsa);
            s->write.now = s->write.buf;
            s->write.handle_done = reds_mig_send_link_id;
            core->set_file_handlers(core, s->fd, reds_mig_write, reds_mig_write, s);
        } else {
            reds_mig_failed(s);
        }
    } else {
        reds_mig_failed(s);
    }

    EVP_PKEY_free(pubkey);
    BIO_free(bio_key);
}

static void reds_mig_receive_cert_public_key(RedsMigSpice *s)
{
    s->cert_pub_key = malloc(s->cert_pub_key_len);
    if (!s->cert_pub_key) {
        red_printf("alloc failed");
        reds_mig_failed(s);
        return;
    }

    memcpy(s->cert_pub_key, s->read.buf, s->cert_pub_key_len);

    s->read.size = RED_TICKET_PUBKEY_BYTES;
    s->read.end_pos = 0;
    s->read.handle_data = reds_mig_send_ticket;

    core->set_file_handlers(core, s->fd, reds_mig_read, NULL, s);
}

static void reds_mig_receive_cert_public_key_info(RedsMigSpice *s)
{
    RedsMigCertPubKeyInfo* pubkey_info = (RedsMigCertPubKeyInfo*)s->read.buf;
    s->cert_pub_key_type = pubkey_info->type;
    s->cert_pub_key_len = pubkey_info->len;

    if (s->cert_pub_key_len > RECIVE_BUF_SIZE) {
        red_printf("certificate public key length exceeds buffer size");
        reds_mig_failed(s);
        return;
    }

    if (s->cert_pub_key_len) {
        s->read.size = s->cert_pub_key_len;
        s->read.end_pos = 0;
        s->read.handle_data = reds_mig_receive_cert_public_key;
    } else {
        s->cert_pub_key = NULL;
        s->read.size = RED_TICKET_PUBKEY_BYTES;
        s->read.end_pos = 0;
        s->read.handle_data = reds_mig_send_ticket;
    }

    core->set_file_handlers(core, s->fd, reds_mig_read, NULL, s);
}

static void reds_mig_handle_send_abort_done(RedsMigSpice *s)
{
    reds_mig_failed(s);
}

static void reds_mig_receive_version(RedsMigSpice *s)
{
    uint32_t* dest_version;
    uint32_t resault;
    dest_version = (uint32_t*)s->read.buf;
    resault = REDS_MIG_ABORT;
    memcpy(s->write.buf, &resault, sizeof(resault));
    s->write.length = sizeof(resault);
    s->write.now = s->write.buf;
    s->write.handle_done = reds_mig_handle_send_abort_done;
    core->set_file_handlers(core, s->fd, reds_mig_write, reds_mig_write, s);
}

static void reds_mig_control(RedsMigSpice *spice_migration)
{
    uint32_t *control;

    core->set_file_handlers(core, spice_migration->fd, NULL, NULL, NULL);
    control = (uint32_t *)spice_migration->read.buf;

    switch (*control) {
    case REDS_MIG_CONTINUE:
        spice_migration->read.size = sizeof(RedsMigCertPubKeyInfo);
        spice_migration->read.end_pos = 0;
        spice_migration->read.handle_data = reds_mig_receive_cert_public_key_info;

        core->set_file_handlers(core, spice_migration->fd, reds_mig_read,
                                NULL, spice_migration);
        break;
    case REDS_MIG_ABORT:
        red_printf("abort");
        reds_mig_failed(spice_migration);
        break;
    case REDS_MIG_DIFF_VERSION:
        red_printf("different versions");
        spice_migration->read.size = sizeof(uint32_t);
        spice_migration->read.end_pos = 0;
        spice_migration->read.handle_data = reds_mig_receive_version;

        core->set_file_handlers(core, spice_migration->fd, reds_mig_read,
                                NULL, spice_migration);
        break;
    default:
        red_printf("invalid control");
        reds_mig_failed(spice_migration);
    }
}

static void reds_mig_receive_control(RedsMigSpice *spice_migration)
{
    spice_migration->read.size = sizeof(uint32_t);
    spice_migration->read.end_pos = 0;
    spice_migration->read.handle_data = reds_mig_control;

    core->set_file_handlers(core, spice_migration->fd, reds_mig_read, NULL, spice_migration);
}

static void reds_mig_started(void *opaque, const char *in_args)
{
    RedsMigSpice *spice_migration = NULL;
    uint32_t *version;
    char *val;
    char *args;
    int option;

    ASSERT(in_args);
    red_printf("");

    reds->mig_inprogress = TRUE;

    if (reds->listen_socket != -1) {
        core->set_file_handlers(core, reds->listen_socket, NULL, NULL, NULL);
    }

    if (reds->secure_listen_socket != -1) {
        core->set_file_handlers(core, reds->secure_listen_socket, NULL, NULL, NULL);
    }

    if (reds->peer == NULL) {
        red_printf("not connected to peer");
        goto error;
    }

    if ((RED_VERSION_MAJOR == 1) && (reds->peer_minor_version < 1)) {
        red_printf("minor version mismatch client %u server %u",
                   reds->peer_minor_version, RED_VERSION_MINOR);
        goto error;
    }

    spice_migration = (RedsMigSpice *)malloc(sizeof(RedsMigSpice));
    if (!spice_migration) {
        red_printf("Could not allocate memory for spice migration structure");
        goto error;
    }
    memset(spice_migration, 0, sizeof(RedsMigSpice));
    spice_migration->port = -1;
    spice_migration->sport = -1;

    if (!(spice_migration->local_args = malloc(strlen(in_args) + 1))) {
        red_printf("str malloc failed");
        goto error;
    }

    strcpy(spice_migration->local_args, in_args);
    args = spice_migration->local_args;
    do {
        switch (option = get_option(&args, &val, spice_mig_options, ',')) {
        case SPICE_OPTION_SPORT: {
            char *endptr;

            if (!val) {
                goto error;
            }
            spice_migration->sport = strtol(val, &endptr, 0);
            if (endptr != val + strlen(val) || spice_migration->sport < 0 ||
                                                                  spice_migration->sport > 0xffff) {
                goto error;
            }
            break;
        }
        case SPICE_OPTION_PORT: {
            char *endptr;

            if (!val) {
                goto error;
            }
            spice_migration->port = strtol(val, &endptr, 0);
            if (
                endptr != val + strlen(val) ||
                spice_migration->port < 0 ||
                spice_migration->port > 0xffff
                ) {
                goto error;
            }
            break;
        }
        case SPICE_OPTION_HOST:
            if (!val) {
                goto error;
            }
            spice_migration->host = val;
            break;
        }
    } while (args);

    if ((spice_migration->sport == -1 && spice_migration->port == -1) || !spice_migration->host) {
        red_printf("invalid args port %d sport %d host %s",
                   spice_migration->port,
                   spice_migration->sport,
                   (spice_migration->host) ? spice_migration->host : "NULL");
        goto error;
    }

    spice_migration->fd = mig->begin_hook(mig, reds->mig_notifier);

    if (spice_migration->fd == -1) {
        goto error;
    }

    spice_migration->write.now = spice_migration->write.buf;
    spice_migration->write.length = sizeof(uint32_t);
    version = (uint32_t *)spice_migration->write.buf;
    *version = REDS_MIG_VERSION;
    spice_migration->write.handle_done = reds_mig_receive_control;
    core->set_file_handlers(core, spice_migration->fd, reds_mig_write,
                            reds_mig_write, spice_migration);
    return;

error:
    if (spice_migration) {
        if (spice_migration->local_args) {
            free(spice_migration->local_args);
        }
        free(spice_migration);
    }

    reds_mig_disconnect();
}

static void reds_mig_finished(void *opaque, int completed)
{
    SimpleOutItem *item;

    red_printf("");
    if (reds->listen_socket != -1) {
        core->set_file_handlers(core, reds->listen_socket, reds_accept, NULL, NULL);
    }

    if (reds->secure_listen_socket != -1) {
        core->set_file_handlers(core, reds->secure_listen_socket, reds_accept_ssl_connection,
                                NULL, NULL);
    }

    if (reds->peer == NULL) {
        red_printf("no peer connected");
        mig->notifier_done(mig, reds->mig_notifier);
        return;
    }
    reds->mig_inprogress = TRUE;

    if (completed) {
        Channel *channel;
        RedMigrate *migrate;

        reds->mig_wait_disconnect = TRUE;
        core->arm_timer(core, reds->mig_timer, MIGRATE_TIMEOUT);

        if (!(item = new_simple_out_item(RED_MIGRATE, sizeof(RedMigrate)))) {
            red_printf("alloc item failed");
            reds_disconnect();
            return;
        }
        migrate = (RedMigrate *)item->data;
        migrate->flags = RED_MIGRATE_NEED_FLUSH | RED_MIGRATE_NEED_DATA_TRANSFER;
        reds_push_pipe_item(&item->base);
        channel = reds->channels;
        while (channel) {
            channel->migrate(channel);
            channel = channel->next;
        }
    } else {
        if (!(item = new_simple_out_item(RED_MIGRATE_CANCEL, 0))) {
            red_printf("alloc item failed");
            reds_disconnect();
            return;
        }
        reds_push_pipe_item(&item->base);
        reds_mig_cleanup();
    }
}

static int write_all(int fd, const void *in_buf, int len1)
{
    int ret, len;
    uint8_t *buf = (uint8_t *)in_buf;

    len = len1;
    while (len > 0) {
        ret = write(fd, buf, len);
        if (ret < 0) {
            if (errno != EINTR && errno != EAGAIN) {
                return -1;
            }
        } else if (ret == 0) {
            break;
        } else {
            buf += ret;
            len -= ret;
        }
    }
    return len1 - len;
}

static int read_all(int fd, void *in_nuf, int lenl)
{
    int ret, len;
    uint8_t *buf = in_nuf;

    len = lenl;
    while (len > 0) {
        ret = read(fd, buf, len);
        if (ret < 0) {
            if (errno != EINTR && errno != EAGAIN) {
                return -1;
            }
        } else if (ret == 0) {
            break;
        } else {
            buf += ret;
            len -= ret;
        }
    }
    return lenl - len;
}

static void reds_mig_read_all(int fd, void *buf, int len, const char *name)
{
    int n = read_all(fd, buf, len);
    if (n != len) {
        red_error("read %s failed, n=%d (%s)", name, n, strerror(errno));
    }
}

static void reds_mig_write_all(int fd, void *buf, int len, const char *name)
{
    int n = write_all(fd, buf, len);
    if (n != len) {
        red_error("write %s faile, n=%d (%s)", name, n, strerror(errno));
    }
}

static void reds_mig_send_cert_public_key(int fd)
{
    FILE* cert_file;
    X509* x509;
    EVP_PKEY* pub_key;
    unsigned char* pp = NULL;
    int length;
    BIO* mem_bio;
    RedsMigCertPubKeyInfo pub_key_info_msg;

    if (spice_secure_port == -1) {
        pub_key_info_msg.type = RED_PUBKEY_TYPE_INVALID;
        pub_key_info_msg.len = 0;
        reds_mig_write_all(fd, &pub_key_info_msg, sizeof(pub_key_info_msg), "cert public key info");
        return;
    }

    cert_file =  fopen(ssl_parameters.certs_file, "r");
    if (!cert_file) {
        red_error("opening certificate failed");
    }

    x509 = PEM_read_X509_AUX(cert_file, NULL, NULL, NULL);
    if (!x509) {
        red_error("reading x509 cert failed");
    }
    pub_key = X509_get_pubkey(x509);
    if (!pub_key) {
        red_error("reading public key failed");
    }

    mem_bio = BIO_new(BIO_s_mem());
    i2d_PUBKEY_bio(mem_bio, pub_key);
    if (BIO_flush(mem_bio) != 1) {
        red_error("bio flush failed");
    }
    length = BIO_get_mem_data(mem_bio, &pp);

    switch(pub_key->type) {
    case EVP_PKEY_RSA:
        pub_key_info_msg.type = RED_PUBKEY_TYPE_RSA;
        break;
    case EVP_PKEY_RSA2:
        pub_key_info_msg.type = RED_PUBKEY_TYPE_RSA2;
        break;
    case EVP_PKEY_DSA:
        pub_key_info_msg.type = RED_PUBKEY_TYPE_DSA;
        break;
    case EVP_PKEY_DSA1:
        pub_key_info_msg.type = RED_PUBKEY_TYPE_DSA1;
        break;
    case EVP_PKEY_DSA2:
        pub_key_info_msg.type = RED_PUBKEY_TYPE_DSA2;
        break;
    case EVP_PKEY_DSA3:
        pub_key_info_msg.type = RED_PUBKEY_TYPE_DSA3;
        break;
    case EVP_PKEY_DSA4:
        pub_key_info_msg.type = RED_PUBKEY_TYPE_DSA4;
        break;
    case EVP_PKEY_DH:
        pub_key_info_msg.type = RED_PUBKEY_TYPE_DH;
        break;
    case EVP_PKEY_EC:
        pub_key_info_msg.type = RED_PUBKEY_TYPE_EC;
        break;
    default:
        red_error("invalid public key type");
    }
    pub_key_info_msg.len = length;
    reds_mig_write_all(fd, &pub_key_info_msg, sizeof(pub_key_info_msg), "cert public key info");
    reds_mig_write_all(fd, pp, length, "cert public key");

    BIO_free(mem_bio);
    fclose(cert_file);
    EVP_PKEY_free(pub_key);
    X509_free(x509);
}

static void reds_mig_recv(void *opaque, int fd)
{
    uint32_t ack_message = *(uint32_t *)"ack_";
    char password[RED_MAX_PASSWORD_LENGTH];
    RedsMigSpiceMessage mig_message;
    unsigned long f4 = RSA_F4;
    TicketInfo ticketing_info;
    uint32_t version;
    uint32_t resault;
    BIO *bio;

    BUF_MEM *buff;

    reds_mig_read_all(fd, &version, sizeof(version), "version");
    // starting from version 3, if the version of the src is bigger
    // than ours, we send our version to the src.
    if (version < REDS_MIG_VERSION) {
        resault = REDS_MIG_ABORT;
        reds_mig_write_all(fd, &resault, sizeof(resault), "resault");
        mig->notifier_done(mig, reds->mig_notifier);
        return;
    } else if (version > REDS_MIG_VERSION) {
        uint32_t src_resault;
        uint32_t self_version = REDS_MIG_VERSION;
        resault = REDS_MIG_DIFF_VERSION;
        reds_mig_write_all(fd, &resault, sizeof(resault), "resault");
        reds_mig_write_all(fd, &self_version, sizeof(self_version), "dest-version");
        reds_mig_read_all(fd, &src_resault, sizeof(src_resault), "src resault");

        if (src_resault == REDS_MIG_ABORT) {
            red_printf("abort (response to REDS_MIG_DIFF_VERSION)");
            mig->notifier_done(mig, reds->mig_notifier);
            return;
        } else if (src_resault != REDS_MIG_CONTINUE) {
            red_printf("invalid response to REDS_MIG_DIFF_VERSION");
            mig->notifier_done(mig, reds->mig_notifier);
            return;
        }
    } else {
        resault = REDS_MIG_CONTINUE;
        reds_mig_write_all(fd, &resault, sizeof(resault), "resault");
    }

    reds_mig_send_cert_public_key(fd);

    ticketing_info.bn = BN_new();
    if (!ticketing_info.bn) {
        red_error("OpenSSL BIGNUMS alloc failed");
    }

    BN_set_word(ticketing_info.bn, f4);
    if (!(ticketing_info.rsa = RSA_new())) {
        red_error("OpenSSL RSA alloc failed");
    }

    RSA_generate_key_ex(ticketing_info.rsa, RED_TICKET_KEY_PAIR_LENGTH, ticketing_info.bn, NULL);
    ticketing_info.rsa_size = RSA_size(ticketing_info.rsa);

    if (!(bio = BIO_new(BIO_s_mem()))) {
        red_error("OpenSSL BIO alloc failed");
    }

    i2d_RSA_PUBKEY_bio(bio, ticketing_info.rsa);
    BIO_get_mem_ptr(bio, &buff);

    reds_mig_write_all(fd, buff->data, RED_TICKET_PUBKEY_BYTES, "publick key");
    reds_mig_read_all(fd, ticketing_info.encrypted_ticket.encrypted_data, ticketing_info.rsa_size,
                      "ticket");

    RSA_private_decrypt(ticketing_info.rsa_size, ticketing_info.encrypted_ticket.encrypted_data,
                        (unsigned char *)password, ticketing_info.rsa, RSA_PKCS1_OAEP_PADDING);

    BN_free(ticketing_info.bn);
    BIO_free(bio);
    RSA_free(ticketing_info.rsa);

    memcpy(reds->taTicket.password, password, sizeof(reds->taTicket.password));
    reds_mig_read_all(fd, &mig_message, sizeof(mig_message), "mig data");
    reds->link_id = mig_message.link_id;
    reds_mig_write_all(fd, &ack_message, sizeof(uint32_t), "ack");
    mig->notifier_done(mig, reds->mig_notifier);
}

static void migrate_timout(void *opaque)
{
    red_printf("");
    ASSERT(reds->mig_wait_connect || reds->mig_wait_disconnect);
    reds_mig_disconnect();
}

static void key_modifiers_sender(void *opaque)
{
    reds_send_keyborad_modifiers(keyboard ? keyboard->get_leds(keyboard) : 0);
}

uint32_t reds_get_mm_time()
{
    struct timespec time_space;
    clock_gettime(CLOCK_MONOTONIC, &time_space);
    return time_space.tv_sec * 1000 + time_space.tv_nsec / 1000 / 1000;
}

void reds_update_mm_timer(uint32_t mm_time)
{
    red_dispatcher_set_mm_time(mm_time);
}

void reds_enable_mm_timer()
{
    RedMultiMediaTime *time_mes;
    SimpleOutItem *item;

    core->arm_timer(core, reds->mm_timer, MM_TIMER_GRANULARITY_MS);
    if (!reds->peer) {
        return;
    }

    if (!(item = new_simple_out_item(RED_MULTI_MEDIA_TIME, sizeof(RedMultiMediaTime)))) {
        red_printf("alloc item failed");
        reds_disconnect();
        return;
    }
    time_mes = (RedMultiMediaTime *)item->data;
    time_mes->time = reds_get_mm_time() - MM_TIME_DELTA;
    reds_push_pipe_item(&item->base);
}

void reds_desable_mm_timer()
{
    core->disarm_timer(core, reds->mm_timer);
}

static void mm_timer_proc(void *opaque)
{
    red_dispatcher_set_mm_time(reds_get_mm_time());
    core->arm_timer(core, reds->mm_timer, MM_TIMER_GRANULARITY_MS);
}

static void add_monitor_action_commands(QTermInterface *mon)
{
    mon->add_action_command_handler(mon, "spice", "set_image_compression", "s",
                                    reds_do_set_image_compression,
                                    "",
                                    "<[on|auto_glz|auto_lz|quic|glz|lz|off]>");
    mon->add_action_command_handler(mon, "spice", "set_streaming_video", "s",
                                    reds_do_set_streaming_video,
                                    "",
                                    "<on|filter|all|off>");
    mon->add_action_command_handler(mon, "spice", "set_playback_compression", "s",
                                    reds_do_set_playback_compression,
                                    "",
                                    "<on|off>");
    mon->add_action_command_handler(mon, "spice", "set_ticket", "ss?",
                                    reds_do_set_ticket,
                                    "<password> [expiration=<seconds>]"
                                    "[,connected=keep|disconnect|fail]",
                                    "set the spice connection ticket");
    mon->add_action_command_handler(mon, "spice", "set_ticket64", "ss?",
                                    reds_do_set_ticket64,
                                    "<password> [expiration=<seconds>]"
                                    "[,connected=keep|disconnect|fail]",
                                    "set the spice connection ticket");
    mon->add_action_command_handler(mon, "spice", "disable_ticketing", "",
                                    reds_do_disable_ticketing,
                                    "",
                                    "entirely disables OTP");
    mon->add_action_command_handler(mon, "spice", "set_agent_mouse", "s",
                                    reds_do_set_agent_mouse,
                                    "",
                                    "<on|off>");
#ifdef RED_STATISTICS
    mon->add_action_command_handler(mon, "spice", "reset_stat", "",
                                    do_reset_statistics,
                                    "",
                                    "reset spice statistics");
    mon->add_action_command_handler(mon, "spice", "ping_client", "s?i?",
                                    do_ping_client,
                                    "[on [interval]|off]",
                                    "ping spice client to measure roundtrip");
#endif
}

static void add_monitor_action_commands_2(QTerm2Interface *mon)
{
    VDIArgDescriptor s[] = {
        { "arg1", ARG_TYPE_STRING, FALSE},
        { NULL, 0, 0},
    };

    VDIArgDescriptor empty[] = {
        { NULL, 0, 0}
    };

    VDIArgDescriptor s_s_o[] = {
        { "arg1", ARG_TYPE_STRING, FALSE},
        { "arg2", ARG_TYPE_STRING, TRUE},
        { NULL, 0, 0}
    };

    VDIArgDescriptor s_o_i_o[] = {
        { "arg1", ARG_TYPE_STRING, TRUE},
        { "arg2", ARG_TYPE_INT, TRUE},
        { NULL, 0, 0}
    };

    mon->add_action_command_handler(mon, "spice", "set_image_compression", s,
                                    reds_do_set_image_compression_2,
                                    "<[on|auto_glz|auto_lz|quic|glz|lz|off]>",
                                    "");

    mon->add_action_command_handler(mon, "spice", "set_streaming_video", s,
                                    reds_do_set_streaming_video_2,
                                    "<on|filter|all|off>",
                                    "");

    mon->add_action_command_handler(mon, "spice", "set_playback_compression", s,
                                    reds_do_set_playback_compression_2,
                                    "<on|off>",
                                    "");

    mon->add_action_command_handler(mon, "spice", "set_ticket", s_s_o,
                                    reds_do_set_ticket_2,
                                    "<password> [expiration=<seconds>]"
                                    "[,connected=keep|disconnect|fail]",
                                    "set the spice connection ticket");
    mon->add_action_command_handler(mon, "spice", "set_ticket64", s_s_o,
                                    reds_do_set_ticket64_2,
                                    "<password> [expiration=<seconds>]"
                                    "[,connected=keep|disconnect|fail]",
                                    "set the spice connection ticket");
    mon->add_action_command_handler(mon, "spice", "disable_ticketing", empty,
                                    reds_do_disable_ticketing_2,
                                    "",
                                    "entirely disables OTP");
    mon->add_action_command_handler(mon, "spice", "set_agent_mouse", s,
                                    reds_do_set_agent_mouse_2,
                                    "<on|off>",
                                    "");
#ifdef RED_STATISTICS
    mon->add_action_command_handler(mon, "spice", "reset_stat", empty,
                                    do_reset_statistics_2,
                                    "",
                                    "reset spice statistics");
    mon->add_action_command_handler(mon, "spice", "ping_client", s_o_i_o,
                                    do_ping_client_2,
                                    "[on [interval]|off]",
                                    "ping spice client to measure roundtrip");
#endif
}

static void add_monitor_info_commands(QTermInterface *mon)
{
    mon->add_info_command_handler(mon, "spice", "state",
                                  reds_do_info_spice,
                                  "show spice state");
    mon->add_info_command_handler(mon, "spice", "ticket",
                                  reds_do_info_ticket,
                                  "show ticket");
#ifdef RED_STATISTICS
    mon->add_info_command_handler(mon, "spice", "stat",
                                  do_info_statistics,
                                  "show spice statistics");
    mon->add_info_command_handler(mon, "spice", "rtt_client",
                                  do_info_rtt_client,
                                  "show rtt to spice client");
#endif
}

static void add_monitor_info_commands_2(QTerm2Interface *mon)
{
    mon->add_info_command_handler(mon, "spice", "state",
                                  reds_do_info_spice,
                                  "show spice state");
    mon->add_info_command_handler(mon, "spice", "ticket",
                                  reds_do_info_ticket,
                                  "show ticket");
#ifdef RED_STATISTICS
    mon->add_info_command_handler(mon, "spice", "stat",
                                  do_info_statistics,
                                  "show spice statistics");
    mon->add_info_command_handler(mon, "spice", "rtt_client",
                                  do_info_rtt_client,
                                  "show rtt to spice client");
#endif
}

static void attach_to_red_agent(VDIPortInterface *interface)
{
    VDIPortState *state = &reds->agent_state;

    vdagent = interface;
    reds_update_mouse_mode();
    if (!reds->peer) {
        return;
    }
    state->plug_ref = vdagent->plug(vdagent, &state->plug);
    reds->agent_state.plug_generation++;

    if (reds->mig_target) {
        return;
    }

    reds_send_agent_connected();
}

static void interface_change_notifier(void *opaque, VDInterface *interface,
                                      VDInterfaceChangeType change)
{
    if (interface->base_version != VM_INTERFACE_VERSION) {
        red_printf("unsuported base interface version");
        return;
    }
    switch (change) {
    case VD_INTERFACE_ADDING:
        if (strcmp(interface->type, VD_INTERFACE_KEYBOARD) == 0) {
            red_printf("VD_INTERFACE_KEYBOARD");
            if (keyboard) {
                red_printf("already have keyboard");
                return;
            }
            if (interface->major_version != VD_INTERFACE_KEYBOARD_MAJOR ||
                interface->minor_version < VD_INTERFACE_KEYBOARD_MINOR) {
                red_printf("unsuported keyboard interface");
                return;
            }
            keyboard = (KeyboardInterface *)interface;
            if (keyboard->register_leds_notifier) {
                if (!keyboard->register_leds_notifier(keyboard, reds_on_keyborad_leads_change, NULL)) {
                    red_error("register leds  notifier failed");
                }
            }
        } else if (strcmp(interface->type, VD_INTERFACE_MOUSE) == 0) {
            red_printf("VD_INTERFACE_MOUSE");
            if (mouse) {
                red_printf("already have mouse");
                return;
            }
            if (interface->major_version != VD_INTERFACE_MOUSE_MAJOR ||
                interface->minor_version < VD_INTERFACE_MOUSE_MINOR) {
                red_printf("unsuported mouse interface");
                return;
            }
            mouse = (MouseInterface *)interface;
        } else if (strcmp(interface->type, VD_INTERFACE_MIGRATION) == 0) {
            red_printf("VD_INTERFACE_MIGRATION");
            if (mig) {
                red_printf("already have migration");
                return;
            }
            if (interface->major_version != VD_INTERFACE_MIGRATION_MAJOR ||
                interface->minor_version < VD_INTERFACE_MIGRATION_MINOR) {
                red_printf("unsuported migration interface");
                return;
            }
            mig = (MigrationInterface *)interface;
            reds->mig_notifier = mig->register_notifiers(mig, MIGRATION_NOTIFY_SPICE_KEY,
                                                         reds_mig_started, reds_mig_finished,
                                                         reds_mig_recv, NULL);
            if (reds->mig_notifier == INVALID_VD_OBJECT_REF) {
                red_error("migration register failed");
            }
        } else if (strcmp(interface->type, VD_INTERFACE_QXL) == 0) {
            QXLInterface *qxl_interface;

            red_printf("VD_INTERFACE_QXL");
            if (interface->major_version != VD_INTERFACE_QXL_MAJOR ||
                interface->minor_version < VD_INTERFACE_QXL_MINOR) {
                red_printf("unsuported qxl interface");
                return;
            }
            qxl_interface = (QXLInterface *)interface;
            red_dispatcher_init(qxl_interface);
        } else if (strcmp(interface->type, VD_INTERFACE_QTERM) == 0) {
            static int was_here = FALSE;
            red_printf("VD_INTERFACE_QTERM");
            if (was_here) {
                return;
            }
            was_here = TRUE;
            if (interface->major_version != VD_INTERFACE_QTERM_MAJOR ||
                interface->minor_version < VD_INTERFACE_QTERM_MINOR) {
                red_printf("unsuported qterm interface");
                return;
            }
            add_monitor_action_commands((QTermInterface *)interface);
            add_monitor_info_commands((QTermInterface *)interface);
        } else if (strcmp(interface->type, VD_INTERFACE_QTERM2) == 0) {
            static int was_here = FALSE;
            red_printf("VD_INTERFACE_QTERM2");
            if (was_here) {
                return;
            }
            was_here = TRUE;
            if (interface->major_version != VD_INTERFACE_QTERM2_MAJOR ||
                interface->minor_version < VD_INTERFACE_QTERM2_MINOR) {
                red_printf("unsuported qterm interface");
                return;
            }
            add_monitor_action_commands_2((QTerm2Interface *)interface);
            add_monitor_info_commands_2((QTerm2Interface *)interface);
        } else if (strcmp(interface->type, VD_INTERFACE_TABLET) == 0) {
            red_printf("VD_INTERFACE_TABLET");
            if (tablet) {
                red_printf("already have tablet");
                return;
            }
            if (interface->major_version != VD_INTERFACE_TABLET_MAJOR ||
                interface->minor_version < VD_INTERFACE_TABLET_MINOR) {
                red_printf("unsuported tablet interface");
                return;
            }
            tablet = (TabletInterface *)interface;
            reds_update_mouse_mode();
            if (reds->is_client_mouse_allowed) {
                tablet->set_logical_size(tablet, reds->monitor_mode.x_res,
                                         reds->monitor_mode.y_res);
            }
        } else if (strcmp(interface->type, VD_INTERFACE_PLAYBACK) == 0) {
            red_printf("VD_INTERFACE_PLAYBACK");
            if (interface->major_version != VD_INTERFACE_PLAYBACK_MAJOR ||
                interface->minor_version < VD_INTERFACE_PLAYBACK_MINOR) {
                red_printf("unsuported playback interface");
                return;
            }
            snd_attach_playback((PlaybackInterface *)interface);
        } else if (strcmp(interface->type, VD_INTERFACE_RECORD) == 0) {
            red_printf("VD_INTERFACE_RECORD");
            if (interface->major_version != VD_INTERFACE_RECORD_MAJOR ||
                interface->minor_version < VD_INTERFACE_RECORD_MINOR) {
                red_printf("unsuported record interface");
                return;
            }
            snd_attach_record((RecordInterface *)interface);
        } else if (strcmp(interface->type, VD_INTERFACE_VDI_PORT) == 0) {
            red_printf("VD_INTERFACE_VDI_PORT");
            if (vdagent) {
                red_printf("vdi port already attached");
                return;
            }
            if (interface->major_version != VD_INTERFACE_VDI_PORT_MAJOR ||
                interface->minor_version < VD_INTERFACE_VDI_PORT_MINOR) {
                red_printf("unsuported vdi port interface");
                return;
            }
            attach_to_red_agent((VDIPortInterface *)interface);
        }
        break;
    case VD_INTERFACE_REMOVING:
        if (strcmp(interface->type, VD_INTERFACE_TABLET) == 0) {
            red_printf("remove VD_INTERFACE_TABLET");
            if (interface == (VDInterface *)tablet) {
                tablet = NULL;
                reds_update_mouse_mode();
            }
            break;
        } else if (strcmp(interface->type, VD_INTERFACE_PLAYBACK) == 0) {
            red_printf("remove VD_INTERFACE_PLAYBACK");
            snd_detach_playback((PlaybackInterface *)interface);
            break;
        } else if (strcmp(interface->type, VD_INTERFACE_RECORD) == 0) {
            red_printf("remove VD_INTERFACE_RECORD");
            snd_detach_record((RecordInterface *)interface);
            break;
        } else if (strcmp(interface->type, VD_INTERFACE_VDI_PORT) == 0) {
            red_printf("remove VD_INTERFACE_VDI_PORT");
            if (interface == (VDInterface *)vdagent) {
                reds_agent_remove();
            }
            break;
        }
        red_error("VD_INTERFACE_REMOVING unsupported");
        break;
    }
}

static void free_external_agent_buff(VDIPortBuf *in_buf)
{
    VDIPortState *state = &reds->agent_state;

    ring_add(&state->external_bufs, &in_buf->link);
    add_token();
}

static void free_internal_agent_buff(VDIPortBuf *in_buf)
{
    VDIPortState *state = &reds->agent_state;

    ring_add(&state->internal_bufs, &in_buf->link);
    if (reds->inputs_state && reds->inputs_state->pending_mouse_event) {
        reds_handle_agent_mouse_event();
    }
}

void reds_prepare_read_buf(RedsOutItem *in_nuf, struct iovec* vec, int *len)
{
    VDIReadBuf *buf = (VDIReadBuf *)in_nuf;

    vec[0].iov_base = &buf->header;
    vec[0].iov_len = sizeof(buf->header);
    vec[1].iov_base = buf->data;
    vec[1].iov_len = buf->len;
    *len = 2;
}

void reds_release_read_buf(RedsOutItem *in_nuf)
{
    VDIReadBuf *buf = (VDIReadBuf *)in_nuf;

    ring_add(&reds->agent_state.read_bufs, &buf->out_item.link);
    read_from_vdi_port();
}

static void init_vd_agent_resources()
{
    VDIPortState *state = &reds->agent_state;
    int i;

    ring_init(&state->external_bufs);
    ring_init(&state->internal_bufs);
    ring_init(&state->write_queue);
    ring_init(&state->read_bufs);

    state->read_state = VDI_PORT_READ_STATE_READ_HADER;
    state->recive_pos = (uint8_t *)&state->vdi_chunk_header;
    state->recive_len = sizeof(state->vdi_chunk_header);

    for (i = 0; i < REDS_AGENT_WINDOW_SIZE; i++) {
        VDAgentExtBuf *buf = (VDAgentExtBuf *)malloc(sizeof(VDAgentExtBuf));
        if (!buf) {
            PANIC("alloc failed");
        }
        memset(buf, 0, sizeof(*buf));
        ring_item_init(&buf->base.link);
        buf->base.chunk_header.port = VDP_CLIENT_PORT;
        buf->base.free = free_external_agent_buff;
        ring_add(&reds->agent_state.external_bufs, &buf->base.link);
    }

    for (i = 0; i < REDS_NUM_INTERNAL_AGENT_MESSAGES; i++) {
        VDInternalBuf *buf = (VDInternalBuf *)malloc(sizeof(VDInternalBuf));
        if (!buf) {
            PANIC("alloc failed");
        }
        memset(buf, 0, sizeof(*buf));
        ring_item_init(&buf->base.link);
        buf->base.free = free_internal_agent_buff;
        buf->base.chunk_header.port = VDP_SERVER_PORT;
        buf->base.chunk_header.size = sizeof(VDAgentMessage) + sizeof(VDAgentMouseState);
        buf->header.protocol = VD_AGENT_PROTOCOL;
        buf->header.type = VD_AGENT_MOUSE_STATE;
        buf->header.opaque = 0;
        buf->header.size = sizeof(VDAgentMouseState);
        ring_add(&reds->agent_state.internal_bufs, &buf->base.link);
    }

    for (i = 0; i < REDS_VDI_PORT_NUM_RECIVE_BUFFS; i++) {
        VDIReadBuf *buf = (VDIReadBuf *)malloc(sizeof(VDIReadBuf));
        if (!buf) {
            PANIC("alloc failed");
        }
        memset(buf, 0, sizeof(*buf));
        buf->out_item.prepare = reds_prepare_read_buf;
        buf->out_item.release = reds_release_read_buf;
        buf->header.type = RED_AGENT_DATA;
        buf->header.sub_list = 0;
        ring_item_init(&buf->out_item.link);
        ring_add(&reds->agent_state.read_bufs, &buf->out_item.link);
    }

    state->plug.major_version = VD_INTERFACE_VDI_PORT_MAJOR;
    state->plug.minor_version = VD_INTERFACE_VDI_PORT_MINOR;
    state->plug.wakeup = reds_agent_wakeup;
}

static const char *version_string = VERSION;
static const char *patch_string = PATCHID;
static const char *distro_string = DISTRIBUTION;

static void do_spice_init(CoreInterface *core_interface)
{
    VDInterface *interface = NULL;

    red_printf("starting %s%s%s%s%s", version_string,
               strlen(patch_string) ? "-" : "", patch_string,
               strlen(distro_string) ? "." : "", distro_string);

    if (core_interface->base.base_version != VM_INTERFACE_VERSION) {
        red_error("bad base interface version");
    }

    if (core_interface->base.major_version != VD_INTERFACE_CORE_MAJOR) {
        red_error("bad core interface version");
    }
    core = core_interface;
    if (core_interface->base.minor_version > 1) {
        log_proc = core->log;
    }
    reds->listen_socket = -1;
    reds->secure_listen_socket = -1;
    reds->peer = NULL;
    reds->in_handler.handle_message = reds_main_handle_message;
    ring_init(&reds->outgoing.pipe);
    reds->outgoing.vec = reds->outgoing.vec_buf;

    init_vd_agent_resources();

    if (!(reds->mig_timer = core->create_timer(core, migrate_timout, NULL))) {
        red_error("migration timer create failed");
    }
    if (!(reds->key_modifiers_timer = core->create_timer(core, key_modifiers_sender, NULL))) {
        red_error("key modifiers timer create failed");
    }

    if (core->next) {
        while ((interface = core->next(core, interface))) {
            interface_change_notifier(&reds, interface, VD_INTERFACE_ADDING);
        }
    }
    if (core->register_change_notifiers) {
        core->register_change_notifiers(core, &reds, interface_change_notifier);
    }

#ifdef RED_STATISTICS
    int shm_name_len = strlen(REDS_STAT_SHM_NAME) + 20;
    int fd;

    if (!(reds->stat_shm_name = (char *)malloc(shm_name_len))) {
        red_error("stat_shm_name alloc failed");
    }
    snprintf(reds->stat_shm_name, shm_name_len, REDS_STAT_SHM_NAME, getpid());
    if ((fd = shm_open(reds->stat_shm_name, O_CREAT | O_RDWR, 0444)) == -1) {
        red_error("statistics shm_open failed, %s", strerror(errno));
    }
    if (ftruncate(fd, REDS_STAT_SHM_SIZE) == -1) {
        red_error("statistics ftruncate failed, %s", strerror(errno));
    }
    reds->stat = mmap(NULL, REDS_STAT_SHM_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    if (reds->stat == (RedsStat *)MAP_FAILED) {
        red_error("statistics mmap failed, %s", strerror(errno));
    }
    memset(reds->stat, 0, REDS_STAT_SHM_SIZE);
    reds->stat->magic = REDS_STAT_MAGIC;
    reds->stat->version = REDS_STAT_VERSION;
    reds->stat->root_index = INVALID_STAT_REF;
    if (pthread_mutex_init(&reds->stat_lock, NULL)) {
        red_error("mutex init failed");
    }
    if (!(reds->ping_timer = core->create_timer(core, ping_timer_cb, NULL))) {
        red_error("ping timer create failed");
    }
    reds->ping_interval = PING_INTERVAL;
#endif

    if (!(reds->mm_timer = core->create_timer(core, mm_timer_proc, NULL))) {
        red_error("mm timer create failed");
    }
    core->arm_timer(core, reds->mm_timer, MM_TIMER_GRANULARITY_MS);

    reds_init_net();
    if (reds->secure_listen_socket != -1) {
        reds_init_ssl();
    }
    inputs_init();

    reds->mouse_mode = RED_MOUSE_MODE_SERVER;
    atexit(reds_exit);
}

void __attribute__ ((visibility ("default"))) spice_init(CoreInterface *core_interface)
{
    spice_server_new();
    do_spice_init(core_interface);
}

/* new interface */
SpiceServer *spice_server_new(void)
{
    /* we can't handle multiple instances (yet) */
    ASSERT(reds == NULL);

    if (!(reds = malloc(sizeof(RedsState)))) {
        red_error("reds alloc failed");
    }
    memset(reds, 0, sizeof(RedsState));
    return reds;
}

int spice_server_init(SpiceServer *s, CoreInterface *core)
{
    ASSERT(reds == s);
    do_spice_init(core);
    if (default_renderer)
        red_dispatcher_add_renderer(default_renderer);
    return 0;
}

void spice_server_destroy(SpiceServer *s)
{
    ASSERT(reds == s);
    reds_exit();
}

int spice_server_set_port(SpiceServer *s, int port)
{
    ASSERT(reds == s);
    if (port < 0 || port > 0xffff)
        return -1;
    spice_port = port;
    return 0;
}

void spice_server_set_addr(SpiceServer *s, const char *addr, int flags)
{
    ASSERT(reds == s);
    strncpy(spice_addr, addr, sizeof(spice_addr));
    if (flags & SPICE_ADDR_FLAG_IPV4_ONLY) {
        spice_family = PF_INET;
    }
    if (flags & SPICE_ADDR_FLAG_IPV6_ONLY) {
        spice_family = PF_INET6;
    }
}

int spice_server_set_noauth(SpiceServer *s)
{
    ASSERT(reds == s);
    memset(taTicket.password, 0, sizeof(taTicket.password));
    ticketing_enabled = 0;
    return 0;
}

int spice_server_set_ticket(SpiceServer *s, const char *passwd, int lifetime,
                            int fail_if_connected, int disconnect_if_connected)
{
    ASSERT(reds == s);

    if (reds->peer) {
        if (fail_if_connected)
            return -1;
        if (disconnect_if_connected)
            reds_disconnect();
    }

    on_activating_ticketing();
    ticketing_enabled = 1;
    if (lifetime == 0) {
        taTicket.expiration_time = INT_MAX;
    } else {
        time_t now = time(NULL);
        taTicket.expiration_time = now + lifetime;
    }
    if (passwd != NULL) {
        strncpy(taTicket.password, passwd, sizeof(taTicket.password));
    } else {
        memset(taTicket.password, 0, sizeof(taTicket.password));
        taTicket.expiration_time = 0;
    }
    return 0;
}

int spice_server_set_tls(SpiceServer *s, int port,
                         const char *ca_cert_file, const char *certs_file,
                         const char *private_key_file, const char *key_passwd,
                         const char *dh_key_file, const char *ciphersuite)
{
    ASSERT(reds == s);
    if (port == 0 || ca_cert_file == NULL || certs_file == NULL ||
        private_key_file == NULL) {
        return -1;
    }
    if (port < 0 || port > 0xffff)
        return -1;
    memset(&ssl_parameters, 0, sizeof(ssl_parameters));

    spice_secure_port = port;
    strncpy(ssl_parameters.ca_certificate_file, ca_cert_file,
            sizeof(ssl_parameters.ca_certificate_file)-1);
    strncpy(ssl_parameters.certs_file, certs_file,
            sizeof(ssl_parameters.certs_file)-1);
    strncpy(ssl_parameters.private_key_file, private_key_file,
            sizeof(ssl_parameters.private_key_file)-1);

    if (key_passwd) {
        strncpy(ssl_parameters.keyfile_password, key_passwd,
                sizeof(ssl_parameters.keyfile_password)-1);
    }
    if (ciphersuite) {
        strncpy(ssl_parameters.ciphersuite, ciphersuite,
                sizeof(ssl_parameters.ciphersuite)-1);
    }
    if (dh_key_file) {
        strncpy(ssl_parameters.dh_key_file, dh_key_file,
                sizeof(ssl_parameters.dh_key_file)-1);
    }
    return 0;
}

int spice_server_set_image_compression(SpiceServer *s,
                                       spice_image_compression_t comp)
{
    ASSERT(reds == s);
    set_image_compression(comp);
    return 0;
}

spice_image_compression_t spice_server_get_image_compression(SpiceServer *s)
{
    ASSERT(reds == s);
    return image_compression;
}

int spice_server_set_channel_security(SpiceServer *s,
                                      spice_channel_t channel,
                                      int security)
{
    ASSERT(reds == s);
    if (channel == SPICE_CHANNEL_ALL) {
        set_all_channels_security(security);
    } else {
        set_one_channel_security(channel, security);
    }
    return 0;
}

int spice_server_set_mouse_absolute(SpiceServer *s, int absolute)
{
    uint32_t mode = absolute ? RED_MOUSE_MODE_CLIENT : RED_MOUSE_MODE_SERVER;

    ASSERT(reds == s);
    reds_set_mouse_mode(mode);
    return 0;
}

int spice_server_add_renderer(SpiceServer *s, const char *name)
{
    ASSERT(reds == s);
    if (!red_dispatcher_add_renderer(name))
        return -1;
    default_renderer = NULL;
    return 0;
}

int spice_server_add_interface(SpiceServer *s, VDInterface *interface)
{
    ASSERT(reds == s);
    interface_change_notifier(NULL, interface, VD_INTERFACE_ADDING);
    return 0;
}

int spice_server_remove_interface(SpiceServer *s, VDInterface *interface)
{
    ASSERT(reds == s);
    interface_change_notifier(NULL, interface, VD_INTERFACE_REMOVING);
    return 0;
}

int spice_server_kbd_leds(SpiceServer *s, KeyboardInterface *kbd, int leds)
{
    ASSERT(reds == s);
    reds_on_keyborad_leads_change(NULL, leds);
    return 0;
}