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
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
|
/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
/* dbus-sysdeps-unix.c Wrappers around UNIX system/libc features (internal to D-Bus implementation)
*
* Copyright (C) 2002, 2003, 2006 Red Hat, Inc.
* Copyright (C) 2003 CodeFactory AB
*
* Licensed under the Academic Free License version 2.1
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include <config.h>
#include "dbus-internals.h"
#include "dbus-sysdeps.h"
#include "dbus-sysdeps-unix.h"
#include "dbus-threads.h"
#include "dbus-protocol.h"
#include "dbus-file.h"
#include "dbus-transport.h"
#include "dbus-string.h"
#include "dbus-userdb.h"
#include "dbus-list.h"
#include "dbus-credentials.h"
#include "dbus-nonce.h"
#include <sys/types.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <dirent.h>
#include <sys/un.h>
#include <pwd.h>
#include <time.h>
#include <locale.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <netdb.h>
#include <grp.h>
#include <arpa/inet.h>
#ifdef HAVE_ERRNO_H
#include <errno.h>
#endif
#ifdef HAVE_SYSLOG_H
#include <syslog.h>
#endif
#ifdef HAVE_WRITEV
#include <sys/uio.h>
#endif
#ifdef HAVE_POLL
#include <sys/poll.h>
#endif
#ifdef HAVE_BACKTRACE
#include <execinfo.h>
#endif
#ifdef HAVE_GETPEERUCRED
#include <ucred.h>
#endif
#ifdef HAVE_ALLOCA_H
#include <alloca.h>
#endif
#ifdef HAVE_ADT
#include <bsm/adt.h>
#endif
#ifdef HAVE_SYSTEMD
#include <systemd/sd-daemon.h>
#endif
#if !DBUS_USE_SYNC
#include <pthread.h>
#endif
#ifndef O_BINARY
#define O_BINARY 0
#endif
#ifndef AI_ADDRCONFIG
#define AI_ADDRCONFIG 0
#endif
#ifndef HAVE_SOCKLEN_T
#define socklen_t int
#endif
#if defined (__sun) || defined (__sun__)
/*
* CMS_SPACE etc. definitions for Solaris < 10, based on
* http://mailman.videolan.org/pipermail/vlc-devel/2006-May/024402.html
* via
* http://wiki.opencsw.org/porting-faq#toc10
*
* These are only redefined for Solaris, for now: if your OS needs these too,
* please file a bug. (Or preferably, improve your OS so they're not needed.)
*/
# ifndef CMSG_ALIGN
# ifdef __sun__
# define CMSG_ALIGN(len) _CMSG_DATA_ALIGN (len)
# else
/* aligning to sizeof (long) is assumed to be portable (fd.o#40235) */
# define CMSG_ALIGN(len) (((len) + sizeof (long) - 1) & \
~(sizeof (long) - 1))
# endif
# endif
# ifndef CMSG_SPACE
# define CMSG_SPACE(len) (CMSG_ALIGN (sizeof (struct cmsghdr)) + \
CMSG_ALIGN (len))
# endif
# ifndef CMSG_LEN
# define CMSG_LEN(len) (CMSG_ALIGN (sizeof (struct cmsghdr)) + (len))
# endif
#endif /* Solaris */
/**
* Ensure that the standard file descriptors stdin, stdout and stderr
* are open, by opening /dev/null if necessary.
*
* This function does not use DBusError, to avoid calling malloc(), so
* that it can be used in contexts where an async-signal-safe function
* is required (for example after fork()). Instead, on failure it sets
* errno and returns something like "Failed to open /dev/null" in
* *error_str_p. Callers are expected to combine *error_str_p
* with _dbus_strerror (errno) to get a full error report.
*
* This function can only be called while single-threaded: either during
* startup of an executable, or after fork().
*/
dbus_bool_t
_dbus_ensure_standard_fds (DBusEnsureStandardFdsFlags flags,
const char **error_str_p)
{
static int const relevant_flag[] = { DBUS_FORCE_STDIN_NULL,
DBUS_FORCE_STDOUT_NULL,
DBUS_FORCE_STDERR_NULL };
/* Should always get replaced with the real error before use */
const char *error_str = "Failed mysteriously";
int devnull = -1;
int saved_errno;
/* This function relies on the standard fds having their POSIX values. */
_DBUS_STATIC_ASSERT (STDIN_FILENO == 0);
_DBUS_STATIC_ASSERT (STDOUT_FILENO == 1);
_DBUS_STATIC_ASSERT (STDERR_FILENO == 2);
int i;
for (i = STDIN_FILENO; i <= STDERR_FILENO; i++)
{
/* Because we rely on being single-threaded, and we want the
* standard fds to not be close-on-exec, we don't set it
* close-on-exec. */
if (devnull < i)
devnull = open ("/dev/null", O_RDWR);
if (devnull < 0)
{
error_str = "Failed to open /dev/null";
goto out;
}
/* We already opened all fds < i, so the only way this assertion
* could fail is if another thread closed one, and we document
* this function as not safe for multi-threading. */
_dbus_assert (devnull >= i);
if (devnull != i && (flags & relevant_flag[i]) != 0)
{
if (dup2 (devnull, i) < 0)
{
error_str = "Failed to dup2 /dev/null onto a standard fd";
goto out;
}
}
}
error_str = NULL;
out:
saved_errno = errno;
if (devnull > STDERR_FILENO)
close (devnull);
if (error_str_p != NULL)
*error_str_p = error_str;
errno = saved_errno;
return (error_str == NULL);
}
static dbus_bool_t _dbus_set_fd_nonblocking (int fd,
DBusError *error);
static dbus_bool_t
_dbus_open_socket (int *fd_p,
int domain,
int type,
int protocol,
DBusError *error)
{
#ifdef SOCK_CLOEXEC
dbus_bool_t cloexec_done;
*fd_p = socket (domain, type | SOCK_CLOEXEC, protocol);
cloexec_done = *fd_p >= 0;
/* Check if kernel seems to be too old to know SOCK_CLOEXEC */
if (*fd_p < 0 && (errno == EINVAL || errno == EPROTOTYPE))
#endif
{
*fd_p = socket (domain, type, protocol);
}
if (*fd_p >= 0)
{
#ifdef SOCK_CLOEXEC
if (!cloexec_done)
#endif
{
_dbus_fd_set_close_on_exec(*fd_p);
}
_dbus_verbose ("socket fd %d opened\n", *fd_p);
return TRUE;
}
else
{
dbus_set_error(error,
_dbus_error_from_errno (errno),
"Failed to open socket: %s",
_dbus_strerror (errno));
return FALSE;
}
}
/**
* Opens a UNIX domain socket (as in the socket() call).
* Does not bind the socket.
*
* This will set FD_CLOEXEC for the socket returned
*
* @param fd return location for socket descriptor
* @param error return location for an error
* @returns #FALSE if error is set
*/
static dbus_bool_t
_dbus_open_unix_socket (int *fd,
DBusError *error)
{
return _dbus_open_socket(fd, PF_UNIX, SOCK_STREAM, 0, error);
}
/**
* Closes a socket. Should not be used on non-socket
* file descriptors or handles.
*
* @param fd the socket
* @param error return location for an error
* @returns #FALSE if error is set
*/
dbus_bool_t
_dbus_close_socket (DBusSocket fd,
DBusError *error)
{
return _dbus_close (fd.fd, error);
}
/**
* Like _dbus_read(), but only works on sockets so is
* available on Windows.
*
* @param fd the socket
* @param buffer string to append data to
* @param count max amount of data to read
* @returns number of bytes appended to the string
*/
int
_dbus_read_socket (DBusSocket fd,
DBusString *buffer,
int count)
{
return _dbus_read (fd.fd, buffer, count);
}
/**
* Like _dbus_write(), but only supports sockets
* and is thus available on Windows.
*
* @param fd the file descriptor to write
* @param buffer the buffer to write data from
* @param start the first byte in the buffer to write
* @param len the number of bytes to try to write
* @returns the number of bytes written or -1 on error
*/
int
_dbus_write_socket (DBusSocket fd,
const DBusString *buffer,
int start,
int len)
{
#if HAVE_DECL_MSG_NOSIGNAL
const char *data;
int bytes_written;
data = _dbus_string_get_const_data_len (buffer, start, len);
again:
bytes_written = send (fd.fd, data, len, MSG_NOSIGNAL);
if (bytes_written < 0 && errno == EINTR)
goto again;
return bytes_written;
#else
return _dbus_write (fd.fd, buffer, start, len);
#endif
}
/**
* Like _dbus_read_socket() but also tries to read unix fds from the
* socket. When there are more fds to read than space in the array
* passed this function will fail with ENOSPC.
*
* @param fd the socket
* @param buffer string to append data to
* @param count max amount of data to read
* @param fds array to place read file descriptors in
* @param n_fds on input space in fds array, on output how many fds actually got read
* @returns number of bytes appended to string
*/
int
_dbus_read_socket_with_unix_fds (DBusSocket fd,
DBusString *buffer,
int count,
int *fds,
unsigned int *n_fds) {
#ifndef HAVE_UNIX_FD_PASSING
int r;
if ((r = _dbus_read_socket(fd, buffer, count)) < 0)
return r;
*n_fds = 0;
return r;
#else
int bytes_read;
int start;
struct msghdr m;
struct iovec iov;
_dbus_assert (count >= 0);
_dbus_assert (*n_fds <= DBUS_MAXIMUM_MESSAGE_UNIX_FDS);
start = _dbus_string_get_length (buffer);
if (!_dbus_string_lengthen (buffer, count))
{
errno = ENOMEM;
return -1;
}
_DBUS_ZERO(iov);
iov.iov_base = _dbus_string_get_data_len (buffer, start, count);
iov.iov_len = count;
_DBUS_ZERO(m);
m.msg_iov = &iov;
m.msg_iovlen = 1;
/* Hmm, we have no clue how long the control data will actually be
that is queued for us. The least we can do is assume that the
caller knows. Hence let's make space for the number of fds that
we shall read at max plus the cmsg header. */
m.msg_controllen = CMSG_SPACE(*n_fds * sizeof(int));
/* It's probably safe to assume that systems with SCM_RIGHTS also
know alloca() */
m.msg_control = alloca(m.msg_controllen);
memset(m.msg_control, 0, m.msg_controllen);
/* Do not include the padding at the end when we tell the kernel
* how much we're willing to receive. This avoids getting
* the padding filled with additional fds that we weren't expecting,
* if a (potentially malicious) sender included them. (fd.o #83622) */
m.msg_controllen = CMSG_LEN (*n_fds * sizeof(int));
again:
bytes_read = recvmsg (fd.fd, &m, 0
#ifdef MSG_CMSG_CLOEXEC
|MSG_CMSG_CLOEXEC
#endif
);
if (bytes_read < 0)
{
if (errno == EINTR)
goto again;
else
{
/* put length back (note that this doesn't actually realloc anything) */
_dbus_string_set_length (buffer, start);
return -1;
}
}
else
{
struct cmsghdr *cm;
dbus_bool_t found = FALSE;
if (m.msg_flags & MSG_CTRUNC)
{
/* Hmm, apparently the control data was truncated. The bad
thing is that we might have completely lost a couple of fds
without chance to recover them. Hence let's treat this as a
serious error. */
errno = ENOSPC;
_dbus_string_set_length (buffer, start);
return -1;
}
for (cm = CMSG_FIRSTHDR(&m); cm; cm = CMSG_NXTHDR(&m, cm))
if (cm->cmsg_level == SOL_SOCKET && cm->cmsg_type == SCM_RIGHTS)
{
size_t i;
int *payload = (int *) CMSG_DATA (cm);
size_t payload_len_bytes = (cm->cmsg_len - CMSG_LEN (0));
size_t payload_len_fds = payload_len_bytes / sizeof (int);
size_t fds_to_use;
/* Every unsigned int fits in a size_t without truncation, so
* casting (size_t) *n_fds is OK */
_DBUS_STATIC_ASSERT (sizeof (size_t) >= sizeof (unsigned int));
if (_DBUS_LIKELY (payload_len_fds <= (size_t) *n_fds))
{
/* The fds in the payload will fit in our buffer */
fds_to_use = payload_len_fds;
}
else
{
/* Too many fds in the payload. This shouldn't happen
* any more because we're setting m.msg_controllen to
* the exact number we can accept, but be safe and
* truncate. */
fds_to_use = (size_t) *n_fds;
/* Close the excess fds to avoid DoS: if they stayed open,
* someone could send us an extra fd per message
* and we'd eventually run out. */
for (i = fds_to_use; i < payload_len_fds; i++)
{
close (payload[i]);
}
}
memcpy (fds, payload, fds_to_use * sizeof (int));
found = TRUE;
/* This narrowing cast from size_t to unsigned int cannot
* overflow because we have chosen fds_to_use
* to be <= *n_fds */
*n_fds = (unsigned int) fds_to_use;
/* Linux doesn't tell us whether MSG_CMSG_CLOEXEC actually
worked, hence we need to go through this list and set
CLOEXEC everywhere in any case */
for (i = 0; i < fds_to_use; i++)
_dbus_fd_set_close_on_exec(fds[i]);
break;
}
if (!found)
*n_fds = 0;
/* put length back (doesn't actually realloc) */
_dbus_string_set_length (buffer, start + bytes_read);
#if 0
if (bytes_read > 0)
_dbus_verbose_bytes_of_string (buffer, start, bytes_read);
#endif
return bytes_read;
}
#endif
}
int
_dbus_write_socket_with_unix_fds(DBusSocket fd,
const DBusString *buffer,
int start,
int len,
const int *fds,
int n_fds) {
#ifndef HAVE_UNIX_FD_PASSING
if (n_fds > 0) {
errno = ENOTSUP;
return -1;
}
return _dbus_write_socket(fd, buffer, start, len);
#else
return _dbus_write_socket_with_unix_fds_two(fd, buffer, start, len, NULL, 0, 0, fds, n_fds);
#endif
}
int
_dbus_write_socket_with_unix_fds_two(DBusSocket fd,
const DBusString *buffer1,
int start1,
int len1,
const DBusString *buffer2,
int start2,
int len2,
const int *fds,
int n_fds) {
#ifndef HAVE_UNIX_FD_PASSING
if (n_fds > 0) {
errno = ENOTSUP;
return -1;
}
return _dbus_write_socket_two(fd,
buffer1, start1, len1,
buffer2, start2, len2);
#else
struct msghdr m;
struct cmsghdr *cm;
struct iovec iov[2];
int bytes_written;
_dbus_assert (len1 >= 0);
_dbus_assert (len2 >= 0);
_dbus_assert (n_fds >= 0);
_DBUS_ZERO(iov);
iov[0].iov_base = (char*) _dbus_string_get_const_data_len (buffer1, start1, len1);
iov[0].iov_len = len1;
if (buffer2)
{
iov[1].iov_base = (char*) _dbus_string_get_const_data_len (buffer2, start2, len2);
iov[1].iov_len = len2;
}
_DBUS_ZERO(m);
m.msg_iov = iov;
m.msg_iovlen = buffer2 ? 2 : 1;
if (n_fds > 0)
{
m.msg_controllen = CMSG_SPACE(n_fds * sizeof(int));
m.msg_control = alloca(m.msg_controllen);
memset(m.msg_control, 0, m.msg_controllen);
cm = CMSG_FIRSTHDR(&m);
cm->cmsg_level = SOL_SOCKET;
cm->cmsg_type = SCM_RIGHTS;
cm->cmsg_len = CMSG_LEN(n_fds * sizeof(int));
memcpy(CMSG_DATA(cm), fds, n_fds * sizeof(int));
}
again:
bytes_written = sendmsg (fd.fd, &m, 0
#if HAVE_DECL_MSG_NOSIGNAL
|MSG_NOSIGNAL
#endif
);
if (bytes_written < 0 && errno == EINTR)
goto again;
#if 0
if (bytes_written > 0)
_dbus_verbose_bytes_of_string (buffer, start, bytes_written);
#endif
return bytes_written;
#endif
}
/**
* Like _dbus_write_two() but only works on sockets and is thus
* available on Windows.
*
* @param fd the file descriptor
* @param buffer1 first buffer
* @param start1 first byte to write in first buffer
* @param len1 number of bytes to write from first buffer
* @param buffer2 second buffer, or #NULL
* @param start2 first byte to write in second buffer
* @param len2 number of bytes to write in second buffer
* @returns total bytes written from both buffers, or -1 on error
*/
int
_dbus_write_socket_two (DBusSocket fd,
const DBusString *buffer1,
int start1,
int len1,
const DBusString *buffer2,
int start2,
int len2)
{
#if HAVE_DECL_MSG_NOSIGNAL
struct iovec vectors[2];
const char *data1;
const char *data2;
int bytes_written;
struct msghdr m;
_dbus_assert (buffer1 != NULL);
_dbus_assert (start1 >= 0);
_dbus_assert (start2 >= 0);
_dbus_assert (len1 >= 0);
_dbus_assert (len2 >= 0);
data1 = _dbus_string_get_const_data_len (buffer1, start1, len1);
if (buffer2 != NULL)
data2 = _dbus_string_get_const_data_len (buffer2, start2, len2);
else
{
data2 = NULL;
start2 = 0;
len2 = 0;
}
vectors[0].iov_base = (char*) data1;
vectors[0].iov_len = len1;
vectors[1].iov_base = (char*) data2;
vectors[1].iov_len = len2;
_DBUS_ZERO(m);
m.msg_iov = vectors;
m.msg_iovlen = data2 ? 2 : 1;
again:
bytes_written = sendmsg (fd.fd, &m, MSG_NOSIGNAL);
if (bytes_written < 0 && errno == EINTR)
goto again;
return bytes_written;
#else
return _dbus_write_two (fd.fd, buffer1, start1, len1,
buffer2, start2, len2);
#endif
}
/**
* Thin wrapper around the read() system call that appends
* the data it reads to the DBusString buffer. It appends
* up to the given count, and returns the same value
* and same errno as read(). The only exception is that
* _dbus_read() handles EINTR for you. Also, _dbus_read() can
* return ENOMEM, even though regular UNIX read doesn't.
*
* Unlike _dbus_read_socket(), _dbus_read() is not available
* on Windows.
*
* @param fd the file descriptor to read from
* @param buffer the buffer to append data to
* @param count the amount of data to read
* @returns the number of bytes read or -1
*/
int
_dbus_read (int fd,
DBusString *buffer,
int count)
{
int bytes_read;
int start;
char *data;
_dbus_assert (count >= 0);
start = _dbus_string_get_length (buffer);
if (!_dbus_string_lengthen (buffer, count))
{
errno = ENOMEM;
return -1;
}
data = _dbus_string_get_data_len (buffer, start, count);
again:
bytes_read = read (fd, data, count);
if (bytes_read < 0)
{
if (errno == EINTR)
goto again;
else
{
/* put length back (note that this doesn't actually realloc anything) */
_dbus_string_set_length (buffer, start);
return -1;
}
}
else
{
/* put length back (doesn't actually realloc) */
_dbus_string_set_length (buffer, start + bytes_read);
#if 0
if (bytes_read > 0)
_dbus_verbose_bytes_of_string (buffer, start, bytes_read);
#endif
return bytes_read;
}
}
/**
* Thin wrapper around the write() system call that writes a part of a
* DBusString and handles EINTR for you.
*
* @param fd the file descriptor to write
* @param buffer the buffer to write data from
* @param start the first byte in the buffer to write
* @param len the number of bytes to try to write
* @returns the number of bytes written or -1 on error
*/
int
_dbus_write (int fd,
const DBusString *buffer,
int start,
int len)
{
const char *data;
int bytes_written;
data = _dbus_string_get_const_data_len (buffer, start, len);
again:
bytes_written = write (fd, data, len);
if (bytes_written < 0 && errno == EINTR)
goto again;
#if 0
if (bytes_written > 0)
_dbus_verbose_bytes_of_string (buffer, start, bytes_written);
#endif
return bytes_written;
}
/**
* Like _dbus_write() but will use writev() if possible
* to write both buffers in sequence. The return value
* is the number of bytes written in the first buffer,
* plus the number written in the second. If the first
* buffer is written successfully and an error occurs
* writing the second, the number of bytes in the first
* is returned (i.e. the error is ignored), on systems that
* don't have writev. Handles EINTR for you.
* The second buffer may be #NULL.
*
* @param fd the file descriptor
* @param buffer1 first buffer
* @param start1 first byte to write in first buffer
* @param len1 number of bytes to write from first buffer
* @param buffer2 second buffer, or #NULL
* @param start2 first byte to write in second buffer
* @param len2 number of bytes to write in second buffer
* @returns total bytes written from both buffers, or -1 on error
*/
int
_dbus_write_two (int fd,
const DBusString *buffer1,
int start1,
int len1,
const DBusString *buffer2,
int start2,
int len2)
{
_dbus_assert (buffer1 != NULL);
_dbus_assert (start1 >= 0);
_dbus_assert (start2 >= 0);
_dbus_assert (len1 >= 0);
_dbus_assert (len2 >= 0);
#ifdef HAVE_WRITEV
{
struct iovec vectors[2];
const char *data1;
const char *data2;
int bytes_written;
data1 = _dbus_string_get_const_data_len (buffer1, start1, len1);
if (buffer2 != NULL)
data2 = _dbus_string_get_const_data_len (buffer2, start2, len2);
else
{
data2 = NULL;
start2 = 0;
len2 = 0;
}
vectors[0].iov_base = (char*) data1;
vectors[0].iov_len = len1;
vectors[1].iov_base = (char*) data2;
vectors[1].iov_len = len2;
again:
bytes_written = writev (fd,
vectors,
data2 ? 2 : 1);
if (bytes_written < 0 && errno == EINTR)
goto again;
return bytes_written;
}
#else /* HAVE_WRITEV */
{
int ret1, ret2;
ret1 = _dbus_write (fd, buffer1, start1, len1);
if (ret1 == len1 && buffer2 != NULL)
{
ret2 = _dbus_write (fd, buffer2, start2, len2);
if (ret2 < 0)
ret2 = 0; /* we can't report an error as the first write was OK */
return ret1 + ret2;
}
else
return ret1;
}
#endif /* !HAVE_WRITEV */
}
#define _DBUS_MAX_SUN_PATH_LENGTH 99
/**
* @def _DBUS_MAX_SUN_PATH_LENGTH
*
* Maximum length of the path to a UNIX domain socket,
* sockaddr_un::sun_path member. POSIX requires that all systems
* support at least 100 bytes here, including the nul termination.
* We use 99 for the max value to allow for the nul.
*
* We could probably also do sizeof (addr.sun_path)
* but this way we are the same on all platforms
* which is probably a good idea.
*/
/**
* Creates a socket and connects it to the UNIX domain socket at the
* given path. The connection fd is returned, and is set up as
* nonblocking.
*
* Uses abstract sockets instead of filesystem-linked sockets if
* requested (it's possible only on Linux; see "man 7 unix" on Linux).
* On non-Linux abstract socket usage always fails.
*
* This will set FD_CLOEXEC for the socket returned.
*
* @param path the path to UNIX domain socket
* @param abstract #TRUE to use abstract namespace
* @param error return location for error code
* @returns connection file descriptor or -1 on error
*/
int
_dbus_connect_unix_socket (const char *path,
dbus_bool_t abstract,
DBusError *error)
{
int fd;
size_t path_len;
struct sockaddr_un addr;
_DBUS_ASSERT_ERROR_IS_CLEAR (error);
_dbus_verbose ("connecting to unix socket %s abstract=%d\n",
path, abstract);
if (!_dbus_open_unix_socket (&fd, error))
{
_DBUS_ASSERT_ERROR_IS_SET(error);
return -1;
}
_DBUS_ASSERT_ERROR_IS_CLEAR(error);
_DBUS_ZERO (addr);
addr.sun_family = AF_UNIX;
path_len = strlen (path);
if (abstract)
{
#ifdef HAVE_ABSTRACT_SOCKETS
addr.sun_path[0] = '\0'; /* this is what says "use abstract" */
path_len++; /* Account for the extra nul byte added to the start of sun_path */
if (path_len > _DBUS_MAX_SUN_PATH_LENGTH)
{
dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
"Abstract socket name too long\n");
_dbus_close (fd, NULL);
return -1;
}
strncpy (&addr.sun_path[1], path, path_len);
/* _dbus_verbose_bytes (addr.sun_path, sizeof (addr.sun_path)); */
#else /* HAVE_ABSTRACT_SOCKETS */
dbus_set_error (error, DBUS_ERROR_NOT_SUPPORTED,
"Operating system does not support abstract socket namespace\n");
_dbus_close (fd, NULL);
return -1;
#endif /* ! HAVE_ABSTRACT_SOCKETS */
}
else
{
if (path_len > _DBUS_MAX_SUN_PATH_LENGTH)
{
dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
"Socket name too long\n");
_dbus_close (fd, NULL);
return -1;
}
strncpy (addr.sun_path, path, path_len);
}
if (connect (fd, (struct sockaddr*) &addr, _DBUS_STRUCT_OFFSET (struct sockaddr_un, sun_path) + path_len) < 0)
{
dbus_set_error (error,
_dbus_error_from_errno (errno),
"Failed to connect to socket %s: %s",
path, _dbus_strerror (errno));
_dbus_close (fd, NULL);
return -1;
}
if (!_dbus_set_fd_nonblocking (fd, error))
{
_DBUS_ASSERT_ERROR_IS_SET (error);
_dbus_close (fd, NULL);
return -1;
}
return fd;
}
/**
* Creates a UNIX domain socket and connects it to the specified
* process to execute.
*
* This will set FD_CLOEXEC for the socket returned.
*
* @param path the path to the executable
* @param argv the argument list for the process to execute.
* argv[0] typically is identical to the path of the executable
* @param error return location for error code
* @returns connection file descriptor or -1 on error
*/
int
_dbus_connect_exec (const char *path,
char *const argv[],
DBusError *error)
{
int fds[2];
pid_t pid;
int retval;
dbus_bool_t cloexec_done = 0;
_DBUS_ASSERT_ERROR_IS_CLEAR (error);
_dbus_verbose ("connecting to process %s\n", path);
#ifdef SOCK_CLOEXEC
retval = socketpair (AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC, 0, fds);
cloexec_done = (retval >= 0);
if (retval < 0 && (errno == EINVAL || errno == EPROTOTYPE))
#endif
{
retval = socketpair (AF_UNIX, SOCK_STREAM, 0, fds);
}
if (retval < 0)
{
dbus_set_error (error,
_dbus_error_from_errno (errno),
"Failed to create socket pair: %s",
_dbus_strerror (errno));
return -1;
}
if (!cloexec_done)
{
_dbus_fd_set_close_on_exec (fds[0]);
_dbus_fd_set_close_on_exec (fds[1]);
}
pid = fork ();
if (pid < 0)
{
dbus_set_error (error,
_dbus_error_from_errno (errno),
"Failed to fork() to call %s: %s",
path, _dbus_strerror (errno));
close (fds[0]);
close (fds[1]);
return -1;
}
if (pid == 0)
{
/* child */
close (fds[0]);
dup2 (fds[1], STDIN_FILENO);
dup2 (fds[1], STDOUT_FILENO);
if (fds[1] != STDIN_FILENO &&
fds[1] != STDOUT_FILENO)
close (fds[1]);
/* Inherit STDERR and the controlling terminal from the
parent */
_dbus_close_all ();
execvp (path, (char * const *) argv);
fprintf (stderr, "Failed to execute process %s: %s\n", path, _dbus_strerror (errno));
_exit(1);
}
/* parent */
close (fds[1]);
if (!_dbus_set_fd_nonblocking (fds[0], error))
{
_DBUS_ASSERT_ERROR_IS_SET (error);
close (fds[0]);
return -1;
}
return fds[0];
}
/**
* Creates a socket and binds it to the given path,
* then listens on the socket. The socket is
* set to be nonblocking.
*
* Uses abstract sockets instead of filesystem-linked
* sockets if requested (it's possible only on Linux;
* see "man 7 unix" on Linux).
* On non-Linux abstract socket usage always fails.
*
* This will set FD_CLOEXEC for the socket returned
*
* @param path the socket name
* @param abstract #TRUE to use abstract namespace
* @param error return location for errors
* @returns the listening file descriptor or -1 on error
*/
int
_dbus_listen_unix_socket (const char *path,
dbus_bool_t abstract,
DBusError *error)
{
int listen_fd;
struct sockaddr_un addr;
size_t path_len;
_DBUS_ASSERT_ERROR_IS_CLEAR (error);
_dbus_verbose ("listening on unix socket %s abstract=%d\n",
path, abstract);
if (!_dbus_open_unix_socket (&listen_fd, error))
{
_DBUS_ASSERT_ERROR_IS_SET(error);
return -1;
}
_DBUS_ASSERT_ERROR_IS_CLEAR(error);
_DBUS_ZERO (addr);
addr.sun_family = AF_UNIX;
path_len = strlen (path);
if (abstract)
{
#ifdef HAVE_ABSTRACT_SOCKETS
/* remember that abstract names aren't nul-terminated so we rely
* on sun_path being filled in with zeroes above.
*/
addr.sun_path[0] = '\0'; /* this is what says "use abstract" */
path_len++; /* Account for the extra nul byte added to the start of sun_path */
if (path_len > _DBUS_MAX_SUN_PATH_LENGTH)
{
dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
"Abstract socket name too long\n");
_dbus_close (listen_fd, NULL);
return -1;
}
strncpy (&addr.sun_path[1], path, path_len);
/* _dbus_verbose_bytes (addr.sun_path, sizeof (addr.sun_path)); */
#else /* HAVE_ABSTRACT_SOCKETS */
dbus_set_error (error, DBUS_ERROR_NOT_SUPPORTED,
"Operating system does not support abstract socket namespace\n");
_dbus_close (listen_fd, NULL);
return -1;
#endif /* ! HAVE_ABSTRACT_SOCKETS */
}
else
{
/* Discussed security implications of this with Nalin,
* and we couldn't think of where it would kick our ass, but
* it still seems a bit sucky. It also has non-security suckage;
* really we'd prefer to exit if the socket is already in use.
* But there doesn't seem to be a good way to do this.
*
* Just to be extra careful, I threw in the stat() - clearly
* the stat() can't *fix* any security issue, but it at least
* avoids inadvertent/accidental data loss.
*/
{
struct stat sb;
if (stat (path, &sb) == 0 &&
S_ISSOCK (sb.st_mode))
unlink (path);
}
if (path_len > _DBUS_MAX_SUN_PATH_LENGTH)
{
dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
"Socket name too long\n");
_dbus_close (listen_fd, NULL);
return -1;
}
strncpy (addr.sun_path, path, path_len);
}
if (bind (listen_fd, (struct sockaddr*) &addr, _DBUS_STRUCT_OFFSET (struct sockaddr_un, sun_path) + path_len) < 0)
{
dbus_set_error (error, _dbus_error_from_errno (errno),
"Failed to bind socket \"%s\": %s",
path, _dbus_strerror (errno));
_dbus_close (listen_fd, NULL);
return -1;
}
if (listen (listen_fd, SOMAXCONN /* backlog */) < 0)
{
dbus_set_error (error, _dbus_error_from_errno (errno),
"Failed to listen on socket \"%s\": %s",
path, _dbus_strerror (errno));
_dbus_close (listen_fd, NULL);
return -1;
}
if (!_dbus_set_fd_nonblocking (listen_fd, error))
{
_DBUS_ASSERT_ERROR_IS_SET (error);
_dbus_close (listen_fd, NULL);
return -1;
}
/* Try opening up the permissions, but if we can't, just go ahead
* and continue, maybe it will be good enough.
*/
if (!abstract && chmod (path, 0777) < 0)
_dbus_warn ("Could not set mode 0777 on socket %s", path);
return listen_fd;
}
/**
* Acquires one or more sockets passed in from systemd. The sockets
* are set to be nonblocking.
*
* This will set FD_CLOEXEC for the sockets returned.
*
* @param fds the file descriptors
* @param error return location for errors
* @returns the number of file descriptors
*/
int
_dbus_listen_systemd_sockets (DBusSocket **fds,
DBusError *error)
{
#ifdef HAVE_SYSTEMD
int r, n;
int fd;
DBusSocket *new_fds;
_DBUS_ASSERT_ERROR_IS_CLEAR (error);
n = sd_listen_fds (TRUE);
if (n < 0)
{
dbus_set_error (error, _dbus_error_from_errno (-n),
"Failed to acquire systemd socket: %s",
_dbus_strerror (-n));
return -1;
}
if (n <= 0)
{
dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
"No socket received.");
return -1;
}
for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; fd ++)
{
r = sd_is_socket (fd, AF_UNSPEC, SOCK_STREAM, 1);
if (r < 0)
{
dbus_set_error (error, _dbus_error_from_errno (-r),
"Failed to verify systemd socket type: %s",
_dbus_strerror (-r));
return -1;
}
if (!r)
{
dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
"Passed socket has wrong type.");
return -1;
}
}
/* OK, the file descriptors are all good, so let's take posession of
them then. */
new_fds = dbus_new (DBusSocket, n);
if (!new_fds)
{
dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
"Failed to allocate file handle array.");
goto fail;
}
for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; fd ++)
{
if (!_dbus_set_fd_nonblocking (fd, error))
{
_DBUS_ASSERT_ERROR_IS_SET (error);
goto fail;
}
new_fds[fd - SD_LISTEN_FDS_START].fd = fd;
}
*fds = new_fds;
return n;
fail:
for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; fd ++)
{
_dbus_close (fd, NULL);
}
dbus_free (new_fds);
return -1;
#else
dbus_set_error_const (error, DBUS_ERROR_NOT_SUPPORTED,
"dbus was compiled without systemd support");
return -1;
#endif
}
/**
* Creates a socket and connects to a socket at the given host
* and port. The connection fd is returned, and is set up as
* nonblocking.
*
* This will set FD_CLOEXEC for the socket returned
*
* @param host the host name to connect to
* @param port the port to connect to
* @param family the address family to listen on, NULL for all
* @param error return location for error code
* @returns connection file descriptor or -1 on error
*/
DBusSocket
_dbus_connect_tcp_socket (const char *host,
const char *port,
const char *family,
DBusError *error)
{
return _dbus_connect_tcp_socket_with_nonce (host, port, family, (const char*)NULL, error);
}
DBusSocket
_dbus_connect_tcp_socket_with_nonce (const char *host,
const char *port,
const char *family,
const char *noncefile,
DBusError *error)
{
int saved_errno = 0;
DBusSocket fd = DBUS_SOCKET_INIT;
int res;
struct addrinfo hints;
struct addrinfo *ai, *tmp;
_DBUS_ASSERT_ERROR_IS_CLEAR(error);
_DBUS_ZERO (hints);
if (!family)
hints.ai_family = AF_UNSPEC;
else if (!strcmp(family, "ipv4"))
hints.ai_family = AF_INET;
else if (!strcmp(family, "ipv6"))
hints.ai_family = AF_INET6;
else
{
dbus_set_error (error,
DBUS_ERROR_BAD_ADDRESS,
"Unknown address family %s", family);
return _dbus_socket_get_invalid ();
}
hints.ai_protocol = IPPROTO_TCP;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_ADDRCONFIG;
if ((res = getaddrinfo(host, port, &hints, &ai)) != 0)
{
dbus_set_error (error,
_dbus_error_from_errno (errno),
"Failed to lookup host/port: \"%s:%s\": %s (%d)",
host, port, gai_strerror(res), res);
return _dbus_socket_get_invalid ();
}
tmp = ai;
while (tmp)
{
if (!_dbus_open_socket (&fd.fd, tmp->ai_family, SOCK_STREAM, 0, error))
{
freeaddrinfo(ai);
_DBUS_ASSERT_ERROR_IS_SET(error);
return _dbus_socket_get_invalid ();
}
_DBUS_ASSERT_ERROR_IS_CLEAR(error);
if (connect (fd.fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) < 0)
{
saved_errno = errno;
_dbus_close (fd.fd, NULL);
fd.fd = -1;
tmp = tmp->ai_next;
continue;
}
break;
}
freeaddrinfo(ai);
if (fd.fd == -1)
{
dbus_set_error (error,
_dbus_error_from_errno (saved_errno),
"Failed to connect to socket \"%s:%s\" %s",
host, port, _dbus_strerror(saved_errno));
return _dbus_socket_get_invalid ();
}
if (noncefile != NULL)
{
DBusString noncefileStr;
dbus_bool_t ret;
_dbus_string_init_const (&noncefileStr, noncefile);
ret = _dbus_send_nonce (fd, &noncefileStr, error);
_dbus_string_free (&noncefileStr);
if (!ret)
{
_dbus_close (fd.fd, NULL);
return _dbus_socket_get_invalid ();
}
}
if (!_dbus_set_fd_nonblocking (fd.fd, error))
{
_dbus_close (fd.fd, NULL);
return _dbus_socket_get_invalid ();
}
return fd;
}
/**
* Creates a socket and binds it to the given path, then listens on
* the socket. The socket is set to be nonblocking. In case of port=0
* a random free port is used and returned in the port parameter.
* If inaddr_any is specified, the hostname is ignored.
*
* This will set FD_CLOEXEC for the socket returned
*
* @param host the host name to listen on
* @param port the port to listen on, if zero a free port will be used
* @param family the address family to listen on, NULL for all
* @param retport string to return the actual port listened on
* @param fds_p location to store returned file descriptors
* @param error return location for errors
* @returns the number of listening file descriptors or -1 on error
*/
int
_dbus_listen_tcp_socket (const char *host,
const char *port,
const char *family,
DBusString *retport,
DBusSocket **fds_p,
DBusError *error)
{
int saved_errno;
int nlisten_fd = 0, res, i;
DBusSocket *listen_fd = NULL;
struct addrinfo hints;
struct addrinfo *ai, *tmp;
unsigned int reuseaddr;
*fds_p = NULL;
_DBUS_ASSERT_ERROR_IS_CLEAR (error);
_DBUS_ZERO (hints);
if (!family)
hints.ai_family = AF_UNSPEC;
else if (!strcmp(family, "ipv4"))
hints.ai_family = AF_INET;
else if (!strcmp(family, "ipv6"))
hints.ai_family = AF_INET6;
else
{
dbus_set_error (error,
DBUS_ERROR_BAD_ADDRESS,
"Unknown address family %s", family);
return -1;
}
hints.ai_protocol = IPPROTO_TCP;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_ADDRCONFIG | AI_PASSIVE;
redo_lookup_with_port:
ai = NULL;
if ((res = getaddrinfo(host, port, &hints, &ai)) != 0 || !ai)
{
dbus_set_error (error,
_dbus_error_from_errno (errno),
"Failed to lookup host/port: \"%s:%s\": %s (%d)",
host ? host : "*", port, gai_strerror(res), res);
goto failed;
}
tmp = ai;
while (tmp)
{
int fd = -1, tcp_nodelay_on;
DBusSocket *newlisten_fd;
if (!_dbus_open_socket (&fd, tmp->ai_family, SOCK_STREAM, 0, error))
{
_DBUS_ASSERT_ERROR_IS_SET(error);
goto failed;
}
_DBUS_ASSERT_ERROR_IS_CLEAR(error);
reuseaddr = 1;
if (setsockopt (fd, SOL_SOCKET, SO_REUSEADDR, &reuseaddr, sizeof(reuseaddr))==-1)
{
_dbus_warn ("Failed to set socket option \"%s:%s\": %s",
host ? host : "*", port, _dbus_strerror (errno));
}
/* Nagle's algorithm imposes a huge delay on the initial messages
going over TCP. */
tcp_nodelay_on = 1;
if (setsockopt (fd, IPPROTO_TCP, TCP_NODELAY, &tcp_nodelay_on, sizeof (tcp_nodelay_on)) == -1)
{
_dbus_warn ("Failed to set TCP_NODELAY socket option \"%s:%s\": %s",
host ? host : "*", port, _dbus_strerror (errno));
}
if (bind (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) < 0)
{
saved_errno = errno;
_dbus_close(fd, NULL);
if (saved_errno == EADDRINUSE)
{
/* Depending on kernel policy, binding to an IPv6 address
might implicitly bind to a corresponding IPv4
address or vice versa, resulting in EADDRINUSE for the
other one (e.g. bindv6only=0 on Linux).
Also, after we "goto redo_lookup_with_port" after binding
a port on one of the possible addresses, we will
try to bind that same port on every address, including the
same address again for a second time; that one will
also fail with EADDRINUSE.
For both those reasons, ignore EADDRINUSE here */
tmp = tmp->ai_next;
continue;
}
dbus_set_error (error, _dbus_error_from_errno (saved_errno),
"Failed to bind socket \"%s:%s\": %s",
host ? host : "*", port, _dbus_strerror (saved_errno));
goto failed;
}
if (listen (fd, 30 /* backlog */) < 0)
{
saved_errno = errno;
_dbus_close (fd, NULL);
dbus_set_error (error, _dbus_error_from_errno (saved_errno),
"Failed to listen on socket \"%s:%s\": %s",
host ? host : "*", port, _dbus_strerror (saved_errno));
goto failed;
}
newlisten_fd = dbus_realloc(listen_fd, sizeof(DBusSocket)*(nlisten_fd+1));
if (!newlisten_fd)
{
saved_errno = errno;
_dbus_close (fd, NULL);
dbus_set_error (error, _dbus_error_from_errno (saved_errno),
"Failed to allocate file handle array: %s",
_dbus_strerror (saved_errno));
goto failed;
}
listen_fd = newlisten_fd;
listen_fd[nlisten_fd].fd = fd;
nlisten_fd++;
if (!_dbus_string_get_length(retport))
{
/* If the user didn't specify a port, or used 0, then
the kernel chooses a port. After the first address
is bound to, we need to force all remaining addresses
to use the same port */
if (!port || !strcmp(port, "0"))
{
int result;
struct sockaddr_storage addr;
socklen_t addrlen;
char portbuf[50];
addrlen = sizeof(addr);
result = getsockname(fd, (struct sockaddr*) &addr, &addrlen);
if (result == -1 ||
(res = getnameinfo ((struct sockaddr*)&addr, addrlen, NULL, 0,
portbuf, sizeof(portbuf),
NI_NUMERICHOST | NI_NUMERICSERV)) != 0)
{
dbus_set_error (error, _dbus_error_from_errno (errno),
"Failed to resolve port \"%s:%s\": %s (%s)",
host ? host : "*", port, gai_strerror(res), res);
goto failed;
}
if (!_dbus_string_append(retport, portbuf))
{
dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
goto failed;
}
/* Release current address list & redo lookup */
port = _dbus_string_get_const_data(retport);
freeaddrinfo(ai);
goto redo_lookup_with_port;
}
else
{
if (!_dbus_string_append(retport, port))
{
dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
goto failed;
}
}
}
tmp = tmp->ai_next;
}
freeaddrinfo(ai);
ai = NULL;
if (!nlisten_fd)
{
errno = EADDRINUSE;
dbus_set_error (error, _dbus_error_from_errno (errno),
"Failed to bind socket \"%s:%s\": %s",
host ? host : "*", port, _dbus_strerror (errno));
goto failed;
}
for (i = 0 ; i < nlisten_fd ; i++)
{
if (!_dbus_set_fd_nonblocking (listen_fd[i].fd, error))
{
goto failed;
}
}
*fds_p = listen_fd;
return nlisten_fd;
failed:
if (ai)
freeaddrinfo(ai);
for (i = 0 ; i < nlisten_fd ; i++)
_dbus_close(listen_fd[i].fd, NULL);
dbus_free(listen_fd);
return -1;
}
static dbus_bool_t
write_credentials_byte (int server_fd,
DBusError *error)
{
int bytes_written;
char buf[1] = { '\0' };
#if defined(HAVE_CMSGCRED)
union {
struct cmsghdr hdr;
char cred[CMSG_SPACE (sizeof (struct cmsgcred))];
} cmsg;
struct iovec iov;
struct msghdr msg;
iov.iov_base = buf;
iov.iov_len = 1;
_DBUS_ZERO(msg);
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
msg.msg_control = (caddr_t) &cmsg;
msg.msg_controllen = CMSG_SPACE (sizeof (struct cmsgcred));
_DBUS_ZERO(cmsg);
cmsg.hdr.cmsg_len = CMSG_LEN (sizeof (struct cmsgcred));
cmsg.hdr.cmsg_level = SOL_SOCKET;
cmsg.hdr.cmsg_type = SCM_CREDS;
#endif
_DBUS_ASSERT_ERROR_IS_CLEAR (error);
again:
#if defined(HAVE_CMSGCRED)
bytes_written = sendmsg (server_fd, &msg, 0
#if HAVE_DECL_MSG_NOSIGNAL
|MSG_NOSIGNAL
#endif
);
/* If we HAVE_CMSGCRED, the OS still might not let us sendmsg()
* with a SOL_SOCKET/SCM_CREDS message - for instance, FreeBSD
* only allows that on AF_UNIX. Try just doing a send() instead. */
if (bytes_written < 0 && errno == EINVAL)
#endif
{
bytes_written = send (server_fd, buf, 1, 0
#if HAVE_DECL_MSG_NOSIGNAL
|MSG_NOSIGNAL
#endif
);
}
if (bytes_written < 0 && errno == EINTR)
goto again;
if (bytes_written < 0)
{
dbus_set_error (error, _dbus_error_from_errno (errno),
"Failed to write credentials byte: %s",
_dbus_strerror (errno));
return FALSE;
}
else if (bytes_written == 0)
{
dbus_set_error (error, DBUS_ERROR_IO_ERROR,
"wrote zero bytes writing credentials byte");
return FALSE;
}
else
{
_dbus_assert (bytes_written == 1);
_dbus_verbose ("wrote credentials byte\n");
return TRUE;
}
}
/* return FALSE on OOM, TRUE otherwise, even if no credentials were found */
static dbus_bool_t
add_linux_security_label_to_credentials (int client_fd,
DBusCredentials *credentials)
{
#if defined(__linux__) && defined(SO_PEERSEC)
DBusString buf;
socklen_t len = 1024;
dbus_bool_t oom = FALSE;
if (!_dbus_string_init_preallocated (&buf, len) ||
!_dbus_string_set_length (&buf, len))
return FALSE;
while (getsockopt (client_fd, SOL_SOCKET, SO_PEERSEC,
_dbus_string_get_data (&buf), &len) < 0)
{
int e = errno;
_dbus_verbose ("getsockopt failed with %s, len now %lu\n",
_dbus_strerror (e), (unsigned long) len);
if (e != ERANGE || len <= _dbus_string_get_length_uint (&buf))
{
_dbus_verbose ("Failed to getsockopt(SO_PEERSEC): %s\n",
_dbus_strerror (e));
goto out;
}
/* If not enough space, len is updated to be enough.
* Try again with a large enough buffer. */
if (!_dbus_string_set_length (&buf, len))
{
oom = TRUE;
goto out;
}
_dbus_verbose ("will try again with %lu\n", (unsigned long) len);
}
if (len <= 0)
{
_dbus_verbose ("getsockopt(SO_PEERSEC) yielded <= 0 bytes: %lu\n",
(unsigned long) len);
goto out;
}
if (len > _dbus_string_get_length_uint (&buf))
{
_dbus_verbose ("%lu > %u", (unsigned long) len,
_dbus_string_get_length_uint (&buf));
_dbus_assert_not_reached ("getsockopt(SO_PEERSEC) overflowed");
}
if (_dbus_string_get_byte (&buf, len - 1) == 0)
{
/* the kernel included the trailing \0 in its count,
* but DBusString always has an extra \0 after the data anyway */
_dbus_verbose ("subtracting trailing \\0\n");
len--;
}
if (!_dbus_string_set_length (&buf, len))
{
_dbus_assert_not_reached ("shortening string should not lead to OOM");
oom = TRUE;
goto out;
}
if (strlen (_dbus_string_get_const_data (&buf)) != len)
{
/* LSM people on the linux-security-module@ mailing list say this
* should never happen: the label should be a bytestring with
* an optional trailing \0 */
_dbus_verbose ("security label from kernel had an embedded \\0, "
"ignoring it\n");
goto out;
}
_dbus_verbose ("getsockopt(SO_PEERSEC): %lu bytes excluding \\0: %s\n",
(unsigned long) len,
_dbus_string_get_const_data (&buf));
if (!_dbus_credentials_add_linux_security_label (credentials,
_dbus_string_get_const_data (&buf)))
{
oom = TRUE;
goto out;
}
out:
_dbus_string_free (&buf);
return !oom;
#else
/* no error */
return TRUE;
#endif
}
/**
* Reads a single byte which must be nul (an error occurs otherwise),
* and reads unix credentials if available. Clears the credentials
* object, then adds pid/uid if available, so any previous credentials
* stored in the object are lost.
*
* DBusServer makes the security assumption that the credentials
* returned by this method are the credentials that were active
* at the time the socket was opened. Do not add APIs to this
* method that would break that assumption.
*
* In particular, it is incorrect to use any API of the form
* "get the process ID at the other end of the connection, then
* determine its uid, gid, or other credentials from the pid"
* (e.g. looking in /proc on Linux). If we did that, we would
* be vulnerable to several attacks. A malicious process could
* queue up the rest of the authentication handshake and a malicious
* message that it should not be allowed to send, then race with
* the DBusServer to exec() a more privileged (e.g. setuid) binary that
* would have been allowed to send that message; or it could exit,
* and arrange for enough setuid processes to be started that its
* pid would be recycled for one of those processes with high
* probability; or it could fd-pass the connection to a more
* privileged process.
*
* Return value indicates whether a byte was read, not whether
* we got valid credentials. On some systems, such as Linux,
* reading/writing the byte isn't actually required, but we do it
* anyway just to avoid multiple codepaths.
*
* Fails if no byte is available, so you must select() first.
*
* The point of the byte is that on some systems we have to
* use sendmsg()/recvmsg() to transmit credentials.
*
* @param client_fd the client file descriptor
* @param credentials object to add client credentials to
* @param error location to store error code
* @returns #TRUE on success
*/
dbus_bool_t
_dbus_read_credentials_socket (DBusSocket client_fd,
DBusCredentials *credentials,
DBusError *error)
{
struct msghdr msg;
struct iovec iov;
char buf;
dbus_uid_t uid_read;
dbus_pid_t pid_read;
int bytes_read;
#ifdef HAVE_CMSGCRED
union {
struct cmsghdr hdr;
char cred[CMSG_SPACE (sizeof (struct cmsgcred))];
} cmsg;
#endif
/* The POSIX spec certainly doesn't promise this, but
* we need these assertions to fail as soon as we're wrong about
* it so we can do the porting fixups
*/
_DBUS_STATIC_ASSERT (sizeof (pid_t) <= sizeof (dbus_pid_t));
_DBUS_STATIC_ASSERT (sizeof (uid_t) <= sizeof (dbus_uid_t));
_DBUS_STATIC_ASSERT (sizeof (gid_t) <= sizeof (dbus_gid_t));
uid_read = DBUS_UID_UNSET;
pid_read = DBUS_PID_UNSET;
_DBUS_ASSERT_ERROR_IS_CLEAR (error);
_dbus_credentials_clear (credentials);
iov.iov_base = &buf;
iov.iov_len = 1;
_DBUS_ZERO(msg);
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
#if defined(HAVE_CMSGCRED)
_DBUS_ZERO(cmsg);
msg.msg_control = (caddr_t) &cmsg;
msg.msg_controllen = CMSG_SPACE (sizeof (struct cmsgcred));
#endif
again:
bytes_read = recvmsg (client_fd.fd, &msg, 0);
if (bytes_read < 0)
{
if (errno == EINTR)
goto again;
/* EAGAIN or EWOULDBLOCK would be unexpected here since we would
* normally only call read_credentials if the socket was ready
* for reading
*/
dbus_set_error (error, _dbus_error_from_errno (errno),
"Failed to read credentials byte: %s",
_dbus_strerror (errno));
return FALSE;
}
else if (bytes_read == 0)
{
/* this should not happen unless we are using recvmsg wrong,
* so is essentially here for paranoia
*/
dbus_set_error (error, DBUS_ERROR_FAILED,
"Failed to read credentials byte (zero-length read)");
return FALSE;
}
else if (buf != '\0')
{
dbus_set_error (error, DBUS_ERROR_FAILED,
"Credentials byte was not nul");
return FALSE;
}
_dbus_verbose ("read credentials byte\n");
{
#ifdef SO_PEERCRED
/* Supported by at least Linux and OpenBSD, with minor differences.
*
* This mechanism passes the process ID through and does not require
* the peer's cooperation, so we prefer it over all others. Notably,
* Linux also supports SCM_CREDENTIALS, which is similar to FreeBSD
* SCM_CREDS; it's implemented in GIO, but we don't use it in dbus at all,
* because this is much less fragile.
*/
#ifdef __OpenBSD__
struct sockpeercred cr;
#else
struct ucred cr;
#endif
socklen_t cr_len = sizeof (cr);
if (getsockopt (client_fd.fd, SOL_SOCKET, SO_PEERCRED, &cr, &cr_len) != 0)
{
_dbus_verbose ("Failed to getsockopt(SO_PEERCRED): %s\n",
_dbus_strerror (errno));
}
else if (cr_len != sizeof (cr))
{
_dbus_verbose ("Failed to getsockopt(SO_PEERCRED), returned %d bytes, expected %d\n",
cr_len, (int) sizeof (cr));
}
else
{
pid_read = cr.pid;
uid_read = cr.uid;
}
#elif defined(HAVE_UNPCBID) && defined(LOCAL_PEEREID)
/* Another variant of the above - used on NetBSD
*/
struct unpcbid cr;
socklen_t cr_len = sizeof (cr);
if (getsockopt (client_fd.fd, 0, LOCAL_PEEREID, &cr, &cr_len) != 0)
{
_dbus_verbose ("Failed to getsockopt(LOCAL_PEEREID): %s\n",
_dbus_strerror (errno));
}
else if (cr_len != sizeof (cr))
{
_dbus_verbose ("Failed to getsockopt(LOCAL_PEEREID), returned %d bytes, expected %d\n",
cr_len, (int) sizeof (cr));
}
else
{
pid_read = cr.unp_pid;
uid_read = cr.unp_euid;
}
#elif defined(HAVE_CMSGCRED)
/* We only check for HAVE_CMSGCRED, but we're really assuming that the
* presence of that struct implies SCM_CREDS. Supported by at least
* FreeBSD and DragonflyBSD.
*
* This mechanism requires the peer to help us (it has to send us a
* SCM_CREDS message) but it does pass the process ID through,
* which makes it better than getpeereid().
*/
struct cmsgcred *cred;
struct cmsghdr *cmsgp;
for (cmsgp = CMSG_FIRSTHDR (&msg);
cmsgp != NULL;
cmsgp = CMSG_NXTHDR (&msg, cmsgp))
{
if (cmsgp->cmsg_type == SCM_CREDS &&
cmsgp->cmsg_level == SOL_SOCKET &&
cmsgp->cmsg_len >= CMSG_LEN (sizeof (struct cmsgcred)))
{
cred = (struct cmsgcred *) CMSG_DATA (cmsgp);
pid_read = cred->cmcred_pid;
uid_read = cred->cmcred_euid;
break;
}
}
#elif defined(HAVE_GETPEERUCRED)
/* Supported in at least Solaris >= 10. It should probably be higher
* up this list, because it carries the pid and we use this code path
* for audit data. */
ucred_t * ucred = NULL;
if (getpeerucred (client_fd.fd, &ucred) == 0)
{
pid_read = ucred_getpid (ucred);
uid_read = ucred_geteuid (ucred);
#ifdef HAVE_ADT
/* generate audit session data based on socket ucred */
adt_session_data_t *adth = NULL;
adt_export_data_t *data = NULL;
size_t size = 0;
if (adt_start_session (&adth, NULL, 0) || (adth == NULL))
{
_dbus_verbose ("Failed to adt_start_session(): %s\n", _dbus_strerror (errno));
}
else
{
if (adt_set_from_ucred (adth, ucred, ADT_NEW))
{
_dbus_verbose ("Failed to adt_set_from_ucred(): %s\n", _dbus_strerror (errno));
}
else
{
size = adt_export_session_data (adth, &data);
if (size <= 0)
{
_dbus_verbose ("Failed to adt_export_session_data(): %s\n", _dbus_strerror (errno));
}
else
{
_dbus_credentials_add_adt_audit_data (credentials, data, size);
free (data);
}
}
(void) adt_end_session (adth);
}
#endif /* HAVE_ADT */
}
else
{
_dbus_verbose ("Failed to getpeerucred() credentials: %s\n", _dbus_strerror (errno));
}
if (ucred != NULL)
ucred_free (ucred);
/* ----------------------------------------------------------------
* When adding new mechanisms, please add them above this point
* if they support passing the process ID through, or below if not.
* ---------------------------------------------------------------- */
#elif defined(HAVE_GETPEEREID)
/* getpeereid() originates from D.J. Bernstein and is fairly
* widely-supported. According to a web search, it might be present in
* any/all of:
*
* - AIX?
* - Blackberry?
* - Cygwin
* - FreeBSD 4.6+ (but we prefer SCM_CREDS: it carries the pid)
* - Mac OS X
* - Minix 3.1.8+
* - MirBSD?
* - NetBSD 5.0+ (but LOCAL_PEEREID would be better: it carries the pid)
* - OpenBSD 3.0+ (but we prefer SO_PEERCRED: it carries the pid)
* - QNX?
*/
uid_t euid;
gid_t egid;
if (getpeereid (client_fd.fd, &euid, &egid) == 0)
{
uid_read = euid;
}
else
{
_dbus_verbose ("Failed to getpeereid() credentials: %s\n", _dbus_strerror (errno));
}
#else /* no supported mechanism */
#warning Socket credentials not supported on this Unix OS
#warning Please tell https://bugs.freedesktop.org/enter_bug.cgi?product=DBus
/* Please add other operating systems known to support at least one of
* the mechanisms above to this list, keeping alphabetical order.
* Everything not in this list is best-effort.
*/
#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || \
defined(__linux__) || \
defined(__OpenBSD__) || \
defined(__NetBSD__)
# error Credentials passing not working on this OS is a regression!
#endif
_dbus_verbose ("Socket credentials not supported on this OS\n");
#endif
}
_dbus_verbose ("Credentials:"
" pid "DBUS_PID_FORMAT
" uid "DBUS_UID_FORMAT
"\n",
pid_read,
uid_read);
if (pid_read != DBUS_PID_UNSET)
{
if (!_dbus_credentials_add_pid (credentials, pid_read))
{
_DBUS_SET_OOM (error);
return FALSE;
}
}
if (uid_read != DBUS_UID_UNSET)
{
if (!_dbus_credentials_add_unix_uid (credentials, uid_read))
{
_DBUS_SET_OOM (error);
return FALSE;
}
}
if (!add_linux_security_label_to_credentials (client_fd.fd, credentials))
{
_DBUS_SET_OOM (error);
return FALSE;
}
return TRUE;
}
/**
* Sends a single nul byte with our UNIX credentials as ancillary
* data. Returns #TRUE if the data was successfully written. On
* systems that don't support sending credentials, just writes a byte,
* doesn't send any credentials. On some systems, such as Linux,
* reading/writing the byte isn't actually required, but we do it
* anyway just to avoid multiple codepaths.
*
* Fails if no byte can be written, so you must select() first.
*
* The point of the byte is that on some systems we have to
* use sendmsg()/recvmsg() to transmit credentials.
*
* @param server_fd file descriptor for connection to server
* @param error return location for error code
* @returns #TRUE if the byte was sent
*/
dbus_bool_t
_dbus_send_credentials_socket (DBusSocket server_fd,
DBusError *error)
{
_DBUS_ASSERT_ERROR_IS_CLEAR (error);
if (write_credentials_byte (server_fd.fd, error))
return TRUE;
else
return FALSE;
}
/**
* Accepts a connection on a listening socket.
* Handles EINTR for you.
*
* This will enable FD_CLOEXEC for the returned socket.
*
* @param listen_fd the listen file descriptor
* @returns the connection fd of the client, or -1 on error
*/
DBusSocket
_dbus_accept (DBusSocket listen_fd)
{
DBusSocket client_fd;
struct sockaddr addr;
socklen_t addrlen;
#ifdef HAVE_ACCEPT4
dbus_bool_t cloexec_done;
#endif
addrlen = sizeof (addr);
retry:
#ifdef HAVE_ACCEPT4
/*
* At compile-time, we assume that if accept4() is available in
* libc headers, SOCK_CLOEXEC is too. At runtime, it is still
* not necessarily true that either is supported by the running kernel.
*/
client_fd.fd = accept4 (listen_fd.fd, &addr, &addrlen, SOCK_CLOEXEC);
cloexec_done = client_fd.fd >= 0;
if (client_fd.fd < 0 && (errno == ENOSYS || errno == EINVAL))
#endif
{
client_fd.fd = accept (listen_fd.fd, &addr, &addrlen);
}
if (client_fd.fd < 0)
{
if (errno == EINTR)
goto retry;
}
_dbus_verbose ("client fd %d accepted\n", client_fd.fd);
#ifdef HAVE_ACCEPT4
if (!cloexec_done)
#endif
{
_dbus_fd_set_close_on_exec(client_fd.fd);
}
return client_fd;
}
/**
* Checks to make sure the given directory is
* private to the user
*
* @param dir the name of the directory
* @param error error return
* @returns #FALSE on failure
**/
dbus_bool_t
_dbus_check_dir_is_private_to_user (DBusString *dir, DBusError *error)
{
const char *directory;
struct stat sb;
_DBUS_ASSERT_ERROR_IS_CLEAR (error);
directory = _dbus_string_get_const_data (dir);
if (stat (directory, &sb) < 0)
{
dbus_set_error (error, _dbus_error_from_errno (errno),
"%s", _dbus_strerror (errno));
return FALSE;
}
if (sb.st_uid != geteuid ())
{
dbus_set_error (error, DBUS_ERROR_FAILED,
"%s directory is owned by user %lu, not %lu",
directory,
(unsigned long) sb.st_uid,
(unsigned long) geteuid ());
return FALSE;
}
if ((S_IROTH & sb.st_mode) || (S_IWOTH & sb.st_mode) ||
(S_IRGRP & sb.st_mode) || (S_IWGRP & sb.st_mode))
{
dbus_set_error (error, DBUS_ERROR_FAILED,
"%s directory is not private to the user", directory);
return FALSE;
}
return TRUE;
}
static dbus_bool_t
fill_user_info_from_passwd (struct passwd *p,
DBusUserInfo *info,
DBusError *error)
{
_dbus_assert (p->pw_name != NULL);
_dbus_assert (p->pw_dir != NULL);
info->uid = p->pw_uid;
info->primary_gid = p->pw_gid;
info->username = _dbus_strdup (p->pw_name);
info->homedir = _dbus_strdup (p->pw_dir);
if (info->username == NULL ||
info->homedir == NULL)
{
dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
return FALSE;
}
return TRUE;
}
static dbus_bool_t
fill_user_info (DBusUserInfo *info,
dbus_uid_t uid,
const DBusString *username,
DBusError *error)
{
const char *username_c;
/* exactly one of username/uid provided */
_dbus_assert (username != NULL || uid != DBUS_UID_UNSET);
_dbus_assert (username == NULL || uid == DBUS_UID_UNSET);
info->uid = DBUS_UID_UNSET;
info->primary_gid = DBUS_GID_UNSET;
info->group_ids = NULL;
info->n_group_ids = 0;
info->username = NULL;
info->homedir = NULL;
if (username != NULL)
username_c = _dbus_string_get_const_data (username);
else
username_c = NULL;
/* For now assuming that the getpwnam() and getpwuid() flavors
* are always symmetrical, if not we have to add more configure
* checks
*/
#if defined (HAVE_POSIX_GETPWNAM_R) || defined (HAVE_NONPOSIX_GETPWNAM_R)
{
struct passwd *p;
int result;
size_t buflen;
char *buf;
struct passwd p_str;
/* retrieve maximum needed size for buf */
buflen = sysconf (_SC_GETPW_R_SIZE_MAX);
/* sysconf actually returns a long, but everything else expects size_t,
* so just recast here.
* https://bugs.freedesktop.org/show_bug.cgi?id=17061
*/
if ((long) buflen <= 0)
buflen = 1024;
result = -1;
while (1)
{
buf = dbus_malloc (buflen);
if (buf == NULL)
{
dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
return FALSE;
}
p = NULL;
#ifdef HAVE_POSIX_GETPWNAM_R
if (uid != DBUS_UID_UNSET)
result = getpwuid_r (uid, &p_str, buf, buflen,
&p);
else
result = getpwnam_r (username_c, &p_str, buf, buflen,
&p);
#else
if (uid != DBUS_UID_UNSET)
p = getpwuid_r (uid, &p_str, buf, buflen);
else
p = getpwnam_r (username_c, &p_str, buf, buflen);
result = 0;
#endif /* !HAVE_POSIX_GETPWNAM_R */
//Try a bigger buffer if ERANGE was returned
if (result == ERANGE && buflen < 512 * 1024)
{
dbus_free (buf);
buflen *= 2;
}
else
{
break;
}
}
if (result == 0 && p == &p_str)
{
if (!fill_user_info_from_passwd (p, info, error))
{
dbus_free (buf);
return FALSE;
}
dbus_free (buf);
}
else
{
dbus_set_error (error, _dbus_error_from_errno (errno),
"User \"%s\" unknown or no memory to allocate password entry\n",
username_c ? username_c : "???");
_dbus_verbose ("User %s unknown\n", username_c ? username_c : "???");
dbus_free (buf);
return FALSE;
}
}
#else /* ! HAVE_GETPWNAM_R */
{
/* I guess we're screwed on thread safety here */
struct passwd *p;
if (uid != DBUS_UID_UNSET)
p = getpwuid (uid);
else
p = getpwnam (username_c);
if (p != NULL)
{
if (!fill_user_info_from_passwd (p, info, error))
{
return FALSE;
}
}
else
{
dbus_set_error (error, _dbus_error_from_errno (errno),
"User \"%s\" unknown or no memory to allocate password entry\n",
username_c ? username_c : "???");
_dbus_verbose ("User %s unknown\n", username_c ? username_c : "???");
return FALSE;
}
}
#endif /* ! HAVE_GETPWNAM_R */
/* Fill this in so we can use it to get groups */
username_c = info->username;
#ifdef HAVE_GETGROUPLIST
{
gid_t *buf;
int buf_count;
int i;
int initial_buf_count;
initial_buf_count = 17;
buf_count = initial_buf_count;
buf = dbus_new (gid_t, buf_count);
if (buf == NULL)
{
dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
goto failed;
}
if (getgrouplist (username_c,
info->primary_gid,
buf, &buf_count) < 0)
{
gid_t *new;
/* Presumed cause of negative return code: buf has insufficient
entries to hold the entire group list. The Linux behavior in this
case is to pass back the actual number of groups in buf_count, but
on Mac OS X 10.5, buf_count is unhelpfully left alone.
So as a hack, try to help out a bit by guessing a larger
number of groups, within reason.. might still fail, of course,
but we can at least print a more informative message. I looked up
the "right way" to do this by downloading Apple's own source code
for the "id" command, and it turns out that they use an
undocumented library function getgrouplist_2 (!) which is not
declared in any header in /usr/include (!!). That did not seem
like the way to go here.
*/
if (buf_count == initial_buf_count)
{
buf_count *= 16; /* Retry with an arbitrarily scaled-up array */
}
new = dbus_realloc (buf, buf_count * sizeof (buf[0]));
if (new == NULL)
{
dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
dbus_free (buf);
goto failed;
}
buf = new;
errno = 0;
if (getgrouplist (username_c, info->primary_gid, buf, &buf_count) < 0)
{
if (errno == 0)
{
_dbus_warn ("It appears that username \"%s\" is in more than %d groups.\nProceeding with just the first %d groups.",
username_c, buf_count, buf_count);
}
else
{
dbus_set_error (error,
_dbus_error_from_errno (errno),
"Failed to get groups for username \"%s\" primary GID "
DBUS_GID_FORMAT ": %s\n",
username_c, info->primary_gid,
_dbus_strerror (errno));
dbus_free (buf);
goto failed;
}
}
}
info->group_ids = dbus_new (dbus_gid_t, buf_count);
if (info->group_ids == NULL)
{
dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
dbus_free (buf);
goto failed;
}
for (i = 0; i < buf_count; ++i)
info->group_ids[i] = buf[i];
info->n_group_ids = buf_count;
dbus_free (buf);
}
#else /* HAVE_GETGROUPLIST */
{
/* We just get the one group ID */
info->group_ids = dbus_new (dbus_gid_t, 1);
if (info->group_ids == NULL)
{
dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
goto failed;
}
info->n_group_ids = 1;
(info->group_ids)[0] = info->primary_gid;
}
#endif /* HAVE_GETGROUPLIST */
_DBUS_ASSERT_ERROR_IS_CLEAR (error);
return TRUE;
failed:
_DBUS_ASSERT_ERROR_IS_SET (error);
return FALSE;
}
/**
* Gets user info for the given username.
*
* @param info user info object to initialize
* @param username the username
* @param error error return
* @returns #TRUE on success
*/
dbus_bool_t
_dbus_user_info_fill (DBusUserInfo *info,
const DBusString *username,
DBusError *error)
{
return fill_user_info (info, DBUS_UID_UNSET,
username, error);
}
/**
* Gets user info for the given user ID.
*
* @param info user info object to initialize
* @param uid the user ID
* @param error error return
* @returns #TRUE on success
*/
dbus_bool_t
_dbus_user_info_fill_uid (DBusUserInfo *info,
dbus_uid_t uid,
DBusError *error)
{
return fill_user_info (info, uid,
NULL, error);
}
/**
* Adds the credentials of the current process to the
* passed-in credentials object.
*
* @param credentials credentials to add to
* @returns #FALSE if no memory; does not properly roll back on failure, so only some credentials may have been added
*/
dbus_bool_t
_dbus_credentials_add_from_current_process (DBusCredentials *credentials)
{
/* The POSIX spec certainly doesn't promise this, but
* we need these assertions to fail as soon as we're wrong about
* it so we can do the porting fixups
*/
_DBUS_STATIC_ASSERT (sizeof (pid_t) <= sizeof (dbus_pid_t));
_DBUS_STATIC_ASSERT (sizeof (uid_t) <= sizeof (dbus_uid_t));
_DBUS_STATIC_ASSERT (sizeof (gid_t) <= sizeof (dbus_gid_t));
if (!_dbus_credentials_add_pid(credentials, _dbus_getpid()))
return FALSE;
if (!_dbus_credentials_add_unix_uid(credentials, _dbus_geteuid()))
return FALSE;
return TRUE;
}
/**
* Append to the string the identity we would like to have when we
* authenticate, on UNIX this is the current process UID and on
* Windows something else, probably a Windows SID string. No escaping
* is required, that is done in dbus-auth.c. The username here
* need not be anything human-readable, it can be the machine-readable
* form i.e. a user id.
*
* @param str the string to append to
* @returns #FALSE on no memory
*/
dbus_bool_t
_dbus_append_user_from_current_process (DBusString *str)
{
return _dbus_string_append_uint (str,
_dbus_geteuid ());
}
/**
* Gets our process ID
* @returns process ID
*/
dbus_pid_t
_dbus_getpid (void)
{
return getpid ();
}
/** Gets our UID
* @returns process UID
*/
dbus_uid_t
_dbus_getuid (void)
{
return getuid ();
}
/** Gets our effective UID
* @returns process effective UID
*/
dbus_uid_t
_dbus_geteuid (void)
{
return geteuid ();
}
/**
* The only reason this is separate from _dbus_getpid() is to allow it
* on Windows for logging but not for other purposes.
*
* @returns process ID to put in log messages
*/
unsigned long
_dbus_pid_for_log (void)
{
return getpid ();
}
/**
* Gets a UID from a UID string.
*
* @param uid_str the UID in string form
* @param uid UID to fill in
* @returns #TRUE if successfully filled in UID
*/
dbus_bool_t
_dbus_parse_uid (const DBusString *uid_str,
dbus_uid_t *uid)
{
int end;
long val;
if (_dbus_string_get_length (uid_str) == 0)
{
_dbus_verbose ("UID string was zero length\n");
return FALSE;
}
val = -1;
end = 0;
if (!_dbus_string_parse_int (uid_str, 0, &val,
&end))
{
_dbus_verbose ("could not parse string as a UID\n");
return FALSE;
}
if (end != _dbus_string_get_length (uid_str))
{
_dbus_verbose ("string contained trailing stuff after UID\n");
return FALSE;
}
*uid = val;
return TRUE;
}
#if !DBUS_USE_SYNC
/* To be thread-safe by default on platforms that don't necessarily have
* atomic operations (notably Debian armel, which is armv4t), we must
* use a mutex that can be initialized statically, like this.
* GLib >= 2.32 uses a similar system.
*/
static pthread_mutex_t atomic_mutex = PTHREAD_MUTEX_INITIALIZER;
#endif
/**
* Atomically increments an integer
*
* @param atomic pointer to the integer to increment
* @returns the value before incrementing
*/
dbus_int32_t
_dbus_atomic_inc (DBusAtomic *atomic)
{
#if DBUS_USE_SYNC
return __sync_add_and_fetch(&atomic->value, 1)-1;
#else
dbus_int32_t res;
pthread_mutex_lock (&atomic_mutex);
res = atomic->value;
atomic->value += 1;
pthread_mutex_unlock (&atomic_mutex);
return res;
#endif
}
/**
* Atomically decrement an integer
*
* @param atomic pointer to the integer to decrement
* @returns the value before decrementing
*/
dbus_int32_t
_dbus_atomic_dec (DBusAtomic *atomic)
{
#if DBUS_USE_SYNC
return __sync_sub_and_fetch(&atomic->value, 1)+1;
#else
dbus_int32_t res;
pthread_mutex_lock (&atomic_mutex);
res = atomic->value;
atomic->value -= 1;
pthread_mutex_unlock (&atomic_mutex);
return res;
#endif
}
/**
* Atomically get the value of an integer. It may change at any time
* thereafter, so this is mostly only useful for assertions.
*
* @param atomic pointer to the integer to get
* @returns the value at this moment
*/
dbus_int32_t
_dbus_atomic_get (DBusAtomic *atomic)
{
#if DBUS_USE_SYNC
__sync_synchronize ();
return atomic->value;
#else
dbus_int32_t res;
pthread_mutex_lock (&atomic_mutex);
res = atomic->value;
pthread_mutex_unlock (&atomic_mutex);
return res;
#endif
}
/**
* Wrapper for poll().
*
* @param fds the file descriptors to poll
* @param n_fds number of descriptors in the array
* @param timeout_milliseconds timeout or -1 for infinite
* @returns numbers of fds with revents, or <0 on error
*/
int
_dbus_poll (DBusPollFD *fds,
int n_fds,
int timeout_milliseconds)
{
#if defined(HAVE_POLL) && !defined(BROKEN_POLL)
/* DBusPollFD is a struct pollfd in this code path, so we can just poll() */
if (timeout_milliseconds < -1)
{
timeout_milliseconds = -1;
}
return poll (fds,
n_fds,
timeout_milliseconds);
#else /* ! HAVE_POLL */
/* Emulate poll() in terms of select() */
fd_set read_set, write_set, err_set;
int max_fd = 0;
int i;
struct timeval tv;
int ready;
FD_ZERO (&read_set);
FD_ZERO (&write_set);
FD_ZERO (&err_set);
for (i = 0; i < n_fds; i++)
{
DBusPollFD *fdp = &fds[i];
if (fdp->events & _DBUS_POLLIN)
FD_SET (fdp->fd, &read_set);
if (fdp->events & _DBUS_POLLOUT)
FD_SET (fdp->fd, &write_set);
FD_SET (fdp->fd, &err_set);
max_fd = MAX (max_fd, fdp->fd);
}
tv.tv_sec = timeout_milliseconds / 1000;
tv.tv_usec = (timeout_milliseconds % 1000) * 1000;
ready = select (max_fd + 1, &read_set, &write_set, &err_set,
timeout_milliseconds < 0 ? NULL : &tv);
if (ready > 0)
{
for (i = 0; i < n_fds; i++)
{
DBusPollFD *fdp = &fds[i];
fdp->revents = 0;
if (FD_ISSET (fdp->fd, &read_set))
fdp->revents |= _DBUS_POLLIN;
if (FD_ISSET (fdp->fd, &write_set))
fdp->revents |= _DBUS_POLLOUT;
if (FD_ISSET (fdp->fd, &err_set))
fdp->revents |= _DBUS_POLLERR;
}
}
return ready;
#endif
}
/**
* Get current time, as in gettimeofday(). Use the monotonic clock if
* available, to avoid problems when the system time changes.
*
* @param tv_sec return location for number of seconds
* @param tv_usec return location for number of microseconds
*/
void
_dbus_get_monotonic_time (long *tv_sec,
long *tv_usec)
{
#ifdef HAVE_MONOTONIC_CLOCK
struct timespec ts;
clock_gettime (CLOCK_MONOTONIC, &ts);
if (tv_sec)
*tv_sec = ts.tv_sec;
if (tv_usec)
*tv_usec = ts.tv_nsec / 1000;
#else
struct timeval t;
gettimeofday (&t, NULL);
if (tv_sec)
*tv_sec = t.tv_sec;
if (tv_usec)
*tv_usec = t.tv_usec;
#endif
}
/**
* Get current time, as in gettimeofday(). Never uses the monotonic
* clock.
*
* @param tv_sec return location for number of seconds
* @param tv_usec return location for number of microseconds
*/
void
_dbus_get_real_time (long *tv_sec,
long *tv_usec)
{
struct timeval t;
gettimeofday (&t, NULL);
if (tv_sec)
*tv_sec = t.tv_sec;
if (tv_usec)
*tv_usec = t.tv_usec;
}
/**
* Creates a directory; succeeds if the directory
* is created or already existed.
*
* @param filename directory filename
* @param error initialized error object
* @returns #TRUE on success
*/
dbus_bool_t
_dbus_create_directory (const DBusString *filename,
DBusError *error)
{
const char *filename_c;
_DBUS_ASSERT_ERROR_IS_CLEAR (error);
filename_c = _dbus_string_get_const_data (filename);
if (mkdir (filename_c, 0700) < 0)
{
if (errno == EEXIST)
return TRUE;
dbus_set_error (error, DBUS_ERROR_FAILED,
"Failed to create directory %s: %s\n",
filename_c, _dbus_strerror (errno));
return FALSE;
}
else
return TRUE;
}
/**
* Appends the given filename to the given directory.
*
* @todo it might be cute to collapse multiple '/' such as "foo//"
* concat "//bar"
*
* @param dir the directory name
* @param next_component the filename
* @returns #TRUE on success
*/
dbus_bool_t
_dbus_concat_dir_and_file (DBusString *dir,
const DBusString *next_component)
{
dbus_bool_t dir_ends_in_slash;
dbus_bool_t file_starts_with_slash;
if (_dbus_string_get_length (dir) == 0 ||
_dbus_string_get_length (next_component) == 0)
return TRUE;
dir_ends_in_slash = '/' == _dbus_string_get_byte (dir,
_dbus_string_get_length (dir) - 1);
file_starts_with_slash = '/' == _dbus_string_get_byte (next_component, 0);
if (dir_ends_in_slash && file_starts_with_slash)
{
_dbus_string_shorten (dir, 1);
}
else if (!(dir_ends_in_slash || file_starts_with_slash))
{
if (!_dbus_string_append_byte (dir, '/'))
return FALSE;
}
return _dbus_string_copy (next_component, 0, dir,
_dbus_string_get_length (dir));
}
/** nanoseconds in a second */
#define NANOSECONDS_PER_SECOND 1000000000
/** microseconds in a second */
#define MICROSECONDS_PER_SECOND 1000000
/** milliseconds in a second */
#define MILLISECONDS_PER_SECOND 1000
/** nanoseconds in a millisecond */
#define NANOSECONDS_PER_MILLISECOND 1000000
/** microseconds in a millisecond */
#define MICROSECONDS_PER_MILLISECOND 1000
/**
* Sleeps the given number of milliseconds.
* @param milliseconds number of milliseconds
*/
void
_dbus_sleep_milliseconds (int milliseconds)
{
#ifdef HAVE_NANOSLEEP
struct timespec req;
struct timespec rem;
req.tv_sec = milliseconds / MILLISECONDS_PER_SECOND;
req.tv_nsec = (milliseconds % MILLISECONDS_PER_SECOND) * NANOSECONDS_PER_MILLISECOND;
rem.tv_sec = 0;
rem.tv_nsec = 0;
while (nanosleep (&req, &rem) < 0 && errno == EINTR)
req = rem;
#elif defined (HAVE_USLEEP)
usleep (milliseconds * MICROSECONDS_PER_MILLISECOND);
#else /* ! HAVE_USLEEP */
sleep (MAX (milliseconds / 1000, 1));
#endif
}
/**
* Generates the given number of securely random bytes,
* using the best mechanism we can come up with.
*
* @param str the string
* @param n_bytes the number of random bytes to append to string
* @param error location to store reason for failure
* @returns #TRUE on success, #FALSE on error
*/
dbus_bool_t
_dbus_generate_random_bytes (DBusString *str,
int n_bytes,
DBusError *error)
{
int old_len;
int fd;
int result;
old_len = _dbus_string_get_length (str);
fd = -1;
/* note, urandom on linux will fall back to pseudorandom */
fd = open ("/dev/urandom", O_RDONLY);
if (fd < 0)
{
dbus_set_error (error, _dbus_error_from_errno (errno),
"Could not open /dev/urandom: %s",
_dbus_strerror (errno));
return FALSE;
}
_dbus_verbose ("/dev/urandom fd %d opened\n", fd);
result = _dbus_read (fd, str, n_bytes);
if (result != n_bytes)
{
if (result < 0)
dbus_set_error (error, _dbus_error_from_errno (errno),
"Could not read /dev/urandom: %s",
_dbus_strerror (errno));
else
dbus_set_error (error, DBUS_ERROR_IO_ERROR,
"Short read from /dev/urandom");
_dbus_close (fd, NULL);
_dbus_string_set_length (str, old_len);
return FALSE;
}
_dbus_verbose ("Read %d bytes from /dev/urandom\n",
n_bytes);
_dbus_close (fd, NULL);
return TRUE;
}
/**
* Exit the process, returning the given value.
*
* @param code the exit code
*/
void
_dbus_exit (int code)
{
_exit (code);
}
/**
* A wrapper around strerror() because some platforms
* may be lame and not have strerror(). Also, never
* returns NULL.
*
* @param error_number errno.
* @returns error description.
*/
const char*
_dbus_strerror (int error_number)
{
const char *msg;
msg = strerror (error_number);
if (msg == NULL)
msg = "unknown";
return msg;
}
/**
* signal (SIGPIPE, SIG_IGN);
*/
void
_dbus_disable_sigpipe (void)
{
signal (SIGPIPE, SIG_IGN);
}
/**
* Sets the file descriptor to be close
* on exec. Should be called for all file
* descriptors in D-Bus code.
*
* @param fd the file descriptor
*/
void
_dbus_fd_set_close_on_exec (int fd)
{
int val;
val = fcntl (fd, F_GETFD, 0);
if (val < 0)
return;
val |= FD_CLOEXEC;
fcntl (fd, F_SETFD, val);
}
/**
* Closes a file descriptor.
*
* @param fd the file descriptor
* @param error error object
* @returns #FALSE if error set
*/
dbus_bool_t
_dbus_close (int fd,
DBusError *error)
{
_DBUS_ASSERT_ERROR_IS_CLEAR (error);
again:
if (close (fd) < 0)
{
if (errno == EINTR)
goto again;
dbus_set_error (error, _dbus_error_from_errno (errno),
"Could not close fd %d", fd);
return FALSE;
}
return TRUE;
}
/**
* Duplicates a file descriptor. Makes sure the fd returned is >= 3
* (i.e. avoids stdin/stdout/stderr). Sets O_CLOEXEC.
*
* @param fd the file descriptor to duplicate
* @param error address of error location.
* @returns duplicated file descriptor
* */
int
_dbus_dup(int fd,
DBusError *error)
{
int new_fd;
#ifdef F_DUPFD_CLOEXEC
dbus_bool_t cloexec_done;
new_fd = fcntl(fd, F_DUPFD_CLOEXEC, 3);
cloexec_done = new_fd >= 0;
if (new_fd < 0 && errno == EINVAL)
#endif
{
new_fd = fcntl(fd, F_DUPFD, 3);
}
if (new_fd < 0) {
dbus_set_error (error, _dbus_error_from_errno (errno),
"Could not duplicate fd %d", fd);
return -1;
}
#ifdef F_DUPFD_CLOEXEC
if (!cloexec_done)
#endif
{
_dbus_fd_set_close_on_exec(new_fd);
}
return new_fd;
}
/**
* Sets a file descriptor to be nonblocking.
*
* @param fd the file descriptor.
* @param error address of error location.
* @returns #TRUE on success.
*/
dbus_bool_t
_dbus_set_socket_nonblocking (DBusSocket fd,
DBusError *error)
{
return _dbus_set_fd_nonblocking (fd.fd, error);
}
static dbus_bool_t
_dbus_set_fd_nonblocking (int fd,
DBusError *error)
{
int val;
_DBUS_ASSERT_ERROR_IS_CLEAR (error);
val = fcntl (fd, F_GETFL, 0);
if (val < 0)
{
dbus_set_error (error, _dbus_error_from_errno (errno),
"Failed to get flags from file descriptor %d: %s",
fd, _dbus_strerror (errno));
_dbus_verbose ("Failed to get flags for fd %d: %s\n", fd,
_dbus_strerror (errno));
return FALSE;
}
if (fcntl (fd, F_SETFL, val | O_NONBLOCK) < 0)
{
dbus_set_error (error, _dbus_error_from_errno (errno),
"Failed to set nonblocking flag of file descriptor %d: %s",
fd, _dbus_strerror (errno));
_dbus_verbose ("Failed to set fd %d nonblocking: %s\n",
fd, _dbus_strerror (errno));
return FALSE;
}
return TRUE;
}
/**
* On GNU libc systems, print a crude backtrace to stderr. On other
* systems, print "no backtrace support" and block for possible gdb
* attachment if an appropriate environment variable is set.
*/
void
_dbus_print_backtrace (void)
{
#if defined (HAVE_BACKTRACE) && defined (DBUS_BUILT_R_DYNAMIC)
void *bt[500];
int bt_size;
int i;
char **syms;
bt_size = backtrace (bt, 500);
syms = backtrace_symbols (bt, bt_size);
i = 0;
while (i < bt_size)
{
/* don't use dbus_warn since it can _dbus_abort() */
fprintf (stderr, " %s\n", syms[i]);
++i;
}
fflush (stderr);
free (syms);
#elif defined (HAVE_BACKTRACE) && ! defined (DBUS_BUILT_R_DYNAMIC)
fprintf (stderr, " D-Bus not built with -rdynamic so unable to print a backtrace\n");
#else
fprintf (stderr, " D-Bus not compiled with backtrace support so unable to print a backtrace\n");
#endif
}
/**
* Creates pair of connect sockets (as in socketpair()).
* Sets both ends of the pair nonblocking.
*
* Marks both file descriptors as close-on-exec
*
* @param fd1 return location for one end
* @param fd2 return location for the other end
* @param blocking #TRUE if pair should be blocking
* @param error error return
* @returns #FALSE on failure (if error is set)
*/
dbus_bool_t
_dbus_socketpair (DBusSocket *fd1,
DBusSocket *fd2,
dbus_bool_t blocking,
DBusError *error)
{
#ifdef HAVE_SOCKETPAIR
int fds[2];
int retval;
#ifdef SOCK_CLOEXEC
dbus_bool_t cloexec_done;
retval = socketpair(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC, 0, fds);
cloexec_done = retval >= 0;
if (retval < 0 && (errno == EINVAL || errno == EPROTOTYPE))
#endif
{
retval = socketpair(AF_UNIX, SOCK_STREAM, 0, fds);
}
if (retval < 0)
{
dbus_set_error (error, _dbus_error_from_errno (errno),
"Could not create full-duplex pipe");
return FALSE;
}
_DBUS_ASSERT_ERROR_IS_CLEAR (error);
#ifdef SOCK_CLOEXEC
if (!cloexec_done)
#endif
{
_dbus_fd_set_close_on_exec (fds[0]);
_dbus_fd_set_close_on_exec (fds[1]);
}
if (!blocking &&
(!_dbus_set_fd_nonblocking (fds[0], NULL) ||
!_dbus_set_fd_nonblocking (fds[1], NULL)))
{
dbus_set_error (error, _dbus_error_from_errno (errno),
"Could not set full-duplex pipe nonblocking");
_dbus_close (fds[0], NULL);
_dbus_close (fds[1], NULL);
return FALSE;
}
fd1->fd = fds[0];
fd2->fd = fds[1];
_dbus_verbose ("full-duplex pipe %d <-> %d\n",
fd1->fd, fd2->fd);
return TRUE;
#else
_dbus_warn ("_dbus_socketpair() not implemented on this OS");
dbus_set_error (error, DBUS_ERROR_FAILED,
"_dbus_socketpair() not implemented on this OS");
return FALSE;
#endif
}
/**
* Measure the length of the given format string and arguments,
* not including the terminating nul.
*
* @param format a printf-style format string
* @param args arguments for the format string
* @returns length of the given format string and args, or -1 if no memory
*/
int
_dbus_printf_string_upper_bound (const char *format,
va_list args)
{
char static_buf[1024];
int bufsize = sizeof (static_buf);
int len;
va_list args_copy;
DBUS_VA_COPY (args_copy, args);
len = vsnprintf (static_buf, bufsize, format, args_copy);
va_end (args_copy);
/* If vsnprintf() returned non-negative, then either the string fits in
* static_buf, or this OS has the POSIX and C99 behaviour where vsnprintf
* returns the number of characters that were needed, or this OS returns the
* truncated length.
*
* We ignore the possibility that snprintf might just ignore the length and
* overrun the buffer (64-bit Solaris 7), because that's pathological.
* If your libc is really that bad, come back when you have a better one. */
if (len == bufsize)
{
/* This could be the truncated length (Tru64 and IRIX have this bug),
* or the real length could be coincidentally the same. Which is it?
* If vsnprintf returns the truncated length, we'll go to the slow
* path. */
DBUS_VA_COPY (args_copy, args);
if (vsnprintf (static_buf, 1, format, args_copy) == 1)
len = -1;
va_end (args_copy);
}
/* If vsnprintf() returned negative, we have to do more work.
* HP-UX returns negative. */
while (len < 0)
{
char *buf;
bufsize *= 2;
buf = dbus_malloc (bufsize);
if (buf == NULL)
return -1;
DBUS_VA_COPY (args_copy, args);
len = vsnprintf (buf, bufsize, format, args_copy);
va_end (args_copy);
dbus_free (buf);
/* If the reported length is exactly the buffer size, round up to the
* next size, in case vsnprintf has been returning the truncated
* length */
if (len == bufsize)
len = -1;
}
return len;
}
/**
* Gets the temporary files directory by inspecting the environment variables
* TMPDIR, TMP, and TEMP in that order. If none of those are set "/tmp" is returned
*
* @returns location of temp directory, or #NULL if no memory for locking
*/
const char*
_dbus_get_tmpdir(void)
{
/* Protected by _DBUS_LOCK_sysdeps */
static const char* tmpdir = NULL;
if (!_DBUS_LOCK (sysdeps))
return NULL;
if (tmpdir == NULL)
{
/* TMPDIR is what glibc uses, then
* glibc falls back to the P_tmpdir macro which
* just expands to "/tmp"
*/
if (tmpdir == NULL)
tmpdir = getenv("TMPDIR");
/* These two env variables are probably
* broken, but maybe some OS uses them?
*/
if (tmpdir == NULL)
tmpdir = getenv("TMP");
if (tmpdir == NULL)
tmpdir = getenv("TEMP");
/* And this is the sane fallback. */
if (tmpdir == NULL)
tmpdir = "/tmp";
}
_DBUS_UNLOCK (sysdeps);
_dbus_assert(tmpdir != NULL);
return tmpdir;
}
#if defined(DBUS_ENABLE_X11_AUTOLAUNCH) || defined(DBUS_ENABLE_LAUNCHD)
/**
* Execute a subprocess, returning up to 1024 bytes of output
* into @p result.
*
* If successful, returns #TRUE and appends the output to @p
* result. If a failure happens, returns #FALSE and
* sets an error in @p error.
*
* @note It's not an error if the subprocess terminates normally
* without writing any data to stdout. Verify the @p result length
* before and after this function call to cover this case.
*
* @param progname initial path to exec (may or may not be absolute)
* @param path_fallback if %TRUE, search PATH for executable
* @param argv NULL-terminated list of arguments
* @param result a DBusString where the output can be append
* @param error a DBusError to store the error in case of failure
* @returns #TRUE on success, #FALSE if an error happened
*/
static dbus_bool_t
_read_subprocess_line_argv (const char *progpath,
dbus_bool_t path_fallback,
const char * const *argv,
DBusString *result,
DBusError *error)
{
int result_pipe[2] = { -1, -1 };
int errors_pipe[2] = { -1, -1 };
pid_t pid;
int ret;
int status;
int orig_len;
dbus_bool_t retval;
sigset_t new_set, old_set;
_DBUS_ASSERT_ERROR_IS_CLEAR (error);
retval = FALSE;
/* We need to block any existing handlers for SIGCHLD temporarily; they
* will cause waitpid() below to fail.
* https://bugs.freedesktop.org/show_bug.cgi?id=21347
*/
sigemptyset (&new_set);
sigaddset (&new_set, SIGCHLD);
sigprocmask (SIG_BLOCK, &new_set, &old_set);
orig_len = _dbus_string_get_length (result);
#define READ_END 0
#define WRITE_END 1
if (pipe (result_pipe) < 0)
{
dbus_set_error (error, _dbus_error_from_errno (errno),
"Failed to create a pipe to call %s: %s",
progpath, _dbus_strerror (errno));
_dbus_verbose ("Failed to create a pipe to call %s: %s\n",
progpath, _dbus_strerror (errno));
goto out;
}
if (pipe (errors_pipe) < 0)
{
dbus_set_error (error, _dbus_error_from_errno (errno),
"Failed to create a pipe to call %s: %s",
progpath, _dbus_strerror (errno));
_dbus_verbose ("Failed to create a pipe to call %s: %s\n",
progpath, _dbus_strerror (errno));
goto out;
}
pid = fork ();
if (pid < 0)
{
dbus_set_error (error, _dbus_error_from_errno (errno),
"Failed to fork() to call %s: %s",
progpath, _dbus_strerror (errno));
_dbus_verbose ("Failed to fork() to call %s: %s\n",
progpath, _dbus_strerror (errno));
goto out;
}
if (pid == 0)
{
/* child process */
const char *error_str;
if (!_dbus_ensure_standard_fds (DBUS_FORCE_STDIN_NULL, &error_str))
{
int saved_errno = errno;
/* Try to write details into the pipe, but don't bother
* trying too hard (no retry loop). */
if (write (errors_pipe[WRITE_END], error_str, strlen (error_str)) < 0 ||
write (errors_pipe[WRITE_END], ": ", 2) < 0)
{
/* ignore, not much we can do */
}
error_str = _dbus_strerror (saved_errno);
if (write (errors_pipe[WRITE_END], error_str, strlen (error_str)) < 0)
{
/* ignore, not much we can do */
}
_exit (1);
}
/* set-up stdXXX */
close (result_pipe[READ_END]);
close (errors_pipe[READ_END]);
if (dup2 (result_pipe[WRITE_END], 1) == -1) /* setup stdout */
_exit (1);
if (dup2 (errors_pipe[WRITE_END], 2) == -1) /* setup stderr */
_exit (1);
_dbus_close_all ();
sigprocmask (SIG_SETMASK, &old_set, NULL);
/* If it looks fully-qualified, try execv first */
if (progpath[0] == '/')
{
execv (progpath, (char * const *) argv);
/* Ok, that failed. Now if path_fallback is given, let's
* try unqualified. This is mostly a hack to work
* around systems which ship dbus-launch in /usr/bin
* but everything else in /bin (because dbus-launch
* depends on X11).
*/
if (path_fallback)
/* We must have a slash, because we checked above */
execvp (strrchr (progpath, '/')+1, (char * const *) argv);
}
else
execvp (progpath, (char * const *) argv);
/* still nothing, we failed */
_exit (1);
}
/* parent process */
close (result_pipe[WRITE_END]);
close (errors_pipe[WRITE_END]);
result_pipe[WRITE_END] = -1;
errors_pipe[WRITE_END] = -1;
ret = 0;
do
{
ret = _dbus_read (result_pipe[READ_END], result, 1024);
}
while (ret > 0);
/* reap the child process to avoid it lingering as zombie */
do
{
ret = waitpid (pid, &status, 0);
}
while (ret == -1 && errno == EINTR);
/* We succeeded if the process exited with status 0 and
anything was read */
if (!WIFEXITED (status) || WEXITSTATUS (status) != 0 )
{
/* The process ended with error */
DBusString error_message;
if (!_dbus_string_init (&error_message))
{
_DBUS_SET_OOM (error);
goto out;
}
ret = 0;
do
{
ret = _dbus_read (errors_pipe[READ_END], &error_message, 1024);
}
while (ret > 0);
_dbus_string_set_length (result, orig_len);
if (_dbus_string_get_length (&error_message) > 0)
dbus_set_error (error, DBUS_ERROR_SPAWN_EXEC_FAILED,
"%s terminated abnormally with the following error: %s",
progpath, _dbus_string_get_data (&error_message));
else
dbus_set_error (error, DBUS_ERROR_SPAWN_EXEC_FAILED,
"%s terminated abnormally without any error message",
progpath);
goto out;
}
retval = TRUE;
out:
sigprocmask (SIG_SETMASK, &old_set, NULL);
if (retval)
_DBUS_ASSERT_ERROR_IS_CLEAR (error);
else
_DBUS_ASSERT_ERROR_IS_SET (error);
if (result_pipe[0] != -1)
close (result_pipe[0]);
if (result_pipe[1] != -1)
close (result_pipe[1]);
if (errors_pipe[0] != -1)
close (errors_pipe[0]);
if (errors_pipe[1] != -1)
close (errors_pipe[1]);
return retval;
}
#endif
/**
* Returns the address of a new session bus.
*
* If successful, returns #TRUE and appends the address to @p
* address. If a failure happens, returns #FALSE and
* sets an error in @p error.
*
* @param scope scope of autolaunch (Windows only)
* @param address a DBusString where the address can be stored
* @param error a DBusError to store the error in case of failure
* @returns #TRUE on success, #FALSE if an error happened
*/
dbus_bool_t
_dbus_get_autolaunch_address (const char *scope,
DBusString *address,
DBusError *error)
{
#ifdef DBUS_ENABLE_X11_AUTOLAUNCH
static const char arg_dbus_launch[] = "dbus-launch";
static const char arg_autolaunch[] = "--autolaunch";
static const char arg_binary_syntax[] = "--binary-syntax";
static const char arg_close_stderr[] = "--close-stderr";
/* Perform X11-based autolaunch. (We also support launchd-based autolaunch,
* but that's done elsewhere, and if it worked, this function wouldn't
* be called.) */
const char *display;
const char *progpath;
const char *argv[6];
int i;
DBusString uuid;
dbus_bool_t retval;
if (_dbus_check_setuid ())
{
dbus_set_error_const (error, DBUS_ERROR_NOT_SUPPORTED,
"Unable to autolaunch when setuid");
return FALSE;
}
_DBUS_ASSERT_ERROR_IS_CLEAR (error);
retval = FALSE;
/* fd.o #19997: if $DISPLAY isn't set to something useful, then
* dbus-launch-x11 is just going to fail. Rather than trying to
* run it, we might as well bail out early with a nice error.
*
* This is not strictly true in a world where the user bus exists,
* because dbus-launch --autolaunch knows how to connect to that -
* but if we were going to connect to the user bus, we'd have done
* so before trying autolaunch: in any case. */
display = _dbus_getenv ("DISPLAY");
if (display == NULL || display[0] == '\0')
{
dbus_set_error_const (error, DBUS_ERROR_NOT_SUPPORTED,
"Unable to autolaunch a dbus-daemon without a $DISPLAY for X11");
return FALSE;
}
if (!_dbus_string_init (&uuid))
{
_DBUS_SET_OOM (error);
return FALSE;
}
if (!_dbus_get_local_machine_uuid_encoded (&uuid, error))
{
goto out;
}
#ifdef DBUS_ENABLE_EMBEDDED_TESTS
progpath = _dbus_getenv ("DBUS_TEST_DBUS_LAUNCH");
if (progpath == NULL)
#endif
progpath = DBUS_BINDIR "/dbus-launch";
/*
* argv[0] is always dbus-launch, that's the name what we'll
* get from /proc, or ps(1), regardless what the progpath is,
* see fd.o#69716
*/
i = 0;
argv[i] = arg_dbus_launch;
++i;
argv[i] = arg_autolaunch;
++i;
argv[i] = _dbus_string_get_data (&uuid);
++i;
argv[i] = arg_binary_syntax;
++i;
argv[i] = arg_close_stderr;
++i;
argv[i] = NULL;
++i;
_dbus_assert (i == _DBUS_N_ELEMENTS (argv));
retval = _read_subprocess_line_argv (progpath,
TRUE,
argv, address, error);
out:
_dbus_string_free (&uuid);
return retval;
#else
dbus_set_error_const (error, DBUS_ERROR_NOT_SUPPORTED,
"Using X11 for dbus-daemon autolaunch was disabled at compile time, "
"set your DBUS_SESSION_BUS_ADDRESS instead");
return FALSE;
#endif
}
/**
* Reads the uuid of the machine we're running on from
* the dbus configuration. Optionally try to create it
* (only root can do this usually).
*
* On UNIX, reads a file that gets created by dbus-uuidgen
* in a post-install script. On Windows, if there's a standard
* machine uuid we could just use that, but I can't find one
* with the right properties (the hardware profile guid can change
* without rebooting I believe). If there's no standard one
* we might want to use the registry instead of a file for
* this, and I'm not sure how we'd ensure the uuid gets created.
*
* @param machine_id guid to init with the machine's uuid
* @param create_if_not_found try to create the uuid if it doesn't exist
* @param error the error return
* @returns #FALSE if the error is set
*/
dbus_bool_t
_dbus_read_local_machine_uuid (DBusGUID *machine_id,
dbus_bool_t create_if_not_found,
DBusError *error)
{
DBusString filename;
dbus_bool_t b;
_dbus_string_init_const (&filename, DBUS_MACHINE_UUID_FILE);
b = _dbus_read_uuid_file (&filename, machine_id, FALSE, error);
if (b)
return TRUE;
dbus_error_free (error);
/* Fallback to the system machine ID */
_dbus_string_init_const (&filename, "/etc/machine-id");
b = _dbus_read_uuid_file (&filename, machine_id, FALSE, error);
if (b)
{
/* try to copy it to the DBUS_MACHINE_UUID_FILE, but do not
* complain if that isn't possible for whatever reason */
_dbus_string_init_const (&filename, DBUS_MACHINE_UUID_FILE);
_dbus_write_uuid_file (&filename, machine_id, NULL);
return TRUE;
}
if (!create_if_not_found)
return FALSE;
/* if none found, try to make a new one */
dbus_error_free (error);
_dbus_string_init_const (&filename, DBUS_MACHINE_UUID_FILE);
if (!_dbus_generate_uuid (machine_id, error))
return FALSE;
return _dbus_write_uuid_file (&filename, machine_id, error);
}
/**
* quries launchd for a specific env var which holds the socket path.
* @param socket_path append the socket path to this DBusString
* @param launchd_env_var the env var to look up
* @param error a DBusError to store the error in case of failure
* @return the value of the env var
*/
dbus_bool_t
_dbus_lookup_launchd_socket (DBusString *socket_path,
const char *launchd_env_var,
DBusError *error)
{
#ifdef DBUS_ENABLE_LAUNCHD
char *argv[4];
int i;
_DBUS_ASSERT_ERROR_IS_CLEAR (error);
if (_dbus_check_setuid ())
{
dbus_set_error_const (error, DBUS_ERROR_NOT_SUPPORTED,
"Unable to find launchd socket when setuid");
return FALSE;
}
i = 0;
argv[i] = "launchctl";
++i;
argv[i] = "getenv";
++i;
argv[i] = (char*)launchd_env_var;
++i;
argv[i] = NULL;
++i;
_dbus_assert (i == _DBUS_N_ELEMENTS (argv));
if (!_read_subprocess_line_argv(argv[0], TRUE, argv, socket_path, error))
{
return FALSE;
}
/* no error, but no result either */
if (_dbus_string_get_length(socket_path) == 0)
{
return FALSE;
}
/* strip the carriage-return */
_dbus_string_shorten(socket_path, 1);
return TRUE;
#else /* DBUS_ENABLE_LAUNCHD */
dbus_set_error(error, DBUS_ERROR_NOT_SUPPORTED,
"can't lookup socket from launchd; launchd support not compiled in");
return FALSE;
#endif
}
#ifdef DBUS_ENABLE_LAUNCHD
static dbus_bool_t
_dbus_lookup_session_address_launchd (DBusString *address, DBusError *error)
{
dbus_bool_t valid_socket;
DBusString socket_path;
if (_dbus_check_setuid ())
{
dbus_set_error_const (error, DBUS_ERROR_NOT_SUPPORTED,
"Unable to find launchd socket when setuid");
return FALSE;
}
if (!_dbus_string_init (&socket_path))
{
_DBUS_SET_OOM (error);
return FALSE;
}
valid_socket = _dbus_lookup_launchd_socket (&socket_path, "DBUS_LAUNCHD_SESSION_BUS_SOCKET", error);
if (dbus_error_is_set(error))
{
_dbus_string_free(&socket_path);
return FALSE;
}
if (!valid_socket)
{
dbus_set_error(error, "no socket path",
"launchd did not provide a socket path, "
"verify that org.freedesktop.dbus-session.plist is loaded!");
_dbus_string_free(&socket_path);
return FALSE;
}
if (!_dbus_string_append (address, "unix:path="))
{
_DBUS_SET_OOM (error);
_dbus_string_free(&socket_path);
return FALSE;
}
if (!_dbus_string_copy (&socket_path, 0, address,
_dbus_string_get_length (address)))
{
_DBUS_SET_OOM (error);
_dbus_string_free(&socket_path);
return FALSE;
}
_dbus_string_free(&socket_path);
return TRUE;
}
#endif
dbus_bool_t
_dbus_lookup_user_bus (dbus_bool_t *supported,
DBusString *address,
DBusError *error)
{
const char *runtime_dir = _dbus_getenv ("XDG_RUNTIME_DIR");
dbus_bool_t ret = FALSE;
struct stat stbuf;
DBusString user_bus_path;
if (runtime_dir == NULL)
{
_dbus_verbose ("XDG_RUNTIME_DIR not found in environment");
*supported = FALSE;
return TRUE; /* Cannot use it, but not an error */
}
if (!_dbus_string_init (&user_bus_path))
{
_DBUS_SET_OOM (error);
return FALSE;
}
if (!_dbus_string_append_printf (&user_bus_path, "%s/bus", runtime_dir))
{
_DBUS_SET_OOM (error);
goto out;
}
if (lstat (_dbus_string_get_const_data (&user_bus_path), &stbuf) == -1)
{
_dbus_verbose ("XDG_RUNTIME_DIR/bus not available: %s",
_dbus_strerror (errno));
*supported = FALSE;
ret = TRUE; /* Cannot use it, but not an error */
goto out;
}
if (stbuf.st_uid != getuid ())
{
_dbus_verbose ("XDG_RUNTIME_DIR/bus owned by uid %ld, not our uid %ld",
(long) stbuf.st_uid, (long) getuid ());
*supported = FALSE;
ret = TRUE; /* Cannot use it, but not an error */
goto out;
}
if ((stbuf.st_mode & S_IFMT) != S_IFSOCK)
{
_dbus_verbose ("XDG_RUNTIME_DIR/bus is not a socket: st_mode = 0o%lo",
(long) stbuf.st_mode);
*supported = FALSE;
ret = TRUE; /* Cannot use it, but not an error */
goto out;
}
if (!_dbus_string_append (address, "unix:path=") ||
!_dbus_address_append_escaped (address, &user_bus_path))
{
_DBUS_SET_OOM (error);
goto out;
}
*supported = TRUE;
ret = TRUE;
out:
_dbus_string_free (&user_bus_path);
return ret;
}
/**
* Determines the address of the session bus by querying a
* platform-specific method.
*
* The first parameter will be a boolean specifying whether
* or not a dynamic session lookup is supported on this platform.
*
* If supported is TRUE and the return value is #TRUE, the
* address will be appended to @p address.
* If a failure happens, returns #FALSE and sets an error in
* @p error.
*
* If supported is FALSE, ignore the return value.
*
* @param supported returns whether this method is supported
* @param address a DBusString where the address can be stored
* @param error a DBusError to store the error in case of failure
* @returns #TRUE on success, #FALSE if an error happened
*/
dbus_bool_t
_dbus_lookup_session_address (dbus_bool_t *supported,
DBusString *address,
DBusError *error)
{
#ifdef DBUS_ENABLE_LAUNCHD
*supported = TRUE;
return _dbus_lookup_session_address_launchd (address, error);
#else
*supported = FALSE;
if (!_dbus_lookup_user_bus (supported, address, error))
return FALSE;
else if (*supported)
return TRUE;
/* On non-Mac Unix platforms, if the session address isn't already
* set in DBUS_SESSION_BUS_ADDRESS environment variable and the
* $XDG_RUNTIME_DIR/bus can't be used, we punt and fall back to the
* autolaunch: global default; see init_session_address in
* dbus/dbus-bus.c. */
return TRUE;
#endif
}
/**
* Called when the bus daemon is signaled to reload its configuration; any
* caches should be nuked. Of course any caches that need explicit reload
* are probably broken, but c'est la vie.
*
*
*/
void
_dbus_flush_caches (void)
{
_dbus_user_database_flush_system ();
}
/**
* Appends the directory in which a keyring for the given credentials
* should be stored. The credentials should have either a Windows or
* UNIX user in them. The directory should be an absolute path.
*
* On UNIX the directory is ~/.dbus-keyrings while on Windows it should probably
* be something else, since the dotfile convention is not normal on Windows.
*
* @param directory string to append directory to
* @param credentials credentials the directory should be for
*
* @returns #FALSE on no memory
*/
dbus_bool_t
_dbus_append_keyring_directory_for_credentials (DBusString *directory,
DBusCredentials *credentials)
{
DBusString homedir;
DBusString dotdir;
dbus_uid_t uid;
_dbus_assert (credentials != NULL);
_dbus_assert (!_dbus_credentials_are_anonymous (credentials));
if (!_dbus_string_init (&homedir))
return FALSE;
uid = _dbus_credentials_get_unix_uid (credentials);
_dbus_assert (uid != DBUS_UID_UNSET);
if (!_dbus_homedir_from_uid (uid, &homedir))
goto failed;
#ifdef DBUS_ENABLE_EMBEDDED_TESTS
{
const char *override;
override = _dbus_getenv ("DBUS_TEST_HOMEDIR");
if (override != NULL && *override != '\0')
{
_dbus_string_set_length (&homedir, 0);
if (!_dbus_string_append (&homedir, override))
goto failed;
_dbus_verbose ("Using fake homedir for testing: %s\n",
_dbus_string_get_const_data (&homedir));
}
else
{
/* Not strictly thread-safe, but if we fail at thread-safety here,
* the worst that will happen is some extra warnings. */
static dbus_bool_t already_warned = FALSE;
if (!already_warned)
{
_dbus_warn ("Using your real home directory for testing, set DBUS_TEST_HOMEDIR to avoid");
already_warned = TRUE;
}
}
}
#endif
_dbus_string_init_const (&dotdir, ".dbus-keyrings");
if (!_dbus_concat_dir_and_file (&homedir,
&dotdir))
goto failed;
if (!_dbus_string_copy (&homedir, 0,
directory, _dbus_string_get_length (directory))) {
goto failed;
}
_dbus_string_free (&homedir);
return TRUE;
failed:
_dbus_string_free (&homedir);
return FALSE;
}
//PENDING(kdab) docs
dbus_bool_t
_dbus_daemon_publish_session_bus_address (const char* addr,
const char *scope)
{
return TRUE;
}
//PENDING(kdab) docs
void
_dbus_daemon_unpublish_session_bus_address (void)
{
}
/**
* See if errno is EAGAIN or EWOULDBLOCK (this has to be done differently
* for Winsock so is abstracted)
*
* @returns #TRUE if e == EAGAIN or e == EWOULDBLOCK
*/
dbus_bool_t
_dbus_get_is_errno_eagain_or_ewouldblock (int e)
{
return e == EAGAIN || e == EWOULDBLOCK;
}
/**
* Removes a directory; Directory must be empty
*
* @param filename directory filename
* @param error initialized error object
* @returns #TRUE on success
*/
dbus_bool_t
_dbus_delete_directory (const DBusString *filename,
DBusError *error)
{
const char *filename_c;
_DBUS_ASSERT_ERROR_IS_CLEAR (error);
filename_c = _dbus_string_get_const_data (filename);
if (rmdir (filename_c) != 0)
{
dbus_set_error (error, DBUS_ERROR_FAILED,
"Failed to remove directory %s: %s\n",
filename_c, _dbus_strerror (errno));
return FALSE;
}
return TRUE;
}
/**
* Checks whether file descriptors may be passed via the socket
*
* @param fd the socket
* @return TRUE when fd passing over this socket is supported
*
*/
dbus_bool_t
_dbus_socket_can_pass_unix_fd (DBusSocket fd)
{
#ifdef SCM_RIGHTS
union {
struct sockaddr sa;
struct sockaddr_storage storage;
struct sockaddr_un un;
} sa_buf;
socklen_t sa_len = sizeof(sa_buf);
_DBUS_ZERO(sa_buf);
if (getsockname(fd.fd, &sa_buf.sa, &sa_len) < 0)
return FALSE;
return sa_buf.sa.sa_family == AF_UNIX;
#else
return FALSE;
#endif
}
/**
* Closes all file descriptors except the first three (i.e. stdin,
* stdout, stderr).
*/
void
_dbus_close_all (void)
{
int maxfds, i;
#ifdef __linux__
DIR *d;
/* On Linux we can optimize this a bit if /proc is available. If it
isn't available, fall back to the brute force way. */
d = opendir ("/proc/self/fd");
if (d)
{
for (;;)
{
struct dirent buf, *de;
int k, fd;
long l;
char *e = NULL;
k = readdir_r (d, &buf, &de);
if (k != 0 || !de)
break;
if (de->d_name[0] == '.')
continue;
errno = 0;
l = strtol (de->d_name, &e, 10);
if (errno != 0 || e == NULL || *e != '\0')
continue;
fd = (int) l;
if (fd < 3)
continue;
if (fd == dirfd (d))
continue;
close (fd);
}
closedir (d);
return;
}
#endif
maxfds = sysconf (_SC_OPEN_MAX);
/* Pick something reasonable if for some reason sysconf says
* unlimited.
*/
if (maxfds < 0)
maxfds = 1024;
/* close all inherited fds */
for (i = 3; i < maxfds; i++)
close (i);
}
/**
* **NOTE**: If you modify this function, please also consider making
* the corresponding change in GLib. See
* glib/gutils.c:g_check_setuid().
*
* Returns TRUE if the current process was executed as setuid (or an
* equivalent __libc_enable_secure is available). See:
* http://osdir.com/ml/linux.lfs.hardened/2007-04/msg00032.html
*/
dbus_bool_t
_dbus_check_setuid (void)
{
/* TODO: get __libc_enable_secure exported from glibc.
* See http://www.openwall.com/lists/owl-dev/2012/08/14/1
*/
#if 0 && defined(HAVE_LIBC_ENABLE_SECURE)
{
/* See glibc/include/unistd.h */
extern int __libc_enable_secure;
return __libc_enable_secure;
}
#elif defined(HAVE_ISSETUGID)
/* BSD: http://www.freebsd.org/cgi/man.cgi?query=issetugid&sektion=2 */
return issetugid ();
#else
uid_t ruid, euid, suid; /* Real, effective and saved user ID's */
gid_t rgid, egid, sgid; /* Real, effective and saved group ID's */
/* We call into this function from _dbus_threads_init_platform_specific()
* to make sure these are initialized before we start threading. */
static dbus_bool_t check_setuid_initialised;
static dbus_bool_t is_setuid;
if (_DBUS_UNLIKELY (!check_setuid_initialised))
{
#ifdef HAVE_GETRESUID
if (getresuid (&ruid, &euid, &suid) != 0 ||
getresgid (&rgid, &egid, &sgid) != 0)
#endif /* HAVE_GETRESUID */
{
suid = ruid = getuid ();
sgid = rgid = getgid ();
euid = geteuid ();
egid = getegid ();
}
check_setuid_initialised = TRUE;
is_setuid = (ruid != euid || ruid != suid ||
rgid != egid || rgid != sgid);
}
return is_setuid;
#endif
}
/**
* Read the address from the socket and append it to the string
*
* @param fd the socket
* @param address
* @param error return location for error code
*/
dbus_bool_t
_dbus_append_address_from_socket (DBusSocket fd,
DBusString *address,
DBusError *error)
{
union {
struct sockaddr sa;
struct sockaddr_storage storage;
struct sockaddr_un un;
struct sockaddr_in ipv4;
struct sockaddr_in6 ipv6;
} socket;
char hostip[INET6_ADDRSTRLEN];
socklen_t size = sizeof (socket);
DBusString path_str;
if (getsockname (fd.fd, &socket.sa, &size))
goto err;
switch (socket.sa.sa_family)
{
case AF_UNIX:
if (socket.un.sun_path[0]=='\0')
{
_dbus_string_init_const (&path_str, &(socket.un.sun_path[1]));
if (_dbus_string_append (address, "unix:abstract=") &&
_dbus_address_append_escaped (address, &path_str))
return TRUE;
}
else
{
_dbus_string_init_const (&path_str, socket.un.sun_path);
if (_dbus_string_append (address, "unix:path=") &&
_dbus_address_append_escaped (address, &path_str))
return TRUE;
}
break;
case AF_INET:
if (inet_ntop (AF_INET, &socket.ipv4.sin_addr, hostip, sizeof (hostip)))
if (_dbus_string_append_printf (address, "tcp:family=ipv4,host=%s,port=%u",
hostip, ntohs (socket.ipv4.sin_port)))
return TRUE;
break;
#ifdef AF_INET6
case AF_INET6:
_dbus_string_init_const (&path_str, hostip);
if (inet_ntop (AF_INET6, &socket.ipv6.sin6_addr, hostip, sizeof (hostip)))
if (_dbus_string_append_printf (address, "tcp:family=ipv6,port=%u,host=",
ntohs (socket.ipv6.sin6_port)) &&
_dbus_address_append_escaped (address, &path_str))
return TRUE;
break;
#endif
default:
dbus_set_error (error,
_dbus_error_from_errno (EINVAL),
"Failed to read address from socket: Unknown socket type.");
return FALSE;
}
err:
dbus_set_error (error,
_dbus_error_from_errno (errno),
"Failed to open socket: %s",
_dbus_strerror (errno));
return FALSE;
}
int
_dbus_save_socket_errno (void)
{
return errno;
}
void
_dbus_restore_socket_errno (int saved_errno)
{
errno = saved_errno;
}
static const char *syslog_tag = "dbus";
#ifdef HAVE_SYSLOG_H
static DBusLogFlags log_flags = DBUS_LOG_FLAGS_STDERR;
#endif
/**
* Initialize the system log.
*
* The "tag" is not copied, and must remain valid for the entire lifetime of
* the process or until _dbus_init_system_log() is called again. In practice
* it will normally be a constant.
*
* On platforms that do not support a system log, the
* #DBUS_LOG_FLAGS_SYSTEM_LOG flag is treated as equivalent to
* #DBUS_LOG_FLAGS_STDERR.
*
* @param tag the name of the executable (syslog tag)
* @param mode whether to log to stderr, the system log or both
*/
void
_dbus_init_system_log (const char *tag,
DBusLogFlags flags)
{
/* We never want to turn off logging completely */
_dbus_assert (
(flags & (DBUS_LOG_FLAGS_STDERR | DBUS_LOG_FLAGS_SYSTEM_LOG)) != 0);
syslog_tag = tag;
#ifdef HAVE_SYSLOG_H
log_flags = flags;
if (log_flags & DBUS_LOG_FLAGS_SYSTEM_LOG)
openlog (tag, LOG_PID, LOG_DAEMON);
#endif
}
/**
* Log a message to the system log file (e.g. syslog on Unix) and/or stderr.
*
* @param severity a severity value
* @param msg a printf-style format string
* @param args arguments for the format string
*
* If the FATAL severity is given, this function will terminate the program
* with an error code.
*/
void
_dbus_logv (DBusSystemLogSeverity severity,
const char *msg,
va_list args)
{
va_list tmp;
#ifdef HAVE_SYSLOG_H
if (log_flags & DBUS_LOG_FLAGS_SYSTEM_LOG)
{
int flags;
switch (severity)
{
case DBUS_SYSTEM_LOG_INFO:
flags = LOG_DAEMON | LOG_NOTICE;
break;
case DBUS_SYSTEM_LOG_WARNING:
flags = LOG_DAEMON | LOG_WARNING;
break;
case DBUS_SYSTEM_LOG_SECURITY:
flags = LOG_AUTH | LOG_NOTICE;
break;
case DBUS_SYSTEM_LOG_FATAL:
flags = LOG_DAEMON|LOG_CRIT;
break;
default:
return;
}
DBUS_VA_COPY (tmp, args);
vsyslog (flags, msg, tmp);
va_end (tmp);
}
/* If we don't have syslog.h, we always behave as though stderr was in
* the flags */
if (log_flags & DBUS_LOG_FLAGS_STDERR)
#endif
{
DBUS_VA_COPY (tmp, args);
fprintf (stderr, "%s[" DBUS_PID_FORMAT "]: ", syslog_tag, _dbus_getpid ());
vfprintf (stderr, msg, tmp);
fputc ('\n', stderr);
va_end (tmp);
}
if (severity == DBUS_SYSTEM_LOG_FATAL)
exit (1);
}
/* tests in dbus-sysdeps-util.c */
|