1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
|
This is gawkinet.info, produced by makeinfo version 6.7 from
gawkinet.texi.
This is Edition 1.6 of 'TCP/IP Internetworking with 'gawk'', for the
5.1.0 (or later) version of the GNU implementation of AWK.
Copyright (C) 2000, 2001, 2002, 2004, 2009, 2010, 2016, 2019, 2020,
2021 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3 or
any later version published by the Free Software Foundation; with the
Invariant Sections being "GNU General Public License", the Front-Cover
texts being (a) (see below), and with the Back-Cover Texts being (b)
(see below). A copy of the license is included in the section entitled
"GNU Free Documentation License".
a. "A GNU Manual"
b. "You have the freedom to copy and modify this GNU manual. Buying
copies from the FSF supports it in developing GNU and promoting
software freedom."
INFO-DIR-SECTION Network applications
START-INFO-DIR-ENTRY
* awkinet: (gawkinet). TCP/IP Internetworking With 'gawk'.
END-INFO-DIR-ENTRY
File: gawkinet.info, Node: Top, Next: Preface, Prev: (dir), Up: (dir)
General Introduction
********************
This file documents the networking features in GNU Awk ('gawk') version
4.0 and later.
This is Edition 1.6 of 'TCP/IP Internetworking with 'gawk'', for the
5.1.0 (or later) version of the GNU implementation of AWK.
Copyright (C) 2000, 2001, 2002, 2004, 2009, 2010, 2016, 2019, 2020,
2021 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3 or
any later version published by the Free Software Foundation; with the
Invariant Sections being "GNU General Public License", the Front-Cover
texts being (a) (see below), and with the Back-Cover Texts being (b)
(see below). A copy of the license is included in the section entitled
"GNU Free Documentation License".
a. "A GNU Manual"
b. "You have the freedom to copy and modify this GNU manual. Buying
copies from the FSF supports it in developing GNU and promoting
software freedom."
* Menu:
* Preface:: About this document.
* Introduction:: About networking.
* Using Networking:: Some examples.
* Some Applications and Techniques:: More extended examples.
* Links:: Where to find the stuff mentioned in this
document.
* GNU Free Documentation License:: The license for this document.
* Index:: The index.
* Stream Communications:: Sending data streams.
* Datagram Communications:: Sending self-contained messages.
* The TCP/IP Protocols:: How these models work in the Internet.
* Basic Protocols:: The basic protocols.
* Ports:: The idea behind ports.
* Making Connections:: Making TCP/IP connections.
* Gawk Special Files:: How to do 'gawk' networking.
* Special File Fields:: The fields in the special file name.
* Comparing Protocols:: Differences between the protocols.
* File /inet/tcp:: The TCP special file.
* File /inet/udp:: The UDP special file.
* TCP Connecting:: Making a TCP connection.
* Troubleshooting:: Troubleshooting TCP/IP connections.
* Interacting:: Interacting with a service.
* Setting Up:: Setting up a service.
* Email:: Reading email.
* Web page:: Reading a Web page.
* Primitive Service:: A primitive Web service.
* Interacting Service:: A Web service with interaction.
* CGI Lib:: A simple CGI library.
* Simple Server:: A simple Web server.
* Caveats:: Network programming caveats.
* Challenges:: Where to go from here.
* PANIC:: An Emergency Web Server.
* GETURL:: Retrieving Web Pages.
* REMCONF:: Remote Configuration Of Embedded Systems.
* URLCHK:: Look For Changed Web Pages.
* WEBGRAB:: Extract Links From A Page.
* STATIST:: Graphing A Statistical Distribution.
* MAZE:: Walking Through A Maze In Virtual Reality.
* MOBAGWHO:: A Simple Mobile Agent.
* STOXPRED:: Stock Market Prediction As A Service.
* PROTBASE:: Searching Through A Protein Database.
File: gawkinet.info, Node: Preface, Next: Introduction, Prev: Top, Up: Top
Preface
*******
In May of 1997, Jürgen Kahrs felt the need for network access from
'awk', and, with a little help from me, set about adding features to do
this for 'gawk'. At that time, he wrote the bulk of this Info file.
The code and documentation were added to the 'gawk' 3.1 development
tree, and languished somewhat until I could finally get down to some
serious work on that version of 'gawk'. This finally happened in the
middle of 2000.
Meantime, Jürgen wrote an article about the Internet special files
and '|&' operator for 'Linux Journal', and made a networking patch for
the production versions of 'gawk' available from his home page. In
August of 2000 (for 'gawk' 3.0.6), this patch also made it to the main
GNU 'ftp' distribution site.
For release with 'gawk', I edited Jürgen's prose for English grammar
and style, as he is not a native English speaker. I also rearranged the
material somewhat for what I felt was a better order of presentation,
and (re)wrote some of the introductory material.
The majority of this document and the code are his work, and the high
quality and interesting ideas speak for themselves. It is my hope that
these features will be of significant value to the 'awk' community.
Arnold Robbins
Nof Ayalon, ISRAEL
March, 2001
File: gawkinet.info, Node: Introduction, Next: Using Networking, Prev: Preface, Up: Top
1 Networking Concepts
*********************
This major node provides a (necessarily) brief introduction to computer
networking concepts. For many applications of 'gawk' to TCP/IP
networking, we hope that this is enough. For more advanced tasks, you
will need deeper background, and it may be necessary to switch to
lower-level programming in C or C++.
There are two real-life models for the way computers send messages to
each other over a network. While the analogies are not perfect, they
are close enough to convey the major concepts. These two models are the
phone system (reliable byte-stream communications), and the postal
system (best-effort datagrams).
* Menu:
* Stream Communications:: Sending data streams.
* Datagram Communications:: Sending self-contained messages.
* The TCP/IP Protocols:: How these models work in the Internet.
* Making Connections:: Making TCP/IP connections.
File: gawkinet.info, Node: Stream Communications, Next: Datagram Communications, Prev: Introduction, Up: Introduction
1.1 Reliable Byte-streams (Phone Calls)
=======================================
When you make a phone call, the following steps occur:
1. You dial a number.
2. The phone system connects to the called party, telling them there
is an incoming call. (Their phone rings.)
3. The other party answers the call, or, in the case of a computer
network, refuses to answer the call.
4. Assuming the other party answers, the connection between you is now
a "duplex" (two-way), "reliable" (no data lost), sequenced (data
comes out in the order sent) data stream.
5. You and your friend may now talk freely, with the phone system
moving the data (your voices) from one end to the other. From your
point of view, you have a direct end-to-end connection with the
person on the other end.
The same steps occur in a duplex reliable computer networking
connection. There is considerably more overhead in setting up the
communications, but once it's done, data moves in both directions,
reliably, in sequence.
File: gawkinet.info, Node: Datagram Communications, Next: The TCP/IP Protocols, Prev: Stream Communications, Up: Introduction
1.2 Best-effort Datagrams (Mailed Letters)
==========================================
Suppose you mail three different documents to your office on the other
side of the country on two different days. Doing so entails the
following.
1. Each document travels in its own envelope.
2. Each envelope contains both the sender and the recipient address.
3. Each envelope may travel a different route to its destination.
4. The envelopes may arrive in a different order from the one in which
they were sent.
5. One or more may get lost in the mail. (Although, fortunately, this
does not occur very often.)
6. In a computer network, one or more "packets" may also arrive
multiple times. (This doesn't happen with the postal system!)
The important characteristics of datagram communications, like those
of the postal system are thus:
* Delivery is "best effort;" the data may never get there.
* Each message is self-contained, including the source and
destination addresses.
* Delivery is _not_ sequenced; packets may arrive out of order,
and/or multiple times.
* Unlike the phone system, overhead is considerably lower. It is not
necessary to set up the call first.
The price the user pays for the lower overhead of datagram
communications is exactly the lower reliability; it is often necessary
for user-level protocols that use datagram communications to add their
own reliability features on top of the basic communications.
File: gawkinet.info, Node: The TCP/IP Protocols, Next: Making Connections, Prev: Datagram Communications, Up: Introduction
1.3 The Internet Protocols
==========================
The Internet Protocol Suite (usually referred to as just TCP/IP)(1)
consists of a number of different protocols at different levels or
"layers." For our purposes, three protocols provide the fundamental
communications mechanisms. All other defined protocols are referred to
as user-level protocols (e.g., HTTP, used later in this Info file).
* Menu:
* Basic Protocols:: The basic protocols.
* Ports:: The idea behind ports.
---------- Footnotes ----------
(1) It should be noted that although the Internet seems to have
conquered the world, there are other networking protocol suites in
existence and in use.
File: gawkinet.info, Node: Basic Protocols, Next: Ports, Prev: The TCP/IP Protocols, Up: The TCP/IP Protocols
1.3.1 The Basic Internet Protocols
----------------------------------
IP
The Internet Protocol. This protocol is almost never used directly
by applications. It provides the basic packet delivery and routing
infrastructure of the Internet. Much like the phone company's
switching centers or the Post Office's trucks, it is not of much
day-to-day interest to the regular user (or programmer). It
happens to be a best effort datagram protocol. In the early
twenty-first century, there are two versions of this protocol in
use:
IPv4
The original version of the Internet Protocol, with 32-bit
addresses, on which most of the current Internet is based.
IPv6
The "next generation" of the Internet Protocol, with 128-bit
addresses. This protocol is in wide use in certain parts of
the world, but has not yet replaced IPv4.(1)
Versions of the other protocols that sit "atop" IP exist for both
IPv4 and IPv6. However, as the IPv6 versions are fundamentally the
same as the original IPv4 versions, we will not distinguish further
between them.
UDP
The User Datagram Protocol. This is a best effort datagram
protocol. It provides a small amount of extra reliability over IP,
and adds the notion of "ports", described in *note TCP and UDP
Ports: Ports.
TCP
The Transmission Control Protocol. This is a duplex, reliable,
sequenced byte-stream protocol, again layered on top of IP, and
also providing the notion of ports. This is the protocol that you
will most likely use when using 'gawk' for network programming.
All other user-level protocols use either TCP or UDP to do their
basic communications. Examples are SMTP (Simple Mail Transfer
Protocol), FTP (File Transfer Protocol), and HTTP (HyperText Transfer
Protocol).
---------- Footnotes ----------
(1) There isn't an IPv5.
File: gawkinet.info, Node: Ports, Prev: Basic Protocols, Up: The TCP/IP Protocols
1.3.2 TCP and UDP Ports
-----------------------
In the postal system, the address on an envelope indicates a physical
location, such as a residence or office building. But there may be more
than one person at the location; thus you have to further quantify the
recipient by putting a person or company name on the envelope.
In the phone system, one phone number may represent an entire
company, in which case you need a person's extension number in order to
reach that individual directly. Or, when you call a home, you have to
say, "May I please speak to ..." before talking to the person directly.
IP networking provides the concept of addressing. An IP address
represents a particular computer, but no more. In order to reach the
mail service on a system, or the FTP or WWW service on a system, you
must have some way to further specify which service you want. In the
Internet Protocol suite, this is done with "port numbers", which
represent the services, much like an extension number used with a phone
number.
Port numbers are 16-bit integers. Unix and Unix-like systems reserve
ports below 1024 for "well known" services, such as SMTP, FTP, and HTTP.
Numbers 1024 and above may be used by any application, although there is
no promise made that a particular port number is always available.
File: gawkinet.info, Node: Making Connections, Prev: The TCP/IP Protocols, Up: Introduction
1.4 Making TCP/IP Connections (And Some Terminology)
====================================================
Two terms come up repeatedly when discussing networking: "client" and
"server". For now, we'll discuss these terms at the "connection level",
when first establishing connections between two processes on different
systems over a network. (Once the connection is established, the higher
level, or "application level" protocols, such as HTTP or FTP, determine
who is the client and who is the server. Often, it turns out that the
client and server are the same in both roles.)
The "server" is the system providing the service, such as the web
server or email server. It is the "host" (system) which is _connected
to_ in a transaction. For this to work though, the server must be
expecting connections. Much as there has to be someone at the office
building to answer the phone,(1) the server process (usually) has to be
started first and be waiting for a connection.
The "client" is the system requesting the service. It is the system
_initiating the connection_ in a transaction. (Just as when you pick up
the phone to call an office or store.)
In the TCP/IP framework, each end of a connection is represented by a
pair of (ADDRESS, PORT) pairs. For the duration of the connection, the
ports in use at each end are unique, and cannot be used simultaneously
by other processes on the same system. (Only after closing a connection
can a new one be built up on the same port. This is contrary to the
usual behavior of fully developed web servers which have to avoid
situations in which they are not reachable. We have to pay this price
in order to enjoy the benefits of a simple communication paradigm in
'gawk'.)
Furthermore, once the connection is established, communications are
"synchronous".(2) I.e., each end waits on the other to finish
transmitting, before replying. This is much like two people in a phone
conversation. While both could talk simultaneously, doing so usually
doesn't work too well.
In the case of TCP, the synchronicity is enforced by the protocol
when sending data. Data writes "block" until the data have been
received on the other end. For both TCP and UDP, data reads block until
there is incoming data waiting to be read. This is summarized in the
following table, where an "x" indicates that the given action blocks.
TCP x x
UDP x
---------- Footnotes ----------
(1) In the days before voice mail systems!
(2) For the technically savvy, data reads block--if there's no
incoming data, the program is made to wait until there is, instead of
receiving a "there's no data" error return.
File: gawkinet.info, Node: Using Networking, Next: Some Applications and Techniques, Prev: Introduction, Up: Top
2 Networking With 'gawk'
************************
The 'awk' programming language was originally developed as a
pattern-matching language for writing short programs to perform data
manipulation tasks. 'awk''s strength is the manipulation of textual
data that is stored in files. It was never meant to be used for
networking purposes. To exploit its features in a networking context,
it's necessary to use an access mode for network connections that
resembles the access of files as closely as possible.
'awk' is also meant to be a prototyping language. It is used to
demonstrate feasibility and to play with features and user interfaces.
This can be done with file-like handling of network connections. 'gawk'
trades the lack of many of the advanced features of the TCP/IP family of
protocols for the convenience of simple connection handling. The
advanced features are available when programming in C or Perl. In fact,
the network programming in this major node is very similar to what is
described in books such as 'Internet Programming with Python', 'Advanced
Perl Programming', or 'Web Client Programming with Perl'.
However, you can do the programming here without first having to
learn object-oriented ideology; underlying languages such as Tcl/Tk,
Perl, Python; or all of the libraries necessary to extend these
languages before they are ready for the Internet.
This major node demonstrates how to use the TCP protocol. The UDP
protocol is much less important for most users.
* Menu:
* Gawk Special Files:: How to do 'gawk' networking.
* TCP Connecting:: Making a TCP connection.
* Troubleshooting:: Troubleshooting TCP/IP connections.
* Interacting:: Interacting with a service.
* Setting Up:: Setting up a service.
* Email:: Reading email.
* Web page:: Reading a Web page.
* Primitive Service:: A primitive Web service.
* Interacting Service:: A Web service with interaction.
* Simple Server:: A simple Web server.
* Caveats:: Network programming caveats.
* Challenges:: Where to go from here.
File: gawkinet.info, Node: Gawk Special Files, Next: TCP Connecting, Prev: Using Networking, Up: Using Networking
2.1 'gawk''s Networking Mechanisms
==================================
The '|&' operator for use in communicating with a "coprocess" is
described in *note Two-way Communications With Another Process:
(gawk)Two-way I/O. It shows how to do two-way I/O to a separate process,
sending it data with 'print' or 'printf' and reading data with
'getline'. If you haven't read it already, you should detour there to
do so.
'gawk' transparently extends the two-way I/O mechanism to simple
networking through the use of special file names. When a "coprocess"
that matches the special files we are about to describe is started,
'gawk' creates the appropriate network connection, and then two-way I/O
proceeds as usual.
At the C, C++, and Perl level, networking is accomplished via
"sockets", an Application Programming Interface (API) originally
developed at the University of California at Berkeley that is now used
almost universally for TCP/IP networking. Socket level programming,
while fairly straightforward, requires paying attention to a number of
details, as well as using binary data. It is not well-suited for use
from a high-level language like 'awk'. The special files provided in
'gawk' hide the details from the programmer, making things much simpler
and easier to use.
The special file name for network access is made up of several
fields, all of which are mandatory:
/NET-TYPE/PROTOCOL/LOCALPORT/HOSTNAME/REMOTEPORT
The NET-TYPE field lets you specify IPv4 versus IPv6, or lets you
allow the system to choose.
* Menu:
* Special File Fields:: The fields in the special file name.
* Comparing Protocols:: Differences between the protocols.
File: gawkinet.info, Node: Special File Fields, Next: Comparing Protocols, Prev: Gawk Special Files, Up: Gawk Special Files
2.1.1 The Fields of the Special File Name
-----------------------------------------
This node explains the meaning of all of the fields, as well as the
range of values and the defaults. All of the fields are mandatory. To
let the system pick a value, or if the field doesn't apply to the
protocol, specify it as '0' (zero):
NET-TYPE
This is one of 'inet4' for IPv4, 'inet6' for IPv6, or 'inet' to use
the system default (which is likely to be IPv4). For the rest of
this document, we will use the generic '/inet' in our descriptions
of how 'gawk''s networking works.
PROTOCOL
Determines which member of the TCP/IP family of protocols is
selected to transport the data across the network. There are two
possible values (always written in lowercase): 'tcp' and 'udp'.
The exact meaning of each is explained later in this node.
LOCALPORT
Determines which port on the local machine is used to communicate
across the network. Application-level clients usually use '0' to
indicate they do not care which local port is used--instead they
specify a remote port to connect to.
It is vital for application-level servers to use a number different
from '0' here because their service has to be available at a
specific publicly known port number. It is possible to use a name
from '/etc/services' here.
HOSTNAME
Determines which remote host is to be at the other end of the
connection. Application-level clients must enter a name different
from '0'. The name can be either symbolic (e.g.,
'jpl-devvax.jpl.nasa.gov') or numeric (e.g., '128.149.1.143').
Application-level servers must fill this field with a '0' to
indicate their being open for all other hosts to connect to them
and enforce connection level server behavior this way. It is not
possible for an application-level server to restrict its
availability to one remote host by entering a host name here.
REMOTEPORT
Determines which port on the remote machine is used to communicate
across the network. For '/inet/tcp' and '/inet/udp',
application-level clients _must_ use a number other than '0' to
indicate to which port on the remote machine they want to connect.
Application-level servers must not fill this field with a '0'.
Instead they specify a local port to which clients connect. It is
possible to use a name from '/etc/services' here.
Experts in network programming will notice that the usual
client/server asymmetry found at the level of the socket API is not
visible here. This is for the sake of simplicity of the high-level
concept. If this asymmetry is necessary for your application, use
another language. For 'gawk', it is more important to enable users to
write a client program with a minimum of code. What happens when first
accessing a network connection is seen in the following pseudocode:
if ((name of remote host given) && (other side accepts connection)) {
rendez-vous successful; transmit with getline or print
} else {
if ((other side did not accept) && (localport == 0))
exit unsuccessful
if (TCP) {
set up a server accepting connections
this means waiting for the client on the other side to connect
} else
ready
}
The exact behavior of this algorithm depends on the values of the
fields of the special file name. When in doubt, *note Table 2.1:
table-inet-components. gives you the combinations of values and their
meaning. If this table is too complicated, focus on the three lines
printed in *bold*. All the examples in *note Networking With 'gawk':
Using Networking, use only the patterns printed in bold letters.
PROTOCOL LOCAL HOST NAME REMOTE RESULTING CONNECTION-LEVEL
PORT PORT BEHAVIOR
------------------------------------------------------------------------------
*tcp* *0* *x* *x* *Dedicated client, fails if
immediately connecting to a
server on the other side
fails*
udp 0 x x Dedicated client
*tcp, *x* *x* *x* *Client, switches to
udp* dedicated server if
necessary*
*tcp, *x* *0* *0* *Dedicated server*
udp*
tcp, udp x x 0 Invalid
tcp, udp 0 0 x Invalid
tcp, udp x 0 x Invalid
tcp, udp 0 0 0 Invalid
tcp, udp 0 x 0 Invalid
Table 2.1: '/inet' Special File Components
In general, TCP is the preferred mechanism to use. It is the
simplest protocol to understand and to use. Use UDP only if
circumstances demand low-overhead.
File: gawkinet.info, Node: Comparing Protocols, Prev: Special File Fields, Up: Gawk Special Files
2.1.2 Comparing Protocols
-------------------------
This node develops a pair of programs (sender and receiver) that do
nothing but send a timestamp from one machine to another. The sender
and the receiver are implemented with each of the two protocols
available and demonstrate the differences between them.
* Menu:
* File /inet/tcp:: The TCP special file.
* File /inet/udp:: The UDP special file.
File: gawkinet.info, Node: File /inet/tcp, Next: File /inet/udp, Prev: Comparing Protocols, Up: Comparing Protocols
2.1.2.1 '/inet/tcp'
...................
Once again, always use TCP. (Use UDP when low overhead is a necessity.)
The first example is the sender program:
# Server
BEGIN {
print strftime() |& "/inet/tcp/8888/0/0"
close("/inet/tcp/8888/0/0")
}
The receiver is very simple:
# Client
BEGIN {
"/inet/tcp/0/localhost/8888" |& getline
print $0
close("/inet/tcp/0/localhost/8888")
}
TCP guarantees that the bytes arrive at the receiving end in exactly
the same order that they were sent. No byte is lost (except for broken
connections), doubled, or out of order. Some overhead is necessary to
accomplish this, but this is the price to pay for a reliable service.
It does matter which side starts first. The sender/server has to be
started first, and it waits for the receiver to read a line.
File: gawkinet.info, Node: File /inet/udp, Prev: File /inet/tcp, Up: Comparing Protocols
2.1.2.2 '/inet/udp'
...................
The server and client programs that use UDP are almost identical to
their TCP counterparts; only the PROTOCOL has changed. As before, it
does matter which side starts first. The receiving side blocks and
waits for the sender. In this case, the receiver/client has to be
started first:
# Server
BEGIN {
print strftime() |& "/inet/udp/8888/0/0"
close("/inet/udp/8888/0/0")
}
The receiver is almost identical to the TCP receiver:
# Client
BEGIN {
print "hi!" |& "/inet/udp/0/localhost/8888"
"/inet/udp/0/localhost/8888" |& getline
print $0
close("/inet/udp/0/localhost/8888")
}
In the case of UDP, the initial 'print' command is the one that
actually sends data so that there is a connection. UDP and "connection"
sounds strange to anyone who has learned that UDP is a connectionless
protocol. Here, "connection" means that the 'connect()' system call has
completed its work and completed the "association" between a certain
socket and an IP address. Thus there are subtle differences between
'connect()' for TCP and UDP; see the man page for details.(1)
UDP cannot guarantee that the datagrams at the receiving end will
arrive in exactly the same order they were sent. Some datagrams could
be lost, some doubled, and some could arrive out of order. But no
overhead is necessary to accomplish this. This unreliable behavior is
good enough for tasks such as data acquisition, logging, and even
stateless services like the original versions of NFS.
---------- Footnotes ----------
(1) This subtlety is just one of many details that are hidden in the
socket API, invisible and intractable for the 'gawk' user. The
developers are currently considering how to rework the network
facilities to make them easier to understand and use.
File: gawkinet.info, Node: TCP Connecting, Next: Troubleshooting, Prev: Gawk Special Files, Up: Using Networking
2.2 Establishing a TCP Connection
=================================
Let's observe a network connection at work. Type in the following
program and watch the output. Within a second, it connects via TCP
('/inet/tcp') to a remote server and asks the service 'daytime' on the
machine what time it is:
BEGIN {
daytime_server = "time-a-g.nist.gov"
daytime_connection = "/inet/tcp/0/" daytime_server "/daytime"
daytime_connection |& getline
print $0
daytime_connection |& getline
print $0
close(daytime_connection)
}
Even experienced 'awk' users will find the fourth and sixth line
strange in two respects:
* A string containing the name of a special file is used as a shell
command that pipes its output into 'getline'. One would rather
expect to see the special file being read like any other file
('getline < "/inet/tcp/0/time-a-g.nist.gov/daytime"').
* The operator '|&' has not been part of any 'awk' implementation
(until now). It is actually the only extension of the 'awk'
language needed (apart from the special files) to introduce network
access.
The '|&' operator was introduced in 'gawk' 3.1 in order to overcome
the crucial restriction that access to files and pipes in 'awk' is
always unidirectional. It was formerly impossible to use both access
modes on the same file or pipe. Instead of changing the whole concept
of file access, the '|&' operator behaves exactly like the usual pipe
operator except for two additions:
* Normal shell commands connected to their 'gawk' program with a '|&'
pipe can be accessed bidirectionally. The '|&' turns out to be a
quite general, useful, and natural extension of 'awk'.
* Pipes that consist of a special file name for network connections
are not executed as shell commands. Instead, they can be read and
written to, just like a full-duplex network connection.
In the earlier example, the '|&' operator tells 'getline' to read a
line from the special file '/inet/tcp/0/time-a-g.nist.gov/daytime'. We
could also have printed a line into the special file. But instead we
just consumed an empty leading line, printed it, then read a line with
the time, printed that, and closed the connection. (While we could just
let 'gawk' close the connection by finishing the program, in this Info
file we are pedantic and always explicitly close the connections.)
Network services like 'daytime' are not really useful because there
are so many better ways to print the current time. In the early days of
TCP networking, such a service may have looked like a good idea for
testing purposes. Later, simple TCP services like these have been used
to teach TCP/IP networking and therefore you can still find much
educational material of good quality on the Internet about such outdated
services. The list of servers (https://tf.nist.gov/tf-cgi/servers.cgi)
that still support the legacy service daytime
(https://en.wikipedia.org/wiki/Daytime_Protocol) can be found at
Wikipedia. We hesitated to use this service in this manual because it
is hard to find servers that still support services like 'daytime'
openly to the Internet. Later on we will see that some of these
nostalgic protocols have turned into security risks.
File: gawkinet.info, Node: Troubleshooting, Next: Interacting, Prev: TCP Connecting, Up: Using Networking
2.3 Troubleshooting Connection Problems
=======================================
It may well be that for some reason the program shown in the previous
example does not run on your machine. When looking at possible reasons
for this, you will learn much about typical problems that arise in
network programming.
For the rest of this major node, we will assume you work on a
POSIX-style system that supports TCP/IP. If the previous example program
does not run on your machine, it may help to replace the value assigned
to the variable 'daytime_server' with the name (or the IP address) of
another server from the list mentioned above. Now you should see the
date and time being printed by the program, otherwise you may have run
out of servers that support the 'daytime' service.
Try changing the service to 'chargen' or 'ftp'. This way, the
program connects to other services that should give you some response.
If you are curious, you should have a look at your '/etc/services' file.
It could look like this:
# /etc/services:
#
# Network services, Internet style
#
# Name Number/Protocol Alternate name # Comments
echo 7/tcp
echo 7/udp
discard 9/tcp sink null
discard 9/udp sink null
daytime 13/tcp
daytime 13/udp
chargen 19/tcp ttytst source
chargen 19/udp ttytst source
ftp 21/tcp
telnet 23/tcp
smtp 25/tcp mail
finger 79/tcp
www 80/tcp http # WorldWideWeb HTTP
www 80/udp # HyperText Transfer Protocol
pop-2 109/tcp postoffice # POP version 2
pop-2 109/udp
pop-3 110/tcp # POP version 3
pop-3 110/udp
nntp 119/tcp readnews untp # USENET News
irc 194/tcp # Internet Relay Chat
irc 194/udp
...
Here, you find a list of services that traditional Unix machines
usually support. If your GNU/Linux machine does not do so, it may be
that these services are switched off in some startup script. Systems
running some flavor of Microsoft Windows usually do _not_ support these
services. Nevertheless, it _is_ possible to do networking with 'gawk'
on Microsoft Windows.(1) The first column of the file gives the name of
the service, and the second column gives a unique number and the
protocol that one can use to connect to this service. The rest of the
line is treated as a comment. You see that some services ('echo')
support TCP as well as UDP.
---------- Footnotes ----------
(1) Microsoft preferred to ignore the TCP/IP family of protocols
until 1995. Then came the rise of the Netscape browser as a landmark
"killer application." Microsoft added TCP/IP support and their own
browser to Microsoft Windows 95 at the last minute. They even
back-ported their TCP/IP implementation to Microsoft Windows for
Workgroups 3.11, but it was a rather rudimentary and half-hearted
implementation. Nevertheless, the equivalent of '/etc/services' resides
under 'C:\WINNT\system32\drivers\etc\services' on Microsoft Windows 2000
and Microsoft Windows XP. On Microsoft Windows 7, 8 and 10 there is a
directory '%WinDir%\System32\Drivers\Etc' that holds the 'hosts' file
(https://support.microsoft.com/en-us/help/972034/how-to-reset-the-hosts-file-back-to-the-default)
and probably also a 'services' file
(https://www.ibm.com/support/knowledgecenter/SSRNYG_7.2.1/com.ibm.rational.synergy.install.win.doc/topics/sg_r_igw_services_file.html).
File: gawkinet.info, Node: Interacting, Next: Setting Up, Prev: Troubleshooting, Up: Using Networking
2.4 Interacting with a Network Service
======================================
The next program begins really interacting with a network service by
printing something into the special file. It asks the so-called
'finger' service if a user of the machine is logged in. When testing
this program, try to change the variable 'finger_server' to some other
machine name in your local network:
BEGIN {
finger_server = "andrew.cmu.edu"
finger_connection = "/inet/tcp/0/" finger_server "/finger"
print "wnace" |& finger_connection
while ((finger_connection |& getline) > 0)
print $0
close(finger_connection)
}
After telling the service on the machine which user to look for, the
program repeatedly reads lines that come as a reply. When no more lines
are available (because the service has closed the connection), the
program also closes the connection. If you tried to replace
'finger_server' with some other server name, the script probably
reported being unable to open the connection, because most servers today
no longer support this service. Try replacing the login name of
Professor Nace ('wnace') with another login name (like 'help'). You
will receive a list of login names similar to the one you asked for. In
the 1980s you could get a list of all users currently logged in by
asking for an empty string ('""').
The final 'close()' call could be safely deleted from the above
script, because the operating system closes any open connection by
default when a script reaches the end of execution. But, in order to
avoid portability problems, it is best to always close connections
explicitly. With the Linux kernel, for example, proper closing results
in flushing of buffers. Letting the close happen by default may result
in discarding buffers.
When looking at '/etc/services' you may have noticed that the
'daytime' service is also available with 'udp'. In the earlier
examples, change 'tcp' to 'udp' and try if the 'finger' and 'daytime'
clients still work as expected. They probably will not respond because
a wise administrator switched off these services. But if they do, you
may see the expected day and time message. The program then hangs,
because it waits for more lines to come from the service. However, they
never do. This behavior is a consequence of the differences between TCP
and UDP. When using UDP, neither party is automatically informed about
the other closing the connection. Continuing to experiment this way
reveals many other subtle differences between TCP and UDP. To avoid such
trouble, you should always remember the advice Douglas E. Comer and
David Stevens give in Volume III of their series 'Internetworking With
TCP' (page 14):
When designing client-server applications, beginners are strongly
advised to use TCP because it provides reliable,
connection-oriented communication. Programs only use UDP if the
application protocol handles reliability, the application requires
hardware broadcast or multicast, or the application cannot tolerate
virtual circuit overhead.
This advice is actually quite dated and we hesitated to repeat it
here. But we left it in because we are still observing beginners
running into this pitfall. While this advice has aged quite well, some
other ideas from the 1980s have not. The 'finger' service may still be
available in Microsoft Windows Server 2019
(https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/finger),
but it turned out to be a never-ending cause of trouble. First of all,
it is now obvious that a server should never reveal personal data about
its users to anonymous client software that connects over the wild wild
Internet. So every server on the Internet should reject 'finger'
requests (by disabling the port and by disabling the software serving
this port). But things got even worse in 2020 when it turned out that
even the client software (the 'finger' command documented in the link
above) is a security problem. A tool called DarkFinger
(https://seclists.org/fulldisclosure/2020/Sep/30) allows to leverage the
Microsoft Windows 'finger.exe' as a file downloader and help evade
network security devices.
File: gawkinet.info, Node: Setting Up, Next: Email, Prev: Interacting, Up: Using Networking
2.5 Setting Up a Service
========================
The preceding programs behaved as clients that connect to a server
somewhere on the Internet and request a particular service. Now we set
up such a service to mimic the behavior of the 'daytime' service. Such
a server does not know in advance who is going to connect to it over the
network. Therefore, we cannot insert a name for the host to connect to
in our special file name.
Start the following program in one window. Notice that the service
does not have the name 'daytime', but the number '8888'. From looking
at '/etc/services', you know that names like 'daytime' are just
mnemonics for predetermined 16-bit integers. Only the system
administrator ('root') could enter our new service into '/etc/services'
with an appropriate name. Also notice that the service name has to be
entered into a different field of the special file name because we are
setting up a server, not a client:
BEGIN {
print strftime() |& "/inet/tcp/8888/0/0"
close("/inet/tcp/8888/0/0")
}
Now open another window on the same machine. Copy the client program
given as the first example (*note Establishing a TCP Connection: TCP
Connecting.) to a new file and edit it, changing the variable
'daytime_server' to 'localhost' and the port name 'daytime' to '8888'.
Then start the modified client. You should get a reply like this:
$ gawk -f awklib/eg/network/daytimeclient.awk
-| Sun Dec 27 17:33:57 CET 2020
-| Sun Dec 27 17:33:57 CET 2020
Both programs explicitly close the connection.
Now we will intentionally make a mistake to see what happens when the
name '8888' (the port) is already used by another service. Start the
server program in both windows. The first one works, but the second one
complains that it could not open the connection. Each port on a single
machine can only be used by one server program at a time. Now terminate
the server program and change the name '8888' to 'echo'. After
restarting it, the server program does not run any more, and you know
why: there is already an 'echo' service running on your machine. But
even if this isn't true, you would not get your own 'echo' server
running on a Unix machine, because the ports with numbers smaller than
1024 ('echo' is at port 7) are reserved for 'root'. On machines running
some flavor of Microsoft Windows, there is no restriction that reserves
ports 1 to 1024 for a privileged user; hence, you can start an 'echo'
server there. Even in later version of Microsoft Windows, this
restriction of the Unix world seems to have never been adopted 'Does
windows(10/server-2016) have privileged ports?'
(https://social.technet.microsoft.com/Forums/windowsserver/en-US/334f0770-eda9-475a-a27f-46b80ab7e872/does-windows10server2016-have-privileged-ports-?forum=ws2016).
In Microsoft Windows it is the level of the firewall that handles port
access restrictions, not the level of the operating system's kernel.
Turning this short server program into something really useful is
simple. Imagine a server that first reads a file name from the client
through the network connection, then does something with the file and
sends a result back to the client. The server-side processing could be:
BEGIN {
NetService = "/inet/tcp/8888/0/0"
NetService |& getline # sets $0 and the fields
CatPipe = ("cat " $1)
while ((CatPipe | getline) > 0)
print $0 |& NetService
close(NetService)
}
and we would have a remote copying facility. Such a server reads the
name of a file from any client that connects to it and transmits the
contents of the named file across the net. The server-side processing
could also be the execution of a command that is transmitted across the
network. From this example, you can see how simple it is to open up a
security hole on your machine. If you allow clients to connect to your
machine and execute arbitrary commands, anyone would be free to do 'rm
-rf *'.
The client side connects to port number 8888 on the server side and
sends the name of the desired file to be sent across the same TCP
connection. The main loop reads all content coming in from the TCP
connection line-wise and prints it.
BEGIN {
NetService = "/inet/tcp/0/localhost/8888"
print "README" |& NetService
while ((NetService |& getline) > 0)
print $0
close(NetService)
}
File: gawkinet.info, Node: Email, Next: Web page, Prev: Setting Up, Up: Using Networking
2.6 Reading Email
=================
The distribution of email is usually done by dedicated email servers
that communicate with your machine using special protocols. In this
node we show how simple the basic steps are.(1)
To receive email, we use the Post Office Protocol (POP). Sending can
be done with the much older Simple Mail Transfer Protocol (SMTP).
When you type in the following program, replace the EMAILHOST by the
name of your local email server. Ask your administrator if the server
has a POP service, and then use its name or number in the program below.
Now the program is ready to connect to your email server, but it will
not succeed in retrieving your mail because it does not yet know your
login name or password. Replace them in the program and it shows you
the first email the server has in store:
BEGIN {
POPService = "/inet/tcp/0/EMAILHOST/pop3"
RS = ORS = "\r\n"
print "user NAME" |& POPService
POPService |& getline
print "pass PASSWORD" |& POPService
POPService |& getline
print "retr 1" |& POPService
POPService |& getline
if ($1 != "+OK") exit
print "quit" |& POPService
RS = "\r\n\\.\r\n"
POPService |& getline
print $0
close(POPService)
}
We redefine the record separators 'RS' and 'ORS' because the protocol
(POP) requires CR-LF to separate lines. After identifying yourself to
the email service, the command 'retr 1' instructs the service to send
the first of all your email messages in line. If the service replies
with something other than '+OK', the program exits; maybe there is no
email. Otherwise, the program first announces that it intends to finish
reading email, and then redefines 'RS' in order to read the entire email
as multiline input in one record. From the POP RFC, we know that the
body of the email always ends with a single line containing a single
dot. The program looks for this using 'RS = "\r\n\\.\r\n"'. When it
finds this sequence in the mail message, it quits. You can invoke this
program as often as you like; it does not delete the message it reads,
but instead leaves it on the server.
---------- Footnotes ----------
(1) No, things are _not_ that simple any more. Things _were_ that
simple when email was young in the 20th century. These days,
unencrypted plaintext authentication is usually disallowed on non-secure
connections. Since encryption of network connections is not supported
in 'gawk', you should not use 'gawk' to write such scripts. We left
this node as it is because it demonstrates how application level
protocols work in principle (a command being issued by the client
followed by a reply coming back). Unfortunately, modern application
level protocols are much more flexible in the sequence of actions. For
example, modern POP3 servers may introduce themselves with an unprompted
initial line that arrives before the initial command. Dealing with such
variance is not worth the effort in 'gawk'.
File: gawkinet.info, Node: Web page, Next: Primitive Service, Prev: Email, Up: Using Networking
2.7 Reading a Web Page
======================
Retrieving a web page from a web server is as simple as retrieving email
from an email server. We only have to use a similar, but not identical,
protocol and a different port. The name of the protocol is HyperText
Transfer Protocol (HTTP) and the port number is usually 80. As in the
preceding node, ask your administrator about the name of your local web
server or proxy web server and its port number for HTTP requests.
The following program employs a rather crude approach toward
retrieving a web page. It uses the prehistoric syntax of HTTP 0.9,
which almost all web servers still support. The most noticeable thing
about it is that the program directs the request to the local proxy
server whose name you insert in the special file name (which in turn
calls 'www.yahoo.com'):
BEGIN {
RS = ORS = "\r\n"
HttpService = "/inet/tcp/0/PROXY/80"
print "GET http://www.yahoo.com" |& HttpService
while ((HttpService |& getline) > 0)
print $0
close(HttpService)
}
Again, lines are separated by a redefined 'RS' and 'ORS'. The 'GET'
request that we send to the server is the only kind of HTTP request that
existed when the web was created in the early 1990s. HTTP calls this
'GET' request a "method," which tells the service to transmit a web page
(here the home page of the Yahoo! search engine). Version 1.0 added
the request methods 'HEAD' and 'POST'. The current version of HTTP is
1.1,(1)(2) and knows the additional request methods 'OPTIONS', 'PUT',
'DELETE', and 'TRACE'. You can fill in any valid web address, and the
program prints the HTML code of that page to your screen.
Notice the similarity between the responses of the POP and HTTP
services. First, you get a header that is terminated by an empty line,
and then you get the body of the page in HTML. The lines of the headers
also have the same form as in POP. There is the name of a parameter,
then a colon, and finally the value of that parameter.
Images ('.png' or '.gif' files) can also be retrieved this way, but
then you get binary data that should be redirected into a file. Another
application is calling a CGI (Common Gateway Interface) script on some
server. CGI scripts are used when the contents of a web page are not
constant, but generated on demand at the moment you send a request for
the page. For example, to get a detailed report about the current
quotes of Motorola stock shares, call a CGI script at Yahoo! with the
following:
get = "GET http://quote.yahoo.com/q?s=MOT&d=t"
print get |& HttpService
You can also request weather reports this way.
---------- Footnotes ----------
(1) Version 1.0 of HTTP was defined in RFC 1945. HTTP 1.1 was
initially specified in RFC 2068. In June 1999, RFC 2068 was made
obsolete by RFC 2616, an update without any substantial changes.
(2) Version 2.0 of HTTP (https://en.wikipedia.org/wiki/HTTP/2) was
defined in RFC7540 (https://tools.ietf.org/html/rfc7540) and was derived
from Google's SPDY (https://en.wikipedia.org/wiki/SPDY) protocol. It is
said to be widely supported. As of 2020 the most popular web sites
still identify themselves as supporting HTTP/1.1. Version 3.0 of HTTP
(https://en.wikipedia.org/wiki/HTTP/3) is still a draft and was derived
from Google's QUIC (https://en.wikipedia.org/wiki/QUIC) protocol.
File: gawkinet.info, Node: Primitive Service, Next: Interacting Service, Prev: Web page, Up: Using Networking
2.8 A Primitive Web Service
===========================
Now we know enough about HTTP to set up a primitive web service that
just says '"Hello, world"' when someone connects to it with a browser.
Compared to the situation in the preceding node, our program changes the
role. It tries to behave just like the server we have observed. Since
we are setting up a server here, we have to insert the port number in
the 'localport' field of the special file name. The other two fields
(HOSTNAME and REMOTEPORT) have to contain a '0' because we do not know
in advance which host will connect to our service.
In the early 1990s, all a server had to do was send an HTML document
and close the connection. Here, we adhere to the modern syntax of HTTP.
The steps are as follows:
1. Send a status line telling the web browser that everything is okay.
2. Send a line to tell the browser how many bytes follow in the body
of the message. This was not necessary earlier because both
parties knew that the document ended when the connection closed.
Nowadays it is possible to stay connected after the transmission of
one web page. This avoids the network traffic necessary for
repeatedly establishing TCP connections for requesting several
images. Thus, it is necessary to tell the receiving party how many
bytes will be sent. The header is terminated as usual with an
empty line.
3. Send the '"Hello, world"' body in HTML. The useless 'while' loop
swallows the request of the browser. We could actually omit the
loop, and on most machines the program would still work. First,
start the following program:
BEGIN {
RS = ORS = "\r\n"
HttpService = "/inet/tcp/8080/0/0"
Hello = "<HTML><HEAD>" \
"<TITLE>A Famous Greeting</TITLE></HEAD>" \
"<BODY><H1>Hello, world</H1></BODY></HTML>"
Len = length(Hello) + length(ORS)
print "HTTP/1.0 200 OK" |& HttpService
print "Content-Length: " Len ORS |& HttpService
print Hello |& HttpService
while ((HttpService |& getline) > 0)
continue;
close(HttpService)
}
Now, on the same machine, start your favorite browser and let it
point to <http://localhost:8080> (the browser needs to know on which
port our server is listening for requests). If this does not work, the
browser probably tries to connect to a proxy server that does not know
your machine. If so, change the browser's configuration so that the
browser does not try to use a proxy to connect to your machine.
File: gawkinet.info, Node: Interacting Service, Next: Simple Server, Prev: Primitive Service, Up: Using Networking
2.9 A Web Service with Interaction
==================================
This node shows how to set up a simple web server. The subnode is a
library file that we will use with all the examples in *note Some
Applications and Techniques::.
* Menu:
* CGI Lib:: A simple CGI library.
Setting up a web service that allows user interaction is more
difficult and shows us the limits of network access in 'gawk'. In this
node, we develop a main program (a 'BEGIN' pattern and its action) that
will become the core of event-driven execution controlled by a graphical
user interface (GUI). Each HTTP event that the user triggers by some
action within the browser is received in this central procedure.
Parameters and menu choices are extracted from this request, and an
appropriate measure is taken according to the user's choice:
BEGIN {
if (MyHost == "") {
"uname -n" | getline MyHost
close("uname -n")
}
if (MyPort == 0) MyPort = 8080
HttpService = "/inet/tcp/" MyPort "/0/0"
MyPrefix = "http://" MyHost ":" MyPort
SetUpServer()
while ("awk" != "complex") {
# header lines are terminated this way
RS = ORS = "\r\n"
Status = 200 # this means OK
Reason = "OK"
Header = TopHeader
Document = TopDoc
Footer = TopFooter
if (GETARG["Method"] == "GET") {
HandleGET()
} else if (GETARG["Method"] == "HEAD") {
# not yet implemented
} else if (GETARG["Method"] != "") {
print "bad method", GETARG["Method"]
}
Prompt = Header Document Footer
print "HTTP/1.0", Status, Reason |& HttpService
print "Connection: Close" |& HttpService
print "Pragma: no-cache" |& HttpService
len = length(Prompt) + length(ORS)
print "Content-length:", len |& HttpService
print ORS Prompt |& HttpService
# ignore all the header lines
while ((HttpService |& getline) > 0)
;
# stop talking to this client
close(HttpService)
# wait for new client request
HttpService |& getline
# do some logging
print systime(), strftime(), $0
# read request parameters
CGI_setup($1, $2, $3)
}
}
This web server presents menu choices in the form of HTML links.
Therefore, it has to tell the browser the name of the host it is
residing on. When starting the server, the user may supply the name of
the host from the command line with 'gawk -v MyHost="Rumpelstilzchen"'.
If the user does not do this, the server looks up the name of the host
it is running on for later use as a web address in HTML documents. The
same applies to the port number. These values are inserted later into
the HTML content of the web pages to refer to the home system.
Each server that is built around this core has to initialize some
application-dependent variables (such as the default home page) in a
function 'SetUpServer()', which is called immediately before entering
the infinite loop of the server. For now, we will write an instance
that initiates a trivial interaction. With this home page, the client
user can click on two possible choices, and receive the current date
either in human-readable format or in seconds since 1970:
function SetUpServer() {
TopHeader = "<HTML><HEAD>"
TopHeader = TopHeader \
"<title>My name is GAWK, GNU AWK</title></HEAD>"
TopDoc = "<BODY><h2>\
Do you prefer your date <A HREF=" MyPrefix \
"/human>human</A> or \
<A HREF=" MyPrefix "/POSIX>POSIXed</A>?</h2>" ORS ORS
TopFooter = "</BODY></HTML>"
}
On the first run through the main loop, the default line terminators
are set and the default home page is copied to the actual home page.
Since this is the first run, 'GETARG["Method"]' is not initialized yet,
hence the case selection over the method does nothing. Now that the
home page is initialized, the server can start communicating to a client
browser.
It does so by printing the HTTP header into the network connection
('print ... |& HttpService'). This command blocks execution of the
server script until a client connects.
If you compare this server script with the primitive one we wrote
before, you will notice two additional lines in the header. The first
instructs the browser to close the connection after each request. The
second tells the browser that it should never try to _remember_ earlier
requests that had identical web addresses (no caching). Otherwise, it
could happen that the browser retrieves the time of day in the previous
example just once, and later it takes the web page from the cache,
always displaying the same time of day although time advances each
second.
Having supplied the initial home page to the browser with a valid
document stored in the parameter 'Prompt', it closes the connection and
waits for the next request. When the request comes, a log line is
printed that allows us to see which request the server receives. The
final step in the loop is to call the function 'CGI_setup()', which
reads all the lines of the request (coming from the browser), processes
them, and stores the transmitted parameters in the array 'PARAM'. The
complete text of these application-independent functions can be found in
*note A Simple CGI Library: CGI Lib. For now, we use a simplified
version of 'CGI_setup()':
function CGI_setup( method, uri, version, i) {
delete GETARG; delete MENU; delete PARAM
GETARG["Method"] = $1
GETARG["URI"] = $2
GETARG["Version"] = $3
i = index($2, "?")
# is there a "?" indicating a CGI request?
if (i > 0) {
split(substr($2, 1, i-1), MENU, "[/:]")
split(substr($2, i+1), PARAM, "&")
for (i in PARAM) {
j = index(PARAM[i], "=")
GETARG[substr(PARAM[i], 1, j-1)] = \
substr(PARAM[i], j+1)
}
} else { # there is no "?", no need for splitting PARAMs
split($2, MENU, "[/:]")
}
}
At first, the function clears all variables used for global storage
of request parameters. The rest of the function serves the purpose of
filling the global parameters with the extracted new values. To
accomplish this, the name of the requested resource is split into parts
and stored for later evaluation. If the request contains a '?', then
the request has CGI variables seamlessly appended to the web address.
Everything in front of the '?' is split up into menu items, and
everything behind the '?' is a list of 'VARIABLE=VALUE' pairs (separated
by '&') that also need splitting. This way, CGI variables are isolated
and stored. This procedure lacks recognition of special characters that
are transmitted in coded form(1). Here, any optional request header and
body parts are ignored. We do not need header parameters and the
request body. However, when refining our approach or working with the
'POST' and 'PUT' methods, reading the header and body becomes
inevitable. Header parameters should then be stored in a global array
as well as the body.
On each subsequent run through the main loop, one request from a
browser is received, evaluated, and answered according to the user's
choice. This can be done by letting the value of the HTTP method guide
the main loop into execution of the procedure 'HandleGET()', which
evaluates the user's choice. In this case, we have only one
hierarchical level of menus, but in the general case, menus are nested.
The menu choices at each level are separated by '/', just as in file
names. Notice how simple it is to construct menus of arbitrary depth:
function HandleGET() {
if ( MENU[2] == "human") {
Footer = strftime() TopFooter
} else if (MENU[2] == "POSIX") {
Footer = systime() TopFooter
}
}
The disadvantage of this approach is that our server is slow and can
handle only one request at a time. Its main advantage, however, is that
the server consists of just one 'gawk' program. No need for installing
an 'httpd', and no need for static separate HTML files, CGI scripts, or
'root' privileges. This is rapid prototyping. This program can be
started on the same host that runs your browser. Then let your browser
point to <http://localhost:8080>.
It is also possible to include images into the HTML pages. Most
browsers support the not very well-known '.xbm' format, which may
contain only monochrome pictures but is an ASCII format. Binary images
are possible but not so easy to handle. Another way of including images
is to generate them with a tool such as GNUPlot, by calling the tool
with the 'system()' function or through a pipe.
---------- Footnotes ----------
(1) As defined in RFC 2068.
File: gawkinet.info, Node: CGI Lib, Prev: Interacting Service, Up: Interacting Service
2.9.1 A Simple CGI Library
--------------------------
HTTP is like being married: you have to be able to handle whatever
you're given, while being very careful what you send back.
-- _Phil Smith III,
<http://www.netfunny.com/rhf/jokes/99/Mar/http.html>_
In *note A Web Service with Interaction: Interacting Service, we saw
the function 'CGI_setup()' as part of the web server "core logic"
framework. The code presented there handles almost everything necessary
for CGI requests. One thing it doesn't do is handle encoded characters
in the requests. For example, an '&' is encoded as a percent sign
followed by the hexadecimal value: '%26'. These encoded values should
be decoded. Following is a simple library to perform these tasks. This
code is used for all web server examples throughout the rest of this
Info file. If you want to use it for your own web server, store the
source code into a file named 'inetlib.awk'. Then you can include these
functions into your code by placing the following statement into your
program (on the first line of your script):
@include inetlib.awk
But beware, this mechanism is only possible if you invoke your web
server script with 'igawk' instead of the usual 'awk' or 'gawk'. Here
is the code:
# CGI Library and core of a web server
# Global arrays
# GETARG --- arguments to CGI GET command
# MENU --- menu items (path names)
# PARAM --- parameters of form x=y
# Optional variable MyHost contains host address
# Optional variable MyPort contains port number
# Needs TopHeader, TopDoc, TopFooter
# Sets MyPrefix, HttpService, Status, Reason
BEGIN {
if (MyHost == "") {
"uname -n" | getline MyHost
close("uname -n")
}
if (MyPort == 0) MyPort = 8080
HttpService = "/inet/tcp/" MyPort "/0/0"
MyPrefix = "http://" MyHost ":" MyPort
SetUpServer()
while ("awk" != "complex") {
# header lines are terminated this way
RS = ORS = "\r\n"
Status = 200 # this means OK
Reason = "OK"
Header = TopHeader
Document = TopDoc
Footer = TopFooter
if (GETARG["Method"] == "GET") {
HandleGET()
} else if (GETARG["Method"] == "HEAD") {
# not yet implemented
} else if (GETARG["Method"] != "") {
print "bad method", GETARG["Method"]
}
Prompt = Header Document Footer
print "HTTP/1.0", Status, Reason |& HttpService
print "Connection: Close" |& HttpService
print "Pragma: no-cache" |& HttpService
len = length(Prompt) + length(ORS)
print "Content-length:", len |& HttpService
print ORS Prompt |& HttpService
# ignore all the header lines
while ((HttpService |& getline) > 0)
continue
# stop talking to this client
close(HttpService)
# wait for new client request
HttpService |& getline
# do some logging
print systime(), strftime(), $0
CGI_setup($1, $2, $3)
}
}
function CGI_setup(method, uri, version, i)
{
delete GETARG
delete MENU
delete PARAM
GETARG["Method"] = method
GETARG["URI"] = uri
GETARG["Version"] = version
i = index(uri, "?")
if (i > 0) { # is there a "?" indicating a CGI request?
split(substr(uri, 1, i-1), MENU, "[/:]")
split(substr(uri, i+1), PARAM, "&")
for (i in PARAM) {
PARAM[i] = _CGI_decode(PARAM[i])
j = index(PARAM[i], "=")
GETARG[substr(PARAM[i], 1, j-1)] = \
substr(PARAM[i], j+1)
}
} else { # there is no "?", no need for splitting PARAMs
split(uri, MENU, "[/:]")
}
for (i in MENU) # decode characters in path
if (i > 4) # but not those in host name
MENU[i] = _CGI_decode(MENU[i])
}
This isolates details in a single function, 'CGI_setup()'. Decoding
of encoded characters is pushed off to a helper function,
'_CGI_decode()'. The use of the leading underscore ('_') in the
function name is intended to indicate that it is an "internal" function,
although there is nothing to enforce this:
function _CGI_decode(str, hexdigs, i, pre, code1, code2,
val, result)
{
hexdigs = "123456789abcdef"
i = index(str, "%")
if (i == 0) # no work to do
return str
do {
pre = substr(str, 1, i-1) # part before %xx
code1 = substr(str, i+1, 1) # first hex digit
code2 = substr(str, i+2, 1) # second hex digit
str = substr(str, i+3) # rest of string
code1 = tolower(code1)
code2 = tolower(code2)
val = index(hexdigs, code1) * 16 \
+ index(hexdigs, code2)
result = result pre sprintf("%c", val)
i = index(str, "%")
} while (i != 0)
if (length(str) > 0)
result = result str
return result
}
This works by splitting the string apart around an encoded character.
The two digits are converted to lowercase characters and looked up in a
string of hex digits. Note that '0' is not in the string on purpose;
'index()' returns zero when it's not found, automatically giving the
correct value! Once the hexadecimal value is converted from characters
in a string into a numerical value, 'sprintf()' converts the value back
into a real character. The following is a simple test harness for the
above functions:
BEGIN {
CGI_setup("GET",
"http://www.gnu.org/cgi-bin/foo?p1=stuff&p2=stuff%26junk" \
"&percent=a %25 sign",
"1.0")
for (i in MENU)
printf "MENU[\"%s\"] = %s\n", i, MENU[i]
for (i in PARAM)
printf "PARAM[\"%s\"] = %s\n", i, PARAM[i]
for (i in GETARG)
printf "GETARG[\"%s\"] = %s\n", i, GETARG[i]
}
And this is the result when we run it:
$ gawk -f testserv.awk
-| MENU["4"] = www.gnu.org
-| MENU["5"] = cgi-bin
-| MENU["6"] = foo
-| MENU["1"] = http
-| MENU["2"] =
-| MENU["3"] =
-| PARAM["1"] = p1=stuff
-| PARAM["2"] = p2=stuff&junk
-| PARAM["3"] = percent=a % sign
-| GETARG["p1"] = stuff
-| GETARG["percent"] = a % sign
-| GETARG["p2"] = stuff&junk
-| GETARG["Method"] = GET
-| GETARG["Version"] = 1.0
-| GETARG["URI"] = http://www.gnu.org/cgi-bin/foo?p1=stuff&
p2=stuff%26junk&percent=a %25 sign
File: gawkinet.info, Node: Simple Server, Next: Caveats, Prev: Interacting Service, Up: Using Networking
2.10 A Simple Web Server
========================
In the preceding node, we built the core logic for event-driven GUIs.
In this node, we finally extend the core to a real application. No one
would actually write a commercial web server in 'gawk', but it is
instructive to see that it is feasible in principle.
The application is ELIZA, the famous program by Joseph Weizenbaum
that mimics the behavior of a professional psychotherapist when talking
to you. Weizenbaum would certainly object to this description, but this
is part of the legend around ELIZA. Take the site-independent core logic
and append the following code:
function SetUpServer() {
SetUpEliza()
TopHeader = \
"<HTML><title>An HTTP-based System with GAWK</title>\
<HEAD><META HTTP-EQUIV=\"Content-Type\"\
CONTENT=\"text/html; charset=iso-8859-1\"></HEAD>\
<BODY BGCOLOR=\"#ffffff\" TEXT=\"#000000\"\
LINK=\"#0000ff\" VLINK=\"#0000ff\"\
ALINK=\"#0000ff\"> <A NAME=\"top\">"
TopDoc = "\
<h2>Please choose one of the following actions:</h2>\
<UL>\
<LI>\
<A HREF=" MyPrefix "/AboutServer>About this server</A>\
</LI><LI>\
<A HREF=" MyPrefix "/AboutELIZA>About Eliza</A></LI>\
<LI>\
<A HREF=" MyPrefix \
"/StartELIZA>Start talking to Eliza</A></LI></UL>"
TopFooter = "</BODY></HTML>"
}
'SetUpServer()' is similar to the previous example, except for
calling another function, 'SetUpEliza()'. This approach can be used to
implement other kinds of servers. The only changes needed to do so are
hidden in the functions 'SetUpServer()' and 'HandleGET()'. Perhaps it
might be necessary to implement other HTTP methods. The 'igawk' program
that comes with 'gawk' may be useful for this process.
When extending this example to a complete application, the first
thing to do is to implement the function 'SetUpServer()' to initialize
the HTML pages and some variables. These initializations determine the
way your HTML pages look (colors, titles, menu items, etc.).
The function 'HandleGET()' is a nested case selection that decides
which page the user wants to see next. Each nesting level refers to a
menu level of the GUI. Each case implements a certain action of the
menu. At the deepest level of case selection, the handler essentially
knows what the user wants and stores the answer into the variable that
holds the HTML page contents:
function HandleGET() {
# A real HTTP server would treat some parts of the URI as a file name.
# We take parts of the URI as menu choices and go on accordingly.
if (MENU[2] == "AboutServer") {
Document = "This is not a CGI script.\
This is an httpd, an HTML file, and a CGI script all \
in one GAWK script. It needs no separate www-server, \
no installation, and no root privileges.\
<p>To run it, do this:</p><ul>\
<li> start this script with \"gawk -f httpserver.awk\",</li>\
<li> and on the same host let your www browser open location\
\"http://localhost:8080\"</li>\
</ul>\<p>\ Details of HTTP come from:</p><ul>\
<li>Hethmon: Illustrated Guide to HTTP</p>\
<li>RFC 2068</li></ul><p>JK 14.9.1997</p>"
} else if (MENU[2] == "AboutELIZA") {
Document = "This is an implementation of the famous ELIZA\
program by Joseph Weizenbaum. It is written in GAWK and\
uses an HTML GUI."
} else if (MENU[2] == "StartELIZA") {
gsub(/\+/, " ", GETARG["YouSay"])
# Here we also have to substitute coded special characters
Document = "<form method=GET>" \
"<h3>" ElizaSays(GETARG["YouSay"]) "</h3>\
<p><input type=text name=YouSay value=\"\" size=60>\
<br><input type=submit value=\"Tell her about it\"></p></form>"
}
}
Now we are down to the heart of ELIZA, so you can see how it works.
Initially the user does not say anything; then ELIZA resets its money
counter and asks the user to tell what comes to mind open-heartedly.
The subsequent answers are converted to uppercase characters and stored
for later comparison. ELIZA presents the bill when being confronted
with a sentence that contains the phrase "shut up." Otherwise, it looks
for keywords in the sentence, conjugates the rest of the sentence,
remembers the keyword for later use, and finally selects an answer from
the set of possible answers:
function ElizaSays(YouSay) {
if (YouSay == "") {
cost = 0
answer = "HI, IM ELIZA, TELL ME YOUR PROBLEM"
} else {
q = toupper(YouSay)
gsub("'", "", q)
if (q == qold) {
answer = "PLEASE DONT REPEAT YOURSELF !"
} else {
if (index(q, "SHUT UP") > 0) {
answer = "WELL, PLEASE PAY YOUR BILL. ITS EXACTLY ... $"\
int(100*rand()+30+cost/100)
} else {
qold = q
w = "-" # no keyword recognized yet
for (i in k) { # search for keywords
if (index(q, i) > 0) {
w = i
break
}
}
if (w == "-") { # no keyword, take old subject
w = wold
subj = subjold
} else { # find subject
subj = substr(q, index(q, w) + length(w)+1)
wold = w
subjold = subj # remember keyword and subject
}
for (i in conj)
gsub(i, conj[i], q) # conjugation
# from all answers to this keyword, select one randomly
answer = r[indices[int(split(k[w], indices) * rand()) + 1]]
# insert subject into answer
gsub("_", subj, answer)
}
}
}
cost += length(answer) # for later payment : 1 cent per character
return answer
}
In the long but simple function 'SetUpEliza()', you can see tables
for conjugation, keywords, and answers.(1) The associative array 'k'
contains indices into the array of answers 'r'. To choose an answer,
ELIZA just picks an index randomly:
function SetUpEliza() {
srand()
wold = "-"
subjold = " "
# table for conjugation
conj[" ARE " ] = " AM "
conj["WERE " ] = "WAS "
conj[" YOU " ] = " I "
conj["YOUR " ] = "MY "
conj[" IVE " ] =\
conj[" I HAVE " ] = " YOU HAVE "
conj[" YOUVE " ] =\
conj[" YOU HAVE "] = " I HAVE "
conj[" IM " ] =\
conj[" I AM " ] = " YOU ARE "
conj[" YOURE " ] =\
conj[" YOU ARE " ] = " I AM "
# table of all answers
r[1] = "DONT YOU BELIEVE THAT I CAN _"
r[2] = "PERHAPS YOU WOULD LIKE TO BE ABLE TO _ ?"
...
# table for looking up answers that
# fit to a certain keyword
k["CAN YOU"] = "1 2 3"
k["CAN I"] = "4 5"
k["YOU ARE"] =\
k["YOURE"] = "6 7 8 9"
...
}
Some interesting remarks and details (including the original source
code of ELIZA) are found on Mark Humphrys's home page 'How my program
passed the Turing Test' (https://computing.dcu.ie/~humphrys/eliza.html).
Wikipedia provides much background information about ELIZA
(https://en.wikipedia.org/wiki/ELIZA), including the original design of
the software and its early implementations.
---------- Footnotes ----------
(1) The version shown here is abbreviated. The full version comes
with the 'gawk' distribution.
File: gawkinet.info, Node: Caveats, Next: Challenges, Prev: Simple Server, Up: Using Networking
2.11 Network Programming Caveats
================================
By now it should be clear that debugging a networked application is more
complicated than debugging a single-process single-hosted application.
The behavior of a networked application sometimes looks noncausal
because it is not reproducible in a strong sense. Whether a network
application works or not sometimes depends on the following:
* How crowded the underlying network is
* If the party at the other end is running or not
* The state of the party at the other end
The most difficult problems for a beginner arise from the hidden
states of the underlying network. After closing a TCP connection, it's
often necessary to wait a short while before reopening the connection.
Even more difficult is the establishment of a connection that previously
ended with a "broken pipe." Those connections have to "time out" for a
minute or so before they can reopen. Check this with the command
'netstat -a', which provides a list of still-active connections.
File: gawkinet.info, Node: Challenges, Prev: Caveats, Up: Using Networking
2.12 Where To Go From Here
==========================
Now, you have learned enough to build your own application. You could,
for example, take part in the Loebner Contest to win $100,000. The
Loebner Prize is the first formal instantiation of a Turing Test. Hugh
Loebner agreed with The Cambridge Center for Behavioral Studies to
underwrite a contest designed to implement the Turing Test. Dr. Loebner
pledged a Grand Prize of $100,000 for the first computer whose responses
were indistinguishable from a human's. Each year an annual prize of
$2000 and a bronze medal is awarded to the _most_ human computer. The
winner of the annual contest is the best entry relative to other entries
that year, irrespective of how good it is in an absolute sense. Here is
an example of a conversation with the winning program of 1997:
(c)1997 Cambridge Center For Behavioral Studies all rights reserved [CONVERSE]
[Intelligent Research Ltd.] Start at: [1997/04/29 08:59:40]
PROGRAM[10:39:20]Hi, my name is Catherine, what's yours?
JUDGE02[10:39:36]My name is Nathan.
PROGRAM[10:39:37]Well, it's nice to meet you, Nathan.
PROGRAM[10:39:45]Did you see that story on CNN last night about the lesbian
PROGRAM[10:40:03]couple who came out at a White House party on Sunday?
JUDGE02[10:40:45]No. I'm sorry I missed that. How did the Prez take it?
PROGRAM[10:40:47]Ellen Degeneres was one of them - she was kissing her lover
PROGRAM[10:41:08]in front of Bill Clinton. Do you think he was very
PROGRAM[10:41:21]embarrassed?
JUDGE02[10:41:37]You tell me. I didn't see it.
PROGRAM[10:41:38]Are you still a Friend of Bill Clinton?
JUDGE02[10:42:22]Yes. I would like to talk about something else. Do you know anything about sculpture.
PROGRAM[10:42:24]Well, I suppose he's doing his best like most of us, but he
PROGRAM[10:42:35]does seem to attract an UNUSUAL amount of bad publicity,
PROGRAM[10:42:51]wouldnt you say--can it all be bad luck?
JUDGE02[10:43:20]I asked you if you knew anything about sculpture.
PROGRAM[10:43:21]OK, but what happens now--does it all drift on, with
PROGRAM[10:43:36]everyone waiting to see how much his friends have said about
PROGRAM[10:43:47]him under threat of lots and lots of jail-or will something
PROGRAM[10:44:01]dramatic actually happen?
JUDGE02[10:44:19]Do you know what sculpture is?
PROGRAM[10:44:20]Well, youre more a fan of his than I am I guess---though I
PROGRAM[10:44:34]cant SWEAR what Id have done in that locked hotel room, I
PROGRAM[10:44:51]must say.
JUDGE02[10:45:26]Have you ever been to the Salmagundi Club?
PROGRAM[10:45:29]Never. to go back to the original discussion Time to get
PROGRAM[10:45:43]off this one I think and onto something more down to earth!
JUDGE02[10:46:20]What is more down to earth than art?
PROGRAM[10:46:21]I don't know what -- to be honest. -
PROGRAM[10:46:30]I suppose it depends on where you're coming from, but as the
PROGRAM[10:46:46]song goes in My Fair Lady, "Why can't a woman be more like a
PROGRAM[10:47:03]man? "
JUDGE02[10:47:52]I liked that song but I prefer "Why can't children be more like we are"
JUDGE02[10:48:10]from another play the name of which I cannot remember.
PROGRAM[10:48:12]What, if anything, do you enjoy about being a man?
JUDGE02[10:49:01]I would enjoy all aspects of life no matter what my gender.
PROGRAM[10:49:02]Do you think of yourself as being attractive?
This program insists on always speaking about the same story around
Bill Clinton. You see, even a program with a rather narrow mind can
behave so much like a human being that it can win this prize. It is
quite common to let these programs talk to each other via network
connections. But during the competition itself, the program and its
computer have to be present at the place the competition is held. We
all would love to see a 'gawk' program win in such an event. Maybe it
is up to you to accomplish this?
Some other ideas for useful networked applications:
* Read the file 'doc/awkforai.txt' in earlier 'gawk'
distributions.(1) It was written by Ronald P. Loui (at the time,
Associate Professor of Computer Science, at Washington University
in St. Louis, <loui@ai.wustl.edu>) and summarizes why he taught
'gawk' to students of Artificial Intelligence. Here are some
passages from the text:
The GAWK manual can be consumed in a single lab session and
the language can be mastered by the next morning by the
average student. GAWK's automatic initialization, implicit
coercion, I/O support and lack of pointers forgive many of the
mistakes that young programmers are likely to make. Those who
have seen C but not mastered it are happy to see that GAWK
retains some of the same sensibilities while adding what must
be regarded as spoonsful of syntactic sugar.
...
There are further simple answers. Probably the best is the
fact that increasingly, undergraduate AI programming is
involving the Web. Oren Etzioni (University of Washington,
Seattle) has for a while been arguing that the "softbot" is
replacing the mechanical engineers' robot as the most
glamorous AI testbed. If the artifact whose behavior needs to
be controlled in an intelligent way is the software agent,
then a language that is well-suited to controlling the
software environment is the appropriate language. That would
imply a scripting language. If the robot is KAREL, then the
right language is "turn left; turn right." If the robot is
Netscape, then the right language is something that can
generate 'netscape -remote
'openURL(http://cs.wustl.edu/~loui)'' with elan.
...
AI programming requires high-level thinking. There have
always been a few gifted programmers who can write high-level
programs in assembly language. Most however need the ambient
abstraction to have a higher floor.
...
Second, inference is merely the expansion of notation. No
matter whether the logic that underlies an AI program is
fuzzy, probabilistic, deontic, defeasible, or deductive, the
logic merely defines how strings can be transformed into other
strings. A language that provides the best support for string
processing in the end provides the best support for logic, for
the exploration of various logics, and for most forms of
symbolic processing that AI might choose to call "reasoning"
instead of "logic." The implication is that PROLOG, which
saves the AI programmer from having to write a unifier, saves
perhaps two dozen lines of GAWK code at the expense of
strongly biasing the logic and representational expressiveness
of any approach.
Now that 'gawk' itself can connect to the Internet, it should be
obvious that it is suitable for writing intelligent web agents.
* 'awk' is strong at pattern recognition and string processing. So,
it is well suited to the classic problem of language translation.
A first try could be a program that knows the 100 most frequent
English words and their counterparts in German or French. The
service could be implemented by regularly reading email with the
program above, replacing each word by its translation and sending
the translation back via SMTP. Users would send English email to
their translation service and get back a translated email message
in return. As soon as this works, more effort can be spent on a
real translation program.
* Another dialogue-oriented application (on the verge of ridicule) is
the email "support service." Troubled customers write an email to
an automatic 'gawk' service that reads the email. It looks for
keywords in the mail and assembles a reply email accordingly. By
carefully investigating the email header, and repeating these
keywords through the reply email, it is rather simple to give the
customer a feeling that someone cares. Ideally, such a service
would search a database of previous cases for solutions. If none
exists, the database could, for example, consist of all the
newsgroups, mailing lists and FAQs on the Internet.
---------- Footnotes ----------
(1) The file is no longer distributed with 'gawk', since the
copyright on the file is not clear.
File: gawkinet.info, Node: Some Applications and Techniques, Next: Links, Prev: Using Networking, Up: Top
3 Some Applications and Techniques
**********************************
In this major node, we look at a number of self-contained scripts, with
an emphasis on concise networking. Along the way, we work towards
creating building blocks that encapsulate often-needed functions of the
networking world, show new techniques that broaden the scope of problems
that can be solved with 'gawk', and explore leading edge technology that
may shape the future of networking.
We often refer to the site-independent core of the server that we
built in *note A Simple Web Server: Simple Server. When building new
and nontrivial servers, we always copy this building block and append
new instances of the two functions 'SetUpServer()' and 'HandleGET()'.
This makes a lot of sense, since this scheme of event-driven
execution provides 'gawk' with an interface to the most widely accepted
standard for GUIs: the web browser. Now, 'gawk' can rival even Tcl/Tk.
Tcl and 'gawk' have much in common. Both are simple scripting
languages that allow us to quickly solve problems with short programs.
But Tcl has Tk on top of it, and 'gawk' had nothing comparable up to
now. While Tcl needs a large and ever-changing library (Tk, which was
originally bound to the X Window System), 'gawk' needs just the
networking interface and some kind of browser on the client's side.
Besides better portability, the most important advantage of this
approach (embracing well-established standards such HTTP and HTML) is
that _we do not need to change the language_. We let others do the work
of fighting over protocols and standards. We can use HTML, JavaScript,
VRML, or whatever else comes along to do our work.
* Menu:
* PANIC:: An Emergency Web Server.
* GETURL:: Retrieving Web Pages.
* REMCONF:: Remote Configuration Of Embedded Systems.
* URLCHK:: Look For Changed Web Pages.
* WEBGRAB:: Extract Links From A Page.
* STATIST:: Graphing A Statistical Distribution.
* MAZE:: Walking Through A Maze In Virtual Reality.
* MOBAGWHO:: A Simple Mobile Agent.
* STOXPRED:: Stock Market Prediction As A Service.
* PROTBASE:: Searching Through A Protein Database.
File: gawkinet.info, Node: PANIC, Next: GETURL, Prev: Some Applications and Techniques, Up: Some Applications and Techniques
3.1 PANIC: An Emergency Web Server
==================================
At first glance, the '"Hello, world"' example in *note A Primitive Web
Service: Primitive Service, seems useless. By adding just a few lines,
we can turn it into something useful.
The PANIC program tells everyone who connects that the local site is
not working. When a web server breaks down, it makes a difference if
customers get a strange "network unreachable" message, or a short
message telling them that the server has a problem. In such an
emergency, the hard disk and everything on it (including the regular web
service) may be unavailable. Rebooting the web server off a USB drive
makes sense in this setting.
To use the PANIC program as an emergency web server, all you need are
the 'gawk' executable and the program below on a USB drive. By default,
it connects to port 8080. A different value may be supplied on the
command line:
BEGIN {
RS = ORS = "\r\n"
if (MyPort == 0) MyPort = 8080
HttpService = "/inet/tcp/" MyPort "/0/0"
Hello = "<HTML><HEAD><TITLE>Out Of Service</TITLE>" \
"</HEAD><BODY><H1>" \
"This site is temporarily out of service." \
"</H1></BODY></HTML>"
Len = length(Hello) + length(ORS)
while ("awk" != "complex") {
print "HTTP/1.0 200 OK" |& HttpService
print "Content-Length: " Len ORS |& HttpService
print Hello |& HttpService
while ((HttpService |& getline) > 0)
continue;
close(HttpService)
}
}
File: gawkinet.info, Node: GETURL, Next: REMCONF, Prev: PANIC, Up: Some Applications and Techniques
3.2 GETURL: Retrieving Web Pages
================================
GETURL is a versatile building block for shell scripts that need to
retrieve files from the Internet. It takes a web address as a
command-line parameter and tries to retrieve the contents of this
address. The contents are printed to standard output, while the header
is printed to '/dev/stderr'. A surrounding shell script could analyze
the contents and extract the text or the links. An ASCII browser could
be written around GETURL. But more interestingly, web robots are
straightforward to write on top of GETURL. On the Internet, you can find
several programs of the same name that do the same job. They are
usually much more complex internally and at least 10 times as big.
At first, GETURL checks if it was called with exactly one web
address. Then, it checks if the user chose to use a special proxy
server whose name is handed over in a variable. By default, it is
assumed that the local machine serves as proxy. GETURL uses the 'GET'
method by default to access the web page. By handing over the name of a
different method (such as 'HEAD'), it is possible to choose a different
behavior. With the 'HEAD' method, the user does not receive the body of
the page content, but does receive the header:
BEGIN {
if (ARGC != 2) {
print "GETURL - retrieve Web page via HTTP 1.0"
print "IN:\n the URL as a command-line parameter"
print "PARAM(S):\n -v Proxy=MyProxy"
print "OUT:\n the page content on stdout"
print " the page header on stderr"
print "JK 16.05.1997"
print "ADR 13.08.2000"
exit
}
URL = ARGV[1]; ARGV[1] = ""
if (Proxy == "") Proxy = "127.0.0.1"
if (ProxyPort == 0) ProxyPort = 80
if (Method == "") Method = "GET"
HttpService = "/inet/tcp/0/" Proxy "/" ProxyPort
ORS = RS = "\r\n\r\n"
print Method " " URL " HTTP/1.0" |& HttpService
HttpService |& getline Header
print Header > "/dev/stderr"
while ((HttpService |& getline) > 0)
printf "%s", $0
close(HttpService)
}
This program can be changed as needed, but be careful with the last
lines. Make sure transmission of binary data is not corrupted by
additional line breaks. Even as it is now, the byte sequence
'"\r\n\r\n"' would disappear if it were contained in binary data. Don't
get caught in a trap when trying a quick fix on this one.
File: gawkinet.info, Node: REMCONF, Next: URLCHK, Prev: GETURL, Up: Some Applications and Techniques
3.3 REMCONF: Remote Configuration of Embedded Systems
=====================================================
Today, you often find powerful processors in embedded systems.
Dedicated network routers and controllers for all kinds of machinery are
examples of embedded systems. Processors like the Intel 80x86 or the
AMD Elan are able to run multitasking operating systems, such as XINU or
GNU/Linux in embedded PCs. These systems are small and usually do not
have a keyboard or a display. Therefore it is difficult to set up their
configuration. There are several widespread ways to set them up:
* DIP switches
* Read Only Memories such as EPROMs
* Serial lines or some kind of keyboard
* Network connections via 'telnet' or SNMP
* HTTP connections with HTML GUIs
In this node, we look at a solution that uses HTTP connections to
control variables of an embedded system that are stored in a file.
Since embedded systems have tight limits on resources like memory, it is
difficult to employ advanced techniques such as SNMP and HTTP servers.
'gawk' fits in quite nicely with its single executable which needs just
a short script to start working. The following program stores the
variables in a file, and a concurrent process in the embedded system may
read the file. The program uses the site-independent part of the simple
web server that we developed in *note A Web Service with Interaction:
Interacting Service. As mentioned there, all we have to do is to write
two new procedures 'SetUpServer()' and 'HandleGET()':
function SetUpServer() {
TopHeader = "<HTML><title>Remote Configuration</title>"
TopDoc = "<BODY>\
<h2>Please choose one of the following actions:</h2>\
<UL>\
<LI><A HREF=" MyPrefix "/AboutServer>About this server</A></LI>\
<LI><A HREF=" MyPrefix "/ReadConfig>Read Configuration</A></LI>\
<LI><A HREF=" MyPrefix "/CheckConfig>Check Configuration</A></LI>\
<LI><A HREF=" MyPrefix "/ChangeConfig>Change Configuration</A></LI>\
<LI><A HREF=" MyPrefix "/SaveConfig>Save Configuration</A></LI>\
</UL>"
TopFooter = "</BODY></HTML>"
if (ConfigFile == "") ConfigFile = "config.asc"
}
The function 'SetUpServer()' initializes the top level HTML texts as
usual. It also initializes the name of the file that contains the
configuration parameters and their values. In case the user supplies a
name from the command line, that name is used. The file is expected to
contain one parameter per line, with the name of the parameter in column
one and the value in column two.
The function 'HandleGET()' reflects the structure of the menu tree as
usual. The first menu choice tells the user what this is all about.
The second choice reads the configuration file line by line and stores
the parameters and their values. Notice that the record separator for
this file is '"\n"', in contrast to the record separator for HTTP. The
third menu choice builds an HTML table to show the contents of the
configuration file just read. The fourth choice does the real work of
changing parameters, and the last one just saves the configuration into
a file:
function HandleGET() {
if (MENU[2] == "AboutServer") {
Document = "This is a GUI for remote configuration of an\
embedded system. It is is implemented as one GAWK script."
} else if (MENU[2] == "ReadConfig") {
RS = "\n"
while ((getline < ConfigFile) > 0)
config[$1] = $2;
close(ConfigFile)
RS = "\r\n"
Document = "Configuration has been read."
} else if (MENU[2] == "CheckConfig") {
Document = "<TABLE BORDER=1 CELLPADDING=5>"
for (i in config)
Document = Document "<TR><TD>" i "</TD>" \
"<TD>" config[i] "</TD></TR>"
Document = Document "</TABLE>"
} else if (MENU[2] == "ChangeConfig") {
if ("Param" in GETARG) { # any parameter to set?
if (GETARG["Param"] in config) { # is parameter valid?
config[GETARG["Param"]] = GETARG["Value"]
Document = (GETARG["Param"] " = " GETARG["Value"] ".")
} else {
Document = "Parameter <b>" GETARG["Param"] "</b> is invalid."
}
} else {
Document = "<FORM method=GET><h4>Change one parameter</h4>\
<TABLE BORDER CELLPADDING=5>\
<TR><TD>Parameter</TD><TD>Value</TD></TR>\
<TR><TD><input type=text name=Param value=\"\" size=20></TD>\
<TD><input type=text name=Value value=\"\" size=40></TD>\
</TR></TABLE><input type=submit value=\"Set\"></FORM>"
}
} else if (MENU[2] == "SaveConfig") {
for (i in config)
printf("%s %s\n", i, config[i]) > ConfigFile
close(ConfigFile)
Document = "Configuration has been saved."
}
}
We could also view the configuration file as a database. From this
point of view, the previous program acts like a primitive database
server. Real SQL database systems also make a service available by
providing a TCP port that clients can connect to. But the application
level protocols they use are usually proprietary and also change from
time to time. This is also true for the protocol that MiniSQL uses.
File: gawkinet.info, Node: URLCHK, Next: WEBGRAB, Prev: REMCONF, Up: Some Applications and Techniques
3.4 URLCHK: Look for Changed Web Pages
======================================
Most people who make heavy use of Internet resources have a large
bookmark file with pointers to interesting web sites. It is impossible
to regularly check by hand if any of these sites have changed. A
program is needed to automatically look at the headers of web pages and
tell which ones have changed. URLCHK does the comparison after using
GETURL with the 'HEAD' method to retrieve the header.
Like GETURL, this program first checks that it is called with exactly
one command-line parameter. URLCHK also takes the same command-line
variables 'Proxy' and 'ProxyPort' as GETURL, because these variables are
handed over to GETURL for each URL that gets checked. The one and only
parameter is the name of a file that contains one line for each URL. In
the first column, we find the URL, and the second and third columns hold
the length of the URL's body when checked for the two last times. Now,
we follow this plan:
1. Read the URLs from the file and remember their most recent lengths
2. Delete the contents of the file
3. For each URL, check its new length and write it into the file
4. If the most recent and the new length differ, tell the user
It may seem a bit peculiar to read the URLs from a file together with
their two most recent lengths, but this approach has several advantages.
You can call the program again and again with the same file. After
running the program, you can regenerate the changed URLs by extracting
those lines that differ in their second and third columns:
BEGIN {
if (ARGC != 2) {
print "URLCHK - check if URLs have changed"
print "IN:\n the file with URLs as a command-line parameter"
print " file contains URL, old length, new length"
print "PARAMS:\n -v Proxy=MyProxy -v ProxyPort=8080"
print "OUT:\n same as file with URLs"
print "JK 02.03.1998"
exit
}
URLfile = ARGV[1]; ARGV[1] = ""
if (Proxy != "") Proxy = " -v Proxy=" Proxy
if (ProxyPort != "") ProxyPort = " -v ProxyPort=" ProxyPort
while ((getline < URLfile) > 0)
Length[$1] = $3 + 0
close(URLfile) # now, URLfile is read in and can be updated
GetHeader = "gawk " Proxy ProxyPort " -v Method=\"HEAD\" -f geturl.awk "
for (i in Length) {
GetThisHeader = GetHeader i " 2>&1"
while ((GetThisHeader | getline) > 0)
if (toupper($0) ~ /CONTENT-LENGTH/) NewLength = $2 + 0
close(GetThisHeader)
print i, Length[i], NewLength > URLfile
if (Length[i] != NewLength) # report only changed URLs
print i, Length[i], NewLength
}
close(URLfile)
}
Another thing that may look strange is the way GETURL is called.
Before calling GETURL, we have to check if the proxy variables need to
be passed on. If so, we prepare strings that will become part of the
command line later. In 'GetHeader', we store these strings together
with the longest part of the command line. Later, in the loop over the
URLs, 'GetHeader' is appended with the URL and a redirection operator to
form the command that reads the URL's header over the Internet. GETURL
always sends the headers to '/dev/stderr'. That is the reason why we
need the redirection operator to have the header piped in.
This program is not perfect because it assumes that changing URLs
results in changed lengths, which is not necessarily true. A more
advanced approach is to look at some other header line that holds time
information. But, as always when things get a bit more complicated,
this is left as an exercise to the reader.
File: gawkinet.info, Node: WEBGRAB, Next: STATIST, Prev: URLCHK, Up: Some Applications and Techniques
3.5 WEBGRAB: Extract Links from a Page
======================================
Sometimes it is necessary to extract links from web pages. Browsers do
it, web robots do it, and sometimes even humans do it. Since we have a
tool like GETURL at hand, we can solve this problem with some help from
the Bourne shell:
BEGIN { RS = "https?://[#%&\\+\\-\\./0-9\\:;\\?A-Z_a-z\\~]*" }
RT != "" {
command = ("gawk -v Proxy=MyProxy -f geturl.awk " RT \
" > doc" NR ".html")
print command
}
Notice that the regular expression for URLs is rather crude. A
precise regular expression is much more complex. But this one works
rather well. One problem is that it is unable to find internal links of
an HTML document. Another problem is that 'ftp', 'telnet', 'news',
'mailto', and other kinds of links are missing in the regular
expression. However, it is straightforward to add them, if doing so is
necessary for other tasks.
This program reads an HTML file and prints all the HTTP links that it
finds. It relies on 'gawk''s ability to use regular expressions as the
record separator. With 'RS' set to a regular expression that matches
links, the second action is executed each time a non-empty link is
found. We can find the matching link itself in 'RT'.
The action could use the 'system()' function to let another GETURL
retrieve the page, but here we use a different approach. This simple
program prints shell commands that can be piped into 'sh' for execution.
This way it is possible to first extract the links, wrap shell commands
around them, and pipe all the shell commands into a file. After editing
the file, execution of the file retrieves only those files that we
really need. In case we do not want to edit, we can retrieve all the
pages like this:
gawk -f geturl.awk http://www.suse.de | gawk -f webgrab.awk | sh
After this, you will find the contents of all referenced documents in
files named 'doc*.html' even if they do not contain HTML code. The most
annoying thing is that we always have to pass the proxy to GETURL. If
you do not like to see the headers of the web pages appear on the
screen, you can redirect them to '/dev/null'. Watching the headers
appear can be quite interesting, because it reveals interesting details
such as which web server the companies use. Now, it is clear how the
clever marketing people use web robots to determine the market shares of
Microsoft and Netscape in the web server market.
Port 80 of any web server is like a small hole in a repellent
firewall. After attaching a browser to port 80, we usually catch a
glimpse of the bright side of the server (its home page). With a tool
like GETURL at hand, we are able to discover some of the more concealed
or even "indecent" services (i.e., lacking conformity to standards of
quality). It can be exciting to see the fancy CGI scripts that lie
there, revealing the inner workings of the server, ready to be called:
* With a command such as:
gawk -f geturl.awk http://any.host.on.the.net/cgi-bin/
some servers give you a directory listing of the CGI files.
Knowing the names, you can try to call some of them and watch for
useful results. Sometimes there are executables in such
directories (such as Perl interpreters) that you may call remotely.
If there are subdirectories with configuration data of the web
server, this can also be quite interesting to read.
* The well-known Apache web server usually has its CGI files in the
directory '/cgi-bin'. There you can often find the scripts
'test-cgi' and 'printenv'. Both tell you some things about the
current connection and the installation of the web server. Just
call:
gawk -f geturl.awk http://any.host.on.the.net/cgi-bin/test-cgi
gawk -f geturl.awk http://any.host.on.the.net/cgi-bin/printenv
* Sometimes it is even possible to retrieve system files like the web
server's log file--possibly containing customer data--or even the
file '/etc/passwd'. (We don't recommend this!)
*Caution:* Although this may sound funny or simply irrelevant, we are
talking about severe security holes. Try to explore your own system
this way and make sure that none of the above reveals too much
information about your system.
File: gawkinet.info, Node: STATIST, Next: MAZE, Prev: WEBGRAB, Up: Some Applications and Techniques
3.6 STATIST: Graphing a Statistical Distribution
================================================
|