Training courses

Kernel and Embedded Linux

Bootlin training courses

Embedded Linux, kernel,
Yocto Project, Buildroot, real-time,
graphics, boot time, debugging...

Bootlin logo

Elixir Cross Referencer

   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
/*
 * Copyright (c) 1998-2006 Proofpoint, Inc. and its suppliers.
 *	All rights reserved.
 * Copyright (c) 1983, 1995-1997 Eric P. Allman.  All rights reserved.
 * Copyright (c) 1988, 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * By using this file, you agree to the terms and conditions set
 * forth in the LICENSE file which can be found at the top level of
 * the sendmail distribution.
 *
 */

#include <sendmail.h>

SM_RCSID("@(#)$Id: parseaddr.c,v 8.407 2013-11-22 20:51:56 ca Exp $")

#include <sm/sendmail.h>
#include "map.h"

static void	allocaddr __P((ADDRESS *, int, char *, ENVELOPE *));
static int	callsubr __P((char**, int, ENVELOPE *));
static char	*map_lookup __P((STAB *, char *, char **, int *, ENVELOPE *));
static ADDRESS	*buildaddr __P((char **, ADDRESS *, int, ENVELOPE *));
static bool	hasctrlchar __P((register char *, bool, bool));

/* replacement for illegal characters in addresses */
#define BAD_CHAR_REPLACEMENT	'?'

/*
**  PARSEADDR -- Parse an address
**
**	Parses an address and breaks it up into three parts: a
**	net to transmit the message on, the host to transmit it
**	to, and a user on that host.  These are loaded into an
**	ADDRESS header with the values squirreled away if necessary.
**	The "user" part may not be a real user; the process may
**	just reoccur on that machine.  For example, on a machine
**	with an arpanet connection, the address
**		csvax.bill@berkeley
**	will break up to a "user" of 'csvax.bill' and a host
**	of 'berkeley' -- to be transmitted over the arpanet.
**
**	Parameters:
**		addr -- the address to parse.
**		a -- a pointer to the address descriptor buffer.
**			If NULL, an address will be created.
**		flags -- describe detail for parsing.  See RF_ definitions
**			in sendmail.h.
**		delim -- the character to terminate the address, passed
**			to prescan.
**		delimptr -- if non-NULL, set to the location of the
**			delim character that was found.
**		e -- the envelope that will contain this address.
**		isrcpt -- true if the address denotes a recipient; false
**			indicates a sender.
**
**	Returns:
**		A pointer to the address descriptor header (`a' if
**			`a' is non-NULL).
**		NULL on error.
**
**	Side Effects:
**		e->e_to = addr
*/

/* following delimiters are inherent to the internal algorithms */
#define DELIMCHARS	"()<>,;\r\n"	/* default word delimiters */

ADDRESS *
parseaddr(addr, a, flags, delim, delimptr, e, isrcpt)
	char *addr;
	register ADDRESS *a;
	int flags;
	int delim;
	char **delimptr;
	register ENVELOPE *e;
	bool isrcpt;
{
	char **pvp;
	auto char *delimptrbuf;
	bool qup;
	char pvpbuf[PSBUFSIZE];

	/*
	**  Initialize and prescan address.
	*/

	e->e_to = addr;
	if (tTd(20, 1))
		sm_dprintf("\n--parseaddr(%s)\n", addr);

	if (delimptr == NULL)
		delimptr = &delimptrbuf;

	pvp = prescan(addr, delim, pvpbuf, sizeof(pvpbuf), delimptr,
			ExtTokenTab, false);
	if (pvp == NULL)
	{
		if (tTd(20, 1))
			sm_dprintf("parseaddr-->NULL\n");
		return NULL;
	}

	if (invalidaddr(addr, delim == '\0' ? NULL : *delimptr, isrcpt))
	{
		if (tTd(20, 1))
			sm_dprintf("parseaddr-->bad address\n");
		return NULL;
	}

	/*
	**  Save addr if we are going to have to.
	**
	**	We have to do this early because there is a chance that
	**	the map lookups in the rewriting rules could clobber
	**	static memory somewhere.
	*/

	if (bitset(RF_COPYPADDR, flags) && addr != NULL)
	{
		char savec = **delimptr;

		if (savec != '\0')
			**delimptr = '\0';
		e->e_to = addr = sm_rpool_strdup_x(e->e_rpool, addr);
		if (savec != '\0')
			**delimptr = savec;
	}

	/*
	**  Apply rewriting rules.
	**	Ruleset 0 does basic parsing.  It must resolve.
	*/

	qup = false;
	if (REWRITE(pvp, 3, e) == EX_TEMPFAIL)
		qup = true;
	if (REWRITE(pvp, 0, e) == EX_TEMPFAIL)
		qup = true;

	/*
	**  Build canonical address from pvp.
	*/

	a = buildaddr(pvp, a, flags, e);

	if (hasctrlchar(a->q_user, isrcpt, true))
	{
		if (tTd(20, 1))
			sm_dprintf("parseaddr-->bad q_user\n");

		/*
		**  Just mark the address as bad so DSNs work.
		**  hasctrlchar() has to make sure that the address
		**  has been sanitized, e.g., shortened.
		*/

		a->q_state = QS_BADADDR;
	}

	/*
	**  Make local copies of the host & user and then
	**  transport them out.
	*/

	allocaddr(a, flags, addr, e);
	if (QS_IS_BADADDR(a->q_state))
	{
		/* weed out bad characters in the printable address too */
		(void) hasctrlchar(a->q_paddr, isrcpt, false);
		return a;
	}

	/*
	**  Select a queue directory for recipient addresses.
	**	This is done here and in split_across_queue_groups(),
	**	but the latter applies to addresses after aliasing,
	**	and only if splitting is done.
	*/

	if ((a->q_qgrp == NOAQGRP || a->q_qgrp == ENVQGRP) &&
	    !bitset(RF_SENDERADDR|RF_HEADERADDR|RF_RM_ADDR, flags) &&
	    OpMode != MD_INITALIAS)
	{
		int r;

		/* call ruleset which should return a queue group name */
		r = rscap(RS_QUEUEGROUP, a->q_user, NULL, e, &pvp, pvpbuf,
			  sizeof(pvpbuf));
		if (r == EX_OK &&
		    pvp != NULL && pvp[0] != NULL &&
		    (pvp[0][0] & 0377) == CANONNET &&
		    pvp[1] != NULL && pvp[1][0] != '\0')
		{
			r = name2qid(pvp[1]);
			if (r == NOQGRP && LogLevel > 10)
				sm_syslog(LOG_INFO, NOQID,
					"can't find queue group name %s, selection ignored",
					pvp[1]);
			if (tTd(20, 4) && r != NOQGRP)
				sm_syslog(LOG_INFO, NOQID,
					"queue group name %s -> %d",
					pvp[1], r);
			a->q_qgrp = r == NOQGRP ? ENVQGRP : r;
		}
	}

	/*
	**  If there was a parsing failure, mark it for queueing.
	*/

	if (qup && OpMode != MD_INITALIAS)
	{
		char *msg = "Transient parse error -- message queued for future delivery";

		if (e->e_sendmode == SM_DEFER)
			msg = "Deferring message until queue run";
		if (tTd(20, 1))
			sm_dprintf("parseaddr: queueing message\n");
		message(msg);
		if (e->e_message == NULL && e->e_sendmode != SM_DEFER)
			e->e_message = sm_rpool_strdup_x(e->e_rpool, msg);
		a->q_state = QS_QUEUEUP;
		a->q_status = "4.4.3";
	}

	/*
	**  Compute return value.
	*/

	if (tTd(20, 1))
	{
		sm_dprintf("parseaddr-->");
		printaddr(sm_debug_file(), a, false);
	}

	return a;
}
/*
**  INVALIDADDR -- check for address containing characters used for macros
**
**	Parameters:
**		addr -- the address to check.
**		  note: this is the complete address (including display part)
**		delimptr -- if non-NULL: end of address to check, i.e.,
**			a pointer in the address string.
**		isrcpt -- true iff the address is for a recipient.
**
**	Returns:
**		true -- if the address has characters that are reservered
**			for macros or is too long.
**		false -- otherwise.
*/

bool
invalidaddr(addr, delimptr, isrcpt)
	register char *addr;
	char *delimptr;
	bool isrcpt;
{
	bool result = false;
	char savedelim = '\0';
	char *b = addr;
	int len = 0;

	if (delimptr != NULL)
	{
		/* delimptr points to the end of the address to test */
		savedelim = *delimptr;
		if (savedelim != '\0')	/* if that isn't '\0' already: */
			*delimptr = '\0';	/* set it */
	}
	for (; *addr != '\0'; addr++)
	{
		if (!EightBitAddrOK && (*addr & 0340) == 0200)
		{
			setstat(EX_USAGE);
			result = true;
			*addr = BAD_CHAR_REPLACEMENT;
		}
		if (++len > MAXNAME - 1)
		{
			char saved = *addr;

			*addr = '\0';
			usrerr("553 5.1.0 Address \"%s\" too long (%d bytes max)",
			       b, MAXNAME - 1);
			*addr = saved;
			result = true;
			goto delim;
		}
	}
	if (result)
	{
		if (isrcpt)
			usrerr("501 5.1.3 8-bit character in mailbox address \"%s\"",
			       b);
		else
			usrerr("501 5.1.7 8-bit character in mailbox address \"%s\"",
			       b);
	}
delim:
	if (delimptr != NULL && savedelim != '\0')
		*delimptr = savedelim;	/* restore old character at delimptr */
	return result;
}
/*
**  HASCTRLCHAR -- check for address containing meta-characters
**
**  Checks that the address contains no meta-characters, and contains
**  no "non-printable" characters unless they are quoted or escaped.
**  Quoted or escaped characters are literals.
**
**	Parameters:
**		addr -- the address to check.
**		isrcpt -- true if the address is for a recipient; false
**			indicates a from.
**		complain -- true if an error should issued if the address
**			is invalid and should be "repaired".
**
**	Returns:
**		true -- if the address has any "weird" characters or
**			non-printable characters or if a quote is unbalanced.
**		false -- otherwise.
*/

static bool
hasctrlchar(addr, isrcpt, complain)
	register char *addr;
	bool isrcpt, complain;
{
	bool quoted = false;
	int len = 0;
	char *result = NULL;
	char *b = addr;

	if (addr == NULL)
		return false;
	for (; *addr != '\0'; addr++)
	{
		if (++len > MAXNAME - 1)
		{
			if (complain)
			{
				(void) shorten_rfc822_string(b, MAXNAME - 1);
				usrerr("553 5.1.0 Address \"%s\" too long (%d bytes max)",
				       b, MAXNAME - 1);
				return true;
			}
			result = "too long";
		}
		if (!EightBitAddrOK && !quoted && (*addr < 32 || *addr == 127))
		{
			result = "non-printable character";
			*addr = BAD_CHAR_REPLACEMENT;
			continue;
		}
		if (*addr == '"')
			quoted = !quoted;
		else if (*addr == '\\')
		{
			/* XXX Generic problem: no '\0' in strings. */
			if (*++addr == '\0')
			{
				result = "trailing \\ character";
				*--addr = BAD_CHAR_REPLACEMENT;
				break;
			}
		}
		if (!EightBitAddrOK && (*addr & 0340) == 0200)
		{
			setstat(EX_USAGE);
			result = "8-bit character";
			*addr = BAD_CHAR_REPLACEMENT;
			continue;
		}
	}
	if (quoted)
		result = "unbalanced quote"; /* unbalanced quote */
	if (result != NULL && complain)
	{
		if (isrcpt)
			usrerr("501 5.1.3 Syntax error in mailbox address \"%s\" (%s)",
			       b, result);
		else
			usrerr("501 5.1.7 Syntax error in mailbox address \"%s\" (%s)",
			       b, result);
	}
	return result != NULL;
}
/*
**  ALLOCADDR -- do local allocations of address on demand.
**
**	Also lowercases the host name if requested.
**
**	Parameters:
**		a -- the address to reallocate.
**		flags -- the copy flag (see RF_ definitions in sendmail.h
**			for a description).
**		paddr -- the printname of the address.
**		e -- envelope
**
**	Returns:
**		none.
**
**	Side Effects:
**		Copies portions of a into local buffers as requested.
*/

static void
allocaddr(a, flags, paddr, e)
	register ADDRESS *a;
	int flags;
	char *paddr;
	ENVELOPE *e;
{
	if (tTd(24, 4))
		sm_dprintf("allocaddr(flags=%x, paddr=%s)\n", flags, paddr);

	a->q_paddr = paddr;

	if (a->q_user == NULL)
		a->q_user = "";
	if (a->q_host == NULL)
		a->q_host = "";

	if (bitset(RF_COPYPARSE, flags))
	{
		a->q_host = sm_rpool_strdup_x(e->e_rpool, a->q_host);
		if (a->q_user != a->q_paddr)
			a->q_user = sm_rpool_strdup_x(e->e_rpool, a->q_user);
	}

	if (a->q_paddr == NULL)
		a->q_paddr = sm_rpool_strdup_x(e->e_rpool, a->q_user);
	a->q_qgrp = NOAQGRP;
}

/*
**  PRESCAN -- Prescan name and make it canonical
**
**	Scans a name and turns it into a set of tokens.  This process
**	deletes blanks and comments (in parentheses) (if the token type
**	for left paren is SPC).
**
**	This routine knows about quoted strings and angle brackets.
**
**	There are certain subtleties to this routine.  The one that
**	comes to mind now is that backslashes on the ends of names
**	are silently stripped off; this is intentional.  The problem
**	is that some versions of sndmsg (like at LBL) set the kill
**	character to something other than @ when reading addresses;
**	so people type "csvax.eric\@berkeley" -- which screws up the
**	berknet mailer.
**
**	Parameters:
**		addr -- the name to chomp.
**		delim -- the delimiter for the address, normally
**			'\0' or ','; \0 is accepted in any case.
**			If '\t' then we are reading the .cf file.
**		pvpbuf -- place to put the saved text -- note that
**			the pointers are static.
**		pvpbsize -- size of pvpbuf.
**		delimptr -- if non-NULL, set to the location of the
**			terminating delimiter.
**		toktab -- if set, a token table to use for parsing.
**			If NULL, use the default table.
**		ignore -- if true, ignore unbalanced addresses
**
**	Returns:
**		A pointer to a vector of tokens.
**		NULL on error.
*/

/* states and character types */
#define OPR		0	/* operator */
#define ATM		1	/* atom */
#define QST		2	/* in quoted string */
#define SPC		3	/* chewing up spaces */
#define ONE		4	/* pick up one character */
#define ILL		5	/* illegal character */

#define NSTATES	6	/* number of states */
#define TYPE		017	/* mask to select state type */

/* meta bits for table */
#define M		020	/* meta character; don't pass through */
#define B		040	/* cause a break */
#define MB		M|B	/* meta-break */

static short StateTab[NSTATES][NSTATES] =
{
   /*	oldst	chtype>	OPR	ATM	QST	SPC	ONE	ILL	*/
	/*OPR*/	{	OPR|B,	ATM|B,	QST|B,	SPC|MB,	ONE|B,	ILL|MB	},
	/*ATM*/	{	OPR|B,	ATM,	QST|B,	SPC|MB,	ONE|B,	ILL|MB	},
	/*QST*/	{	QST,	QST,	OPR,	QST,	QST,	QST	},
	/*SPC*/	{	OPR,	ATM,	QST,	SPC|M,	ONE,	ILL|MB	},
	/*ONE*/	{	OPR,	OPR,	OPR,	OPR,	OPR,	ILL|MB	},
	/*ILL*/	{	OPR|B,	ATM|B,	QST|B,	SPC|MB,	ONE|B,	ILL|M	}
};

/* these all get modified with the OperatorChars */

/* token type table for external strings */
unsigned char	ExtTokenTab[256] =
{
    /*	nul soh stx etx eot enq ack bel  bs  ht  nl  vt  np  cr  so  si   */
	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,SPC,SPC,SPC,SPC,SPC,ATM,ATM,
    /*	dle dc1 dc2 dc3 dc4 nak syn etb  can em  sub esc fs  gs  rs  us   */
	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
    /*  sp  !   "   #   $   %   &   '    (   )   *   +   ,   -   .   /    */
	SPC,ATM,QST,ATM,ATM,ATM,ATM,ATM, SPC,SPC,ATM,ATM,ATM,ATM,ATM,ATM,
    /*	0   1   2   3   4   5   6   7    8   9   :   ;   <   =   >   ?    */
	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
    /*	@   A   B   C   D   E   F   G    H   I   J   K   L   M   N   O    */
	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
    /*  P   Q   R   S   T   U   V   W    X   Y   Z   [   \   ]   ^   _    */
	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
    /*	`   a   b   c   d   e   f   g    h   i   j   k   l   m   n   o    */
	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
    /*  p   q   r   s   t   u   v   w    x   y   z   {   |   }   ~   del  */
	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,

    /*	nul soh stx etx eot enq ack bel  bs  ht  nl  vt  np  cr  so  si   */
	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
    /*	dle dc1 dc2 dc3 dc4 nak syn etb  can em  sub esc fs  gs  rs  us   */
	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
    /*  sp  !   "   #   $   %   &   '    (   )   *   +   ,   -   .   /    */
	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
    /*	0   1   2   3   4   5   6   7    8   9   :   ;   <   =   >   ?    */
	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
    /*	@   A   B   C   D   E   F   G    H   I   J   K   L   M   N   O    */
	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
    /*  P   Q   R   S   T   U   V   W    X   Y   Z   [   \   ]   ^   _    */
	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
    /*	`   a   b   c   d   e   f   g    h   i   j   k   l   m   n   o    */
	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
    /*  p   q   r   s   t   u   v   w    x   y   z   {   |   }   ~   del  */
	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM
};

/* token type table for internal strings */
unsigned char	IntTokenTab[256] =
{
    /*	nul soh stx etx eot enq ack bel  bs  ht  nl  vt  np  cr  so  si   */
	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,SPC,SPC,SPC,SPC,SPC,ATM,ATM,
    /*	dle dc1 dc2 dc3 dc4 nak syn etb  can em  sub esc fs  gs  rs  us   */
	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
    /*  sp  !   "   #   $   %   &   '    (   )   *   +   ,   -   .   /    */
	SPC,ATM,QST,ATM,ATM,ATM,ATM,ATM, SPC,SPC,ATM,ATM,ATM,ATM,ATM,ATM,
    /*	0   1   2   3   4   5   6   7    8   9   :   ;   <   =   >   ?    */
	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
    /*	@   A   B   C   D   E   F   G    H   I   J   K   L   M   N   O    */
	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
    /*  P   Q   R   S   T   U   V   W    X   Y   Z   [   \   ]   ^   _    */
	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
    /*	`   a   b   c   d   e   f   g    h   i   j   k   l   m   n   o    */
	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
    /*  p   q   r   s   t   u   v   w    x   y   z   {   |   }   ~   del  */
	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,

    /*	nul soh stx etx eot enq ack bel  bs  ht  nl  vt  np  cr  so  si   */
	OPR,OPR,ONE,OPR,OPR,OPR,OPR,OPR, OPR,OPR,OPR,OPR,OPR,OPR,OPR,OPR,
    /*	dle dc1 dc2 dc3 dc4 nak syn etb  can em  sub esc fs  gs  rs  us   */
	OPR,OPR,OPR,ONE,ONE,ONE,OPR,OPR, OPR,OPR,OPR,OPR,OPR,OPR,OPR,OPR,
    /*  sp  !   "   #   $   %   &   '    (   )   *   +   ,   -   .   /    */
	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
    /*	0   1   2   3   4   5   6   7    8   9   :   ;   <   =   >   ?    */
	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
    /*	@   A   B   C   D   E   F   G    H   I   J   K   L   M   N   O    */
	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
    /*  P   Q   R   S   T   U   V   W    X   Y   Z   [   \   ]   ^   _    */
	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
    /*	`   a   b   c   d   e   f   g    h   i   j   k   l   m   n   o    */
	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
    /*  p   q   r   s   t   u   v   w    x   y   z   {   |   }   ~   del  */
	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ONE
};

/* token type table for MIME parsing */
unsigned char	MimeTokenTab[256] =
{
    /*	nul soh stx etx eot enq ack bel  bs  ht  nl  vt  np  cr  so  si   */
	ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL, ILL,SPC,SPC,SPC,SPC,SPC,ILL,ILL,
    /*	dle dc1 dc2 dc3 dc4 nak syn etb  can em  sub esc fs  gs  rs  us   */
	ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL, ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL,
    /*  sp  !   "   #   $   %   &   '    (   )   *   +   ,   -   .   /    */
	SPC,ATM,QST,ATM,ATM,ATM,ATM,ATM, SPC,SPC,ATM,ATM,OPR,ATM,ATM,OPR,
    /*	0   1   2   3   4   5   6   7    8   9   :   ;   <   =   >   ?    */
	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,OPR,OPR,OPR,OPR,OPR,OPR,
    /*	@   A   B   C   D   E   F   G    H   I   J   K   L   M   N   O    */
	OPR,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
    /*  P   Q   R   S   T   U   V   W    X   Y   Z   [   \   ]   ^   _    */
	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,OPR,OPR,OPR,ATM,ATM,
    /*	`   a   b   c   d   e   f   g    h   i   j   k   l   m   n   o    */
	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
    /*  p   q   r   s   t   u   v   w    x   y   z   {   |   }   ~   del  */
	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,

    /*	nul soh stx etx eot enq ack bel  bs  ht  nl  vt  np  cr  so  si   */
	ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL, ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL,
    /*	dle dc1 dc2 dc3 dc4 nak syn etb  can em  sub esc fs  gs  rs  us   */
	ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL, ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL,
    /*  sp  !   "   #   $   %   &   '    (   )   *   +   ,   -   .   /    */
	ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL, ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL,
    /*	0   1   2   3   4   5   6   7    8   9   :   ;   <   =   >   ?    */
	ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL, ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL,
    /*	@   A   B   C   D   E   F   G    H   I   J   K   L   M   N   O    */
	ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL, ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL,
    /*  P   Q   R   S   T   U   V   W    X   Y   Z   [   \   ]   ^   _    */
	ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL, ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL,
    /*	`   a   b   c   d   e   f   g    h   i   j   k   l   m   n   o    */
	ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL, ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL,
    /*  p   q   r   s   t   u   v   w    x   y   z   {   |   }   ~   del  */
	ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL, ILL,ILL,ILL,ILL,ILL,ILL,ILL,ONE
};

/* token type table: don't strip comments */
unsigned char	TokTypeNoC[256] =
{
    /*	nul soh stx etx eot enq ack bel  bs  ht  nl  vt  np  cr  so  si   */
	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,SPC,SPC,SPC,SPC,SPC,ATM,ATM,
    /*	dle dc1 dc2 dc3 dc4 nak syn etb  can em  sub esc fs  gs  rs  us   */
	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
    /*  sp  !   "   #   $   %   &   '    (   )   *   +   ,   -   .   /    */
	SPC,ATM,QST,ATM,ATM,ATM,ATM,ATM, OPR,OPR,ATM,ATM,ATM,ATM,ATM,ATM,
    /*	0   1   2   3   4   5   6   7    8   9   :   ;   <   =   >   ?    */
	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
    /*	@   A   B   C   D   E   F   G    H   I   J   K   L   M   N   O    */
	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
    /*  P   Q   R   S   T   U   V   W    X   Y   Z   [   \   ]   ^   _    */
	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
    /*	`   a   b   c   d   e   f   g    h   i   j   k   l   m   n   o    */
	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
    /*  p   q   r   s   t   u   v   w    x   y   z   {   |   }   ~   del  */
	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,

    /*	nul soh stx etx eot enq ack bel  bs  ht  nl  vt  np  cr  so  si   */
	OPR,OPR,ONE,OPR,OPR,OPR,OPR,OPR, OPR,OPR,OPR,OPR,OPR,OPR,OPR,OPR,
    /*	dle dc1 dc2 dc3 dc4 nak syn etb  can em  sub esc fs  gs  rs  us   */
	OPR,OPR,OPR,ONE,ONE,ONE,OPR,OPR, OPR,OPR,OPR,OPR,OPR,OPR,OPR,OPR,
    /*  sp  !   "   #   $   %   &   '    (   )   *   +   ,   -   .   /    */
	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
    /*	0   1   2   3   4   5   6   7    8   9   :   ;   <   =   >   ?    */
	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
    /*	@   A   B   C   D   E   F   G    H   I   J   K   L   M   N   O    */
	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
    /*  P   Q   R   S   T   U   V   W    X   Y   Z   [   \   ]   ^   _    */
	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
    /*	`   a   b   c   d   e   f   g    h   i   j   k   l   m   n   o    */
	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM,
    /*  p   q   r   s   t   u   v   w    x   y   z   {   |   }   ~   del  */
	ATM,ATM,ATM,ATM,ATM,ATM,ATM,ATM, ATM,ATM,ATM,ATM,ATM,ATM,ATM,ONE
};


#define NOCHAR		(-1)	/* signal nothing in lookahead token */

char **
prescan(addr, delim, pvpbuf, pvpbsize, delimptr, toktab, ignore)
	char *addr;
	int delim;
	char pvpbuf[];
	int pvpbsize;
	char **delimptr;
	unsigned char *toktab;
	bool ignore;
{
	register char *p;
	register char *q;
	register int c;
	char **avp;
	bool bslashmode;
	bool route_syntax;
	int cmntcnt;
	int anglecnt;
	char *tok;
	int state;
	int newstate;
	char *saveto = CurEnv->e_to;
	static char *av[MAXATOM + 1];
	static bool firsttime = true;

	if (firsttime)
	{
		/* initialize the token type table */
		char obuf[50];

		firsttime = false;
		if (OperatorChars == NULL)
		{
			if (ConfigLevel < 7)
				OperatorChars = macvalue('o', CurEnv);
			if (OperatorChars == NULL)
				OperatorChars = ".:@[]";
		}
		expand(OperatorChars, obuf, sizeof(obuf) - sizeof(DELIMCHARS),
		       CurEnv);
		(void) sm_strlcat(obuf, DELIMCHARS, sizeof(obuf));
		for (p = obuf; *p != '\0'; p++)
		{
			if (IntTokenTab[*p & 0xff] == ATM)
				IntTokenTab[*p & 0xff] = OPR;
			if (ExtTokenTab[*p & 0xff] == ATM)
				ExtTokenTab[*p & 0xff] = OPR;
			if (TokTypeNoC[*p & 0xff] == ATM)
				TokTypeNoC[*p & 0xff] = OPR;
		}
	}
	if (toktab == NULL)
		toktab = ExtTokenTab;

	/* make sure error messages don't have garbage on them */
	errno = 0;

	q = pvpbuf;
	bslashmode = false;
	route_syntax = false;
	cmntcnt = 0;
	anglecnt = 0;
	avp = av;
	state = ATM;
	c = NOCHAR;
	p = addr;
	CurEnv->e_to = p;
	if (tTd(22, 11))
	{
		sm_dprintf("prescan: ");
		xputs(sm_debug_file(), p);
		sm_dprintf("\n");
	}

	do
	{
		/* read a token */
		tok = q;
		for (;;)
		{
			/* store away any old lookahead character */
			if (c != NOCHAR && !bslashmode)
			{
				/* see if there is room */
				if (q >= &pvpbuf[pvpbsize - 5])
				{
	addrtoolong:
					usrerr("553 5.1.1 Address too long");
					if (strlen(addr) > MAXNAME)
						addr[MAXNAME] = '\0';
	returnnull:
					if (delimptr != NULL)
					{
						if (p > addr)
							--p;
						*delimptr = p;
					}
					CurEnv->e_to = saveto;
					return NULL;
				}

				/* squirrel it away */
#if !ALLOW_255
				if ((char) c == (char) -1 && !tTd(82, 101) &&
				    !EightBitAddrOK)
					c &= 0x7f;
#endif /* !ALLOW_255 */
				*q++ = c;
			}

			/* read a new input character */
			c = (*p++) & 0x00ff;
			if (c == '\0')
			{
				/* diagnose and patch up bad syntax */
				if (ignore)
					break;
				else if (state == QST)
				{
					usrerr("553 Unbalanced '\"'");
					c = '"';
				}
				else if (cmntcnt > 0)
				{
					usrerr("553 Unbalanced '('");
					c = ')';
				}
				else if (anglecnt > 0)
				{
					c = '>';
					usrerr("553 Unbalanced '<'");
				}
				else
					break;

				p--;
			}
			else if (c == delim && cmntcnt <= 0 && state != QST)
			{
				if (anglecnt <= 0)
					break;

				/* special case for better error management */
				if (delim == ',' && !route_syntax && !ignore)
				{
					usrerr("553 Unbalanced '<'");
					c = '>';
					p--;
				}
			}

			if (tTd(22, 101))
				sm_dprintf("c=%c, s=%d; ", c, state);

			/* chew up special characters */
			*q = '\0';
			if (bslashmode)
			{
				bslashmode = false;

				/* kludge \! for naive users */
				if (cmntcnt > 0)
				{
					c = NOCHAR;
					continue;
				}
				else if (c != '!' || state == QST)
				{
					/* see if there is room */
					if (q >= &pvpbuf[pvpbsize - 5])
						goto addrtoolong;
					*q++ = '\\';
					continue;
				}
			}

			if (c == '\\')
			{
				bslashmode = true;
			}
			else if (state == QST)
			{
				/* EMPTY */
				/* do nothing, just avoid next clauses */
			}
			else if (c == '(' && toktab['('] == SPC)
			{
				cmntcnt++;
				c = NOCHAR;
			}
			else if (c == ')' && toktab['('] == SPC)
			{
				if (cmntcnt <= 0)
				{
					if (!ignore)
					{
						usrerr("553 Unbalanced ')'");
						c = NOCHAR;
					}
				}
				else
					cmntcnt--;
			}
			else if (cmntcnt > 0)
			{
				c = NOCHAR;
			}
			else if (c == '<')
			{
				char *ptr = p;

				anglecnt++;
				while (isascii(*ptr) && isspace(*ptr))
					ptr++;
				if (*ptr == '@')
					route_syntax = true;
			}
			else if (c == '>')
			{
				if (anglecnt <= 0)
				{
					if (!ignore)
					{
						usrerr("553 Unbalanced '>'");
						c = NOCHAR;
					}
				}
				else
					anglecnt--;
				route_syntax = false;
			}
			else if (delim == ' ' && isascii(c) && isspace(c))
				c = ' ';

			if (c == NOCHAR)
				continue;

			/* see if this is end of input */
			if (c == delim && anglecnt <= 0 && state != QST)
				break;

			newstate = StateTab[state][toktab[c & 0xff]];
			if (tTd(22, 101))
				sm_dprintf("ns=%02o\n", newstate);
			state = newstate & TYPE;
			if (state == ILL)
			{
				if (isascii(c) && isprint(c))
					usrerr("553 Illegal character %c", c);
				else
					usrerr("553 Illegal character 0x%02x",
					       c & 0x0ff);
			}
			if (bitset(M, newstate))
				c = NOCHAR;
			if (bitset(B, newstate))
				break;
		}

		/* new token */
		if (tok != q)
		{
			/* see if there is room */
			if (q >= &pvpbuf[pvpbsize - 5])
				goto addrtoolong;
			*q++ = '\0';
			if (tTd(22, 36))
			{
				sm_dprintf("tok=");
				xputs(sm_debug_file(), tok);
				sm_dprintf("\n");
			}
			if (avp >= &av[MAXATOM])
			{
				usrerr("553 5.1.0 prescan: too many tokens");
				goto returnnull;
			}
			if (q - tok > MAXNAME)
			{
				usrerr("553 5.1.0 prescan: token too long");
				goto returnnull;
			}
			*avp++ = tok;
		}
	} while (c != '\0' && (c != delim || anglecnt > 0));
	*avp = NULL;
	if (delimptr != NULL)
	{
		if (p > addr)
			p--;
		*delimptr = p;
	}
	if (tTd(22, 12))
	{
		sm_dprintf("prescan==>");
		printav(sm_debug_file(), av);
	}
	CurEnv->e_to = saveto;
	if (av[0] == NULL)
	{
		if (tTd(22, 1))
			sm_dprintf("prescan: null leading token\n");
		return NULL;
	}
	return av;
}
/*
**  REWRITE -- apply rewrite rules to token vector.
**
**	This routine is an ordered production system.  Each rewrite
**	rule has a LHS (called the pattern) and a RHS (called the
**	rewrite); 'rwr' points the the current rewrite rule.
**
**	For each rewrite rule, 'avp' points the address vector we
**	are trying to match against, and 'pvp' points to the pattern.
**	If pvp points to a special match value (MATCHZANY, MATCHANY,
**	MATCHONE, MATCHCLASS, MATCHNCLASS) then the address in avp
**	matched is saved away in the match vector (pointed to by 'mvp').
**
**	When a match between avp & pvp does not match, we try to
**	back out.  If we back up over MATCHONE, MATCHCLASS, or MATCHNCLASS
**	we must also back out the match in mvp.  If we reach a
**	MATCHANY or MATCHZANY we just extend the match and start
**	over again.
**
**	When we finally match, we rewrite the address vector
**	and try over again.
**
**	Parameters:
**		pvp -- pointer to token vector.
**		ruleset -- the ruleset to use for rewriting.
**		reclevel -- recursion level (to catch loops).
**		e -- the current envelope.
**		maxatom -- maximum length of buffer (usually MAXATOM)
**
**	Returns:
**		A status code.  If EX_TEMPFAIL, higher level code should
**			attempt recovery.
**
**	Side Effects:
**		pvp is modified.
*/

struct match
{
	char	**match_first;		/* first token matched */
	char	**match_last;		/* last token matched */
	char	**match_pattern;	/* pointer to pattern */
};

int
rewrite(pvp, ruleset, reclevel, e, maxatom)
	char **pvp;
	int ruleset;
	int reclevel;
	register ENVELOPE *e;
	int maxatom;
{
	register char *ap;		/* address pointer */
	register char *rp;		/* rewrite pointer */
	register char *rulename;	/* ruleset name */
	register char *prefix;
	register char **avp;		/* address vector pointer */
	register char **rvp;		/* rewrite vector pointer */
	register struct match *mlp;	/* cur ptr into mlist */
	register struct rewrite *rwr;	/* pointer to current rewrite rule */
	int ruleno;			/* current rule number */
	int rstat = EX_OK;		/* return status */
	int loopcount;
	struct match mlist[MAXMATCH];	/* stores match on LHS */
	char *npvp[MAXATOM + 1];	/* temporary space for rebuild */
	char buf[MAXLINE];
	char name[6];

	/*
	**  mlp will not exceed mlist[] because readcf enforces
	**	the upper limit of entries when reading rulesets.
	*/

	if (ruleset < 0 || ruleset >= MAXRWSETS)
	{
		syserr("554 5.3.5 rewrite: illegal ruleset number %d", ruleset);
		return EX_CONFIG;
	}
	rulename = RuleSetNames[ruleset];
	if (rulename == NULL)
	{
		(void) sm_snprintf(name, sizeof(name), "%d", ruleset);
		rulename = name;
	}
	if (OpMode == MD_TEST)
		prefix = "";
	else
		prefix = "rewrite: ruleset ";
	if (OpMode == MD_TEST)
	{
		(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
				     "%s%-16.16s   input:", prefix, rulename);
		printav(smioout, pvp);
	}
	else if (tTd(21, 1))
	{
		sm_dprintf("%s%-16.16s   input:", prefix, rulename);
		printav(sm_debug_file(), pvp);
	}
	if (reclevel++ > MaxRuleRecursion)
	{
		syserr("rewrite: excessive recursion (max %d), ruleset %s",
			MaxRuleRecursion, rulename);
		return EX_CONFIG;
	}
	if (pvp == NULL)
		return EX_USAGE;
	if (maxatom <= 0)
		return EX_USAGE;

	/*
	**  Run through the list of rewrite rules, applying
	**	any that match.
	*/

	ruleno = 1;
	loopcount = 0;
	for (rwr = RewriteRules[ruleset]; rwr != NULL; )
	{
		int status;

		/* if already canonical, quit now */
		if (pvp[0] != NULL && (pvp[0][0] & 0377) == CANONNET)
			break;

		if (tTd(21, 12))
		{
			if (tTd(21, 15))
				sm_dprintf("-----trying rule (line %d):",
				       rwr->r_line);
			else
				sm_dprintf("-----trying rule:");
			printav(sm_debug_file(), rwr->r_lhs);
		}

		/* try to match on this rule */
		mlp = mlist;
		rvp = rwr->r_lhs;
		avp = pvp;
		if (++loopcount > 100)
		{
			syserr("554 5.3.5 Infinite loop in ruleset %s, rule %d",
				rulename, ruleno);
			if (tTd(21, 1))
			{
				sm_dprintf("workspace: ");
				printav(sm_debug_file(), pvp);
			}
			break;
		}

		while ((ap = *avp) != NULL || *rvp != NULL)
		{
			rp = *rvp;
			if (tTd(21, 35))
			{
				sm_dprintf("ADVANCE rp=");
				xputs(sm_debug_file(), rp);
				sm_dprintf(", ap=");
				xputs(sm_debug_file(), ap);
				sm_dprintf("\n");
			}
			if (rp == NULL)
			{
				/* end-of-pattern before end-of-address */
				goto backup;
			}
			if (ap == NULL &&
			    (rp[0] & 0377) != MATCHZANY &&
			    (rp[0] & 0377) != MATCHZERO)
			{
				/* end-of-input with patterns left */
				goto backup;
			}

			switch (rp[0] & 0377)
			{
			  case MATCHCLASS:
				/* match any phrase in a class */
				mlp->match_pattern = rvp;
				mlp->match_first = avp;
	extendclass:
				ap = *avp;
				if (ap == NULL)
					goto backup;
				mlp->match_last = avp++;
				cataddr(mlp->match_first, mlp->match_last,
					buf, sizeof(buf), '\0', true);
				if (!wordinclass(buf, rp[1]))
				{
					if (tTd(21, 36))
					{
						sm_dprintf("EXTEND  rp=");
						xputs(sm_debug_file(), rp);
						sm_dprintf(", ap=");
						xputs(sm_debug_file(), ap);
						sm_dprintf("\n");
					}
					goto extendclass;
				}
				if (tTd(21, 36))
					sm_dprintf("CLMATCH\n");
				mlp++;
				break;

			  case MATCHNCLASS:
				/* match any token not in a class */
				if (wordinclass(ap, rp[1]))
					goto backup;

				/* FALLTHROUGH */

			  case MATCHONE:
			  case MATCHANY:
				/* match exactly one token */
				mlp->match_pattern = rvp;
				mlp->match_first = avp;
				mlp->match_last = avp++;
				mlp++;
				break;

			  case MATCHZANY:
				/* match zero or more tokens */
				mlp->match_pattern = rvp;
				mlp->match_first = avp;
				mlp->match_last = avp - 1;
				mlp++;
				break;

			  case MATCHZERO:
				/* match zero tokens */
				break;

			  case MACRODEXPAND:
				/*
				**  Match against run-time macro.
				**  This algorithm is broken for the
				**  general case (no recursive macros,
				**  improper tokenization) but should
				**  work for the usual cases.
				*/

				ap = macvalue(rp[1], e);
				mlp->match_first = avp;
				if (tTd(21, 2))
					sm_dprintf("rewrite: LHS $&{%s} => \"%s\"\n",
						macname(rp[1]),
						ap == NULL ? "(NULL)" : ap);

				if (ap == NULL)
					break;
				while (*ap != '\0')
				{
					if (*avp == NULL ||
					    sm_strncasecmp(ap, *avp,
							   strlen(*avp)) != 0)
					{
						/* no match */
						avp = mlp->match_first;
						goto backup;
					}
					ap += strlen(*avp++);
				}

				/* match */
				break;

			  default:
				/* must have exact match */
				if (sm_strcasecmp(rp, ap))
					goto backup;
				avp++;
				break;
			}

			/* successful match on this token */
			rvp++;
			continue;

	  backup:
			/* match failed -- back up */
			while (--mlp >= mlist)
			{
				rvp = mlp->match_pattern;
				rp = *rvp;
				avp = mlp->match_last + 1;
				ap = *avp;

				if (tTd(21, 36))
				{
					sm_dprintf("BACKUP  rp=");
					xputs(sm_debug_file(), rp);
					sm_dprintf(", ap=");
					xputs(sm_debug_file(), ap);
					sm_dprintf("\n");
				}

				if (ap == NULL)
				{
					/* run off the end -- back up again */
					continue;
				}

				if ((rp[0] & 0377) == MATCHANY ||
				    (rp[0] & 0377) == MATCHZANY)
				{
					/* extend binding and continue */
					mlp->match_last = avp++;
					rvp++;
					mlp++;
					break;
				}
				if ((rp[0] & 0377) == MATCHCLASS)
				{
					/* extend binding and try again */
					mlp->match_last = avp;
					goto extendclass;
				}
			}

			if (mlp < mlist)
			{
				/* total failure to match */
				break;
			}
		}

		/*
		**  See if we successfully matched
		*/

		if (mlp < mlist || *rvp != NULL)
		{
			if (tTd(21, 10))
				sm_dprintf("----- rule fails\n");
			rwr = rwr->r_next;
			ruleno++;
			loopcount = 0;
			continue;
		}

		rvp = rwr->r_rhs;
		if (tTd(21, 12))
		{
			sm_dprintf("-----rule matches:");
			printav(sm_debug_file(), rvp);
		}

		rp = *rvp;
		if (rp != NULL)
		{
			if ((rp[0] & 0377) == CANONUSER)
			{
				rvp++;
				rwr = rwr->r_next;
				ruleno++;
				loopcount = 0;
			}
			else if ((rp[0] & 0377) == CANONHOST)
			{
				rvp++;
				rwr = NULL;
			}
		}

		/* substitute */
		for (avp = npvp; *rvp != NULL; rvp++)
		{
			register struct match *m;
			register char **pp;

			rp = *rvp;
			if ((rp[0] & 0377) == MATCHREPL)
			{
				/* substitute from LHS */
				m = &mlist[rp[1] - '1'];
				if (m < mlist || m >= mlp)
				{
					syserr("554 5.3.5 rewrite: ruleset %s: replacement $%c out of bounds",
						rulename, rp[1]);
					return EX_CONFIG;
				}
				if (tTd(21, 15))
				{
					sm_dprintf("$%c:", rp[1]);
					pp = m->match_first;
					while (pp <= m->match_last)
					{
						sm_dprintf(" %p=\"", *pp);
						sm_dflush();
						sm_dprintf("%s\"", *pp++);
					}
					sm_dprintf("\n");
				}
				pp = m->match_first;
				while (pp <= m->match_last)
				{
					if (avp >= &npvp[maxatom])
						goto toolong;
					*avp++ = *pp++;
				}
			}
			else
			{
				/* some sort of replacement */
				if (avp >= &npvp[maxatom])
				{
	toolong:
					syserr("554 5.3.0 rewrite: expansion too long");
					if (LogLevel > 9)
						sm_syslog(LOG_ERR, e->e_id,
							"rewrite: expansion too long, ruleset=%s, ruleno=%d",
							rulename, ruleno);
					return EX_DATAERR;
				}
				if ((rp[0] & 0377) != MACRODEXPAND)
				{
					/* vanilla replacement from RHS */
					*avp++ = rp;
				}
				else
				{
					/* $&{x} replacement */
					char *mval = macvalue(rp[1], e);
					char **xpvp;
					size_t trsize = 0;
					static size_t pvpb1_size = 0;
					static char **pvpb1 = NULL;
					char pvpbuf[PSBUFSIZE];

					if (tTd(21, 2))
						sm_dprintf("rewrite: RHS $&{%s} => \"%s\"\n",
							macname(rp[1]),
							mval == NULL ? "(NULL)" : mval);
					if (mval == NULL || *mval == '\0')
						continue;

					/* save the remainder of the input */
					for (xpvp = pvp; *xpvp != NULL; xpvp++)
						trsize += sizeof(*xpvp);
					if (trsize > pvpb1_size)
					{
						if (pvpb1 != NULL)
							sm_free(pvpb1);
						pvpb1 = (char **)
							sm_pmalloc_x(trsize);
						pvpb1_size = trsize;
					}

					memmove((char *) pvpb1,
						(char *) pvp,
						trsize);

					/* scan the new replacement */
					xpvp = prescan(mval, '\0', pvpbuf,
						       sizeof(pvpbuf), NULL,
						       NULL, false);
					if (xpvp == NULL)
					{
						/* prescan pre-printed error */
						return EX_DATAERR;
					}

					/* insert it into the output stream */
					while (*xpvp != NULL)
					{
						if (tTd(21, 19))
							sm_dprintf(" ... %s\n",
								*xpvp);
						*avp++ = sm_rpool_strdup_x(
							e->e_rpool, *xpvp);
						if (avp >= &npvp[maxatom])
							goto toolong;
						xpvp++;
					}
					if (tTd(21, 19))
						sm_dprintf(" ... DONE\n");

					/* restore the old trailing input */
					memmove((char *) pvp,
						(char *) pvpb1,
						trsize);
				}
			}
		}
		*avp++ = NULL;

		/*
		**  Check for any hostname/keyword lookups.
		*/

		for (rvp = npvp; *rvp != NULL; rvp++)
		{
			char **hbrvp;
			char **xpvp;
			size_t trsize;
			char *replac;
			int endtoken;
			bool external;
			STAB *map;
			char *mapname;
			char **key_rvp;
			char **arg_rvp;
			char **default_rvp;
			char cbuf[MAXKEY];
			char *pvpb1[MAXATOM + 1];
			char *argvect[MAX_MAP_ARGS];
			char pvpbuf[PSBUFSIZE];
			char *nullpvp[1];

			hbrvp = rvp;
			if ((rvp[0][0] & 0377) == HOSTBEGIN)
			{
				endtoken = HOSTEND;
				mapname = "host";
			}
			else if ((rvp[0][0] & 0377) == LOOKUPBEGIN)
			{
				endtoken = LOOKUPEND;
				mapname = *++rvp;
				if (mapname == NULL)
				{
					syserr("554 5.3.0 rewrite: missing mapname");
					/* NOTREACHED */
					SM_ASSERT(0);
				}
			}
			else
				continue;

			/*
			**  Got a hostname/keyword lookup.
			**
			**	This could be optimized fairly easily.
			*/

			map = stab(mapname, ST_MAP, ST_FIND);
			if (map == NULL)
				syserr("554 5.3.0 rewrite: map %s not found",
					mapname);

			/* extract the match part */
			key_rvp = ++rvp;
			if (key_rvp == NULL)
			{
				syserr("554 5.3.0 rewrite: missing key for map %s",
					mapname);
				/* NOTREACHED */
				SM_ASSERT(0);
			}
			default_rvp = NULL;
			arg_rvp = argvect;
			xpvp = NULL;
			replac = pvpbuf;
			while (*rvp != NULL && ((rvp[0][0] & 0377) != endtoken))
			{
				int nodetype = rvp[0][0] & 0377;

				if (nodetype != CANONHOST &&
				    nodetype != CANONUSER)
				{
					rvp++;
					continue;
				}

				*rvp++ = NULL;

				if (xpvp != NULL)
				{
					cataddr(xpvp, NULL, replac,
						&pvpbuf[sizeof(pvpbuf)] - replac,
						'\0', false);
					if (arg_rvp <
					    &argvect[MAX_MAP_ARGS - 1])
						*++arg_rvp = replac;
					replac += strlen(replac) + 1;
					xpvp = NULL;
				}
				switch (nodetype)
				{
				  case CANONHOST:
					xpvp = rvp;
					break;

				  case CANONUSER:
					default_rvp = rvp;
					break;
				}
			}
			if (*rvp != NULL)
				*rvp++ = NULL;
			if (xpvp != NULL)
			{
				cataddr(xpvp, NULL, replac,
					&pvpbuf[sizeof(pvpbuf)] - replac,
					'\0', false);
				if (arg_rvp < &argvect[MAX_MAP_ARGS - 1])
					*++arg_rvp = replac;
			}
			if (arg_rvp >= &argvect[MAX_MAP_ARGS - 1])
				argvect[MAX_MAP_ARGS - 1] = NULL;
			else
				*++arg_rvp = NULL;

			/* save the remainder of the input string */
			trsize = (avp - rvp + 1) * sizeof(*rvp);
			memmove((char *) pvpb1, (char *) rvp, trsize);

			/* look it up */
			cataddr(key_rvp, NULL, cbuf, sizeof(cbuf),
				map == NULL ? '\0' : map->s_map.map_spacesub,
				true);
			argvect[0] = cbuf;
			replac = map_lookup(map, cbuf, argvect, &rstat, e);
			external = replac != NULL;

			/* if no replacement, use default */
			if (replac == NULL && default_rvp != NULL)
			{
				/* create the default */
				cataddr(default_rvp, NULL, cbuf, sizeof(cbuf),
					'\0', false);
				replac = cbuf;
			}

			if (replac == NULL)
			{
				xpvp = key_rvp;
			}
			else if (*replac == '\0')
			{
				/* null replacement */
				nullpvp[0] = NULL;
				xpvp = nullpvp;
			}
			else
			{
				/* scan the new replacement */
				xpvp = prescan(replac, '\0', pvpbuf,
					       sizeof(pvpbuf), NULL,
					       external ? NULL : IntTokenTab,
					       false);
				if (xpvp == NULL)
				{
					/* prescan already printed error */
					return EX_DATAERR;
				}
			}

			/* append it to the token list */
			for (avp = hbrvp; *xpvp != NULL; xpvp++)
			{
				*avp++ = sm_rpool_strdup_x(e->e_rpool, *xpvp);
				if (avp >= &npvp[maxatom])
					goto toolong;
			}

			/* restore the old trailing information */
			rvp = avp - 1;
			for (xpvp = pvpb1; (*avp++ = *xpvp++) != NULL; )
				if (avp >= &npvp[maxatom])
					goto toolong;
		}

		/*
		**  Check for subroutine calls.
		*/

		status = callsubr(npvp, reclevel, e);
		if (rstat == EX_OK || status == EX_TEMPFAIL)
			rstat = status;

		/* copy vector back into original space. */
		for (avp = npvp; *avp++ != NULL;)
			continue;
		memmove((char *) pvp, (char *) npvp,
		      (int) (avp - npvp) * sizeof(*avp));

		if (tTd(21, 4))
		{
			sm_dprintf("rewritten as:");
			printav(sm_debug_file(), pvp);
		}
	}

	if (OpMode == MD_TEST)
	{
		(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
				     "%s%-16.16s returns:", prefix, rulename);
		printav(smioout, pvp);
	}
	else if (tTd(21, 1))
	{
		sm_dprintf("%s%-16.16s returns:", prefix, rulename);
		printav(sm_debug_file(), pvp);
	}
	return rstat;
}
/*
**  CALLSUBR -- call subroutines in rewrite vector
**
**	Parameters:
**		pvp -- pointer to token vector.
**		reclevel -- the current recursion level.
**		e -- the current envelope.
**
**	Returns:
**		The status from the subroutine call.
**
**	Side Effects:
**		pvp is modified.
*/

static int
callsubr(pvp, reclevel, e)
	char **pvp;
	int reclevel;
	ENVELOPE *e;
{
	char **avp;
	register int i;
	int subr, j;
	int nsubr;
	int status;
	int rstat = EX_OK;
#define MAX_SUBR	16
	int subrnumber[MAX_SUBR];
	int subrindex[MAX_SUBR];

	nsubr = 0;

	/*
	**  Look for subroutine calls in pvp, collect them into subr*[]
	**  We will perform the calls in the next loop, because we will
	**  call the "last" subroutine first to avoid recursive calls
	**  and too much copying.
	*/

	for (avp = pvp, j = 0; *avp != NULL; avp++, j++)
	{
		if ((avp[0][0] & 0377) == CALLSUBR && avp[1] != NULL)
		{
			stripquotes(avp[1]);
			subr = strtorwset(avp[1], NULL, ST_FIND);
			if (subr < 0)
			{
				syserr("554 5.3.5 Unknown ruleset %s", avp[1]);
				return EX_CONFIG;
			}

			/*
			**  XXX instead of doing this we could optimize
			**  the rules after reading them: just remove
			**  calls to empty rulesets
			*/

			/* subroutine is an empty ruleset?  don't call it */
			if (RewriteRules[subr] == NULL)
			{
				if (tTd(21, 3))
					sm_dprintf("-----skip subr %s (%d)\n",
						avp[1], subr);
				for (i = 2; avp[i] != NULL; i++)
					avp[i - 2] = avp[i];
				avp[i - 2] = NULL;
				continue;
			}
			if (++nsubr >= MAX_SUBR)
			{
				syserr("554 5.3.0 Too many subroutine calls (%d max)",
					MAX_SUBR);
				return EX_CONFIG;
			}
			subrnumber[nsubr] = subr;
			subrindex[nsubr] = j;
		}
	}

	/*
	**  Perform the actual subroutines calls, "last" one first, i.e.,
	**  go from the right to the left through all calls,
	**  do the rewriting in place.
	*/

	for (; nsubr > 0; nsubr--)
	{
		subr = subrnumber[nsubr];
		avp = pvp + subrindex[nsubr];

		/* remove the subroutine call and name */
		for (i = 2; avp[i] != NULL; i++)
			avp[i - 2] = avp[i];
		avp[i - 2] = NULL;

		/*
		**  Now we need to call the ruleset specified for
		**  the subroutine. We can do this in place since
		**  we call the "last" subroutine first.
		*/

		status = rewrite(avp, subr, reclevel, e,
				MAXATOM - subrindex[nsubr]);
		if (status != EX_OK && status != EX_TEMPFAIL)
			return status;
		if (rstat == EX_OK || status == EX_TEMPFAIL)
			rstat = status;
	}
	return rstat;
}
/*
**  MAP_LOOKUP -- do lookup in map
**
**	Parameters:
**		smap -- the map to use for the lookup.
**		key -- the key to look up.
**		argvect -- arguments to pass to the map lookup.
**		pstat -- a pointer to an integer in which to store the
**			status from the lookup.
**		e -- the current envelope.
**
**	Returns:
**		The result of the lookup.
**		NULL -- if there was no data for the given key.
*/

static char *
map_lookup(smap, key, argvect, pstat, e)
	STAB *smap;
	char key[];
	char **argvect;
	int *pstat;
	ENVELOPE *e;
{
	auto int status = EX_OK;
	MAP *map;
	char *replac;

	if (smap == NULL)
		return NULL;

	map = &smap->s_map;
	DYNOPENMAP(map);

	if (e->e_sendmode == SM_DEFER &&
	    bitset(MF_DEFER, map->map_mflags))
	{
		/* don't do any map lookups */
		if (tTd(60, 1))
			sm_dprintf("map_lookup(%s, %s) => DEFERRED\n",
				smap->s_name, key);
		*pstat = EX_TEMPFAIL;
		return NULL;
	}

	if (!bitset(MF_KEEPQUOTES, map->map_mflags))
		stripquotes(key);

	if (tTd(60, 1))
	{
		sm_dprintf("map_lookup(%s, ", smap->s_name);
		xputs(sm_debug_file(), key);
		if (tTd(60, 5))
		{
			int i;

			for (i = 0; argvect[i] != NULL; i++)
				sm_dprintf(", %%%d=%s", i, argvect[i]);
		}
		sm_dprintf(") => ");
	}
	replac = (*map->map_class->map_lookup)(map, key, argvect, &status);
	if (tTd(60, 1))
		sm_dprintf("%s (%d)\n",
			replac != NULL ? replac : "NOT FOUND",
			status);

	/* should recover if status == EX_TEMPFAIL */
	if (status == EX_TEMPFAIL && !bitset(MF_NODEFER, map->map_mflags))
	{
		*pstat = EX_TEMPFAIL;
		if (tTd(60, 1))
			sm_dprintf("map_lookup(%s, %s) tempfail: errno=%d\n",
				smap->s_name, key, errno);
		if (e->e_message == NULL)
		{
			char mbuf[320];

			(void) sm_snprintf(mbuf, sizeof(mbuf),
				"%.80s map: lookup (%s): deferred",
				smap->s_name,
				shortenstring(key, MAXSHORTSTR));
			e->e_message = sm_rpool_strdup_x(e->e_rpool, mbuf);
		}
	}
	if (status == EX_TEMPFAIL && map->map_tapp != NULL)
	{
		size_t i = strlen(key) + strlen(map->map_tapp) + 1;
		static char *rwbuf = NULL;
		static size_t rwbuflen = 0;

		if (i > rwbuflen)
		{
			if (rwbuf != NULL)
				sm_free(rwbuf);
			rwbuflen = i;
			rwbuf = (char *) sm_pmalloc_x(rwbuflen);
		}
		(void) sm_strlcpyn(rwbuf, rwbuflen, 2, key, map->map_tapp);
		if (tTd(60, 4))
			sm_dprintf("map_lookup tempfail: returning \"%s\"\n",
				rwbuf);
		return rwbuf;
	}
	return replac;
}
/*
**  INITERRMAILERS -- initialize error and discard mailers
**
**	Parameters:
**		none.
**
**	Returns:
**		none.
**
**	Side Effects:
**		initializes error and discard mailers.
*/

static MAILER discardmailer;
static MAILER errormailer;
static char *discardargv[] = { "DISCARD", NULL };
static char *errorargv[] = { "ERROR", NULL };

void
initerrmailers()
{
	if (discardmailer.m_name == NULL)
	{
		/* initialize the discard mailer */
		discardmailer.m_name = "*discard*";
		discardmailer.m_mailer = "DISCARD";
		discardmailer.m_argv = discardargv;
	}
	if (errormailer.m_name == NULL)
	{
		/* initialize the bogus mailer */
		errormailer.m_name = "*error*";
		errormailer.m_mailer = "ERROR";
		errormailer.m_argv = errorargv;
	}
}
/*
**  BUILDADDR -- build address from token vector.
**
**	Parameters:
**		tv -- token vector.
**		a -- pointer to address descriptor to fill.
**			If NULL, one will be allocated.
**		flags -- info regarding whether this is a sender or
**			a recipient.
**		e -- the current envelope.
**
**	Returns:
**		NULL if there was an error.
**		'a' otherwise.
**
**	Side Effects:
**		fills in 'a'
*/

static struct errcodes
{
	char	*ec_name;		/* name of error code */
	int	ec_code;		/* numeric code */
} ErrorCodes[] =
{
	{ "usage",		EX_USAGE	},
	{ "nouser",		EX_NOUSER	},
	{ "nohost",		EX_NOHOST	},
	{ "unavailable",	EX_UNAVAILABLE	},
	{ "software",		EX_SOFTWARE	},
	{ "tempfail",		EX_TEMPFAIL	},
	{ "protocol",		EX_PROTOCOL	},
	{ "config",		EX_CONFIG	},
	{ NULL,			EX_UNAVAILABLE	}
};

static ADDRESS *
buildaddr(tv, a, flags, e)
	register char **tv;
	register ADDRESS *a;
	int flags;
	register ENVELOPE *e;
{
	bool tempfail = false;
	int maxatom;
	struct mailer **mp;
	register struct mailer *m;
	register char *p;
	char *mname;
	char **hostp;
	char hbuf[MAXNAME + 1];
	static char ubuf[MAXNAME + 2];

	if (tTd(24, 5))
	{
		sm_dprintf("buildaddr, flags=%x, tv=", flags);
		printav(sm_debug_file(), tv);
	}

	maxatom = MAXATOM;
	if (a == NULL)
		a = (ADDRESS *) sm_rpool_malloc_x(e->e_rpool, sizeof(*a));
	memset((char *) a, '\0', sizeof(*a));
	hbuf[0] = '\0';

	/* set up default error return flags */
	a->q_flags |= DefaultNotify;

	/* figure out what net/mailer to use */
	if (*tv == NULL || (**tv & 0377) != CANONNET)
	{
		syserr("554 5.3.5 buildaddr: no mailer in parsed address");
badaddr:
		/*
		**  ExitStat may have been set by an earlier map open
		**  failure (to a permanent error (EX_OSERR) in syserr())
		**  so we also need to check if this particular $#error
		**  return wanted a 4XX failure.
		**
		**  XXX the real fix is probably to set ExitStat correctly,
		**  i.e., to EX_TEMPFAIL if the map open is just a temporary
		**  error.
		*/

		if (ExitStat == EX_TEMPFAIL || tempfail)
			a->q_state = QS_QUEUEUP;
		else
		{
			a->q_state = QS_BADADDR;
			a->q_mailer = &errormailer;
		}
		return a;
	}
	mname = *++tv;
	--maxatom;

	/* extract host and user portions */
	if (*++tv != NULL && (**tv & 0377) == CANONHOST)
	{
		hostp = ++tv;
		--maxatom;
	}
	else
		hostp = NULL;
	--maxatom;
	while (*tv != NULL && (**tv & 0377) != CANONUSER)
	{
		tv++;
		--maxatom;
	}
	if (*tv == NULL)
	{
		syserr("554 5.3.5 buildaddr: no user");
		goto badaddr;
	}
	if (tv == hostp)
		hostp = NULL;
	else if (hostp != NULL)
		cataddr(hostp, tv - 1, hbuf, sizeof(hbuf), '\0', false);
	cataddr(++tv, NULL, ubuf, sizeof(ubuf), ' ', false);
	--maxatom;

	/* save away the host name */
	if (sm_strcasecmp(mname, "error") == 0)
	{
		/* Set up triplet for use by -bv */
		a->q_mailer = &errormailer;
		a->q_user = sm_rpool_strdup_x(e->e_rpool, ubuf);
		/* XXX wrong place? */

		if (hostp != NULL)
		{
			register struct errcodes *ep;

			a->q_host = sm_rpool_strdup_x(e->e_rpool, hbuf);
			if (strchr(hbuf, '.') != NULL)
			{
				a->q_status = sm_rpool_strdup_x(e->e_rpool,
								hbuf);
				setstat(dsntoexitstat(hbuf));
			}
			else if (isascii(hbuf[0]) && isdigit(hbuf[0]))
			{
				setstat(atoi(hbuf));
			}
			else
			{
				for (ep = ErrorCodes; ep->ec_name != NULL; ep++)
					if (sm_strcasecmp(ep->ec_name, hbuf) == 0)
						break;
				setstat(ep->ec_code);
			}
		}
		else
		{
			a->q_host = NULL;
			setstat(EX_UNAVAILABLE);
		}
		stripquotes(ubuf);
		if (ISSMTPCODE(ubuf) && ubuf[3] == ' ')
		{
			char fmt[16];
			int off;

			if ((off = isenhsc(ubuf + 4, ' ')) > 0)
			{
				ubuf[off + 4] = '\0';
				off += 5;
			}
			else
			{
				off = 4;
				ubuf[3] = '\0';
			}
			(void) sm_strlcpyn(fmt, sizeof(fmt), 2, ubuf, " %s");
			if (off > 4)
				usrerr(fmt, ubuf + off);
			else if (isenhsc(hbuf, '\0') > 0)
				usrerrenh(hbuf, fmt, ubuf + off);
			else
				usrerr(fmt, ubuf + off);
			/* XXX ubuf[off - 1] = ' '; */
			if (ubuf[0] == '4')
				tempfail = true;
		}
		else
		{
			usrerr("553 5.3.0 %s", ubuf);
		}
		goto badaddr;
	}

	for (mp = Mailer; (m = *mp++) != NULL; )
	{
		if (sm_strcasecmp(m->m_name, mname) == 0)
			break;
	}
	if (m == NULL)
	{
		syserr("554 5.3.5 buildaddr: unknown mailer %s", mname);
		goto badaddr;
	}
	a->q_mailer = m;

	/* figure out what host (if any) */
	if (hostp == NULL)
	{
		if (!bitnset(M_LOCALMAILER, m->m_flags))
		{
			syserr("554 5.3.5 buildaddr: no host");
			goto badaddr;
		}
		a->q_host = NULL;
	}
	else
		a->q_host = sm_rpool_strdup_x(e->e_rpool, hbuf);

	/* figure out the user */
	p = ubuf;
	if (bitnset(M_CHECKUDB, m->m_flags) && *p == '@')
	{
		p++;
		tv++;
		--maxatom;
		a->q_flags |= QNOTREMOTE;
	}

	/* do special mapping for local mailer */
	if (*p == '"')
		p++;
	if (*p == '|' && bitnset(M_CHECKPROG, m->m_flags))
		a->q_mailer = m = ProgMailer;
	else if (*p == '/' && bitnset(M_CHECKFILE, m->m_flags))
		a->q_mailer = m = FileMailer;
	else if (*p == ':' && bitnset(M_CHECKINCLUDE, m->m_flags))
	{
		/* may be :include: */
		stripquotes(ubuf);
		if (sm_strncasecmp(ubuf, ":include:", 9) == 0)
		{
			/* if :include:, don't need further rewriting */
			a->q_mailer = m = InclMailer;
			a->q_user = sm_rpool_strdup_x(e->e_rpool, &ubuf[9]);
			return a;
		}
	}

	/* rewrite according recipient mailer rewriting rules */
	macdefine(&e->e_macro, A_PERM, 'h', a->q_host);

	if (ConfigLevel >= 10 ||
	    !bitset(RF_SENDERADDR|RF_HEADERADDR, flags))
	{
		/* sender addresses done later */
		(void) rewrite(tv, 2, 0, e, maxatom);
		if (m->m_re_rwset > 0)
		       (void) rewrite(tv, m->m_re_rwset, 0, e, maxatom);
	}
	(void) rewrite(tv, 4, 0, e, maxatom);

	/* save the result for the command line/RCPT argument */
	cataddr(tv, NULL, ubuf, sizeof(ubuf), '\0', true);
	a->q_user = sm_rpool_strdup_x(e->e_rpool, ubuf);

	/*
	**  Do mapping to lower case as requested by mailer
	*/

	if (a->q_host != NULL && !bitnset(M_HST_UPPER, m->m_flags))
		makelower(a->q_host);
	if (!bitnset(M_USR_UPPER, m->m_flags))
		makelower(a->q_user);

	if (tTd(24, 6))
	{
		sm_dprintf("buildaddr => ");
		printaddr(sm_debug_file(), a, false);
	}
	return a;
}

/*
**  CATADDR -- concatenate pieces of addresses (putting in <LWSP> subs)
**
**	Parameters:
**		pvp -- parameter vector to rebuild.
**		evp -- last parameter to include.  Can be NULL to
**			use entire pvp.
**		buf -- buffer to build the string into.
**		sz -- size of buf.
**		spacesub -- the space separator character;
**			'\0': SpaceSub.
**			NOSPACESEP: no separator
**		external -- convert to external form?
**			(no metacharacters; METAQUOTEs removed, see below)
**
**	Returns:
**		none.
**
**	Side Effects:
**		Destroys buf.
**
**	Notes:
**	There are two formats for strings: internal and external.
**	The external format is just an eight-bit clean string (no
**	null bytes, everything else OK).  The internal format can
**	include sendmail metacharacters.  The special character
**	METAQUOTE essentially quotes the character following, stripping
**	it of all special semantics.
**
**	The cataddr routine needs to be aware of whether it is producing
**	an internal or external form as output (it only takes internal
**	form as input).
**
**	The parseaddr routine has a similar issue on input, but that
**	is flagged on the basis of which token table is passed in.
*/

void
cataddr(pvp, evp, buf, sz, spacesub, external)
	char **pvp;
	char **evp;
	char *buf;
	register int sz;
	int spacesub;
	bool external;
{
	bool oatomtok, natomtok;
	char *p;

	oatomtok = natomtok = false;
	if (tTd(59, 14))
	{
		sm_dprintf("cataddr(%d) <==", external);
		printav(sm_debug_file(), pvp);
	}

	if (sz <= 0)
		return;

	if (spacesub == '\0')
		spacesub = SpaceSub;

	if (pvp == NULL)
	{
		*buf = '\0';
		return;
	}
	p = buf;
	sz -= 2;
	while (*pvp != NULL && sz > 0)
	{
		char *q;

		natomtok = (IntTokenTab[**pvp & 0xff] == ATM);
		if (oatomtok && natomtok && spacesub != NOSPACESEP)
		{
			*p++ = spacesub;
			if (--sz <= 0)
				break;
		}
		for (q = *pvp; *q != '\0'; )
		{
			int c;

			if (--sz <= 0)
				break;
			*p++ = c = *q++;

			/*
			**  If the current character (c) is METAQUOTE and we
			**  want the "external" form and the next character
			**  is not NUL, then overwrite METAQUOTE with that
			**  character (i.e., METAQUOTE ch is changed to
			**  ch).  p[-1] is used because p is advanced (above).
			*/

			if ((c & 0377) == METAQUOTE && external && *q != '\0')
				p[-1] = *q++;
		}
		if (sz <= 0)
			break;
		oatomtok = natomtok;
		if (pvp++ == evp)
			break;
	}

#if 0
	/*
	**  Silently truncate long strings: even though this doesn't
	**  seem like a good idea it is necessary because header checks
	**  send the whole header value to rscheck() and hence rewrite().
	**  The latter however sometimes uses a "short" buffer (e.g.,
	**  cbuf[MAXNAME + 1]) to call cataddr() which then triggers this
	**  error function.  One possible fix to the problem is to pass
	**  flags to rscheck() and rewrite() to distinguish the various
	**  calls and only trigger the error if necessary.  For now just
	**  undo the change from 8.13.0.
	*/

	if (sz <= 0)
		usrerr("cataddr: string too long");
#endif
	*p = '\0';

	if (tTd(59, 14))
		sm_dprintf("  cataddr => %s\n", str2prt(buf));
}

/*
**  SAMEADDR -- Determine if two addresses are the same
**
**	This is not just a straight comparison -- if the mailer doesn't
**	care about the host we just ignore it, etc.
**
**	Parameters:
**		a, b -- pointers to the internal forms to compare.
**
**	Returns:
**		true -- they represent the same mailbox.
**		false -- they don't.
**
**	Side Effects:
**		none.
*/

bool
sameaddr(a, b)
	register ADDRESS *a;
	register ADDRESS *b;
{
	register ADDRESS *ca, *cb;

	/* if they don't have the same mailer, forget it */
	if (a->q_mailer != b->q_mailer)
		return false;

	/*
	**  Addresses resolving to error mailer
	**  should not be considered identical
	*/

	if (a->q_mailer == &errormailer)
		return false;

	/* if the user isn't the same, we can drop out */
	if (strcmp(a->q_user, b->q_user) != 0)
		return false;

	/* do the required flags match? */
	if (!ADDR_FLAGS_MATCH(a, b))
		return false;

	/* if we have good uids for both but they differ, these are different */
	if (a->q_mailer == ProgMailer)
	{
		ca = getctladdr(a);
		cb = getctladdr(b);
		if (ca != NULL && cb != NULL &&
		    bitset(QGOODUID, ca->q_flags & cb->q_flags) &&
		    ca->q_uid != cb->q_uid)
			return false;
	}

	/* otherwise compare hosts (but be careful for NULL ptrs) */
	if (a->q_host == b->q_host)
	{
		/* probably both null pointers */
		return true;
	}
	if (a->q_host == NULL || b->q_host == NULL)
	{
		/* only one is a null pointer */
		return false;
	}
	if (strcmp(a->q_host, b->q_host) != 0)
		return false;

	return true;
}
/*
**  PRINTADDR -- print address (for debugging)
**
**	Parameters:
**		a -- the address to print
**		follow -- follow the q_next chain.
**
**	Returns:
**		none.
**
**	Side Effects:
**		none.
*/

struct qflags
{
	char		*qf_name;
	unsigned long	qf_bit;
};

/* :'a,.s;^#define \(Q[A-Z]*\)	.*;	{ "\1",	\1	},; */
static struct qflags	AddressFlags[] =
{
	{ "QGOODUID",		QGOODUID	},
	{ "QPRIMARY",		QPRIMARY	},
	{ "QNOTREMOTE",		QNOTREMOTE	},
	{ "QSELFREF",		QSELFREF	},
	{ "QBOGUSSHELL",	QBOGUSSHELL	},
	{ "QUNSAFEADDR",	QUNSAFEADDR	},
	{ "QPINGONSUCCESS",	QPINGONSUCCESS	},
	{ "QPINGONFAILURE",	QPINGONFAILURE	},
	{ "QPINGONDELAY",	QPINGONDELAY	},
	{ "QHASNOTIFY",		QHASNOTIFY	},
	{ "QRELAYED",		QRELAYED	},
	{ "QEXPANDED",		QEXPANDED	},
	{ "QDELIVERED",		QDELIVERED	},
	{ "QDELAYED",		QDELAYED	},
	{ "QTHISPASS",		QTHISPASS	},
	{ "QALIAS",		QALIAS		},
	{ "QBYTRACE",		QBYTRACE	},
	{ "QBYNDELAY",		QBYNDELAY	},
	{ "QBYNRELAY",		QBYNRELAY	},
	{ "QINTBCC",		QINTBCC		},
	{ "QDYNMAILER",		QDYNMAILER	},
	{ "QRCPTOK",		QRCPTOK		},
	{ NULL,			0		}
};

void
printaddr(fp, a, follow)
	SM_FILE_T *fp;
	register ADDRESS *a;
	bool follow;
{
	register MAILER *m;
	MAILER pseudomailer;
	register struct qflags *qfp;
	bool firstone;

	if (a == NULL)
	{
		(void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "[NULL]\n");
		return;
	}

	while (a != NULL)
	{
		(void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "%p=", a);
		(void) sm_io_flush(fp, SM_TIME_DEFAULT);

		/* find the mailer -- carefully */
		m = a->q_mailer;
		if (m == NULL)
		{
			m = &pseudomailer;
			m->m_mno = -1;
			m->m_name = "NULL";
		}

		(void) sm_io_fprintf(fp, SM_TIME_DEFAULT,
				     "%s:\n\tmailer %d (%s), host `%s'\n",
				     a->q_paddr == NULL ? "<null>" : a->q_paddr,
				     m->m_mno, m->m_name,
				     a->q_host == NULL ? "<null>" : a->q_host);
		(void) sm_io_fprintf(fp, SM_TIME_DEFAULT,
				     "\tuser `%s', ruser `%s'\n",
				     a->q_user,
				     a->q_ruser == NULL ? "<null>" : a->q_ruser);
		(void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "\tstate=");
		switch (a->q_state)
		{
		  case QS_OK:
			(void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "OK");
			break;

		  case QS_DONTSEND:
			(void) sm_io_fprintf(fp, SM_TIME_DEFAULT,
					     "DONTSEND");
			break;

		  case QS_BADADDR:
			(void) sm_io_fprintf(fp, SM_TIME_DEFAULT,
					     "BADADDR");
			break;

		  case QS_QUEUEUP:
			(void) sm_io_fprintf(fp, SM_TIME_DEFAULT,
					     "QUEUEUP");
			break;

		  case QS_RETRY:
			(void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "RETRY");
			break;

		  case QS_SENT:
			(void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "SENT");
			break;

		  case QS_VERIFIED:
			(void) sm_io_fprintf(fp, SM_TIME_DEFAULT,
					     "VERIFIED");
			break;

		  case QS_EXPANDED:
			(void) sm_io_fprintf(fp, SM_TIME_DEFAULT,
					     "EXPANDED");
			break;

		  case QS_SENDER:
			(void) sm_io_fprintf(fp, SM_TIME_DEFAULT,
					     "SENDER");
			break;

		  case QS_CLONED:
			(void) sm_io_fprintf(fp, SM_TIME_DEFAULT,
					     "CLONED");
			break;

		  case QS_DISCARDED:
			(void) sm_io_fprintf(fp, SM_TIME_DEFAULT,
					     "DISCARDED");
			break;

		  case QS_REPLACED:
			(void) sm_io_fprintf(fp, SM_TIME_DEFAULT,
					     "REPLACED");
			break;

		  case QS_REMOVED:
			(void) sm_io_fprintf(fp, SM_TIME_DEFAULT,
					     "REMOVED");
			break;

		  case QS_DUPLICATE:
			(void) sm_io_fprintf(fp, SM_TIME_DEFAULT,
					     "DUPLICATE");
			break;

		  case QS_INCLUDED:
			(void) sm_io_fprintf(fp, SM_TIME_DEFAULT,
					     "INCLUDED");
			break;

		  default:
			(void) sm_io_fprintf(fp, SM_TIME_DEFAULT,
					     "%d", a->q_state);
			break;
		}
		(void) sm_io_fprintf(fp, SM_TIME_DEFAULT,
				     ", next=%p, alias %p, uid %d, gid %d\n",
				     a->q_next, a->q_alias,
				     (int) a->q_uid, (int) a->q_gid);
		(void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "\tflags=%lx<",
				     a->q_flags);
		firstone = true;
		for (qfp = AddressFlags; qfp->qf_name != NULL; qfp++)
		{
			if (!bitset(qfp->qf_bit, a->q_flags))
				continue;
			if (!firstone)
				(void) sm_io_fprintf(fp, SM_TIME_DEFAULT,
						     ",");
			firstone = false;
			(void) sm_io_fprintf(fp, SM_TIME_DEFAULT, "%s",
					     qfp->qf_name);
		}
		(void) sm_io_fprintf(fp, SM_TIME_DEFAULT, ">\n");
		(void) sm_io_fprintf(fp, SM_TIME_DEFAULT,
				     "\towner=%s, home=\"%s\", fullname=\"%s\"\n",
				     a->q_owner == NULL ? "(none)" : a->q_owner,
				     a->q_home == NULL ? "(none)" : a->q_home,
				     a->q_fullname == NULL ? "(none)" : a->q_fullname);
		(void) sm_io_fprintf(fp, SM_TIME_DEFAULT,
				     "\torcpt=\"%s\", statmta=%s, status=%s\n",
				     a->q_orcpt == NULL ? "(none)" : a->q_orcpt,
				     a->q_statmta == NULL ? "(none)" : a->q_statmta,
				     a->q_status == NULL ? "(none)" : a->q_status);
		(void) sm_io_fprintf(fp, SM_TIME_DEFAULT,
				     "\tfinalrcpt=\"%s\"\n",
				     a->q_finalrcpt == NULL ? "(none)" : a->q_finalrcpt);
		(void) sm_io_fprintf(fp, SM_TIME_DEFAULT,
				     "\trstatus=\"%s\"\n",
				     a->q_rstatus == NULL ? "(none)" : a->q_rstatus);
		(void) sm_io_fprintf(fp, SM_TIME_DEFAULT,
				     "\tstatdate=%s\n",
				     a->q_statdate == 0 ? "(none)" : ctime(&a->q_statdate));

		if (!follow)
			return;
		a = a->q_next;
	}
}
/*
**  EMPTYADDR -- return true if this address is empty (``<>'')
**
**	Parameters:
**		a -- pointer to the address
**
**	Returns:
**		true -- if this address is "empty" (i.e., no one should
**			ever generate replies to it.
**		false -- if it is a "regular" (read: replyable) address.
*/

bool
emptyaddr(a)
	register ADDRESS *a;
{
	return a->q_paddr == NULL || strcmp(a->q_paddr, "<>") == 0 ||
	       a->q_user == NULL || strcmp(a->q_user, "<>") == 0;
}
/*
**  REMOTENAME -- return the name relative to the current mailer
**
**	Parameters:
**		name -- the name to translate.
**		m -- the mailer that we want to do rewriting relative to.
**		flags -- fine tune operations.
**		pstat -- pointer to status word.
**		e -- the current envelope.
**
**	Returns:
**		the text string representing this address relative to
**			the receiving mailer.
**
**	Side Effects:
**		none.
**
**	Warnings:
**		The text string returned is tucked away locally;
**			copy it if you intend to save it.
*/

char *
remotename(name, m, flags, pstat, e)
	char *name;
	struct mailer *m;
	int flags;
	int *pstat;
	register ENVELOPE *e;
{
	register char **pvp;
	char *SM_NONVOLATILE fancy;
	char *oldg;
	int rwset;
	static char buf[MAXNAME + 1];
	char lbuf[MAXNAME + 1];
	char pvpbuf[PSBUFSIZE];
	char addrtype[4];

	if (tTd(12, 1))
	{
		sm_dprintf("remotename(");
		xputs(sm_debug_file(), name);
		sm_dprintf(")\n");
	}

	/* don't do anything if we are tagging it as special */
	if (bitset(RF_SENDERADDR, flags))
	{
		rwset = bitset(RF_HEADERADDR, flags) ? m->m_sh_rwset
						     : m->m_se_rwset;
		addrtype[2] = 's';
	}
	else
	{
		rwset = bitset(RF_HEADERADDR, flags) ? m->m_rh_rwset
						     : m->m_re_rwset;
		addrtype[2] = 'r';
	}
	if (rwset < 0)
		return name;
	addrtype[1] = ' ';
	addrtype[3] = '\0';
	addrtype[0] = bitset(RF_HEADERADDR, flags) ? 'h' : 'e';
	macdefine(&e->e_macro, A_TEMP, macid("{addr_type}"), addrtype);

	/*
	**  Do a heuristic crack of this name to extract any comment info.
	**	This will leave the name as a comment and a $g macro.
	*/

	if (bitset(RF_CANONICAL, flags) || bitnset(M_NOCOMMENT, m->m_flags))
		fancy = "\201g";
	else
		fancy = crackaddr(name, e);

	/*
	**  Turn the name into canonical form.
	**	Normally this will be RFC 822 style, i.e., "user@domain".
	**	If this only resolves to "user", and the "C" flag is
	**	specified in the sending mailer, then the sender's
	**	domain will be appended.
	*/

	pvp = prescan(name, '\0', pvpbuf, sizeof(pvpbuf), NULL, NULL, false);
	if (pvp == NULL)
		return name;
	if (REWRITE(pvp, 3, e) == EX_TEMPFAIL)
		*pstat = EX_TEMPFAIL;
	if (bitset(RF_ADDDOMAIN, flags) && e->e_fromdomain != NULL)
	{
		/* append from domain to this address */
		register char **pxp = pvp;
		int l = MAXATOM;	/* size of buffer for pvp */

		/* see if there is an "@domain" in the current name */
		while (*pxp != NULL && strcmp(*pxp, "@") != 0)
		{
			pxp++;
			--l;
		}
		if (*pxp == NULL)
		{
			/* no.... append the "@domain" from the sender */
			register char **qxq = e->e_fromdomain;

			while ((*pxp++ = *qxq++) != NULL)
			{
				if (--l <= 0)
				{
					*--pxp = NULL;
					usrerr("553 5.1.0 remotename: too many tokens");
					*pstat = EX_UNAVAILABLE;
					break;
				}
			}
			if (REWRITE(pvp, 3, e) == EX_TEMPFAIL)
				*pstat = EX_TEMPFAIL;
		}
	}

	/*
	**  Do more specific rewriting.
	**	Rewrite using ruleset 1 or 2 depending on whether this is
	**		a sender address or not.
	**	Then run it through any receiving-mailer-specific rulesets.
	*/

	if (bitset(RF_SENDERADDR, flags))
	{
		if (REWRITE(pvp, 1, e) == EX_TEMPFAIL)
			*pstat = EX_TEMPFAIL;
	}
	else
	{
		if (REWRITE(pvp, 2, e) == EX_TEMPFAIL)
			*pstat = EX_TEMPFAIL;
	}
	if (rwset > 0)
	{
		if (REWRITE(pvp, rwset, e) == EX_TEMPFAIL)
			*pstat = EX_TEMPFAIL;
	}

	/*
	**  Do any final sanitation the address may require.
	**	This will normally be used to turn internal forms
	**	(e.g., user@host.LOCAL) into external form.  This
	**	may be used as a default to the above rules.
	*/

	if (REWRITE(pvp, 4, e) == EX_TEMPFAIL)
		*pstat = EX_TEMPFAIL;

	/*
	**  Now restore the comment information we had at the beginning.
	*/

	cataddr(pvp, NULL, lbuf, sizeof(lbuf), '\0', false);
	oldg = macget(&e->e_macro, 'g');
	macset(&e->e_macro, 'g', lbuf);

	SM_TRY
		/* need to make sure route-addrs have <angle brackets> */
		if (bitset(RF_CANONICAL, flags) && lbuf[0] == '@')
			expand("<\201g>", buf, sizeof(buf), e);
		else
			expand(fancy, buf, sizeof(buf), e);
	SM_FINALLY
		macset(&e->e_macro, 'g', oldg);
	SM_END_TRY

	if (tTd(12, 1))
	{
		sm_dprintf("remotename => `");
		xputs(sm_debug_file(), buf);
		sm_dprintf("', stat=%d\n", *pstat);
	}
	return buf;
}
/*
**  MAPLOCALUSER -- run local username through ruleset 5 for final redirection
**
**	Parameters:
**		a -- the address to map (but just the user name part).
**		sendq -- the sendq in which to install any replacement
**			addresses.
**		aliaslevel -- the alias nesting depth.
**		e -- the envelope.
**
**	Returns:
**		none.
*/

#define Q_COPYFLAGS	(QPRIMARY|QBOGUSSHELL|QUNSAFEADDR|\
			 Q_PINGFLAGS|QHASNOTIFY|\
			 QRELAYED|QEXPANDED|QDELIVERED|QDELAYED|\
			 QBYTRACE|QBYNDELAY|QBYNRELAY)

void
maplocaluser(a, sendq, aliaslevel, e)
	register ADDRESS *a;
	ADDRESS **sendq;
	int aliaslevel;
	ENVELOPE *e;
{
	register char **pvp;
	register ADDRESS *SM_NONVOLATILE a1 = NULL;
	char pvpbuf[PSBUFSIZE];

	if (tTd(29, 1))
	{
		sm_dprintf("maplocaluser: ");
		printaddr(sm_debug_file(), a, false);
	}
	pvp = prescan(a->q_user, '\0', pvpbuf, sizeof(pvpbuf), NULL, NULL,
			false);
	if (pvp == NULL)
	{
		if (tTd(29, 9))
			sm_dprintf("maplocaluser: cannot prescan %s\n",
				a->q_user);
		return;
	}

	macdefine(&e->e_macro, A_PERM, 'h', a->q_host);
	macdefine(&e->e_macro, A_PERM, 'u', a->q_user);
	macdefine(&e->e_macro, A_PERM, 'z', a->q_home);

	macdefine(&e->e_macro, A_PERM, macid("{addr_type}"), "e r");
	if (REWRITE(pvp, 5, e) == EX_TEMPFAIL)
	{
		if (tTd(29, 9))
			sm_dprintf("maplocaluser: rewrite tempfail\n");
		a->q_state = QS_QUEUEUP;
		a->q_status = "4.4.3";
		return;
	}
	if (pvp[0] == NULL || (pvp[0][0] & 0377) != CANONNET)
	{
		if (tTd(29, 9))
			sm_dprintf("maplocaluser: doesn't resolve\n");
		return;
	}

	SM_TRY
		a1 = buildaddr(pvp, NULL, 0, e);
	SM_EXCEPT(exc, "E:mta.quickabort")

		/*
		**  mark address as bad, S5 returned an error
		**	and we gave that back to the SMTP client.
		*/

		a->q_state = QS_DONTSEND;
		sm_exc_raisenew_x(&EtypeQuickAbort, 2);
	SM_END_TRY

	/* if non-null, mailer destination specified -- has it changed? */
	if (a1 == NULL || sameaddr(a, a1))
	{
		if (tTd(29, 9))
			sm_dprintf("maplocaluser: address unchanged\n");
		return;
	}

	/* make new address take on flags and print attributes of old */
	a1->q_flags &= ~Q_COPYFLAGS;
	a1->q_flags |= a->q_flags & Q_COPYFLAGS;
	a1->q_paddr = sm_rpool_strdup_x(e->e_rpool, a->q_paddr);
	a1->q_finalrcpt = a->q_finalrcpt;
	a1->q_orcpt = a->q_orcpt;

	/* mark old address as dead; insert new address */
	a->q_state = QS_REPLACED;
	if (tTd(29, 5))
	{
		sm_dprintf("maplocaluser: QS_REPLACED ");
		printaddr(sm_debug_file(), a, false);
	}
	a1->q_alias = a;
	allocaddr(a1, RF_COPYALL, sm_rpool_strdup_x(e->e_rpool, a->q_paddr), e);
	(void) recipient(a1, sendq, aliaslevel, e);
}
/*
**  DEQUOTE_INIT -- initialize dequote map
**
**	Parameters:
**		map -- the internal map structure.
**		args -- arguments.
**
**	Returns:
**		true.
*/

bool
dequote_init(map, args)
	MAP *map;
	char *args;
{
	register char *p = args;

	/* there is no check whether there is really an argument */
	map->map_mflags |= MF_KEEPQUOTES;
	for (;;)
	{
		while (isascii(*p) && isspace(*p))
			p++;
		if (*p != '-')
			break;
		switch (*++p)
		{
		  case 'a':
			map->map_app = ++p;
			break;

		  case 'D':
			map->map_mflags |= MF_DEFER;
			break;

		  case 'S':
		  case 's':
			map->map_spacesub = *++p;
			break;
		}
		while (*p != '\0' && !(isascii(*p) && isspace(*p)))
			p++;
		if (*p != '\0')
			*p = '\0';
	}
	if (map->map_app != NULL)
		map->map_app = newstr(map->map_app);

	return true;
}
/*
**  DEQUOTE_MAP -- unquote an address
**
**	Parameters:
**		map -- the internal map structure (ignored).
**		name -- the name to dequote.
**		av -- arguments (ignored).
**		statp -- pointer to status out-parameter.
**
**	Returns:
**		NULL -- if there were no quotes, or if the resulting
**			unquoted buffer would not be acceptable to prescan.
**		else -- The dequoted buffer.
*/

/* ARGSUSED2 */
char *
dequote_map(map, name, av, statp)
	MAP *map;
	char *name;
	char **av;
	int *statp;
{
	register char *p;
	register char *q;
	register char c;
	int anglecnt = 0;
	int cmntcnt = 0;
	int quotecnt = 0;
	int spacecnt = 0;
	bool quotemode = false;
	bool bslashmode = false;
	char spacesub = map->map_spacesub;

	for (p = q = name; (c = *p++) != '\0'; )
	{
		if (bslashmode)
		{
			bslashmode = false;
			*q++ = c;
			continue;
		}

		if (c == ' ' && spacesub != '\0')
			c = spacesub;

		switch (c)
		{
		  case '\\':
			bslashmode = true;
			break;

		  case '(':
			cmntcnt++;
			break;

		  case ')':
			if (cmntcnt-- <= 0)
				return NULL;
			break;

		  case ' ':
		  case '\t':
			spacecnt++;
			break;
		}

		if (cmntcnt > 0)
		{
			*q++ = c;
			continue;
		}

		switch (c)
		{
		  case '"':
			quotemode = !quotemode;
			quotecnt++;
			continue;

		  case '<':
			anglecnt++;
			break;

		  case '>':
			if (anglecnt-- <= 0)
				return NULL;
			break;
		}
		*q++ = c;
	}

	if (anglecnt != 0 || cmntcnt != 0 || bslashmode ||
	    quotemode || quotecnt <= 0 || spacecnt != 0)
		return NULL;
	*q++ = '\0';
	return map_rewrite(map, name, strlen(name), NULL);
}
/*
**  RSCHECK -- check string(s) for validity using rewriting sets
**
**	Parameters:
**		rwset -- the rewriting set to use.
**		p1 -- the first string to check.
**		p2 -- the second string to check -- may be null.
**		e -- the current envelope.
**		flags -- control some behavior, see RSF_ in sendmail.h
**		logl -- logging level.
**		host -- NULL or relay host.
**		logid -- id for sm_syslog.
**		addr -- if not NULL and ruleset returns $#error:
**				store mailer triple here.
**		addrstr -- if not NULL and ruleset does not return $#:
**				address string
**
**	Returns:
**		EX_OK -- if the rwset doesn't resolve to $#error
**		else -- the failure status (message printed)
*/

int
rscheck(rwset, p1, p2, e, flags, logl, host, logid, addr, addrstr)
	char *rwset;
	char *p1;
	char *p2;
	ENVELOPE *e;
	int flags;
	int logl;
	char *host;
	char *logid;
	ADDRESS *addr;
	char **addrstr;
{
	char *volatile buf;
	size_t bufsize;
	int saveexitstat;
	int volatile rstat = EX_OK;
	char **pvp;
	int rsno;
	bool volatile discard = false;
	bool saveQuickAbort = QuickAbort;
	bool saveSuprErrs = SuprErrs;
	bool quarantine = false;
	char ubuf[BUFSIZ * 2];
	char buf0[MAXLINE];
	char pvpbuf[PSBUFSIZE];
	extern char MsgBuf[];

	if (tTd(48, 2))
		sm_dprintf("rscheck(%s, %s, %s)\n", rwset, p1,
			p2 == NULL ? "(NULL)" : p2);

	rsno = strtorwset(rwset, NULL, ST_FIND);
	if (rsno < 0)
		return EX_OK;

	if (p2 != NULL)
	{
		bufsize = strlen(p1) + strlen(p2) + 2;
		if (bufsize > sizeof(buf0))
			buf = sm_malloc_x(bufsize);
		else
		{
			buf = buf0;
			bufsize = sizeof(buf0);
		}
		(void) sm_snprintf(buf, bufsize, "%s%c%s", p1, CONDELSE, p2);
	}
	else
	{
		bufsize = strlen(p1) + 1;
		if (bufsize > sizeof(buf0))
			buf = sm_malloc_x(bufsize);
		else
		{
			buf = buf0;
			bufsize = sizeof(buf0);
		}
		(void) sm_strlcpy(buf, p1, bufsize);
	}
	SM_TRY
	{
		SuprErrs = true;
		QuickAbort = false;
		pvp = prescan(buf, '\0', pvpbuf, sizeof(pvpbuf), NULL,
			      bitset(RSF_RMCOMM, flags) ?
					IntTokenTab : TokTypeNoC,
			      bitset(RSF_RMCOMM, flags) ? false : true);
		SuprErrs = saveSuprErrs;
		if (pvp == NULL)
		{
			if (tTd(48, 2))
				sm_dprintf("rscheck: cannot prescan input\n");
	/*
			syserr("rscheck: cannot prescan input: \"%s\"",
				shortenstring(buf, MAXSHORTSTR));
			rstat = EX_DATAERR;
	*/
			goto finis;
		}
		if (bitset(RSF_UNSTRUCTURED, flags))
			SuprErrs = true;
		(void) REWRITE(pvp, rsno, e);
		if (bitset(RSF_UNSTRUCTURED, flags))
			SuprErrs = saveSuprErrs;

		if (pvp[0] != NULL && (pvp[0][0] & 0377) != CANONNET &&
		    bitset(RSF_ADDR, flags) && addrstr != NULL)
		{
			cataddr(&(pvp[0]), NULL, ubuf, sizeof(ubuf),
				bitset(RSF_STRING, flags) ? NOSPACESEP : ' ',
				true);
			*addrstr = sm_rpool_strdup_x(e->e_rpool, ubuf);
			goto finis;
		}

		if (pvp[0] == NULL || (pvp[0][0] & 0377) != CANONNET ||
		    pvp[1] == NULL || (strcmp(pvp[1], "error") != 0 &&
				       strcmp(pvp[1], "discard") != 0))
		{
			goto finis;
		}

		if (strcmp(pvp[1], "discard") == 0)
		{
			if (tTd(48, 2))
				sm_dprintf("rscheck: discard mailer selected\n");
			e->e_flags |= EF_DISCARD;
			discard = true;
		}
		else if (strcmp(pvp[1], "error") == 0 &&
			 pvp[2] != NULL && (pvp[2][0] & 0377) == CANONHOST &&
			 pvp[3] != NULL && strcmp(pvp[3], "quarantine") == 0)
		{
			if (pvp[4] == NULL ||
			    (pvp[4][0] & 0377) != CANONUSER ||
			    pvp[5] == NULL)
				e->e_quarmsg = sm_rpool_strdup_x(e->e_rpool,
								 rwset);
			else
			{
				cataddr(&(pvp[5]), NULL, ubuf,
					sizeof(ubuf), ' ', true);
				e->e_quarmsg = sm_rpool_strdup_x(e->e_rpool,
								 ubuf);
			}
			macdefine(&e->e_macro, A_PERM,
				  macid("{quarantine}"), e->e_quarmsg);
			quarantine = true;
		}
		else
		{
			auto ADDRESS a1;
			int savelogusrerrs = LogUsrErrs;
			static bool logged = false;

			/* got an error -- process it */
			saveexitstat = ExitStat;
			LogUsrErrs = false;
			(void) buildaddr(pvp, &a1, 0, e);
			if (addr != NULL)
			{
				addr->q_mailer = a1.q_mailer;
				addr->q_user = a1.q_user;
				addr->q_host = a1.q_host;
			}
			LogUsrErrs = savelogusrerrs;
			rstat = ExitStat;
			ExitStat = saveexitstat;
			if (!logged)
			{
				if (bitset(RSF_COUNT, flags))
					markstats(e, &a1, STATS_REJECT);
				logged = true;
			}
		}

		if (LogLevel > logl)
		{
			char *relay;
			char *p;
			char lbuf[MAXLINE];

			p = lbuf;
			if (p2 != NULL)
			{
				(void) sm_snprintf(p, SPACELEFT(lbuf, p),
					", arg2=%s",
					p2);
				p += strlen(p);
			}

			if (host != NULL)
				relay = host;
			else
				relay = macvalue('_', e);
			if (relay != NULL)
			{
				(void) sm_snprintf(p, SPACELEFT(lbuf, p),
					", relay=%s", relay);
				p += strlen(p);
			}
			*p = '\0';
			if (discard)
				sm_syslog(LOG_NOTICE, logid,
					  "ruleset=%s, arg1=%s%s, discard",
					  rwset, p1, lbuf);
			else if (quarantine)
				sm_syslog(LOG_NOTICE, logid,
					  "ruleset=%s, arg1=%s%s, quarantine=%s",
					  rwset, p1, lbuf, ubuf);
			else
				sm_syslog(LOG_NOTICE, logid,
					  "ruleset=%s, arg1=%s%s, reject=%s",
					  rwset, p1, lbuf, MsgBuf);
		}

	 finis: ;
	}
	SM_FINALLY
	{
		/* clean up */
		if (buf != buf0)
			sm_free(buf);
		QuickAbort = saveQuickAbort;
	}
	SM_END_TRY

	setstat(rstat);

	/* rulesets don't set errno */
	errno = 0;
	if (rstat != EX_OK && QuickAbort)
		sm_exc_raisenew_x(&EtypeQuickAbort, 2);
	return rstat;
}
/*
**  RSCAP -- call rewriting set to return capabilities
**
**	Parameters:
**		rwset -- the rewriting set to use.
**		p1 -- the first string to check.
**		p2 -- the second string to check -- may be null.
**		e -- the current envelope.
**		pvp -- pointer to token vector.
**		pvpbuf -- buffer space.
**		size -- size of buffer space.
**
**	Returns:
**		EX_UNAVAILABLE -- ruleset doesn't exist.
**		EX_DATAERR -- prescan() failed.
**		EX_OK -- rewrite() was successful.
**		else -- return status from rewrite().
*/

int
rscap(rwset, p1, p2, e, pvp, pvpbuf, size)
	char *rwset;
	char *p1;
	char *p2;
	ENVELOPE *e;
	char ***pvp;
	char *pvpbuf;
	int size;
{
	char *volatile buf;
	size_t bufsize;
	int volatile rstat = EX_OK;
	int rsno;
	bool saveQuickAbort = QuickAbort;
	bool saveSuprErrs = SuprErrs;
	char buf0[MAXLINE];
	extern char MsgBuf[];

	if (tTd(48, 2))
		sm_dprintf("rscap(%s, %s, %s)\n", rwset, p1,
			p2 == NULL ? "(NULL)" : p2);

	SM_REQUIRE(pvp != NULL);
	rsno = strtorwset(rwset, NULL, ST_FIND);
	if (rsno < 0)
		return EX_UNAVAILABLE;

	if (p2 != NULL)
	{
		bufsize = strlen(p1) + strlen(p2) + 2;
		if (bufsize > sizeof(buf0))
			buf = sm_malloc_x(bufsize);
		else
		{
			buf = buf0;
			bufsize = sizeof(buf0);
		}
		(void) sm_snprintf(buf, bufsize, "%s%c%s", p1, CONDELSE, p2);
	}
	else
	{
		bufsize = strlen(p1) + 1;
		if (bufsize > sizeof(buf0))
			buf = sm_malloc_x(bufsize);
		else
		{
			buf = buf0;
			bufsize = sizeof(buf0);
		}
		(void) sm_strlcpy(buf, p1, bufsize);
	}
	SM_TRY
	{
		SuprErrs = true;
		QuickAbort = false;
		*pvp = prescan(buf, '\0', pvpbuf, size, NULL, IntTokenTab,
				false);
		if (*pvp != NULL)
			rstat = rewrite(*pvp, rsno, 0, e, size);
		else
		{
			if (tTd(48, 2))
				sm_dprintf("rscap: cannot prescan input\n");
			rstat = EX_DATAERR;
		}
	}
	SM_FINALLY
	{
		/* clean up */
		if (buf != buf0)
			sm_free(buf);
		SuprErrs = saveSuprErrs;
		QuickAbort = saveQuickAbort;

		/* prevent information leak, this may contain rewrite error */
		MsgBuf[0] = '\0';
	}
	SM_END_TRY
	return rstat;
}