summaryrefslogtreecommitdiff
path: root/src/presence-cache.c
blob: 4b73104d3119a8bb3f5d27f91f9158b016b1caa9 (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
/*
 * gabble-presence-cache.c - Gabble's contact presence cache
 * Copyright (C) 2005 Collabora Ltd.
 * Copyright (C) 2005 Nokia Corporation
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "config.h"
#include "presence-cache.h"
#include "vcard-manager.h"
#include "gabble-enumtypes.h"

#include <stdlib.h>
#include <string.h>
#include <glib.h>

/* When five DIFFERENT guys report the same caps for a given bundle, it'll
 * be enough. But if only ONE guy use the verification string (XEP-0115 v1.5),
 * it'll be enough too.
 */
#define CAPABILITY_BUNDLE_ENOUGH_TRUST 5
#define DEBUG_FLAG GABBLE_DEBUG_PRESENCE

#include <dbus/dbus-glib.h>
#include <telepathy-glib/channel-manager.h>
#include <telepathy-glib/intset.h>
#include <wocky/wocky-caps-cache.h>
#include <wocky/wocky-caps-hash.h>
#include <wocky/wocky-disco-identity.h>
#include <wocky/wocky-utils.h>
#include <wocky/wocky-namespaces.h>
#include <wocky/wocky-data-form.h>
#include <wocky/wocky-xmpp-error-enumtypes.h>

#define DEBUG_FLAG GABBLE_DEBUG_PRESENCE

#include "gabble/capabilities.h"
#include "gabble/caps-channel-manager.h"
#include "conn-presence.h"
#include "debug.h"
#include "disco.h"
#include "gabble-signals-marshal.h"
#include "namespaces.h"
#include "util.h"
#include "roster.h"
#include "types.h"

/* Time period from the cache creation in which we're unsure whether we
 * got initial presence from all the contacts. */
#define UNSURE_PERIOD 5

/* Time period from a de-cloak request in which we're unsure whether the
 * contact will disclose their presence later, or not at all. */
#define DECLOAK_PERIOD 5

G_DEFINE_TYPE (GabblePresenceCache, gabble_presence_cache, G_TYPE_OBJECT);

/* properties */
enum
{
  PROP_CONNECTION = 1,
  LAST_PROPERTY
};

/* signal enum */
enum
{
  PRESENCES_UPDATED,
  NICKNAME_UPDATE,
  CAPABILITIES_UPDATE,
  AVATAR_UPDATE,
  CAPABILITIES_DISCOVERED,
  LOCATION_UPDATED,
  UNSURE_PERIOD_ENDED,
  CLIENT_TYPES_UPDATED,
  LAST_SIGNAL
};

static guint signals[LAST_SIGNAL] = { 0 };

struct _GabblePresenceCachePrivate
{
  GabbleConnection *conn;

  gulong status_changed_cb;
  guint message_cb;
  guint presence_cb;

  GHashTable *presence;
  TpHandleSet *presence_handles;

  GHashTable *capabilities;
  GHashTable *disco_pending;
  guint caps_serial;

  guint unsure_id;
  /* handle => DecloakContext */
  GHashTable *decloak_requests;
  TpHandleSet *decloak_handles;

  /* The cached contacts' location.
   * The key is the contact's TpHandle.
   * The value is a GHashTable of the user's location:
   *   - the key is a gchar* as per XEP-0080
   *   - the value is a slice allocation GValue, the exact
   *     type depends on the key.
   */
  GHashTable *location;

  /* Are we resetting the image hash as per XEP-0153 section 4.4 */
  gboolean avatar_reset_pending;

  gboolean dispose_has_run;
};

typedef struct _DiscoWaiter DiscoWaiter;

struct _DiscoWaiter
{
  TpHandleRepoIface *repo;
  TpHandle handle;
  gchar *resource;
  guint serial;
  gboolean disco_requested;
  gchar *hash;
  gchar *ver;
};

/**
 * disco_waiter_new ()
 */
static DiscoWaiter *
disco_waiter_new (TpHandleRepoIface *repo,
                  TpHandle handle,
                  const gchar *resource,
                  const gchar *hash,
                  const gchar *ver,
                  guint serial)
{
  DiscoWaiter *waiter;

  g_assert (repo);
  tp_handle_ref (repo, handle);

  waiter = g_slice_new0 (DiscoWaiter);
  waiter->repo = repo;
  waiter->handle = handle;
  waiter->resource = g_strdup (resource);
  waiter->hash = g_strdup (hash);
  waiter->ver = g_strdup (ver);
  waiter->serial = serial;

  DEBUG ("created waiter %p for handle %u with serial %u", waiter, handle,
      serial);

  return waiter;
}

static void
disco_waiter_free (DiscoWaiter *waiter)
{
  g_assert (NULL != waiter);

  DEBUG ("freeing waiter %p for handle %u with serial %u", waiter,
      waiter->handle, waiter->serial);

  tp_handle_unref (waiter->repo, waiter->handle);

  g_free (waiter->resource);
  g_free (waiter->hash);
  g_free (waiter->ver);
  g_slice_free (DiscoWaiter, waiter);
}

static void
disco_waiter_list_free (GSList *list)
{
  GSList *i;

  DEBUG ("list %p", list);

  for (i = list; NULL != i; i = i->next)
    disco_waiter_free ((DiscoWaiter *) i->data);

  g_slist_free (list);
}

static guint
disco_waiter_list_get_request_count (GSList *list)
{
  guint c = 0;
  GSList *i;

  for (i = list; i; i = i->next)
    {
      DiscoWaiter *waiter = (DiscoWaiter *) i->data;

      if (waiter->disco_requested)
        {
          if (!tp_strdiff (waiter->hash, "sha-1"))
            /* One waiter is enough if
             * 1. the request has a verification string
             * 2. the hash algorithm is supported
             */
            c += CAPABILITY_BUNDLE_ENOUGH_TRUST;
          else
            c++;
        }
    }

  return c;
}

static GabbleCapabilityInfo *
capability_info_get (GabblePresenceCache *cache, const gchar *node)
{
  GabblePresenceCachePrivate *priv = cache->priv;
  GabbleCapabilityInfo *info = g_hash_table_lookup (priv->capabilities, node);

  if (NULL == info)
    {
      info = g_slice_new0 (GabbleCapabilityInfo);
      info->cap_set = NULL;
      info->client_types = 0;
      info->guys = tp_intset_new ();
      g_hash_table_insert (priv->capabilities, g_strdup (node), info);
    }

  return info;
}

static void
capability_info_free (GabbleCapabilityInfo *info)
{
  if (info->cap_set != NULL)
    {
      gabble_capability_set_free (info->cap_set);
      info->cap_set = NULL;
    }

  wocky_disco_identity_array_free (info->identities);
  info->identities = NULL;

  if (info->data_forms != NULL)
    g_ptr_array_unref (info->data_forms);
  info->data_forms = NULL;

  tp_intset_destroy (info->guys);

  g_slice_free (GabbleCapabilityInfo, info);
}

static void
replace_data_forms (GabbleCapabilityInfo *info,
    GPtrArray *data_forms)
{
  if (data_forms == info->data_forms)
    return;

  tp_clear_pointer (&info->data_forms, g_ptr_array_unref);

  if (data_forms != NULL)
    info->data_forms = g_ptr_array_ref (data_forms);
}

static guint
capability_info_recvd (GabblePresenceCache *cache,
    const gchar *node,
    TpHandle handle,
    GabbleCapabilitySet *cap_set,
    guint trust_inc,
    guint client_types,
    GPtrArray *data_forms)
{
  GabbleCapabilityInfo *info = capability_info_get (cache, node);

  if (info->cap_set == NULL ||
      !gabble_capability_set_equals (cap_set, info->cap_set))
    {
      /* The caps are not valid, either because we detected inconsistency
       * between several contacts using the same node (when the hash is not
       * used), or because this is the first caps report and the caps were
       * never set.
       */
      tp_intset_clear (info->guys);

      if (info->cap_set == NULL)
        info->cap_set = gabble_capability_set_new ();
      else
        gabble_capability_set_clear (info->cap_set);

      gabble_capability_set_update (info->cap_set, cap_set);
      info->trust = 0;
    }

  if (!tp_intset_is_member (info->guys, handle))
    {
      tp_intset_add (info->guys, handle);
      info->trust += trust_inc;
    }

  info->client_types = client_types;

  replace_data_forms (info, data_forms);

  return info->trust;
}

typedef struct {
    GabblePresenceCache *cache;
    TpHandle handle;
    guint timeout_id;
    const gchar *reason;
} DecloakContext;

static DecloakContext *
decloak_context_new (GabblePresenceCache *cache,
    TpHandle handle,
    const gchar *reason)
{
  DecloakContext *dc = g_slice_new0 (DecloakContext);

  dc->cache = cache;
  dc->handle = handle;
  dc->reason = reason;
  dc->timeout_id = 0;
  return dc;
}

static void
decloak_context_free (gpointer data)
{
  DecloakContext *dc = data;

  tp_handle_set_remove (dc->cache->priv->decloak_handles, dc->handle);

  if (dc->timeout_id != 0)
    g_source_remove (dc->timeout_id);

  g_slice_free (DecloakContext, dc);
}

static void gabble_presence_cache_init (GabblePresenceCache *presence_cache);
static GObject * gabble_presence_cache_constructor (GType type, guint n_props,
    GObjectConstructParam *props);
static void gabble_presence_cache_dispose (GObject *object);
static void gabble_presence_cache_finalize (GObject *object);
static void gabble_presence_cache_set_property (GObject *object, guint
    property_id, const GValue *value, GParamSpec *pspec);
static void gabble_presence_cache_get_property (GObject *object, guint
    property_id, GValue *value, GParamSpec *pspec);
static GabblePresence *_cache_insert (GabblePresenceCache *cache,
    TpHandle handle);

static void gabble_presence_cache_porter_available_cb (
    GabbleConnection *conn,
    WockyPorter *porter,
    gpointer user_data);
static void gabble_presence_cache_status_changed_cb (GabbleConnection *,
    TpConnectionStatus, TpConnectionStatusReason, gpointer);
static gboolean _parse_message_message (
    WockyPorter *porter,
    WockyStanza *message,
    gpointer user_data);
static gboolean gabble_presence_cache_presence_cb (
    WockyPorter *porter,
    WockyStanza *message,
    gpointer user_data);

static void
gabble_presence_cache_class_init (GabblePresenceCacheClass *klass)
{
  GObjectClass *object_class = G_OBJECT_CLASS (klass);
  GParamSpec *param_spec;

  g_type_class_add_private (object_class, sizeof (GabblePresenceCachePrivate));

  object_class->constructor = gabble_presence_cache_constructor;

  object_class->dispose = gabble_presence_cache_dispose;
  object_class->finalize = gabble_presence_cache_finalize;

  object_class->get_property = gabble_presence_cache_get_property;
  object_class->set_property = gabble_presence_cache_set_property;

  param_spec = g_param_spec_object ("connection", "GabbleConnection object",
      "Gabble connection object that owns this presence cache.",
      GABBLE_TYPE_CONNECTION,
      G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);
  g_object_class_install_property (object_class,
                                   PROP_CONNECTION,
                                   param_spec);

  signals[PRESENCES_UPDATED] = g_signal_new (
    "presences-updated",
    G_TYPE_FROM_CLASS (klass),
    G_SIGNAL_RUN_LAST,
    0,
    NULL, NULL,
    g_cclosure_marshal_VOID__BOXED, G_TYPE_NONE, 1, DBUS_TYPE_G_UINT_ARRAY);
  signals[NICKNAME_UPDATE] = g_signal_new (
    "nickname-update",
    G_TYPE_FROM_CLASS (klass),
    G_SIGNAL_RUN_LAST,
    0,
    NULL, NULL,
    g_cclosure_marshal_VOID__UINT, G_TYPE_NONE, 1, G_TYPE_UINT);
  signals[CAPABILITIES_UPDATE] = g_signal_new (
    "capabilities-update",
    G_TYPE_FROM_CLASS (klass),
    G_SIGNAL_RUN_LAST,
    0,
    NULL, NULL,
    gabble_marshal_VOID__UINT_POINTER_POINTER, G_TYPE_NONE,
    3, G_TYPE_UINT, G_TYPE_POINTER, G_TYPE_POINTER);
  signals[AVATAR_UPDATE] = g_signal_new (
    "avatar-update",
    G_TYPE_FROM_CLASS (klass),
    G_SIGNAL_RUN_LAST,
    0,
    NULL, NULL,
    g_cclosure_marshal_VOID__UINT_POINTER, G_TYPE_NONE, 2, G_TYPE_UINT, G_TYPE_POINTER);
  signals[CAPABILITIES_DISCOVERED] = g_signal_new (
    "capabilities-discovered",
    G_TYPE_FROM_CLASS (klass),
    G_SIGNAL_RUN_LAST,
    0,
    NULL, NULL,
    g_cclosure_marshal_VOID__UINT, G_TYPE_NONE,
    1, G_TYPE_UINT);

  signals[LOCATION_UPDATED] = g_signal_new (
    "location-update",
    G_TYPE_FROM_CLASS (klass),
    G_SIGNAL_RUN_LAST,
    0,
    NULL, NULL,
    g_cclosure_marshal_VOID__UINT, G_TYPE_NONE, 1, G_TYPE_UINT);

  signals[UNSURE_PERIOD_ENDED] = g_signal_new (
    "unsure-period-ended",
    G_TYPE_FROM_CLASS (klass),
    G_SIGNAL_RUN_LAST,
    0,
    NULL, NULL,
    g_cclosure_marshal_VOID__VOID, G_TYPE_NONE,
    0);

  signals[CLIENT_TYPES_UPDATED] = g_signal_new (
    "client-types-updated",
    G_TYPE_FROM_CLASS (klass),
    G_SIGNAL_RUN_LAST,
    0,
    NULL, NULL,
    g_cclosure_marshal_VOID__UINT, G_TYPE_NONE, 1, TP_TYPE_HANDLE);
}

static gboolean
gabble_presence_cache_end_unsure_period (gpointer data)
{
  GabblePresenceCache *self = GABBLE_PRESENCE_CACHE (data);

  DEBUG ("%p", data);
  self->priv->unsure_id = 0;
  g_signal_emit (self, signals[UNSURE_PERIOD_ENDED], 0);
  return FALSE;
}

static void
gabble_presence_cache_init (GabblePresenceCache *cache)
{
  GabblePresenceCachePrivate *priv = G_TYPE_INSTANCE_GET_PRIVATE (cache,
      GABBLE_TYPE_PRESENCE_CACHE, GabblePresenceCachePrivate);

  cache->priv = priv;

  priv->presence = g_hash_table_new_full (NULL, NULL, NULL, g_object_unref);
  priv->capabilities = g_hash_table_new_full (g_str_hash, g_str_equal, g_free,
      (GDestroyNotify) capability_info_free);
  priv->disco_pending = g_hash_table_new_full (g_str_hash, g_str_equal,
    g_free, (GDestroyNotify) disco_waiter_list_free);
  priv->caps_serial = 1;

  priv->decloak_requests = g_hash_table_new_full (NULL, NULL, NULL,
      decloak_context_free);

  priv->location = g_hash_table_new_full (g_direct_hash, g_direct_equal, NULL,
      (GDestroyNotify) g_hash_table_unref);
}

static void gabble_presence_cache_add_bundle_caps (GabblePresenceCache *cache,
    const gchar *node, const gchar *ns);

static void
gabble_presence_cache_add_bundles (GabblePresenceCache *cache)
{
#define GOOGLE_BUNDLE(cap, features) \
  gabble_presence_cache_add_bundle_caps (cache, \
      "http://www.google.com/xmpp/client/caps#" cap, features); \
  gabble_presence_cache_add_bundle_caps (cache, \
      "http://talk.google.com/xmpp/client/caps#" cap, features); \
  gabble_presence_cache_add_bundle_caps (cache, \
      "http://www.android.com/gtalk/client/caps#" cap, features);

  /* Cache various bundle from the Google Talk clients as trusted.  Some old
   * versions of Google Talk do not reply correctly to discovery requests.
   * Plus, we know what Google's bundles mean, so it's a waste of time to disco
   * them, particularly the ones for features we don't support. The desktop
   * client doesn't currently have all of these, but it doesn't hurt to cache
   * them anyway.
   */
  GOOGLE_BUNDLE ("voice-v1", NS_GOOGLE_FEAT_VOICE);
  GOOGLE_BUNDLE ("video-v1", NS_GOOGLE_FEAT_VIDEO);

  /* File transfer support */
  GOOGLE_BUNDLE ("share-v1", NS_GOOGLE_FEAT_SHARE);

  /* Not really sure what this ones is. */
  GOOGLE_BUNDLE ("sms-v1", NULL);

  /* TODO: remove this when we fix fd.o#22768. */
  GOOGLE_BUNDLE ("pmuc-v1", NULL);

  /* The camera-v1 bundle seems to mean "I have a camera plugged in". Not
   * having it doesn't seem to affect anything, and we have no way of exposing
   * that information anyway.
   */
  GOOGLE_BUNDLE ("camera-v1", NULL);

#undef GOOGLE_BUNDLE

  /* We should also cache the ext='' bundles Gabble advertises: older Gabbles
   * advertise these and don't support hashed caps, and we shouldn't need to
   * disco them.
   */
  gabble_presence_cache_add_bundle_caps (cache,
      NS_GABBLE_CAPS "#" BUNDLE_VOICE_V1, NS_GOOGLE_FEAT_VOICE);
  gabble_presence_cache_add_bundle_caps (cache,
      NS_GABBLE_CAPS "#" BUNDLE_VIDEO_V1, NS_GOOGLE_FEAT_VIDEO);
  gabble_presence_cache_add_bundle_caps (cache,
      NS_GABBLE_CAPS "#" BUNDLE_SHARE_V1, NS_GOOGLE_FEAT_SHARE);
}

static GObject *
gabble_presence_cache_constructor (GType type, guint n_props,
                                   GObjectConstructParam *props)
{
  GObject *obj;
  GabblePresenceCachePrivate *priv;

  obj = G_OBJECT_CLASS (gabble_presence_cache_parent_class)->
           constructor (type, n_props, props);
  priv = GABBLE_PRESENCE_CACHE (obj)->priv;

  g_assert (priv->conn != NULL);
  g_assert (priv->presence_handles != NULL);
  g_assert (priv->decloak_handles != NULL);

  gabble_presence_cache_add_bundles ((GabblePresenceCache *) obj);

  priv->status_changed_cb = g_signal_connect (priv->conn, "status-changed",
      G_CALLBACK (gabble_presence_cache_status_changed_cb), obj);
  tp_g_signal_connect_object (priv->conn, "porter-available",
      G_CALLBACK (gabble_presence_cache_porter_available_cb), obj, 0);

  return obj;
}

static void
gabble_presence_cache_dispose (GObject *object)
{
  GabblePresenceCache *self = GABBLE_PRESENCE_CACHE (object);
  GabblePresenceCachePrivate *priv = self->priv;

  if (priv->dispose_has_run)
    return;

  DEBUG ("dispose called");

  priv->dispose_has_run = TRUE;

  if (priv->unsure_id != 0)
    {
      g_source_remove (priv->unsure_id);
      priv->unsure_id = 0;
    }

  tp_clear_pointer (&priv->decloak_requests, g_hash_table_unref);
  tp_clear_pointer (&priv->decloak_handles, tp_handle_set_destroy);

  g_assert (priv->message_cb == 0);
  g_assert (priv->presence_cb == 0);

  g_signal_handler_disconnect (priv->conn, priv->status_changed_cb);

  tp_clear_pointer (&priv->presence, g_hash_table_unref);
  tp_clear_pointer (&priv->capabilities, g_hash_table_unref);
  tp_clear_pointer (&priv->disco_pending, g_hash_table_unref);
  tp_clear_pointer (&priv->presence_handles, tp_handle_set_destroy);
  tp_clear_pointer (&priv->location, g_hash_table_unref);

  if (G_OBJECT_CLASS (gabble_presence_cache_parent_class)->dispose)
    G_OBJECT_CLASS (gabble_presence_cache_parent_class)->dispose (object);
}

static void
gabble_presence_cache_finalize (GObject *object)
{
  DEBUG ("called with %p", object);

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

static void
gabble_presence_cache_get_property (GObject    *object,
                                    guint       property_id,
                                    GValue     *value,
                                    GParamSpec *pspec)
{
  GabblePresenceCache *cache = GABBLE_PRESENCE_CACHE (object);
  GabblePresenceCachePrivate *priv = cache->priv;

  switch (property_id) {
    case PROP_CONNECTION:
      g_value_set_object (value, priv->conn);
      break;
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
      break;
  }
}

static void
gabble_presence_cache_set_property (GObject     *object,
                                    guint        property_id,
                                    const GValue *value,
                                    GParamSpec   *pspec)
{
  GabblePresenceCache *cache = GABBLE_PRESENCE_CACHE (object);
  GabblePresenceCachePrivate *priv = cache->priv;
  TpHandleRepoIface *contact_repo;

  switch (property_id) {
    case PROP_CONNECTION:
      g_assert (priv->conn == NULL);              /* construct-only */
      g_assert (priv->presence_handles == NULL);  /* construct-only */
      g_assert (priv->decloak_handles == NULL);   /* construct-only */

      priv->conn = g_value_get_object (value);
      contact_repo = tp_base_connection_get_handles (
          (TpBaseConnection *) priv->conn, TP_HANDLE_TYPE_CONTACT);
      priv->presence_handles = tp_handle_set_new (contact_repo);
      priv->decloak_handles = tp_handle_set_new (contact_repo);
      break;

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

static void
gabble_presence_cache_porter_available_cb (
    GabbleConnection *conn,
    WockyPorter *porter,
    gpointer user_data)
{
  GabblePresenceCache *cache = GABBLE_PRESENCE_CACHE (user_data);
  GabblePresenceCachePrivate *priv = cache->priv;

  priv->message_cb = wocky_porter_register_handler_from_anyone (porter,
      WOCKY_STANZA_TYPE_MESSAGE, WOCKY_STANZA_SUB_TYPE_NONE,
      WOCKY_PORTER_HANDLER_PRIORITY_MAX,
      _parse_message_message, cache,
      NULL);
  priv->presence_cb = wocky_porter_register_handler_from_anyone (porter,
      WOCKY_STANZA_TYPE_PRESENCE, WOCKY_STANZA_SUB_TYPE_NONE,
      WOCKY_PORTER_HANDLER_PRIORITY_MIN,
      gabble_presence_cache_presence_cb, cache,
      NULL);
}

static void
gabble_presence_cache_status_changed_cb (GabbleConnection *conn,
                                         TpConnectionStatus status,
                                         TpConnectionStatusReason reason,
                                         gpointer data)
{
  GabblePresenceCache *cache = GABBLE_PRESENCE_CACHE (data);
  GabblePresenceCachePrivate *priv = cache->priv;

  g_assert (conn == priv->conn);

  switch (status)
    {
    case TP_CONNECTION_STATUS_CONNECTING:
      break;

    case TP_CONNECTION_STATUS_CONNECTED:
      /* After waiting UNSURE_PERIOD seconds for initial presences to trickle
       * in, the "unsure period" ends. */
      priv->unsure_id = g_timeout_add_seconds (UNSURE_PERIOD,
          gabble_presence_cache_end_unsure_period, cache);
      break;

    case TP_CONNECTION_STATUS_DISCONNECTED:
      if (conn->session != NULL)
        {
          WockyPorter *porter = wocky_session_get_porter (conn->session);

          if (priv->message_cb != 0)
            wocky_porter_unregister_handler (porter, priv->message_cb);

          if (priv->presence_cb != 0)
            wocky_porter_unregister_handler (porter, priv->presence_cb);

          priv->message_cb = 0;
          priv->presence_cb = 0;
        }

      break;

    default:
      g_assert_not_reached ();
    }
}

static GabblePresenceId
_presence_node_get_status (WockyNode *pres_node)
{
  const gchar *presence_show =
      wocky_node_get_content_from_child (pres_node, "show");

  if (!presence_show)
    {
      /*
      NODE_DEBUG (pres_node,
        "empty <show> tag received from server, "
        "setting presence to available");
      */
      return GABBLE_PRESENCE_AVAILABLE;
    }

  if (0 == strcmp (presence_show, JABBER_PRESENCE_SHOW_AWAY))
    return GABBLE_PRESENCE_AWAY;
  else if (0 == strcmp (presence_show, JABBER_PRESENCE_SHOW_CHAT))
    return GABBLE_PRESENCE_CHAT;
  else if (0 == strcmp (presence_show, JABBER_PRESENCE_SHOW_DND))
    return GABBLE_PRESENCE_DND;
  else if (0 == strcmp (presence_show, JABBER_PRESENCE_SHOW_XA))
    return GABBLE_PRESENCE_XA;
  else
    {
       NODE_DEBUG (pres_node,
        "unrecognised <show/> value received from server, "
        "setting presence to available");
      return GABBLE_PRESENCE_AVAILABLE;
    }
}

static void
_grab_nickname (GabblePresenceCache *cache,
                TpHandle handle,
                const gchar *from,
                WockyNode *node)
{
  const gchar *nickname;
  GabblePresence *presence;

  node = wocky_node_get_child_ns (node, "nick", NS_NICK);

  if (NULL == node)
    return;

  presence = gabble_presence_cache_get (cache, handle);

  if (NULL == presence)
    return;

  nickname = node->content;
  DEBUG ("got nickname \"%s\" for %s", nickname, from);

  if (tp_strdiff (presence->nickname, nickname))
    {
      g_free (presence->nickname);
      presence->nickname = g_strdup (nickname);
      g_signal_emit (cache, signals[NICKNAME_UPDATE], 0, handle);
    }
}

static void
self_vcard_request_cb (GabbleVCardManager *self,
                       GabbleVCardManagerRequest *request,
                       TpHandle handle,
                       WockyNode *vcard,
                       GError *error,
                       gpointer user_data)
{
  GabblePresenceCache *cache = user_data;
  GabblePresenceCachePrivate *priv = cache->priv;
  gchar *sha1 = NULL;

  priv->avatar_reset_pending = FALSE;

  if (vcard != NULL)
    {
      sha1 = vcard_get_avatar_sha1 (vcard);

      /* FIXME: presence->avatar_sha1 is resetted in
       * self_avatar_resolve_conflict() and the following signal set it in
       * conn-avatars.c. Doing that in 2 different files is confusing.
       */
      g_signal_emit (cache, signals[AVATAR_UPDATE], 0, handle, sha1);

      g_free (sha1);
    }
  DEBUG ("End of avatar conflict resolution");
}

static void
self_avatar_resolve_conflict (GabblePresenceCache *cache)
{
  GabblePresenceCachePrivate *priv = cache->priv;
  TpBaseConnection *base_conn = (TpBaseConnection *) priv->conn;
  GabblePresence *presence = priv->conn->self_presence;
  GError *error = NULL;

  if (base_conn->status != TP_CONNECTION_STATUS_CONNECTED)
    {
      DEBUG ("no longer connected");
      return;
    }

  /* We don't want recursive image resetting
   *
   * FIXME: There is a race here: if the other resource sends us first the
   * hash 'hash1', and then 'hash2' while the vCard request generated for
   * 'hash1' is still pending, the current code doesn't send a new vCard
   * request, although it should because Gabble cannot know whether the reply
   * will be for hash1 or hash2. The good solution would be to store the
   * received hash and each time the hash is different, cancel the previous
   * vCard request and send a new one. However, this is tricky, so we don't
   * implement it.
   *
   * This race is not so bad: the only bad consequence is if the other Jabber
   * client changes the avatar twice quickly, we may get only the first one.
   * The real contacts should still get the last avatar.
   */
  if (priv->avatar_reset_pending)
    {
      DEBUG ("There is already an avatar conflict resolution pending.");
      return;
    }

  /* according to XEP-0153 section 4.3-2. 3rd bullet:
   * if we receive a photo from another resource, then we MUST
   * immediately send a presence update with an empty update child
   * element (no photo node), then re-download our own vCard;
   * when that arrives, we may start setting the photo node in our
   * presence again.
   */
  DEBUG ("Reset our avatar, signal our presence without an avatar and request"
         " our own vCard.");
  priv->avatar_reset_pending = TRUE;
  g_free (presence->avatar_sha1);
  presence->avatar_sha1 = NULL;
  if (!conn_presence_signal_own_presence (priv->conn, NULL, &error))
    {
      DEBUG ("failed to send own presence: %s", error->message);
      g_error_free (error);
    }

  gabble_vcard_manager_invalidate_cache (priv->conn->vcard_manager,
      base_conn->self_handle);
  gabble_vcard_manager_request (priv->conn->vcard_manager,
      base_conn->self_handle, 0, self_vcard_request_cb, cache,
      NULL);
}

static void
_grab_avatar_sha1 (GabblePresenceCache *cache,
                   TpHandle handle,
                   const gchar *from,
                   WockyNode *node)
{
  GabblePresenceCachePrivate *priv = cache->priv;
  TpBaseConnection *base_conn = (TpBaseConnection *) priv->conn;
  const gchar *sha1;
  WockyNode *x_node, *photo_node;
  GabblePresence *presence;

  if (handle == base_conn->self_handle)
    presence = priv->conn->self_presence;
  else
    presence = gabble_presence_cache_get (cache, handle);

  if (NULL == presence)
    return;

  x_node = wocky_node_get_child_ns (node, "x",
      NS_VCARD_TEMP_UPDATE);

  if (NULL == x_node)
    {
      /* If (handle == base_conn->self_handle), then this means
       * that one of our other resources does not support XEP-0153. According
       * to that XEP, we MUST now stop advertising the image hash, at least
       * until all instances of non-conforming resources have gone offline, by
       * setting presence->avatar_sha1 to NULL.
       *
       * However, this would mean that logging in (e.g.) with an old version
       * of Gabble would disable avatars in this newer version, which is
       * quite a silly failure mode. As a result, we ignore this
       * requirement and hope that non-conforming clients won't alter the
       * <PHOTO>, which should in practice be true.
       *
       * If handle != self_handle, then in any case we want to ignore this
       * message for vCard purposes. */
      return;
    }

  photo_node = wocky_node_get_child (x_node, "photo");

  /* If there is no photo node, the resource supports XEP-0153, but has
   * nothing in particular to say about the avatar. */
  if (NULL == photo_node)
    return;

  sha1 = photo_node->content;

  /* "" means we know there is no avatar. NULL means we don't know what is the
   * avatar. In this case, there is a <photo> node. */
  if (sha1 == NULL)
    sha1 = "";

  if (tp_strdiff (presence->avatar_sha1, sha1))
    {
      if (handle == base_conn->self_handle)
        {
          DEBUG ("Avatar conflict! Received hash '%s' and our cache is '%s'",
            sha1, presence->avatar_sha1 == NULL ?
              "<NULL>" : presence->avatar_sha1);
          self_avatar_resolve_conflict (cache);
        }
      else if (base_conn->status == TP_CONNECTION_STATUS_CONNECTED)
        {
          g_free (presence->avatar_sha1);
          presence->avatar_sha1 = g_strdup (sha1);
          gabble_vcard_manager_invalidate_cache (priv->conn->vcard_manager, handle);
          g_signal_emit (cache, signals[AVATAR_UPDATE], 0, handle, sha1);
        }
    }
}

static GSList *
_parse_cap_bundles (
    WockyNode *lm_node,
    const gchar **hash,
    const gchar **ver)
{
  const gchar *node, *ext;
  GSList *uris = NULL;
  WockyNode *cap_node;

  *hash = NULL;
  *ver = NULL;

  cap_node = wocky_node_get_child_ns (lm_node, "c", NS_CAPS);

  if (NULL == cap_node)
      return NULL;

  *hash = wocky_node_get_attribute (cap_node, "hash");

  node = wocky_node_get_attribute (cap_node, "node");

  if (NULL == node)
    return NULL;

  *ver = wocky_node_get_attribute (cap_node, "ver");

  if (NULL != *ver)
    uris = g_slist_prepend (uris, g_strdup_printf ("%s#%s", node, *ver));

  /* If there is a hash, the remote contact uses XEP-0115 v1.5 and the 'ext'
   * attribute MUST be ignored. */
  if (NULL != *hash)
    return uris;

  ext = wocky_node_get_attribute (cap_node, "ext");

  if (NULL != ext)
    {
      gchar **exts, **i;

      exts = g_strsplit (ext, " ", 0);

      for (i = exts; NULL != *i; i++)
        uris = g_slist_prepend (uris, g_strdup_printf ("%s#%s", node, *i));

      g_strfreev (exts);
    }

  return uris;
}

static void
_parse_node (GabblePresence *presence,
    WockyNode *lm_node,
    const gchar *resource,
    guint serial)
{
  WockyNode *cap_node;
  const gchar *node;

  cap_node = wocky_node_get_child_ns (lm_node, "c", NS_CAPS);

  if (NULL == cap_node)
    return;

  node = wocky_node_get_attribute (cap_node, "node");

  if (!tp_strdiff (node, "http://mail.google.com/xmpp/client/caps"))
    {
      GabbleCapabilitySet *cap_set = gabble_capability_set_new ();

      DEBUG ("Client is Google Web Client");

      gabble_capability_set_add (cap_set, QUIRK_GOOGLE_WEBMAIL_CLIENT);
      gabble_capability_set_add (cap_set, QUIRK_OMITS_CONTENT_CREATORS);
      gabble_presence_set_capabilities (presence, resource, cap_set, NULL, serial);
      gabble_capability_set_free (cap_set);
    }
}


static void _caps_disco_cb (GabbleDisco *disco,
    GabbleDiscoRequest *request,
    const gchar *jid,
    const gchar *node,
    WockyNode *query_result,
    GError *error,
    gpointer user_data);

static void
redisco (GabblePresenceCache *cache,
    GabbleDisco *disco,
    DiscoWaiter *waiter,
    const gchar *node)
{
  const gchar *waiter_jid;
  gchar *full_jid;

  waiter_jid = tp_handle_inspect (waiter->repo, waiter->handle);
  if (waiter->resource != NULL)
    full_jid = g_strdup_printf ("%s/%s", waiter_jid, waiter->resource);
  else
    full_jid = g_strdup (waiter_jid);

  gabble_disco_request (disco, GABBLE_DISCO_TYPE_INFO, full_jid,
      node, _caps_disco_cb, cache, G_OBJECT (cache), NULL);
  waiter->disco_requested = TRUE;

  g_free (full_jid);
}

static void
disco_failed (GabblePresenceCache *cache,
    GabbleDisco *disco,
    const gchar *node,
    GSList *waiters)
{
  GabblePresenceCachePrivate *priv = cache->priv;
  GSList *i;
  DiscoWaiter *waiter = NULL;
  gchar *full_jid = NULL;

  for (i = waiters; NULL != i; i = i->next)
    {
      waiter = (DiscoWaiter *) i->data;

      if (!waiter->disco_requested)
        {
          redisco (cache, disco, waiter, node);
          break;
        }
    }

  if (NULL != i)
    {
      DEBUG ("sent a retry disco request to %s for URI %s", full_jid, node);
    }
  else
    {
      /* The contact sends us an error and we don't have any other
       * contacts to send the discovery request on the same node. We
       * cannot get the caps for this node. */
      DEBUG ("failed to find a suitable candidate to retry disco "
          "request for URI %s", node);
      g_hash_table_remove (priv->disco_pending, node);
    }

  g_free (full_jid);
}

static DiscoWaiter *
find_matching_waiter (GSList *waiters,
    TpHandle godot,
    const gchar *resource)
{
  GSList *i;

  for (i = waiters; NULL != i; i = i->next)
    {
      DiscoWaiter *waiter = i->data;

      if (waiter->handle == godot && !tp_strdiff (waiter->resource, resource))
        return waiter;
    }

  return NULL;
}

static void
emit_capabilities_update (GabblePresenceCache *cache,
    TpHandle handle,
    const GabbleCapabilitySet *old_cap_set,
    const GabbleCapabilitySet *new_cap_set)
{
  if (gabble_capability_set_equals (old_cap_set, new_cap_set))
    {
      DEBUG ("no change in caps for handle %u", handle);
    }
  else
    {
      if (DEBUGGING)
        {
          gchar *diff = gabble_capability_set_dump_diff (old_cap_set,
              new_cap_set, "  ");

          DEBUG ("Emitting caps update for handle %u\n%s", handle, diff);
          g_free (diff);
        }

      g_signal_emit (cache, signals[CAPABILITIES_UPDATE], 0,
          handle, old_cap_set, new_cap_set);
    }
}

/**
 * set_caps_for:
 *
 * Sets caps for @waiter to (@caps, @cap_set), having received
 * a trusted reply from @responder_{handle,jid}.
 */
static void
set_caps_for (DiscoWaiter *waiter,
    GabblePresenceCache *cache,
    GabbleCapabilitySet *cap_set,
    guint client_types,
    GPtrArray *data_forms,
    TpHandle responder_handle,
    const gchar *responder_jid)
{
  GabblePresence *presence = gabble_presence_cache_get (cache, waiter->handle);
  GabbleCapabilitySet *old_cap_set;
  const GabbleCapabilitySet *new_cap_set;

  if (presence == NULL)
    return;

  old_cap_set = gabble_presence_dup_caps (presence);

  DEBUG ("setting caps for %d (thanks to %d %s)",
      waiter->handle, responder_handle, responder_jid);

  gabble_presence_set_capabilities (presence, waiter->resource, cap_set,
      data_forms, waiter->serial);
  new_cap_set = gabble_presence_peek_caps (presence);
  emit_capabilities_update (cache, waiter->handle, old_cap_set, new_cap_set);
  gabble_capability_set_free (old_cap_set);

  if (gabble_presence_update_client_types (presence, waiter->resource,
        client_types))
    g_signal_emit (cache, signals[CLIENT_TYPES_UPDATED], 0, waiter->handle);
}

static void
emit_capabilities_discovered (GabblePresenceCache *cache,
    TpHandle handle)
{
  g_signal_emit (cache, signals[CAPABILITIES_DISCOVERED], 0, handle);
}

static guint
client_types_from_message (TpHandle handle,
    WockyNode *lm_node,
    const gchar *resource)
{
  WockyNode *identity, *query_result = (WockyNode *) lm_node;
  WockyNodeIter iter;
  guint client_types = 0;

  /* Find all identity nodes in the result. */
  wocky_node_iter_init (&iter, query_result, "identity", NS_DISCO_INFO);
  while (wocky_node_iter_next (&iter, &identity))
    {
      const gchar *category = wocky_node_get_attribute (identity, "category");
      const gchar *type = wocky_node_get_attribute (identity, "type");
      guint value;

      if (category == NULL || type == NULL)
        continue;

      /* So, turns out if you disco a specific resource of a gtalk
      contact, the Google servers will reply with the identity node as
      if you disco'd the bare jid, so will get something like:

          <identity category='account' type='registered' name='Google Talk User Account'/>

      which is just great. So, let's special case android phones as
      their resources will start with "android" and let's just say
      they're phones. */

      if (!tp_strdiff (category, "account")
          && (resource != NULL && g_str_has_prefix (resource, "android"))
          && !tp_strdiff (type, "registered"))
        {
          client_types |= GABBLE_CLIENT_TYPE_PHONE;
        }
      else if (!tp_strdiff (category, "client") &&
          gabble_flag_from_nick (GABBLE_TYPE_CLIENT_TYPE, type, &value))
        {
          DEBUG ("Got type for %u: %s (%u)", handle, type, value);
          client_types |= value;
        }
    }

  return client_types;
}

static GPtrArray *
data_forms_from_message (WockyNode *node)
{
  GPtrArray *out = g_ptr_array_new_with_free_func (g_object_unref);

  WockyNodeIter iter;
  WockyNode *x_node = NULL;

  wocky_node_iter_init (&iter, node, "x", WOCKY_XMPP_NS_DATA);
  while (wocky_node_iter_next (&iter, &x_node))
    {
      WockyDataForm *form  = wocky_data_form_new_from_node (x_node, NULL);

      /* we've already parsed the reply to check the hash matches, so
       * we can already guarantee these data forms will be parsed
       * fine */
      if (G_LIKELY (form != NULL))
        g_ptr_array_add (out, form);
   }

  return out;
}

static void
_signal_presences_updated (GabblePresenceCache *cache,
    TpHandle handle)
{
  GArray *handles;

  handles = g_array_sized_new (FALSE, FALSE, sizeof (TpHandle), 1);
  g_array_append_val (handles, handle);
  g_signal_emit (cache, signals[PRESENCES_UPDATED], 0, handles);
  g_array_unref (handles);
}

static void
_caps_disco_cb (GabbleDisco *disco,
                GabbleDiscoRequest *request,
                const gchar *jid,
                const gchar *node,
                WockyNode *query_result,
                GError *error,
                gpointer user_data)
{
  GSList *waiters, *i;
  DiscoWaiter *waiter_self;
  GabblePresenceCache *cache;
  GabblePresenceCachePrivate *priv;
  TpHandleRepoIface *contact_repo;
  GabbleCapabilitySet *cap_set;
  guint trust;
  TpHandle handle = 0;
  gboolean bad_hash = FALSE;
  TpBaseConnection *base_conn;
  gchar *resource;
  gboolean jid_is_valid;
  gpointer key;
  guint client_types = 0;
  GPtrArray *data_forms = NULL;

  cache = GABBLE_PRESENCE_CACHE (user_data);
  priv = cache->priv;
  base_conn = TP_BASE_CONNECTION (priv->conn);
  contact_repo = tp_base_connection_get_handles (base_conn,
      TP_HANDLE_TYPE_CONTACT);

  if (NULL == node)
    {
      DEBUG ("got disco response with NULL node, ignoring");
      return;
    }

  waiters = g_hash_table_lookup (priv->disco_pending, node);

  if (NULL != error)
    {
      DEBUG ("disco query failed: %s", error->message);

      disco_failed (cache, disco, node, waiters);

      return;
    }

  handle = tp_handle_ensure (contact_repo, jid, NULL, NULL);

  if (handle == 0)
    {
      DEBUG ("Ignoring presence from invalid JID %s", jid);
      return;
    }

  /* If tp_handle_ensure () was happy with the jid, it's valid. */
  jid_is_valid = wocky_decode_jid (jid, NULL, NULL, &resource);
  g_assert (jid_is_valid);
  waiter_self = find_matching_waiter (waiters, handle, resource);
  g_free (resource);

  if (NULL == waiter_self)
    {
      DEBUG ("Ignoring non requested disco reply from %s", jid);
      goto OUT;
    }

  /* Now onto caps */
  cap_set = gabble_capability_set_new_from_stanza (query_result);
  client_types = client_types_from_message (handle, query_result,
      waiter_self->resource);
  data_forms = data_forms_from_message (query_result);

  /* Only 'sha-1' is mandatory to implement by XEP-0115. If the remote contact
   * uses another hash algorithm, don't check the hash and fallback to the old
   * method. The hash method is not included in the discovery request nor
   * response but we saved it in disco_pending when we received the presence
   * stanza. */
  if (!tp_strdiff (waiter_self->hash, "sha-1"))
    {
      gchar *computed_hash;

      computed_hash = wocky_caps_hash_compute_from_node (query_result);

      if (computed_hash == NULL)
        {
          DEBUG ("Unable to compute caps hash for '%s'.", jid);
          trust = 0;
          bad_hash = TRUE;
        }
      else if (g_str_equal (waiter_self->ver, computed_hash))
        {
          trust = capability_info_recvd (cache, node, handle, cap_set,
              CAPABILITY_BUNDLE_ENOUGH_TRUST, client_types, data_forms);
        }
      else
        {
          DEBUG ("The verification string '%s' announced by '%s' does not "
              "match our hash of their disco reply '%s'.", waiter_self->ver,
              jid, computed_hash);
          trust = 0;
          bad_hash = TRUE;
        }

      g_free (computed_hash);
    }
  else
    {
      trust = capability_info_recvd (cache, node, handle, cap_set, 1,
          client_types, data_forms);
    }

  /* Remove the node from the hash table without freeing the key or list of
   * waiters.
   *
   * In the 'enough trust' case, this needs to be done before emitting the
   * signal, so that when recipients of the capabilities-discovered signal ask
   * whether we're unsure about the handle, there is no pending disco request
   * that would make us unsure.
   *
   * In the 'not enough trust' branch, we re-use 'key' when updating the table.
   */
  if (!g_hash_table_lookup_extended (priv->disco_pending, node, &key, NULL))
    g_assert_not_reached ();
  g_hash_table_steal (priv->disco_pending, node);

  if (trust >= CAPABILITY_BUNDLE_ENOUGH_TRUST)
    {
      WockyNodeTree *query_node = wocky_node_tree_new_from_node (query_result);
      WockyCapsCache *caps_cache = wocky_caps_cache_dup_shared ();

      if (DEBUGGING)
        {
          gchar *tmp = gabble_capability_set_dump (cap_set, "  ");

          DEBUG ("trusting %s to mean:\n%s", node, tmp);
          g_free (tmp);
        }

      /* Update external cache. */
      wocky_caps_cache_insert (caps_cache, node, query_node);
      g_object_unref (caps_cache);
      g_object_unref (query_node);

      /* We trust this caps node. Serve all its waiters. */
      for (i = waiters; NULL != i; i = i->next)
        {
          DiscoWaiter *waiter = (DiscoWaiter *) i->data;

          set_caps_for (waiter, cache, cap_set, client_types,
              data_forms, handle, jid);
          emit_capabilities_discovered (cache, waiter->handle);
        }

      g_free (key);
      disco_waiter_list_free (waiters);
    }
  else
    {
      /* We don't trust this yet (either the hash was bad, or we haven't had
       * enough responses, as appropriate).
       */

      /* Set caps for the contact that replied (if the hash was correct) and
       * remove them from the list of waiters.
       * FIXME I think we should respect the caps, even if the hash is wrong,
       *       for the jid that answered the query.
       */
      if (!bad_hash)
        {
          if (DEBUGGING)
            {
              gchar *tmp = gabble_capability_set_dump (cap_set, "  ");

              DEBUG ("%s not yet fully trusted to mean:\n%s", node, tmp);
              g_free (tmp);
            }

          set_caps_for (waiter_self, cache, cap_set, client_types,
              data_forms, handle, jid);
        }

      waiters = g_slist_remove (waiters, waiter_self);
      g_hash_table_insert (priv->disco_pending, key, waiters);

      emit_capabilities_discovered (cache, waiter_self->handle);
      disco_waiter_free (waiter_self);

      /* Ensure that we have enough pending requests to get enough trust for
       * this node.
       */
      for (i = waiters; i != NULL; i = i->next)
        {
          DiscoWaiter *waiter = (DiscoWaiter *) i->data;

          if (trust + disco_waiter_list_get_request_count (waiters)
              >= CAPABILITY_BUNDLE_ENOUGH_TRUST)
            break;

          if (!waiter->disco_requested)
            redisco (cache, disco, waiter, node);
        }
    }

  gabble_capability_set_free (cap_set);
  g_ptr_array_unref (data_forms);

OUT:
  if (handle)
    tp_handle_unref (contact_repo, handle);
}

static void
_process_caps_uri (GabblePresenceCache *cache,
                   const gchar *from,
                   const gchar *uri,
                   const gchar *hash,
                   const gchar *ver,
                   TpHandle handle,
                   const gchar *resource,
                   guint serial)
{
  GabbleCapabilityInfo *info;
  WockyNodeTree *cached_query_reply;
  GabbleCapabilitySet *cached_caps = NULL;
  GabblePresenceCachePrivate *priv;
  TpHandleRepoIface *contact_repo;
  WockyCapsCache *caps_cache;

  priv = cache->priv;
  contact_repo = tp_base_connection_get_handles (
      (TpBaseConnection *) priv->conn, TP_HANDLE_TYPE_CONTACT);
  info = capability_info_get (cache, uri);

  caps_cache = wocky_caps_cache_dup_shared ();
  cached_query_reply = wocky_caps_cache_lookup (caps_cache, uri);

  if (cached_query_reply != NULL)
    {
      WockyNode *query = wocky_node_tree_get_top_node (cached_query_reply);

      cached_caps = gabble_capability_set_new_from_stanza (query);

      if (cached_caps == NULL)
        {
          gchar *query_str = wocky_node_to_string (query);

          g_warning ("couldn't re-parse cached query node, which was: %s",
              query_str);
          g_free (query_str);
        }
    }

  g_object_unref (caps_cache);

  if (cached_caps != NULL ||
      info->trust >= CAPABILITY_BUNDLE_ENOUGH_TRUST ||
      tp_intset_is_member (info->guys, handle))
    {
      GabblePresence *presence = gabble_presence_cache_get (cache, handle);
      GabbleCapabilitySet *cap_set = cached_caps ? cached_caps : info->cap_set;

      /* we already have enough trust for this node; apply the cached value to
       * the (handle, resource) */
      DEBUG ("enough trust for URI %s, setting caps for %u (%s)", uri, handle,
          from);

      if (presence)
        {
          guint types;

          gabble_presence_set_capabilities (
              presence, resource, cap_set, info->data_forms, serial);

          /* We can only get this information from actual disco replies,
           * so we depend on having this information from the caps cache. */
          if (cached_query_reply != NULL)
            {
              WockyNode *query = wocky_node_tree_get_top_node (cached_query_reply);
              types = client_types_from_message (handle, query, resource);
            }
          else
            {
              types = info->client_types;
            }

          if (gabble_presence_update_client_types (presence, resource, types))
            g_signal_emit (cache, signals[CLIENT_TYPES_UPDATED], 0, handle);
        }
      else
        DEBUG ("presence not found");

      if (cached_caps != NULL)
        gabble_capability_set_free (cached_caps);
    }
  else
    {
      GSList *waiters;
      DiscoWaiter *waiter;
      guint possible_trust;
      gboolean found;
      gpointer key;
      gpointer value = NULL;

      DEBUG ("not enough trust for URI %s", uri);

      /* Are we already waiting for responses for this URI? */
      found = g_hash_table_lookup_extended (priv->disco_pending, uri, &key,
          &value);
      waiters = (GSList *) value;

      waiter = find_matching_waiter (waiters, handle, resource);

      if (waiter != NULL)
        {
          /* We've already asked this jid about this node; just update the
           * serial.
           */
          DEBUG ("updating serial for waiter (%s, %s) from %u to %u",
              from, uri, waiter->serial, serial);
          waiter->serial = serial;
          goto out;
        }

      waiter = disco_waiter_new (contact_repo, handle, resource,
          hash, ver, serial);
      waiters = g_slist_prepend (waiters, waiter);

      /* If the URI was already in the hash table, steal it and re-use the same
       * URI for the following insertion. Otherwise, make a copy of the URI for
       * use as a key.
       */
      if (found)
        g_hash_table_steal (priv->disco_pending, key);
      else
        key = g_strdup (uri);

      g_hash_table_insert (priv->disco_pending, key, waiters);

      /* When all the responses we're waiting for return, will we have enough
       * trust?
       */
      possible_trust = disco_waiter_list_get_request_count (waiters);

      if (info->trust + possible_trust < CAPABILITY_BUNDLE_ENOUGH_TRUST)
        {
          /* DISCO */
          DEBUG ("only %u trust out of %u possible thus far, sending "
              "disco for URI %s", info->trust + possible_trust,
              CAPABILITY_BUNDLE_ENOUGH_TRUST, uri);
          gabble_disco_request (priv->conn->disco, GABBLE_DISCO_TYPE_INFO,
              from, uri, _caps_disco_cb, cache, G_OBJECT (cache), NULL);
          /* enough DISCO for you, buddy */
          waiter->disco_requested = TRUE;
        }
    }

out:
  if (cached_query_reply != NULL)
    g_object_unref (cached_query_reply);
}

static void
_process_caps (GabblePresenceCache *cache,
               GabblePresence *presence,
               TpHandle handle,
               const gchar *from,
               WockyNode *lm_node)
{
  const gchar *resource;
  GSList *uris, *i;
  GabblePresenceCachePrivate *priv;
  GabbleCapabilitySet *old_cap_set = NULL;
  guint serial;
  const gchar *hash, *ver;

  priv = cache->priv;
  serial = priv->caps_serial++;

  resource = strchr (from, '/');
  if (resource != NULL)
    resource++;

  uris = _parse_cap_bundles (lm_node, &hash, &ver);

  if (presence)
    {
      old_cap_set = gabble_presence_dup_caps (presence);

      _parse_node (presence, lm_node, resource, serial);
    }

  /* XEP-0115 ยง8.4 allows a server to strip out <c/> from presences it relays
   * to a client if it knows that the <c/> hasn't changed since the last time
   * it relayed one for this resource to the client. Thus, the client MUST NOT
   * expect to get <c/> on every <presence/>, and shouldn't erase previous caps
   * in that case.
   *
   * If the <presence/> stanza didn't contain a <c/> node at all, then there
   * will be no iterations of this loop, and hence no calls to
   * gabble_presence_set_capabilities(), and hence the caps will be preserved.
   * Not pretty, but it seems to work.
   */
  for (i = uris; NULL != i; i = i->next)
    {
      _process_caps_uri (cache, from, (gchar *) i->data, hash, ver, handle,
          resource, serial);
      g_free (i->data);

    }

  if (presence)
    {
      const GabbleCapabilitySet *new_cap_set =
          gabble_presence_peek_caps (presence);

      emit_capabilities_update (cache, handle, old_cap_set, new_cap_set);
    }
  else
    {
      DEBUG ("No presence for handle %u, not updating caps", handle);
    }

  if (old_cap_set != NULL)
    gabble_capability_set_free (old_cap_set);

  g_slist_free (uris);
}

static void
presence_cache_check_for_decloak_request (
    GabblePresenceCache *cache,
    WockyStanza *stanza,
    TpHandle handle,
    const gchar *from)
{
  GabblePresenceCachePrivate *priv = cache->priv;
  WockyNode *presence_node = wocky_stanza_get_top_node (stanza);
  WockyNode *child_node;

  /* If we receive (directed or broadcast) presence of any sort from someone,
   * it counts as a reply to any pending de-cloak request we might have been
   * tracking */
  g_hash_table_remove (priv->decloak_requests, GUINT_TO_POINTER (handle));

  child_node = wocky_node_get_child_ns (presence_node, "temppres",
      NS_TEMPPRES);

  if (child_node != NULL)
    {
      gboolean decloak;
      const gchar *reason;

      /* this is a request to de-cloak, i.e. leak a minimal version of our
       * presence to the peer */
      g_object_get (priv->conn,
          "decloak-automatically", &decloak,
          NULL);

      reason = wocky_node_get_attribute (child_node, "reason");

      if (reason == NULL)
        reason = "";

      DEBUG ("Considering whether to decloak, reason='%s', conclusion=%d",
          reason, decloak);

      conn_decloak_emit_requested (priv->conn, handle, reason, decloak);

      if (decloak)
        gabble_connection_send_capabilities (priv->conn, from, NULL);
    }

}


/* FIXME: in a cruel twist of fate, this is called by GabbleMucChannel!
 * Presumably this is because the handler priority here is MIN, so WockyMuc
 * steals the presence stanza before we can scrape our information out of it?
 */
gboolean
gabble_presence_parse_presence_message (
    GabblePresenceCache *cache,
    TpHandle handle,
    const gchar *from,
    WockyStanza *message)
{
  GabblePresenceCachePrivate *priv = cache->priv;
  const gchar *prio;
  gint8 priority = 0;
  const gchar *resource, *status_message = NULL;
  gchar *my_full_jid;
  WockyNode *presence_node;
  WockyStanzaSubType sub_type;
  GabblePresenceId presence_id;
  GabblePresence *presence;

  /* The server should not send back the presence stanza about ourself (same
   * resource). If it does, we just ignore the received stanza. We want to
   * avoid any infinite ping-pong with the server due to XEP-0153 4.2-2-3.
   */
  my_full_jid = gabble_connection_get_full_jid (priv->conn);
  if (!tp_strdiff (from, my_full_jid))
    {
      g_free (my_full_jid);
      return TRUE;
    }
  g_free (my_full_jid);

  presence_node = wocky_stanza_get_top_node (message);
  g_assert (0 == strcmp (presence_node->name, "presence"));

  resource = strchr (from, '/');
  if (resource != NULL)
    resource++;

  presence = gabble_presence_cache_get (cache, handle);

  if (NULL != presence)
      /* Once we've received presence from somebody, we don't need to keep the
       * presence around when it's unavailable. */
      presence->keep_unavailable = FALSE;

  status_message = wocky_node_get_content_from_child (presence_node, "status");
  prio = wocky_node_get_content_from_child (presence_node, "priority");

  if (prio != NULL)
    priority = CLAMP (atoi (prio), G_MININT8, G_MAXINT8);

  presence_cache_check_for_decloak_request (cache, message, handle, from);

  wocky_stanza_get_type_info (message, NULL, &sub_type);
  switch (sub_type)
    {
    case WOCKY_STANZA_SUB_TYPE_NONE:
    case WOCKY_STANZA_SUB_TYPE_AVAILABLE:
      presence_id = _presence_node_get_status (presence_node);
      gabble_presence_cache_update (cache, handle, resource, presence_id,
          status_message, priority);

      if (!presence)
          presence = gabble_presence_cache_get (cache, handle);

      _grab_nickname (cache, handle, from, presence_node);
      _grab_avatar_sha1 (cache, handle, from, presence_node);
      _process_caps (cache, presence, handle, from, presence_node);

      return TRUE;

    case WOCKY_STANZA_SUB_TYPE_ERROR:
    {
      GError *error = NULL;
      gboolean ret;

      NODE_DEBUG (presence_node, "Received error presence");

      ret = wocky_stanza_extract_errors (message, NULL, &error, NULL, NULL);
      g_assert (ret);

      /* If there's a <status/> in this presence, it's our own echoed back at
       * us. So we don't want to use that. Instead, we use the <error><text> if
       * there is any, or the name of the error condition if not. */
      if (tp_str_empty (error->message))
        status_message = wocky_enum_to_nick (WOCKY_TYPE_XMPP_ERROR,
            error->code);
      else
        status_message = error->message;

      gabble_presence_cache_update (cache, handle, resource,
          GABBLE_PRESENCE_ERROR, status_message, priority);

      return TRUE;
    }

    case WOCKY_STANZA_SUB_TYPE_UNAVAILABLE:
      if (gabble_roster_handle_sends_presence_to_us (priv->conn->roster,
            handle))
        presence_id = GABBLE_PRESENCE_OFFLINE;
      else
        presence_id = GABBLE_PRESENCE_UNKNOWN;

      gabble_presence_cache_update (cache, handle, resource,
          presence_id, status_message, priority);

      return TRUE;

    default:
      return FALSE;
    }
}

/* FIXME: this scrapes nicknames out of <messages>, and relies on im-channel.c
 * setting keep_unavailable back to FALSE to make nicknames random peers send
 * us disappear once we close the accompanying messages. As a side effect, it
 * makes specifying <nick> in MUC messages work, which is questionable
 * behaviour. See vcard/test-alias-message.py.
 *
 * It would be cleaner to make the IM channel stash the nickname if we want it
 * to go away when the channel closes, rather than relying on this
 * spooky-action-at-a-distance.
 */
static gboolean
_parse_message_message (
    WockyPorter *porter,
    WockyStanza *message,
    gpointer user_data)
{
  GabblePresenceCache *cache = GABBLE_PRESENCE_CACHE (user_data);
  GabblePresenceCachePrivate *priv = cache->priv;
  TpHandleRepoIface *contact_repo = tp_base_connection_get_handles (
      (TpBaseConnection *) priv->conn, TP_HANDLE_TYPE_CONTACT);
  const gchar *from = wocky_stanza_get_from (message);
  TpHandle handle;
  WockyStanzaSubType sub_type;
  WockyNode *node;
  GabblePresence *presence;

  if (NULL == from)
    {
      STANZA_DEBUG (message, "message without from attribute, ignoring");
      return FALSE;
    }

  handle = tp_handle_ensure (contact_repo, from, NULL, NULL);
  if (0 == handle)
    {
      STANZA_DEBUG (message, "ignoring message from malformed jid");
      return FALSE;
    }

  wocky_stanza_get_type_info (message, NULL, &sub_type);
  switch (sub_type)
    {
    case WOCKY_STANZA_SUB_TYPE_NONE:
    case WOCKY_STANZA_SUB_TYPE_NORMAL:
    case WOCKY_STANZA_SUB_TYPE_CHAT:
    case WOCKY_STANZA_SUB_TYPE_GROUPCHAT:
      break;
    default:
      return FALSE;
    }

  presence = gabble_presence_cache_get (cache, handle);

  if (NULL == presence)
    {
      presence = _cache_insert (cache, handle);
      presence->keep_unavailable = TRUE;
    }

  node = wocky_stanza_get_top_node (message);

  _grab_nickname (cache, handle, from, node);

  return FALSE;
}


/*
 * gabble_presence_cache_presence_cb:
 *
 * Called by Wocky when we get an incoming <presence>.
 */
static gboolean
gabble_presence_cache_presence_cb (
    WockyPorter *porter,
    WockyStanza *message,
    gpointer user_data)
{
  GabblePresenceCache *cache = GABBLE_PRESENCE_CACHE (user_data);
  GabblePresenceCachePrivate *priv = cache->priv;
  TpHandleRepoIface *contact_repo = tp_base_connection_get_handles (
      (TpBaseConnection *) priv->conn, TP_HANDLE_TYPE_CONTACT);
  const char *from = wocky_stanza_get_from (message);
  TpHandle handle;

  if (NULL == from)
    {
      STANZA_DEBUG (message, "message without from attribute, ignoring");
      return FALSE;
    }

  handle = tp_handle_ensure (contact_repo, from, NULL, NULL);
  if (0 == handle)
    {
      STANZA_DEBUG (message, "ignoring message from malformed jid");
      return FALSE;
    }

  return gabble_presence_parse_presence_message (cache, handle, from, message);
}


GabblePresenceCache *
gabble_presence_cache_new (GabbleConnection *conn)
{
  return g_object_new (GABBLE_TYPE_PRESENCE_CACHE,
                       "connection", conn,
                       NULL);
}

GabblePresence *
gabble_presence_cache_get (GabblePresenceCache *cache, TpHandle handle)
{
  GabblePresenceCachePrivate *priv = cache->priv;
  TpHandleRepoIface *contact_repo = tp_base_connection_get_handles (
      (TpBaseConnection *) priv->conn, TP_HANDLE_TYPE_CONTACT);

  g_assert (tp_handle_is_valid (contact_repo, handle, NULL));

  return g_hash_table_lookup (priv->presence, GUINT_TO_POINTER (handle));
}

void
gabble_presence_cache_maybe_remove (
    GabblePresenceCache *cache,
    TpHandle handle)
{
  GabblePresenceCachePrivate *priv = cache->priv;
  TpHandleRepoIface *contact_repo = tp_base_connection_get_handles (
      (TpBaseConnection *) priv->conn, TP_HANDLE_TYPE_CONTACT);
  GabblePresence *presence;

  presence = gabble_presence_cache_get (cache, handle);

  if (NULL == presence)
    return;

  if ((presence->status == GABBLE_PRESENCE_OFFLINE ||
       presence->status == GABBLE_PRESENCE_UNKNOWN) &&
      presence->status_message == NULL &&
      !presence->keep_unavailable)
    {
      const gchar *jid;

      jid = tp_handle_inspect (contact_repo, handle);
      DEBUG ("discarding cached presence for unavailable jid %s", jid);
      g_hash_table_remove (priv->presence, GUINT_TO_POINTER (handle));
      tp_handle_set_remove (priv->presence_handles, handle);
    }
}

static GabblePresence *
_cache_insert (
    GabblePresenceCache *cache,
    TpHandle handle)
{
  GabblePresenceCachePrivate *priv = cache->priv;
  GabblePresence *presence;

  presence = gabble_presence_new ();
  g_hash_table_insert (priv->presence, GUINT_TO_POINTER (handle), presence);
  tp_handle_set_add (priv->presence_handles, handle);
  return presence;
}

static gboolean
gabble_presence_cache_do_update (
    GabblePresenceCache *cache,
    TpHandle handle,
    const gchar *resource,
    GabblePresenceId presence_id,
    const gchar *status_message,
    gint8 priority,
    gboolean *update_client_types)
{
  GabblePresenceCachePrivate *priv = cache->priv;
  GabblePresence *presence;
  GabbleCapabilitySet *old_cap_set;
  const GabbleCapabilitySet *new_cap_set;
  gboolean ret = FALSE;

  if (DEBUGGING)
    {
      TpHandleRepoIface *contact_repo = tp_base_connection_get_handles (
          (TpBaseConnection *) priv->conn, TP_HANDLE_TYPE_CONTACT);
      const gchar *jid = tp_handle_inspect (contact_repo, handle);
      const gchar *presence_name = wocky_enum_to_nick (
          GABBLE_TYPE_PRESENCE_ID, presence_id);

      if (presence_name == NULL)
        presence_name = "plugin-specific, not an element of GabblePresenceId";

      DEBUG ("%s (%d) resource %s prio %d presence %d (%s) message \"%s\"",
          jid, handle,
          resource == NULL ? "<null>" : resource,
          priority, presence_id, presence_name,
          status_message == NULL ? "<null>" : status_message);
    }

  presence = gabble_presence_cache_get (cache, handle);

  if (presence == NULL)
    presence = _cache_insert (cache, handle);

  old_cap_set = gabble_presence_dup_caps (presence);

  ret = gabble_presence_update (presence, resource, presence_id,
      status_message, priority, update_client_types,
      time (NULL));

  new_cap_set = gabble_presence_peek_caps (presence);

  emit_capabilities_update (cache, handle, old_cap_set, new_cap_set);

  gabble_capability_set_free (old_cap_set);

  return ret;
}

void
gabble_presence_cache_update (
    GabblePresenceCache *cache,
    TpHandle handle,
    const gchar *resource,
    GabblePresenceId presence_id,
    const gchar *status_message,
    gint8 priority)
{
  gboolean update_client_types = FALSE;

  if (gabble_presence_cache_do_update (cache, handle, resource, presence_id,
          status_message, priority, &update_client_types))
    {
      _signal_presences_updated (cache, handle);
    }

  if (update_client_types)
    g_signal_emit (cache, signals[CLIENT_TYPES_UPDATED], 0, handle);

  gabble_presence_cache_maybe_remove (cache, handle);
}

void
gabble_presence_cache_update_many (
    GabblePresenceCache *cache,
    const GArray *contact_handles,
    const gchar *resource,
    GabblePresenceId presence_id,
    const gchar *status_message,
    gint8 priority)
{
  GArray *updated;
  guint i;

  updated = g_array_sized_new (FALSE, FALSE, sizeof (TpHandle),
      contact_handles->len);

  for (i = 0 ; i < contact_handles->len ; i++)
    {
      TpHandle handle;

      handle = g_array_index (contact_handles, TpHandle, i);

      if (gabble_presence_cache_do_update (cache, handle, resource,
          presence_id, status_message, priority, NULL))
        {
          g_array_append_val (updated, handle);
        }
    }

  if (updated->len > 0)
    g_signal_emit (cache, signals[PRESENCES_UPDATED], 0, updated);

  g_array_unref (updated);

  for (i = 0 ; i < contact_handles->len ; i++)
    {
      TpHandle handle;

      handle = g_array_index (contact_handles, TpHandle, i);
      gabble_presence_cache_maybe_remove (cache, handle);
    }

}

static void
gabble_presence_cache_add_bundle_caps (GabblePresenceCache *cache,
    const gchar *node,
    const gchar *namespace)
{
  GabbleCapabilityInfo *info;

  info = capability_info_get (cache, node);

  /* The caps are immediately valid, because we already know this bundle */
  if (info->cap_set == NULL)
    info->cap_set = gabble_capability_set_new ();

  info->trust = CAPABILITY_BUNDLE_ENOUGH_TRUST;

  if (namespace != NULL)
    gabble_capability_set_add (info->cap_set, namespace);
}

void
gabble_presence_cache_add_own_caps (
    GabblePresenceCache *cache,
    const gchar *ver,
    const GabbleCapabilitySet *cap_set,
    const GPtrArray *identities,
    GPtrArray *data_forms)
{
  gchar *uri = g_strdup_printf ("%s#%s", NS_GABBLE_CAPS, ver);
  GabbleCapabilityInfo *info = capability_info_get (cache, uri);

  if (info->complete)
    goto out;

  DEBUG ("caching our own caps (%s)", uri);

  /* If this node was already in the cache but not labelled as complete, either
   * the entry's correct, or someone's poisoning us with a SHA-1 collision.
   * Let's update the entry just in case.
   */
  if (info->cap_set == NULL)
    {
      info->cap_set = gabble_capability_set_copy (cap_set);
    }
  else
    {
      gabble_capability_set_clear (info->cap_set);
      gabble_capability_set_update (info->cap_set, cap_set);
    }

  wocky_disco_identity_array_free (info->identities);

  info->identities = NULL;

  if (identities != NULL)
    info->identities = wocky_disco_identity_array_copy (identities);

  info->complete = TRUE;
  info->trust = CAPABILITY_BUNDLE_ENOUGH_TRUST;
  tp_intset_add (info->guys, cache->priv->conn->parent.self_handle);

  replace_data_forms (info, data_forms);

  /* FIXME: we should satisfy any waiters for this node now. fd.o bug #24619. */

out:
  g_free (uri);
}

/**
 * gabble_presence_cache_peek_own_caps:
 * @cache: a presence cache
 * @ver: a verification string or bundle name
 *
 * If the capabilities corresponding to @ver have been added to the cache with
 * gabble_presence_cache_add_own_caps(), returns a set of those capabilities;
 * otherwise, returns %NULL.
 *
 * Since the cache only records features Gabble understands (omitting unknown
 * features, identities, and data forms), we can only serve up disco replies
 * from the cache if we know we once advertised exactly this verification
 * string ourselves.
 *
 * Returns: a set of capabilities, if we know exactly what @ver means.
 */
const GabbleCapabilityInfo *
gabble_presence_cache_peek_own_caps (
    GabblePresenceCache *cache,
    const gchar *ver)
{
  gchar *uri = g_strdup_printf ("%s#%s", NS_GABBLE_CAPS, ver);
  GabbleCapabilityInfo *info = capability_info_get (cache, uri);

  g_free (uri);

  if (info->complete)
    {
      g_assert (info->cap_set != NULL);
      return info;
    }
  else
    {
      return NULL;
    }
}

void
gabble_presence_cache_really_remove (
    GabblePresenceCache *cache,
    TpHandle handle)
{
  GabblePresenceCachePrivate *priv = cache->priv;
  TpHandleRepoIface *contact_repo = tp_base_connection_get_handles (
      (TpBaseConnection *) priv->conn, TP_HANDLE_TYPE_CONTACT);
  const gchar *jid;

  jid = tp_handle_inspect (contact_repo, handle);
  DEBUG ("forced to discard cached presence for jid %s", jid);
  g_hash_table_remove (priv->presence, GUINT_TO_POINTER (handle));
  tp_handle_set_remove (priv->presence_handles, handle);
}

void
gabble_presence_cache_contacts_added_to_olpc_view (GabblePresenceCache *self,
                                                   TpHandleSet *handles)
{
  GArray *tmp, *changed;
  guint i;

  tmp = tp_handle_set_to_array (handles);

  changed = g_array_new (FALSE, FALSE, sizeof (TpHandle));

  for (i = 0; i < tmp->len; i++)
    {
      TpHandle handle;
      GabblePresence *presence;

      handle = g_array_index (tmp, TpHandle, i);

      presence = gabble_presence_cache_get (self, handle);
      if (presence == NULL)
        {
          presence = _cache_insert (self, handle);
        }

      if (gabble_presence_added_to_view (presence))
        {
          g_array_append_val (changed, handle);
        }
    }

  if (changed->len > 0)
    {
      g_signal_emit (self, signals[PRESENCES_UPDATED], 0, changed);
    }

  g_array_unref (tmp);
  g_array_unref (changed);
}

void
gabble_presence_cache_contacts_removed_from_olpc_view (
    GabblePresenceCache *self,
    TpHandleSet *handles)
{
  GArray *tmp, *changed;
  guint i;

  tmp = tp_handle_set_to_array (handles);

  changed = g_array_new (FALSE, FALSE, sizeof (TpHandle));

  for (i = 0; i < tmp->len; i++)
    {
      TpHandle handle;
      GabblePresence *presence;

      handle = g_array_index (tmp, TpHandle, i);

      presence = gabble_presence_cache_get (self, handle);
      if (presence == NULL)
        {
          presence = _cache_insert (self, handle);
        }

      if (gabble_presence_removed_from_view (presence))
        {
          g_array_append_val (changed, handle);
          gabble_presence_cache_maybe_remove (self, handle);
        }
    }

  if (changed->len > 0)
    {
      g_signal_emit (self, signals[PRESENCES_UPDATED], 0, changed);
    }

  g_array_unref (tmp);
  g_array_unref (changed);
}

static gboolean
gabble_presence_cache_caps_pending (GabblePresenceCache *cache,
                                    TpHandle handle)
{
  GabblePresenceCachePrivate *priv = cache->priv;
  GList *uris, *li;

  uris = g_hash_table_get_values (priv->disco_pending);

  for (li = uris; li != NULL; li = li->next)
    {
      GSList *waiters;

      for (waiters = li->data; waiters != NULL; waiters = waiters->next)
        {
          DiscoWaiter *w = waiters->data;
          if (w->handle == handle)
            {
              g_list_free (uris);
              return TRUE;
            }

        }
    }

  g_list_free (uris);
  return FALSE;
}

/* Return whether we're "unsure" about the capabilities of @handle.
 * Currently, this means either of:
 *
 * - we've connected within the last UNSURE_PERIOD seconds and haven't
 *   received presence for @handle yet
 * - we know what @handle's caps hash/bundles are, but we're still
 *   performing service discovery to find out what they mean
 */
gboolean
gabble_presence_cache_is_unsure (GabblePresenceCache *cache,
    TpHandle handle)
{
  GabblePresenceCachePrivate *priv = cache->priv;
  TpBaseConnection *base_conn = TP_BASE_CONNECTION (priv->conn);

  /* we might not have had any presence at all - if we're not connected yet, or
   * are still in the "unsure period", assume we might get initial presence
   * soon.
   *
   * Presences with keep_unavailable are the result of caching someone's
   * nick from <message> stanzas, so they don't count as real presence - if
   * someone sends us a <message>, their presence might still follow. */
  if (base_conn->status != TP_CONNECTION_STATUS_CONNECTED ||
      priv->unsure_id != 0)
    {
      GabblePresence *presence = gabble_presence_cache_get (cache, handle);

      if (presence == NULL || presence->keep_unavailable)
        {
          DEBUG ("No presence for %u yet, still waiting for possible initial "
              "presence burst", handle);
          return TRUE;
        }
    }

  /* FIXME: if we've had the roster, we can be sure that people who're
   * not in it won't be sending us an initial presence, so ideally the
   * above should be roster-aware? */

  /* if we don't know what the caps mean, we're unsure */
  if (gabble_presence_cache_caps_pending (cache, handle))
    {
      DEBUG ("Still working out what %u's caps hash means", handle);
      return TRUE;
    }

  /* if we're waiting for a de-cloak response, we're unsure */
  if (tp_handle_set_is_member (priv->decloak_handles, handle))
    {
      DEBUG ("Waiting to see if %u will decloak", handle);
      return TRUE;
    }

  DEBUG ("No, I'm sure about %u by now", handle);
  return FALSE;
}

static gboolean
gabble_presence_cache_decloak_timeout_cb (gpointer data)
{
  DecloakContext *dc = data;
  GabblePresenceCache *self = dc->cache;
  TpHandle handle = dc->handle;

  DEBUG ("De-cloak request for %u timed out", handle);

  /* This frees @dc, do not dereference it afterwards. This needs to be done
   * before emitting the signal, so that when recipients of the channel ask
   * whether we're unsure about the handle, there is no pending decloak
   * request that would make us unsure. */
  g_hash_table_remove (self->priv->decloak_requests,
      GUINT_TO_POINTER (handle));
  /* As a side-effect of freeing @dc, this should have happened. */
  g_assert (!tp_handle_set_is_member (self->priv->decloak_handles, handle));

  /* FIXME: this is an abuse of this signal, but it serves the same
   * purpose: poking any pending media channels to tell them that @handle
   * might have left the "unsure" state */
  emit_capabilities_discovered (self, handle);

  return FALSE;
}

/* @reason must be a statically-allocated string. */
gboolean
gabble_presence_cache_request_decloaking (GabblePresenceCache *self,
    TpHandle handle,
    const gchar *reason)
{
  DecloakContext *dc;
  GabblePresence *presence;
  TpHandleRepoIface *contact_repo = tp_base_connection_get_handles (
      (TpBaseConnection *) self->priv->conn, TP_HANDLE_TYPE_CONTACT);

  presence = gabble_presence_cache_get (self, handle);

  if (presence != NULL &&
      presence->status != GABBLE_PRESENCE_OFFLINE &&
      presence->status != GABBLE_PRESENCE_UNKNOWN)
    {
      DEBUG ("We know that this contact is online, no point asking for "
          "decloak");
      return FALSE;
    }

  /* if we've already asked them to de-cloak for the same reason, do nothing */
  if (tp_handle_set_is_member (self->priv->decloak_handles, handle))
    {
      dc = g_hash_table_lookup (self->priv->decloak_requests,
          GUINT_TO_POINTER (handle));

      if (dc != NULL && !tp_strdiff (reason, dc->reason))
        {
          DEBUG ("Already asked %u to decloak for reason '%s'", handle,
              reason);
          return TRUE;
        }
    }

  DEBUG ("Asking %u to decloak", handle);

  dc = decloak_context_new (self, handle, reason);
  dc->timeout_id = g_timeout_add_seconds (DECLOAK_PERIOD,
      gabble_presence_cache_decloak_timeout_cb, dc);
  g_hash_table_insert (self->priv->decloak_requests, GUINT_TO_POINTER (handle),
      dc);
  tp_handle_set_add (self->priv->decloak_handles, handle);

  gabble_connection_request_decloak (self->priv->conn,
      tp_handle_inspect (contact_repo, handle), reason, NULL);

  return TRUE;
}

void
gabble_presence_cache_update_location (GabblePresenceCache *cache,
                                       TpHandle handle,
                                       GHashTable *new_location)
{
  GabblePresenceCachePrivate *priv = cache->priv;

  g_hash_table_insert (priv->location, GUINT_TO_POINTER (handle), new_location);

  g_signal_emit (cache, signals[LOCATION_UPDATED], 0, handle);
}

/* The return value should be g_hash_table_unref'ed. */
GHashTable *
gabble_presence_cache_get_location (GabblePresenceCache *cache,
                                    TpHandle handle)
{
  GabblePresenceCachePrivate *priv = cache->priv;
  GHashTable *location = NULL;

  location = g_hash_table_lookup (priv->location, GUINT_TO_POINTER (handle));
  if (location != NULL)
    {
      g_hash_table_ref (location);
      return location;
    }

  return NULL;
}

gboolean
gabble_presence_cache_disco_in_progress (GabblePresenceCache *cache,
    TpHandle handle,
    const gchar *resource)
{
  GabblePresenceCachePrivate *priv = cache->priv;
  GList *l, *waiter_list;
  gboolean in_progress = FALSE;

  waiter_list = g_hash_table_get_values (priv->disco_pending);

  for (l = waiter_list; !in_progress && l != NULL; l = l->next)
    {
      GList *j;

      for (j = l->data; !in_progress && j != NULL; j = j->next)
        {
          DiscoWaiter *w = j->data;

          if (w != NULL &&
              w->handle == handle &&
              !tp_strdiff (w->resource, resource))
            in_progress = TRUE;
        }
    }

  g_list_free (waiter_list);

  return in_progress;
}

TpHandle
gabble_presence_cache_get_handle (GabblePresenceCache *cache,
    GabblePresence *presence)
{
  GHashTableIter iter;
  gpointer key, val;

  g_hash_table_iter_init (&iter, cache->priv->presence);
  while (g_hash_table_iter_next (&iter, &key, &val))
    {
      if (presence == val)
        return GPOINTER_TO_UINT (key);
    }

  return 0;
}