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
|
# $Id: TLUtils.pm 70774 2024-03-26 15:39:45Z karl $
# TeXLive::TLUtils.pm - the inevitable utilities for TeX Live.
# Copyright 2007-2024 Norbert Preining, Reinhard Kotucha
# This file is licensed under the GNU General Public License version 2
# or any later version.
use strict; use warnings;
package TeXLive::TLUtils;
my $svnrev = '$Revision: 70774 $';
my $_modulerevision = ($svnrev =~ m/: ([0-9]+) /) ? $1 : "unknown";
sub module_revision { return $_modulerevision; }
=pod
=head1 NAME
C<TeXLive::TLUtils> - TeX Live infrastructure miscellany
=head1 SYNOPSIS
use TeXLive::TLUtils;
=head2 Platform detection
TeXLive::TLUtils::platform();
TeXLive::TLUtils::platform_name($canonical_host);
TeXLive::TLUtils::platform_desc($platform);
TeXLive::TLUtils::wndws();
TeXLive::TLUtils::unix();
=head2 System tools
TeXLive::TLUtils::getenv($string);
TeXLive::TLUtils::which($string);
TeXLive::TLUtils::initialize_global_tmpdir();
TeXLive::TLUtils::tl_tmpdir();
TeXLive::TLUtils::tl_tmpfile();
TeXLive::TLUtils::xchdir($dir);
TeXLive::TLUtils::wsystem($msg,@args);
TeXLive::TLUtils::xsystem(@args);
TeXLive::TLUtils::run_cmd($cmd [, @envvars ]);
TeXLive::TLUtils::run_cmd_with_log($cmd, $logfn);
TeXLive::TLUtils::system_pipe($prog, $infile, $outfile, $removeIn, @args);
TeXLive::TLUtils::diskfree($path);
TeXLive::TLUtils::get_user_home();
TeXLive::TLUtils::expand_tilde($str);
=head2 File utilities
TeXLive::TLUtils::dirname($path);
TeXLive::TLUtils::basename($path);
TeXLive::TLUtils::dirname_and_basename($path);
TeXLive::TLUtils::tl_abs_path($path);
TeXLive::TLUtils::dir_writable($path);
TeXLive::TLUtils::dir_creatable($path);
TeXLive::TLUtils::mkdirhier($path);
TeXLive::TLUtils::rmtree($root, $verbose, $safe);
TeXLive::TLUtils::copy($file, $target_dir);
TeXLive::TLUtils::touch(@files);
TeXLive::TLUtils::collapse_dirs(@files);
TeXLive::TLUtils::all_dirs_and_removed_dirs(@files);
TeXLive::TLUtils::dirs_of_files(@files);
TeXLive::TLUtils::removed_dirs(@files);
TeXLive::TLUtils::download_file($path, $destination);
TeXLive::TLUtils::setup_programs($bindir, $platform);
TeXLive::TLUtils::tlcmp($file, $file);
TeXLive::TLUtils::nulldev();
TeXLive::TLUtils::get_full_line($fh);
=head2 Installer functions
TeXLive::TLUtils::make_var_skeleton($path);
TeXLive::TLUtils::make_local_skeleton($path);
TeXLive::TLUtils::create_fmtutil($tlpdb,$dest);
TeXLive::TLUtils::create_updmap($tlpdb,$dest);
TeXLive::TLUtils::create_language_dat($tlpdb,$dest,$localconf);
TeXLive::TLUtils::create_language_def($tlpdb,$dest,$localconf);
TeXLive::TLUtils::create_language_lua($tlpdb,$dest,$localconf);
TeXLive::TLUtils::time_estimate($totalsize, $donesize, $starttime)
TeXLive::TLUtils::install_packages($from_tlpdb,$media,$to_tlpdb,$what,$opt_src, $opt_doc, $retry, $continue);
TeXLive::TLUtils::do_postaction($how, $tlpobj, $do_fileassocs, $do_menu, $do_desktop, $do_script);
TeXLive::TLUtils::update_context_cache($plat_bindir);
TeXLive::TLUtils::announce_execute_actions($how, @executes, $what);
TeXLive::TLUtils::add_symlinks($root, $arch, $sys_bin, $sys_man, $sys_info);
TeXLive::TLUtils::remove_symlinks($root, $arch, $sys_bin, $sys_man, $sys_info);
TeXLive::TLUtils::w32_add_to_path($bindir, $multiuser);
TeXLive::TLUtils::w32_remove_from_path($bindir, $multiuser);
TeXLive::TLUtils::setup_persistent_downloads();
=head2 Logging and debugging
TeXLive::TLUtils::info($str1, ...); # output unless -q
TeXLive::TLUtils::debug($str1, ...); # output if -v
TeXLive::TLUtils::ddebug($str1, ...); # output if -vv
TeXLive::TLUtils::dddebug($str1, ...); # output if -vvv
TeXLive::TLUtils::log($str1, ...); # only to log file
TeXLive::TLUtils::tlwarn($str1, ...); # warn on stderr and log
TeXLive::TLUtils::tldie($str1, ...); # tlwarn and die
TeXLive::TLUtils::debug_hash_str($label, HASH); # stringified HASH
TeXLive::TLUtils::debug_hash($label, HASH); # warn stringified HASH
TeXLive::TLUtils::backtrace(); # return call stack as string
TeXLive::TLUtils::process_logging_options($texdir); # handle -q -v* -logfile
=head2 Miscellaneous
TeXLive::TLUtils::sort_uniq(@list);
TeXLive::TLUtils::push_uniq(\@list, @items);
TeXLive::TLUtils::member($item, @list);
TeXLive::TLUtils::merge_into(\%to, \%from);
TeXLive::TLUtils::texdir_check($texdir);
TeXLive::TLUtils::compare_tlpobjs($tlpA, $tlpB);
TeXLive::TLUtils::compare_tlpdbs($tlpdbA, $tlpdbB);
TeXLive::TLUtils::report_tlpdb_differences(\%ret);
TeXLive::TLUtils::tlnet_disabled_packages($root);
TeXLive::TLUtils::mktexupd();
TeXLive::TLUtils::setup_sys_user_mode($prg,$optsref,$tmfc,$tmfsc,$tmfv,$tmfsv);
TeXLive::TLUtils::prepend_own_path();
TeXLive::TLUtils::repository_to_array($str);
=head2 Windows and paths
TeXLive::TLUtils::quotify_path_with_spaces($path);
TeXLive::TLUtils::conv_to_w32_path($path);
TeXLive::TLUtils::native_slashify($internal_path);
TeXLive::TLUtils::forward_slashify($path_from_user);
=head2 CTAN
TeXLive::TLUtils::give_ctan_mirror();
TeXLive::TLUtils::give_ctan_mirror_base();
=head2 JSON
TeXLive::TLUtils::encode_json($ref);
TeXLive::TLUtils::True();
TeXLive::TLUtils::False();
=head1 DESCRIPTION
=cut
# avoid -warnings.
our $PERL_SINGLE_QUOTE; # we steal code from Text::ParseWords
# We use myriad global and package-global variables, unfortunately.
# To avoid "used only once" warnings, we must use the variable names again.
#
# This ugly repetition in the BEGIN block works with all Perl versions;
# cleaner/fancier ways of handling this don't.
BEGIN {
$::LOGFILE = $::LOGFILE;
$::LOGFILENAME = $::LOGFILENAME;
@::LOGLINES = @::LOGLINES;
@::debug_hook = @::debug_hook;
@::ddebug_hook = @::ddebug_hook;
@::dddebug_hook = @::dddebug_hook;
@::info_hook = @::info_hook;
@::install_packages_hook = @::install_packages_hook;
@::installation_failed_packages = @::installation_failed_packages;
@::warn_hook = @::warn_hook;
$::checksum_method = $::checksum_method;
$::gui_mode = $::gui_mode;
$::machinereadable = $::machinereadable;
$::no_execute_actions = $::no_execute_actions;
$::regenerate_all_formats = $::regenerate_all_formats;
$::context_cache_update_needed = $::context_cache_update_needed;
#
$JSON::false = $JSON::false;
$JSON::true = $JSON::true;
#
$TeXLive::TLDownload::net_lib_avail = $TeXLive::TLDownload::net_lib_avail;
}
## A cleaner way is to use the "package PKGNAME BLOCK" syntax:
## when providing a block to the package command, the scope is
## limited to that block, so the current real package ends up unaffected.
## Example in first reply to: https://perlmonks.org/?node_id=11139324
## (Other solutions are also given there, but they don't work well in
## our context here, although we use them elsewhere.)
##
## Unfortunately the package BLOCK syntax was invented for perl 5.14.0,
## ca.2011, and OpenCSW on Solaris 10 only provides an older Perl. If we
## ever drop Solaris 10 support, we can replace the above with this.
##
#package main {
# our ($LOGFILE, $LOGFILENAME, @LOGLINES,
# @debug_hook, @ddebug_hook, @dddebug_hook, @info_hook,
# @install_packages_hook, @warn_hook,
# $checksum_method, $gui_mode, $machinereadable,
# $no_execute_actions, $regenerate_all_formats); }
#package JSON { our ($false, $true); }
#package TeXLive::TLDownload { our $net_lib_avail; }
BEGIN {
use Exporter ();
use vars qw(@ISA @EXPORT_OK @EXPORT);
@ISA = qw(Exporter);
@EXPORT_OK = qw(
&platform
&platform_name
&platform_desc
&unix
&getenv
&which
&initialize_global_tmpdir
&dirname
&basename
&dirname_and_basename
&tl_abs_path
&dir_writable
&dir_creatable
&mkdirhier
&rmtree
©
&touch
&collapse_dirs
&all_dirs_and_removed_dirs
&dirs_of_files
&removed_dirs
&install_package
&install_packages
&make_var_skeleton
&make_local_skeleton
&create_fmtutil
&create_updmap
&create_language_dat
&create_language_def
&create_language_lua
&parse_AddFormat_line
&parse_AddHyphen_line
&sort_uniq
&push_uniq
&texdir_check
&member
"ewords
"ify_path_with_spaces
&conv_to_w32_path
&native_slashify
&forward_slashify
&untar
&unpack
&merge_into
&give_ctan_mirror
&give_ctan_mirror_base
&create_mirror_list
&extract_mirror_entry
&system_ok
&wsystem
&xsystem
&run_cmd
&run_cmd_with_log
&system_pipe
&diskfree
&get_user_home
&expand_tilde
&announce_execute_actions
&add_symlinks
&remove_symlinks
&w32_add_to_path
&w32_remove_from_path
&tlcmp
&time_estimate
&compare_tlpobjs
&compare_tlpdbs
&report_tlpdb_differences
&setup_persistent_downloads
&mktexupd
&setup_sys_user_mode
&prepend_own_path
&nulldev
&get_full_line
&sort_archs
&repository_to_array
&encode_json
&True
&False
&SshURIRegex
);
@EXPORT = qw(setup_programs download_file process_logging_options
tldie tlwarn info log debug ddebug dddebug debug
debug_hash_str debug_hash
wndws xchdir xsystem run_cmd system_pipe sort_archs);
}
use Cwd;
use Getopt::Long;
use File::Temp;
use TeXLive::TLConfig;
$::opt_verbosity = 0; # see process_logging_options
our $SshURIRegex = '^((ssh|scp)://([^@]*)@([^/]*)/|([^@]*)@([^:]*):).*$';
=head2 Platform detection
=over 4
=item C<platform>
If C<$^O =~ /MSWin/i> is true we know that we're on
Windows and we set the global variable C<$::_platform_> to C<windows>.
Otherwise we call C<platform_name> with the output of C<config.guess>
as argument.
The result is stored in a global variable C<$::_platform_>, and
subsequent calls just return that value.
As of 2021, C<config.guess> unfortunately requires a shell that
understands the C<$(...)> construct. This means that on old-enough
systems, such as Solaris, we have to look for a shell. We use the value
of the C<CONFIG_SHELL> environment variable if it is set, else
C</bin/ksh> if it exists, else C</bin/bash> if it exists, else give up.
Happily, C<config.guess> later reverted this change, but we keep our
shell-finding code anyway to defend against future mistakes of the same ilk.
=cut
sub platform {
if (! defined $::_platform_) {
if ($^O =~ /^MSWin/i) {
# print STDERR "\$^O is $^O\n";
$::_platform_ = "windows";
} else {
my $config_guess = "$::installerdir/tlpkg/installer/config.guess";
# For example, if the disc or reader has hardware problems.
die "$0: config.guess script does not exist, goodbye: $config_guess"
if ! -r $config_guess;
# We cannot rely on #! in config.guess but have to call /bin/sh
# explicitly because sometimes the 'noexec' flag is set in
# /etc/fstab for ISO9660 file systems.
#
# In addition, config.guess was (unnecessarily) changed in 2020 by
# to use $(...) instead of `...`, although $(...) is not supported
# by Solaris /bin/sh (and others). The maintainers have declined
# to revert the change, so now every caller of config.guess must
# laboriously find a usable shell. Sigh.
#
my $config_shell = $ENV{"CONFIG_SHELL"} || "/bin/sh";
#
# check if $(...) is supported:
my $paren_cmdout = `'$config_shell' -c 'echo \$(echo foo)' 2>/dev/null`;
#warn "paren test out: `$paren_cmdout'.\n";
#
# The echo command might output a newline (maybe CRLF?) even if
# the $(...) fails, so don't just check for non-empty output.
# Maybe checking exit status would be better, but maybe not.
#
if (length ($paren_cmdout) <= 2) {
# if CONFIG_SHELL is set to something bad, give up.
if ($ENV{"CONFIG_SHELL"}) {
die <<END_BAD_CONFIG_SHELL;
$0: the CONFIG_SHELL environment variable is set to $ENV{CONFIG_SHELL}
but this cannot execute \$(...) shell constructs,
which is required. Set CONFIG_SHELL to something that works.
END_BAD_CONFIG_SHELL
} elsif (-x "/bin/ksh") {
$config_shell = "/bin/ksh";
} elsif (-x "/bin/bash") {
$config_shell = "/bin/bash";
} else {
die <<END_NO_PAREN_CMDS_SHELL
$0: can't find shell to execute $config_guess
(which gratuitously requires support for \$(...) command substitution).
Tried $config_shell, /bin/ksh, bin/bash.
Set the environment variable CONFIG_SHELL to specify explicitly.
END_NO_PAREN_CMDS_SHELL
}
}
#warn "executing config.guess with $config_shell\n";
chomp (my $guessed_platform = `'$config_shell' '$config_guess'`);
# If we didn't get anything usable, give up.
die "$0: could not run $config_guess, cannot proceed, sorry"
if ! $guessed_platform;
$::_platform_ = platform_name($guessed_platform);
}
}
return $::_platform_;
}
=item C<platform_name($canonical_host)>
Convert the C<$canonical_host> argument, a system description as
returned by C<config.guess>, into a TeX Live platform name, that is, a
name used as a subdirectory of our C<bin/> dir. Our names have the
form CPU-OS, for example, C<x86_64-linux>.
We need this because what's returned from C<config.,guess> does not
match our historical names, e.g., C<config.guess> returns C<linux-gnu>
but we need C<linux>.
The C<CPU> part of our name is always taken from the argument, with
various transformation.
For the C<OS> part, if the environment variable C<TEXLIVE_OS_NAME> is
set, it is used as-is. Otherwise we do our best to figure it out.
This function still handles old systems which are no longer supported,
just in case.
=cut
sub platform_name {
my ($orig_platform) = @_;
my $guessed_platform = $orig_platform;
# try to parse out some bsd variants that use amd64.
# We throw away everything after the "bsd" to elide version numbers,
# as in amd64-unknown-midnightbsd1.2.
$guessed_platform =~ s/^x86_64-(.*-k?)(free|net)bsd/amd64-$1$2bsd/;
my $CPU; # CPU type as reported by config.guess.
my $OS; # O/S type as reported by config.guess.
($CPU = $guessed_platform) =~ s/(.*?)-.*/$1/;
$CPU =~ s/^alpha(.*)/alpha/; # alphaev whatever
$CPU =~ s/mips64el/mipsel/; # don't distinguish mips64 and 32 el
$CPU =~ s/powerpc64/powerpc/; # don't distinguish ppc64
$CPU =~ s/sparc64/sparc/; # don't distinguish sparc64
# armv6l-unknown-linux-gnueabihf -> armhf-linux (RPi)
# armv7l-unknown-linux-gnueabi -> armel-linux (Android)
if ($CPU =~ /^arm/) {
$CPU = $guessed_platform =~ /hf$/ ? "armhf" : "armel";
}
if ($ENV{"TEXLIVE_OS_NAME"}) {
$OS = $ENV{"TEXLIVE_OS_NAME"};
} else {
my @OSs = qw(aix cygwin darwin dragonfly freebsd hpux irix
kfreebsd linux midnightbsd netbsd openbsd solaris);
for my $os (@OSs) {
# Match word boundary at the beginning of the os name so that
# freebsd and kfreebsd are distinguished.
# Do not match word boundary at the end of the os so that
# solaris2 is matched.
$OS = $os if $guessed_platform =~ /\b$os/;
}
}
if (! $OS) {
warn "$0: could not guess OS from config.guess string: $orig_platform";
$OS = "unknownOS";
}
if ($OS eq "linux") {
# deal with the special case of musl based distributions
# config.guess returns
# x86_64-pc-linux-musl
# i386-pc-linux-musl
$OS = "linuxmusl" if $guessed_platform =~ /\blinux-musl/;
}
if ($OS eq "darwin") {
# We have two versions of Mac binary sets.
# 10.x and newer -> universal-darwin [MacTeX]
# 10.6/Snow Leopard through 10.x -> x86_64-darwinlegacy, if 64-bit.
# x changes every year. As of TL 2021 (Big Sur) Apple started with 11.x.
#
# (BTW, uname -r numbers are larger by 4 than the Mac minor version.
# We don't use uname numbers here.)
#
# this changes each year, per above:
my $mactex_darwin = 14; # lowest minor rev supported by universal-darwin.
#
# Most robust approach is apparently to check sw_vers (os version,
# returns "10.x" values), and sysctl (processor hardware).
chomp (my $sw_vers = `sw_vers -productVersion`);
my ($os_major,$os_minor) = split (/\./, $sw_vers);
if ($os_major < 10) {
warn "$0: only MacOSX is supported, not $OS $os_major.$os_minor "
. " (from sw_vers -productVersion: $sw_vers)\n";
return "unknownmac-unknownmac";
}
# have to refine after all 10.x become "legacy".
if ($os_major >= 11 || $os_minor >= $mactex_darwin) {
$CPU = "universal";
$OS = "darwin";
} elsif ($os_major == 10 && 6 <= $os_minor && $os_minor < $mactex_darwin){
# in between, x86 hardware only. On 10.6 only, must check if 64-bit,
# since if later than that, always 64-bit.
my $is64 = $os_minor == 6
? `/usr/sbin/sysctl -n hw.cpu64bit_capable` >= 1
: 1;
if ($is64) {
$CPU = "x86_64";
$OS = "darwinlegacy";
} # if not 64-bit, default is ok (i386-darwin).
} else {
; # older version, default is ok (i386-darwin, powerpc-darwin).
}
} elsif ($CPU =~ /^i.86$/) {
$CPU = "i386"; # 586, 686, whatever
}
if (! defined $OS) {
($OS = $guessed_platform) =~ s/.*-(.*)/$1/;
}
return "$CPU-$OS";
}
=item C<platform_desc($platform)>
Return a string which describes a particular platform identifier, e.g.,
given C<i386-linux> we return C<Intel x86 with GNU/Linux>.
=cut
sub platform_desc {
my ($platform) = @_;
my %platform_name = (
'aarch64-linux' => 'GNU/Linux on ARM64',
'alpha-linux' => 'GNU/Linux on DEC Alpha',
'amd64-freebsd' => 'FreeBSD on x86_64',
'amd64-kfreebsd' => 'GNU/kFreeBSD on x86_64',
'amd64-midnightbsd'=> 'MidnightBSD on x86_64',
'amd64-netbsd' => 'NetBSD on x86_64',
'armel-linux' => 'GNU/Linux on ARM',
'armhf-linux' => 'GNU/Linux on RPi(32-bit) and ARMv7',
'hppa-hpux' => 'HP-UX',
'i386-cygwin' => 'Cygwin on Intel x86',
'i386-darwin' => 'MacOSX legacy (10.5-10.6) on Intel x86',
'i386-freebsd' => 'FreeBSD on Intel x86',
'i386-kfreebsd' => 'GNU/kFreeBSD on Intel x86',
'i386-linux' => 'GNU/Linux on Intel x86',
'i386-linuxmusl' => 'GNU/Linux on Intel x86 with musl',
'i386-netbsd' => 'NetBSD on Intel x86',
'i386-openbsd' => 'OpenBSD on Intel x86',
'i386-solaris' => 'Solaris on Intel x86',
'mips-irix' => 'SGI IRIX',
'mipsel-linux' => 'GNU/Linux on MIPSel',
'powerpc-aix' => 'AIX on PowerPC',
'powerpc-darwin' => 'MacOSX legacy (10.5) on PowerPC',
'powerpc-linux' => 'GNU/Linux on PowerPC',
'sparc-linux' => 'GNU/Linux on Sparc',
'sparc-solaris' => 'Solaris on Sparc',
'universal-darwin' => 'MacOSX current (10.14-) on ARM/x86_64',
'win32' => 'Windows (32-bit)',
'windows' => 'Windows (64-bit)',
'x86_64-cygwin' => 'Cygwin on x86_64',
'x86_64-darwinlegacy' => 'MacOSX legacy (10.6-) on x86_64',
'x86_64-dragonfly' => 'DragonFlyBSD on x86_64',
'x86_64-linux' => 'GNU/Linux on x86_64',
'x86_64-linuxmusl' => 'GNU/Linux on x86_64 with musl',
'x86_64-solaris' => 'Solaris on x86_64',
);
# the inconsistency between amd64-freebsd and x86_64-linux is
# unfortunate (it's the same hardware), but the os people say those
# are the conventional names on the respective os's, so we follow suit.
if (exists $platform_name{$platform}) {
return "$platform_name{$platform}";
} else {
my ($CPU,$OS) = split ('-', $platform);
$OS = "" if ! defined $OS; # e.g., -force-platform foo
return "$CPU with " . ucfirst "$OS";
}
}
=item C<wndws>
Return C<1> if platform is Windows and C<0> otherwise. The test is
currently based on the value of Perl's C<$^O> variable.
=cut
sub wndws {
if ($^O =~ /^MSWin/i) {
return 1;
} else {
return 0;
}
# the following needs config.guess, which is quite bad ...
# return (&platform eq "windows")? 1:0;
}
=item C<unix>
Return C<1> if platform is UNIX and C<0> otherwise.
=cut
sub unix {
return (&platform eq "windows")? 0:1;
}
=back
=head2 System Tools
=over 4
=item C<getenv($string)>
Get an environment variable. It is assumed that the environment
variable contains a path. On Windows all backslashes are replaced by
forward slashes as required by Perl. If this behavior is not desired,
use C<$ENV{"$variable"}> instead. C<0> is returned if the
environment variable is not set.
=cut
sub getenv {
my $envvar=shift;
my $var=$ENV{"$envvar"};
return 0 unless (defined $var);
if (&wndws) {
$var=~s!\\!/!g; # change \ -> / (required by Perl)
}
return "$var";
}
=item C<which($string)>
C<which> does the same as the UNIX command C<which(1)>, but it is
supposed to work on Windows too. On Windows we have to try all the
extensions given in the C<PATHEXT> environment variable. We also try
without appending an extension because if C<$string> comes from an
environment variable, an extension might already be present.
=cut
sub which {
my ($prog) = @_;
my @PATH;
my $PATH = getenv('PATH');
if (&wndws) {
my @PATHEXT = split (';', getenv('PATHEXT'));
push (@PATHEXT, ''); # in case argument contains an extension
@PATH = split (';', $PATH);
for my $dir (@PATH) {
for my $ext (@PATHEXT) {
if (-f "$dir/$prog$ext") {
return "$dir/$prog$ext";
}
}
}
} else { # not windows
@PATH = split (':', $PATH);
for my $dir (@PATH) {
if (-x "$dir/$prog") {
return "$dir/$prog";
}
}
}
return 0;
}
=item C<initialize_global_tmpdir();>
Initializes a directory for all temporary files. This uses C<File::Temp>
and thus honors various env variables like C<TMPDIR>, C<TMP>, and C<TEMP>.
=cut
sub initialize_global_tmpdir {
$::tl_tmpdir = File::Temp::tempdir(CLEANUP => 1);
ddebug("TLUtils::initialize_global_tmpdir: creating global tempdir $::tl_tmpdir\n");
return ($::tl_tmpdir);
}
=item C<tl_tmpdir>
Create a temporary directory which is removed when the program
is terminated.
=cut
sub tl_tmpdir {
initialize_global_tmpdir() if (!defined($::tl_tmpdir));
my $tmp = File::Temp::tempdir(DIR => $::tl_tmpdir, CLEANUP => 1);
ddebug("TLUtils::tl_tmpdir: creating tempdir $tmp\n");
return ($tmp);
}
=item C<tl_tmpfile>
Create a temporary file which is removed when the program
is terminated. Returns file handle and file name.
Arguments are passed on to C<File::Temp::tempfile>.
=cut
sub tl_tmpfile {
initialize_global_tmpdir() if (!defined($::tl_tmpdir));
my ($fh, $fn) = File::Temp::tempfile(@_, DIR => $::tl_tmpdir, UNLINK => 1);
ddebug("TLUtils::tl_tempfile: creating tempfile $fn\n");
return ($fh, $fn);
}
=item C<xchdir($dir)>
C<chdir($dir)> or die.
=cut
sub xchdir {
my ($dir) = @_;
chdir($dir) || die "$0: chdir($dir) failed: $!";
ddebug("xchdir($dir) ok\n");
}
=item C<system_ok($cmdline)>
Run C<system($cmdline)> and return true if return status was zero, false
if status was nonzero. Throw away stdout and stderr.
=cut
sub system_ok {
my $nulldev = nulldev();
my ($cmdline) = @_;
`$cmdline >$nulldev 2>&1`;
return $? == 0;
}
=item C<wsystem($msg, @args)>
Call C<info> about what is being done starting with C<$msg>, then run
C<system(@args)>; C<tlwarn> if unsuccessful and return the exit status.
=cut
sub wsystem {
my ($msg,@args) = @_;
info("$msg @args ...\n");
my $retval = system(@args);
if ($retval != 0) {
$retval /= 256 if $retval > 0;
tlwarn("$0: command failed (status $retval): @args: $!\n");
}
return $retval;
}
=item C<xsystem(@args)>
Call C<ddebug> about what is being done, then run C<system(@args)>, and
die if unsuccessful.
=cut
sub xsystem {
my (@args) = @_;
ddebug("running system(@args)\n");
my $retval = system(@args);
if ($retval != 0) {
$retval /= 256 if $retval > 0;
my $pwd = cwd ();
die "$0: system(@args) failed in $pwd, status $retval";
}
return $retval;
}
=item C<run_cmd($cmd, @envvars)>
Run shell command C<$cmd> and captures its standard output (not standard
error). Returns a list with CMD's output as the first element and its
return value (exit code) as second.
If given, C<@envvars> is a list of environment variable name / value
pairs set in C<%ENV> for the call and reset to their original value (or
unset if not defined initially).
=cut
sub run_cmd {
my $cmd = shift;
my %envvars = @_;
my %envvarsSetState;
my %envvarsValue;
for my $k (keys %envvars) {
$envvarsSetState{$k} = exists $ENV{$k};
$envvarsValue{$k} = $ENV{$k};
$ENV{$k} = $envvars{$k};
}
my $output = `$cmd`;
for my $k (keys %envvars) {
if ($envvarsSetState{$k}) {
$ENV{$k} = $envvarsValue{$k};
} else {
delete $ENV{$k};
}
}
$output = "" if ! defined ($output); # don't return undef
my $retval = $?;
if ($retval != 0) {
$retval /= 256 if $retval > 0;
}
return ($output,$retval);
}
=item C<run_cmd_with_log($cmd, $logfn)>
Run shell command C<$cmd> and captures both standard output and standard
error (as one string), passing them to C<$logfn>. The return value is
the exit status of C<$cmd>. Environment variable overrides cannot be
passed. (This is used for running special post-installation commands in
install-tl and tlmgr.)
The C<info> function is called to report what is happening.
=cut
sub run_cmd_with_log {
my ($cmd,$logfn) = @_;
info ("running $cmd ...");
my ($out,$ret) = TeXLive::TLUtils::run_cmd ("$cmd 2>&1");
if ($ret == 0) {
info ("done\n");
} else {
info ("failed\n");
tlwarn ("$0: $cmd failed (status $ret): $!\n");
$ret = 1;
}
&$logfn ($out); # log the output
return $ret;
} # run_cmd_with_log
=item C<system_pipe($prog, $infile, $outfile, $removeIn, @extraargs)>
Runs C<$prog> with C<@extraargs> redirecting stdin from C<$infile>,
stdout to C<$outfile>. Removes C<$infile> if C<$removeIn> is true.
=cut
sub system_pipe {
my ($prog, $infile, $outfile, $removeIn, @extraargs) = @_;
my $progQuote = quotify_path_with_spaces($prog);
if (wndws()) {
$infile =~ s!/!\\!g;
$outfile =~ s!/!\\!g;
}
my $infileQuote = "\"$infile\"";
my $outfileQuote = "\"$outfile\"";
debug("TLUtils::system_pipe: calling $progQuote @extraargs < $infileQuote > $outfileQuote\n");
my $retval = system("$progQuote @extraargs < $infileQuote > $outfileQuote");
if ($retval != 0) {
$retval /= 256 if $retval > 0;
debug("TLUtils::system_pipe: system exit code = $retval\n");
return 0;
} else {
if ($removeIn) {
debug("TLUtils::system_pipe: removing $infile\n");
unlink($infile);
}
return 1;
}
}
=item C<diskfree($path)>
If a POSIX compliant C<df> program is found, returns the number of Mb
free at C<$path>, otherwise C<-1>. If C<$path> does not exist, check
upwards for two levels for an existing parent, and if found, use it for
computing the disk space.
=cut
sub diskfree {
my $td = shift;
my ($output, $retval);
if (wndws()) {
# the powershell one-liner only works from win8 on.
my @winver = Win32::GetOSVersion();
if ($winver[1]<=6 && $winver[2]<=1) {
return -1;
}
my $avl;
if ($td =~ /^[a-zA-Z]:/) {
my $drv = substr($td,0,1);
# ea ignore: error action ignore: no output at all
my $cmd = "powershell -nologo -noninteractive -noprofile -command " .
"\"get-psdrive -name $drv -ea ignore |select-object free |format-wide\"";
($output, $retval) = run_cmd($cmd);
# ignore exit code, just parse the output, which should
# consist of empty lines and a number surrounded by spaces
my @lines = split(/\r*\n/, $output);
foreach (@lines) {
chomp $_;
if ($_ !~ /^\s*$/) {
$_ =~ s/^\s*//;
$_ =~ s/\s*$//;
$avl = $_;
last;
}
}
if ($avl !~ /^[0-9]+$/) {
return (-1);
} else {
return (int($avl/(1024*1024)));
}
} else {
# maybe UNC drive; do not try to handle this
return -1;
}
}
# now windows case has been taken care of
return (-1) if (! $::progs{"df"});
# drop final /
$td =~ s!/$!!;
if (! -e $td) {
my $ptd = dirname($td);
if (-e $ptd) {
$td = $ptd;
} else {
my $pptd = dirname($ptd);
if (-e $pptd) {
$td = $pptd;
}
}
}
$td .= "/" if ($td !~ m!/$!);
return (-1) if (! -e $td);
debug("checking diskfree() in $td\n");
($output, $retval) = run_cmd("df -Pk \"$td\"");
# With -k (mandated by POSIX), we should always get 1024-blocks.
# Otherwise, the POSIXLY_CORRECT envvar for GNU df would need to
# be set, to force 512-blocks; and the BLOCKSIZE envvar would need
# to be unset to avoid overriding.
if ($retval == 0) {
# Output format should be this:
# Filesystem 1024-blocks Used Available Capacity Mounted on
# /dev/sdb3 209611780 67718736 141893044 33% /
my ($h,$l) = split(/\n/, $output);
my ($fs, $nrb, $used, $avail, @rest) = split(' ', $l);
debug("diskfree: df -Pk output: $output");
debug("diskfree: used=$used (1024-block), avail=$avail (1024-block)\n");
# $avail is in 1024-byte blocks, so we divide by 1024 to obtain Mb.
return (int($avail / 1024));
} else {
# error in running df -P for whatever reason, just skip the check.
return (-1);
}
}
=item C<get_user_home()>
Returns the current user's home directory (C<$HOME> on Unix,
C<$USERPROFILE> on Windows, and C<~> if none of the two are
set. Save in package variable C<$user_home_dir> after computing.
=cut
# only search for home directory once, and save expansion here
my $user_home_dir;
sub get_user_home {
return $user_home_dir if ($user_home_dir);
$user_home_dir = getenv (wndws() ? 'USERPROFILE' : 'HOME') || '~';
return $user_home_dir;
}
=item C<expand_tilde($str)>
Expands initial C<~> with the user's home directory in C<$str> if
available, else leave C<~> in place.
=cut
sub expand_tilde {
my $str = shift;
my $h = get_user_home();
$str =~ s/^~/$h/;
return $str;
}
=back
=head2 File utilities
=over 4
=item C<dirname_and_basename($path)>
Return both C<dirname> and C<basename>. Example:
($dirpart,$filepart) = dirname_and_basename ($path);
=cut
sub dirname_and_basename {
my $path=shift;
my ($share, $base) = ("", "");
if (wndws()) {
$path=~s!\\!/!g;
}
# do not try to make sense of paths ending with /..
return (undef, undef) if $path =~ m!/\.\.$!;
if ($path=~m!/!) { # dirname("foo/bar/baz") -> "foo/bar"
# eliminate `/.' path components
while ($path =~ s!/\./!/!) {};
# UNC path? => first split in $share = //xxx/yy and $path = /zzzz
if (wndws() and $path =~ m!^(//[^/]+/[^/]+)(.*)$!) {
($share, $path) = ($1, $2);
if ($path =~ m!^/?$!) {
$path = $share;
$base = "";
} elsif ($path =~ m!(/.*)/(.*)!) {
$path = $share.$1;
$base = $2;
} else {
$base = $path;
$path = $share;
}
return ($path, $base);
}
# not a UNC path
$path=~m!(.*)/(.*)!; # works because of greedy matching
return ((($1 eq '') ? '/' : $1), $2);
} else { # dirname("ignore") -> "."
return (".", $path);
}
}
=item C<dirname($path)>
Return C<$path> with its trailing C</component> removed.
=cut
sub dirname {
my $path = shift;
my ($dirname, $basename) = dirname_and_basename($path);
return $dirname;
}
=item C<basename($path)>
Return C<$path> with any leading directory components removed.
=cut
sub basename {
my $path = shift;
my ($dirname, $basename) = dirname_and_basename($path);
return $basename;
}
=item C<tl_abs_path($path)>
# Other than Cwd::abs_path, tl_abs_path also works if the argument does not
# yet exist as long as the path does not contain '..' components.
=cut
sub tl_abs_path {
my $path = shift;
if (wndws()) {
$path=~s!\\!/!g;
}
if (-e $path) {
$path = Cwd::abs_path($path);
} elsif ($path eq '.') {
$path = Cwd::getcwd();
} else{
# collapse /./ components
$path =~ s!/\./!/!g;
# no support for .. path components or for windows long-path syntax
# (//?/ path prefix)
die "Unsupported path syntax" if $path =~ m!/\.\./! || $path =~ m!/\.\.$!
|| $path =~ m!^\.\.!;
die "Unsupported path syntax" if wndws() && $path =~ m!^//\?/!;
if ($path !~ m!^(.:)?/!) { # relative path
if (wndws() && $path =~ /^.:/) { # drive letter
my $dcwd;
# starts with drive letter: current dir on drive
$dcwd = Cwd::getdcwd ($1);
$dcwd .= '/' unless $dcwd =~ m!/$!;
return $dcwd.$path;
} else { # relative path without drive letter
my $cwd = Cwd::getcwd();
$cwd .= '/' unless $cwd =~ m!/$!;
return $cwd . $path;
}
} # else absolute path
}
$path =~ s!/$!! unless $path =~ m!^(.:)?/$!;
return $path;
}
=item C<dir_creatable($path)>
Tests whether its argument is a directory where we can create a directory.
=cut
sub dir_slash {
my $d = shift;
$d = "$d/" unless $d =~ m!/!;
return $d;
}
# test whether subdirectories can be created in the argument
sub dir_creatable {
my $path=shift;
#print STDERR "testing $path\n";
$path =~ s!\\!/!g if wndws;
return 0 unless -d $path;
$path .= '/' unless $path =~ m!/$!;
#print STDERR "testing $path\n";
my $d;
for my $i (1..100) {
$d = "";
# find a non-existent dirname
$d = $path . int(rand(1000000));
last unless -e $d;
}
if (!$d) {
tlwarn("Cannot find available testdir name\n");
return 0;
}
#print STDERR "creating $d\n";
return 0 unless mkdir $d;
return 0 unless -d $d;
rmdir $d;
return 1;
}
=item C<dir_writable($path)>
Tests whether its argument is writable by trying to write to
it. This function is necessary because the built-in C<-w> test just
looks at mode and uid/gid, which on Windows always returns true and
even on Unix is not always good enough for directories mounted from
a fileserver.
=cut
# The Unix test gives the wrong answer when used under Windows Vista
# with one of the `virtualized' directories such as Program Files:
# lacking administrative permissions, it would write successfully to
# the virtualized Program Files rather than fail to write to the
# real Program Files. Ugh.
sub dir_writable {
my ($path) = @_;
return 0 unless -d $path;
$path =~ s!\\!/!g if wndws;
$path .= '/' unless $path =~ m!/$!;
my $i = 0;
my $f;
for my $i (1..100) {
$f = "";
# find a non-existent filename
$f = $path . int(rand(1000000));
last unless -e $f;
}
if (!$f) {
tlwarn("Cannot find available testfile name\n");
return 0;
}
return 0 if ! open (TEST, ">$f");
my $written = 0;
$written = (print TEST "\n");
close (TEST);
unlink ($f);
return $written;
}
=item C<mkdirhier($path, [$mode])>
The function C<mkdirhier> does the same as the UNIX command C<mkdir -p>.
It behaves differently depending on the context in which it is called:
If called in void context it will die on failure. If called in
scalar context, it will return 1/0 on sucess/failure. If called in
list context, it returns 1/0 as first element and an error message
as second, if an error occurred (and no second element in case of
success). The optional parameter sets the permission bits.
=cut
sub mkdirhier {
my ($tree,$mode) = @_;
my $ret = 1;
my $reterror;
if (-d "$tree") {
$ret = 1;
} else {
my $subdir = "";
# windows is special as usual: we need to separate //servername/ part
# from the UNC path, since (! -d //servername/) tests true
$subdir = $& if ( wndws() && ($tree =~ s!^//[^/]+/!!) );
my @dirs = split (/[\/\\]/, $tree);
for my $dir (@dirs) {
$subdir .= "$dir/";
if (! -d $subdir) {
if (defined $mode) {
if (! mkdir ($subdir, $mode)) {
$ret = 0;
$reterror = "mkdir($subdir,$mode) failed: $!";
last;
}
} else {
if (! mkdir ($subdir)) {
$ret = 0;
$reterror = "mkdir($subdir) failed for tree $tree: $!";
last;
}
}
}
}
}
if ($ret) {
return(1); # nothing bad here returning 1 in any case, will
# be ignored in void context, and give 1 in list context
} else {
if (wantarray) {
return(0, $reterror);
} elsif (defined wantarray) {
return(0);
} else {
die "$0: $reterror";
}
}
}
=item C<rmtree($root, $verbose, $safe)>
The C<rmtree> function provides a convenient way to delete a
subtree from the directory structure, much like the Unix command C<rm -r>.
C<rmtree> takes three arguments:
=over 4
=item *
the root of the subtree to delete, or a reference to
a list of roots. All of the files and directories
below each root, as well as the roots themselves,
will be deleted.
=item *
a boolean value, which if TRUE will cause C<rmtree> to
print a message each time it examines a file, giving the
name of the file, and indicating whether it's using C<rmdir>
or C<unlink> to remove it, or that it's skipping it.
(defaults to FALSE)
=item *
a boolean value, which if TRUE will cause C<rmtree> to
skip any files to which you do not have delete access
(if running under VMS) or write access (if running
under another OS). This will change in the future when
a criterion for 'delete permission' under OSs other
than VMS is settled. (defaults to FALSE)
=back
It returns the number of files successfully deleted. Symlinks are
simply deleted and not followed.
B<NOTE:> There are race conditions internal to the implementation of
C<rmtree> making it unsafe to use on directory trees which may be
altered or moved while C<rmtree> is running, and in particular on any
directory trees with any path components or subdirectories potentially
writable by untrusted users.
Additionally, if the third parameter is not TRUE and C<rmtree> is
interrupted, it may leave files and directories with permissions altered
to allow deletion (and older versions of this module would even set
files and directories to world-read/writable!)
Note also that the occurrence of errors in C<rmtree> can be determined I<only>
by trapping diagnostic messages using C<$SIG{__WARN__}>; it is not apparent
from the return value.
=cut
#taken from File/Path.pm
#
my $Is_VMS = $^O eq 'VMS';
my $Is_MacOS = $^O eq 'MacOS';
# These OSes complain if you want to remove a file that you have no
# write permission to:
my $force_writeable = ($^O eq 'os2' || $^O eq 'dos' || $^O eq 'MSWin32' ||
$^O eq 'amigaos' || $^O eq 'MacOS' || $^O eq 'epoc');
sub rmtree {
my($roots, $verbose, $safe) = @_;
my(@files);
my($count) = 0;
$verbose ||= 0;
$safe ||= 0;
if ( defined($roots) && length($roots) ) {
$roots = [$roots] unless ref $roots;
} else {
warn "No root path(s) specified";
return 0;
}
my($root);
foreach $root (@{$roots}) {
if ($Is_MacOS) {
$root = ":$root" if $root !~ /:/;
$root =~ s#([^:])\z#$1:#;
} else {
$root =~ s#/\z##;
}
(undef, undef, my $rp) = lstat $root or next;
$rp &= 07777; # don't forget setuid, setgid, sticky bits
if ( -d _ ) {
# notabene: 0700 is for making readable in the first place,
# it's also intended to change it to writable in case we have
# to recurse in which case we are better than rm -rf for
# subtrees with strange permissions
chmod($rp | 0700, ($Is_VMS ? VMS::Filespec::fileify($root) : $root))
or warn "Can't make directory $root read+writeable: $!"
unless $safe;
if (opendir my $d, $root) {
no strict 'refs';
if (!defined ${"\cTAINT"} or ${"\cTAINT"}) {
# Blindly untaint dir names
@files = map { /^(.*)$/s ; $1 } readdir $d;
} else {
@files = readdir $d;
}
closedir $d;
} else {
warn "Can't read $root: $!";
@files = ();
}
# Deleting large numbers of files from VMS Files-11 filesystems
# is faster if done in reverse ASCIIbetical order
@files = reverse @files if $Is_VMS;
($root = VMS::Filespec::unixify($root)) =~ s#\.dir\z## if $Is_VMS;
if ($Is_MacOS) {
@files = map("$root$_", @files);
} else {
@files = map("$root/$_", grep $_!~/^\.{1,2}\z/s,@files);
}
$count += rmtree(\@files,$verbose,$safe);
if ($safe &&
($Is_VMS ? !&VMS::Filespec::candelete($root) : !-w $root)) {
print "skipped $root\n" if $verbose;
next;
}
chmod $rp | 0700, $root
or warn "Can't make directory $root writeable: $!"
if $force_writeable;
print "rmdir $root\n" if $verbose;
if (rmdir $root) {
++$count;
} else {
warn "Can't remove directory $root: $!";
chmod($rp, ($Is_VMS ? VMS::Filespec::fileify($root) : $root))
or warn("and can't restore permissions to "
. sprintf("0%o",$rp) . "\n");
}
} else {
if ($safe &&
($Is_VMS ? !&VMS::Filespec::candelete($root)
: !(-l $root || -w $root)))
{
print "skipped $root\n" if $verbose;
next;
}
chmod $rp | 0600, $root
or warn "Can't make file $root writeable: $!"
if $force_writeable;
print "unlink $root\n" if $verbose;
# delete all versions under VMS
for (;;) {
unless (unlink $root) {
warn "Can't unlink file $root: $!";
if ($force_writeable) {
chmod $rp, $root
or warn("and can't restore permissions to "
. sprintf("0%o",$rp) . "\n");
}
last;
}
++$count;
last unless $Is_VMS && lstat $root;
}
}
}
$count;
}
=item C<copy($file, $target_dir)>
=item C<copy("-f", $file, $destfile)>
=item C<copy("-L", $file, $destfile)>
Copy file C<$file> to directory C<$target_dir>, or to the C<$destfile>
if the first argument is C<"-f">. No external programs are involved.
Since we need C<sysopen()>, the Perl module C<Fcntl.pm> is required. The
time stamps are preserved and symlinks are created on Unix systems. On
Windows, C<(-l $file)> will never return 'C<true>' and so symlinks will
be (uselessly) copied as regular files.
If the first argument is C<"-L"> and C<$file> is a symlink, the link is
dereferenced before the copying is done. (If both C<"-f"> and C<"-L">
are desired, they must be given in that order, although the codebase
currently has no need to do this.)
C<copy> invokes C<mkdirhier> if target directories do not exist. Files
start with mode C<0777> if they are executable and C<0666> otherwise,
with the set bits in I<umask> cleared in each case.
C<$file> can begin with a C<file:/> prefix.
If C<$file> is not readable, we return without copying anything. (This
can happen when the database and files are not in perfect sync.) On the
other file, if the destination is not writable, or the writing fails,
that is a fatal error.
=cut
sub copy {
#too verbose ddebug("TLUtils::copy(", join (",", @_), "\n");
my $infile = shift;
my $filemode = 0;
my $dereference = 0;
if ($infile eq "-f") { # second argument is a file
$filemode = 1;
$infile = shift;
}
if ($infile eq "-L") {
$dereference = 1;
$infile = shift;
}
my $destdir=shift;
# while we're trying to figure out the versioned containers.
#debug("copy($infile, $destdir, filemode=$filemode)\n");
#debug("copy: backtrace:\n", backtrace(), "copy: end backtrace\n");
my $outfile;
my @stat;
my $mode;
my $buffer;
my $offset;
my $filename;
my $dirmode = 0755;
my $blocksize = $TeXLive::TLConfig::BlockSize;
$infile =~ s!^file://*!/!i; # remove file:/ url prefix
$filename = basename "$infile";
if ($filemode) {
# given a destination file
$outfile = $destdir;
$destdir = dirname($outfile);
} else {
$outfile = "$destdir/$filename";
}
if (! -d $destdir) {
my ($ret,$err) = mkdirhier ($destdir);
die "mkdirhier($destdir) failed: $err\n" if ! $ret;
}
# if we should dereference, change $infile to refer to the link target.
if (-l $infile && $dereference) {
my $linktarget = readlink($infile);
# The symlink target should always be relative, and we need to
# prepend the directory containing the link in that case.
# (Although it should never happen, if the symlink target happens
# to already be absolute, do not prepend.)
if ($linktarget !~ m,^/,) {
$infile = Cwd::abs_path(dirname($infile)) . "/$linktarget";
}
ddebug("TLUtils::copy: dereferencing symlink $infile -> $linktarget");
}
if (-l $infile) {
my $linktarget = readlink($infile);
my $dest = "$destdir/$filename";
ddebug("TLUtils::copy: doing symlink($linktarget,$dest)"
. " [from readlink($infile)]\n");
symlink($linktarget, $dest) || die "symlink($linktarget,$dest) failed: $!";
} else {
if (! open (IN, $infile)) {
warn "open($infile) failed, not copying: $!";
return;
}
binmode IN;
$mode = (-x $infile) ? oct("0777") : oct("0666");
$mode &= ~umask;
open (OUT, ">$outfile") || die "open(>$outfile) failed: $!";
binmode OUT;
chmod ($mode, $outfile) || warn "chmod($mode,$outfile) failed: $!";
while (my $read = sysread (IN, $buffer, $blocksize)) {
die "read($infile) failed: $!" unless defined $read;
$offset = 0;
while ($read) {
my $written = syswrite (OUT, $buffer, $read, $offset);
die "write($outfile) failed: $!" unless defined $written;
$read -= $written;
$offset += $written;
}
}
close (OUT) || warn "close($outfile) failed: $!";
close (IN) || warn "close($infile) failed: $!";;
@stat = lstat ($infile);
die "lstat($infile) failed: $!" if ! @stat;
utime ($stat[8], $stat[9], $outfile);
}
}
=item C<touch(@files)>
Update modification and access time of C<@files>. Non-existent files
are created.
=cut
sub touch {
my @files=@_;
foreach my $file (@_) {
if (-e $file) {
utime time, time, $file;
} else {
if (open( TMP, ">$file")) {
close(TMP);
} else {
warn "Can't create file $file: $!\n";
}
}
}
}
=item C<collapse_dirs(@files)>
Return a (more or less) minimal list of directories and files, given an
original list of files C<@files>. That is, if every file within a given
directory is included in C<@files>, replace all of those files with the
absolute directory name in the return list. Any files which have
sibling files not included are retained and made absolute.
We try to walk up the tree so that the highest-level directory
containing only directories or files that are in C<@files> is returned.
(This logic may not be perfect, though.)
This is not just a string function; we check for other directory entries
existing on disk within the directories of C<@files>. Therefore, if the
entries are relative pathnames, the current directory must be set by the
caller so that file tests work.
As mentioned above, the returned list is absolute paths to directories
and files.
For example, suppose the input list is
dir1/subdir1/file1
dir1/subdir2/file2
dir1/file3
If there are no other entries under C<dir1/>, the result will be
C</absolute/path/to/dir1>.
=cut
sub collapse_dirs {
my (@files) = @_;
my @ret = ();
my %by_dir;
# construct hash of all directories mentioned, values are lists of the
# files in that directory.
for my $f (@files) {
my $abs_f = Cwd::abs_path ($f);
die ("oops, no abs_path($f) from " . `pwd`) unless $abs_f;
(my $d = $abs_f) =~ s,/[^/]*$,,;
my @a = exists $by_dir{$d} ? @{$by_dir{$d}} : ();
push (@a, $abs_f);
$by_dir{$d} = \@a;
}
# for each of our directories, see if we are given everything in
# the directory. if so, return the directory; else return the
# individual files.
for my $d (sort keys %by_dir) {
opendir (DIR, $d) || die "opendir($d) failed: $!";
my @dirents = readdir (DIR);
closedir (DIR) || warn "closedir($d) failed: $!";
# initialize test hash with all the files we saw in this dir.
# (These idioms are due to "Finding Elements in One Array and Not
# Another" in the Perl Cookbook.)
my %seen;
my @rmfiles = @{$by_dir{$d}};
@seen{@rmfiles} = ();
# see if everything is the same.
my $ok_to_collapse = 1;
for my $dirent (@dirents) {
next if $dirent =~ /^\.(\.|svn)?$/; # ignore . .. .svn
my $item = "$d/$dirent"; # prepend directory for comparison
if (! exists $seen{$item}) {
ddebug(" no collapse of $d because of: $dirent\n");
$ok_to_collapse = 0;
last; # no need to keep looking after the first.
}
}
push (@ret, $ok_to_collapse ? $d : @{$by_dir{$d}});
}
if (@ret != @files) {
@ret = &collapse_dirs (@ret);
}
return @ret;
}
=item C<dirs_of_files(@files)>
Returns all the directories in which at least one of the given
files reside.
=cut
sub dirs_of_files {
my (@files) = @_;
my %by_dir;
# construct hash of all directories mentioned, values are lists of the
# files/dirs in that directory.
for my $f (@files) {
# what should we do with not existing entries????
next if (! -r "$f");
my $abs_f = Cwd::abs_path ($f);
# the following is necessary because on windows,
# abs_path("tl-portable")
# returns
# c:\tl test\...
# and not forward slashes, while, if there is already a forward /
# in the path, also the rest is done with forward slashes.
$abs_f =~ s!\\!/!g if wndws();
if (!$abs_f) {
warn ("oops, no abs_path($f) from " . `pwd`);
next;
}
(my $d = $abs_f) =~ s,/[^/]*$,,;
my @a = exists $by_dir{$d} ? @{$by_dir{$d}} : ();
push (@a, $abs_f);
$by_dir{$d} = \@a;
}
return %by_dir;
}
=item C<all_dirs_and_removed_dirs(@files)>
Returns all the directories for files and those from which all
content will be removed.
=cut
sub all_dirs_and_removed_dirs {
my (@files) = @_;
my %removed_dirs;
my %by_dir = dirs_of_files(@files);
# for each of our directories, see if we are removing everything in
# the directory. if so, return the directory; else return the
# individual files.
for my $d (reverse sort keys %by_dir) {
opendir (DIR, $d) || die "opendir($d) failed: $!";
my @dirents = readdir (DIR);
closedir (DIR) || warn "closedir($d) failed: $!";
# initialize test hash with all the files we saw in this dir.
# (These idioms are due to "Finding Elements in One Array and Not
# Another" in the Perl Cookbook.)
my %seen;
my @rmfiles = @{$by_dir{$d}};
@seen{@rmfiles} = ();
# see if everything is the same.
my $cleandir = 1;
for my $dirent (@dirents) {
next if $dirent =~ /^\.(\.|svn)?$/; # ignore . .. .svn
my $item = "$d/$dirent"; # prepend directory for comparison
if (
((-d $item) && (defined($removed_dirs{$item})))
||
(exists $seen{$item})
) {
# do nothing
} else {
$cleandir = 0;
last;
}
}
if ($cleandir) {
$removed_dirs{$d} = 1;
}
}
return (%by_dir, %removed_dirs);
}
=item C<removed_dirs(@files)>
Returns all the directories from which all content will be removed.
Here is the idea:
=over 4
=item create a hashes by_dir listing all files that should be removed
by directory, i.e., key = dir, value is list of files
=item for each of the dirs (keys of by_dir and ordered deepest first)
check that all actually contained files are removed
and all the contained dirs are in the removal list. If this is the
case put that directory into the removal list
=item return this removal list
=back
=cut
sub removed_dirs {
my (@files) = @_;
my (%by_dir, %removed_dirs) = all_dirs_and_removed_dirs(@files);
return keys %removed_dirs;
}
=item C<time_estimate($totalsize, $donesize, $starttime)>
Returns the current running time and the estimated total time
based on the total size, the already done size, and the start time.
=cut
sub time_estimate {
my ($totalsize, $donesize, $starttime) = @_;
if ($donesize <= 0) {
return ("??:??", "??:??");
}
my $curtime = time();
my $passedtime = $curtime - $starttime;
my $esttotalsecs = int ( ( $passedtime * $totalsize ) / $donesize );
#
# we change the display to show that passed time instead of the
# estimated remaining time. We keep the old code and naming and
# only initialize the $remsecs to the $passedtime instead.
# my $remsecs = $esttotalsecs - $passedtime;
my $remsecs = $passedtime;
my $min = int($remsecs/60);
my $hour;
if ($min >= 60) {
$hour = int($min/60);
$min %= 60;
}
my $sec = $remsecs % 60;
my $remtime = sprintf("%02d:%02d", $min, $sec);
if ($hour) {
$remtime = sprintf("%02d:$remtime", $hour);
}
my $tmin = int($esttotalsecs/60);
my $thour;
if ($tmin >= 60) {
$thour = int($tmin/60);
$tmin %= 60;
}
my $tsec = $esttotalsecs % 60;
my $tottime = sprintf("%02d:%02d", $tmin, $tsec);
if ($thour) {
$tottime = sprintf("%02d:$tottime", $thour);
}
return($remtime, $tottime);
}
=item C<install_packages($from_tlpdb, $media, $to_tlpdb, $what, $opt_src, $opt_doc, $retry, $continue)>
Installs the list of packages found in C<@$what> (a ref to a list) into
the TLPDB given by C<$to_tlpdb>. Information on files are taken from
the TLPDB C<$from_tlpdb>.
C<$opt_src> and C<$opt_doc> specify whether srcfiles and docfiles should
be installed (currently implemented only for installation from
uncompressed media).
If C<$retry> is trueish, retry failed packages a second time.
If C<$continue> is trueish, installation failure of non-critical packages
will be ignored (success is returned).
Returns 1 on success and 0 on error.
=cut
sub install_packages {
my ($fromtlpdb,$media,$totlpdb,$what,
$opt_src,$opt_doc,$opt_retry,$opt_continue) = @_;
my $container_src_split = $fromtlpdb->config_src_container;
my $container_doc_split = $fromtlpdb->config_doc_container;
my $root = $fromtlpdb->root;
my @packs = @$what;
my $totalnr = $#packs + 1;
my $td = length("$totalnr");
my $n = 0;
my %tlpobjs;
my $totalsize = 0;
my $donesize = 0;
my %tlpsizes;
debug("TLUtils::install_packages: fromtlpdb.root=$root, media=$media,"
. " totlpdb.root=" . $totlpdb->root
. " what=$what ($totalnr), opt_src=$opt_src, opt_doc=$opt_doc\n");
foreach my $p (@packs) {
$tlpobjs{$p} = $fromtlpdb->get_package($p);
if (!defined($tlpobjs{$p})) {
die "STRANGE: $p not to be found in ", $fromtlpdb->root;
}
if ($media ne 'local_uncompressed') {
# we use the container size as the measuring unit since probably
# downloading will be the limiting factor
$tlpsizes{$p} = $tlpobjs{$p}->containersize;
$tlpsizes{$p} += $tlpobjs{$p}->srccontainersize if $opt_src;
$tlpsizes{$p} += $tlpobjs{$p}->doccontainersize if $opt_doc;
} else {
# we have to add the respective sizes, that is checking for
# installation of src and doc file
$tlpsizes{$p} = $tlpobjs{$p}->runsize;
$tlpsizes{$p} += $tlpobjs{$p}->srcsize if $opt_src;
$tlpsizes{$p} += $tlpobjs{$p}->docsize if $opt_doc;
my %foo = %{$tlpobjs{$p}->binsize};
for my $k (keys %foo) { $tlpsizes{$p} += $foo{$k}; }
# all the packages sizes are in blocks, so transfer that to bytes
$tlpsizes{$p} *= $TeXLive::TLConfig::BlockSize;
}
$totalsize += $tlpsizes{$p};
}
my $starttime = time();
my @packs_again; # packages that we failed to download and should retry later
foreach my $package (@packs) {
my $tlpobj = $tlpobjs{$package};
my $reloc = $tlpobj->relocated;
$n++;
my ($estrem, $esttot) = time_estimate($totalsize, $donesize, $starttime);
my $infostr = sprintf("Installing [%0${td}d/$totalnr, "
. "time/total: $estrem/$esttot]: $package [%dk]",
$n, int($tlpsizes{$package}/1024) + 1);
info("$infostr\n");
foreach my $h (@::install_packages_hook) {
&$h($n,$totalnr);
}
# push $package to @packs_again if download failed
# (and not installing from disk).
if (!$fromtlpdb->install_package($package, $totlpdb)) {
tlwarn("TLUtils::install_packages: Failed to install $package\n");
if ($opt_retry) {
tlwarn(" $package will be retried later.\n");
push @packs_again, $package;
} else {
# return false as soon as one package failed, since we won't
# be trying again.
return 0;
}
} else {
$donesize += $tlpsizes{$package};
}
}
# try to download packages in @packs_again again
foreach my $package (@packs_again) {
my $infostr = sprintf("Retrying to install: $package [%dk]",
int($tlpsizes{$package}/1024) + 1);
info("$infostr\n");
# return false if download failed again
if (!$fromtlpdb->install_package($package, $totlpdb)) {
if ($opt_continue) {
push @::installation_failed_packages, $package;
tlwarn("Failed to install $package, but continuing anyway!\n");
} else {
return 0;
}
}
$donesize += $tlpsizes{$package};
}
my $totaltime = time() - $starttime;
my $tothour = int ($totaltime/3600);
my $totmin = (int ($totaltime/60)) % 60;
my $totsec = $totaltime % 60;
my $hrstr = ($tothour > 0 ? "$tothour:" : "");
info(sprintf("Time used for installing the packages: $hrstr%02d:%02d\n",
$totmin, $totsec));
$totlpdb->save;
return 1;
}
=item C<do_postaction($how, $tlpobj, $do_fileassocs, $do_menu, $do_desktop, $do_script)>
Evaluates the C<postaction> fields in the C<$tlpobj>. The first parameter
can be either C<install> or C<remove>. The second gives the TLPOBJ whos
postactions should be evaluated, and the last four arguments specify
what type of postactions should (or shouldn't) be evaluated.
Returns 1 on success, and 0 on failure.
=cut
sub do_postaction {
my ($how, $tlpobj, $do_fileassocs, $do_menu, $do_desktop, $do_script) = @_;
my $ret = 1;
if (!defined($tlpobj)) {
tlwarn("do_postaction: didn't get a tlpobj\n");
return 0;
}
debug("running postaction=$how for " . $tlpobj->name . "\n")
if $tlpobj->postactions;
for my $pa ($tlpobj->postactions) {
if ($pa =~ m/^\s*shortcut\s+(.*)\s*$/) {
$ret &&= _do_postaction_shortcut($how, $tlpobj, $do_menu, $do_desktop, $1);
} elsif ($pa =~ m/\s*filetype\s+(.*)\s*$/) {
next unless $do_fileassocs;
$ret &&= _do_postaction_filetype($how, $tlpobj, $1);
} elsif ($pa =~ m/\s*fileassoc\s+(.*)\s*$/) {
$ret &&= _do_postaction_fileassoc($how, $do_fileassocs, $tlpobj, $1);
next;
} elsif ($pa =~ m/\s*progid\s+(.*)\s*$/) {
next unless $do_fileassocs;
$ret &&= _do_postaction_progid($how, $tlpobj, $1);
} elsif ($pa =~ m/\s*script\s+(.*)\s*$/) {
next unless $do_script;
$ret &&= _do_postaction_script($how, $tlpobj, $1);
} else {
tlwarn("do_postaction: don't know how to do $pa\n");
$ret = 0;
}
}
# nothing to do
return $ret;
}
sub _do_postaction_fileassoc {
my ($how, $mode, $tlpobj, $pa) = @_;
return 1 unless wndws();
my ($errors, %keyval) =
parse_into_keywords($pa, qw/extension filetype/);
if ($errors) {
tlwarn("parsing the postaction line >>$pa<< did not succeed!\n");
return 0;
}
# name can be an arbitrary string
if (!defined($keyval{'extension'})) {
tlwarn("extension of fileassoc postaction not given\n");
return 0;
}
my $extension = $keyval{'extension'};
# cmd can be an arbitrary string
if (!defined($keyval{'filetype'})) {
tlwarn("filetype of fileassoc postaction not given\n");
return 0;
}
my $filetype = $keyval{'filetype'}.'.'.$ReleaseYear;
&log("postaction $how fileassoc for " . $tlpobj->name .
": $extension, $filetype\n");
if ($how eq "install") {
TeXLive::TLWinGoo::register_extension($mode, $extension, $filetype);
} elsif ($how eq "remove") {
TeXLive::TLWinGoo::unregister_extension($mode, $extension, $filetype);
} else {
tlwarn("Unknown mode $how\n");
return 0;
}
return 1;
}
sub _do_postaction_filetype {
my ($how, $tlpobj, $pa) = @_;
return 1 unless wndws();
my ($errors, %keyval) =
parse_into_keywords($pa, qw/name cmd/);
if ($errors) {
tlwarn("parsing the postaction line >>$pa<< did not succeed!\n");
return 0;
}
# name can be an arbitrary string
if (!defined($keyval{'name'})) {
tlwarn("name of filetype postaction not given\n");
return 0;
}
my $name = $keyval{'name'}.'.'.$ReleaseYear;
# cmd can be an arbitrary string
if (!defined($keyval{'cmd'})) {
tlwarn("cmd of filetype postaction not given\n");
return 0;
}
my $cmd = $keyval{'cmd'};
my $texdir = `kpsewhich -var-value=TEXMFROOT`;
chomp($texdir);
my $texdir_bsl = conv_to_w32_path($texdir);
$cmd =~ s!^("?)TEXDIR/!$1$texdir/!g;
&log("postaction $how filetype for " . $tlpobj->name .
": $name, $cmd\n");
if ($how eq "install") {
TeXLive::TLWinGoo::register_file_type($name, $cmd);
} elsif ($how eq "remove") {
TeXLive::TLWinGoo::unregister_file_type($name);
} else {
tlwarn("Unknown mode $how\n");
return 0;
}
return 1;
}
# alternate filetype (= progid) for an extension;
# associated program shows up in `open with' menu
sub _do_postaction_progid {
my ($how, $tlpobj, $pa) = @_;
return 1 unless wndws();
my ($errors, %keyval) =
parse_into_keywords($pa, qw/extension filetype/);
if ($errors) {
tlwarn("parsing the postaction line >>$pa<< did not succeed!\n");
return 0;
}
if (!defined($keyval{'extension'})) {
tlwarn("extension of progid postaction not given\n");
return 0;
}
my $extension = $keyval{'extension'};
if (!defined($keyval{'filetype'})) {
tlwarn("filetype of progid postaction not given\n");
return 0;
}
my $filetype = $keyval{'filetype'}.'.'.$ReleaseYear;
&log("postaction $how progid for " . $tlpobj->name .
": $extension, $filetype\n");
if ($how eq "install") {
TeXLive::TLWinGoo::add_to_progids($extension, $filetype);
} elsif ($how eq "remove") {
TeXLive::TLWinGoo::remove_from_progids($extension, $filetype);
} else {
tlwarn("Unknown mode $how\n");
return 0;
}
return 1;
}
sub _do_postaction_script {
my ($how, $tlpobj, $pa) = @_;
my ($errors, %keyval) =
parse_into_keywords($pa, qw/file filew32/);
if ($errors) {
tlwarn("parsing the postaction line >>$pa<< did not succeed!\n");
return 0;
}
# file can be an arbitrary string
if (!defined($keyval{'file'})) {
tlwarn("filename of script not given\n");
return 0;
}
my $file = $keyval{'file'};
if (wndws() && defined($keyval{'filew32'})) {
$file = $keyval{'filew32'};
}
my $texdir = `kpsewhich -var-value=TEXMFROOT`;
chomp($texdir);
my @syscmd;
if ($file =~ m/\.pl$/i) {
# we got a perl script, call it via perl
push @syscmd, "perl", "$texdir/$file";
} elsif ($file =~ m/\.texlua$/i) {
# we got a texlua script, call it via texlua
push @syscmd, "texlua", "$texdir/$file";
} else {
# we got anything else, call it directly and hope it is excutable
push @syscmd, "$texdir/$file";
}
&log("postaction $how script for " . $tlpobj->name . ": @syscmd\n");
push @syscmd, $how, $texdir;
my $ret = system (@syscmd);
if ($ret != 0) {
$ret /= 256 if $ret > 0;
my $pwd = cwd ();
warn "$0: calling post action script $file did not succeed in $pwd, status $ret";
return 0;
}
return 1;
}
sub _do_postaction_shortcut {
my ($how, $tlpobj, $do_menu, $do_desktop, $pa) = @_;
return 1 unless wndws();
my ($errors, %keyval) =
parse_into_keywords($pa, qw/type name icon cmd args hide/);
if ($errors) {
tlwarn("parsing the postaction line >>$pa<< did not succeed!\n");
return 0;
}
# type can be either menu or desktop
if (!defined($keyval{'type'})) {
tlwarn("type of shortcut postaction not given\n");
return 0;
}
my $type = $keyval{'type'};
if (($type ne "menu") && ($type ne "desktop")) {
tlwarn("type of shortcut postaction $type is unknown (menu, desktop)\n");
return 0;
}
if (($type eq "menu") && !$do_menu) {
return 1;
}
if (($type eq "desktop") && !$do_desktop) {
return 1;
}
# name can be an arbitrary string
if (!defined($keyval{'name'})) {
tlwarn("name of shortcut postaction not given\n");
return 0;
}
my $name = $keyval{'name'};
# icon, cmd, args is optional
my $icon = (defined($keyval{'icon'}) ? $keyval{'icon'} : '');
my $cmd = (defined($keyval{'cmd'}) ? $keyval{'cmd'} : '');
my $args = (defined($keyval{'args'}) ? $keyval{'args'} : '');
# hide can be only 0 or 1, and defaults to 1
my $hide = (defined($keyval{'hide'}) ? $keyval{'hide'} : 1);
if (($hide ne "0") && ($hide ne "1")) {
tlwarn("hide of shortcut postaction $hide is unknown (0, 1)\n");
return 0;
}
&log("postaction $how shortcut for " . $tlpobj->name . "\n");
if ($how eq "install") {
my $texdir = `kpsewhich -var-value=TEXMFROOT`;
chomp($texdir);
my $texdir_bsl = conv_to_w32_path($texdir);
$icon =~ s!^TEXDIR/!$texdir/!;
$cmd =~ s!^TEXDIR/!$texdir/!;
# $cmd can be an URL, in which case we do NOT want to convert it to
# w32 paths!
if ($cmd !~ m!^\s*(https?://|ftp://)!) {
if (!(-e $cmd) or !(-r $cmd)) {
tlwarn("Target of shortcut action does not exist: $cmd\n")
if $cmd =~ /\.(exe|bat|cmd)$/i;
# if not an executable, just omit shortcut silently: no error
return 1;
}
$cmd = conv_to_w32_path($cmd);
}
if ($type eq "menu" ) {
TeXLive::TLWinGoo::add_menu_shortcut(
$TeXLive::TLConfig::WindowsMainMenuName,
$name, $icon, $cmd, $args, $hide);
} elsif ($type eq "desktop") {
TeXLive::TLWinGoo::add_desktop_shortcut(
$name, $icon, $cmd, $args, $hide);
} else {
tlwarn("Unknown type of shortcut: $type\n");
return 0;
}
} elsif ($how eq "remove") {
if ($type eq "menu") {
TeXLive::TLWinGoo::remove_menu_shortcut(
$TeXLive::TLConfig::WindowsMainMenuName, $name);
} elsif ($type eq "desktop") {
TeXLive::TLWinGoo::remove_desktop_shortcut($name);
} else {
tlwarn("Unknown type of shortcut: $type\n");
return 0;
}
} else {
tlwarn("Unknown mode $how\n");
return 0;
}
return 1;
}
=item C<parse_into_keywords>
=cut
sub parse_into_keywords {
my ($str, @keys) = @_;
my @words = quotewords('\s+', 0, $str);
my %ret;
my $error = 0;
while (@words) {
$_ = shift @words;
if (/^([^=]+)=(.*)$/) {
$ret{$1} = $2;
} else {
tlwarn("parser found a invalid word in parsing keys: $_\n");
$error++;
$ret{$_} = "";
}
}
for my $k (keys %ret) {
if (!member($k, @keys)) {
$error++;
tlwarn("parser found invalid keyword: $k\n");
}
}
return($error, %ret);
}
=item C<update_context_cache($bindir,$progext,$run_postinst_cmd)>
Run the ConTeXt cache generation commands, using C<$bindir> and
C<$progext> to check if commands can be run. Use the function reference
C<$run_postinst_cmd> to actually run the commands. The return status is
zero if all succeeded, nonzero otherwise. If the main ConTeXt program
(C<luametatex>) cannot be run at all, the return status is zero.
Functions C<info> and C<debug> are called with status reports.
=cut
sub update_context_cache {
my ($bindir,$progext,$run_postinst_cmd) = @_;
my $errcount = 0;
# The story here is that in 2023, the provided lmtx binary for
# x86_64-linux was too new to run on the system where we build TL.
# (luametatex: /lib64/libm.so.6: version `GLIBC_2.23' not found)
# So we have to try running the binary to see if it works, not just
# test for its existence. And since it exits nonzero given no args, we
# have to specify --version. Hope it keeps working like that ...
#
# If lmtx is not runnable, don't consider that an error, since nothing
# can be done about it.
my $lmtx = "$bindir/luametatex$progext";
if (TeXLive::TLUtils::system_ok("$lmtx --version")) {
info("setting up ConTeXt cache: ");
$errcount += &$run_postinst_cmd("mtxrun --generate");
#
# If mtxrun failed, don't bother trying more.
if ($errcount == 0) {
$errcount += &$run_postinst_cmd("context --luatex --generate");
#
# If context succeeded too, try luajittex. Missing on some platforms.
# Although we build luajittex normally, instead of importing the
# binary, testing for file existence should suffice, we may as
# well test execution since it's just as easy.
#
if ($errcount == 0) {
my $luajittex = "$bindir/luajittex$progext";
if (TeXLive::TLUtils::system_ok("$luajittex --version")) {
$errcount += &$run_postinst_cmd("context --luajittex --generate");
} else {
debug("skipped luajittex cache setup, can't run $luajittex\n");
}
}
}
}
return $errcount;
}
=item C<announce_execute_actions($how, [$tlpobj[, $what]])>
Announces (records) that the actions, usually given in C<$tlpobj> (but
can be omitted for global actions), should be executed after all
packages have been unpacked. The optional C<$what> depends on the
action, e.g., a parse_AddFormat_line reference for formats; not sure if
it's used for anything else.
This is called for every package that gets installed.
=cut
sub announce_execute_actions {
my ($type,$tlp,$what) = @_;
# return immediately if execute actions are suppressed
return if $::no_execute_actions;
# since we're called for every package with "enable",
# it's not helpful to report that again.
if ($type ne "enable") {
my $forpkg = $tlp ? ("for " . $tlp->name) : "no package";
debug("announce_execute_actions: given $type ($forpkg)\n");
}
if (defined($type) && ($type eq "regenerate-formats")) {
$::regenerate_all_formats = 1;
return;
}
if (defined($type) && ($type eq "files-changed")) {
$::files_changed = 1;
return;
}
if (defined($type) && ($type eq "context-cache")) {
$::context_cache_update_needed = 1;
return;
}
if (defined($type) && ($type eq "rebuild-format")) {
# rebuild-format must feed in a hashref of a parse_AddFormat_line data
# the $tlp argument is not used
$::execute_actions{'enable'}{'formats'}{$what->{'name'}} = $what;
return;
}
if (!defined($type) || (($type ne "enable") && ($type ne "disable"))) {
die "announce_execute_actions: enable or disable, not type $type";
}
if ($tlp->runfiles || $tlp->srcfiles || $tlp->docfiles) {
$::files_changed = 1;
}
#
$what = "map format hyphen" if (!defined($what)); # do all by default
foreach my $e ($tlp->executes) {
if ($e =~ m/^add((Mixed|Kanji)?Map)\s+([^\s]+)\s*$/) {
# save the refs as we have another =~ grep in the following lines
my $a = $1;
my $b = $3;
$::execute_actions{$type}{'maps'}{$b} = $a if ($what =~ m/map/);
} elsif ($e =~ m/^AddFormat\s+(.*)\s*$/) {
my %r = TeXLive::TLUtils::parse_AddFormat_line("$1");
if (defined($r{"error"})) {
tlwarn ("$r{'error'} in parsing $e for return hash\n");
} else {
$::execute_actions{$type}{'formats'}{$r{'name'}} = \%r
if ($what =~ m/format/);
}
} elsif ($e =~ m/^AddHyphen\s+(.*)\s*$/) {
my %r = TeXLive::TLUtils::parse_AddHyphen_line("$1");
if (defined($r{"error"})) {
tlwarn ("$r{'error'} in parsing $e for return hash\n");
} else {
$::execute_actions{$type}{'hyphens'}{$r{'name'}} = \%r
if ($what =~ m/hyphen/);
}
} else {
tlwarn("Unknown execute $e in ", $tlp->name, "\n");
}
}
}
=pod
=item C<add_symlinks($root, $arch, $sys_bin, $sys_man, $sys_info)>
=item C<remove_symlinks($root, $arch, $sys_bin, $sys_man, $sys_info)>
These two functions try to create/remove symlinks for binaries, man pages,
and info files as specified by the options $sys_bin, $sys_man, $sys_info.
The functions return 1 on success and 0 on error.
On Windows it returns undefined.
=cut
sub add_link_dir_dir {
my ($from,$to) = @_;
my ($ret, $err) = mkdirhier ($to);
if (!$ret) {
tlwarn("$err\n");
return 0;
}
if (-w $to) {
debug ("TLUtils::add_link_dir_dir: linking from $from to $to\n");
chomp (my @files = `ls "$from"`);
my $ret = 1;
for my $f (@files) {
# don't make a system-dir link to our special "man" link.
if ($f eq "man") {
debug ("not linking `man' into $to.\n");
next;
}
#
# attempt to remove an existing symlink, but nothing else.
unlink ("$to/$f") if -l "$to/$f";
#
# if the destination still exists, skip it.
if (-e "$to/$f") {
tlwarn ("add_link_dir_dir: $to/$f exists; not making symlink.\n");
next;
}
#
# try to make the link.
if (symlink ("$from/$f", "$to/$f") == 0) {
tlwarn ("add_link_dir_dir: symlink of $f from $from to $to failed: $!\n");
$ret = 0;
}
}
return $ret;
} else {
tlwarn ("add_link_dir_dir: destination $to not writable, "
. "no links from $from.\n");
return 0;
}
}
sub remove_link_dir_dir {
my ($from, $to) = @_;
if ((-d "$to") && (-w "$to")) {
debug("TLUtils::remove_link_dir_dir: removing links from $from to $to\n");
chomp (my @files = `ls "$from"`);
my $ret = 1;
foreach my $f (@files) {
next if (! -r "$to/$f");
if ($f eq "man") {
debug("TLUtils::remove_link_dir_dir: not considering man in $to, it should not be from us!\n");
next;
}
if ((-l "$to/$f") &&
(readlink("$to/$f") =~ m;^$from/;)) {
$ret = 0 unless unlink("$to/$f");
} else {
$ret = 0;
tlwarn ("TLUtils::remove_link_dir_dir: not removing $to/$f, not a link or wrong destination!\n");
}
}
# try to remove the destination directory, it might be empty and
# we might have write permissions, ignore errors
# `rmdir "$to" 2>/dev/null`;
return $ret;
} else {
tlwarn ("TLUtils::remove_link_dir_dir: destination $to not writable, no removal of links done!\n");
return 0;
}
}
sub add_remove_symlinks {
my ($mode, $Master, $arch, $sys_bin, $sys_man, $sys_info) = @_;
my $errors = 0;
my $plat_bindir = "$Master/bin/$arch";
# nothing to do with symlinks on Windows, of course.
return if wndws();
my $info_dir = "$Master/texmf-dist/doc/info";
if ($mode eq "add") {
$errors++ unless add_link_dir_dir($plat_bindir, $sys_bin); # bin
if (-d $info_dir) {
$errors++ unless add_link_dir_dir($info_dir, $sys_info);
}
} elsif ($mode eq "remove") {
$errors++ unless remove_link_dir_dir($plat_bindir, $sys_bin); # bin
if (-d $info_dir) {
$errors++ unless remove_link_dir_dir($info_dir, $sys_info);
}
} else {
die ("should not happen, unknown mode $mode in add_remove_symlinks!");
}
# man
my $top_man_dir = "$Master/texmf-dist/doc/man";
debug("TLUtils::add_remove_symlinks: $mode symlinks for man pages to $sys_man from $top_man_dir\n");
if (! -d $top_man_dir) {
; # better to be silent?
#info("skipping add of man symlinks, no source directory $top_man_dir\n");
} else {
my $man_doable = 1;
if ($mode eq "add") {
my ($ret, $err) = mkdirhier $sys_man;
if (!$ret) {
$man_doable = 0;
tlwarn("$err\n");
$errors++;
}
}
if ($man_doable) {
if (-w $sys_man) {
my $foo = `(cd "$top_man_dir" && echo *)`;
my @mans = split (' ', $foo);
chomp (@mans);
foreach my $m (@mans) {
my $mandir = "$top_man_dir/$m";
next unless -d $mandir;
if ($mode eq "add") {
$errors++ unless add_link_dir_dir($mandir, "$sys_man/$m");
} else {
$errors++ unless remove_link_dir_dir($mandir, "$sys_man/$m");
}
}
#`rmdir "$sys_man" 2>/dev/null` if ($mode eq "remove");
} else {
tlwarn("TLUtils::add_remove_symlinks: man symlink destination ($sys_man) not writable, "
. "cannot $mode symlinks.\n");
$errors++;
}
}
}
# we collected errors in $errors, so return the negation of it
if ($errors) {
info("TLUtils::add_remove_symlinks: $mode of symlinks had $errors error(s), see messages above.\n");
return $F_ERROR;
} else {
return $F_OK;
}
}
sub add_symlinks { return (add_remove_symlinks("add", @_)); }
sub remove_symlinks { return (add_remove_symlinks("remove", @_)); }
=pod
=item C<w32_add_to_path($bindir, $multiuser)>
=item C<w32_remove_from_path($bindir, $multiuser)>
These two functions try to add/remove the binary directory $bindir
on Windows to the registry PATH variable.
If running as admin user and $multiuser is set, the system path will
be adjusted, otherwise the user path.
After calling these functions TeXLive::TLWinGoo::broadcast_env() should
be called to make the changes immediately visible.
=cut
sub w32_add_to_path {
my ($bindir, $multiuser) = @_;
return if (!wndws());
my $path = TeXLive::TLWinGoo::get_system_env() -> {'/Path'};
$path =~ s/[\s\x00]+$//;
&log("Old system path: $path\n");
$path = TeXLive::TLWinGoo::get_user_env() -> {'/Path'};
if ($path) {
$path =~ s/[\s\x00]+$//;
&log("Old user path: $path\n");
} else {
&log("Old user path: none\n");
}
my $mode = 'user';
if (TeXLive::TLWinGoo::admin() && $multiuser) {
$mode = 'system';
}
debug("TLUtils:w32_add_to_path: calling adjust_reg_path_for_texlive add $bindir $mode\n");
TeXLive::TLWinGoo::adjust_reg_path_for_texlive('add', $bindir, $mode);
$path = TeXLive::TLWinGoo::get_system_env() -> {'/Path'};
$path =~ s/[\s\x00]+$//;
&log("New system path: $path\n");
$path = TeXLive::TLWinGoo::get_user_env() -> {'/Path'};
if ($path) {
$path =~ s/[\s\x00]+$//;
&log("New user path: $path\n");
} else {
&log("New user path: none\n");
}
}
sub w32_remove_from_path {
my ($bindir, $multiuser) = @_;
my $mode = 'user';
if (TeXLive::TLWinGoo::admin() && $multiuser) {
$mode = 'system';
}
debug("w32_remove_from_path: trying to remove $bindir in $mode\n");
TeXLive::TLWinGoo::adjust_reg_path_for_texlive('remove', $bindir, $mode);
}
=pod
=item C<check_file_and_remove($what, $checksum, $checksize>
Remove the file C<$what> if either the given C<$checksum> or
C<$checksize> for C<$what> does not agree with our recomputation using
C<TLCrypto::tlchecksum> and C<stat>, respectively. If a check argument
is not given, that check is not performed. If the checksums agree, the
size is not checked. The return status is random.
This unusual behavior (removing the given file) is because this is used
for newly-downloaded files; see the calls in the C<unpack> routine
(which is the only caller).
=cut
sub check_file_and_remove {
my ($xzfile, $checksum, $checksize) = @_;
my $fn_name = (caller(0))[3];
debug("$fn_name $xzfile, $checksum, $checksize\n");
if (!$checksum && !$checksize) {
tlwarn("$fn_name: neither checksum nor checksize " .
"available for $xzfile, cannot check integrity");
return;
}
# The idea is that if one of the tests fail, we want to save a copy of
# the input file for debugging. But we can't just omit removing the
# file, since the caller depends on the removal. So we copy it to a
# new temporary directory, which we want to persist, so can't use tl_tmpdir.
my $check_file_tmpdir = undef;
# only run checksum tests if we can actually compute the checksum
if ($checksum && ($checksum ne "-1") && $::checksum_method) {
my $tlchecksum = TeXLive::TLCrypto::tlchecksum($xzfile);
if ($tlchecksum ne $checksum) {
tlwarn("$fn_name: checksums differ for $xzfile:\n");
tlwarn("$fn_name: tlchecksum=$tlchecksum, arg=$checksum\n");
tlwarn("$fn_name: backtrace:\n" . backtrace());
# on Windows passing a pattern creates the tmpdir in PWD
# which means that it will be tried to be created on the DVD
# $check_file_tmpdir = File::Temp::tempdir("tlcheckfileXXXXXXXX");
$check_file_tmpdir = File::Temp::tempdir();
tlwarn("$fn_name: removing $xzfile, "
. "but saving copy in $check_file_tmpdir\n");
copy($xzfile, $check_file_tmpdir);
unlink($xzfile);
return;
} else {
debug("$fn_name: checksums for $xzfile agree\n");
# if we have checked the checksum, we don't need to check the size, too
return;
}
}
if ($checksize && ($checksize ne "-1")) {
my $filesize = (stat $xzfile)[7];
if ($filesize != $checksize) {
tlwarn("$fn_name: removing $xzfile, sizes differ:\n");
tlwarn("$fn_name: tlfilesize=$filesize, arg=$checksize\n");
if (!defined($check_file_tmpdir)) {
# the tmpdir should always be undefined, since we shouldn't get
# here if the checksums failed, but test anyway.
$check_file_tmpdir = File::Temp::tempdir("tlcheckfileXXXXXXXX");
tlwarn("$fn_name: saving copy in $check_file_tmpdir\n");
copy($xzfile, $check_file_tmpdir);
}
unlink($xzfile);
return;
}
}
# We cannot remove the file here, otherwise restoring of backups
# or unwind packages might die.
}
=pod
=item C<unpack($what, $targetdir, @opts>
If necessary, downloads C$what>, and then unpacks it into C<$targetdir>.
C<@opts> is assigned to a hash and can contain the following
keys: C<tmpdir> (use this directory for downloaded files),
C<checksum> (check downloaded file against this checksum),
C<size> (check downloaded file against this size),
C<remove> (remove temporary files after operation).
Returns a pair of values: in case of error return 0 and an additional
explanation, in case of success return 1 and the name of the package.
If C<checksum> or C<size> is C<-1>, no warnings about missing checksum/size
is printed. This is used during restore and unwinding of failed updates.
=cut
sub unpack {
my ($what, $target, %opts) = @_;
# remove by default
my $remove = (defined($opts{'remove'}) ? $opts{'remove'} : 1);
my $tempdir = (defined($opts{'tmpdir'}) ? $opts{'tmpdir'} : tl_tmpdir());
my $checksum = (defined($opts{'checksum'}) ? $opts{'checksum'} : 0);
my $size = (defined($opts{'size'}) ? $opts{'size'} : 0);
if (!defined($what)) {
return (0, "nothing to unpack");
}
my $decompressorType;
my $compressorextension;
if ($what =~ m/\.tar\.$CompressorExtRegexp$/) {
$compressorextension = $1;
$decompressorType = $1 eq "gz" ? "gzip" : $1;
}
if (!$decompressorType) {
return(0, "don't know how to unpack");
}
# make sure that the found uncompressor type is also available
if (!member($decompressorType, @{$::progs{'working_compressors'}})) {
return(0, "unsupported container format $decompressorType");
}
# only check the necessary compressor program
my $decompressor = $::progs{$decompressorType};
my @decompressorArgs = @{$Compressors{$decompressorType}{'decompress_args'}};
my $fn = basename($what);
my $pkg = $fn;
$pkg =~ s/\.tar\.$compressorextension$//;
my $remove_containerfile = $remove;
my $containerfile = "$tempdir/$fn";
my $tarfile = "$tempdir/$fn";
$tarfile =~ s/\.$compressorextension$//;
if ($what =~ m,^(https?|ftp)://, || $what =~ m!$SshURIRegex!) {
# we are installing from the NET
# check for the presence of $what in $tempdir
if (-r $containerfile) {
check_file_and_remove($containerfile, $checksum, $size);
}
# if the file is now not present, we can use it
if (! -r $containerfile) {
# try download the file and put it into temp
if (!download_file($what, $containerfile)) {
return(0, "downloading did not succeed (download_file failed)");
}
# remove false downloads
check_file_and_remove($containerfile, $checksum, $size);
if ( ! -r $containerfile ) {
return(0, "downloading did not succeed (check_file_and_remove failed)");
}
}
} else {
# we are installing from local compressed files
# copy it to temp with dereferencing of link target
TeXLive::TLUtils::copy("-L", $what, $tempdir);
check_file_and_remove($containerfile, $checksum, $size);
if (! -r $containerfile) {
return (0, "consistency checks failed");
}
# we can remove it afterwards
$remove_containerfile = 1;
}
if (!system_pipe($decompressor, $containerfile, $tarfile,
$remove_containerfile, @decompressorArgs)
||
! -f $tarfile) {
unlink($tarfile, $containerfile);
return(0, "Decompressing $containerfile failed");
}
if (untar($tarfile, $target, 1)) {
return (1, "$pkg");
} else {
return (0, "untar failed");
}
}
=pod
=item C<untar($tarfile, $targetdir, $remove_tarfile)>
Unpacks C<$tarfile> in C<$targetdir> (changing directories to
C<$targetdir> and then back to the original directory). If
C<$remove_tarfile> is true, unlink C<$tarfile> after unpacking.
Assumes the global C<$::progs{"tar"}> has been set up.
=cut
# return 1 if success, 0 if failure.
sub untar {
my ($tarfile, $targetdir, $remove_tarfile) = @_;
my $ret;
my $tar = $::progs{'tar'}; # assume it's been set up
# don't use the -C option to tar since Solaris tar et al. don't support it.
# don't use system("cd ... && $tar ...") since that opens us up to
# quoting issues.
# so fall back on chdir in Perl.
#
debug("TLUtils::untar: unpacking $tarfile in $targetdir\n");
my $cwd = cwd();
chdir($targetdir) || die "chdir($targetdir) failed: $!";
# on w32 don't extract file modified time, because AV soft can open
# files in the mean time causing time stamp modification to fail
my $taropt = wndws() ? "xmf" : "xf";
if (system($tar, $taropt, $tarfile) != 0) {
tlwarn("TLUtils::untar: $tar $taropt $tarfile failed (in $targetdir)\n");
$ret = 0;
} else {
$ret = 1;
}
unlink($tarfile) if $remove_tarfile;
chdir($cwd) || die "chdir($cwd) failed: $!";
return $ret;
}
=item C<tlcmp($file, $file)>
Compare two files considering CR, LF, and CRLF as equivalent.
Returns 1 if different, 0 if the same.
=cut
sub tlcmp {
my ($filea, $fileb) = @_;
if (!defined($fileb)) {
die <<END_USAGE;
tlcmp needs two arguments FILE1 FILE2.
Compare as text files, ignoring line endings.
Exit status is zero if the same, 1 if different, something else if trouble.
END_USAGE
}
my $file1 = &read_file_ignore_cr ($filea);
my $file2 = &read_file_ignore_cr ($fileb);
return $file1 eq $file2 ? 0 : 1;
}
=item C<read_file_ignore_cr($file)>
Return contents of FILE as a string, converting all of CR, LF, and
CRLF to just LF.
=cut
sub read_file_ignore_cr {
my ($fname) = @_;
my $ret = "";
local *FILE;
open (FILE, $fname) || die "open($fname) failed: $!";
while (<FILE>) {
s/\r\n?/\n/g;
#warn "line is |$_|";
$ret .= $_;
}
close (FILE) || warn "close($fname) failed: $!";
return $ret;
}
=item C<setup_programs($bindir, $platform, $tlfirst)>
Populate the global C<$::progs> hash containing the paths to the
programs C<lz4>, C<tar>, C<wget>, C<xz>. The C<$bindir> argument specifies
the path to the location of the C<xz> binaries, the C<$platform>
gives the TeX Live platform name, used as the extension on our
executables. If a program is not present in the TeX Live tree, we also
check along PATH (without the platform extension.)
If the C<$tlfirst> argument or the C<TEXLIVE_PREFER_OWN> envvar is set,
prefer TL versions; else prefer system versions (except for Windows
C<tar.exe>, where we always use ours).
Check many different downloads and compressors to determine what is
working.
Return 0 if failure, nonzero if success.
=cut
sub setup_programs {
my ($bindir, $platform, $tlfirst) = @_;
my $ok = 1;
# tlfirst is (currently) not passed in by either the installer or
# tlmgr, so it will be always false.
# If it is not defined, we check for the env variable
# TEXLIVE_PREFER_OWN
#
if (!defined($tlfirst)) {
if ($ENV{'TEXLIVE_PREFER_OWN'}) {
debug("setup_programs: TEXLIVE_PREFER_OWN is set!\n");
$tlfirst = 1;
}
}
debug("setup_programs: preferring " . ($tlfirst ? "TL" : "system") . " versions\n");
my $isWin = ($^O =~ /^MSWin/i);
if ($isWin) {
# we need to make sure that we use our own tar, since
# Windows system tar is stupid bsdtar ...
setup_one("w32", 'tar', "$bindir/tar.exe", "--version", 1);
$platform = "exe";
} else {
# tar needs to be provided by the system, we not even check!
$::progs{'tar'} = "tar";
setup_one("unix", "df", undef, "-P .", 0);
if (!defined($platform) || ($platform eq "")) {
# we assume that we run from uncompressed media, so we can call
# platform() and thus also the config.guess script but we have to
# setup $::installerdir because the platform script relies on it
$::installerdir = "$bindir/../..";
$platform = platform();
}
}
# setup of the fallback downloaders
my @working_downloaders;
for my $dltype (@AcceptedFallbackDownloaders) {
my $defprog = $FallbackDownloaderProgram{$dltype};
# do not warn on errors
push @working_downloaders, $dltype if
setup_one(($isWin ? "w32" : "unix"), $defprog,
"$bindir/$dltype/$defprog.$platform", "--version", $tlfirst);
}
# check for curl special stuff on MacOS
if (member("curl", @working_downloaders) && platform() =~ m/darwin/) {
# copied from platform_name
chomp (my $sw_vers = `sw_vers -productVersion`);
my ($os_major,$os_minor) = split (/\./, $sw_vers);
if ($os_major == 10 && ($os_minor == 13 || $os_minor == 14)) {
my @curlargs = @{$TeXLive::TLConfig::FallbackDownloaderArgs{'curl'}};
# can't push new arg at end of list because builtin list ends with
# -o to set the output file.
unshift (@curlargs, '--cacert', "$::installerdir/tlpkg/installer/curl/curl-ca-bundle.crt");
$TeXLive::TLConfig::FallbackDownloaderArgs{'curl'} = \@curlargs;
debug("TLUtils::setup_programs: curl on old darwin, final curl args: @{$TeXLive::TLConfig::FallbackDownloaderArgs{'curl'}}\n");
}
}
# check for wget/ssl support
if (member("wget", @working_downloaders)) {
debug("TLUtils::setup_programs: checking for ssl enabled wget\n");
my @lines = `$::progs{'wget'} --version 2>&1`;
if (grep(/\+ssl/, @lines)) {
$::progs{'options'}{'wget-ssl'} = 1;
my @wgetargs = @{$TeXLive::TLConfig::FallbackDownloaderArgs{'wget'}};
# can't push new arg at end of list because builtin list ends with
# -O to set the output file.
unshift (@wgetargs, '--no-check-certificate');
$TeXLive::TLConfig::FallbackDownloaderArgs{'wget'} = \@wgetargs;
debug("TLUtils::setup_programs: wget has ssl, final wget args: @{$TeXLive::TLConfig::FallbackDownloaderArgs{'wget'}}\n");
} else {
debug("TLUtils::setup_programs: wget without ssl support found\n");
$::progs{'options'}{'wget-ssl'} = 0;
}
}
$::progs{'working_downloaders'} = [ @working_downloaders ];
my @working_compressors;
for my $defprog (sort
{ $Compressors{$a}{'priority'} <=> $Compressors{$b}{'priority'} }
keys %Compressors) {
# do not warn on errors
if (setup_one(($isWin ? "w32" : "unix"), $defprog,
"$bindir/$defprog/$defprog.$platform", "--version",
$tlfirst)) {
push @working_compressors, $defprog;
# also set up $::{'compressor'} if not already done
# this selects the first one, but we might reset this depending on
# TEXLIVE_COMPRESSOR setting, see below
defined($::progs{'compressor'}) || ($::progs{'compressor'} = $defprog);
}
}
$::progs{'working_compressors'} = [ @working_compressors ];
# check whether selected downloader/compressor is working
# for downloader we allow 'lwp' as setting, too
if ($ENV{'TEXLIVE_DOWNLOADER'}
&& $ENV{'TEXLIVE_DOWNLOADER'} ne 'lwp'
&& !TeXLive::TLUtils::member($ENV{'TEXLIVE_DOWNLOADER'},
@{$::progs{'working_downloaders'}})) {
tlwarn(<<END_DOWNLOADER_BAD);
Selected download program TEXLIVE_DOWNLOADER=$ENV{'TEXLIVE_DOWNLOADER'}
is not working!
Please choose a different downloader or don't set TEXLIVE_DOWNLOADER.
Detected working downloaders: @{$::progs{'working_downloaders'}}.
END_DOWNLOADER_BAD
$ok = 0;
}
if ($ENV{'TEXLIVE_COMPRESSOR'}
&& !TeXLive::TLUtils::member($ENV{'TEXLIVE_COMPRESSOR'},
@{$::progs{'working_compressors'}})) {
tlwarn(<<END_COMPRESSOR_BAD);
Selected compression program TEXLIVE_COMPRESSOR=$ENV{'TEXLIVE_COMPRESSOR'}
is not working!
Please choose a different compressor or don't set TEXLIVE_COMPRESSOR.
Detected working compressors: @{$::progs{'working_compressors'}}.
END_COMPRESSOR_BAD
$ok = 0;
}
# setup default compressor $::progs{'compressor'} which is used in
# tlmgr in the calls to make_container. By default we have already
# chosen the first that is actually working from our list of
# @AcceptableCompressors, but let the user override this.
if ($ENV{'TEXLIVE_COMPRESSOR'}) {
$::progs{'compressor'} = $ENV{'TEXLIVE_COMPRESSOR'};
}
if ($::opt_verbosity >= 2) {
require Data::Dumper;
# avoid spurious "used only once" warnings due to require
# (warnings restored at end of scope). https://perlmonks.org/?node_id=3333
no warnings 'once';
local $Data::Dumper::Sortkeys = 1; # stable output
local $Data::Dumper::Purity = 1; # reconstruct recursive structures
print STDERR "DD:dumping ";
print STDERR Data::Dumper->Dump([\%::progs], [qw(::progs)]);
}
return $ok;
}
sub setup_one {
my ($what, $p, $def, $arg, $tlfirst) = @_;
my $setupfunc = ($what eq "unix") ? \&setup_unix_tl_one : \&setup_windows_tl_one ;
if ($tlfirst) {
if (&$setupfunc($p, $def, $arg)) {
return(1);
} else {
return(setup_system_one($p, $arg));
}
} else {
if (setup_system_one($p, $arg)) {
return(1);
} else {
return(&$setupfunc($p, $def, $arg));
}
}
}
sub setup_system_one {
my ($p, $arg) = @_;
my $nulldev = nulldev();
ddebug("trying to set up system $p, arg $arg\n");
my $ret = system("$p $arg >$nulldev 2>&1");
if ($ret == 0) {
debug("program $p found in path\n");
$::progs{$p} = $p;
return(1);
} else {
debug("program $p not usable from path\n");
return(0);
}
}
sub setup_windows_tl_one {
my ($p, $def, $arg) = @_;
debug("(w32) trying to set up $p, default $def, arg $arg\n");
if (-r $def) {
my $prog = conv_to_w32_path($def);
my $ret = system("$prog $arg >nul 2>&1"); # on windows
if ($ret == 0) {
debug("Using shipped $def for $p (tested).\n");
$::progs{$p} = $prog;
return(1);
} else {
tlwarn("Setting up $p with $def as $prog didn't work\n");
system("$prog $arg");
return(0);
}
} else {
debug("Default program $def not readable?\n");
return(0);
}
}
# setup one prog on unix using the following logic:
# - if the shipped one is -x and can be executed, use it
# - if the shipped one is -x but cannot be executed, copy it. set -x
# . if the copy is -x and executable, use it
# - if the shipped one is not -x, copy it, set -x
# . if the copy is -x and executable, use it
sub setup_unix_tl_one {
my ($p, $def, $arg) = @_;
if (!$def) {
debug("(unix) no default program for $p, no setup done\n");
return(1);
}
our $tmp;
debug("(unix) trying to set up $p, default $def, arg $arg\n");
if (-r $def) {
if (-x $def) {
ddebug(" Default $def has executable permissions\n");
# we have to check for actual "executability" since a "noexec"
# mount option may interfere, which is not taken into account by -x.
my $ret = system("'$def' $arg >/dev/null 2>&1" ); # we are on Unix
if ($ret == 0) {
$::progs{$p} = $def;
debug(" Using shipped $def for $p (tested).\n");
return(1);
} else {
ddebug(" Shipped $def has -x but cannot be executed, "
. "trying tmp copy.\n");
}
}
# we are still here
# out of some reasons we couldn't execute the shipped program
# try to copy it to a temp directory and make it executable
#
# create tmp dir only when necessary
$tmp = TeXLive::TLUtils::tl_tmpdir() unless defined($tmp);
# probably we are running from uncompressed media and want to copy it to
# some temporary location
copy($def, $tmp);
my $bn = basename($def);
my $tmpprog = "$tmp/$bn";
chmod(0755,$tmpprog);
# we do not check the return value of chmod, but check whether
# the -x bit is now set, the only thing that counts
if (! -x $tmpprog) {
# hmm, something is going really bad, not even the copy is
# executable. Fall back to normal path element
ddebug(" Copied $p $tmpprog does not have -x bit, strange!\n");
return(0);
} else {
# check again for executability
my $ret = system("$tmpprog $arg > /dev/null 2>&1");
if ($ret == 0) {
# ok, the copy works
debug(" Using copied $tmpprog for $p (tested).\n");
$::progs{$p} = $tmpprog;
return(1);
} else {
# even the copied prog is not executable, strange
ddebug(" Copied $p $tmpprog has x bit but not executable?!\n");
return(0);
}
}
} else {
# default program is not readable
return(0);
}
}
=item C<download_file( $relpath, $destination )>
Try to download the file given in C<$relpath> from C<$TeXLiveURL>
into C<$destination>, which can be either
a filename of simply C<|>. In the latter case a file handle is returned.
Downloading first checks for the environment variable C<TEXLIVE_DOWNLOADER>,
which takes various built-in values. If not set, the next check is for
C<TL_DOWNLOAD_PROGRAM> and C<TL_DOWNLOAD_ARGS>. The former overrides the
above specification devolving to C<wget>, and the latter overrides the
default wget arguments.
C<TL_DOWNLOAD_ARGS> must be defined so that the file the output goes to
is the first argument after the C<TL_DOWNLOAD_ARGS>. Thus, for wget it
would end in C<-O>. Use with care.
=cut
sub download_file {
my ($relpath, $dest) = @_;
# create output dir if necessary
my $par;
if ($dest ne "|") {
$par = dirname($dest);
mkdirhier ($par) unless -d "$par";
}
my $url;
if ($relpath =~ m;^file://*(.*)$;) {
my $filetoopen = "/$1";
# $dest is a file name, we have to get the respective dirname
if ($dest eq "|") {
open(RETFH, "<$filetoopen") or
die("Cannot open $filetoopen for reading");
# opening to a pipe always succeeds, so we return immediately
return \*RETFH;
} else {
if (-r $filetoopen) {
copy ("-f", "-L", $filetoopen, $dest);
return 1;
}
return 0;
}
}
if ($relpath =~ m!$SshURIRegex!) {
my $downdest;
if ($dest eq "|") {
my ($fh, $fn) = TeXLive::TLUtils::tl_tmpfile();
$downdest = $fn;
} else {
$downdest = $dest;
}
# massage ssh:// into the scp-acceptable scp://
$relpath =~ s!^ssh://!scp://!;
my $retval = system("scp", "-q", $relpath, $downdest);
if ($retval != 0) {
$retval /= 256 if $retval > 0;
my $pwd = cwd ();
tlwarn("$0: system(scp -q $relpath $downdest) failed in $pwd, status $retval");
return 0;
}
if ($dest eq "|") {
open(RETFH, "<$downdest") or
die("Cannot open $downdest for reading");
# opening to a pipe always succeeds, so we return immediately
return \*RETFH;
} else {
return 1;
}
}
if ($relpath =~ /^(https?|ftp):\/\//) {
$url = $relpath;
} else {
$url = "$TeXLiveURL/$relpath";
}
my @downloader_trials;
if ($ENV{'TEXLIVE_DOWNLOADER'}) {
push @downloader_trials, $ENV{'TEXLIVE_DOWNLOADER'};
} elsif ($ENV{"TL_DOWNLOAD_PROGRAM"}) {
push @downloader_trials, 'custom';
} else {
@downloader_trials = qw/lwp curl wget/;
}
my $success = 0;
for my $downtype (@downloader_trials) {
if ($downtype eq 'lwp') {
if (_download_file_lwp($url, $dest)) {
$success = $downtype;
last;
}
}
if ($downtype eq "custom" || TeXLive::TLUtils::member($downtype, @{$::progs{'working_downloaders'}})) {
if (_download_file_program($url, $dest, $downtype)) {
$success = $downtype;
last;
}
}
}
if ($success) {
debug("TLUtils::download_file: downloading using $success succeeded\n");
return(1);
} else {
debug("TLUtils::download_file: tried to download using @downloader_trials, none succeeded\n");
return(0);
}
}
sub _download_file_lwp {
my ($url, $dest) = @_;
if (!defined($::tldownload_server)) {
ddebug("::tldownload_server not defined\n");
return(0);
}
if (!$::tldownload_server->enabled) {
# try to reinitialize a disabled connection
# disabling happens after 6 failed download trials
# we just re-initialize the connection
if (!setup_persistent_downloads()) {
# setup failed, give up
debug("reinitialization of LWP download failed\n");
return(0);
}
# we don't need to check for ->enabled, because
# setup_persistent_downloads calls TLDownload->new()
# which, if it succeeds, automatically set enabled to 1
}
# we are still here, so try to download
debug("persistent connection set up, trying to get $url (for $dest)\n");
my $ret = $::tldownload_server->get_file($url, $dest);
if ($ret) {
ddebug("downloading file via persistent connection succeeded\n");
return $ret;
} else {
debug("TLUtils::download_file: persistent connection ok,"
. " but download failed: $url\n");
debug("TLUtils::download_file: retrying with other downloaders.\n");
}
# if we are still here, download with LWP didn't succeed.
return(0);
}
sub _download_file_program {
my ($url, $dest, $type) = @_;
if (wndws()) {
$dest =~ s!/!\\!g;
}
debug("TLUtils::_download_file_program: $type $url $dest\n");
my $downloader;
my $downloaderargs;
my @downloaderargs;
if ($type eq 'custom') {
$downloader = $ENV{"TL_DOWNLOAD_PROGRAM"};
if ($ENV{"TL_DOWNLOAD_ARGS"}) {
$downloaderargs = $ENV{"TL_DOWNLOAD_ARGS"};
@downloaderargs = split(' ', $downloaderargs);
}
} else {
$downloader = $::progs{$FallbackDownloaderProgram{$type}};
@downloaderargs = @{$FallbackDownloaderArgs{$type}};
$downloaderargs = join(' ',@downloaderargs);
}
debug("downloading $url using $downloader $downloaderargs\n");
my $ret;
if ($dest eq "|") {
open(RETFH, "$downloader $downloaderargs - $url|")
|| die "open($url) via $downloader $downloaderargs failed: $!";
# opening to a pipe always succeeds, so we return immediately
return \*RETFH;
} else {
$ret = system ($downloader, @downloaderargs, $dest, $url);
# we have to reverse the meaning of ret because system has 0=success.
$ret = ($ret ? 0 : 1);
}
# return false/undef in case the download did not succeed.
return ($ret) unless $ret;
debug("download of $url succeeded\n");
if ($dest eq "|") {
return \*RETFH;
} else {
return 1;
}
}
=item C<nulldev ()>
Return C</dev/null> on Unix and C<nul> on Windows.
=cut
sub nulldev {
return (&wndws()) ? 'nul' : '/dev/null';
}
=item C<get_full_line ($fh)>
returns the next line from the file handle $fh, taking
continuation lines into account (last character of a line is \, and
no quoting is parsed).
=cut
# open my $f, '<', $file_name or die;
# while (my $l = get_full_line($f)) { ... }
# close $f or die;
sub get_full_line {
my ($fh) = @_;
my $line = <$fh>;
return undef unless defined $line;
return $line unless $line =~ s/\\\r?\n$//;
my $cont = get_full_line($fh);
if (!defined($cont)) {
tlwarn('Continuation disallowed at end of file');
$cont = "";
}
$cont =~ s/^\s*//;
return $line . $cont;
}
=back
=head2 Installer Functions
=over 4
=item C<make_var_skeleton($prefix)>
Generate a skeleton of empty directories in the C<TEXMFSYSVAR> tree.
=cut
sub make_var_skeleton {
my ($prefix) = @_;
mkdirhier "$prefix/tex/generic/config";
mkdirhier "$prefix/fonts/map/dvipdfmx/updmap";
mkdirhier "$prefix/fonts/map/dvips/updmap";
mkdirhier "$prefix/fonts/map/pdftex/updmap";
mkdirhier "$prefix/fonts/pk";
mkdirhier "$prefix/fonts/tfm";
mkdirhier "$prefix/web2c";
mkdirhier "$prefix/xdvi";
mkdirhier "$prefix/tex/context/config";
}
=item C<make_local_skeleton($prefix)>
Generate a skeleton of empty directories in the C<TEXMFLOCAL> tree,
unless C<TEXMFLOCAL> already exists.
=cut
sub make_local_skeleton {
my ($prefix) = @_;
return if (-d $prefix);
mkdirhier "$prefix/bibtex/bib/local";
mkdirhier "$prefix/bibtex/bst/local";
mkdirhier "$prefix/doc/local";
mkdirhier "$prefix/dvips/local";
mkdirhier "$prefix/fonts/source/local";
mkdirhier "$prefix/fonts/tfm/local";
mkdirhier "$prefix/fonts/type1/local";
mkdirhier "$prefix/fonts/vf/local";
mkdirhier "$prefix/metapost/local";
mkdirhier "$prefix/tex/latex/local";
mkdirhier "$prefix/tex/plain/local";
mkdirhier "$prefix/tlpkg";
mkdirhier "$prefix/web2c";
}
=item C<create_fmtutil($tlpdb, $dest)>
=item C<create_updmap($tlpdb, $dest)>
=item C<create_language_dat($tlpdb, $dest, $localconf)>
=item C<create_language_def($tlpdb, $dest, $localconf)>
=item C<create_language_lua($tlpdb, $dest, $localconf)>
These five functions create C<fmtutil.cnf>, C<updmap.cfg>, C<language.dat>,
C<language.def>, and C<language.dat.lua> respectively, in C<$dest> (which by
default is below C<$TEXMFSYSVAR>). These functions merge the information
present in the TLPDB C<$tlpdb> (formats, maps, hyphenations) with local
configuration additions: C<$localconf>.
Currently the merging is done by omitting disabled entries specified
in the local file, and then appending the content of the local
configuration files at the end of the file. We should also check for
duplicates, maybe even error checking.
=cut
#
# get_disabled_local_configs
# returns the list of disabled formats/hyphenpatterns/maps
# disabling is done by putting
# #!NAME
# or
# %!NAME
# into the respective foo-local.cnf/cfg file
#
sub get_disabled_local_configs {
my $localconf = shift;
my $cc = shift;
my @disabled = ();
if ($localconf && -r $localconf) {
open (FOO, "<$localconf")
|| die "strange, -r ok but open($localconf) failed: $!";
my @tmp = <FOO>;
close(FOO) || warn("close($localconf) failed: $!");
@disabled = map { if (m/^$cc!(\S+)\s*$/) { $1 } else { } } @tmp;
}
return @disabled;
}
sub create_fmtutil {
my ($tlpdb,$dest) = @_;
my @lines = $tlpdb->fmtutil_cnf_lines();
_create_config_files($tlpdb, "texmf-dist/web2c/fmtutil-hdr.cnf", $dest,
undef, 0, '#', \@lines);
}
sub create_updmap {
my ($tlpdb,$dest) = @_;
check_for_old_updmap_cfg();
my @tlpdblines = $tlpdb->updmap_cfg_lines();
_create_config_files($tlpdb, "texmf-dist/web2c/updmap-hdr.cfg", $dest,
undef, 0, '#', \@tlpdblines);
}
sub check_for_old_updmap_cfg {
chomp( my $tmfsysconf = `kpsewhich -var-value=TEXMFSYSCONFIG` ) ;
my $oldupd = "$tmfsysconf/web2c/updmap.cfg";
return unless -r $oldupd; # if no such file, good.
open (OLDUPD, "<$oldupd") || die "open($oldupd) failed: $!";
my $firstline = <OLDUPD>;
close(OLDUPD);
# cygwin returns undef when reading from an empty file, we have
# to make sure that this is anyway initialized
$firstline = "" if (!defined($firstline));
chomp ($firstline);
#
if ($firstline =~ m/^# Generated by (install-tl|.*\/tlmgr) on/) {
# assume it was our doing, rename it.
my $nn = "$oldupd.DISABLED";
if (-r $nn) {
my $fh;
($fh, $nn) = tl_tmpfile(
"updmap.cfg.DISABLED.XXXXXX", DIR => "$tmfsysconf/web2c");
}
print "Renaming old config file from
$oldupd
to
$nn
";
if (rename($oldupd, $nn)) {
if (system("mktexlsr", $tmfsysconf) != 0) {
die "mktexlsr $tmfsysconf failed after updmap.cfg rename, fix fix: $!";
}
print "No further action should be necessary.\n";
} else {
print STDERR "
Renaming of
$oldupd
did not succeed. This config file should not be used anymore,
so please do what's necessary to eliminate it.
See the documentation for updmap.
";
}
} else { # first line did not match
# that is NOT a good idea, because updmap creates updmap.cfg in
# TEXMFSYSCONFIG when called with --enable Map etc, so we should
# NOT warn here
# print STDERR "Apparently
# $oldupd
# was created by hand. This config file should not be used anymore,
# so please do what's necessary to eliminate it.
# See the documentation for updmap.
# ";
}
}
sub check_updmap_config_value {
my ($k, $v, $f) = @_;
return 0 if !defined($k);
return 0 if !defined($v);
if (member( $k, qw/dvipsPreferOutline dvipsDownloadBase35
pdftexDownloadBase14 dvipdfmDownloadBase14/)) {
if ($v eq "true" || $v eq "false") {
return 1;
} else {
tlwarn("Unknown setting for $k in $f: $v\n");
return 0;
}
} elsif ($k eq "LW35") {
if (member($v, qw/URW URWkb ADOBE ADOBEkb/)) {
return 1;
} else {
tlwarn("Unknown setting for LW35 in $f: $v\n");
return 0;
}
} elsif ($k eq "kanjiEmbed") {
# any string is fine
return 1;
} else {
return 0;
}
}
sub create_language_dat {
my ($tlpdb,$dest,$localconf) = @_;
# no checking for disabled stuff for language.dat and .def
my @lines = $tlpdb->language_dat_lines(
get_disabled_local_configs($localconf, '%'));
_create_config_files($tlpdb, "texmf-dist/tex/generic/config/language.us",
$dest, $localconf, 0, '%', \@lines);
}
sub create_language_def {
my ($tlpdb,$dest,$localconf) = @_;
# no checking for disabled stuff for language.dat and .def
my @lines = $tlpdb->language_def_lines(
get_disabled_local_configs($localconf, '%'));
my @postlines;
push @postlines, "%%% No changes may be made beyond this point.\n";
push @postlines, "\n";
push @postlines, "\\uselanguage {USenglish} %%% This MUST be the last line of the file.\n";
_create_config_files ($tlpdb,"texmf-dist/tex/generic/config/language.us.def",
$dest, $localconf, 1, '%', \@lines, @postlines);
}
sub create_language_lua {
my ($tlpdb,$dest,$localconf) = @_;
# no checking for disabled stuff for language.dat and .lua
my @lines = $tlpdb->language_lua_lines(
get_disabled_local_configs($localconf, '--'));
my @postlines = ("}\n");
_create_config_files ($tlpdb,"texmf-dist/tex/generic/config/language.us.lua",
$dest, $localconf, 0, '--', \@lines, @postlines);
}
sub _create_config_files {
my ($tlpdb, $headfile, $dest,$localconf, $keepfirstline, $cc,
$tlpdblinesref, @postlines) = @_;
my $root = $tlpdb->root;
my @lines = ();
my $usermode = $tlpdb->setting( "usertree" );
if (-r "$root/$headfile") {
open (INFILE, "<$root/$headfile")
|| die "open($root/$headfile) failed, but -r ok: $!";
@lines = <INFILE>;
close (INFILE);
} elsif (!$usermode) {
# we might be in user mode and then do *not* want the generation
# of the configuration file to just bail out.
tldie ("TLUtils::_create_config_files: giving up, unreadable: "
. "$root/$headfile\n")
}
push @lines, @$tlpdblinesref;
if (defined($localconf) && -r $localconf) {
#
# this should be done more intelligently, but for now only add those
# lines without any duplication check ...
open (FOO, "<$localconf")
|| die "strange, -r ok but cannot open $localconf: $!";
my @tmp = <FOO>;
close (FOO);
push @lines, @tmp;
}
if (@postlines) {
push @lines, @postlines;
}
if ($usermode && -e $dest) {
tlwarn("Updating $dest, backup copy in $dest.backup\n");
copy("-f", $dest, "$dest.backup");
}
open(OUTFILE,">$dest")
or die("Cannot open $dest for writing: $!");
if (!$keepfirstline) {
print OUTFILE $cc;
printf OUTFILE " Generated by %s on %s\n", "$0", scalar localtime;
}
print OUTFILE @lines;
close(OUTFILE) || warn "close(>$dest) failed: $!";
}
sub parse_AddHyphen_line {
my $line = shift;
my %ret;
# default values
my $default_lefthyphenmin = 2;
my $default_righthyphenmin = 3;
$ret{"lefthyphenmin"} = $default_lefthyphenmin;
$ret{"righthyphenmin"} = $default_righthyphenmin;
$ret{"synonyms"} = [];
for my $p (quotewords('\s+', 0, "$line")) {
my ($a, $b) = split /=/, $p;
if ($a eq "name") {
if (!$b) {
$ret{"error"} = "AddHyphen line needs name=something";
return %ret;
}
$ret{"name"} = $b;
next;
}
if ($a eq "lefthyphenmin") {
$ret{"lefthyphenmin"} = ( $b ? $b : $default_lefthyphenmin );
next;
}
if ($a eq "righthyphenmin") {
$ret{"righthyphenmin"} = ( $b ? $b : $default_righthyphenmin );
next;
}
if ($a eq "file") {
if (!$b) {
$ret{"error"} = "AddHyphen line needs file=something";
return %ret;
}
$ret{"file"} = $b;
next;
}
if ($a eq "file_patterns") {
$ret{"file_patterns"} = $b;
next;
}
if ($a eq "file_exceptions") {
$ret{"file_exceptions"} = $b;
next;
}
if ($a eq "luaspecial") {
$ret{"luaspecial"} = $b;
next;
}
if ($a eq "databases") {
@{$ret{"databases"}} = split /,/, $b;
next;
}
if ($a eq "synonyms") {
@{$ret{"synonyms"}} = split /,/, $b;
next;
}
if ($a eq "comment") {
$ret{"comment"} = $b;
next;
}
# should not be reached at all
$ret{"error"} = "Unknown language directive $a";
return %ret;
}
# this default value couldn't be set earlier
if (not defined($ret{"databases"})) {
if (defined $ret{"file_patterns"} or defined $ret{"file_exceptions"}
or defined $ret{"luaspecial"}) {
@{$ret{"databases"}} = qw(dat def lua);
} else {
@{$ret{"databases"}} = qw(dat def);
}
}
return %ret;
}
#
# return hash of items on AddFormat line LINE (which must not have the
# leading "execute AddFormat"). If parse fails, hash will contain a key
# "error" with a message.
#
sub parse_AddFormat_line {
my $line = shift;
my %ret;
$ret{"options"} = "";
$ret{"patterns"} = "-";
$ret{"mode"} = 1;
for my $p (quotewords('\s+', 0, "$line")) {
my ($a, $b);
if ($p =~ m/^(name|engine|mode|patterns|options|fmttriggers)=(.*)$/) {
$a = $1;
$b = $2;
} else {
$ret{"error"} = "Unknown format directive $p";
return %ret;
}
if ($a eq "name") {
if (!$b) {
$ret{"error"} = "AddFormat line needs name=something";
return %ret;
}
$ret{"name"} = $b;
next;
}
if ($a eq "engine") {
if (!$b) {
$ret{"error"} = "AddFormat line needs engine=something";
return %ret;
}
$ret{"engine"} = $b;
next;
}
if ($a eq "patterns") {
$ret{"patterns"} = ( $b ? $b : "-" );
next;
}
if ($a eq "mode") {
$ret{"mode"} = ( $b eq "disabled" ? 0 : 1 );
next;
}
if ($a eq "options") {
$ret{"options"} = ( $b ? $b : "" );
next;
}
if ($a eq "fmttriggers") {
my @tl = split(',',$b);
$ret{"fmttriggers"} = \@tl ;
next;
}
# should not be reached at all
$ret{"error"} = "Unknown format directive $p";
return %ret;
}
return %ret;
}
=back
=head2 Logging
Logging and debugging messages.
=over 4
=item C<logit($out,$level,@rest)>
Internal routine to write message to both C<$out> (references to
filehandle) and C<$::LOGFILE>, at level C<$level>, of concatenated items
in C<@rest>. If the log file is not initialized yet, the message is
saved to be logged later (unless the log file never comes into existence).
=cut
sub logit {
my ($out, $level, @rest) = @_;
_logit($out, $level, @rest) unless $::opt_quiet;
_logit('file', $level, @rest);
}
sub _logit {
my ($out, $level, @rest) = @_;
if ($::opt_verbosity >= $level) {
# if $out is a ref/glob to STDOUT or STDERR, print it there
if (ref($out) eq "GLOB") {
print $out @rest;
} else {
# we should log it into the logfile, but that might be not initialized
# so either print it to the filehandle $::LOGFILE, or push it onto
# the to be printed log lines @::LOGLINES
if (defined($::LOGFILE)) {
print $::LOGFILE @rest;
} else {
push (@::LOGLINES, join ("", @rest));
}
}
}
}
=item C<info ($str1, $str2, ...)>
Write a normal informational message, the concatenation of the argument
strings. The message will be written unless C<-q> was specified. If
the global C<$::machinereadable> is set (the C<--machine-readable>
option to C<tlmgr>), then output is written to stderr, else to stdout.
If the log file (see L<process_logging_options>) is defined, it also
writes there.
It is best to use this sparingly, mainly to give feedback during lengthy
operations and for final results.
=cut
sub info {
my $str = join("", @_);
my $fh = ($::machinereadable ? \*STDERR : \*STDOUT);
logit($fh, 0, $str);
for my $i (@::info_hook) {
&{$i}($str);
}
}
=item C<debug ($str1, $str2, ...)>
Write a debugging message, the concatenation of the argument strings.
The message will be omitted unless C<-v> was specified. If the log
file (see L<process_logging_options>) is defined, it also writes there.
This first level debugging message reports on the overall flow of
work, but does not include repeated messages about processing of each
package.
=cut
sub debug {
return if ($::opt_verbosity < 1);
my $str = "D:" . join("", @_);
logit(\*STDERR, 1, $str);
for my $i (@::debug_hook) {
&{$i}($str);
}
}
=item C<ddebug ($str1, $str2, ...)>
Write a deep debugging message, the concatenation of the argument
strings. The message will be omitted unless C<-v -v> (or higher) was
specified. If the log file (see L<process_logging_options>) is defined,
it also writes there.
This second level debugging message reports messages about processing
each package, in addition to the first level.
=cut
sub ddebug {
return if ($::opt_verbosity < 2);
my $str = "DD:" . join("", @_);
logit(\*STDERR, 2, $str);
for my $i (@::ddebug_hook) {
&{$i}($str);
}
}
=item C<dddebug ($str1, $str2, ...)>
Write the deepest debugging message, the concatenation of the argument
strings. The message will be omitted unless C<-v -v -v> was specified.
If the log file (see L<process_logging_options>) is defined, it also
writes there.
In addition to the first and second levels, this third level debugging
message reports messages about processing each line of any tlpdb files
read, and messages about files tested or matched against tlpsrc
patterns. This output is extremely voluminous, so unless you're
debugging those parts of the code, it just gets in the way.
=cut
sub dddebug {
return if ($::opt_verbosity < 3);
my $str = "DDD:" . join("", @_);
logit(\*STDERR, 3, $str);
for my $i (@::dddebug_hook) {
&{$i}($str);
}
}
=item C<log ($str1, $str2, ...)>
Write a message to the log file (and nowhere else), the concatenation of
the argument strings. The log file may not ever be defined (e.g., the
C<-logfile> option isn't given), in which case the message will never be
written anywhere.
=cut
sub log {
my $savequiet = $::opt_quiet;
$::opt_quiet = 0;
_logit('file', -100, @_);
$::opt_quiet = $savequiet;
}
=item C<tlwarn ($str1, $str2, ...)>
Write a warning message, the concatenation of the argument strings.
This always and unconditionally writes the message to standard error; if
the log file (see L<process_logging_options>) is defined, it also writes
there.
=cut
sub tlwarn {
my $savequiet = $::opt_quiet;
my $str = join("", @_);
$::opt_quiet = 0;
logit (\*STDERR, -100, $str);
$::opt_quiet = $savequiet;
for my $i (@::warn_hook) {
&{$i}($str);
}
}
=item C<tldie ($str1, $str2, ...)>
Uses C<tlwarn> to issue a warning for @_ preceded by a newline, then
exits with exit code 1.
=cut
sub tldie {
tlwarn("\n", @_);
if ($::gui_mode) {
Tk::exit(1);
} else {
exit(1);
}
}
=item C<debug_hash_str($label, HASH)>
Return LABEL followed by HASH elements, followed by a newline, as a
single string. If HASH is a reference, it is followed (but no recursive
derefencing).
=item C<debug_hash($label, HASH)>
Write the result of C<debug_hash_str> to stderr.
=cut
sub debug_hash_str {
my ($label) = shift;
my (%hash) = (ref $_[0] && $_[0] =~ /.*HASH.*/) ? %{$_[0]} : @_;
my $str = "$label: {";
my @items = ();
for my $key (sort keys %hash) {
my $val = $hash{$key};
$val = ".undef" if ! defined $val;
$key =~ s/\n/\\n/g;
$val =~ s/\n/\\n/g;
push (@items, "$key:$val");
}
$str .= join (",", @items);
$str .= "}";
return "$str\n";
}
sub debug_hash {
warn &debug_hash_str(@_);
}
=item C<backtrace()>
Return call(er) stack, as a string.
=cut
sub backtrace {
my $ret = "";
my ($filename, $line, $subr);
my $stackframe = 1; # skip ourselves
while ((undef,$filename,$line,$subr) = caller ($stackframe)) {
# the undef is for the package, which is already included in $subr.
$ret .= " -> ${filename}:${line}: ${subr}\n";
$stackframe++;
}
return $ret;
}
=item C<process_logging_options ($texdir)>
This function handles the common logging options for TeX Live scripts.
It should be called before C<GetOptions> for any program-specific option
handling. For our conventional calling sequence, see (for example) the
L<tlpfiles> script.
These are the options handled here:
=over 4
=item B<-q>
Omit normal informational messages.
=item B<-v>
Include debugging messages. With one C<-v>, reports overall flow; with
C<-v -v> (or C<-vv>), also reports per-package processing; with C<-v -v
-v> (or C<-vvv>), also reports each line read from any tlpdb files.
Further repeats of C<-v>, as in C<-v -v -v -v>, are accepted but
ignored. C<-vvvv> is an error.
The idea behind these levels is to be able to specify C<-v> to get an
overall idea of what is going on, but avoid terribly voluminous output
when processing many packages, as we often are. When debugging a
specific problem with a specific package, C<-vv> can help. When
debugging problems with parsing tlpdb files, C<-vvv> gives that too.
=item B<-logfile> I<file>
Write all messages (informational, debugging, warnings) to I<file>, in
addition to standard output or standard error. In TeX Live, only the
installer sets a log file by default; none of the other standard TeX
Live scripts use this feature, but you can specify it explicitly.
=back
See also the L<info>, L<debug>, L<ddebug>, and L<tlwarn> functions,
which actually write the messages.
=cut
sub process_logging_options {
$::opt_verbosity = 0;
$::opt_quiet = 0;
my $opt_logfile;
my $opt_Verbosity = 0;
my $opt_VERBOSITY = 0;
# check all the command line options for occurrences of -q and -v;
# do not report errors.
my $oldconfig = Getopt::Long::Configure(qw(pass_through permute));
GetOptions("logfile=s" => \$opt_logfile,
"v+" => \$::opt_verbosity,
"vv" => \$opt_Verbosity,
"vvv" => \$opt_VERBOSITY,
"q" => \$::opt_quiet);
Getopt::Long::Configure($oldconfig);
# verbosity level, forcing -v -v instead of -vv is too annoying.
$::opt_verbosity = 2 if $opt_Verbosity;
$::opt_verbosity = 3 if $opt_VERBOSITY;
# open log file if one was requested.
if ($opt_logfile) {
open(TLUTILS_LOGFILE, ">$opt_logfile")
|| die "open(>$opt_logfile) failed: $!\n";
$::LOGFILE = \*TLUTILS_LOGFILE;
$::LOGFILENAME = $opt_logfile;
}
}
=back
=head2 Miscellaneous
A few ideas from Fabrice Popineau's C<FileUtils.pm>.
=over 4
=item C<sort_uniq(@list)>
The C<sort_uniq> function sorts the given array and throws away multiple
occurrences of elements. It returns a sorted and unified array.
=cut
sub sort_uniq {
my (@l) = @_;
my ($e, $f, @r);
$f = "";
@l = sort(@l);
foreach $e (@l) {
if ($e ne $f) {
$f = $e;
push @r, $e;
}
}
return @r;
}
=item C<push_uniq(\@list, @new_items)>
The C<push_uniq> function pushes each element in the last argument
@ITEMS to the $LIST referenced by the first argument, if it is not
already in the list.
=cut
sub push_uniq {
my ($l, @new_items) = @_;
for my $e (@new_items) {
# turns out this is one of the most-used functions when updating the
# tlpdb, with hundreds of thousands of calls. So let's write it out
# to eliminate the sub overhead.
#if (! &member($e, @$l)) {
if (! scalar grep($_ eq $e, @$l)) {
push (@$l, $e);
}
}
}
=item C<member($item, @list)>
The C<member> function returns true if the first argument
is also inclued in the list of the remaining arguments.
=cut
sub member {
my $what = shift;
return scalar grep($_ eq $what, @_);
}
=item C<merge_into(\%to, \%from)>
Merges the keys of %from into %to.
=cut
sub merge_into {
my ($to, $from) = @_;
foreach my $k (keys %$from) {
if (defined($to->{$k})) {
push @{$to->{$k}}, @{$from->{$k}};
} else {
$to->{$k} = [ @{$from->{$k}} ];
}
}
}
=item C<texdir_check($texdir)>
Test whether installation with TEXDIR set to $texdir should be ok, e.g.,
would be a creatable directory. Return 1 if ok, 0 if not.
Writable or not, we will not allow installation to the root
directory (Unix) or the root of a drive (Windows).
We also do not allow paths containing various special characters, and
print a message about this if second argument WARN is true. (We only
want to do this for the regular text installer, since spewing output in
a GUI program wouldn't be good; the generic message will have to do for
them.)
=cut
sub texdir_check {
my ($orig_texdir,$warn) = @_;
return 0 unless defined $orig_texdir;
# convert to absolute, for safer parsing.
# also replaces backslashes with slashes on w32.
# The return value may still contain symlinks,
# but no unnecessary terminating '/'.
my $texdir = tl_abs_path($orig_texdir);
return 0 unless defined $texdir;
# reject the root of a drive,
# assuming that only the canonical form of the root ends with /
return 0 if $texdir =~ m!/$!;
# Unfortunately we have lots of special characters.
# On Windows, backslashes are normal but will already have been changed
# to slashes by tl_abs_path. And we should only check for : on Unix.
my $colon = wndws() ? "" : ":";
if ($texdir =~ /[,$colon;\\{}\$]/) {
if ($warn) {
print " !! TEXDIR value has problematic characters: $orig_texdir\n";
print " !! (such as comma, colon, semicolon, backslash, braces\n";
print " !! and dollar sign; sorry)\n";
}
# although we could check each character individually and give a
# specific error, it seems plausibly useful to report all the chars
# that cause problems, regardless of which was there. Simpler too.
return 0;
}
# w32: for now, reject the root of a samba share
return 0 if wndws() && $texdir =~ m!^//[^/]+/[^/]+$!;
# if texdir already exists, make sure we can write into it.
return dir_writable($texdir) if (-d $texdir);
# if texdir doesn't exist, make sure we can write the parent.
(my $texdirparent = $texdir) =~ s!/[^/]*$!!;
#print STDERR "Checking $texdirparent".'[/]'."\n";
return dir_creatable($texdirparent) if -d dir_slash($texdirparent);
# ditto for the next level up the tree
(my $texdirpparent = $texdirparent) =~ s!/[^/]*$!!;
#print STDERR "Checking $texdirpparent".'[/]'."\n";
return dir_creatable($texdirpparent) if -d dir_slash($texdirpparent);
# doesn't look plausible.
return 0;
}
=pod
This function takes a single argument I<path> and returns it with
C<"> chars surrounding it on Unix. On Windows, the C<"> chars are only
added if I<path> contains special characters, since unconditional quoting
leads to errors there. In all cases, any C<"> chars in I<path> itself
are (erroneously) eradicated.
=cut
sub quotify_path_with_spaces {
my $p = shift;
my $m = wndws() ? '[+=^&();,!%\s]' : '.';
if ( $p =~ m/$m/ ) {
$p =~ s/"//g; # remove any existing double quotes
$p = "\"$p\"";
}
return($p);
}
=pod
This function returns a "Windows-ized" version of its single argument
I<path>, i.e., replaces all forward slashes with backslashes, and adds
an additional C<"> at the beginning and end if I<path> contains any
spaces. It also makes the path absolute. So if $path does not start
with one (arbitrary) characer followed by C<:>, we add the output of
C<`cd`>.
The result is suitable for running in shell commands, but not file tests
or other manipulations, since in such internal Perl contexts, the quotes
would be considered part of the filename.
=cut
sub conv_to_w32_path {
my $p = shift;
# we need absolute paths, too
my $pabs = tl_abs_path($p);
if (not $pabs) {
$pabs = $p;
tlwarn ("sorry, could not determine absolute path of $p!\n".
"using original path instead");
}
$pabs =~ s!/!\\!g;
$pabs = quotify_path_with_spaces($pabs);
return($pabs);
}
=pod
The next two functions are meant for user input/output in installer menus.
They help making the windows user happy by turning slashes into backslashes
before displaying a path, and our code happy by turning backslashes into forwars
slashes after reading a path. They both are no-ops on Unix.
=cut
sub native_slashify {
my ($r) = @_;
$r =~ s!/!\\!g if wndws();
return $r;
}
sub forward_slashify {
my ($r) = @_;
$r =~ s!\\!/!g if wndws();
return $r;
}
=item C<setup_persistent_downloads()>
Set up to use persistent connections using LWP/TLDownload, that is look
for a download server. Return the TLDownload object if successful, else
false.
=cut
sub setup_persistent_downloads {
my $certs = shift;
if ($TeXLive::TLDownload::net_lib_avail) {
ddebug("setup_persistent_downloads has net_lib_avail set\n");
if ($::tldownload_server) {
if ($::tldownload_server->initcount() > $TeXLive::TLConfig::MaxLWPReinitCount) {
debug("stop retrying to initialize LWP after 10 failures\n");
return 0;
} else {
$::tldownload_server->reinit(certificates => $certs);
}
} else {
$::tldownload_server = TeXLive::TLDownload->new(certificates => $certs);
}
if (!defined($::tldownload_server)) {
ddebug("TLUtils:setup_persistent_downloads: failed to get ::tldownload_server\n");
} else {
ddebug("TLUtils:setup_persistent_downloads: got ::tldownload_server\n");
}
return $::tldownload_server;
}
return 0;
}
=item C<query_ctan_mirror()>
Return a particular mirror given by the generic CTAN auto-redirecting
default (specified in L<$TLConfig::TexLiveServerURL>) if we get a
response, else the empty string.
Use C<curl> if it is listed as a C<working_downloader>, else C<wget>,
else give up. We can't support arbitrary downloaders here, as we do for
regular package downloads, since certain options have to be set and the
output has to be parsed.
We try invoking the program three times (hardwired).
=cut
sub query_ctan_mirror {
my @working_downloaders = @{$::progs{'working_downloaders'}};
ddebug("query_ctan_mirror: working_downloaders: @working_downloaders\n");
if (TeXLive::TLUtils::member("curl", @working_downloaders)) {
return query_ctan_mirror_curl();
} elsif (TeXLive::TLUtils::member("wget", @working_downloaders)) {
if ($::progs{'options'}{'wget-ssl'}) {
# we need ssl enabled wget to query ctan
return query_ctan_mirror_wget();
} else {
tlwarn(<<END_NO_SSL);
TLUtils::query_ctan_mirror: neither curl nor an ssl-enabled wget is
available, so no CTAN mirror can be resolved via https://mirror.ctan.org.
Please install curl or ssl-enabled wget; otherwise, please pick an
http (not https) mirror from the list at https://ctan.org/mirrors/mirmon.
To report a bug about this, please rerun your command with -vv and
include the resulting output with the report.
END_NO_SSL
return;
}
} else {
return;
}
}
# curl will follow the redirect chain for us.
#
sub query_ctan_mirror_curl {
my $max_trial = 3;
my $warg = (wndws() ? '-w "%{url_effective}" ' : "-w '%{url_effective}' ");
for (my $i = 1; $i <= $max_trial; $i++) {
# -L -> follow redirects
# -s -> silent
# -w -> what to output after completion
my $cmd = "$::progs{'curl'} -Ls "
. "-o " . nulldev() . " "
. $warg
. "--connect-timeout $NetworkTimeout "
. "--max-time $NetworkTimeout "
. $TeXLiveServerURL;
ddebug("query_ctan_mirror_curl: cmd: $cmd\n");
my $url = `$cmd`;
if (length $url) {
# remove trailing slashes
$url =~ s,/*$,,;
ddebug("query_ctan_mirror_curl: returning url: $url\n");
return $url;
}
sleep(1);
}
return;
}
sub query_ctan_mirror_wget {
my $wget = $::progs{'wget'};
if (!defined ($wget)) {
tlwarn("query_ctan_mirror_wget: Programs not set up, trying wget\n");
$wget = "wget";
}
# we need the verbose output, so no -q.
# do not reduce retries here, but timeout still seems desirable.
my $mirror = $TeXLiveServerURL;
my $cmd = "$wget $mirror --timeout=$NetworkTimeout "
. "-O " . nulldev() . " 2>&1";
ddebug("query_ctan_mirror_wget: cmd is $cmd\n");
# since we are reading the output of wget to find a mirror
# we have to make sure that the locale is unset
my $saved_lcall;
if (defined($ENV{'LC_ALL'})) {
$saved_lcall = $ENV{'LC_ALL'};
}
$ENV{'LC_ALL'} = "C";
# we try 3 times to get a mirror from mirror.ctan.org in case we have
# bad luck with what gets returned.
my $max_trial = 3;
my $mhost;
for (my $i = 1; $i <= $max_trial; $i++) {
my @out = `$cmd`;
# analyze the output for the mirror actually selected.
foreach (@out) {
if (m/^Location: (\S*)\s*.*$/) {
(my $mhost = $1) =~ s,/*$,,; # remove trailing slashes since we add it
ddebug("query_ctan_mirror_wget: returning url: $mhost\n");
return $mhost;
}
}
sleep(1);
}
# reset LC_ALL to undefined or the previous value
if (defined($saved_lcall)) {
$ENV{'LC_ALL'} = $saved_lcall;
} else {
delete($ENV{'LC_ALL'});
}
# we are still here, so three times we didn't get a mirror, give up
# and return undefined
return;
}
=item C<check_on_working_mirror($mirror)>
Check if MIRROR is functional.
=cut
sub check_on_working_mirror {
my $mirror = shift;
my $wget = $::progs{'wget'};
if (!defined ($wget)) {
tlwarn ("check_on_working_mirror: Programs not set up, trying wget\n");
$wget = "wget";
}
$wget = quotify_path_with_spaces($wget);
#
# the test is currently not completely correct, because we do not
# use the LWP if it is set up for it, but I am currently too lazy
# to program it,
# so try wget and only check for the return value
# please KEEP the / after $mirror, some ftp mirrors do give back
# an error if the / is missing after ../CTAN/
my $cmd = "$wget $mirror/ --timeout=$NetworkTimeout -O -"
. " >" . (TeXLive::TLUtils::nulldev())
. " 2>" . (TeXLive::TLUtils::nulldev());
my $ret = system($cmd);
# if return value is not zero it is a failure, so switch the meanings
return ($ret ? 0 : 1);
}
=item C<give_ctan_mirror_base()>
1. get a mirror (retries 3 times to contact mirror.ctan.org)
- if no mirror found, use one of the backbone servers
- if it is an http server return it (no test is done)
- if it is a ftp server, continue
2. if the ftp mirror is good, return it
3. if the ftp mirror is bad, search for http mirror (5 times)
4. if http mirror is found, return it (again, no test,)
5. if no http mirror is found, return one of the backbone servers
=cut
sub give_ctan_mirror_base {
# only one backbone has existed for a while (2018).
my @backbone = qw!https://www.ctan.org/tex-archive!;
# start by selecting a mirror and test its operationality
ddebug("give_ctan_mirror_base: calling query_ctan_mirror\n");
my $mirror = query_ctan_mirror();
if (!defined($mirror)) {
# three times calling mirror.ctan.org did not give anything useful,
# return one of the backbone servers
tlwarn("cannot contact mirror.ctan.org, returning a backbone server!\n");
return $backbone[int(rand($#backbone + 1))];
}
if ($mirror =~ m!^https?://!) { # if http mirror, assume good and return.
return $mirror;
}
# we are still here, so we got a ftp mirror from mirror.ctan.org
if (check_on_working_mirror($mirror)) {
return $mirror; # ftp mirror is working, return.
}
# we are still here, so the ftp mirror failed, retry and hope for http.
# theory is that if one ftp fails, probably all ftp is broken.
my $max_mirror_trial = 5;
for (my $try = 1; $try <= $max_mirror_trial; $try++) {
my $m = query_ctan_mirror();
debug("querying mirror, got " . (defined($m) ? $m : "(nothing)") . "\n");
if (defined($m) && $m =~ m!^https?://!) {
return $m; # got http this time, assume ok.
}
# sleep to make mirror happy, but only if we are not ready to return
sleep(1) if $try < $max_mirror_trial;
}
# 5 times contacting the mirror service did not return a http server,
# use one of the backbone servers.
debug("no mirror found ... randomly selecting backbone\n");
return $backbone[int(rand($#backbone + 1))];
}
sub give_ctan_mirror {
return (give_ctan_mirror_base(@_) . "/$TeXLiveServerPath");
}
=item C<create_mirror_list()>
=item C<extract_mirror_entry($listentry)>
C<create_mirror_list> returns the lists of viable mirrors according to
ctan-mirrors.pl, in a list which also contains continents, and country headers.
C<extract_mirror_entry> extracts the actual repository data from one
of these entries.
# KEEP THESE TWO FUNCTIONS IN SYNC!!!
=cut
sub create_mirror_list {
our $mirrors;
my @ret = ();
require("installer/ctan-mirrors.pl");
my @continents = sort keys %$mirrors;
for my $continent (@continents) {
# first push the name of the continent
push @ret, uc($continent);
my @countries = sort keys %{$mirrors->{$continent}};
for my $country (@countries) {
my @mirrors = sort keys %{$mirrors->{$continent}{$country}};
my $first = 1;
for my $mirror (@mirrors) {
my $mfull = $mirror;
$mfull =~ s!/$!!;
# do not append the server path part here, but add
# it down there in the extract mirror entry
#$mfull .= "/" . $TeXLive::TLConfig::TeXLiveServerPath;
#if ($first) {
my $country_str = sprintf "%-12s", $country;
push @ret, " $country_str $mfull";
# $first = 0;
#} else {
# push @ret, " $mfull";
#}
}
}
}
return @ret;
}
# extract_mirror_entry is not very intelligent, it assumes that
# the last "word" is the URL
sub extract_mirror_entry {
my $ent = shift;
my @foo = split ' ', $ent;
return $foo[$#foo] . "/" . $TeXLive::TLConfig::TeXLiveServerPath;
}
=pod
=item C<< slurp_file($file) >>
Reads the whole file and returns the content in a scalar.
=cut
sub slurp_file {
my $file = shift;
my $file_data = do {
local $/ = undef;
open my $fh, "<", $file || die "open($file) failed: $!";
<$fh>;
};
return($file_data);
}
=pod
=item C<< download_to_temp_or_file($url) >>
If C<$url> is a url, tries to download the file into a temporary file.
Otherwise assume that C<$url> is a local file.
In both cases returns the local file.
Returns the local file name if succeeded, otherwise undef.
=cut
sub download_to_temp_or_file {
my $url = shift;
my $ret;
my ($url_fh, $url_file);
if ($url =~ m,^(https?|ftp|file)://, || $url =~ m!$SshURIRegex!) {
($url_fh, $url_file) = tl_tmpfile();
# now $url_fh filehandle is open, the file created
# TLUtils::download_file will just overwrite what is there
# on windows that doesn't work, so we close the fh immediately
# this creates a short loophole, but much better than before anyway
close($url_fh);
$ret = download_file($url, $url_file);
} else {
$url_file = $url;
$ret = 1;
}
if ($ret && (-r "$url_file")) {
return $url_file;
}
return;
}
=item C<< compare_tlpobjs($tlpA, $tlpB) >>
Compare the two passed L<TLPOBJ> objects. Returns a hash:
$ret{'revision'} = "revA:revB" # if revisions differ
$ret{'removed'} = \[ list of files removed from A to B ]
$ret{'added'} = \[ list of files added from A to B ]
$ret{'fmttriggers'} = 1 if the fmttriggers have changed
=cut
sub compare_tlpobjs {
my ($tlpA, $tlpB) = @_;
my %ret;
my $rA = $tlpA->revision;
my $rB = $tlpB->revision;
if ($rA != $rB) {
$ret{'revision'} = "$rA:$rB";
}
if ($tlpA->relocated) {
$tlpA->replace_reloc_prefix;
}
if ($tlpB->relocated) {
$tlpB->replace_reloc_prefix;
}
my @fA = $tlpA->all_files;
my @fB = $tlpB->all_files;
my %removed;
my %added;
for my $f (@fA) { $removed{$f} = 1; }
for my $f (@fB) { delete($removed{$f}); $added{$f} = 1; }
for my $f (@fA) { delete($added{$f}); }
my @rem = sort keys %removed;
my @add = sort keys %added;
$ret{'removed'} = \@rem if @rem;
$ret{'added'} = \@add if @add;
# changed dependencies should not trigger a change without a
# change in revision, so for now (until we find a reason why
# we need to) we don't check.
# OTOH, execute statements like
# execute AddFormat name=aleph engine=aleph options=*aleph.ini fmttriggers=cm,hyphen-base,knuth-lib,plain
# might change due to changes in the fmttriggers variables.
# Again, name/engine/options are only defined in the package's
# tlpsrc file, so changes here will trigger revision changes,
# but fmttriggers are defined outside the tlpsrc and thus do
# not trigger an automatic revision change. Check for that!
# No need to record actual changes, just record that it has changed.
my %triggersA;
my %triggersB;
# we sort executes after format/engine like fmtutil does, since this
# should be unique
for my $e ($tlpA->executes) {
if ($e =~ m/AddFormat\s+(.*)\s*/) {
my %r = parse_AddFormat_line("$1");
if (defined($r{"error"})) {
die "$r{'error'} when comparing packages $tlpA->name execute $e";
}
for my $t (@{$r{'fmttriggers'}}) {
$triggersA{"$r{'name'}:$r{'engine'}:$t"} = 1;
}
}
}
for my $e ($tlpB->executes) {
if ($e =~ m/AddFormat\s+(.*)\s*/) {
my %r = parse_AddFormat_line("$1");
if (defined($r{"error"})) {
die "$r{'error'} when comparing packages $tlpB->name execute $e";
}
for my $t (@{$r{'fmttriggers'}}) {
$triggersB{"$r{'name'}:$r{'engine'}:$t"} = 1;
}
}
}
for my $t (keys %triggersA) {
delete($triggersA{$t});
delete($triggersB{$t});
}
if (keys(%triggersA) || keys(%triggersB)) {
$ret{'fmttrigger'} = 1;
}
return %ret;
}
=item C<< compare_tlpdbs($tlpdbA, $tlpdbB, @more_ignored_pkgs) >>
Compare the two passed L<TLPDB> objects, ignoring the packages
C<00texlive.installer>, C<00texlive.image>, and any passed
C<@more_ignore_pkgs>. Returns a hash:
$ret{'removed_packages'} = \[ list of removed packages from A to B ]
$ret{'added_packages'} = \[ list of added packages from A to B ]
$ret{'different_packages'}->{$package} = output of compare_tlpobjs
=cut
sub compare_tlpdbs {
my ($tlpdbA, $tlpdbB, @add_ignored_packs) = @_;
my @ignored_packs = qw/00texlive.installer 00texlive.image/;
push @ignored_packs, @add_ignored_packs;
my @inAnotinB;
my @inBnotinA;
my %diffpacks;
my %do_compare;
my %ret;
for my $p ($tlpdbA->list_packages()) {
my $is_ignored = 0;
for my $ign (@ignored_packs) {
if (($p =~ m/^$ign$/) || ($p =~ m/^$ign\./)) {
$is_ignored = 1;
last;
}
}
next if $is_ignored;
my $tlpB = $tlpdbB->get_package($p);
if (!defined($tlpB)) {
push @inAnotinB, $p;
} else {
$do_compare{$p} = 1;
}
}
$ret{'removed_packages'} = \@inAnotinB if @inAnotinB;
for my $p ($tlpdbB->list_packages()) {
my $is_ignored = 0;
for my $ign (@ignored_packs) {
if (($p =~ m/^$ign$/) || ($p =~ m/^$ign\./)) {
$is_ignored = 1;
last;
}
}
next if $is_ignored;
my $tlpA = $tlpdbA->get_package($p);
if (!defined($tlpA)) {
push @inBnotinA, $p;
} else {
$do_compare{$p} = 1;
}
}
$ret{'added_packages'} = \@inBnotinA if @inBnotinA;
for my $p (sort keys %do_compare) {
my $tlpA = $tlpdbA->get_package($p);
my $tlpB = $tlpdbB->get_package($p);
my %foo = compare_tlpobjs($tlpA, $tlpB);
if (keys %foo) {
# some diffs were found
$diffpacks{$p} = \%foo;
}
}
$ret{'different_packages'} = \%diffpacks if (keys %diffpacks);
return %ret;
}
sub tlnet_disabled_packages {
my ($root) = @_;
my $disabled_pkgs = "$root/tlpkg/dev/tlnet-disabled-packages.txt";
my @ret;
if (-r $disabled_pkgs) {
open (DISABLED, "<$disabled_pkgs") || die "Huu, -r but cannot open: $?";
while (<DISABLED>) {
chomp;
next if /^\s*#/;
next if /^\s*$/;
$_ =~ s/^\s*//;
$_ =~ s/\s*$//;
push @ret, $_;
}
close(DISABLED) || warn ("Cannot close tlnet-disabled-packages.txt: $?");
}
return @ret;
}
sub report_tlpdb_differences {
my $rret = shift;
my %ret = %$rret;
if (defined($ret{'removed_packages'})) {
info ("removed packages from A to B:\n");
for my $f (sort @{$ret{'removed_packages'}}) {
info (" $f\n");
}
}
if (defined($ret{'added_packages'})) {
info ("added packages from A to B:\n");
for my $f (sort @{$ret{'added_packages'}}) {
info (" $f\n");
}
}
if (defined($ret{'different_packages'})) {
info ("different packages from A to B:\n");
for my $p (sort keys %{$ret{'different_packages'}}) {
info (" $p\n");
for my $k (sort keys %{$ret{'different_packages'}->{$p}}) {
if ($k eq "revision") {
info(" revision differ: $ret{'different_packages'}->{$p}->{$k}\n");
} elsif ($k eq "removed" || $k eq "added") {
info(" $k files:\n");
for my $f (sort @{$ret{'different_packages'}->{$p}->{$k}}) {
info(" $f\n");
}
} else {
# e.g., fmttriggers; don't bother making a nice report.
info(" unknown differ $k\n");
}
}
}
}
}
sub sort_archs ($$) {
my $aa = $_[0];
my $bb = $_[1];
$aa =~ s/^(.*)-(.*)$/$2-$1/;
$bb =~ s/^(.*)-(.*)$/$2-$1/;
$aa cmp $bb ;
}
# Taken from Text::ParseWords
#
sub quotewords {
my($delim, $keep, @lines) = @_;
my($line, @words, @allwords);
foreach $line (@lines) {
@words = parse_line($delim, $keep, $line);
return() unless (@words || !length($line));
push(@allwords, @words);
}
return(@allwords);
}
sub parse_line {
my($delimiter, $keep, $line) = @_;
my($word, @pieces);
no warnings 'uninitialized'; # we will be testing undef strings
$line =~ s/\s+$//; # kill trailing whitespace
while (length($line)) {
$line =~ s/^(["']) # a $quote
((?:\\.|(?!\1)[^\\])*) # and $quoted text
\1 # followed by the same quote
| # --OR--
^((?:\\.|[^\\"'])*?) # an $unquoted text
(\Z(?!\n)|(?-x:$delimiter)|(?!^)(?=["']))
# plus EOL, delimiter, or quote
//xs or return; # extended layout
my($quote, $quoted, $unquoted, $delim) = ($1, $2, $3, $4);
return() unless( defined($quote) || length($unquoted) || length($delim));
if ($keep) {
$quoted = "$quote$quoted$quote";
} else {
$unquoted =~ s/\\(.)/$1/sg;
if (defined $quote) {
$quoted =~ s/\\(.)/$1/sg if ($quote eq '"');
$quoted =~ s/\\([\\'])/$1/g if ( $PERL_SINGLE_QUOTE && $quote eq "'");
}
}
$word .= substr($line, 0, 0); # leave results tainted
$word .= defined $quote ? $quoted : $unquoted;
if (length($delim)) {
push(@pieces, $word);
push(@pieces, $delim) if ($keep eq 'delimiters');
undef $word;
}
if (!length($line)) {
push(@pieces, $word);
}
}
return(@pieces);
}
=item C<mktexupd ()>
Append entries to C<ls-R> files. Usage example:
my $updLSR=&mktexupd();
$updLSR->{mustexist}(1);
$updLSR->{add}(file1);
$updLSR->{add}(file2);
$updLSR->{add}(file3);
$updLSR->{exec}();
The first line creates a new object. Only one such object should be
created in a program in order to avoid duplicate entries in C<ls-R> files.
C<add> pushes a filename or a list of filenames to a hash encapsulated
in a closure. Filenames must be specified with the full (absolute) path.
Duplicate entries are ignored.
C<exec> checks for each component of C<$TEXMFDBS> whether there are files
in the hash which have to be appended to the corresponding C<ls-R> files
and eventually updates the corresponding C<ls-R> files. Files which are
in directories not stated in C<$TEXMFDBS> are silently ignored.
If the flag C<mustexist> is set, C<exec> aborts with an error message
if a file supposed to be appended to an C<ls-R> file doesn't exist physically
on the file system. This option was added for compatibility with the
C<mktexupd> shell script. This option shouldn't be enabled in scripts,
except for testing, because it degrades performance on non-cached file
systems.
=cut
sub mktexupd {
my %files;
my $mustexist=0;
my $hash={
"add" => sub {
foreach my $file (@_) {
$file =~ s|\\|/|g;
$files{$file}=1;
}
},
"reset" => sub {
%files=();
},
"mustexist" => sub {
$mustexist=shift;
},
"exec" => sub {
# check whether files exist
if ($mustexist) {
foreach my $file (keys %files) {
die "mktexupd: exec file does not exist: $file" if (! -f $file);
}
}
my $delim= (&wndws)? ';' : ':';
my $TEXMFDBS;
chomp($TEXMFDBS=`kpsewhich --show-path="ls-R"`);
my @texmfdbs=split ($delim, "$TEXMFDBS");
my %dbs;
foreach my $path (keys %files) {
foreach my $db (@texmfdbs) {
$db=substr($db, -1) if ($db=~m|/$|); # strip leading /
$db = lc($db) if wndws();
my $up = (wndws() ? lc($path) : $path);
if (substr($up, 0, length("$db/")) eq "$db/") {
# we appended a / because otherwise "texmf" is recognized as a
# substring of "texmf-dist".
my $np = './' . substr($up, length("$db/"));
my ($dir, $file);
$_=$np;
($dir, $file) = m|(.*)/(.*)|;
$dbs{$db}{$dir}{$file}=1;
}
}
}
foreach my $db (keys %dbs) {
if (! -f "$db" || ! -w "$db/ls-R") {
&mkdirhier ($db);
}
open LSR, ">>$db/ls-R";
foreach my $dir (keys %{$dbs{$db}}) {
print LSR "\n$dir:\n";
foreach my $file (keys %{$dbs{$db}{$dir}}) {
print LSR "$file\n";
}
}
close LSR;
}
}
};
return $hash;
}
=item C<setup_sys_user_mode($prg, $optsref, $tmfc, $tmfsc, $tmfv, $tmfsv)>
Return two-element list C<($texmfconfig,$texmfvar)> specifying which
directories to use, either user or sys. If C<$optsref->{'sys'}> is
true, we are in sys mode; else if C<$optsref->{'user'}> is set, we are
in user mode; else a fatal error.
If C<$prg> eq C<"mktexfmt">, and C<$TEXMFSYSVAR/web2c> is writable, use
it instead of C<$TEXMFVAR>, even if we are in user mode. C<$TEXMFCONFIG>
is not switched, however.
=cut
sub setup_sys_user_mode {
my ($prg, $optsref, $TEXMFCONFIG, $TEXMFSYSCONFIG,
$TEXMFVAR, $TEXMFSYSVAR) = @_;
if ($optsref->{'user'} && $optsref->{'sys'}) {
print STDERR "$prg [ERROR]: only one of -sys or -user can be used.\n";
exit(1);
}
# check if we are in *hidden* sys mode, in which case we switch
# to sys mode
# Nowdays we use -sys switch instead of simply overriding TEXMFVAR
# and TEXMFCONFIG
# This is used to warn users when they run updmap in usermode the first time.
# But it might happen that this script is called via another wrapper that
# sets TEXMFCONFIG and TEXMFVAR, and does not pass on the -sys option.
# for this case we check whether the SYS and non-SYS variants agree,
# and if, then switch to sys mode (with a warning)
if (($TEXMFSYSCONFIG eq $TEXMFCONFIG) && ($TEXMFSYSVAR eq $TEXMFVAR)) {
if ($optsref->{'user'}) {
print STDERR "$prg [ERROR]: -user mode but path setup is -sys type, bailing out.\n";
exit(1);
}
if (!$optsref->{'sys'}) {
print STDERR "$prg [WARNING]: hidden sys mode found, switching to sys mode.\n"
if (!$optsref->{'quiet'});
$optsref->{'sys'} = 1;
}
}
my ($texmfconfig, $texmfvar);
if ($optsref->{'sys'}) {
# we are running as updmap-sys, make sure that the right tree is used
$texmfconfig = $TEXMFSYSCONFIG;
$texmfvar = $TEXMFSYSVAR;
&debug("TLUtils::setup_sys_user_mode: sys mode\n");
} elsif ($optsref->{'user'}) {
$texmfconfig = $TEXMFCONFIG;
$texmfvar = $TEXMFVAR;
&debug("TLUtils::setup_sys_user_mode: user mode\n");
# mktexfmt is run (accidentally or on purpose) by a user with
# missing formats; we want to put the resulting format dumps in
# TEXMFSYSVAR if possible, so that future format updates will just
# work. Until 2021, they were put in TEXMFVAR, causing problems.
#
# We only do this for mktexfmt, not fmtutil; if fmtutil is called
# explicitly with fmtutil -user, ok, do what they said to do.
#
if ($prg eq "mktexfmt") {
my $switchit = 0;
if (-d "$TEXMFSYSVAR/web2c") {
$switchit = 1 if (-w "$TEXMFSYSVAR/web2c");
} elsif (-d $TEXMFSYSVAR && -w $TEXMFSYSVAR) {
$switchit = 1;
}
if ($switchit) {
$texmfvar = $TEXMFSYSVAR;
&ddebug(" switched to $texmfvar for mktexfmt\n");
}
}
} else {
print STDERR
"$prg [ERROR]: Either -sys or -user mode is required.\n" .
"$prg [ERROR]: In nearly all cases you should use $prg -sys.\n" .
"$prg [ERROR]: For special cases see https://tug.org/texlive/scripts-sys-user.html\n" ;
exit(1);
}
&debug(" returning: ($texmfconfig,$texmfvar)\n");
return ($texmfconfig, $texmfvar);
}
=item C<prepend_own_path()>
Prepend the location of the TeX Live binaries to the PATH environment
variable. This is used by (e.g.) C<fmtutil>. The location is found by
calling C<Cwd::abs_path> on C<which('kpsewhich')>. We use kpsewhich
because it is known to be a true binary executable; C<$0> could be a
symlink into (say) C<texmf-dist/scripts/>, which is not a useful
directory for PATH.
=cut
sub prepend_own_path {
my $bindir = dirname(Cwd::abs_path(which('kpsewhich')));
if (wndws()) {
$bindir =~ s!\\!/!g;
$ENV{'PATH'} = "$bindir;$ENV{PATH}";
} else {
$ENV{'PATH'} = "$bindir:$ENV{PATH}";
}
}
=item C<repository_to_array($r)>
Return hash of tags to urls for space-separated list of repositories
passed in C<$r>. If passed undef or empty string, die.
=cut
sub repository_to_array {
my $r = shift;
my %r;
if (!$r) {
# either empty string or undef was passed
# before 20181023 we die here, now we return
# an empty array
return %r;
}
#die "internal error, repository_to_array passed nothing (caller="
# . caller . ")" if (!$r);
my @repos = split (' ', $r);
if ($#repos == 0) {
# only one repo, this is the main one!
$r{'main'} = $repos[0];
return %r;
}
for my $rr (@repos) {
my $tag;
my $url;
# decode spaces and % in reverse order
$rr =~ s/%20/ /g;
$rr =~ s/%25/%/g;
$tag = $url = $rr;
if ($rr =~ m/^([^#]+)#(.*)$/) {
$tag = $2;
$url = $1;
}
$r{$tag} = $url;
}
return %r;
}
=back
=head2 JSON
=over 4
=item C<encode_json($ref)>
Returns the JSON representation of the object C<$ref> is pointing at.
This tries to load the C<JSON> Perl module, and uses it if available,
otherwise falls back to module internal conversion.
The used backend can be selected by setting the environment variable
C<TL_JSONMODE> to either C<json> or C<texlive> (all other values are
ignored). If C<json> is requested and the C<JSON> module cannot be loaded
the program terminates.
=cut
my $TLTrueValue = 1;
my $TLFalseValue = 0;
my $TLTrue = \$TLTrueValue;
my $TLFalse = \$TLFalseValue;
bless $TLTrue, 'TLBOOLEAN';
bless $TLFalse, 'TLBOOLEAN';
our $jsonmode = "";
=pod
=item C<True()>
=item C<False()>
These two crazy functions must be used to get proper JSON C<true> and
C<false> in the output independent of the backend used.
=cut
sub True {
ensure_json_available();
if ($jsonmode eq "json") {
return($JSON::true);
} else {
return($TLTrue);
}
}
sub False {
ensure_json_available();
if ($jsonmode eq "json") {
return($JSON::false);
} else {
return($TLFalse);
}
}
sub ensure_json_available {
return if ($jsonmode);
# check the environment for mode to use:
# $ENV{'TL_JSONMODE'} = texlive | json
my $envdefined = 0;
if ($ENV{'TL_JSONMODE'}) {
$envdefined = 1;
if ($ENV{'TL_JSONMODE'} eq "texlive") {
$jsonmode = "texlive";
debug("texlive json module used!\n");
return;
} elsif ($ENV{'TL_JSONMODE'} eq "json") {
# nothing to do
} else {
tlwarn("Unsupported mode \'$ENV{TL_JSONMODE}\' set in TL_JSONMODE, ignoring it!");
$envdefined = 0;
}
}
return if ($jsonmode); # was set to texlive
eval { require JSON; };
if ($@) {
# that didn't work out, use home-grown json
if ($envdefined) {
# environment asks for JSON but cannot be loaded, die!
tldie("envvar TL_JSONMODE request JSON module but cannot be loaded!\n");
}
$jsonmode = "texlive";
debug("texlive json module used!\n");
} else {
$jsonmode = "json";
my $json = JSON->new;
debug("JSON " . $json->backend . " used!\n");
}
}
sub encode_json {
my $val = shift;
ensure_json_available();
if ($jsonmode eq "json") {
my $utf8_encoded_json_text = JSON::encode_json($val);
return $utf8_encoded_json_text;
} else {
my $type = ref($val);
if ($type eq "") {
tldie("encode_json: accept only refs: $val");
} elsif ($type eq 'SCALAR') {
return(scalar_to_json($$val));
} elsif ($type eq 'ARRAY') {
return(array_to_json($val));
} elsif ($type eq 'HASH') {
return(hash_to_json($val));
} elsif ($type eq 'REF') {
return(encode_json($$val));
} elsif (Scalar::Util::blessed($val)) {
if ($type eq "TLBOOLEAN") {
return($$val ? "true" : "false");
} else {
tldie("encode_json: unsupported blessed object");
}
} else {
tldie("encode_json: unsupported format $type");
}
}
}
sub scalar_to_json {
sub looks_like_numeric {
# code from JSON/backportPP.pm
my $value = shift;
no warnings 'numeric';
# detect numbers
# string & "" -> ""
# number & "" -> 0 (with warning)
# nan and inf can detect as numbers, so check with * 0
return unless length((my $dummy = "") & $value);
return unless 0 + $value eq $value;
return 1 if $value * 0 == 0;
return -1; # inf/nan
}
my $val = shift;
if (defined($val)) {
if (looks_like_numeric($val)) {
return("$val");
} else {
return(string_to_json($val));
}
} else {
return("null");
}
}
sub string_to_json {
my $val = shift;
my %esc = (
"\n" => '\n',
"\r" => '\r',
"\t" => '\t',
"\f" => '\f',
"\b" => '\b',
"\"" => '\"',
"\\" => '\\\\',
"\'" => '\\\'',
);
$val =~ s/([\x22\x5c\n\r\t\f\b])/$esc{$1}/g;
return("\"$val\"");
}
sub hash_to_json {
my $hr = shift;
my @retvals;
for my $k (keys(%$hr)) {
my $val = $hr->{$k};
push @retvals, "\"$k\":" . encode_json(\$val);
}
my $ret = "{" . join(",", @retvals) . "}";
return($ret);
}
sub array_to_json {
my $hr = shift;
my $ret = "[" . join(",", map { encode_json(\$_) } @$hr) . "]";
return($ret);
}
=pod
=back
=cut
1;
__END__
=head1 SEE ALSO
The other modules in C<Master/tlpkg/TeXLive/> (L<TeXLive::TLConfig> and
the rest), and the scripts in C<Master/tlpg/bin/> (especially
C<tl-update-tlpdb>), the documentation in C<Master/tlpkg/doc/>, etc.
=head1 AUTHORS AND COPYRIGHT
This script and its documentation were written for the TeX Live
distribution (L<https://tug.org/texlive>) and both are licensed under the
GNU General Public License Version 2 or later.
=cut
### Local Variables:
### perl-indent-level: 2
### tab-width: 2
### indent-tabs-mode: nil
### End:
# vim:set tabstop=2 shiftwidth=2 expandtab: #
|