summaryrefslogtreecommitdiff
path: root/src/mcd-connection.c
blob: e2b60dd68ad66e957edaa15fc8c7fa00b565741c (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
/* vi: set et sw=4 ts=8 cino=t0,(0: */
/* -*- Mode: C; indent-tabs-mode: nil; c-basic-offset: 4; tab-width: 8 -*- */
/*
 * This file is part of mission-control
 *
 * Copyright © 2007-2011 Nokia Corporation.
 * Copyright © 2009-2011 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
 * version 2.1 as published by the Free Software Foundation.
 *
 * 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
 *
 */

/**
 * SECTION:mcd-connection
 * @title: McdConnection
 * @short_description: Connection class representing Telepathy connection class
 * @see_also: 
 * @stability: Unstable
 * @include: mcd-connection.h
 * 
 * FIXME
 */

#include "config.h"

#include "mcd-connection.h"
#include "mcd-connection-service-points.h"

#include <string.h>
#include <sys/types.h>
#include <sched.h>

#include <glib.h>
#include <glib/gstdio.h>
#include <gio/gio.h>

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

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

#include <telepathy-glib/proxy-subclass.h>

#include "mcd-account-priv.h"
#include "mcd-channel-priv.h"
#include "mcd-connection-priv.h"
#include "mcd-dispatcher-priv.h"
#include "mcd-channel.h"
#include "mcd-misc.h"
#include "mcd-slacker.h"
#include "sp_timestamp.h"

#define INITIAL_RECONNECTION_TIME   3 /* seconds */
#define RECONNECTION_MULTIPLIER     3
#define MAXIMUM_RECONNECTION_TIME   30 * 60 /* half an hour */

#define MCD_CONNECTION_PRIV(mcdconn) (MCD_CONNECTION (mcdconn)->priv)

G_DEFINE_TYPE (McdConnection, mcd_connection, MCD_TYPE_OPERATION);

/* Private */
struct _McdConnectionPrivate
{
    /* Factory for TpConnection objects */
    TpClientFactory *client_factory;

    /* Channel dispatcher */
    McdDispatcher *dispatcher;

    /* Account */
    McdAccount *account;

    /* Telepathy connection manager */
    TpConnectionManager *tp_conn_mgr;

    /* Telepathy connection */
    TpConnection *tp_conn;

    /* Things to do before calling Connect */
    guint tasks_before_connect;

    guint reconnect_timer; 	/* timer for reconnection */
    guint reconnect_interval;
    guint probation_timer;      /* for mcd_connection_probation_ended_cb */
    guint probation_drop_count;

    /* Supported presences (values are McdPresenceInfo structs) */
    GHashTable *recognized_presences;

    TpConnectionStatusReason abort_reason;
    guint got_contact_capabilities : 1;
    guint has_presence_if : 1;
    guint has_contact_capabilities_if : 1;
    guint has_power_saving_if : 1;

    /* FALSE until the dispatcher has said it's ready for us */
    guint dispatching_started : 1;
    /* FALSE until channels announced by NewChannel need to be
     * dispatched */
    guint dispatched_initial_channels : 1;

    /* TRUE if the last status change was to CONNECTED */
    guint connected : 1;

    /* FALSE until mcd_connection_close() is called */
    guint closed : 1;

    /* FALSE until connected and the supported presence statuses retrieved */
    guint presence_info_ready : 1;

    gboolean is_disposed;
    gboolean service_points_watched;

    McdSlacker *slacker;

    /* Emergency service points' handles.
     * Set of handles, lazily-allocated. */
    TpIntset *service_point_handles;
    /* Emergency service points' identifiers.
     * Set of (transfer full) (type utf8), lazily-allocated. */
    GHashTable *service_point_ids;
};

typedef struct
{
    TpConnectionPresenceType presence;
    guint may_set_on_self : 1;
    guint can_have_message : 1;
} McdPresenceInfo;

enum
{
    PROP_0,
    PROP_CLIENT_FACTORY,
    PROP_TP_MANAGER,
    PROP_TP_CONNECTION,
    PROP_ACCOUNT,
    PROP_DISPATCHER,
    PROP_SLACKER,
};

enum
{
    READY,
    CONNECTION_STATUS_CHANGED,
    N_SIGNALS
};

static guint signals[N_SIGNALS] = { 0 };

static const gchar * const _available_fb[] = { NULL };
static const gchar * const _away_fb[] = { "away", NULL };
static const gchar * const _ext_away_fb[] = { "xa", "away", NULL };
static const gchar * const _hidden_fb[] = { "hidden", "dnd", "busy", "away", NULL };
static const gchar * const _busy_fb[] = { "busy", "dnd", "away", NULL };
static const gchar * const *presence_fallbacks[] = {
    _available_fb, _away_fb, _ext_away_fb, _hidden_fb, _busy_fb
};

static void _mcd_connection_release_tp_connection (McdConnection *connection,
                                                   McdInhibit *inhibit,
                                                   gboolean already_signalled);
static gboolean request_channel_new_iface (McdConnection *connection,
                                           McdChannel *channel);

static void
mcd_presence_info_free (McdPresenceInfo *pi)
{
    g_slice_free (McdPresenceInfo, pi);
}

static void
presence_set_status_cb (TpConnection *proxy, const GError *error,
			gpointer user_data, GObject *weak_object)
{
    McdConnectionPrivate *priv = user_data;

    if (error)
    {
        _mcd_account_set_changing_presence (priv->account, FALSE);

        g_warning ("%s: Setting presence of %s failed: %s",
		   G_STRFUNC, mcd_account_get_unique_name (priv->account),
                   error->message);
    }
}

static gboolean
_check_presence (McdConnectionPrivate *priv, TpConnectionPresenceType presence,
                 const gchar **status)
{
    const gchar * const *fallbacks;

    if (priv->recognized_presences == NULL ||
        g_hash_table_size (priv->recognized_presences) == 0)
    {
        DEBUG ("account %s: recognized presences unknown, not setting "
               "presence yet", mcd_account_get_unique_name (priv->account));
        return FALSE;
    }

    if (presence == TP_CONNECTION_PRESENCE_TYPE_UNSET || *status == NULL)
        return FALSE;

    if (g_hash_table_lookup (priv->recognized_presences, *status))
        return TRUE;

    if (presence < TP_CONNECTION_PRESENCE_TYPE_AVAILABLE ||
        presence > TP_CONNECTION_PRESENCE_TYPE_BUSY)
        return FALSE;

    fallbacks =
        presence_fallbacks[presence - TP_CONNECTION_PRESENCE_TYPE_AVAILABLE];

    for (; *fallbacks != NULL; fallbacks++)
        if (g_hash_table_lookup (priv->recognized_presences, *fallbacks))
            break;

    /* assume that "available" is always supported -- otherwise, an error will
     * be returned by SetPresence, but it's not a big loss */

    if (*fallbacks != NULL)
    {
        DEBUG ("account %s: presence %s not supported, setting %s",
               mcd_account_get_unique_name (priv->account), *status,
               *fallbacks);
        *status = *fallbacks;
    }
    else
    {
        DEBUG ("account %s: presence %s not supported and no fallback is "
               "supported either, trying \"available\" and hoping for the "
               "best...", mcd_account_get_unique_name (priv->account),
               *status);
        *status = "available";
    }

    return TRUE;
}

static void
_mcd_connection_attempt (McdConnection *connection)
{
    g_return_if_fail (connection->priv->tp_conn_mgr != NULL);
    g_return_if_fail (connection->priv->account != NULL);

    DEBUG ("called for %p, account %s", connection,
           mcd_account_get_unique_name (connection->priv->account));

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

    if (mcd_account_get_connection_status (connection->priv->account) ==
        TP_CONNECTION_STATUS_DISCONNECTED)
    {
        /* not user-initiated */
        _mcd_account_connection_begin (connection->priv->account, FALSE);
    }
    else
    {
        /* Can this happen? We just don't know. */
        DEBUG ("Not connecting because not disconnected (%i)",
               mcd_account_get_connection_status (connection->priv->account));
    }
}

static void
_mcd_connection_set_presence (McdConnection * connection,
                              TpConnectionPresenceType presence,
			      const gchar *status, const gchar *message)
{
    McdConnectionPrivate *priv = connection->priv;
    const gchar *adj_status = status;

    if (!priv->tp_conn)
    {
        DEBUG ("tp_conn is NULL");
        _mcd_connection_attempt (connection);
        return;
    }
    g_return_if_fail (TP_IS_CONNECTION (priv->tp_conn));

    if (!priv->has_presence_if)
    {
        DEBUG ("Presence not supported on this connection");
        return;
    }

    if (_check_presence (priv, presence, &adj_status))
    {
        TpConnectionPresenceType curr_presence;
        const gchar *curr_status;
        const gchar *curr_message;

        DEBUG ("Setting status '%s' of type %u ('%s' was requested)",
               adj_status, presence, status);

        mcd_account_get_current_presence (priv->account, &curr_presence,
                                          &curr_status, &curr_message);
        if (curr_presence == presence &&
            tp_strdiff (curr_status, adj_status) == 0 &&
            tp_strdiff (curr_message, message) == 0)
        {
            // PresencesChanged won't be emitted and Account.ChangingPresence
            // will never go to FALSE, so forcibly set it to FALSE
            _mcd_account_set_changing_presence (priv->account, FALSE);
        }

        tp_cli_connection_interface_presence1_call_set_presence
            (priv->tp_conn, -1, adj_status, message, presence_set_status_cb,
             priv, NULL, (GObject *)connection);
    }
    else
    {
        DEBUG ("Unable to set status '%s', or anything suitable for type %u",
               status, presence);
    }
}


static void
presence_get_statuses_cb (TpProxy *proxy, const GValue *v_statuses,
			  const GError *error, gpointer user_data,
			  GObject *weak_object)
{
    McdConnectionPrivate *priv = user_data;
    McdConnection *connection = MCD_CONNECTION (weak_object);
    TpConnectionPresenceType presence;
    const gchar *status, *message;
    GHashTable *statuses;
    GHashTableIter iter;
    gpointer ht_key, ht_value;

    if (error)
    {
        g_warning ("%s: Get statuses failed for account %s: %s", G_STRFUNC,
                   mcd_account_get_unique_name (priv->account),
                   error->message);
        return;
    }
    else if (G_VALUE_TYPE (v_statuses) != TP_HASH_TYPE_STATUS_SPEC_MAP)
    {
        g_warning ("%s: Get(Statuses) returned the wrong type: %s",
                   mcd_account_get_unique_name (priv->account),
                   G_VALUE_TYPE_NAME (v_statuses));
        return;
    }

    if (!priv->recognized_presences)
        priv->recognized_presences =
            g_hash_table_new_full (g_str_hash, g_str_equal, g_free,
                                   (GDestroyNotify)mcd_presence_info_free);

    DEBUG ("account %s:", mcd_account_get_unique_name (priv->account));
    statuses = g_value_get_boxed (v_statuses);

    g_return_if_fail (statuses != NULL);

    /* This function can be called both before and after Connect() - before
     * CONNECTED the Connection tells us the presences it believes it will
     * probably support, and after CONNECTED it tells us the presences it
     * *actually* supports (which might be less numerous). */
    g_hash_table_remove_all (priv->recognized_presences);

    g_hash_table_iter_init (&iter, statuses);

    while (g_hash_table_iter_next (&iter, &ht_key, &ht_value))
    {
        GValueArray *va = ht_value;
        McdPresenceInfo *pi;

        status = ht_key;
        DEBUG ("  %s", status);

        pi = g_slice_new (McdPresenceInfo);
        pi->presence = g_value_get_uint (va->values);
        pi->may_set_on_self = g_value_get_boolean (va->values + 1);
        pi->can_have_message = g_value_get_boolean (va->values + 2);
        g_hash_table_insert (priv->recognized_presences,
                             g_strdup (status), pi);
    }

    /* Now the presence info is ready. We can set the presence */
    mcd_account_get_requested_presence (priv->account, &presence,
                                         &status, &message);
    if (priv->connected)
    {
        priv->presence_info_ready = TRUE;
    }

    _mcd_connection_set_presence (connection, presence, status, message);
}

static void
_mcd_connection_setup_presence (McdConnection *connection)
{
    McdConnectionPrivate *priv =  connection->priv;

    tp_cli_dbus_properties_call_get
        (priv->tp_conn, -1, TP_IFACE_CONNECTION_INTERFACE_PRESENCE1,
         "Statuses", presence_get_statuses_cb, priv, NULL,
         (GObject *)connection);
}

static void
disconnect_cb (TpConnection *proxy, const GError *error, gpointer user_data,
	       GObject *weak_object)
{
  if (error != NULL)
    WARNING ("Disconnect failed: %s", error->message);
  else
    DEBUG ("Disconnected %s", tp_proxy_get_object_path (TP_PROXY (proxy)));
}

static void
_mcd_connection_call_disconnect (McdConnection *connection,
                                 McdInhibit *inhibit)
{
    TpConnection *tp_conn = connection->priv->tp_conn;

    if (!tp_conn || tp_proxy_get_invalidated (TP_PROXY (tp_conn)) != NULL)
        return;

    if (tp_connection_get_status (tp_conn, NULL) ==
        TP_CONNECTION_STATUS_DISCONNECTED) return;
    tp_cli_connection_call_disconnect (tp_conn, -1, disconnect_cb,
        inhibit ? mcd_inhibit_hold (inhibit) : NULL,
        inhibit ? (GDestroyNotify) mcd_inhibit_release : NULL,
        NULL);

}

/* Update the presence of the tp_connection.
 *
 * Note, that the only presence transition not served by this function 
 * is getting to non-offline state since when presence is offline this object 
 * does not exist.
 *
 * So, here we just submit the request to the tp_connection object. The return off 
 * the operation is handled by (yet to be written) handler
 */
void
_mcd_connection_request_presence (McdConnection *self,
                                  TpConnectionPresenceType presence,
                                  const gchar *status, const gchar *message)
{
    g_return_if_fail (MCD_IS_CONNECTION (self));

    DEBUG ("Presence requested: %d", presence);
    if (presence == TP_CONNECTION_PRESENCE_TYPE_UNSET) return;

    if (presence == TP_CONNECTION_PRESENCE_TYPE_OFFLINE)
    {
        /* Connection Proxy */
        self->priv->abort_reason = TP_CONNECTION_STATUS_REASON_REQUESTED;
        mcd_mission_disconnect (MCD_MISSION (self));
        _mcd_connection_call_disconnect (self, NULL);

        /* if a reconnection attempt is scheduled, cancel it */
        if (self->priv->reconnect_timer)
        {
            g_source_remove (self->priv->reconnect_timer);
            self->priv->reconnect_timer = 0;
        }
    }
    else
    {
        _mcd_connection_set_presence (self, presence, status, message);
    }
}

static void
_foreach_channel_remove (McdMission * mission, McdOperation * operation)
{
    g_assert (MCD_IS_MISSION (mission));
    g_assert (MCD_IS_OPERATION (operation));

    mcd_operation_remove_mission (operation, mission);
}

static void
_mcd_connection_setup_power_saving (McdConnection *connection)
{
  McdConnectionPrivate *priv = connection->priv;

  if (priv->slacker == NULL)
    return;

  DEBUG ("is %sactive", mcd_slacker_is_inactive (priv->slacker) ? "in" : "");

  if (mcd_slacker_is_inactive (priv->slacker))
    tp_cli_connection_interface_power_saving1_call_set_power_saving (priv->tp_conn, -1,
        TRUE, NULL, NULL, NULL, NULL);
}

static gboolean
mcd_connection_reconnect (McdConnection *connection)
{
    DEBUG ("%p", connection);
    _mcd_connection_attempt (connection);
    return FALSE;
}

/* Number of seconds after which to assume the connection is basically stable.
 * If we have too many disconnections within this time, assume something
 * serious is wrong, and stop reconnecting. */
#define PROBATION_SEC 120
/* Maximum number of dropped connections within PROBATION_SEC. Connections
 * that never reached CONNECTED state don't count towards this limit, so we'll
 * keep retrying indefinitely for those (with exponential back-off). */
#define PROBATION_MAX_DROPPED 3

static gboolean
mcd_connection_probation_ended_cb (gpointer user_data)
{
    McdConnection *self = MCD_CONNECTION (user_data);
    McdConnectionPrivate *priv = MCD_CONNECTION_PRIV (self);

    /* We've been connected for PROBATION_SEC seconds. We can probably now
     * assume that the connection is stable */
    if (priv->tp_conn != NULL)
    {
        DEBUG ("probation finished, assuming connection is stable: %s",
               tp_proxy_get_object_path (self->priv->tp_conn));
        self->priv->probation_drop_count = 0;
        self->priv->reconnect_interval = INITIAL_RECONNECTION_TIME;
    }
    else /* probation timer survived beyond its useful life */
    {
        g_warning ("probation error: timer should have been removed when the "
                   "TpConnection was released");
    }

    self->priv->probation_timer = 0;

    return FALSE;
}

static void
on_connection_status_changed (TpConnection *tp_conn, GParamSpec *pspec,
			      McdConnection *connection)
{
    McdConnectionPrivate *priv = MCD_CONNECTION_PRIV (connection);
    TpConnectionStatus conn_status;
    TpConnectionStatusReason conn_reason;

    g_object_get (G_OBJECT (tp_conn),
		  "status", &conn_status,
		  "status-reason", &conn_reason,
		  NULL);
    DEBUG ("status_changed called from tp (%d)", conn_status);

    switch (conn_status)
    {
    case TP_CONNECTION_STATUS_CONNECTING:
        g_signal_emit (connection, signals[CONNECTION_STATUS_CHANGED], 0,
                       conn_status, conn_reason, tp_conn, NULL, NULL);
        priv->abort_reason = TP_CONNECTION_STATUS_REASON_NONE_SPECIFIED;
        priv->connected = FALSE;
        break;

    case TP_CONNECTION_STATUS_CONNECTED:
        {
            g_signal_emit (connection, signals[CONNECTION_STATUS_CHANGED], 0,
                           conn_status, conn_reason, tp_conn, NULL, NULL);

            if (priv->probation_timer == 0)
            {
                DEBUG ("setting probation timer (%d) seconds, for %s",
                       PROBATION_SEC, tp_proxy_get_object_path (tp_conn));
                priv->probation_timer = g_timeout_add_seconds (PROBATION_SEC,
                    mcd_connection_probation_ended_cb, connection);
                priv->probation_drop_count = 0;
            }

            priv->connected = TRUE;
        }
        break;

    case TP_CONNECTION_STATUS_DISCONNECTED:
	/* Connection could die during account status updated if its
	 * manager is the only one holding the reference to it (manager will
	 * remove the connection from itself). To ensure we get a chance to
	 * emit abort signal (there could be others holding a ref to it), we
	 * will hold a temporary ref to it.
	 */
	priv->abort_reason = conn_reason;
        /* priv->connected will be reset to FALSE in the invalidated
         * callback */
	break;

    default:
	g_warning ("Unknown telepathy connection status");
    }
}

static gboolean
connection_should_reconnect (TpConnection *tp_conn,
                             guint domain,
                             gint code)
{
    TpConnectionStatusReason reason;

    if (domain == TP_ERROR)
    {
        switch (code)
        {
        case TP_ERROR_CONNECTION_FAILED:
        case TP_ERROR_CONNECTION_LOST:
        case TP_ERROR_DISCONNECTED:
        case TP_ERROR_NETWORK_ERROR:
            DEBUG ("error code %s, reconnecting",
                tp_error_get_dbus_name (code));
            return TRUE;

        case TP_ERROR_SOFTWARE_UPGRADE_REQUIRED:
        case TP_ERROR_SERVICE_BUSY:
        case TP_ERROR_CONNECTION_REPLACED:
        case TP_ERROR_ALREADY_CONNECTED:
        case TP_ERROR_CONNECTION_REFUSED:
        case TP_ERROR_INVALID_ARGUMENT:
        case TP_ERROR_INVALID_HANDLE:
        case TP_ERROR_CANCELLED:
        case TP_ERROR_AUTHENTICATION_FAILED:
        case TP_ERROR_ENCRYPTION_NOT_AVAILABLE:
        case TP_ERROR_ENCRYPTION_ERROR:
        case TP_ERROR_CERT_NOT_PROVIDED:
        case TP_ERROR_CERT_UNTRUSTED:
        case TP_ERROR_CERT_EXPIRED:
        case TP_ERROR_CERT_NOT_ACTIVATED:
        case TP_ERROR_CERT_FINGERPRINT_MISMATCH:
        case TP_ERROR_CERT_HOSTNAME_MISMATCH:
        case TP_ERROR_CERT_SELF_SIGNED:
        case TP_ERROR_CERT_INVALID:
        case TP_ERROR_CERT_REVOKED:
        case TP_ERROR_CERT_INSECURE:
        case TP_ERROR_CERT_LIMIT_EXCEEDED:
            DEBUG ("error code %s, not reconnecting",
                tp_error_get_dbus_name (code));
            return FALSE;

        default:
            DEBUG ("TpError code %s not handled",
                tp_error_get_dbus_name (code));
        }
    }
    else if (domain == TP_DBUS_ERRORS)
    {
        switch (code)
        {
        case TP_DBUS_ERROR_NAME_OWNER_LOST:
            /* CM crashed */
            DEBUG ("dbus error code: OWNER_LOST, reconnecting");
            return TRUE;
        }
    }

    /* not sure what the GError meant, so check the generic status code */
    tp_connection_get_status (tp_conn, &reason);

    switch (reason)
    {
    case TP_CONNECTION_STATUS_REASON_NETWORK_ERROR:
        DEBUG ("StatusReason %d, reconnecting", reason);
        return TRUE;
    default:
        break;
    }

    DEBUG ("not reconnecting");

    return FALSE;
}

static void
mcd_connection_invalidated_cb (TpConnection *tp_conn,
                               guint domain,
                               gint code,
                               gchar *message,
                               McdConnection *connection)
{
    McdConnectionPrivate *priv = MCD_CONNECTION_PRIV (connection);

    DEBUG ("Proxy destroyed (%s)!", message);

    _mcd_connection_release_tp_connection (connection, NULL, FALSE);

    if (priv->connected &&
        priv->abort_reason != TP_CONNECTION_STATUS_REASON_REQUESTED &&
        priv->probation_timer != 0)
    {
        DEBUG ("connection dropped while on probation: %s",
               tp_proxy_get_object_path (tp_conn));

        if (++priv->probation_drop_count > PROBATION_MAX_DROPPED)
        {
            DEBUG ("connection dropped too many times, will stop "
                   "reconnecting");
        }
    }

    priv->connected = FALSE;

    if (connection_should_reconnect (tp_conn, domain, code) &&
        priv->probation_drop_count <= PROBATION_MAX_DROPPED)
    {
        /* we were disconnected by a network error or by a connection manager
         * crash (in the latter case, we get NoneSpecified as a reason): don't
         * abort the connection but try to reconnect later */
        if (priv->reconnect_timer == 0)
        {
            DEBUG ("Preparing for reconnection in %u seconds",
                priv->reconnect_interval);
            priv->reconnect_timer = g_timeout_add_seconds
                (priv->reconnect_interval,
                 (GSourceFunc)mcd_connection_reconnect, connection);
            priv->reconnect_interval *= RECONNECTION_MULTIPLIER;

            if (priv->reconnect_interval >= MAXIMUM_RECONNECTION_TIME)
                priv->reconnect_interval = MAXIMUM_RECONNECTION_TIME;
        }
    }
    else
    {
	g_object_ref (connection);
	/* Notify connection abort */
	mcd_mission_abort (MCD_MISSION (connection));
	g_object_unref (connection);
    }
}

static void
connect_cb (TpConnection *tp_conn, const GError *error,
		      gpointer user_data, GObject *weak_object)
{
    McdConnection *connection = MCD_CONNECTION (weak_object);

    DEBUG ("called for connection %p", connection);

    if (error)
    {
	g_warning ("%s: tp_conn_connect failed: %s",
		   G_STRFUNC, error->message);
    }
}

static gboolean
_mcd_connection_request_channel (McdConnection *connection,
                                 McdChannel *channel);

static void
request_unrequested_channels (McdConnection *connection)
{
    const GList *channels;

    channels = mcd_operation_get_missions ((McdOperation *)connection);

    DEBUG ("called");
    /* go through the channels that were requested while the connection was not
     * ready, and process them */
    while (channels)
    {
	McdChannel *channel = MCD_CHANNEL (channels->data);

        if (mcd_channel_get_status (channel) == MCD_CHANNEL_STATUS_REQUEST)
        {
            DEBUG ("Requesting channel %p", channel);
            mcd_connection_request_channel (connection, channel);
        }
        channels = channels->next;
    }
}

McdChannel *
mcd_connection_find_channel_by_path (McdConnection *connection,
                      const gchar *object_path)
{
    const GList *list = NULL;

    list = mcd_operation_get_missions (MCD_OPERATION (connection));

    while (list)
    {
        McdChannel *channel = MCD_CHANNEL (list->data);

        if (_mcd_channel_is_primary_for_path (channel, object_path))
        {
            return channel;
        }

        list = list->next;
    }
    return NULL;
}

static gboolean mcd_connection_need_dispatch (McdConnection *connection,
                                              const gchar *object_path,
                                              GHashTable *props);

static void
on_new_channel (TpConnection *proxy,
                const gchar *object_path,
                GHashTable *props,
                gpointer user_data,
                GObject *weak_object)
{
    McdConnection *connection = MCD_CONNECTION (weak_object);
    McdConnectionPrivate *priv = user_data;
    GValue *value;
    gboolean requested = FALSE;
    gboolean only_observe = FALSE;
    McdChannel *channel;

    if (DEBUGGING)
    {
        GHashTableIter iter;
        gpointer k, v;

        DEBUG ("%s", object_path);

        g_hash_table_iter_init (&iter, props);

        while (g_hash_table_iter_next (&iter, &k, &v))
        {
            gchar *repr = g_strdup_value_contents (v);

            DEBUG("  \"%s\" => %s", (const gchar *) k, repr);
            g_free (repr);
        }
    }

    /* we can completely ignore the channels that arrive while this is
     * FALSE: they'll also be in Channels in the GetAll(Requests) result */
    if (!priv->dispatched_initial_channels) return;

    sp_timestamp ("NewChannel received");

    only_observe = !mcd_connection_need_dispatch (connection, object_path,
                                                  props);

    /* Don't do anything for requested channels */
    value = g_hash_table_lookup (props, TP_IFACE_CHANNEL ".Requested");
    if (value && g_value_get_boolean (value))
        requested = TRUE;

    /* if the channel was a request, we already have an object for it;
     * otherwise, create a new one */
    channel = mcd_connection_find_channel_by_path (connection, object_path);
    if (!channel)
    {
        channel = mcd_channel_new_from_properties (proxy, object_path,
                                                   props);
        if (G_UNLIKELY (!channel))
            return;

        mcd_operation_take_mission (MCD_OPERATION (connection),
                                    MCD_MISSION (channel));
    }

    if (!requested)
    {
        /* we always dispatch unrequested (incoming) channels */
        only_observe = FALSE;
    }

    _mcd_dispatcher_add_channel (priv->dispatcher, channel, requested,
                                     only_observe);
}

static void
mcd_connection_recover_channel (McdConnection *connection,
                                const gchar *object_path,
                                const GHashTable *properties)
{
    McdConnectionPrivate *priv = connection->priv;
    McdChannel *channel;

    DEBUG ("called for %s", object_path);
    channel = mcd_channel_new_from_properties (priv->tp_conn, object_path,
                                               properties);
    if (G_UNLIKELY (!channel)) return;

    mcd_operation_take_mission (MCD_OPERATION (connection),
                                MCD_MISSION (channel));

    _mcd_dispatcher_recover_channel (priv->dispatcher, channel,
      mcd_account_get_object_path (priv->account));
}

static void
mcd_connection_found_channel (McdConnection *self,
                              const gchar *object_path,
                              GHashTable *channel_props)
{
    const GList *list;
    gboolean found = FALSE;

    /* find the McdChannel */
    /* NOTE: we cannot move the mcd_operation_get_missions() call out of
     * the loop, because mcd_dispatcher_send() can cause the channel to be
     * destroyed, at which point our list would contain a finalized channel
     * (and a crash will happen) */
    list = mcd_operation_get_missions ((McdOperation *) self);
    for (; list != NULL; list = list->next)
    {
        McdChannel *channel = MCD_CHANNEL (list->data);

        if (g_strcmp0 (object_path,
                       mcd_channel_get_object_path (channel)) == 0)
        {
            found = TRUE;
            break;
        }

        if (mcd_channel_get_status (channel) !=
            MCD_CHANNEL_STATUS_UNDISPATCHED)
            continue;
    }

    if (!found)
    {
        /* We don't have a McdChannel for this channel, which most likely
         * means that it was already present on the connection before MC
         * started. Let's try to recover it */
        mcd_connection_recover_channel (self, object_path, channel_props);
    }
}

static void get_all_requests_cb (TpProxy *proxy, GHashTable *properties,
                                 const GError *error, gpointer user_data,
                                 GObject *weak_object)
{
    McdConnection *connection = MCD_CONNECTION (weak_object);
    McdConnectionPrivate *priv = user_data;
    GPtrArray *channels;
    GValue *value;
    guint i;

    if (error)
    {
        g_warning ("%s got error: %s", G_STRFUNC, error->message);
        return;
    }

    value = g_hash_table_lookup (properties, "Channels");

    if (value == NULL)
    {
        g_warning ("%s: no Channels property on %s",
                   G_STRFUNC, tp_proxy_get_object_path (proxy));
        return;
    }

    if (!G_VALUE_HOLDS (value, TP_ARRAY_TYPE_CHANNEL_DETAILS_LIST))
    {
        g_warning ("%s: property Channels has type %s, expecting %s",
                   G_STRFUNC, G_VALUE_TYPE_NAME (value),
                   g_type_name (TP_ARRAY_TYPE_CHANNEL_DETAILS_LIST));
        return;
    }

    channels = g_value_get_boxed (value);
    for (i = 0; i < channels->len; i++)
    {
        GValueArray *va;
        const gchar *object_path;
        GHashTable *channel_props;

        va = g_ptr_array_index (channels, i);
        object_path = g_value_get_boxed (va->values);
        channel_props = g_value_get_boxed (va->values + 1);

        if (DEBUGGING)
        {
            GHashTableIter iter;
            gpointer k, v;

            DEBUG ("%s", object_path);

            g_hash_table_iter_init (&iter, channel_props);

            while (g_hash_table_iter_next (&iter, &k, &v))
            {
                gchar *repr = g_strdup_value_contents (v);

                DEBUG("  \"%s\" => %s", (const gchar *) k, repr);
                g_free (repr);
            }
        }

        mcd_connection_found_channel (connection, object_path, channel_props);
    }

    priv->dispatched_initial_channels = TRUE;
}

static void
mcd_connection_setup_requests (McdConnection *connection)
{
    McdConnectionPrivate *priv = connection->priv;

    /*
     * 1. connect to the NewChannel
     * 2. get existing channels
     * 3. disconnect from NewChannel
     * 4. dispatch the UNDISPATCHED
     */
    tp_cli_connection_interface_requests_connect_to_new_channel
        (priv->tp_conn, on_new_channel, priv, NULL,
         (GObject *)connection, NULL);

    tp_cli_dbus_properties_call_get_all (priv->tp_conn, -1,
        TP_IFACE_CONNECTION_INTERFACE_REQUESTS,
        get_all_requests_cb, priv, NULL, (GObject *)connection);
}

static void
on_connection_ready (GObject *source_object, GAsyncResult *result,
                     gpointer user_data)
{
    TpConnection *tp_conn = TP_CONNECTION (source_object);
    TpWeakRef *weak_ref = user_data;
    McdConnection *connection = tp_weak_ref_dup_object (weak_ref);
    McdConnectionPrivate *priv;
    GError *error = NULL;

    if (!tp_proxy_prepare_finish (tp_conn, result, &error))
    {
        DEBUG ("got error: %s", error->message);
        g_clear_error (&error);
        goto finally;
    }

    if (!connection)
        goto finally;

    DEBUG ("connection is ready");
    priv = MCD_CONNECTION_PRIV (connection);

    if (tp_proxy_has_interface_by_id (tp_conn,
        TP_IFACE_QUARK_CONNECTION_INTERFACE_SERVICE_POINT1))
    {
        mcd_connection_service_point_setup (connection,
                                            !priv->service_points_watched);
        priv->service_points_watched = TRUE;
    }

    priv->has_presence_if = tp_proxy_has_interface_by_id
        (tp_conn, TP_IFACE_QUARK_CONNECTION_INTERFACE_PRESENCE1);
    priv->has_contact_capabilities_if = tp_proxy_has_interface_by_id (tp_conn,
        TP_IFACE_QUARK_CONNECTION_INTERFACE_CONTACT_CAPABILITIES1);
    priv->has_power_saving_if = tp_proxy_has_interface_by_id (tp_conn,
        TP_IFACE_QUARK_CONNECTION_INTERFACE_POWER_SAVING1);

    if (priv->has_presence_if)
	_mcd_connection_setup_presence (connection);

    if (priv->has_power_saving_if)
      _mcd_connection_setup_power_saving (connection);

    if (!priv->dispatching_started)
        _mcd_dispatcher_add_connection (priv->dispatcher, connection);

    request_unrequested_channels (connection);

    g_signal_emit (connection, signals[READY], 0);

finally:
    g_clear_object (&connection);
    tp_weak_ref_destroy (weak_ref);
}

void
_mcd_connection_start_dispatching (McdConnection *self,
                                   GPtrArray *client_caps)
{
    g_return_if_fail (MCD_IS_CONNECTION (self));
    g_return_if_fail (!self->priv->dispatching_started);

    DEBUG ("%p", self);

    self->priv->dispatching_started = TRUE;

    mcd_connection_setup_requests (self);

    /* FIXME: why is this here? if we need to update caps before and after   *
     * connected, it should be in the call_when_ready callback.              */
    _mcd_connection_update_client_caps (self, client_caps);
}

void
_mcd_connection_update_client_caps (McdConnection *self,
                                    GPtrArray *client_caps)
{
    g_return_if_fail (MCD_IS_CONNECTION (self));

    if (!self->priv->has_contact_capabilities_if)
    {
        DEBUG ("ContactCapabilities unsupported");
        return;
    }

    DEBUG ("Sending client caps to connection");
    tp_cli_connection_interface_contact_capabilities1_call_update_capabilities
      (self->priv->tp_conn, -1, client_caps, NULL, NULL, NULL, NULL);
}

static void
mcd_connection_done_task_before_connect (McdConnection *self)
{
    if (--self->priv->tasks_before_connect == 0)
    {
        if (self->priv->tp_conn == NULL)
        {
            DEBUG ("TpConnection went away, not doing anything");
        }

        _mcd_dispatcher_add_connection (self->priv->dispatcher, self);

        DEBUG ("%s: Calling Connect()",
               tp_proxy_get_object_path (self->priv->tp_conn));
        tp_cli_connection_call_connect (self->priv->tp_conn, -1, connect_cb,
                                        self->priv, NULL, (GObject *) self);
    }
}

static void
mcd_connection_early_get_statuses_cb (TpProxy *proxy,
                                      const GValue *v_statuses,
                                      const GError *error,
                                      gpointer user_data,
                                      GObject *weak_object)
{
    McdConnection *self = MCD_CONNECTION (weak_object);

    if (self->priv->tp_conn != (TpConnection *) proxy)
    {
        DEBUG ("Connection %p has been replaced with %p, stopping",
               proxy, self->priv->tp_conn);
        return;
    }

    /* This is before we called Connect(), and may or may not be before
     * connection-ready has been signalled. */

    if (error == NULL)
    {
        DEBUG ("%s: Early Get(Statuses) succeeded",
               tp_proxy_get_object_path (proxy));

        /* This will trigger a call to SetPresence, but don't wait for that to
         * finish before calling Connect (there's no need to). */
        presence_get_statuses_cb (proxy, v_statuses, error, self->priv,
                                  weak_object);
    }
    else
    {
        DEBUG ("%s: Early Get(Statuses) failed (not a problem, will try "
               "again later): %s #%d: %s",
               tp_proxy_get_object_path (proxy),
               g_quark_to_string (error->domain), error->code, error->message);
    }

    mcd_connection_done_task_before_connect (self);
}

static void
mcd_connection_early_get_interfaces_cb (TpProxy *proxy,
                                        const GValue *value,
                                        const GError *error,
                                        gpointer user_data,
                                        GObject *weak_object)
{
    TpConnection *tp_conn = TP_CONNECTION (proxy);
    McdConnection *self = MCD_CONNECTION (weak_object);
    const gchar **iter;

    if (self->priv->tp_conn != tp_conn)
    {
        DEBUG ("Connection %p has been replaced with %p, stopping",
               tp_conn, self->priv->tp_conn);
        return;
    }

    if (error != NULL)
    {
        DEBUG ("%s: Early GetInterfaces failed (not a problem, will try "
               "again later): %s #%d: %s",
               tp_proxy_get_object_path (tp_conn),
               g_quark_to_string (error->domain), error->code, error->message);
    }
    else if (G_VALUE_HOLDS (value, G_TYPE_STRV))
    {
        for (iter = g_value_get_boxed (value);
             iter != NULL && *iter != NULL;
             iter++)
        {
            GQuark q = g_quark_try_string (*iter);

            /* if the interface is not recognised, q will just be 0 */

            if (q == TP_IFACE_QUARK_CONNECTION_INTERFACE_PRESENCE1)
            {
                /* nail on the interface (TpConnection will eventually know
                 * how to do this for itself) */
                tp_proxy_add_interface_by_id ((TpProxy *) tp_conn, q);
                self->priv->has_presence_if = TRUE;

                self->priv->tasks_before_connect++;

                tp_cli_dbus_properties_call_get (tp_conn, -1,
                    TP_IFACE_CONNECTION_INTERFACE_PRESENCE1, "Statuses",
                    mcd_connection_early_get_statuses_cb, NULL, NULL,
                    (GObject *) self);
            }
            else if (q == TP_IFACE_QUARK_CONNECTION_INTERFACE_CONTACT_CAPABILITIES1)
            {
                GPtrArray *client_caps;

                /* nail on the interface (TpConnection will eventually know
                 * how to do this for itself) */
                tp_proxy_add_interface_by_id ((TpProxy *) tp_conn, q);
                self->priv->has_contact_capabilities_if = TRUE;

                /* we don't need to delay Connect for this, it can be
                 * fire-and-forget */

                client_caps = _mcd_dispatcher_dup_client_caps (
                    self->priv->dispatcher);

                if (client_caps != NULL)
                {
                    _mcd_connection_update_client_caps (self, client_caps);
                    g_ptr_array_foreach (client_caps,
                                         (GFunc) g_value_array_free, NULL);
                    g_ptr_array_unref (client_caps);
                }
                /* else the McdDispatcher hasn't sorted itself out yet, so
                 * we can't usefully pre-load capabilities - we'll be told
                 * the real capabilities as soon as it has worked them out */
            }
        }
    }
    else
    {
        DEBUG ("%s: Early GetInterfaces returned unexpected type %s",
               tp_proxy_get_object_path (tp_conn),
               G_VALUE_TYPE_NAME (value));
    }

    mcd_connection_done_task_before_connect (self);
}

static gchar *
translate_g_error (GQuark domain,
    gint code,
    const gchar *message)
{
  if (domain == TP_ERROR)
    {
      return g_strdup (tp_error_get_dbus_name (code));
    }
  else if (domain == TP_DBUS_ERRORS)
    {
      switch (code)
        {
        case TP_DBUS_ERROR_UNKNOWN_REMOTE_ERROR:
            {
              const gchar *p = strchr (message, ':');

              if (p != NULL)
                {
                  gchar *tmp = g_strndup (message, message - p);

                  /* The syntactic restrictions for error names are the same
                   * as for interface names. */
                  if (g_dbus_is_interface_name (tmp))
                    return tmp;

                  g_free (tmp);
                }
            }
          break;

        case TP_DBUS_ERROR_NO_INTERFACE:
          return g_strdup (DBUS_ERROR_UNKNOWN_INTERFACE);

        case TP_DBUS_ERROR_NAME_OWNER_LOST:
          return g_strdup (DBUS_ERROR_NAME_HAS_NO_OWNER);
        }
    }

  /* catch-all */
  return g_strdup (DBUS_ERROR_FAILED);
}

static void
request_connection_cb (TpConnectionManager *proxy, const gchar *bus_name,
                       const gchar *obj_path, const GError *tperror,
                       gpointer user_data, GObject *weak_object)
{
    TpWeakRef *weak_ref = user_data;
    McdConnection *connection = tp_weak_ref_dup_object (weak_ref);
    McdConnectionPrivate *priv;
    GError *error = NULL;

    if (connection == NULL || connection->priv->closed)
    {
        DEBUG ("RequestConnection returned after we'd decided not to use this "
               "connection");

        /* We no longer want this connection, in fact */
        if (tperror != NULL)
        {
            DEBUG ("It failed anyway: %s", tperror->message);
        }
        else
        {
            /* no point in making a TpConnection for something we're just
             * going to throw away */
            DBusGProxy *tmp_proxy = dbus_g_proxy_new_for_name
                (tp_proxy_get_dbus_connection (proxy),
                 bus_name, obj_path, TP_IFACE_CONNECTION);

            DEBUG ("Disconnecting it: %s", obj_path);
            dbus_g_proxy_call_no_reply (tmp_proxy, "Disconnect",
                                        G_TYPE_INVALID);
            g_object_unref (tmp_proxy);
        }

        if (connection != NULL)
        {
            g_signal_emit (connection, signals[CONNECTION_STATUS_CHANGED], 0,
                           TP_CONNECTION_STATUS_DISCONNECTED,
                           TP_CONNECTION_STATUS_REASON_REQUESTED,
                           NULL, "", NULL);
        }

        goto finally;
    }

    priv = connection->priv;

    if (tperror)
    {
        gchar *dbus_error = translate_g_error (tperror->domain,
            tperror->code, tperror->message);
        GHashTable *details = tp_asv_new (
            "debug-message", G_TYPE_STRING, tperror->message,
            NULL);

        g_warning ("%s: RequestConnection failed: %s",
                   G_STRFUNC, tperror->message);

        g_signal_emit (connection, signals[CONNECTION_STATUS_CHANGED], 0,
            TP_CONNECTION_STATUS_DISCONNECTED,
            TP_CONNECTION_STATUS_REASON_NONE_SPECIFIED, NULL,
            dbus_error, details);
        g_hash_table_unref (details);
        g_free (dbus_error);
        goto finally;
    }

    DEBUG ("created %s", obj_path);

    _mcd_connection_set_tp_connection (connection, bus_name, obj_path, &error);
    if (G_UNLIKELY (error))
    {
        g_warning ("%s: got error: %s", G_STRFUNC, error->message);
	g_error_free (error);
        goto finally;
    }

    priv->tasks_before_connect = 1;

    /* TpConnection doesn't yet know how to get this information before
     * the Connection goes to CONNECTED, so we'll have to do it ourselves */
    tp_cli_dbus_properties_call_get (priv->tp_conn, -1,
        TP_IFACE_CONNECTION, "Interfaces",
        mcd_connection_early_get_interfaces_cb, NULL, NULL,
        (GObject *) connection);

finally:
    g_clear_object (&connection);
    /* weak_ref is freed by the telepathy-glib call's destructor */
}

static void
_mcd_connection_connect_with_params (McdConnection *connection,
                                     GHashTable *params)
{
    McdConnectionPrivate *priv = connection->priv;
    const gchar *protocol_name;

    protocol_name = mcd_account_get_protocol_name (priv->account);

    DEBUG ("Trying connect account: %s",
           mcd_account_get_unique_name (priv->account));

    g_signal_emit (connection, signals[CONNECTION_STATUS_CHANGED], 0,
                   TP_CONNECTION_STATUS_CONNECTING,
                   TP_CONNECTION_STATUS_REASON_REQUESTED, NULL, NULL, NULL);

    /* If the McdConnection gets aborted (which results in it being freed!),
     * we need to kill off the Connection. So, we can't use connection as the
     * weak_object.
     *
     * A better design in MC 5.3.x would be for the McdConnection to have
     * a ref held for the duration of this call, not be freed, and signal
     * that it is no longer useful in some way other than getting aborted. */
    tp_cli_connection_manager_call_request_connection (priv->tp_conn_mgr, -1,
        protocol_name, params, request_connection_cb,
        tp_weak_ref_new (connection, NULL, NULL),
        (GDestroyNotify) tp_weak_ref_destroy, NULL);
}

static void
_mcd_connection_finalize (GObject * object)
{
    McdConnection *connection = MCD_CONNECTION (object);
    McdConnectionPrivate *priv = MCD_CONNECTION_PRIV (connection);

    if (priv->recognized_presences)
        g_hash_table_unref (priv->recognized_presences);

    tp_clear_pointer (&priv->service_point_handles, tp_intset_destroy);
    tp_clear_pointer (&priv->service_point_ids, g_hash_table_unref);

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

static void
_mcd_connection_release_tp_connection (McdConnection *connection,
                                       McdInhibit *inhibit,
                                       gboolean already_signalled)
{
    McdConnectionPrivate *priv = MCD_CONNECTION_PRIV (connection);

    DEBUG ("%p", connection);

    if (already_signalled)
    {
        DEBUG ("already emitted connection-status-changed");
    }
    else if (priv->abort_reason == TP_CONNECTION_STATUS_REASON_REQUESTED)
    {
        g_signal_emit (connection, signals[CONNECTION_STATUS_CHANGED], 0,
                       TP_CONNECTION_STATUS_DISCONNECTED,
                       priv->abort_reason, priv->tp_conn, "", NULL);
    }
    else
    {
        const gchar *dbus_error = NULL;
        const GHashTable *details = NULL;

        if (priv->tp_conn != NULL)
        {
            dbus_error = tp_connection_get_detailed_error (priv->tp_conn,
                &details);
        }

        g_signal_emit (connection, signals[CONNECTION_STATUS_CHANGED], 0,
                       TP_CONNECTION_STATUS_DISCONNECTED,
                       priv->abort_reason, priv->tp_conn, dbus_error, details);
    }

    if (priv->tp_conn)
    {
	/* Disconnect signals */
	g_signal_handlers_disconnect_by_func (priv->tp_conn,
					      G_CALLBACK (on_connection_status_changed),
					      connection);
        g_signal_handlers_disconnect_by_func (G_OBJECT (priv->tp_conn),
            G_CALLBACK (mcd_connection_invalidated_cb), connection);

        _mcd_connection_call_disconnect (connection, inhibit);

        /* the tp_connection has gone away, so we no longer need (or want) *
           the probation timer to go off: there's nothing for it to check  */
        if (priv->probation_timer > 0)
        {
            g_source_remove (priv->probation_timer);
            priv->probation_timer = 0;
        }

        tp_clear_object (&priv->tp_conn);
    }

    if (priv->recognized_presences)
        g_hash_table_remove_all (priv->recognized_presences);

  priv->dispatching_started = FALSE;
}

static void
on_account_removed (McdAccount *account, McdConnection *connection)
{
    DEBUG ("Account %s removed, aborting connection",
             mcd_account_get_unique_name (account));
    mcd_mission_abort (MCD_MISSION (connection));
}

static void
on_inactivity_changed (McdSlacker *slacker,
    gboolean inactive,
    McdConnection *self)
{
  McdConnectionPrivate *priv = self->priv;
  DEBUG ("%sactive, connection %s have power saving iface.", inactive ? "in" : "",
      priv->has_power_saving_if ? "does" : "doesn't");

  if (priv->tp_conn != NULL && priv->has_power_saving_if)
    tp_cli_connection_interface_power_saving1_call_set_power_saving (priv->tp_conn, -1,
        inactive, NULL, NULL, NULL, NULL);
}

static void
_mcd_connection_constructed (GObject * object)
{
    McdConnection *self = MCD_CONNECTION (object);
    McdConnectionPrivate *priv = self->priv;

    if (priv->slacker != NULL)
      g_signal_connect (priv->slacker, "inactivity-changed",
          G_CALLBACK (on_inactivity_changed), self);
}

static void
_mcd_connection_dispose (GObject * object)
{
    McdConnection *connection = MCD_CONNECTION (object);
    McdConnectionPrivate *priv = MCD_CONNECTION_PRIV (connection);

    DEBUG ("called for object %p", object);

    if (priv->is_disposed)
    {
	return;
    }

    priv->is_disposed = TRUE;

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

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

    mcd_operation_foreach (MCD_OPERATION (connection),
			   (GFunc) _foreach_channel_remove, connection);

    _mcd_connection_release_tp_connection (connection, NULL, FALSE);
    g_assert (priv->tp_conn == NULL);

    if (priv->account)
    {
        g_signal_handlers_disconnect_by_func (priv->account,
                                              G_CALLBACK (on_account_removed),
                                              object);
        tp_clear_object (&priv->account);
    }

    if (priv->slacker != NULL)
      {
        g_signal_handlers_disconnect_by_func (priv->slacker,
                                              G_CALLBACK (on_inactivity_changed),
                                              connection);

        tp_clear_object (&priv->slacker);
      }

    tp_clear_object (&priv->tp_conn_mgr);
    tp_clear_object (&priv->dispatcher);
    tp_clear_object (&priv->client_factory);

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

static void
_mcd_connection_set_property (GObject * obj, guint prop_id,
			      const GValue * val, GParamSpec * pspec)
{
    McdDispatcher *dispatcher;
    McdAccount *account;
    TpConnectionManager *tp_conn_mgr;
    McdConnectionPrivate *priv = MCD_CONNECTION_PRIV (obj);

    switch (prop_id)
    {
    case PROP_DISPATCHER:
	dispatcher = g_value_get_object (val);
	if (dispatcher)
	{
	    g_return_if_fail (MCD_IS_DISPATCHER (dispatcher));
	    g_object_ref (dispatcher);
	}
	tp_clear_object (&priv->dispatcher);
	priv->dispatcher = dispatcher;
	break;

    case PROP_CLIENT_FACTORY:
        g_assert (priv->client_factory == NULL); /* construct-only */
        priv->client_factory = g_value_dup_object (val);
        break;

    case PROP_TP_MANAGER:
	tp_conn_mgr = g_value_get_object (val);
	g_object_ref (tp_conn_mgr);
	tp_clear_object (&priv->tp_conn_mgr);
	priv->tp_conn_mgr = tp_conn_mgr;
	break;
    case PROP_ACCOUNT:
	account = g_value_get_object (val);
	g_return_if_fail (MCD_IS_ACCOUNT (account));
	g_object_ref (account);
	priv->account = account;
        g_signal_connect (priv->account, "removed",
                          G_CALLBACK (on_account_removed),
                          obj);
        _mcd_account_set_connection (account, MCD_CONNECTION (obj));
	break;
    case PROP_SLACKER:
      g_assert (priv->slacker == NULL);
      priv->slacker = g_value_dup_object (val);
    break;
    default:
	G_OBJECT_WARN_INVALID_PROPERTY_ID (obj, prop_id, pspec);
	break;
    }
}

static void
_mcd_connection_get_property (GObject * obj, guint prop_id,
			      GValue * val, GParamSpec * pspec)
{
    McdConnectionPrivate *priv = MCD_CONNECTION_PRIV (obj);

    switch (prop_id)
    {
    case PROP_ACCOUNT:
	g_value_set_object (val, priv->account);
	break;
    case PROP_TP_MANAGER:
	g_value_set_object (val, priv->tp_conn_mgr);
	break;
    case PROP_TP_CONNECTION:
	g_value_set_object (val, priv->tp_conn);
	break;
    case PROP_DISPATCHER:
	g_value_set_object (val, priv->dispatcher);
	break;
    case PROP_SLACKER:
      g_value_set_object (val, priv->slacker);
	break;
    default:
	G_OBJECT_WARN_INVALID_PROPERTY_ID (obj, prop_id, pspec);
	break;
    }
}

/*
 * mcd_connection_need_dispatch:
 * @connection: the #McdConnection.
 * @object_path: the object path of the new channel (only for debugging)
 * @props: the properties of the new channel
 *
 * This functions must be called in response to a NewChannel signals, and is
 * responsible for deciding whether MC must handle the channels or not.
 */
static gboolean
mcd_connection_need_dispatch (McdConnection *connection,
                              const gchar *object_path,
                              GHashTable *props)
{
    McdAccount *account = mcd_connection_get_account (connection);
    gboolean requested = FALSE, requested_by_us = FALSE;

    if (_mcd_account_needs_dispatch (account))
    {
        DEBUG ("Account %s must always be dispatched, bypassing checks",
               mcd_account_get_object_path (account));
        return TRUE;
    }

    /* We must _not_ handle channels that have the Requested flag set but that
     * have no McdChannel object associated: these are the channels directly
     * requested to the CM by some other application, and we must ignore them
     */

    requested = tp_asv_get_boolean (props, TP_IFACE_CHANNEL ".Requested",
                                    NULL);
    if (requested)
    {
        if (mcd_connection_find_channel_by_path (connection, object_path))
            requested_by_us = TRUE;
    }

    /* handle only bundles which were not requested or that were requested
     * through MC */
    return !requested || requested_by_us;
}

gboolean
_mcd_connection_target_id_is_urgent (McdConnection *self,
    const gchar *name)
{
  return self->priv->service_point_ids != NULL &&
      g_hash_table_contains (self->priv->service_point_ids, name);
}

gboolean
_mcd_connection_target_handle_is_urgent (McdConnection *self,
    guint handle)
{
  return self->priv->service_point_handles != NULL &&
      tp_intset_is_member (self->priv->service_point_handles, handle);
}

static gboolean
_mcd_connection_request_channel (McdConnection *connection,
                                 McdChannel *channel)
{
    McdConnectionPrivate *priv = MCD_CONNECTION_PRIV (connection);
    gboolean ret;

    g_return_val_if_fail (priv->tp_conn != NULL, FALSE);
    g_return_val_if_fail (TP_IS_CONNECTION (priv->tp_conn), FALSE);

    if (!tp_proxy_is_prepared (priv->tp_conn, TP_CONNECTION_FEATURE_CONNECTED))
    {
        /* don't request any channel until the connection is ready (because we
         * don't know if the CM implements the Requests interface). The channel
         * will be processed once the connection is ready */
        return TRUE;
    }

    ret = request_channel_new_iface (connection, channel);

    if (ret)
        _mcd_channel_set_status (channel, MCD_CHANNEL_STATUS_REQUESTED);
    return ret;
}

static void
mcd_connection_class_init (McdConnectionClass * klass)
{
    GObjectClass *object_class = G_OBJECT_CLASS (klass);
    g_type_class_add_private (object_class, sizeof (McdConnectionPrivate));

    object_class->finalize = _mcd_connection_finalize;
    object_class->dispose = _mcd_connection_dispose;
    object_class->constructed = _mcd_connection_constructed;
    object_class->set_property = _mcd_connection_set_property;
    object_class->get_property = _mcd_connection_get_property;

    _mcd_ext_register_dbus_glib_marshallers ();

    tp_connection_init_known_interfaces ();

    /* Properties */
    g_object_class_install_property
        (object_class, PROP_DISPATCHER,
         g_param_spec_object ("dispatcher",
                              "Dispatcher",
                              "Dispatcher",
                              MCD_TYPE_DISPATCHER,
                              G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));

    g_object_class_install_property (object_class, PROP_CLIENT_FACTORY,
        g_param_spec_object ("client-factory", "Client factory",
            "Client factory", TP_TYPE_CLIENT_FACTORY,
            G_PARAM_WRITABLE | G_PARAM_CONSTRUCT_ONLY));

    g_object_class_install_property
        (object_class, PROP_TP_MANAGER,
         g_param_spec_object ("tp-manager",
                              "Telepathy Manager",
                              "Telepathy Manager",
                              TP_TYPE_CONNECTION_MANAGER,
                              G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));
    g_object_class_install_property
        (object_class, PROP_TP_CONNECTION,
         g_param_spec_object ("tp-connection",
                              "Telepathy Connection",
                              "Telepathy Connection",
                              TP_TYPE_CONNECTION,
                              G_PARAM_READABLE));
    g_object_class_install_property
        (object_class, PROP_ACCOUNT,
         g_param_spec_object ("account",
                              "Account",
                              "Account",
                              MCD_TYPE_ACCOUNT,
                              G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));
    g_object_class_install_property
        (object_class, PROP_SLACKER,
         g_param_spec_object ("slacker",
                              "Slacker",
                              "Slacker object notifies us of user inactivity",
                              MCD_TYPE_SLACKER,
                              G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));

    /**
     * @status:
     * @status_reason:
     * @connection:
     * @dbus_error: a D-Bus error name, or %NULL
     * @details: a #GHashTable from string to #GValue, or %NULL
     */
    signals[CONNECTION_STATUS_CHANGED] = g_signal_new (
        "connection-status-changed", G_OBJECT_CLASS_TYPE (klass),
        G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED, 0,
        NULL, NULL, NULL,
        G_TYPE_NONE, 5, G_TYPE_UINT, G_TYPE_UINT, TP_TYPE_CONNECTION,
        G_TYPE_STRING, G_TYPE_HASH_TABLE);

    signals[READY] = g_signal_new ("ready",
        G_OBJECT_CLASS_TYPE (klass),
        G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED, 0,
        NULL, NULL, g_cclosure_marshal_VOID__VOID,
        G_TYPE_NONE, 0);
}

static void
mcd_connection_init (McdConnection * connection)
{
    McdConnectionPrivate *priv;
   
    priv = G_TYPE_INSTANCE_GET_PRIVATE (connection, MCD_TYPE_CONNECTION,
					McdConnectionPrivate);
    connection->priv = priv;

    priv->abort_reason = TP_CONNECTION_STATUS_REASON_NONE_SPECIFIED;

    priv->reconnect_interval = INITIAL_RECONNECTION_TIME;
}

/* Public methods */

/* Constant getters. These should probably be removed */

McdAccount *
mcd_connection_get_account (McdConnection * id)
{
    McdConnectionPrivate *priv = MCD_CONNECTION_PRIV (id);
    return priv->account;
}

static void
common_request_channel_cb (TpConnection *proxy, gboolean yours,
                           const gchar *channel_path, GHashTable *properties,
                           const GError *error,
                           McdConnection *connection, McdChannel *channel)
{
    McdConnectionPrivate *priv = connection->priv;

    if (error != NULL)
    {
        GError *mc_error;

        /* No special handling of "no capabilities" error: being confident that
         * https://bugs.freedesktop.org/show_bug.cgi?id=15769 will be fixed
         * soon :-) */
        DEBUG ("got error: %s", error->message);
        mc_error = g_error_copy (error);
        mcd_channel_take_error (channel, mc_error);
        mcd_mission_abort ((McdMission *)channel);
        return;
    }
    DEBUG ("%p, object %s", channel, channel_path);

    /* if this was a call to EnsureChannel, it can happen that the returned
     * channel was already created before; in that case we keep the McdChannel
     * alive only as a proxy for the status-changed signals from the "real"
     * McdChannel */
    if (_mcd_channel_get_request_use_existing (channel))
    {
        McdChannel *existing;
        existing = mcd_connection_find_channel_by_path (connection,
            channel_path);
        if (existing)
        {
            _mcd_dispatcher_add_channel_request (priv->dispatcher, existing,
                                                 channel);
            return;
        }
    }

    /* Everything here is well and fine. We can create the channel. */
    if (!_mcd_channel_create_proxy (channel, priv->tp_conn,
                                    channel_path, properties))
    {
        mcd_mission_abort ((McdMission *)channel);
        return;
    }

    /* if the channel request was cancelled, abort the channel now */
    if (mcd_channel_get_status (channel) == MCD_CHANNEL_STATUS_FAILED)
    {
        DEBUG ("Channel %p was cancelled, aborting", channel);
        _mcd_channel_close (channel);
        mcd_mission_abort (MCD_MISSION (channel));
    }

    /* No dispatching here: the channel will be dispatched upon receiving the
     * NewChannel signal */
}

static void
ensure_channel_cb (TpConnection *proxy, gboolean yours,
                   const gchar *channel_path, GHashTable *properties,
                   const GError *error,
                   gpointer user_data, GObject *weak_object)
{
    common_request_channel_cb (proxy, yours, channel_path, properties, error,
                               MCD_CONNECTION (user_data),
                               MCD_CHANNEL (weak_object));
}

static void
create_channel_cb (TpConnection *proxy, const gchar *channel_path,
                   GHashTable *properties, const GError *error,
                   gpointer user_data, GObject *weak_object)
{
    common_request_channel_cb (proxy, TRUE, channel_path, properties, error,
                               MCD_CONNECTION (user_data),
                               MCD_CHANNEL (weak_object));
}

static gboolean
request_channel_new_iface (McdConnection *connection, McdChannel *channel)
{
    McdConnectionPrivate *priv = MCD_CONNECTION_PRIV (connection);
    GHashTable *properties;

    properties = _mcd_channel_get_requested_properties (channel);
    if (_mcd_channel_get_request_use_existing (channel))
    {
        /* Timeout of 5 hours: 5 * 3600 * 1000 */
        tp_cli_connection_interface_requests_call_ensure_channel
            (priv->tp_conn, 18000000, properties, ensure_channel_cb,
             connection, NULL, (GObject *)channel);
    }
    else
    {
        /* Timeout of 5 hours: 5 * 3600 * 1000 */
        tp_cli_connection_interface_requests_call_create_channel
            (priv->tp_conn, 18000000, properties, create_channel_cb,
             connection, NULL, (GObject *)channel);
    }
    return TRUE;
}

gboolean
mcd_connection_request_channel (McdConnection *connection,
                                McdChannel *channel)
{
    g_return_val_if_fail (MCD_IS_CONNECTION (connection), FALSE);
    g_return_val_if_fail (MCD_IS_CHANNEL (channel), FALSE);

    if (mcd_channel_get_status (channel) == MCD_CHANNEL_STATUS_FAILED)
    {
        DEBUG ("Channel %p failed already, never mind", channel);
        _mcd_channel_close (channel);
        mcd_mission_abort (MCD_MISSION (channel));
        /* FIXME: the boolean return is a decoy - everyone returns TRUE and
         * every caller ignores it - so it's not clear what FALSE would
         * mean. */
        return TRUE;
    }

    if (!mcd_mission_get_parent ((McdMission *)channel))
        mcd_operation_take_mission (MCD_OPERATION (connection),
                                    MCD_MISSION (channel));

    return _mcd_connection_request_channel (connection, channel);
}

void
mcd_connection_close (McdConnection *connection,
                      McdInhibit *inhibit)
{
    g_return_if_fail (MCD_IS_CONNECTION (connection));

    connection->priv->closed = TRUE;
    connection->priv->abort_reason = TP_CONNECTION_STATUS_REASON_REQUESTED;
    _mcd_connection_release_tp_connection (connection, inhibit, FALSE);
    mcd_mission_abort (MCD_MISSION (connection));
}

/*
 * _mcd_connection_connect:
 * @connection: the #McdConnection.
 * @params: a #GHashTable of connection parameters
 *
 * Activate @connection.
 */
void
_mcd_connection_connect (McdConnection *connection, GHashTable *params)
{
    McdConnectionPrivate *priv;
    TpConnectionStatus status = TP_CONNECTION_STATUS_DISCONNECTED;

    g_return_if_fail (MCD_IS_CONNECTION (connection));
    g_return_if_fail (params != NULL);
    priv = connection->priv;

    g_return_if_fail (priv->tp_conn_mgr);
    g_return_if_fail (priv->account);
    DEBUG ("called for %p, account %s", connection,
           mcd_account_get_unique_name (priv->account));

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

    /* the account's status can be CONNECTING _before_ we get here, because
     * for the account that includes things like trying to bring up an IAP
     * via an McdTransport plugin. So we have to use the actual status of
     * the connection (or DISCONNECTED if we havan't got one yet) */
    if (priv->tp_conn != NULL)
        status = tp_connection_get_status (priv->tp_conn, NULL);

    if (status == TP_CONNECTION_STATUS_DISCONNECTED ||
        status == TP_UNKNOWN_CONNECTION_STATUS)
    {
        _mcd_connection_connect_with_params (connection, params);
    }
    else
    {
        DEBUG ("Not connecting because not disconnected (%i)",
               mcd_account_get_connection_status (priv->account));
    }
}

const gchar *
mcd_connection_get_object_path (McdConnection *connection)
{
    McdConnectionPrivate *priv = connection->priv;

    if (priv->tp_conn)
        return tp_proxy_get_object_path (TP_PROXY (priv->tp_conn));
    else
	return NULL;
}

const gchar *
mcd_connection_get_name (McdConnection *connection)
{
    McdConnectionPrivate *priv = connection->priv;

    if (priv->tp_conn)
        return tp_proxy_get_bus_name (TP_PROXY (priv->tp_conn));
    else
	return NULL;
}

/**
 * _mcd_connection_update_property:
 * @connection: the #McdConnection.
 * @name: the qualified name of the property to be updated.
 * @value: the new value of the property.
 *
 * Sets the property @name to @value.
 */
void
_mcd_connection_update_property (McdConnection *connection, const gchar *name,
                                 const GValue *value)
{
    McdConnectionPrivate *priv;
    const gchar *dot, *member;
    gchar *interface;

    g_return_if_fail (MCD_IS_CONNECTION (connection));
    g_return_if_fail (name != NULL);
    priv = connection->priv;

    if (G_UNLIKELY (!priv->tp_conn)) return;

    dot = strrchr (name, '.');
    if (G_UNLIKELY (!dot)) return;

    interface = g_strndup (name, dot - name);
    member = dot + 1;
    tp_cli_dbus_properties_call_set (priv->tp_conn, -1,
                                     interface, member, value,
                                     NULL, NULL, NULL, NULL);
    g_free (interface);
}

void
_mcd_connection_set_tp_connection (McdConnection *connection,
                                   const gchar *bus_name,
                                   const gchar *obj_path, GError **error)
{
    McdConnectionPrivate *priv;
    GQuark features[] = {
      TP_CONNECTION_FEATURE_CONNECTED,
      0
    };
    GError *inner_error = NULL;

    g_return_if_fail (MCD_IS_CONNECTION (connection));
    g_return_if_fail (error != NULL);
    priv = connection->priv;

    if (priv->tp_conn != NULL)
    {
        if (G_UNLIKELY (!tp_strdiff (tp_proxy_get_object_path (priv->tp_conn),
                                     obj_path)))
        {
            /* not really meant to happen */
            g_warning ("%s: We already have %s", G_STRFUNC,
                       tp_proxy_get_object_path (priv->tp_conn));
            return;
        }

        DEBUG ("releasing old connection first");
        _mcd_connection_release_tp_connection (connection, NULL, FALSE);
    }

    g_assert (priv->tp_conn == NULL);
    priv->tp_conn = tp_client_factory_ensure_connection (
        priv->client_factory, obj_path, NULL, &inner_error);
    DEBUG ("new connection is %p", priv->tp_conn);
    if (!priv->tp_conn)
    {
        GHashTable *details = tp_asv_new (
            "debug-message", inner_error->message,
            NULL);

        /* Constructing a TpConnection can only fail from invalid arguments,
         * which would mean either MC or the connection manager is confused. */
        g_signal_emit (connection, signals[CONNECTION_STATUS_CHANGED], 0,
            TP_CONNECTION_STATUS_DISCONNECTED,
            TP_CONNECTION_STATUS_REASON_NONE_SPECIFIED,
            NULL, TP_ERROR_STR_CONFUSED, details);

        g_hash_table_unref (details);
        g_propagate_error (error, inner_error);
        return;
    }
    /* FIXME: need some way to feed the status into the Account, but we don't
     * actually know it yet */
    _mcd_account_tp_connection_changed (priv->account, priv->tp_conn);

    /* Setup signals */
    g_signal_connect (priv->tp_conn, "invalidated",
                      G_CALLBACK (mcd_connection_invalidated_cb), connection);
    g_signal_connect (priv->tp_conn, "notify::status",
                      G_CALLBACK (on_connection_status_changed),
                      connection);
    /* HACK for cancelling the _call_when_ready() callback when our object gets
     * destroyed */
    tp_proxy_prepare_async (priv->tp_conn, features,
                            on_connection_ready,
                            tp_weak_ref_new (connection, NULL, NULL));
}

/**
 * mcd_connection_get_tp_connection:
 * @connection: the #McdConnection.
 *
 * Returns: the #TpConnection being used, or %NULL if none.
 */
TpConnection *
mcd_connection_get_tp_connection (McdConnection *connection)
{
    g_return_val_if_fail (MCD_IS_CONNECTION (connection), NULL);
    return connection->priv->tp_conn;
}

gboolean
_mcd_connection_is_ready (McdConnection *self)
{
    g_return_val_if_fail (MCD_IS_CONNECTION (self), FALSE);

    return (self->priv->tp_conn != NULL) &&
        tp_proxy_is_prepared (self->priv->tp_conn, TP_CONNECTION_FEATURE_CONNECTED);
}

gboolean
_mcd_connection_presence_info_is_ready (McdConnection *self)
{
    g_return_val_if_fail (MCD_IS_CONNECTION (self), FALSE);

    return self->priv->presence_info_ready;
}

void
_mcd_connection_take_emergency_numbers (McdConnection *self,
    GSList *numbers)
{
  GSList *iter;

  if (self->priv->service_point_ids == NULL)
    self->priv->service_point_ids = g_hash_table_new_full (g_str_hash,
        g_str_equal, g_free, NULL);

  for (iter = numbers; iter != NULL; iter = iter->next)
    {
      GStrv ids = iter->data;
      gchar **id_p;

      /* We treat emergency numbers as "sticky": if a given ID has ever
       * been considered an emergency number, it stays an emergency number.
       * This seems safer than ever removing one and losing their special
       * treatment. */
      for (id_p = ids; id_p != NULL && *id_p != NULL; id_p++)
        g_hash_table_add (self->priv->service_point_ids, *id_p);
    }

  /* GStrv members' ownership has already been transferred */
  g_slist_free_full (numbers, g_free);
}

void
mcd_connection_add_emergency_handle (McdConnection *self,
    TpHandle handle)
{
  if (self->priv->service_point_handles == NULL)
    self->priv->service_point_handles = tp_intset_new ();

  /* As above, we treat emergency numbers as "sticky". */
  tp_intset_add (self->priv->service_point_handles, handle);
}