summaryrefslogtreecommitdiff
path: root/ytstenut/yts-client.c
blob: 2faee0639f20ed8f1372faf19b2e6c31f9965874 (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
/*
 * Copyright © 2011 Intel Corp.
 *
 * This  library is free  software; you can  redistribute it and/or
 * modify it  under  the terms  of the  GNU Lesser  General  Public
 * License  as published  by the Free  Software  Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed  in the hope that it will be useful,
 * but  WITHOUT ANY WARRANTY; without even  the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library. If not, see
 * <http://www.gnu.org/licenses/>.
 *
 * Authored by: Tomas Frydrych <tf@linux.intel.com>
 *              Rob Staudinger <robsta@linux.intel.com>
 */

#include <string.h>
#include <rest/rest-xml-parser.h>
#include <telepathy-glib/telepathy-glib.h>
#include <telepathy-glib/connection-manager.h>
#include <telepathy-glib/gtypes.h>
#include <telepathy-glib/connection.h>
#include <telepathy-glib/account.h>
#include <telepathy-glib/interfaces.h>
#include <telepathy-glib/util.h>
#include <telepathy-glib/contact.h>
#include <telepathy-glib/debug.h>
#include <telepathy-glib/proxy-subclass.h>
#include <telepathy-ytstenut-glib/telepathy-ytstenut-glib.h>

#include "empathy-tp-file.h"
#include "ytstenut-internal.h"
#include "yts-adapter-factory.h"
#include "yts-client-internal.h"
#include "yts-client-status.h"
#include "yts-contact-internal.h"
#include "yts-enum-types.h"
#include "yts-error-message.h"
#include "yts-event-message.h"
#include "yts-invocation-message.h"
#include "yts-marshal.h"
#include "yts-metadata-internal.h"
#include "yts-outgoing-file-internal.h"
#include "yts-response-message.h"
#include "yts-roster-impl.h"
#include "yts-service.h"
#include "yts-service-adapter.h"
#include "yts-xml.h"

#include "profile/yts-profile.h"
#include "profile/yts-profile-adapter.h"
#include "profile/yts-profile-impl.h"

#include "config.h"

#define RECONNECT_DELAY 20 /* in seconds */

static void yts_client_make_connection (YtsClient *client);

G_DEFINE_TYPE (YtsClient, yts_client, G_TYPE_OBJECT)

#define GET_PRIVATE(o) \
  (G_TYPE_INSTANCE_GET_PRIVATE ((o), YTS_TYPE_CLIENT, YtsClientPrivate))

#undef G_LOG_DOMAIN
#define G_LOG_DOMAIN PACKAGE"\0client\0"G_STRLOC

/**
 * SECTION: yts-client
 * @title: YtsClient
 * @short_description: Represents a connection to the Ytstenut mesh.
 *
 * #YtsClient is an object that mediates connection between the current
 * application and the Ytstenut application mesh. It provides access to roster
 * of availalble services (#YtsRoster) and means to advertises status within
 * the mesh.
 */

typedef struct {
  YtsRoster       *roster;    /* the roster of this client */
  YtsRoster       *unwanted;  /* roster of unwanted items */
  YtsClientStatus *client_status;

  /* connection parameters */
  char        *account_id;
  char        *service_id;
  YtsProtocol  protocol;

  char         *incoming_dir; /* destination directory for incoming files */

  /* Telepathy bits */
  TpYtsAccountManager  *tp_am;
  TpAccount            *tp_account;
  TpConnection         *tp_conn;
  TpProxy              *tp_debug_proxy;
  TpYtsStatus          *tp_status;
  TpYtsClient          *tp_client;

  /* Implemented services */
  GHashTable  *services;

  /* Ongoing invocations */
  GHashTable  *invocations;

  /* Registered proxies */
  GHashTable *proxies;

  /* callback ids */
  guint reconnect_id;

  bool authenticated;   /* are we authenticated ? */
  bool ready;           /* is TP setup done ? */
  bool connect;         /* connect once we get our connection ? */
  bool reconnect;       /* should we attempt to reconnect ? */
  bool dialing;         /* are we currently acquiring connection ? */
  bool members_pending; /* requery members when TP set up completed ? */
  bool prepared;        /* are connection features set up ? */
  bool disposed;        /* dispose guard */

} YtsClientPrivate;

enum
{
  AUTHENTICATED,
  READY,
  DISCONNECTED,
  RAW_MESSAGE,
  TEXT_MESSAGE,
  LIST_MESSAGE,
  DICTIONARY_MESSAGE,
  ERROR,
  INCOMING_FILE,
  INCOMING_FILE_FINISHED,
  N_SIGNALS,
};

enum
{
  PROP_0,
  PROP_ACCOUNT_ID,
  PROP_CONTACT_ID,
  PROP_SERVICE_ID,
  PROP_PROTOCOL,

  PROP_TP_ACCOUNT
};

static guint signals[N_SIGNALS] = {0};

/*
 * ServiceData
 */

typedef struct {
  YtsClient  *client;
  char        *capability;
} ServiceData;

static ServiceData *
service_data_create (YtsClient *client,
                     char const *capability)
{
  ServiceData *self;

  g_return_val_if_fail (YTS_IS_CLIENT (client), NULL);
  g_return_val_if_fail (capability, NULL);

  self = g_new0 (ServiceData, 1);
  self->client = g_object_ref (client);
  self->capability = g_strdup (capability);

  return self;
}

static void
service_data_destroy (ServiceData *self)
{
  g_return_if_fail (self);

  g_object_unref (self->client);
  g_free (self->capability);
  g_free (self);
}

/*
 * InvocationData
 */

/* PONDERING this should probably be configurable. */
#define INVOCATION_RESPONSE_TIMEOUT_S 20

typedef struct {
  YtsClient    *client;            /* free pointer, no ref */
  YtsContact   *contact;           /* free pointer, no ref */
  char          *proxy_id;
  char          *invocation_id;
  unsigned int   timeout_s;
  unsigned int   timeout_id;
} InvocationData;

static void
invocation_data_destroy (InvocationData *self)
{
  g_return_if_fail (self);

  if (self->timeout_id) {
    g_source_remove (self->timeout_id);
    self->timeout_id = 0;
  }

  g_free (self->proxy_id);
  g_free (self->invocation_id);
  g_free (self);
}

static bool
client_conclude_invocation (YtsClient  *self,
                            char const  *invocation_id)
{
  YtsClientPrivate *priv = GET_PRIVATE (self);
  bool found;

  found = g_hash_table_remove (priv->invocations, invocation_id);
  if (!found) {
    g_warning ("%s : Pending invocation for ID %s not found",
               G_STRLOC,
               invocation_id);
    return false;
  }

  return true;
}

static bool
_invocation_timeout (InvocationData *self)
{
  g_critical ("%s : Invocation %s timed out after %i seconds",
              G_STRLOC,
              self->invocation_id,
              self->timeout_s);

  /* This destroys self */
  client_conclude_invocation (self->client, self->invocation_id);

  // TODO emit timeout / error

  /* Remove timeout */
  return false;
}

static InvocationData *
invocation_data_create (YtsClient    *client,
                        YtsContact   *contact,
                        char const    *proxy_id,
                        char const    *invocation_id,
                        unsigned int   timeout_s)
{
  InvocationData *self;

  self = g_new0 (InvocationData, 1);
  self->client = client;
  self->contact = contact;
  self->proxy_id = g_strdup (proxy_id);
  self->invocation_id = g_strdup (invocation_id);
  self->timeout_s = timeout_s;
  self->timeout_id = g_timeout_add_seconds (timeout_s,
                                            (GSourceFunc) _invocation_timeout,
                                            self);

  return self;
}

static bool
client_establish_invocation (YtsClient   *self,
                             char const   *invocation_id,
                             YtsContact  *contact,
                             char const   *proxy_id)
{
  YtsClientPrivate *priv = GET_PRIVATE (self);
  InvocationData *invocation_data;

  invocation_data = g_hash_table_lookup (priv->invocations,
                                         invocation_id);
  if (invocation_data) {
    /* Already an invocation running with this ID, bail out. */
    g_critical ("%s: Already have an invocation for ID %s",
                G_STRLOC,
                invocation_id);
    return false;
  }

  invocation_data = invocation_data_create (self,
                                            contact,
                                            proxy_id,
                                            invocation_id,
                                            INVOCATION_RESPONSE_TIMEOUT_S);
  g_hash_table_insert (priv->invocations,
                       g_strdup (invocation_id),
                       invocation_data);

  return true;
}

/*
 * ProxyData
 */

typedef struct {
  YtsContact const *contact;    /* free pointer, no ref. */
  char              *proxy_id;
} ProxyData;

static ProxyData *
proxy_data_create (YtsContact const  *contact,
                   char const         *proxy_id)
{
  ProxyData *self;

  self = g_new0 (ProxyData, 1);
  self->contact = contact;
  self->proxy_id = g_strdup (proxy_id);

  return self;
}

static void
proxy_data_destroy (ProxyData *self)
{
  g_free (self->proxy_id);
  g_free (self);
}

/*
 * ProxyList
 */

typedef struct {
  GList *list;
} ProxyList;

static ProxyList *
proxy_list_create_with_proxy (YtsContact const *contact,
                              char const        *proxy_id)
{
  ProxyList *self;
  ProxyData *data;

  self = g_new0 (ProxyList, 1);

  data = proxy_data_create (contact, proxy_id);

  self->list = g_list_append (NULL, data);

  return self;
}

static bool
proxy_list_ensure_proxy (ProxyList          *self,
                         YtsContact const  *contact,
                         char const         *proxy_id)
{
  GList const *iter;
  ProxyData   *proxy_data;

  g_return_val_if_fail (self, false);
  g_warn_if_fail (self->list);

  for (iter = self->list; iter; iter = iter->next) {
    proxy_data = (ProxyData *) iter->data;
    if (proxy_data->contact == contact &&
        0 == g_strcmp0 (proxy_data->proxy_id, proxy_id)) {
      /* Proxy already in list */
      return false;
    }
  }

  proxy_data = proxy_data_create (contact, proxy_id);
  self->list = g_list_prepend (self->list, proxy_data);

  return true;
}

static void
proxy_list_purge_contact (ProxyList         *self,
                          YtsContact const *contact)
{
  GList *iter;
  bool   found;

  g_return_if_fail (self);
  g_return_if_fail (self->list);

  // FIXME need to do this in a smarter way.
  do {
    found = false;
    for (iter = self->list; iter; iter = iter->next) {

      ProxyData *data = (ProxyData *) iter->data;

      if (data->contact == contact) {
        proxy_data_destroy (data);
        iter->data = NULL;
        self->list = g_list_delete_link (self->list, iter);
        found = true;
        break;
      }
    }
  } while (found);
}

static void
proxy_list_purge_proxy_id (ProxyList  *self,
                           char const *proxy_id)
{
  GList *iter;
  bool   found;

  g_return_if_fail (self);
  g_return_if_fail (self->list);

  // FIXME need to do this in a smarter way.
  do {
    found = false;
    for (iter = self->list; iter; iter = iter->next) {

      ProxyData *data = (ProxyData *) iter->data;

      if (0 == g_strcmp0 (data->proxy_id, proxy_id)) {
        proxy_data_destroy (data);
        iter->data = NULL;
        self->list = g_list_delete_link (self->list, iter);
        found = true;
        break;
      }
    }
  } while (found);
}

static bool
proxy_list_is_empty (ProxyList  *self)
{
  g_return_val_if_fail (self, true);

  return self->list == NULL;
}

static void
proxy_list_destroy (ProxyList *self)
{
  g_return_if_fail (self);

  if (self->list) {
    do {
      ProxyData *data = (ProxyData *) self->list->data;
      proxy_data_destroy (data);
      self->list->data = NULL;
    } while (NULL != (self->list = g_list_delete_link (self->list, self->list)));
  }

  g_free (self);
}

/*
 * YtsClient
 */

static gboolean
yts_client_channel_requested (TpChannel *proxy)
{
  GHashTable *props;
  gboolean    requested;

  props = tp_channel_borrow_immutable_properties ((TpChannel*)proxy);

  requested = tp_asv_get_boolean (props, TP_PROP_CHANNEL_REQUESTED, NULL);

  return requested;
}

static void
yts_client_ft_op_cb (EmpathyTpFile *tp_file,
                      const GError  *error,
                      gpointer       data)
{
  if (error)
    {
      g_warning ("Incoming file transfer failed: %s", error->message);
    }
}

static void
yts_client_ft_accept_cb (TpProxy      *proxy,
                          GHashTable   *props,
                          const GError *error,
                          gpointer      self,
                          GObject      *weak_object)
{
  YtsClientPrivate *priv = GET_PRIVATE (self);
  char const        *name;
  char const        *contact_id;
  uint64_t            offset;
  uint64_t            size;
  GHashTable        *iprops;
  YtsContact       *item;
  guint32            ihandle;

  iprops = tp_channel_borrow_immutable_properties ((TpChannel*)proxy);

  ihandle = tp_asv_get_uint32 (iprops,
                               TP_PROP_CHANNEL_INITIATOR_HANDLE,
                               NULL);

  if ((item = yts_roster_find_contact_by_handle (priv->roster, ihandle)))
    {
      contact_id = yts_contact_get_id (item);
    }
  else
    {
      g_warning ("Unknown originator with handle %d", ihandle);

      tp_cli_channel_call_close ((TpChannel*)proxy,
                                 -1,
                                 NULL,
                                 NULL,
                                 NULL,
                                 NULL);

      return;
    }

  tp_asv_dump (props);

  name   = tp_asv_get_string (props, "Filename");
  offset = tp_asv_get_uint64 (props, "InitialOffset", NULL);
  size   = tp_asv_get_uint64 (props, "Size", NULL);

  if (!size || size < offset)
    {
      g_warning ("Meaningless file size");

      tp_cli_channel_call_close ((TpChannel*)proxy,
                                 -1,
                                 NULL,
                                 NULL,
                                 NULL,
                                 NULL);

      return;
    }

  g_signal_emit (self, signals[INCOMING_FILE], 0,
                 contact_id, name, size, offset, proxy);
}

static void
yts_client_ft_handle_state (YtsClient *self, TpChannel *proxy, guint state)
{
  YtsClientPrivate *priv = GET_PRIVATE (self);
  GHashTable        *props;
  gboolean           requested;

  props = tp_channel_borrow_immutable_properties ((TpChannel*)proxy);
  if (!(requested = tp_asv_get_boolean (props, TP_PROP_CHANNEL_REQUESTED,NULL)))
    {
      YtsContact *item;
      guint32      ihandle;

      ihandle = tp_asv_get_uint32 (props,
                                   TP_PROP_CHANNEL_INITIATOR_HANDLE,
                                   NULL);
      item = yts_roster_find_contact_by_handle (priv->roster, ihandle);

      switch (state)
        {
        case 1:
          {
            if (item)
              g_message ("Got request for FT channel from %s (%s)",
                         yts_contact_get_id (item),
                         tp_proxy_get_bus_name (proxy));
            else
              g_message ("Got request for FT channel from handle %d",
                         ihandle);

            tp_cli_dbus_properties_call_get_all (proxy,
                                           -1,
                                           TP_IFACE_CHANNEL_TYPE_FILE_TRANSFER,
                                           yts_client_ft_accept_cb,
                                           self,
                                           NULL,
                                           (GObject*) self);
          }
          break;
        case 2:
          g_message ("Incoming stream state (%s) --> 'accepted'",
                     tp_proxy_get_bus_name (proxy));
          break;
        case 3:
          g_message ("Incoming stream state (%s) --> 'open'",
                     tp_proxy_get_bus_name (proxy));
          break;
        case 4:
        case 5:
          g_message ("Incoming stream state (%s) --> '%s'",
                     tp_proxy_get_bus_name (proxy),
                     state == 4 ? "completed" : "cancelled");
          {
            char const *name;
            char const *contact_id;

            if (item)
              {
                contact_id = yts_contact_get_id (item);

                name   = tp_asv_get_string (props, "Filename");

                g_signal_emit (self, signals[INCOMING_FILE_FINISHED], 0,
                               contact_id, name, state == 4 ? TRUE : FALSE);
              }
          }
          break;
        default:
          g_message ("Invalid value of stream state: %d", state);
        }
    }
  else
    g_message ("The FT channel was requested by us ... (%s)",
             tp_proxy_get_bus_name (proxy));
}

static void
yts_client_ft_state_cb (TpChannel *proxy,
                         guint      state,
                         guint      reason,
                         gpointer   data,
                         GObject   *object)
{
  YtsClient *client = data;

  g_message ("FT channel changed status to %d (reason %d)", state, reason);

  yts_client_ft_handle_state (client, proxy, state);
}

static void
yts_client_ft_core_cb (GObject *proxy, GAsyncResult *res, gpointer data)
{
  YtsClient *client  = data;
  TpChannel  *channel = (TpChannel*) proxy;
  GError     *error   = NULL;

  g_message ("FT channel ready");

  tp_cli_channel_type_file_transfer_connect_to_file_transfer_state_changed
    (channel,
     yts_client_ft_state_cb,
     client,
     NULL,
     (GObject*)client,
     &error);

  if (!yts_client_channel_requested (channel))
    yts_client_ft_handle_state (client, channel, 1);
}

static void
yts_client_channel_cb (TpConnection *proxy,
                        char const   *path,
                        char const   *type,
                        guint         handle_type,
                        guint         handle,
                        gboolean      suppress_handle,
                        gpointer      self,
                        GObject      *weak_object)
{
  YtsClientPrivate *priv = GET_PRIVATE (self);

  if (!path)
    {
      g_warning (G_STRLOC ":%s: no path!", __FUNCTION__);
      return;
    }

  g_message ("New channel: %s: %s: h type %d, h %d",
             path, type, handle_type, handle);

  switch (handle_type)
    {
    case TP_HANDLE_TYPE_CONTACT:
      /* FIXME -- this is where the messaging channel will go */
      if (!g_strcmp0 (type, TP_IFACE_CHANNEL_TYPE_FILE_TRANSFER))
        {
          GError      *error = NULL;
          TpChannel   *ch;
          GQuark       features[] = { TP_CHANNEL_FEATURE_CORE, 0};
          YtsContact *item;

          ch = tp_channel_new (proxy, path, type, handle_type, handle, &error);

          if ((item = yts_roster_find_contact_by_handle (priv->roster,
                                                           handle)))
            {
              yts_contact_set_ft_channel (item, ch);

              tp_proxy_prepare_async (ch, features,
                                      yts_client_ft_core_cb, self);
            }
          else
            {
              g_warning (G_STRLOC ": orphaned channel ?");
              g_object_unref (ch);
            }
        }
      break;
    case TP_HANDLE_TYPE_LIST:
      break;
    case TP_HANDLE_TYPE_GROUP:
      break;
    default:;
    }
}

static void
yts_client_authenticated (YtsClient *self)
{
  YtsClientPrivate *priv = GET_PRIVATE (self);

  priv->authenticated = true;

  g_message ("Authenticated");
}

static void
_tp_yts_status_advertise_status_cb (GObject       *source_object,
                                    GAsyncResult  *result,
                                    gpointer       user_data)
{
  TpYtsStatus *status = TP_YTS_STATUS (source_object);
  GError      *error = NULL;

  if (!tp_yts_status_advertise_status_finish (status, result, &error)) {
      g_critical ("Failed to advertise status: %s", error->message);
  } else {
    g_message ("Advertising of status succeeded");
  }

  g_clear_error (&error);
}

static bool
_client_status_foreach_capability_advertise_status (YtsClientStatus const *client_status,
                                                    char const            *capability,
                                                    char const            *status_xml,
                                                    YtsClient             *self)
{
  YtsClientPrivate *priv = GET_PRIVATE (self);

  tp_yts_status_advertise_status_async (priv->tp_status,
                                        capability,
                                        priv->service_id,
                                        status_xml,
                                        NULL,
                                        _tp_yts_status_advertise_status_cb,
                                        self);

  return true;
}

static void
yts_client_ready (YtsClient *self)
{
  YtsClientPrivate *priv = GET_PRIVATE (self);

  g_return_if_fail (priv->tp_status);

  priv->ready = TRUE;

  g_message ("YtsClient is ready");

  yts_client_status_foreach_capability (
    priv->client_status,
    (YtsClientStatusCapabilityIterator) _client_status_foreach_capability_advertise_status,
    self);
}

static void
yts_client_cleanup_connection_resources (YtsClient *self)
{
  YtsClientPrivate *priv = GET_PRIVATE (self);

  /*
   * Clean up items associated with this connection.
   */

  priv->ready    = FALSE;
  priv->prepared = FALSE;

  /*
   * Empty roster
   */
  if (priv->roster)
    yts_roster_clear (priv->roster);

  if (priv->tp_conn)
    {
      g_object_unref (priv->tp_conn);
      priv->tp_conn = NULL;
    }
}

static gboolean
yts_client_reconnect_cb (YtsClient *self)
{
  YtsClientPrivate *priv = GET_PRIVATE (self);

  priv->reconnect_id = 0;

  yts_client_connect (self);

  /* one off */
  return FALSE;
}

static void
yts_client_reconnect_after (YtsClient *self, guint after_seconds)
{
  YtsClientPrivate *priv = GET_PRIVATE (self);

  g_return_if_fail (YTS_IS_CLIENT (self));

  priv->reconnect = TRUE;

  priv->reconnect_id =
    g_timeout_add_seconds (after_seconds,
                           (GSourceFunc) yts_client_reconnect_cb,
                           self);
}

static void
yts_client_disconnected (YtsClient *self)
{
  YtsClientPrivate *priv = GET_PRIVATE (self);

  yts_client_cleanup_connection_resources (self);

  if (priv->reconnect)
    yts_client_reconnect_after (self, RECONNECT_DELAY);
}

static void
yts_client_raw_message (YtsClient   *self,
                        char const  *xml_payload)
{
}

static bool
yts_client_incoming_file (YtsClient   *self,
                          char const  *from,
                          char const  *name,
                          uint64_t     size,
                          uint64_t     offset,
                          TpChannel   *proxy,
                          void        *data)
{
  YtsClientPrivate *priv = GET_PRIVATE (self);
  char              *path;
  GFile             *gfile;
  EmpathyTpFile     *tp_file;
  GCancellable      *cancellable;

  g_message ("Incoming file from %s", from);

  if (g_mkdir_with_parents (priv->incoming_dir, 0700))
    {
      g_warning ("Unable to create directory %s", priv->incoming_dir);

      tp_cli_channel_call_close (proxy,
                                 -1,
                                 NULL,
                                 NULL,
                                 NULL,
                                 NULL);

      return FALSE;
    }

  path = g_build_filename (priv->incoming_dir, name, NULL);

  gfile = g_file_new_for_path (path);

  tp_file = empathy_tp_file_new ((TpChannel*)proxy, TRUE);

  cancellable = g_cancellable_new ();

  empathy_tp_file_accept (tp_file, offset, gfile,
                          cancellable,
                          NULL /*progress_callback*/,
                          NULL /*progress_user_data*/,
                          yts_client_ft_op_cb,
                          self);

  g_free (path);
  g_object_unref (gfile);
  g_object_unref (cancellable);

  return TRUE;
}

static gboolean
yts_client_stop_accumulator (GSignalInvocationHint *ihint,
                              GValue                *accumulated,
                              const GValue          *returned,
                              gpointer               data)
{
  gboolean cont = g_value_get_boolean (returned);

  g_value_set_boolean (accumulated, cont);

  return cont;
}

/*
 * Callback for #TpProxy::interface-added: we need to add the signals we
 * care for here.
 *
 * TODO -- should we not be able to connect directly to the signal bypassing
 * the unsightly TP machinery ?
 */
static void
yts_client_debug_iface_added_cb (TpProxy    *tproxy,
                                  guint       id,
                                  DBusGProxy *proxy,
                                  gpointer    data)
{
  if (id != TP_IFACE_QUARK_DEBUG)
    return;

  dbus_g_proxy_add_signal (proxy, "NewDebugMessage",
                           G_TYPE_DOUBLE,
                           G_TYPE_STRING,
                           G_TYPE_UINT,
                           G_TYPE_STRING,
                           G_TYPE_INVALID);
}

/*
 * Handler for Mgr debug output.
 */
static void
yts_client_debug_msg_cb (TpProxy    *proxy,
                          gdouble     timestamp,
                          char const *domain,
                          guint       level,
                          char const *msg,
                          gpointer    data,
                          GObject    *weak_object)
{
  char            *log_domain;
  GLogLevelFlags   log_level;

  log_domain = g_strdup_printf ("%s%c%s%c%s",
                                PACKAGE, '\0', "telepathy", '\0', domain);

  switch (level) {
    case 0:
      log_level = G_LOG_LEVEL_ERROR;
      break;
    case 1:
      log_level = G_LOG_LEVEL_CRITICAL;
      break;
    case 2:
      log_level = G_LOG_LEVEL_WARNING;
      break;
    case 3:
      log_level = G_LOG_LEVEL_MESSAGE;
      break;
    default:
      log_level = G_LOG_LEVEL_INFO;
  }

  g_log (log_domain, log_level, "%s", msg);
  g_free (log_domain);
}

/*
 * The machinery for adding the NewDebugMessage signal; this is PITA, and can
 * probably be autogenerated from somewhere, but no documentation.
 *
 * TODO - check we cannot connect directly to the dbus proxy avoiding all
 * this unsightly marshaling.
 *
 * First, the collect function
 */
static void
yts_client_debug_msg_collect (DBusGProxy              *proxy,
                               gdouble                  timestamp,
                               char const              *domain,
                               guint                    level,
                               char const              *msg,
                               TpProxySignalConnection *signal)
{
  GValueArray *args = g_value_array_new (4);
  GValue t = { 0 };

  g_value_init (&t, G_TYPE_DOUBLE);
  g_value_set_double (&t, timestamp);
  g_value_array_append (args, &t);
  g_value_unset (&t);

  g_value_init (&t, G_TYPE_STRING);
  g_value_set_string (&t, domain);
  g_value_array_append (args, &t);
  g_value_unset (&t);

  g_value_init (&t, G_TYPE_UINT);
  g_value_set_uint (&t, level);
  g_value_array_append (args, &t);
  g_value_unset (&t);

  g_value_init (&t, G_TYPE_STRING);
  g_value_set_string (&t, msg);
  g_value_array_append (args, &t);

  tp_proxy_signal_connection_v0_take_results (signal, args);
}

typedef void (*YtsClientMgrNewDebugMsg)(TpProxy *,
                                         gdouble,
                                         char const *,
                                         guint,
                                         char const *,
                                         gpointer, GObject *);

/*
 * The callback invoker
 */
static void
yts_client_debug_msg_invoke (TpProxy     *proxy,
                              GError      *error,
                              GValueArray *args,
                              GCallback    callback,
                              gpointer     data,
                              GObject     *weak_object)
{
  YtsClientMgrNewDebugMsg cb = (YtsClientMgrNewDebugMsg) callback;

  if (cb)
    {
      cb (g_object_ref (proxy),
          g_value_get_double (args->values),
          g_value_get_string (args->values + 1),
          g_value_get_uint (args->values + 2),
          g_value_get_string (args->values + 3),
          data,
          weak_object);

      g_object_unref (proxy);
    }

  g_value_array_free (args);
}

/*
 * Connects to the signal(s) and enable debugging output.
 */
static void
yts_client_connect_debug_signals (YtsClient *client, TpProxy *proxy)
{
  GError   *error = NULL;
  GValue    v = {0};
  GType     expected[] =
    {
      G_TYPE_DOUBLE, G_TYPE_STRING, G_TYPE_UINT, G_TYPE_STRING,
      G_TYPE_INVALID
    };

  g_value_init (&v, G_TYPE_BOOLEAN);
  g_value_set_boolean (&v, TRUE);

  tp_proxy_signal_connection_v0_new (proxy,
                                     TP_IFACE_QUARK_DEBUG,
                                     "NewDebugMessage",
                                     &expected[0],
                                     G_CALLBACK (yts_client_debug_msg_collect),
                                     yts_client_debug_msg_invoke,
                                     G_CALLBACK (yts_client_debug_msg_cb),
                                     client,
                                     NULL,
                                     (GObject*)client,
                                     &error);

  if (error)
    {
      g_message ("%s", error->message);
      g_clear_error (&error);
    }

  tp_cli_dbus_properties_call_set (proxy, -1, TP_IFACE_DEBUG,
                                   "Enabled", &v, NULL, NULL, NULL, NULL);
}

static void
yts_client_setup_debug  (YtsClient *self)
{
  YtsClientPrivate *priv = GET_PRIVATE (self);
  TpDBusDaemon      *dbus;
  TpProxy           *proxy;
  char              *busname;
  char const        *mgr_name = NULL;
  GError            *error = NULL;

  dbus = tp_dbus_daemon_dup (&error);

  if (error != NULL)
    {
      g_warning ("%s", error->message);
      g_clear_error (&error);
      return;
    }

  switch (priv->protocol) {
    case YTS_PROTOCOL_XMPP:
      mgr_name = "gabble";
      break;
    case YTS_PROTOCOL_LOCAL_XMPP:
      mgr_name = "salut";
      break;
  }

  busname = g_strdup_printf ("org.freedesktop.Telepathy.ConnectionManager.%s",
                             mgr_name);
  proxy =
    g_object_new (TP_TYPE_PROXY,
                  "bus-name", busname,
                  "dbus-daemon", dbus,
                  "object-path", "/org/freedesktop/Telepathy/debug",
                  NULL);

  priv->tp_debug_proxy = proxy;

  g_signal_connect (proxy, "interface-added",
                    G_CALLBACK (yts_client_debug_iface_added_cb), self);

  tp_proxy_add_interface_by_id (proxy, TP_IFACE_QUARK_DEBUG);

  /*
   * Connecting to the signals triggers the interface-added signal
   */
  yts_client_connect_debug_signals (self, proxy);

  g_object_unref (dbus);
  g_free (busname);
}

static bool
_client_status_foreach_interest_add (YtsClientStatus const  *client_status,
                                     char const             *capability,
                                     YtsClient              *self)
{
  YtsClientPrivate *priv = GET_PRIVATE (self);

  tp_yts_client_add_interest (priv->tp_client, capability);

  return true;
}

static bool
_client_status_foreach_capability_add (YtsClientStatus const  *client_status,
                                       char const             *capability,
                                       char const             *status_xml,
                                       YtsClient              *self)
{
  YtsClientPrivate *priv = GET_PRIVATE (self);

  tp_yts_client_add_capability (priv->tp_client, capability);

  return true;
}

static void
setup_tp_client (YtsClient  *self,
                 TpAccount  *account)
{
  YtsClientPrivate *priv = GET_PRIVATE (self);

  g_return_if_fail (TP_IS_ACCOUNT (account));

  priv->tp_account = account;
  priv->tp_client = tp_yts_client_new (priv->service_id, account);

  if (YTS_DEBUG_TELEPATHY & ytstenut_get_debug_flags ()) {
    yts_client_setup_debug (self);
  }

  /* Publish capabilities */
  yts_client_status_foreach_capability (
    priv->client_status,
    (YtsClientStatusCapabilityIterator) _client_status_foreach_capability_add,
    self);

  /* Publish interests */
  yts_client_status_foreach_interest (
    priv->client_status,
    (YtsClientStatusInterestIterator) _client_status_foreach_interest_add,
    self);

  /*
   * If connection has been requested already, make one
   */
  if (priv->connect)
    yts_client_make_connection (self);
}

/*
 * Callback from the async tp_proxy_prepare_async() call
 *
 * This function is ready for the New World Order according to Ytstenut ...
 */
static void
yts_client_account_prepared_cb (GObject       *source_object,
                                GAsyncResult  *res,
                                gpointer       self)
{
  TpAccount *account = TP_ACCOUNT (source_object);
  GError    *error   = NULL;

  if (!tp_proxy_prepare_finish (account, res, &error)) {
    g_critical ("Account unprepared: %s", error->message);
    g_clear_error (&error);
    return;
  }

  g_message ("Account successfully opened");

  setup_tp_client (YTS_CLIENT (self), account);
}

static void
yts_client_account_cb (GObject      *source_object,
                       GAsyncResult *res,
                       gpointer      self)
{
  TpYtsAccountManager *yts_am = TP_YTS_ACCOUNT_MANAGER (source_object);
  TpAccount           *account;
  GError              *error = NULL;
  const GQuark         features[] = { TP_ACCOUNT_FEATURE_CORE, 0 };

  g_return_if_fail (TP_IS_YTS_ACCOUNT_MANAGER (yts_am));

  account = tp_yts_account_manager_get_account_finish (yts_am,
                                                       res,
                                                       &error);
  if (error) {
    g_critical ("Could not access account: %s", error->message);
    g_clear_error (&error);
    return;
  }

  g_message ("Got account");

  tp_proxy_prepare_async (account,
                          features,
                          yts_client_account_prepared_cb,
                          self);
}

static void
_roster_send_message (YtsRoster    *roster,
                      YtsContact   *contact,
                      YtsService   *service,
                      YtsMetadata  *message,
                      YtsClient    *self)
{
  char const *service_id;

  service_id = yts_service_get_id (service);

  yts_client_send_message (self, contact, service_id, message);
}

static YtsOutgoingFile *
_roster_send_file (YtsRoster   *roster,
                   YtsContact  *contact,
                   YtsService  *service,
                   GFile       *file,
                   char const  *description,
                   GError     **error_out,
                   YtsClient   *self)
{
  YtsClientPrivate  *priv = GET_PRIVATE (self);
  YtsOutgoingFile   *outgoing;
  char const        *recipient_contact_id;
  char const        *recipient_service_id;
  GError            *error = NULL;

  g_return_val_if_fail (YTS_IS_CLIENT (self), NULL);

  recipient_contact_id = yts_contact_get_id (contact);
  recipient_service_id = yts_service_get_id (service);
  outgoing = yts_outgoing_file_new (priv->tp_account,
                                    file,
                                    recipient_contact_id,
                                    recipient_service_id,
                                    description);

  g_initable_init (G_INITABLE (outgoing), NULL, &error);
  if (error) {
    g_object_unref (outgoing);
    g_propagate_error (error_out, error);
    g_clear_error (&error);
    return NULL;
  }

  return outgoing;
}

static void
_roster_contact_removed (YtsRoster  *roster,
                         YtsContact *contact,
                         YtsClient  *self)
{
  YtsClientPrivate *priv = GET_PRIVATE (self);
  GHashTableIter   iter;
  bool             start_over;

  /*
   * Clear pending responses.
   */

  // FIXME this would be better solved using g_hash_table_foreach_remove().
  do {
    char const *invocation_id;
    InvocationData *data;
    start_over = false;
    g_hash_table_iter_init (&iter, priv->invocations);
    while (g_hash_table_iter_next (&iter,
                                   (void **) &invocation_id,
                                   (void **) &data)) {

      if (data->contact == contact) {
        g_hash_table_remove (priv->invocations, invocation_id);
        start_over = true;
        break;
      }
    }
  } while (start_over);

  /*
   * Unregister proxies
   */

  // FIXME this would be better solved using g_hash_table_foreach_remove().
  do {
    char const *capability;
    ProxyList *proxy_list;
    start_over = false;
    g_hash_table_iter_init (&iter, priv->proxies);
    while (g_hash_table_iter_next (&iter,
                                   (void **) &capability,
                                   (void **) &proxy_list)) {

      proxy_list_purge_contact (proxy_list, contact);
      if (proxy_list_is_empty (proxy_list)) {
        g_hash_table_remove (priv->proxies, capability);
        start_over = true;
        break;
      }
    }
  } while (start_over);
}

/*
 * C2S Setup
 */

static void
_account_prepared (GObject      *source_object,
                   GAsyncResult *result,
                   gpointer      user_data)
{
  YtsClient *self = YTS_CLIENT (user_data);
  TpAccount *account = TP_ACCOUNT (source_object);
  GError    *error = NULL;

  if (!tp_proxy_prepare_finish (account, result, &error)) {
    g_critical ("Failed to prepare account: %s\n", error->message);
    g_clear_error (&error);
    return;
  }

  setup_tp_client (self, account);
}

/**/

static void
yts_client_constructed (GObject *object)
{
  YtsClientPrivate *priv = GET_PRIVATE (object);
  GError              *error     = NULL;

  if (G_OBJECT_CLASS (yts_client_parent_class)->constructed)
    G_OBJECT_CLASS (yts_client_parent_class)->constructed (object);

  priv->roster   = yts_roster_impl_new ();
  g_signal_connect (priv->roster, "send-message",
                    G_CALLBACK (_roster_send_message), object);
  g_signal_connect (priv->roster, "send-file",
                    G_CALLBACK (_roster_send_file), object);
  g_signal_connect (priv->roster, "contact-removed",
                    G_CALLBACK (_roster_contact_removed), object);

  priv->unwanted = yts_roster_impl_new ();
#if 0 /* TODO */
  g_signal_connect (priv->unwanted, "send-message",
                    G_CALLBACK (_roster_send_message), object);
  g_signal_connect (priv->roster, "send-file",
                    G_CALLBACK (_roster_send_file), object);
  g_signal_connect (priv->unwanted, "contact-removed",
                    G_CALLBACK (_roster_contact_removed), object);
#endif

  if (!priv->service_id || !*priv->service_id) {
    g_critical ("Service-ID must be set at construction time.");
    return;
  }

  priv->client_status = yts_client_status_new (priv->service_id);

  priv->tp_am = tp_yts_account_manager_dup ();
  if (!TP_IS_YTS_ACCOUNT_MANAGER (priv->tp_am)) {
    g_error ("Missing Account Manager");
    return;
  }
  tp_yts_account_manager_hold (priv->tp_am);

  if (priv->protocol == YTS_PROTOCOL_LOCAL_XMPP) {
    tp_yts_account_manager_get_account_async (priv->tp_am, NULL,
                                              yts_client_account_cb,
                                              object);
  } else {

    TpAccount *account;
    char      *escaped_account_id;
    char      *path;

    if (NULL == priv->account_id) {
      g_critical ("Missing account ID");
      return;
    }

    /* TODO iterate account manager to find matching account, rather than
     * relying on escaping and path -- those are not guaranteed to stay
     * compatible. */

    escaped_account_id = tp_escape_as_identifier (priv->account_id);
    path = g_strdup_printf ("%s%s%s",
                            TP_ACCOUNT_OBJECT_PATH_BASE,
                            "gabble/jabber/",
                            escaped_account_id);

    g_message ("account path: %s", path);

    account = tp_yts_account_manager_ensure_account (priv->tp_am, path, &error);
    if (error) {
      g_critical ("Could not access account %s: %s",
                  priv->account_id,
                  error->message);
      g_clear_error (&error);
      return;
    }

    tp_proxy_prepare_async (account, NULL, _account_prepared, object);

    g_free (path);
    g_free (escaped_account_id);
  }
}

static void
yts_client_get_property (GObject    *object,
                          guint       property_id,
                          GValue     *value,
                          GParamSpec *pspec)
{
  YtsClientPrivate *priv = GET_PRIVATE (object);

  switch (property_id)
    {
    case PROP_ACCOUNT_ID:
      g_value_set_string (value, priv->account_id);
      break;
    case PROP_CONTACT_ID:
      g_value_set_string (value,
                          yts_client_get_contact_id (YTS_CLIENT (object)));
      break;
    case PROP_SERVICE_ID:
      g_value_set_string (value, priv->service_id);
      break;
    case PROP_PROTOCOL:
      g_value_set_enum (value, priv->protocol);
      break;
    case PROP_TP_ACCOUNT:
      g_value_set_object (value, priv->tp_account);
      break;
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
    }
}

static void
yts_client_set_property (GObject      *object,
                          guint         property_id,
                          const GValue *value,
                          GParamSpec   *pspec)
{
  YtsClientPrivate *priv = GET_PRIVATE (object);

  switch (property_id)
    {
    case PROP_ACCOUNT_ID:
      /* Construct-only */
      priv->account_id = g_value_dup_string (value);
      break;
    case PROP_SERVICE_ID:
      {
        /* Construct-only */
        g_return_if_fail (NULL == priv->service_id);
        priv->service_id = g_value_dup_string (value);
      }
      break;
    case PROP_PROTOCOL:
      priv->protocol = g_value_get_enum (value);
      break;

    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
    }
}

static void
yts_client_dispose (GObject *object)
{
  YtsClientPrivate *priv = GET_PRIVATE (object);

  if (priv->disposed)
    return;

  priv->disposed = TRUE;

  if (priv->roster)
    {
      g_object_unref (priv->roster);
      priv->roster = NULL;
    }

  if (priv->unwanted)
    {
      g_object_unref (priv->unwanted);
      priv->unwanted = NULL;
    }

  if (priv->tp_conn)
    {
      tp_cli_connection_call_disconnect  (priv->tp_conn,
                                          -1,
                                          NULL, NULL, NULL, NULL);
      g_object_unref (priv->tp_conn);
      priv->tp_conn = NULL;
    }

  if (priv->tp_am)
    {
      tp_yts_account_manager_release (priv->tp_am);

      g_object_unref (priv->tp_am);
      priv->tp_am = NULL;
    }

  if (priv->tp_debug_proxy)
    {
      g_object_unref (priv->tp_debug_proxy);
      priv->tp_debug_proxy = NULL;
    }

  if (priv->services)
    {
      g_hash_table_destroy (priv->services);
      priv->services = NULL;
    }

  if (priv->invocations)
    {
      g_hash_table_destroy (priv->invocations);
      priv->invocations = NULL;
    }

  if (priv->proxies)
    {
      g_hash_table_destroy (priv->proxies);
      priv->proxies = NULL;
    }

  G_OBJECT_CLASS (yts_client_parent_class)->dispose (object);
}

static void
yts_client_finalize (GObject *object)
{
  YtsClientPrivate *priv = GET_PRIVATE (object);

  g_free (priv->account_id);
  g_free (priv->service_id);
  g_free (priv->incoming_dir);
  g_object_unref (priv->client_status);

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

static void
yts_client_class_init (YtsClientClass *klass)
{
  GParamSpec   *pspec;
  GObjectClass *object_class = (GObjectClass *)klass;

  /* Initialize logging. */
  static bool is_initialized = false;
  if (!is_initialized) {
    ytstenut_init ();
    is_initialized = true;
  }

  g_type_class_add_private (klass, sizeof (YtsClientPrivate));

  object_class->dispose      = yts_client_dispose;
  object_class->finalize     = yts_client_finalize;
  object_class->constructed  = yts_client_constructed;
  object_class->get_property = yts_client_get_property;
  object_class->set_property = yts_client_set_property;

  klass->authenticated       = yts_client_authenticated;
  klass->ready               = yts_client_ready;
  klass->disconnected        = yts_client_disconnected;
  klass->raw_message         = yts_client_raw_message;

  /**
   * YtsClient:account-id:
   *
   * The account ID used by this client instance when running in C2S
   * (client-to-server) mode. This is the non-normalized JID as passed when
   * the client was instantiated. Might be %NULL when in P2P mode.
   *
   * Since: 0.4
   */
  pspec = g_param_spec_string ("account-id", "", "",
                               NULL,
                               G_PARAM_READWRITE |
                               G_PARAM_CONSTRUCT_ONLY);
  g_object_class_install_property (object_class, PROP_ACCOUNT_ID, pspec);

  /**
   * YtsClient:contact-id:
   *
   * The contact ID of this service.
   *
   * Since: 0.4
   */
  pspec = g_param_spec_string ("contact-id", "", "",
                               NULL,
                               G_PARAM_READABLE);
  g_object_class_install_property (object_class, PROP_CONTACT_ID, pspec);

  /**
   * YtsClient:service-id:
   *
   * The unique ID of this service.
   *
   * Since: 0.4
   */
  pspec = g_param_spec_string ("service-id", "", "",
                               NULL,
                               G_PARAM_READWRITE |
                               G_PARAM_CONSTRUCT_ONLY);
  g_object_class_install_property (object_class, PROP_SERVICE_ID, pspec);

  /**
   * YtsClient:protocol:
   *
   * XMPP protocol to use for connection.
   *
   * Since: 0.1
   */
  pspec = g_param_spec_enum ("protocol",
                             "Protocol",
                             "Protocol",
                             YTS_TYPE_PROTOCOL,
                             0,
                             G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY);
  g_object_class_install_property (object_class, PROP_PROTOCOL, pspec);

  /**
   * YtsClient:tp-account:
   *
   * Telepathies #TpAccount object used by this instance.
   *
   * Since: 0.4
   *
   * <note>There is no API guarantee for this and other fields that expose telepathy.</note>
   */
  pspec = g_param_spec_object ("tp-account", "", "",
                               TP_TYPE_ACCOUNT,
                               G_PARAM_READABLE);
  g_object_class_install_property (object_class, PROP_TP_ACCOUNT, pspec);

  /**
   * YtsClient::authenticated:
   * @self: object which emitted the signal.
   *
   * The authenticated signal is emited when connection to the Ytstenut server
   * is successfully established.
   *
   * Since: 0.1
   */
  signals[AUTHENTICATED] =
    g_signal_new ("authenticated",
                  G_TYPE_FROM_CLASS (object_class),
                  G_SIGNAL_RUN_FIRST,
                  G_STRUCT_OFFSET (YtsClientClass, authenticated),
                  NULL, NULL,
                  yts_marshal_VOID__VOID,
                  G_TYPE_NONE, 0);

  /**
   * YtsClient::ready:
   * @self: object which emitted the signal.
   *
   * The ready signal is emited when the initial Telepathy set up is ready.
   * (In practical terms this means the subscription channels are prepared.)
   *
   * Since: 0.1
   */
  signals[READY] =
    g_signal_new ("ready",
                  G_TYPE_FROM_CLASS (object_class),
                  G_SIGNAL_RUN_FIRST,
                  G_STRUCT_OFFSET (YtsClientClass, ready),
                  NULL, NULL,
                  yts_marshal_VOID__VOID,
                  G_TYPE_NONE, 0);

  /**
   * YtsClient::disconnected:
   * @self: object which emitted the signal.
   *
   * The disconnected signal is emited when connection to the Ytstenut server
   * is successfully established.
   *
   * Since: 0.1
   */
  signals[DISCONNECTED] =
    g_signal_new ("disconnected",
                  G_TYPE_FROM_CLASS (object_class),
                  G_SIGNAL_RUN_FIRST,
                  G_STRUCT_OFFSET (YtsClientClass, disconnected),
                  NULL, NULL,
                  yts_marshal_VOID__VOID,
                  G_TYPE_NONE, 0);

  /**
   * YtsClient::raw-message:
   * @self: object which emitted the signal.
   * @message: #YtsMessage, the message
   *
   * The message signal is emitted when message is received from one of the
   * contacts.
   *
   * Since: 0.3
   */
  signals[RAW_MESSAGE] =
    g_signal_new ("raw-message",
                  G_TYPE_FROM_CLASS (object_class),
                  G_SIGNAL_RUN_LAST,
                  G_STRUCT_OFFSET (YtsClientClass, raw_message),
                  NULL, NULL,
                  yts_marshal_VOID__STRING,
                  G_TYPE_NONE, 1,
                  G_TYPE_STRING);

  /**
   * YtsClient::text-message:
   * @self: object which emitted the signal.
   * @text: Message payload.
   *
   * This signal is emitted when a remote service sent a text message.
   *
   * Since: 0.3
   */
  signals[TEXT_MESSAGE] =
    g_signal_new ("text-message",
                  G_TYPE_FROM_CLASS (object_class),
                  G_SIGNAL_RUN_LAST,
                  0, NULL, NULL,
                  yts_marshal_VOID__STRING,
                  G_TYPE_NONE, 1,
                  G_TYPE_STRING);

  /**
   * YtsClient::list-message:
   * @self: object which emitted the signal.
   * @list: %NULL-terminated string vector holding the message content.
   *
   * This signal is emitted when a remote service sent a list of strings.
   *
   * Since: 0.3
   */
  signals[LIST_MESSAGE] =
    g_signal_new ("list-message",
                  G_TYPE_FROM_CLASS (object_class),
                  G_SIGNAL_RUN_LAST,
                  0, NULL, NULL,
                  yts_marshal_VOID__BOXED,
                  G_TYPE_NONE, 1,
                  G_TYPE_STRV);

  /**
   * YtsClient::dictionary-message:
   * @self: object which emitted the signal.
   * @dictionary: %NULL-terminated string vector where even indices are keys and
   *              odd ones are values.
   *
   * This signal is emitted when a remote service sent a dictionary message.
   *
   * Since: 0.3
   */
  signals[DICTIONARY_MESSAGE] =
    g_signal_new ("dictionary-message",
                  G_TYPE_FROM_CLASS (object_class),
                  G_SIGNAL_RUN_LAST,
                  0, NULL, NULL,
                  yts_marshal_VOID__BOXED,
                  G_TYPE_NONE, 1,
                  G_TYPE_STRV);

  /**
   * YtsClient::error:
   * @self: object which emitted the signal.
   * @error: #YtsError
   *
   * The error signal is emitted to indicate an error (or eventual success)
   * during the handling of an operation for which the Ytstenut API initially
   * returned %YTS_ERROR_PENDING. The original operation can be determined
   * using the atom part of the #YtsError parameter.
   *
   * Since: 0.1
   */
  signals[ERROR] =
    g_signal_new ("error",
                  G_TYPE_FROM_CLASS (object_class),
                  G_SIGNAL_RUN_LAST,
                  0,
                  NULL, NULL,
                  yts_marshal_VOID__UINT,
                  G_TYPE_NONE, 1,
                  G_TYPE_UINT);

  /**
   * YtsClient::incoming-file:
   * @self: object which emitted the signal.
   * @from: contact_id of the originator
   * @name: name of the file
   * @size: size of the file
   * @offset: offset into the file,
   * @channel: #TpChannel
   *
   * The #YtsClient::incoming-file signal is emitted when the client receives
   * incoming request for a file transfer. The signal closure will
   * kickstart the transfer -- this can be prevented by a connected handler
   * returning %FALSE.
   *
   * Since: 0.1
   */
  signals[INCOMING_FILE] =
    g_signal_new ("incoming-file",
                  G_TYPE_FROM_CLASS (object_class),
                  G_SIGNAL_RUN_LAST,
                  0,
                  yts_client_stop_accumulator, NULL,
                  yts_marshal_BOOLEAN__STRING_STRING_UINT64_UINT64_OBJECT,
                  G_TYPE_BOOLEAN, 5,
                  G_TYPE_STRING,
                  G_TYPE_STRING,
                  G_TYPE_UINT64,
                  G_TYPE_UINT64,
                  TP_TYPE_CHANNEL);

  /**
   * YtsClient::incoming-file-finished:
   * @self: object which emitted the signal.
   * @from: contact_id of the originator
   * @name: name of the file
   * @success: %TRUE if the transfer was completed successfully.
   *
   * The #YtsClient::incoming-file-finished signal is emitted when a file
   * transfer is completed.
   *
   * Since: 0.1
   */
  signals[INCOMING_FILE_FINISHED] =
    g_signal_new ("incoming-file-finished",
                  G_TYPE_FROM_CLASS (object_class),
                  G_SIGNAL_RUN_LAST,
                  0,
                  NULL, NULL,
                  yts_marshal_VOID__STRING_STRING_BOOLEAN,
                  G_TYPE_NONE, 3,
                  G_TYPE_STRING,
                  G_TYPE_STRING,
                  G_TYPE_BOOLEAN);
}

static void
yts_client_init (YtsClient *self)
{
  YtsClientPrivate *priv = GET_PRIVATE (self);

  yts_client_set_incoming_file_directory (self, NULL);

  priv->services = g_hash_table_new_full (g_str_hash,
                                          g_str_equal,
                                          g_free,
                                          g_object_unref);

  priv->invocations = g_hash_table_new_full (g_str_hash,
                                             g_str_equal,
                                             g_free,
                                             (GDestroyNotify) invocation_data_destroy);

  priv->proxies = g_hash_table_new_full (g_str_hash,
                                         g_str_equal,
                                         g_free,
                                         (GDestroyNotify) proxy_list_destroy);

  g_signal_connect (self, "incoming-file",
                    G_CALLBACK (yts_client_incoming_file), self);
}

YtsClient *
yts_client_new_c2s (char const *account_id,
                    char const *service_id)
{
  g_return_val_if_fail (account_id, NULL);
  g_return_val_if_fail (service_id, NULL);

  return g_object_new (YTS_TYPE_CLIENT,
                       "protocol",    YTS_PROTOCOL_XMPP,
                       "account-id",  account_id,
                       "service-id",  service_id,
                       NULL);
}

/**
 * yts_client_new_p2p:
 * @service_id: Unique ID for this service; UIDs must follow the dbus
 *              convention for unique names.
 *
 * Creates a new #YtsClient object.
 *
 * Returns: (transfer full): a #YtsClient object.
 *
 * Since: 0.1
 */
YtsClient *
yts_client_new_p2p (char const *service_id)
{
  g_return_val_if_fail (service_id, NULL);

  return g_object_new (YTS_TYPE_CLIENT,
                       "protocol",    YTS_PROTOCOL_LOCAL_XMPP,
                       "service-id",  service_id,
                       NULL);
}

static GVariant *
variant_new_from_escaped_literal (char const *string)
{
  GVariant  *v;
  char      *unescaped;

  unescaped = g_uri_unescape_string (string, NULL);
  v = g_variant_new_parsed (unescaped);
  g_free (unescaped);

  return v;
}

static gboolean
dispatch_to_service (YtsClient  *self,
                     char const *sender_contact_id,
                     char const *xml)
{
  YtsClientPrivate *priv = GET_PRIVATE (self);
  RestXmlParser *parser;
  RestXmlNode   *node;
  char const    *proxy_id;
  char const    *capability;
  char const    *type;
  YtsContact   *contact;
  gboolean       dispatched = FALSE;

  parser = rest_xml_parser_new ();
  node = rest_xml_parser_parse_from_data (parser, xml, strlen (xml));
  if (NULL == node) {
    // FIXME report error
    g_critical ("%s : Failed to parse message '%s'", G_STRLOC, xml);
    return false;
  }

  proxy_id = rest_xml_node_get_attr (node, "from-service");
  if (NULL == proxy_id) {
    // FIXME report error
    g_critical ("%s : Malformed message, 'from-service' missing in '%s'",
                G_STRLOC,
                xml);
    return false;
  }

  capability = rest_xml_node_get_attr (node, "capability");
  if (NULL == capability) {
    // FIXME report error
    g_critical ("%s : Malformed message, 'capability' missing in '%s'",
                G_STRLOC,
                xml);
    return false;
  }

  type = rest_xml_node_get_attr (node, "type");
  if (NULL == type) {
    // FIXME report error
    g_critical ("%s : Malformed message, 'type' missing in '%s'",
                G_STRLOC,
                xml);
    return false;
  }

  contact = yts_roster_find_contact_by_id (priv->roster, sender_contact_id);
  if (NULL == contact) {
    // FIXME report error
    g_critical ("%s : Contact for '%s' not found",
                G_STRLOC,
                sender_contact_id);
    return false;
  }

  /*
   * Low-level interface
   */

  if (0 == g_strcmp0 (SERVICE_FQC_ID, capability) &&
      0 == g_strcmp0 ("text", type))
    {
      char const *escaped_payload = rest_xml_node_get_attr (node, "payload");
      GVariant *payload = escaped_payload ?
                            variant_new_from_escaped_literal (escaped_payload) :
                            NULL;
      if (payload)
        {
          char const *text = g_variant_get_string (payload, NULL);
          g_signal_emit (self, signals[TEXT_MESSAGE], 0, text);
          g_variant_unref (payload);
        }
      else
        {
          // FIXME report
          g_warning ("%s : Message empty", G_STRLOC);
        }
    }
  else if (0 == g_strcmp0 (SERVICE_FQC_ID, capability) &&
           0 == g_strcmp0 ("list", type))
    {
      char const *escaped_payload = rest_xml_node_get_attr (node, "payload");
      GVariant *payload = escaped_payload ?
                            variant_new_from_escaped_literal (escaped_payload) :
                            NULL;
      if (payload)
        {
          char const **list = g_variant_get_strv (payload, NULL);
          g_signal_emit (self, signals[LIST_MESSAGE], 0, list);
          g_free (list);
          g_variant_unref (payload);
        }
      else
        {
          // FIXME report
          g_warning ("%s : Message empty", G_STRLOC);
        }
    }
  else if (0 == g_strcmp0 (SERVICE_FQC_ID, capability) &&
           0 == g_strcmp0 ("dictionary", type))
    {
      char const *escaped_payload = rest_xml_node_get_attr (node, "payload");
      GVariant *payload = escaped_payload ?
                            variant_new_from_escaped_literal (escaped_payload) :
                            NULL;
      if (payload)
        {
          GVariantIter iter;
          char const *name;
          char const *value;
          size_t n_entries;
          if (0 < (n_entries = g_variant_iter_init (&iter, payload)))
            {
              char **dictionary = g_new0 (char *, n_entries * 2 + 1);
              unsigned i = 0;
              while (g_variant_iter_loop (&iter, "{ss}", &name, &value))
                {
                  dictionary[i++] = g_strdup (name);
                  dictionary[i++] = g_strdup (value);
                }
              dictionary[i] = NULL;
              g_signal_emit (self, signals[DICTIONARY_MESSAGE], 0, dictionary);
              g_strfreev (dictionary);
            }
          g_variant_unref (payload);
        }
      else
        {
          // FIXME report
          g_warning ("%s : Message empty", G_STRLOC);
        }
    }

  /*
   * High-level interface
   */

  else if (0 == g_strcmp0 ("invocation", type))
    {
      /* Deliver to service */
      YtsServiceAdapter *adapter = g_hash_table_lookup (priv->services,
                                                         capability);
      if (adapter)
        {
          bool keep_sae;
          char const *invocation_id = rest_xml_node_get_attr (node, "invocation");
          char const *aspect = rest_xml_node_get_attr (node, "aspect");
          char const *args = rest_xml_node_get_attr (node, "arguments");
          GVariant *arguments = args ? variant_new_from_escaped_literal (args) : NULL;

          // FIXME check return value
          client_establish_invocation (self,
                                       invocation_id,
                                       contact,
                                       proxy_id);
          keep_sae = yts_service_adapter_invoke (adapter,
                                                  invocation_id,
                                                  aspect,
                                                  arguments);
          if (!keep_sae) {
            client_conclude_invocation (self, invocation_id);
          }

          dispatched = TRUE;
        }
      else
        {
          // FIXME we should probably report back that there's no adapter?
        }
    }
  else if (0 == g_strcmp0 ("event", type))
    {
      char const *aspect = rest_xml_node_get_attr (node, "aspect");
      char const *args = rest_xml_node_get_attr (node, "arguments");
      GVariant *arguments = args ? variant_new_from_escaped_literal (args) : NULL;

      dispatched = yts_contact_dispatch_event (contact,
                                                capability,
                                                aspect,
                                                arguments);
    }
  else if (0 == g_strcmp0 ("response", type))
    {
      char const *invocation_id = rest_xml_node_get_attr (node, "invocation");
      char const *ret = rest_xml_node_get_attr (node, "response");
      GVariant *response = ret ? variant_new_from_escaped_literal (ret) : NULL;

      dispatched = yts_contact_dispatch_response (contact,
                                                   capability,
                                                   invocation_id,
                                                   response);
    }
  else
    {
      // FIXME report error
      g_critical ("%s : Unknown message type '%s'", G_STRLOC, type);
    }

  g_object_unref (parser);
  return dispatched;
}

static void
yts_client_yts_channels_received_cb (TpYtsClient *tp_client,
                                      YtsClient  *client)
{
  TpYtsChannel  *ch;

  while ((ch = tp_yts_client_accept_channel (tp_client)))
    {
      char const      *from;
      GHashTable      *props;
      GHashTableIter   iter;
      gpointer         key, value;

      from = tp_channel_get_initiator_identifier (TP_CHANNEL (ch));

      g_object_get (ch, "channel-properties", &props, NULL);
      g_assert (props);

      g_hash_table_iter_init (&iter, props);
      while (g_hash_table_iter_next (&iter, &key, &value))
        {
          GValue      *v = value;
          char        *k = key;

          if (!g_strcmp0 (k, "org.freedesktop.ytstenut.xpmn.Channel.RequestBody"))
            {
              char const *xml_payload = g_value_get_string (v);
              gboolean dispatched = dispatch_to_service (client,
                                                         from,
                                                         xml_payload);

              if (!dispatched)
                {
                  g_signal_emit (client, signals[RAW_MESSAGE], 0, xml_payload);
                }
            }
        }
    }
}

/**
 * yts_client_disconnect:
 * @self: object on which to invoke this method.
 *
 * Disconnects @self.
 *
 * Since: 0.1
 */
void
yts_client_disconnect (YtsClient *self)
{
  YtsClientPrivate *priv = GET_PRIVATE (self);

  g_return_if_fail (YTS_IS_CLIENT (self));

  /* cancel any pending reconnect timeout */
  if (priv->reconnect_id)
    {
      g_source_remove (priv->reconnect_id);
      priv->reconnect_id = 0;
    }

  /* clear flag indicating pending connect */
  priv->connect = FALSE;

  /*
   * Since this was a disconnect at our end, clear the reconnect flag,
   * to avoid the signal closure from installing a reconnect callback.
   */
  priv->reconnect = FALSE;

  if (priv->tp_conn)
    tp_cli_connection_call_disconnect  (priv->tp_conn,
                                        -1, NULL, NULL, NULL, NULL);
}

static void
yts_client_connected_cb (TpConnection   *proxy,
                          const GError  *error,
                          YtsClient     *self,
                          GObject       *weak_object)
{
  if (error)
    {
      g_warning (G_STRLOC ": %s: %s", __FUNCTION__, error->message);

      yts_client_disconnect (self);
      yts_client_reconnect_after (self, RECONNECT_DELAY);
    }
}

static void
yts_client_error_cb (TpConnection *proxy,
                      char const   *arg_Error,
                      GHashTable   *arg_Details,
                      gpointer      user_data,
                      GObject      *weak_object)
{
  g_message ("Error: %s", arg_Error);
}

static void
yts_client_status_cb (TpConnection  *proxy,
                       guint         arg_Status,
                       guint         arg_Reason,
                       YtsClient    *self,
                       GObject      *weak_object)
{
  YtsClientPrivate *priv = GET_PRIVATE (self);

  char const *status[] = {"'connected'   ",
                          "'connecting'  ",
                          "'disconnected'"};
  char const *reason[] =
    {
      "NONE_SPECIFIED",
      "REQUESTED",
      "NETWORK_ERROR",
      "AUTHENTICATION_FAILED",
      "ENCRYPTION_ERROR",
      "NAME_IN_USE",
      "CERT_NOT_PROVIDED",
      "CERT_UNTRUSTED",
      "CERT_EXPIRED",
      "CERT_NOT_ACTIVATED",
      "CERT_HOSTNAME_MISMATCH",
      "CERT_FINGERPRINT_MISMATCH",
      "CERT_SELF_SIGNED",
      "CERT_OTHER_ERROR"
    };

  if (priv->disposed)
    return;

  g_message ("Connection: %s: '%s'",
           status[arg_Status], reason[arg_Reason]);

  if (arg_Status == TP_CONNECTION_STATUS_CONNECTED)
    g_signal_emit (self, signals[AUTHENTICATED], 0);
  else if (arg_Status == TP_CONNECTION_STATUS_DISCONNECTED)
    g_signal_emit (self, signals[DISCONNECTED], 0);
}

static gboolean
yts_client_process_one_service (YtsClient         *self,
                                char const        *contact_id,
                                char const        *service_id,
                                const GValueArray *service_info)
{
  YtsClientPrivate *priv = GET_PRIVATE (self);
  char const        *type;
  GHashTable        *names;
  char             **caps;
  GHashTable        *service_statuses;

  if (service_info->n_values != 3)
    {
      g_warning ("Missformed service description (nvalues == %d)",
                 service_info->n_values);
      return FALSE;
    }

  g_message ("Processing service %s:%s", contact_id, service_id);

  type  = g_value_get_string (&service_info->values[0]);
  names = g_value_get_boxed (&service_info->values[1]);
  caps  = g_value_get_boxed (&service_info->values[2]);

  service_statuses = g_hash_table_new_full (g_str_hash,
                                            g_str_equal,
                                            g_free,
                                            g_free);
  if (priv->tp_status) {
    GHashTable *discovered_statuses = tp_yts_status_get_discovered_statuses (
                                                              priv->tp_status);
    if (discovered_statuses) {
      GHashTable *contact_statuses = g_hash_table_lookup (discovered_statuses,
                                                          contact_id);
      if (contact_statuses) {
        unsigned i;
        for (i = 0; caps && caps[i]; i++) {
          GHashTable *capability_statuses = g_hash_table_lookup (contact_statuses,
                                                                 caps[i]);
          if (capability_statuses) {
            char const *status_xml = g_hash_table_lookup (capability_statuses,
                                                          service_id);
            if (status_xml) {
              g_hash_table_insert (service_statuses,
                                   g_strdup (caps[i]),
                                   g_strdup (status_xml));
            }
          }
        }
      }
    }
  }

  yts_roster_add_service (priv->roster,
                          priv->tp_conn,
                          contact_id,
                          service_id,
                          type,
                          (char const **)caps,
                          names,
                          service_statuses);

  g_hash_table_unref (service_statuses);

  return TRUE;
}

static void
yts_client_service_added_cb (TpYtsStatus        *tp_status,
                             char const         *contact_id,
                             char const         *service_id,
                             const GValueArray  *service_info,
                             YtsClient          *self)
{
  yts_client_process_one_service (self, contact_id, service_id, service_info);
}

static void
yts_client_service_removed_cb (TpYtsStatus  *tp_status,
                               char const   *contact_id,
                               char const   *service_id,
                               YtsClient    *self)
{
  YtsClientPrivate *priv = GET_PRIVATE (self);
  GHashTableIter   iter;
  bool             start_over;

  yts_roster_remove_service_by_id (priv->roster, contact_id, service_id);

  /*
   * Clear pending responses.
   */

  // FIXME this would be better solved using g_hash_table_foreach_remove().
  do {
    char const *invocation_id;
    InvocationData *data;
    start_over = false;
    g_hash_table_iter_init (&iter, priv->invocations);
    while (g_hash_table_iter_next (&iter,
                                   (void **) &invocation_id,
                                   (void **) &data)) {

      if (0 == g_strcmp0 (data->proxy_id, service_id)) {
        g_hash_table_remove (priv->invocations, invocation_id);
        start_over = true;
        break;
      }
    }
  } while (start_over);

  /*
   * Unregister proxies
   */

  // FIXME this would be better solved using g_hash_table_foreach_remove().
  do {
    char const *capability;
    ProxyList *proxy_list;
    start_over = false;
    g_hash_table_iter_init (&iter, priv->proxies);
    while (g_hash_table_iter_next (&iter,
                                   (void **) &capability,
                                   (void **) &proxy_list)) {

      proxy_list_purge_proxy_id (proxy_list, service_id);
      if (proxy_list_is_empty (proxy_list)) {
        g_hash_table_remove (priv->proxies, capability);
        start_over = true;
        break;
      }
    }
  } while (start_over);
}

static void
yts_client_process_status (YtsClient *self)
{
  YtsClientPrivate *priv = GET_PRIVATE (self);
  GHashTable        *services;

  if ((services = tp_yts_status_get_discovered_services (priv->tp_status)))
    {
      char           *contact_id;
      GHashTable     *service;
      GHashTableIter  iter;

      if (g_hash_table_size (services) <= 0)
        g_message ("No services discovered so far");

      g_hash_table_iter_init (&iter, services);
      while (g_hash_table_iter_next (&iter,
                                     (void **) &contact_id,
                                     (void **) &service))
        {
          char           *service_id;
          GValueArray    *service_info;
          GHashTableIter  iter2;

          g_hash_table_iter_init (&iter2, service);
          while (g_hash_table_iter_next (&iter2,
                                         (void **) &service_id,
                                         (void **) &service_info))
            {
              yts_client_process_one_service (self,
                                              contact_id,
                                              service_id,
                                              service_info);
            }
        }
    }
  else
    g_message ("No discovered services");
}

/* FIXME is this really needed or can we just advertise the new
 * per-capability status on any change? */
static void
yts_client_dispatch_status (YtsClient *self)
{
  YtsClientPrivate *priv = GET_PRIVATE (self);

  yts_client_status_foreach_capability (
    priv->client_status,
    (YtsClientStatusCapabilityIterator) _client_status_foreach_capability_advertise_status,
    self);
}

static void
_tp_yts_status_changed (TpYtsStatus *tp_status,
                        char const  *contact_id,
                        char const  *fqc_id,
                        char const  *service_id,
                        char const  *status_xml,
                        YtsClient   *self)
{
  YtsClientPrivate *priv = GET_PRIVATE (self);

  yts_roster_update_contact_status (priv->roster,
                                    contact_id,
                                    service_id,
                                    fqc_id,
                                    status_xml);
}

static void
yts_client_yts_status_cb (GObject       *obj,
                          GAsyncResult  *res,
                          YtsClient     *self)
{
  YtsClientPrivate *priv = GET_PRIVATE (self);
  TpAccount         *acc    = TP_ACCOUNT (obj);
  GError            *error  = NULL;
  TpYtsStatus       *tp_status;

  if (!(tp_status = tp_yts_status_ensure_finish (acc, res,&error)))
    {
      g_error ("Failed to obtain tp_status: %s", error->message);
    }

  g_message ("Processing tp_status");

  priv->tp_status = tp_status;

  tp_g_signal_connect_object (tp_status, "service-added",
                              G_CALLBACK (yts_client_service_added_cb),
                              self, 0);
  tp_g_signal_connect_object (tp_status, "service-removed",
                              G_CALLBACK (yts_client_service_removed_cb),
                              self, 0);
  tp_g_signal_connect_object (tp_status, "status-changed",
                              G_CALLBACK (_tp_yts_status_changed),
                              self, 0);


  yts_client_dispatch_status (self);
  yts_client_process_status (self);

  if (!priv->ready)
    {
      g_message ("Emitting 'ready' signal");
      g_signal_emit (self, signals[READY], 0);
    }
}

static void
yts_client_connection_ready_cb (TpConnection *conn,
                                GParamSpec   *par,
                                YtsClient   *self)
{
  YtsClientPrivate *priv = GET_PRIVATE (self);
  GCancellable      *cancellable;

  if (tp_connection_is_ready (conn))
    {
      g_message ("TP Connection entered ready state");

      cancellable = g_cancellable_new ();

      tp_yts_status_ensure_async (priv->tp_account,
                                  cancellable,
                                  (GAsyncReadyCallback) yts_client_yts_status_cb,
                                  self);

      /*
       * TODO -- this should be stored, so we can clean up in dispose any
       * pending op, ???
       *
       * But the TpYtsStatus docs say it's not used ...
       */
      g_object_unref (cancellable);
    }
}

static void
yts_client_connection_prepare_cb (GObject       *connection,
                                  GAsyncResult  *res,
                                  YtsClient     *self)
{
  YtsClientPrivate *priv = GET_PRIVATE (self);
  GError            *error  = NULL;

  if (!tp_proxy_prepare_finish (connection, res, &error))
    {
      g_critical ("Failed to prepare info: %s", error->message);
    }
  else
    {
      if (!tp_yts_client_register (priv->tp_client, &error))
        {
          g_error ("Failed to register account: %s", error->message);
        }
      else
        g_message ("Registered TpYtsClient");

      tp_g_signal_connect_object (priv->tp_client, "received-channels",
                              G_CALLBACK (yts_client_yts_channels_received_cb),
                              self, 0);
#if 0
      /* TODO -- */
      /*
       * local-xmpp / salut does not support the ContactCapabilities interface,
       * but file transfer is enabled by default, so it does not matter to us.
       */
      if (priv->protocol != YTS_PROTOCOL_LOCAL_XMPP)
        yts_client_setup_caps (client);
#endif
    }
}

/*
 * Sets up required features on the connection, and connects callbacks to
 * signals that we care about.
 */
static void
yts_client_setup_account_connection (YtsClient *self)
{
  YtsClientPrivate *priv = GET_PRIVATE (self);
  GError            *error = NULL;
  GQuark             features[] = { TP_CONNECTION_FEATURE_CONTACT_INFO,
                                    TP_CONNECTION_FEATURE_CAPABILITIES,
                                    TP_CONNECTION_FEATURE_CONNECTED,
                                    0 };

  priv->tp_conn = tp_account_get_connection (priv->tp_account);

  g_assert (priv->tp_conn);

  priv->dialing = FALSE;

  g_message ("Connection ready ?: %d",
             tp_connection_is_ready (priv->tp_conn));

  tp_g_signal_connect_object (priv->tp_conn, "notify::connection-ready",
                              G_CALLBACK (yts_client_connection_ready_cb),
                              self, 0);

  tp_cli_connection_connect_to_connection_error (priv->tp_conn,
                                                 yts_client_error_cb,
                                                 self,
                                                 NULL,
                                                 (GObject*)self,
                                                 &error);

  if (error)
    {
      g_critical (G_STRLOC ": %s: %s; no Ytstenut functionality will be "
                  "available", __FUNCTION__, error->message);
      g_clear_error (&error);
      return;
    }

  tp_cli_connection_connect_to_status_changed (priv->tp_conn,
      (tp_cli_connection_signal_callback_status_changed) yts_client_status_cb,
                                               self,
                                               NULL,
                                               (GObject*) self,
                                               &error);

  if (error)
    {
      g_critical (G_STRLOC ": %s: %s; no Ytstenut functionality will be "
                  "available", __FUNCTION__, error->message);
      g_clear_error (&error);
      return;
    }

  tp_cli_connection_connect_to_new_channel (priv->tp_conn,
                                            yts_client_channel_cb,
                                            self,
                                            NULL,
                                            (GObject*)self,
                                            &error);

  if (error)
    {
      g_critical (G_STRLOC ": %s: %s; no Ytstenut functionality will be "
                  "available", __FUNCTION__, error->message);
      g_clear_error (&error);
      return;
    }

  tp_proxy_prepare_async (priv->tp_conn,
                          features,
                          (GAsyncReadyCallback) yts_client_connection_prepare_cb,
                          self);
}

/*
 * Callback for the async request to change presence ... not that we do
 * do anything with it, except when it fails.
 */
static void
yts_client_account_online_cb (GObject      *acc,
                               GAsyncResult *res,
                               gpointer      data)
{
  GError    *error   = NULL;
  TpAccount *account = (TpAccount*)acc;
  char      *stat;
  char      *msg;
  TpConnectionPresenceType presence;

  if (!tp_account_request_presence_finish (account, res, &error))
    {
      g_error ("Failed to change presence to online");
    }

  presence = tp_account_get_current_presence (account, &stat, &msg);

  g_message ("Request to change presence to 'online' succeeded: %d, %s:%s",
             presence, stat, msg);

  g_free (stat);
  g_free (msg);
}

/*
 * One off handler for connection coming online
 */
static void
yts_client_account_connection_notify_cb (TpAccount  *account,
                                          GParamSpec *pspec,
                                          YtsClient *client)
{
  g_message ("We got connection!");

  g_signal_handlers_disconnect_by_func (account,
                                   yts_client_account_connection_notify_cb,
                                   client);

  yts_client_setup_account_connection (client);
}

static void
yts_client_make_connection (YtsClient *self)
{
  YtsClientPrivate *priv = GET_PRIVATE (self);

  /*
   * If we don't have an account yet, we do nothing and will make call to this
   * function when the account is ready.
   */
  if (!priv->tp_account)
    {
      g_message ("Account not yet available");
      return;
    }

  /*
   * At this point the account is prepared, but that does not mean we have a
   * connection (i.e., the current presence could 'off line' -- if we do not
   * have a connection, we request that the presence changes to 'on line' and
   * listen for when the :connection property changes.
   */
  if (!tp_account_get_connection (priv->tp_account))
    {
      g_message ("Currently off line, changing ...");

      g_signal_connect (priv->tp_account, "notify::connection",
                        G_CALLBACK (yts_client_account_connection_notify_cb),
                        self);

      tp_account_request_presence_async (priv->tp_account,
                                         TP_CONNECTION_PRESENCE_TYPE_AVAILABLE,
                                         "online",
                                         "online",
                                         yts_client_account_online_cb,
                                         self);
    }
  else
    yts_client_setup_account_connection (self);
}

/**
 * yts_client_connect:
 * @self: object on which to invoke this method.
 *
 * Initiates connection to the mesh. Once the connection is established,
 * the #YtsClient::authenticated signal will be emitted.
 *
 * Since 0.3
 */
void
yts_client_connect (YtsClient *self)
{
  YtsClientPrivate *priv = GET_PRIVATE (self);

  g_message ("Connecting ...");

  g_return_if_fail (YTS_IS_CLIENT (self));

  /* cancel any pending reconnect timeout */
  if (priv->reconnect_id)
    {
      g_source_remove (priv->reconnect_id);
      priv->reconnect_id = 0;
    }

  priv->connect = TRUE;

  if (priv->tp_conn)
    {
      /*
       * We already have the connection, so just connect.
       */
      tp_cli_connection_call_connect (priv->tp_conn,
                                      -1,
(tp_cli_connection_callback_for_connect) yts_client_connected_cb,
                                      self,
                                      NULL,
                                      (GObject*)self);
    }
  else if (!priv->dialing)
    yts_client_make_connection (self);
}

// TODO get rid of this, it invalidates the proxies
static void
yts_client_refresh_roster (YtsClient *self)
{
  YtsClientPrivate *priv = GET_PRIVATE (self);

  g_message ("Refreshing roster");

  if (!priv->tp_status)
    return;

  yts_roster_clear (priv->roster);
  yts_roster_clear (priv->unwanted);

  yts_client_process_status (self);
}

/**
 * yts_client_add_capability:
 * @self: object on which to invoke this method.
 * @capability: Name of the capability.
 *
 * Adds a capability to the capability set of this client; multiple capabilities
 * can be added by making mulitiple calls to this function.
 *
 * Since: 0.3
 */
void
yts_client_add_capability (YtsClient          *self,
                           char const         *c,
                           YtsCapabilityMode   mode)
{
  YtsClientPrivate *priv = GET_PRIVATE (self);
  char *capability;

  /* FIXME check that there's no collision with service owned capabilities. */

  g_return_if_fail (YTS_IS_CLIENT (self));
  g_return_if_fail (c);

  // TODO make sure c doesn't have prefix already
  capability = g_strdup_printf ("urn:ytstenut:capabilities:%s", c);

  if (YTS_CAPABILITY_MODE_PROVIDED == mode) {

    if (yts_client_status_add_capability (priv->client_status, capability)) {
      /* Advertise right away if possible, otherwise the advertising will
       * happen when the tp_client is ready. */
      if (priv->tp_client) {
        tp_yts_client_add_capability (priv->tp_client, capability);
      }
    } else {
      g_message ("Capablity '%s' already set", capability);
      return;
    }

    yts_client_refresh_roster (self);

  } else if (YTS_CAPABILITY_MODE_CONSUMED == mode) {

    if (yts_client_status_add_interest (priv->client_status, capability)) {
      /* Advertise right away if possible, otherwise the advertising will
       * happen when the tp_client is ready. */
      if (priv->tp_client) {
        tp_yts_client_add_interest (priv->tp_client, capability);
      }
    } else {
      g_message ("Interest '%s' already set", capability);
      return;
    }

  } else {
    g_critical ("Invalid capability mode %d", mode);
  }

  g_free (capability);
}

/**
 * yts_client_get_roster:
 * @self: object on which to invoke this method.
 *
 * Gets the #YtsRoster for this client. The object is owned by the client
 * and must not be freed by the caller.
 *
 * Returns: (transfer none): #YtsRoster.
 */
YtsRoster *const
yts_client_get_roster (YtsClient const *self)
{
  YtsClientPrivate *priv = GET_PRIVATE (self);

  g_return_val_if_fail (YTS_IS_CLIENT (self), NULL);

  return priv->roster;
}

/**
 * yts_client_emit_error:
 * @self: object on which to invoke this method.
 * @error: #YtsError
 *
 * Emits the #YtsClient::error signal with the suplied error parameter.
 *
 * This function is intened primarily for internal use, but can be also used by
 * toolkit libraries that need to generate asynchronous errors. Any function
 * call that returns the %YTS_ERROR_PENDING code to the caller should
 * eventually lead to emission of the ::error signal with either an appropriate
 * error code or %YTS_ERROR_SUCCESS to indicate the operation successfully
 * completed.
 *
 * Deprecated: This function will be removed in 0.4
 */
void
yts_client_emit_error (YtsClient *self, YtsError error)
{
  g_return_if_fail (YTS_IS_CLIENT (self));

  /*
   * There is no point in throwing an error that has no atom specified.
   */
  g_return_if_fail (yts_error_get_atom (error));

  g_signal_emit (self, signals[ERROR], 0, error);
}

/**
 * yts_client_set_incoming_file_directory:
 * @self: object on which to invoke this method.
 * @directory: path to a directory or %NULL.
 *
 * Sets the directory where incoming files will be stored; if the provided path
 * is %NULL, the directory will be reset to the default (~/.Ytstenut/). This
 * function does not do any checks regarding validity of the path provided,
 * though an attempt to create the directory before it is used, with permissions
 * of 0700.
 *
 * To change the directory for a specific file call this function from a
 * callback to the #YtsClient::incoming-file signal.
 */
void
yts_client_set_incoming_file_directory (YtsClient *self,
                                         char const *directory)
{
  YtsClientPrivate *priv = GET_PRIVATE (self);

  g_return_if_fail (YTS_IS_CLIENT (self));

  if (!directory || !*directory)
    priv->incoming_dir =
      g_build_filename (g_get_home_dir (), ".ytstenut", NULL);
  else
    priv->incoming_dir = g_strdup (directory);
}

/**
 * yts_client_get_incoming_file_directory:
 * @self: object on which to invoke this method.
 *
 * Returns the directory into which any files from incoming file transfers will
 * be placed.
 *
 * Returns: (transfer none): directory where incoming files are stored.
 */
char const *
yts_client_get_incoming_file_directory (YtsClient const *self)
{
  YtsClientPrivate *priv = GET_PRIVATE (self);

  g_return_val_if_fail (YTS_IS_CLIENT (self), NULL);

  return priv->incoming_dir;
}

/**
 * yts_client_get_contact_id:
 * @self: object on which to invoke this method.
 *
 * Getter for #YtsClient.#YtsClient:contact-id.
 *
 * Returns: (transfer none): the jabber id.
 */
char const *
yts_client_get_contact_id (const YtsClient *self)
{
  YtsClientPrivate *priv = GET_PRIVATE (self);

  g_return_val_if_fail (YTS_IS_CLIENT (self), NULL);
  g_return_val_if_fail (priv->tp_account, NULL);

  return tp_account_get_normalized_name (priv->tp_account);
}

/**
 * yts_client_get_service_id:
 * @self: object on which to invoke this method.
 *
 * Getter for #YtsClient.#YtsClient:service-id.
 *
 * Returns: (transfer none): the service ID.
 */
char const *
yts_client_get_service_id (const YtsClient *self)
{
  YtsClientPrivate *priv = GET_PRIVATE (self);

  g_return_val_if_fail (YTS_IS_CLIENT (self), NULL);

  return priv->service_id;
}

TpConnection *
yts_client_get_connection (YtsClient *self)
{
  YtsClientPrivate *priv = GET_PRIVATE (self);

  g_return_val_if_fail (YTS_IS_CLIENT (self), NULL);

  return priv->tp_conn;
}

TpYtsStatus *
yts_client_get_tp_status (YtsClient *self)
{
  YtsClientPrivate *priv = GET_PRIVATE (self);

  g_return_val_if_fail (YTS_IS_CLIENT (self), NULL);

  return priv->tp_status;
}

/**
 * yts_client_set_status_by_capability:
 * @self: object on which to invoke this method.
 * @capability: the capability to set status for
 * @activity: the activity to set the status to.
 *
 * Set the status of the service represented by this client to @activity for
 * @capability.
 *
 * FIXME: Maybe this should be named yts_client_set_status_on_capability() or
 *        yts_client_set_status_for_capability() ?
 *        Also maybe the "activity" should not be exposed any more because we're
 *        kinda moving away from it, instead allow setting the xml payload?
 *        Will things work at all without the activity attribut -- to to check
 *        the spec.
 */
void
yts_client_set_status_by_capability (YtsClient    *self,
                                      char const  *cap_value,
                                      char const  *activity,
                                      char const  *status_xml)
{
  YtsClientPrivate *priv = GET_PRIVATE (self);
  char        *capability;
  char const  *capability_status_xml;
  char const  *attribs[] = {
    "activity", activity,
    NULL
  };

  g_return_if_fail (YTS_IS_CLIENT (self));
  g_return_if_fail (cap_value);
  g_return_if_fail (activity);

  capability = g_strdup_printf ("%s%s",
                                YTS_XML_CAPABILITY_NAMESPACE,
                                cap_value);

  /* Check if the capability is already advertised. */
  if (yts_client_status_add_capability (priv->client_status, capability)) {
    /* Add capability if we already have a tp_client,
     * otherwise that's done when it's ready. */
    if (priv->tp_client) {
      tp_yts_client_add_capability (priv->tp_client, capability);
    }
  }

  capability_status_xml = yts_client_status_set (priv->client_status,
                                                 capability,
                                                 attribs,
                                                 status_xml);

  /* Advertise if we already have a tp_status,
   * otherwise that's done when it's ready. */
  if (priv->client_status) {
    tp_yts_status_advertise_status_async (priv->tp_status,
                                          capability,
                                          priv->service_id,
                                          capability_status_xml,
                                          NULL,
                                          _tp_yts_status_advertise_status_cb,
                                          self);
  }
}

struct YtsCLChannelData
{
  YtsClient  *client;
  YtsContact *contact;
  GHashTable  *attrs;
  char        *xml;
  char        *service_id;
  YtsError    error;
  gboolean     status_done;
  int          ref_count;
};

static void
yts_cl_channel_data_unref (struct YtsCLChannelData *d)
{
  d->ref_count--;

  if (d->ref_count <= 0)
    {
      g_hash_table_unref (d->attrs);
      g_free (d->xml);
      g_free (d->service_id);
      g_free (d);
    }
}

static struct YtsCLChannelData *
yts_cl_channel_data_ref (struct YtsCLChannelData *d)
{
  d->ref_count++;
  return d;
}

static void
yts_client_msg_replied_cb (TpYtsChannel *proxy,
                            GHashTable   *attributes,
                            char const   *body,
                            gpointer      data,
                            GObject      *weak_object)
{
  GHashTableIter            iter;
  gpointer                  key, value;
  struct YtsCLChannelData *d = data;

  g_message ("Got reply with attributes:");

  g_hash_table_iter_init (&iter, attributes);

  while (g_hash_table_iter_next (&iter, &key, &value))
    {
      g_message ("    %s = %s\n",
                 (char const *) key, (char const  *) value);
    }

  g_message ("    body: %s\n", body);

  if (!d->status_done)
    {
      guint32   a;
      YtsError e;

      a = yts_error_get_atom (d->error);
      e = yts_error_make (a, YTS_ERROR_SUCCESS);

      yts_client_emit_error (d->client, e);

      d->status_done = TRUE;
    }

  yts_cl_channel_data_unref (d);
}

static void
yts_client_msg_failed_cb (TpYtsChannel *proxy,
                           guint         error_type,
                           char const   *stanza_error_name,
                           char const   *ytstenut_error_name,
                           char const   *text,
                           gpointer      data,
                           GObject      *weak_object)
{
  guint32                   a;
  YtsError                 e;
  struct YtsCLChannelData *d = data;

  a = yts_error_get_atom (d->error);

  g_warning ("Sending of message failed: type %u, %s, %s, %s",
             error_type, stanza_error_name, ytstenut_error_name, text);

  e = yts_error_make (a, YTS_ERROR_NO_MSG_CHANNEL);

  yts_client_emit_error (d->client, e);

  d->status_done = TRUE;

  yts_cl_channel_data_unref (d);
}

static void
yts_client_msg_closed_cb (TpChannel *channel,
                           gpointer   data,
                           GObject   *weak_object)
{
  struct YtsCLChannelData *d = data;

  g_message ("Channel closed");

  if (!d->status_done)
    {
      guint32   a;
      YtsError e;

      a = yts_error_get_atom (d->error);
      e = yts_error_make (a, YTS_ERROR_SUCCESS);

      yts_client_emit_error (d->client, e);

      d->status_done = TRUE;
    }

  yts_cl_channel_data_unref (d);
}

static void
yts_client_msg_request_cb (GObject      *source_object,
                            GAsyncResult *result,
                            gpointer      data)
{
  GError *error = NULL;

  if (!tp_yts_channel_request_finish (
          TP_YTS_CHANNEL (source_object), result, &error))
    {
      g_warning ("Failed to Request on channel: %s\n", error->message);
    }
  else
    {
      g_message ("Channel requested");
    }

  g_clear_error (&error);
}

static void
yts_client_outgoing_channel_cb (GObject      *obj,
                                 GAsyncResult *res,
                                 gpointer      data)
{
  TpYtsChannel             *ch;
  TpYtsClient              *client = TP_YTS_CLIENT (obj);
  GError                   *error  = NULL;
  struct YtsCLChannelData *d      = data;

  if (!(ch = tp_yts_client_request_channel_finish (client, res, &error)))
    {
      guint32   a;
      YtsError e;

      a = yts_error_get_atom (d->error);

      g_warning ("Failed to open outgoing channel: %s", error->message);
      g_clear_error (&error);

      e = yts_error_make (a, YTS_ERROR_NO_MSG_CHANNEL);

      yts_client_emit_error (d->client, e);
    }
  else
    {
      g_message ("Got message channel, sending request");

      tp_yts_channel_connect_to_replied (ch, yts_client_msg_replied_cb,
                                         yts_cl_channel_data_ref (d),
                                         NULL, NULL, NULL);
      tp_yts_channel_connect_to_failed (ch, yts_client_msg_failed_cb,
                                        yts_cl_channel_data_ref (d),
                                        NULL, NULL, NULL);
      tp_cli_channel_connect_to_closed (TP_CHANNEL (ch),
                                        yts_client_msg_closed_cb,
                                        yts_cl_channel_data_ref (d),
                                        NULL, NULL, NULL);

      tp_yts_channel_request_async (ch, NULL, yts_client_msg_request_cb, NULL);
    }

  yts_cl_channel_data_unref (d);
}

static YtsError
yts_client_dispatch_message (struct YtsCLChannelData *d)
{
  TpContact         *tp_contact;
  YtsClientPrivate *priv = GET_PRIVATE (d->client);

  g_message ("Dispatching delayed message to %s", d->service_id);

  tp_contact = yts_contact_get_tp_contact (d->contact);
  g_assert (tp_contact);

  tp_yts_client_request_channel_async (priv->tp_client,
                                       tp_contact,
                                       d->service_id,
                                       TP_YTS_REQUEST_TYPE_GET,
                                       d->attrs,
                                       d->xml,
                                       NULL,
                                       yts_client_outgoing_channel_cb,
                                       d);

  return d->error;
}

static void
yts_client_notify_tp_contact_cb (YtsContact              *contact,
                                  GParamSpec               *pspec,
                                  struct YtsCLChannelData *d)
{
  g_message ("Contact ready");
  yts_client_dispatch_message (d);
  g_signal_handlers_disconnect_by_func (contact,
                                        yts_client_notify_tp_contact_cb,
                                        d);
}

YtsError
yts_client_send_message (YtsClient   *client,
                           YtsContact  *contact,
                           char const   *service_id,
                           YtsMetadata *message)
{
  GHashTable               *attrs;
  struct YtsCLChannelData *d;
  YtsError                 e;
  char                     *xml = NULL;

  if (!(attrs = yts_metadata_extract (message, &xml)))
    {
      g_warning ("Failed to extract content from YtsMessage object");

      e = yts_error_new (YTS_ERROR_INVALID_PARAMETER);
      g_free (xml);
      return e;
    }

  e = yts_error_new (YTS_ERROR_PENDING);

  d              = g_new (struct YtsCLChannelData, 1);
  d->error       = e;
  d->client      = client;
  d->contact     = contact;
  d->status_done = FALSE;
  d->ref_count   = 1;
  d->attrs       = attrs;
  d->xml         = xml;
  d->service_id  = g_strdup (service_id);

  if (yts_contact_get_tp_contact (contact))
    {
      yts_client_dispatch_message (d);
    }
  else
    {
      g_message ("Contact not ready, postponing message dispatch");

      g_signal_connect (contact, "notify::tp-contact",
                        G_CALLBACK (yts_client_notify_tp_contact_cb),
                        d);
    }

  return e;
}

static void
_adapter_error (YtsServiceAdapter  *adapter,
                char const          *invocation_id,
                GError const        *error,
                YtsClient          *self)
{
  YtsMetadata *message;

  message = yts_error_message_new (g_quark_to_string (error->domain),
                                    error->code,
                                    error->message,
                                    invocation_id);

  // TODO
  g_debug ("%s() not implemented at %s", __FUNCTION__, G_STRLOC);

  g_object_unref (message);
}

static void
_adapter_event (YtsServiceAdapter  *adapter,
                char const          *aspect,
                GVariant            *arguments,
                YtsClient          *self)
{
  YtsClientPrivate *priv = GET_PRIVATE (self);
  YtsMetadata *message;
  ProxyList   *proxy_list;
  char        *fqc_id;

  fqc_id = yts_service_adapter_get_fqc_id (adapter);
  message = yts_event_message_new (fqc_id, aspect, arguments);

  /* Dispatch to all registered proxies. */
  proxy_list = g_hash_table_lookup (priv->proxies, fqc_id);
  if (proxy_list) {
    GList const *iter;
    for (iter = proxy_list->list; iter; iter = iter->next) {
      ProxyData const *proxy_data = (ProxyData const *) iter->data;
      yts_client_send_message (self,
                                 YTS_CONTACT (proxy_data->contact),
                                 proxy_data->proxy_id,
                                 message);
    }
  }
  g_free (fqc_id);
  g_object_unref (message);
}

static void
_adapter_response (YtsServiceAdapter *adapter,
                   char const         *invocation_id,
                   GVariant           *return_value,
                   YtsClient         *self)
{
  YtsClientPrivate *priv = GET_PRIVATE (self);
  InvocationData  *invocation;
  YtsMetadata    *message;
  char            *fqc_id;

  invocation = g_hash_table_lookup (priv->invocations, invocation_id);
  if (NULL == invocation) {
    // FIXME report error
    g_critical ("%s : Data not found to respond to invocation %s",
                G_STRLOC,
                invocation_id);
  }

  fqc_id = yts_service_adapter_get_fqc_id (adapter);
  message = yts_response_message_new (fqc_id,
                                       invocation_id,
                                       return_value);
  yts_client_send_message (self,
                             invocation->contact,
                             invocation->proxy_id,
                             message);
  g_object_unref (message);
  g_free (fqc_id);

  client_conclude_invocation (self, invocation_id);
}

static void
_service_destroyed (ServiceData *data,
                    void        *stale_service_ptr)
{
  YtsClientPrivate *priv = GET_PRIVATE (data->client);

  g_hash_table_remove (priv->services, data->capability);
  service_data_destroy (data);
}

/**
 * yts_client_publish_service:
 * @self: object on which to invoke this method.
 * @service: Service implementation.
 *
 * Publish a service to the Ytstenut network.
 *
 * Returns: %true if publishing succeeded.
 *
 * Since 0.3
 */
bool
yts_client_publish_service (YtsClient     *self,
                            YtsCapability *service)
{
/*
 * TODO add GError reporting
 * The client does not take ownership of the service, it will be
 * unregistered upon destruction.
 */
  YtsClientPrivate *priv = GET_PRIVATE (self);
  YtsServiceAdapter   *adapter;
  YtsProfileImpl      *profile_impl;
  ServiceData          *service_data;
  char                **fqc_ids;
  unsigned              i;
  YtsAdapterFactory   *const factory = yts_adapter_factory_get_default ();

  g_return_val_if_fail (YTS_IS_CLIENT (self), FALSE);
  g_return_val_if_fail (YTS_IS_CAPABILITY (service), FALSE);

  fqc_ids = yts_capability_get_fqc_ids (service);

  /* Check that capabilities are not implemented yet. */
  for (i = 0; fqc_ids[i] != NULL; i++) {

    adapter = g_hash_table_lookup (priv->services, fqc_ids[i]);
    if (adapter)
      {
        g_critical ("%s : Service for capability %s already registered",
                    G_STRLOC,
                    fqc_ids[i]);
        g_strfreev (fqc_ids);
        return FALSE;
      }
  }

  /* Hook up the service */
  for (i = 0; fqc_ids[i] != NULL; i++) {

    adapter = yts_adapter_factory_create_adapter (factory, service, fqc_ids[i]);
    g_return_val_if_fail (adapter, FALSE);

    service_data = service_data_create (self, fqc_ids[i]);
    g_object_weak_ref (G_OBJECT (service),
                       (GWeakNotify) _service_destroyed,
                       service_data);

    g_signal_connect (adapter, "error",
                      G_CALLBACK (_adapter_error), self);
    g_signal_connect (adapter, "event",
                      G_CALLBACK (_adapter_event), self);
    g_signal_connect (adapter, "response",
                      G_CALLBACK (_adapter_response), self);

    /* Hash table takes adapter reference */
    g_hash_table_insert (priv->services,
                         g_strdup (fqc_ids[i]),
                         adapter);
    yts_client_add_capability (self, fqc_ids[i], YTS_CAPABILITY_MODE_PROVIDED);

    /* Keep the proxy management service up to date. */
    adapter = g_hash_table_lookup (priv->services, YTS_PROFILE_FQC_ID);
    if (NULL == adapter) {
      profile_impl = yts_profile_impl_new (self);
      adapter = g_object_new (YTS_TYPE_PROFILE_ADAPTER,
                              "service", profile_impl,
                              NULL);
      g_hash_table_insert (priv->services,
                           g_strdup (YTS_PROFILE_FQC_ID),
                           adapter);

      g_signal_connect (adapter, "error",
                        G_CALLBACK (_adapter_error), self);
      g_signal_connect (adapter, "event",
                        G_CALLBACK (_adapter_event), self);
      g_signal_connect (adapter, "response",
                        G_CALLBACK (_adapter_response), self);

    } else {
      profile_impl = YTS_PROFILE_IMPL (
                        yts_service_adapter_get_service (adapter));
      /* Not nice, but it's still referenced by the adapter. */
      g_object_unref (profile_impl);
    }

    yts_profile_impl_add_capability (profile_impl, fqc_ids[i]);
  }

  g_strfreev (fqc_ids);

  return TRUE;
}

bool
yts_client_get_invocation_proxy (YtsClient   *self,
                                  char const   *invocation_id,
                                  YtsContact **contact,
                                  char const  **proxy_id)
{
  YtsClientPrivate *priv = GET_PRIVATE (self);
  InvocationData const *invocation;

  g_return_val_if_fail (YTS_IS_CLIENT (self), false);
  g_return_val_if_fail (contact, false);
  g_return_val_if_fail (proxy_id, false);

  invocation = g_hash_table_lookup (priv->invocations, invocation_id);
  g_return_val_if_fail (invocation, false);

  *contact = invocation->contact;
  *proxy_id = invocation->proxy_id;

  return true;
}

GVariant *
yts_client_register_proxy (YtsClient  *self,
                            char const  *capability,
                            YtsContact *contact,
                            char const  *proxy_id)
{
  YtsClientPrivate *priv = GET_PRIVATE (self);
  ProxyList           *proxy_list;
  YtsServiceAdapter  *adapter = NULL;
  GVariant            *properties = NULL;

  g_return_val_if_fail (YTS_IS_CLIENT (self), false);

  proxy_list = g_hash_table_lookup (priv->proxies, capability);
  if (NULL == proxy_list) {
    proxy_list = proxy_list_create_with_proxy (contact, proxy_id);
    g_hash_table_insert (priv->proxies,
                         g_strdup (capability),
                         proxy_list);
  } else {
    proxy_list_ensure_proxy (proxy_list, contact, proxy_id);
  }


  /* This is a bit of a hack but we're returning the collected
   * object properties as response to the register-proxy invocation. */
  adapter = g_hash_table_lookup (priv->services, capability);
  if (adapter) {
    properties = yts_service_adapter_collect_properties (adapter);

  } else {

    g_critical ("%s : Could not find adapter for capability %s",
                G_STRLOC,
                capability);
  }

  return properties;
}

bool
yts_client_unregister_proxy (YtsClient  *self,
                              char const  *capability,
                              char const  *proxy_id)
{
  YtsClientPrivate *priv = GET_PRIVATE (self);
  ProxyList *proxy_list;

  g_return_val_if_fail (YTS_IS_CLIENT (self), false);

  proxy_list = g_hash_table_lookup (priv->proxies, capability);
  if (NULL == proxy_list) {
    g_warning ("%s : No proxy for %s:%s",
               G_STRLOC,
               proxy_id,
               capability);
    return false;
  }

  proxy_list_purge_proxy_id (proxy_list, proxy_id);
  if (proxy_list_is_empty (proxy_list)) {
    g_hash_table_remove (priv->proxies, capability);
  }

  return true;
}

/**
 * yts_client_foreach_service:
 * @self: object on which to invoke this method.
 * @iterator: iterator function.
 * @user_data: context to pass to the iterator function.
 *
 * Iterate over @self's published services.
 *
 * Returns: %true if all the services have been iterated.
 *
 * Since: 0.3
 */
bool
yts_client_foreach_service (YtsClient                 *self,
                            YtsClientServiceIterator   iterator,
                            void                      *user_data)
{
  YtsClientPrivate *priv = GET_PRIVATE (self);
  GHashTableIter     iter;
  char const        *fqc_id;
  YtsServiceAdapter *adapter;
  bool               ret = true;

  g_return_val_if_fail (YTS_IS_CLIENT (self), false);
  g_return_val_if_fail (iterator, false);

  g_hash_table_iter_init (&iter, priv->services);
  while (ret &&
         g_hash_table_iter_next (&iter,
                                 (void **) &fqc_id,
                                 (void **) &adapter)) {
    YtsCapability *capability = yts_service_adapter_get_service (adapter);
    ret = iterator (self, fqc_id, capability, user_data);
  }

  return ret;
}