File: flatpak-proxy.c

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

#include "config.h"

#include <unistd.h>
#include <string.h>

#include "flatpak-proxy.h"

#include <gio/gunixsocketaddress.h>
#include <gio/gunixconnection.h>
#include <gio/gunixfdmessage.h>

#if !GLIB_CHECK_VERSION(2, 58, 0)
# define G_SOURCE_FUNC(f) ((GSourceFunc) (void (*)(void)) (f))
#endif

/**
 * The proxy listens to a unix domain socket, and for each new
 * connection it opens up a new connection to a specified dbus bus
 * address (typically the session bus) and forwards data between the
 * two. During the authentication phase all data is forwarded as
 * received, and additionally for the first 1 byte zero we also send
 * the proxy credentials to the bus.
 *
 * Once the connection is authenticated there are two modes, filtered
 * and unfiltered. In the unfiltered mode we just send all messages on
 * as we receive, but in the in the filtering mode we apply a policy,
 * which is similar to the policy supported by kdbus.
 *
 * The policy for the filtering consists of a mapping from well-known
 * names to a policy that is either SEE, TALK or OWN. The default
 * initial policy is that the the user is only allowed to TALK to the
 * bus itself (org.freedesktop.DBus, or no destination specified), and
 * TALK to its own unique id. All other clients are invisible. The
 * well-known names can be specified exactly, or as a arg0namespace
 * wildcards like "org.foo.*" which matches "org.foo", "org.foo.bar",
 * and "org.foo.bar.gazonk", but not "org.foobar".
 *
 * Polices are specified for well-known names, but they also affect
 * the owner of that name, so that the policy for a unique id is the
 * superset of the polices for all the names it owns. Due to technical
 * reasons the policy for a unique name is "sticky", in that we keep
 * the highest policy granted by a once-owned name even when the client
 * releases that name. This is impossible to avoid in a race-free way
 * in a proxy. But this is rarely a problem in practice, as clients
 * rarely release names and stay on the bus.
 *
 * Here is a description of the policy levels:
 * (all policy levels also imply the ones before it)
 *
 * SEE:
 *    The name/id is visible in the ListNames reply
 *    The name/id is visible in the ListActivatableNames reply
 *    You can call GetNameOwner on the name
 *    You can call NameHasOwner on the name
 *    You see NameOwnerChanged signals on the name
 *    You see NameOwnerChanged signals on the id when the client disconnects
 *    You can call the GetXXX methods on the name/id to get e.g. the peer pid
 *    You get AccessDenied rather than NameHasNoOwner when sending messages to the name/id
 *
 * TALK:
 *    You can send any method calls and signals to the name/id
 *    You will receive broadcast signals from the name/id (if you have a match rule for them)
 *    You can call StartServiceByName on the name
 *
 * OWN:
 *    You are allowed to call RequestName/ReleaseName/ListQueuedOwners on the name.
 *
 * Additionally, there can be more detailed filters installed that
 * limits what messages you can send to and receive broadcasts from.
 * However, if you can *ever* call or recieve broadcasts from a name (even if
 * filtered to some subset of paths/interfaces) its visibility is considered
 * to be as TALK.
 *
 * The policy applies only to outgoing signals and method calls and
 * incoming broadcast. All replies (errors or method returns) are
 * allowed once for an outstanding method call, and never
 * otherwise.
 *
 * Every peer on the bus is considered priviledged, and we thus trust
 * it and don't apply any filtering (except broadcasts). So we rely on
 * similar proxies to be running for all untrusted clients. Any such
 * priviledged peer is allowed to send method call or unicast signal
 * messages to the proxied client. Once another peer
 * sends you a message the unique id of that peer is now made visible
 * (policy SEE) to the proxied client, allowing the client to track
 * caller lifetimes via NameOwnerChanged signals.
 *
 * Differences to kdbus custom endpoint policies:
 *
 *  * The proxy will return the credentials (like pid) of the proxy,
 *    not the real client.
 *
 *  * Policy is not dropped when a peer releases a name.
 *
 *  * Peers that call you become visible (SEE) (and get signals for
 *    NameOwnerChange disconnect) In kdbus currently custom endpoints
 *    never get NameOwnerChange signals for unique ids, but this is
 *    problematic as it disallows a services to track lifetimes of its
 *    clients.
 *
 * Mode of operation
 *
 * Once authenticated we receive incoming messages one at a time,
 * and then we demarshal the message headers to make routing decisions.
 * This means we trust the bus to do message format validation, etc.
 * (because we don't parse the body). Also we assume that the bus verifies
 * reply_serials, i.e. that a reply can only be sent once and by the real
 * recipient of an previously sent method call.
 *
 * Serial numbers larger than MAX_CLIENT_SERIAL reserved for messages created by the
 * proxy itself (fake messages). This limits the possible values of serials
 * available to the client to the value of MAX_CLIENT_SERIAL. Versions
 * older than 0.1.6 required monotonically increasing serials instead. This
 * mechanism was dropped since it caused regular issues with multiple D-Bus
 * clients.
 *
 * In order to track the ownership of the allowed names we hijack the
 * connection after the initial Hello message, sending AddMatch,
 * ListNames and GetNameOwner messages to get a proper view of who
 * owns the names atm. Then we listen to NameOwnerChanged events for
 * further updates. This causes some serials abow MAX_CLIENT_SERIAL to be
 * used for "fake messages".
 *
 * After that the filter is strictly passive, in that we never
 * construct our own requests. For each message received from the
 * client we look up the type and the destination policy and make a
 * decision to either pass it on as is, rewrite it before passing on
 * (for instance ListName replies), drop it completely, or return a
 * made-up reply/error to the sender.
 *
 * When returning a made-up reply we replace the actual message with a
 * Ping request to the bus with the same serial and replace the resulting
 * reply with the made up reply (with the serial from the Ping reply).
 * This means we keep the strict message ordering and serial numbers of
 * the bus.
 *
 * Policy is applied to unique ids in the following cases:
 *  * During startup we call AddWatch for signals on all policy names
 *    and wildcards (using arg0namespace) so that we get NameOwnerChanged
 *    events which we use to update the unique id policies.
 *  * During startup we create synthetic GetNameOwner requests for all
 *    normal policy names, and if there are wildcarded names we create a
 *    synthetic ListNames request and use the results of that to do further
 *    GetNameOwner for the existing names matching the wildcards. When we get
 *    replies for the GetNameOwner requests the unique id policy is updated.
 *  * When we get a method call from a unique id, it gets SEE
 *  * When we get a reply to the initial Hello request we give
 *    our own assigned unique id policy TALK.
 *
 * There is also a mode called "sloppy-names" where you automatically get
 * SEE access to all the unique names on the bus. This is used only for
 * the a11y bus.
 *
 * All messages sent to the bus itself are fully demarshalled
 * and handled on a per-method basis:
 *
 * Hello, AddMatch, RemoveMatch, GetId: Always allowed
 * ListNames, ListActivatableNames: Always allowed, but response filtered
 * UpdateActivationEnvironment, BecomeMonitor: Always denied
 * RequestName, ReleaseName, ListQueuedOwners: Only allowed if arg0 is a name with policy OWN
 * NameHasOwner, GetNameOwner: Only pass on if arg0 is a name with policy SEE, otherwise return synthetic reply
 * StartServiceByName: Only allowed if policy TALK on arg0
 * GetConnectionUnixProcessID, GetConnectionCredentials,
 *  GetAdtAuditSessionData, GetConnectionSELinuxSecurityContext,
 *  GetConnectionUnixUser: Allowed if policy SEE on arg0
 *
 * For unknown methods, we return a synthetic error.
 */

typedef struct FlatpakProxyClient FlatpakProxyClient;

#define FIND_AUTH_END_CONTINUE -1
#define FIND_AUTH_END_ABORT -2

#define AUTH_LINE_SENTINEL "\r\n"
#define AUTH_BEGIN "BEGIN"

// Use a relatively hight number since there are not a lot of fake requests we need to do
#define MAX_CLIENT_SERIAL (G_MAXUINT32 - 65536)

typedef enum {
  /* The client has not sent BEGIN yet */
  AUTH_WAITING_FOR_BEGIN,
  /* The client sent BEGIN, but the server has not yet responded to the auth
     messages that the client sent before */
  AUTH_WAITING_FOR_BACKLOG,
  /* Authentication is fully complete */
  AUTH_COMPLETE,
} AuthState;

typedef enum {
  EXPECTED_REPLY_NONE,
  EXPECTED_REPLY_NORMAL,
  EXPECTED_REPLY_HELLO,
  EXPECTED_REPLY_FILTER,
  EXPECTED_REPLY_FAKE_GET_NAME_OWNER,
  EXPECTED_REPLY_FAKE_LIST_NAMES,
  EXPECTED_REPLY_LIST_NAMES,
  EXPECTED_REPLY_REWRITE,
} ExpectedReplyType;

typedef struct
{
  /* During write and message parsing this is the size of the valid data in the buffer.
     During reads this is the capacity of the buffer. */
  gsize    size;
  /* Offset to the first writable position (the buffer is full when pos ==
   * size) */
  gsize    pos;
  /* Offset to the first byte that hasn't been sent yet */
  gsize    sent;
  int      refcount;
  gboolean send_credentials;
  GList   *control_messages;

  guchar   data[16];
  /* data continues here */
} Buffer;

typedef struct
{
  Buffer     *buffer;
  gboolean    big_endian;
  guchar      type;
  guchar      flags;
  guint32     length;
  guint32     serial;
  const char *path;
  const char *interface;
  const char *member;
  const char *error_name;
  const char *destination;
  const char *sender;
  const char *signature;
  gboolean    has_reply_serial;
  guint32     reply_serial;
  guint32     unix_fds;
} Header;

typedef enum {
  FILTER_TYPE_CALL = 1 << 0,
  FILTER_TYPE_BROADCAST = 1 << 1,
} FilterTypeMask;

#define FILTER_TYPE_ALL (FILTER_TYPE_CALL | FILTER_TYPE_BROADCAST)

typedef struct
{
  char         *name;
  gboolean      name_is_subtree;
  FlatpakPolicy policy;

  /* More detailed filter */
  FilterTypeMask types;
  char          *path;
  gboolean       path_is_subtree;
  char          *interface;
  char          *member;
} Filter;

static void header_free (Header *header);
G_DEFINE_AUTOPTR_CLEANUP_FUNC (Header, header_free)

typedef struct
{
  gboolean            got_first_byte; /* always true on bus side */
  gboolean            closed; /* always true on bus side */

  FlatpakProxyClient *client;
  GSocketConnection  *connection;
  GSource            *in_source;
  GSource            *out_source;

  GBytes             *extra_input_data;
  Buffer             *current_read_buffer;
  Buffer              header_buffer;

  GList              *buffers; /* to be sent */
  GList              *control_messages;

  GHashTable         *expected_replies;
} ProxySide;

struct FlatpakProxyClient
{
  GObject       parent;

  FlatpakProxy *proxy;

  AuthState     auth_state;
  gsize         auth_requests;
  gsize         auth_replies;
  GByteArray   *auth_buffer;

  ProxySide     client_side;
  ProxySide     bus_side;

  /* Filtering data: */
  guint32     hello_serial;
  guint32     last_fake_serial;
  GHashTable *rewrite_reply;
  GHashTable *get_owner_reply;

  GHashTable *unique_id_policy;
  GHashTable *unique_id_owned_names;
};

typedef struct
{
  GObjectClass parent_class;
} FlatpakProxyClientClass;

struct FlatpakProxy
{
  GSocketService parent;

  gboolean       log_messages;

  GList         *clients;
  char          *socket_path;
  char          *dbus_address;

  gboolean       filter;
  gboolean       sloppy_names;

  GHashTable    *filters;
};

typedef struct
{
  GSocketServiceClass parent_class;
} FlatpakProxyClass;


enum {
  PROP_0,

  PROP_DBUS_ADDRESS,
  PROP_SOCKET_PATH
};

#define FLATPAK_TYPE_PROXY flatpak_proxy_get_type ()
#define FLATPAK_PROXY(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), FLATPAK_TYPE_PROXY, FlatpakProxy))
#define FLATPAK_IS_PROXY(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), FLATPAK_TYPE_PROXY))


#define FLATPAK_TYPE_PROXY_CLIENT flatpak_proxy_client_get_type ()
#define FLATPAK_PROXY_CLIENT(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), FLATPAK_TYPE_PROXY_CLIENT, FlatpakProxyClient))
#define FLATPAK_IS_PROXY_CLIENT(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), FLATPAK_TYPE_PROXY_CLIENT))

GType flatpak_proxy_client_get_type (void);

G_DEFINE_TYPE (FlatpakProxy, flatpak_proxy, G_TYPE_SOCKET_SERVICE)
G_DEFINE_TYPE (FlatpakProxyClient, flatpak_proxy_client, G_TYPE_OBJECT)

static void start_reading (ProxySide *side);
static void stop_reading (ProxySide *side);

static void
string_list_free (GList *filters)
{
  g_list_free_full (filters, (GDestroyNotify) g_free);
}

static void
buffer_unref (Buffer *buffer)
{
  g_assert (buffer->refcount > 0);
  buffer->refcount--;

  if (buffer->refcount == 0)
    {
      g_list_free_full (buffer->control_messages, g_object_unref);
      g_free (buffer);
    }
}

static Buffer *
buffer_ref (Buffer *buffer)
{
  g_assert (buffer->refcount > 0);
  buffer->refcount++;
  return buffer;
}

static void
free_side (ProxySide *side)
{
  g_clear_object (&side->connection);
  g_clear_pointer (&side->extra_input_data, g_bytes_unref);

  g_list_free_full (side->buffers, (GDestroyNotify) buffer_unref);
  g_list_free_full (side->control_messages, (GDestroyNotify) g_object_unref);

  if (side->in_source)
    g_source_destroy (side->in_source);
  if (side->out_source)
    g_source_destroy (side->out_source);

  g_hash_table_destroy (side->expected_replies);
}

static void
flatpak_proxy_client_finalize (GObject *object)
{
  FlatpakProxyClient *client = FLATPAK_PROXY_CLIENT (object);

  client->proxy->clients = g_list_remove (client->proxy->clients, client);
  g_clear_object (&client->proxy);

  g_byte_array_free (client->auth_buffer, TRUE);
  g_hash_table_destroy (client->rewrite_reply);
  g_hash_table_destroy (client->get_owner_reply);
  g_hash_table_destroy (client->unique_id_policy);
  g_hash_table_destroy (client->unique_id_owned_names);

  free_side (&client->client_side);
  free_side (&client->bus_side);

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

static void
flatpak_proxy_client_class_init (FlatpakProxyClientClass *klass)
{
  GObjectClass *object_class = G_OBJECT_CLASS (klass);

  object_class->finalize = flatpak_proxy_client_finalize;
}

static void
init_side (FlatpakProxyClient *client, ProxySide *side)
{
  side->got_first_byte = (side == &client->bus_side);
  side->client = client;
  side->header_buffer.size = 16;
  side->header_buffer.pos = 0;
  side->current_read_buffer = &side->header_buffer;
  side->expected_replies = g_hash_table_new (g_direct_hash, g_direct_equal);
}

static void
flatpak_proxy_client_init (FlatpakProxyClient *client)
{
  init_side (client, &client->client_side);
  init_side (client, &client->bus_side);

  client->last_fake_serial = MAX_CLIENT_SERIAL;
  client->auth_buffer = g_byte_array_new ();
  client->rewrite_reply = g_hash_table_new_full (g_direct_hash, g_direct_equal, NULL, g_object_unref);
  client->get_owner_reply = g_hash_table_new_full (g_direct_hash, g_direct_equal, NULL, g_free);
  client->unique_id_policy = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
  client->unique_id_owned_names = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, (GDestroyNotify) string_list_free);
}

static FlatpakProxyClient *
flatpak_proxy_client_new (FlatpakProxy *proxy, GSocketConnection *connection)
{
  FlatpakProxyClient *client;

  g_socket_set_blocking (g_socket_connection_get_socket (connection), FALSE);

  client = g_object_new (FLATPAK_TYPE_PROXY_CLIENT, NULL);
  client->proxy = g_object_ref (proxy);
  client->client_side.connection = g_object_ref (connection);

  proxy->clients = g_list_prepend (proxy->clients, client);

  return client;
}

void
flatpak_proxy_set_filter (FlatpakProxy *proxy,
                          gboolean      filter)
{
  proxy->filter = filter;
}

void
flatpak_proxy_set_sloppy_names (FlatpakProxy *proxy,
                                gboolean      sloppy_names)
{
  proxy->sloppy_names = sloppy_names;
}

void
flatpak_proxy_set_log_messages (FlatpakProxy *proxy,
                                gboolean      log)
{
  proxy->log_messages = log;
}

static void
filter_free (Filter *filter)
{
  g_free (filter->name);
  g_free (filter->path);
  g_free (filter->interface);
  g_free (filter->member);
  g_free (filter);
}

static void
filter_list_free (GList *filters)
{
  g_list_free_full (filters, (GDestroyNotify) filter_free);
}


static Filter *
filter_new (const char   *name,
            gboolean      name_is_subtree,
            FlatpakPolicy policy)
{
  Filter *filter = g_new0 (Filter, 1);

  filter->name = g_strdup (name);
  filter->name_is_subtree = name_is_subtree;
  filter->policy = policy;
  filter->types = FILTER_TYPE_ALL;

  return filter;
}

// rules are of the form [*|org.the.interface.[method|*]]|[@/obj/path[/*]]
static Filter *
filter_new_from_rule (const char    *name,
                      gboolean       name_is_subtree,
                      FilterTypeMask types,
                      const char    *rule)
{
  Filter *filter;
  const char *obj_path_start = NULL;
  const char *method_end = NULL;

  filter = filter_new (name, name_is_subtree, FLATPAK_POLICY_TALK);
  filter->types = types;

  obj_path_start = strchr (rule, '@');
  if (obj_path_start && obj_path_start[1] != 0)
    {
      filter->path = g_strdup (obj_path_start + 1);

      if (g_str_has_suffix (filter->path, "/*"))
        {
          filter->path_is_subtree = TRUE;
          filter->path[strlen (filter->path) - 2] = 0;
        }
    }

  if (obj_path_start != NULL)
    method_end = obj_path_start;
  else
    method_end = rule + strlen (rule);

  if (method_end != rule)
    {
      if (rule[0] == '*')
        {
          /* Both interface and method wildcarded */
        }
      else
        {
          filter->interface = g_strndup (rule, method_end - rule);
          char *dot = strrchr (filter->interface, '.');
          if (dot != NULL)
            {
              *dot = 0;
              if (strcmp (dot + 1, "*") != 0)
                filter->member = g_strdup (dot + 1);
            }
        }
    }

  return filter;
}

static gboolean
filter_matches (Filter        *filter,
                FilterTypeMask type,
                const char    *path,
                const char    *interface,
                const char    *member)
{
  if (filter->policy < FLATPAK_POLICY_TALK ||
      (filter->types & type) == 0)
    return FALSE;

  if (filter->path)
    {
      if (path == NULL)
        return FALSE;

      if (filter->path_is_subtree)
        {
          gsize filter_path_len = strlen (filter->path);
          if (strncmp (path, filter->path, filter_path_len) != 0 ||
              (path[filter_path_len] != 0 && path[filter_path_len] != '/'))
            return FALSE;
        }
      else if (strcmp (filter->path, path) != 0)
        return FALSE;
    }

  if (filter->interface && g_strcmp0 (filter->interface, interface) != 0)
    return FALSE;

  if (filter->member && g_strcmp0 (filter->member, member) != 0)
    return FALSE;

  return TRUE;
}

static gboolean
any_filter_matches (GList         *filters,
                    FilterTypeMask type,
                    const char    *path,
                    const char    *interface,
                    const char    *member)
{
  GList *l;

  for (l = filters; l != NULL; l = l->next)
    {
      Filter *filter = l->data;
      if (filter_matches (filter, type, path, interface, member))
        return TRUE;
    }

  return FALSE;
}


static void
flatpak_proxy_add_filter (FlatpakProxy *proxy,
                          Filter       *filter)
{
  GList *filters, *new_filters;

  if (g_hash_table_lookup_extended (proxy->filters,
                                    filter->name,
                                    NULL, (void **) &filters))
    {
      new_filters = g_list_append (filters, filter);
      g_assert (new_filters == filters);
    }
  else
    {
      filters = g_list_append (NULL, filter);
      g_hash_table_insert (proxy->filters, g_strdup (filter->name), filters);
    }
}

void
flatpak_proxy_add_policy (FlatpakProxy *proxy,
                          const char   *name,
                          gboolean      name_is_subtree,
                          FlatpakPolicy policy)
{
  Filter *filter = filter_new (name, name_is_subtree, policy);

  flatpak_proxy_add_filter (proxy, filter);
}

void
flatpak_proxy_add_call_rule (FlatpakProxy *proxy,
                             const char   *name,
                             gboolean      name_is_subtree,
                             const char   *rule)
{
  Filter *filter = filter_new_from_rule (name, name_is_subtree, FILTER_TYPE_CALL, rule);

  flatpak_proxy_add_filter (proxy, filter);
}

void
flatpak_proxy_add_broadcast_rule (FlatpakProxy *proxy,
                                  const char   *name,
                                  gboolean      name_is_subtree,
                                  const char   *rule)
{
  Filter *filter = filter_new_from_rule (name, name_is_subtree, FILTER_TYPE_BROADCAST, rule);

  flatpak_proxy_add_filter (proxy, filter);
}

static void
flatpak_proxy_finalize (GObject *object)
{
  FlatpakProxy *proxy = FLATPAK_PROXY (object);

  if (g_socket_service_is_active (G_SOCKET_SERVICE (proxy)))
    unlink (proxy->socket_path);

  g_assert (proxy->clients == NULL);

  g_hash_table_destroy (proxy->filters);

  g_free (proxy->socket_path);
  g_free (proxy->dbus_address);

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

static void
flatpak_proxy_set_property (GObject      *object,
                            guint         prop_id,
                            const GValue *value,
                            GParamSpec   *pspec)
{
  FlatpakProxy *proxy = FLATPAK_PROXY (object);

  switch (prop_id)
    {
    case PROP_DBUS_ADDRESS:
      proxy->dbus_address = g_value_dup_string (value);
      break;

    case PROP_SOCKET_PATH:
      proxy->socket_path = g_value_dup_string (value);
      break;

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

static void
flatpak_proxy_get_property (GObject    *object,
                            guint       prop_id,
                            GValue     *value,
                            GParamSpec *pspec)
{
  FlatpakProxy *proxy = FLATPAK_PROXY (object);

  switch (prop_id)
    {
    case PROP_DBUS_ADDRESS:
      g_value_set_string (value, proxy->dbus_address);
      break;

    case PROP_SOCKET_PATH:
      g_value_set_string (value, proxy->socket_path);
      break;

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

/* Buffer contains a default size of data that is 16 bytes, so that
   it can be used on the stack for reading the header. However we
   also support passing in sizes smaller that 16, which will allocate
   a smaller object than the full Buffer object. This is safe as we
   respect the size member, however there is no way for GCC to know this,
   so we silence it manually.
*/
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Warray-bounds"
static Buffer *
buffer_new (gsize size, Buffer *old)
{
  Buffer *buffer = g_malloc0 (sizeof (Buffer) + size - 16);

  buffer->control_messages = NULL;
  buffer->size = size;
  buffer->refcount = 1;

  if (old)
    {
      buffer->pos = old->pos;
      buffer->sent = old->sent;
      /* Takes ownership of any old control messages */
      buffer->control_messages = old->control_messages;
      old->control_messages = NULL;

      g_assert (size >= old->size);
      memcpy (buffer->data, old->data, old->size);
    }

  return buffer;
}
#pragma GCC diagnostic pop

static ProxySide *
get_other_side (ProxySide *side)
{
  FlatpakProxyClient *client = side->client;

  if (side == &client->client_side)
    return &client->bus_side;

  return &client->client_side;
}

static void
side_closed (ProxySide *side)
{
  GSocket *socket, *other_socket;
  ProxySide *other_side = get_other_side (side);

  if (side->closed)
    return;

  socket = g_socket_connection_get_socket (side->connection);
  g_socket_close (socket, NULL);
  side->closed = TRUE;

  other_socket = g_socket_connection_get_socket (other_side->connection);
  if (!other_side->closed && other_side->buffers == NULL)
    {
      g_socket_close (other_socket, NULL);
      other_side->closed = TRUE;
    }

  if (other_side->closed)
    {
      g_object_unref (side->client);
    }
  else
    {
      GError *error = NULL;

      if (!g_socket_shutdown (other_socket, TRUE, FALSE, &error))
        {
          g_warning ("Unable to shutdown read side: %s", error->message);
          g_error_free (error);
        }
    }
}

static gboolean
buffer_read (ProxySide *side,
             Buffer    *buffer,
             GSocket   *socket)
{
  FlatpakProxyClient *client = side->client;
  gsize received = 0;
  GInputVector v;
  GError *error = NULL;
  GSocketControlMessage **messages;
  int num_messages, i;

  if (client->auth_state == AUTH_WAITING_FOR_BACKLOG &&
      side == &client->client_side)
    return FALSE;

  if (side->extra_input_data && client->auth_state == AUTH_COMPLETE)
    {
      gsize extra_size;
      const guchar *extra_bytes = g_bytes_get_data (side->extra_input_data, &extra_size);

      g_assert (buffer->size >= buffer->pos);
      received = MIN (extra_size, buffer->size - buffer->pos);
      memcpy (&buffer->data[buffer->pos], extra_bytes, received);

      if (received < extra_size)
        {
          side->extra_input_data =
            g_bytes_new_with_free_func (extra_bytes + received,
                                        extra_size - received,
                                        (GDestroyNotify) g_bytes_unref,
                                        side->extra_input_data);
        }
      else
        {
          g_clear_pointer (&side->extra_input_data, g_bytes_unref);
        }
    }
  else if (!side->extra_input_data)
    {
      gssize res;
      int flags = 0;
      v.buffer = &buffer->data[buffer->pos];
      v.size = buffer->size - buffer->pos;

      res = g_socket_receive_message (socket, NULL, &v, 1,
                                      &messages,
                                      &num_messages,
                                      &flags, NULL, &error);
      if (res < 0 && g_error_matches (error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK))
        {
          g_error_free (error);
          return FALSE;
        }

      if (res <= 0)
        {
          if (res != 0)
            {
              g_debug ("Error reading from socket: %s", error->message);
              g_error_free (error);
            }

          side_closed (side);
          return FALSE;
        }

      /* We now know res is strictly positive */
      received = (gsize) res;

      for (i = 0; i < num_messages; i++)
        buffer->control_messages = g_list_append (buffer->control_messages, messages[i]);

      g_free (messages);
    }

  buffer->pos += received;
  return TRUE;
}

static gboolean
buffer_write (ProxySide *side,
              Buffer    *buffer,
              GSocket   *socket)
{
  gssize res;
  GOutputVector v;
  GError *error = NULL;
  GSocketControlMessage **messages = NULL;
  int i, n_messages;
  GList *l;

  if (buffer->send_credentials &&
      G_IS_UNIX_CONNECTION (side->connection))
    {
      g_assert (buffer->size == 1);

      if (!g_unix_connection_send_credentials (G_UNIX_CONNECTION (side->connection),
                                               NULL,
                                               &error))
        {
          if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK))
            {
              g_error_free (error);
              return FALSE;
            }

          g_warning ("Error writing credentials to socket: %s", error->message);
          g_error_free (error);

          side_closed (side);
          return FALSE;
        }

      buffer->sent = 1;
      return TRUE;
    }

  n_messages = g_list_length (buffer->control_messages);
  messages = g_new (GSocketControlMessage *, n_messages);
  for (l = buffer->control_messages, i = 0; l != NULL; l = l->next, i++)
    messages[i] = l->data;

  v.buffer = &buffer->data[buffer->sent];
  v.size = buffer->pos - buffer->sent;

  res = g_socket_send_message (socket, NULL, &v, 1,
                               messages, n_messages,
                               G_SOCKET_MSG_NONE, NULL, &error);
  g_free (messages);
  if (res < 0 && g_error_matches (error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK))
    {
      g_error_free (error);
      return FALSE;
    }

  if (res <= 0)
    {
      if (res < 0)
        {
          g_warning ("Error writing credentials to socket: %s", error->message);
          g_error_free (error);
        }

      side_closed (side);
      return FALSE;
    }

  g_list_free_full (buffer->control_messages, g_object_unref);
  buffer->control_messages = NULL;

  buffer->sent += res;
  return TRUE;
}

static gboolean
send_outgoing_buffers (GSocket *socket, ProxySide *side)
{
  FlatpakProxyClient *client = side->client;
  gboolean all_done = FALSE;

  g_object_ref (client);

  while (side->buffers)
    {
      Buffer *buffer = side->buffers->data;

      if (buffer_write (side, buffer, socket))
        {
          if (buffer->sent == buffer->size)
            {
              side->buffers = g_list_delete_link (side->buffers, side->buffers);
              buffer_unref (buffer);
            }
        }
      else
        {
          break;
        }
    }

  if (side->buffers == NULL)
    {
      ProxySide *other_side = get_other_side (side);

      all_done = TRUE;

      if (other_side->closed)
        side_closed (side);
    }

  g_object_unref (client);

  return all_done;
}

static gboolean
side_out_cb (GSocket *socket, GIOCondition condition, gpointer user_data)
{
  ProxySide *side = user_data;

  gboolean all_done = send_outgoing_buffers (socket, side);
  if (all_done)
    {
      side->out_source = NULL;
      return G_SOURCE_REMOVE;
    }
  else
    {
      return G_SOURCE_CONTINUE;
    }
}

static void
queue_expected_reply (ProxySide *side, guint32 serial, ExpectedReplyType type)
{
  g_hash_table_replace (side->expected_replies,
                        GUINT_TO_POINTER (serial),
                        GUINT_TO_POINTER (type));
}

static ExpectedReplyType
steal_expected_reply (ProxySide *side, guint32 serial)
{
  ExpectedReplyType type;

  type = GPOINTER_TO_UINT (g_hash_table_lookup (side->expected_replies,
                                                GUINT_TO_POINTER (serial)));
  if (type)
    g_hash_table_remove (side->expected_replies,
                         GUINT_TO_POINTER (serial));
  return type;
}


static void
queue_outgoing_buffer (ProxySide *side, Buffer *buffer)
{
  if (side->out_source == NULL)
    {
      GSocket *socket;

      socket = g_socket_connection_get_socket (side->connection);
      side->out_source = g_socket_create_source (socket, G_IO_OUT, NULL);
      g_source_set_callback (side->out_source, G_SOURCE_FUNC (side_out_cb), side, NULL);
      g_source_attach (side->out_source, NULL);
      g_source_unref (side->out_source);
    }

  side->buffers = g_list_append (side->buffers, buffer);
}

static guint32
read_uint32 (Header *header, guint8 *ptr)
{
  if (header->big_endian)
    return GUINT32_FROM_BE (*(guint32 *) ptr);
  else
    return GUINT32_FROM_LE (*(guint32 *) ptr);
}

static inline guint32
align_by_8 (guint32 offset)
{
  return (offset + 8 - 1) & ~(8 - 1);
}

static inline guint32
align_by_4 (guint32 offset)
{
  return (offset + 4 - 1) & ~(4 - 1);
}

static const char *
get_signature (Buffer *buffer, guint32 *offset, guint32 end_offset)
{
  guint8 len;
  char *str;

  if (*offset >= end_offset)
    return FALSE;

  len = buffer->data[*offset];
  (*offset)++;

  if ((*offset) + len + 1 > end_offset)
    return FALSE;

  if (buffer->data[(*offset) + len] != 0)
    return FALSE;

  str = (char *) &buffer->data[(*offset)];
  *offset += len + 1;

  return str;
}

static const char *
get_string (Buffer *buffer, Header *header, guint32 *offset, guint32 end_offset, GError **error)
{
  guint32 len;
  char *str;

  *offset = align_by_4 (*offset);
  if (*offset + 4  >= end_offset)
    {
      g_set_error (error,
                   G_IO_ERROR,
                   G_IO_ERROR_INVALID_DATA,
                   "String header would align past boundary");
      return FALSE;
    }

  len = read_uint32 (header, &buffer->data[*offset]);
  *offset += 4;

  if ((*offset) + len + 1 > end_offset)
    {
      g_set_error (error,
                   G_IO_ERROR,
                   G_IO_ERROR_INVALID_DATA,
                   "String would align past boundary");
      return FALSE;
    }

  if (buffer->data[(*offset) + len] != 0)
    {
      g_set_error (error,
                   G_IO_ERROR,
                   G_IO_ERROR_INVALID_DATA,
                   "String is not nul-terminated (%.*s)",
                   buffer->data[(*offset) + len],
                   (char *) &buffer->data[(*offset)]);
      return FALSE;
    }

  str = (char *) &buffer->data[(*offset)];
  *offset += len + 1;

  return str;
}

static void
header_free (Header *header)
{
  if (header->buffer)
    buffer_unref (header->buffer);
  g_free (header);
}

static const char *
header_debug_str (GString *s, Header *header)
{
  if (header->path)
    g_string_append_printf (s, "\n\tPath: %s", header->path);
  if (header->interface)
    g_string_append_printf (s, "\n\tInterface: %s", header->interface);
  if (header->member)
    g_string_append_printf (s, "\n\tMember: %s", header->member);
  if (header->error_name)
    g_string_append_printf (s, "\n\tError name: %s", header->error_name);
  if (header->destination)
    g_string_append_printf (s, "\n\tDestination: %s", header->destination);
  if (header->sender)
    g_string_append_printf (s, "\n\tSender: %s", header->sender);
  return s->str;
}

static Header *
parse_header (Buffer *buffer, GError **error)
{
  guint32 array_len, header_len;
  guint32 offset, end_offset;
  guint8 header_type;
  const char *signature;
  g_autoptr(GError) str_error = NULL;
  g_autoptr(GString) header_str = NULL;

  g_autoptr(Header) header = g_new0 (Header, 1);

  header->buffer = buffer_ref (buffer);

  if (buffer->size < 16)
    {
      g_set_error (error,
                   G_IO_ERROR,
                   G_IO_ERROR_INVALID_DATA,
                   "Buffer too small: %"G_GSIZE_FORMAT, buffer->size);
      return NULL;
    }

  if (buffer->data[3] != 1) /* Protocol version */
    {
      g_set_error (error,
                   G_IO_ERROR,
                   G_IO_ERROR_INVALID_DATA,
                   "Wrong protocol version: %d", buffer->data[3]);
      return NULL;
    }

  if (buffer->data[0] == 'B')
    header->big_endian = TRUE;
  else if (buffer->data[0] == 'l')
    header->big_endian = FALSE;
  else
    {
      g_set_error (error,
                   G_IO_ERROR,
                   G_IO_ERROR_INVALID_DATA,
                   "Invalid endianess marker: %c", buffer->data[0]);
      return NULL;
    }

  header->type = buffer->data[1];
  header->flags = buffer->data[2];

  header->length = read_uint32 (header, &buffer->data[4]);
  header->serial = read_uint32 (header, &buffer->data[8]);

  if (header->serial == 0)
    {
      g_set_error (error,
                   G_IO_ERROR,
                   G_IO_ERROR_INVALID_DATA,
                   "No serial");
      return NULL;
    }

  array_len = read_uint32 (header, &buffer->data[12]);

  header_len = align_by_8 (12 + 4 + array_len);
  g_assert (buffer->size >= header_len); /* We should have verified this when reading in the message */
  if (header_len > buffer->size)
    {
      g_set_error (error,
                   G_IO_ERROR,
                   G_IO_ERROR_INVALID_DATA,
                   "Header len (%d) bigger than buffer size (%"G_GSIZE_FORMAT")",
                   header_len, buffer->size);
      return NULL;
    }

  offset = 12 + 4;
  end_offset = offset + array_len;

  header_str = g_string_new (NULL);

  while (offset < end_offset)
    {
      offset = align_by_8 (offset); /* Structs must be 8 byte aligned */
      if (offset >= end_offset)
        {
          g_set_error (error,
                       G_IO_ERROR,
                       G_IO_ERROR_INVALID_DATA,
                       "Struct would align past boundary%s",
                       header_debug_str (header_str, header));
          return NULL;
        }

      header_type = buffer->data[offset++];
      if (offset >= end_offset)
        {
          g_set_error (error,
                       G_IO_ERROR,
                       G_IO_ERROR_INVALID_DATA,
                       "Went past boundary after parsing header_type%s",
                       header_debug_str (header_str, header));
          return NULL;
        }

      signature = get_signature (buffer, &offset, end_offset);
      if (signature == NULL)
        {
          g_set_error (error,
                       G_IO_ERROR,
                       G_IO_ERROR_INVALID_DATA,
                       "Could not parse signature%s",
                       header_debug_str (header_str, header));
          return NULL;
        }

      switch (header_type)
        {
        case G_DBUS_MESSAGE_HEADER_FIELD_INVALID:
          g_set_error (error,
                       G_IO_ERROR,
                       G_IO_ERROR_INVALID_DATA,
                       "Field is invalid%s",
                       header_debug_str (header_str, header));
          return NULL;

        case G_DBUS_MESSAGE_HEADER_FIELD_PATH:
          if (strcmp (signature, "o") != 0)
            {
              g_set_error (error,
                           G_IO_ERROR,
                           G_IO_ERROR_INVALID_DATA,
                           "Signature is invalid for path ('%s')%s",
                           signature,
                           header_debug_str (header_str, header));
              return NULL;
            }
          header->path = get_string (buffer, header, &offset, end_offset, &str_error);
          if (header->path == NULL)
            {
              g_set_error (error,
                           G_IO_ERROR,
                           G_IO_ERROR_INVALID_DATA,
                           "Could not parse path in path field: %s%s",
                           str_error->message,
                           header_debug_str (header_str, header));
              return NULL;
            }
          break;

        case G_DBUS_MESSAGE_HEADER_FIELD_INTERFACE:
          if (strcmp (signature, "s") != 0)
            {
              g_set_error (error,
                           G_IO_ERROR,
                           G_IO_ERROR_INVALID_DATA,
                           "Signature is invalid for interface ('%s')%s",
                           signature,
                           header_debug_str (header_str, header));
              return NULL;
            }
          header->interface = get_string (buffer, header, &offset, end_offset, &str_error);
          if (header->interface == NULL)
            {
              g_set_error (error,
                           G_IO_ERROR,
                           G_IO_ERROR_INVALID_DATA,
                           "Could not parse interface in interface field: %s%s",
                           str_error->message,
                           header_debug_str (header_str, header));
              return NULL;
            }
          break;

        case G_DBUS_MESSAGE_HEADER_FIELD_MEMBER:
          if (strcmp (signature, "s") != 0)
            {
              g_set_error (error,
                           G_IO_ERROR,
                           G_IO_ERROR_INVALID_DATA,
                           "Signature is invalid for member ('%s')%s",
                           signature,
                           header_debug_str (header_str, header));
              return NULL;
            }
          header->member = get_string (buffer, header, &offset, end_offset, &str_error);
          if (header->member == NULL)
            {
              g_set_error (error,
                           G_IO_ERROR,
                           G_IO_ERROR_INVALID_DATA,
                           "Could not parse member in member field: %s%s",
                           str_error->message,
                           header_debug_str (header_str, header));
              return NULL;
            }
          break;

        case G_DBUS_MESSAGE_HEADER_FIELD_ERROR_NAME:
          if (strcmp (signature, "s") != 0)
            {
              g_set_error (error,
                           G_IO_ERROR,
                           G_IO_ERROR_INVALID_DATA,
                           "Signature is invalid for error ('%s')%s",
                           signature,
                           header_debug_str (header_str, header));
              return NULL;
            }
          header->error_name = get_string (buffer, header, &offset, end_offset, &str_error);
          if (header->error_name == NULL)
            {
              g_set_error (error,
                           G_IO_ERROR,
                           G_IO_ERROR_INVALID_DATA,
                           "Could not parse error in error field: %s%s",
                           str_error->message,
                           header_debug_str (header_str, header));
              return NULL;
            }
          break;

        case G_DBUS_MESSAGE_HEADER_FIELD_REPLY_SERIAL:
          if (offset + 4 > end_offset)
            {
              g_set_error (error,
                           G_IO_ERROR,
                           G_IO_ERROR_INVALID_DATA,
                           "Header too small to fit reply serial%s",
                           header_debug_str (header_str, header));
              return NULL;
            }

          header->has_reply_serial = TRUE;
          header->reply_serial = read_uint32 (header, &buffer->data[offset]);
          offset += 4;
          break;

        case G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION:
          if (strcmp (signature, "s") != 0)
            {
              g_set_error (error,
                           G_IO_ERROR,
                           G_IO_ERROR_INVALID_DATA,
                           "Signature is invalid for destination ('%s')%s",
                           signature,
                           header_debug_str (header_str, header));
              return NULL;
            }
          header->destination = get_string (buffer, header, &offset, end_offset, &str_error);
          if (header->destination == NULL)
            {
              g_set_error (error,
                           G_IO_ERROR,
                           G_IO_ERROR_INVALID_DATA,
                           "Could not parse destination in destination field: %s%s",
                           str_error->message,
                           header_debug_str (header_str, header));
              return NULL;
            }
          break;

        case G_DBUS_MESSAGE_HEADER_FIELD_SENDER:
          if (strcmp (signature, "s") != 0)
            {
              g_set_error (error,
                           G_IO_ERROR,
                           G_IO_ERROR_INVALID_DATA,
                           "Signature is invalid for sender ('%s')%s",
                           signature,
                           header_debug_str (header_str, header));
              return NULL;
            }
          header->sender = get_string (buffer, header, &offset, end_offset, &str_error);
          if (header->sender == NULL)
            {
              g_set_error (error,
                           G_IO_ERROR,
                           G_IO_ERROR_INVALID_DATA,
                           "Could not parse sender in sender field: %s%s",
                           str_error->message,
                           header_debug_str (header_str, header));
              return NULL;
            }
          break;

        case G_DBUS_MESSAGE_HEADER_FIELD_SIGNATURE:
          if (strcmp (signature, "g") != 0)
            {
              g_set_error (error,
                           G_IO_ERROR,
                           G_IO_ERROR_INVALID_DATA,
                           "Signature is invalid for signature ('%s')%s",
                           signature,
                           header_debug_str (header_str, header));
              return NULL;
            }
          header->signature = get_signature (buffer, &offset, end_offset);
          if (header->signature == NULL)
            {
              g_set_error (error,
                           G_IO_ERROR,
                           G_IO_ERROR_INVALID_DATA,
                           "Could not parse signature in signature field%s",
                           header_debug_str (header_str, header));
              return NULL;
            }
          break;

        case G_DBUS_MESSAGE_HEADER_FIELD_NUM_UNIX_FDS:
          if (offset + 4 > end_offset)
            {
              g_set_error (error,
                           G_IO_ERROR,
                           G_IO_ERROR_INVALID_DATA,
                           "Header too small to fit Unix FDs%s",
                           header_debug_str (header_str, header));
              return NULL;
            }

          header->unix_fds = read_uint32 (header, &buffer->data[offset]);
          offset += 4;
          break;

        default:
          /* Unknown header field, for safety, fail parse */
          g_set_error (error,
                       G_IO_ERROR,
                       G_IO_ERROR_INVALID_DATA,
                       "Unknown header field (%d)%s",
                       header_type,
                       header_debug_str (header_str, header));
          return NULL;
        }
    }

  switch (header->type)
    {
    case G_DBUS_MESSAGE_TYPE_METHOD_CALL:
      if (header->path == NULL || header->member == NULL)
        {
          g_set_error (error,
                       G_IO_ERROR,
                       G_IO_ERROR_INVALID_DATA,
                       "Method call is missing path or member%s",
                       header_debug_str (header_str, header));
          return NULL;
        }
      break;

    case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
      if (!header->has_reply_serial)
        {
          g_set_error (error,
                       G_IO_ERROR,
                       G_IO_ERROR_INVALID_DATA,
                       "Method return has no reply serial%s",
                       header_debug_str (header_str, header));
          return NULL;
        }
      break;

    case G_DBUS_MESSAGE_TYPE_ERROR:
      if (header->error_name  == NULL || !header->has_reply_serial)
        {
          g_set_error (error,
                       G_IO_ERROR,
                       G_IO_ERROR_INVALID_DATA,
                       "Error is missing error name or reply serial%s",
                       header_debug_str (header_str, header));
          return NULL;
        }
      break;

    case G_DBUS_MESSAGE_TYPE_SIGNAL:
      if (header->path == NULL ||
          header->interface == NULL ||
          header->member == NULL)
        {
          g_set_error (error,
                       G_IO_ERROR,
                       G_IO_ERROR_INVALID_DATA,
                       "Signal is missing path, interface or member%s",
                       header_debug_str (header_str, header));
          return NULL;
        }
      if (strcmp (header->path, "/org/freedesktop/DBus/Local") == 0 ||
          strcmp (header->interface, "org.freedesktop.DBus.Local") == 0)
        {
          g_set_error (error,
                       G_IO_ERROR,
                       G_IO_ERROR_INVALID_DATA,
                       "Signal is to D-Bus Local path or interface%s",
                       header_debug_str (header_str, header));
          return NULL;
        }
      break;

    default:
      /* Unknown message type, for safety, fail parse */
      g_set_error (error,
                   G_IO_ERROR,
                   G_IO_ERROR_INVALID_DATA,
                   "Unknown message type (%d)%s",
                   header->type,
                   header_debug_str (header_str, header));
      return NULL;
    }

  return g_steal_pointer (&header);
}

static void
print_outgoing_header (Header *header)
{
  switch (header->type)
    {
    case G_DBUS_MESSAGE_TYPE_METHOD_CALL:
      g_print ("C%d: -> %s call %s.%s at %s\n",
               header->serial,
               header->destination ? header->destination : "(no dest)",
               header->interface ? header->interface : "",
               header->member ? header->member : "",
               header->path ? header->path : "");
      break;

    case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
      g_print ("C%d: -> %s return from B%d\n",
               header->serial,
               header->destination ? header->destination : "(no dest)",
               header->reply_serial);
      break;

    case G_DBUS_MESSAGE_TYPE_ERROR:
      g_print ("C%d: -> %s return error %s from B%d\n",
               header->serial,
               header->destination ? header->destination : "(no dest)",
               header->error_name ? header->error_name : "(no error)",
               header->reply_serial);
      break;

    case G_DBUS_MESSAGE_TYPE_SIGNAL:
      g_print ("C%d: -> %s signal %s.%s at %s\n",
               header->serial,
               header->destination ? header->destination : "all",
               header->interface ? header->interface : "",
               header->member ? header->member : "",
               header->path ? header->path : "");
      break;

    default:
      g_print ("unknown message type\n");
    }
}

static void
print_incoming_header (Header *header)
{
  switch (header->type)
    {
    case G_DBUS_MESSAGE_TYPE_METHOD_CALL:
      g_print ("B%d: <- %s call %s.%s at %s\n",
               header->serial,
               header->sender ? header->sender : "(no sender)",
               header->interface ? header->interface : "",
               header->member ? header->member : "",
               header->path ? header->path : "");
      break;

    case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
      g_print ("B%d: <- %s return from C%d\n",
               header->serial,
               header->sender ? header->sender : "(no sender)",
               header->reply_serial);
      break;

    case G_DBUS_MESSAGE_TYPE_ERROR:
      g_print ("B%d: <- %s return error %s from C%d\n",
               header->serial,
               header->sender ? header->sender : "(no sender)",
               header->error_name ? header->error_name : "(no error)",
               header->reply_serial);
      break;

    case G_DBUS_MESSAGE_TYPE_SIGNAL:
      g_print ("B%d: <- %s signal %s.%s at %s\n",
               header->serial,
               header->sender ? header->sender : "(no sender)",
               header->interface ? header->interface : "",
               header->member ? header->member : "",
               header->path ? header->path : "");
      break;

    default:
      g_print ("unknown message type\n");
    }
}


static Filter *match_all[FLATPAK_POLICY_OWN + 1] = { NULL };


static FlatpakPolicy
flatpak_proxy_client_get_max_policy_and_matched (FlatpakProxyClient *client,
                                                 const char         *source,
                                                 GList             **matched_filters)
{
  GList *names, *filters, *l;
  FlatpakPolicy max_policy = FLATPAK_POLICY_NONE;
  g_autofree char *name = NULL;
  gboolean exact_name_match;
  char *dot;

  if (match_all[FLATPAK_POLICY_SEE] == NULL)
    {
      match_all[FLATPAK_POLICY_SEE] = filter_new ("", FALSE, FLATPAK_POLICY_SEE);
      match_all[FLATPAK_POLICY_TALK] = filter_new ("", FALSE, FLATPAK_POLICY_TALK);
      match_all[FLATPAK_POLICY_OWN] = filter_new ("", FALSE, FLATPAK_POLICY_OWN);
    }

  if (source == NULL)
    {
      if (matched_filters)
        *matched_filters = g_list_append (*matched_filters,  match_all[FLATPAK_POLICY_TALK]);

      return FLATPAK_POLICY_TALK; /* All clients can talk to the bus itself */
    }

  if (source[0] == ':')
    {
      /* Default to the unique id policy, i.e. TALK for self, and SEE for trusted peers */
      max_policy = GPOINTER_TO_UINT (g_hash_table_lookup (client->unique_id_policy, source));
      if (max_policy > FLATPAK_POLICY_NONE && matched_filters)
        *matched_filters = g_list_append (*matched_filters, match_all[max_policy]);

      /* Treat this as the merged list of filters for all the names the unique id ever owned */
      names = g_hash_table_lookup (client->unique_id_owned_names, source);
      for (l = names; l != NULL; l = l->next)
        {
          const char *owned_name = l->data;
          max_policy = MAX (max_policy, flatpak_proxy_client_get_max_policy_and_matched (client, owned_name, matched_filters));
        }


      return max_policy;
    }

  name = g_strdup (source);
  exact_name_match = TRUE;
  do
    {
      filters = g_hash_table_lookup (client->proxy->filters, name);

      for (l = filters; l != NULL; l = l->next)
        {
          Filter *filter = l->data;

          if (exact_name_match || filter->name_is_subtree)
            {
              max_policy = MAX (max_policy, filter->policy);
              if (matched_filters)
                *matched_filters = g_list_append (*matched_filters, filter);
            }
        }

      exact_name_match = FALSE;
      dot = strrchr (name, '.');
      if (dot != NULL)
        *dot = 0;
    }
  while (dot != NULL);

  return max_policy;
}

static FlatpakPolicy
flatpak_proxy_client_get_max_policy (FlatpakProxyClient *client,
                                     const char         *source)
{
  return flatpak_proxy_client_get_max_policy_and_matched (client, source, NULL);
}

static void
flatpak_proxy_client_update_unique_id_policy (FlatpakProxyClient *client,
                                              const char         *unique_id,
                                              FlatpakPolicy       policy)
{
  if (policy > FLATPAK_POLICY_NONE)
    {
      FlatpakPolicy old_policy;
      old_policy = GPOINTER_TO_UINT (g_hash_table_lookup (client->unique_id_policy, unique_id));
      if (policy > old_policy)
        g_hash_table_replace (client->unique_id_policy, g_strdup (unique_id), GINT_TO_POINTER (policy));
    }
}


static void
flatpak_proxy_client_add_unique_id_owned_name (FlatpakProxyClient *client,
                                               const char         *unique_id,
                                               const char         *owned_name)
{
  GList *names;
  gboolean already_added;

  names = NULL;
  already_added = g_hash_table_lookup_extended (client->unique_id_owned_names,
                                                unique_id,
                                                NULL, (void **) &names);
  names = g_list_append (names, g_strdup (owned_name));

  if (!already_added)
    g_hash_table_insert (client->unique_id_owned_names, g_strdup (unique_id), names);
}


static gboolean
client_message_generates_reply (Header *header)
{
  switch (header->type)
    {
    case G_DBUS_MESSAGE_TYPE_METHOD_CALL:
      return (header->flags & G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED) == 0;

    case G_DBUS_MESSAGE_TYPE_SIGNAL:
    case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
    case G_DBUS_MESSAGE_TYPE_ERROR:
    default:
      return FALSE;
    }
}

static Buffer *
message_to_buffer (GDBusMessage *message)
{
  Buffer *buffer;
  guchar *blob;
  gsize blob_size;

  blob = g_dbus_message_to_blob (message, &blob_size, G_DBUS_CAPABILITY_FLAGS_NONE, NULL);
  buffer = buffer_new (blob_size, NULL);
  memcpy (buffer->data, blob, blob_size);
  buffer->pos = blob_size;
  g_free (blob);

  return buffer;
}

static GDBusMessage *
get_error_for_header (FlatpakProxyClient *client, Header *header, const char *error)
{
  GDBusMessage *reply;

  reply = g_dbus_message_new ();
  g_dbus_message_set_message_type (reply, G_DBUS_MESSAGE_TYPE_ERROR);
  g_dbus_message_set_flags (reply, G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED);
  g_dbus_message_set_reply_serial (reply, header->serial);
  g_dbus_message_set_error_name (reply, error);
  g_dbus_message_set_body (reply, g_variant_new ("(s)", error));

  return reply;
}

static GDBusMessage *
get_bool_reply_for_header (FlatpakProxyClient *client, Header *header, gboolean val)
{
  GDBusMessage *reply;

  reply = g_dbus_message_new ();
  g_dbus_message_set_message_type (reply, G_DBUS_MESSAGE_TYPE_METHOD_RETURN);
  g_dbus_message_set_flags (reply, G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED);
  g_dbus_message_set_reply_serial (reply, header->serial);
  g_dbus_message_set_body (reply, g_variant_new ("(b)", val));

  return reply;
}

static Buffer *
get_ping_buffer_for_header (Header *header)
{
  Buffer *buffer;
  GDBusMessage *dummy;

  dummy = g_dbus_message_new_method_call (NULL, "/", "org.freedesktop.DBus.Peer", "Ping");
  g_dbus_message_set_serial (dummy, header->serial);
  g_dbus_message_set_flags (dummy, header->flags);

  buffer = message_to_buffer (dummy);

  g_object_unref (dummy);

  return buffer;
}

static Buffer *
get_error_for_roundtrip (FlatpakProxyClient *client, Header *header, const char *error_name)
{
  Buffer *ping_buffer = get_ping_buffer_for_header (header);
  GDBusMessage *reply;

  reply = get_error_for_header (client, header, error_name);
  g_hash_table_replace (client->rewrite_reply, GINT_TO_POINTER (header->serial), reply);
  return ping_buffer;
}

static Buffer *
get_bool_reply_for_roundtrip (FlatpakProxyClient *client, Header *header, gboolean val)
{
  Buffer *ping_buffer = get_ping_buffer_for_header (header);
  GDBusMessage *reply;

  reply = get_bool_reply_for_header (client, header, val);
  g_hash_table_replace (client->rewrite_reply, GINT_TO_POINTER (header->serial), reply);

  return ping_buffer;
}

typedef enum {
  HANDLE_PASS,
  HANDLE_DENY,
  HANDLE_HIDE,
  HANDLE_FILTER_NAME_LIST_REPLY,
  HANDLE_FILTER_HAS_OWNER_REPLY,
  HANDLE_FILTER_GET_OWNER_REPLY,
  HANDLE_VALIDATE_OWN,
  HANDLE_VALIDATE_SEE,
  HANDLE_VALIDATE_TALK,
  HANDLE_VALIDATE_MATCH,
} BusHandler;

static gboolean
is_for_bus (Header *header)
{
  return g_strcmp0 (header->destination, "org.freedesktop.DBus") == 0;
}

static gboolean
is_dbus_method_call (Header *header)
{
  return
    is_for_bus (header) &&
    header->type == G_DBUS_MESSAGE_TYPE_METHOD_CALL &&
    g_strcmp0 (header->interface, "org.freedesktop.DBus") == 0;
}

static gboolean
is_introspection_call (Header *header)
{
  return
    header->type == G_DBUS_MESSAGE_TYPE_METHOD_CALL &&
    g_strcmp0 (header->interface, "org.freedesktop.DBus.Introspectable") == 0;
}

static BusHandler
get_dbus_method_handler (FlatpakProxyClient *client, Header *header)
{
  FlatpakPolicy policy;
  const char *method;

  g_autoptr(GList) filters = NULL;

  if (header->has_reply_serial)
    {
      ExpectedReplyType expected_reply =
        steal_expected_reply (&client->bus_side,
                              header->reply_serial);
      if (expected_reply == EXPECTED_REPLY_NONE)
        return HANDLE_DENY;

      return HANDLE_PASS;
    }

  policy = flatpak_proxy_client_get_max_policy_and_matched (client, header->destination, &filters);
  if (policy < FLATPAK_POLICY_SEE)
    return HANDLE_HIDE;
  if (policy < FLATPAK_POLICY_TALK)
    return HANDLE_DENY;

  if (!is_for_bus (header))
    {
      if (policy == FLATPAK_POLICY_OWN ||
          any_filter_matches (filters, FILTER_TYPE_CALL,
                              header->path,
                              header->interface,
                              header->member))
        return HANDLE_PASS;

      return HANDLE_DENY;
    }

  /* Its a bus call */

  if (is_introspection_call (header))
    {
      return HANDLE_PASS;
    }
  else if (is_dbus_method_call (header))
    {
      method = header->member;
      if (method == NULL)
        return HANDLE_DENY;

      if (strcmp (method, "AddMatch") == 0)
        return HANDLE_VALIDATE_MATCH;

      if (strcmp (method, "Hello") == 0 ||
          strcmp (method, "RemoveMatch") == 0 ||
          strcmp (method, "GetId") == 0)
        return HANDLE_PASS;

      if (strcmp (method, "UpdateActivationEnvironment") == 0 ||
          strcmp (method, "BecomeMonitor") == 0)
        return HANDLE_DENY;

      if (strcmp (method, "RequestName") == 0 ||
          strcmp (method, "ReleaseName") == 0 ||
          strcmp (method, "ListQueuedOwners") == 0)
        return HANDLE_VALIDATE_OWN;

      if (strcmp (method, "NameHasOwner") == 0)
        return HANDLE_FILTER_HAS_OWNER_REPLY;

      if (strcmp (method, "GetNameOwner") == 0)
        return HANDLE_FILTER_GET_OWNER_REPLY;

      if (strcmp (method, "GetConnectionUnixProcessID") == 0 ||
          strcmp (method, "GetConnectionCredentials") == 0 ||
          strcmp (method, "GetAdtAuditSessionData") == 0 ||
          strcmp (method, "GetConnectionSELinuxSecurityContext") == 0 ||
          strcmp (method, "GetConnectionUnixUser") == 0)
        return HANDLE_VALIDATE_SEE;

      if (strcmp (method, "StartServiceByName") == 0)
        return HANDLE_VALIDATE_TALK;

      if (strcmp (method, "ListNames") == 0 ||
          strcmp (method, "ListActivatableNames") == 0)
        return HANDLE_FILTER_NAME_LIST_REPLY;

      g_warning ("Unknown bus method %s", method);
      return HANDLE_DENY;
    }
  else
    {
      return HANDLE_DENY;
    }
}

static FlatpakPolicy
policy_from_handler (BusHandler handler)
{
  switch (handler)
    {
    case HANDLE_VALIDATE_OWN:
      return FLATPAK_POLICY_OWN;

    case HANDLE_VALIDATE_TALK:
      return FLATPAK_POLICY_TALK;

    case HANDLE_VALIDATE_SEE:
      return FLATPAK_POLICY_SEE;

    case HANDLE_DENY:
    case HANDLE_FILTER_GET_OWNER_REPLY:
    case HANDLE_FILTER_HAS_OWNER_REPLY:
    case HANDLE_FILTER_NAME_LIST_REPLY:
    case HANDLE_HIDE:
    case HANDLE_PASS:
    case HANDLE_VALIDATE_MATCH:
    default:
      return FLATPAK_POLICY_NONE;
    }
}

static char *
get_arg0_string (Buffer *buffer)
{
  g_autoptr(GDBusMessage) message =
    g_dbus_message_new_from_blob (buffer->data, buffer->size, 0, NULL);
  GVariant *body;
  g_autoptr(GVariant) arg0 = NULL;

  if (message != NULL &&
      (body = g_dbus_message_get_body (message)) != NULL &&
      (arg0 = g_variant_get_child_value (body, 0)) != NULL &&
      g_variant_is_of_type (arg0, G_VARIANT_TYPE_STRING))
    return g_variant_dup_string (arg0, NULL);

  return NULL;
}

static gboolean
validate_arg0_match (FlatpakProxyClient *client, Buffer *buffer)
{
  g_autoptr(GDBusMessage) message =
    g_dbus_message_new_from_blob (buffer->data, buffer->size, 0, NULL);
  GVariant *body;
  g_autoptr(GVariant) arg0 = NULL;
  const char *match;

  if (message != NULL &&
      (body = g_dbus_message_get_body (message)) != NULL &&
      (arg0 = g_variant_get_child_value (body, 0)) != NULL &&
      g_variant_is_of_type (arg0, G_VARIANT_TYPE_STRING))
    {
      match = g_variant_get_string (arg0, NULL);
      if (strstr (match, "eavesdrop=") != NULL)
        return FALSE;
    }

  return TRUE;
}

static gboolean
validate_arg0_name (FlatpakProxyClient *client, Buffer *buffer, FlatpakPolicy required_policy, FlatpakPolicy *has_policy)
{
  g_autoptr(GDBusMessage) message =
    g_dbus_message_new_from_blob (buffer->data, buffer->size, 0, NULL);
  GVariant *body;
  g_autoptr(GVariant) arg0 = NULL;
  const char *name;
  FlatpakPolicy name_policy;

  if (has_policy)
    *has_policy = FLATPAK_POLICY_NONE;

  if (message != NULL &&
      (body = g_dbus_message_get_body (message)) != NULL &&
      (arg0 = g_variant_get_child_value (body, 0)) != NULL &&
      g_variant_is_of_type (arg0, G_VARIANT_TYPE_STRING))
    {
      name = g_variant_get_string (arg0, NULL);
      name_policy = flatpak_proxy_client_get_max_policy (client, name);

      if (has_policy)
        *has_policy = name_policy;

      if (name_policy >= required_policy)
        return TRUE;

      if (client->proxy->log_messages)
        g_print ("Filtering message due to arg0 %s, policy: %d (required %d)\n", name, name_policy, required_policy);
    }

  return FALSE;
}

static Buffer *
filter_names_list (FlatpakProxyClient *client, Buffer *buffer)
{
  g_autoptr(GDBusMessage) message =
    g_dbus_message_new_from_blob (buffer->data, buffer->size, 0, NULL);
  GVariant *body, *new_names;
  g_autoptr(GVariant) arg0 = NULL;
  const gchar **names;
  int i;
  GVariantBuilder builder;
  Buffer *filtered;

  if (message == NULL ||
      (body = g_dbus_message_get_body (message)) == NULL ||
      (arg0 = g_variant_get_child_value (body, 0)) == NULL ||
      !g_variant_is_of_type (arg0, G_VARIANT_TYPE_STRING_ARRAY))
    return NULL;

  names = g_variant_get_strv (arg0, NULL);

  g_variant_builder_init (&builder, G_VARIANT_TYPE_STRING_ARRAY);
  for (i = 0; names[i] != NULL; i++)
    {
      if (flatpak_proxy_client_get_max_policy (client, names[i]) >= FLATPAK_POLICY_SEE)
        g_variant_builder_add (&builder, "s", names[i]);
    }
  g_free (names);

  new_names = g_variant_builder_end (&builder);
  g_dbus_message_set_body (message,
                           g_variant_new_tuple (&new_names, 1));

  filtered = message_to_buffer (message);
  return filtered;
}

static gboolean
message_is_name_owner_changed (FlatpakProxyClient *client, Header *header)
{
  if (header->type == G_DBUS_MESSAGE_TYPE_SIGNAL &&
      g_strcmp0 (header->sender, "org.freedesktop.DBus") == 0 &&
      g_strcmp0 (header->interface, "org.freedesktop.DBus") == 0 &&
      g_strcmp0 (header->member, "NameOwnerChanged") == 0)
    return TRUE;
  return FALSE;
}

static gboolean
should_filter_name_owner_changed (FlatpakProxyClient *client, Buffer *buffer)
{
  g_autoptr(GDBusMessage) message =
    g_dbus_message_new_from_blob (buffer->data, buffer->size, 0, NULL);
  GVariant *body;
  g_autoptr(GVariant) arg0 = NULL;
  g_autoptr(GVariant) arg1 = NULL;
  g_autoptr(GVariant) arg2 = NULL;
  const gchar *name, *new;

  if (message == NULL ||
      (body = g_dbus_message_get_body (message)) == NULL ||
      (arg0 = g_variant_get_child_value (body, 0)) == NULL ||
      !g_variant_is_of_type (arg0, G_VARIANT_TYPE_STRING) ||
      (arg1 = g_variant_get_child_value (body, 1)) == NULL ||
      !g_variant_is_of_type (arg1, G_VARIANT_TYPE_STRING) ||
      (arg2 = g_variant_get_child_value (body, 2)) == NULL ||
      !g_variant_is_of_type (arg2, G_VARIANT_TYPE_STRING))
    return TRUE;

  name = g_variant_get_string (arg0, NULL);
  new = g_variant_get_string (arg2, NULL);

  if (flatpak_proxy_client_get_max_policy (client, name) >= FLATPAK_POLICY_SEE ||
      (client->proxy->sloppy_names && name[0] == ':'))
    {
      if (name[0] != ':')
        {
          if (new[0] != 0)
            flatpak_proxy_client_add_unique_id_owned_name (client, new, name);
        }

      return FALSE;
    }

  return TRUE;
}

static GList *
side_get_n_unix_fds (ProxySide *side, int n_fds)
{
  GList *res = NULL;

  while (side->control_messages != NULL)
    {
      GSocketControlMessage *control_message = side->control_messages->data;

      if (G_IS_UNIX_FD_MESSAGE (control_message))
        {
          GUnixFDMessage *fd_message = G_UNIX_FD_MESSAGE (control_message);
          GUnixFDList *fd_list = g_unix_fd_message_get_fd_list (fd_message);
          int len = g_unix_fd_list_get_length (fd_list);

          /* I believe that socket control messages are never merged, and
             the sender side sends only one unix-fd-list per message, so
             at this point there should always be one full fd list
             per requested number of fds */
          if (len != n_fds)
            {
              g_warning ("Not right nr of fds in socket message");
              return NULL;
            }

          side->control_messages = g_list_delete_link (side->control_messages, side->control_messages);

          return g_list_append (NULL, control_message);
        }

      g_object_unref (control_message);
      side->control_messages = g_list_delete_link (side->control_messages, side->control_messages);
    }

  return res;
}

static gboolean
update_socket_messages (ProxySide *side, Buffer *buffer, Header *header)
{
  /* We may accidentally combine multiple control messages into one
     buffer when we receive (since we can do several recvs), so we
     keep a list of all we get and then only re-attach the amount
     specified in the header to the buffer. */

  side->control_messages = g_list_concat (side->control_messages, buffer->control_messages);
  buffer->control_messages = NULL;
  if (header->unix_fds > 0)
    {
      buffer->control_messages = side_get_n_unix_fds (side, header->unix_fds);
      if (buffer->control_messages == NULL)
        {
          g_warning ("Not enough fds for message");
          side_closed (side);
          buffer_unref (buffer);
          return FALSE;
        }
    }
  return TRUE;
}

static void
queue_fake_message (FlatpakProxyClient *client, GDBusMessage *message, ExpectedReplyType reply_type)
{
  Buffer *buffer;

  client->last_fake_serial++;
  g_assert (client->last_fake_serial > MAX_CLIENT_SERIAL);
  g_dbus_message_set_serial (message, client->last_fake_serial);
  buffer = message_to_buffer (message);
  g_object_unref (message);

  queue_outgoing_buffer (&client->bus_side, buffer);
  queue_expected_reply (&client->client_side, client->last_fake_serial, reply_type);
}

/* After the first Hello message we need to synthesize a bunch of messages to synchronize the
   ownership state for the names in the policy */
static void
queue_initial_name_ops (FlatpakProxyClient *client)
{
  GHashTableIter iter;
  gpointer key, value;
  gboolean has_wildcards = FALSE;

  g_hash_table_iter_init (&iter, client->proxy->filters);
  while (g_hash_table_iter_next (&iter, &key, &value))
    {
      const char *name = key;
      GList *filters = value;
      gboolean name_needs_subtree = FALSE;
      GDBusMessage *message;
      GVariant *match;
      GList *l;

      for (l = filters; l != NULL; l = l->next)
        {
          Filter *filter = l->data;
          if (filter->name_is_subtree)
            {
              name_needs_subtree = TRUE;
              break;
            }
        }

      if (strcmp (name, "org.freedesktop.DBus") == 0)
        continue;

      /* AddMatch the name so we get told about ownership changes.
         Do it before the GetNameOwner to avoid races */
      message = g_dbus_message_new_method_call ("org.freedesktop.DBus", "/", "org.freedesktop.DBus", "AddMatch");
      if (name_needs_subtree)
        match = g_variant_new_printf ("type='signal',sender='org.freedesktop.DBus',interface='org.freedesktop.DBus',member='NameOwnerChanged',arg0namespace='%s'", name);
      else
        match = g_variant_new_printf ("type='signal',sender='org.freedesktop.DBus',interface='org.freedesktop.DBus',member='NameOwnerChanged',arg0='%s'", name);
      g_dbus_message_set_body (message, g_variant_new_tuple (&match, 1));
      queue_fake_message (client, message, EXPECTED_REPLY_FILTER);

      if (client->proxy->log_messages)
        g_print ("C%d: -> org.freedesktop.DBus fake %sAddMatch for %s\n", client->last_fake_serial, name_needs_subtree ? "wildcarded " : "", name);

      if (!name_needs_subtree)
        {
          /* Get the current owner of the name (if any) so we can apply policy to it */
          message = g_dbus_message_new_method_call ("org.freedesktop.DBus", "/", "org.freedesktop.DBus", "GetNameOwner");
          g_dbus_message_set_body (message, g_variant_new ("(s)", name));
          queue_fake_message (client, message, EXPECTED_REPLY_FAKE_GET_NAME_OWNER);
          g_hash_table_replace (client->get_owner_reply, GINT_TO_POINTER (client->last_fake_serial), g_strdup (name));

          if (client->proxy->log_messages)
            g_print ("C%d: -> org.freedesktop.DBus fake GetNameOwner for %s\n", client->last_fake_serial, name);
        }
      else
        has_wildcards = TRUE; /* Send ListNames below */
    }

  /* For wildcarded rules we don't know the actual names to GetNameOwner for, so we have to list all current names */
  if (has_wildcards)
    {
      GDBusMessage *message;

      /* AddMatch the name so we get told about ownership changes.
         Do it before the GetNameOwner to avoid races */
      message = g_dbus_message_new_method_call ("org.freedesktop.DBus", "/", "org.freedesktop.DBus", "ListNames");
      g_dbus_message_set_body (message, g_variant_new ("()"));
      queue_fake_message (client, message, EXPECTED_REPLY_FAKE_LIST_NAMES);

      if (client->proxy->log_messages)
        g_print ("C%d: -> org.freedesktop.DBus fake ListNames\n", client->last_fake_serial);

      /* Stop reading from the client, to avoid incoming messages fighting with the ListNames roundtrip.
         We will start it again once we have handled the ListNames reply */
      stop_reading (&client->client_side);

      /* Once we get the reply to this queue_wildcard_initial_name_ops() will be called and we continue there */
    }
}

static void
queue_wildcard_initial_name_ops (FlatpakProxyClient *client, Header *header, Buffer *buffer)
{
  g_autoptr(GDBusMessage) decoded_message =
    g_dbus_message_new_from_blob (buffer->data, buffer->size, 0, NULL);
  GVariant *body;
  g_autoptr(GVariant) arg0 = NULL;
  g_autofree const gchar **names = NULL;
  int i;

  if (decoded_message == NULL ||
      header->type != G_DBUS_MESSAGE_TYPE_METHOD_RETURN ||
      (body = g_dbus_message_get_body (decoded_message)) == NULL ||
      (arg0 = g_variant_get_child_value (body, 0)) == NULL ||
      !g_variant_is_of_type (arg0, G_VARIANT_TYPE_STRING_ARRAY))
    return;

  names = g_variant_get_strv (arg0, NULL);

  /* Loop over all current names and get the owner for all the ones that match our rules
     policies so that we can update the unique id policies for those */
  for (i = 0; names[i] != NULL; i++)
    {
      const char *name = names[i];

      if (name[0] != ':' &&
          flatpak_proxy_client_get_max_policy (client, name) != FLATPAK_POLICY_NONE)
        {
          /* Get the current owner of the name (if any) so we can apply policy to it */
          GDBusMessage *message = g_dbus_message_new_method_call ("org.freedesktop.DBus", "/", "org.freedesktop.DBus", "GetNameOwner");
          g_dbus_message_set_body (message, g_variant_new ("(s)", name));
          queue_fake_message (client, message, EXPECTED_REPLY_FAKE_GET_NAME_OWNER);
          g_hash_table_replace (client->get_owner_reply, GINT_TO_POINTER (client->last_fake_serial), g_strdup (name));

          if (client->proxy->log_messages)
            g_print ("C%d: -> org.freedesktop.DBus fake GetNameOwner for %s\n", client->last_fake_serial, name);
        }
    }
}


static void
got_buffer_from_client (FlatpakProxyClient *client, ProxySide *side, Buffer *buffer)
{
  ExpectedReplyType expecting_reply = EXPECTED_REPLY_NONE;

  if (client->auth_state == AUTH_COMPLETE && client->proxy->filter)
    {
      g_autoptr(Header) header = NULL;
      g_autoptr(GError) error = NULL;
      BusHandler handler;

      /* Filter and rewrite outgoing messages as needed */

      header = parse_header (buffer, &error);
      if (header == NULL)
        {
          g_warning ("Invalid message header format from client: %s",
                     error->message);
          side_closed (side);
          buffer_unref (buffer);
          return;
        }

      if (!update_socket_messages (side, buffer, header))
        return;

      if (header->serial > MAX_CLIENT_SERIAL)
        {
          g_warning ("Invalid client serial: Exceeds maximum value of %u", MAX_CLIENT_SERIAL);
          side_closed (side);
          buffer_unref (buffer);
          return;
        }

      if (client->proxy->log_messages)
        print_outgoing_header (header);

      /* Keep track of the initial Hello request so that we can read
         the reply which has our assigned unique id */
      if (is_dbus_method_call (header) &&
          g_strcmp0 (header->member, "Hello") == 0)
        {
          expecting_reply = EXPECTED_REPLY_HELLO;
          client->hello_serial = header->serial;
        }

      handler = get_dbus_method_handler (client, header);

      switch (handler)
        {
        case HANDLE_FILTER_HAS_OWNER_REPLY:
        case HANDLE_FILTER_GET_OWNER_REPLY:
          if (!validate_arg0_name (client, buffer, FLATPAK_POLICY_SEE, NULL))
            {
              g_clear_pointer (&buffer, buffer_unref);
              if (handler == HANDLE_FILTER_GET_OWNER_REPLY)
                buffer = get_error_for_roundtrip (client, header,
                                                  "org.freedesktop.DBus.Error.NameHasNoOwner");
              else
                buffer = get_bool_reply_for_roundtrip (client, header, FALSE);

              expecting_reply = EXPECTED_REPLY_REWRITE;
              break;
            }

          goto handle_pass;

        case HANDLE_VALIDATE_MATCH:
          if (!validate_arg0_match (client, buffer))
            {
              if (client->proxy->log_messages)
                g_print ("*DENIED* (ping)\n");
              g_clear_pointer (&buffer, buffer_unref);
              buffer = get_error_for_roundtrip (client, header,
                                                "org.freedesktop.DBus.Error.AccessDenied");
              expecting_reply = EXPECTED_REPLY_REWRITE;
              break;
            }

          goto handle_pass;

        case HANDLE_VALIDATE_OWN:
        case HANDLE_VALIDATE_SEE:
        case HANDLE_VALIDATE_TALK:
          {
            FlatpakPolicy name_policy;
            if (validate_arg0_name (client, buffer, policy_from_handler (handler), &name_policy))
              goto handle_pass;

            if (name_policy < (int) FLATPAK_POLICY_SEE)
              goto handle_hide;
            else
              goto handle_deny;
          }

        case HANDLE_FILTER_NAME_LIST_REPLY:
          expecting_reply = EXPECTED_REPLY_LIST_NAMES;
          goto handle_pass;

        case HANDLE_PASS:
handle_pass:
          if (client_message_generates_reply (header))
            {
              if (expecting_reply == EXPECTED_REPLY_NONE)
                expecting_reply = EXPECTED_REPLY_NORMAL;
            }

          break;

        case HANDLE_HIDE:
handle_hide:
          g_clear_pointer (&buffer, buffer_unref);

          if (client_message_generates_reply (header))
            {
              const char *error_str;

              if (client->proxy->log_messages)
                g_print ("*HIDDEN* (ping)\n");

              if ((header->destination != NULL && header->destination[0] == ':') ||
                  (header->flags & G_DBUS_MESSAGE_FLAGS_NO_AUTO_START) != 0)
                error_str = "org.freedesktop.DBus.Error.NameHasNoOwner";
              else
                error_str = "org.freedesktop.DBus.Error.ServiceUnknown";

              buffer = get_error_for_roundtrip (client, header, error_str);
              expecting_reply = EXPECTED_REPLY_REWRITE;
            }
          else
            {
              if (client->proxy->log_messages)
                g_print ("*HIDDEN*\n");
            }
          break;

        default:
        case HANDLE_DENY:
handle_deny:
          g_clear_pointer (&buffer, buffer_unref);

          if (client_message_generates_reply (header))
            {
              if (client->proxy->log_messages)
                g_print ("*DENIED* (ping)\n");

              buffer = get_error_for_roundtrip (client, header,
                                                "org.freedesktop.DBus.Error.AccessDenied");
              expecting_reply = EXPECTED_REPLY_REWRITE;
            }
          else
            {
              if (client->proxy->log_messages)
                g_print ("*DENIED*\n");
            }
          break;
        }

      if (buffer != NULL && expecting_reply != EXPECTED_REPLY_NONE)
        queue_expected_reply (side, header->serial, expecting_reply);
    }

  if (buffer)
    queue_outgoing_buffer (&client->bus_side, buffer);

  if (buffer != NULL && expecting_reply == EXPECTED_REPLY_HELLO)
    queue_initial_name_ops (client);
}

static void
got_buffer_from_bus (FlatpakProxyClient *client, ProxySide *side, Buffer *buffer)
{
  if (client->auth_state == AUTH_COMPLETE && client->proxy->filter)
    {
      g_autoptr(Header) header = NULL;
      g_autoptr(GError) error = NULL;
      GDBusMessage *rewritten;
      FlatpakPolicy policy;
      ExpectedReplyType expected_reply;

      /* Filter and rewrite incoming messages as needed */

      header = parse_header (buffer, &error);
      if (header == NULL)
        {
          g_warning ("Invalid message header format from bus: %s",
                     error->message);
          buffer_unref (buffer);
          side_closed (side);
          return;
        }

      if (!update_socket_messages (side, buffer, header))
        return;

      if (client->proxy->log_messages)
        print_incoming_header (header);

      if (header->has_reply_serial)
        {
          expected_reply = steal_expected_reply (get_other_side (side), header->reply_serial);

          switch (expected_reply)
            {
            case EXPECTED_REPLY_NONE:
              /* We only allow replies we expect */
              if (client->proxy->log_messages)
                g_print ("*Unexpected reply*\n");
              buffer_unref (buffer);
              return;

            case EXPECTED_REPLY_HELLO:
              /* When we get the initial reply to Hello, allow all
                 further communications to our own unique id. */
              if (header->type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN)
                {
                  g_autofree char *my_id = get_arg0_string (buffer);
                  flatpak_proxy_client_update_unique_id_policy (client, my_id, FLATPAK_POLICY_TALK);
                }
              /* ... else it's an ERROR or something. Either way, pass it
               * through to the client unedited. */
              break;

            case EXPECTED_REPLY_REWRITE:
              /* Replace a roundtrip ping with the rewritten message */

              rewritten = g_hash_table_lookup (client->rewrite_reply,
                                               GINT_TO_POINTER (header->reply_serial));

              if (client->proxy->log_messages)
                g_print ("*REWRITTEN*\n");

              g_dbus_message_set_serial (rewritten, header->serial);
              g_clear_pointer (&buffer, buffer_unref);
              buffer = message_to_buffer (rewritten);

              g_hash_table_remove (client->rewrite_reply,
                                   GINT_TO_POINTER (header->reply_serial));
              break;

            case EXPECTED_REPLY_FAKE_LIST_NAMES:
              /* This is a reply from the bus to a fake ListNames
                 request, request ownership of any name matching a
                 wildcard policy */

              queue_wildcard_initial_name_ops (client, header, buffer);

              /* Don't forward fake replies to the app */
              if (client->proxy->log_messages)
                g_print ("*SKIPPED*\n");
              g_clear_pointer (&buffer, buffer_unref);

              /* Start reading the clients requests now that we are done with the names */
              start_reading (&client->client_side);
              break;

            case EXPECTED_REPLY_FAKE_GET_NAME_OWNER:
              /* This is a reply from the bus to a fake GetNameOwner
                 request, update the policy for this unique name based on
                 the policy */
              {
                char *requested_name = g_hash_table_lookup (client->get_owner_reply, GINT_TO_POINTER (header->reply_serial));

                if (header->type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN)
                  {
                    g_autofree char *owner = get_arg0_string (buffer);
                    flatpak_proxy_client_add_unique_id_owned_name (client, owner, requested_name);
                  }

                g_hash_table_remove (client->get_owner_reply, GINT_TO_POINTER (header->reply_serial));

                /* Don't forward fake replies to the app */
                if (client->proxy->log_messages)
                  g_print ("*SKIPPED*\n");
                g_clear_pointer (&buffer, buffer_unref);
                break;
              }

            case EXPECTED_REPLY_FILTER:
              if (client->proxy->log_messages)
                g_print ("*SKIPPED*\n");
              g_clear_pointer (&buffer, buffer_unref);
              break;

            case EXPECTED_REPLY_LIST_NAMES:
              /* This is a reply from the bus to a ListNames request, filter
                 it according to the policy */
              if (header->type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN)
                {
                  Buffer *filtered_buffer;

                  filtered_buffer = filter_names_list (client, buffer);
                  g_clear_pointer (&buffer, buffer_unref);
                  buffer = filtered_buffer;
                }

              break;

            case EXPECTED_REPLY_NORMAL:
              break;

            default:
              g_warning ("Unexpected expected reply type %d", expected_reply);
            }
        }
      else /* Not reply */
        {

          /* Don't allow reply types with no reply_serial */
          if (header->type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN ||
              header->type == G_DBUS_MESSAGE_TYPE_ERROR)
            {
              if (client->proxy->log_messages)
                g_print ("*Invalid reply*\n");
              g_clear_pointer (&buffer, buffer_unref);
            }

          /* We filter all NameOwnerChanged signal according to the policy */
          if (message_is_name_owner_changed (client, header))
            {
              if (should_filter_name_owner_changed (client, buffer))
                g_clear_pointer (&buffer, buffer_unref);
            }
        }

      /* All incoming broadcast signals are filtered according to policy */
      if (header->type == G_DBUS_MESSAGE_TYPE_SIGNAL && header->destination == NULL)
        {
          g_autoptr(GList) filters = NULL;
          gboolean filtered = TRUE;

          policy = flatpak_proxy_client_get_max_policy_and_matched (client, header->sender, &filters);

          if (policy == FLATPAK_POLICY_OWN ||
              policy == FLATPAK_POLICY_TALK ||
              any_filter_matches (filters, FILTER_TYPE_BROADCAST,
                                  header->path,
                                  header->interface,
                                  header->member))
            filtered = FALSE;

          if (filtered)
            {
              if (client->proxy->log_messages)
                g_print ("*FILTERED IN*\n");
              g_clear_pointer (&buffer, buffer_unref);
            }
        }

      /* We received and forwarded a message from a trusted peer. Make the policy for
         this unique id SEE so that the client can track its lifetime. */
      if (buffer && header->sender && header->sender[0] == ':')
        flatpak_proxy_client_update_unique_id_policy (client, header->sender, FLATPAK_POLICY_SEE);

      if (buffer && client_message_generates_reply (header))
        queue_expected_reply (side, header->serial, EXPECTED_REPLY_NORMAL);
    }

  if (buffer)
    queue_outgoing_buffer (&client->client_side, buffer);
}

static void
got_buffer_from_side (ProxySide *side, Buffer *buffer)
{
  FlatpakProxyClient *client = side->client;

  if (side == &client->client_side)
    got_buffer_from_client (client, side, buffer);
  else
    got_buffer_from_bus (client, side, buffer);
}

#define _DBUS_ISASCII(c) ((c) != '\0' && (((c) & ~0x7f) == 0))

static gboolean
auth_line_is_valid (guint8 *line, guint8 *line_end)
{
  guint8 *p;

  for (p = line; p < line_end; p++)
    {
      if (!_DBUS_ISASCII (*p))
        return FALSE;

      /* Technically, the dbus spec allows all ASCII characters, but for robustness we also
         fail if we see any control characters. Such low values will appear in  potential attacks,
         but will never happen in real sasl (where all binary data is hex encoded). */
      if (*p < ' ')
        return FALSE;
    }

  /* For robustness we require the first char of the line to be an upper case letter.
     This is not technically required by the dbus spec, but all commands are upper
     case, and there is no provisioning for whitespace before the command, so in practice
     this is true, and this means we're not confused by e.g. initial whitespace. */
  if (line[0] < 'A' || line[0] > 'Z')
    return FALSE;

  return TRUE;
}

static gboolean
auth_line_is_begin (guint8 *line)
{
  guint8 next_char;

  if (!g_str_has_prefix ((char *) line, AUTH_BEGIN))
    return FALSE;

  /* dbus-daemon accepts either nothing, or a whitespace followed by anything as end of auth */
  next_char = line[strlen (AUTH_BEGIN)];
  return next_char == 0 ||
         next_char == ' ' ||
         next_char == '\t';
}

static guint8 *
find_auth_line_end (guint8 *line_start, gsize buffer_size)
{
  return memmem (line_start, buffer_size,
                 AUTH_LINE_SENTINEL, strlen (AUTH_LINE_SENTINEL));
}

static gssize
find_auth_end (FlatpakProxyClient *client, Buffer *buffer, gsize *out_lines_skipped)
{
  goffset offset = 0;
  gsize original_size = client->auth_buffer->len;
  gsize lines_skipped = 0;

  /* Add the new data to the remaining data from last iteration */
  g_byte_array_append (client->auth_buffer, buffer->data, buffer->pos);

  while (TRUE)
    {
      guint8 *line_start = client->auth_buffer->data + offset;
      gsize remaining_data = client->auth_buffer->len - offset;
      guint8 *line_end;

      line_end = find_auth_line_end (line_start, remaining_data);
      if (line_end) /* Found end of line */
        {
          offset = (line_end + strlen (AUTH_LINE_SENTINEL) - client->auth_buffer->data);

          if (!auth_line_is_valid (line_start, line_end))
            return FIND_AUTH_END_ABORT;

          *line_end = 0;
          if (auth_line_is_begin (line_start))
            {
              *out_lines_skipped = lines_skipped;
              return offset - original_size;
            }

          /* continue with next line */
          ++lines_skipped;
        }
      else
        {
          /* No more end-of-line in this buffer */
          *out_lines_skipped = lines_skipped;
          g_byte_array_remove_range (client->auth_buffer, 0, offset);

          /* Abort if more than 16k before newline, similar to what dbus-daemon does */
          if (client->auth_buffer->len >= 16 * 1024)
            return FIND_AUTH_END_ABORT;

          return FIND_AUTH_END_CONTINUE;
        }
    }
}

static gboolean
side_in_cb (GSocket *socket, GIOCondition condition, gpointer user_data)
{
  ProxySide *side = user_data;
  FlatpakProxyClient *client = side->client;
  GError *error = NULL;
  Buffer *buffer;
  gboolean retval = G_SOURCE_CONTINUE;
  gboolean wake_client_reader = FALSE;

  g_object_ref (client);

  while (!side->closed)
    {
      if (!side->got_first_byte)
        buffer = buffer_new (1, NULL);
      else if (client->auth_state != AUTH_COMPLETE)
        buffer = buffer_new (256, NULL);
      else
        buffer = side->current_read_buffer;

      if (!buffer_read (side, buffer, socket))
        {
          if (buffer != side->current_read_buffer)
            buffer_unref (buffer);
          break;
        }

      if (client->auth_state != AUTH_COMPLETE)
        {
          if (buffer->pos == 0)
            {
              buffer_unref (buffer);
              continue;
            }

          /* The state of the client after handling this buffer */
          AuthState new_auth_state = client->auth_state;

          buffer->size = buffer->pos;
          if (!side->got_first_byte)
            {
              buffer->send_credentials = TRUE;
              side->got_first_byte = TRUE;
            }
          /* Look for end of authentication mechanism */
          else if (side == &client->client_side && client->auth_state == AUTH_WAITING_FOR_BEGIN)
            {
              gsize lines_skipped = 0;
              gssize auth_end = find_auth_end (client, buffer, &lines_skipped);

              client->auth_requests += lines_skipped;

              if (auth_end >= 0)
                {
                  gsize extra_data;

                  if (client->auth_replies == client->auth_requests)
                    new_auth_state = AUTH_COMPLETE;
                  else
                    new_auth_state = AUTH_WAITING_FOR_BACKLOG;

                  extra_data = buffer->pos - auth_end;
                  buffer->size = buffer->pos = auth_end;

                  /* We may have gotten some extra data which is not part of
                     the auth handshake, keep it for the next iteration. */
                  if (extra_data > 0)
                    side->extra_input_data = g_bytes_new (buffer->data + buffer->size, extra_data);
                }
              else if (auth_end == FIND_AUTH_END_ABORT)
                {
                  buffer_unref (buffer);
                  if (client->proxy->log_messages)
                    g_print ("Invalid AUTH line, aborting\n");
                  side_closed (side);
                  break;
                }
            }
          else if (side == &client->bus_side)
            {
              gsize remaining = buffer->pos;
              guint8 *line_start = buffer->data;

              while (remaining > 0)
                {
                  guint8 *line_end = NULL;

                  if (client->auth_replies == client->auth_requests)
                    {
                      buffer_unref (buffer);
                      if (client->proxy->log_messages)
                        g_print ("Unexpected auth reply line from bus, aborting\n");
                      side_closed (side);
                      break;
                    }

                  line_end = find_auth_line_end (line_start, remaining);
                  if (line_end == NULL)
                    line_end = line_start + remaining;
                  else
                    {
                      line_end += strlen (AUTH_LINE_SENTINEL);
                      client->auth_replies++;
                    }

                  remaining -= line_end - line_start;
                  line_start = line_end;

                  if (client->auth_state == AUTH_WAITING_FOR_BACKLOG &&
                      client->auth_replies == client->auth_requests)
                    {
                      new_auth_state = AUTH_COMPLETE;
                      /* We may have added extra data on the input, ensure we read it directly */
                      wake_client_reader = TRUE;

                      buffer->pos = buffer->size = line_start - buffer->data;

                      /* We may have gotten some extra data which is not part of
                         the auth handshake, keep it for the next iteration. */
                      if (remaining > 0)
                        side->extra_input_data = g_bytes_new (line_start, remaining);

                      break;
                    }
                }
            }

          got_buffer_from_side (side, buffer);

          client->auth_state = new_auth_state;
        }
      else if (buffer->pos == buffer->size)
        {
          if (buffer == &side->header_buffer)
            {
              gssize required;
              required = g_dbus_message_bytes_needed (buffer->data, buffer->size, &error);
              if (required < 0)
                {
                  g_warning ("Invalid message header read");
                  side_closed (side);
                }
              else
                {
                  side->current_read_buffer = buffer_new (required, buffer);
                }
            }
          else
            {
              got_buffer_from_side (side, buffer);
              side->header_buffer.pos = 0;
              side->current_read_buffer = &side->header_buffer;
            }
        }
    }

  if (side->closed)
    {
      side->in_source = NULL;
      retval = G_SOURCE_REMOVE;
    }
  else if (wake_client_reader)
    {
      GSocket *client_socket = g_socket_connection_get_socket (client->client_side.connection);
      side_in_cb (client_socket, G_IO_IN, &client->client_side);
    }

  g_object_unref (client);

  return retval;
}

static void
start_reading (ProxySide *side)
{
  GSocket *socket;

  socket = g_socket_connection_get_socket (side->connection);
  side->in_source = g_socket_create_source (socket, G_IO_IN, NULL);
  g_source_set_callback (side->in_source, G_SOURCE_FUNC (side_in_cb), side, NULL);
  g_source_attach (side->in_source, NULL);
  g_source_unref (side->in_source);
}

static void
stop_reading (ProxySide *side)
{
  if (side->in_source)
    {
      g_source_destroy (side->in_source);
      side->in_source = NULL;
    }
}


static void
client_connected_to_dbus (GObject      *source_object,
                          GAsyncResult *res,
                          gpointer      user_data)
{
  FlatpakProxyClient *client = user_data;
  GSocketConnection *connection;
  GError *error = NULL;
  GIOStream *stream;

  stream = g_dbus_address_get_stream_finish (res, NULL, &error);
  if (stream == NULL)
    {
      g_warning ("Failed to connect to bus: %s", error->message);
      g_object_unref (client);
      return;
    }

  connection = G_SOCKET_CONNECTION (stream);
  g_socket_set_blocking (g_socket_connection_get_socket (connection), FALSE);
  client->bus_side.connection = connection;

  start_reading (&client->client_side);
  start_reading (&client->bus_side);
}

static gboolean
flatpak_proxy_incoming (GSocketService    *service,
                        GSocketConnection *connection,
                        GObject           *source_object)
{
  FlatpakProxy *proxy = FLATPAK_PROXY (service);
  FlatpakProxyClient *client;

  client = flatpak_proxy_client_new (proxy, connection);

  g_dbus_address_get_stream (proxy->dbus_address,
                             NULL,
                             client_connected_to_dbus,
                             client);
  return TRUE;
}

static void
flatpak_proxy_init (FlatpakProxy *proxy)
{
  proxy->filters = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, (GDestroyNotify) filter_list_free);
  flatpak_proxy_add_policy (proxy, "org.freedesktop.DBus", FALSE, FLATPAK_POLICY_TALK);
}

static void
flatpak_proxy_class_init (FlatpakProxyClass *klass)
{
  GObjectClass *object_class = G_OBJECT_CLASS (klass);
  GSocketServiceClass *socket_service_class = G_SOCKET_SERVICE_CLASS (klass);

  object_class->get_property = flatpak_proxy_get_property;
  object_class->set_property = flatpak_proxy_set_property;
  object_class->finalize = flatpak_proxy_finalize;

  socket_service_class->incoming = flatpak_proxy_incoming;

  g_object_class_install_property (object_class,
                                   PROP_DBUS_ADDRESS,
                                   g_param_spec_string ("dbus-address",
                                                        "",
                                                        "",
                                                        NULL,
                                                        G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));
  g_object_class_install_property (object_class,
                                   PROP_SOCKET_PATH,
                                   g_param_spec_string ("socket-path",
                                                        "",
                                                        "",
                                                        NULL,
                                                        G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));

}

FlatpakProxy *
flatpak_proxy_new (const char *dbus_address,
                   const char *socket_path)
{
  FlatpakProxy *proxy;

  proxy = g_object_new (FLATPAK_TYPE_PROXY, "dbus-address", dbus_address, "socket-path", socket_path, NULL);
  return proxy;
}

gboolean
flatpak_proxy_start (FlatpakProxy *proxy, GError **error)
{
  GSocketAddress *address;
  gboolean res;

  unlink (proxy->socket_path);

  address = g_unix_socket_address_new (proxy->socket_path);

  res = g_socket_listener_add_address (G_SOCKET_LISTENER (proxy),
                                       address,
                                       G_SOCKET_TYPE_STREAM,
                                       G_SOCKET_PROTOCOL_DEFAULT,
                                       NULL, /* source_object */
                                       NULL, /* effective_address */
                                       error);
  g_object_unref (address);

  if (!res)
    return FALSE;


  g_socket_service_start (G_SOCKET_SERVICE (proxy));
  return TRUE;
}

void
flatpak_proxy_stop (FlatpakProxy *proxy)
{
  unlink (proxy->socket_path);

  g_socket_service_stop (G_SOCKET_SERVICE (proxy));
}