summaryrefslogtreecommitdiff
path: root/bus/connection.c
blob: b358343384eebfa606070e4e70f622482b5466c1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
/* connection.c  Client connections
 *
 * Copyright (C) 2003  Red Hat, Inc.
 *
 * Licensed under the Academic Free License version 2.1
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 */

#include <config.h>
#include "connection.h"
#include "dispatch.h"
#include "policy.h"
#include "services.h"
#include "utils.h"
#include "signals.h"
#include "expirelist.h"
#include "selinux.h"
#include "apparmor.h"
#include <dbus/dbus-list.h>
#include <dbus/dbus-hash.h>
#include <dbus/dbus-timeout.h>
#include <dbus/dbus-connection-internal.h>
#include <dbus/dbus-internals.h>

/* Trim executed commands to this length; we want to keep logs readable */
#define MAX_LOG_COMMAND_LEN 50

static void bus_connection_remove_transactions (DBusConnection *connection);

typedef struct
{
  BusExpireItem expire_item;

  DBusConnection *will_get_reply;
  DBusConnection *will_send_reply;

  dbus_uint32_t reply_serial;
  
} BusPendingReply;

struct BusConnections
{
  int refcount;
  DBusList *completed;  /**< List of all completed connections */
  int n_completed;      /**< Length of completed list */
  DBusList *incomplete; /**< List of all not-yet-active connections */
  int n_incomplete;     /**< Length of incomplete list */
  BusContext *context;
  DBusHashTable *completed_by_user; /**< Number of completed connections for each UID */
  DBusTimeout *expire_timeout; /**< Timeout for expiring incomplete connections. */
  int stamp;                   /**< Incrementing number */
  BusExpireList *pending_replies; /**< List of pending replies */

  /** List of all monitoring connections, a subset of completed.
   * Each member is a #DBusConnection. */
  DBusList *monitors;
  BusMatchmaker *monitor_matchmaker;

#ifdef DBUS_ENABLE_STATS
  int total_match_rules;
  int peak_match_rules;
  int peak_match_rules_per_conn;

  int total_bus_names;
  int peak_bus_names;
  int peak_bus_names_per_conn;
#endif
};

static dbus_int32_t connection_data_slot = -1;

typedef struct
{
  BusConnections *connections;
  DBusList *link_in_connection_list;
  DBusConnection *connection;
  DBusList *services_owned;
  int n_services_owned;
  DBusList *match_rules;
  int n_match_rules;
  char *name;
  DBusList *transaction_messages; /**< Stuff we need to send as part of a transaction */
  DBusMessage *oom_message;
  DBusPreallocatedSend *oom_preallocated;
  BusClientPolicy *policy;

  char *cached_loginfo_string;
  BusSELinuxID *selinux_id;
  BusAppArmorConfinement *apparmor_confinement;

  long connection_tv_sec;  /**< Time when we connected (seconds component) */
  long connection_tv_usec; /**< Time when we connected (microsec component) */
  int stamp;               /**< connections->stamp last time we were traversed */

#ifdef DBUS_ENABLE_STATS
  int peak_match_rules;
  int peak_bus_names;
#endif
  int n_pending_unix_fds;
  DBusTimeout *pending_unix_fds_timeout;

  /** non-NULL if and only if this is a monitor */
  DBusList *link_in_monitors;
} BusConnectionData;

static dbus_bool_t bus_pending_reply_expired (BusExpireList *list,
                                              DBusList      *link,
                                              void          *data);

static void bus_connection_drop_pending_replies (BusConnections  *connections,
                                                 DBusConnection  *connection);

static dbus_bool_t expire_incomplete_timeout (void *data);

#define BUS_CONNECTION_DATA(connection) (dbus_connection_get_data ((connection), connection_data_slot))

static DBusLoop*
connection_get_loop (DBusConnection *connection)
{
  BusConnectionData *d;

  d = BUS_CONNECTION_DATA (connection);
  _dbus_assert(d != NULL);

  return bus_context_get_loop (d->connections->context);
}


static int
get_connections_for_uid (BusConnections *connections,
                         dbus_uid_t      uid)
{
  void *val;
  int current_count;

  /* val is NULL is 0 when it isn't in the hash yet */
  
  val = _dbus_hash_table_lookup_uintptr (connections->completed_by_user,
                                       uid);

  current_count = _DBUS_POINTER_TO_INT (val);

  return current_count;
}

static dbus_bool_t
adjust_connections_for_uid (BusConnections *connections,
                            dbus_uid_t      uid,
                            int             adjustment)
{
  int current_count;

  current_count = get_connections_for_uid (connections, uid);

  _dbus_verbose ("Adjusting connection count for UID " DBUS_UID_FORMAT
                 ": was %d adjustment %d making %d\n",
                 uid, current_count, adjustment, current_count + adjustment);
  
  _dbus_assert (current_count >= 0);
  
  current_count += adjustment;

  _dbus_assert (current_count >= 0);

  if (current_count == 0)
    {
      _dbus_hash_table_remove_uintptr (connections->completed_by_user, uid);
      return TRUE;
    }
  else
    {
      dbus_bool_t retval;
      
      retval = _dbus_hash_table_insert_uintptr (connections->completed_by_user,
                                              uid, _DBUS_INT_TO_POINTER (current_count));

      /* only positive adjustment can fail as otherwise
       * a hash entry should already exist
       */
      _dbus_assert (adjustment > 0 ||
                    (adjustment <= 0 && retval));

      return retval;
    }
}

void
bus_connection_disconnected (DBusConnection *connection)
{
  BusConnectionData *d;
  BusService *service;
  BusMatchmaker *matchmaker;
  
  d = BUS_CONNECTION_DATA (connection);
  _dbus_assert (d != NULL);

  _dbus_verbose ("%s disconnected, dropping all service ownership and releasing\n",
                 d->name ? d->name : "(inactive)");

  /* Delete our match rules */
  if (d->n_match_rules > 0)
    {
      matchmaker = bus_context_get_matchmaker (d->connections->context);
      bus_matchmaker_disconnected (matchmaker, connection);
    }
  
  /* Drop any service ownership. Unfortunately, this requires
   * memory allocation and there doesn't seem to be a good way to
   * handle it other than sleeping; we can't "fail" the operation of
   * disconnecting a client, and preallocating a broadcast "service is
   * now gone" message for every client-service pair seems kind of
   * involved.
   */
  while ((service = _dbus_list_get_last (&d->services_owned)))
    {
      BusTransaction *transaction;
      DBusError error;

    retry:
      
      dbus_error_init (&error);
        
      while ((transaction = bus_transaction_new (d->connections->context)) == NULL)
        _dbus_wait_for_memory ();
        
      if (!bus_service_remove_owner (service, connection,
                                     transaction, &error))
        {
          _DBUS_ASSERT_ERROR_IS_SET (&error);
          
          if (dbus_error_has_name (&error, DBUS_ERROR_NO_MEMORY))
            {
              dbus_error_free (&error);
              bus_transaction_cancel_and_free (transaction);
              _dbus_wait_for_memory ();
              goto retry;
            }
          else
            {
              _dbus_verbose ("Failed to remove service owner: %s %s\n",
                             error.name, error.message);
              _dbus_assert_not_reached ("Removing service owner failed for non-memory-related reason");
            }
        }
        
      bus_transaction_execute_and_free (transaction);
    }

  bus_dispatch_remove_connection (connection);
  
  /* no more watching */
  if (!dbus_connection_set_watch_functions (connection,
                                            NULL, NULL, NULL,
                                            connection,
                                            NULL))
    _dbus_assert_not_reached ("setting watch functions to NULL failed");

  if (!dbus_connection_set_timeout_functions (connection,
                                              NULL, NULL, NULL,
                                              connection,
                                              NULL))
    _dbus_assert_not_reached ("setting timeout functions to NULL failed");
  
  dbus_connection_set_unix_user_function (connection,
                                          NULL, NULL, NULL);
  dbus_connection_set_windows_user_function (connection,
                                             NULL, NULL, NULL);
  
  dbus_connection_set_dispatch_status_function (connection,
                                                NULL, NULL, NULL);

  if (d->pending_unix_fds_timeout)
    {
      _dbus_loop_remove_timeout (bus_context_get_loop (d->connections->context),
                                 d->pending_unix_fds_timeout);
      _dbus_timeout_unref (d->pending_unix_fds_timeout);
    }
  d->pending_unix_fds_timeout = NULL;
  _dbus_connection_set_pending_fds_function (connection, NULL, NULL);
  
  bus_connection_remove_transactions (connection);

  if (d->link_in_monitors != NULL)
    {
      BusMatchmaker *mm = d->connections->monitor_matchmaker;

      if (mm != NULL)
        bus_matchmaker_disconnected (mm, connection);

      _dbus_list_remove_link (&d->connections->monitors, d->link_in_monitors);
      d->link_in_monitors = NULL;
    }

  if (d->link_in_connection_list != NULL)
    {
      if (d->name != NULL)
        {
          unsigned long uid;
          
          _dbus_list_remove_link (&d->connections->completed, d->link_in_connection_list);
          d->link_in_connection_list = NULL;
          d->connections->n_completed -= 1;

          if (dbus_connection_get_unix_user (connection, &uid))
            {
              if (!adjust_connections_for_uid (d->connections,
                                               uid, -1))
                _dbus_assert_not_reached ("adjusting downward should never fail");
            }
        }
      else
        {
          _dbus_list_remove_link (&d->connections->incomplete, d->link_in_connection_list);
          d->link_in_connection_list = NULL;
          d->connections->n_incomplete -= 1;

          /* If we have dropped below the max. number of incomplete
           * connections, start accept()ing again */
          bus_context_check_all_watches (d->connections->context);
        }
      
      _dbus_assert (d->connections->n_incomplete >= 0);
      _dbus_assert (d->connections->n_completed >= 0);
    }

  bus_connection_drop_pending_replies (d->connections, connection);
  
  /* frees "d" as side effect */
  dbus_connection_set_data (connection,
                            connection_data_slot,
                            NULL, NULL);
  
  dbus_connection_unref (connection);
}

static dbus_bool_t
add_connection_watch (DBusWatch      *watch,
                      void           *data)
{
  DBusConnection *connection = data;

  return _dbus_loop_add_watch (connection_get_loop (connection), watch);
}

static void
remove_connection_watch (DBusWatch      *watch,
                         void           *data)
{
  DBusConnection *connection = data;
  
  _dbus_loop_remove_watch (connection_get_loop (connection), watch);
}

static void
toggle_connection_watch (DBusWatch      *watch,
                         void           *data)
{
  DBusConnection *connection = data;

  _dbus_loop_toggle_watch (connection_get_loop (connection), watch);
}

static dbus_bool_t
add_connection_timeout (DBusTimeout    *timeout,
                        void           *data)
{
  DBusConnection *connection = data;
  
  return _dbus_loop_add_timeout (connection_get_loop (connection), timeout);
}

static void
remove_connection_timeout (DBusTimeout    *timeout,
                           void           *data)
{
  DBusConnection *connection = data;
  
  _dbus_loop_remove_timeout (connection_get_loop (connection), timeout);
}

static void
dispatch_status_function (DBusConnection    *connection,
                          DBusDispatchStatus new_status,
                          void              *data)
{
  DBusLoop *loop = data;
  
  if (new_status != DBUS_DISPATCH_COMPLETE)
    {
      while (!_dbus_loop_queue_dispatch (loop, connection))
        _dbus_wait_for_memory ();
    }
}

static dbus_bool_t
allow_unix_user_function (DBusConnection *connection,
                          unsigned long   uid,
                          void           *data)
{
  BusConnectionData *d;
    
  d = BUS_CONNECTION_DATA (connection);

  _dbus_assert (d != NULL);
  
  return bus_context_allow_unix_user (d->connections->context, uid);
}

static void
free_connection_data (void *data)
{
  BusConnectionData *d = data;

  /* services_owned should be NULL since we should be disconnected */
  _dbus_assert (d->services_owned == NULL);
  _dbus_assert (d->n_services_owned == 0);
  /* similarly */
  _dbus_assert (d->transaction_messages == NULL);

  if (d->oom_preallocated)
    dbus_connection_free_preallocated_send (d->connection, d->oom_preallocated);

  if (d->oom_message)
    dbus_message_unref (d->oom_message);

  if (d->policy)
    bus_client_policy_unref (d->policy);

  if (d->apparmor_confinement)
    bus_apparmor_confinement_unref (d->apparmor_confinement);
  
  dbus_free (d->cached_loginfo_string);
  
  dbus_free (d->name);
  
  dbus_free (d);
}

BusConnections*
bus_connections_new (BusContext *context)
{
  BusConnections *connections;

  if (!dbus_connection_allocate_data_slot (&connection_data_slot))
    goto failed_0;

  connections = dbus_new0 (BusConnections, 1);
  if (connections == NULL)
    goto failed_1;

  connections->completed_by_user = _dbus_hash_table_new (DBUS_HASH_UINTPTR,
                                                         NULL, NULL);
  if (connections->completed_by_user == NULL)
    goto failed_2;

  connections->expire_timeout = _dbus_timeout_new (100, /* irrelevant */
                                                   expire_incomplete_timeout,
                                                   connections, NULL);
  if (connections->expire_timeout == NULL)
    goto failed_3;

  _dbus_timeout_disable (connections->expire_timeout);

  connections->pending_replies = bus_expire_list_new (bus_context_get_loop (context),
                                                      bus_context_get_reply_timeout (context),
                                                      bus_pending_reply_expired,
                                                      connections);
  if (connections->pending_replies == NULL)
    goto failed_4;
  
  if (!_dbus_loop_add_timeout (bus_context_get_loop (context),
                               connections->expire_timeout))
    goto failed_5;
  
  connections->refcount = 1;
  connections->context = context;
  
  return connections;

 failed_5:
  bus_expire_list_free (connections->pending_replies);
 failed_4:
  _dbus_timeout_unref (connections->expire_timeout);
 failed_3:
  _dbus_hash_table_unref (connections->completed_by_user);
 failed_2:
  dbus_free (connections);
 failed_1:
  dbus_connection_free_data_slot (&connection_data_slot);
 failed_0:
  return NULL;
}

BusConnections *
bus_connections_ref (BusConnections *connections)
{
  _dbus_assert (connections->refcount > 0);
  connections->refcount += 1;

  return connections;
}

void
bus_connections_unref (BusConnections *connections)
{
  _dbus_assert (connections->refcount > 0);
  connections->refcount -= 1;
  if (connections->refcount == 0)
    {
      /* drop all incomplete */
      while (connections->incomplete != NULL)
        {
          DBusConnection *connection;

          connection = connections->incomplete->data;

          dbus_connection_ref (connection);
          dbus_connection_close (connection);
          bus_connection_disconnected (connection);
          dbus_connection_unref (connection);
        }

      _dbus_assert (connections->n_incomplete == 0);

      /* drop all real connections */
      while (connections->completed != NULL)
        {
          DBusConnection *connection;

          connection = connections->completed->data;

          dbus_connection_ref (connection);
          dbus_connection_close (connection);
          bus_connection_disconnected (connection);
          dbus_connection_unref (connection);
        }

      _dbus_assert (connections->n_completed == 0);

      /* disconnecting all the connections should have emptied the list of
       * monitors (each link is removed in bus_connection_disconnected) */
      _dbus_assert (connections->monitors == NULL);

      bus_expire_list_free (connections->pending_replies);
      
      _dbus_loop_remove_timeout (bus_context_get_loop (connections->context),
                                 connections->expire_timeout);
      
      _dbus_timeout_unref (connections->expire_timeout);
      
      _dbus_hash_table_unref (connections->completed_by_user);

      if (connections->monitor_matchmaker != NULL)
        bus_matchmaker_unref (connections->monitor_matchmaker);

      dbus_free (connections);

      dbus_connection_free_data_slot (&connection_data_slot);
    }
}

/* Used for logging */
static dbus_bool_t
cache_peer_loginfo_string (BusConnectionData *d, 
                           DBusConnection    *connection)
{
  DBusString loginfo_buf;
  unsigned long uid;
  unsigned long pid;
  char *windows_sid = NULL, *security_label = NULL;
  dbus_bool_t prev_added;

  if (!_dbus_string_init (&loginfo_buf))
    return FALSE;
  
  prev_added = FALSE;
  if (dbus_connection_get_unix_user (connection, &uid))
    {
      if (!_dbus_string_append_printf (&loginfo_buf, "uid=%ld", uid))
        goto oom;
      else
        prev_added = TRUE;
    }

  if (dbus_connection_get_unix_process_id (connection, &pid))
    {
      if (prev_added)
        {
          if (!_dbus_string_append_byte (&loginfo_buf, ' '))
            goto oom;
        }
      if (!_dbus_string_append_printf (&loginfo_buf, "pid=%ld comm=\"", pid))
        goto oom;
      /* Ignore errors here; we may not have permissions to read the
       * proc file. */
      _dbus_command_for_pid (pid, &loginfo_buf, MAX_LOG_COMMAND_LEN, NULL);
      if (!_dbus_string_append_byte (&loginfo_buf, '"'))
        goto oom;
      else
        prev_added = TRUE;
    }

  if (dbus_connection_get_windows_user (connection, &windows_sid))
    {
      dbus_bool_t did_append;

      if (prev_added)
        {
          if (!_dbus_string_append_byte (&loginfo_buf, ' '))
            goto oom;
        }

      did_append = _dbus_string_append_printf (&loginfo_buf,
                                               "sid=\"%s\"", windows_sid);
      dbus_free (windows_sid);
      windows_sid = NULL;
      if (!did_append)
        goto oom;
      else
        prev_added = TRUE;
    }

  if (_dbus_connection_get_linux_security_label (connection, &security_label))
    {
      dbus_bool_t did_append;

      if (prev_added)
        {
          if (!_dbus_string_append_byte (&loginfo_buf, ' '))
            goto oom;
        }

      did_append = _dbus_string_append_printf (&loginfo_buf,
                                               "label=\"%s\"", security_label);
      dbus_free (security_label);
      security_label = NULL;
      if (!did_append)
        goto oom;
      else
        prev_added = TRUE;
    }

  if (!_dbus_string_steal_data (&loginfo_buf, &(d->cached_loginfo_string)))
    goto oom;

  _dbus_string_free (&loginfo_buf); 

  return TRUE;
oom:
   _dbus_string_free (&loginfo_buf);
   if (security_label != NULL)
     dbus_free (security_label);
   if (windows_sid != NULL)
     dbus_free (windows_sid);

   return FALSE;
}

static void
check_pending_fds_cb (DBusConnection *connection)
{
  BusConnectionData *d = BUS_CONNECTION_DATA (connection);
  int n_pending_unix_fds_old;
  int n_pending_unix_fds_new;

  _dbus_assert(d != NULL);

  n_pending_unix_fds_old = d->n_pending_unix_fds;
  n_pending_unix_fds_new = _dbus_connection_get_pending_fds_count (connection);

  _dbus_verbose ("Pending fds count changed on connection %p: %d -> %d\n",
                 connection, n_pending_unix_fds_old, n_pending_unix_fds_new);

  if (n_pending_unix_fds_old == 0 && n_pending_unix_fds_new > 0)
    {
      _dbus_timeout_restart (d->pending_unix_fds_timeout,
              bus_context_get_pending_fd_timeout (d->connections->context));
    }

  if (n_pending_unix_fds_old > 0 && n_pending_unix_fds_new == 0)
    {
      _dbus_timeout_disable (d->pending_unix_fds_timeout);
    }


  d->n_pending_unix_fds = n_pending_unix_fds_new;
}

static dbus_bool_t
pending_unix_fds_timeout_cb (void *data)
{
  DBusConnection *connection = data;
  BusConnectionData *d = BUS_CONNECTION_DATA (connection);
  int limit;

  _dbus_assert (d != NULL);
  limit = bus_context_get_pending_fd_timeout (d->connections->context);
  bus_context_log (d->connections->context, DBUS_SYSTEM_LOG_WARNING,
      "Connection \"%s\" (%s) has had Unix fds pending for too long, "
      "closing it (pending_fd_timeout=%d ms)",
      d->name != NULL ? d->name : "(null)",
      bus_connection_get_loginfo (connection),
      limit);

  dbus_connection_close (connection);
  return TRUE;
}

dbus_bool_t
bus_connections_setup_connection (BusConnections *connections,
                                  DBusConnection *connection)
{

  BusConnectionData *d = NULL;
  DBusError error;

  d = dbus_new0 (BusConnectionData, 1);
  
  if (d == NULL)
    goto oom;

  d->connections = connections;
  d->connection = connection;
  
  _dbus_get_monotonic_time (&d->connection_tv_sec,
                            &d->connection_tv_usec);
  
  _dbus_assert (connection_data_slot >= 0);
  
  if (!dbus_connection_set_data (connection,
                                 connection_data_slot,
                                 d, free_connection_data))
    {
      /* We have to free d explicitly, because this is the only code
       * path where it's non-NULL but dbus_connection_set_data() hasn't
       * taken responsibility for freeing it. */
      dbus_free (d);
      d = NULL;
      goto oom;
    }

  dbus_connection_set_route_peer_messages (connection, TRUE);

  dbus_error_init (&error);
  d->selinux_id = bus_selinux_init_connection_id (connection,
                                                  &error);
  if (dbus_error_is_set (&error))
    {
      bus_context_log (connections->context, DBUS_SYSTEM_LOG_WARNING,
                       "Unable to set up new connection: %s", error.message);
      dbus_error_free (&error);
      goto error;
    }

  d->apparmor_confinement = bus_apparmor_init_connection_confinement (connection,
                                                                      &error);
  if (dbus_error_is_set (&error))
    {
      bus_context_log (connections->context, DBUS_SYSTEM_LOG_WARNING,
                       "Unable to set up new connection: %s", error.message);
      dbus_error_free (&error);
      goto error;
    }

  if (!dbus_connection_set_watch_functions (connection,
                                            add_connection_watch,
                                            remove_connection_watch,
                                            toggle_connection_watch,
                                            connection,
                                            NULL))
    goto oom;
  
  if (!dbus_connection_set_timeout_functions (connection,
                                              add_connection_timeout,
                                              remove_connection_timeout,
                                              NULL,
                                              connection, NULL))
    goto oom;

  /* For now we don't need to set a Windows user function because
   * there are no policies in the config file controlling what
   * Windows users can connect. The default 'same user that owns the
   * bus can connect' behavior of DBusConnection is fine on Windows.
   */
  dbus_connection_set_unix_user_function (connection,
                                          allow_unix_user_function,
                                          NULL, NULL);

  dbus_connection_set_dispatch_status_function (connection,
                                                dispatch_status_function,
                                                bus_context_get_loop (connections->context),
                                                NULL);

  d->link_in_connection_list = _dbus_list_alloc_link (connection);
  if (d->link_in_connection_list == NULL)
    goto oom;
  
  /* Setup the connection with the dispatcher */
  if (!bus_dispatch_add_connection (connection))
    goto oom;

  if (dbus_connection_get_dispatch_status (connection) != DBUS_DISPATCH_COMPLETE)
    {
      if (!_dbus_loop_queue_dispatch (bus_context_get_loop (connections->context), connection))
        {
          bus_dispatch_remove_connection (connection);
          goto oom;
        }
    }

  /* Setup pending fds timeout (see #80559) */
  d->pending_unix_fds_timeout = _dbus_timeout_new (100, /* irrelevant */
                                                   pending_unix_fds_timeout_cb,
                                                   connection, NULL);
  if (d->pending_unix_fds_timeout == NULL)
    goto oom;

  _dbus_timeout_disable (d->pending_unix_fds_timeout);
  if (!_dbus_loop_add_timeout (bus_context_get_loop (connections->context),
                               d->pending_unix_fds_timeout))
    goto oom;

  _dbus_connection_set_pending_fds_function (connection,
          (DBusPendingFdsChangeFunction) check_pending_fds_cb,
          connection);

  _dbus_list_append_link (&connections->incomplete, d->link_in_connection_list);
  connections->n_incomplete += 1;
  
  dbus_connection_ref (connection);

  bus_connections_expire_incomplete (connections);
  
  /* The listening socket is removed from the main loop,
   * i.e. does not accept(), while n_incomplete is at its
   * maximum value; so we shouldn't get here in that case */
  _dbus_assert (connections->n_incomplete <=
      bus_context_get_max_incomplete_connections (connections->context));

  /* If we have the maximum number of incomplete connections,
   * stop accept()ing any more, to avert a DoS. See fd.o #80919 */
  bus_context_check_all_watches (d->connections->context);
  
  return TRUE;

oom:
  bus_context_log (connections->context, DBUS_SYSTEM_LOG_WARNING,
                   "No memory to set up new connection");
  /* fall through */
error:
  if (d != NULL)
    {
      d->selinux_id = NULL;

      if (d->apparmor_confinement)
        bus_apparmor_confinement_unref (d->apparmor_confinement);
      d->apparmor_confinement = NULL;
      
      if (!dbus_connection_set_watch_functions (connection,
                                                NULL, NULL, NULL,
                                                connection,
                                                NULL))
        _dbus_assert_not_reached ("setting watch functions to NULL failed");
      
      if (!dbus_connection_set_timeout_functions (connection,
                                                  NULL, NULL, NULL,
                                                  connection,
                                                  NULL))
        _dbus_assert_not_reached ("setting timeout functions to NULL failed");

      dbus_connection_set_unix_user_function (connection,
                                              NULL, NULL, NULL);

      dbus_connection_set_windows_user_function (connection,
                                                 NULL, NULL, NULL);
      
      dbus_connection_set_dispatch_status_function (connection,
                                                    NULL, NULL, NULL);

      if (d->pending_unix_fds_timeout)
        _dbus_timeout_unref (d->pending_unix_fds_timeout);

      d->pending_unix_fds_timeout = NULL;

      _dbus_connection_set_pending_fds_function (connection, NULL, NULL);

      if (d->link_in_connection_list != NULL)
        {
          _dbus_assert (d->link_in_connection_list->next == NULL);
          _dbus_assert (d->link_in_connection_list->prev == NULL);
          _dbus_list_free_link (d->link_in_connection_list);
          d->link_in_connection_list = NULL;
        }
      
      if (!dbus_connection_set_data (connection,
                                     connection_data_slot,
                                     NULL, NULL))
        _dbus_assert_not_reached ("failed to set connection data to null");

      /* "d" has now been freed */
    }
  
  return FALSE;
}

void
bus_connections_expire_incomplete (BusConnections *connections)
{    
  int next_interval;

  next_interval = -1;
  
  if (connections->incomplete != NULL)
    {
      long tv_sec, tv_usec;
      DBusList *link;
      int auth_timeout;
      
      _dbus_get_monotonic_time (&tv_sec, &tv_usec);
      auth_timeout = bus_context_get_auth_timeout (connections->context);
  
      link = _dbus_list_get_first_link (&connections->incomplete);
      while (link != NULL)
        {
          DBusList *next = _dbus_list_get_next_link (&connections->incomplete, link);
          DBusConnection *connection;
          BusConnectionData *d;
          double elapsed;
      
          connection = link->data;
      
          d = BUS_CONNECTION_DATA (connection);
      
          _dbus_assert (d != NULL);
      
          elapsed = ELAPSED_MILLISECONDS_SINCE (d->connection_tv_sec,
                                                d->connection_tv_usec,
                                                tv_sec, tv_usec);

          if (elapsed >= (double) auth_timeout)
            {
              /* Unfortunately, we can't identify the connection: it doesn't
               * have a unique name yet, we don't know its uid/pid yet,
               * and so on. */
              bus_context_log (connections->context, DBUS_SYSTEM_LOG_WARNING,
                  "Connection has not authenticated soon enough, closing it "
                  "(auth_timeout=%dms, elapsed: %.0fms)",
                  auth_timeout, elapsed);

              _dbus_verbose ("Timing out authentication for connection %p\n", connection);
              dbus_connection_close (connection);
            }
          else
            {
              /* We can end the loop, since the connections are in oldest-first order */
              next_interval = ((double)auth_timeout) - elapsed;
              _dbus_verbose ("Connection %p authentication expires in %d milliseconds\n",
                             connection, next_interval);
          
              break;
            }
      
          link = next;
        }
    }

  bus_expire_timeout_set_interval (connections->expire_timeout,
                                   next_interval);
}

static dbus_bool_t
expire_incomplete_timeout (void *data)
{
  BusConnections *connections = data;

  _dbus_verbose ("Running\n");
  
  /* note that this may remove the timeout */
  bus_connections_expire_incomplete (connections);

  return TRUE;
}

dbus_bool_t
bus_connection_get_unix_groups  (DBusConnection   *connection,
                                 unsigned long   **groups,
                                 int              *n_groups,
                                 DBusError        *error)
{
  unsigned long uid;

  *groups = NULL;
  *n_groups = 0;

  if (dbus_connection_get_unix_user (connection, &uid))
    {
      if (!_dbus_unix_groups_from_uid (uid, groups, n_groups))
        {
          _dbus_verbose ("Did not get any groups for UID %lu\n",
                         uid);
          return FALSE;
        }
      else
        {
          _dbus_verbose ("Got %d groups for UID %lu\n",
                         *n_groups, uid);
          return TRUE;
        }
    }
  else
    return TRUE; /* successfully got 0 groups */
}

dbus_bool_t
bus_connection_is_in_unix_group (DBusConnection *connection,
                                 unsigned long   gid)
{
  int i;
  unsigned long *group_ids;
  int n_group_ids;

  if (!bus_connection_get_unix_groups (connection, &group_ids, &n_group_ids,
                                       NULL))
    return FALSE;

  i = 0;
  while (i < n_group_ids)
    {
      if (group_ids[i] == gid)
        {
          dbus_free (group_ids);
          return TRUE;
        }
      ++i;
    }

  dbus_free (group_ids);
  return FALSE;
}

const char *
bus_connection_get_loginfo (DBusConnection        *connection)
{
  BusConnectionData *d;
    
  d = BUS_CONNECTION_DATA (connection);
  _dbus_assert(d != NULL);

  if (!bus_connection_is_active (connection))
    return "inactive";
  return d->cached_loginfo_string;  
}

BusClientPolicy*
bus_connection_get_policy (DBusConnection *connection)
{
  BusConnectionData *d;
    
  d = BUS_CONNECTION_DATA (connection);

  _dbus_assert (d != NULL);
  _dbus_assert (d->policy != NULL);
  
  return d->policy;
}

static dbus_bool_t
foreach_active (BusConnections               *connections,
                BusConnectionForeachFunction  function,
                void                         *data)
{
  DBusList *link;
  
  link = _dbus_list_get_first_link (&connections->completed);
  while (link != NULL)
    {
      DBusConnection *connection = link->data;
      DBusList *next = _dbus_list_get_next_link (&connections->completed, link);

      if (!(* function) (connection, data))
        return FALSE;
      
      link = next;
    }

  return TRUE;
}

static dbus_bool_t
foreach_inactive (BusConnections               *connections,
                  BusConnectionForeachFunction  function,
                  void                         *data)
{
  DBusList *link;
  
  link = _dbus_list_get_first_link (&connections->incomplete);
  while (link != NULL)
    {
      DBusConnection *connection = link->data;
      DBusList *next = _dbus_list_get_next_link (&connections->incomplete, link);

      if (!(* function) (connection, data))
        return FALSE;
      
      link = next;
    }

  return TRUE;
}

/**
 * Calls function on each active connection; if the function returns
 * #FALSE, stops iterating. Active connections are authenticated
 * and have sent a Hello message.
 *
 * @param connections the connections object
 * @param function the function
 * @param data data to pass to it as a second arg
 */
void
bus_connections_foreach_active (BusConnections               *connections,
                                BusConnectionForeachFunction  function,
                                void                         *data)
{
  foreach_active (connections, function, data);
}

/**
 * Calls function on each connection; if the function returns
 * #FALSE, stops iterating.
 *
 * @param connections the connections object
 * @param function the function
 * @param data data to pass to it as a second arg
 */
void
bus_connections_foreach (BusConnections               *connections,
                         BusConnectionForeachFunction  function,
                         void                         *data)
{
  if (!foreach_active (connections, function, data))
    return;

  foreach_inactive (connections, function, data);
}

BusContext*
bus_connections_get_context (BusConnections *connections)
{
  return connections->context;
}

/*
 * This is used to avoid covering the same connection twice when
 * traversing connections. Note that it assumes we will
 * bus_connection_mark_stamp() each connection at least once per
 * INT_MAX increments of the global stamp, or wraparound would break
 * things.
 */
void
bus_connections_increment_stamp (BusConnections *connections)
{
  connections->stamp += 1;
}

/* Mark connection with current stamp, return TRUE if it
 * didn't already have that stamp
 */
dbus_bool_t
bus_connection_mark_stamp (DBusConnection *connection)
{
  BusConnectionData *d;
  
  d = BUS_CONNECTION_DATA (connection);
  
  _dbus_assert (d != NULL);

  if (d->stamp == d->connections->stamp)
    return FALSE;
  else
    {
      d->stamp = d->connections->stamp;
      return TRUE;
    }
}

BusContext*
bus_connection_get_context (DBusConnection *connection)
{
  BusConnectionData *d;

  d = BUS_CONNECTION_DATA (connection);

  _dbus_assert (d != NULL);

  return d->connections->context;
}

BusConnections*
bus_connection_get_connections (DBusConnection *connection)
{
  BusConnectionData *d;
    
  d = BUS_CONNECTION_DATA (connection);

  _dbus_assert (d != NULL);

  return d->connections;
}

BusRegistry*
bus_connection_get_registry (DBusConnection *connection)
{
  BusConnectionData *d;

  d = BUS_CONNECTION_DATA (connection);

  _dbus_assert (d != NULL);

  return bus_context_get_registry (d->connections->context);
}

BusActivation*
bus_connection_get_activation (DBusConnection *connection)
{
  BusConnectionData *d;

  d = BUS_CONNECTION_DATA (connection);

  _dbus_assert (d != NULL);

  return bus_context_get_activation (d->connections->context);
}

BusMatchmaker*
bus_connection_get_matchmaker (DBusConnection *connection)
{
  BusConnectionData *d;

  d = BUS_CONNECTION_DATA (connection);

  _dbus_assert (d != NULL);

  return bus_context_get_matchmaker (d->connections->context);
}

BusSELinuxID*
bus_connection_get_selinux_id (DBusConnection *connection)
{
  BusConnectionData *d;

  d = BUS_CONNECTION_DATA (connection);

  _dbus_assert (d != NULL);

  return d->selinux_id;
}

BusAppArmorConfinement*
bus_connection_dup_apparmor_confinement (DBusConnection *connection)
{
  BusConnectionData *d;

  d = BUS_CONNECTION_DATA (connection);

  _dbus_assert (d != NULL);

  bus_apparmor_confinement_ref (d->apparmor_confinement);
  return d->apparmor_confinement;
}

/**
 * Checks whether the connection is registered with the message bus.
 *
 * @param connection the connection
 * @returns #TRUE if we're an active message bus participant
 */
dbus_bool_t
bus_connection_is_active (DBusConnection *connection)
{
  BusConnectionData *d;

  d = BUS_CONNECTION_DATA (connection);
  _dbus_assert(d != NULL);
  
  return d->name != NULL;
}

dbus_bool_t
bus_connection_preallocate_oom_error (DBusConnection *connection)
{
  DBusMessage *message;
  DBusPreallocatedSend *preallocated;
  BusConnectionData *d;

  d = BUS_CONNECTION_DATA (connection);  

  _dbus_assert (d != NULL);

  if (d->oom_preallocated != NULL)
    return TRUE;
  
  preallocated = dbus_connection_preallocate_send (connection);
  if (preallocated == NULL)
    return FALSE;

  message = dbus_message_new (DBUS_MESSAGE_TYPE_ERROR);

  if (message == NULL)
    {
      dbus_connection_free_preallocated_send (connection, preallocated);
      return FALSE;
    }

  /* d->name may be NULL, but that is OK */
  if (!dbus_message_set_error_name (message, DBUS_ERROR_NO_MEMORY) ||
      !dbus_message_set_destination (message, d->name) ||
      !dbus_message_set_sender (message,
                                DBUS_SERVICE_DBUS))
    {
      dbus_connection_free_preallocated_send (connection, preallocated);
      dbus_message_unref (message);
      return FALSE;
    }
  
  /* set reply serial to placeholder value just so space is already allocated
   * for it.
   */
  if (!dbus_message_set_reply_serial (message, 14))
    {
      dbus_connection_free_preallocated_send (connection, preallocated);
      dbus_message_unref (message);
      return FALSE;
    }

  d->oom_message = message;
  d->oom_preallocated = preallocated;
  
  return TRUE;
}

void
bus_connection_send_oom_error (DBusConnection *connection,
                               DBusMessage    *in_reply_to)
{
  BusConnectionData *d;

  d = BUS_CONNECTION_DATA (connection);  

  _dbus_assert (d != NULL);  
  _dbus_assert (d->oom_message != NULL);

  bus_context_log (d->connections->context, DBUS_SYSTEM_LOG_WARNING,
                   "dbus-daemon transaction failed (OOM), sending error to "
                   "sender %s", bus_connection_get_loginfo (connection));

  /* should always succeed since we set it to a placeholder earlier */
  if (!dbus_message_set_reply_serial (d->oom_message,
                                      dbus_message_get_serial (in_reply_to)))
    _dbus_assert_not_reached ("Failed to set reply serial for preallocated oom message");

  _dbus_assert (dbus_message_get_sender (d->oom_message) != NULL);
  
  dbus_connection_send_preallocated (connection, d->oom_preallocated,
                                     d->oom_message, NULL);

  dbus_message_unref (d->oom_message);
  d->oom_message = NULL;
  d->oom_preallocated = NULL;
}

#ifdef DBUS_ENABLE_STATS
static void
update_peak (int *peak,
             int n)
{
  if (*peak < n)
    *peak = n;
}
#endif

void
bus_connection_add_match_rule_link (DBusConnection *connection,
                                    DBusList       *link)
{
  BusConnectionData *d;

  d = BUS_CONNECTION_DATA (connection);
  _dbus_assert (d != NULL);

  _dbus_list_append_link (&d->match_rules, link);

  d->n_match_rules += 1;

#ifdef DBUS_ENABLE_STATS
  update_peak (&d->peak_match_rules, d->n_match_rules);
  update_peak (&d->connections->peak_match_rules_per_conn, d->n_match_rules);

  d->connections->total_match_rules += 1;
  update_peak (&d->connections->peak_match_rules,
               d->connections->total_match_rules);
#endif
}

dbus_bool_t
bus_connection_add_match_rule (DBusConnection *connection,
                               BusMatchRule   *rule)
{
    DBusList *link;

  link = _dbus_list_alloc_link (rule);

  if (link == NULL)
    return FALSE;

  bus_connection_add_match_rule_link (connection, link);

  return TRUE;
}

void
bus_connection_remove_match_rule (DBusConnection *connection,
                                  BusMatchRule   *rule)
{
  BusConnectionData *d;

  d = BUS_CONNECTION_DATA (connection);
  _dbus_assert (d != NULL);

  _dbus_list_remove_last (&d->match_rules, rule);

  d->n_match_rules -= 1;
  _dbus_assert (d->n_match_rules >= 0);

#ifdef DBUS_ENABLE_STATS
  d->connections->total_match_rules -= 1;
#endif
}

int
bus_connection_get_n_match_rules (DBusConnection *connection)
{
  BusConnectionData *d;

  d = BUS_CONNECTION_DATA (connection);
  _dbus_assert (d != NULL);
  
  return d->n_match_rules;
}

void
bus_connection_add_owned_service_link (DBusConnection *connection,
                                       DBusList       *link)
{
  BusConnectionData *d;

  d = BUS_CONNECTION_DATA (connection);
  _dbus_assert (d != NULL);

  _dbus_list_append_link (&d->services_owned, link);

  d->n_services_owned += 1;

#ifdef DBUS_ENABLE_STATS
  update_peak (&d->peak_bus_names, d->n_services_owned);
  update_peak (&d->connections->peak_bus_names_per_conn,
               d->n_services_owned);

  d->connections->total_bus_names += 1;
  update_peak (&d->connections->peak_bus_names,
               d->connections->total_bus_names);
#endif
}

dbus_bool_t
bus_connection_add_owned_service (DBusConnection *connection,
                                  BusService     *service)
{
  DBusList *link;

  link = _dbus_list_alloc_link (service);

  if (link == NULL)
    return FALSE;

  bus_connection_add_owned_service_link (connection, link);

  return TRUE;
}

void
bus_connection_remove_owned_service (DBusConnection *connection,
                                     BusService     *service)
{
  BusConnectionData *d;

  d = BUS_CONNECTION_DATA (connection);
  _dbus_assert (d != NULL);

  _dbus_list_remove_last (&d->services_owned, service);

  d->n_services_owned -= 1;
  _dbus_assert (d->n_services_owned >= 0);

#ifdef DBUS_ENABLE_STATS
  d->connections->total_bus_names -= 1;
#endif
}

int
bus_connection_get_n_services_owned (DBusConnection *connection)
{
  BusConnectionData *d;

  d = BUS_CONNECTION_DATA (connection);
  _dbus_assert (d != NULL);
  
  return d->n_services_owned;
}

dbus_bool_t
bus_connection_complete (DBusConnection   *connection,
			 const DBusString *name,
                         DBusError        *error)
{
  BusConnectionData *d;
  unsigned long uid;
  
  d = BUS_CONNECTION_DATA (connection);
  _dbus_assert (d != NULL);
  _dbus_assert (d->name == NULL);
  _dbus_assert (d->policy == NULL);

  _dbus_assert (!bus_connection_is_active (connection));
  
  if (!_dbus_string_copy_data (name, &d->name))
    {
      BUS_SET_OOM (error);
      return FALSE;
    }

  _dbus_assert (d->name != NULL);
  
  _dbus_verbose ("Name %s assigned to %p\n", d->name, connection);

  d->policy = bus_context_create_client_policy (d->connections->context,
                                                connection,
                                                error);

  /* we may have a NULL policy on OOM or error getting list of
   * groups for a user. In the latter case we don't handle it so
   * well currently, as it will just keep failing over and over.
   */

  if (d->policy == NULL)
    {
      _dbus_verbose ("Failed to create security policy for connection %p\n",
                     connection);
      _DBUS_ASSERT_ERROR_IS_SET (error);
      dbus_free (d->name);
      d->name = NULL;
      return FALSE;
    }
  
  if (dbus_connection_get_unix_user (connection, &uid))
    {
      if (!adjust_connections_for_uid (d->connections,
                                       uid, 1))
        goto fail;
    }

  /* Create and cache a string which holds information about the 
   * peer process; used for logging purposes.
   */
  if (!cache_peer_loginfo_string (d, connection))
    goto fail;

  /* Now the connection is active, move it between lists */
  _dbus_list_unlink (&d->connections->incomplete,
                     d->link_in_connection_list);
  d->connections->n_incomplete -= 1;
  _dbus_list_append_link (&d->connections->completed,
                          d->link_in_connection_list);
  d->connections->n_completed += 1;

  _dbus_assert (d->connections->n_incomplete >= 0);
  _dbus_assert (d->connections->n_completed > 0);

  /* If we have dropped below the max. number of incomplete
   * connections, start accept()ing again */
  bus_context_check_all_watches (d->connections->context);

  /* See if we can remove the timeout */
  bus_connections_expire_incomplete (d->connections);

  _dbus_assert (bus_connection_is_active (connection));
  
  return TRUE;
fail:
  BUS_SET_OOM (error);
  dbus_free (d->name);
  d->name = NULL;
  if (d->policy)
    bus_client_policy_unref (d->policy);
  d->policy = NULL;
  return FALSE;
}

dbus_bool_t
bus_connections_reload_policy (BusConnections *connections,
                               DBusError      *error)
{
  BusConnectionData *d;
  DBusConnection *connection;
  DBusList *link;

  _dbus_assert (connections != NULL);
  _DBUS_ASSERT_ERROR_IS_CLEAR (error);

  for (link = _dbus_list_get_first_link (&(connections->completed));
       link;
       link = _dbus_list_get_next_link (&(connections->completed), link))
    {
      connection = link->data;
      d = BUS_CONNECTION_DATA (connection);
      _dbus_assert (d != NULL);
      _dbus_assert (d->policy != NULL);

      bus_client_policy_unref (d->policy);
      d->policy = bus_context_create_client_policy (connections->context,
                                                    connection,
                                                    error);
      if (d->policy == NULL)
        {
          _dbus_verbose ("Failed to create security policy for connection %p\n",
                      connection);
          _DBUS_ASSERT_ERROR_IS_SET (error);
          return FALSE;
        }
    }

  return TRUE;
}

const char *
bus_connection_get_name (DBusConnection *connection)
{
  BusConnectionData *d;
  
  d = BUS_CONNECTION_DATA (connection);
  _dbus_assert (d != NULL);
  
  return d->name;
}

/**
 * Check whether completing the passed-in connection would
 * exceed limits, and if so set error and return #FALSE
 */
dbus_bool_t
bus_connections_check_limits (BusConnections  *connections,
                              DBusConnection  *requesting_completion,
                              const char     **limit_name_out,
                              int             *limit_out,
                              DBusError       *error)
{
  unsigned long uid;
  int limit;

  limit = bus_context_get_max_completed_connections (connections->context);

  if (connections->n_completed >= limit)
    {
      if (limit_name_out != NULL)
        *limit_name_out = "max_completed_connections";

      if (limit_out != NULL)
        *limit_out = limit;

      dbus_set_error (error, DBUS_ERROR_LIMITS_EXCEEDED,
                      "The maximum number of active connections has been reached");
      return FALSE;
    }
  
  if (dbus_connection_get_unix_user (requesting_completion, &uid))
    {
      limit = bus_context_get_max_connections_per_user (connections->context);

      if (get_connections_for_uid (connections, uid) >= limit)
        {
          if (limit_name_out != NULL)
            *limit_name_out = "max_connections_per_user";

          if (limit_out != NULL)
            *limit_out = limit;

          dbus_set_error (error, DBUS_ERROR_LIMITS_EXCEEDED,
                          "The maximum number of active connections for UID %lu has been reached",
                          uid);
          return FALSE;
        }
    }
  
  return TRUE;
}

static void
bus_pending_reply_free (BusPendingReply *pending)
{
  _dbus_verbose ("Freeing pending reply %p, replier %p receiver %p serial %u\n",
                 pending,
                 pending->will_send_reply,
                 pending->will_get_reply,
                 pending->reply_serial);

  dbus_free (pending);
}

static dbus_bool_t
bus_pending_reply_send_no_reply (BusConnections  *connections,
                                 BusTransaction  *transaction,
                                 BusPendingReply *pending)
{
  DBusMessage *message;
  DBusMessageIter iter;
  dbus_bool_t retval;
  const char *errmsg;

  retval = FALSE;
  
  message = dbus_message_new (DBUS_MESSAGE_TYPE_ERROR);
  if (message == NULL)
    return FALSE;
  
  dbus_message_set_no_reply (message, TRUE);
  
  if (!dbus_message_set_reply_serial (message,
                                      pending->reply_serial))
    goto out;

  if (!dbus_message_set_error_name (message,
                                    DBUS_ERROR_NO_REPLY))
    goto out;

  /* If you change these messages, adjust test/dbus-daemon.c to match */
  if (pending->will_send_reply == NULL)
    errmsg = "Message recipient disconnected from message bus without replying";
  else
    errmsg = "Message did not receive a reply (timeout by message bus)";

  dbus_message_iter_init_append (message, &iter);
  if (!dbus_message_iter_append_basic (&iter, DBUS_TYPE_STRING, &errmsg))
    goto out;
    
  if (!bus_transaction_send_from_driver (transaction, pending->will_get_reply,
                                         message))
    goto out;

  retval = TRUE;

 out:
  dbus_message_unref (message);
  return retval;
}

static dbus_bool_t
bus_pending_reply_expired (BusExpireList *list,
                           DBusList      *link,
                           void          *data)
{
  BusPendingReply *pending = link->data;
  BusConnections *connections = data;
  BusTransaction *transaction;
  
  /* No reply is forthcoming. So nuke it if we can. If not,
   * leave it in the list to try expiring again later when we
   * get more memory.
   */

  _dbus_verbose ("Expiring pending reply %p, replier %p receiver %p serial %u\n",
                 pending,
                 pending->will_send_reply,
                 pending->will_get_reply,
                 pending->reply_serial);
  
  transaction = bus_transaction_new (connections->context);
  if (transaction == NULL)
    return FALSE;
  
  if (!bus_pending_reply_send_no_reply (connections,
                                        transaction,
                                        pending))
    {
      bus_transaction_cancel_and_free (transaction);
      return FALSE;
    }

  bus_expire_list_remove_link (connections->pending_replies, link);

  bus_pending_reply_free (pending);
  bus_transaction_execute_and_free (transaction);

  return TRUE;
}

static void
bus_connection_drop_pending_replies (BusConnections  *connections,
                                     DBusConnection  *connection)
{
  /* The DBusConnection is almost 100% finalized here, so you can't
   * do anything with it except check for pointer equality
   */
  DBusList *link;

  _dbus_verbose ("Dropping pending replies that involve connection %p\n",
                 connection);
  
  link = bus_expire_list_get_first_link (connections->pending_replies);
  while (link != NULL)
    {
      DBusList *next;
      BusPendingReply *pending;

      next = bus_expire_list_get_next_link (connections->pending_replies,
                                            link);
      pending = link->data;

      if (pending->will_get_reply == connection)
        {
          /* We don't need to track this pending reply anymore */

          _dbus_verbose ("Dropping pending reply %p, replier %p receiver %p serial %u\n",
                         pending,
                         pending->will_send_reply,
                         pending->will_get_reply,
                         pending->reply_serial);
          
          bus_expire_list_remove_link (connections->pending_replies,
                                       link);
          bus_pending_reply_free (pending);
        }
      else if (pending->will_send_reply == connection)
        {
          /* The reply isn't going to be sent, so set things
           * up so it will be expired right away
           */
          _dbus_verbose ("Will expire pending reply %p, replier %p receiver %p serial %u\n",
                         pending,
                         pending->will_send_reply,
                         pending->will_get_reply,
                         pending->reply_serial);
          
          pending->will_send_reply = NULL;
          pending->expire_item.added_tv_sec = 0;
          pending->expire_item.added_tv_usec = 0;

          bus_expire_list_recheck_immediately (connections->pending_replies);
        }
      
      link = next;
    }
}


typedef struct
{
  BusPendingReply *pending;
  BusConnections  *connections;
} CancelPendingReplyData;

static void
cancel_pending_reply (void *data)
{
  CancelPendingReplyData *d = data;

  _dbus_verbose ("d = %p\n", d);
  
  if (!bus_expire_list_remove (d->connections->pending_replies,
                               &d->pending->expire_item))
    _dbus_assert_not_reached ("pending reply did not exist to be cancelled");

  bus_pending_reply_free (d->pending); /* since it's been cancelled */
}

static void
cancel_pending_reply_data_free (void *data)
{
  CancelPendingReplyData *d = data;

  _dbus_verbose ("d = %p\n", d);
  
  /* d->pending should be either freed or still
   * in the list of pending replies (owned by someone
   * else)
   */
  
  dbus_free (d);
}

/*
 * Record that a reply is allowed; return TRUE on success.
 */
dbus_bool_t
bus_connections_expect_reply (BusConnections  *connections,
                              BusTransaction  *transaction,
                              DBusConnection  *will_get_reply,
                              DBusConnection  *will_send_reply,
                              DBusMessage     *reply_to_this,
                              DBusError       *error)
{
  BusPendingReply *pending;
  dbus_uint32_t reply_serial;
  DBusList *link;
  CancelPendingReplyData *cprd;
  int count;
  int limit;

  _dbus_assert (will_get_reply != NULL);
  _dbus_assert (will_send_reply != NULL);
  _dbus_assert (reply_to_this != NULL);
  
  if (dbus_message_get_no_reply (reply_to_this))
    return TRUE; /* we won't allow a reply, since client doesn't care for one. */
  
  reply_serial = dbus_message_get_serial (reply_to_this);

  link = bus_expire_list_get_first_link (connections->pending_replies);
  count = 0;
  while (link != NULL)
    {
      pending = link->data;

      if (pending->reply_serial == reply_serial &&
          pending->will_get_reply == will_get_reply &&
          pending->will_send_reply == will_send_reply)
        {
          dbus_set_error (error, DBUS_ERROR_ACCESS_DENIED,
                          "Message has the same reply serial as a currently-outstanding existing method call");
          return FALSE;
        }
      
      link = bus_expire_list_get_next_link (connections->pending_replies,
                                            link);
      if (pending->will_get_reply == will_get_reply)
        ++count;
    }

  limit = bus_context_get_max_replies_per_connection (connections->context);

  if (count >= limit)
    {
      bus_context_log (connections->context, DBUS_SYSTEM_LOG_WARNING,
                       "The maximum number of pending replies for "
                       "\"%s\" (%s) has been reached "
                       "(max_replies_per_connection=%d)",
                       bus_connection_get_name (will_get_reply),
                       bus_connection_get_loginfo (will_get_reply),
                       limit);

      dbus_set_error (error, DBUS_ERROR_LIMITS_EXCEEDED,
		      "The maximum number of pending replies per connection has been reached");
      return FALSE;
    }

  pending = dbus_new0 (BusPendingReply, 1);
  if (pending == NULL)
    {
      BUS_SET_OOM (error);
      return FALSE;
    }

#ifdef DBUS_ENABLE_VERBOSE_MODE
  /* so we can see a not-yet-added pending reply */
  pending->expire_item.added_tv_sec = 1;
  pending->expire_item.added_tv_usec = 1;
#endif

  pending->will_get_reply = will_get_reply;
  pending->will_send_reply = will_send_reply;
  pending->reply_serial = reply_serial;
  
  cprd = dbus_new0 (CancelPendingReplyData, 1);
  if (cprd == NULL)
    {
      BUS_SET_OOM (error);
      bus_pending_reply_free (pending);
      return FALSE;
    }
  
  if (!bus_expire_list_add (connections->pending_replies,
                            &pending->expire_item))
    {
      BUS_SET_OOM (error);
      dbus_free (cprd);
      bus_pending_reply_free (pending);
      return FALSE;
    }

  if (!bus_transaction_add_cancel_hook (transaction,
                                        cancel_pending_reply,
                                        cprd,
                                        cancel_pending_reply_data_free))
    {
      BUS_SET_OOM (error);
      bus_expire_list_remove (connections->pending_replies, &pending->expire_item);
      dbus_free (cprd);
      bus_pending_reply_free (pending);
      return FALSE;
    }
                                        
  cprd->pending = pending;
  cprd->connections = connections;
  
  _dbus_get_monotonic_time (&pending->expire_item.added_tv_sec,
                            &pending->expire_item.added_tv_usec);

  _dbus_verbose ("Added pending reply %p, replier %p receiver %p serial %u\n",
                 pending,
                 pending->will_send_reply,
                 pending->will_get_reply,
                 pending->reply_serial);
  
  return TRUE;
}

typedef struct
{
  DBusList        *link;
  BusConnections  *connections;
} CheckPendingReplyData;

static void
cancel_check_pending_reply (void *data)
{
  CheckPendingReplyData *d = data;

  _dbus_verbose ("d = %p\n",d);

  bus_expire_list_add_link (d->connections->pending_replies,
                            d->link);
  d->link = NULL;
}

static void
check_pending_reply_data_free (void *data)
{
  CheckPendingReplyData *d = data;

  _dbus_verbose ("d = %p\n",d);
  
  if (d->link != NULL)
    {
      BusPendingReply *pending = d->link->data;
      
      _dbus_assert (!bus_expire_list_contains_item (d->connections->pending_replies,
                                                    &pending->expire_item));
      
      bus_pending_reply_free (pending);
      _dbus_list_free_link (d->link);
    }
  
  dbus_free (d);
}

/*
 * Check whether a reply is allowed, remove BusPendingReply
 * if so, return TRUE if so.
 */
dbus_bool_t
bus_connections_check_reply (BusConnections *connections,
                             BusTransaction *transaction,
                             DBusConnection *sending_reply,
                             DBusConnection *receiving_reply,
                             DBusMessage    *reply,
                             DBusError      *error)
{
  CheckPendingReplyData *cprd;
  DBusList *link;
  dbus_uint32_t reply_serial;
  
  _dbus_assert (sending_reply != NULL);
  _dbus_assert (receiving_reply != NULL);

  reply_serial = dbus_message_get_reply_serial (reply);

  link = bus_expire_list_get_first_link (connections->pending_replies);
  while (link != NULL)
    {
      BusPendingReply *pending = link->data;

      if (pending->reply_serial == reply_serial &&
          pending->will_get_reply == receiving_reply &&
          pending->will_send_reply == sending_reply)
        {
          _dbus_verbose ("Found pending reply with serial %u\n", reply_serial);
          break;
        }
      
      link = bus_expire_list_get_next_link (connections->pending_replies,
                                            link);
    }

  if (link == NULL)
    {
      _dbus_verbose ("No pending reply expected\n");

      return FALSE;
    }

  cprd = dbus_new0 (CheckPendingReplyData, 1);
  if (cprd == NULL)
    {
      BUS_SET_OOM (error);
      return FALSE;
    }
  
  if (!bus_transaction_add_cancel_hook (transaction,
                                        cancel_check_pending_reply,
                                        cprd,
                                        check_pending_reply_data_free))
    {
      BUS_SET_OOM (error);
      dbus_free (cprd);
      return FALSE;
    }

  cprd->link = link;
  cprd->connections = connections;
  
  bus_expire_list_unlink (connections->pending_replies,
                          link);
  
  _dbus_assert (!bus_expire_list_contains_item (connections->pending_replies, link->data));

  return TRUE;
}

/*
 * Transactions
 *
 * Note that this is fairly fragile; in particular, don't try to use
 * one transaction across any main loop iterations.
 */

typedef struct
{
  BusTransaction *transaction;
  DBusMessage    *message;
  DBusPreallocatedSend *preallocated;
} MessageToSend;

typedef struct
{
  BusTransactionCancelFunction cancel_function;
  DBusFreeFunction free_data_function;
  void *data;
} CancelHook;

struct BusTransaction
{
  DBusList *connections;
  BusContext *context;
  DBusList *cancel_hooks;
};

static void
message_to_send_free (DBusConnection *connection,
                      MessageToSend  *to_send)
{
  if (to_send->message)
    dbus_message_unref (to_send->message);

  if (to_send->preallocated)
    dbus_connection_free_preallocated_send (connection, to_send->preallocated);

  dbus_free (to_send);
}

static void
cancel_hook_cancel (void *element,
                    void *data)
{
  CancelHook *ch = element;

  _dbus_verbose ("Running transaction cancel hook\n");
  
  if (ch->cancel_function)
    (* ch->cancel_function) (ch->data);  
}

static void
cancel_hook_free (void *element,
                  void *data)
{
  CancelHook *ch = element;

  if (ch->free_data_function)
    (* ch->free_data_function) (ch->data);

  dbus_free (ch);
}

static void
free_cancel_hooks (BusTransaction *transaction)
{
  _dbus_list_foreach (&transaction->cancel_hooks,
                      cancel_hook_free, NULL);
  
  _dbus_list_clear (&transaction->cancel_hooks);
}

BusTransaction*
bus_transaction_new (BusContext *context)
{
  BusTransaction *transaction;

  transaction = dbus_new0 (BusTransaction, 1);
  if (transaction == NULL)
    return NULL;

  transaction->context = context;
  
  return transaction;
}

BusContext*
bus_transaction_get_context (BusTransaction  *transaction)
{
  return transaction->context;
}

/**
 * Reserve enough memory to capture the given message if the
 * transaction goes through.
 */
dbus_bool_t
bus_transaction_capture (BusTransaction *transaction,
                         DBusConnection *sender,
                         DBusConnection *addressed_recipient,
                         DBusMessage    *message)
{
  BusConnections *connections;
  BusMatchmaker *mm;
  DBusList *link;
  DBusList *recipients = NULL;
  dbus_bool_t ret = FALSE;

  connections = bus_context_get_connections (transaction->context);

  /* shortcut: don't compose the message unless someone wants it */
  if (connections->monitors == NULL)
    return TRUE;

  mm = connections->monitor_matchmaker;
  /* This is non-null if there has ever been a monitor - we don't GC it.
   * There's little point, since there is up to 1 per process. */
  _dbus_assert (mm != NULL);

  if (!bus_matchmaker_get_recipients (mm, connections, sender,
        addressed_recipient, message, &recipients))
    goto out;

  for (link = _dbus_list_get_first_link (&recipients);
      link != NULL;
      link = _dbus_list_get_next_link (&recipients, link))
    {
      DBusConnection *recipient = link->data;

      if (!bus_transaction_send (transaction, recipient, message))
        goto out;
    }

  ret = TRUE;

out:
  _dbus_list_clear (&recipients);
  return ret;
}

dbus_bool_t
bus_transaction_capture_error_reply (BusTransaction  *transaction,
                                     DBusConnection  *addressed_recipient,
                                     const DBusError *error,
                                     DBusMessage     *in_reply_to)
{
  BusConnections *connections;
  DBusMessage *reply;
  dbus_bool_t ret = FALSE;

  _dbus_assert (error != NULL);
  _DBUS_ASSERT_ERROR_IS_SET (error);

  connections = bus_context_get_connections (transaction->context);

  /* shortcut: don't compose the message unless someone wants it */
  if (connections->monitors == NULL)
    return TRUE;

  reply = dbus_message_new_error (in_reply_to,
                                  error->name,
                                  error->message);

  if (reply == NULL)
    return FALSE;

  if (!dbus_message_set_sender (reply, DBUS_SERVICE_DBUS))
    goto out;

  ret = bus_transaction_capture (transaction, NULL, addressed_recipient, reply);

out:
  dbus_message_unref (reply);
  return ret;
}

dbus_bool_t
bus_transaction_send_from_driver (BusTransaction *transaction,
                                  DBusConnection *connection,
                                  DBusMessage    *message)
{
  DBusError error = DBUS_ERROR_INIT;

  /* We have to set the sender to the driver, and have
   * to check security policy since it was not done in
   * dispatch.c
   */
  _dbus_verbose ("Sending %s %s %s from driver\n",
                 dbus_message_get_interface (message) ?
                 dbus_message_get_interface (message) : "(no interface)",
                 dbus_message_get_member (message) ?
                 dbus_message_get_member (message) : "(no member)",
                 dbus_message_get_error_name (message) ?
                 dbus_message_get_error_name (message) : "(no error name)");
                 
  if (!dbus_message_set_sender (message, DBUS_SERVICE_DBUS))
    return FALSE;

  if (bus_connection_is_active (connection))
    {
      if (!dbus_message_set_destination (message,
                                         bus_connection_get_name (connection)))
        return FALSE;
    }
  
  /* bus driver never wants a reply */
  dbus_message_set_no_reply (message, TRUE);

  /* Capture it for monitors, even if the real recipient's receive policy
   * does not allow it to receive this message from us (which would be odd).
   */
  if (!bus_transaction_capture (transaction, NULL, connection, message))
    return FALSE;

  /* If security policy doesn't allow the message, we would silently
   * eat it; the driver doesn't care about getting a reply. However,
   * if we're actively capturing messages, it's nice to log that we
   * tried to send it and did not allow ourselves to do so.
   */
  if (!bus_context_check_security_policy (bus_transaction_get_context (transaction),
                                          transaction,
                                          NULL, connection, connection,
                                          message, NULL, &error))
    {
      if (!bus_transaction_capture_error_reply (transaction, connection,
                                                &error, message))
        {
          bus_context_log (transaction->context, DBUS_SYSTEM_LOG_WARNING,
                           "message from dbus-daemon rejected but not enough "
                           "memory to capture it");
        }

      /* This is not fatal to the transaction so silently eat the disallowed
       * message (see reasoning above) */
      dbus_error_free (&error);
      return TRUE;
    }

  return bus_transaction_send (transaction, connection, message);
}

dbus_bool_t
bus_transaction_send (BusTransaction *transaction,
                      DBusConnection *connection,
                      DBusMessage    *message)
{
  MessageToSend *to_send;
  BusConnectionData *d;
  DBusList *link;

  _dbus_verbose ("  trying to add %s interface=%s member=%s error=%s to transaction%s\n",
                 dbus_message_get_type (message) == DBUS_MESSAGE_TYPE_ERROR ? "error" :
                 dbus_message_get_reply_serial (message) != 0 ? "reply" :
                 "message",
                 dbus_message_get_interface (message) ?
                 dbus_message_get_interface (message) : "(unset)",
                 dbus_message_get_member (message) ?
                 dbus_message_get_member (message) : "(unset)",
                 dbus_message_get_error_name (message) ?
                 dbus_message_get_error_name (message) : "(unset)",
                 dbus_connection_get_is_connected (connection) ?
                 "" : " (disconnected)");

  _dbus_assert (dbus_message_get_sender (message) != NULL);
  
  if (!dbus_connection_get_is_connected (connection))
    return TRUE; /* silently ignore disconnected connections */
  
  d = BUS_CONNECTION_DATA (connection);
  _dbus_assert (d != NULL);
  
  to_send = dbus_new (MessageToSend, 1);
  if (to_send == NULL)
    {
      return FALSE;
    }

  to_send->preallocated = dbus_connection_preallocate_send (connection);
  if (to_send->preallocated == NULL)
    {
      dbus_free (to_send);
      return FALSE;
    }  
  
  dbus_message_ref (message);
  to_send->message = message;
  to_send->transaction = transaction;

  _dbus_verbose ("about to prepend message\n");
  
  if (!_dbus_list_prepend (&d->transaction_messages, to_send))
    {
      message_to_send_free (connection, to_send);
      return FALSE;
    }

  _dbus_verbose ("prepended message\n");
  
  /* See if we already had this connection in the list
   * for this transaction. If we have a pending message,
   * then we should already be in transaction->connections
   */
  link = _dbus_list_get_first_link (&d->transaction_messages);
  _dbus_assert (link->data == to_send);
  link = _dbus_list_get_next_link (&d->transaction_messages, link);
  while (link != NULL)
    {
      MessageToSend *m = link->data;
      DBusList *next = _dbus_list_get_next_link (&d->transaction_messages, link);
      
      if (m->transaction == transaction)
        break;
        
      link = next;
    }

  if (link == NULL)
    {
      if (!_dbus_list_prepend (&transaction->connections, connection))
        {
          _dbus_list_remove (&d->transaction_messages, to_send);
          message_to_send_free (connection, to_send);
          return FALSE;
        }
    }

  return TRUE;
}

static void
transaction_free (BusTransaction *transaction)
{
  _dbus_assert (transaction->connections == NULL);

  free_cancel_hooks (transaction);

  dbus_free (transaction);
}

static void
connection_cancel_transaction (DBusConnection *connection,
                               BusTransaction *transaction)
{
  DBusList *link;
  BusConnectionData *d;
  
  d = BUS_CONNECTION_DATA (connection);
  _dbus_assert (d != NULL);
  
  link = _dbus_list_get_first_link (&d->transaction_messages);
  while (link != NULL)
    {
      MessageToSend *m = link->data;
      DBusList *next = _dbus_list_get_next_link (&d->transaction_messages, link);
      
      if (m->transaction == transaction)
        {
          _dbus_list_remove_link (&d->transaction_messages,
                                  link);
          
          message_to_send_free (connection, m);
        }
        
      link = next;
    }
}

void
bus_transaction_cancel_and_free (BusTransaction *transaction)
{
  DBusConnection *connection;

  _dbus_verbose ("TRANSACTION: cancelled\n");
  
  while ((connection = _dbus_list_pop_first (&transaction->connections)))
    connection_cancel_transaction (connection, transaction);

  _dbus_list_foreach (&transaction->cancel_hooks,
                      cancel_hook_cancel, NULL);

  transaction_free (transaction);
}

static void
connection_execute_transaction (DBusConnection *connection,
                                BusTransaction *transaction)
{
  DBusList *link;
  BusConnectionData *d;
  
  d = BUS_CONNECTION_DATA (connection);
  _dbus_assert (d != NULL);

  /* Send the queue in order (FIFO) */
  link = _dbus_list_get_last_link (&d->transaction_messages);
  while (link != NULL)
    {
      MessageToSend *m = link->data;
      DBusList *prev = _dbus_list_get_prev_link (&d->transaction_messages, link);
      
      if (m->transaction == transaction)
        {
          _dbus_list_remove_link (&d->transaction_messages,
                                  link);

          _dbus_assert (dbus_message_get_sender (m->message) != NULL);
          
          dbus_connection_send_preallocated (connection,
                                             m->preallocated,
                                             m->message,
                                             NULL);

          m->preallocated = NULL; /* so we don't double-free it */
          
          message_to_send_free (connection, m);
        }
        
      link = prev;
    }
}

void
bus_transaction_execute_and_free (BusTransaction *transaction)
{
  /* For each connection in transaction->connections
   * send the messages
   */
  DBusConnection *connection;

  _dbus_verbose ("TRANSACTION: executing\n");
  
  while ((connection = _dbus_list_pop_first (&transaction->connections)))
    connection_execute_transaction (connection, transaction);

  transaction_free (transaction);
}

static void
bus_connection_remove_transactions (DBusConnection *connection)
{
  MessageToSend *to_send;
  BusConnectionData *d;
  
  d = BUS_CONNECTION_DATA (connection);
  _dbus_assert (d != NULL);
  
  while ((to_send = _dbus_list_get_first (&d->transaction_messages)))
    {
      /* only has an effect for the first MessageToSend listing this transaction */
      _dbus_list_remove (&to_send->transaction->connections,
                         connection);

      _dbus_list_remove (&d->transaction_messages, to_send);
      message_to_send_free (connection, to_send);
    }
}

/**
 * Converts the DBusError to a message reply
 */
dbus_bool_t
bus_transaction_send_error_reply (BusTransaction  *transaction,
                                  DBusConnection  *connection,
                                  const DBusError *error,
                                  DBusMessage     *in_reply_to)
{
  DBusMessage *reply;
  
  _dbus_assert (error != NULL);
  _DBUS_ASSERT_ERROR_IS_SET (error);
  
  _dbus_verbose ("Sending error reply %s \"%s\"\n",
                 error->name, error->message);

  reply = dbus_message_new_error (in_reply_to,
                                  error->name,
                                  error->message);
  if (reply == NULL)
    return FALSE;

  if (!bus_transaction_send_from_driver (transaction, connection, reply))
    {
      dbus_message_unref (reply);
      return FALSE;
    }

  dbus_message_unref (reply);
  
  return TRUE;
}

dbus_bool_t
bus_transaction_add_cancel_hook (BusTransaction               *transaction,
                                 BusTransactionCancelFunction  cancel_function,
                                 void                         *data,
                                 DBusFreeFunction              free_data_function)
{
  CancelHook *ch;

  ch = dbus_new (CancelHook, 1);
  if (ch == NULL)
    return FALSE;

  _dbus_verbose ("     adding cancel hook function = %p data = %p\n",
                 cancel_function, data);
  
  ch->cancel_function = cancel_function;
  ch->data = data;
  ch->free_data_function = free_data_function;

  /* It's important that the hooks get run in reverse order that they
   * were added
   */
  if (!_dbus_list_prepend (&transaction->cancel_hooks, ch))
    {
      dbus_free (ch);
      return FALSE;
    }

  return TRUE;
}

int
bus_connections_get_n_active (BusConnections *connections)
{
  return connections->n_completed;
}

int
bus_connections_get_n_incomplete (BusConnections *connections)
{
  return connections->n_incomplete;
}

#ifdef DBUS_ENABLE_STATS
int
bus_connections_get_total_match_rules (BusConnections *connections)
{
  return connections->total_match_rules;
}

int
bus_connections_get_peak_match_rules (BusConnections *connections)
{
  return connections->peak_match_rules;
}

int
bus_connections_get_peak_match_rules_per_conn (BusConnections *connections)
{
  return connections->peak_match_rules_per_conn;
}

int
bus_connections_get_total_bus_names (BusConnections *connections)
{
  return connections->total_bus_names;
}

int
bus_connections_get_peak_bus_names (BusConnections *connections)
{
  return connections->peak_bus_names;
}

int
bus_connections_get_peak_bus_names_per_conn (BusConnections *connections)
{
  return connections->peak_bus_names_per_conn;
}

int
bus_connection_get_peak_match_rules (DBusConnection *connection)
{
  BusConnectionData *d;

  d = BUS_CONNECTION_DATA (connection);
  _dbus_assert(d != NULL);

  return d->peak_match_rules;
}

int
bus_connection_get_peak_bus_names (DBusConnection *connection)
{
  BusConnectionData *d;

  d = BUS_CONNECTION_DATA (connection);
  _dbus_assert(d != NULL);

  return d->peak_bus_names;
}
#endif /* DBUS_ENABLE_STATS */

dbus_bool_t
bus_connection_is_monitor (DBusConnection *connection)
{
  BusConnectionData *d;

  d = BUS_CONNECTION_DATA (connection);
  _dbus_assert(d != NULL);

  return d->link_in_monitors != NULL;
}

static dbus_bool_t
bcd_add_monitor_rules (BusConnectionData  *d,
                       DBusConnection     *connection,
                       DBusList          **rules)
{
  BusMatchmaker *mm = d->connections->monitor_matchmaker;
  DBusList *iter;

  if (mm == NULL)
    {
      mm = bus_matchmaker_new ();

      if (mm == NULL)
        return FALSE;

      d->connections->monitor_matchmaker = mm;
    }

  for (iter = _dbus_list_get_first_link (rules);
      iter != NULL;
      iter = _dbus_list_get_next_link (rules, iter))
    {
      if (!bus_matchmaker_add_rule (mm, iter->data))
        {
          bus_matchmaker_disconnected (mm, connection);
          return FALSE;
        }
    }

  return TRUE;
}

static void
bcd_drop_monitor_rules (BusConnectionData *d,
                        DBusConnection *connection)
{
  BusMatchmaker *mm = d->connections->monitor_matchmaker;

  if (mm != NULL)
    bus_matchmaker_disconnected (mm, connection);
}

dbus_bool_t
bus_connection_be_monitor (DBusConnection  *connection,
                           BusTransaction  *transaction,
                           DBusList       **rules,
                           DBusError       *error)
{
  BusConnectionData *d;
  DBusList *link;
  DBusList *tmp;
  DBusList *iter;

  d = BUS_CONNECTION_DATA (connection);
  _dbus_assert (d != NULL);

  link = _dbus_list_alloc_link (connection);

  if (link == NULL)
    {
      BUS_SET_OOM (error);
      return FALSE;
    }

  if (!bcd_add_monitor_rules (d, connection, rules))
    {
      _dbus_list_free_link (link);
      BUS_SET_OOM (error);
      return FALSE;
    }

  /* release all its names */
  if (!_dbus_list_copy (&d->services_owned, &tmp))
    {
      bcd_drop_monitor_rules (d, connection);
      _dbus_list_free_link (link);
      BUS_SET_OOM (error);
      return FALSE;
    }

  for (iter = _dbus_list_get_first_link (&tmp);
      iter != NULL;
      iter = _dbus_list_get_next_link (&tmp, iter))
    {
      BusService *service = iter->data;

      /* This call is transactional: if there isn't enough memory to
       * do everything, then the service gets all its names back when
       * the transaction is cancelled due to OOM. */
      if (!bus_service_remove_owner (service, connection, transaction, error))
        {
          bcd_drop_monitor_rules (d, connection);
          _dbus_list_free_link (link);
          _dbus_list_clear (&tmp);
          return FALSE;
        }
    }

  /* We have now done everything that can fail, so there is no problem
   * with doing the irrevocable stuff. */

  _dbus_list_clear (&tmp);

  bus_context_log (transaction->context, DBUS_SYSTEM_LOG_INFO,
                   "Connection %s (%s) became a monitor.", d->name,
                   d->cached_loginfo_string);

  if (d->n_match_rules > 0)
    {
      BusMatchmaker *mm;

      mm = bus_context_get_matchmaker (d->connections->context);
      bus_matchmaker_disconnected (mm, connection);
    }

  /* flag it as a monitor */
  d->link_in_monitors = link;
  _dbus_list_append_link (&d->connections->monitors, link);

  /* it isn't allowed to reply, and it is no longer relevant whether it
   * receives replies */
  bus_connection_drop_pending_replies (d->connections, connection);

  return TRUE;
}