summarylogtreecommitdiffstats
path: root/0001-Add-duktape-as-javascript-engine.patch
blob: b1fa87dbe6a73652663819a8c9ce5fde3ddc37a6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
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
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
From 4f66a9549a393e4d74b93eb85301a04ea94bc750 Mon Sep 17 00:00:00 2001
From: Wu Xiaotian <yetist@gmail.com>
Date: Wed, 24 Jul 2019 15:55:17 +0800
Subject: [PATCH 01/17] Add duktape as javascript engine.

Signed-off-by: Gustavo Lima Chaves <gustavo.chaves@microsoft.com>
---
 configure.ac                                  |   28 +-
 src/polkitbackend/Makefile.am                 |   14 +-
 .../polkitbackendduktapeauthority.c           | 1402 +++++++++++++++++
 3 files changed, 1436 insertions(+), 8 deletions(-)
 create mode 100644 src/polkitbackend/polkitbackendduktapeauthority.c

diff --git a/configure.ac b/configure.ac
index e434ca2..5a03593 100644
--- a/configure.ac
+++ b/configure.ac
@@ -80,11 +80,22 @@ PKG_CHECK_MODULES(GLIB, [gmodule-2.0 gio-unix-2.0 >= 2.30.0])
 AC_SUBST(GLIB_CFLAGS)
 AC_SUBST(GLIB_LIBS)
 
-PKG_CHECK_MODULES(LIBJS, [mozjs-78])
-
-AC_SUBST(LIBJS_CFLAGS)
-AC_SUBST(LIBJS_CXXFLAGS)
-AC_SUBST(LIBJS_LIBS)
+dnl ---------------------------------------------------------------------------
+dnl - Check javascript backend
+dnl ---------------------------------------------------------------------------
+AC_ARG_WITH(duktape, AS_HELP_STRING([--with-duktape],[Use Duktape as javascript backend]),with_duktape=yes,with_duktape=no)
+AS_IF([test x${with_duktape} == xyes], [
+  PKG_CHECK_MODULES(LIBJS, [duktape >= 2.0.0 ])
+  AC_SUBST(LIBJS_CFLAGS)
+  AC_SUBST(LIBJS_LIBS)
+], [
+  PKG_CHECK_MODULES(LIBJS, [mozjs-78])
+
+  AC_SUBST(LIBJS_CFLAGS)
+  AC_SUBST(LIBJS_CXXFLAGS)
+  AC_SUBST(LIBJS_LIBS)
+])
+AM_CONDITIONAL(USE_DUKTAPE, [test x$with_duktape == xyes], [Using duktape as javascript engine library])
 
 EXPAT_LIB=""
 AC_ARG_WITH(expat, [  --with-expat=<dir>      Use expat from here],
@@ -585,6 +596,13 @@ echo "
         PAM support:                ${have_pam}
         systemdsystemunitdir:       ${systemdsystemunitdir}
         polkitd user:               ${POLKITD_USER}"
+if test "x${with_duktape}" = xyes; then
+echo "
+        Javascript engine:          Duktape"
+else
+echo "
+        Javascript engine:          Mozjs"
+fi
 
 if test "$have_pam" = yes ; then
 echo "
diff --git a/src/polkitbackend/Makefile.am b/src/polkitbackend/Makefile.am
index 7e3c080..abcbc6f 100644
--- a/src/polkitbackend/Makefile.am
+++ b/src/polkitbackend/Makefile.am
@@ -33,7 +33,7 @@ libpolkit_backend_1_la_SOURCES =                                   			\
 	polkitbackendprivate.h								\
 	polkitbackendauthority.h		polkitbackendauthority.c		\
 	polkitbackendinteractiveauthority.h	polkitbackendinteractiveauthority.c	\
-	polkitbackendjsauthority.h		polkitbackendjsauthority.cpp		\
+	polkitbackendjsauthority.h				\
 	polkitbackendactionpool.h		polkitbackendactionpool.c		\
 	polkitbackendactionlookup.h		polkitbackendactionlookup.c		\
         $(NULL)
@@ -51,19 +51,27 @@ libpolkit_backend_1_la_CFLAGS =                                        	\
         -D_POLKIT_BACKEND_COMPILATION                                  	\
         $(GLIB_CFLAGS)							\
 	$(LIBSYSTEMD_CFLAGS)						\
-	$(LIBJS_CFLAGS)							\
+	$(LIBJS_CFLAGS)						\
         $(NULL)
 
 libpolkit_backend_1_la_CXXFLAGS = $(libpolkit_backend_1_la_CFLAGS)
 
 libpolkit_backend_1_la_LIBADD =                               		\
         $(GLIB_LIBS)							\
+        $(DUKTAPE_LIBS)							\
 	$(LIBSYSTEMD_LIBS)						\
 	$(top_builddir)/src/polkit/libpolkit-gobject-1.la		\
 	$(EXPAT_LIBS)							\
-	$(LIBJS_LIBS)							\
+	$(LIBJS_LIBS)                                                   \
         $(NULL)
 
+if USE_DUKTAPE
+libpolkit_backend_1_la_SOURCES += polkitbackendduktapeauthority.c
+libpolkit_backend_1_la_LIBADD += -lm
+else
+libpolkit_backend_1_la_SOURCES += polkitbackendjsauthority.cpp
+endif
+
 rulesdir = $(sysconfdir)/polkit-1/rules.d
 rules_DATA = 50-default.rules
 
diff --git a/src/polkitbackend/polkitbackendduktapeauthority.c b/src/polkitbackend/polkitbackendduktapeauthority.c
new file mode 100644
index 0000000..ae98453
--- /dev/null
+++ b/src/polkitbackend/polkitbackendduktapeauthority.c
@@ -0,0 +1,1402 @@
+/*
+ * Copyright (C) 2008-2012 Red Hat, Inc.
+ * Copyright (C) 2015 Tangent Space <jstpierre@mecheye.net>
+ * Copyright (C) 2019 Wu Xiaotian <yetist@gmail.com>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General
+ * Public License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
+ * Boston, MA 02111-1307, USA.
+ *
+ * Author: David Zeuthen <davidz@redhat.com>
+ */
+
+#include "config.h"
+#include <sys/wait.h>
+#include <errno.h>
+#include <pwd.h>
+#include <grp.h>
+#include <netdb.h>
+#include <string.h>
+#include <glib/gstdio.h>
+#include <locale.h>
+#include <glib/gi18n-lib.h>
+
+#include <polkit/polkit.h>
+#include "polkitbackendjsauthority.h"
+
+#include <polkit/polkitprivate.h>
+
+#ifdef HAVE_LIBSYSTEMD
+#include <systemd/sd-login.h>
+#endif /* HAVE_LIBSYSTEMD */
+
+#include "initjs.h" /* init.js */
+#include "duktape.h"
+
+/**
+ * SECTION:polkitbackendjsauthority
+ * @title: PolkitBackendJsAuthority
+ * @short_description: JS Authority
+ * @stability: Unstable
+ *
+ * An implementation of #PolkitBackendAuthority that reads and
+ * evalates Javascript files and supports interaction with
+ * authentication agents (virtue of being based on
+ * #PolkitBackendInteractiveAuthority).
+ */
+
+/* ---------------------------------------------------------------------------------------------------- */
+
+struct _PolkitBackendJsAuthorityPrivate
+{
+  gchar **rules_dirs;
+  GFileMonitor **dir_monitors; /* NULL-terminated array of GFileMonitor instances */
+  duk_context *cx;
+};
+
+#define WATCHDOG_TIMEOUT (15 * G_TIME_SPAN_SECOND)
+
+static void utils_spawn (const gchar *const  *argv,
+                         guint                timeout_seconds,
+                         GCancellable        *cancellable,
+                         GAsyncReadyCallback  callback,
+                         gpointer             user_data);
+
+gboolean utils_spawn_finish (GAsyncResult   *res,
+                             gint           *out_exit_status,
+                             gchar         **out_standard_output,
+                             gchar         **out_standard_error,
+                             GError        **error);
+
+static void on_dir_monitor_changed (GFileMonitor     *monitor,
+                                    GFile            *file,
+                                    GFile            *other_file,
+                                    GFileMonitorEvent event_type,
+                                    gpointer          user_data);
+
+/* ---------------------------------------------------------------------------------------------------- */
+
+enum
+{
+  PROP_0,
+  PROP_RULES_DIRS,
+};
+
+/* ---------------------------------------------------------------------------------------------------- */
+
+static GList *polkit_backend_js_authority_get_admin_auth_identities (PolkitBackendInteractiveAuthority *authority,
+                                                                     PolkitSubject                     *caller,
+                                                                     PolkitSubject                     *subject,
+                                                                     PolkitIdentity                    *user_for_subject,
+                                                                     gboolean                           subject_is_local,
+                                                                     gboolean                           subject_is_active,
+                                                                     const gchar                       *action_id,
+                                                                     PolkitDetails                     *details);
+
+static PolkitImplicitAuthorization polkit_backend_js_authority_check_authorization_sync (
+                                                          PolkitBackendInteractiveAuthority *authority,
+                                                          PolkitSubject                     *caller,
+                                                          PolkitSubject                     *subject,
+                                                          PolkitIdentity                    *user_for_subject,
+                                                          gboolean                           subject_is_local,
+                                                          gboolean                           subject_is_active,
+                                                          const gchar                       *action_id,
+                                                          PolkitDetails                     *details,
+                                                          PolkitImplicitAuthorization        implicit);
+
+G_DEFINE_TYPE (PolkitBackendJsAuthority, polkit_backend_js_authority, POLKIT_BACKEND_TYPE_INTERACTIVE_AUTHORITY);
+
+/* ---------------------------------------------------------------------------------------------------- */
+
+/* ---------------------------------------------------------------------------------------------------- */
+
+static void
+polkit_backend_js_authority_init (PolkitBackendJsAuthority *authority)
+{
+  authority->priv = G_TYPE_INSTANCE_GET_PRIVATE (authority,
+                                                 POLKIT_BACKEND_TYPE_JS_AUTHORITY,
+                                                 PolkitBackendJsAuthorityPrivate);
+}
+
+static gint
+rules_file_name_cmp (const gchar *a,
+                     const gchar *b)
+{
+  gint ret;
+  const gchar *a_base;
+  const gchar *b_base;
+
+  a_base = strrchr (a, '/');
+  b_base = strrchr (b, '/');
+
+  g_assert (a_base != NULL);
+  g_assert (b_base != NULL);
+  a_base += 1;
+  b_base += 1;
+
+  ret = g_strcmp0 (a_base, b_base);
+  if (ret == 0)
+    {
+      /* /etc wins over /usr */
+      ret = g_strcmp0 (a, b);
+      g_assert (ret != 0);
+    }
+
+  return ret;
+}
+
+static void
+load_scripts (PolkitBackendJsAuthority  *authority)
+{
+  duk_context *cx = authority->priv->cx;
+  GList *files = NULL;
+  GList *l;
+  guint num_scripts = 0;
+  GError *error = NULL;
+  guint n;
+
+  files = NULL;
+
+  for (n = 0; authority->priv->rules_dirs != NULL && authority->priv->rules_dirs[n] != NULL; n++)
+    {
+      const gchar *dir_name = authority->priv->rules_dirs[n];
+      GDir *dir = NULL;
+
+      polkit_backend_authority_log (POLKIT_BACKEND_AUTHORITY (authority),
+                                    "Loading rules from directory %s",
+                                    dir_name);
+
+      dir = g_dir_open (dir_name,
+                        0,
+                        &error);
+      if (dir == NULL)
+        {
+          polkit_backend_authority_log (POLKIT_BACKEND_AUTHORITY (authority),
+                                        "Error opening rules directory: %s (%s, %d)",
+                                        error->message, g_quark_to_string (error->domain), error->code);
+          g_clear_error (&error);
+        }
+      else
+        {
+          const gchar *name;
+          while ((name = g_dir_read_name (dir)) != NULL)
+            {
+              if (g_str_has_suffix (name, ".rules"))
+                files = g_list_prepend (files, g_strdup_printf ("%s/%s", dir_name, name));
+            }
+          g_dir_close (dir);
+        }
+    }
+
+  files = g_list_sort (files, (GCompareFunc) rules_file_name_cmp);
+
+  for (l = files; l != NULL; l = l->next)
+    {
+      const gchar *filename = l->data;
+
+#if (DUK_VERSION >= 20000)
+      gchar *contents;
+      gsize length;
+      GError *error = NULL;
+      if (!g_file_get_contents (filename, &contents, &length, &error)){
+        g_warning("Error when file contents of %s: %s\n", filename, error->message);
+        g_error_free (error);
+        continue;
+      }
+      if (duk_peval_lstring_noresult(cx, contents,length) != 0)
+#else
+      if (duk_peval_file_noresult (cx, filename) != 0)
+#endif
+        {
+          polkit_backend_authority_log (POLKIT_BACKEND_AUTHORITY (authority),
+                                        "Error compiling script %s: %s",
+                                        filename, duk_safe_to_string (authority->priv->cx, -1));
+#if (DUK_VERSION >= 20000)
+          g_free (contents);
+#endif
+          continue;
+        }
+#if (DUK_VERSION >= 20000)
+      g_free (contents);
+#endif
+      num_scripts++;
+    }
+
+  polkit_backend_authority_log (POLKIT_BACKEND_AUTHORITY (authority),
+                                "Finished loading, compiling and executing %d rules",
+                                num_scripts);
+  g_list_free_full (files, g_free);
+}
+
+static void
+reload_scripts (PolkitBackendJsAuthority *authority)
+{
+  duk_context *cx = authority->priv->cx;
+
+  duk_set_top (cx, 0);
+  duk_get_global_string (cx, "polkit");
+  duk_push_string (cx, "_deleteRules");
+
+  duk_call_prop (cx, 0, 0);
+
+  polkit_backend_authority_log (POLKIT_BACKEND_AUTHORITY (authority),
+                                "Collecting garbage unconditionally...");
+
+  load_scripts (authority);
+
+  /* Let applications know we have new rules... */
+  g_signal_emit_by_name (authority, "changed");
+}
+
+static void
+on_dir_monitor_changed (GFileMonitor     *monitor,
+                        GFile            *file,
+                        GFile            *other_file,
+                        GFileMonitorEvent event_type,
+                        gpointer          user_data)
+{
+  PolkitBackendJsAuthority *authority = POLKIT_BACKEND_JS_AUTHORITY (user_data);
+
+  /* TODO: maybe rate-limit so storms of events are collapsed into one with a 500ms resolution?
+   *       Because when editing a file with emacs we get 4-8 events..
+   */
+
+  if (file != NULL)
+    {
+      gchar *name;
+
+      name = g_file_get_basename (file);
+
+      /* g_print ("event_type=%d file=%p name=%s\n", event_type, file, name); */
+      if (!g_str_has_prefix (name, ".") &&
+          !g_str_has_prefix (name, "#") &&
+          g_str_has_suffix (name, ".rules") &&
+          (event_type == G_FILE_MONITOR_EVENT_CREATED ||
+           event_type == G_FILE_MONITOR_EVENT_DELETED ||
+           event_type == G_FILE_MONITOR_EVENT_CHANGES_DONE_HINT))
+        {
+          polkit_backend_authority_log (POLKIT_BACKEND_AUTHORITY (authority),
+                                        "Reloading rules");
+          reload_scripts (authority);
+        }
+      g_free (name);
+    }
+}
+
+
+static void
+setup_file_monitors (PolkitBackendJsAuthority *authority)
+{
+  guint n;
+  GPtrArray *p;
+
+  p = g_ptr_array_new ();
+  for (n = 0; authority->priv->rules_dirs != NULL && authority->priv->rules_dirs[n] != NULL; n++)
+    {
+      GFile *file;
+      GError *error;
+      GFileMonitor *monitor;
+
+      file = g_file_new_for_path (authority->priv->rules_dirs[n]);
+      error = NULL;
+      monitor = g_file_monitor_directory (file,
+                                          G_FILE_MONITOR_NONE,
+                                          NULL,
+                                          &error);
+      g_object_unref (file);
+      if (monitor == NULL)
+        {
+          g_warning ("Error monitoring directory %s: %s",
+                     authority->priv->rules_dirs[n],
+                     error->message);
+          g_clear_error (&error);
+        }
+      else
+        {
+          g_signal_connect (monitor,
+                            "changed",
+                            G_CALLBACK (on_dir_monitor_changed),
+                            authority);
+          g_ptr_array_add (p, monitor);
+        }
+    }
+  g_ptr_array_add (p, NULL);
+  authority->priv->dir_monitors = (GFileMonitor**) g_ptr_array_free (p, FALSE);
+}
+
+static duk_ret_t js_polkit_log (duk_context *cx);
+static duk_ret_t js_polkit_spawn (duk_context *cx);
+static duk_ret_t js_polkit_user_is_in_netgroup (duk_context *cx);
+
+static const duk_function_list_entry js_polkit_functions[] =
+{
+  { "log", js_polkit_log, 1 },
+  { "spawn", js_polkit_spawn, 1 },
+  { "_userIsInNetGroup", js_polkit_user_is_in_netgroup, 2 },
+  { NULL, NULL, 0 },
+};
+
+static void
+polkit_backend_js_authority_constructed (GObject *object)
+{
+  PolkitBackendJsAuthority *authority = POLKIT_BACKEND_JS_AUTHORITY (object);
+  duk_context *cx;
+
+  cx = duk_create_heap (NULL, NULL, NULL, authority, NULL);
+  if (cx == NULL)
+    goto fail;
+
+  authority->priv->cx = cx;
+
+  duk_push_global_object (cx);
+  duk_push_object (cx);
+  duk_put_function_list (cx, -1, js_polkit_functions);
+  duk_put_prop_string (cx, -2, "polkit");
+
+  duk_eval_string (cx, init_js);
+
+  if (authority->priv->rules_dirs == NULL)
+    {
+      authority->priv->rules_dirs = g_new0 (gchar *, 3);
+      authority->priv->rules_dirs[0] = g_strdup (PACKAGE_SYSCONF_DIR "/polkit-1/rules.d");
+      authority->priv->rules_dirs[1] = g_strdup (PACKAGE_DATA_DIR "/polkit-1/rules.d");
+    }
+
+  setup_file_monitors (authority);
+  load_scripts (authority);
+
+  G_OBJECT_CLASS (polkit_backend_js_authority_parent_class)->constructed (object);
+  return;
+
+ fail:
+  g_critical ("Error initializing JavaScript environment");
+  g_assert_not_reached ();
+}
+
+static void
+polkit_backend_js_authority_finalize (GObject *object)
+{
+  PolkitBackendJsAuthority *authority = POLKIT_BACKEND_JS_AUTHORITY (object);
+  guint n;
+
+  for (n = 0; authority->priv->dir_monitors != NULL && authority->priv->dir_monitors[n] != NULL; n++)
+    {
+      GFileMonitor *monitor = authority->priv->dir_monitors[n];
+      g_signal_handlers_disconnect_by_func (monitor,
+                                            G_CALLBACK (on_dir_monitor_changed),
+                                            authority);
+      g_object_unref (monitor);
+    }
+  g_free (authority->priv->dir_monitors);
+  g_strfreev (authority->priv->rules_dirs);
+
+  duk_destroy_heap (authority->priv->cx);
+
+  G_OBJECT_CLASS (polkit_backend_js_authority_parent_class)->finalize (object);
+}
+
+static void
+polkit_backend_js_authority_set_property (GObject      *object,
+                                          guint         property_id,
+                                          const GValue *value,
+                                          GParamSpec   *pspec)
+{
+  PolkitBackendJsAuthority *authority = POLKIT_BACKEND_JS_AUTHORITY (object);
+
+  switch (property_id)
+    {
+      case PROP_RULES_DIRS:
+        g_assert (authority->priv->rules_dirs == NULL);
+        authority->priv->rules_dirs = (gchar **) g_value_dup_boxed (value);
+        break;
+
+      default:
+        G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
+        break;
+    }
+}
+
+static const gchar *
+polkit_backend_js_authority_get_name (PolkitBackendAuthority *authority)
+{
+  return "js";
+}
+
+static const gchar *
+polkit_backend_js_authority_get_version (PolkitBackendAuthority *authority)
+{
+  return PACKAGE_VERSION;
+}
+
+static PolkitAuthorityFeatures
+polkit_backend_js_authority_get_features (PolkitBackendAuthority *authority)
+{
+  return POLKIT_AUTHORITY_FEATURES_TEMPORARY_AUTHORIZATION;
+}
+
+static void
+polkit_backend_js_authority_class_init (PolkitBackendJsAuthorityClass *klass)
+{
+  GObjectClass *gobject_class;
+  PolkitBackendAuthorityClass *authority_class;
+  PolkitBackendInteractiveAuthorityClass *interactive_authority_class;
+
+
+  gobject_class = G_OBJECT_CLASS (klass);
+  gobject_class->finalize                               = polkit_backend_js_authority_finalize;
+  gobject_class->set_property                           = polkit_backend_js_authority_set_property;
+  gobject_class->constructed                            = polkit_backend_js_authority_constructed;
+
+  authority_class = POLKIT_BACKEND_AUTHORITY_CLASS (klass);
+  authority_class->get_name                             = polkit_backend_js_authority_get_name;
+  authority_class->get_version                          = polkit_backend_js_authority_get_version;
+  authority_class->get_features                         = polkit_backend_js_authority_get_features;
+
+  interactive_authority_class = POLKIT_BACKEND_INTERACTIVE_AUTHORITY_CLASS (klass);
+  interactive_authority_class->get_admin_identities     = polkit_backend_js_authority_get_admin_auth_identities;
+  interactive_authority_class->check_authorization_sync = polkit_backend_js_authority_check_authorization_sync;
+
+  g_object_class_install_property (gobject_class,
+                                   PROP_RULES_DIRS,
+                                   g_param_spec_boxed ("rules-dirs",
+                                                       NULL,
+                                                       NULL,
+                                                       G_TYPE_STRV,
+                                                       G_PARAM_CONSTRUCT_ONLY | G_PARAM_WRITABLE));
+
+
+  g_type_class_add_private (klass, sizeof (PolkitBackendJsAuthorityPrivate));
+}
+
+/* ---------------------------------------------------------------------------------------------------- */
+
+static void
+set_property_str (duk_context *cx,
+                  const gchar *name,
+                  const gchar *value)
+{
+  duk_push_string (cx, value);
+  duk_put_prop_string (cx, -2, name);
+}
+
+static void
+set_property_strv (duk_context *cx,
+                   const gchar *name,
+                   GPtrArray   *value)
+{
+  guint n;
+  duk_push_array (cx);
+  for (n = 0; n < value->len; n++)
+    {
+      duk_push_string (cx, g_ptr_array_index (value, n));
+      duk_put_prop_index (cx, -2, n);
+    }
+  duk_put_prop_string (cx, -2, name);
+}
+
+static void
+set_property_int32 (duk_context *cx,
+                    const gchar *name,
+                    gint32       value)
+{
+  duk_push_int (cx, value);
+  duk_put_prop_string (cx, -2, name);
+}
+
+static void
+set_property_bool (duk_context *cx,
+                   const char  *name,
+                   gboolean     value)
+{
+  duk_push_boolean (cx, value);
+  duk_put_prop_string (cx, -2, name);
+}
+
+/* ---------------------------------------------------------------------------------------------------- */
+
+static gboolean
+push_subject (duk_context               *cx,
+              PolkitSubject             *subject,
+              PolkitIdentity            *user_for_subject,
+              gboolean                   subject_is_local,
+              gboolean                   subject_is_active,
+              GError                   **error)
+{
+  gboolean ret = FALSE;
+  pid_t pid;
+  uid_t uid;
+  gchar *user_name = NULL;
+  GPtrArray *groups = NULL;
+  struct passwd *passwd;
+  char *seat_str = NULL;
+  char *session_str = NULL;
+
+  duk_get_global_string (cx, "Subject");
+  duk_new (cx, 0);
+
+  if (POLKIT_IS_UNIX_PROCESS (subject))
+    {
+      pid = polkit_unix_process_get_pid (POLKIT_UNIX_PROCESS (subject));
+    }
+  else if (POLKIT_IS_SYSTEM_BUS_NAME (subject))
+    {
+      PolkitSubject *process;
+      process = polkit_system_bus_name_get_process_sync (POLKIT_SYSTEM_BUS_NAME (subject), NULL, error);
+      if (process == NULL)
+        goto out;
+      pid = polkit_unix_process_get_pid (POLKIT_UNIX_PROCESS (process));
+      g_object_unref (process);
+    }
+  else
+    {
+      g_assert_not_reached ();
+    }
+
+#ifdef HAVE_LIBSYSTEMD
+  if (sd_pid_get_session (pid, &session_str) == 0)
+    {
+      if (sd_session_get_seat (session_str, &seat_str) == 0)
+        {
+          /* do nothing */
+        }
+    }
+#endif /* HAVE_LIBSYSTEMD */
+
+  g_assert (POLKIT_IS_UNIX_USER (user_for_subject));
+  uid = polkit_unix_user_get_uid (POLKIT_UNIX_USER (user_for_subject));
+
+  groups = g_ptr_array_new_with_free_func (g_free);
+
+  passwd = getpwuid (uid);
+  if (passwd == NULL)
+    {
+      user_name = g_strdup_printf ("%d", (gint) uid);
+      g_warning ("Error looking up info for uid %d: %m", (gint) uid);
+    }
+  else
+    {
+      gid_t gids[512];
+      int num_gids = 512;
+
+      user_name = g_strdup (passwd->pw_name);
+
+      if (getgrouplist (passwd->pw_name,
+                        passwd->pw_gid,
+                        gids,
+                        &num_gids) < 0)
+        {
+          g_warning ("Error looking up groups for uid %d: %m", (gint) uid);
+        }
+      else
+        {
+          gint n;
+          for (n = 0; n < num_gids; n++)
+            {
+              struct group *group;
+              group = getgrgid (gids[n]);
+              if (group == NULL)
+                {
+                  g_ptr_array_add (groups, g_strdup_printf ("%d", (gint) gids[n]));
+                }
+              else
+                {
+                  g_ptr_array_add (groups, g_strdup (group->gr_name));
+                }
+            }
+        }
+    }
+
+  set_property_int32 (cx, "pid", pid);
+  set_property_str (cx, "user", user_name);
+  set_property_strv (cx, "groups", groups);
+  set_property_str (cx, "seat", seat_str);
+  set_property_str (cx, "session", session_str);
+  set_property_bool (cx, "local", subject_is_local);
+  set_property_bool (cx, "active", subject_is_active);
+
+  ret = TRUE;
+
+ out:
+  free (session_str);
+  free (seat_str);
+  g_free (user_name);
+  if (groups != NULL)
+    g_ptr_array_unref (groups);
+
+  return ret;
+}
+
+/* ---------------------------------------------------------------------------------------------------- */
+
+static gboolean
+push_action_and_details (duk_context               *cx,
+                         const gchar               *action_id,
+                         PolkitDetails             *details,
+                         GError                   **error)
+{
+  gchar **keys;
+  guint n;
+
+  duk_get_global_string (cx, "Action");
+  duk_new (cx, 0);
+
+  set_property_str (cx, "id", action_id);
+
+  keys = polkit_details_get_keys (details);
+  for (n = 0; keys != NULL && keys[n] != NULL; n++)
+    {
+      gchar *key;
+      const gchar *value;
+      key = g_strdup_printf ("_detail_%s", keys[n]);
+      value = polkit_details_lookup (details, keys[n]);
+      set_property_str (cx, key, value);
+      g_free (key);
+    }
+  g_strfreev (keys);
+
+  return TRUE;
+}
+
+/* ---------------------------------------------------------------------------------------------------- */
+
+/* ---------------------------------------------------------------------------------------------------- */
+
+static GList *
+polkit_backend_js_authority_get_admin_auth_identities (PolkitBackendInteractiveAuthority *_authority,
+                                                       PolkitSubject                     *caller,
+                                                       PolkitSubject                     *subject,
+                                                       PolkitIdentity                    *user_for_subject,
+                                                       gboolean                           subject_is_local,
+                                                       gboolean                           subject_is_active,
+                                                       const gchar                       *action_id,
+                                                       PolkitDetails                     *details)
+{
+  PolkitBackendJsAuthority *authority = POLKIT_BACKEND_JS_AUTHORITY (_authority);
+  GList *ret = NULL;
+  guint n;
+  GError *error = NULL;
+  const char *ret_str = NULL;
+  gchar **ret_strs = NULL;
+  duk_context *cx = authority->priv->cx;
+
+  duk_set_top (cx, 0);
+  duk_get_global_string (cx, "polkit");
+  duk_push_string (cx, "_runAdminRules");
+
+  if (!push_action_and_details (cx, action_id, details, &error))
+    {
+      polkit_backend_authority_log (POLKIT_BACKEND_AUTHORITY (authority),
+                                    "Error converting action and details to JS object: %s",
+                                    error->message);
+      g_clear_error (&error);
+      goto out;
+    }
+
+  if (!push_subject (cx, subject, user_for_subject, subject_is_local, subject_is_active, &error))
+    {
+      polkit_backend_authority_log (POLKIT_BACKEND_AUTHORITY (authority),
+                                    "Error converting subject to JS object: %s",
+                                    error->message);
+      g_clear_error (&error);
+      goto out;
+    }
+
+  if (duk_pcall_prop (cx, 0, 2) != DUK_ERR_NONE)
+    {
+      polkit_backend_authority_log (POLKIT_BACKEND_AUTHORITY (authority),
+                                    "Error evaluating admin rules: ",
+                                    duk_safe_to_string (cx, -1));
+      goto out;
+    }
+
+  ret_str = duk_require_string (cx, -1);
+
+  ret_strs = g_strsplit (ret_str, ",", -1);
+  for (n = 0; ret_strs != NULL && ret_strs[n] != NULL; n++)
+    {
+      const gchar *identity_str = ret_strs[n];
+      PolkitIdentity *identity;
+
+      error = NULL;
+      identity = polkit_identity_from_string (identity_str, &error);
+      if (identity == NULL)
+        {
+          polkit_backend_authority_log (POLKIT_BACKEND_AUTHORITY (authority),
+                                        "Identity `%s' is not valid, ignoring: %s",
+                                        identity_str, error->message);
+          g_clear_error (&error);
+        }
+      else
+        {
+          ret = g_list_prepend (ret, identity);
+        }
+    }
+  ret = g_list_reverse (ret);
+
+ out:
+  g_strfreev (ret_strs);
+  /* fallback to root password auth */
+  if (ret == NULL)
+    ret = g_list_prepend (ret, polkit_unix_user_new (0));
+
+  return ret;
+}
+
+/* ---------------------------------------------------------------------------------------------------- */
+
+static PolkitImplicitAuthorization
+polkit_backend_js_authority_check_authorization_sync (PolkitBackendInteractiveAuthority *_authority,
+                                                      PolkitSubject                     *caller,
+                                                      PolkitSubject                     *subject,
+                                                      PolkitIdentity                    *user_for_subject,
+                                                      gboolean                           subject_is_local,
+                                                      gboolean                           subject_is_active,
+                                                      const gchar                       *action_id,
+                                                      PolkitDetails                     *details,
+                                                      PolkitImplicitAuthorization        implicit)
+{
+  PolkitBackendJsAuthority *authority = POLKIT_BACKEND_JS_AUTHORITY (_authority);
+  PolkitImplicitAuthorization ret = implicit;
+  GError *error = NULL;
+  gchar *ret_str = NULL;
+  gboolean good = FALSE;
+  duk_context *cx = authority->priv->cx;
+
+  duk_set_top (cx, 0);
+  duk_get_global_string (cx, "polkit");
+  duk_push_string (cx, "_runRules");
+
+  if (!push_action_and_details (cx, action_id, details, &error))
+    {
+      polkit_backend_authority_log (POLKIT_BACKEND_AUTHORITY (authority),
+                                    "Error converting action and details to JS object: %s",
+                                    error->message);
+      g_clear_error (&error);
+      goto out;
+    }
+
+  if (!push_subject (cx, subject, user_for_subject, subject_is_local, subject_is_active, &error))
+    {
+      polkit_backend_authority_log (POLKIT_BACKEND_AUTHORITY (authority),
+                                    "Error converting subject to JS object: %s",
+                                    error->message);
+      g_clear_error (&error);
+      goto out;
+    }
+
+  if (duk_pcall_prop (cx, 0, 2) != DUK_ERR_NONE)
+  {
+      polkit_backend_authority_log (POLKIT_BACKEND_AUTHORITY (authority),
+                                    "Error evaluating authorization rules: ",
+                                    duk_safe_to_string (cx, -1));
+      goto out;
+  }
+
+  if (duk_is_null(cx, -1)) {
+    good = TRUE;
+    goto out;
+  }
+  ret_str = g_strdup (duk_require_string (cx, -1));
+  if (!polkit_implicit_authorization_from_string (ret_str, &ret))
+    {
+      polkit_backend_authority_log (POLKIT_BACKEND_AUTHORITY (authority),
+                                    "Returned result `%s' is not valid",
+                                    ret_str);
+      goto out;
+    }
+
+  good = TRUE;
+
+ out:
+  if (!good)
+    ret = POLKIT_IMPLICIT_AUTHORIZATION_NOT_AUTHORIZED;
+  g_free (ret_str);
+
+  return ret;
+}
+
+/* ---------------------------------------------------------------------------------------------------- */
+
+static duk_ret_t
+js_polkit_log (duk_context *cx)
+{
+  const char *str = duk_require_string (cx, 0);
+  fprintf (stderr, "%s\n", str);
+  return 0;
+}
+
+/* ---------------------------------------------------------------------------------------------------- */
+
+static const gchar *
+get_signal_name (gint signal_number)
+{
+  switch (signal_number)
+    {
+#define _HANDLE_SIG(sig) case sig: return #sig;
+    _HANDLE_SIG (SIGHUP);
+    _HANDLE_SIG (SIGINT);
+    _HANDLE_SIG (SIGQUIT);
+    _HANDLE_SIG (SIGILL);
+    _HANDLE_SIG (SIGABRT);
+    _HANDLE_SIG (SIGFPE);
+    _HANDLE_SIG (SIGKILL);
+    _HANDLE_SIG (SIGSEGV);
+    _HANDLE_SIG (SIGPIPE);
+    _HANDLE_SIG (SIGALRM);
+    _HANDLE_SIG (SIGTERM);
+    _HANDLE_SIG (SIGUSR1);
+    _HANDLE_SIG (SIGUSR2);
+    _HANDLE_SIG (SIGCHLD);
+    _HANDLE_SIG (SIGCONT);
+    _HANDLE_SIG (SIGSTOP);
+    _HANDLE_SIG (SIGTSTP);
+    _HANDLE_SIG (SIGTTIN);
+    _HANDLE_SIG (SIGTTOU);
+    _HANDLE_SIG (SIGBUS);
+#ifdef SIGPOLL
+    _HANDLE_SIG (SIGPOLL);
+#endif
+    _HANDLE_SIG (SIGPROF);
+    _HANDLE_SIG (SIGSYS);
+    _HANDLE_SIG (SIGTRAP);
+    _HANDLE_SIG (SIGURG);
+    _HANDLE_SIG (SIGVTALRM);
+    _HANDLE_SIG (SIGXCPU);
+    _HANDLE_SIG (SIGXFSZ);
+#undef _HANDLE_SIG
+    default:
+      break;
+    }
+  return "UNKNOWN_SIGNAL";
+}
+
+typedef struct
+{
+  GMainLoop *loop;
+  GAsyncResult *res;
+} SpawnData;
+
+static void
+spawn_cb (GObject       *source_object,
+          GAsyncResult  *res,
+          gpointer       user_data)
+{
+  SpawnData *data = user_data;
+  data->res = g_object_ref (res);
+  g_main_loop_quit (data->loop);
+}
+
+static duk_ret_t
+js_polkit_spawn (duk_context *cx)
+{
+#if (DUK_VERSION >= 20000)
+  duk_ret_t ret = DUK_RET_ERROR;
+#else
+  duk_ret_t ret = DUK_RET_INTERNAL_ERROR;
+#endif
+  gchar *standard_output = NULL;
+  gchar *standard_error = NULL;
+  gint exit_status;
+  GError *error = NULL;
+  guint32 array_len;
+  gchar **argv = NULL;
+  GMainContext *context = NULL;
+  GMainLoop *loop = NULL;
+  SpawnData data = {0};
+  char *err_str = NULL;
+  guint n;
+
+  if (!duk_is_array (cx, 0))
+    goto out;
+
+  array_len = duk_get_length (cx, 0);
+
+  argv = g_new0 (gchar*, array_len + 1);
+  for (n = 0; n < array_len; n++)
+    {
+      duk_get_prop_index (cx, 0, n);
+      argv[n] = g_strdup (duk_to_string (cx, -1));
+      duk_pop (cx);
+    }
+
+  context = g_main_context_new ();
+  loop = g_main_loop_new (context, FALSE);
+
+  g_main_context_push_thread_default (context);
+
+  data.loop = loop;
+  utils_spawn ((const gchar *const *) argv,
+               10, /* timeout_seconds */
+               NULL, /* cancellable */
+               spawn_cb,
+               &data);
+
+  g_main_loop_run (loop);
+
+  g_main_context_pop_thread_default (context);
+
+  if (!utils_spawn_finish (data.res,
+                           &exit_status,
+                           &standard_output,
+                           &standard_error,
+                           &error))
+    {
+      err_str = g_strdup_printf ("Error spawning helper: %s (%s, %d)",
+                                 error->message, g_quark_to_string (error->domain), error->code);
+      g_clear_error (&error);
+      goto out;
+    }
+
+  if (!(WIFEXITED (exit_status) && WEXITSTATUS (exit_status) == 0))
+    {
+      GString *gstr;
+      gstr = g_string_new (NULL);
+      if (WIFEXITED (exit_status))
+        {
+          g_string_append_printf (gstr,
+                                  "Helper exited with non-zero exit status %d",
+                                  WEXITSTATUS (exit_status));
+        }
+      else if (WIFSIGNALED (exit_status))
+        {
+          g_string_append_printf (gstr,
+                                  "Helper was signaled with signal %s (%d)",
+                                  get_signal_name (WTERMSIG (exit_status)),
+                                  WTERMSIG (exit_status));
+        }
+      g_string_append_printf (gstr, ", stdout=`%s', stderr=`%s'",
+                              standard_output, standard_error);
+      err_str = g_string_free (gstr, FALSE);
+      goto out;
+    }
+
+  duk_push_string (cx, standard_output);
+  ret = 1;
+
+ out:
+  g_strfreev (argv);
+  g_free (standard_output);
+  g_free (standard_error);
+  g_clear_object (&data.res);
+  if (loop != NULL)
+    g_main_loop_unref (loop);
+  if (context != NULL)
+    g_main_context_unref (context);
+
+  if (err_str)
+    duk_error (cx, DUK_ERR_ERROR, err_str);
+
+  return ret;
+}
+
+/* ---------------------------------------------------------------------------------------------------- */
+
+
+static duk_ret_t
+js_polkit_user_is_in_netgroup (duk_context *cx)
+{
+  const char *user;
+  const char *netgroup;
+  gboolean is_in_netgroup = FALSE;
+
+  user = duk_require_string (cx, 0);
+  netgroup = duk_require_string (cx, 1);
+
+  if (innetgr (netgroup,
+               NULL,  /* host */
+               user,
+               NULL)) /* domain */
+    {
+      is_in_netgroup = TRUE;
+    }
+
+  duk_push_boolean (cx, is_in_netgroup);
+  return 1;
+}
+
+/* ---------------------------------------------------------------------------------------------------- */
+
+typedef struct
+{
+  GSimpleAsyncResult *simple; /* borrowed reference */
+  GMainContext *main_context; /* may be NULL */
+
+  GCancellable *cancellable;  /* may be NULL */
+  gulong cancellable_handler_id;
+
+  GPid child_pid;
+  gint child_stdout_fd;
+  gint child_stderr_fd;
+
+  GIOChannel *child_stdout_channel;
+  GIOChannel *child_stderr_channel;
+
+  GSource *child_watch_source;
+  GSource *child_stdout_source;
+  GSource *child_stderr_source;
+
+  guint timeout_seconds;
+  gboolean timed_out;
+  GSource *timeout_source;
+
+  GString *child_stdout;
+  GString *child_stderr;
+
+  gint exit_status;
+} UtilsSpawnData;
+
+static void
+utils_child_watch_from_release_cb (GPid     pid,
+                                   gint     status,
+                                   gpointer user_data)
+{
+}
+
+static void
+utils_spawn_data_free (UtilsSpawnData *data)
+{
+  if (data->timeout_source != NULL)
+    {
+      g_source_destroy (data->timeout_source);
+      data->timeout_source = NULL;
+    }
+
+  /* Nuke the child, if necessary */
+  if (data->child_watch_source != NULL)
+    {
+      g_source_destroy (data->child_watch_source);
+      data->child_watch_source = NULL;
+    }
+
+  if (data->child_pid != 0)
+    {
+      GSource *source;
+      kill (data->child_pid, SIGTERM);
+      /* OK, we need to reap for the child ourselves - we don't want
+       * to use waitpid() because that might block the calling
+       * thread (the child might handle SIGTERM and use several
+       * seconds for cleanup/rollback).
+       *
+       * So we use GChildWatch instead.
+       *
+       * Avoid taking a references to ourselves. but note that we need
+       * to pass the GSource so we can nuke it once handled.
+       */
+      source = g_child_watch_source_new (data->child_pid);
+      g_source_set_callback (source,
+                             (GSourceFunc) utils_child_watch_from_release_cb,
+                             source,
+                             (GDestroyNotify) g_source_destroy);
+      g_source_attach (source, data->main_context);
+      g_source_unref (source);
+      data->child_pid = 0;
+    }
+
+  if (data->child_stdout != NULL)
+    {
+      g_string_free (data->child_stdout, TRUE);
+      data->child_stdout = NULL;
+    }
+
+  if (data->child_stderr != NULL)
+    {
+      g_string_free (data->child_stderr, TRUE);
+      data->child_stderr = NULL;
+    }
+
+  if (data->child_stdout_channel != NULL)
+    {
+      g_io_channel_unref (data->child_stdout_channel);
+      data->child_stdout_channel = NULL;
+    }
+  if (data->child_stderr_channel != NULL)
+    {
+      g_io_channel_unref (data->child_stderr_channel);
+      data->child_stderr_channel = NULL;
+    }
+
+  if (data->child_stdout_source != NULL)
+    {
+      g_source_destroy (data->child_stdout_source);
+      data->child_stdout_source = NULL;
+    }
+  if (data->child_stderr_source != NULL)
+    {
+      g_source_destroy (data->child_stderr_source);
+      data->child_stderr_source = NULL;
+    }
+
+  if (data->child_stdout_fd != -1)
+    {
+      g_warn_if_fail (close (data->child_stdout_fd) == 0);
+      data->child_stdout_fd = -1;
+    }
+  if (data->child_stderr_fd != -1)
+    {
+      g_warn_if_fail (close (data->child_stderr_fd) == 0);
+      data->child_stderr_fd = -1;
+    }
+
+  if (data->cancellable_handler_id > 0)
+    {
+      g_cancellable_disconnect (data->cancellable, data->cancellable_handler_id);
+      data->cancellable_handler_id = 0;
+    }
+
+  if (data->main_context != NULL)
+    g_main_context_unref (data->main_context);
+
+  if (data->cancellable != NULL)
+    g_object_unref (data->cancellable);
+
+  g_slice_free (UtilsSpawnData, data);
+}
+
+/* called in the thread where @cancellable was cancelled */
+static void
+utils_on_cancelled (GCancellable *cancellable,
+                    gpointer      user_data)
+{
+  UtilsSpawnData *data = user_data;
+  GError *error;
+
+  error = NULL;
+  g_warn_if_fail (g_cancellable_set_error_if_cancelled (cancellable, &error));
+  g_simple_async_result_take_error (data->simple, error);
+  g_simple_async_result_complete_in_idle (data->simple);
+  g_object_unref (data->simple);
+}
+
+static gboolean
+utils_read_child_stderr (GIOChannel *channel,
+                         GIOCondition condition,
+                         gpointer user_data)
+{
+  UtilsSpawnData *data = user_data;
+  gchar buf[1024];
+  gsize bytes_read;
+
+  g_io_channel_read_chars (channel, buf, sizeof buf, &bytes_read, NULL);
+  g_string_append_len (data->child_stderr, buf, bytes_read);
+  return TRUE;
+}
+
+static gboolean
+utils_read_child_stdout (GIOChannel *channel,
+                         GIOCondition condition,
+                         gpointer user_data)
+{
+  UtilsSpawnData *data = user_data;
+  gchar buf[1024];
+  gsize bytes_read;
+
+  g_io_channel_read_chars (channel, buf, sizeof buf, &bytes_read, NULL);
+  g_string_append_len (data->child_stdout, buf, bytes_read);
+  return TRUE;
+}
+
+static void
+utils_child_watch_cb (GPid     pid,
+                      gint     status,
+                      gpointer user_data)
+{
+  UtilsSpawnData *data = user_data;
+  gchar *buf;
+  gsize buf_size;
+
+  if (g_io_channel_read_to_end (data->child_stdout_channel, &buf, &buf_size, NULL) == G_IO_STATUS_NORMAL)
+    {
+      g_string_append_len (data->child_stdout, buf, buf_size);
+      g_free (buf);
+    }
+  if (g_io_channel_read_to_end (data->child_stderr_channel, &buf, &buf_size, NULL) == G_IO_STATUS_NORMAL)
+    {
+      g_string_append_len (data->child_stderr, buf, buf_size);
+      g_free (buf);
+    }
+
+  data->exit_status = status;
+
+  /* ok, child watch is history, make sure we don't free it in spawn_data_free() */
+  data->child_pid = 0;
+  data->child_watch_source = NULL;
+
+  /* we're done */
+  g_simple_async_result_complete_in_idle (data->simple);
+  g_object_unref (data->simple);
+}
+
+static gboolean
+utils_timeout_cb (gpointer user_data)
+{
+  UtilsSpawnData *data = user_data;
+
+  data->timed_out = TRUE;
+
+  /* ok, timeout is history, make sure we don't free it in spawn_data_free() */
+  data->timeout_source = NULL;
+
+  /* we're done */
+  g_simple_async_result_complete_in_idle (data->simple);
+  g_object_unref (data->simple);
+
+  return FALSE; /* remove source */
+}
+
+static void
+utils_spawn (const gchar *const  *argv,
+             guint                timeout_seconds,
+             GCancellable        *cancellable,
+             GAsyncReadyCallback  callback,
+             gpointer             user_data)
+{
+  UtilsSpawnData *data;
+  GError *error;
+
+  data = g_slice_new0 (UtilsSpawnData);
+  data->timeout_seconds = timeout_seconds;
+  data->simple = g_simple_async_result_new (NULL,
+                                            callback,
+                                            user_data,
+                                            utils_spawn);
+  data->main_context = g_main_context_get_thread_default ();
+  if (data->main_context != NULL)
+    g_main_context_ref (data->main_context);
+
+  data->cancellable = cancellable != NULL ? g_object_ref (cancellable) : NULL;
+
+  data->child_stdout = g_string_new (NULL);
+  data->child_stderr = g_string_new (NULL);
+  data->child_stdout_fd = -1;
+  data->child_stderr_fd = -1;
+
+  /* the life-cycle of UtilsSpawnData is tied to its GSimpleAsyncResult */
+  g_simple_async_result_set_op_res_gpointer (data->simple, data, (GDestroyNotify) utils_spawn_data_free);
+
+  error = NULL;
+  if (data->cancellable != NULL)
+    {
+      /* could already be cancelled */
+      error = NULL;
+      if (g_cancellable_set_error_if_cancelled (data->cancellable, &error))
+        {
+          g_simple_async_result_take_error (data->simple, error);
+          g_simple_async_result_complete_in_idle (data->simple);
+          g_object_unref (data->simple);
+          goto out;
+        }
+
+      data->cancellable_handler_id = g_cancellable_connect (data->cancellable,
+                                                            G_CALLBACK (utils_on_cancelled),
+                                                            data,
+                                                            NULL);
+    }
+
+  error = NULL;
+  if (!g_spawn_async_with_pipes (NULL, /* working directory */
+                                 (gchar **) argv,
+                                 NULL, /* envp */
+                                 G_SPAWN_SEARCH_PATH | G_SPAWN_DO_NOT_REAP_CHILD,
+                                 NULL, /* child_setup */
+                                 NULL, /* child_setup's user_data */
+                                 &(data->child_pid),
+                                 NULL, /* gint *stdin_fd */
+                                 &(data->child_stdout_fd),
+                                 &(data->child_stderr_fd),
+                                 &error))
+    {
+      g_prefix_error (&error, "Error spawning: ");
+      g_simple_async_result_take_error (data->simple, error);
+      g_simple_async_result_complete_in_idle (data->simple);
+      g_object_unref (data->simple);
+      goto out;
+    }
+
+  if (timeout_seconds > 0)
+    {
+      data->timeout_source = g_timeout_source_new_seconds (timeout_seconds);
+      g_source_set_priority (data->timeout_source, G_PRIORITY_DEFAULT);
+      g_source_set_callback (data->timeout_source, utils_timeout_cb, data, NULL);
+      g_source_attach (data->timeout_source, data->main_context);
+      g_source_unref (data->timeout_source);
+    }
+
+  data->child_watch_source = g_child_watch_source_new (data->child_pid);
+  g_source_set_callback (data->child_watch_source, (GSourceFunc) utils_child_watch_cb, data, NULL);
+  g_source_attach (data->child_watch_source, data->main_context);
+  g_source_unref (data->child_watch_source);
+
+  data->child_stdout_channel = g_io_channel_unix_new (data->child_stdout_fd);
+  g_io_channel_set_flags (data->child_stdout_channel, G_IO_FLAG_NONBLOCK, NULL);
+  data->child_stdout_source = g_io_create_watch (data->child_stdout_channel, G_IO_IN);
+  g_source_set_callback (data->child_stdout_source, (GSourceFunc) utils_read_child_stdout, data, NULL);
+  g_source_attach (data->child_stdout_source, data->main_context);
+  g_source_unref (data->child_stdout_source);
+
+  data->child_stderr_channel = g_io_channel_unix_new (data->child_stderr_fd);
+  g_io_channel_set_flags (data->child_stderr_channel, G_IO_FLAG_NONBLOCK, NULL);
+  data->child_stderr_source = g_io_create_watch (data->child_stderr_channel, G_IO_IN);
+  g_source_set_callback (data->child_stderr_source, (GSourceFunc) utils_read_child_stderr, data, NULL);
+  g_source_attach (data->child_stderr_source, data->main_context);
+  g_source_unref (data->child_stderr_source);
+
+ out:
+  ;
+}
+
+gboolean
+utils_spawn_finish (GAsyncResult   *res,
+                    gint           *out_exit_status,
+                    gchar         **out_standard_output,
+                    gchar         **out_standard_error,
+                    GError        **error)
+{
+  GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
+  UtilsSpawnData *data;
+  gboolean ret = FALSE;
+
+  g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
+  g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
+
+  g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == utils_spawn);
+
+  if (g_simple_async_result_propagate_error (simple, error))
+    goto out;
+
+  data = g_simple_async_result_get_op_res_gpointer (simple);
+
+  if (data->timed_out)
+    {
+      g_set_error (error,
+                   G_IO_ERROR,
+                   G_IO_ERROR_TIMED_OUT,
+                   "Timed out after %d seconds",
+                   data->timeout_seconds);
+      goto out;
+    }
+
+  if (out_exit_status != NULL)
+    *out_exit_status = data->exit_status;
+
+  if (out_standard_output != NULL)
+    *out_standard_output = g_strdup (data->child_stdout->str);
+
+  if (out_standard_error != NULL)
+    *out_standard_error = g_strdup (data->child_stderr->str);
+
+  ret = TRUE;
+
+ out:
+  return ret;
+}
-- 
GitLab


From d74aad8152a7c51999fffa9abe28e4306a052399 Mon Sep 17 00:00:00 2001
From: Wu Xiaotian <yetist@gmail.com>
Date: Sun, 22 Nov 2020 13:15:17 +0800
Subject: [PATCH 02/17] check netgroup.h header file

Signed-off-by: Gustavo Lima Chaves <gustavo.chaves@microsoft.com>
---
 src/polkitbackend/polkitbackendduktapeauthority.c | 4 ++++
 1 file changed, 4 insertions(+)

diff --git a/src/polkitbackend/polkitbackendduktapeauthority.c b/src/polkitbackend/polkitbackendduktapeauthority.c
index ae98453..543d6fd 100644
--- a/src/polkitbackend/polkitbackendduktapeauthority.c
+++ b/src/polkitbackend/polkitbackendduktapeauthority.c
@@ -26,7 +26,11 @@
 #include <errno.h>
 #include <pwd.h>
 #include <grp.h>
+#ifdef HAVE_NETGROUP_H
+#include <netgroup.h>
+#else
 #include <netdb.h>
+#endif
 #include <string.h>
 #include <glib/gstdio.h>
 #include <locale.h>
-- 
GitLab


From 69c761506cbe458807e4ae2742c9e05bc60dad3d Mon Sep 17 00:00:00 2001
From: Wu Xiaotian <yetist@gmail.com>
Date: Sun, 22 Nov 2020 10:59:03 +0800
Subject: [PATCH 03/17] check return value

Signed-off-by: Gustavo Lima Chaves <gustavo.chaves@microsoft.com>
---
 src/polkitbackend/polkitbackendduktapeauthority.c | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)

diff --git a/src/polkitbackend/polkitbackendduktapeauthority.c b/src/polkitbackend/polkitbackendduktapeauthority.c
index 543d6fd..a54ed5b 100644
--- a/src/polkitbackend/polkitbackendduktapeauthority.c
+++ b/src/polkitbackend/polkitbackendduktapeauthority.c
@@ -249,7 +249,11 @@ reload_scripts (PolkitBackendJsAuthority *authority)
   duk_context *cx = authority->priv->cx;
 
   duk_set_top (cx, 0);
-  duk_get_global_string (cx, "polkit");
+  if (!duk_get_global_string (cx, "polkit")) {
+      polkit_backend_authority_log (POLKIT_BACKEND_AUTHORITY (authority),
+                                    "Error deleting old rules, not loading new ones");
+      return;
+  }
   duk_push_string (cx, "_deleteRules");
 
   duk_call_prop (cx, 0, 0);
-- 
GitLab


From f1536c4899934fd3c8243fda2d084a472fe57d2e Mon Sep 17 00:00:00 2001
From: Wu Xiaotian <yetist@gmail.com>
Date: Sun, 22 Nov 2020 11:22:39 +0800
Subject: [PATCH 04/17] check return value

Signed-off-by: Gustavo Lima Chaves <gustavo.chaves@microsoft.com>
---
 src/polkitbackend/polkitbackendduktapeauthority.c | 12 ++++++++++--
 1 file changed, 10 insertions(+), 2 deletions(-)

diff --git a/src/polkitbackend/polkitbackendduktapeauthority.c b/src/polkitbackend/polkitbackendduktapeauthority.c
index a54ed5b..1a7e6d3 100644
--- a/src/polkitbackend/polkitbackendduktapeauthority.c
+++ b/src/polkitbackend/polkitbackendduktapeauthority.c
@@ -656,7 +656,10 @@ push_action_and_details (duk_context               *cx,
   gchar **keys;
   guint n;
 
-  duk_get_global_string (cx, "Action");
+  if (!duk_get_global_string (cx, "Action")) {
+    return FALSE;
+  }
+
   duk_new (cx, 0);
 
   set_property_str (cx, "id", action_id);
@@ -699,7 +702,12 @@ polkit_backend_js_authority_get_admin_auth_identities (PolkitBackendInteractiveA
   duk_context *cx = authority->priv->cx;
 
   duk_set_top (cx, 0);
-  duk_get_global_string (cx, "polkit");
+  if (!duk_get_global_string (cx, "polkit")) {
+      polkit_backend_authority_log (POLKIT_BACKEND_AUTHORITY (authority),
+                                    "Error deleting old rules, not loading new ones");
+      goto out;
+  }
+
   duk_push_string (cx, "_runAdminRules");
 
   if (!push_action_and_details (cx, action_id, details, &error))
-- 
GitLab


From ca15eecf5dc7755947515c1bfc651fd8770aaf8f Mon Sep 17 00:00:00 2001
From: Wu Xiaotian <yetist@gmail.com>
Date: Sun, 22 Nov 2020 13:17:16 +0800
Subject: [PATCH 05/17] check return value

Signed-off-by: Gustavo Lima Chaves <gustavo.chaves@microsoft.com>
---
 src/polkitbackend/polkitbackendduktapeauthority.c | 10 ++++++++--
 1 file changed, 8 insertions(+), 2 deletions(-)

diff --git a/src/polkitbackend/polkitbackendduktapeauthority.c b/src/polkitbackend/polkitbackendduktapeauthority.c
index 1a7e6d3..3f1b32d 100644
--- a/src/polkitbackend/polkitbackendduktapeauthority.c
+++ b/src/polkitbackend/polkitbackendduktapeauthority.c
@@ -550,7 +550,10 @@ push_subject (duk_context               *cx,
   char *seat_str = NULL;
   char *session_str = NULL;
 
-  duk_get_global_string (cx, "Subject");
+  if (!duk_get_global_string (cx, "Subject")) {
+    return FALSE;
+  }
+
   duk_new (cx, 0);
 
   if (POLKIT_IS_UNIX_PROCESS (subject))
@@ -789,8 +792,11 @@ polkit_backend_js_authority_check_authorization_sync (PolkitBackendInteractiveAu
   gboolean good = FALSE;
   duk_context *cx = authority->priv->cx;
 
+  if (!duk_get_global_string (cx, "polkit")) {
+      goto out;
+  }
+
   duk_set_top (cx, 0);
-  duk_get_global_string (cx, "polkit");
   duk_push_string (cx, "_runRules");
 
   if (!push_action_and_details (cx, action_id, details, &error))
-- 
GitLab


From 870348365cc0166e14f28e0d144ed552bba4d794 Mon Sep 17 00:00:00 2001
From: Wu Xiaotian <yetist@gmail.com>
Date: Sun, 22 Nov 2020 13:18:13 +0800
Subject: [PATCH 06/17] check return value

Signed-off-by: Gustavo Lima Chaves <gustavo.chaves@microsoft.com>
---
 src/polkitbackend/polkitbackendduktapeauthority.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/src/polkitbackend/polkitbackendduktapeauthority.c b/src/polkitbackend/polkitbackendduktapeauthority.c
index 3f1b32d..6294ad9 100644
--- a/src/polkitbackend/polkitbackendduktapeauthority.c
+++ b/src/polkitbackend/polkitbackendduktapeauthority.c
@@ -843,7 +843,8 @@ polkit_backend_js_authority_check_authorization_sync (PolkitBackendInteractiveAu
  out:
   if (!good)
     ret = POLKIT_IMPLICIT_AUTHORIZATION_NOT_AUTHORIZED;
-  g_free (ret_str);
+  if (ret_str != NULL)
+      g_free (ret_str);
 
   return ret;
 }
-- 
GitLab


From 81c916ff08fdcee3c7340c4b2d4632086b89666c Mon Sep 17 00:00:00 2001
From: Wu Xiaotian <yetist@gmail.com>
Date: Sun, 22 Nov 2020 11:23:04 +0800
Subject: [PATCH 07/17] fix typecase

Signed-off-by: Gustavo Lima Chaves <gustavo.chaves@microsoft.com>
---
 src/polkitbackend/polkitbackendduktapeauthority.c | 10 +++++-----
 1 file changed, 5 insertions(+), 5 deletions(-)

diff --git a/src/polkitbackend/polkitbackendduktapeauthority.c b/src/polkitbackend/polkitbackendduktapeauthority.c
index 6294ad9..d466c9d 100644
--- a/src/polkitbackend/polkitbackendduktapeauthority.c
+++ b/src/polkitbackend/polkitbackendduktapeauthority.c
@@ -1191,7 +1191,7 @@ static void
 utils_on_cancelled (GCancellable *cancellable,
                     gpointer      user_data)
 {
-  UtilsSpawnData *data = user_data;
+  UtilsSpawnData *data = (UtilsSpawnData *)user_data;
   GError *error;
 
   error = NULL;
@@ -1206,7 +1206,7 @@ utils_read_child_stderr (GIOChannel *channel,
                          GIOCondition condition,
                          gpointer user_data)
 {
-  UtilsSpawnData *data = user_data;
+  UtilsSpawnData *data = (UtilsSpawnData *)user_data;
   gchar buf[1024];
   gsize bytes_read;
 
@@ -1220,7 +1220,7 @@ utils_read_child_stdout (GIOChannel *channel,
                          GIOCondition condition,
                          gpointer user_data)
 {
-  UtilsSpawnData *data = user_data;
+  UtilsSpawnData *data = (UtilsSpawnData *)user_data;
   gchar buf[1024];
   gsize bytes_read;
 
@@ -1234,7 +1234,7 @@ utils_child_watch_cb (GPid     pid,
                       gint     status,
                       gpointer user_data)
 {
-  UtilsSpawnData *data = user_data;
+  UtilsSpawnData *data = (UtilsSpawnData *)user_data;
   gchar *buf;
   gsize buf_size;
 
@@ -1263,7 +1263,7 @@ utils_child_watch_cb (GPid     pid,
 static gboolean
 utils_timeout_cb (gpointer user_data)
 {
-  UtilsSpawnData *data = user_data;
+  UtilsSpawnData *data = (UtilsSpawnData *)user_data;
 
   data->timed_out = TRUE;
 
-- 
GitLab


From acb956bf52f0a78bf7aaf925876f96e97a146995 Mon Sep 17 00:00:00 2001
From: Wu Xiaotian <yetist@gmail.com>
Date: Sun, 22 Nov 2020 18:04:27 +0800
Subject: [PATCH 08/17] typecase

Signed-off-by: Gustavo Lima Chaves <gustavo.chaves@microsoft.com>
---
 src/polkitbackend/polkitbackendduktapeauthority.c | 10 +++++-----
 1 file changed, 5 insertions(+), 5 deletions(-)

diff --git a/src/polkitbackend/polkitbackendduktapeauthority.c b/src/polkitbackend/polkitbackendduktapeauthority.c
index d466c9d..237b1ad 100644
--- a/src/polkitbackend/polkitbackendduktapeauthority.c
+++ b/src/polkitbackend/polkitbackendduktapeauthority.c
@@ -915,8 +915,8 @@ spawn_cb (GObject       *source_object,
           GAsyncResult  *res,
           gpointer       user_data)
 {
-  SpawnData *data = user_data;
-  data->res = g_object_ref (res);
+  SpawnData *data = (SpawnData *)user_data;
+  data->res = (GAsyncResult*)g_object_ref (res);
   g_main_loop_quit (data->loop);
 }
 
@@ -1292,12 +1292,12 @@ utils_spawn (const gchar *const  *argv,
   data->simple = g_simple_async_result_new (NULL,
                                             callback,
                                             user_data,
-                                            utils_spawn);
+                                            (gpointer*)utils_spawn);
   data->main_context = g_main_context_get_thread_default ();
   if (data->main_context != NULL)
     g_main_context_ref (data->main_context);
 
-  data->cancellable = cancellable != NULL ? g_object_ref (cancellable) : NULL;
+  data->cancellable = cancellable != NULL ? (GCancellable*)g_object_ref (cancellable) : NULL;
 
   data->child_stdout = g_string_new (NULL);
   data->child_stderr = g_string_new (NULL);
@@ -1397,7 +1397,7 @@ utils_spawn_finish (GAsyncResult   *res,
   if (g_simple_async_result_propagate_error (simple, error))
     goto out;
 
-  data = g_simple_async_result_get_op_res_gpointer (simple);
+  data = (UtilsSpawnData*)g_simple_async_result_get_op_res_gpointer (simple);
 
   if (data->timed_out)
     {
-- 
GitLab


From be060e4d48aceb09af34868b555b6c73c7afdabb Mon Sep 17 00:00:00 2001
From: Wu Xiaotian <yetist@gmail.com>
Date: Sun, 22 Nov 2020 13:53:23 +0800
Subject: [PATCH 09/17] some change

Signed-off-by: Gustavo Lima Chaves <gustavo.chaves@microsoft.com>
---
 .../polkitbackendduktapeauthority.c           | 26 +++++++++++--------
 1 file changed, 15 insertions(+), 11 deletions(-)

diff --git a/src/polkitbackend/polkitbackendduktapeauthority.c b/src/polkitbackend/polkitbackendduktapeauthority.c
index 237b1ad..fad9017 100644
--- a/src/polkitbackend/polkitbackendduktapeauthority.c
+++ b/src/polkitbackend/polkitbackendduktapeauthority.c
@@ -207,18 +207,22 @@ load_scripts (PolkitBackendJsAuthority  *authority)
 
   for (l = files; l != NULL; l = l->next)
     {
-      const gchar *filename = l->data;
-
+      const gchar *filename = (gchar *)l->data;
 #if (DUK_VERSION >= 20000)
-      gchar *contents;
-      gsize length;
-      GError *error = NULL;
-      if (!g_file_get_contents (filename, &contents, &length, &error)){
-        g_warning("Error when file contents of %s: %s\n", filename, error->message);
-        g_error_free (error);
-        continue;
-      }
-      if (duk_peval_lstring_noresult(cx, contents,length) != 0)
+      GFile *file = g_file_new_for_path (filename);
+      char *contents;
+      gsize len;
+      if (!g_file_load_contents (file, NULL, &contents, &len, NULL, NULL))
+        {
+          polkit_backend_authority_log (POLKIT_BACKEND_AUTHORITY (authority),
+                                        "Error compiling script %s",
+                                        filename);
+          g_object_unref (file);
+          continue;
+        }
+
+      g_object_unref (file);
+      if (duk_peval_lstring_noresult(cx, contents,len) != 0)
 #else
       if (duk_peval_file_noresult (cx, filename) != 0)
 #endif
-- 
GitLab


From 2ffb62048a5ebedfe3bb053feb7385c7270ede28 Mon Sep 17 00:00:00 2001
From: Wu Xiaotian <yetist@gmail.com>
Date: Sun, 22 Nov 2020 15:25:45 +0800
Subject: [PATCH 10/17] some change

Signed-off-by: Gustavo Lima Chaves <gustavo.chaves@microsoft.com>
---
 .../polkitbackendduktapeauthority.c           | 24 +++++++++----------
 1 file changed, 12 insertions(+), 12 deletions(-)

diff --git a/src/polkitbackend/polkitbackendduktapeauthority.c b/src/polkitbackend/polkitbackendduktapeauthority.c
index fad9017..6fac3be 100644
--- a/src/polkitbackend/polkitbackendduktapeauthority.c
+++ b/src/polkitbackend/polkitbackendduktapeauthority.c
@@ -125,6 +125,18 @@ G_DEFINE_TYPE (PolkitBackendJsAuthority, polkit_backend_js_authority, POLKIT_BAC
 
 /* ---------------------------------------------------------------------------------------------------- */
 
+static duk_ret_t js_polkit_log (duk_context *cx);
+static duk_ret_t js_polkit_spawn (duk_context *cx);
+static duk_ret_t js_polkit_user_is_in_netgroup (duk_context *cx);
+
+static const duk_function_list_entry js_polkit_functions[] =
+{
+  { "log", js_polkit_log, 1 },
+  { "spawn", js_polkit_spawn, 1 },
+  { "_userIsInNetGroup", js_polkit_user_is_in_netgroup, 2 },
+  { NULL, NULL, 0 },
+};
+
 static void
 polkit_backend_js_authority_init (PolkitBackendJsAuthority *authority)
 {
@@ -347,18 +359,6 @@ setup_file_monitors (PolkitBackendJsAuthority *authority)
   authority->priv->dir_monitors = (GFileMonitor**) g_ptr_array_free (p, FALSE);
 }
 
-static duk_ret_t js_polkit_log (duk_context *cx);
-static duk_ret_t js_polkit_spawn (duk_context *cx);
-static duk_ret_t js_polkit_user_is_in_netgroup (duk_context *cx);
-
-static const duk_function_list_entry js_polkit_functions[] =
-{
-  { "log", js_polkit_log, 1 },
-  { "spawn", js_polkit_spawn, 1 },
-  { "_userIsInNetGroup", js_polkit_user_is_in_netgroup, 2 },
-  { NULL, NULL, 0 },
-};
-
 static void
 polkit_backend_js_authority_constructed (GObject *object)
 {
-- 
GitLab


From edb70ef69eed3275f5654510d135e680eb46c85d Mon Sep 17 00:00:00 2001
From: Wu Xiaotian <yetist@gmail.com>
Date: Sun, 22 Nov 2020 15:25:35 +0800
Subject: [PATCH 11/17] remove WATCHDOG_TIMEOUT define

Signed-off-by: Gustavo Lima Chaves <gustavo.chaves@microsoft.com>
---
 src/polkitbackend/polkitbackendduktapeauthority.c | 1 -
 1 file changed, 1 deletion(-)

diff --git a/src/polkitbackend/polkitbackendduktapeauthority.c b/src/polkitbackend/polkitbackendduktapeauthority.c
index 6fac3be..51e03fd 100644
--- a/src/polkitbackend/polkitbackendduktapeauthority.c
+++ b/src/polkitbackend/polkitbackendduktapeauthority.c
@@ -69,7 +69,6 @@ struct _PolkitBackendJsAuthorityPrivate
   duk_context *cx;
 };
 
-#define WATCHDOG_TIMEOUT (15 * G_TIME_SPAN_SECOND)
 
 static void utils_spawn (const gchar *const  *argv,
                          guint                timeout_seconds,
-- 
GitLab


From 906ae404f29f15ef8c529b999bf091b5d18ed7ac Mon Sep 17 00:00:00 2001
From: Wu Xiaotian <yetist@gmail.com>
Date: Sun, 22 Nov 2020 12:46:40 +0800
Subject: [PATCH 12/17] add meson build system support

Signed-off-by: Gustavo Lima Chaves <gustavo.chaves@microsoft.com>
---
 meson.build                   | 11 ++++++++++-
 meson_options.txt             |  1 +
 src/polkitbackend/meson.build | 10 ++++++++--
 3 files changed, 19 insertions(+), 3 deletions(-)

diff --git a/meson.build b/meson.build
index 858078d..4e44723 100644
--- a/meson.build
+++ b/meson.build
@@ -133,7 +133,13 @@ expat_dep = dependency('expat')
 assert(cc.has_header('expat.h', dependencies: expat_dep), 'Can\'t find expat.h. Please install expat.')
 assert(cc.has_function('XML_ParserCreate', dependencies: expat_dep), 'Can\'t find expat library. Please install expat.')
 
-mozjs_dep = dependency('mozjs-78')
+js_engine = get_option('js_engine')
+if js_engine == 'duktape'
+  js_dep = dependency('duktape')
+  libm_dep = cc.find_library('m')
+elif js_engine == 'mozjs'
+  js_dep = dependency('mozjs-78')
+endif
 
 dbus_dep = dependency('dbus-1', required: false)
 dbus_policydir = pk_prefix / pk_datadir / 'dbus-1/system.d'
@@ -361,6 +367,9 @@ if enable_logind
   output += '        systemdsystemunitdir:     ' + systemd_systemdsystemunitdir + '\n'
 endif
 output += '        polkitd user:             ' + polkitd_user + ' \n'
+output += '        Javascript engine:        ' + js_engine + '\n'
+if enable_logind
+endif
 output += '        PAM support:              ' + enable_pam.to_string() + '\n\n'
 if enable_pam
   output += '        PAM file auth:            ' + pam_conf['PAM_FILE_INCLUDE_AUTH'] + '\n'
diff --git a/meson_options.txt b/meson_options.txt
index 25e3e77..76aa311 100644
--- a/meson_options.txt
+++ b/meson_options.txt
@@ -16,3 +16,4 @@ option('introspection', type: 'boolean', value: true, description: 'Enable intro
 
 option('gtk_doc', type: 'boolean', value: false, description: 'use gtk-doc to build documentation')
 option('man', type: 'boolean', value: false, description: 'build manual pages')
+option('js_engine', type: 'combo', choices: ['mozjs', 'duktape'], value: 'duktape', description: 'javascript engine')
diff --git a/src/polkitbackend/meson.build b/src/polkitbackend/meson.build
index 64f0e4a..489897d 100644
--- a/src/polkitbackend/meson.build
+++ b/src/polkitbackend/meson.build
@@ -5,7 +5,6 @@ sources = files(
   'polkitbackendactionpool.c',
   'polkitbackendauthority.c',
   'polkitbackendinteractiveauthority.c',
-  'polkitbackendjsauthority.cpp',
 )
 
 output = 'initjs.h'
@@ -21,7 +20,7 @@ sources += custom_target(
 deps = [
   expat_dep,
   libpolkit_gobject_dep,
-  mozjs_dep,
+  js_dep,
 ]
 
 c_flags = [
@@ -31,6 +30,13 @@ c_flags = [
   '-DPACKAGE_SYSCONF_DIR="@0@"'.format(pk_prefix / pk_sysconfdir),
 ]
 
+if js_engine == 'duktape'
+  sources += files('polkitbackendduktapeauthority.c')
+  deps += libm_dep
+elif js_engine == 'mozjs'
+  sources += files('polkitbackendjsauthority.cpp')
+endif
+
 if enable_logind
   sources += files('polkitbackendsessionmonitor-systemd.c')
 
-- 
GitLab


From 1380b505c25be4aebe54b1b4223a570d64af83cc Mon Sep 17 00:00:00 2001
From: Wu Xiaotian <yetist@gmail.com>
Date: Sun, 22 Nov 2020 18:49:14 +0800
Subject: [PATCH 13/17] fix run error

Signed-off-by: Gustavo Lima Chaves <gustavo.chaves@microsoft.com>
---
 src/polkitbackend/polkitbackendduktapeauthority.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/src/polkitbackend/polkitbackendduktapeauthority.c b/src/polkitbackend/polkitbackendduktapeauthority.c
index 51e03fd..4b4f8fd 100644
--- a/src/polkitbackend/polkitbackendduktapeauthority.c
+++ b/src/polkitbackend/polkitbackendduktapeauthority.c
@@ -795,11 +795,11 @@ polkit_backend_js_authority_check_authorization_sync (PolkitBackendInteractiveAu
   gboolean good = FALSE;
   duk_context *cx = authority->priv->cx;
 
+  duk_set_top (cx, 0);
   if (!duk_get_global_string (cx, "polkit")) {
       goto out;
   }
 
-  duk_set_top (cx, 0);
   duk_push_string (cx, "_runRules");
 
   if (!push_action_and_details (cx, action_id, details, &error))
-- 
GitLab


From 6856a704b70378948ef5f66e9b09555d97d4070b Mon Sep 17 00:00:00 2001
From: Gustavo Lima Chaves <gustavo.chaves@microsoft.com>
Date: Fri, 10 Sep 2021 15:17:58 -0700
Subject: [PATCH 14/17] Deduplicate code for "Add duktape as JS engine backend"
 effort/MR

This leverages Wu Xiaotian (@yetist)'s original MR
(https://gitlab.freedesktop.org/polkit/polkit/-/merge_requests/35), in
an effort to complete said work.

This is the first of the requests from maintainers--to reduce
eliminate code duplication.

The runaway-killer missing functionality will come in the sequence.

Signed-off-by: Gustavo Lima Chaves <gustavo.chaves@microsoft.com>
---
 src/polkitbackend/Makefile.am                 |   1 +
 src/polkitbackend/meson.build                 |   1 +
 src/polkitbackend/polkitbackendcommon.c       | 530 +++++++++++++
 src/polkitbackend/polkitbackendcommon.h       | 156 ++++
 .../polkitbackendduktapeauthority.c           | 714 ++----------------
 .../polkitbackendjsauthority.cpp              | 711 ++---------------
 6 files changed, 790 insertions(+), 1323 deletions(-)
 create mode 100644 src/polkitbackend/polkitbackendcommon.c
 create mode 100644 src/polkitbackend/polkitbackendcommon.h

diff --git a/src/polkitbackend/Makefile.am b/src/polkitbackend/Makefile.am
index abcbc6f..6a8b4ae 100644
--- a/src/polkitbackend/Makefile.am
+++ b/src/polkitbackend/Makefile.am
@@ -31,6 +31,7 @@ libpolkit_backend_1_la_SOURCES =                                   			\
         polkitbackend.h									\
 	polkitbackendtypes.h								\
 	polkitbackendprivate.h								\
+	polkitbackendcommon.h			polkitbackendcommon.c			\
 	polkitbackendauthority.h		polkitbackendauthority.c		\
 	polkitbackendinteractiveauthority.h	polkitbackendinteractiveauthority.c	\
 	polkitbackendjsauthority.h				\
diff --git a/src/polkitbackend/meson.build b/src/polkitbackend/meson.build
index 489897d..9ec01b2 100644
--- a/src/polkitbackend/meson.build
+++ b/src/polkitbackend/meson.build
@@ -4,6 +4,7 @@ sources = files(
   'polkitbackendactionlookup.c',
   'polkitbackendactionpool.c',
   'polkitbackendauthority.c',
+  'polkitbackendcommon.c',
   'polkitbackendinteractiveauthority.c',
 )
 
diff --git a/src/polkitbackend/polkitbackendcommon.c b/src/polkitbackend/polkitbackendcommon.c
new file mode 100644
index 0000000..6783dff
--- /dev/null
+++ b/src/polkitbackend/polkitbackendcommon.c
@@ -0,0 +1,530 @@
+/*
+ * Copyright (C) 2008 Red Hat, Inc.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General
+ * Public License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
+ * Boston, MA 02111-1307, USA.
+ *
+ * Author: David Zeuthen <davidz@redhat.com>
+ */
+
+#include "polkitbackendcommon.h"
+
+static void
+utils_child_watch_from_release_cb (GPid     pid,
+                                   gint     status,
+                                   gpointer user_data)
+{
+}
+
+static void
+utils_spawn_data_free (UtilsSpawnData *data)
+{
+  if (data->timeout_source != NULL)
+    {
+      g_source_destroy (data->timeout_source);
+      data->timeout_source = NULL;
+    }
+
+  /* Nuke the child, if necessary */
+  if (data->child_watch_source != NULL)
+    {
+      g_source_destroy (data->child_watch_source);
+      data->child_watch_source = NULL;
+    }
+
+  if (data->child_pid != 0)
+    {
+      GSource *source;
+      kill (data->child_pid, SIGTERM);
+      /* OK, we need to reap for the child ourselves - we don't want
+       * to use waitpid() because that might block the calling
+       * thread (the child might handle SIGTERM and use several
+       * seconds for cleanup/rollback).
+       *
+       * So we use GChildWatch instead.
+       *
+       * Avoid taking a references to ourselves. but note that we need
+       * to pass the GSource so we can nuke it once handled.
+       */
+      source = g_child_watch_source_new (data->child_pid);
+      g_source_set_callback (source,
+                             (GSourceFunc) utils_child_watch_from_release_cb,
+                             source,
+                             (GDestroyNotify) g_source_destroy);
+      g_source_attach (source, data->main_context);
+      g_source_unref (source);
+      data->child_pid = 0;
+    }
+
+  if (data->child_stdout != NULL)
+    {
+      g_string_free (data->child_stdout, TRUE);
+      data->child_stdout = NULL;
+    }
+
+  if (data->child_stderr != NULL)
+    {
+      g_string_free (data->child_stderr, TRUE);
+      data->child_stderr = NULL;
+    }
+
+  if (data->child_stdout_channel != NULL)
+    {
+      g_io_channel_unref (data->child_stdout_channel);
+      data->child_stdout_channel = NULL;
+    }
+  if (data->child_stderr_channel != NULL)
+    {
+      g_io_channel_unref (data->child_stderr_channel);
+      data->child_stderr_channel = NULL;
+    }
+
+  if (data->child_stdout_source != NULL)
+    {
+      g_source_destroy (data->child_stdout_source);
+      data->child_stdout_source = NULL;
+    }
+  if (data->child_stderr_source != NULL)
+    {
+      g_source_destroy (data->child_stderr_source);
+      data->child_stderr_source = NULL;
+    }
+
+  if (data->child_stdout_fd != -1)
+    {
+      g_warn_if_fail (close (data->child_stdout_fd) == 0);
+      data->child_stdout_fd = -1;
+    }
+  if (data->child_stderr_fd != -1)
+    {
+      g_warn_if_fail (close (data->child_stderr_fd) == 0);
+      data->child_stderr_fd = -1;
+    }
+
+  if (data->cancellable_handler_id > 0)
+    {
+      g_cancellable_disconnect (data->cancellable, data->cancellable_handler_id);
+      data->cancellable_handler_id = 0;
+    }
+
+  if (data->main_context != NULL)
+    g_main_context_unref (data->main_context);
+
+  if (data->cancellable != NULL)
+    g_object_unref (data->cancellable);
+
+  g_slice_free (UtilsSpawnData, data);
+}
+
+/* called in the thread where @cancellable was cancelled */
+static void
+utils_on_cancelled (GCancellable *cancellable,
+                    gpointer      user_data)
+{
+  UtilsSpawnData *data = (UtilsSpawnData *)user_data;
+  GError *error;
+
+  error = NULL;
+  g_warn_if_fail (g_cancellable_set_error_if_cancelled (cancellable, &error));
+  g_simple_async_result_take_error (data->simple, error);
+  g_simple_async_result_complete_in_idle (data->simple);
+  g_object_unref (data->simple);
+}
+
+static gboolean
+utils_timeout_cb (gpointer user_data)
+{
+  UtilsSpawnData *data = (UtilsSpawnData *)user_data;
+
+  data->timed_out = TRUE;
+
+  /* ok, timeout is history, make sure we don't free it in spawn_data_free() */
+  data->timeout_source = NULL;
+
+  /* we're done */
+  g_simple_async_result_complete_in_idle (data->simple);
+  g_object_unref (data->simple);
+
+  return FALSE; /* remove source */
+}
+
+static void
+utils_child_watch_cb (GPid     pid,
+                      gint     status,
+                      gpointer user_data)
+{
+  UtilsSpawnData *data = (UtilsSpawnData *)user_data;
+  gchar *buf;
+  gsize buf_size;
+
+  if (g_io_channel_read_to_end (data->child_stdout_channel, &buf, &buf_size, NULL) == G_IO_STATUS_NORMAL)
+    {
+      g_string_append_len (data->child_stdout, buf, buf_size);
+      g_free (buf);
+    }
+  if (g_io_channel_read_to_end (data->child_stderr_channel, &buf, &buf_size, NULL) == G_IO_STATUS_NORMAL)
+    {
+      g_string_append_len (data->child_stderr, buf, buf_size);
+      g_free (buf);
+    }
+
+  data->exit_status = status;
+
+  /* ok, child watch is history, make sure we don't free it in spawn_data_free() */
+  data->child_pid = 0;
+  data->child_watch_source = NULL;
+
+  /* we're done */
+  g_simple_async_result_complete_in_idle (data->simple);
+  g_object_unref (data->simple);
+}
+
+static gboolean
+utils_read_child_stderr (GIOChannel *channel,
+                         GIOCondition condition,
+                         gpointer user_data)
+{
+  UtilsSpawnData *data = (UtilsSpawnData *)user_data;
+  gchar buf[1024];
+  gsize bytes_read;
+
+  g_io_channel_read_chars (channel, buf, sizeof buf, &bytes_read, NULL);
+  g_string_append_len (data->child_stderr, buf, bytes_read);
+  return TRUE;
+}
+
+static gboolean
+utils_read_child_stdout (GIOChannel *channel,
+                         GIOCondition condition,
+                         gpointer user_data)
+{
+  UtilsSpawnData *data = (UtilsSpawnData *)user_data;
+  gchar buf[1024];
+  gsize bytes_read;
+
+  g_io_channel_read_chars (channel, buf, sizeof buf, &bytes_read, NULL);
+  g_string_append_len (data->child_stdout, buf, bytes_read);
+  return TRUE;
+}
+
+void
+polkit_backend_common_spawn (const gchar *const  *argv,
+                             guint                timeout_seconds,
+                             GCancellable        *cancellable,
+                             GAsyncReadyCallback  callback,
+                             gpointer             user_data)
+{
+  UtilsSpawnData *data;
+  GError *error;
+
+  data = g_slice_new0 (UtilsSpawnData);
+  data->timeout_seconds = timeout_seconds;
+  data->simple = g_simple_async_result_new (NULL,
+                                            callback,
+                                            user_data,
+                                            (gpointer*)polkit_backend_common_spawn);
+  data->main_context = g_main_context_get_thread_default ();
+  if (data->main_context != NULL)
+    g_main_context_ref (data->main_context);
+
+  data->cancellable = cancellable != NULL ? (GCancellable*)g_object_ref (cancellable) : NULL;
+
+  data->child_stdout = g_string_new (NULL);
+  data->child_stderr = g_string_new (NULL);
+  data->child_stdout_fd = -1;
+  data->child_stderr_fd = -1;
+
+  /* the life-cycle of UtilsSpawnData is tied to its GSimpleAsyncResult */
+  g_simple_async_result_set_op_res_gpointer (data->simple, data, (GDestroyNotify) utils_spawn_data_free);
+
+  error = NULL;
+  if (data->cancellable != NULL)
+    {
+      /* could already be cancelled */
+      error = NULL;
+      if (g_cancellable_set_error_if_cancelled (data->cancellable, &error))
+        {
+          g_simple_async_result_take_error (data->simple, error);
+          g_simple_async_result_complete_in_idle (data->simple);
+          g_object_unref (data->simple);
+          goto out;
+        }
+
+      data->cancellable_handler_id = g_cancellable_connect (data->cancellable,
+                                                            G_CALLBACK (utils_on_cancelled),
+                                                            data,
+                                                            NULL);
+    }
+
+  error = NULL;
+  if (!g_spawn_async_with_pipes (NULL, /* working directory */
+                                 (gchar **) argv,
+                                 NULL, /* envp */
+                                 G_SPAWN_SEARCH_PATH | G_SPAWN_DO_NOT_REAP_CHILD,
+                                 NULL, /* child_setup */
+                                 NULL, /* child_setup's user_data */
+                                 &(data->child_pid),
+                                 NULL, /* gint *stdin_fd */
+                                 &(data->child_stdout_fd),
+                                 &(data->child_stderr_fd),
+                                 &error))
+    {
+      g_prefix_error (&error, "Error spawning: ");
+      g_simple_async_result_take_error (data->simple, error);
+      g_simple_async_result_complete_in_idle (data->simple);
+      g_object_unref (data->simple);
+      goto out;
+    }
+
+  if (timeout_seconds > 0)
+    {
+      data->timeout_source = g_timeout_source_new_seconds (timeout_seconds);
+      g_source_set_priority (data->timeout_source, G_PRIORITY_DEFAULT);
+      g_source_set_callback (data->timeout_source, utils_timeout_cb, data, NULL);
+      g_source_attach (data->timeout_source, data->main_context);
+      g_source_unref (data->timeout_source);
+    }
+
+  data->child_watch_source = g_child_watch_source_new (data->child_pid);
+  g_source_set_callback (data->child_watch_source, (GSourceFunc) utils_child_watch_cb, data, NULL);
+  g_source_attach (data->child_watch_source, data->main_context);
+  g_source_unref (data->child_watch_source);
+
+  data->child_stdout_channel = g_io_channel_unix_new (data->child_stdout_fd);
+  g_io_channel_set_flags (data->child_stdout_channel, G_IO_FLAG_NONBLOCK, NULL);
+  data->child_stdout_source = g_io_create_watch (data->child_stdout_channel, G_IO_IN);
+  g_source_set_callback (data->child_stdout_source, (GSourceFunc) utils_read_child_stdout, data, NULL);
+  g_source_attach (data->child_stdout_source, data->main_context);
+  g_source_unref (data->child_stdout_source);
+
+  data->child_stderr_channel = g_io_channel_unix_new (data->child_stderr_fd);
+  g_io_channel_set_flags (data->child_stderr_channel, G_IO_FLAG_NONBLOCK, NULL);
+  data->child_stderr_source = g_io_create_watch (data->child_stderr_channel, G_IO_IN);
+  g_source_set_callback (data->child_stderr_source, (GSourceFunc) utils_read_child_stderr, data, NULL);
+  g_source_attach (data->child_stderr_source, data->main_context);
+  g_source_unref (data->child_stderr_source);
+
+ out:
+  ;
+}
+
+void
+polkit_backend_common_on_dir_monitor_changed (GFileMonitor     *monitor,
+                                              GFile            *file,
+                                              GFile            *other_file,
+                                              GFileMonitorEvent event_type,
+                                              gpointer          user_data)
+{
+  PolkitBackendJsAuthority *authority = POLKIT_BACKEND_JS_AUTHORITY (user_data);
+
+  /* TODO: maybe rate-limit so storms of events are collapsed into one with a 500ms resolution?
+   *       Because when editing a file with emacs we get 4-8 events..
+   */
+
+  if (file != NULL)
+    {
+      gchar *name;
+
+      name = g_file_get_basename (file);
+
+      /* g_print ("event_type=%d file=%p name=%s\n", event_type, file, name); */
+      if (!g_str_has_prefix (name, ".") &&
+          !g_str_has_prefix (name, "#") &&
+          g_str_has_suffix (name, ".rules") &&
+          (event_type == G_FILE_MONITOR_EVENT_CREATED ||
+           event_type == G_FILE_MONITOR_EVENT_DELETED ||
+           event_type == G_FILE_MONITOR_EVENT_CHANGES_DONE_HINT))
+        {
+          polkit_backend_authority_log (POLKIT_BACKEND_AUTHORITY (authority),
+                                        "Reloading rules");
+          polkit_backend_common_reload_scripts (authority);
+        }
+      g_free (name);
+    }
+}
+
+gboolean
+polkit_backend_common_spawn_finish (GAsyncResult   *res,
+                                    gint           *out_exit_status,
+                                    gchar         **out_standard_output,
+                                    gchar         **out_standard_error,
+                                    GError        **error)
+{
+  GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
+  UtilsSpawnData *data;
+  gboolean ret = FALSE;
+
+  g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
+  g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
+
+  g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == polkit_backend_common_spawn);
+
+  if (g_simple_async_result_propagate_error (simple, error))
+    goto out;
+
+  data = (UtilsSpawnData*)g_simple_async_result_get_op_res_gpointer (simple);
+
+  if (data->timed_out)
+    {
+      g_set_error (error,
+                   G_IO_ERROR,
+                   G_IO_ERROR_TIMED_OUT,
+                   "Timed out after %d seconds",
+                   data->timeout_seconds);
+      goto out;
+    }
+
+  if (out_exit_status != NULL)
+    *out_exit_status = data->exit_status;
+
+  if (out_standard_output != NULL)
+    *out_standard_output = g_strdup (data->child_stdout->str);
+
+  if (out_standard_error != NULL)
+    *out_standard_error = g_strdup (data->child_stderr->str);
+
+  ret = TRUE;
+
+ out:
+  return ret;
+}
+
+static const gchar *
+polkit_backend_js_authority_get_name (PolkitBackendAuthority *authority)
+{
+  return "js";
+}
+
+static const gchar *
+polkit_backend_js_authority_get_version (PolkitBackendAuthority *authority)
+{
+  return PACKAGE_VERSION;
+}
+
+static PolkitAuthorityFeatures
+polkit_backend_js_authority_get_features (PolkitBackendAuthority *authority)
+{
+  return POLKIT_AUTHORITY_FEATURES_TEMPORARY_AUTHORIZATION;
+}
+
+void
+polkit_backend_common_js_authority_class_init_common (PolkitBackendJsAuthorityClass *klass)
+{
+  GObjectClass *gobject_class;
+  PolkitBackendAuthorityClass *authority_class;
+  PolkitBackendInteractiveAuthorityClass *interactive_authority_class;
+
+  gobject_class = G_OBJECT_CLASS (klass);
+  gobject_class->finalize                               = polkit_backend_common_js_authority_finalize;
+  gobject_class->set_property                           = polkit_backend_common_js_authority_set_property;
+  gobject_class->constructed                            = polkit_backend_common_js_authority_constructed;
+
+  authority_class = POLKIT_BACKEND_AUTHORITY_CLASS (klass);
+  authority_class->get_name                             = polkit_backend_js_authority_get_name;
+  authority_class->get_version                          = polkit_backend_js_authority_get_version;
+  authority_class->get_features                         = polkit_backend_js_authority_get_features;
+
+  interactive_authority_class = POLKIT_BACKEND_INTERACTIVE_AUTHORITY_CLASS (klass);
+  interactive_authority_class->get_admin_identities     = polkit_backend_common_js_authority_get_admin_auth_identities;
+  interactive_authority_class->check_authorization_sync = polkit_backend_common_js_authority_check_authorization_sync;
+
+  g_object_class_install_property (gobject_class,
+                                   PROP_RULES_DIRS,
+                                   g_param_spec_boxed ("rules-dirs",
+                                                       NULL,
+                                                       NULL,
+                                                       G_TYPE_STRV,
+                                                       G_PARAM_CONSTRUCT_ONLY | G_PARAM_WRITABLE));
+}
+
+gint
+polkit_backend_common_rules_file_name_cmp (const gchar *a,
+                                           const gchar *b)
+{
+  gint ret;
+  const gchar *a_base;
+  const gchar *b_base;
+
+  a_base = strrchr (a, '/');
+  b_base = strrchr (b, '/');
+
+  g_assert (a_base != NULL);
+  g_assert (b_base != NULL);
+  a_base += 1;
+  b_base += 1;
+
+  ret = g_strcmp0 (a_base, b_base);
+  if (ret == 0)
+    {
+      /* /etc wins over /usr */
+      ret = g_strcmp0 (a, b);
+      g_assert (ret != 0);
+    }
+
+  return ret;
+}
+
+const gchar *
+polkit_backend_common_get_signal_name (gint signal_number)
+{
+  switch (signal_number)
+    {
+#define _HANDLE_SIG(sig) case sig: return #sig;
+    _HANDLE_SIG (SIGHUP);
+    _HANDLE_SIG (SIGINT);
+    _HANDLE_SIG (SIGQUIT);
+    _HANDLE_SIG (SIGILL);
+    _HANDLE_SIG (SIGABRT);
+    _HANDLE_SIG (SIGFPE);
+    _HANDLE_SIG (SIGKILL);
+    _HANDLE_SIG (SIGSEGV);
+    _HANDLE_SIG (SIGPIPE);
+    _HANDLE_SIG (SIGALRM);
+    _HANDLE_SIG (SIGTERM);
+    _HANDLE_SIG (SIGUSR1);
+    _HANDLE_SIG (SIGUSR2);
+    _HANDLE_SIG (SIGCHLD);
+    _HANDLE_SIG (SIGCONT);
+    _HANDLE_SIG (SIGSTOP);
+    _HANDLE_SIG (SIGTSTP);
+    _HANDLE_SIG (SIGTTIN);
+    _HANDLE_SIG (SIGTTOU);
+    _HANDLE_SIG (SIGBUS);
+#ifdef SIGPOLL
+    _HANDLE_SIG (SIGPOLL);
+#endif
+    _HANDLE_SIG (SIGPROF);
+    _HANDLE_SIG (SIGSYS);
+    _HANDLE_SIG (SIGTRAP);
+    _HANDLE_SIG (SIGURG);
+    _HANDLE_SIG (SIGVTALRM);
+    _HANDLE_SIG (SIGXCPU);
+    _HANDLE_SIG (SIGXFSZ);
+#undef _HANDLE_SIG
+    default:
+      break;
+    }
+  return "UNKNOWN_SIGNAL";
+}
+
+void
+polkit_backend_common_spawn_cb (GObject       *source_object,
+                                GAsyncResult  *res,
+                                gpointer       user_data)
+{
+  SpawnData *data = (SpawnData *)user_data;
+  data->res = (GAsyncResult*)g_object_ref (res);
+  g_main_loop_quit (data->loop);
+}
diff --git a/src/polkitbackend/polkitbackendcommon.h b/src/polkitbackend/polkitbackendcommon.h
new file mode 100644
index 0000000..6d0d267
--- /dev/null
+++ b/src/polkitbackend/polkitbackendcommon.h
@@ -0,0 +1,156 @@
+/*
+ * Copyright (C) 2008 Red Hat, Inc.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General
+ * Public License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
+ * Boston, MA 02111-1307, USA.
+ *
+ * Author: David Zeuthen <davidz@redhat.com>
+ */
+
+#if !defined (_POLKIT_BACKEND_COMPILATION) && !defined(_POLKIT_BACKEND_INSIDE_POLKIT_BACKEND_H)
+#error "Only <polkitbackend/polkitbackend.h> can be included directly, this file may disappear or change contents."
+#endif
+
+#ifndef __POLKIT_BACKEND_COMMON_H
+#define __POLKIT_BACKEND_COMMON_H
+
+#include "config.h"
+#include <sys/wait.h>
+#include <errno.h>
+#include <pwd.h>
+#include <grp.h>
+#ifdef HAVE_NETGROUP_H
+#include <netgroup.h>
+#else
+#include <netdb.h>
+#endif
+#include <string.h>
+#include <glib/gstdio.h>
+#include <locale.h>
+#include <glib/gi18n-lib.h> //here, all things glib via glib.h (including -> gspawn.h)
+
+#include <polkit/polkit.h>
+#include "polkitbackendjsauthority.h"
+
+#include <polkit/polkitprivate.h>
+
+#ifdef HAVE_LIBSYSTEMD
+#include <systemd/sd-login.h>
+#endif /* HAVE_LIBSYSTEMD */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+enum
+{
+  PROP_0,
+  PROP_RULES_DIRS,
+};
+
+typedef struct
+{
+  GSimpleAsyncResult *simple; /* borrowed reference */
+  GMainContext *main_context; /* may be NULL */
+
+  GCancellable *cancellable;  /* may be NULL */
+  gulong cancellable_handler_id;
+
+  GPid child_pid;
+  gint child_stdout_fd;
+  gint child_stderr_fd;
+
+  GIOChannel *child_stdout_channel;
+  GIOChannel *child_stderr_channel;
+
+  GSource *child_watch_source;
+  GSource *child_stdout_source;
+  GSource *child_stderr_source;
+
+  guint timeout_seconds;
+  gboolean timed_out;
+  GSource *timeout_source;
+
+  GString *child_stdout;
+  GString *child_stderr;
+
+  gint exit_status;
+} UtilsSpawnData;
+
+typedef struct
+{
+  GMainLoop *loop;
+  GAsyncResult *res;
+} SpawnData;
+
+void polkit_backend_common_spawn (const gchar *const  *argv,
+                                  guint                timeout_seconds,
+                                  GCancellable        *cancellable,
+                                  GAsyncReadyCallback  callback,
+                                  gpointer             user_data);
+void polkit_backend_common_spawn_cb (GObject       *source_object,
+                                     GAsyncResult  *res,
+                                     gpointer       user_data);
+gboolean polkit_backend_common_spawn_finish (GAsyncResult   *res,
+                                             gint           *out_exit_status,
+                                             gchar         **out_standard_output,
+                                             gchar         **out_standard_error,
+                                             GError        **error);
+
+void polkit_backend_common_on_dir_monitor_changed (GFileMonitor     *monitor,
+                                                   GFile            *file,
+                                                   GFile            *other_file,
+                                                   GFileMonitorEvent event_type,
+                                                   gpointer          user_data);
+
+void polkit_backend_common_js_authority_class_init_common (PolkitBackendJsAuthorityClass *klass);
+
+gint polkit_backend_common_rules_file_name_cmp (const gchar *a,
+                                                const gchar *b);
+
+const gchar *polkit_backend_common_get_signal_name (gint signal_number);
+
+/* To be provided by each JS backend, from here onwards  ---------------------------------------------- */
+
+void polkit_backend_common_reload_scripts (PolkitBackendJsAuthority *authority);
+void polkit_backend_common_js_authority_finalize (GObject *object);
+void polkit_backend_common_js_authority_constructed (GObject *object);
+GList *polkit_backend_common_js_authority_get_admin_auth_identities (PolkitBackendInteractiveAuthority *_authority,
+                                                                     PolkitSubject                     *caller,
+                                                                     PolkitSubject                     *subject,
+                                                                     PolkitIdentity                    *user_for_subject,
+                                                                     gboolean                           subject_is_local,
+                                                                     gboolean                           subject_is_active,
+                                                                     const gchar                       *action_id,
+                                                                     PolkitDetails                     *details);
+void polkit_backend_common_js_authority_set_property (GObject      *object,
+                                                      guint         property_id,
+                                                      const GValue *value,
+                                                      GParamSpec   *pspec);
+PolkitImplicitAuthorization polkit_backend_common_js_authority_check_authorization_sync (PolkitBackendInteractiveAuthority *_authority,
+                                                                                         PolkitSubject                     *caller,
+                                                                                         PolkitSubject                     *subject,
+                                                                                         PolkitIdentity                    *user_for_subject,
+                                                                                         gboolean                           subject_is_local,
+                                                                                         gboolean                           subject_is_active,
+                                                                                         const gchar                       *action_id,
+                                                                                         PolkitDetails                     *details,
+                                                                                         PolkitImplicitAuthorization        implicit);
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __POLKIT_BACKEND_COMMON_H */
+
diff --git a/src/polkitbackend/polkitbackendduktapeauthority.c b/src/polkitbackend/polkitbackendduktapeauthority.c
index 4b4f8fd..a2b4420 100644
--- a/src/polkitbackend/polkitbackendduktapeauthority.c
+++ b/src/polkitbackend/polkitbackendduktapeauthority.c
@@ -21,32 +21,12 @@
  * Author: David Zeuthen <davidz@redhat.com>
  */
 
-#include "config.h"
-#include <sys/wait.h>
-#include <errno.h>
-#include <pwd.h>
-#include <grp.h>
-#ifdef HAVE_NETGROUP_H
-#include <netgroup.h>
-#else
-#include <netdb.h>
-#endif
-#include <string.h>
-#include <glib/gstdio.h>
-#include <locale.h>
-#include <glib/gi18n-lib.h>
-
-#include <polkit/polkit.h>
-#include "polkitbackendjsauthority.h"
-
-#include <polkit/polkitprivate.h>
+#include "polkitbackendcommon.h"
 
-#ifdef HAVE_LIBSYSTEMD
-#include <systemd/sd-login.h>
-#endif /* HAVE_LIBSYSTEMD */
+#include "duktape.h"
 
+/* Built source and not too big to worry about deduplication */
 #include "initjs.h" /* init.js */
-#include "duktape.h"
 
 /**
  * SECTION:polkitbackendjsauthority
@@ -54,10 +34,9 @@
  * @short_description: JS Authority
  * @stability: Unstable
  *
- * An implementation of #PolkitBackendAuthority that reads and
- * evalates Javascript files and supports interaction with
- * authentication agents (virtue of being based on
- * #PolkitBackendInteractiveAuthority).
+ * An (Duktape-based) implementation of #PolkitBackendAuthority that reads and
+ * evaluates Javascript files and supports interaction with authentication
+ * agents (virtue of being based on #PolkitBackendInteractiveAuthority).
  */
 
 /* ---------------------------------------------------------------------------------------------------- */
@@ -66,64 +45,16 @@ struct _PolkitBackendJsAuthorityPrivate
 {
   gchar **rules_dirs;
   GFileMonitor **dir_monitors; /* NULL-terminated array of GFileMonitor instances */
-  duk_context *cx;
-};
-
-
-static void utils_spawn (const gchar *const  *argv,
-                         guint                timeout_seconds,
-                         GCancellable        *cancellable,
-                         GAsyncReadyCallback  callback,
-                         gpointer             user_data);
-
-gboolean utils_spawn_finish (GAsyncResult   *res,
-                             gint           *out_exit_status,
-                             gchar         **out_standard_output,
-                             gchar         **out_standard_error,
-                             GError        **error);
 
-static void on_dir_monitor_changed (GFileMonitor     *monitor,
-                                    GFile            *file,
-                                    GFile            *other_file,
-                                    GFileMonitorEvent event_type,
-                                    gpointer          user_data);
-
-/* ---------------------------------------------------------------------------------------------------- */
-
-enum
-{
-  PROP_0,
-  PROP_RULES_DIRS,
+  duk_context *cx;
 };
 
 /* ---------------------------------------------------------------------------------------------------- */
 
-static GList *polkit_backend_js_authority_get_admin_auth_identities (PolkitBackendInteractiveAuthority *authority,
-                                                                     PolkitSubject                     *caller,
-                                                                     PolkitSubject                     *subject,
-                                                                     PolkitIdentity                    *user_for_subject,
-                                                                     gboolean                           subject_is_local,
-                                                                     gboolean                           subject_is_active,
-                                                                     const gchar                       *action_id,
-                                                                     PolkitDetails                     *details);
-
-static PolkitImplicitAuthorization polkit_backend_js_authority_check_authorization_sync (
-                                                          PolkitBackendInteractiveAuthority *authority,
-                                                          PolkitSubject                     *caller,
-                                                          PolkitSubject                     *subject,
-                                                          PolkitIdentity                    *user_for_subject,
-                                                          gboolean                           subject_is_local,
-                                                          gboolean                           subject_is_active,
-                                                          const gchar                       *action_id,
-                                                          PolkitDetails                     *details,
-                                                          PolkitImplicitAuthorization        implicit);
-
 G_DEFINE_TYPE (PolkitBackendJsAuthority, polkit_backend_js_authority, POLKIT_BACKEND_TYPE_INTERACTIVE_AUTHORITY);
 
 /* ---------------------------------------------------------------------------------------------------- */
 
-/* ---------------------------------------------------------------------------------------------------- */
-
 static duk_ret_t js_polkit_log (duk_context *cx);
 static duk_ret_t js_polkit_spawn (duk_context *cx);
 static duk_ret_t js_polkit_user_is_in_netgroup (duk_context *cx);
@@ -144,33 +75,6 @@ polkit_backend_js_authority_init (PolkitBackendJsAuthority *authority)
                                                  PolkitBackendJsAuthorityPrivate);
 }
 
-static gint
-rules_file_name_cmp (const gchar *a,
-                     const gchar *b)
-{
-  gint ret;
-  const gchar *a_base;
-  const gchar *b_base;
-
-  a_base = strrchr (a, '/');
-  b_base = strrchr (b, '/');
-
-  g_assert (a_base != NULL);
-  g_assert (b_base != NULL);
-  a_base += 1;
-  b_base += 1;
-
-  ret = g_strcmp0 (a_base, b_base);
-  if (ret == 0)
-    {
-      /* /etc wins over /usr */
-      ret = g_strcmp0 (a, b);
-      g_assert (ret != 0);
-    }
-
-  return ret;
-}
-
 static void
 load_scripts (PolkitBackendJsAuthority  *authority)
 {
@@ -214,7 +118,7 @@ load_scripts (PolkitBackendJsAuthority  *authority)
         }
     }
 
-  files = g_list_sort (files, (GCompareFunc) rules_file_name_cmp);
+  files = g_list_sort (files, (GCompareFunc) polkit_backend_common_rules_file_name_cmp);
 
   for (l = files; l != NULL; l = l->next)
     {
@@ -258,8 +162,8 @@ load_scripts (PolkitBackendJsAuthority  *authority)
   g_list_free_full (files, g_free);
 }
 
-static void
-reload_scripts (PolkitBackendJsAuthority *authority)
+void
+polkit_backend_common_reload_scripts (PolkitBackendJsAuthority *authority)
 {
   duk_context *cx = authority->priv->cx;
 
@@ -282,42 +186,6 @@ reload_scripts (PolkitBackendJsAuthority *authority)
   g_signal_emit_by_name (authority, "changed");
 }
 
-static void
-on_dir_monitor_changed (GFileMonitor     *monitor,
-                        GFile            *file,
-                        GFile            *other_file,
-                        GFileMonitorEvent event_type,
-                        gpointer          user_data)
-{
-  PolkitBackendJsAuthority *authority = POLKIT_BACKEND_JS_AUTHORITY (user_data);
-
-  /* TODO: maybe rate-limit so storms of events are collapsed into one with a 500ms resolution?
-   *       Because when editing a file with emacs we get 4-8 events..
-   */
-
-  if (file != NULL)
-    {
-      gchar *name;
-
-      name = g_file_get_basename (file);
-
-      /* g_print ("event_type=%d file=%p name=%s\n", event_type, file, name); */
-      if (!g_str_has_prefix (name, ".") &&
-          !g_str_has_prefix (name, "#") &&
-          g_str_has_suffix (name, ".rules") &&
-          (event_type == G_FILE_MONITOR_EVENT_CREATED ||
-           event_type == G_FILE_MONITOR_EVENT_DELETED ||
-           event_type == G_FILE_MONITOR_EVENT_CHANGES_DONE_HINT))
-        {
-          polkit_backend_authority_log (POLKIT_BACKEND_AUTHORITY (authority),
-                                        "Reloading rules");
-          reload_scripts (authority);
-        }
-      g_free (name);
-    }
-}
-
-
 static void
 setup_file_monitors (PolkitBackendJsAuthority *authority)
 {
@@ -349,7 +217,7 @@ setup_file_monitors (PolkitBackendJsAuthority *authority)
         {
           g_signal_connect (monitor,
                             "changed",
-                            G_CALLBACK (on_dir_monitor_changed),
+                            G_CALLBACK (polkit_backend_common_on_dir_monitor_changed),
                             authority);
           g_ptr_array_add (p, monitor);
         }
@@ -358,8 +226,8 @@ setup_file_monitors (PolkitBackendJsAuthority *authority)
   authority->priv->dir_monitors = (GFileMonitor**) g_ptr_array_free (p, FALSE);
 }
 
-static void
-polkit_backend_js_authority_constructed (GObject *object)
+void
+polkit_backend_common_js_authority_constructed (GObject *object)
 {
   PolkitBackendJsAuthority *authority = POLKIT_BACKEND_JS_AUTHORITY (object);
   duk_context *cx;
@@ -395,8 +263,8 @@ polkit_backend_js_authority_constructed (GObject *object)
   g_assert_not_reached ();
 }
 
-static void
-polkit_backend_js_authority_finalize (GObject *object)
+void
+polkit_backend_common_js_authority_finalize (GObject *object)
 {
   PolkitBackendJsAuthority *authority = POLKIT_BACKEND_JS_AUTHORITY (object);
   guint n;
@@ -405,7 +273,7 @@ polkit_backend_js_authority_finalize (GObject *object)
     {
       GFileMonitor *monitor = authority->priv->dir_monitors[n];
       g_signal_handlers_disconnect_by_func (monitor,
-                                            G_CALLBACK (on_dir_monitor_changed),
+                                            G_CALLBACK (polkit_backend_common_on_dir_monitor_changed),
                                             authority);
       g_object_unref (monitor);
     }
@@ -417,11 +285,11 @@ polkit_backend_js_authority_finalize (GObject *object)
   G_OBJECT_CLASS (polkit_backend_js_authority_parent_class)->finalize (object);
 }
 
-static void
-polkit_backend_js_authority_set_property (GObject      *object,
-                                          guint         property_id,
-                                          const GValue *value,
-                                          GParamSpec   *pspec)
+void
+polkit_backend_common_js_authority_set_property (GObject      *object,
+                                                 guint         property_id,
+                                                 const GValue *value,
+                                                 GParamSpec   *pspec)
 {
   PolkitBackendJsAuthority *authority = POLKIT_BACKEND_JS_AUTHORITY (object);
 
@@ -438,55 +306,10 @@ polkit_backend_js_authority_set_property (GObject      *object,
     }
 }
 
-static const gchar *
-polkit_backend_js_authority_get_name (PolkitBackendAuthority *authority)
-{
-  return "js";
-}
-
-static const gchar *
-polkit_backend_js_authority_get_version (PolkitBackendAuthority *authority)
-{
-  return PACKAGE_VERSION;
-}
-
-static PolkitAuthorityFeatures
-polkit_backend_js_authority_get_features (PolkitBackendAuthority *authority)
-{
-  return POLKIT_AUTHORITY_FEATURES_TEMPORARY_AUTHORIZATION;
-}
-
 static void
 polkit_backend_js_authority_class_init (PolkitBackendJsAuthorityClass *klass)
 {
-  GObjectClass *gobject_class;
-  PolkitBackendAuthorityClass *authority_class;
-  PolkitBackendInteractiveAuthorityClass *interactive_authority_class;
-
-
-  gobject_class = G_OBJECT_CLASS (klass);
-  gobject_class->finalize                               = polkit_backend_js_authority_finalize;
-  gobject_class->set_property                           = polkit_backend_js_authority_set_property;
-  gobject_class->constructed                            = polkit_backend_js_authority_constructed;
-
-  authority_class = POLKIT_BACKEND_AUTHORITY_CLASS (klass);
-  authority_class->get_name                             = polkit_backend_js_authority_get_name;
-  authority_class->get_version                          = polkit_backend_js_authority_get_version;
-  authority_class->get_features                         = polkit_backend_js_authority_get_features;
-
-  interactive_authority_class = POLKIT_BACKEND_INTERACTIVE_AUTHORITY_CLASS (klass);
-  interactive_authority_class->get_admin_identities     = polkit_backend_js_authority_get_admin_auth_identities;
-  interactive_authority_class->check_authorization_sync = polkit_backend_js_authority_check_authorization_sync;
-
-  g_object_class_install_property (gobject_class,
-                                   PROP_RULES_DIRS,
-                                   g_param_spec_boxed ("rules-dirs",
-                                                       NULL,
-                                                       NULL,
-                                                       G_TYPE_STRV,
-                                                       G_PARAM_CONSTRUCT_ONLY | G_PARAM_WRITABLE));
-
-
+  polkit_backend_common_js_authority_class_init_common (klass);
   g_type_class_add_private (klass, sizeof (PolkitBackendJsAuthorityPrivate));
 }
 
@@ -689,15 +512,15 @@ push_action_and_details (duk_context               *cx,
 
 /* ---------------------------------------------------------------------------------------------------- */
 
-static GList *
-polkit_backend_js_authority_get_admin_auth_identities (PolkitBackendInteractiveAuthority *_authority,
-                                                       PolkitSubject                     *caller,
-                                                       PolkitSubject                     *subject,
-                                                       PolkitIdentity                    *user_for_subject,
-                                                       gboolean                           subject_is_local,
-                                                       gboolean                           subject_is_active,
-                                                       const gchar                       *action_id,
-                                                       PolkitDetails                     *details)
+GList *
+polkit_backend_common_js_authority_get_admin_auth_identities (PolkitBackendInteractiveAuthority *_authority,
+                                                              PolkitSubject                     *caller,
+                                                              PolkitSubject                     *subject,
+                                                              PolkitIdentity                    *user_for_subject,
+                                                              gboolean                           subject_is_local,
+                                                              gboolean                           subject_is_active,
+                                                              const gchar                       *action_id,
+                                                              PolkitDetails                     *details)
 {
   PolkitBackendJsAuthority *authority = POLKIT_BACKEND_JS_AUTHORITY (_authority);
   GList *ret = NULL;
@@ -777,16 +600,16 @@ polkit_backend_js_authority_get_admin_auth_identities (PolkitBackendInteractiveA
 
 /* ---------------------------------------------------------------------------------------------------- */
 
-static PolkitImplicitAuthorization
-polkit_backend_js_authority_check_authorization_sync (PolkitBackendInteractiveAuthority *_authority,
-                                                      PolkitSubject                     *caller,
-                                                      PolkitSubject                     *subject,
-                                                      PolkitIdentity                    *user_for_subject,
-                                                      gboolean                           subject_is_local,
-                                                      gboolean                           subject_is_active,
-                                                      const gchar                       *action_id,
-                                                      PolkitDetails                     *details,
-                                                      PolkitImplicitAuthorization        implicit)
+PolkitImplicitAuthorization
+polkit_backend_common_js_authority_check_authorization_sync (PolkitBackendInteractiveAuthority *_authority,
+                                                             PolkitSubject                     *caller,
+                                                             PolkitSubject                     *subject,
+                                                             PolkitIdentity                    *user_for_subject,
+                                                             gboolean                           subject_is_local,
+                                                             gboolean                           subject_is_active,
+                                                             const gchar                       *action_id,
+                                                             PolkitDetails                     *details,
+                                                             PolkitImplicitAuthorization        implicit)
 {
   PolkitBackendJsAuthority *authority = POLKIT_BACKEND_JS_AUTHORITY (_authority);
   PolkitImplicitAuthorization ret = implicit;
@@ -864,65 +687,6 @@ js_polkit_log (duk_context *cx)
 
 /* ---------------------------------------------------------------------------------------------------- */
 
-static const gchar *
-get_signal_name (gint signal_number)
-{
-  switch (signal_number)
-    {
-#define _HANDLE_SIG(sig) case sig: return #sig;
-    _HANDLE_SIG (SIGHUP);
-    _HANDLE_SIG (SIGINT);
-    _HANDLE_SIG (SIGQUIT);
-    _HANDLE_SIG (SIGILL);
-    _HANDLE_SIG (SIGABRT);
-    _HANDLE_SIG (SIGFPE);
-    _HANDLE_SIG (SIGKILL);
-    _HANDLE_SIG (SIGSEGV);
-    _HANDLE_SIG (SIGPIPE);
-    _HANDLE_SIG (SIGALRM);
-    _HANDLE_SIG (SIGTERM);
-    _HANDLE_SIG (SIGUSR1);
-    _HANDLE_SIG (SIGUSR2);
-    _HANDLE_SIG (SIGCHLD);
-    _HANDLE_SIG (SIGCONT);
-    _HANDLE_SIG (SIGSTOP);
-    _HANDLE_SIG (SIGTSTP);
-    _HANDLE_SIG (SIGTTIN);
-    _HANDLE_SIG (SIGTTOU);
-    _HANDLE_SIG (SIGBUS);
-#ifdef SIGPOLL
-    _HANDLE_SIG (SIGPOLL);
-#endif
-    _HANDLE_SIG (SIGPROF);
-    _HANDLE_SIG (SIGSYS);
-    _HANDLE_SIG (SIGTRAP);
-    _HANDLE_SIG (SIGURG);
-    _HANDLE_SIG (SIGVTALRM);
-    _HANDLE_SIG (SIGXCPU);
-    _HANDLE_SIG (SIGXFSZ);
-#undef _HANDLE_SIG
-    default:
-      break;
-    }
-  return "UNKNOWN_SIGNAL";
-}
-
-typedef struct
-{
-  GMainLoop *loop;
-  GAsyncResult *res;
-} SpawnData;
-
-static void
-spawn_cb (GObject       *source_object,
-          GAsyncResult  *res,
-          gpointer       user_data)
-{
-  SpawnData *data = (SpawnData *)user_data;
-  data->res = (GAsyncResult*)g_object_ref (res);
-  g_main_loop_quit (data->loop);
-}
-
 static duk_ret_t
 js_polkit_spawn (duk_context *cx)
 {
@@ -962,21 +726,21 @@ js_polkit_spawn (duk_context *cx)
   g_main_context_push_thread_default (context);
 
   data.loop = loop;
-  utils_spawn ((const gchar *const *) argv,
-               10, /* timeout_seconds */
-               NULL, /* cancellable */
-               spawn_cb,
-               &data);
+  polkit_backend_common_spawn ((const gchar *const *) argv,
+                               10, /* timeout_seconds */
+                               NULL, /* cancellable */
+                               polkit_backend_common_spawn_cb,
+                               &data);
 
   g_main_loop_run (loop);
 
   g_main_context_pop_thread_default (context);
 
-  if (!utils_spawn_finish (data.res,
-                           &exit_status,
-                           &standard_output,
-                           &standard_error,
-                           &error))
+  if (!polkit_backend_common_spawn_finish (data.res,
+                                           &exit_status,
+                                           &standard_output,
+                                           &standard_error,
+                                           &error))
     {
       err_str = g_strdup_printf ("Error spawning helper: %s (%s, %d)",
                                  error->message, g_quark_to_string (error->domain), error->code);
@@ -998,7 +762,7 @@ js_polkit_spawn (duk_context *cx)
         {
           g_string_append_printf (gstr,
                                   "Helper was signaled with signal %s (%d)",
-                                  get_signal_name (WTERMSIG (exit_status)),
+                                  polkit_backend_common_get_signal_name (WTERMSIG (exit_status)),
                                   WTERMSIG (exit_status));
         }
       g_string_append_printf (gstr, ", stdout=`%s', stderr=`%s'",
@@ -1052,377 +816,3 @@ js_polkit_user_is_in_netgroup (duk_context *cx)
 }
 
 /* ---------------------------------------------------------------------------------------------------- */
-
-typedef struct
-{
-  GSimpleAsyncResult *simple; /* borrowed reference */
-  GMainContext *main_context; /* may be NULL */
-
-  GCancellable *cancellable;  /* may be NULL */
-  gulong cancellable_handler_id;
-
-  GPid child_pid;
-  gint child_stdout_fd;
-  gint child_stderr_fd;
-
-  GIOChannel *child_stdout_channel;
-  GIOChannel *child_stderr_channel;
-
-  GSource *child_watch_source;
-  GSource *child_stdout_source;
-  GSource *child_stderr_source;
-
-  guint timeout_seconds;
-  gboolean timed_out;
-  GSource *timeout_source;
-
-  GString *child_stdout;
-  GString *child_stderr;
-
-  gint exit_status;
-} UtilsSpawnData;
-
-static void
-utils_child_watch_from_release_cb (GPid     pid,
-                                   gint     status,
-                                   gpointer user_data)
-{
-}
-
-static void
-utils_spawn_data_free (UtilsSpawnData *data)
-{
-  if (data->timeout_source != NULL)
-    {
-      g_source_destroy (data->timeout_source);
-      data->timeout_source = NULL;
-    }
-
-  /* Nuke the child, if necessary */
-  if (data->child_watch_source != NULL)
-    {
-      g_source_destroy (data->child_watch_source);
-      data->child_watch_source = NULL;
-    }
-
-  if (data->child_pid != 0)
-    {
-      GSource *source;
-      kill (data->child_pid, SIGTERM);
-      /* OK, we need to reap for the child ourselves - we don't want
-       * to use waitpid() because that might block the calling
-       * thread (the child might handle SIGTERM and use several
-       * seconds for cleanup/rollback).
-       *
-       * So we use GChildWatch instead.
-       *
-       * Avoid taking a references to ourselves. but note that we need
-       * to pass the GSource so we can nuke it once handled.
-       */
-      source = g_child_watch_source_new (data->child_pid);
-      g_source_set_callback (source,
-                             (GSourceFunc) utils_child_watch_from_release_cb,
-                             source,
-                             (GDestroyNotify) g_source_destroy);
-      g_source_attach (source, data->main_context);
-      g_source_unref (source);
-      data->child_pid = 0;
-    }
-
-  if (data->child_stdout != NULL)
-    {
-      g_string_free (data->child_stdout, TRUE);
-      data->child_stdout = NULL;
-    }
-
-  if (data->child_stderr != NULL)
-    {
-      g_string_free (data->child_stderr, TRUE);
-      data->child_stderr = NULL;
-    }
-
-  if (data->child_stdout_channel != NULL)
-    {
-      g_io_channel_unref (data->child_stdout_channel);
-      data->child_stdout_channel = NULL;
-    }
-  if (data->child_stderr_channel != NULL)
-    {
-      g_io_channel_unref (data->child_stderr_channel);
-      data->child_stderr_channel = NULL;
-    }
-
-  if (data->child_stdout_source != NULL)
-    {
-      g_source_destroy (data->child_stdout_source);
-      data->child_stdout_source = NULL;
-    }
-  if (data->child_stderr_source != NULL)
-    {
-      g_source_destroy (data->child_stderr_source);
-      data->child_stderr_source = NULL;
-    }
-
-  if (data->child_stdout_fd != -1)
-    {
-      g_warn_if_fail (close (data->child_stdout_fd) == 0);
-      data->child_stdout_fd = -1;
-    }
-  if (data->child_stderr_fd != -1)
-    {
-      g_warn_if_fail (close (data->child_stderr_fd) == 0);
-      data->child_stderr_fd = -1;
-    }
-
-  if (data->cancellable_handler_id > 0)
-    {
-      g_cancellable_disconnect (data->cancellable, data->cancellable_handler_id);
-      data->cancellable_handler_id = 0;
-    }
-
-  if (data->main_context != NULL)
-    g_main_context_unref (data->main_context);
-
-  if (data->cancellable != NULL)
-    g_object_unref (data->cancellable);
-
-  g_slice_free (UtilsSpawnData, data);
-}
-
-/* called in the thread where @cancellable was cancelled */
-static void
-utils_on_cancelled (GCancellable *cancellable,
-                    gpointer      user_data)
-{
-  UtilsSpawnData *data = (UtilsSpawnData *)user_data;
-  GError *error;
-
-  error = NULL;
-  g_warn_if_fail (g_cancellable_set_error_if_cancelled (cancellable, &error));
-  g_simple_async_result_take_error (data->simple, error);
-  g_simple_async_result_complete_in_idle (data->simple);
-  g_object_unref (data->simple);
-}
-
-static gboolean
-utils_read_child_stderr (GIOChannel *channel,
-                         GIOCondition condition,
-                         gpointer user_data)
-{
-  UtilsSpawnData *data = (UtilsSpawnData *)user_data;
-  gchar buf[1024];
-  gsize bytes_read;
-
-  g_io_channel_read_chars (channel, buf, sizeof buf, &bytes_read, NULL);
-  g_string_append_len (data->child_stderr, buf, bytes_read);
-  return TRUE;
-}
-
-static gboolean
-utils_read_child_stdout (GIOChannel *channel,
-                         GIOCondition condition,
-                         gpointer user_data)
-{
-  UtilsSpawnData *data = (UtilsSpawnData *)user_data;
-  gchar buf[1024];
-  gsize bytes_read;
-
-  g_io_channel_read_chars (channel, buf, sizeof buf, &bytes_read, NULL);
-  g_string_append_len (data->child_stdout, buf, bytes_read);
-  return TRUE;
-}
-
-static void
-utils_child_watch_cb (GPid     pid,
-                      gint     status,
-                      gpointer user_data)
-{
-  UtilsSpawnData *data = (UtilsSpawnData *)user_data;
-  gchar *buf;
-  gsize buf_size;
-
-  if (g_io_channel_read_to_end (data->child_stdout_channel, &buf, &buf_size, NULL) == G_IO_STATUS_NORMAL)
-    {
-      g_string_append_len (data->child_stdout, buf, buf_size);
-      g_free (buf);
-    }
-  if (g_io_channel_read_to_end (data->child_stderr_channel, &buf, &buf_size, NULL) == G_IO_STATUS_NORMAL)
-    {
-      g_string_append_len (data->child_stderr, buf, buf_size);
-      g_free (buf);
-    }
-
-  data->exit_status = status;
-
-  /* ok, child watch is history, make sure we don't free it in spawn_data_free() */
-  data->child_pid = 0;
-  data->child_watch_source = NULL;
-
-  /* we're done */
-  g_simple_async_result_complete_in_idle (data->simple);
-  g_object_unref (data->simple);
-}
-
-static gboolean
-utils_timeout_cb (gpointer user_data)
-{
-  UtilsSpawnData *data = (UtilsSpawnData *)user_data;
-
-  data->timed_out = TRUE;
-
-  /* ok, timeout is history, make sure we don't free it in spawn_data_free() */
-  data->timeout_source = NULL;
-
-  /* we're done */
-  g_simple_async_result_complete_in_idle (data->simple);
-  g_object_unref (data->simple);
-
-  return FALSE; /* remove source */
-}
-
-static void
-utils_spawn (const gchar *const  *argv,
-             guint                timeout_seconds,
-             GCancellable        *cancellable,
-             GAsyncReadyCallback  callback,
-             gpointer             user_data)
-{
-  UtilsSpawnData *data;
-  GError *error;
-
-  data = g_slice_new0 (UtilsSpawnData);
-  data->timeout_seconds = timeout_seconds;
-  data->simple = g_simple_async_result_new (NULL,
-                                            callback,
-                                            user_data,
-                                            (gpointer*)utils_spawn);
-  data->main_context = g_main_context_get_thread_default ();
-  if (data->main_context != NULL)
-    g_main_context_ref (data->main_context);
-
-  data->cancellable = cancellable != NULL ? (GCancellable*)g_object_ref (cancellable) : NULL;
-
-  data->child_stdout = g_string_new (NULL);
-  data->child_stderr = g_string_new (NULL);
-  data->child_stdout_fd = -1;
-  data->child_stderr_fd = -1;
-
-  /* the life-cycle of UtilsSpawnData is tied to its GSimpleAsyncResult */
-  g_simple_async_result_set_op_res_gpointer (data->simple, data, (GDestroyNotify) utils_spawn_data_free);
-
-  error = NULL;
-  if (data->cancellable != NULL)
-    {
-      /* could already be cancelled */
-      error = NULL;
-      if (g_cancellable_set_error_if_cancelled (data->cancellable, &error))
-        {
-          g_simple_async_result_take_error (data->simple, error);
-          g_simple_async_result_complete_in_idle (data->simple);
-          g_object_unref (data->simple);
-          goto out;
-        }
-
-      data->cancellable_handler_id = g_cancellable_connect (data->cancellable,
-                                                            G_CALLBACK (utils_on_cancelled),
-                                                            data,
-                                                            NULL);
-    }
-
-  error = NULL;
-  if (!g_spawn_async_with_pipes (NULL, /* working directory */
-                                 (gchar **) argv,
-                                 NULL, /* envp */
-                                 G_SPAWN_SEARCH_PATH | G_SPAWN_DO_NOT_REAP_CHILD,
-                                 NULL, /* child_setup */
-                                 NULL, /* child_setup's user_data */
-                                 &(data->child_pid),
-                                 NULL, /* gint *stdin_fd */
-                                 &(data->child_stdout_fd),
-                                 &(data->child_stderr_fd),
-                                 &error))
-    {
-      g_prefix_error (&error, "Error spawning: ");
-      g_simple_async_result_take_error (data->simple, error);
-      g_simple_async_result_complete_in_idle (data->simple);
-      g_object_unref (data->simple);
-      goto out;
-    }
-
-  if (timeout_seconds > 0)
-    {
-      data->timeout_source = g_timeout_source_new_seconds (timeout_seconds);
-      g_source_set_priority (data->timeout_source, G_PRIORITY_DEFAULT);
-      g_source_set_callback (data->timeout_source, utils_timeout_cb, data, NULL);
-      g_source_attach (data->timeout_source, data->main_context);
-      g_source_unref (data->timeout_source);
-    }
-
-  data->child_watch_source = g_child_watch_source_new (data->child_pid);
-  g_source_set_callback (data->child_watch_source, (GSourceFunc) utils_child_watch_cb, data, NULL);
-  g_source_attach (data->child_watch_source, data->main_context);
-  g_source_unref (data->child_watch_source);
-
-  data->child_stdout_channel = g_io_channel_unix_new (data->child_stdout_fd);
-  g_io_channel_set_flags (data->child_stdout_channel, G_IO_FLAG_NONBLOCK, NULL);
-  data->child_stdout_source = g_io_create_watch (data->child_stdout_channel, G_IO_IN);
-  g_source_set_callback (data->child_stdout_source, (GSourceFunc) utils_read_child_stdout, data, NULL);
-  g_source_attach (data->child_stdout_source, data->main_context);
-  g_source_unref (data->child_stdout_source);
-
-  data->child_stderr_channel = g_io_channel_unix_new (data->child_stderr_fd);
-  g_io_channel_set_flags (data->child_stderr_channel, G_IO_FLAG_NONBLOCK, NULL);
-  data->child_stderr_source = g_io_create_watch (data->child_stderr_channel, G_IO_IN);
-  g_source_set_callback (data->child_stderr_source, (GSourceFunc) utils_read_child_stderr, data, NULL);
-  g_source_attach (data->child_stderr_source, data->main_context);
-  g_source_unref (data->child_stderr_source);
-
- out:
-  ;
-}
-
-gboolean
-utils_spawn_finish (GAsyncResult   *res,
-                    gint           *out_exit_status,
-                    gchar         **out_standard_output,
-                    gchar         **out_standard_error,
-                    GError        **error)
-{
-  GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
-  UtilsSpawnData *data;
-  gboolean ret = FALSE;
-
-  g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
-  g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
-
-  g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == utils_spawn);
-
-  if (g_simple_async_result_propagate_error (simple, error))
-    goto out;
-
-  data = (UtilsSpawnData*)g_simple_async_result_get_op_res_gpointer (simple);
-
-  if (data->timed_out)
-    {
-      g_set_error (error,
-                   G_IO_ERROR,
-                   G_IO_ERROR_TIMED_OUT,
-                   "Timed out after %d seconds",
-                   data->timeout_seconds);
-      goto out;
-    }
-
-  if (out_exit_status != NULL)
-    *out_exit_status = data->exit_status;
-
-  if (out_standard_output != NULL)
-    *out_standard_output = g_strdup (data->child_stdout->str);
-
-  if (out_standard_error != NULL)
-    *out_standard_error = g_strdup (data->child_stderr->str);
-
-  ret = TRUE;
-
- out:
-  return ret;
-}
diff --git a/src/polkitbackend/polkitbackendjsauthority.cpp b/src/polkitbackend/polkitbackendjsauthority.cpp
index ca17108..e28091d 100644
--- a/src/polkitbackend/polkitbackendjsauthority.cpp
+++ b/src/polkitbackend/polkitbackendjsauthority.cpp
@@ -19,29 +19,7 @@
  * Author: David Zeuthen <davidz@redhat.com>
  */
 
-#include "config.h"
-#include <sys/wait.h>
-#include <errno.h>
-#include <pwd.h>
-#include <grp.h>
-#ifdef HAVE_NETGROUP_H
-#include <netgroup.h>
-#else
-#include <netdb.h>
-#endif
-#include <string.h>
-#include <glib/gstdio.h>
-#include <locale.h>
-#include <glib/gi18n-lib.h>
-
-#include <polkit/polkit.h>
-#include "polkitbackendjsauthority.h"
-
-#include <polkit/polkitprivate.h>
-
-#ifdef HAVE_LIBSYSTEMD
-#include <systemd/sd-login.h>
-#endif /* HAVE_LIBSYSTEMD */
+#include "polkitbackendcommon.h"
 
 #include <js/CompilationAndEvaluation.h>
 #include <js/ContextOptions.h>
@@ -52,6 +30,7 @@
 #include <js/Array.h>
 #include <jsapi.h>
 
+/* Built source and not too big to worry about deduplication */
 #include "initjs.h" /* init.js */
 
 #ifdef JSGC_USE_EXACT_ROOTING
@@ -67,10 +46,9 @@
  * @short_description: JS Authority
  * @stability: Unstable
  *
- * An implementation of #PolkitBackendAuthority that reads and
- * evalates Javascript files and supports interaction with
- * authentication agents (virtue of being based on
- * #PolkitBackendInteractiveAuthority).
+ * An (SpiderMonkey-based) implementation of #PolkitBackendAuthority that reads
+ * and evaluates Javascript files and supports interaction with authentication
+ * agents (virtue of being based on #PolkitBackendInteractiveAuthority).
  */
 
 /* ---------------------------------------------------------------------------------------------------- */
@@ -100,57 +78,11 @@ static bool execute_script_with_runaway_killer (PolkitBackendJsAuthority *author
                                     JS::HandleScript                 script,
                                     JS::MutableHandleValue           rval);
 
-static void utils_spawn (const gchar *const  *argv,
-                         guint                timeout_seconds,
-                         GCancellable        *cancellable,
-                         GAsyncReadyCallback  callback,
-                         gpointer             user_data);
-
-gboolean utils_spawn_finish (GAsyncResult   *res,
-                             gint           *out_exit_status,
-                             gchar         **out_standard_output,
-                             gchar         **out_standard_error,
-                             GError        **error);
-
-static void on_dir_monitor_changed (GFileMonitor     *monitor,
-                                    GFile            *file,
-                                    GFile            *other_file,
-                                    GFileMonitorEvent event_type,
-                                    gpointer          user_data);
-
-/* ---------------------------------------------------------------------------------------------------- */
-
-enum
-{
-  PROP_0,
-  PROP_RULES_DIRS,
-};
-
 /* ---------------------------------------------------------------------------------------------------- */
 
 static gpointer runaway_killer_thread_func (gpointer user_data);
 static void runaway_killer_terminate (PolkitBackendJsAuthority *authority);
 
-static GList *polkit_backend_js_authority_get_admin_auth_identities (PolkitBackendInteractiveAuthority *authority,
-                                                                     PolkitSubject                     *caller,
-                                                                     PolkitSubject                     *subject,
-                                                                     PolkitIdentity                    *user_for_subject,
-                                                                     gboolean                           subject_is_local,
-                                                                     gboolean                           subject_is_active,
-                                                                     const gchar                       *action_id,
-                                                                     PolkitDetails                     *details);
-
-static PolkitImplicitAuthorization polkit_backend_js_authority_check_authorization_sync (
-                                                          PolkitBackendInteractiveAuthority *authority,
-                                                          PolkitSubject                     *caller,
-                                                          PolkitSubject                     *subject,
-                                                          PolkitIdentity                    *user_for_subject,
-                                                          gboolean                           subject_is_local,
-                                                          gboolean                           subject_is_active,
-                                                          const gchar                       *action_id,
-                                                          PolkitDetails                     *details,
-                                                          PolkitImplicitAuthorization        implicit);
-
 G_DEFINE_TYPE (PolkitBackendJsAuthority, polkit_backend_js_authority, POLKIT_BACKEND_TYPE_INTERACTIVE_AUTHORITY);
 
 /* ---------------------------------------------------------------------------------------------------- */
@@ -229,33 +161,6 @@ polkit_backend_js_authority_init (PolkitBackendJsAuthority *authority)
                                                  PolkitBackendJsAuthorityPrivate);
 }
 
-static gint
-rules_file_name_cmp (const gchar *a,
-                     const gchar *b)
-{
-  gint ret;
-  const gchar *a_base;
-  const gchar *b_base;
-
-  a_base = strrchr (a, '/');
-  b_base = strrchr (b, '/');
-
-  g_assert (a_base != NULL);
-  g_assert (b_base != NULL);
-  a_base += 1;
-  b_base += 1;
-
-  ret = g_strcmp0 (a_base, b_base);
-  if (ret == 0)
-    {
-      /* /etc wins over /usr */
-      ret = g_strcmp0 (a, b);
-      g_assert (ret != 0);
-    }
-
-  return ret;
-}
-
 /* authority->priv->cx must be within a request */
 static void
 load_scripts (PolkitBackendJsAuthority  *authority)
@@ -299,7 +204,7 @@ load_scripts (PolkitBackendJsAuthority  *authority)
         }
     }
 
-  files = g_list_sort (files, (GCompareFunc) rules_file_name_cmp);
+  files = g_list_sort (files, (GCompareFunc) polkit_backend_common_rules_file_name_cmp);
 
   for (l = files; l != NULL; l = l->next)
     {
@@ -365,8 +270,8 @@ load_scripts (PolkitBackendJsAuthority  *authority)
   g_list_free_full (files, g_free);
 }
 
-static void
-reload_scripts (PolkitBackendJsAuthority *authority)
+void
+polkit_backend_common_reload_scripts (PolkitBackendJsAuthority *authority)
 {
   JS::RootedValueArray<1> args(authority->priv->cx);
   JS::RootedValue rval(authority->priv->cx);
@@ -395,42 +300,6 @@ reload_scripts (PolkitBackendJsAuthority *authority)
   g_signal_emit_by_name (authority, "changed");
 }
 
-static void
-on_dir_monitor_changed (GFileMonitor     *monitor,
-                        GFile            *file,
-                        GFile            *other_file,
-                        GFileMonitorEvent event_type,
-                        gpointer          user_data)
-{
-  PolkitBackendJsAuthority *authority = POLKIT_BACKEND_JS_AUTHORITY (user_data);
-
-  /* TODO: maybe rate-limit so storms of events are collapsed into one with a 500ms resolution?
-   *       Because when editing a file with emacs we get 4-8 events..
-   */
-
-  if (file != NULL)
-    {
-      gchar *name;
-
-      name = g_file_get_basename (file);
-
-      /* g_print ("event_type=%d file=%p name=%s\n", event_type, file, name); */
-      if (!g_str_has_prefix (name, ".") &&
-          !g_str_has_prefix (name, "#") &&
-          g_str_has_suffix (name, ".rules") &&
-          (event_type == G_FILE_MONITOR_EVENT_CREATED ||
-           event_type == G_FILE_MONITOR_EVENT_DELETED ||
-           event_type == G_FILE_MONITOR_EVENT_CHANGES_DONE_HINT))
-        {
-          polkit_backend_authority_log (POLKIT_BACKEND_AUTHORITY (authority),
-                                        "Reloading rules");
-          reload_scripts (authority);
-        }
-      g_free (name);
-    }
-}
-
-
 static void
 setup_file_monitors (PolkitBackendJsAuthority *authority)
 {
@@ -462,7 +331,7 @@ setup_file_monitors (PolkitBackendJsAuthority *authority)
         {
           g_signal_connect (monitor,
                             "changed",
-                            G_CALLBACK (on_dir_monitor_changed),
+                            G_CALLBACK (polkit_backend_common_on_dir_monitor_changed),
                             authority);
           g_ptr_array_add (p, monitor);
         }
@@ -471,8 +340,8 @@ setup_file_monitors (PolkitBackendJsAuthority *authority)
   authority->priv->dir_monitors = (GFileMonitor**) g_ptr_array_free (p, FALSE);
 }
 
-static void
-polkit_backend_js_authority_constructed (GObject *object)
+void
+polkit_backend_common_js_authority_constructed (GObject *object)
 {
   PolkitBackendJsAuthority *authority = POLKIT_BACKEND_JS_AUTHORITY (object);
 
@@ -561,8 +430,8 @@ polkit_backend_js_authority_constructed (GObject *object)
   g_assert_not_reached ();
 }
 
-static void
-polkit_backend_js_authority_finalize (GObject *object)
+void
+polkit_backend_common_js_authority_finalize (GObject *object)
 {
   PolkitBackendJsAuthority *authority = POLKIT_BACKEND_JS_AUTHORITY (object);
   guint n;
@@ -577,7 +446,7 @@ polkit_backend_js_authority_finalize (GObject *object)
     {
       GFileMonitor *monitor = authority->priv->dir_monitors[n];
       g_signal_handlers_disconnect_by_func (monitor,
-                                            (gpointer*)G_CALLBACK (on_dir_monitor_changed),
+                                            (gpointer*)G_CALLBACK (polkit_backend_common_on_dir_monitor_changed),
                                             authority);
       g_object_unref (monitor);
     }
@@ -594,11 +463,11 @@ polkit_backend_js_authority_finalize (GObject *object)
   G_OBJECT_CLASS (polkit_backend_js_authority_parent_class)->finalize (object);
 }
 
-static void
-polkit_backend_js_authority_set_property (GObject      *object,
-                                          guint         property_id,
-                                          const GValue *value,
-                                          GParamSpec   *pspec)
+void
+polkit_backend_common_js_authority_set_property (GObject      *object,
+                                                 guint         property_id,
+                                                 const GValue *value,
+                                                 GParamSpec   *pspec)
 {
   PolkitBackendJsAuthority *authority = POLKIT_BACKEND_JS_AUTHORITY (object);
 
@@ -615,57 +484,12 @@ polkit_backend_js_authority_set_property (GObject      *object,
     }
 }
 
-static const gchar *
-polkit_backend_js_authority_get_name (PolkitBackendAuthority *authority)
-{
-  return "js";
-}
-
-static const gchar *
-polkit_backend_js_authority_get_version (PolkitBackendAuthority *authority)
-{
-  return PACKAGE_VERSION;
-}
-
-static PolkitAuthorityFeatures
-polkit_backend_js_authority_get_features (PolkitBackendAuthority *authority)
-{
-  return POLKIT_AUTHORITY_FEATURES_TEMPORARY_AUTHORIZATION;
-}
-
 static void
 polkit_backend_js_authority_class_init (PolkitBackendJsAuthorityClass *klass)
 {
-  GObjectClass *gobject_class;
-  PolkitBackendAuthorityClass *authority_class;
-  PolkitBackendInteractiveAuthorityClass *interactive_authority_class;
-
-
-  gobject_class = G_OBJECT_CLASS (klass);
-  gobject_class->finalize                               = polkit_backend_js_authority_finalize;
-  gobject_class->set_property                           = polkit_backend_js_authority_set_property;
-  gobject_class->constructed                            = polkit_backend_js_authority_constructed;
-
-  authority_class = POLKIT_BACKEND_AUTHORITY_CLASS (klass);
-  authority_class->get_name                             = polkit_backend_js_authority_get_name;
-  authority_class->get_version                          = polkit_backend_js_authority_get_version;
-  authority_class->get_features                         = polkit_backend_js_authority_get_features;
-
-  interactive_authority_class = POLKIT_BACKEND_INTERACTIVE_AUTHORITY_CLASS (klass);
-  interactive_authority_class->get_admin_identities     = polkit_backend_js_authority_get_admin_auth_identities;
-  interactive_authority_class->check_authorization_sync = polkit_backend_js_authority_check_authorization_sync;
-
-  g_object_class_install_property (gobject_class,
-                                   PROP_RULES_DIRS,
-                                   g_param_spec_boxed ("rules-dirs",
-                                                       NULL,
-                                                       NULL,
-                                                       G_TYPE_STRV,
-                                                       GParamFlags(G_PARAM_CONSTRUCT_ONLY | G_PARAM_WRITABLE)));
-
+  polkit_backend_common_js_authority_class_init_common (klass);
 
   g_type_class_add_private (klass, sizeof (PolkitBackendJsAuthorityPrivate));
-
   JS_Init ();
 }
 
@@ -1099,15 +923,15 @@ call_js_function_with_runaway_killer (PolkitBackendJsAuthority *authority,
 
 /* ---------------------------------------------------------------------------------------------------- */
 
-static GList *
-polkit_backend_js_authority_get_admin_auth_identities (PolkitBackendInteractiveAuthority *_authority,
-                                                       PolkitSubject                     *caller,
-                                                       PolkitSubject                     *subject,
-                                                       PolkitIdentity                    *user_for_subject,
-                                                       gboolean                           subject_is_local,
-                                                       gboolean                           subject_is_active,
-                                                       const gchar                       *action_id,
-                                                       PolkitDetails                     *details)
+GList *
+polkit_backend_common_js_authority_get_admin_auth_identities (PolkitBackendInteractiveAuthority *_authority,
+                                                              PolkitSubject                     *caller,
+                                                              PolkitSubject                     *subject,
+                                                              PolkitIdentity                    *user_for_subject,
+                                                              gboolean                           subject_is_local,
+                                                              gboolean                           subject_is_active,
+                                                              const gchar                       *action_id,
+                                                              PolkitDetails                     *details)
 {
   PolkitBackendJsAuthority *authority = POLKIT_BACKEND_JS_AUTHORITY (_authority);
   GList *ret = NULL;
@@ -1202,16 +1026,16 @@ polkit_backend_js_authority_get_admin_auth_identities (PolkitBackendInteractiveA
 
 /* ---------------------------------------------------------------------------------------------------- */
 
-static PolkitImplicitAuthorization
-polkit_backend_js_authority_check_authorization_sync (PolkitBackendInteractiveAuthority *_authority,
-                                                      PolkitSubject                     *caller,
-                                                      PolkitSubject                     *subject,
-                                                      PolkitIdentity                    *user_for_subject,
-                                                      gboolean                           subject_is_local,
-                                                      gboolean                           subject_is_active,
-                                                      const gchar                       *action_id,
-                                                      PolkitDetails                     *details,
-                                                      PolkitImplicitAuthorization        implicit)
+PolkitImplicitAuthorization
+polkit_backend_common_js_authority_check_authorization_sync (PolkitBackendInteractiveAuthority *_authority,
+                                                             PolkitSubject                     *caller,
+                                                             PolkitSubject                     *subject,
+                                                             PolkitIdentity                    *user_for_subject,
+                                                             gboolean                           subject_is_local,
+                                                             gboolean                           subject_is_active,
+                                                             const gchar                       *action_id,
+                                                             PolkitDetails                     *details,
+                                                             PolkitImplicitAuthorization        implicit)
 {
   PolkitBackendJsAuthority *authority = POLKIT_BACKEND_JS_AUTHORITY (_authority);
   PolkitImplicitAuthorization ret = implicit;
@@ -1324,65 +1148,6 @@ js_polkit_log (JSContext  *cx,
 
 /* ---------------------------------------------------------------------------------------------------- */
 
-static const gchar *
-get_signal_name (gint signal_number)
-{
-  switch (signal_number)
-    {
-#define _HANDLE_SIG(sig) case sig: return #sig;
-    _HANDLE_SIG (SIGHUP);
-    _HANDLE_SIG (SIGINT);
-    _HANDLE_SIG (SIGQUIT);
-    _HANDLE_SIG (SIGILL);
-    _HANDLE_SIG (SIGABRT);
-    _HANDLE_SIG (SIGFPE);
-    _HANDLE_SIG (SIGKILL);
-    _HANDLE_SIG (SIGSEGV);
-    _HANDLE_SIG (SIGPIPE);
-    _HANDLE_SIG (SIGALRM);
-    _HANDLE_SIG (SIGTERM);
-    _HANDLE_SIG (SIGUSR1);
-    _HANDLE_SIG (SIGUSR2);
-    _HANDLE_SIG (SIGCHLD);
-    _HANDLE_SIG (SIGCONT);
-    _HANDLE_SIG (SIGSTOP);
-    _HANDLE_SIG (SIGTSTP);
-    _HANDLE_SIG (SIGTTIN);
-    _HANDLE_SIG (SIGTTOU);
-    _HANDLE_SIG (SIGBUS);
-#ifdef SIGPOLL
-    _HANDLE_SIG (SIGPOLL);
-#endif
-    _HANDLE_SIG (SIGPROF);
-    _HANDLE_SIG (SIGSYS);
-    _HANDLE_SIG (SIGTRAP);
-    _HANDLE_SIG (SIGURG);
-    _HANDLE_SIG (SIGVTALRM);
-    _HANDLE_SIG (SIGXCPU);
-    _HANDLE_SIG (SIGXFSZ);
-#undef _HANDLE_SIG
-    default:
-      break;
-    }
-  return "UNKNOWN_SIGNAL";
-}
-
-typedef struct
-{
-  GMainLoop *loop;
-  GAsyncResult *res;
-} SpawnData;
-
-static void
-spawn_cb (GObject       *source_object,
-          GAsyncResult  *res,
-          gpointer       user_data)
-{
-  SpawnData *data = (SpawnData *)user_data;
-  data->res = (GAsyncResult*)g_object_ref (res);
-  g_main_loop_quit (data->loop);
-}
-
 static bool
 js_polkit_spawn (JSContext  *cx,
                  unsigned    js_argc,
@@ -1440,21 +1205,21 @@ js_polkit_spawn (JSContext  *cx,
   g_main_context_push_thread_default (context);
 
   data.loop = loop;
-  utils_spawn ((const gchar *const *) argv,
-               10, /* timeout_seconds */
-               NULL, /* cancellable */
-               spawn_cb,
-               &data);
+  polkit_backend_common_spawn ((const gchar *const *) argv,
+                               10, /* timeout_seconds */
+                               NULL, /* cancellable */
+                               polkit_backend_common_spawn_cb,
+                               &data);
 
   g_main_loop_run (loop);
 
   g_main_context_pop_thread_default (context);
 
-  if (!utils_spawn_finish (data.res,
-                           &exit_status,
-                           &standard_output,
-                           &standard_error,
-                           &error))
+  if (!polkit_backend_common_spawn_finish (data.res,
+                                           &exit_status,
+                                           &standard_output,
+                                           &standard_error,
+                                           &error))
     {
       JS_ReportErrorUTF8 (cx,
                       "Error spawning helper: %s (%s, %d)",
@@ -1477,7 +1242,7 @@ js_polkit_spawn (JSContext  *cx,
         {
           g_string_append_printf (gstr,
                                   "Helper was signaled with signal %s (%d)",
-                                  get_signal_name (WTERMSIG (exit_status)),
+                                  polkit_backend_common_get_signal_name (WTERMSIG (exit_status)),
                                   WTERMSIG (exit_status));
         }
       g_string_append_printf (gstr, ", stdout=`%s', stderr=`%s'",
@@ -1542,381 +1307,5 @@ js_polkit_user_is_in_netgroup (JSContext  *cx,
   return ret;
 }
 
-
-
 /* ---------------------------------------------------------------------------------------------------- */
 
-typedef struct
-{
-  GSimpleAsyncResult *simple; /* borrowed reference */
-  GMainContext *main_context; /* may be NULL */
-
-  GCancellable *cancellable;  /* may be NULL */
-  gulong cancellable_handler_id;
-
-  GPid child_pid;
-  gint child_stdout_fd;
-  gint child_stderr_fd;
-
-  GIOChannel *child_stdout_channel;
-  GIOChannel *child_stderr_channel;
-
-  GSource *child_watch_source;
-  GSource *child_stdout_source;
-  GSource *child_stderr_source;
-
-  guint timeout_seconds;
-  gboolean timed_out;
-  GSource *timeout_source;
-
-  GString *child_stdout;
-  GString *child_stderr;
-
-  gint exit_status;
-} UtilsSpawnData;
-
-static void
-utils_child_watch_from_release_cb (GPid     pid,
-                                   gint     status,
-                                   gpointer user_data)
-{
-}
-
-static void
-utils_spawn_data_free (UtilsSpawnData *data)
-{
-  if (data->timeout_source != NULL)
-    {
-      g_source_destroy (data->timeout_source);
-      data->timeout_source = NULL;
-    }
-
-  /* Nuke the child, if necessary */
-  if (data->child_watch_source != NULL)
-    {
-      g_source_destroy (data->child_watch_source);
-      data->child_watch_source = NULL;
-    }
-
-  if (data->child_pid != 0)
-    {
-      GSource *source;
-      kill (data->child_pid, SIGTERM);
-      /* OK, we need to reap for the child ourselves - we don't want
-       * to use waitpid() because that might block the calling
-       * thread (the child might handle SIGTERM and use several
-       * seconds for cleanup/rollback).
-       *
-       * So we use GChildWatch instead.
-       *
-       * Avoid taking a references to ourselves. but note that we need
-       * to pass the GSource so we can nuke it once handled.
-       */
-      source = g_child_watch_source_new (data->child_pid);
-      g_source_set_callback (source,
-                             (GSourceFunc) utils_child_watch_from_release_cb,
-                             source,
-                             (GDestroyNotify) g_source_destroy);
-      /* attach source to the global default main context */
-      g_source_attach (source, NULL);
-      g_source_unref (source);
-      data->child_pid = 0;
-    }
-
-  if (data->child_stdout != NULL)
-    {
-      g_string_free (data->child_stdout, TRUE);
-      data->child_stdout = NULL;
-    }
-
-  if (data->child_stderr != NULL)
-    {
-      g_string_free (data->child_stderr, TRUE);
-      data->child_stderr = NULL;
-    }
-
-  if (data->child_stdout_channel != NULL)
-    {
-      g_io_channel_unref (data->child_stdout_channel);
-      data->child_stdout_channel = NULL;
-    }
-  if (data->child_stderr_channel != NULL)
-    {
-      g_io_channel_unref (data->child_stderr_channel);
-      data->child_stderr_channel = NULL;
-    }
-
-  if (data->child_stdout_source != NULL)
-    {
-      g_source_destroy (data->child_stdout_source);
-      data->child_stdout_source = NULL;
-    }
-  if (data->child_stderr_source != NULL)
-    {
-      g_source_destroy (data->child_stderr_source);
-      data->child_stderr_source = NULL;
-    }
-
-  if (data->child_stdout_fd != -1)
-    {
-      g_warn_if_fail (close (data->child_stdout_fd) == 0);
-      data->child_stdout_fd = -1;
-    }
-  if (data->child_stderr_fd != -1)
-    {
-      g_warn_if_fail (close (data->child_stderr_fd) == 0);
-      data->child_stderr_fd = -1;
-    }
-
-  if (data->cancellable_handler_id > 0)
-    {
-      g_cancellable_disconnect (data->cancellable, data->cancellable_handler_id);
-      data->cancellable_handler_id = 0;
-    }
-
-  if (data->main_context != NULL)
-    g_main_context_unref (data->main_context);
-
-  if (data->cancellable != NULL)
-    g_object_unref (data->cancellable);
-
-  g_slice_free (UtilsSpawnData, data);
-}
-
-/* called in the thread where @cancellable was cancelled */
-static void
-utils_on_cancelled (GCancellable *cancellable,
-                    gpointer      user_data)
-{
-  UtilsSpawnData *data = (UtilsSpawnData *)user_data;
-  GError *error;
-
-  error = NULL;
-  g_warn_if_fail (g_cancellable_set_error_if_cancelled (cancellable, &error));
-  g_simple_async_result_take_error (data->simple, error);
-  g_simple_async_result_complete_in_idle (data->simple);
-  g_object_unref (data->simple);
-}
-
-static gboolean
-utils_read_child_stderr (GIOChannel *channel,
-                         GIOCondition condition,
-                         gpointer user_data)
-{
-  UtilsSpawnData *data = (UtilsSpawnData *)user_data;
-  gchar buf[1024];
-  gsize bytes_read;
-
-  g_io_channel_read_chars (channel, buf, sizeof buf, &bytes_read, NULL);
-  g_string_append_len (data->child_stderr, buf, bytes_read);
-  return TRUE;
-}
-
-static gboolean
-utils_read_child_stdout (GIOChannel *channel,
-                         GIOCondition condition,
-                         gpointer user_data)
-{
-  UtilsSpawnData *data = (UtilsSpawnData *)user_data;
-  gchar buf[1024];
-  gsize bytes_read;
-
-  g_io_channel_read_chars (channel, buf, sizeof buf, &bytes_read, NULL);
-  g_string_append_len (data->child_stdout, buf, bytes_read);
-  return TRUE;
-}
-
-static void
-utils_child_watch_cb (GPid     pid,
-                      gint     status,
-                      gpointer user_data)
-{
-  UtilsSpawnData *data = (UtilsSpawnData *)user_data;
-  gchar *buf;
-  gsize buf_size;
-
-  if (g_io_channel_read_to_end (data->child_stdout_channel, &buf, &buf_size, NULL) == G_IO_STATUS_NORMAL)
-    {
-      g_string_append_len (data->child_stdout, buf, buf_size);
-      g_free (buf);
-    }
-  if (g_io_channel_read_to_end (data->child_stderr_channel, &buf, &buf_size, NULL) == G_IO_STATUS_NORMAL)
-    {
-      g_string_append_len (data->child_stderr, buf, buf_size);
-      g_free (buf);
-    }
-
-  data->exit_status = status;
-
-  /* ok, child watch is history, make sure we don't free it in spawn_data_free() */
-  data->child_pid = 0;
-  data->child_watch_source = NULL;
-
-  /* we're done */
-  g_simple_async_result_complete_in_idle (data->simple);
-  g_object_unref (data->simple);
-}
-
-static gboolean
-utils_timeout_cb (gpointer user_data)
-{
-  UtilsSpawnData *data = (UtilsSpawnData *)user_data;
-
-  data->timed_out = TRUE;
-
-  /* ok, timeout is history, make sure we don't free it in spawn_data_free() */
-  data->timeout_source = NULL;
-
-  /* we're done */
-  g_simple_async_result_complete_in_idle (data->simple);
-  g_object_unref (data->simple);
-
-  return FALSE; /* remove source */
-}
-
-static void
-utils_spawn (const gchar *const  *argv,
-             guint                timeout_seconds,
-             GCancellable        *cancellable,
-             GAsyncReadyCallback  callback,
-             gpointer             user_data)
-{
-  UtilsSpawnData *data;
-  GError *error;
-
-  data = g_slice_new0 (UtilsSpawnData);
-  data->timeout_seconds = timeout_seconds;
-  data->simple = g_simple_async_result_new (NULL,
-                                            callback,
-                                            user_data,
-                                            (gpointer*)utils_spawn);
-  data->main_context = g_main_context_get_thread_default ();
-  if (data->main_context != NULL)
-    g_main_context_ref (data->main_context);
-
-  data->cancellable = cancellable != NULL ? (GCancellable*)g_object_ref (cancellable) : NULL;
-
-  data->child_stdout = g_string_new (NULL);
-  data->child_stderr = g_string_new (NULL);
-  data->child_stdout_fd = -1;
-  data->child_stderr_fd = -1;
-
-  /* the life-cycle of UtilsSpawnData is tied to its GSimpleAsyncResult */
-  g_simple_async_result_set_op_res_gpointer (data->simple, data, (GDestroyNotify) utils_spawn_data_free);
-
-  error = NULL;
-  if (data->cancellable != NULL)
-    {
-      /* could already be cancelled */
-      error = NULL;
-      if (g_cancellable_set_error_if_cancelled (data->cancellable, &error))
-        {
-          g_simple_async_result_take_error (data->simple, error);
-          g_simple_async_result_complete_in_idle (data->simple);
-          g_object_unref (data->simple);
-          goto out;
-        }
-
-      data->cancellable_handler_id = g_cancellable_connect (data->cancellable,
-                                                            G_CALLBACK (utils_on_cancelled),
-                                                            data,
-                                                            NULL);
-    }
-
-  error = NULL;
-  if (!g_spawn_async_with_pipes (NULL, /* working directory */
-                                 (gchar **) argv,
-                                 NULL, /* envp */
-                                 GSpawnFlags(G_SPAWN_SEARCH_PATH | G_SPAWN_DO_NOT_REAP_CHILD),
-                                 NULL, /* child_setup */
-                                 NULL, /* child_setup's user_data */
-                                 &(data->child_pid),
-                                 NULL, /* gint *stdin_fd */
-                                 &(data->child_stdout_fd),
-                                 &(data->child_stderr_fd),
-                                 &error))
-    {
-      g_prefix_error (&error, "Error spawning: ");
-      g_simple_async_result_take_error (data->simple, error);
-      g_simple_async_result_complete_in_idle (data->simple);
-      g_object_unref (data->simple);
-      goto out;
-    }
-
-  if (timeout_seconds > 0)
-    {
-      data->timeout_source = g_timeout_source_new_seconds (timeout_seconds);
-      g_source_set_priority (data->timeout_source, G_PRIORITY_DEFAULT);
-      g_source_set_callback (data->timeout_source, utils_timeout_cb, data, NULL);
-      g_source_attach (data->timeout_source, data->main_context);
-      g_source_unref (data->timeout_source);
-    }
-
-  data->child_watch_source = g_child_watch_source_new (data->child_pid);
-  g_source_set_callback (data->child_watch_source, (GSourceFunc) utils_child_watch_cb, data, NULL);
-  g_source_attach (data->child_watch_source, data->main_context);
-  g_source_unref (data->child_watch_source);
-
-  data->child_stdout_channel = g_io_channel_unix_new (data->child_stdout_fd);
-  g_io_channel_set_flags (data->child_stdout_channel, G_IO_FLAG_NONBLOCK, NULL);
-  data->child_stdout_source = g_io_create_watch (data->child_stdout_channel, G_IO_IN);
-  g_source_set_callback (data->child_stdout_source, (GSourceFunc) utils_read_child_stdout, data, NULL);
-  g_source_attach (data->child_stdout_source, data->main_context);
-  g_source_unref (data->child_stdout_source);
-
-  data->child_stderr_channel = g_io_channel_unix_new (data->child_stderr_fd);
-  g_io_channel_set_flags (data->child_stderr_channel, G_IO_FLAG_NONBLOCK, NULL);
-  data->child_stderr_source = g_io_create_watch (data->child_stderr_channel, G_IO_IN);
-  g_source_set_callback (data->child_stderr_source, (GSourceFunc) utils_read_child_stderr, data, NULL);
-  g_source_attach (data->child_stderr_source, data->main_context);
-  g_source_unref (data->child_stderr_source);
-
- out:
-  ;
-}
-
-gboolean
-utils_spawn_finish (GAsyncResult   *res,
-                    gint           *out_exit_status,
-                    gchar         **out_standard_output,
-                    gchar         **out_standard_error,
-                    GError        **error)
-{
-  GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
-  UtilsSpawnData *data;
-  gboolean ret = FALSE;
-
-  g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
-  g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
-
-  g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == utils_spawn);
-
-  if (g_simple_async_result_propagate_error (simple, error))
-    goto out;
-
-  data = (UtilsSpawnData*)g_simple_async_result_get_op_res_gpointer (simple);
-
-  if (data->timed_out)
-    {
-      g_set_error (error,
-                   G_IO_ERROR,
-                   G_IO_ERROR_TIMED_OUT,
-                   "Timed out after %d seconds",
-                   data->timeout_seconds);
-      goto out;
-    }
-
-  if (out_exit_status != NULL)
-    *out_exit_status = data->exit_status;
-
-  if (out_standard_output != NULL)
-    *out_standard_output = g_strdup (data->child_stdout->str);
-
-  if (out_standard_error != NULL)
-    *out_standard_error = g_strdup (data->child_stderr->str);
-
-  ret = TRUE;
-
- out:
-  return ret;
-}
-- 
GitLab


From 4858128107be9c3ab11828ee8f35c5e26efd36ce Mon Sep 17 00:00:00 2001
From: Gustavo Lima Chaves <gustavo.chaves@microsoft.com>
Date: Tue, 14 Sep 2021 14:38:15 -0700
Subject: [PATCH 15/17] Gitlab CI: add duktape pkgconfig dependency

Make way for the CI to be able to build with duktape too

Signed-off-by: Gustavo Lima Chaves <gustavo.chaves@microsoft.com>
---
 .gitlab-ci.yml | 1 +
 1 file changed, 1 insertion(+)

diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml
index 23cf0d6..942415d 100644
--- a/.gitlab-ci.yml
+++ b/.gitlab-ci.yml
@@ -14,6 +14,7 @@ variables:
                 libxslt
                 pkgconfig(gio-2.0)
                 pkgconfig(mozjs-78)
+                pkgconfig(duktape)
                 expat-devel
                 pkgconfig(libsystemd)
                 pkgconfig(systemd)
-- 
GitLab


From 4262c8a5c952e7f5d15d233c1cd2955086b622a9 Mon Sep 17 00:00:00 2001
From: Gustavo Lima Chaves <gustavo.chaves@microsoft.com>
Date: Mon, 20 Sep 2021 17:17:26 -0700
Subject: [PATCH 16/17] duktape: implement runaway scripts killer timeout

This was missing on Duktape's JS backend proposal, now in. As
discussed in
https://gitlab.freedesktop.org/polkit/polkit/-/merge_requests/35 and
verified by the commit author, Duktape has no interrupt injection
mechanism (it has no thread-safe API entry whatsoever, even). Using
DUK_USE_EXEC_TIMEOUT_CHECK is also not feasible, because:

  i) It must be enabled at build time and shared object builds of the
  lib on distros go with the default options, something we cannot
  change/control

  ii) That does not account for non-ECMAScript explicit execution
  contexts, like regex execution, native C calls, etc.

It has been agreed, on that thread, that pthread_cond_timedwait()-ing
and having proper Duktape evaluation/execution calls take place in a
separate thread, to be killed after the runaway script killer's
accorded timeout value, a reasonable approach. We have considered
using glib wrappers for direct pthread usage, but that way would make
it impossible to issue
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, ...) natively, and
we want to be paranoid in that regard. Worse than that, they have no
exposure of pthread_cancel() either. We go for pthreads direct usage,
then. Fancy threading build system checks courtesy of Evgeny Grin.

On Duktape, we don't get to err from the JS context (to be captured by
the offending script), but to be forcibly killed on timeout scenarios,
leading to null returns, thus polkit negation, by definition. It's a
reasonable design/compromise.

A fatal error handler routine, for the Duktape context, has also been
added, using the polkit_backend_authority_log() logging infra to
better assist users on what went wrong.

Finally, the script evaluation routine has been made to use
duk_peval_lstring() (previously using _noresult variant), so to able
to present the user with proper error messages, should any occur.

NB: The original runaway script killer test has been adjusted to
please both JS backends and we now also require Duktape version >=
2.0.0 on meson builds as well (removing the code checks for previous
versions).

Signed-off-by: Gustavo Lima Chaves <gustavo.chaves@microsoft.com>
Co-authored-by: Evgeny Grin <k2k@narod.ru>
---
 buildutil/ax_pthread.m4                       | 522 ++++++++++++++++++
 configure.ac                                  |   8 +-
 meson.build                                   |   7 +-
 src/polkitbackend/Makefile.am                 |   2 +
 src/polkitbackend/meson.build                 |   3 +
 src/polkitbackend/polkitbackendcommon.h       |   2 +
 .../polkitbackendduktapeauthority.c           | 329 +++++++++--
 .../polkitbackendjsauthority.cpp              |  10 +-
 .../etc/polkit-1/rules.d/10-testing.rules     |   6 +-
 .../test-polkitbackendjsauthority.c           |   2 +-
 10 files changed, 836 insertions(+), 55 deletions(-)
 create mode 100644 buildutil/ax_pthread.m4

diff --git a/buildutil/ax_pthread.m4 b/buildutil/ax_pthread.m4
new file mode 100644
index 0000000..9f35d13
--- /dev/null
+++ b/buildutil/ax_pthread.m4
@@ -0,0 +1,522 @@
+# ===========================================================================
+#        https://www.gnu.org/software/autoconf-archive/ax_pthread.html
+# ===========================================================================
+#
+# SYNOPSIS
+#
+#   AX_PTHREAD([ACTION-IF-FOUND[, ACTION-IF-NOT-FOUND]])
+#
+# DESCRIPTION
+#
+#   This macro figures out how to build C programs using POSIX threads. It
+#   sets the PTHREAD_LIBS output variable to the threads library and linker
+#   flags, and the PTHREAD_CFLAGS output variable to any special C compiler
+#   flags that are needed. (The user can also force certain compiler
+#   flags/libs to be tested by setting these environment variables.)
+#
+#   Also sets PTHREAD_CC and PTHREAD_CXX to any special C compiler that is
+#   needed for multi-threaded programs (defaults to the value of CC
+#   respectively CXX otherwise). (This is necessary on e.g. AIX to use the
+#   special cc_r/CC_r compiler alias.)
+#
+#   NOTE: You are assumed to not only compile your program with these flags,
+#   but also to link with them as well. For example, you might link with
+#   $PTHREAD_CC $CFLAGS $PTHREAD_CFLAGS $LDFLAGS ... $PTHREAD_LIBS $LIBS
+#   $PTHREAD_CXX $CXXFLAGS $PTHREAD_CFLAGS $LDFLAGS ... $PTHREAD_LIBS $LIBS
+#
+#   If you are only building threaded programs, you may wish to use these
+#   variables in your default LIBS, CFLAGS, and CC:
+#
+#     LIBS="$PTHREAD_LIBS $LIBS"
+#     CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
+#     CXXFLAGS="$CXXFLAGS $PTHREAD_CFLAGS"
+#     CC="$PTHREAD_CC"
+#     CXX="$PTHREAD_CXX"
+#
+#   In addition, if the PTHREAD_CREATE_JOINABLE thread-attribute constant
+#   has a nonstandard name, this macro defines PTHREAD_CREATE_JOINABLE to
+#   that name (e.g. PTHREAD_CREATE_UNDETACHED on AIX).
+#
+#   Also HAVE_PTHREAD_PRIO_INHERIT is defined if pthread is found and the
+#   PTHREAD_PRIO_INHERIT symbol is defined when compiling with
+#   PTHREAD_CFLAGS.
+#
+#   ACTION-IF-FOUND is a list of shell commands to run if a threads library
+#   is found, and ACTION-IF-NOT-FOUND is a list of commands to run it if it
+#   is not found. If ACTION-IF-FOUND is not specified, the default action
+#   will define HAVE_PTHREAD.
+#
+#   Please let the authors know if this macro fails on any platform, or if
+#   you have any other suggestions or comments. This macro was based on work
+#   by SGJ on autoconf scripts for FFTW (http://www.fftw.org/) (with help
+#   from M. Frigo), as well as ac_pthread and hb_pthread macros posted by
+#   Alejandro Forero Cuervo to the autoconf macro repository. We are also
+#   grateful for the helpful feedback of numerous users.
+#
+#   Updated for Autoconf 2.68 by Daniel Richard G.
+#
+# LICENSE
+#
+#   Copyright (c) 2008 Steven G. Johnson <stevenj@alum.mit.edu>
+#   Copyright (c) 2011 Daniel Richard G. <skunk@iSKUNK.ORG>
+#   Copyright (c) 2019 Marc Stevens <marc.stevens@cwi.nl>
+#
+#   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 3 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, see <https://www.gnu.org/licenses/>.
+#
+#   As a special exception, the respective Autoconf Macro's copyright owner
+#   gives unlimited permission to copy, distribute and modify the configure
+#   scripts that are the output of Autoconf when processing the Macro. You
+#   need not follow the terms of the GNU General Public License when using
+#   or distributing such scripts, even though portions of the text of the
+#   Macro appear in them. The GNU General Public License (GPL) does govern
+#   all other use of the material that constitutes the Autoconf Macro.
+#
+#   This special exception to the GPL applies to versions of the Autoconf
+#   Macro released by the Autoconf Archive. When you make and distribute a
+#   modified version of the Autoconf Macro, you may extend this special
+#   exception to the GPL to apply to your modified version as well.
+
+#serial 31
+
+AU_ALIAS([ACX_PTHREAD], [AX_PTHREAD])
+AC_DEFUN([AX_PTHREAD], [
+AC_REQUIRE([AC_CANONICAL_HOST])
+AC_REQUIRE([AC_PROG_CC])
+AC_REQUIRE([AC_PROG_SED])
+AC_LANG_PUSH([C])
+ax_pthread_ok=no
+
+# We used to check for pthread.h first, but this fails if pthread.h
+# requires special compiler flags (e.g. on Tru64 or Sequent).
+# It gets checked for in the link test anyway.
+
+# First of all, check if the user has set any of the PTHREAD_LIBS,
+# etcetera environment variables, and if threads linking works using
+# them:
+if test "x$PTHREAD_CFLAGS$PTHREAD_LIBS" != "x"; then
+        ax_pthread_save_CC="$CC"
+        ax_pthread_save_CFLAGS="$CFLAGS"
+        ax_pthread_save_LIBS="$LIBS"
+        AS_IF([test "x$PTHREAD_CC" != "x"], [CC="$PTHREAD_CC"])
+        AS_IF([test "x$PTHREAD_CXX" != "x"], [CXX="$PTHREAD_CXX"])
+        CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
+        LIBS="$PTHREAD_LIBS $LIBS"
+        AC_MSG_CHECKING([for pthread_join using $CC $PTHREAD_CFLAGS $PTHREAD_LIBS])
+        AC_LINK_IFELSE([AC_LANG_CALL([], [pthread_join])], [ax_pthread_ok=yes])
+        AC_MSG_RESULT([$ax_pthread_ok])
+        if test "x$ax_pthread_ok" = "xno"; then
+                PTHREAD_LIBS=""
+                PTHREAD_CFLAGS=""
+        fi
+        CC="$ax_pthread_save_CC"
+        CFLAGS="$ax_pthread_save_CFLAGS"
+        LIBS="$ax_pthread_save_LIBS"
+fi
+
+# We must check for the threads library under a number of different
+# names; the ordering is very important because some systems
+# (e.g. DEC) have both -lpthread and -lpthreads, where one of the
+# libraries is broken (non-POSIX).
+
+# Create a list of thread flags to try. Items with a "," contain both
+# C compiler flags (before ",") and linker flags (after ","). Other items
+# starting with a "-" are C compiler flags, and remaining items are
+# library names, except for "none" which indicates that we try without
+# any flags at all, and "pthread-config" which is a program returning
+# the flags for the Pth emulation library.
+
+ax_pthread_flags="pthreads none -Kthread -pthread -pthreads -mthreads pthread --thread-safe -mt pthread-config"
+
+# The ordering *is* (sometimes) important.  Some notes on the
+# individual items follow:
+
+# pthreads: AIX (must check this before -lpthread)
+# none: in case threads are in libc; should be tried before -Kthread and
+#       other compiler flags to prevent continual compiler warnings
+# -Kthread: Sequent (threads in libc, but -Kthread needed for pthread.h)
+# -pthread: Linux/gcc (kernel threads), BSD/gcc (userland threads), Tru64
+#           (Note: HP C rejects this with "bad form for `-t' option")
+# -pthreads: Solaris/gcc (Note: HP C also rejects)
+# -mt: Sun Workshop C (may only link SunOS threads [-lthread], but it
+#      doesn't hurt to check since this sometimes defines pthreads and
+#      -D_REENTRANT too), HP C (must be checked before -lpthread, which
+#      is present but should not be used directly; and before -mthreads,
+#      because the compiler interprets this as "-mt" + "-hreads")
+# -mthreads: Mingw32/gcc, Lynx/gcc
+# pthread: Linux, etcetera
+# --thread-safe: KAI C++
+# pthread-config: use pthread-config program (for GNU Pth library)
+
+case $host_os in
+
+        freebsd*)
+
+        # -kthread: FreeBSD kernel threads (preferred to -pthread since SMP-able)
+        # lthread: LinuxThreads port on FreeBSD (also preferred to -pthread)
+
+        ax_pthread_flags="-kthread lthread $ax_pthread_flags"
+        ;;
+
+        hpux*)
+
+        # From the cc(1) man page: "[-mt] Sets various -D flags to enable
+        # multi-threading and also sets -lpthread."
+
+        ax_pthread_flags="-mt -pthread pthread $ax_pthread_flags"
+        ;;
+
+        openedition*)
+
+        # IBM z/OS requires a feature-test macro to be defined in order to
+        # enable POSIX threads at all, so give the user a hint if this is
+        # not set. (We don't define these ourselves, as they can affect
+        # other portions of the system API in unpredictable ways.)
+
+        AC_EGREP_CPP([AX_PTHREAD_ZOS_MISSING],
+            [
+#            if !defined(_OPEN_THREADS) && !defined(_UNIX03_THREADS)
+             AX_PTHREAD_ZOS_MISSING
+#            endif
+            ],
+            [AC_MSG_WARN([IBM z/OS requires -D_OPEN_THREADS or -D_UNIX03_THREADS to enable pthreads support.])])
+        ;;
+
+        solaris*)
+
+        # On Solaris (at least, for some versions), libc contains stubbed
+        # (non-functional) versions of the pthreads routines, so link-based
+        # tests will erroneously succeed. (N.B.: The stubs are missing
+        # pthread_cleanup_push, or rather a function called by this macro,
+        # so we could check for that, but who knows whether they'll stub
+        # that too in a future libc.)  So we'll check first for the
+        # standard Solaris way of linking pthreads (-mt -lpthread).
+
+        ax_pthread_flags="-mt,-lpthread pthread $ax_pthread_flags"
+        ;;
+esac
+
+# Are we compiling with Clang?
+
+AC_CACHE_CHECK([whether $CC is Clang],
+    [ax_cv_PTHREAD_CLANG],
+    [ax_cv_PTHREAD_CLANG=no
+     # Note that Autoconf sets GCC=yes for Clang as well as GCC
+     if test "x$GCC" = "xyes"; then
+        AC_EGREP_CPP([AX_PTHREAD_CC_IS_CLANG],
+            [/* Note: Clang 2.7 lacks __clang_[a-z]+__ */
+#            if defined(__clang__) && defined(__llvm__)
+             AX_PTHREAD_CC_IS_CLANG
+#            endif
+            ],
+            [ax_cv_PTHREAD_CLANG=yes])
+     fi
+    ])
+ax_pthread_clang="$ax_cv_PTHREAD_CLANG"
+
+
+# GCC generally uses -pthread, or -pthreads on some platforms (e.g. SPARC)
+
+# Note that for GCC and Clang -pthread generally implies -lpthread,
+# except when -nostdlib is passed.
+# This is problematic using libtool to build C++ shared libraries with pthread:
+# [1] https://gcc.gnu.org/bugzilla/show_bug.cgi?id=25460
+# [2] https://bugzilla.redhat.com/show_bug.cgi?id=661333
+# [3] https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=468555
+# To solve this, first try -pthread together with -lpthread for GCC
+
+AS_IF([test "x$GCC" = "xyes"],
+      [ax_pthread_flags="-pthread,-lpthread -pthread -pthreads $ax_pthread_flags"])
+
+# Clang takes -pthread (never supported any other flag), but we'll try with -lpthread first
+
+AS_IF([test "x$ax_pthread_clang" = "xyes"],
+      [ax_pthread_flags="-pthread,-lpthread -pthread"])
+
+
+# The presence of a feature test macro requesting re-entrant function
+# definitions is, on some systems, a strong hint that pthreads support is
+# correctly enabled
+
+case $host_os in
+        darwin* | hpux* | linux* | osf* | solaris*)
+        ax_pthread_check_macro="_REENTRANT"
+        ;;
+
+        aix*)
+        ax_pthread_check_macro="_THREAD_SAFE"
+        ;;
+
+        *)
+        ax_pthread_check_macro="--"
+        ;;
+esac
+AS_IF([test "x$ax_pthread_check_macro" = "x--"],
+      [ax_pthread_check_cond=0],
+      [ax_pthread_check_cond="!defined($ax_pthread_check_macro)"])
+
+
+if test "x$ax_pthread_ok" = "xno"; then
+for ax_pthread_try_flag in $ax_pthread_flags; do
+
+        case $ax_pthread_try_flag in
+                none)
+                AC_MSG_CHECKING([whether pthreads work without any flags])
+                ;;
+
+                *,*)
+                PTHREAD_CFLAGS=`echo $ax_pthread_try_flag | sed "s/^\(.*\),\(.*\)$/\1/"`
+                PTHREAD_LIBS=`echo $ax_pthread_try_flag | sed "s/^\(.*\),\(.*\)$/\2/"`
+                AC_MSG_CHECKING([whether pthreads work with "$PTHREAD_CFLAGS" and "$PTHREAD_LIBS"])
+                ;;
+
+                -*)
+                AC_MSG_CHECKING([whether pthreads work with $ax_pthread_try_flag])
+                PTHREAD_CFLAGS="$ax_pthread_try_flag"
+                ;;
+
+                pthread-config)
+                AC_CHECK_PROG([ax_pthread_config], [pthread-config], [yes], [no])
+                AS_IF([test "x$ax_pthread_config" = "xno"], [continue])
+                PTHREAD_CFLAGS="`pthread-config --cflags`"
+                PTHREAD_LIBS="`pthread-config --ldflags` `pthread-config --libs`"
+                ;;
+
+                *)
+                AC_MSG_CHECKING([for the pthreads library -l$ax_pthread_try_flag])
+                PTHREAD_LIBS="-l$ax_pthread_try_flag"
+                ;;
+        esac
+
+        ax_pthread_save_CFLAGS="$CFLAGS"
+        ax_pthread_save_LIBS="$LIBS"
+        CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
+        LIBS="$PTHREAD_LIBS $LIBS"
+
+        # Check for various functions.  We must include pthread.h,
+        # since some functions may be macros.  (On the Sequent, we
+        # need a special flag -Kthread to make this header compile.)
+        # We check for pthread_join because it is in -lpthread on IRIX
+        # while pthread_create is in libc.  We check for pthread_attr_init
+        # due to DEC craziness with -lpthreads.  We check for
+        # pthread_cleanup_push because it is one of the few pthread
+        # functions on Solaris that doesn't have a non-functional libc stub.
+        # We try pthread_create on general principles.
+
+        AC_LINK_IFELSE([AC_LANG_PROGRAM([#include <pthread.h>
+#                       if $ax_pthread_check_cond
+#                        error "$ax_pthread_check_macro must be defined"
+#                       endif
+                        static void *some_global = NULL;
+                        static void routine(void *a)
+                          {
+                             /* To avoid any unused-parameter or
+                                unused-but-set-parameter warning.  */
+                             some_global = a;
+                          }
+                        static void *start_routine(void *a) { return a; }],
+                       [pthread_t th; pthread_attr_t attr;
+                        pthread_create(&th, 0, start_routine, 0);
+                        pthread_join(th, 0);
+                        pthread_attr_init(&attr);
+                        pthread_cleanup_push(routine, 0);
+                        pthread_cleanup_pop(0) /* ; */])],
+            [ax_pthread_ok=yes],
+            [])
+
+        CFLAGS="$ax_pthread_save_CFLAGS"
+        LIBS="$ax_pthread_save_LIBS"
+
+        AC_MSG_RESULT([$ax_pthread_ok])
+        AS_IF([test "x$ax_pthread_ok" = "xyes"], [break])
+
+        PTHREAD_LIBS=""
+        PTHREAD_CFLAGS=""
+done
+fi
+
+
+# Clang needs special handling, because older versions handle the -pthread
+# option in a rather... idiosyncratic way
+
+if test "x$ax_pthread_clang" = "xyes"; then
+
+        # Clang takes -pthread; it has never supported any other flag
+
+        # (Note 1: This will need to be revisited if a system that Clang
+        # supports has POSIX threads in a separate library.  This tends not
+        # to be the way of modern systems, but it's conceivable.)
+
+        # (Note 2: On some systems, notably Darwin, -pthread is not needed
+        # to get POSIX threads support; the API is always present and
+        # active.  We could reasonably leave PTHREAD_CFLAGS empty.  But
+        # -pthread does define _REENTRANT, and while the Darwin headers
+        # ignore this macro, third-party headers might not.)
+
+        # However, older versions of Clang make a point of warning the user
+        # that, in an invocation where only linking and no compilation is
+        # taking place, the -pthread option has no effect ("argument unused
+        # during compilation").  They expect -pthread to be passed in only
+        # when source code is being compiled.
+        #
+        # Problem is, this is at odds with the way Automake and most other
+        # C build frameworks function, which is that the same flags used in
+        # compilation (CFLAGS) are also used in linking.  Many systems
+        # supported by AX_PTHREAD require exactly this for POSIX threads
+        # support, and in fact it is often not straightforward to specify a
+        # flag that is used only in the compilation phase and not in
+        # linking.  Such a scenario is extremely rare in practice.
+        #
+        # Even though use of the -pthread flag in linking would only print
+        # a warning, this can be a nuisance for well-run software projects
+        # that build with -Werror.  So if the active version of Clang has
+        # this misfeature, we search for an option to squash it.
+
+        AC_CACHE_CHECK([whether Clang needs flag to prevent "argument unused" warning when linking with -pthread],
+            [ax_cv_PTHREAD_CLANG_NO_WARN_FLAG],
+            [ax_cv_PTHREAD_CLANG_NO_WARN_FLAG=unknown
+             # Create an alternate version of $ac_link that compiles and
+             # links in two steps (.c -> .o, .o -> exe) instead of one
+             # (.c -> exe), because the warning occurs only in the second
+             # step
+             ax_pthread_save_ac_link="$ac_link"
+             ax_pthread_sed='s/conftest\.\$ac_ext/conftest.$ac_objext/g'
+             ax_pthread_link_step=`AS_ECHO(["$ac_link"]) | sed "$ax_pthread_sed"`
+             ax_pthread_2step_ac_link="($ac_compile) && (echo ==== >&5) && ($ax_pthread_link_step)"
+             ax_pthread_save_CFLAGS="$CFLAGS"
+             for ax_pthread_try in '' -Qunused-arguments -Wno-unused-command-line-argument unknown; do
+                AS_IF([test "x$ax_pthread_try" = "xunknown"], [break])
+                CFLAGS="-Werror -Wunknown-warning-option $ax_pthread_try -pthread $ax_pthread_save_CFLAGS"
+                ac_link="$ax_pthread_save_ac_link"
+                AC_LINK_IFELSE([AC_LANG_SOURCE([[int main(void){return 0;}]])],
+                    [ac_link="$ax_pthread_2step_ac_link"
+                     AC_LINK_IFELSE([AC_LANG_SOURCE([[int main(void){return 0;}]])],
+                         [break])
+                    ])
+             done
+             ac_link="$ax_pthread_save_ac_link"
+             CFLAGS="$ax_pthread_save_CFLAGS"
+             AS_IF([test "x$ax_pthread_try" = "x"], [ax_pthread_try=no])
+             ax_cv_PTHREAD_CLANG_NO_WARN_FLAG="$ax_pthread_try"
+            ])
+
+        case "$ax_cv_PTHREAD_CLANG_NO_WARN_FLAG" in
+                no | unknown) ;;
+                *) PTHREAD_CFLAGS="$ax_cv_PTHREAD_CLANG_NO_WARN_FLAG $PTHREAD_CFLAGS" ;;
+        esac
+
+fi # $ax_pthread_clang = yes
+
+
+
+# Various other checks:
+if test "x$ax_pthread_ok" = "xyes"; then
+        ax_pthread_save_CFLAGS="$CFLAGS"
+        ax_pthread_save_LIBS="$LIBS"
+        CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
+        LIBS="$PTHREAD_LIBS $LIBS"
+
+        # Detect AIX lossage: JOINABLE attribute is called UNDETACHED.
+        AC_CACHE_CHECK([for joinable pthread attribute],
+            [ax_cv_PTHREAD_JOINABLE_ATTR],
+            [ax_cv_PTHREAD_JOINABLE_ATTR=unknown
+             for ax_pthread_attr in PTHREAD_CREATE_JOINABLE PTHREAD_CREATE_UNDETACHED; do
+                 AC_LINK_IFELSE([AC_LANG_PROGRAM([#include <pthread.h>],
+                                                 [int attr = $ax_pthread_attr; return attr /* ; */])],
+                                [ax_cv_PTHREAD_JOINABLE_ATTR=$ax_pthread_attr; break],
+                                [])
+             done
+            ])
+        AS_IF([test "x$ax_cv_PTHREAD_JOINABLE_ATTR" != "xunknown" && \
+               test "x$ax_cv_PTHREAD_JOINABLE_ATTR" != "xPTHREAD_CREATE_JOINABLE" && \
+               test "x$ax_pthread_joinable_attr_defined" != "xyes"],
+              [AC_DEFINE_UNQUOTED([PTHREAD_CREATE_JOINABLE],
+                                  [$ax_cv_PTHREAD_JOINABLE_ATTR],
+                                  [Define to necessary symbol if this constant
+                                   uses a non-standard name on your system.])
+               ax_pthread_joinable_attr_defined=yes
+              ])
+
+        AC_CACHE_CHECK([whether more special flags are required for pthreads],
+            [ax_cv_PTHREAD_SPECIAL_FLAGS],
+            [ax_cv_PTHREAD_SPECIAL_FLAGS=no
+             case $host_os in
+             solaris*)
+             ax_cv_PTHREAD_SPECIAL_FLAGS="-D_POSIX_PTHREAD_SEMANTICS"
+             ;;
+             esac
+            ])
+        AS_IF([test "x$ax_cv_PTHREAD_SPECIAL_FLAGS" != "xno" && \
+               test "x$ax_pthread_special_flags_added" != "xyes"],
+              [PTHREAD_CFLAGS="$ax_cv_PTHREAD_SPECIAL_FLAGS $PTHREAD_CFLAGS"
+               ax_pthread_special_flags_added=yes])
+
+        AC_CACHE_CHECK([for PTHREAD_PRIO_INHERIT],
+            [ax_cv_PTHREAD_PRIO_INHERIT],
+            [AC_LINK_IFELSE([AC_LANG_PROGRAM([[#include <pthread.h>]],
+                                             [[int i = PTHREAD_PRIO_INHERIT;
+                                               return i;]])],
+                            [ax_cv_PTHREAD_PRIO_INHERIT=yes],
+                            [ax_cv_PTHREAD_PRIO_INHERIT=no])
+            ])
+        AS_IF([test "x$ax_cv_PTHREAD_PRIO_INHERIT" = "xyes" && \
+               test "x$ax_pthread_prio_inherit_defined" != "xyes"],
+              [AC_DEFINE([HAVE_PTHREAD_PRIO_INHERIT], [1], [Have PTHREAD_PRIO_INHERIT.])
+               ax_pthread_prio_inherit_defined=yes
+              ])
+
+        CFLAGS="$ax_pthread_save_CFLAGS"
+        LIBS="$ax_pthread_save_LIBS"
+
+        # More AIX lossage: compile with *_r variant
+        if test "x$GCC" != "xyes"; then
+            case $host_os in
+                aix*)
+                AS_CASE(["x/$CC"],
+                    [x*/c89|x*/c89_128|x*/c99|x*/c99_128|x*/cc|x*/cc128|x*/xlc|x*/xlc_v6|x*/xlc128|x*/xlc128_v6],
+                    [#handle absolute path differently from PATH based program lookup
+                     AS_CASE(["x$CC"],
+                         [x/*],
+                         [
+			   AS_IF([AS_EXECUTABLE_P([${CC}_r])],[PTHREAD_CC="${CC}_r"])
+			   AS_IF([test "x${CXX}" != "x"], [AS_IF([AS_EXECUTABLE_P([${CXX}_r])],[PTHREAD_CXX="${CXX}_r"])])
+			 ],
+                         [
+			   AC_CHECK_PROGS([PTHREAD_CC],[${CC}_r],[$CC])
+			   AS_IF([test "x${CXX}" != "x"], [AC_CHECK_PROGS([PTHREAD_CXX],[${CXX}_r],[$CXX])])
+			 ]
+                     )
+                    ])
+                ;;
+            esac
+        fi
+fi
+
+test -n "$PTHREAD_CC" || PTHREAD_CC="$CC"
+test -n "$PTHREAD_CXX" || PTHREAD_CXX="$CXX"
+
+AC_SUBST([PTHREAD_LIBS])
+AC_SUBST([PTHREAD_CFLAGS])
+AC_SUBST([PTHREAD_CC])
+AC_SUBST([PTHREAD_CXX])
+
+# Finally, execute ACTION-IF-FOUND/ACTION-IF-NOT-FOUND:
+if test "x$ax_pthread_ok" = "xyes"; then
+        ifelse([$1],,[AC_DEFINE([HAVE_PTHREAD],[1],[Define if you have POSIX threads libraries and header files.])],[$1])
+        :
+else
+        ax_pthread_ok=no
+        $2
+fi
+AC_LANG_POP
+])dnl AX_PTHREAD
diff --git a/configure.ac b/configure.ac
index 5a03593..e182238 100644
--- a/configure.ac
+++ b/configure.ac
@@ -85,7 +85,7 @@ dnl - Check javascript backend
 dnl ---------------------------------------------------------------------------
 AC_ARG_WITH(duktape, AS_HELP_STRING([--with-duktape],[Use Duktape as javascript backend]),with_duktape=yes,with_duktape=no)
 AS_IF([test x${with_duktape} == xyes], [
-  PKG_CHECK_MODULES(LIBJS, [duktape >= 2.0.0 ])
+  PKG_CHECK_MODULES(LIBJS, [duktape >= 2.2.0 ])
   AC_SUBST(LIBJS_CFLAGS)
   AC_SUBST(LIBJS_LIBS)
 ], [
@@ -111,6 +111,12 @@ AC_CHECK_LIB(expat,XML_ParserCreate,[EXPAT_LIBS="-lexpat"],
 	     [AC_MSG_ERROR([Can't find expat library. Please install expat.])])
 AC_SUBST(EXPAT_LIBS)
 
+AX_PTHREAD([], [AC_MSG_ERROR([Cannot find the way to enable pthread support.])])
+LIBS="$PTHREAD_LIBS $LIBS"
+CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
+CC="$PTHREAD_CC"
+AC_CHECK_FUNCS([pthread_condattr_setclock])
+
 AC_CHECK_FUNCS(clearenv fdatasync)
 
 if test "x$GCC" = "xyes"; then
diff --git a/meson.build b/meson.build
index 4e44723..ad9ab07 100644
--- a/meson.build
+++ b/meson.build
@@ -133,10 +133,15 @@ expat_dep = dependency('expat')
 assert(cc.has_header('expat.h', dependencies: expat_dep), 'Can\'t find expat.h. Please install expat.')
 assert(cc.has_function('XML_ParserCreate', dependencies: expat_dep), 'Can\'t find expat library. Please install expat.')
 
+duktape_req_version = '>= 2.2.0'
+
 js_engine = get_option('js_engine')
 if js_engine == 'duktape'
-  js_dep = dependency('duktape')
+  js_dep = dependency('duktape', version: duktape_req_version)
   libm_dep = cc.find_library('m')
+  thread_dep = dependency('threads')
+  func = 'pthread_condattr_setclock'
+  config_h.set('HAVE_' + func.to_upper(), cc.has_function(func, prefix : '#include <pthread.h>'))
 elif js_engine == 'mozjs'
   js_dep = dependency('mozjs-78')
 endif
diff --git a/src/polkitbackend/Makefile.am b/src/polkitbackend/Makefile.am
index 6a8b4ae..935fb98 100644
--- a/src/polkitbackend/Makefile.am
+++ b/src/polkitbackend/Makefile.am
@@ -17,6 +17,8 @@ AM_CPPFLAGS =                                                   \
         -DPACKAGE_LIB_DIR=\""$(libdir)"\"                       \
         -D_POSIX_PTHREAD_SEMANTICS                              \
         -D_REENTRANT                                            \
+        -D_XOPEN_SOURCE=700                                     \
+        -D_GNU_SOURCE=1                                         \
         $(NULL)
 
 noinst_LTLIBRARIES=libpolkit-backend-1.la
diff --git a/src/polkitbackend/meson.build b/src/polkitbackend/meson.build
index 9ec01b2..266f280 100644
--- a/src/polkitbackend/meson.build
+++ b/src/polkitbackend/meson.build
@@ -29,11 +29,14 @@ c_flags = [
   '-D_POLKIT_BACKEND_COMPILATION',
   '-DPACKAGE_DATA_DIR="@0@"'.format(pk_prefix / pk_datadir),
   '-DPACKAGE_SYSCONF_DIR="@0@"'.format(pk_prefix / pk_sysconfdir),
+  '-D_XOPEN_SOURCE=700',
+  '-D_GNU_SOURCE=1',
 ]
 
 if js_engine == 'duktape'
   sources += files('polkitbackendduktapeauthority.c')
   deps += libm_dep
+  deps += thread_dep
 elif js_engine == 'mozjs'
   sources += files('polkitbackendjsauthority.cpp')
 endif
diff --git a/src/polkitbackend/polkitbackendcommon.h b/src/polkitbackend/polkitbackendcommon.h
index 6d0d267..dd700fc 100644
--- a/src/polkitbackend/polkitbackendcommon.h
+++ b/src/polkitbackend/polkitbackendcommon.h
@@ -50,6 +50,8 @@
 #include <systemd/sd-login.h>
 #endif /* HAVE_LIBSYSTEMD */
 
+#define RUNAWAY_KILLER_TIMEOUT (15)
+
 #ifdef __cplusplus
 extern "C" {
 #endif
diff --git a/src/polkitbackend/polkitbackendduktapeauthority.c b/src/polkitbackend/polkitbackendduktapeauthority.c
index a2b4420..c89dbcf 100644
--- a/src/polkitbackend/polkitbackendduktapeauthority.c
+++ b/src/polkitbackend/polkitbackendduktapeauthority.c
@@ -21,6 +21,8 @@
  * Author: David Zeuthen <davidz@redhat.com>
  */
 
+#include <pthread.h>
+
 #include "polkitbackendcommon.h"
 
 #include "duktape.h"
@@ -47,8 +49,20 @@ struct _PolkitBackendJsAuthorityPrivate
   GFileMonitor **dir_monitors; /* NULL-terminated array of GFileMonitor instances */
 
   duk_context *cx;
+
+  pthread_t runaway_killer_thread;
 };
 
+enum
+{
+  RUNAWAY_KILLER_THREAD_EXIT_STATUS_UNSET,
+  RUNAWAY_KILLER_THREAD_EXIT_STATUS_SUCCESS,
+  RUNAWAY_KILLER_THREAD_EXIT_STATUS_FAILURE,
+};
+
+static gboolean execute_script_with_runaway_killer(PolkitBackendJsAuthority *authority,
+                                                   const gchar *filename);
+
 /* ---------------------------------------------------------------------------------------------------- */
 
 G_DEFINE_TYPE (PolkitBackendJsAuthority, polkit_backend_js_authority, POLKIT_BACKEND_TYPE_INTERACTIVE_AUTHORITY);
@@ -67,6 +81,15 @@ static const duk_function_list_entry js_polkit_functions[] =
   { NULL, NULL, 0 },
 };
 
+static void report_error (void     *udata,
+                          const char *msg)
+{
+    PolkitBackendJsAuthority *authority = udata;
+    polkit_backend_authority_log (POLKIT_BACKEND_AUTHORITY (authority),
+                                  "fatal Duktape JS backend error: %s",
+                                  (msg ? msg : "no message"));
+}
+
 static void
 polkit_backend_js_authority_init (PolkitBackendJsAuthority *authority)
 {
@@ -78,7 +101,6 @@ polkit_backend_js_authority_init (PolkitBackendJsAuthority *authority)
 static void
 load_scripts (PolkitBackendJsAuthority  *authority)
 {
-  duk_context *cx = authority->priv->cx;
   GList *files = NULL;
   GList *l;
   guint num_scripts = 0;
@@ -123,36 +145,9 @@ load_scripts (PolkitBackendJsAuthority  *authority)
   for (l = files; l != NULL; l = l->next)
     {
       const gchar *filename = (gchar *)l->data;
-#if (DUK_VERSION >= 20000)
-      GFile *file = g_file_new_for_path (filename);
-      char *contents;
-      gsize len;
-      if (!g_file_load_contents (file, NULL, &contents, &len, NULL, NULL))
-        {
-          polkit_backend_authority_log (POLKIT_BACKEND_AUTHORITY (authority),
-                                        "Error compiling script %s",
-                                        filename);
-          g_object_unref (file);
-          continue;
-        }
 
-      g_object_unref (file);
-      if (duk_peval_lstring_noresult(cx, contents,len) != 0)
-#else
-      if (duk_peval_file_noresult (cx, filename) != 0)
-#endif
-        {
-          polkit_backend_authority_log (POLKIT_BACKEND_AUTHORITY (authority),
-                                        "Error compiling script %s: %s",
-                                        filename, duk_safe_to_string (authority->priv->cx, -1));
-#if (DUK_VERSION >= 20000)
-          g_free (contents);
-#endif
+      if (!execute_script_with_runaway_killer(authority, filename))
           continue;
-        }
-#if (DUK_VERSION >= 20000)
-      g_free (contents);
-#endif
       num_scripts++;
     }
 
@@ -232,7 +227,7 @@ polkit_backend_common_js_authority_constructed (GObject *object)
   PolkitBackendJsAuthority *authority = POLKIT_BACKEND_JS_AUTHORITY (object);
   duk_context *cx;
 
-  cx = duk_create_heap (NULL, NULL, NULL, authority, NULL);
+  cx = duk_create_heap (NULL, NULL, NULL, authority, report_error);
   if (cx == NULL)
     goto fail;
 
@@ -243,6 +238,9 @@ polkit_backend_common_js_authority_constructed (GObject *object)
   duk_put_function_list (cx, -1, js_polkit_functions);
   duk_put_prop_string (cx, -2, "polkit");
 
+  /* load polkit objects/functions into JS context (e.g. addRule(),
+   * _deleteRules(), _runRules() et al)
+   */
   duk_eval_string (cx, init_js);
 
   if (authority->priv->rules_dirs == NULL)
@@ -510,6 +508,250 @@ push_action_and_details (duk_context               *cx,
 
 /* ---------------------------------------------------------------------------------------------------- */
 
+typedef struct {
+  PolkitBackendJsAuthority *authority;
+  const gchar *filename;
+  pthread_cond_t cond;
+  pthread_mutex_t mutex;
+  gint ret;
+} RunawayKillerCtx;
+
+static gpointer
+runaway_killer_thread_execute_js (gpointer user_data)
+{
+  RunawayKillerCtx *ctx = user_data;
+  duk_context *cx = ctx->authority->priv->cx;
+
+  int oldtype, pthread_err;
+
+  if ((pthread_err = pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldtype))) {
+    polkit_backend_authority_log (POLKIT_BACKEND_AUTHORITY (ctx->authority),
+                                  "Error setting thread cancel type: %s",
+                                  strerror(pthread_err));
+    goto err;
+  }
+
+  GFile *file = g_file_new_for_path(ctx->filename);
+  char *contents;
+  gsize len;
+
+  if (!g_file_load_contents(file, NULL, &contents, &len, NULL, NULL)) {
+    polkit_backend_authority_log(POLKIT_BACKEND_AUTHORITY(ctx->authority),
+                                 "Error loading script %s", ctx->filename);
+    g_object_unref(file);
+    goto err;
+  }
+
+  g_object_unref(file);
+
+  /* evaluate the script, trying to print context in any syntax errors
+     found */
+  if (duk_peval_lstring(cx, contents, len) != 0)
+  {
+    polkit_backend_authority_log(POLKIT_BACKEND_AUTHORITY(ctx->authority),
+                                 "Error compiling script %s: %s", ctx->filename,
+                                 duk_safe_to_string(cx, -1));
+    duk_pop(cx);
+    goto free_err;
+  }
+  g_free(contents);
+
+  ctx->ret = RUNAWAY_KILLER_THREAD_EXIT_STATUS_SUCCESS;
+  goto end;
+
+free_err:
+  g_free(contents);
+err:
+  ctx->ret = RUNAWAY_KILLER_THREAD_EXIT_STATUS_FAILURE;
+end:
+  if ((pthread_err = pthread_cond_signal(&ctx->cond))) {
+    polkit_backend_authority_log (POLKIT_BACKEND_AUTHORITY (ctx->authority),
+                                  "Error signaling on condition variable: %s",
+                                  strerror(pthread_err));
+    ctx->ret = RUNAWAY_KILLER_THREAD_EXIT_STATUS_FAILURE;
+  }
+  return NULL;
+}
+
+static gpointer
+runaway_killer_thread_call_js (gpointer user_data)
+{
+  RunawayKillerCtx *ctx = user_data;
+  duk_context *cx = ctx->authority->priv->cx;
+  int oldtype, pthread_err;
+
+  if ((pthread_err = pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldtype))) {
+    polkit_backend_authority_log (POLKIT_BACKEND_AUTHORITY (ctx->authority),
+                                  "Error setting thread cancel type: %s",
+                                  strerror(pthread_err));
+    goto err;
+  }
+
+  if (duk_pcall_prop (cx, 0, 2) != DUK_EXEC_SUCCESS)
+    {
+      polkit_backend_authority_log (POLKIT_BACKEND_AUTHORITY (ctx->authority),
+                                    "Error evaluating admin rules: ",
+                                    duk_safe_to_string (cx, -1));
+      goto err;
+    }
+
+  ctx->ret = RUNAWAY_KILLER_THREAD_EXIT_STATUS_SUCCESS;
+  goto end;
+
+err:
+  ctx->ret = RUNAWAY_KILLER_THREAD_EXIT_STATUS_FAILURE;
+end:
+  if ((pthread_err = pthread_cond_signal(&ctx->cond))) {
+    polkit_backend_authority_log (POLKIT_BACKEND_AUTHORITY (ctx->authority),
+                                  "Error signaling on condition variable: %s",
+                                  strerror(pthread_err));
+    ctx->ret = RUNAWAY_KILLER_THREAD_EXIT_STATUS_FAILURE;
+  }
+  return NULL;
+}
+
+#if defined (HAVE_PTHREAD_CONDATTR_SETCLOCK)
+#  if defined(CLOCK_MONOTONIC)
+#    define PK_CLOCK CLOCK_MONOTONIC
+#  elif defined(CLOCK_BOOTTIME)
+#    define PK_CLOCK CLOCK_BOOTTIME
+#  else
+     /* No suitable clock */
+#    undef HAVE_PTHREAD_CONDATTR_SETCLOCK
+#    define PK_CLOCK CLOCK_REALTIME
+#  endif
+#else  /* ! HAVE_PTHREAD_CONDATTR_SETCLOCK */
+#  define PK_CLOCK CLOCK_REALTIME
+#endif /* ! HAVE_PTHREAD_CONDATTR_SETCLOCK */
+
+static gboolean
+runaway_killer_common(PolkitBackendJsAuthority *authority, RunawayKillerCtx *ctx, void *js_context_cb (void *user_data))
+{
+  int pthread_err;
+  gboolean cancel = FALSE;
+  pthread_condattr_t attr;
+  struct timespec abs_time;
+
+#ifdef HAVE_PTHREAD_CONDATTR_SETCLOCK
+  if ((pthread_err = pthread_condattr_init(&attr))) {
+    polkit_backend_authority_log (POLKIT_BACKEND_AUTHORITY (authority),
+                                  "Error initializing condition variable attributes: %s",
+                                  strerror(pthread_err));
+    return FALSE;
+  }
+  if ((pthread_err = pthread_condattr_setclock(&attr, PK_CLOCK))) {
+    polkit_backend_authority_log (POLKIT_BACKEND_AUTHORITY (authority),
+                                  "Error setting condition variable attributes: %s",
+                                  strerror(pthread_err));
+    goto err_clean_condattr;
+  }
+  /* Init again, with needed attr */
+  if ((pthread_err = pthread_cond_init(&ctx->cond, &attr))) {
+    polkit_backend_authority_log (POLKIT_BACKEND_AUTHORITY (authority),
+                                  "Error initializing condition variable: %s",
+                                  strerror(pthread_err));
+    goto err_clean_condattr;
+  }
+#endif
+
+  if ((pthread_err = pthread_mutex_lock(&ctx->mutex))) {
+    polkit_backend_authority_log (POLKIT_BACKEND_AUTHORITY (authority),
+                                  "Error locking mutex: %s",
+                                  strerror(pthread_err));
+    goto err_clean_cond;
+  }
+
+  if (clock_gettime(PK_CLOCK, &abs_time)) {
+    polkit_backend_authority_log (POLKIT_BACKEND_AUTHORITY (authority),
+                                  "Error getting system's monotonic time: %s",
+                                  strerror(errno));
+    goto err_clean_cond;
+  }
+  abs_time.tv_sec += RUNAWAY_KILLER_TIMEOUT;
+
+  if ((pthread_err = pthread_create(&authority->priv->runaway_killer_thread, NULL,
+                                    js_context_cb, ctx))) {
+    polkit_backend_authority_log (POLKIT_BACKEND_AUTHORITY (authority),
+                                  "Error creating runaway JS killer thread: %s",
+                                  strerror(pthread_err));
+    goto err_clean_cond;
+  }
+
+  while (ctx->ret == RUNAWAY_KILLER_THREAD_EXIT_STATUS_UNSET) /* loop to treat spurious wakeups */
+    if (pthread_cond_timedwait(&ctx->cond, &ctx->mutex, &abs_time) == ETIMEDOUT) {
+      cancel = TRUE;
+
+      /* Log that we are terminating the script */
+      polkit_backend_authority_log (POLKIT_BACKEND_AUTHORITY (authority),
+                                    "Terminating runaway script after %d seconds",
+                                    RUNAWAY_KILLER_TIMEOUT);
+
+      break;
+    }
+
+  if ((pthread_err = pthread_mutex_unlock(&ctx->mutex))) {
+    polkit_backend_authority_log (POLKIT_BACKEND_AUTHORITY (authority),
+                                  "Error unlocking mutex: %s",
+                                  strerror(pthread_err));
+    goto err_clean_cond;
+  }
+
+  if (cancel) {
+    if ((pthread_err = pthread_cancel (authority->priv->runaway_killer_thread))) {
+      polkit_backend_authority_log (POLKIT_BACKEND_AUTHORITY (authority),
+                                    "Error cancelling runaway JS killer thread: %s",
+                                    strerror(pthread_err));
+      goto err_clean_cond;
+    }
+  }
+  if ((pthread_err = pthread_join (authority->priv->runaway_killer_thread, NULL))) {
+      polkit_backend_authority_log (POLKIT_BACKEND_AUTHORITY (authority),
+                                    "Error joining runaway JS killer thread: %s",
+                                    strerror(pthread_err));
+      goto err_clean_cond;
+    }
+
+  return ctx->ret == RUNAWAY_KILLER_THREAD_EXIT_STATUS_SUCCESS;
+
+    err_clean_cond:
+#ifdef HAVE_PTHREAD_CONDATTR_SETCLOCK
+  pthread_cond_destroy(&ctx->cond);
+#endif
+    err_clean_condattr:
+#ifdef HAVE_PTHREAD_CONDATTR_SETCLOCK
+  pthread_condattr_destroy(&attr);
+#endif
+  return FALSE;
+}
+
+/* Blocking for at most RUNAWAY_KILLER_TIMEOUT */
+static gboolean
+execute_script_with_runaway_killer(PolkitBackendJsAuthority *authority,
+                                   const gchar *filename)
+{
+  RunawayKillerCtx ctx = {.authority = authority, .filename = filename,
+                          .ret = RUNAWAY_KILLER_THREAD_EXIT_STATUS_UNSET,
+                          .mutex = PTHREAD_MUTEX_INITIALIZER,
+                          .cond = PTHREAD_COND_INITIALIZER};
+
+  return runaway_killer_common(authority, &ctx, &runaway_killer_thread_execute_js);
+}
+
+/* Calls already stacked function and args. Blocking for at most
+ * RUNAWAY_KILLER_TIMEOUT. If timeout is the case, ctx.ret will be
+ * RUNAWAY_KILLER_THREAD_EXIT_STATUS_UNSET, thus returning FALSE.
+ */
+static gboolean
+call_js_function_with_runaway_killer(PolkitBackendJsAuthority *authority)
+{
+  RunawayKillerCtx ctx = {.authority = authority,
+                          .ret = RUNAWAY_KILLER_THREAD_EXIT_STATUS_UNSET,
+                          .mutex = PTHREAD_MUTEX_INITIALIZER,
+                          .cond = PTHREAD_COND_INITIALIZER};
+
+  return runaway_killer_common(authority, &ctx, &runaway_killer_thread_call_js);
+}
+
 /* ---------------------------------------------------------------------------------------------------- */
 
 GList *
@@ -557,13 +799,8 @@ polkit_backend_common_js_authority_get_admin_auth_identities (PolkitBackendInter
       goto out;
     }
 
-  if (duk_pcall_prop (cx, 0, 2) != DUK_ERR_NONE)
-    {
-      polkit_backend_authority_log (POLKIT_BACKEND_AUTHORITY (authority),
-                                    "Error evaluating admin rules: ",
-                                    duk_safe_to_string (cx, -1));
-      goto out;
-    }
+  if (!call_js_function_with_runaway_killer (authority))
+    goto out;
 
   ret_str = duk_require_string (cx, -1);
 
@@ -643,15 +880,15 @@ polkit_backend_common_js_authority_check_authorization_sync (PolkitBackendIntera
       goto out;
     }
 
-  if (duk_pcall_prop (cx, 0, 2) != DUK_ERR_NONE)
-  {
-      polkit_backend_authority_log (POLKIT_BACKEND_AUTHORITY (authority),
-                                    "Error evaluating authorization rules: ",
-                                    duk_safe_to_string (cx, -1));
-      goto out;
-  }
+  // If any error is the js context happened (ctx.ret ==
+  // RUNAWAY_KILLER_THREAD_EXIT_STATUS_FAILURE) or it never properly returned
+  // (runaway scripts or ctx.ret == RUNAWAY_KILLER_THREAD_EXIT_STATUS_UNSET),
+  // unauthorize
+  if (!call_js_function_with_runaway_killer (authority))
+    goto out;
 
   if (duk_is_null(cx, -1)) {
+    /* this is fine, means there was no match, use implicit authorizations */
     good = TRUE;
     goto out;
   }
@@ -690,11 +927,7 @@ js_polkit_log (duk_context *cx)
 static duk_ret_t
 js_polkit_spawn (duk_context *cx)
 {
-#if (DUK_VERSION >= 20000)
   duk_ret_t ret = DUK_RET_ERROR;
-#else
-  duk_ret_t ret = DUK_RET_INTERNAL_ERROR;
-#endif
   gchar *standard_output = NULL;
   gchar *standard_error = NULL;
   gint exit_status;
diff --git a/src/polkitbackend/polkitbackendjsauthority.cpp b/src/polkitbackend/polkitbackendjsauthority.cpp
index e28091d..11e91c0 100644
--- a/src/polkitbackend/polkitbackendjsauthority.cpp
+++ b/src/polkitbackend/polkitbackendjsauthority.cpp
@@ -829,11 +829,14 @@ runaway_killer_setup (PolkitBackendJsAuthority *authority)
 {
   g_assert (authority->priv->rkt_source == NULL);
 
-  /* set-up timer for runaway scripts, will be executed in runaway_killer_thread */
+  /* set-up timer for runaway scripts, will be executed in
+     runaway_killer_thread, that is one, permanent thread running a glib
+     mainloop (rkt_loop) whose context (rkt_context) has a timeout source
+     (rkt_source) */
   g_mutex_lock (&authority->priv->rkt_timeout_pending_mutex);
   authority->priv->rkt_timeout_pending = FALSE;
   g_mutex_unlock (&authority->priv->rkt_timeout_pending_mutex);
-  authority->priv->rkt_source = g_timeout_source_new_seconds (15);
+  authority->priv->rkt_source = g_timeout_source_new_seconds (RUNAWAY_KILLER_TIMEOUT);
   g_source_set_callback (authority->priv->rkt_source, rkt_on_timeout, authority, NULL);
   g_source_attach (authority->priv->rkt_source, authority->priv->rkt_context);
 
@@ -893,6 +896,9 @@ execute_script_with_runaway_killer (PolkitBackendJsAuthority *authority,
 {
   bool ret;
 
+  // tries to JS_ExecuteScript(), may hang for > RUNAWAY_KILLER_TIMEOUT,
+  // runaway_killer_thread makes sure the call returns, due to exception
+  // injection
   runaway_killer_setup (authority);
   ret = JS_ExecuteScript (authority->priv->cx,
                           script,
diff --git a/test/data/etc/polkit-1/rules.d/10-testing.rules b/test/data/etc/polkit-1/rules.d/10-testing.rules
index 98bf062..e346b5d 100644
--- a/test/data/etc/polkit-1/rules.d/10-testing.rules
+++ b/test/data/etc/polkit-1/rules.d/10-testing.rules
@@ -189,8 +189,10 @@ polkit.addRule(function(action, subject) {
                 ;
         } catch (error) {
             if (error == "Terminating runaway script")
-                return polkit.Result.YES;
-            return polkit.Result.NO;
+                // Inverted logic to accomodate Duktape's model as well, which
+                // will always fail with negation, on timeouts
+                return polkit.Result.NO;
+            return polkit.Result.YES;
         }
     }
 });
diff --git a/test/polkitbackend/test-polkitbackendjsauthority.c b/test/polkitbackend/test-polkitbackendjsauthority.c
index f97e0e0..2103b17 100644
--- a/test/polkitbackend/test-polkitbackendjsauthority.c
+++ b/test/polkitbackend/test-polkitbackendjsauthority.c
@@ -328,7 +328,7 @@ static const RulesTestCase rules_test_cases[] = {
     "net.company.run_away_script",
     "unix-user:root",
     NULL,
-    POLKIT_IMPLICIT_AUTHORIZATION_AUTHORIZED,
+    POLKIT_IMPLICIT_AUTHORIZATION_NOT_AUTHORIZED,
   },
 
   {
-- 
GitLab


From 478bcc0b6b4fb44d4199c475d1581d78a8b6c30b Mon Sep 17 00:00:00 2001
From: Gustavo Lima Chaves <gustavo.chaves@microsoft.com>
Date: Thu, 28 Oct 2021 10:04:53 -0700
Subject: [PATCH 17/17] duktape: document runaway behavior

Signed-off-by: Gustavo Lima Chaves <gustavo.chaves@microsoft.com>
---
 docs/man/polkit.xml | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)

diff --git a/docs/man/polkit.xml b/docs/man/polkit.xml
index 99aa474..90715a5 100644
--- a/docs/man/polkit.xml
+++ b/docs/man/polkit.xml
@@ -639,7 +639,9 @@ polkit.Result = {
         If user-provided code takes a long time to execute, an exception
         will be thrown which normally results in the function being
         terminated (the current limit is 15 seconds). This is used to
-        catch runaway scripts.
+        catch runaway scripts. If the duktape JavaScript backend is
+        compiled in, instead of mozjs, no exception will be thrown—the
+        script will be killed right away (same timeout).
       </para>
 
       <para>
-- 
GitLab