[0001]
[0002]
[0003]
[0004]
[0005]
[0006]
[0007]
[0008]
[0009]
[0010]
[0011]
[0012]
[0013]
[0014]
[0015]
[0016]
[0017]
[0018]
[0019]
[0020]
[0021]
[0022]
[0023]
[0024]
[0025]
[0026]
[0027]
[0028]
[0029]
[0030]
[0031]
[0032]
[0033]
[0034]
[0035]
[0036]
[0037]
[0038]
[0039]
[0040]
[0041]
[0042]
[0043]
[0044]
[0045]
[0046]
[0047]
[0048]
[0049]
[0050]
[0051]
[0052]
[0053]
[0054]
[0055]
[0056]
[0057]
[0058]
[0059]
[0060]
[0061]
[0062]
[0063]
[0064]
[0065]
[0066]
[0067]
[0068]
[0069]
[0070]
[0071]
[0072]
[0073]
[0074]
[0075]
[0076]
[0077]
[0078]
[0079]
[0080]
[0081]
[0082]
[0083]
[0084]
[0085]
[0086]
[0087]
[0088]
[0089]
[0090]
[0091]
[0092]
[0093]
[0094]
[0095]
[0096]
[0097]
[0098]
[0099]
[0100]
[0101]
[0102]
[0103]
[0104]
[0105]
[0106]
[0107]
[0108]
[0109]
[0110]
[0111]
[0112]
[0113]
[0114]
[0115]
[0116]
[0117]
[0118]
[0119]
[0120]
[0121]
[0122]
[0123]
[0124]
[0125]
[0126]
[0127]
[0128]
[0129]
[0130]
[0131]
[0132]
[0133]
[0134]
[0135]
[0136]
[0137]
[0138]
[0139]
[0140]
[0141]
[0142]
[0143]
[0144]
[0145]
[0146]
[0147]
[0148]
[0149]
[0150]
[0151]
[0152]
[0153]
[0154]
[0155]
[0156]
[0157]
[0158]
[0159]
[0160]
[0161]
[0162]
[0163]
[0164]
[0165]
[0166]
[0167]
[0168]
[0169]
[0170]
[0171]
[0172]
[0173]
[0174]
[0175]
[0176]
[0177]
[0178]
[0179]
[0180]
[0181]
[0182]
[0183]
[0184]
[0185]
[0186]
[0187]
[0188]
[0189]
[0190]
[0191]
[0192]
[0193]
[0194]
[0195]
[0196]
[0197]
[0198]
[0199]
[0200]
[0201]
[0202]
[0203]
[0204]
[0205]
[0206]
[0207]
[0208]
[0209]
[0210]
[0211]
[0212]
[0213]
[0214]
[0215]
[0216]
[0217]
[0218]
[0219]
[0220]
[0221]
[0222]
[0223]
[0224]
[0225]
[0226]
[0227]
[0228]
[0229]
[0230]
[0231]
[0232]
[0233]
[0234]
[0235]
[0236]
[0237]
[0238]
[0239]
[0240]
[0241]
[0242]
[0243]
[0244]
[0245]
[0246]
[0247]
[0248]
[0249]
[0250]
[0251]
[0252]
[0253]
[0254]
[0255]
[0256]
[0257]
[0258]
[0259]
[0260]
[0261]
[0262]
[0263]
[0264]
[0265]
[0266]
[0267]
[0268]
[0269]
[0270]
[0271]
[0272]
[0273]
[0274]
[0275]
[0276]
[0277]
[0278]
[0279]
[0280]
[0281]
[0282]
[0283]
[0284]
[0285]
[0286]
[0287]
[0288]
[0289]
[0290]
[0291]
[0292]
[0293]
[0294]
[0295]
[0296]
[0297]
[0298]
[0299]
[0300]
[0301]
[0302]
[0303]
[0304]
[0305]
[0306]
[0307]
[0308]
[0309]
[0310]
[0311]
[0312]
[0313]
[0314]
[0315]
[0316]
[0317]
[0318]
[0319]
[0320]
[0321]
[0322]
[0323]
[0324]
[0325]
[0326]
[0327]
[0328]
[0329]
[0330]
[0331]
[0332]
[0333]
[0334]
[0335]
[0336]
[0337]
[0338]
[0339]
[0340]
[0341]
[0342]
[0343]
[0344]
[0345]
[0346]
[0347]
[0348]
[0349]
[0350]
[0351]
[0352]
[0353]
[0354]
[0355]
[0356]
[0357]
[0358]
[0359]
[0360]
[0361]
[0362]
[0363]
[0364]
[0365]
[0366]
[0367]
[0368]
[0369]
[0370]
[0371]
[0372]
[0373]
[0374]
[0375]
[0376]
[0377]
[0378]
[0379]
[0380]
[0381]
[0382]
[0383]
[0384]
[0385]
[0386]
[0387]
[0388]
[0389]
[0390]
[0391]
[0392]
[0393]
[0394]
[0395]
[0396]
[0397]
[0398]
[0399]
[0400]
[0401]
[0402]
[0403]
[0404]
[0405]
[0406]
[0407]
[0408]
[0409]
[0410]
[0411]
[0412]
[0413]
[0414]
[0415]
[0416]
[0417]
[0418]
[0419]
[0420]
[0421]
[0422]
[0423]
[0424]
[0425]
[0426]
[0427]
[0428]
[0429]
[0430]
[0431]
[0432]
[0433]
[0434]
[0435]
[0436]
[0437]
[0438]
[0439]
[0440]
[0441]
[0442]
[0443]
[0444]
[0445]
[0446]
[0447]
[0448]
[0449]
[0450]
[0451]
[0452]
[0453]
[0454]
[0455]
[0456]
[0457]
[0458]
[0459]
[0460]
[0461]
[0462]
[0463]
[0464]
[0465]
[0466]
[0467]
[0468]
[0469]
[0470]
[0471]
[0472]
[0473]
[0474]
[0475]
[0476]
[0477]
[0478]
[0479]
[0480]
[0481]
[0482]
[0483]
[0484]
[0485]
[0486]
[0487]
[0488]
[0489]
[0490]
[0491]
[0492]
[0493]
[0494]
[0495]
[0496]
[0497]
[0498]
[0499]
[0500]
[0501]
[0502]
[0503]
[0504]
[0505]
[0506]
[0507]
[0508]
[0509]
[0510]
[0511]
[0512]
[0513]
[0514]
[0515]
[0516]
[0517]
[0518]
[0519]
[0520]
[0521]
[0522]
[0523]
[0524]
[0525]
[0526]
[0527]
[0528]
[0529]
[0530]
[0531]
[0532]
[0533]
[0534]
[0535]
[0536]
[0537]
[0538]
[0539]
[0540]
[0541]
[0542]
[0543]
[0544]
[0545]
[0546]
[0547]
[0548]
[0549]
[0550]
[0551]
[0552]
[0553]
[0554]
[0555]
[0556]
[0557]
[0558]
[0559]
[0560]
[0561]
[0562]
[0563]
[0564]
[0565]
[0566]
[0567]
[0568]
[0569]
[0570]
[0571]
[0572]
[0573]
[0574]
[0575]
[0576]
[0577]
[0578]
[0579]
[0580]
[0581]
[0582]
[0583]
[0584]
[0585]
[0586]
[0587]
[0588]
[0589]
[0590]
[0591]
[0592]
[0593]
[0594]
[0595]
[0596]
[0597]
[0598]
[0599]
[0600]
[0601]
[0602]
[0603]
[0604]
[0605]
[0606]
[0607]
[0608]
[0609]
[0610]
[0611]
[0612]
[0613]
[0614]
[0615]
[0616]
[0617]
[0618]
[0619]
[0620]
[0621]
[0622]
[0623]
[0624]
[0625]
[0626]
[0627]
[0628]
[0629]
[0630]
[0631]
[0632]
[0633]
[0634]
[0635]
[0636]
[0637]
[0638]
[0639]
[0640]
[0641]
[0642]
[0643]
[0644]
[0645]
[0646]
[0647]
[0648]
[0649]
[0650]
[0651]
[0652]
[0653]
[0654]
[0655]
[0656]
[0657]
[0658]
[0659]
[0660]
[0661]
[0662]
[0663]
[0664]
[0665]
[0666]
[0667]
[0668]
[0669]
[0670]
[0671]
[0672]
[0673]
[0674]
[0675]
[0676]
[0677]
[0678]
[0679]
[0680]
[0681]
[0682]
[0683]
[0684]
[0685]
[0686]
[0687]
[0688]
[0689]
[0690]
[0691]
[0692]
[0693]
[0694]
[0695]
[0696]
[0697]
[0698]
[0699]
[0700]
[0701]
[0702]
[0703]
[0704]
[0705]
[0706]
[0707]
[0708]
[0709]
[0710]
[0711]
[0712]
[0713]
[0714]
[0715]
[0716]
[0717]
[0718]
[0719]
[0720]
[0721]
[0722]
[0723]
[0724]
[0725]
[0726]
[0727]
[0728]
[0729]
[0730]
[0731]
[0732]
[0733]
[0734]
[0735]
[0736]
[0737]
[0738]
[0739]
[0740]
[0741]
[0742]
[0743]
[0744]
[0745]
[0746]
[0747]
[0748]
[0749]
[0750]
[0751]
[0752]
[0753]
[0754]
[0755]
[0756]
[0757]
[0758]
[0759]
[0760]
[0761]
[0762]
[0763]
[0764]
[0765]
[0766]
[0767]
[0768]
[0769]
[0770]
[0771]
[0772]
[0773]
[0774]
[0775]
[0776]
[0777]
[0778]
[0779]
[0780]
[0781]
[0782]
[0783]
[0784]
[0785]
[0786]
[0787]
[0788]
[0789]
[0790]
[0791]
[0792]
[0793]
[0794]
[0795]
[0796]
[0797]
[0798]
[0799]
[0800]
[0801]
[0802]
[0803]
[0804]
[0805]
[0806]
[0807]
[0808]
[0809]
[0810]
[0811]
[0812]
[0813]
[0814]
[0815]
[0816]
[0817]
[0818]
[0819]
[0820]
[0821]
[0822]
[0823]
[0824]
[0825]
[0826]
[0827]
[0828]
[0829]
[0830]
[0831]
[0832]
[0833]
[0834]
[0835]
[0836]
[0837]
[0838]
[0839]
[0840]
[0841]
[0842]
[0843]
[0844]
[0845]
[0846]
[0847]
[0848]
[0849]
[0850]
[0851]
[0852]
[0853]
[0854]
[0855]
[0856]
[0857]
[0858]
[0859]
[0860]
[0861]
[0862]
[0863]
[0864]
[0865]
[0866]
[0867]
[0868]
[0869]
[0870]
[0871]
[0872]
[0873]
[0874]
[0875]
[0876]
[0877]
[0878]
[0879]
[0880]
[0881]
[0882]
[0883]
[0884]
[0885]
[0886]
[0887]
[0888]
[0889]
[0890]
[0891]
[0892]
[0893]
[0894]
[0895]
[0896]
[0897]
[0898]
[0899]
[0900]
[0901]
[0902]
[0903]
[0904]
[0905]
[0906]
[0907]
[0908]
[0909]
[0910]
[0911]
[0912]
[0913]
[0914]
[0915]
[0916]
[0917]
[0918]
[0919]
[0920]
[0921]
[0922]
[0923]
[0924]
[0925]
[0926]
[0927]
[0928]
[0929]
[0930]
[0931]
[0932]
[0933]
[0934]
[0935]
[0936]
[0937]
[0938]
[0939]
[0940]
[0941]
[0942]
[0943]
[0944]
[0945]
[0946]
[0947]
[0948]
[0949]
[0950]
[0951]
[0952]
[0953]
[0954]
[0955]
[0956]
[0957]
[0958]
[0959]
[0960]
[0961]
[0962]
[0963]
[0964]
[0965]
[0966]
[0967]
[0968]
[0969]
[0970]
[0971]
[0972]
[0973]
[0974]
[0975]
[0976]
[0977]
[0978]
[0979]
[0980]
[0981]
[0982]
[0983]
[0984]
[0985]
[0986]
[0987]
[0988]
[0989]
[0990]
[0991]
[0992]
[0993]
[0994]
[0995]
[0996]
[0997]
[0998]
[0999]
[1000]
[1001]
[1002]
[1003]
[1004]
[1005]
[1006]
[1007]
[1008]
[1009]
[1010]
[1011]
[1012]
[1013]
[1014]
[1015]
[1016]
[1017]
[1018]
[1019]
[1020]
[1021]
[1022]
[1023]
[1024]
[1025]
[1026]
[1027]
[1028]
[1029]
[1030]
[1031]
[1032]
[1033]
[1034]
[1035]
[1036]
[1037]
[1038]
[1039]
[1040]
[1041]
[1042]
[1043]
[1044]
[1045]
[1046]
[1047]
[1048]
[1049]
[1050]
[1051]
[1052]
[1053]
[1054]
[1055]
[1056]
[1057]
[1058]
[1059]
[1060]
[1061]
[1062]
[1063]
[1064]
[1065]
[1066]
[1067]
[1068]
[1069]
[1070]
[1071]
[1072]
[1073]
[1074]
[1075]
[1076]
[1077]
[1078]
[1079]
[1080]
[1081]
[1082]
[1083]
[1084]
[1085]
[1086]
[1087]
[1088]
[1089]
[1090]
[1091]
[1092]
[1093]
[1094]
[1095]
[1096]
[1097]
[1098]
[1099]
[1100]
[1101]
[1102]
[1103]
[1104]
[1105]
[1106]
[1107]
[1108]
[1109]
[1110]
[1111]
[1112]
[1113]
[1114]
[1115]
[1116]
[1117]
[1118]
[1119]
[1120]
[1121]
[1122]
[1123]
[1124]
[1125]
[1126]
[1127]
[1128]
[1129]
[1130]
[1131]
[1132]
[1133]
[1134]
[1135]
[1136]
[1137]
[1138]
[1139]
[1140]
[1141]
[1142]
[1143]
[1144]
[1145]
[1146]
[1147]
[1148]
[1149]
[1150]
[1151]
[1152]
[1153]
[1154]
[1155]
[1156]
[1157]
[1158]
[1159]
[1160]
[1161]
[1162]
[1163]
[1164]
[1165]
[1166]
[1167]
[1168]
[1169]
[1170]
[1171]
[1172]
[1173]
[1174]
[1175]
[1176]
[1177]
[1178]
[1179]
[1180]
[1181]
[1182]
[1183]
[1184]
[1185]
[1186]
[1187]
[1188]
[1189]
[1190]
[1191]
[1192]
[1193]
[1194]
[1195]
[1196]
[1197]
[1198]
[1199]
[1200]
[1201]
[1202]
[1203]
[1204]
[1205]
[1206]
[1207]
[1208]
[1209]
[1210]
[1211]
[1212]
[1213]
[1214]
[1215]
[1216]
[1217]
[1218]
[1219]
[1220]
[1221]
[1222]
[1223]
[1224]
[1225]
[1226]
[1227]
[1228]
[1229]
[1230]
[1231]
[1232]
[1233]
[1234]
[1235]
[1236]
[1237]
[1238]
[1239]
[1240]
[1241]
[1242]
[1243]
[1244]
[1245]
[1246]
[1247]
[1248]
[1249]
[1250]
[1251]
[1252]
[1253]
[1254]
[1255]
[1256]
[1257]
[1258]
[1259]
[1260]
[1261]
[1262]
[1263]
[1264]
[1265]
[1266]
[1267]
[1268]
[1269]
[1270]
[1271]
[1272]
[1273]
[1274]
[1275]
[1276]
[1277]
[1278]
[1279]
[1280]
[1281]
[1282]
[1283]
[1284]
[1285]
[1286]
[1287]
[1288]
[1289]
[1290]
[1291]
[1292]
[1293]
[1294]
[1295]
[1296]
[1297]
[1298]
[1299]
[1300]
[1301]
[1302]
[1303]
[1304]
[1305]
[1306]
[1307]
[1308]
[1309]
[1310]
[1311]
[1312]
[1313]
[1314]
[1315]
[1316]
[1317]
[1318]
[1319]
[1320]
[1321]
[1322]
[1323]
[1324]
[1325]
[1326]
[1327]
[1328]
[1329]
[1330]
[1331]
[1332]
[1333]
[1334]
[1335]
[1336]
[1337]
[1338]
[1339]
[1340]
[1341]
[1342]
[1343]
[1344]
[1345]
[1346]
[1347]
[1348]
[1349]
[1350]
[1351]
[1352]
[1353]
[1354]
[1355]
[1356]
[1357]
[1358]
[1359]
[1360]
[1361]
[1362]
[1363]
[1364]
[1365]
[1366]
[1367]
[1368]
[1369]
[1370]
[1371]
[1372]
[1373]
[1374]
[1375]
[1376]
[1377]
[1378]
[1379]
[1380]
[1381]
[1382]
[1383]
[1384]
[1385]
[1386]
[1387]
[1388]
[1389]
[1390]
[1391]
[1392]
[1393]
[1394]
[1395]
[1396]
[1397]
[1398]
[1399]
[1400]
[1401]
[1402]
[1403]
[1404]
[1405]
[1406]
[1407]
[1408]
[1409]
[1410]
[1411]
[1412]
[1413]
[1414]
[1415]
[1416]
[1417]
[1418]
[1419]
[1420]
[1421]
[1422]
[1423]
[1424]
[1425]
[1426]
[1427]
[1428]
[1429]
[1430]
[1431]
[1432]
[1433]
[1434]
[1435]
[1436]
[1437]
[1438]
[1439]
[1440]
[1441]
[1442]
[1443]
[1444]
[1445]
[1446]
[1447]
[1448]
[1449]
[1450]
[1451]
[1452]
[1453]
[1454]
[1455]
[1456]
[1457]
[1458]
[1459]
[1460]
[1461]
[1462]
[1463]
[1464]
[1465]
[1466]
[1467]
[1468]
[1469]
[1470]
[1471]
[1472]
[1473]
[1474]
[1475]
[1476]
[1477]
[1478]
[1479]
[1480]
[1481]
[1482]
[1483]
[1484]
[1485]
[1486]
[1487]
[1488]
[1489]
[1490]
[1491]
[1492]
[1493]
[1494]
[1495]
[1496]
[1497]
[1498]
[1499]
[1500]
[1501]
[1502]
[1503]
[1504]
[1505]
[1506]
[1507]
[1508]
[1509]
[1510]
[1511]
[1512]
[1513]
[1514]
[1515]
[1516]
[1517]
[1518]
[1519]
[1520]
[1521]
[1522]
[1523]
[1524]
[1525]
[1526]
[1527]
[1528]
[1529]
[1530]
[1531]
[1532]
[1533]
[1534]
[1535]
[1536]
[1537]
[1538]
[1539]
[1540]
[1541]
[1542]
[1543]
[1544]
[1545]
[1546]
[1547]
[1548]
[1549]
[1550]
[1551]
[1552]
[1553]
[1554]
[1555]
[1556]
[1557]
[1558]
[1559]
[1560]
[1561]
[1562]
[1563]
[1564]
[1565]
[1566]
[1567]
[1568]
[1569]
[1570]
[1571]
[1572]
[1573]
[1574]
[1575]
[1576]
[1577]
[1578]
[1579]
[1580]
[1581]
[1582]
[1583]
[1584]
[1585]
[1586]
[1587]
[1588]
[1589]
[1590]
[1591]
[1592]
[1593]
[1594]
[1595]
[1596]
[1597]
[1598]
[1599]
[1600]
[1601]
[1602]
[1603]
[1604]
[1605]
[1606]
[1607]
[1608]
[1609]
[1610]
[1611]
[1612]
[1613]
[1614]
[1615]
[1616]
[1617]
[1618]
[1619]
[1620]
[1621]
[1622]
[1623]
[1624]
[1625]
[1626]
[1627]
[1628]
[1629]
[1630]
[1631]
[1632]
[1633]
[1634]
[1635]
[1636]
[1637]
[1638]
[1639]
[1640]
[1641]
[1642]
[1643]
[1644]
[1645]
[1646]
[1647]
[1648]
[1649]
[1650]
[1651]
[1652]
[1653]
[1654]
[1655]
[1656]
[1657]
[1658]
[1659]
[1660]
[1661]
[1662]
[1663]
[1664]
[1665]
[1666]
[1667]
[1668]
[1669]
[1670]
[1671]
[1672]
[1673]
[1674]
[1675]
[1676]
[1677]
[1678]
[1679]
[1680]
[1681]
[1682]
[1683]
[1684]
[1685]
[1686]
[1687]
[1688]
[1689]
[1690]
[1691]
[1692]
[1693]
[1694]
[1695]
[1696]
[1697]
[1698]
[1699]
[1700]
[1701]
[1702]
[1703]
[1704]
[1705]
[1706]
[1707]
[1708]
[1709]
[1710]
[1711]
[1712]
[1713]
[1714]
[1715]
[1716]
[1717]
[1718]
[1719]
[1720]
[1721]
[1722]
[1723]
[1724]
[1725]
[1726]
[1727]
[1728]
[1729]
[1730]
[1731]
[1732]
[1733]
[1734]
[1735]
[1736]
[1737]
[1738]
[1739]
[1740]
[1741]
[1742]
[1743]
[1744]
[1745]
[1746]
[1747]
[1748]
[1749]
[1750]
[1751]
[1752]
[1753]
[1754]
[1755]
[1756]
[1757]
[1758]
[1759]
[1760]
[1761]
[1762]
[1763]
[1764]
[1765]
[1766]
[1767]
[1768]
[1769]
[1770]
[1771]
[1772]
[1773]
[1774]
[1775]
[1776]
[1777]
[1778]
[1779]
[1780]
[1781]
[1782]
[1783]
[1784]
[1785]
[1786]
[1787]
[1788]
[1789]
[1790]
[1791]
[1792]
[1793]
[1794]
[1795]
[1796]
[1797]
[1798]
[1799]
[1800]
[1801]
[1802]
[1803]
[1804]
[1805]
[1806]
[1807]
[1808]
[1809]
[1810]
[1811]
[1812]
[1813]
[1814]
[1815]
[1816]
[1817]
[1818]
[1819]
[1820]
[1821]
[1822]
[1823]
[1824]
[1825]
[1826]
[1827]
[1828]
[1829]
[1830]
[1831]
[1832]
[1833]
[1834]
[1835]
[1836]
[1837]
[1838]
[1839]
[1840]
[1841]
[1842]
[1843]
[1844]
[1845]
[1846]
[1847]
[1848]
[1849]
[1850]
[1851]
[1852]
[1853]
[1854]
[1855]
[1856]
[1857]
[1858]
[1859]
[1860]
[1861]
[1862]
[1863]
[1864]
[1865]
[1866]
[1867]
[1868]
[1869]
[1870]
[1871]
[1872]
[1873]
[1874]
[1875]
[1876]
[1877]
[1878]
[1879]
[1880]
[1881]
[1882]
[1883]
[1884]
[1885]
[1886]
[1887]
[1888]
[1889]
[1890]
[1891]
[1892]
[1893]
[1894]
[1895]
[1896]
[1897]
[1898]
[1899]
[1900]
[1901]
[1902]
[1903]
[1904]
[1905]
[1906]
[1907]
[1908]
[1909]
[1910]
[1911]
[1912]
[1913]
[1914]
[1915]
[1916]
[1917]
[1918]
[1919]
[1920]
[1921]
[1922]
[1923]
[1924]
[1925]
[1926]
[1927]
[1928]
[1929]
[1930]
[1931]
[1932]
[1933]
[1934]
[1935]
[1936]
[1937]
[1938]
[1939]
[1940]
[1941]
[1942]
[1943]
[1944]
[1945]
[1946]
[1947]
[1948]
[1949]
[1950]
[1951]
[1952]
[1953]
[1954]
[1955]
[1956]
[1957]
[1958]
[1959]
[1960]
[1961]
[1962]
[1963]
[1964]
[1965]
[1966]
[1967]
[1968]
[1969]
[1970]
[1971]
[1972]
[1973]
[1974]
[1975]
[1976]
[1977]
[1978]
[1979]
[1980]
[1981]
[1982]
[1983]
[1984]
[1985]
[1986]
[1987]
[1988]
[1989]
[1990]
[1991]
[1992]
[1993]
[1994]
[1995]
[1996]
[1997]
[1998]
[1999]
[2000]
[2001]
[2002]
[2003]
[2004]
[2005]
[2006]
[2007]
[2008]
[2009]
[2010]
[2011]
[2012]
[2013]
[2014]
[2015]
[2016]
[2017]
[2018]
[2019]
[2020]
[2021]
[2022]
[2023]
[2024]
[2025]
[2026]
[2027]
[2028]
[2029]
[2030]
[2031]
[2032]
[2033]
[2034]
[2035]
[2036]
[2037]
[2038]
[2039]
[2040]
[2041]
[2042]
[2043]
[2044]
[2045]
[2046]
[2047]
[2048]
[2049]
[2050]
[2051]
[2052]
[2053]
[2054]
[2055]
[2056]
[2057]
[2058]
[2059]
[2060]
[2061]
[2062]
[2063]
[2064]
[2065]
[2066]
[2067]
[2068]
[2069]
[2070]
[2071]
[2072]
[2073]
[2074]
[2075]
[2076]
[2077]
[2078]
[2079]
[2080]
[2081]
[2082]
[2083]
[2084]
[2085]
[2086]
[2087]
[2088]
[2089]
[2090]
[2091]
[2092]
[2093]
[2094]
[2095]
[2096]
[2097]
[2098]
[2099]
[2100]
[2101]
[2102]
[2103]
[2104]
[2105]
[2106]
[2107]
[2108]
[2109]
[2110]
[2111]
[2112]
[2113]
[2114]
[2115]
[2116]
[2117]
[2118]
[2119]
[2120]
[2121]
[2122]
[2123]
[2124]
[2125]
[2126]
[2127]
[2128]
[2129]
[2130]
[2131]
[2132]
[2133]
[2134]
[2135]
[2136]
[2137]
[2138]
[2139]
[2140]
[2141]
[2142]
[2143]
[2144]
[2145]
[2146]
[2147]
[2148]
[2149]
[2150]
[2151]
[2152]
[2153]
[2154]
[2155]
[2156]
[2157]
[2158]
[2159]
[2160]
[2161]
[2162]
[2163]
[2164]
[2165]
[2166]
[2167]
[2168]
[2169]
[2170]
[2171]
[2172]
[2173]
[2174]
[2175]
[2176]
[2177]
[2178]
[2179]
[2180]
[2181]
[2182]
[2183]
[2184]
[2185]
[2186]
[2187]
[2188]
[2189]
[2190]
[2191]
[2192]
[2193]
[2194]
[2195]
[2196]
[2197]
[2198]
[2199]
[2200]
[2201]
[2202]
[2203]
[2204]
[2205]
[2206]
[2207]
[2208]
[2209]
[2210]
[2211]
[2212]
[2213]
[2214]
[2215]
[2216]
[2217]
[2218]
[2219]
[2220]
[2221]
[2222]
[2223]
[2224]
[2225]
[2226]
[2227]
[2228]
[2229]
[2230]
[2231]
[2232]
[2233]
[2234]
[2235]
[2236]
[2237]
[2238]
[2239]
[2240]
[2241]
[2242]
[2243]
[2244]
[2245]
[2246]
[2247]
[2248]
[2249]
[2250]
[2251]
[2252]
[2253]
[2254]
[2255]
[2256]
[2257]
[2258]
[2259]
[2260]
[2261]
[2262]
[2263]
[2264]
[2265]
[2266]
[2267]
[2268]
[2269]
[2270]
[2271]
[2272]
[2273]
[2274]
[2275]
[2276]
[2277]
[2278]
[2279]
[2280]
[2281]
[2282]
[2283]
[2284]
[2285]
[2286]
[2287]
[2288]
[2289]
[2290]
[2291]
[2292]
[2293]
[2294]
[2295]
[2296]
[2297]
[2298]
[2299]
[2300]
[2301]
[2302]
[2303]
[2304]
[2305]
[2306]
[2307]
[2308]
[2309]
[2310]
[2311]
[2312]
[2313]
[2314]
[2315]
[2316]
[2317]
[2318]
[2319]
[2320]
[2321]
[2322]
[2323]
[2324]
[2325]
[2326]
[2327]
[2328]
[2329]
[2330]
[2331]
[2332]
[2333]
[2334]
[2335]
[2336]
[2337]
[2338]
[2339]
[2340]
[2341]
[2342]
[2343]
[2344]
[2345]
[2346]
[2347]
[2348]
[2349]
[2350]
[2351]
[2352]
[2353]
[2354]
[2355]
[2356]
[2357]
[2358]
[2359]
[2360]
[2361]
[2362]
[2363]
[2364]
[2365]
[2366]
[2367]
[2368]
[2369]
[2370]
[2371]
[2372]
[2373]
[2374]
[2375]
[2376]
[2377]
[2378]
[2379]
[2380]
[2381]
[2382]
[2383]
[2384]
[2385]
[2386]
[2387]
[2388]
[2389]
[2390]
[2391]
[2392]
[2393]
[2394]
[2395]
[2396]
[2397]
[2398]
[2399]
[2400]
[2401]
[2402]
[2403]
[2404]
[2405]
[2406]
[2407]
[2408]
[2409]
[2410]
[2411]
[2412]
[2413]
[2414]
[2415]
[2416]
[2417]
[2418]
[2419]
[2420]
[2421]
[2422]
[2423]
[2424]
[2425]
[2426]
[2427]
[2428]
[2429]
[2430]
[2431]
[2432]
[2433]
[2434]
[2435]
[2436]
[2437]
[2438]
[2439]
[2440]
[2441]
[2442]
[2443]
[2444]
[2445]
[2446]
[2447]
[2448]
[2449]
[2450]
[2451]
[2452]
[2453]
[2454]
[2455]
[2456]
[2457]
[2458]
[2459]
[2460]
[2461]
[2462]
[2463]
[2464]
[2465]
[2466]
[2467]
[2468]
[2469]
[2470]
[2471]
[2472]
[2473]
[2474]
[2475]
[2476]
[2477]
[2478]
[2479]
[2480]
[2481]
[2482]
[2483]
[2484]
[2485]
[2486]
[2487]
[2488]
[2489]
[2490]
[2491]
[2492]
[2493]
[2494]
[2495]
[2496]
[2497]
[2498]
[2499]
[2500]
[2501]
[2502]
[2503]
[2504]
[2505]
[2506]
[2507]
[2508]
[2509]
[2510]
[2511]
[2512]
[2513]
[2514]
[2515]
[2516]
[2517]
[2518]
[2519]
[2520]
[2521]
[2522]
[2523]
[2524]
[2525]
[2526]
[2527]
[2528]
[2529]
[2530]
[2531]
[2532]
[2533]
[2534]
[2535]
[2536]
[2537]
[2538]
[2539]
[2540]
[2541]
[2542]
[2543]
[2544]
[2545]
[2546]
[2547]
[2548]
[2549]
[2550]
[2551]
[2552]
[2553]
[2554]
[2555]
[2556]
[2557]
[2558]
[2559]
[2560]
[2561]
[2562]
[2563]
[2564]
[2565]
[2566]
[2567]
[2568]
[2569]
[2570]
[2571]
[2572]
[2573]
[2574]
[2575]
[2576]
[2577]
[2578]
[2579]
[2580]
[2581]
[2582]
[2583]
[2584]
[2585]
[2586]
[2587]
[2588]
[2589]
[2590]
[2591]
[2592]
[2593]
[2594]
[2595]
[2596]
[2597]
[2598]
[2599]
[2600]
[2601]
[2602]
[2603]
[2604]
[2605]
[2606]
[2607]
[2608]
[2609]
[2610]
[2611]
[2612]
[2613]
[2614]
[2615]
[2616]
[2617]
[2618]
[2619]
[2620]
[2621]
[2622]
[2623]
[2624]
[2625]
[2626]
[2627]
[2628]
[2629]
[2630]
[2631]
[2632]
[2633]
[2634]
[2635]
[2636]
[2637]
[2638]
[2639]
[2640]
[2641]
[2642]
[2643]
[2644]
[2645]
[2646]
[2647]
[2648]
[2649]
[2650]
[2651]
[2652]
[2653]
[2654]
[2655]
[2656]
[2657]
[2658]
[2659]
[2660]
[2661]
[2662]
[2663]
[2664]
[2665]
[2666]
[2667]
[2668]
[2669]
[2670]
[2671]
[2672]
[2673]
[2674]
[2675]
[2676]
[2677]
[2678]
[2679]
[2680]
[2681]
[2682]
[2683]
[2684]
[2685]
[2686]
[2687]
[2688]
[2689]
[2690]
[2691]
[2692]
[2693]
[2694]
[2695]
[2696]
[2697]
[2698]
[2699]
[2700]
[2701]
[2702]
[2703]
[2704]
[2705]
[2706]
[2707]
[2708]
[2709]
[2710]
[2711]
[2712]
[2713]
[2714]
[2715]
[2716]
[2717]
[2718]
[2719]
[2720]
[2721]
[2722]
[2723]
[2724]
[2725]
[2726]
[2727]
[2728]
[2729]
[2730]
[2731]
[2732]
[2733]
[2734]
[2735]
[2736]
[2737]
[2738]
[2739]
[2740]
[2741]
[2742]
[2743]
[2744]
[2745]
[2746]
[2747]
[2748]
[2749]
[2750]
[2751]
[2752]
[2753]
[2754]
[2755]
[2756]
[2757]
[2758]
[2759]
[2760]
[2761]
[2762]
[2763]
[2764]
[2765]
[2766]
[2767]
[2768]
[2769]
[2770]
[2771]
[2772]
[2773]
[2774]
[2775]
[2776]
[2777]
[2778]
[2779]
[2780]
[2781]
[2782]
[2783]
[2784]
[2785]
[2786]
[2787]
[2788]
[2789]
[2790]
[2791]
[2792]
[2793]
[2794]
[2795]
[2796]
[2797]
[2798]
[2799]
[2800]
[2801]
[2802]
[2803]
[2804]
[2805]
[2806]
[2807]
[2808]
[2809]
[2810]
[2811]
[2812]
[2813]
[2814]
[2815]
[2816]
[2817]
[2818]
[2819]
[2820]
[2821]
[2822]
[2823]
[2824]
[2825]
[2826]
[2827]
[2828]
[2829]
[2830]
[2831]
[2832]
[2833]
[2834]
[2835]
[2836]
[2837]
[2838]
[2839]
[2840]
[2841]
[2842]
[2843]
[2844]
[2845]
[2846]
[2847]
[2848]
[2849]
[2850]
[2851]
[2852]
[2853]
[2854]
[2855]
[2856]
[2857]
[2858]
[2859]
[2860]
[2861]
[2862]
[2863]
[2864]
[2865]
[2866]
[2867]
[2868]
[2869]
[2870]
[2871]
[2872]
[2873]
[2874]
[2875]
[2876]
[2877]
[2878]
[2879]
[2880]
[2881]
[2882]
[2883]
[2884]
[2885]
[2886]
[2887]
[2888]
[2889]
[2890]
[2891]
[2892]
[2893]
[2894]
[2895]
[2896]
[2897]
[2898]
[2899]
[2900]
[2901]
[2902]
[2903]
[2904]
[2905]
[2906]
[2907]
[2908]
[2909]
[2910]
[2911]
[2912]
[2913]
[2914]
[2915]
[2916]
[2917]
[2918]
[2919]
[2920]
[2921]
[2922]
[2923]
[2924]
[2925]
[2926]
[2927]
[2928]
[2929]
[2930]
[2931]
[2932]
[2933]
[2934]
[2935]
[2936]
[2937]
[2938]
[2939]
[2940]
[2941]
[2942]
[2943]
[2944]
[2945]
[2946]
[2947]
[2948]
[2949]
[2950]
[2951]
[2952]
[2953]
[2954]
[2955]
[2956]
[2957]
[2958]
[2959]
[2960]
[2961]
[2962]
[2963]
[2964]
[2965]
[2966]
[2967]
[2968]
[2969]
[2970]
[2971]
[2972]
[2973]
[2974]
[2975]
[2976]
[2977]
[2978]
[2979]
[2980]
[2981]
[2982]
[2983]
[2984]
[2985]
[2986]
[2987]
[2988]
[2989]
[2990]
[2991]
[2992]
[2993]
[2994]
[2995]
[2996]
[2997]
[2998]
[2999]
[3000]
[3001]
[3002]
[3003]
[3004]
[3005]
[3006]
[3007]
[3008]
[3009]
[3010]
[3011]
[3012]
[3013]
[3014]
[3015]
[3016]
[3017]
[3018]
[3019]
[3020]
[3021]
[3022]
[3023]
[3024]
[3025]
[3026]
[3027]
[3028]
[3029]
[3030]
[3031]
[3032]
[3033]
[3034]
[3035]
[3036]
[3037]
[3038]
[3039]
[3040]
[3041]
[3042]
[3043]
[3044]
[3045]
[3046]
[3047]
[3048]
[3049]
[3050]
[3051]
[3052]
[3053]
[3054]
[3055]
[3056]
[3057]
[3058]
[3059]
[3060]
[3061]
[3062]
[3063]
[3064]
[3065]
[3066]
[3067]
[3068]
[3069]
[3070]
[3071]
[3072]
[3073]
[3074]
[3075]
[3076]
[3077]
[3078]
[3079]
[3080]
[3081]
[3082]
[3083]
[3084]
[3085]
[3086]
[3087]
[3088]
[3089]
[3090]
[3091]
[3092]
[3093]
[3094]
[3095]
[3096]
[3097]
[3098]
[3099]
[3100]
[3101]
[3102]
[3103]
[3104]
[3105]
[3106]
[3107]
[3108]
[3109]
[3110]
[3111]
[3112]
[3113]
[3114]
[3115]
[3116]
[3117]
[3118]
[3119]
[3120]
[3121]
[3122]
[3123]
[3124]
[3125]
[3126]
[3127]
[3128]
[3129]
[3130]
[3131]
[3132]
[3133]
[3134]
[3135]
[3136]
[3137]
[3138]
[3139]
[3140]
[3141]
[3142]
[3143]
[3144]
[3145]
[3146]
[3147]
[3148]
[3149]
[3150]
[3151]
[3152]
[3153]
[3154]
[3155]
[3156]
[3157]
[3158]
[3159]
[3160]
[3161]
[3162]
[3163]
[3164]
[3165]
[3166]
[3167]
[3168]
[3169]
[3170]
[3171]
[3172]
[3173]
[3174]
[3175]
[3176]
[3177]
[3178]
[3179]
[3180]
[3181]
[3182]
[3183]
[3184]
[3185]
[3186]
[3187]
[3188]
[3189]
[3190]
[3191]
[3192]
[3193]
[3194]
[3195]
[3196]
[3197]
[3198]
[3199]
[3200]
[3201]
[3202]
[3203]
[3204]
[3205]
[3206]
[3207]
[3208]
[3209]
[3210]
[3211]
[3212]
[3213]
[3214]
[3215]
[3216]
[3217]
[3218]
[3219]
[3220]
[3221]
[3222]
[3223]
[3224]
[3225]
[3226]
[3227]
[3228]
[3229]
[3230]
[3231]
[3232]
[3233]
[3234]
[3235]
[3236]
[3237]
[3238]
[3239]
[3240]
[3241]
[3242]
[3243]
[3244]
[3245]
[3246]
[3247]
[3248]
[3249]
[3250]
[3251]
[3252]
[3253]
[3254]
[3255]
[3256]
[3257]
[3258]
[3259]
[3260]
[3261]
[3262]
[3263]
[3264]
[3265]
[3266]
[3267]
[3268]
[3269]
[3270]
[3271]
[3272]
[3273]
[3274]
[3275]
[3276]
[3277]
[3278]
[3279]
[3280]
[3281]
[3282]
[3283]
[3284]
[3285]
[3286]
[3287]
[3288]
[3289]
[3290]
[3291]
[3292]
[3293]
[3294]
[3295]
[3296]
[3297]
[3298]
[3299]
[3300]
[3301]
[3302]
[3303]
[3304]
[3305]
[3306]
[3307]
[3308]
[3309]
[3310]
[3311]
[3312]
[3313]
[3314]
[3315]
[3316]
[3317]
[3318]
[3319]
[3320]
[3321]
[3322]
[3323]
[3324]
[3325]
[3326]
[3327]
[3328]
[3329]
[3330]
[3331]
[3332]
[3333]
[3334]
[3335]
[3336]
[3337]
[3338]
[3339]
[3340]
[3341]
[3342]
[3343]
[3344]
[3345]
[3346]
[3347]
[3348]
[3349]
[3350]
[3351]
[3352]
[3353]
[3354]
[3355]
[3356]
[3357]
[3358]
[3359]
[3360]
[3361]
[3362]
[3363]
[3364]
[3365]
[3366]
[3367]
[3368]
[3369]
[3370]
[3371]
[3372]
[3373]
[3374]
[3375]
[3376]
[3377]
[3378]
[3379]
[3380]
[3381]
[3382]
[3383]
[3384]
[3385]
[3386]
[3387]
[3388]
[3389]
[3390]
[3391]
[3392]
[3393]
[3394]
[3395]
[3396]
[3397]
[3398]
[3399]
[3400]
[3401]
[3402]
[3403]
[3404]
[3405]
[3406]
[3407]
[3408]
[3409]
[3410]
[3411]
[3412]
[3413]
[3414]
[3415]
[3416]
[3417]
[3418]
[3419]
[3420]
[3421]
[3422]
[3423]
[3424]
[3425]
[3426]
[3427]
[3428]
[3429]
[3430]
[3431]
[3432]
[3433]
[3434]
[3435]
[3436]
[3437]
[3438]
[3439]
[3440]
[3441]
[3442]
[3443]
[3444]
[3445]
[3446]
[3447]
[3448]
[3449]
[3450]
[3451]
[3452]
[3453]
[3454]
[3455]
[3456]
[3457]
[3458]
[3459]
[3460]
[3461]
[3462]
[3463]
[3464]
[3465]
[3466]
[3467]
[3468]
[3469]
[3470]
[3471]
[3472]
[3473]
[3474]
[3475]
[3476]
[3477]
[3478]
[3479]
[3480]
[3481]
[3482]
[3483]
[3484]
[3485]
[3486]
[3487]
[3488]
[3489]
[3490]
[3491]
[3492]
[3493]
[3494]
[3495]
[3496]
[3497]
[3498]
[3499]
[3500]
[3501]
[3502]
[3503]
[3504]
[3505]
[3506]
[3507]
[3508]
[3509]
[3510]
[3511]
[3512]
[3513]
[3514]
[3515]
[3516]
[3517]
[3518]
[3519]
[3520]
[3521]
[3522]
[3523]
[3524]
[3525]
[3526]
[3527]
[3528]
[3529]
[3530]
[3531]
[3532]
[3533]
[3534]
[3535]
[3536]
[3537]
[3538]
[3539]
[3540]
[3541]
[3542]
[3543]
[3544]
[3545]
[3546]
[3547]
[3548]
[3549]
[3550]
[3551]
[3552]
[3553]
[3554]
[3555]
[3556]
[3557]
[3558]
[3559]
[3560]
[3561]
[3562]
[3563]
[3564]
[3565]
[3566]
[3567]
[3568]
[3569]
[3570]
[3571]
[3572]
[3573]
[3574]
[3575]
[3576]
[3577]
[3578]
[3579]
[3580]
[3581]
[3582]
[3583]
[3584]
[3585]
[3586]
[3587]
[3588]
[3589]
[3590]
[3591]
[3592]
[3593]
[3594]
[3595]
[3596]
[3597]
[3598]
[3599]
[3600]
[3601]
[3602]
[3603]
[3604]
[3605]
[3606]
[3607]
[3608]
[3609]
[3610]
[3611]
[3612]
[3613]
[3614]
[3615]
[3616]
[3617]
[3618]
[3619]
[3620]
[3621]
[3622]
[3623]
[3624]
[3625]
[3626]
[3627]
[3628]
[3629]
[3630]
[3631]
[3632]
[3633]
[3634]
[3635]
[3636]
[3637]
[3638]
[3639]
[3640]
[3641]
[3642]
[3643]
[3644]
[3645]
[3646]
[3647]
[3648]
[3649]
[3650]
[3651]
[3652]
[3653]
[3654]
[3655]
[3656]
[3657]
[3658]
[3659]
[3660]
[3661]
[3662]
[3663]
[3664]
[3665]
[3666]
[3667]
[3668]
[3669]
[3670]
[3671]
[3672]
[3673]
[3674]
[3675]
[3676]
[3677]
[3678]
[3679]
[3680]
[3681]
[3682]
[3683]
[3684]
[3685]
[3686]
[3687]
[3688]
[3689]
[3690]
[3691]
[3692]
[3693]
[3694]
[3695]
[3696]
[3697]
[3698]
[3699]
[3700]
[3701]
[3702]
[3703]
[3704]
[3705]
[3706]
[3707]
[3708]
[3709]
[3710]
[3711]
[3712]
[3713]
[3714]
[3715]
[3716]
[3717]
[3718]
[3719]
[3720]
[3721]
[3722]
[3723]
[3724]
[3725]
[3726]
[3727]
[3728]
[3729]
[3730]
[3731]
[3732]
[3733]
[3734]
[3735]
[3736]
[3737]
[3738]
[3739]
[3740]
[3741]
[3742]
[3743]
[3744]
[3745]
[3746]
[3747]
[3748]
[3749]
[3750]
[3751]
[3752]
[3753]
[3754]
[3755]
[3756]
[3757]
[3758]
[3759]
[3760]
[3761]
[3762]
[3763]
[3764]
[3765]
[3766]
[3767]
[3768]
[3769]
[3770]
[3771]
[3772]
[3773]
[3774]
[3775]
[3776]
[3777]
[3778]
[3779]
[3780]
[3781]
[3782]
[3783]
[3784]
[3785]
[3786]
[3787]
[3788]
[3789]
[3790]
[3791]
[3792]
[3793]
[3794]
[3795]
[3796]
[3797]
[3798]
[3799]
[3800]
[3801]
[3802]
[3803]
[3804]
[3805]
[3806]
[3807]
[3808]
[3809]
[3810]
[3811]
[3812]
[3813]
[3814]
[3815]
[3816]
[3817]
[3818]
[3819]
[3820]
[3821]
[3822]
[3823]
[3824]
[3825]
[3826]
[3827]
[3828]
[3829]
[3830]
[3831]
[3832]
[3833]
[3834]
[3835]
[3836]
[3837]
[3838]
[3839]
[3840]
[3841]
[3842]
[3843]
[3844]
[3845]
[3846]
[3847]
[3848]
[3849]
[3850]
[3851]
[3852]
[3853]
[3854]
[3855]
[3856]
[3857]
[3858]
[3859]
[3860]
[3861]
[3862]
[3863]
[3864]
[3865]
[3866]
[3867]
[3868]
[3869]
[3870]
[3871]
[3872]
[3873]
[3874]
[3875]
[3876]
[3877]
[3878]
[3879]
[3880]
[3881]
[3882]
[3883]
[3884]
[3885]
[3886]
[3887]
[3888]
[3889]
[3890]
[3891]
[3892]
[3893]
[3894]
[3895]
[3896]
[3897]
[3898]
[3899]
[3900]
[3901]
[3902]
[3903]
[3904]
[3905]
[3906]
[3907]
[3908]
[3909]
[3910]
[3911]
[3912]
[3913]
[3914]
[3915]
[3916]
[3917]
[3918]
[3919]
[3920]
[3921]
[3922]
[3923]
[3924]
[3925]
[3926]
[3927]
[3928]
[3929]
[3930]
[3931]
[3932]
[3933]
[3934]
[3935]
[3936]
[3937]
[3938]
[3939]
[3940]
[3941]
[3942]
[3943]
[3944]
[3945]
[3946]
[3947]
[3948]
[3949]
[3950]
[3951]
[3952]
[3953]
[3954]
[3955]
[3956]
[3957]
[3958]
[3959]
[3960]
[3961]
[3962]
[3963]
[3964]
[3965]
[3966]
[3967]
[3968]
[3969]
[3970]
[3971]
[3972]
[3973]
[3974]
[3975]
[3976]
[3977]
[3978]
[3979]
[3980]
[3981]
[3982]
[3983]
[3984]
[3985]
[3986]
[3987]
[3988]
[3989]
[3990]
[3991]
[3992]
[3993]
[3994]
[3995]
[3996]
[3997]
[3998]
[3999]
[4000]
[4001]
[4002]
[4003]
[4004]
[4005]
[4006]
[4007]
[4008]
[4009]
[4010]
[4011]
[4012]
[4013]
[4014]
[4015]
[4016]
[4017]
[4018]
[4019]
[4020]
[4021]
[4022]
[4023]
[4024]
[4025]
[4026]
[4027]
[4028]
[4029]
[4030]
[4031]
[4032]
[4033]
[4034]
[4035]
[4036]
[4037]
[4038]
[4039]
[4040]
[4041]
[4042]
[4043]
[4044]
[4045]
[4046]
[4047]
[4048]
[4049]
[4050]
[4051]
[4052]
[4053]
[4054]
[4055]
[4056]
[4057]
[4058]
[4059]
[4060]
[4061]
[4062]
[4063]
[4064]
[4065]
[4066]
[4067]
[4068]
[4069]
[4070]
[4071]
[4072]
[4073]
[4074]
[4075]
[4076]
[4077]
[4078]
[4079]
[4080]
[4081]
[4082]
[4083]
[4084]
[4085]
[4086]
[4087]
[4088]
[4089]
[4090]
[4091]
[4092]
[4093]
[4094]
[4095]
[4096]
[4097]
[4098]
[4099]
[4100]
[4101]
[4102]
[4103]
[4104]
[4105]
[4106]
[4107]
[4108]
[4109]
[4110]
[4111]
[4112]
[4113]
[4114]
[4115]
[4116]
[4117]
[4118]
[4119]
[4120]
[4121]
[4122]
[4123]
[4124]
[4125]
[4126]
[4127]
[4128]
[4129]
[4130]
[4131]
[4132]
[4133]
[4134]
[4135]
[4136]
[4137]
[4138]
[4139]
[4140]
[4141]
[4142]
[4143]
[4144]
[4145]
[4146]
[4147]
[4148]
[4149]
[4150]
[4151]
[4152]
[4153]
[4154]
[4155]
[4156]
[4157]
[4158]
[4159]
[4160]
[4161]
[4162]
[4163]
[4164]
[4165]
[4166]
[4167]
[4168]
[4169]
[4170]
[4171]
[4172]
[4173]
[4174]
[4175]
[4176]
[4177]
[4178]
[4179]
[4180]
[4181]
[4182]
[4183]
[4184]
[4185]
[4186]
[4187]
[4188]
[4189]
[4190]
[4191]
[4192]
[4193]
[4194]
[4195]
[4196]
[4197]
[4198]
[4199]
[4200]
[4201]
[4202]
[4203]
[4204]
[4205]
[4206]
[4207]
[4208]
[4209]
[4210]
[4211]
[4212]
[4213]
[4214]
[4215]
[4216]
[4217]
[4218]
[4219]
[4220]
[4221]
[4222]
[4223]
[4224]
[4225]
[4226]
[4227]
[4228]
[4229]
[4230]
[4231]
[4232]
[4233]
[4234]
[4235]
[4236]
[4237]
[4238]
/*****************************************************************************/
/*
                                 fetch.c

Provides a number of uses where accessing a remote HTTP or FTP resource is
necessary, including a quasi-proxy, server-up? checking, command-line
document/image inclusion from other servers during DCL script processing,
HEAD/GET method and HTTP 0.9/1.0 experimenting.

MUST be mapped as "/fetch" or it can't be used as a script.  This has been done
quite deliberately to make this functionality only available by deliberate act
of the server administrator. The reason should be obvious.  Want your server to
be acting as a client, getting any old page from any old server any old user
wants?

Why use QIOs instead of Berkeley-style sockets?  Well, this program is also
used as a vehicle for experimentation before functionality is included in the
HTTPd proper.


HTTP-PROXY
----------
This script can be used as a working (but non-caching) HTTP proxy.  The need
has diminished since proxy/caching became an integral function of WASD, but
this functionality may still be useful in some situations.  See also the
"Clayton's proxy" described below.  The default (no protocol specified) is an
HTTP request (can be modified using /FTP).

Rules required in HTTPD$MAP for acting as an agent of (script for) proxy:

  [[the.proxy.service:port]]
  redirect http://* /fetch/http://*
  pass /http://* 
  script+ /fetch/* /cgi-bin/fetch/*
  pass * "403 something's amiss!"


REVERSE-PROXY AGENT
-------------------
Fetch can assist with the provision of reverse-proxy services (access to
internal servers via an external-facing proxy server), particularly for
internal resources that insist on supplying full URLs in anchors.

  *** THE PROVIDING SERVICE DOES NOT NEED TO BE SET UP AS A PROXY! ***
          FETCH CAN DO ALL THE PROXY FUNCTIONALITY REQUIRED!!

In this sense the reverse-proxy service refered to can be a standard, non-proxy
HTTP service.  Though using suitable mapping rules it could perform as both.

Fetch can be used to replace selected host components or all host components
from the URLs in HTTP and FTP anchors and replace them with a host component
representing the reverse proxy server.  It also massages the request "Referer:"
field; the response "Location:" and "Content-Location:", fields; disables the
response "Content-Length:" field (as it intends to alter the content); and will
massage the DOMAIN= and PATH= components of a response cookie if it considers
it necessary.

To make all URLs refer to reverse-proxy-server use a mapping construct with a
asterisk parameter similar to the following example.

Rules required in HTTPD$MAP:

  [[the.reverse-proxy.service:port]]
  script+ /fetch/* /cgi-bin/fetch/* \
          map=once script=params=FETCH_REVERSE_PROXY=*
  redirect /* /fetch/http://the.internal.host/*?
  pass * "403 something's amiss!"

Note that the '?' in the redirect is required to propagate query-strings.

This will change the <A HREF="http://internal.server.name/path">anchor</A> and
<A HREF="http://another.host.name/path">anchor</A> in the
returned page both to <A HREF="http[s]://reverse.proxy.name/path">anchor</A>.

To selectively make all internal-server URLs refer to the reverse-rpoxy-server
use a '#' or specify the internal host name as the script parameter.

  script+ /fetch/* /cgi-bin/fetch/* \
          map=once script=params=FETCH_REVERSE_PROXY=#

This will change the <A HREF="http://internal.server.name/path">anchor</A>
returned page to <A HREF="http[s]://reverse.proxy.name/path">anchor</A> but the
anchor <A HREF="http://another.host.name/path">anchor</A> will remain
unmodified.

Rules required in HTTPD$AUTH if internal authorization is required:

  [[the.reverse-proxy.service:port]]
  if (authorization:%*)
     [EXTERNAL]
     * r+w
  endif

If it is necessary to differentiate multiple resources at the proxy-server end
it is possible to use a path prefix.  For instance, to access separate internal
sites /res1/ and /res2/ via a single reverse proxy service, perhaps

  https://the.reverse-proxy.service/res1/
  https://the.reverse-proxy.service/res2/

these could be mapped using an arrangement similar to

  [[the.reverse-proxy.service:port]]
  set /fetch/http://one.internal.host/* \
      script=params=(FETCH_REVERSE_PROXY="*",FETCH_REVERSE_PATH="/res1")
  set /fetch/http://two.internal.host/* \
      script=params=(FETCH_REVERSE_PROXY="#",FETCH_REVERSE_PATH="/res2")
  script+ /fetch/* /cgi-bin/fetch/* map=once
  redirect /res1/* /fetch/http://one.internal.host/*?
  redirect /res2/* /fetch/http://two.internal.host/*?
  pass * "403 something's amiss!"

where the FETCH=REVERSE=PATH=<string> provides the prepended path.  Note that
because of the two different path settings they can no longer be set on the
script mapping but must be differentiated prior to this.


FTP-PROXY
---------
This script can access FTP servers to provide a script-based FTP proxy access. 
As WASD does not yet support integrated FTP proxy this program provides this
functionality.

The (probable) file system of the FTP server host is determined by examining
the results of an FTP PWD command.  If it returns a current working directory
specification containing a "/" then it's assumes it to be Unix(-like), if ":["
then VMS, if a "\" then DOS.  Anything else is unknown and it tries to do it's
best with an uninterpreted listing.

Note that the content-type of the transfer is determined by the way the local
server interprets the FTP request path's "file" extension.  This may or may not
correspond with what the remote system might consider the file type to be.  The
default content-type for unknown files is "application/octet-stream" (binary). 
This can be changed using the /UNKNOWN= qualifier.  In addition, a directory
listing contains three links indicated by the italicised characters, "aid". 
These allow the user to specify the transfer mode, text ("a" for ASCII), binary
("i" for image) and "d" for directory listing (no RFC959 equivalent), for files
which content-type is not obvious to the software (see immediately below).

Supports the FTP URL ";type=a" (return document as plain text), ";type=i"
(return document as binary) and ";type=d" (return directory listing) modifiers.

By default icons from the proxy server system are used in directory listings. 
The path to directory.gif and file.gif files may be specified using the /ICONS=
qualifier (e.g. /ICON="/path/to/icons/"), or icons my be eliminated from
listings altogether with an empty icon path (e.g. /ICON="").

Also support the WASD extensions ";type=dos", ";type=unix", ";type=unknown" and
";type=vms" modifiers for adjusting the way the script interacts with the FTP
server, and ";type=debug" which for investigative purposes reveals the FTP
client-server dialog in progress.  The ";cwd=initial-directory" WASD extension
explicitly sets the directory before other commands, and so allows the request
to move to directories other than subdirectories of the account.

Rules required in HTTPD$MAP for acting as an agent of (script for) proxy:

  redirect ftp://* /fetch/ftp://*
  pass /ftp://* 
  script+ /fetch/* /cgi-bin/fetch/*

Ad hoc FTP commands may be sent to the FTP server by prefixing and separating
them with vertical bar characters ("|"), and supplying as the path.  This is
only intended for checking the characteristics of the target server, and cannot
create data connections transfering files, etc.  This example show server help
and status being requested.

  ftp://the.host.name/|help|stat

With FTP it is possible to include a username and password with the request. 

  ftp://username:password@the.host.name/pub/

If none are provided they defaults "anonymous" and "anonymous@hostname".


CLAYTON'S-HTTP-PROXY
--------------------
This script can act as a Clayton's proxy (for those not up with Australian
advertising folklore, Clayton's Kola-based mixer at one stage had a campaign
where, it being alcohol-free, was promoted to adults as "the drink you're
having when not having a drink").  This is the proxy you're having when you're
not having genuine proxy. 

When accessed via a URL such as

  http://local.host.name/fetch/~http://remote.host.name/path

it retrieves the remote resource, returning it to the client.  If the resource
is "text/html" it massages the links inside that page so that references are
also accessed via the quasi-proxy local server.  Note that the entire response
is retrieved (and stored dynamically) before returning to the client, so this
is probably not well suited to accessing very large resources.

Occasionally the browser confuses document-relative resources (for instance
graphics).  Adding another one or two '/' after the remote host name will
sometimes resolve this.

Rules required in HTTPD$MAP:

  script+ /fetch/* /cgi-bin/fetch/*
  pass /~http://*
  pass /~ftp://*


INCLUDING A RESPONSE IN OTHER SCRIPT OUTPUT
-------------------------------------------
This program can be used from within other scripts to fetch a document
from a server and display it as part of the script's output, in various
combinations of header, body, and plain-text, as well just check the document
exists.  Output can also be placed directly into a file.

When used in this way the program creates a local CLI symbol for the contents
of each response header field (line) named FETCH_field-name, plus one named
FETCH_STATUS with the response status (first) line.

These should be deleted using DELETE/SYMBOL/LOCAL/ALL before repeated use.

Requires a foreign verb to be assigned.

  $ FETCH="$HT_EXE:FETCH"

To fetch a document from some place:

  $ FETCH "http://the.host.name/path/to/file.html"

To fetch an HTML document displayed as it's plain-text source:

  $ FETCH /ESCAPE "http://the.host.name/path/to/file.html"

To fetch a request and show the complete response (header and body):

  $ FETCH /HEADER "http://the.host.name/path/to/file.html"

Just the request header:

  $ FETCH /HEADER /NOBODY "http://the.host.name/path/to/file.html"

To check whether a particular document is available (HEADs the document). Exits
with a success status is the request was successful, with no message and a
status STS$K_ERROR status if the server was accessable and the request was not
successful, other error status may be returned (e.g. if the server was not
accessable, etc.)

  $ FETCH /CHECK "http://the.host.name/path/to/file.html"

Request a document straight into a file.  FETCH always outputs the request
header, unless directed not to by the /NOHEADER qualifier.  Therefore when
wishing to store a copy of the request body (document, graphic, etc) it is
necessary to specifically suppress the header.

  $ FETCH /OUTPUT=file.html /NOHEAD "http://the.host.name/path/to/file.html"
  $ FETCH /OUTPUT=image.gif /NOHEAD "http://the.host.name/path/to/image.gif"
  $ FETCH /OUTPUT=prog.exe /NOHEAD "http://the.host.name/path/to/image.exe"

FTP services may also be accessed.  HTTP qualifiers, etc., that are not
applicable to FTP are ignored.

  $ FETCH /OUTPUT=file.html "http://the.host.name/path/to/file.html"
  $ FETCH /OUTPUT=image.gif "http://the.host.name/path/to/image.gif"
  $ FETCH /CHECK "http://the.host.name/path/to/file.html"


OTHER COMMAND LINE USE
----------------------
All fetch functionality is available from the command-line.  This makes it
possible to use from batch jobs, etc., to regularly retrieve resources from
the Web, check whether a particular server is (still) available, etc.  Just
supplying it as a parameter is  acceptable.  For example, checking for a
specific server being up:

  $ FETCH /CHECK "http://the.host.name/"
  $ FETCH /CHECK "ftp://the.host.name/"

The /CHECK qualifier produces no output.  It just exits with either a normal
or error status.  No message is generated.  It is up to any procedure to test
and act on that status.  Example procedural use:                        

   $ SET NOON
   $ FETCH = "$HT_EXE:FETCH"
   $ FETCH /CHECK *P1
   $ FETCH_$STATUS = $STATUS .AND. %XFFFFFFF
   $ SHOW SYMBOL FETCH_$STATUS
   $ EXIT FETCH_$STATUS

Getting parameters from the CGI environment into the command-line qualifiers
and/or parameter is best done without DCL (') substitution.  The /SUBSTITUTE=
qualifier allows the specification of a character that if present as the first
character of a /QUALIFIER=<string> specification results in the rest of the
string being used as an environment variable name (CGI and others).  The
getenv() C-RTL function is used to get a value against that name.  An astersisk
is the default substitution character.  A substitution character may be escaped
using a leading backslash.

   $ FETCH = "$HT_EXE:FETCH"
   $ FETCH /URL=*WWW_FORM_URL -
           /HEADER /NOBODY -
           /METHOD=*WWW_FORM_HTTP_METHOD -
           /VERSION=*WWW_FORM_HTTP_VERSION

In the above example the literal string "*WWW_FORM_URL" (etc.) is read by the
FETCH utility and then detecting the leading asterisk it resolves the
remaining part of the string as an environment variable "WWW_FORM_URL" and uses
the value of that (usually a symbol - see the C-RTL document for the
description of the behaviour of the getenv() function).  The contents of CGI
variables should not be substituted into such a command-line (e.g.
"''WWW_FORM_URL'").

Why an asterisk?  Well, trying to find a character that doesn't have some very
specific command-line interpreter, VMS or HTTP meaning (so as to avoid
confusion) is quite difficult.  The asterisk is slightly reminiscent of the C
language pointer dereference operator.  And anyway, it can be specified locally
using /SUBSTITUTE=.


QUALIFIERS
----------
Parameters and qualifiers may be supplied to this program via the command line
or via a defined logical or assigned DCL symbol named FETCH$PARAM.

/[NO]BODY       (do not) output the response body (default is BODY)
/CHECK          just check whether the document can be accessed
/CHUNK=         chunks of memory to allocate while reading response (Kbytes)
/[NO]ESCAPE     escape HTML-forbidden characters (<, > and &) (default NO)
/FTP            access via FTP protocol (used in absence of "ftp://...")
/[NO]HEADER     (do not) output full response header (default is NOHEADER)
/HTTP           access via HTTP protocol (used in absence of "http://...")
/ICONS=         path to directory with FTP dir.gif and file.gif icons
/METHOD=        HTTP method to be used, GET (default) or HEAD
/OUTPUT=        file name or "TERMINAL" or "SYS$OUTPUT"
/REPORT         report errors direct to the client using an HTML report
/REVERSE=       reverse proxy match string
/SUBSTITUTE=    specify the character for parameter substitution
/UNKNOWN=       fallback content-type for FTP transfer when file unknown
/URL=           same as first parameter
/USER_AGENT=    browser user-agent string used when making request
/VERSION        (no parameter) output FETCH software version
/VERSION=       make request using HTTP 0.9 or 1.0 (default)
/WATCH          watch the request and response


LOGICAL NAMES
-------------
FETCH$DBUG         turns on all "if (Debug)" statements
FETCH$DBUG_CGILIB  turns on CGILIB debug mode
FETCH$DBUG_FTP     displays FTP dialog
FETCH$PARAM        equivalent to (overrides) the command line
                   parameters/qualifiers
FETCH$WATCH        if defined as an IP address enables 'watch' mode for
                   that client IP address, if not an IP address just enables


BUILD_DETAILS
-------------
See BUILD_FETCH.COM


COPYRIGHT
---------
Copyright (C) 1998-2021 Mark G.Daniel

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.


VERSION HISTORY
---------------
18-MAR-2005  MGD  v1.9.0, reverse proxy link massaging,
                          enhanced 'watch' mode
23-DEC-2003  MGD  v1.8.1, minor conditional mods to support IA64
01-OCT-2002  MGD  v1.8.0, modify command-line parsing
08-JUN-2001  MGD  v1.7.1, modify /VERSION to provide software version
28-OCT-2000  MGD  v1.7.0, use CGILIB object module
15-SEP-2000  MGD  v1.6.0, refine handling of Unix symbolic links,
                          major refinements to FTP processing,
                          use IP-related system services more in-line
02-SEP-2000  MGD  v1.5.2, bugfix; FTP "PORT ..." command q&d IP address
                          octets sign shifted not unsigned shifted - mask!
15-JUL-2000  MGD  v1.5.1, bugfix; OpenConnection() host name resolution
08-JUL-2000  MGD  v1.5.0, add /WATCH, minor fixes
12-APR-2000  MGD  v1.4.0, improve command-line interface handling,
                          minor changes for CGILIB 1.4
30-OCT-1999  MGD  v1.3.0, remove NETLIB support,
                          add "Host:" request header line,
                          bugfix; 302 processing in MessageLinks()
09-MAY-1999  MGD  v1.2.0, use CGILIB.C,
                          add FTP protocol,
                          maintenance and refinement
21-JUN-1998  MGD  v1.1.0, revision of CgiVar()
07-MAR-1998  MGD  v1.0.0, initial
*/
/*****************************************************************************/

#define SOFTWAREVN "1.9.0"
#define SOFTWARENM "FETCH"
#ifdef __ALPHA
#  define SOFTWAREID SOFTWARENM " AXP-" SOFTWAREVN
#endif
#ifdef __ia64
#  define SOFTWAREID SOFTWARENM " IA64-" SOFTWAREVN
#endif
#ifdef __VAX
#  define SOFTWAREID SOFTWARENM " VAX-" SOFTWAREVN
#endif
#ifdef __x86_64
#  define SOFTWAREID SOFTWARENM " X86-" SOFTWAREVN
#endif

/* standard C header files */
#include <ctype.h>
#include <errno.h>
#include <stdarg.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

/* VMS related header files */
#include <descrip.h>
#include <dvidef.h>
#include <iodef.h>
#include <libclidef.h>
#include <lnmdef.h>
#include <rms.h>
#include <ssdef.h>
#include <stsdef.h>

/* Internet-related header files */
#include <socket.h>
#include <in.h>
#include <netdb.h>
#include <inet.h>

/* define required values from UCX$INETDEF.H (Multinet does not supply one) */
#define INET_PROTYP$C_STREAM 1
#define INETACP$C_TRANS 2
#define INETACP_FUNC$C_GETHOSTBYNAME 1
#define INETACP_FUNC$C_GETHOSTBYADDR 2
#define UCX$C_AF_INET 2
#define UCX$C_DSC_ALL 2
#define UCX$C_FULL_DUPLEX_CLOSE 8192
#define UCX$C_REUSEADDR 4
#define UCX$C_SOCK_NAME 4
#define UCX$C_SOCKOPT 1
#define UCX$C_TCP 6

/* application related header file */
#include <cgilib.h>

#define BOOL int
#define true 1
#define false 0

#define VMSok(x) ((x) & STS$M_SUCCESS)
#define VMSnok(x) !(((x) & STS$M_SUCCESS))

#define FI_LI __FILE__, __LINE__

#define DEFAULT_BUFFER_CHUNK 32
#define DEFAULT_FTP_CONTENT_TYPE "application/octet-stream"
#define DEFAULT_ICON_PATH "/httpd/-/"
#define DEFAULT_PARAM_SUBS_CHAR '*'
#define DEFAULT_PROXY_SCRIPT_NAME "/fetch"

/******************/
/* global storage */
/******************/

char  CopyrightInfo [] =
"Copyright (C) 1998-2005 Mark G.Daniel.\n\
This software comes with ABSOLUTELY NO WARRANTY.\n\
This is free software, and you are welcome to redistribute it\n\
under the conditions of the GNU GENERAL PUBLIC LICENSE, version 2.";

char  Utility [] = "FETCH";

BOOL  CgiLibDebug,
      Debug,
      DoCheckOnly,
      DoEscapeHtml,
      DoFtp,
      DoMassageLinks,
      DoReport,
      DoResponseBody,
      DoResponseHeader,
      FetchDebugFtp,
      IsCgiPlus,
      IsFetchScript,
      WatchEnabled;

int  BufferChunk,
     BufferCount,
     BufferRemaining,
     BufferSize,
     CgiScriptNameLength,
     FetchPrefixLength,
     RemoteHostPortLength,
     RemotePort,
     RequestHttpVersion,
     ResponseHttpVersion,
     ReverseProxyLength;

char  *BufferPtr,
      *BufferCurrentPtr,
      *CgiContentTypePtr,
      *CgiLibEnvironmentPtr,
      *CgiQueryStringPtr,
      *CgiRequestSchemePtr,
      *CgiRequestMethodPtr,
      *CgiScriptNamePtr,
      *CgiServerNamePtr,
      *CgiServerPortPtr,
      *CgiServerSoftwarePtr,
      *CliHttpMethodPtr,
      *FetchScriptNamePtr,
      *FetchUrlPtr,
      *FtpDefaultContentTypePtr = DEFAULT_FTP_CONTENT_TYPE,
      *HttpMethodPtr,
      *IconPathPtr = DEFAULT_ICON_PATH,
      *OutputPtr,
      *ReversePathPtr,
      *ReverseProxyPtr,
      *UserAgentPtr;

struct HttpEnvironmentStruct
{
   char  *field,
         *cgi;
}
/* those commented out should be commented-out for a reason :-) */
HttpEnvironment [] =
{
   { "Accept: ",          "HTTP_ACCEPT" },
   { "Accept-Charset: ",  "HTTP_ACCEPT_CHARSET" },
   /** { "Accept-Encoding: ", "HTTP_ACCEPT_ENCODING" }, **/
   { "Accept-Language: ", "HTTP_ACCEPT_LANGUAGE" },
   { "Authorization: ",   "HTTP_AUTHORIZATION" },
   /** { "Cache-Control: ",   "HTTP_CACHE_CONTROL" }, **/
   /** { "Connection: ",      "HTTP_CONNECTION" }, **/
   /** { "Content-Length: ",  "HTTP_CONTENT_LENGTH" }, **/
   /* not 'HTTP_' to be backward-compatible with pre-9.0 WASD */
   { "Content-Type: ",    "CONTENT_TYPE" },
   { "Cookie: ",          "HTTP_COOKIE" },
   /** { "Forwarded: ",       "HTTP_FORWARDED" }, **/
   /** { "Host: ",            "HTTP_HOST" }, **/
   { "If-Match: ",        "HTTP_IF_MATCH" },
   { "If-None-Match: ",   "HTTP_IF_NONE_MATCH" },
   { "If-Modified-Since: ", "HTTP_IF_MODIFIED_SINCE" },
   { "If-Unmodified-Since: ", "HTTP_IF_UNMODIFIED_SINCE" },
   { "If-Range: ",        "HTTP_IF_RANGE" },
   /** { "Pragma: ",          "HTTP_PRAGMA" }, **/
   { "Range: ",           "HTTP_RANGE" },
   /** { "Referer: ",         "HTTP_REFERER" }, **/
   { "Trailer: ",         "HTTP_TRAILER" },
   /** { "Transfer-Encoding: ", "HTTP_TRANSFER_ENCODING" }, **/
   /** { "User-Agent: ",      "HTTP_USER_AGENT" }, **/
   /** { "X-Forwarded-For: ", "HTTP_X_FORWARDED_FOR" }, **/
   { NULL, NULL }
};

char  ParamSubsChar = DEFAULT_PARAM_SUBS_CHAR;

char  FetchPrefix [256],
      FetchUrlBuffer [1024],
      FtpIconDirImg [256],
      FtpIconFileImg [256],
      LocalHostPort [256],
      MassageLinksPath [256],
      RemoteHost [256],
      RemoteHostPort [256],
      RequestHeader [4096],
      RequestPath [1024],
      RequestScheme [64],
      ResponseContentType [256],
      ReverseProxyPrefix [256],
      SoftwareId [96];

struct AnIOsb {
   unsigned short  Status;
   unsigned short  Count;
   unsigned long  Unused;
}  IOsb;

#define CGIVAR(p,n) \
{ p = CgiLibVar(n); \
if (WatchEnabled) WatchThis ("CGIVAR !AZ=!AZ",n,p); }

#define CGIVARNULL(p,n) \
{ p = CgiLibVarNull(n); \
if (WatchEnabled) WatchThis ("CGIVAR !AZ=!AZ",n,p?p:"(null)"); }

$DESCRIPTOR (InetDeviceDsc, "UCX$DEVICE");

unsigned short  RemoteChannel;

int  OptionEnabled = 1;

struct {
   unsigned short  Length;
   unsigned short  Parameter;
   void  *Address;
} ReuseAddress =
   { sizeof(OptionEnabled), UCX$C_REUSEADDR, &OptionEnabled },
  ReuseAddressSocketOption =
   { sizeof(ReuseAddress), UCX$C_SOCKOPT, &ReuseAddress };

unsigned short  TcpSocket [3] =
   { UCX$C_TCP, INET_PROTYP$C_STREAM, UCX$C_AF_INET };

/* these 3 strings may be changed to a desired language */

char  FtpCurrentDirectory [] = "Current directory is";

char  FtpFilesDirectories [] =
"<FONT SIZE=-1><I>\n\
<P>Files: %d\n\
<BR>Directories: %d\n\
%s\
</I></FONT>\n";

char  FtpGetAs [] =
"<BR>a ... get as text\n\
<BR>i ... as binary\n\
<BR>d ... as directory\n";

/* required prototypes */

char* FetchFtpResponse ();
char* FetchHttpResponse ();
char* FtpCommand (BOOL, unsigned short, char*, ...);
char* FtpReply (unsigned short);
char* GetParameterString (char*);
char* TrnLnm (char*, char*, int);
int ReadConnection (unsigned short, char*, int, int*, BOOL);
char* ReplyVmsError (int);
int WriteConnection (unsigned short, char*, int);
int WatchDump (char*, int);
int WatchThis (char*, ...);

/*****************************************************************************/
/*
*/ 

main
(
int argc,
char *argv[]
)
{
   int  status;
   char  *cptr;

   /*********/
   /* begin */
   /*********/

   sprintf (SoftwareId, "%s, %s", SOFTWAREID, CgiLibEnvironmentVersion());

   FetchScriptNamePtr = DEFAULT_PROXY_SCRIPT_NAME;
   HttpMethodPtr = "GET";
   RequestHttpVersion = 10;
   OutputPtr = "";
   DoResponseBody = DoResponseHeader = true;
   DoEscapeHtml = DoFtp = DoReport = false;

   if (TrnLnm ("FETCH$DBUG", NULL, 0)) Debug = true;
   if (TrnLnm ("FETCH$DBUG_CGILIB", NULL, 0)) CgiLibDebug = true;

   GetParameters ();

   if (CliHttpMethodPtr) HttpMethodPtr = CliHttpMethodPtr;
   if (!HttpMethodPtr[0]) HttpMethodPtr = "GET";

   if (RequestHttpVersion != 9 && RequestHttpVersion != 10)
   {
      fprintf (stdout, "%%%s-E-VERSION, must be 0.9 or 1.0\n", Utility);
      exit (STS$K_ERROR | STS$M_INHIB_MSG);
   }

   /***********/
   /* process */
   /***********/

   CgiLibEnvironmentInit (argc, argv, false);
   CgiLibEnvironmentSetDebug (Debug);

   CgiLibResponseSetSoftwareID (SoftwareId);
   CgiLibResponseSetErrorStatus (502);
   CgiLibResponseSetErrorMessage ("Reported by Proxy Agent");

   IsCgiPlus = CgiLibEnvironmentIsCgiPlus ();

   if (IsCgiPlus)
   {
      for (;;)
      {
         if (Debug) fprintf (stdout,
"Content-Type: text/plain\nScript-Control: X-content-encoding-gzip=0\n\n");
         /* block waiting for the next request */
         CgiLibVar ("");
         ProcessRequest ();
         CgiLibCgiPlusEOF ();
         CgiQueryStringPtr = FetchUrlPtr = NULL;
      }
   }
   else
      ProcessRequest ();

   exit (SS$_NORMAL);
}

/*****************************************************************************/
/*
*/ 

ProcessRequest ()

{
   int  StatusValue;
   char  *cptr, *sptr;

   /*********/
   /* begin */
   /*********/

   if (Debug) fprintf (stdout, "ProcessRequest()\n");

   if (cptr = TrnLnm ("FETCH$WATCH", NULL, 0))
   {
      if (Debug) fprintf (stdout, "FETCH$WATCH |%s|\n", cptr);
      WatchEnabled = 1;
      if (isdigit(*cptr))
      {
         /* if it doesn't match the remote address then disable again */
         if (!(sptr = CgiVar ("REMOTE_ADDR"))) sptr = "";
         if (strcmp (cptr, sptr)) WatchEnabled = 0;
      }
   }

   if (Debug) WatchEnabled = 1;

   if (WatchEnabled)
   {
      /* initialize watch mode */
      WatchThis (NULL);
      if (CgiLibVarNull ("SCRIPT_RTE"))
         cptr = "RTE";
      else
      if (IsCgiPlus)
         cptr = "CGIplus";
      else
         cptr = "CGI";
      WatchThis ("BEGIN !AZ; !AZ", cptr, SoftwareId);
   }

   CgiLibEnvironmentPtr = CgiLibEnvironmentName();

   CGIVAR (CgiScriptNamePtr, "WWW_SCRIPT_NAME");
   CgiScriptNameLength = strlen(CgiScriptNamePtr);
   if (CgiScriptNamePtr[0] && !FetchUrlPtr)
   {
      if (!strsame (CgiScriptNamePtr, FetchScriptNamePtr, -1))
      {
         fprintf (stdout, "%%%s-E-SCRIPT, must be mapped to \"%s\"\n",
                  Utility, FetchScriptNamePtr);
         exit (STS$K_ERROR | STS$M_INHIB_MSG);
      }
      IsFetchScript = true;
   }
   else
      IsFetchScript = false;

   CGIVAR (CgiRequestSchemePtr, "WWW_REQUEST_SCHEME");
   CGIVAR (CgiRequestMethodPtr, "WWW_REQUEST_METHOD");
   CGIVAR (CgiServerNamePtr, "WWW_SERVER_NAME");
   CGIVAR (CgiServerPortPtr, "WWW_SERVER_PORT");
   CGIVAR (CgiServerSoftwarePtr, "WWW_SERVER_SOFTWARE");
   CGIVAR (CgiQueryStringPtr, "WWW_QUERY_STRING");
   CGIVAR (UserAgentPtr, "WWW_HTTP_USER_AGENT");
   if (!UserAgentPtr[0]) UserAgentPtr = SoftwareId;

   /* e.g. created with a 'set * script=param=FETCH_REVERSE_PROXY=*' */
   CGIVARNULL (ReverseProxyPtr, "FETCH_REVERSE_PROXY");
   if (ReverseProxyPtr) ReverseProxyLength = strlen(ReverseProxyPtr);

   /* e.g. created with a 'set * script=param=FETCH_REVERSE_PATH=/whatever' */
   CGIVAR (ReversePathPtr, "FETCH_REVERSE_PATH");

   /* URL not supplied on command line, get it from the script path */
   if (!FetchUrlPtr)
   {
      CGIVAR (FetchUrlPtr, "WWW_PATH_INFO");
      FetchUrlPtr++;
   }

   if (!FetchUrlPtr)
   {
      fprintf (stdout, "%%%s-E-URL, no URL supplied\n", Utility);
      exit (STS$K_ERROR | STS$M_INHIB_MSG);
   }

   /* buffer in case the following code distorts the original URL */
   strcpy (FetchUrlBuffer, FetchUrlPtr);

   /* pages with massaged links will have the circumflex before the protocol */
   if (!memcmp (FetchUrlPtr, "~http://", 8) ||
       !memcmp (FetchUrlPtr, "~ftp://", 7))
   {
      /* step over the circumflex */
      FetchUrlPtr++;
      DoMassageLinks = true;
   }
   else
   if (ReverseProxyPtr)
      DoMassageLinks = true;
   else
      DoMassageLinks = false;

   /* the leading '_' is just a contrivance to allow easier HTTPd mapping */
   if (!memcmp (FetchUrlPtr, "_http://", 8) ||
       !memcmp (FetchUrlPtr, "_ftp://", 7))
   {
      /* step over the underscore */
      FetchUrlPtr++;
   }

   if (DoFtp || !memcmp (FetchUrlPtr, "ftp://", 6))
   {
      /***************/
      /* FTP request */
      /***************/

      cptr = FetchFtpResponse ();
      SetLocalSymbol ("FETCH_RESPONSE", cptr);

      if (*cptr != '2')
      {
         if (IsFetchScript || DoReport)
         {
            if (!memcmp (cptr, "599", 3))
               CgiLibResponseError (FI_LI, 0, "<!-- %10.10s --> %s",
                                    cptr+4, cptr+14);
            else
               CgiLibResponseError (FI_LI, 0, "%s", cptr);
         }
         else
         {
            if (!memcmp (cptr, "599", 3))
               sscanf (cptr+6, "%x", &StatusValue);
            else
               StatusValue = STS$K_ERROR;
            exit (StatusValue | (WatchEnabled ? 0 : STS$M_INHIB_MSG));
         }
      }
   }
   else
   {
      /****************/
      /* HTTP request */
      /****************/

      if (DoCheckOnly)
         HttpMethodPtr = "HEAD";
      else
      if (CliHttpMethodPtr)
         HttpMethodPtr = CliHttpMethodPtr;
      else
      if (CgiRequestMethodPtr[0])
      {
         HttpMethodPtr = CgiRequestMethodPtr;
         if (strcmp (HttpMethodPtr, "GET") &&
             strcmp (HttpMethodPtr, "HEAD") &&
             strcmp (HttpMethodPtr, "POST"))
         {
            CgiLibResponseError (FI_LI, 0, "HTTP method %s not supported",
                                 HttpMethodPtr);
            return;
         }
      }
      else
         HttpMethodPtr = "GET";

      cptr = FetchHttpResponse ();
      SetLocalSymbol ("FETCH_RESPONSE", cptr);

      if (*cptr == '2')
      {
         if (DoCheckOnly)
         {
            if (!(cptr = BufferPtr))
               exit (STS$K_ERROR | STS$M_INHIB_MSG);

            if (Debug) fprintf (stdout, "|%s|\n", BufferPtr);
            /* this just creates the informational symbols */
            ProcessHttpResponse ();

            /* check the response status code for success */
            while (*cptr && !isspace(*cptr)) cptr++;
            while (*cptr && isspace(*cptr)) cptr++;
            if (*cptr == '2') exit (SS$_NORMAL);

            if (!memcmp (cptr, "599", 3))
               sscanf (cptr+6, "%x", &StatusValue);
            else
               StatusValue = 0;
            exit (StatusValue | (WatchEnabled ? 0 : STS$M_INHIB_MSG));
         }

         /* HTTP response is being written to a file */
         if (*OutputPtr)
            if (!(stdout = freopen (OutputPtr, "w", stdout)))
               exit (vaxc$errno);

         if (DoMassageLinks)
            MassageLinks ();
         else
            ProcessHttpResponse ();
      }
      else
      if (!memcmp (cptr, "302", 3))
         exit (SS$_NORMAL);
      else
      {
         if (IsFetchScript || DoReport)
         {
            if (!memcmp (cptr, "599", 3))
               CgiLibResponseError (FI_LI, 0, "<!-- %10.10s --> %s",
                                    cptr+4, cptr+14);
            else
               CgiLibResponseError (FI_LI, 0, "%s", cptr);
         }
         else
         {
            if (!memcmp (cptr, "599", 3))
               sscanf (cptr+6, "%x", &StatusValue);
            else
               StatusValue = STS$K_ERROR;
            exit (StatusValue | (WatchEnabled ? 0 : STS$M_INHIB_MSG));
         }
      }
   }

   /* reset watch mode as necessary */
   if (WatchEnabled) WatchThis (NULL);
}

/****************************************************************************/
/*
Determine the host name and port and then create a request to send to it. 
Connect and send that request, reading the complete response into a buffer of
dynamically allocated memory.
*/

char* FetchHttpResponse ()

{
   static char  HexDigits [] = "0123456789ABCDEF";

   int  idx, status,
        BodyLength,
        LocalPort,
        ReadCount;
   unsigned short  RemoteChannel;
   unsigned char  ch;
   char  *cptr, *hptr, *sptr,
         *BodyPtr;
   char  LocalHost [128];

   /*********/
   /* begin */
   /*********/

   if (!FetchUrlPtr[0]) return ("599 %x00038268");

   RequestHeader[0] = RemoteHost[0] = '\0';

   hptr = RequestHeader;
   for (cptr = HttpMethodPtr; *cptr; *hptr++ = *cptr++);
   *hptr++ = ' ';

   cptr = FetchUrlPtr;
   if (strsame (cptr, "http://", 7)) cptr += 7;

   if (*CgiServerNamePtr)
      strcpy (LocalHost, CgiServerNamePtr);
   else
      gethostname (LocalHost, sizeof(LocalHost));
   if (*CgiServerPortPtr)
      LocalPort = atoi(CgiServerPortPtr);
   else
      LocalPort = 80;
   if (LocalPort == 80 || LocalPort == 443)
      strcpy (LocalHostPort, LocalHost);
   else
      sprintf (LocalHostPort, "%s:%d", LocalHost, LocalPort);
   if (Debug) fprintf (stdout, "LocalHostPort |%s|\n", LocalHostPort);

   if (*cptr == '/')
   {
      strcpy (RemoteHost, LocalHost);
      RemotePort = LocalPort;
      strcpy (RemoteHostPort, LocalHostPort);
   }
   else
   {
      /* get host and optional port */
      sptr = RemoteHost;
      while (*cptr && *cptr != '/' && *cptr != ':')
          *sptr++ = *cptr++;
      *sptr = '\0';
      if (*cptr == ':')
      {
         cptr++;
         RemotePort = atoi(cptr);
         if (!RemotePort) RemotePort = 80;
         while (*cptr && *cptr != '/') cptr++;
      }
      else
         RemotePort = 80;

      if (RemotePort == 80)
         strcpy (RemoteHostPort, RemoteHost);
      else
         sprintf (RemoteHostPort, "%s:%d", RemoteHost, RemotePort);
   }
   RemoteHostPortLength = strlen(RemoteHostPort);

   if (Debug) fprintf (stdout, "|%s|%s|\n", RemoteHostPort, cptr);

   if (DoMassageLinks)
   {
      sprintf (FetchPrefix, "%s//%s%s/~",
               CgiRequestSchemePtr, LocalHostPort, CgiScriptNamePtr);
      sprintf (MassageLinksPath, "%s/~", CgiScriptNamePtr);
      sprintf (ReverseProxyPrefix, "%s//%s%s",
               CgiRequestSchemePtr, LocalHostPort, ReversePathPtr);
   }
   else
      FetchPrefix[0] = MassageLinksPath[0] = ReverseProxyPrefix[0] = '\0';

   if (IsFetchScript && *cptr != '/')
   {
      /* no path (i.e. "http://remote.host.name") which can break links */
      fprintf (stdout,
"HTTP/1.0 302 Moved temporarily\r\n\
Location: %s%s/\r\n\
\r\n",
         FetchPrefix, FetchUrlPtr);
      return ("302 Redirection!");
   }

   if (!strcmp (CgiRequestMethodPtr, "POST"))
   {
      if (!CgiLibReadRequestBody (&BodyPtr, &BodyLength))
      {
         CgiLibResponseError (FI_LI, 0, "Could not read request body.");
         return ("502 Could not read request body.");
      }
      if (WatchEnabled)
      {
         WatchThis ("POST !UL", BodyLength);
         WatchDump (BodyPtr, BodyLength);
      }
   }

   /* rest of the path, which is actually the desired request path */
   sptr = RequestPath;

   if (!*cptr) *hptr++ = *sptr++ = '/';

   /* escape any URL forbidden characters in the path */
   while (ch = *cptr)
   {
      if (iscntrl(ch) || isspace(ch))
      {
         *hptr++ = *sptr++ = '%';
         *hptr++ = *sptr++ = HexDigits[ch >> 4];
         *hptr++ = *sptr++ = HexDigits[ch & 0x0f];
         cptr++;
      }
      else
         *hptr++ = *sptr++ = *cptr++;
   }

   /* any non-command-line query string */
   if (IsFetchScript && (cptr = CgiQueryStringPtr))
   {
      if (*cptr)
      {
         if (*cptr) *hptr++ = *sptr++ = '?';
         while (*cptr) *hptr++ = *sptr++ = *cptr++;
      }
   }

   /* terminate the request path */
   *sptr = '\0';

   if (RequestHttpVersion == 9)
   {
      /* end of request line */
      *hptr++ = '\r';
      *hptr++ = '\n';
   }
   else
   {
      /* add the HTTP protocol to the request */
      for (cptr = " HTTP/1.0\r\n"; *cptr; *hptr++ = *cptr++);

      /* fudge the "Host:" request field */
      for (sptr = "Host: "; *sptr; *hptr++ = *sptr++);
      cptr = RemoteHostPort;
      while (*cptr) *hptr++ = *cptr++;
      *hptr++ = '\r';
      *hptr++ = '\n';

      cptr = CgiLibVarNull("WWW_HTTP_REFERER");

      if (cptr && ReverseProxyPtr)
      {
         /* if it referes to the proxy server then replace with proxied-to */
         if (strstr (cptr, CgiLibVar("WWW_HTTP_HOST")))
         {
            for (sptr = "Referer: http://"; *sptr; *hptr++ = *sptr++);
            for (sptr = RemoteHostPort; *sptr; *hptr++ = *sptr++);
            /* skip over the scheme and host components */
            while (*cptr && *cptr != '/') cptr++;
            while (*cptr && *cptr == '/') cptr++;
            while (*cptr && *cptr != '/') cptr++;
         }
         else
            for (sptr = "Referer: "; *sptr; *hptr++ = *sptr++);
         while (*cptr) *hptr++ = *cptr++;
         *hptr++ = '\r';
         *hptr++ = '\n';
      }
      else
      if (cptr)
      {
         sptr = cptr;
         if (!memcmp (sptr, "http://", 7))
         {
            sptr += 7;
            while (*sptr && *sptr != '/') sptr++;
            if (!memcmp (sptr, CgiScriptNamePtr, CgiScriptNameLength))
            {
               sptr += CgiScriptNameLength;
               if (*sptr == '/') cptr = sptr + 1;
               if (Debug) fprintf (stdout, "Referer |%s|\n", cptr);
            }
         }
         for (sptr = "Referer: "; *sptr; *hptr++ = *sptr++);
         while (*cptr) *hptr++ = *cptr++;
         *hptr++ = '\r';
         *hptr++ = '\n';
      }

      if (!UserAgentPtr) UserAgentPtr = CgiLibVarNull ("HTTP_USER_AGENT");
      if ((cptr = UserAgentPtr))
      {
         for (sptr = "User-Agent: "; *sptr; *hptr++ = *sptr++);
         while (*cptr) *hptr++ = *cptr++;
         *hptr++ = '\r';
         *hptr++ = '\n';
      }

      if (!strcmp (CgiRequestMethodPtr, "POST"))
         hptr += sprintf (hptr, "Content-Length: %d\r\n", BodyLength);

      for (idx = 0; HttpEnvironment[idx].cgi; idx++)
      {
         if (!(cptr = CgiLibVarNull(HttpEnvironment[idx].cgi))) continue;
         for (sptr = HttpEnvironment[idx].field; *sptr; *hptr++ = *sptr++);
         while (*cptr) *hptr++ = *cptr++;
         *hptr++ = '\r';
         *hptr++ = '\n';
      }

      /* end of request header blank line */
      *hptr++ = '\r';
      *hptr++ = '\n';
   }

   /* terminate the request header */
   *hptr = '\0';

   if (hptr > RequestHeader + sizeof(RequestHeader)) exit (SS$_BUGCHECK);

   if (WatchEnabled) WatchThis ("HTTP\n!AZ", RequestHeader);

   /*******************/
   /* open connection */
   /*******************/

   status = OpenConnection (&RemoteChannel, RemoteHost, RemotePort, NULL);
   if (VMSnok (status)) return (ReplyVmsError (status));

   /****************/
   /* send request */
   /****************/

   if (Debug) fprintf (stdout, "request |%s|\n", RequestHeader);

   status = WriteConnection (RemoteChannel, RequestHeader, -1);
   if (VMSnok (status)) return (ReplyVmsError (status));

   if (!strcmp (CgiRequestMethodPtr, "POST"))
   {
      status = WriteConnection (RemoteChannel, BodyPtr, BodyLength);
      if (VMSnok (status)) return (ReplyVmsError (status));
   }

   /*********************/
   /* read the response */
   /*********************/

   if (BufferChunk <= 0) BufferChunk = DEFAULT_BUFFER_CHUNK;

   /* with CGIplus 'BufferPtr'/'BufferSize' may still have memory allocated */
   BufferCount = 0;
   BufferRemaining = BufferSize;
   BufferCurrentPtr = BufferPtr;

   for (;;)
   {
      if (BufferCount == BufferSize)
      {
         BufferSize += (BufferRemaining = (BufferChunk << 10));
         if (!(BufferPtr = realloc (BufferPtr, BufferSize+1)))
            exit (vaxc$errno);
         BufferCurrentPtr = BufferPtr + BufferSize - BufferRemaining;
      }

      ReadCount = BufferRemaining <= 32767 ? BufferRemaining : 32767,
      status = ReadConnection (RemoteChannel, BufferCurrentPtr, ReadCount,
                               &ReadCount, false);
      if (VMSnok (status)) break;

      BufferCount += ReadCount;
      BufferCurrentPtr += ReadCount;
      BufferRemaining -= ReadCount;

      if (Debug)
         fprintf (stdout, "Remaining: %d Count: %d\n",
                  BufferRemaining, BufferCount);
   }

   /****************/
   /* close socket */
   /****************/

   if (status == SS$_LINKDISCON) status = SS$_NORMAL;

   sys$dassgn (RemoteChannel);

   return ("200 OK!");
}

/****************************************************************************/
/*
Output the response.  Can output only the header, only the body, both, and
also escape the HTML-forbidden characters "<", ">", and "&" so an HTML file
can be presented as plain text inside another HTML document.
*/

ProcessHttpResponse ()

{
   int  cnt;
   char  *bptr, *cptr, *sptr;
   char  SymbolName [256],
         SymbolValue [1024];

   /*********/
   /* begin */
   /*********/

   if (Debug) fprintf (stdout, "ProcessHttpResponse()\n");

   ResponseContentType[0] = '\0';

   if (!(cptr = BufferPtr)) return;
   if (!(cnt = BufferCount)) return;

   if (memcmp (cptr, "HTTP/", 5) ||
       !isdigit(cptr[5]) ||
       cptr[6] != '.' ||
       !isdigit(cptr[7]))
      ResponseHttpVersion = 9;
   else
      ResponseHttpVersion = 10;

   if (ResponseHttpVersion == 9)
   {
      /* HTTP/0.9 only ever returned HTML! */
      strcpy (ResponseContentType, "text/html");
   }
   else
   {
      /* process the response header */
      while (cnt)
      {
         /* create a symbol representing the response header line */
         sptr = SymbolName;
         for (bptr = "FETCH_"; *bptr; *sptr++ = *bptr++);
         if (!memcmp (cptr, "HTTP/", 5))
         {
            for (bptr = "STATUS"; *bptr; *sptr++ = *bptr++);
            *sptr = '\0';
            bptr = cptr;
         }
         else
         {
            for (bptr = cptr;
                 *bptr && *bptr != ':' &&
                    *bptr != ' ' && *bptr != '\t' &&
                    *bptr != '\r' && *bptr != '\n';
                 bptr++)
            {
               if (!isalnum(*bptr))
                  *sptr++ = '_';
               else
                  *sptr++ = *bptr;
            }
            *sptr = '\0';
         }
         if (*bptr == ':') bptr++;
         while (*bptr && (*bptr == ' ' || *bptr == '\t')) bptr++;
         sptr = SymbolValue;
         while (*bptr && *bptr != '\r' && *bptr != '\n')
            *sptr++ = *bptr++;
         *sptr = '\0';
         SetLocalSymbol (SymbolName, SymbolValue);

         if (toupper (cptr[0]) == 'C' &&
             strsame (cptr, "Content-Type:", 13))
         {
            cptr += 13;
            cnt -= 13;
            while (cnt && isspace(*cptr))
            {
               cptr++;
               cnt--;
            }
            sptr = ResponseContentType;
            while (cnt && *cptr != '\r' && *cptr != '\n')
            {
               *sptr++ = *cptr++;
               cnt--;
            }
            *sptr = '\0';
         }

         /* skip to end-of-line */
         while (cnt && *cptr != '\r' && *cptr != '\n')
         {
            cptr++;
            cnt--;
         }
         if (cnt && *cptr == '\r')
         {
            cptr++;
            cnt--;
         }
         if (cnt && *cptr == '\n')
         {
            cptr++;
            cnt--;
         }

         /* break if end of request header */
         if (cnt && *cptr == '\n')
         {
            cptr++;
            cnt--;
            break;
         }
         if (cnt >= 2 && cptr[0] == '\r' && cptr[1] == '\n')
         {
            cptr += 2;
            cnt -= 2;
            break;
         }
      }
   }

   if (Debug)
      fprintf (stdout, "ResponseContentType |%s|\n", ResponseContentType);

   if (DoCheckOnly) return;

   if (DoResponseHeader)
   {
      if (Debug) fprintf (stdout, "DoResponseHeader\n");
      if (cptr > BufferPtr)
         fwrite (BufferPtr, cptr-BufferPtr, 1, stdout);
   }

   if (DoResponseBody)
   {
      if (Debug) fprintf (stdout, "DoResponseBody\n");

      if (DoEscapeHtml)
      {
         cptr = (char*)CgiLibHtmlEscape (cptr, cnt, NULL, 0);
         cnt = strlen (cptr);
         fwrite (cptr, cnt, 1, stdout);
      }
      else
      if (cnt)
      {
         /* write response as-is */
         fwrite (cptr, cnt, 1, stdout);
      }
   }
}

/****************************************************************************/
/*
Fetch a response (directory listing or file) using the FTP protocol.
*/

char* FetchFtpResponse ()

{
   BOOL IsDirList,
        IsDosFileSystem,
        IsTypeAscii,
        IsUnixFileSystem,
        IsVmsFileSystem,
        IsUnknownFileSystem;
   int  status,
        ListenPort,
        LocalPort,
        IpAddress,
        ReadCount,
        ReturnLength;
   unsigned short  DataChannel,
                   FtpChannel,
                   ListenChannel;
   char  ch;
   char  *cptr, *sptr,
         *FileSystemPtr,
         *RemotePassPtr;
   char  Buffer [4096],
         CwdFtpDirectory [256],
         CwdFtpDirEncoded [256],
         FtpDirectory [256],
         FtpFile [256],
         FtpGreetingEscaped [256],
         FtpPwdEscaped [256],
         FtpStatEscaped [256],
         FtpSystemEscaped [256],
         LocalHost [128],
         RemotePass [256],
         RemoteUser [256],
         RemoteUserPass [256],
         RemoteUserPassEncoded [256],
         RequestPathEncoded [256],
         RequestPathEscaped [256],
         Scratch [1024];
   struct AnIOsb  IOsb;
   struct sockaddr_in  SocketName;
   struct {
      unsigned long  Length;
      void  *Address;
      int  *LengthPtr;
   } SocketNameItem =
      { sizeof(SocketName), &SocketName, &ReturnLength };

   /*********/
   /* begin */
   /*********/

   if (WatchEnabled) WatchThis ("FTP !AZ", FetchUrlPtr);

   if (WatchEnabled)
      FetchDebugFtp = true;
   else
   if (!TrnLnm ("FETCH$DBUG_FTP", NULL, 0))
      FetchDebugFtp = false;
   else
   {
      FetchDebugFtp = true;
      fprintf (stdout,
"HTTP/1.0 200 Success\n\
Content-Type: text/plain\n\
Script-Control: X-content-encoding-gzip=0\n\
\n");
   }

   CgiContentTypePtr = CgiLibVar ("WWW_CONTENT_TYPE");
   if (!CgiContentTypePtr[0])
      CgiContentTypePtr = FtpDefaultContentTypePtr;
   else
   if (!strcmp (CgiContentTypePtr, "x-internal/unknown"))
      CgiContentTypePtr = FtpDefaultContentTypePtr;

   RemotePassPtr = NULL;
   RemoteHost[0] = RemoteUser[0] =
      RemoteUserPass[0] = RemoteUserPassEncoded[0] = '\0';

   if (strsame (FetchUrlPtr, "/ftp://", 7)) FetchUrlPtr++;
   cptr = FetchUrlPtr;
   if (strsame (cptr, "ftp://", 6)) cptr += 6;

   if (*CgiServerNamePtr)
      strcpy (LocalHost, CgiServerNamePtr);
   else
      strcpy (LocalHost, "localhost");
   if (*CgiServerPortPtr)
      LocalPort = atoi(CgiServerPortPtr);
   else
      LocalPort = 21;
   if (LocalPort == 21)
      strcpy (LocalHostPort, LocalHost);
   else
      sprintf (LocalHostPort, "%s:%d", LocalHost, LocalPort);
   if (Debug) fprintf (stdout, "LocalHostPort |%s|\n", LocalHostPort);

   if (*cptr == '/')
   {
      strcpy (RemoteHost, LocalHost);
      RemotePort = LocalPort;
      strcpy (RemoteHostPort, LocalHostPort);
   }
   else
   {
      /* get optional username[:password], host and optional port */
      for (sptr = cptr; *sptr && *sptr != '/' && *sptr != '@'; sptr++);
      if (*sptr == '@')
      {
         sptr = RemoteUser;
         while (*cptr && *cptr != '@') *sptr++ = *cptr++;
         *sptr = '\0';
         if (*cptr) cptr++;
         for (sptr = RemoteUser; *sptr && *sptr != ':'; sptr++);
         if (*sptr)
         {
            *sptr++ = '\0';
            RemotePassPtr = sptr;
         }
         sprintf (RemoteUserPass, "%s:%s", RemoteUser, RemotePassPtr);
      }
      sptr = RemoteHost;
      while (*cptr && *cptr != '/' && *cptr != ':')
          *sptr++ = *cptr++;
      *sptr = '\0';
      if (*cptr == ':')
      {
         cptr++;
         RemotePort = atoi(cptr);
         if (!RemotePort) RemotePort = 80;
         while (*cptr && *cptr != '/') cptr++;
      }
      else
         RemotePort = 21;

      if (RemotePort == 21)
         strcpy (RemoteHostPort, RemoteHost);
      else
         sprintf (RemoteHostPort, "%s:%d", RemoteHost, RemotePort);
   }
   RemoteHostPortLength = strlen(RemoteHostPort);
   if (Debug) fprintf (stdout, "|%s|%s|\n", RemoteHostPort, cptr);

   if (IsFetchScript && *cptr != '/')
   {
      /* no path (i.e. "http://remote.host.name") which can break links */
      fprintf (stdout,
"HTTP/1.0 302 Moved temporarily\r\n\
Location: %s%s/\r\n\
\r\n",
         FetchPrefix, FetchUrlPtr);
      return ("302 Redirection!");
   }

   if (DoMassageLinks)
   {
      sprintf (FetchPrefix, "%s//%s%s/~",
               CgiRequestSchemePtr, LocalHostPort, CgiScriptNamePtr);
      sprintf (MassageLinksPath, "%s/~", CgiScriptNamePtr);
   }
   else
      FetchPrefix[0] = MassageLinksPath[0] = '\0';

   sptr = RequestPath;
   while (*cptr) *sptr++ = *cptr++;
   *sptr = '\0';
   if (Debug) fprintf (stdout, "|%s|\n", RequestPath);

   if (RemoteUserPass[0])
   {
      sptr = RemoteUserPassEncoded;
      cptr = RemoteUserPass;
      while (*cptr)
      {
         switch (*cptr)
         {
            case ' ' :
               *sptr++ = '%'; *sptr++ = '2'; *sptr++ = '0'; cptr++; break;
            case '?' :
               *sptr++ = '%'; *sptr++ = '3'; *sptr++ = 'f'; cptr++; break;
            case '@' :
               *sptr++ = '%'; *sptr++ = '4'; *sptr++ = '0'; cptr++; break;
            default : *sptr++ = *cptr++;
         }
      }
      *sptr++ = '@';
      *sptr = '\0';
   }
   if (Debug)
      fprintf (stdout, "RemoteUserPassEncoded |%s|\n", RemoteUserPassEncoded);

   if (DoMassageLinks)
   {
      sprintf (FetchPrefix, "%s//%s%s/",
               CgiRequestSchemePtr, LocalHostPort, CgiScriptNamePtr);
      if (Debug) fprintf (stdout, "FetchPrefix |%s|\n", FetchPrefix);
   }
   else
      FetchPrefix[0] = '\0';

   IsDirList = IsTypeAscii = false;
   CwdFtpDirectory[0] = CwdFtpDirEncoded[0] = FtpDirectory[0] = '\0';

   for (cptr = RequestPath; *cptr && *cptr != ';'; cptr++);
   if (cptr[-1] == '/') IsDirList = true;
   if (*cptr)
      *cptr++ = '\0';
   else
   {
      /* no request modifies on path, have a look on the query string */
      strcpy (cptr = Scratch, CgiQueryStringPtr);
      CgiLibUrlDecode (cptr);
   }

   while (*cptr)
   {
      /**************************/
      /* URL file type modifier */
      /**************************/

      if (Debug) fprintf (stdout, "cptr |%s|\n", cptr);
      if (*cptr == ';') cptr++; 
      if (!memcmp (cptr, "type=", 5))
      {
         if (!memcmp (cptr, "type=debug", 10))
         {
            cptr += 10;
            FetchDebugFtp = true;
         }
         else
         if (!memcmp (cptr, "type=dos", 8))
         {
            cptr += 8;
            IsUnixFileSystem = IsUnknownFileSystem = IsVmsFileSystem = false;
            IsDosFileSystem = true;
         }
         else
         if (!memcmp (cptr, "type=unix", 9))
         {
            cptr += 9;
            IsDosFileSystem = IsUnknownFileSystem = IsVmsFileSystem = false;
            IsUnixFileSystem = true;
         }
         else
         if (!memcmp (cptr, "type=unknown", 12))
         {
            cptr += 12;
            IsDosFileSystem = IsUnixFileSystem = IsVmsFileSystem = false;
            IsUnknownFileSystem = true;
         }
         else
         if (!memcmp (cptr, "type=vms", 8))
         {
            cptr += 8;
            IsDosFileSystem = IsUnknownFileSystem = IsUnixFileSystem = false;
            IsVmsFileSystem = true;
         }
         else
         if (!memcmp (cptr, "type=a", 6))
         {
            cptr += 6;
            IsTypeAscii = true;
            CgiContentTypePtr = "text/plain";
         }
         else
         if (!memcmp (cptr, "type=d", 6))
         {
            cptr += 6;
            IsDirList = true;
            /* if not already that way terminate the path with a '/' */
            strcat (RequestPath, "/");
         }
         else
         if (!memcmp (cptr, "type=i", 6))
         {
            cptr += 6;
            IsTypeAscii = false;
            CgiContentTypePtr = "application/octet-stream";
         }
      }
      else
      if (!memcmp (cptr, "cwd=", 4))
      {
         cptr += 4;
         sptr = CwdFtpDirectory;
         while (*cptr && *cptr != ';') *sptr++ = *cptr++;
         *sptr = '\0';
         if (Debug) fprintf (stdout, "CwdFtpDirectory |%s|\n", CwdFtpDirectory);
         strcpy (CwdFtpDirEncoded, "cwd=");
         CgiLibUrlEncode (CwdFtpDirectory, -1,
                          CwdFtpDirEncoded+4, sizeof(CwdFtpDirEncoded)-4);
      }
      else
         return ("500 Unknown modifier.");
   }

   if (IsDirList || !memcmp(CgiContentTypePtr, "text/", 5))
      IsTypeAscii = true;

   /*********/
   /* login */
   /*********/

   status = OpenConnection (&FtpChannel, RemoteHost, RemotePort, NULL);
   if (VMSnok (status)) return (ReplyVmsError (status));
   cptr = FtpReply (FtpChannel);
   for (sptr = cptr; *sptr && *sptr != '\r' && *sptr != '\n'; sptr++);
   *sptr = '\0';
   if (cptr[0] == '4' || cptr[0] == '5')
   {
      sys$dassgn (FtpChannel);
      return (cptr);
   }
   CgiLibHtmlEscape (cptr+4, -1, FtpGreetingEscaped,
                    sizeof(FtpGreetingEscaped));
   
   /* get the IP address of the connected command socket */
   if (Debug) fprintf (stdout, "sys$qiow() IO$_SENSEMODE\n");
   status = sys$qiow (0, FtpChannel, IO$_SENSEMODE, &IOsb, 0, 0,
                      0, 0, &SocketNameItem, 0, 0, 0);
   if (Debug)
      fprintf (stdout, "sys$qiow() %%X%08.08X IOsb %%X%08.08X\n",
               status, IOsb.Status);
   if (VMSok (status) && VMSnok (IOsb.Status)) status = IOsb.Status;
   if (VMSnok (status)) return (ReplyVmsError (status));
   memcpy (&IpAddress, &SocketName.sin_addr.s_addr, 4);

   /* now we've got the IP address we can build an anonymous password */
   if (!RemoteUser[0]) strcpy (RemoteUser, "anonymous");
   if (!RemotePassPtr)
   {
      sprintf (RemotePassPtr = RemotePass, "proxy@%d.%d.%d.%d",
               IpAddress & 0x000000ff,
               (IpAddress & 0x0000ff00) >> 8,
               (IpAddress & 0x00ff0000) >> 16,
               /* signed ints, mask off the shifted sign bit */
               ((IpAddress & 0xff000000) >> 24) & 0xff);
   }

   cptr = FtpCommand (true, FtpChannel, "USER %s\r\n", RemoteUser);
   if (cptr[0] == '4' || cptr[0] == '5')
   {
      sys$dassgn (FtpChannel);
      return (cptr);
   }

   if (!memcmp (cptr, "331", 3))
   {
      cptr = FtpCommand (true, FtpChannel, "PASS %s\r\n", RemotePassPtr);
      if (cptr[0] == '4' || cptr[0] == '5')
      {
         sys$dassgn (FtpChannel);
         return (cptr);
      }
   }

   if (IsTypeAscii)
      cptr = FtpCommand (true, FtpChannel, "TYPE A\r\n");
   else
      cptr = FtpCommand (true, FtpChannel, "TYPE I\r\n");
   if (cptr[0] == '4' || cptr[0] == '5')
   {
      sys$dassgn (FtpChannel);
      return (cptr);
   }

   if (RequestPath[0] == '/' && RequestPath[1] == '|')
   {
      /********************/
      /* ad hoc commands */
      /*******************/

      fprintf (stdout,
"HTTP/1.0 200 Success\n\
Content-Type: text/plain\n\
\n");

      strcpy (sptr = Scratch, RequestPath+2);
      CgiLibUrlDecode (sptr);

      while (*sptr)
      {
         cptr = sptr;
         while (*sptr && *sptr != '|') sptr++;
         if (*sptr) *sptr++ = '\0';
         cptr = FtpCommand (false, FtpChannel, "%s\r\n", cptr);
         if (cptr[0] == '4' || cptr[0] == '5')
         {
            fprintf (stdout, "%s\n", ReplyVmsError (status));
            break;
         }

         for (;;)
         {
            status = ReadConnection (FtpChannel, Buffer, sizeof(Buffer),
                                     &ReadCount, true);
            if (VMSnok (status))
            {
               fprintf (stdout, "%s\n", ReplyVmsError (status));
               break;
            }
            fprintf (stdout, "%s", Buffer);
            cptr = Buffer;
            while (*cptr)
            {
               if (isdigit(cptr[0]) && isdigit(cptr[1]) &&
                   isdigit(cptr[2]) && cptr[3] == ' ') break;
               while (*cptr && *cptr != '\r' && *cptr != '\n') cptr++;
               while (*cptr == '\r' || *cptr == '\n') cptr++;
            }
            if (isdigit(cptr[0]) && isdigit(cptr[1]) &&
                isdigit(cptr[2]) && cptr[3] == ' ') break;
         }
      }

      sys$dassgn (FtpChannel);

      return ("200 OK!");
   }

   /************************************/
   /* determine (probable) file system */
   /************************************/

   cptr = FtpCommand (true, FtpChannel, "SYST\r\n");
   if (cptr[0] == '4' || cptr[0] == '5')
   {
      sys$dassgn (FtpChannel);
      return (cptr);
   }
   for (sptr = cptr; *sptr && *sptr != '\r' && *sptr != '\n'; sptr++);
   *sptr = '\0';
   CgiLibHtmlEscape (cptr+4, -1, FtpSystemEscaped, sizeof(FtpSystemEscaped));

   cptr = FtpCommand (true, FtpChannel, "PWD\r\n");
   if (cptr[0] == '4' || cptr[0] == '5')
   {
      sys$dassgn (FtpChannel);
      return (cptr);
   }

   IsDosFileSystem = IsUnixFileSystem =
      IsUnknownFileSystem = IsVmsFileSystem = false;
   if (strchr (cptr, '/'))
   {
      IsUnixFileSystem = true;
      FileSystemPtr = "Unix";
   }
   else
   if (strstr (cptr, ":["))
   {
      IsVmsFileSystem = true;
      FileSystemPtr = "VMS";
   }
   else
   if (strchr (cptr, '\\'))
   {
      IsDosFileSystem = true;
      FileSystemPtr = "DOS";
   }
   else
   {
      IsUnknownFileSystem = true;
      FileSystemPtr = "unknown";
   }

   if (WatchEnabled) WatchThis ("FTP FILE-SYSTEM !AZ", FileSystemPtr);

   if (RequestPath[1] && IsVmsFileSystem)
   {
      sptr = FtpDirectory;
      if (strchr (RequestPath+1, '/'))
      {
         *sptr++ = '[';
         *sptr++ = '.';
      }
      for (cptr = RequestPath+1; *cptr; *sptr++ = *cptr++);
      *sptr = '\0';
      /* turn any final '/' into a directory delimiting ']' */
      while (sptr > FtpDirectory && *sptr != '/')
      {
         sptr--;
         cptr--;
      }
      if (*sptr == '/')
      {
         *sptr++ = ']';
         cptr++;
      }
      *sptr = '\0';
      /* turn any intermediate '/' into directory separating '.' */
      for (sptr = FtpDirectory; *sptr; sptr++)
         if (*sptr == '/') *sptr = '.';
      /* get any file component */
      sptr = FtpFile;
      while (*cptr) *sptr++ = *cptr++;
      *sptr = '\0';
   }
   else
   if (RequestPath[1])
   {
      sptr = FtpDirectory;
      *sptr++ = '.';
      for (cptr = RequestPath; *cptr; *sptr++ = *cptr++);
      *sptr = '\0';
      while (sptr > FtpDirectory && *sptr != '/')
      {
         sptr--;
         cptr--;
      }
      if (*sptr == '/')
      {
         sptr++;
         cptr++;
      }
      *sptr = '\0';
      /* get any file component */
      sptr = FtpFile;
      while (*cptr) *sptr++ = *cptr++;
      *sptr = '\0';
      if (IsDosFileSystem)
      {
         /* for DOS, turn each forward slash into a back-slash */
         for (sptr = FtpDirectory; *sptr; sptr++)
            if (*sptr == '/') *sptr = '\\';
      }
   }
   else
      strcpy (FtpFile, RequestPath+1);
   if (Debug) fprintf (stdout, "|%s|%s|\n", FtpDirectory, FtpFile);

   if (CwdFtpDirectory[0])
   {
      /*******************/
      /* ;cwd= directory */
      /*******************/

      cptr = FtpCommand (true, FtpChannel, "CWD %s\r\n", CwdFtpDirectory);
      if (cptr[0] == '4' || cptr[0] == '5')
      {
         sys$dassgn (ListenChannel);
         sys$dassgn (FtpChannel);
         return (cptr);
      }
   }

   if (FtpDirectory[0])
   {
      /*********************/
      /* request directory */
      /*********************/

      cptr = FtpCommand (true, FtpChannel, "CWD %s\r\n", FtpDirectory);
      if (cptr[0] == '4' || cptr[0] == '5')
      {
         sys$dassgn (ListenChannel);
         sys$dassgn (FtpChannel);
         return (cptr);
      }
   }

   if (IsDirList)
   {
      /* get the directory location for inclusion in the directory listing */
      cptr = FtpCommand (true, FtpChannel, "PWD\r\n");
      if (cptr[0] == '4' || cptr[0] == '5')
      {
         sys$dassgn (FtpChannel);
         return (cptr);
      }
      for (sptr = cptr; *sptr && *sptr != '\r' && *sptr != '\n'; sptr++)
         if (*sptr == '\"') *sptr = '\'';
      *sptr = '\0';
      CgiLibHtmlEscape (cptr+4, -1, FtpPwdEscaped, sizeof(FtpPwdEscaped));
   }

   /**********************/
   /* open listen socket */
   /**********************/

   /* assign a channel to the internet template device */
   if (VMSnok (status = sys$assign (&InetDeviceDsc, &ListenChannel, 0, 0)))
      return (ReplyVmsError (status));

   SocketNameItem.Length = sizeof(SocketName);
   SocketNameItem.Address = &SocketName;

   status = sys$qiow (0, ListenChannel, IO$_SETMODE, &IOsb, 0, 0,
                      &TcpSocket, 0, 0, 1, 0, 0);
   if (Debug)
      fprintf (stdout, "sys$qiow() %%X%08.08X IOsb %%X%08.08X\n",
               status, IOsb.Status);
   if (VMSok (status) && VMSnok (IOsb.Status)) status = IOsb.Status;
   if (VMSnok (status))
   {
      sys$dassgn (FtpChannel);
      return (ReplyVmsError (status));
   }

   /* get the port number listening */
   if (Debug) fprintf (stdout, "sys$qiow() IO$_SENSEMODE\n");
   status = sys$qiow (0, ListenChannel, IO$_SENSEMODE, &IOsb, 0, 0,
                      0, 0, &SocketNameItem, 0, 0, 0);
   if (Debug)
      fprintf (stdout, "sys$qiow() %%X%08.08X IOsb %%X%08.08X\n",
               status, IOsb.Status);
   if (VMSok (status) && VMSnok (IOsb.Status)) status = IOsb.Status;
   if (VMSnok (status))
   {
      sys$dassgn (FtpChannel);
      sys$dassgn (ListenChannel);
      return (ReplyVmsError (status));
   }
   ListenPort = (int)SocketName.sin_port;

   /*****************************/
   /* tell FTP server data port */
   /*****************************/

   cptr = FtpCommand (true, FtpChannel, "PORT %d,%d,%d,%d,%d,%d\r\n",
                      IpAddress & 0x000000ff,
                      (IpAddress & 0x0000ff00) >> 8,
                      (IpAddress & 0x00ff0000) >> 16,
                      /* signed ints, mask off the shifted sign bit */
                      ((IpAddress & 0xff000000) >> 24) & 0xff,
                      (ListenPort & 0x000000ff),
                      (ListenPort & 0x0000ff00) >> 8);
   if (cptr[0] == '4' || cptr[0] == '5')
   {
      sys$dassgn (FtpChannel);
      return (cptr);
   }
 
   if (IsDirList)
   {
      /*********************/
      /* directory listing */
      /*********************/

      if (!FtpIconDirImg[0] && IconPathPtr[0])
      {
         sprintf (FtpIconDirImg,
            "<IMG SRC=\"%s//%s:%s%sdirectory.gif\" ALT=\" [DIR] \" ALIGN=top> ",
            CgiRequestSchemePtr, CgiServerNamePtr,
            CgiServerPortPtr, IconPathPtr); 
         sprintf (FtpIconFileImg,
            "<IMG SRC=\"%s//%s:%s%sfile.gif\" ALT=\"[FILE] \" ALIGN=top> ",
            CgiRequestSchemePtr, CgiServerNamePtr,
            CgiServerPortPtr, IconPathPtr); 
      }

      if (IsVmsFileSystem)
         cptr = FtpCommand (true, FtpChannel, "LIST *.*;0\r\n");
      else
      if (IsUnixFileSystem || IsDosFileSystem)
         cptr = FtpCommand (true, FtpChannel, "LIST\r\n");
      else
         cptr = FtpCommand (true, FtpChannel, "NLST\r\n");
      if (cptr[0] == '4' || cptr[0] == '5')
      {
         sys$dassgn (ListenChannel);
         sys$dassgn (FtpChannel);
         return (cptr);
      }
      /* it has been observed that responses can span commands with LIST */
      while (*cptr && *cptr != '\n') cptr++;
      if (*cptr) cptr++;

      /*************************/
      /* accept on data socket */
      /*************************/

      /* assign a channel to the internet template device */
      if (VMSnok (status = sys$assign (&InetDeviceDsc, &DataChannel, 0, 0)))
         return (ReplyVmsError (status));

      status = sys$qiow (0, ListenChannel, IO$_ACCESS|IO$M_ACCEPT, &IOsb, 0, 0,
                         0, 0, &SocketNameItem, &DataChannel, 0, 0);
      if (Debug)
         fprintf (stdout, "sys$qiow() %%X%08.08X IOsb %%X%08.08X\n",
                  status, IOsb.Status);
      if (VMSok (status) && VMSnok (IOsb.Status)) status = IOsb.Status;
      if (VMSnok (status))
      {
         sys$dassgn (ListenChannel);
         sys$dassgn (FtpChannel);
         return (ReplyVmsError (status));
      }

      /********************/
      /* read data stream */
      /********************/

      if (BufferChunk <= 0) BufferChunk = DEFAULT_BUFFER_CHUNK;

      /* with CGIplus 'BufferPtr'/'BufferSize' may still have memory */
      BufferCount = 0;
      BufferRemaining = BufferSize;
      BufferCurrentPtr = BufferPtr;

      for (;;)
      {
         if (BufferCount == BufferSize)
         {
            BufferSize += (BufferRemaining = (BufferChunk << 10));
            if (!(BufferPtr = realloc (BufferPtr, BufferSize+1)))
               exit (vaxc$errno);
            BufferCurrentPtr = BufferPtr + BufferSize - BufferRemaining;
         }

         ReadCount = BufferRemaining <= 32767 ? BufferRemaining : 32767,
         status = ReadConnection (DataChannel, BufferCurrentPtr, ReadCount,
                                  &ReadCount, false);
         if (VMSnok (status)) break;

         BufferCount += ReadCount;
         BufferCurrentPtr += ReadCount;
         BufferRemaining -= ReadCount;

         if (Debug)
            fprintf (stdout, "Remaining: %d Count: %d\n",
                     BufferRemaining, BufferCount);
      }

      BufferPtr[BufferCount] = '\0';
      /** if (Debug) fprintf (stdout, "|%s|\n", BufferPtr); **/

      if (FetchDebugFtp) fprintf (stdout, "->|%s|\n", BufferPtr);

      sys$dassgn (DataChannel);
      sys$dassgn (ListenChannel);

      /*******************/
      /* final FTP reply */
      /*******************/

      /* it has been observed that responses can span commands with LIST */
      if (!*cptr) cptr = FtpReply (FtpChannel);
      if (cptr[0] == '4' || cptr[0] == '5')
      {
         sys$dassgn (FtpChannel);
         return (cptr);
      }

      if (DoCheckOnly)
      {
         FtpCommand (true, FtpChannel, "QUIT\r\n");
         sys$dassgn (FtpChannel);
         return ("200 OK!");
      }

      /*****************/
      /* generate page */
      /*****************/

      CgiLibUrlEncode (RequestPath, -1,
                       RequestPathEncoded, sizeof(RequestPathEncoded));
      CgiLibHtmlEscape (RequestPath, -1,
                        RequestPathEscaped, sizeof(RequestPathEscaped));

      fprintf (stdout,
"HTTP/1.0 200 Success\n\
Server: %s\n\
Content-Type: text/html\n\
\n\
<HTML>\n\
<HEAD>\n\
<META NAME=\"generator\" CONTENT=\"%s\">\n\
<META NAME=\"ftp-greeting\" CONTENT=\"%s\">\n\
<META NAME=\"ftp-system\" CONTENT=\"%s\">\n\
<META NAME=\"ftp-pwd\" CONTENT=\"%s\">\n\
<META NAME=\"file-system\" CONTENT=\"%s\">\n\
<TITLE>Directory of %s</TITLE>\n\
</HEAD>\n\
<BODY>\n\
<H2>%s %s</H2>\n\
%s\
<PRE>",
         CgiServerSoftwarePtr, SoftwareId,
         FtpGreetingEscaped, FtpSystemEscaped, FtpPwdEscaped, FileSystemPtr,
         RequestPathEscaped, FtpCurrentDirectory, RequestPathEscaped,
         IsUnknownFileSystem ?
           "<B>Note:</B> &nbsp;FTP server type not recognized!\n<P>\n" : "");

      if (IsVmsFileSystem)
         ProcessFtpVmsList (RequestPathEncoded,
                            RemoteUserPassEncoded,
                            CwdFtpDirEncoded);
      else
      if (IsUnixFileSystem)
         ProcessFtpUnixList (RequestPathEncoded,
                             RemoteUserPassEncoded,
                             CwdFtpDirEncoded);
      else
      if (IsDosFileSystem)
         ProcessFtpDosList (RequestPathEncoded,
                            RemoteUserPassEncoded,
                            CwdFtpDirEncoded);
      else
         ProcessFtpUnknownList (RequestPathEncoded,
                                RemoteUserPassEncoded,
                                CwdFtpDirEncoded);

      fprintf (stdout,
"</PRE>\n\
</BODY>\n\
</HTML>\n");
   }
   else
   {
      /*****************/
      /* file transfer */
      /*****************/

      cptr = FtpCommand (true, FtpChannel, "RETR %s\r\n", FtpFile);
      if (Debug) fprintf (stdout, "cptr |%s|\n", cptr);
      if (cptr[0] == '4' || cptr[0] == '5')
      {
         sys$dassgn (ListenChannel);
         sys$dassgn (FtpChannel);
         return (cptr);
      }
      /* it has been observed that responses can span commands with RETR */
      while (*cptr && *cptr != '\n') cptr++;
      if (*cptr) cptr++;

      /*************************/
      /* accept on data socket */
      /*************************/

      /* assign a channel to the internet template device */
      if (VMSnok (status = sys$assign (&InetDeviceDsc, &DataChannel, 0, 0)))
         return (ReplyVmsError (status));

      status = sys$qiow (0, ListenChannel, IO$_ACCESS|IO$M_ACCEPT, &IOsb, 0, 0,
                         0, 0, &SocketNameItem, &DataChannel, 0, 0);
      if (Debug)
         fprintf (stdout, "sys$qiow() %%X%08.08X IOsb %%X%08.08X\n",
                  status, IOsb.Status);
      if (VMSok (status) && VMSnok (IOsb.Status)) status = IOsb.Status;
      if (VMSnok (status))
      {
         sys$dassgn (ListenChannel);
         sys$dassgn (FtpChannel);
         return (ReplyVmsError (status));
      }

      /********************/
      /* read data stream */
      /********************/

      if (*OutputPtr)
      {
         /* FTP response is being output to a file */
         if (!(stdout = freopen (OutputPtr, "w", stdout)))
            exit (vaxc$errno);
      }
      else
      {
         fprintf (stdout,
"HTTP/1.0 200 Success\n\
Server: %s\n\
Content-Type: %s\n\
\n",
            CgiServerSoftwarePtr, CgiContentTypePtr);
      }

      for (;;)
      {
         status = ReadConnection (DataChannel, Buffer, sizeof(Buffer),
                                  &ReadCount, false);
         if (VMSnok (status)) break;
         if (!DoCheckOnly) fwrite (Buffer, ReadCount, 1, stdout);
      }

      sys$dassgn (DataChannel);
      sys$dassgn (ListenChannel);

      /* was being written to a file, reopen to <stdout> */
      if (*OutputPtr)
      {
         if (!(stdout = freopen ("SYS$OUTPUT:", "w", stdout)))
            exit (vaxc$errno);
      }

      /* it has been observed that responses can span commands with RETR */
      if (!*cptr) cptr = FtpReply (FtpChannel);
      if (Debug) fprintf (stdout, "cptr |%s|\n", cptr);
      if (cptr[0] == '4' || cptr[0] == '5')
      {
         sys$dassgn (FtpChannel);
         return (cptr);
      }
   }

   /********************/
   /* close connection */
   /********************/

   if (status == SS$_LINKDISCON) status = SS$_NORMAL;

   FtpCommand (true, FtpChannel, "QUIT\r\n");
   sys$dassgn (FtpChannel);

   if (VMSnok (status)) return (ReplyVmsError (status));

   return ("200 OK!");
}

/****************************************************************************/
/*
Variable length argument list.  Send the printf()ed command to the FTP server,
optionally reading the reply.
*/

char* FtpCommand
(
BOOL GetReply,
unsigned short Channel,
char *FormatString,
...
)
{
   int  status,
        argcnt,
        Length;
   char  *cptr;
   char  Buffer [1024];
   va_list  argptr;

   /*********/
   /* begin */
   /*********/

   if (Debug) fprintf (stdout, "FtpCommand() |%s|\n", FormatString);

   va_count (argcnt);

   va_start (argptr, FormatString);
   Length = vsprintf (Buffer, FormatString, argptr);
   if (Debug) fprintf (stdout, "%d |%s|\n", Length, Buffer);

   if (FetchDebugFtp)
   {
      for (cptr = Buffer + Length;
           cptr > Buffer && (!*cptr || *cptr == '\r' || *cptr == '\n');
           cptr--);
      if (*cptr && *cptr != '\r' && *cptr != '\n') cptr++;
      fprintf (stdout, "->|%*.*s|\n", cptr-Buffer, cptr-Buffer, Buffer);
   }
   status = WriteConnection (Channel, Buffer, Length);
   if (VMSnok (status)) return (ReplyVmsError (status));

   if (GetReply) return (FtpReply (Channel));

   return ("200 OK!");
}

/****************************************************************************/
/*
Read and return a single line response from the FTP server (With multi-line
responses it returns only the last line).
*/

char* FtpReply (unsigned short Channel)

{
   static char  Message [256] = "599 ",
                Buffer [1024];
   static $DESCRIPTOR (MessageDsc, Message);

   int  status,
        BufferRemaining,
        ReadCount;
   short int  Length;
   char  *cptr, *sptr,
         *BufferPtr;

   /*********/
   /* begin */
   /*********/

   if (Debug) fprintf (stdout, "FtpReply()\n");

   BufferPtr = Buffer;
   BufferRemaining = sizeof(Buffer)-1;

   for (;;)
   {
      status = ReadConnection (Channel, BufferPtr, BufferRemaining,
                               &ReadCount, true);
      if (VMSnok (status)) return (ReplyVmsError (status));

      for (cptr = BufferPtr; *cptr && *cptr != '\r' && *cptr != '\n'; cptr++);
      if (*cptr != '\r' && *cptr != '\n')
      {
         /* all lines must be terminated with carriage control, get rest */
         BufferPtr += ReadCount;
         BufferRemaining -= ReadCount;
         continue;
      }
      if (Debug) fprintf (stdout, "|%s|\n", Buffer);

      if (FetchDebugFtp) fprintf (stdout, "<-|%s|\n", Buffer);

      cptr = sptr = Buffer;
      while (*cptr)
      {
         sptr = cptr;
         if (isdigit(cptr[0]) && isdigit(cptr[1]) &&
             isdigit(cptr[2]) && cptr[3] == ' ') break;
         while (*cptr && *cptr != '\r' && *cptr != '\n') cptr++;
         while (*cptr == '\r' || *cptr == '\n') cptr++;
      }
      if (isdigit(cptr[0]) && isdigit(cptr[1]) &&
          isdigit(cptr[2]) && cptr[3] == ' ') return (sptr);
   }
}

/****************************************************************************/
/*
Convert a VMS status value into a pseudo-reply-message containing the
corresponding VMS error message.  For example,
"599 %X0000028C Remote node is unknown".  The hexadecimal status value can be
converted back and used as an exit status.
*/

char* ReplyVmsError (int StatusValue)

{
   static $DESCRIPTOR (StringFaoDsc, "599 %X!XL !AZ.");
   static char  Message [256],
                String [256];
   static $DESCRIPTOR (MessageDsc, Message);
   static $DESCRIPTOR (StringDsc, String);

   int  status;
   short int  Length;

   /*********/
   /* begin */
   /*********/

   if (Debug) fprintf (stdout, "ReplyVmsError() %%X%08.08X\n", StatusValue);

   status = sys$getmsg (StatusValue, &Length, &MessageDsc, 1, 0); 
   if (VMSok (status))
   {
      Message[Length] = '\0';
      Message[0] = toupper(Message[0]);
   }
   else
      strcpy (Message, "&quot;sys$getmsg() failed&quot;");

   status = sys$fao (&StringFaoDsc, &Length, &StringDsc, StatusValue, Message); 
   if (VMSok (status))
      String[Length] = '\0';
   else
      strcpy (String, "599 %X00000002 &quot;sys$fao() failed&quot;");

   if (Debug) fprintf (stdout, "|%s|\n", String);
   return (String);
}

/****************************************************************************/
/*
HTML format a VMS FTP server directory listing.
Expected format: "file-name  size-blocks  date_time  any-thing-else..."
*/

ProcessFtpVmsList 
(
char *RequestPathEncoded,
char *RemoteUserPassEncoded,
char *CwdFtpDirEncoded
)
{
   BOOL  IsDirectory;
   int  DirectoryCount,
        FileCount;
   char  *cptr, *sptr;
   char  FileDate [256],
         FileNameEncoded [256],
         FileNameEscaped [256],
         FileName [256],
         FileSize [256];

   /*********/
   /* begin */
   /*********/

   if (Debug) fprintf (stdout, "ProcessFtpVmsList()\n");

   DirectoryCount = FileCount = 0;

   cptr = BufferPtr;
   while (*cptr)
   {
      /* skip leading white-space, blank lines, etc. */
      while (*cptr && *cptr == ' ') cptr++;
      if (!cptr) break;
      if (*cptr == '\r' || *cptr == '\n')
      {
         while (*cptr == '\r' || *cptr == '\n') cptr++;
         continue;
      }

      sptr = FileName;
      while (*cptr && *cptr != ' ' && *cptr != ';' &&
             *cptr != '\r' && *cptr != '\n')
         *sptr++ = *cptr++;
      *sptr = '\0';

      if (*cptr == ';')
      {
         /* skip version number in file specification */
         while (*cptr && *cptr != ' ' && *cptr != '\r' && *cptr != '\n')
            cptr++;
      }
      /* absorb white-space between name and size */
      while (*cptr == ' ') cptr++;

      sptr = FileSize;
      while (*cptr && *cptr != ' ' && *cptr != '\r' && *cptr != '\n')
         *sptr++ = *cptr++;
      *sptr = '\0';

      /* absorb white-space between size and date */
      while (*cptr == ' ') cptr++;

      sptr = FileDate;
      while (*cptr && *cptr != ' ' && *cptr != '\r' && *cptr != '\n')
         *sptr++ = *cptr++;
      while (*cptr == ' ') *sptr++ = *cptr++;
      while (*cptr && *cptr != ' ' && *cptr != '\r' && *cptr != '\n')
         *sptr++ = *cptr++;
      *sptr = '\0';

      /* skip to start of next line */
      while (*cptr && *cptr != '\r' && *cptr != '\n') cptr++;
      while (*cptr == '\r' || *cptr == '\n') cptr++;

      if (FileName[0] && !FileSize[0] && !FileDate[0] &&
          strlen(FileName) > 16)
      {
         /***************************************************/
         /* file name too long, distibuted across two lines */
         /***************************************************/

         /* skip leading white-space */
         while (*cptr && *cptr == ' ') cptr++;
         if (!cptr) break;

         sptr = FileSize;
         while (*cptr && *cptr != ' ' && *cptr != '\r' && *cptr != '\n')
            *sptr++ = *cptr++;
         *sptr = '\0';

         /* absorb white-space between size and date */
         while (*cptr == ' ') cptr++;

         sptr = FileDate;
         while (*cptr && *cptr != ' ' && *cptr != '\r' && *cptr != '\n')
            *sptr++ = *cptr++;
         while (*cptr == ' ') *sptr++ = *cptr++;
         while (*cptr && *cptr != ' ' && *cptr != '\r' && *cptr != '\n')
            *sptr++ = *cptr++;
         *sptr = '\0';
      }

      /* if all components not present then just ignore */
      if (!FileName[0] || !FileSize[0] || !FileDate[0]) continue;

      /* try to eliminate other lines ... file size really look like one? */
      for (sptr = FileSize; isdigit(*sptr) || *sptr == '/'; sptr++);
      if (*sptr) continue;

      /* try to eliminate other lines ... file date really look like one? */
      sptr = FileDate;
      if (!((isdigit(sptr[0]) && isdigit(sptr[1]) && sptr[2] == '-') ||
            (isdigit(sptr[0]) && sptr[1] == '-')))
         continue;

      for (sptr = FileName; *sptr; sptr++);
      while (sptr > FileName && *sptr != '.') sptr--;
      if (*(unsigned long*)sptr == '.DIR')
      {
         /* terminate to eliminate the ".DIR" */
         *sptr++ = '/';
         *sptr = '\0';
         IsDirectory = true;
         sptr = FtpIconDirImg;
         DirectoryCount++;
      }
      else
      {
         IsDirectory = false;
         sptr = FtpIconFileImg;
         FileCount++;
      }

      CgiLibUrlEncode (FileName, -1, FileNameEncoded, sizeof(FileNameEncoded));
      CgiLibHtmlEscape (FileName, -1, FileNameEscaped, sizeof(FileNameEscaped));

      fprintf (stdout,
" %s<A HREF=\"%sftp://%s%s%s%s%s%s\">%s</A>%*s ",
         sptr, MassageLinksPath,
         RemoteUserPassEncoded, RemoteHostPort, RequestPathEncoded,
         FileNameEncoded, CwdFtpDirEncoded[0] ? ";" : "", CwdFtpDirEncoded,
         FileNameEscaped, 30-strlen(FileName), "");

      if (IsDirectory)
      {
         for (sptr = FileNameEncoded; *sptr; sptr++);
         *--sptr = '\0';
      }

      fprintf (stdout,
"<I>\
<A HREF=\"%sftp://%s%s%s%s;type=a%s%s\">a</A>\
<A HREF=\"%sftp://%s%s%s%s;type=i%s%s\">i</A>\
<A HREF=\"%sftp://%s%s%s%s;type=d%s%s\">d</A>\
</I>",
         MassageLinksPath, RemoteUserPassEncoded, RemoteHostPort,
         RequestPathEncoded, FileNameEncoded,
         CwdFtpDirEncoded[0] ? ";" : "", CwdFtpDirEncoded,
         MassageLinksPath, RemoteUserPassEncoded, RemoteHostPort,
         RequestPathEncoded, FileNameEncoded, 
         CwdFtpDirEncoded[0] ? ";" : "", CwdFtpDirEncoded,
         MassageLinksPath, RemoteUserPassEncoded, RemoteHostPort,
         RequestPathEncoded, FileNameEncoded,
         CwdFtpDirEncoded[0] ? ";" : "", CwdFtpDirEncoded);

      if (IsDirectory)
         fprintf (stdout, "\n");
      else
         fprintf (stdout, "  %14s   %20s\n", FileSize, FileDate);
   }

   fprintf (stdout, FtpFilesDirectories,
            FileCount, DirectoryCount,
            FileCount || DirectoryCount ? FtpGetAs : "");
}

/****************************************************************************/
/*
HTML format a "Unix" FTP server directory listing.
Expected format: "mode  links  owner  group  size  time_time_time  file-name"  
*/

ProcessFtpUnixList
(
char *RequestPathEncoded,
char *RemoteUserPassEncoded,
char *CwdFtpDirEncoded
)
{
#define MAX_FIELDS 16

   static char  *MonthName [] = { "Jan","Feb","Mar","Apr","May","Jun",
                                  "Jul","Aug","Sep","Oct","Nov","Dec" };

   BOOL  IsDirectory;
   int  idx,
        DirectoryCount,
        FieldCount,
        FileCount,
        MonthField;
   char  *cptr, *sptr;
   char  *FieldPtr [MAX_FIELDS];
   char  FileName [256],
         FileNameEncoded [256],
         FileNameEscaped [256],
         LinkTarget [256];

   /*********/
   /* begin */
   /*********/

   if (Debug) fprintf (stdout, "ProcessFtpUnixList()\n");

   DirectoryCount = FileCount = 0;

   cptr = BufferPtr;
   while (*cptr)
   {
      /* skip leading white-space, blank lines, etc. */
      while (*cptr == ' ') cptr++;
      if (!cptr) break;
      if (*cptr == '\r' || *cptr == '\n')
      {
         while (*cptr == '\r' || *cptr == '\n') cptr++;
         continue;
      }

      FieldCount = 0;
      while (*cptr && *cptr != '\r' && *cptr != '\n')
      {
         if (FieldCount >= MAX_FIELDS) continue;
         FieldPtr[FieldCount++] = cptr;
         while (*cptr && *cptr != ' ' && *cptr != '\r' && *cptr != '\n') cptr++;
         /* terminate that field */
         if (*cptr) *cptr++ = '\0';
         while (*cptr == ' ') cptr++;
      }
      if (Debug)
         for (idx = 1; idx < FieldCount; idx++)
             fprintf (stdout, "%d |%s|\n", idx, FieldPtr[idx]);

      /* skip to start of next line */
      while (*cptr && *cptr != '\r' && *cptr != '\n') cptr++;
      while (*cptr == '\r' || *cptr == '\n') cptr++;

      /* won't make any sense at all unless there are at least six fields */
      if (FieldCount < 6) continue;

      /* find field containing month name */
      for (MonthField = 1; MonthField < FieldCount; MonthField++)
      {
         for (idx = 0; idx < 12; idx++)
             if (strsame (FieldPtr[MonthField], MonthName[idx], 3))
                break;
         if (idx < 12) break;
      }

      /* doesn't make sense if it doesn't contain a month name somewhere */
      if (MonthField >= FieldCount) continue;

      strcpy (FileName, FieldPtr[MonthField+3]);

      /* dot and double-dot directories are ignored */
      if (FileName[0] == '.' && !FileName[1]) continue;
      if (FileName[0] == '.' && FileName[1] == '.' && !FileName[2]) continue;

      if (FieldPtr[0][0] == 'd')
      {
         IsDirectory = true;
         strcat (FileName, "/");
         sptr = FtpIconDirImg;
         DirectoryCount++;
      }
      else
      if (FieldPtr[0][0] == 'l')
      {
         for (sptr = FieldPtr[MonthField+5]; *sptr; sptr++);
         if (sptr > FieldPtr[MonthField+5] && sptr[-1] == '/')
         {
            IsDirectory = true;
            strcat (FileName, "/");
            sptr = FtpIconDirImg;
            DirectoryCount++;
         }
         else
         {
            IsDirectory = false;
            sptr = FtpIconFileImg;
            FileCount++;
         }
      }
      else
      {
         IsDirectory = false;
         sptr = FtpIconFileImg;
         FileCount++;
      }

      CgiLibUrlEncode (FileName, -1, FileNameEncoded, sizeof(FileNameEncoded));
      CgiLibHtmlEscape (FileName, -1, FileNameEscaped, sizeof(FileNameEscaped));

      fprintf (stdout,
" %s<A HREF=\"%sftp://%s%s%s%s%s%s\">%s</A>%*s ",
         sptr, MassageLinksPath,
         RemoteUserPassEncoded, RemoteHostPort, RequestPathEncoded,
         FileNameEncoded, CwdFtpDirEncoded[0] ? ";" : "", CwdFtpDirEncoded,
         FileNameEscaped, 30-strlen(FileName), "");

      if (IsDirectory)
      {
         for (sptr = FileNameEncoded; *sptr; sptr++);
         *--sptr = '\0';
      }

      fprintf (stdout,
"<I>\
<A HREF=\"%sftp://%s%s%s%s;type=a%s%s\">a</A>\
<A HREF=\"%sftp://%s%s%s%s;type=i%s%s\">i</A>\
<A HREF=\"%sftp://%s%s%s%s;type=d%s%s\">d</A>\
</I>",
         MassageLinksPath, RemoteUserPassEncoded, RemoteHostPort,
         RequestPathEncoded, FileNameEncoded,
         CwdFtpDirEncoded[0] ? ";" : "", CwdFtpDirEncoded,
         MassageLinksPath, RemoteUserPassEncoded, RemoteHostPort,
         RequestPathEncoded, FileNameEncoded, 
         CwdFtpDirEncoded[0] ? ";" : "", CwdFtpDirEncoded,
         MassageLinksPath, RemoteUserPassEncoded, RemoteHostPort,
         RequestPathEncoded, FileNameEncoded,
         CwdFtpDirEncoded[0] ? ";" : "", CwdFtpDirEncoded);

      if (IsDirectory)
         fprintf (stdout, "\n");
      else
         fprintf (stdout, "  %10s   %3.3s %2.2s %4.4s\n",
                  FieldPtr[MonthField-1], FieldPtr[MonthField],
                  FieldPtr[MonthField+1], FieldPtr[MonthField+2]);
   }

   fprintf (stdout, FtpFilesDirectories,
            FileCount, DirectoryCount,
            FileCount || DirectoryCount ? FtpGetAs : "");
}

/****************************************************************************/
/*
HTML format a "DOS" FTP server directory listing.
Expected format: "mm-dd-yy_hh:mm  <DIR>|size  file-name"
*/

ProcessFtpDosList
(
char *RequestPathEncoded,
char *RemoteUserPassEncoded,
char *CwdFtpDirEncoded
)
{
   BOOL  IsDirectory;
   int  DirectoryCount,
        FileCount;
   char  *cptr, *sptr;
   char  FileDate [256],
         FileName [256],
         FileNameEncoded [256],
         FileNameEscaped [256],
         FileSize [256];

   /*********/
   /* begin */
   /*********/

   if (Debug) fprintf (stdout, "ProcessFtpDosList()\n");

   DirectoryCount = FileCount = 0;

   cptr = BufferPtr;
   while (*cptr)
   {
      /* skip leading white-space, blank lines, etc. */
      while (*cptr && *cptr == ' ') cptr++;
      if (!cptr) break;
      if (*cptr == '\r' || *cptr == '\n')
      {
         while (*cptr == '\r' || *cptr == '\n') cptr++;
         continue;
      }

      IsDirectory = false;

      /* get the two fields comprising the date */
      sptr = FileDate;
      while (*cptr && *cptr != ' ' && *cptr != '\r' && *cptr != '\n')
         *sptr++ = *cptr++;
      while (*cptr == ' ') *sptr++ = *cptr++;
      while (*cptr && *cptr != ' ' && *cptr != '\r' && *cptr != '\n')
         *sptr++ = *cptr++;
      *sptr = '\0';

      /* absorb white-space */
      while (*cptr == ' ') cptr++;

      if (*cptr == '<')
      {
         /* it's a directory */
         if (!memcmp (cptr, "<DIR>", 5)) IsDirectory = true;
         while (*cptr && *cptr != ' ' && *cptr != '\r' && *cptr != '\n') cptr++;
         FileSize[0] = '\0';
      }
      else
      {
         /* file size */
         sptr = FileSize;
         while (*cptr && *cptr != ' ' && *cptr != '\r' && *cptr != '\n')
            *sptr++ = *cptr++;
         *sptr = '\0';
      }

      /* absorb white space between <DIR> or file size and file name */
      while (*cptr == ' ') cptr++;

      sptr = FileName;
      while (*cptr && *cptr != ' ' && *cptr != '\r' && *cptr != '\n')
         *sptr++ = *cptr++;
      *sptr = '\0';

      /* skip to start of next line */
      while (*cptr && *cptr != '\r' && *cptr != '\n') cptr++;
      while (*cptr == '\r' || *cptr == '\n') cptr++;

      /* if all components not present then just ignore */
      if (!FileName[0]) continue;
      if (!IsDirectory && !FileSize[0]) continue;

      /* dot and double-dot directories are ignored */
      if (FileName[0] == '.' && !FileName[1]) continue;
      if (FileName[0] == '.' && FileName[1] == '.' && !FileName[2]) continue;

      CgiLibUrlEncode (FileName, -1, FileNameEncoded, sizeof(FileNameEncoded));
      CgiLibHtmlEscape (FileName, -1, FileNameEscaped, sizeof(FileNameEscaped));

      if (IsDirectory)
      {
         IsDirectory = true;
         strcat (FileName, "/");
         sptr = FtpIconDirImg;
         DirectoryCount++;
      }
      else
      {
         IsDirectory = false;
         sptr = FtpIconFileImg;
         FileCount++;
      }

      CgiLibUrlEncode (FileName, -1, FileNameEncoded, sizeof(FileNameEncoded));
      CgiLibHtmlEscape (FileName, -1, FileNameEscaped, sizeof(FileNameEscaped));

      fprintf (stdout,
" %s<A HREF=\"%sftp://%s%s%s%s%s%s\">%s</A>%*s ",
         sptr, MassageLinksPath,
         RemoteUserPassEncoded, RemoteHostPort, RequestPathEncoded,
         FileNameEncoded, CwdFtpDirEncoded[0] ? ";" : "", CwdFtpDirEncoded,
         FileNameEscaped, 30-strlen(FileName), "");

      if (IsDirectory)
      {
         for (sptr = FileNameEncoded; *sptr; sptr++);
         *--sptr = '\0';
      }

      fprintf (stdout,
"<I>\
<A HREF=\"%sftp://%s%s%s%s;type=a%s%s\">a</A>\
<A HREF=\"%sftp://%s%s%s%s;type=i%s%s\">i</A>\
<A HREF=\"%sftp://%s%s%s%s;type=d%s%s\">d</A>\
</I>",
         MassageLinksPath, RemoteUserPassEncoded, RemoteHostPort,
         RequestPathEncoded, FileNameEncoded,
         CwdFtpDirEncoded[0] ? ";" : "", CwdFtpDirEncoded,
         MassageLinksPath, RemoteUserPassEncoded, RemoteHostPort,
         RequestPathEncoded, FileNameEncoded, 
         CwdFtpDirEncoded[0] ? ";" : "", CwdFtpDirEncoded,
         MassageLinksPath, RemoteUserPassEncoded, RemoteHostPort,
         RequestPathEncoded, FileNameEncoded,
         CwdFtpDirEncoded[0] ? ";" : "", CwdFtpDirEncoded);

      if (IsDirectory)
         fprintf (stdout, "\n");
      else
         fprintf (stdout, "  %10s   %s\n", FileSize, FileDate);
   }

   fprintf (stdout, FtpFilesDirectories,
            FileCount, DirectoryCount,
            FileCount || DirectoryCount ? FtpGetAs : "");
}

/****************************************************************************/
/*
HTML format an unknown format FTP server directory listing.  Now this was done
as a "NLST" and so should contain one name per lines, that's all!
*/

ProcessFtpUnknownList
(
char *RequestPathEncoded,
char *RemoteUserPassEncoded,
char *CwdFtpDirEncoded
)
{
   int  FileCount;
   char  *cptr, *sptr;
   char  FileName [256],
         FileNameEncoded [256],
         FileNameEscaped [256];

   /*********/
   /* begin */
   /*********/

   if (Debug) fprintf (stdout, "ProcessFtpUnknownList()\n");

   FileCount = 0;

   cptr = BufferPtr;
   while (*cptr)
   {
      /* skip leading white-space, blank lines, etc. */
      while (*cptr && *cptr == ' ') cptr++;
      if (!cptr) break;
      if (*cptr == '\r' || *cptr == '\n')
      {
         while (*cptr == '\r' || *cptr == '\n') cptr++;
         continue;
      }

      sptr = FileName;
      while (*cptr && *cptr != ' ' && *cptr != '\r' && *cptr != '\n')
         *sptr++ = *cptr++;
      *sptr = '\0';

      /* skip to start of next line */
      while (*cptr && *cptr != '\r' && *cptr != '\n') cptr++;
      while (*cptr == '\r' || *cptr == '\n') cptr++;

      if (!FileName[0]) continue;
      FileCount++;

      CgiLibUrlEncode (FileName, -1, FileNameEncoded, sizeof(FileNameEncoded));
      CgiLibHtmlEscape (FileName, -1, FileNameEscaped, sizeof(FileNameEscaped));

      fprintf (stdout,
" %s<A HREF=\"%sftp://%s%s%s%s\">%s</A>%*s \
<I>\
<A HREF=\"%sftp://%s%s%s%s;type=a%s\">a</A>\
<A HREF=\"%sftp://%s%s%s%s;type=i%s\">i</A>\
<A HREF=\"%sftp://%s%s%s%s;type=d%s\">d</A>\
</I>\n",
         FtpIconFileImg, MassageLinksPath,
         RemoteUserPassEncoded, RemoteHostPort, RequestPathEncoded,
         FileNameEncoded, FileNameEscaped, 30-strlen(FileName), "",
         MassageLinksPath, RemoteUserPassEncoded, RemoteHostPort,
         RequestPathEncoded, FileNameEncoded, CwdFtpDirEncoded,
         MassageLinksPath, RemoteUserPassEncoded, RemoteHostPort,
         RequestPathEncoded, FileNameEncoded, CwdFtpDirEncoded, 
         MassageLinksPath, RemoteUserPassEncoded, RemoteHostPort,
         RequestPathEncoded, FileNameEncoded, CwdFtpDirEncoded);
   }

   fprintf (stdout, FtpFilesDirectories,
            FileCount, 0,
            FileCount ? FtpGetAs : "");
}

/****************************************************************************/
/*
Open a "socket" connect to the specific host name and port.  If 'IpAddressPtr'
is not NULL then set where it points to the 32 IP address of the remote system.
*/

OpenConnection
(
unsigned short *ChannelPtr,
char *RemoteName,
int RemotePort,
int *IpAddressPtr
)
{
   int  status,
        IpAddress;
   unsigned short Channel;
   char  *cptr;
   struct AnIOsb  IOsb;
   struct sockaddr_in  SocketName;
   struct hostent  *HostEntryPtr;

   struct {
      unsigned long  Length;
      void  *Address;
      int  *LengthPtr;
   } SocketNameItem =
      { sizeof(SocketName), &SocketName, 0 };

   /*********/
   /* begin */
   /*********/

   if (WatchEnabled)
      WatchThis ("TCPIP CONNECT !AZ:!UL", RemoteName, RemotePort);

   if (isdigit((cptr = RemoteName)[0]))
      while (*cptr && (isdigit(*cptr) || *cptr == '.')) cptr++;
   if (!*cptr)
   {
      /*************************/
      /* address "131.185.2.4" */
      /*************************/

      if ((IpAddress = inet_addr (RemoteName)) == -1)
         return (vaxc$errno);
   }
   else
   {
      /***************************/
      /* address "the.host.name" */
      /***************************/

      if (!(HostEntryPtr = gethostbyname (RemoteName)))
      {
         if (vaxc$errno == RMS$_RNF) return (SS$_NOSUCHNODE);
         if (vaxc$errno == SS$_ENDOFFILE) return (SS$_NOSUCHNODE);
         return (vaxc$errno);
      }
      memcpy (&IpAddress, HostEntryPtr->h_addr, 4);
   }

   /* assign a channel to the internet template device */
   if (VMSnok (status = sys$assign (&InetDeviceDsc, &Channel, 0, 0)))
      return (status);

   /* make the channel a TCP, connection-oriented socket */
   status = sys$qiow (0, Channel, IO$_SETMODE, &IOsb, 0, 0,
                      &TcpSocket, 0, 0, 0, 0, 0);

   if (Debug)
      fprintf (stdout, "sys$qiow() %%X%08.08X IOsb.Status %%X%08.08X\n",
               status, IOsb.Status);
   if (VMSok (status) && VMSnok (IOsb.Status)) status = IOsb.Status;
   if (VMSnok (status)) return (status);

   SocketName.sin_family = AF_INET;
   SocketName.sin_port = htons (RemotePort);
   memcpy (&SocketName.sin_addr.s_addr, &IpAddress, 4);
   if (IpAddressPtr) memcpy (IpAddressPtr, &IpAddress, 4);

   status = sys$qiow (0, Channel, IO$_ACCESS, &IOsb, 0, 0,
                      0, 0, &SocketNameItem, 0, 0, 0);
   if (Debug)
      fprintf (stdout, "sys$qiow() %%X%08.08X IOsb.Status %%X%08.08X\n",
               status, IOsb.Status);

   if (VMSok (status) && VMSnok (IOsb.Status)) status = IOsb.Status;
   if (VMSok (status))
      *ChannelPtr = Channel;
   else
      *ChannelPtr = 0;
   return (status);
}

/****************************************************************************/
/*
Read from the specific "socket" into the the supplied buffer.  If 'AsText' is
true the allow for and supply a terminating null character.  If 'ReadCountPtr'
is not NULL then set it's location to the number of bytes read.
*/

int ReadConnection
(
unsigned short Channel,
char *DataBuffer,
int SizeOfDataBuffer,
int *ReadCountPtr,
BOOL AsText
)
{
   int  status;
   struct AnIOsb  IOsb;

   /*********/
   /* begin */
   /*********/

   if (Debug)
      fprintf (stdout, "ReadConnection() %d %d\n", SizeOfDataBuffer, AsText);

   if (AsText) SizeOfDataBuffer--;

   status = sys$qiow (0, Channel, IO$_READVBLK, &IOsb, 0, 0,
                      DataBuffer, SizeOfDataBuffer, 0, 0, 0, 0);
   if (Debug)
      fprintf (stdout,
          "sys$qiow() status %%X%08.08X IOsb.Status %%X%08.08X %d bytes\n",
          status, IOsb.Status, IOsb.Count);

   if (VMSok (status) && VMSnok (IOsb.Status)) status = IOsb.Status;
   if (VMSok (status))
   {
      if (AsText)
      {
         DataBuffer[IOsb.Count] = '\0';
         if (Debug) fprintf (stdout, "|%s|\n", DataBuffer);
      }

      if (WatchEnabled)
      {
         WatchThis ("TCPIP READ !UL", IOsb.Count);
         WatchDump (DataBuffer, IOsb.Count);
      }

      if (ReadCountPtr) *ReadCountPtr = IOsb.Count;
   }
   else
   {
      if (WatchEnabled) WatchThis ("TCPIP READ %X!8XL", status);
      if (ReadCountPtr) *ReadCountPtr = 0;
   }

   return (status);
}

/****************************************************************************/
/*
Write the supplied data to the specific "socket".  If 'DataLength' is -1 then
consider the data to be a null-terminated string and get it's length using
strlen().
*/

int WriteConnection
(
unsigned short Channel,
char *DataPtr,
int DataLength
)
{
   int  status;
   struct AnIOsb  IOsb;

   /*********/
   /* begin */
   /*********/

   if (Debug)
      fprintf (stdout, "WriteConnection() %d |%s|\n", DataLength, DataPtr);

   if (DataLength == -1) DataLength = strlen(DataPtr);

   if (WatchEnabled)
   {
      WatchThis ("TCPIP WRITE !UL", DataLength);
      WatchDump (DataPtr, DataLength);
   }

   status = sys$qiow (0, Channel, IO$_WRITEVBLK, &IOsb, 0, 0,
                      DataPtr, DataLength, 0, 0, 0, 0);
   if (Debug)
      fprintf (stdout, "sys$qiow() %%X%08.08X IOsb.Status %%X%08.08X\n",
               status, IOsb.Status);

   if (VMSok (status) && VMSnok (IOsb.Status)) status = IOsb.Status;

   if (WatchEnabled && VMSnok(status))
      WatchThis ("TCPIP WRITE %X!8XL", status);

   return (status);
}

/****************************************************************************/
/*
Script is being used as a quasi-proxy.  Examine the response header.  If not
"text/html" content type just return it directly to the client.  If HTML then
parse the body looking for things that look like HTTP URL links.   When found
either 1) prefix the link with the quasi-proxy server host name (and port if
not 80) and the quasi-proxy script name, or 2) convert it from an absolute to
relative link for reverse proxy purposes.
*/

MassageLinks ()

{
#define FLUSH_TO_CPTR { \
\
   if (cptr > BufferCurrentPtr) \
   { \
      ch = *cptr; \
      *cptr = '\0'; \
      fputs (BufferCurrentPtr, stdout); \
      *cptr = ch; \
   } \
}

   BOOL  FullUrl,
         NextPlease;
   char  ch;
   char  *cptr, *hptr, *sptr;

   /*********/
   /* begin */
   /*********/

   if (Debug) fprintf (stdout, "MassageLinks()\n");

   cptr = BufferCurrentPtr = BufferPtr;
   cptr[BufferCount] = '\0';

   /* when massaging let's limit ourselves to HTTP/1.0 responses */
   if (!memcmp (cptr, "HTTP/1.1", 8)) memcpy (cptr, "HTTP/1.0", 8);

   while (*cptr)
   {
      if (toupper (cptr[0]) == 'C' && tolower(cptr[1]) == 'o' &&
          strsame (cptr, "Content-Type:", 13))
      {
         sptr = cptr + 13;
         if (Debug) fprintf (stdout, "|%13.13s|\n", cptr);
         while (*sptr && isspace(*sptr)) *sptr++;
         if (Debug) fprintf (stdout, "|%20.20s|\n", sptr);

         /* if not HTML, just output original data */
         if (!strsame (sptr, "text/html", 9))
         {
            fwrite (BufferPtr, BufferCount, 1, stdout);
            return;
         }
      }

      if (toupper(cptr[0]) == 'C' && strsame (cptr, "Content-Length:", 15))
      {
         /* as we're intending to alter the content disable the length field */
         memcpy (cptr, "C_ntent-L_ngth:", 15);
      }
      else
      if (toupper(cptr[0]) == 'S' && strsame (cptr, "Set-Cookie:", 11))
      {
         /* certain components will need massaging to reflect the proxy */
         cptr += 11;
         while (*cptr && *cptr != '\r' && *cptr != '\n')
         {
            if (tolower(*cptr) == 'd' && strsame (cptr, "domain=", 7))
            {
               /* make any cookie domain reflect the reverse-proxy server */
               cptr += 7;

               FLUSH_TO_CPTR
               while (*cptr && *cptr != ';' && *cptr != ',' && !isspace(*cptr))
                  cptr++;
               BufferCurrentPtr = cptr;

               fputs (CgiServerNamePtr, stdout);
            }
            else
            if (tolower(*cptr) == 'p' && strsame (cptr, "path=", 5) &&
                ReversePathPtr[0])
            {
               /* prepend the path discriminator */
               cptr += 5;

               FLUSH_TO_CPTR
               BufferCurrentPtr = cptr;

               fputs (ReversePathPtr, stdout);
            }
            else
               cptr++;
         }
      }
      else
      if ((toupper (cptr[0]) == 'L' &&
           strsame (cptr, "Location:", 9)) ||
          (toupper (cptr[0]) == 'C' &&
           strsame (cptr, "Content-Location:", 17)))
      {
         while (*cptr && *cptr != ' ') cptr++;
         if (*cptr == ' ') cptr++;

         FLUSH_TO_CPTR

         if (ReverseProxyPtr)
         {
            hptr = cptr + 7;
            if (!strsame (cptr, "http://", 7))
               fprintf (stdout, "%s", ReversePathPtr);
            else
            if (ReverseProxyPtr[0] == '*')
            {
               /* modify all full URLs */
               cptr = hptr;
               while (*cptr && *cptr != '/' &&
                      (isalnum(*cptr) || *cptr == '.' ||
                       *cptr == '-' || *cptr == '_')) cptr++;
               fprintf (stdout, "%s%s",
                        ReverseProxyPrefix, *cptr == '/' ? "" : "/");
            }
            else
            if (ReverseProxyPtr[0] == '#')
            {
               /* modify URLs only belonging to the proxied-to host */
               if (strsame (hptr, RemoteHostPort, RemoteHostPortLength) &&
                   !isalnum(hptr[RemoteHostPortLength]) &&
                   hptr[RemoteHostPortLength] != '.')
               {
                  /* matches the reverse-proxied-to host so modify */
                  cptr = hptr + RemoteHostPortLength;
                  fprintf (stdout, "%s%s",
                           ReverseProxyPrefix, *cptr == '/' ? "" : "/");
               }
            }
            else
            if (strsame (hptr, ReverseProxyPtr, ReverseProxyLength) &&
                !isalnum(hptr[ReverseProxyLength]) &&
                hptr[ReverseProxyLength] != '.')
            {
               /* matches the supplied string (host name) so modify */
               cptr = hptr + ReverseProxyLength;
               fprintf (stdout, "%s%s",
                        ReverseProxyPrefix, *cptr == '/' ? "" : "/");
            }
         }
         else
            fprintf (stdout, "%s%s", FetchPrefix, cptr);

         BufferCurrentPtr = cptr;
      }
 
      /* skip to end-of-line */
      while (*cptr && *cptr != '\r' && *cptr != '\n') cptr++;

      /* break if end of request header */
      if (*(unsigned long*)cptr == '\r\n\r\n')
      {
         cptr += 4;
         break;
      }
      if (*(unsigned short*)cptr == '\n\n')
      {
         cptr += 2;
         break;
      }

      /* skip to start-of-line */
      while (*cptr && (*cptr == '\r' || *cptr == '\n')) cptr++;
   }

   NextPlease = true;

   while (*cptr)
   {
      if (*cptr != '=')
      {
         cptr++;
         continue;
      }

      FullUrl = false;
      hptr = "";

      if (!memcmp (cptr, "=\"http://", 9))
      {
         if (Debug) fprintf (stdout, "|%9.9s|\n", cptr);
         cptr += 2;
         hptr = cptr + 7;
         FullUrl = true;
         NextPlease = false;
      }
      else
      if (!memcmp (cptr, "=\"ftp://", 8))
      {
         if (Debug) fprintf (stdout, "|%8.8s|\n", cptr);
         cptr += 2;
         hptr = cptr + 6;
         FullUrl = true;
         NextPlease = false;
      }
      else
      if (!memcmp (cptr, "=\'http://", 9))
      {
         if (Debug) fprintf (stdout, "|%9.9s|\n", cptr);
         cptr += 2;
         hptr = cptr + 7;
         FullUrl = true;
         NextPlease = false;
      }
      else
      if (!memcmp (cptr, "=\'ftp://", 8))
      {
         if (Debug) fprintf (stdout, "|%8.8s|\n", cptr);
         cptr += 2;
         hptr = cptr + 6;
         FullUrl = true;
         NextPlease = false;
      }
      else
      if (!memcmp (cptr, "=http://", 8))
      {
         if (Debug) fprintf (stdout, "|%8.8s|\n", cptr);
         cptr++;
         hptr = cptr + 7;
         FullUrl = true;
         NextPlease = false;
      }
      else
      if (!memcmp (cptr, "=ftp://", 7))
      {
         if (Debug) fprintf (stdout, "|%7.7s|\n", cptr);
         cptr++;
         hptr = cptr + 6;
         FullUrl = true;
         NextPlease = false;
      }
      else
      if (*(unsigned short*)(cptr+1) == '\"/')
      {
         if (Debug) fprintf (stdout, "|%2.2s|\n", cptr);
         sptr = cptr+2;
         while (*sptr && *sptr != '\"') sptr++;
         if (*sptr == '\"')
         {
            /* starts with a '="/' and ends with a '"', looks likely */
            if (Debug) fprintf (stdout, "|%c|\n", *sptr);
            cptr += 2;
            NextPlease = false;
         }
      }
      else
      if (*(unsigned short*)(cptr+1) == '\'/')
      {
         if (Debug) fprintf (stdout, "|%2.2s|\n", cptr);
         sptr = cptr+2;
         while (*sptr && *sptr != '\'') sptr++;
         if (*sptr == '\'')
         {
            /* starts with a '='/' and ends with a ''', looks likely */
            if (Debug) fprintf (stdout, "|%c|\n", *sptr);
            cptr += 2;
            NextPlease = false;
         }
      }
      else
      if (*(cptr+1) == '/')
      {
         if (Debug) fprintf (stdout, "|%2.2s|\n", cptr);
         sptr = cptr+1;
         while (*sptr &&
                *sptr != ' ' &&
                *sptr != '\t' &&
                *sptr != '>' &&
                *sptr != '\r' &&
                *sptr != '\n') sptr++;

         if (*sptr == ' ' ||
             *sptr == '\t' ||
             *sptr == '>' ||
             *sptr == '\r' ||
             *sptr == '\n')
         {
            /* starts with a '=/' and ends plausably, looks possible */
            if (Debug) fprintf (stdout, "|%c|\n", *sptr);
            cptr++;
            NextPlease = false;
         }
      }

      if (NextPlease)
      {
         cptr++;
         continue;
      }

      FLUSH_TO_CPTR

      if (FullUrl)
      {
         if (ReverseProxyPtr)
         {
            if (ReverseProxyPtr[0] == '*')
            {
               /* modify all full URLs */
               cptr = hptr;
               while (*cptr && *cptr != '/' &&
                      (isalnum(*cptr) || *cptr == '.' ||
                       *cptr == '-' || *cptr == '_')) cptr++;
               fprintf (stdout, "%s%s",
                        ReverseProxyPrefix, *cptr == '/' ? "" : "/");
            }
            else
            if (ReverseProxyPtr[0] == '#')
            {
               /* modify URLs only belonging to the proxied-to host */
               if (strsame (hptr, RemoteHostPort, RemoteHostPortLength) &&
                   !isalnum(hptr[RemoteHostPortLength]) &&
                   hptr[RemoteHostPortLength] != '.')
               {
                  /* matches the reverse-proxied-to host so modify */
                  cptr = hptr + RemoteHostPortLength;
                  fprintf (stdout, "%s%s",
                           ReverseProxyPrefix, *cptr == '/' ? "" : "/");
               }
            }
            else
            if (strsame (hptr, ReverseProxyPtr, ReverseProxyLength) &&
                !isalnum(hptr[ReverseProxyLength]) &&
                hptr[ReverseProxyLength] != '.')
            {
               /* matches the supplied string (host name) so modify */
               cptr = hptr + ReverseProxyLength;
               fprintf (stdout, "%s%s",
                        ReverseProxyPrefix, *cptr == '/' ? "" : "/");
            }
         }
         else
            fputs (MassageLinksPath, stdout);
      }
      else
      if (ReverseProxyPtr)
         fprintf (stdout, "%s%s", ReversePathPtr, *cptr == '/' ? "" : "/");
      else
         fprintf (stdout, "%shttp://%s%s",
                  MassageLinksPath, RemoteHostPort, *cptr == '/' ? "" : "/");

      BufferCurrentPtr = cptr++;

      NextPlease = true;
   }

   FLUSH_TO_CPTR
}

/*****************************************************************************/
/*
Hmmm, idea look familiar? :-)
*/

int WatchThis
(
char *FaoString,
...
)
{
   static unsigned long  LibStatTimerReal = 1,
                         LibStatTimerCpu = 2;

   static int  WatchCount;

   int  argcnt, status;
   char  *cptr, *sptr, *zptr;
   char  Buffer [1024],
         FaoBuffer [256];
   unsigned long  CpuBinTime;
   unsigned long  RealBinTime [2];
   unsigned long  *vecptr;
   $DESCRIPTOR (BufferDsc, Buffer);
   $DESCRIPTOR (FaoBufferDsc, FaoBuffer);
   unsigned long  FaoVector [32];
   va_list  argptr;

   /*********/
   /* begin */
   /*********/

   va_count (argcnt);

   if (Debug) fprintf (stdout, "WatchThis() %d |%s|\n", argcnt, FaoString);

   if (!FaoString)
   {
      if (WatchCount)
      {
         /* post-processing reset */
         lib$stat_timer (&LibStatTimerReal, &RealBinTime, 0);
         lib$stat_timer (&LibStatTimerCpu, &CpuBinTime, 0);
         WatchThis ("TIME REAL=!%T CPU=!UL.!2ZL",
                    &RealBinTime, CpuBinTime/100, CpuBinTime%100);
         WatchThis ("WATCH end");
         WatchEnabled = WatchCount = 0;

         /* back to binary mode (remove if necessary) */
         if (!(stdout = freopen ("SYS$OUTPUT:", "w", stdout, "ctx=bin")))
            exit (vaxc$errno);
         if (!(stderr = freopen ("SYS$OUTPUT:", "w", stderr, "ctx=bin")))
            exit (vaxc$errno);
      }
      else
      {
         /* pre-processing initialize */
         WatchCount = 1;

         /* back to record mode as WATCH is line-oriented output */
         if (!(stdout = freopen ("SYS$OUTPUT:", "w", stdout, "ctx=rec")))
            exit (vaxc$errno);
         if (!(stderr = freopen ("SYS$OUTPUT:", "w", stderr, "ctx=rec")))
            exit (vaxc$errno);

         lib$init_timer (0);
         fprintf (stdout,
"Content-Type: text/plain\nScript-Control: X-content-encoding-gzip=0\n\n");
         WatchThis ("WATCH begin");
      }
      return (SS$_NORMAL);
   }

   vecptr = FaoVector;
   *vecptr++ = WatchCount++;
   *vecptr++ = 0;
   va_start (argptr, FaoString);
   for (argcnt -= 1; argcnt; argcnt--)
      *vecptr++ = (unsigned long)va_arg (argptr, unsigned long);
   va_end (argptr);

   zptr = (sptr = FaoBuffer) + sizeof(FaoBuffer)-3;
   for (cptr = "|!4ZL|!%T|"; *cptr; *sptr++ = *cptr++);
   for (cptr = FaoString; *cptr && sptr < zptr; *sptr++ = *cptr++);
   *sptr++ = '|';
   *sptr++ = '\n';
   *sptr++ = '\0';
   FaoBufferDsc.dsc$a_pointer = FaoBuffer;
   FaoBufferDsc.dsc$w_length = sptr - FaoBuffer;
   status = sys$faol (&FaoBufferDsc, 0, &BufferDsc,
                      (unsigned long*)&FaoVector);
   if (Debug) fprintf (stdout, "sys$fao() %%X%08.08X\n", status);
   if (!(status & 1)) exit (status);
   fputs (Buffer, stdout);

   return (status);
}

/*****************************************************************************/
/*
Ditto? :-)
*/

int WatchDump
(
char *DataPtr,
int DataLength
)
{
   int  cnt, len;
   char  *cptr, *lptr, *sptr;
   char  WatchBuffer [256];

   /*********/
   /* begin */
   /*********/

   if (Debug) fprintf (stdout, "WatchDump() %d\n", DataLength);

   cptr = DataPtr;
   len = DataLength;
   while (len)
   {
      sptr = WatchBuffer;
      lptr = cptr;
      cnt = 0;
      while (cnt < 32)
      {
         if (cnt < len)
            sptr += sprintf (sptr, "%02.02X", (unsigned char)*cptr++);
         else
         {
            *sptr++ = ' ';
            *sptr++ = ' ';
         }
         if (!(++cnt % 4)) *sptr++ = ' ';
      }
      *sptr++ = ' ';
      cptr = lptr;
      cnt = 0;
      while (cnt < 32 && cnt < len)
      {
         if (isprint(*cptr))
            *sptr++ = *cptr;
         else
            *sptr++ = '.';
         cptr++;
         cnt++;
      }
      if (len > 32) len -= 32; else len = 0;
      *sptr++ = '\n';
      *sptr = '\0';
      fputs (WatchBuffer, stdout);
   }

   return (1);
}

/*****************************************************************************/
/*
Translate a logical name using LNM$FILE_DEV.  Returns a pointer to the value
string, or NULL if the name does not exist.  If 'LogValue' is supplied the
logical name is translated into that (assumed to be large enough), otherwise
it's translated into an internal static buffer.  'IndexValue' should be zero
for a 'flat' logical name, or 0..127 for interative translations.
*/

char* TrnLnm
(
char *LogName,
char *LogValue,
int IndexValue
)
{
   static unsigned short  ValueLength;
   static unsigned long  LnmAttributes,
                         LnmIndex;
   static char  StaticLogValue [256];
   static $DESCRIPTOR (LogNameDsc, "");
   static $DESCRIPTOR (LnmFileDevDsc, "LNM$FILE_DEV");
   static struct {
      short int  buf_len;
      short int  item;
      void  *buf_addr;
      unsigned short  *ret_len;
   } LnmItems [] =
   {
      { sizeof(LnmIndex), LNM$_INDEX, &LnmIndex, 0 },
      { sizeof(LnmAttributes), LNM$_ATTRIBUTES, &LnmAttributes, 0 },
      { 255, LNM$_STRING, 0, &ValueLength },
      { 0,0,0,0 }
   };

   int  status;
   char  *cptr;

   /*********/
   /* begin */
   /*********/

   if (Debug) fprintf (stdout, "TrnLnm() |%s| %d\n", LogName, IndexValue);

   LnmIndex = IndexValue;

   LogNameDsc.dsc$a_pointer = LogName;
   LogNameDsc.dsc$w_length = strlen(LogName);
   if (LogValue)
      cptr = LnmItems[2].buf_addr = LogValue;
   else
      cptr = LnmItems[2].buf_addr = StaticLogValue;

   status = sys$trnlnm (0, &LnmFileDevDsc, &LogNameDsc, 0, &LnmItems);
   if (Debug) fprintf (stdout, "sys$trnlnm() %%X%08.08X\n", status);
   if (!(status & 1) || !(LnmAttributes & LNM$M_EXISTS))
   {
      if (Debug) fprintf (stdout, "|(null)|\n");
      return (NULL);
   }

   cptr[ValueLength] = '\0';
   if (Debug) fprintf (stdout, "|%s|\n", cptr);
   return (cptr);
}

/*****************************************************************************/
/*
Get "command-line" parameters, whether from the command-line or from a
configuration symbol or logical containing the equivalent.
*/

GetParameters ()

{
   static char  CommandLine [256];
   static unsigned long  Flags = 0;

   int  status;
   unsigned short  Length;
   char  ch;
   char  *aptr, *cptr, *clptr, *sptr;
   $DESCRIPTOR (CommandLineDsc, CommandLine);

   /*********/
   /* begin */
   /*********/

   if (Debug) fprintf (stdout, "GetParameters()\n");

   if (!(clptr = getenv ("FETCH$PARAM")))
   {
      /* get the entire command line following the verb */
      if (VMSnok (status =
          lib$get_foreign (&CommandLineDsc, 0, &Length, &Flags)))
         exit (status);
      (clptr = CommandLine)[Length] = '\0';
   }

   aptr = NULL;
   ch = *clptr;
   for (;;)
   {
      if (aptr && *aptr == '/') *aptr = '\0';
      if (!ch) break;

      *clptr = ch;
      if (Debug) fprintf (stdout, "clptr |%s|\n", clptr);
      while (*clptr && isspace(*clptr)) *clptr++ = '\0';
      aptr = clptr;
      if (*clptr == '/') clptr++;
      while (*clptr && !isspace (*clptr) && *clptr != '/')
      {
         if (*clptr != '\"')
         {
            clptr++;
            continue;
         }
         cptr = clptr;
         clptr++;
         while (*clptr)
         {
            if (*clptr == '\"')
               if (*(clptr+1) == '\"')
                  clptr++;
               else
                  break;
            *cptr++ = *clptr++;
         }
         *cptr = '\0';
         if (*clptr) clptr++;
      }
      ch = *clptr;
      if (*clptr) *clptr = '\0';
      if (Debug) fprintf (stdout, "aptr |%s|\n", aptr);
      if (!*aptr) continue;

      if (strsame (aptr, "/BODY", 4))
      {
         DoResponseBody = true;
         continue;
      }
      if (strsame (aptr, "/NOBODY", 6))
      {
         DoResponseBody = false;
         continue;
      }

      if (strsame (aptr, "/CHECK", 4))
      {
         DoCheckOnly = true;
         continue;
      }

      if (strsame (aptr, "/CHUNK=", 4))
      {
         cptr = GetParameterString (aptr);
         if (!cptr || !*cptr) continue;
         BufferChunk = atoi(cptr);
         continue;
      }

      if (strsame (aptr, "/DBUG", -1))
      {
         Debug = true;
         continue;
      }

      if (strsame (aptr, "/ESCAPE_HTML", 4))
      {
         DoEscapeHtml = true;
         continue;
      }
      if (strsame (aptr, "/NOESCAPE_HTML", 6))
      {
         DoEscapeHtml = false;
         continue;
      }

      if (strsame (aptr, "/FETCH=", 4))
      {
         cptr = GetParameterString (aptr);
         if (!cptr || !*cptr) continue;
         FetchScriptNamePtr = cptr;
         continue;
      }

      if (strsame (aptr, "/FTP", 4))
      {
         DoFtp = true;
         continue;
      }

      if (strsame (aptr, "/HEADER", 4))
      {
         DoResponseHeader = true;
         continue;
      }
      if (strsame (aptr, "/NOHEADER", 6))
      {
         DoResponseHeader = false;
         continue;
      }

      if (strsame (aptr, "/HTTP", 4))
      {
         DoFtp = false;
         continue;
      }

      if (strsame (aptr, "/ICONS=", 4))
      {
         cptr = GetParameterString (aptr);
         if (!cptr || !*cptr) continue;
         IconPathPtr = cptr;
         continue;
      }

      if (strsame (aptr, "/METHOD=", 4))
      {
         cptr = GetParameterString (aptr);
         if (!cptr || !*cptr) continue;
         CliHttpMethodPtr = cptr;
         continue;
      }

      if (strsame (aptr, "/OUTPUT=", 4))
      {
         cptr = GetParameterString (aptr);
         if (!cptr || !*cptr) continue;
         OutputPtr = cptr;

         if (strsame (OutputPtr, "TT:", -1) ||
             strsame (OutputPtr, "TERMINAL", -1) ||
             strsame (OutputPtr, "SYS$OUTPUT", 10))
            OutputPtr = "";

         continue;
      }

      if (strsame (aptr, "/REPORT", 4))
      {
         DoReport = true;
         continue;
      }

      if (strsame (aptr, "/REVERSE=", 4))
      {
         cptr = GetParameterString (aptr);
         if (!cptr || !*cptr) continue;
         ReverseProxyPtr = cptr;
         ReverseProxyLength = strlen(cptr);
         continue;
      }

      if (strsame (aptr, "/SUBSTITUTE=", 4))
      {
         /* get this one by hand :^) */
         for (cptr = aptr; *cptr && *cptr != '='; cptr++);
         if (*cptr) cptr++;
         if (*cptr) ParamSubsChar = *cptr;
         continue;
      }

      if (strsame (aptr, "/URL=", 4))
      {
         cptr = GetParameterString (aptr);
         if (!cptr || !*cptr) continue;
         FetchUrlPtr = cptr;
         continue;
      }

      if (strsame (aptr, "/UNKNOWN=", 4))
      {
         cptr = GetParameterString (aptr);
         if (!cptr || !*cptr) continue;
         FtpDefaultContentTypePtr = cptr;
         continue;
      }

      if (strsame (aptr, "/USER_AGENT=", 4))
      {
         cptr = GetParameterString (aptr);
         if (!cptr || !*cptr) continue;
         UserAgentPtr = cptr;
         continue;
      }

      if (strsame (aptr, "/VERSION=", 4))
      {
         cptr = GetParameterString (aptr);
         if (!cptr || !*cptr)
         {
            fprintf (stdout, "%%%s-I-SOFTWAREID, %s\n%s\n",
                     Utility, SoftwareId, CopyrightInfo);
            exit (SS$_NORMAL);
         }
         if (strsame (cptr, "1.0", -1))
            RequestHttpVersion = 10;
         else
         if (strsame (cptr, "0.9", -1))
            RequestHttpVersion = 9;
         else
            RequestHttpVersion = -1;
         continue;
      }

      if (strsame (aptr, "/WATCH", 4))
      {
         WatchEnabled = true;
         continue;
      }

      if (*aptr == '/')
      {
         fprintf (stdout, "%%%s-E-IVQUAL, unrecognized qualifier\n \\%s\\\n",
                  Utility, aptr+1);
         exit (STS$K_ERROR | STS$M_INHIB_MSG);
      }

      if (!FetchUrlPtr)
      {
         cptr = GetParameterString (aptr);
         if (!cptr || !*cptr) continue;
         FetchUrlPtr = cptr;
         continue;
      }

      fprintf (stdout, "%%%s-E-MAXPARM, too many parameters\n \\%s\\\n",
               Utility, aptr);
      exit (STS$K_ERROR | STS$M_INHIB_MSG);
   }
}

/*****************************************************************************/
/*
Get a string from the command-line.  It can be a qualifier specified string
(e.g. /QUALIFIER=<string>) or just a string supplied as a parameter.  If a
qualifier then it must have a string following the '=' otherwise a NULL is
returned.  If the string begins with the character specified by global variable
'ParamSubsChar' (which in turn can be specified by the /SUBSTITUTE= qualifier)
and the parameter string begins with this as the first character the remainder
of the string is used as a C-RTL getenv() function argument and it's value is
attempted to be resolved.  If it does not exist the function returns a NULL. 
If it does exist the a pointer to it's value is returned.  If the string does
not begin with the substitution character a pointer to it is returned.  The
substitution character may be escaped using a leading backslash.
*/

char* GetParameterString (char *aptr)

{
   char  *cptr;

   /*********/
   /* begin */
   /*********/

   if (Debug)
      fprintf (stdout, "GetParameterString() %c |%s|\n", ParamSubsChar, aptr);

   if (!aptr) return (NULL);
   if (*aptr == '/')
   {
      for (cptr = aptr; *cptr && *cptr != '='; cptr++);
      if (!*cptr) return (NULL);
      cptr++;
   }
   else
      cptr = aptr;
   if (*cptr == ParamSubsChar)
      cptr = getenv(cptr+1);
   else
   if (*cptr == '\\' && *(cptr+1) == ParamSubsChar)
      cptr++;

   if (Debug) fprintf (stdout, "|%s|\n", cptr ? cptr : "(null)");
   return (cptr);
}

/*****************************************************************************/
/*
*/

int SetLocalSymbol
(
char *SymbolName,
char *SymbolValue
)
{
   static int  LocalSymbol = LIB$K_CLI_LOCAL_SYM;
   static $DESCRIPTOR (SymbolNameDsc, "");
   static $DESCRIPTOR (SymbolValueDsc, "");

   int  status;

   /*********/
   /* begin */
   /*********/

   if (WatchEnabled) WatchThis ("SYMBOL !AZ \"!AZ\"", SymbolName, SymbolValue);

   SymbolNameDsc.dsc$w_length = strlen(SymbolName);
   SymbolNameDsc.dsc$a_pointer = SymbolName;

   SymbolValueDsc.dsc$w_length = strlen(SymbolValue);
   SymbolValueDsc.dsc$a_pointer = SymbolValue;

   status = lib$set_symbol (&SymbolNameDsc, &SymbolValueDsc, &LocalSymbol);
   if (Debug) fprintf (stdout, "lib$set_symbol() %%X%08.08X\n", status);
   return (status);
}

/****************************************************************************/
/*
Does a case-insensitive, character-by-character string compare and returns 
true if two strings are the same, or false if not.  If a maximum number of 
characters are specified only those will be compared, if the entire strings 
should be compared then specify the number of characters as 0.
*/ 

BOOL strsame
(
char *sptr1,
char *sptr2,
int  count
)
{
   /*********/
   /* begin */
   /*********/

   /** if (Debug) fprintf (stdout, "strsame() |%s|%s|\n", sptr1, sptr2); **/

   while (*sptr1 && *sptr2)
   {
      if (toupper (*sptr1++) != toupper (*sptr2++)) return (false);
      if (count)
         if (!--count) return (true);
   }
   if (*sptr1 || *sptr2)
      return (false);
   else
      return (true);
}

/****************************************************************************/