summaryrefslogtreecommitdiff
path: root/src/mcd-storage.c
blob: 68ccd431b96804eae9032b4db050e37df174389c (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
/* Representation of the account manager as presented to plugins. This is
 * deliberately a "smaller" API than McdAccountManager.
 *
 * Copyright © 2010 Nokia Corporation
 * Copyright © 2010-2012 Collabora Ltd.
 *
 * 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 "mcd-storage.h"

#include "mcd-account.h"
#include "mcd-account-config.h"
#include "mcd-debug.h"
#include "mcd-misc.h"
#include "plugin-loader.h"

#include <errno.h>
#include <string.h>

#include <dbus/dbus.h>
#include <telepathy-glib/telepathy-glib.h>
#include <telepathy-glib/telepathy-glib-dbus.h>

#include "mission-control-plugins/implementation.h"

/* these pseudo-plugins take care of the actual account storage/retrieval */
#include "mcd-account-manager-default.h"

#define MAX_KEY_LENGTH (DBUS_MAXIMUM_NAME_LENGTH + 6)

static GList *stores = NULL;
static void sort_and_cache_plugins (void);

enum {
  PROP_DBUS_DAEMON = 1,
};

struct _McdStorageClass {
    GObjectClass parent;
};

static void plugin_iface_init (McpAccountManagerIface *iface,
    gpointer unused G_GNUC_UNUSED);

G_DEFINE_TYPE_WITH_CODE (McdStorage, mcd_storage,
    G_TYPE_OBJECT,
    G_IMPLEMENT_INTERFACE (MCP_TYPE_ACCOUNT_MANAGER, plugin_iface_init))

static void
mcd_storage_init (McdStorage *self)
{
  self->accounts = g_hash_table_new_full (g_str_hash, g_str_equal,
      g_free, g_object_unref);
}

static void
storage_finalize (GObject *object)
{
  McdStorage *self = MCD_STORAGE (object);
  GObjectFinalizeFunc finalize =
    G_OBJECT_CLASS (mcd_storage_parent_class)->finalize;

  g_hash_table_unref (self->accounts);
  self->accounts = NULL;

  if (finalize != NULL)
    finalize (object);
}

static void
storage_dispose (GObject *object)
{
  McdStorage *self = MCD_STORAGE (object);
  GObjectFinalizeFunc dispose =
    G_OBJECT_CLASS (mcd_storage_parent_class)->dispose;

  tp_clear_object (&self->dbusd);

  if (dispose != NULL)
    dispose (object);
}

static void
storage_set_property (GObject *obj, guint prop_id,
	      const GValue *val, GParamSpec *pspec)
{
    McdStorage *self = MCD_STORAGE (obj);

    switch (prop_id)
    {
      case PROP_DBUS_DAEMON:
        tp_clear_object (&self->dbusd);
        self->dbusd = TP_DBUS_DAEMON (g_value_dup_object (val));
        break;

      default:
        G_OBJECT_WARN_INVALID_PROPERTY_ID (obj, prop_id, pspec);
        break;
    }
}

static void
storage_get_property (GObject *obj, guint prop_id,
	      GValue *val, GParamSpec *pspec)
{
    McdStorage *self = MCD_STORAGE (obj);

    switch (prop_id)
    {
      case PROP_DBUS_DAEMON:
        g_value_set_object (val, self->dbusd);
        break;
      default:
        G_OBJECT_WARN_INVALID_PROPERTY_ID (obj, prop_id, pspec);
        break;
    }
}

static void
mcd_storage_class_init (McdStorageClass *cls)
{
  GObjectClass *object_class = (GObjectClass *) cls;
  GParamSpec *spec = g_param_spec_object ("dbus-daemon",
      "DBus daemon",
      "DBus daemon",
      TP_TYPE_DBUS_DAEMON,
      G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);

  object_class->set_property = storage_set_property;
  object_class->get_property = storage_get_property;
  object_class->dispose = storage_dispose;
  object_class->finalize = storage_finalize;

  g_object_class_install_property (object_class, PROP_DBUS_DAEMON, spec);
}

McdStorage *
mcd_storage_new (TpDBusDaemon *dbus_daemon)
{
  return g_object_new (MCD_TYPE_STORAGE,
      "dbus-daemon", dbus_daemon,
      NULL);
}

static gchar *
mcd_keyfile_escape_variant (GVariant *variant)
{
  GKeyFile *keyfile;
  gchar *ret;

  g_return_val_if_fail (variant != NULL, NULL);

  keyfile = g_key_file_new ();
  mcd_keyfile_set_variant (keyfile, "g", "k", variant);
  ret = g_key_file_get_value (keyfile, "g", "k", NULL);
  g_key_file_free (keyfile);
  return ret;
}

static struct {
    const gchar *type;
    const gchar *name;
} known_attributes[] = {
    /* Please keep this sorted by type, then by name. */

    /* Structs */
      { "(uss)", MC_ACCOUNTS_KEY_AUTOMATIC_PRESENCE },

    /* Array of object path */
      { "ao", MC_ACCOUNTS_KEY_SUPERSEDES },

    /* Array of string */
      { "as", MC_ACCOUNTS_KEY_URI_SCHEMES },

    /* Booleans */
      { "b", MC_ACCOUNTS_KEY_ALWAYS_DISPATCH },
      { "b", MC_ACCOUNTS_KEY_CONNECT_AUTOMATICALLY },
      { "b", MC_ACCOUNTS_KEY_ENABLED },
      { "b", MC_ACCOUNTS_KEY_HAS_BEEN_ONLINE },

    /* Strings */
      { "s", MC_ACCOUNTS_KEY_AUTO_PRESENCE_MESSAGE },
      { "s", MC_ACCOUNTS_KEY_AUTO_PRESENCE_STATUS },
      { "s", MC_ACCOUNTS_KEY_AVATAR_MIME },
      { "s", MC_ACCOUNTS_KEY_AVATAR_TOKEN },
      { "s", MC_ACCOUNTS_KEY_DISPLAY_NAME },
      { "s", MC_ACCOUNTS_KEY_ICON },
      { "s", MC_ACCOUNTS_KEY_MANAGER },
      { "s", MC_ACCOUNTS_KEY_NICKNAME },
      { "s", MC_ACCOUNTS_KEY_NORMALIZED_NAME },
      { "s", MC_ACCOUNTS_KEY_PROTOCOL },
      { "s", MC_ACCOUNTS_KEY_SERVICE },

    /* Integers */
      { "u", MC_ACCOUNTS_KEY_AUTO_PRESENCE_TYPE },

      { NULL, NULL }
};

const GVariantType *
mcd_storage_get_attribute_type (const gchar *attribute)
{
  guint i;

  for (i = 0; known_attributes[i].type != NULL; i++)
    {
      if (!tp_strdiff (attribute, known_attributes[i].name))
        return G_VARIANT_TYPE (known_attributes[i].type);
    }

  return NULL;
}

gboolean
mcd_storage_init_value_for_attribute (GValue *value,
    const gchar *attribute,
    const GVariantType **variant_type)
{
  const GVariantType *s = mcd_storage_get_attribute_type (attribute);

  if (s == NULL)
    return FALSE;

  if (variant_type != NULL)
    *variant_type = s;

  switch (g_variant_type_peek_string (s)[0])
    {
      case 's':
        g_value_init (value, G_TYPE_STRING);
        return TRUE;

      case 'b':
        g_value_init (value, G_TYPE_BOOLEAN);
        return TRUE;

      case 'u':
        /* this seems wrong but it's how we've always done it */
        g_value_init (value, G_TYPE_INT);
        return TRUE;

      case 'a':
          {
            switch (g_variant_type_peek_string (s)[1])
              {
                case 'o':
                  g_value_init (value, TP_ARRAY_TYPE_OBJECT_PATH_LIST);
                  return TRUE;

                case 's':
                  g_value_init (value, G_TYPE_STRV);
                  return TRUE;
              }
          }
        break;

      case '(':
          {
            if (g_variant_type_equal (s, G_VARIANT_TYPE ("(uss)")))
              {
                g_value_init (value, TP_STRUCT_TYPE_SIMPLE_PRESENCE);
                return TRUE;
              }
          }
        break;
    }

  return FALSE;
}

static gchar *
unique_name (const McpAccountManager *ma,
    const gchar *manager,
    const gchar *protocol,
    const gchar *identification)
{
  McdStorage *self = MCD_STORAGE (ma);
  gchar *esc_manager, *esc_protocol, *esc_base;
  guint i;
  gsize base_len = strlen (TP_ACCOUNT_OBJECT_PATH_BASE);
  DBusGConnection *connection = tp_proxy_get_dbus_connection (self->dbusd);

  esc_manager = tp_escape_as_identifier (manager);
  esc_protocol = g_strdelimit (g_strdup (protocol), "-", '_');
  esc_base = tp_escape_as_identifier (identification);

  for (i = 0; i < G_MAXUINT; i++)
    {
      gchar *path = g_strdup_printf (
          TP_ACCOUNT_OBJECT_PATH_BASE "%s/%s/%s%u",
          esc_manager, esc_protocol, esc_base, i);

      if (!g_hash_table_contains (self->accounts, path + base_len) &&
          dbus_g_connection_lookup_g_object (connection, path) == NULL)
        {
          gchar *ret = g_strdup (path + base_len);

          g_free (path);
          return ret;
        }

      g_free (path);
    }

  return NULL;
}

static void
identify_account_cb (TpProxy *proxy,
    const gchar *identification,
    const GError *error,
    gpointer task,
    GObject *weak_object G_GNUC_UNUSED)
{
  if (error == NULL)
    {
      DEBUG ("identified account: %s", identification);
      g_task_return_pointer (task, g_strdup (identification), g_free);
    }
  else if (g_error_matches (error, TP_ERROR, TP_ERROR_INVALID_HANDLE) ||
      g_error_matches (error, TP_ERROR, TP_ERROR_INVALID_ARGUMENT))
    {
      /* The connection manager didn't like our account parameters.
       * Give up now. */
      DEBUG ("failed to identify account: %s #%d: %s",
          g_quark_to_string (error->domain), error->code, error->message);
      g_task_return_error (task, g_error_copy (error));
    }
  else
    {
      /* We weren't able to identify the account, but carry on and hope
       * for the best... */
      DEBUG ("ignoring failure to identify account: %s #%d: %s",
          g_quark_to_string (error->domain), error->code, error->message);
      g_task_return_pointer (task, g_strdup (g_task_get_task_data (task)),
          g_free);
    }
}

static gchar *
identify_account_finish (McpAccountManager *mcpa,
    GAsyncResult *result,
    GError **error)
{
  g_return_val_if_fail (g_task_is_valid (result, mcpa), NULL);

  return g_task_propagate_pointer (G_TASK (result), error);
}

static void
identify_account_async (McpAccountManager *mcpa,
    const gchar *manager,
    const gchar *protocol_name,
    GVariant *parameters,
    GCancellable *cancellable,
    GAsyncReadyCallback callback,
    gpointer user_data)
{
  McdStorage *self = MCD_STORAGE (mcpa);
  GError *error = NULL;
  TpProtocol *protocol;
  GTask *task;
  GValue value = G_VALUE_INIT;
  const gchar *base;

  task = g_task_new (self, cancellable, callback, user_data);

  /* in case IdentifyAccount fails and we need to make something up */
  if (!g_variant_lookup (parameters, "account", "&s", &base))
    base = "account";

  g_task_set_task_data (task, g_strdup (base), g_free);

  protocol = tp_protocol_new (self->dbusd, manager, protocol_name,
      NULL, &error);

  if (protocol == NULL)
    {
      g_task_return_error (task, error);
      g_object_unref (task);
      return;
    }

  dbus_g_value_parse_g_variant (parameters, &value);

  tp_cli_protocol_call_identify_account (protocol, -1,
      g_value_get_boxed (&value), identify_account_cb, task, g_object_unref,
      NULL);
  g_object_unref (protocol);
  g_value_unset (&value);
}

/* sort in descending order of priority (ie higher prio => earlier in list) */
static gint
account_storage_cmp (gconstpointer a, gconstpointer b)
{
    gint pa = mcp_account_storage_priority ((McpAccountStorage *) a);
    gint pb = mcp_account_storage_priority ((McpAccountStorage *) b);

    if (pa > pb) return -1;
    if (pa < pb) return 1;

    return 0;
}

static void
add_storage_plugin (McpAccountStorage *plugin)
{
  stores = g_list_insert_sorted (stores, plugin, account_storage_cmp);
}

static void
sort_and_cache_plugins ()
{
  const GList *p;
  static gboolean plugins_cached = FALSE;

  if (plugins_cached)
    return;

  /* not guaranteed to have been called, but idempotent: */
  _mcd_plugin_loader_init ();

  /* Add compiled-in plugins */
  add_storage_plugin (MCP_ACCOUNT_STORAGE (mcd_account_manager_default_new ()));

  for (p = mcp_list_objects(); p != NULL; p = g_list_next (p))
    {
      if (MCP_IS_ACCOUNT_STORAGE (p->data))
        {
          McpAccountStorage *plugin = g_object_ref (p->data);

          add_storage_plugin (plugin);
        }
    }

  for (p = stores; p != NULL; p = g_list_next (p))
    {
      McpAccountStorage *plugin = p->data;

      DEBUG ("found plugin %s [%s; priority %d]\n%s",
          mcp_account_storage_name (plugin),
          g_type_name (G_TYPE_FROM_INSTANCE (plugin)),
          mcp_account_storage_priority (plugin),
          mcp_account_storage_description (plugin));
    }

    plugins_cached = TRUE;
}

void
mcd_storage_connect_signal (const gchar *signame,
    GCallback func,
    gpointer user_data)
{
  GList *p;

  for (p = stores; p != NULL; p = g_list_next (p))
    {
      McpAccountStorage *plugin = p->data;

      DEBUG ("connecting handler to %s plugin signal %s ",
          mcp_account_storage_name (plugin), signame);
      g_signal_connect (plugin, signame, func, user_data);
    }
}

/*
 * mcd_storage_load:
 * @storage: An object implementing the #McdStorage interface
 *
 * Load the long term account settings storage into our internal cache.
 * Should only really be called during startup, ie before our DBus names
 * have been claimed and other people might be relying on responses from us.
 */
void
mcd_storage_load (McdStorage *self)
{
  McpAccountManager *ma = MCP_ACCOUNT_MANAGER (self);
  GList *store = NULL;

  g_return_if_fail (MCD_IS_STORAGE (self));

  sort_and_cache_plugins ();

  /* fetch accounts stored in plugins, highest priority first, so that
   * low priority plugins can be overidden by high priority */
  for (store = stores; store != NULL; store = store->next)
    {
      GList *account;
      McpAccountStorage *plugin = store->data;
      GList *stored = mcp_account_storage_list (plugin, ma);
      const gchar *pname = mcp_account_storage_name (plugin);
      const gint prio = mcp_account_storage_priority (plugin);

      DEBUG ("listing from plugin %s [prio: %d]", pname, prio);
      for (account = stored; account != NULL; account = g_list_next (account))
        {
          GError *error = NULL;
          gchar *name = account->data;

          DEBUG ("fetching %s from plugin %s [prio: %d]", name, pname, prio);

          if (!mcd_storage_add_account_from_plugin (self, plugin, name,
                &error))
            {
              DEBUG ("%s", error->message);
              g_clear_error (&error);
            }

          g_free (name);
        }

      /* already freed the contents, just need to free the list itself */
      g_list_free (stored);
    }
}

/*
 * mcd_storage_get_accounts:
 * @storage: An object implementing the #McdStorage interface
 * @n: place for the number of accounts to be written to (or %NULL)
 *
 * Returns: (transfer none) (element-type utf8 Mcp.AccountStorage): a
 *  map from account object path tail to plugin
 */
GHashTable *
mcd_storage_get_accounts (McdStorage *self)
{
  return self->accounts;
}

/*
 * mcd_storage_get_plugin:
 * @storage: An object implementing the #McdStorage interface
 * @account: unique name of the account
 *
 * Returns: the #McpAccountStorage object which is handling the account,
 * if any (if a new account has not yet been flushed to storage this can
 * be %NULL).
 *
 * Plugins are kept in permanent storage and can never be unloaded, so
 * the returned pointer need not be reffed or unreffed. (Indeed, it's
 * probably safer not to)
 */
McpAccountStorage *
mcd_storage_get_plugin (McdStorage *self,
    const gchar *account)
{
  McpAccountStorage *plugin;

  g_return_val_if_fail (MCD_IS_STORAGE (self), NULL);
  g_return_val_if_fail (account != NULL, NULL);

  plugin = g_hash_table_lookup (self->accounts, account);
  g_return_val_if_fail (plugin != NULL, NULL);

  return plugin;
}

/*
 * mcd_storage_dup_string:
 * @storage: An object implementing the #McdStorage interface
 * @account: unique name of the account
 * @attribute: name of the attribute to be retrieved (which must not be a
 *  parameter)
 *
 * Returns: a newly allocated gchar * which must be freed with g_free().
 */
gchar *
mcd_storage_dup_string (McdStorage *self,
    const gchar *account,
    const gchar *attribute)
{
  GValue tmp = G_VALUE_INIT;
  gchar *ret;

  g_return_val_if_fail (MCD_IS_STORAGE (self), NULL);
  g_return_val_if_fail (account != NULL, NULL);
  g_return_val_if_fail (attribute != NULL, NULL);
  g_return_val_if_fail (!g_str_has_prefix (attribute, "param-"), NULL);

  g_value_init (&tmp, G_TYPE_STRING);

  if (!mcd_storage_get_attribute (self, account, attribute,
        G_VARIANT_TYPE_STRING, &tmp, NULL))
    return NULL;

  ret = g_value_dup_string (&tmp);
  g_value_unset (&tmp);
  return ret;
}

static gboolean
mcd_storage_coerce_variant_to_value (GVariant *variant,
    GValue *value,
    GError **error)
{
  GValue tmp = G_VALUE_INIT;
  gboolean ret;
  gchar *escaped;

  dbus_g_value_parse_g_variant (variant, &tmp);

  if (G_VALUE_TYPE (&tmp) == G_VALUE_TYPE (value))
    {
      memcpy (value, &tmp, sizeof (tmp));
      return TRUE;
    }

  /* This is really pretty stupid but it'll do for now.
   * FIXME: implement a better similar-type-coercion mechanism than
   * round-tripping through a GKeyFile. */
  g_value_unset (&tmp);
  escaped = mcd_keyfile_escape_variant (variant);
  ret = mcd_keyfile_unescape_value (escaped, value, error);
  g_free (escaped);
  return ret;
}

/*
 * mcd_storage_get_attribute:
 * @storage: An object implementing the #McdStorage interface
 * @account: unique name of the account
 * @attribute: name of the attribute to be retrieved, e.g. 'DisplayName'
 * @value: location to return the value, initialized to the right #GType
 * @error: a place to store any #GError<!-- -->s that occur
 */
gboolean
mcd_storage_get_attribute (McdStorage *self,
    const gchar *account,
    const gchar *attribute,
    const GVariantType *type,
    GValue *value,
    GError **error)
{
  McpAccountManager *ma = MCP_ACCOUNT_MANAGER (self);
  McpAccountStorage *plugin;
  GVariant *variant;
  gboolean ret;

  g_return_val_if_fail (MCD_IS_STORAGE (self), FALSE);
  g_return_val_if_fail (account != NULL, FALSE);
  g_return_val_if_fail (attribute != NULL, FALSE);
  g_return_val_if_fail (!g_str_has_prefix (attribute, "param-"), FALSE);

  plugin = g_hash_table_lookup (self->accounts, account);

  if (plugin == NULL)
    {
      g_set_error (error, TP_ERROR, TP_ERROR_NOT_AVAILABLE,
          "Account %s does not exist", account);
      return FALSE;
    }

  variant = mcp_account_storage_get_attribute (plugin, ma, account,
      attribute, type, NULL);

  if (variant == NULL)
    {
      g_set_error (error, TP_ERROR, TP_ERROR_NOT_AVAILABLE,
          "Account %s has no attribute '%s'", account, attribute);
      return FALSE;
    }

  ret = mcd_storage_coerce_variant_to_value (variant, value, error);
  g_variant_unref (variant);
  return ret;
}

/*
 * mcd_storage_get_parameter:
 * @storage: An object implementing the #McdStorage interface
 * @account: unique name of the account
 * @parameter: name of the parameter to be retrieved, e.g. 'account'
 * @value: location to return the value, initialized to the right #GType
 * @error: a place to store any #GError<!-- -->s that occur
 */
gboolean
mcd_storage_get_parameter (McdStorage *self,
    const gchar *account,
    const gchar *parameter,
    const GVariantType *type,
    GValue *value,
    GError **error)
{
  McpAccountManager *ma = MCP_ACCOUNT_MANAGER (self);
  McpAccountStorage *plugin;
  GVariant *variant;
  gboolean ret;

  g_return_val_if_fail (MCD_IS_STORAGE (self), FALSE);
  g_return_val_if_fail (account != NULL, FALSE);
  g_return_val_if_fail (parameter != NULL, FALSE);
  g_return_val_if_fail (!g_str_has_prefix (parameter, "param-"), FALSE);

  plugin = g_hash_table_lookup (self->accounts, account);

  if (plugin == NULL)
    {
      g_set_error (error, TP_ERROR, TP_ERROR_NOT_AVAILABLE,
          "Account %s does not exist", account);
      return FALSE;
    }

  variant = mcp_account_storage_get_parameter (plugin, ma, account,
      parameter, type, NULL);

  if (variant == NULL)
    {
      g_set_error (error, TP_ERROR, TP_ERROR_NOT_AVAILABLE,
          "Account %s has no parameter '%s'", account, parameter);
      return FALSE;
    }

  ret = mcd_storage_coerce_variant_to_value (variant, value, error);
  g_variant_unref (variant);
  return ret;
}

/*
 * @escaped: a keyfile-escaped string
 * @value: a #GValue initialized with a supported #GType
 * @error: used to raise an error if %FALSE is returned
 *
 * Try to interpret @escaped as a value of the type of @value. If we can,
 * write the resulting value into @value and return %TRUE.
 *
 * Returns: %TRUE if @escaped could be interpreted as a value of that type
 */
gboolean
mcd_keyfile_unescape_value (const gchar *escaped,
    GValue *value,
    GError **error)
{
  GKeyFile *keyfile;
  gboolean ret;

  g_return_val_if_fail (escaped != NULL, FALSE);
  g_return_val_if_fail (G_IS_VALUE (value), FALSE);

  keyfile = g_key_file_new ();
  g_key_file_set_value (keyfile, "g", "k", escaped);
  ret = mcd_keyfile_get_value (keyfile, "g", "k", value, error);
  g_key_file_free (keyfile);
  return ret;
}

/*
 * mcd_keyfile_get_value:
 * @keyfile: A #GKeyFile
 * @group: name of a group
 * @key: name of a key
 * @value: location to return the value, initialized to the right #GType
 * @error: a place to store any #GError<!-- -->s that occur
 */
gboolean
mcd_keyfile_get_value (GKeyFile *keyfile,
    const gchar *group,
    const gchar *key,
    GValue *value,
    GError **error)
{
  GType type;
  GVariant *variant = NULL;

  g_return_val_if_fail (keyfile != NULL, FALSE);
  g_return_val_if_fail (group != NULL, FALSE);
  g_return_val_if_fail (key != NULL, FALSE);
  g_return_val_if_fail (G_IS_VALUE (value), FALSE);

  type = G_VALUE_TYPE (value);

  switch (type)
    {
      case G_TYPE_STRING:
        variant = mcd_keyfile_get_variant (keyfile, group, key,
            G_VARIANT_TYPE_STRING, error);
        break;

      case G_TYPE_INT:
        variant = mcd_keyfile_get_variant (keyfile, group, key,
            G_VARIANT_TYPE_INT32, error);
        break;

      case G_TYPE_INT64:
        variant = mcd_keyfile_get_variant (keyfile, group, key,
            G_VARIANT_TYPE_INT64, error);
        break;

      case G_TYPE_UINT:
        variant = mcd_keyfile_get_variant (keyfile, group, key,
            G_VARIANT_TYPE_UINT32, error);
        break;

      case G_TYPE_UCHAR:
        variant = mcd_keyfile_get_variant (keyfile, group, key,
            G_VARIANT_TYPE_BYTE, error);
        break;

      case G_TYPE_UINT64:
        variant = mcd_keyfile_get_variant (keyfile, group, key,
            G_VARIANT_TYPE_UINT64, error);
        break;

      case G_TYPE_BOOLEAN:
        variant = mcd_keyfile_get_variant (keyfile, group, key,
            G_VARIANT_TYPE_BOOLEAN, error);
        break;

      case G_TYPE_DOUBLE:
        variant = mcd_keyfile_get_variant (keyfile, group, key,
            G_VARIANT_TYPE_DOUBLE, error);
        break;

      default:
        if (type == G_TYPE_STRV)
          {
            variant = mcd_keyfile_get_variant (keyfile, group, key,
                G_VARIANT_TYPE_STRING_ARRAY, error);
          }
        else if (type == DBUS_TYPE_G_OBJECT_PATH)
          {
            variant = mcd_keyfile_get_variant (keyfile, group, key,
                G_VARIANT_TYPE_OBJECT_PATH, error);
          }
        else if (type == TP_ARRAY_TYPE_OBJECT_PATH_LIST)
          {
            variant = mcd_keyfile_get_variant (keyfile, group, key,
                G_VARIANT_TYPE_OBJECT_PATH_ARRAY, error);
          }
        else if (type == TP_STRUCT_TYPE_SIMPLE_PRESENCE)
          {
            variant = mcd_keyfile_get_variant (keyfile, group, key,
                G_VARIANT_TYPE ("(uss)"), error);
          }
        else
          {
            gchar *message =
              g_strdup_printf ("cannot get key %s from group %s: "
                  "unknown type %s",
                  key, group, g_type_name (type));

            g_warning ("%s: %s", G_STRFUNC, message);
            g_set_error (error, MCD_ACCOUNT_ERROR,
                MCD_ACCOUNT_ERROR_GET_PARAMETER,
                "%s", message);
            g_free (message);
          }
    }

  if (variant == NULL)
    return FALSE;

  g_variant_ref_sink (variant);
  g_value_unset (value);
  dbus_g_value_parse_g_variant (variant, value);
  g_assert (G_VALUE_TYPE (value) == type);
  g_variant_unref (variant);
  return TRUE;
}

/*
 * mcd_keyfile_get_variant:
 * @keyfile: A #GKeyFile
 * @group: name of a group
 * @key: name of a key
 * @type: the desired type
 * @error: a place to store any #GError<!-- -->s that occur
 *
 * Returns: a new floating #GVariant
 */
GVariant *
mcd_keyfile_get_variant (GKeyFile *keyfile,
    const gchar *group,
    const gchar *key,
    const GVariantType *type,
    GError **error)
{
  const gchar *type_str = g_variant_type_peek_string (type);
  GVariant *ret = NULL;

  g_return_val_if_fail (keyfile != NULL, NULL);
  g_return_val_if_fail (group != NULL, NULL);
  g_return_val_if_fail (key != NULL, NULL);
  g_return_val_if_fail (g_variant_type_string_scan (type_str, NULL, NULL),
      NULL);

  switch (type_str[0])
    {
      case G_VARIANT_CLASS_STRING:
          {
            gchar *v_string = g_key_file_get_string (keyfile, group,
                key, error);

            if (v_string != NULL)
              ret = g_variant_new_string (v_string);
            /* else error is already set */
          }
        break;

      case G_VARIANT_CLASS_INT32:
          {
            GError *e = NULL;
            gint v_int = g_key_file_get_integer (keyfile, group,
                key, &e);

            if (e != NULL)
              {
                g_propagate_error (error, e);
              }
            else
              {
                ret = g_variant_new_int32 (v_int);
              }
          }
        break;

      case G_VARIANT_CLASS_INT64:
          {
            GError *e = NULL;
            gint64 v_int = g_key_file_get_int64 (keyfile, group,
                key, &e);

            if (e != NULL)
              {
                g_propagate_error (error, e);
              }
            else
              {
                ret = g_variant_new_int64 (v_int);
              }
          }
        break;

      case G_VARIANT_CLASS_UINT32:
          {
            GError *e = NULL;
            guint64 v_uint = g_key_file_get_uint64 (keyfile, group,
                key, &e);

            if (e != NULL)
              {
                g_propagate_error (error, e);
              }
            else if (v_uint > G_MAXUINT32)
              {
                g_set_error (error, MCD_ACCOUNT_ERROR,
                    MCD_ACCOUNT_ERROR_GET_PARAMETER,
                    "Parameter '%s' out of range for an unsigned 32-bit "
                    "integer: %" G_GUINT64_FORMAT, key, v_uint);
              }
            else
              {
                ret = g_variant_new_uint32 (v_uint);
              }
          }
        break;

    case G_VARIANT_CLASS_BYTE:
          {
            GError *e = NULL;
            gint v_int = g_key_file_get_integer (keyfile, group,
                key, &e);

            if (e != NULL)
              {
                g_propagate_error (error, e);
              }
            else if (v_int < 0 || v_int > 0xFF)
              {
                g_set_error (error, MCD_ACCOUNT_ERROR,
                    MCD_ACCOUNT_ERROR_GET_PARAMETER,
                    "Parameter '%s' out of range for an unsigned byte: "
                    "%d", key, v_int);
              }
            else
              {
                ret = g_variant_new_byte (v_int);
              }
          }
        break;

      case G_VARIANT_CLASS_UINT64:
          {
            GError *e = NULL;
            guint64 v_uint = g_key_file_get_uint64 (keyfile, group,
                key, &e);

            if (e != NULL)
              {
                g_propagate_error (error, e);
              }
            else
              {
                ret = g_variant_new_uint64 (v_uint);
              }
          }
        break;

      case G_VARIANT_CLASS_BOOLEAN:
          {
            GError *e = NULL;
            gboolean v_bool = g_key_file_get_boolean (keyfile, group,
                key, &e);

            if (e != NULL)
              {
                g_propagate_error (error, e);
              }
            else
              {
                ret = g_variant_new_boolean (v_bool);
              }
          }
        break;

      case G_VARIANT_CLASS_DOUBLE:
          {
            GError *e = NULL;
            gdouble v_double = g_key_file_get_double (keyfile, group,
                key, &e);

            if (e != NULL)
              {
                g_propagate_error (error, e);
              }
            else
              {
                ret = g_variant_new_double (v_double);
              }
          }
        break;

      default:
        if (g_variant_type_equal (type, G_VARIANT_TYPE_STRING_ARRAY))
          {
            gchar **v = g_key_file_get_string_list (keyfile, group,
                key, NULL, error);

            if (v != NULL)
              {
                ret = g_variant_new_strv ((const gchar **) v, -1);
                g_strfreev (v);
              }
          }
        else if (g_variant_type_equal (type, G_VARIANT_TYPE_OBJECT_PATH))
          {
            gchar *v_string = g_key_file_get_string (keyfile, group,
                key, error);

            if (v_string == NULL)
              {
                /* do nothing, error is already set */
              }
            else if (!tp_dbus_check_valid_object_path (v_string, NULL))
              {
                g_set_error (error, MCD_ACCOUNT_ERROR,
                    MCD_ACCOUNT_ERROR_GET_PARAMETER,
                    "Invalid object path %s", v_string);
              }
            else
              {
                ret = g_variant_new_object_path (v_string);
              }

            g_free (v_string);
          }
        else if (g_variant_type_equal (type, G_VARIANT_TYPE_OBJECT_PATH_ARRAY))
          {
            gchar **v = g_key_file_get_string_list (keyfile, group,
                key, NULL, error);

            if (v != NULL)
              {
                gchar **iter;

                for (iter = v; iter != NULL && *iter != NULL; iter++)
                  {
                    if (!g_variant_is_object_path (*iter))
                      {
                        g_set_error (error, MCD_ACCOUNT_ERROR,
                            MCD_ACCOUNT_ERROR_GET_PARAMETER,
                            "Invalid object path %s stored in keyfile", *iter);
                        g_strfreev (v);
                        v = NULL;
                        break;
                      }
                  }

                ret = g_variant_new_objv ((const gchar **) v, -1);
                g_strfreev (v);
              }
          }
        else if (g_variant_type_equal (type, G_VARIANT_TYPE ("(uss)")))
          {
            gchar **v = g_key_file_get_string_list (keyfile, group,
                key, NULL, error);

            if (v == NULL)
              {
                /* error is already set, do nothing */
              }
            else if (g_strv_length (v) != 3)
              {
                g_set_error (error, TP_ERROR, TP_ERROR_NOT_AVAILABLE,
                    "Invalid simple-presence structure stored in keyfile");
              }
            else
              {
                guint64 u;
                gchar *endptr;

                errno = 0;
                u = g_ascii_strtoull (v[0], &endptr, 10);

                if (errno != 0 || *endptr != '\0' || u > G_MAXUINT32)
                  {
                    g_set_error (error, TP_ERROR, TP_ERROR_NOT_AVAILABLE,
                        "Invalid presence type stored in keyfile: %s", v[0]);
                  }
                else
                  {
                    /* a syntactically valid simple presence */
                    ret = g_variant_new_parsed ("(%u, %s, %s)",
                        (guint32) u, v[1], v[2]);
                  }
              }

            g_strfreev (v);
          }
        else
          {
            gchar *message =
              g_strdup_printf ("cannot get key %s from group %s: "
                  "unknown type %.*s", key, group,
                  (int) g_variant_type_get_string_length (type),
                  type_str);

            g_warning ("%s: %s", G_STRFUNC, message);
            g_set_error (error, MCD_ACCOUNT_ERROR,
                MCD_ACCOUNT_ERROR_GET_PARAMETER,
                "%s", message);
            g_free (message);
          }
    }

  g_assert (ret == NULL || g_variant_is_of_type (ret, type));
  return ret;
}

/*
 * mcd_storage_get_boolean:
 * @storage: An object implementing the #McdStorage interface
 * @account: unique name of the account
 * @key: name of the attribute to be retrieved
 *
 * Returns: a #gboolean. Unset/unparseable values are returned as %FALSE
 */
gboolean
mcd_storage_get_boolean (McdStorage *self,
    const gchar *account,
    const gchar *attribute)
{
  GValue tmp = G_VALUE_INIT;

  g_return_val_if_fail (MCD_IS_STORAGE (self), FALSE);
  g_return_val_if_fail (account != NULL, FALSE);
  g_return_val_if_fail (attribute != NULL, FALSE);
  g_return_val_if_fail (!g_str_has_prefix (attribute, "param-"), FALSE);

  g_value_init (&tmp, G_TYPE_BOOLEAN);

  if (!mcd_storage_get_attribute (self, account, attribute,
        G_VARIANT_TYPE_BOOLEAN, &tmp, NULL))
    return FALSE;

  return g_value_get_boolean (&tmp);
}

/*
 * mcd_storage_get_integer:
 * @storage: An object implementing the #McdStorage interface
 * @account: unique name of the account
 * @attribute: name of the attribute to be retrieved
 *
 * Returns: a #gint. Unset or non-numeric values are returned as 0
 */
gint
mcd_storage_get_integer (McdStorage *self,
    const gchar *account,
    const gchar *attribute)
{
  GValue tmp = G_VALUE_INIT;

  g_return_val_if_fail (MCD_IS_STORAGE (self), 0);
  g_return_val_if_fail (account != NULL, 0);
  g_return_val_if_fail (attribute != NULL, 0);
  g_return_val_if_fail (!g_str_has_prefix (attribute, "param-"), 0);

  g_value_init (&tmp, G_TYPE_INT);

  if (!mcd_storage_get_attribute (self, account, attribute,
        G_VARIANT_TYPE_INT32, &tmp, NULL))
    return FALSE;

  return g_value_get_int (&tmp);
}

static gboolean
update_storage (McdStorage *self,
    const gchar *account,
    gboolean parameter,
    const gchar *key,
    GVariant *variant)
{
  McpAccountManager *ma = MCP_ACCOUNT_MANAGER (self);
  gboolean updated = FALSE;
  McpAccountStorage *plugin;
  const gchar *pn;
  McpAccountStorageSetResult res;

  plugin = g_hash_table_lookup (self->accounts, account);
  g_return_val_if_fail (plugin != NULL, FALSE);
  pn = mcp_account_storage_name (plugin);

  if (parameter)
    res = mcp_account_storage_set_parameter (plugin, ma, account,
        key, variant, MCP_PARAMETER_FLAG_NONE);
  else
    res = mcp_account_storage_set_attribute (plugin, ma, account,
        key, variant, MCP_ATTRIBUTE_FLAG_NONE);

  switch (res)
    {
      case MCP_ACCOUNT_STORAGE_SET_RESULT_CHANGED:
        DEBUG ("MCP:%s -> store %s %s.%s", pn,
            parameter ? "parameter" : "attribute", account, key);
        updated = TRUE;
        break;

      case MCP_ACCOUNT_STORAGE_SET_RESULT_FAILED:
        DEBUG ("MCP:%s -> failed to store %s %s.%s",
            pn, parameter ? "parameter" : "attribute", account, key);
        break;

      case MCP_ACCOUNT_STORAGE_SET_RESULT_UNCHANGED:
        DEBUG ("MCP:%s -> no change to %s %s.%s",
            pn, parameter ? "parameter" : "attribute", account, key);
        break;

      default:
        g_warn_if_reached ();
    }

  return updated;
}

/*
 * mcd_storage_set_string:
 * @storage: An object implementing the #McdStorage interface
 * @account: the unique name of an account
 * @key: the name of the attribute
 * @value: the value to be stored (or %NULL to erase it)
 *
 * Copies and stores the supplied @value (or removes it if %NULL) to the
 * internal cache.
 *
 * Returns: a #gboolean indicating whether the cache actually required an
 * update (so that the caller can decide whether to request a commit to
 * long term storage or not). %TRUE indicates the cache was updated and
 * may not be in sync with the store any longer, %FALSE indicates we already
 * held the value supplied.
 */
gboolean
mcd_storage_set_string (McdStorage *self,
    const gchar *account,
    const gchar *attribute,
    const gchar *val)
{
  gboolean updated;

  g_return_val_if_fail (MCD_IS_STORAGE (self), FALSE);
  g_return_val_if_fail (account != NULL, FALSE);
  g_return_val_if_fail (attribute != NULL, FALSE);
  g_return_val_if_fail (!g_str_has_prefix (attribute, "param-"), FALSE);

  if (val == NULL)
    {
      updated = mcd_storage_set_attribute (self, account, attribute, NULL);
    }
  else
    {
      GValue tmp = G_VALUE_INIT;

      g_value_init (&tmp, G_TYPE_STRING);
      g_value_set_string (&tmp, val);
      updated = mcd_storage_set_attribute (self, account, attribute, &tmp);
      g_value_unset (&tmp);
    }

  return updated;
}

/*
 * mcd_storage_set_attribute:
 * @storage: An object implementing the #McdStorage interface
 * @account: the unique name of an account
 * @attribute: the name of the attribute, e.g. "DisplayName"
 * @value: the value to be stored (or %NULL to erase it)
 *
 * Copies and stores the supplied @value (or removes it if %NULL) in the
 * internal cache.
 *
 * Returns: a #gboolean indicating whether the cache actually required an
 * update (so that the caller can decide whether to request a commit to
 * long term storage or not). %TRUE indicates the cache was updated and
 * may not be in sync with the store any longer, %FALSE indicates we already
 * held the value supplied.
 */
gboolean
mcd_storage_set_attribute (McdStorage *self,
    const gchar *account,
    const gchar *attribute,
    const GValue *value)
{
  GVariant *new_v;
  gboolean updated = FALSE;
  McpAccountStorage *plugin;

  g_return_val_if_fail (MCD_IS_STORAGE (self), FALSE);
  g_return_val_if_fail (account != NULL, FALSE);
  g_return_val_if_fail (attribute != NULL, FALSE);
  g_return_val_if_fail (!g_str_has_prefix (attribute, "param-"), FALSE);

  plugin = g_hash_table_lookup (self->accounts, account);
  g_return_val_if_fail (plugin != NULL, FALSE);

  if (value != NULL)
    new_v = g_variant_ref_sink (dbus_g_value_build_g_variant (value));
  else
    new_v = NULL;

  updated = update_storage (self, account, FALSE, attribute, new_v);

  tp_clear_pointer (&new_v, g_variant_unref);
  return updated;
}

/*
 * mcd_storage_set_parameter:
 * @storage: An object implementing the #McdStorage interface
 * @account: the unique name of an account
 * @parameter: the name of the parameter, e.g. "account"
 * @value: the value to be stored (or %NULL to erase it)
 *
 * Copies and stores the supplied @value (or removes it if %NULL) in the
 * internal cache.
 *
 * Returns: a #gboolean indicating whether the cache actually required an
 * update (so that the caller can decide whether to request a commit to
 * long term storage or not). %TRUE indicates the cache was updated and
 * may not be in sync with the store any longer, %FALSE indicates we already
 * held the value supplied.
 */
gboolean
mcd_storage_set_parameter (McdStorage *self,
    const gchar *account,
    const gchar *parameter,
    const GValue *value)
{
  GVariant *new_v = NULL;
  gboolean updated = FALSE;
  McpAccountStorage *plugin;

  g_return_val_if_fail (MCD_IS_STORAGE (self), FALSE);
  g_return_val_if_fail (account != NULL, FALSE);
  g_return_val_if_fail (parameter != NULL, FALSE);

  plugin = g_hash_table_lookup (self->accounts, account);
  g_return_val_if_fail (plugin != NULL, FALSE);

  if (value != NULL)
    {
      new_v = g_variant_ref_sink (dbus_g_value_build_g_variant (value));
    }

  updated = update_storage (self, account, TRUE, parameter, new_v);

  tp_clear_pointer (&new_v, g_variant_unref);
  return updated;
}

/*
 * @value: a populated #GValue of a supported #GType
 *
 * Escape the contents of @value to go in a #GKeyFile. Return the
 * value that would go in the keyfile.
 *
 * For instance, for a boolean value TRUE this would return "true",
 * and for a string containing one space, it would return "\s".
 */
gchar *
mcd_keyfile_escape_value (const GValue *value)
{
  GVariant *variant;
  gchar *ret;

  g_return_val_if_fail (G_IS_VALUE (value), NULL);

  variant = dbus_g_value_build_g_variant (value);

  if (variant == NULL)
    {
      g_warning ("Unable to convert %s to GVariant",
          G_VALUE_TYPE_NAME (value));
      return NULL;
    }

  g_variant_ref_sink (variant);
  ret = mcd_keyfile_escape_variant (variant);
  g_variant_unref (variant);
  return ret;
}

static gchar *
mcpa_escape_variant_for_keyfile (const McpAccountManager *unused G_GNUC_UNUSED,
    GVariant *variant)
{
  return mcd_keyfile_escape_variant (variant);
}

/*
 * mcd_keyfile_set_value:
 * @keyfile: a keyfile
 * @name: the name of a group
 * @key: the key in the group
 * @value: the value to be stored (or %NULL to erase it)
 *
 * Copies and stores the supplied @value (or removes it if %NULL) to the
 * internal cache.
 *
 * Returns: a #gboolean indicating whether the cache actually required an
 * update (so that the caller can decide whether to request a commit to
 * long term storage or not). %TRUE indicates the cache was updated and
 * may not be in sync with the store any longer, %FALSE indicates we already
 * held the value supplied.
 */
gboolean
mcd_keyfile_set_value (GKeyFile *keyfile,
    const gchar *name,
    const gchar *key,
    const GValue *value)
{
  g_return_val_if_fail (name != NULL, FALSE);
  g_return_val_if_fail (key != NULL, FALSE);

  if (value == NULL)
    {
      return mcd_keyfile_set_variant (keyfile, name, key, NULL);
    }
  else
    {
      GVariant *variant;
      gboolean ret;

      variant = dbus_g_value_build_g_variant (value);

      if (variant == NULL)
        {
          g_warning ("Unable to convert %s to GVariant",
              G_VALUE_TYPE_NAME (value));
          return FALSE;
        }

      g_variant_ref_sink (variant);
      ret = mcd_keyfile_set_variant (keyfile, name, key, variant);
      g_variant_unref (variant);
      return ret;
    }
}

/*
 * mcd_keyfile_set_variant:
 * @keyfile: a keyfile
 * @name: the name of a group
 * @key: the key in the group
 * @value: the value to be stored (or %NULL to erase it)
 *
 * Escape @variant and store it in the keyfile.
 *
 * Returns: %TRUE if the keyfile actually changed,
 * so that the caller can decide whether to request a commit to
 * long term storage or not.
 */
gboolean
mcd_keyfile_set_variant (GKeyFile *keyfile,
    const gchar *name,
    const gchar *key,
    GVariant *value)
{
  g_return_val_if_fail (name != NULL, FALSE);
  g_return_val_if_fail (key != NULL, FALSE);

  if (value == NULL)
    {
      gchar *old = g_key_file_get_value (keyfile, name, key, NULL);
      gboolean updated = (old != NULL);

      g_free (old);
      g_key_file_remove_key (keyfile, name, key, NULL);
      return updated;
    }
  else
    {
      gboolean updated = FALSE;
      gchar *old = g_key_file_get_value (keyfile, name, key, NULL);
      gchar *new = NULL;
      gchar *buf = NULL;

      switch (g_variant_classify (value))
        {
          case G_VARIANT_CLASS_STRING:
          case G_VARIANT_CLASS_OBJECT_PATH:
          case G_VARIANT_CLASS_SIGNATURE:
            g_key_file_set_string (keyfile, name, key,
                g_variant_get_string (value, NULL));
            break;

          case G_VARIANT_CLASS_UINT16:
            buf = g_strdup_printf ("%u", g_variant_get_uint16 (value));
            break;

          case G_VARIANT_CLASS_UINT32:
            buf = g_strdup_printf ("%u", g_variant_get_uint32 (value));
            break;

          case G_VARIANT_CLASS_INT16:
            buf = g_strdup_printf ("%d", g_variant_get_int16 (value));
            break;

          case G_VARIANT_CLASS_INT32:
            buf = g_strdup_printf ("%d", g_variant_get_int32 (value));
            break;

          case G_VARIANT_CLASS_BOOLEAN:
            g_key_file_set_boolean (keyfile, name, key,
                g_variant_get_boolean (value));
            break;

          case G_VARIANT_CLASS_BYTE:
            buf = g_strdup_printf ("%u", g_variant_get_byte (value));
            break;

          case G_VARIANT_CLASS_UINT64:
            buf = g_strdup_printf ("%" G_GUINT64_FORMAT,
                                   g_variant_get_uint64 (value));
            break;

          case G_VARIANT_CLASS_INT64:
            buf = g_strdup_printf ("%" G_GINT64_FORMAT,
                                   g_variant_get_int64 (value));
            break;

          case G_VARIANT_CLASS_DOUBLE:
            g_key_file_set_double (keyfile, name, key,
                g_variant_get_double (value));
            break;

          case G_VARIANT_CLASS_ARRAY:
            if (g_variant_is_of_type (value, G_VARIANT_TYPE_STRING_ARRAY))
              {
                gsize len;
                const gchar **strings = g_variant_get_strv (value, &len);

                g_key_file_set_string_list (keyfile, name, key, strings, len);
              }
            else if (g_variant_is_of_type (value,
                  G_VARIANT_TYPE_OBJECT_PATH_ARRAY))
              {
                gsize len;
                const gchar **strings = g_variant_get_objv (value, &len);

                g_key_file_set_string_list (keyfile, name, key, strings, len);
              }
            else
              {
                g_warning ("Unexpected array type %s",
                    g_variant_get_type_string (value));
                return FALSE;
              }
            break;

          case G_VARIANT_CLASS_TUPLE:
            if (g_variant_is_of_type (value, G_VARIANT_TYPE ("(uss)")))
              {
                guint32 type;
                /* enough for "4294967296" + \0 */
                gchar printf_buf[11];
                const gchar * strv[4] = { NULL, NULL, NULL, NULL };

                g_variant_get (value, "(u&s&s)",
                    &type,
                    &(strv[1]),
                    &(strv[2]));
                g_snprintf (printf_buf, sizeof (printf_buf), "%u", type);
                strv[0] = printf_buf;

                g_key_file_set_string_list (keyfile, name, key, strv, 3);
              }
            else
              {
                g_warning ("Unexpected struct type %s",
                    g_variant_get_type_string (value));
                return FALSE;
              }
            break;

          default:
              {
                g_warning ("Unexpected variant type %s",
                    g_variant_get_type_string (value));
                return FALSE;
              }
        }

      if (buf != NULL)
        g_key_file_set_string (keyfile, name, key, buf);

      new = g_key_file_get_value (keyfile, name, key, NULL);

      if (tp_strdiff (old, new))
        updated = TRUE;

      g_free (new);
      g_free (buf);
      g_free (old);

      return updated;
    }
}

/*
 * mcd_storage_create_account:
 * @storage: An object implementing the #McdStorage interface
 * @provider: the desired storage provider, or %NULL
 * @manager: the name of the manager
 * @protocol: the name of the protocol
 * @identification: the result of IdentifyAccount
 * @plugin_out: (out) (transfer full): the plugin we used
 * @error: a #GError to fill when returning %NULL
 *
 * Create a new account in storage. This should not store any
 * information on the long term storage until mcd_storage_commit() is called.
 *
 * See mcp_account_storage_create().
 *
 * Returns: the unique name to use for the new account, or %NULL on error.
 */
gchar *
mcd_storage_create_account (McdStorage *self,
    const gchar *provider,
    const gchar *manager,
    const gchar *protocol,
    const gchar *identification,
    McpAccountStorage **plugin_out,
    GError **error)
{
  GList *store;
  McpAccountManager *ma = MCP_ACCOUNT_MANAGER (self);
  gchar *ret;

  if (plugin_out != NULL)
    *plugin_out = NULL;

  g_return_val_if_fail (MCD_IS_STORAGE (self), NULL);
  g_return_val_if_fail (!tp_str_empty (manager), NULL);
  g_return_val_if_fail (!tp_str_empty (protocol), NULL);

  /* If a storage provider is specified, use only it or fail */
  if (provider != NULL)
    {
      for (store = stores; store != NULL; store = g_list_next (store))
        {
          McpAccountStorage *plugin = store->data;

          if (!tp_strdiff (mcp_account_storage_provider (plugin), provider))
            {
              ret = mcp_account_storage_create (plugin, ma, manager,
                  protocol, identification, error);
              if (mcd_storage_add_account_from_plugin (self, plugin, ret,
                    error))
                {
                  if (plugin_out != NULL)
                    *plugin_out = g_object_ref (plugin);

                  return ret;
                }
              else
                {
                  g_free (ret);
                  return NULL;
                }
            }
        }

      g_set_error (error, TP_ERROR, TP_ERROR_INVALID_ARGUMENT,
          "Storage provider '%s' does not exist", provider);

      return NULL;
    }

  /* No provider specified, let's pick the first plugin able to create this
   * account in priority order.
   */
  for (store = stores; store != NULL; store = g_list_next (store))
    {
      McpAccountStorage *plugin = store->data;

      ret = mcp_account_storage_create (plugin, ma, manager, protocol,
          identification, error);

      if (ret != NULL)
        {
          if (mcd_storage_add_account_from_plugin (self, plugin, ret,
                error))
            {
              if (plugin_out != NULL)
                *plugin_out = g_object_ref (plugin);

              return ret;
            }
          else
            {
              g_free (ret);
              return NULL;
            }
        }

      g_clear_error (error);
    }

  /* This should never happen since the default storage is always able to create
   * an account */
  g_warn_if_reached ();
  g_set_error (error, TP_ERROR, TP_ERROR_INVALID_ARGUMENT,
      "None of the storage provider are able to create the account");

  return NULL;
}

static void
delete_cb (GObject *source,
    GAsyncResult *res,
    gpointer user_data)
{
  GError *error = NULL;
  const gchar *account_name = user_data;

  if (mcp_account_storage_delete_finish (MCP_ACCOUNT_STORAGE (source),
        res, &error))
    {
      DEBUG ("deleted account %s", account_name);
    }
  else
    {
      DEBUG ("could not delete account %s (but no way to signal that): "
          "%s #%d: %s", account_name,
          g_quark_to_string (error->domain), error->code, error->message);
      g_error_free (error);
    }

  g_free (user_data);
}

/*
 * mcd_storage_delete_account:
 * @storage: An object implementing the #McdStorage interface
 * @account: unique name of the account
 *
 * Removes an account's settings from long term storage.
 * This does not handle any of the other logic to do with removing
 * accounts, it merely ensures that no trace of the account remains
 * in long term storage once mcd_storage_commit() has been called.
 */
void
mcd_storage_delete_account (McdStorage *self,
    const gchar *account)
{
  McpAccountManager *ma = MCP_ACCOUNT_MANAGER (self);
  McpAccountStorage *plugin;

  g_return_if_fail (MCD_IS_STORAGE (self));
  g_return_if_fail (account != NULL);

  plugin = g_hash_table_lookup (self->accounts, account);
  g_return_if_fail (plugin != NULL);

  /* FIXME: stop ignoring the error (if any), and make this method async
   * in order to pass the error up to McdAccount */
  mcp_account_storage_delete_async (plugin, ma, account, NULL,
      delete_cb, g_strdup (account));
}

/*
 * mcd_storage_commit:
 * @storage: An object implementing the #McdStorage interface
 * @account: the unique name of an account
 *
 * Sync the long term storage (whatever it might be) with the current
 * state of our internal cache.
 */
void
mcd_storage_commit (McdStorage *self, const gchar *account)
{
  McpAccountManager *ma = MCP_ACCOUNT_MANAGER (self);
  McpAccountStorage *plugin;
  const gchar *pname;

  g_return_if_fail (MCD_IS_STORAGE (self));
  g_return_if_fail (account != NULL);

  plugin = g_hash_table_lookup (self->accounts, account);
  g_return_if_fail (plugin != NULL);

  pname = mcp_account_storage_name (plugin);

  /* FIXME: fd.o #29563: this should be async, really */
  DEBUG ("flushing plugin %s %s to long term storage", pname, account);
  mcp_account_storage_commit (plugin, ma, account);
}

/*
 * mcd_storage_set_strv:
 * @storage: An object implementing the #McdStorage interface
 * @account: the unique name of an account
 * @attribute: the name of the attribute
 * @strv: the string vector to be stored (where %NULL is treated as equivalent
 * to an empty vector)
 *
 * Copies and stores the supplied string vector to the internal cache.
 *
 * Returns: a #gboolean indicating whether the cache actually required an
 * update (so that the caller can decide whether to request a commit to
 * long term storage or not). %TRUE indicates the cache was updated and
 * may not be in sync with the store any longer, %FALSE indicates we already
 * held the value supplied.
 */
gboolean
mcd_storage_set_strv (McdStorage *storage,
    const gchar *account,
    const gchar *attribute,
    const gchar * const *strv)
{
  GValue v = G_VALUE_INIT;
  static const gchar * const *empty = { NULL };
  gboolean ret;

  g_return_val_if_fail (MCD_IS_STORAGE (storage), FALSE);
  g_return_val_if_fail (account != NULL, FALSE);
  g_return_val_if_fail (attribute != NULL, FALSE);
  g_return_val_if_fail (!g_str_has_prefix (attribute, "param-"), FALSE);

  g_value_init (&v, G_TYPE_STRV);
  g_value_set_static_boxed (&v, strv == NULL ? empty : strv);
  ret = mcd_storage_set_attribute (storage, account, attribute, &v);
  g_value_unset (&v);
  return ret;
}

void
mcd_storage_ready (McdStorage *self)
{
  GList *store;
  McpAccountManager *ma = MCP_ACCOUNT_MANAGER (self);

  for (store = stores; store != NULL; store = g_list_next (store))
    {
      McpAccountStorage *plugin = store->data;
      const gchar *plugin_name = mcp_account_storage_name (plugin);

      DEBUG ("Unblocking async account ops by %s", plugin_name);
      mcp_account_storage_ready (plugin, ma);
    }
}

static GVariant *
mcpa_unescape_variant_from_keyfile (const McpAccountManager *mcpa,
    const gchar *escaped,
    const GVariantType *type,
    GError **error)
{
  GKeyFile *keyfile;
  GVariant *ret;

  g_return_val_if_fail (escaped != NULL, NULL);
  g_return_val_if_fail (type != NULL, NULL);

  keyfile = g_key_file_new ();
  g_key_file_set_value (keyfile, "g", "k", escaped);
  ret = mcd_keyfile_get_variant (keyfile, "g", "k", type, error);
  g_key_file_free (keyfile);

  if (ret != NULL)
    g_variant_ref_sink (ret);

  return ret;
}

static void
plugin_iface_init (McpAccountManagerIface *iface,
    gpointer unused G_GNUC_UNUSED)
{
  DEBUG ();

  iface->unique_name = unique_name;
  iface->identify_account_async = identify_account_async;
  iface->identify_account_finish = identify_account_finish;
  iface->escape_variant_for_keyfile = mcpa_escape_variant_for_keyfile;
  iface->unescape_variant_from_keyfile = mcpa_unescape_variant_from_keyfile;
}

gboolean
mcd_storage_add_account_from_plugin (McdStorage *self,
    McpAccountStorage *plugin,
    const gchar *account,
    GError **error)
{
  McpAccountStorage *other = g_hash_table_lookup (self->accounts, account);
  McpAccountManager *api = (McpAccountManager *) self;
  gchar **typed_parameters;
  gchar **untyped_parameters;

  if (other != NULL)
    {
      g_set_error (error, TP_ERROR, TP_ERROR_NOT_AVAILABLE,
          "account %s already exists in plugin '%s', cannot create "
          "for plugin '%s'",
          account,
          mcp_account_storage_name (other),
          mcp_account_storage_name (plugin));
      return FALSE;
    }

  g_hash_table_insert (self->accounts, g_strdup (account),
      g_object_ref (plugin));

  typed_parameters = mcp_account_storage_list_typed_parameters (plugin, api,
      account);
  untyped_parameters = mcp_account_storage_list_untyped_parameters (plugin,
      api, account);

  DEBUG ("Account parameters for %s", account);

  if (typed_parameters != NULL)
    {
      gsize i;

      for (i = 0; typed_parameters[i] != NULL; i++)
        {
          GVariant *v = mcp_account_storage_get_parameter (plugin, api, account,
              typed_parameters[i], NULL, NULL);

          if (v == NULL)
            {
              CRITICAL ("%s: could not be retrieved", typed_parameters[i]);
            }
          else
            {
              DEBUG ("%s: type '%s'", typed_parameters[i],
                  g_variant_get_type_string (v));
              g_variant_unref (v);
            }
        }
    }

  if (untyped_parameters != NULL)
    {
      gsize i;

      for (i = 0; untyped_parameters[i] != NULL; i++)
        {
          DEBUG ("%s: type not stored", untyped_parameters[i]);
        }
    }

  DEBUG ("End of parameters");

  g_strfreev (typed_parameters);
  g_strfreev (untyped_parameters);

  return TRUE;
}

GHashTable *
mcd_storage_dup_typed_parameters (McdStorage *self,
    const gchar *account_name)
{
  McpAccountStorage *plugin;
  McpAccountManager *api = (McpAccountManager *) self;
  gsize i;
  gchar **typed_parameters;
  GHashTable *params;

  g_return_val_if_fail (MCD_IS_STORAGE (self), NULL);

  plugin = g_hash_table_lookup (self->accounts, account_name);
  g_return_val_if_fail (plugin != NULL, NULL);

  typed_parameters = mcp_account_storage_list_typed_parameters (plugin, api,
      account_name);

  params = g_hash_table_new_full (g_str_hash, g_str_equal,
      g_free, (GDestroyNotify) tp_g_value_slice_free);

  for (i = 0;
       typed_parameters != NULL && typed_parameters[i] != NULL;
       i++)
    {
      GVariant *v = mcp_account_storage_get_parameter (plugin, api,
          account_name, typed_parameters[i], NULL, NULL);
      GValue *value;

      if (v == NULL)
        {
          CRITICAL ("%s was in list_typed_parameters() but could not be "
              "retrieved", typed_parameters[i]);
          continue;
        }

      value = g_slice_new0 (GValue);
      dbus_g_value_parse_g_variant (v, value);

      if (!G_IS_VALUE (value))
        {
          CRITICAL ("could not turn %s into a GValue", typed_parameters[i]);
          g_slice_free (GValue, value);
          continue;
        }

      g_hash_table_insert (params, g_strdup (typed_parameters[i]),
          value);
      g_variant_unref (v);
    }

  return params;
}

/* See whether we can migrate the parameters from being stored without
 * their types, to being stored with their types.
 * Commit changes and return TRUE if anything happened. */
gboolean
mcd_storage_maybe_migrate_parameters (McdStorage *self,
    const gchar *account_name,
    TpProtocol *protocol)
{
  McpAccountManager *api = MCP_ACCOUNT_MANAGER (self);
  McpAccountStorage *plugin;
  gchar **untyped_parameters = NULL;
  gsize i;
  gboolean ret = FALSE;

  plugin = g_hash_table_lookup (self->accounts, account_name);
  g_return_val_if_fail (plugin != NULL, FALSE);

  /* If the storage backend can't store typed parameters, there's no point. */
  if (!mcp_account_storage_has_any_flag (plugin, account_name,
        MCP_ACCOUNT_STORAGE_FLAG_STORES_TYPES))
    goto finally;

  untyped_parameters = mcp_account_storage_list_untyped_parameters (
      plugin, api, account_name);

  /* If there's nothing to migrate, there's also no point. */
  if (untyped_parameters == NULL || untyped_parameters[0] == NULL)
    goto finally;

  DEBUG ("trying to migrate %s", account_name);

  for (i = 0; untyped_parameters[i] != NULL; i++)
    {
      const gchar *param_name = untyped_parameters[i];
      const TpConnectionManagerParam *param = tp_protocol_get_param (protocol,
          param_name);
      GError *error = NULL;
      GVariantType *type = NULL;
      GVariant *value;
      McpAccountStorageSetResult res;

      if (param == NULL)
        {
          DEBUG ("cannot migrate parameter '%s': not supported by %s/%s",
              param_name, tp_protocol_get_cm_name (protocol),
              tp_protocol_get_name (protocol));
          goto next_param;
        }

      type = tp_connection_manager_param_dup_variant_type (param);

      DEBUG ("Migrating parameter '%s' of type '%.*s'",
          param_name,
          (gint) g_variant_type_get_string_length (type),
          g_variant_type_peek_string (type));

      value = mcp_account_storage_get_parameter (plugin, api,
          account_name, param_name, type, NULL);

      if (value == NULL)
        {
          DEBUG ("cannot migrate parameter '%s': %s #%d: %s",
              param_name, g_quark_to_string (error->domain), error->code,
              error->message);
          g_error_free (error);
          goto next_param;
        }

      if (!g_variant_is_of_type (value, type))
        {
          DEBUG ("trying to convert parameter from type '%s'",
              g_variant_get_type_string (value));

          /* consumes parameter */
          value = tp_variant_convert (value, type);

          if (value == NULL)
            {
              DEBUG ("could not convert parameter to desired type");
              goto next_param;
            }
        }

      res = mcp_account_storage_set_parameter (plugin, api,
          account_name, param_name, value, MCP_PARAMETER_FLAG_NONE);

      switch (res)
        {
          case MCP_ACCOUNT_STORAGE_SET_RESULT_UNCHANGED:
            /* it really ought to be CHANGED, surely? */
            DEBUG ("Tried to upgrade parameter %s but the "
                "storage backend claims not to have changed it? "
                "Not sure I really believe that", param_name);
            /* fall through to the CHANGED case */

          case MCP_ACCOUNT_STORAGE_SET_RESULT_CHANGED:
            ret = TRUE;
            break;

          case MCP_ACCOUNT_STORAGE_SET_RESULT_FAILED:
            WARNING ("Failed to set parameter %s", param_name);
            break;

          default:
            WARNING ("set_parameter returned invalid result code %d "
                "for parameter %s", res, param_name);
        }

next_param:
      if (type != NULL)
        g_variant_type_free (type);
    }

  if (ret)
    mcp_account_storage_commit (plugin, api, account_name);

finally:
  g_strfreev (untyped_parameters);
  return ret;
}