File: MIME.st

package info (click to toggle)
gnu-smalltalk 3.2.5-1.3
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 32,272 kB
  • sloc: ansic: 87,539; sh: 23,443; asm: 8,465; perl: 4,497; cpp: 3,548; xml: 1,671; awk: 1,582; yacc: 1,357; makefile: 1,220; lisp: 988; lex: 843; sed: 258; objc: 124
file content (3798 lines) | stat: -rw-r--r-- 101,270 bytes parent folder | download | duplicates (2)
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
"======================================================================
|
|   MIME support
|
|
 ======================================================================"

"======================================================================
|
| Copyright (c) 2000 Cincom, Inc.
| Copyright (c) 2009 Free Software Foundation
|
| This file is part of the GNU Smalltalk class library.
|
| The GNU Smalltalk class library is free software; you can redistribute it
| and/or modify it under the terms of the GNU Lesser General Public License
| as published by the Free Software Foundation; either version 2.1, or (at
| your option) any later version.
|
| The GNU Smalltalk class library is distributed in the hope that it will be
| useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser
| General Public License for more details.
|
| You should have received a copy of the GNU Lesser General Public License
| along with the GNU Smalltalk class library; see the file COPYING.LIB.
| If not, write to the Free Software Foundation, 59 Temple Place - Suite
| 330, Boston, MA 02110-1301, USA.
|
 ======================================================================"



Namespace current: NetClients.MIME [

Object subclass: MessageElement [
    
    <category: 'NetClients-MIME'>
    <comment: nil>

    MessageElement class >> new [
	<category: 'instance creation'>
	^self basicNew initialize
    ]

    MessageElement class >> fromLine: aString [
	"For compatibility with Swazoo"

	<category: 'parsing'>
	self subclassResponsibility
    ]

    MessageElement class >> readFrom: aStream [
	"Each message element has responsibility to read itself from input stream. Reading usually involves parsing, so implementations of this method create an instance of lexical scanner and invoke a parser (see explanation for parse: method)"

	<category: 'parsing'>
	self subclassResponsibility
    ]

    MessageElement class >> readFromClient: aStream [
	"This just parses a RFC821 message (with dots before each line)"

	<category: 'parsing'>
	^self readFrom: (RemoveDotStream on: aStream)
    ]

    MessageElement class >> scannerOn: aStream [
	<category: 'parsing'>
	^((aStream respondsTo: #isRFC822Scanner) 
	    and: [aStream respondsTo: #isRFC822Scanner]) 
		ifTrue: [aStream]
		ifFalse: [self scannerType on: aStream]
    ]

    MessageElement class >> scannerType [
	<category: 'parsing'>
	self subclassResponsibility
    ]

    canonicalValue [
	"Canonical value of an item represents its external representation as required by relevant protocols. Usually an element has to be converted to a cannonical representation before it can be sent over the network. This is a requirement of RFC822 and MIME. Canonical representation removes all whitespace between adjacent tokens"

	<category: 'accessing'>
	self subclassResponsibility
    ]

    value [
	"Answers current value of the item. For structured elements (i.e. structured header fields) this value may be different for the source value read from source stream. For unstructured elements source and value are the same"

	<category: 'accessing'>
	^self source
    ]

    value: aValue [
	<category: 'accessing'>
	self source: aValue
    ]

    parse: scanner [
	"Each message element has responsibility to parse itself. The argument is an appropriate scanner. Scanners for RFC822, Mime and HTTP messages are stream wrappers, so they can be used to read and tokenize input stream"

	<category: 'parsing'>
	self subclassResponsibility
    ]

    readFrom: aStream [
	"Each message element has responsibility to read itself from input stream. Reading usually involves parsing, so implementations of this method typically create an instance of lexical scanner and invoke a parser (see explanation for parse: method)"

	<category: 'parsing'>
	self subclassResponsibility
    ]

    readFromClient: aStream [
	"This just parses a RFC821 message (with dots before each line)"

	<category: 'parsing'>
	^self readFrom: (RemoveDotStream on: aStream)
    ]

    scannerOn: aStream [
	"Each element should know what the underlying syntax is. For example, structured fields would mostly use MIME syntax and tokenize input streams into MIME 'tokens' while <address-spec> which is part of many standards, has to be tokenized using RFC822 syntax (using RFC822 'atoms')"

	<category: 'parsing'>
	^self class scannerOn: aStream
    ]

    printOn: aStream [
	<category: 'printing'>
	self subclassResponsibility
    ]

    storeOn: aStream [
	<category: 'printing'>
	self printOn: aStream
    ]

    initialize [
	<category: 'private-initialize'>
	
    ]

    valueFrom: aString [
	"Swazoo compatibility"

	<category: 'private-initialize'>
	^self readFrom: aString readStream
    ]
]

]



Namespace current: NetClients.MIME [

Object subclass: SimpleScanner [
    | source hereChar token tokenType saveComments currentComment classificationMask sourceTrailStream lookahead |
    
    <category: 'NetClients-MIME'>
    <comment: nil>

    SimpleScanner class [
	| classificationTable |
	
    ]

    Lf := nil.
    AlphabeticMask := nil.
    EndOfLineMask := nil.
    CRLF := nil.
    NilMask := nil.
    CRLFMask := nil.
    WhiteSpaceMask := nil.
    Cr := nil.
    DigitMask := nil.

    SimpleScanner class >> classificationTable [
	<category: 'accessing'>
	^classificationTable isNil 
	    ifTrue: [self superclass classificationTable]
	    ifFalse: [classificationTable]
    ]

    SimpleScanner class >> classificationTable: aValue [
	<category: 'accessing'>
	classificationTable := aValue
    ]

    SimpleScanner class >> cr [
	<category: 'accessing'>
	^Cr
    ]

    SimpleScanner class >> crlf [
	<category: 'accessing'>
	^CRLF
    ]

    SimpleScanner class >> lf [
	<category: 'accessing'>
	^Lf
    ]

    SimpleScanner class >> whiteSpace [
	<category: 'character classification'>
	^String with: Character space with: Character tab
    ]

    SimpleScanner class >> initClassificationTable [
	<category: 'class initialization'>
	classificationTable := WordArray new: 256.
	self initClassificationTableWith: AlphabeticMask
	    when: [:c | ($a <= c and: [c <= $z]) or: [$A <= c and: [c <= $Z]]].
	self initClassificationTableWith: DigitMask
	    when: [:c | c >= $0 and: [c <= $9]].
	self initClassificationTableWith: WhiteSpaceMask
	    when: 
		[:c | 
		"space"

		"tab"

		#(32 9) includes: c asInteger].
	self initClassificationTableWith: CRLFMask
	    when: [:c | c == Character cr or: [c == Character nl]].
	"self initClassificationTableWith: EndOfLineMask
	    when: [:c | c == Character cr]"
    ]

    SimpleScanner class >> initClassificationTableWith: mask when: aBlock [
	"Set the mask in all entries of the classificationTable for which
	 aBlock answers true."

	<category: 'class initialization'>
	0 to: classificationTable size - 1
	    do: 
		[:i | 
		(aBlock value: (Character value: i)) 
		    ifTrue: 
			[classificationTable at: i + 1
			    put: ((classificationTable at: i + 1) bitOr: mask)]]
    ]

    SimpleScanner class >> initialize [
	"SimpleScanner initialize"

	<category: 'class initialization'>
	self
	    initializeConstants;
	    initClassificationTable
    ]

    SimpleScanner class >> initializeConstants [
	<category: 'class initialization'>
	AlphabeticMask := 1.
	DigitMask := 2.
	WhiteSpaceMask := 4.
	CRLFMask := 8.
	EndOfLineMask := 16.
	NilMask := 0.
	Cr := Character cr.
	Lf := Character nl.
	CRLF := Array with: Character cr with: Character nl
    ]

    SimpleScanner class >> new [
	<category: 'instance creation'>
	^self basicNew initialize
    ]

    SimpleScanner class >> on: stream [
	<category: 'instance creation'>
	^self new on: stream
    ]

    SimpleScanner class >> defaultTokenType [
	<category: 'printing'>
	self subclassResponsibility
    ]

    SimpleScanner class >> printToken: assocOrValue on: stream [
	<category: 'printing'>
	| tokenType token |
	(assocOrValue isKindOf: Association) 
	    ifTrue: 
		[tokenType := assocOrValue key.
		token := assocOrValue value]
	    ifFalse: 
		[tokenType := self defaultTokenType.
		token := assocOrValue].
	self 
	    printToken: token
	    tokenType: tokenType
	    on: stream
    ]

    SimpleScanner class >> printToken: value tokenType: aSymbol on: stream [
	<category: 'printing'>
	self subclassResponsibility
    ]

    classificationMask [
	<category: 'accessing'>
	^classificationMask
    ]

    currentComment [
	<category: 'accessing'>
	^currentComment
    ]

    hereChar [
	<category: 'accessing'>
	^hereChar
    ]

    hereChar: char [
	<category: 'accessing'>
	hereChar := char.
	classificationMask := self classificationMaskFor: hereChar.
	lookahead := nil.
	^hereChar
    ]

    saveComments [
	<category: 'accessing'>
	^saveComments
    ]

    saveComments: aValue [
	<category: 'accessing'>
	saveComments := aValue
    ]

    token [
	<category: 'accessing'>
	^token
    ]

    tokenType [
	<category: 'accessing'>
	^tokenType
    ]

    expected: aString [
	"Notify that there is a problem at current token."

	<category: 'error handling'>
	^self notify: 'expected `%1''' % {aString}
    ]

    notify: string [
	"Subclasses may wish to override this"

	<category: 'error handling'>
	self error: string
    ]

    offEnd: aString [
	"Parser overrides this"

	<category: 'error handling'>
	^self notify: aString
    ]

    classificationMaskFor: charOrNil [
	<category: 'expression types'>
	^charOrNil isNil 
	    ifTrue: [NilMask]
	    ifFalse: [^self class classificationTable at: charOrNil asInteger + 1]
    ]

    matchCharacterType: mask [
	<category: 'expression types'>
	^self classificationMask anyMask: mask
    ]

    mustMatch: char [
	<category: 'expression types'>
	^self mustMatch: char notify: [self expected: (String with: char)]
    ]

    mustMatch: char notify: message [
	<category: 'expression types'>
	self skipWhiteSpace.
	self next == char ifFalse: [self notify: message]
    ]

    scanTokenMask: tokenMask [
	"Scan token based on character mask. Answers token's value. Stream is positioned before the character that terminated scan"

	<category: 'expression types'>
	^self scanWhile: [self matchCharacterType: tokenMask]
    ]

    scanUntil: aNiladicBlock [
	"Scan token using a block until match is found. At the end of scan the stream is positioned after the
	 matching character. Answers token value"

	<category: 'expression types'>
	| stream |
	stream := (String new: 40) writeStream.
	
	[self atEnd 
	    ifTrue: 
		[self hereChar: nil.
		^stream contents].
	self step.
	aNiladicBlock value] 
		whileFalse: [stream nextPut: hereChar].
	^stream contents
    ]

    scanWhile: aNiladicBlock [
	"Scan token using a block. At the end of scan the stream is positioned at the first character that does not match. hereChar is nil. Answers token value"

	<category: 'expression types'>
	| str |
	str := self scanUntil: [aNiladicBlock value not].
	hereChar notNil ifTrue: [self stepBack].
	^str
    ]

    step [
	<category: 'expression types'>
	^self next
    ]

    stepBack [
	<category: 'expression types'>
	lookahead isNil ifFalse: [self error: 'cannot step back twice'].
	self sourceTrailSkip: -1.
	lookahead := hereChar.
	hereChar := nil
    ]

    initialize [
	<category: 'initialize-release'>
	saveComments := true.
	self hereChar: nil
    ]

    on: inputStream [
	"Bind the input stream"

	<category: 'initialize-release'>
	self hereChar: nil.
	source := inputStream
    ]

    scan: inputStream [
	"Bind the input stream, fill the character buffers and first token buffer"

	<category: 'initialize-release'>
	self on: inputStream.
	^self nextToken
    ]

    skipWhiteSpace [
	"It is inefficient because intermediate stream is created. Perhaps refactoring scanWhile: can help"

	<category: 'multi-character scans'>
	self scanWhile: [self matchCharacterType: WhiteSpaceMask]
    ]

    printToken: assoc on: stream [
	<category: 'printing'>
	self class printToken: assoc on: stream
    ]

    printToken: value tokenType: aSymbol on: stream [
	<category: 'printing'>
	self class 
	    printToken: value
	    tokenType: aSymbol
	    on: stream
    ]

    resetToken [
	<category: 'private'>
	token := tokenType := nil
    ]

    sourceTrail [
	<category: 'source trail'>
	| res |
	sourceTrailStream notNil ifTrue: [res := sourceTrailStream contents].
	sourceTrailStream := nil.
	^res
    ]

    sourceTrailNextPut: char [
	<category: 'source trail'>
	(sourceTrailStream notNil and: [char notNil]) 
	    ifTrue: [sourceTrailStream nextPut: char]
    ]

    sourceTrailNextPutAll: string [
	<category: 'source trail'>
	(sourceTrailStream notNil and: [string notNil]) 
	    ifTrue: [sourceTrailStream nextPutAll: string]
    ]

    sourceTrailOff [
	<category: 'source trail'>
	sourceTrailStream := nil
    ]

    sourceTrailOn [
	<category: 'source trail'>
	sourceTrailStream := (String new: 64) writeStream
    ]

    sourceTrailSkip: integer [
	<category: 'source trail'>
	sourceTrailStream notNil ifTrue: [sourceTrailStream skip: integer]
    ]

    atEnd [
	<category: 'stream interface -- reading'>
	^lookahead isNil and: [source atEnd]
    ]

    contents [
	<category: 'stream interface -- reading'>
	| contents |
	contents := source contents lookahead notNil 
		    ifTrue: 
			[contents := (contents species with: lookahead) , contents.
			lookahead := nil].
	^contents
    ]

    next [
	<category: 'stream interface -- reading'>
	self hereChar: self peek.
	self sourceTrailNextPut: hereChar.
	lookahead := nil.
	^hereChar
    ]

    next: anInteger [
	"Answer the next anInteger elements of the receiver."

	<category: 'stream interface -- reading'>
	| newCollection res |
	newCollection := self species new: anInteger.
	res := self 
		    next: anInteger
		    into: newCollection
		    startingAt: 1.
	self sourceTrailNextPutAll: res.
	^res
    ]

    next: anInteger into: aSequenceableCollection startingAt: startIndex [
	"Store the next anInteger elements of the receiver into aSequenceableCollection
	 starting at startIndex in aSequenceableCollection. Answer aSequenceableCollection."

	<category: 'stream interface -- reading'>
	| index stopIndex |
	index := startIndex.
	stopIndex := index + anInteger.
	(lookahead notNil and: [anInteger > 0]) 
	    ifTrue: 
		[aSequenceableCollection at: index put: lookahead.
		index := index + 1.
		lookahead := nil].
	anInteger > 0 ifTrue: [self hereChar: nil].
	[index < stopIndex] whileTrue: 
		[aSequenceableCollection at: index put: source next.
		index := index + 1].
	^aSequenceableCollection
    ]

    nextLine [
	<category: 'stream interface -- reading'>
	| line |
	line := self scanUntil: [self matchCharacterType: CRLFMask].
	self scanWhile: [self matchCharacterType: CRLFMask].
	^line
    ]

    peek [
	"Answer what would be returned with a self next, without
	 changing position.  If the receiver is at the end, answer nil."

	<category: 'stream interface -- reading'>
	lookahead notNil ifTrue: [^lookahead].
	self atEnd ifTrue: [^nil].
	hereChar := nil.
	lookahead := source next.
	^lookahead
    ]

    peekFor: anObject [
	"Answer false and do not move the position if self next ~= anObject or if the
	 receiver is at the end. Answer true and increment position if self next = anObject."

	"This sets lookahead"

	<category: 'stream interface -- reading'>
	self peek isNil ifTrue: [^false].

	"peek for matching element"
	anObject = lookahead 
	    ifTrue: 
		[self next.
		^true].
	^false
    ]

    position [
	<category: 'stream interface -- reading'>
	^source position - (lookahead isNil ifTrue: [0] ifFalse: [1])
    ]

    position: anInt [
	<category: 'stream interface -- reading'>
	lookahead := nil.
	^source position: anInt
    ]

    skip: integer [
	<category: 'stream interface -- reading'>
	self sourceTrailSkip: integer.
	lookahead isNil 
	    ifFalse: 
		[lookahead := nil.
		source skip: integer - 1]
	    ifTrue: [source skip: integer]
    ]

    species [
	<category: 'stream interface -- reading'>
	^source species
    ]

    upTo: anObject [
	"Answer a subcollection from position to the occurrence (if any, exclusive) of anObject.
	 The stream is left positioned after anObject.
	 If anObject is not found answer everything."

	<category: 'stream interface -- reading'>
	| str |
	lookahead = anObject 
	    ifTrue: 
		[self sourceTrailNextPut: lookahead.
		lookahead := nil.
		^''].
	str := source upTo: anObject.
	lookahead isNil 
	    ifFalse: 
		[str := lookahead asString , str.
		lookahead := nil].
	self
	    sourceTrailNextPutAll: str;
	    sourceTrailNextPut: anObject.
	^str
    ]

    upToAll: pattern [
	<category: 'stream interface -- reading'>
	| str |
	lookahead isNil 
	    ifFalse: 
		[source skip: -1.
		lookahead := nil].
	str := source upToAll: pattern.
	self
	    sourceTrailNextPutAll: str;
	    sourceTrailNextPutAll: pattern.
	^str
    ]

    upToEnd [
	<category: 'stream interface -- reading'>
	| str |
	str := source upToEnd.
	lookahead isNil 
	    ifFalse: 
		[str := lookahead asString , str.
		lookahead := nil].
	self sourceTrailNextPutAll: str.
	^str
    ]

    testScanTokens [
	<category: 'sunit test helpers'>
	| s st |
	s := WriteStream on: (Array new: 16).
	st := WriteStream on: (Array new: 16).
	[tokenType = #doIt] whileFalse: 
		[s nextPut: token.
		st nextPut: tokenType.
		self nextToken].
	^Array with: s contents with: st contents
    ]

    testScanTokens: textOrString [
	"Answer with an Array which has been tokenized"

	<category: 'sunit test helpers'>
	self scan: (ReadStream on: textOrString asString).
	^self testScanTokens
    ]

    nextToken [
	<category: 'tokenization'>
	self subclassResponsibility
    ]

    nextTokenAsAssociation [
	"Read next token and and answer tokenType->token"

	<category: 'tokenization'>
	self nextToken.
	^tokenType -> token
    ]

    scanToken: aNiladicBlock delimitedBy: anArray notify: errorMessageString [
	"Scan next lexical token based on the criteria defined by NiladicBlock. The block is evaluated for every character read from input stream until it yields false. Stream is positioned before character that terminated scan"

	"Example: self scanToken: [ self scanQuotedChar; matchCharacterType: DomainTextMask ]
	 delimitedBy: '[]' notify: 'Malformed domain text'."

	<category: 'tokenization'>
	| string |
	self mustMatch: anArray first.
	string := self scanWhile: aNiladicBlock.
	self mustMatch: anArray last notify: errorMessageString.
	^string
    ]

    scanTokens: textOrString [
	"Answer with an Array which has been tokenized"

	<category: 'tokenization'>
	^self
	    on: (ReadStream on: textOrString asString);
	    tokenize
    ]

    tokenize [
	<category: 'tokenization'>
	| s |
	s := WriteStream on: (Array new: 16).
	
	[self nextToken.
	tokenType = #doIt] whileFalse: [s nextPut: token].
	^s contents
    ]

    tokenizeList: aBlock separatedBy: comparisonBlock [
	"list = token *( separator token)"

	<category: 'tokenization'>
	| stream block |
	stream := (Array new: 4) writeStream.
	block := [stream nextPut: aBlock value].
	block value.	"Evaluate for the first element"
	self tokenizeWhile: [comparisonBlock value] do: block.
	^stream contents
    ]

    tokenizeUntil: aBlock do: actionBlock [
	<category: 'tokenization'>
	
	[self skipWhiteSpace.
	self position.
	self nextToken.
	tokenType == #doIt or: aBlock] 
		whileFalse: [actionBlock value]
    ]

    tokenizeWhile: aBlock [
	<category: 'tokenization'>
	| s |
	s := WriteStream on: (Array new: 16).
	self tokenizeWhile: [aBlock value] do: [s nextPut: token].
	^s contents
    ]

    tokenizeWhile: aBlock do: actionBlock [
	<category: 'tokenization'>
	| pos |
	
	[self skipWhiteSpace.
	pos := self position.
	self nextToken.
	tokenType ~= #doIt & aBlock value	"#######"] 
		whileTrue: [actionBlock value].
	self position: pos	"Reset position to the beginning of the token that did not match"
    ]
]

]



Namespace current: NetClients.MIME [

MessageElement subclass: MimeEntity [
    | parent fields body |
    
    <category: 'NetClients-MIME'>
    <comment: nil>

    MimeEntity class >> contentLengthFieldName [
	<category: 'constants'>
	^'content-length'
    ]

    MimeEntity class >> contentTypeFieldName [
	<category: 'constants'>
	^'content-type'
    ]

    MimeEntity class >> syntaxOfMultiPartMimeBodies [
	"From RFC 2046: Media Types                  November 1996
	 
	 The Content-Type field for multipart entities requires one parameter,
	 'boundary'. The boundary delimiter line is then defined as a line
	 consisting entirely of two hyphen characters ($-, decimal value 45)
	 followed by the boundary parameter value from the Content-Type header
	 field, optional linear whitespace, and a terminating CRLF.
	 
	 WARNING TO IMPLEMENTORS:  The grammar for parameters on the Content-
	 type field is such that it is often necessary to enclose the boundary
	 parameter values in quotes on the Content-type line.  This is not
	 always necessary, but never hurts. Implementors should be sure to
	 study the grammar carefully in order to avoid producing invalid
	 Content-type fields.  Thus, a typical 'multipart' Content-Type header
	 field might look like this:
	 
	 Content-Type: multipart/mixed; boundary=gc0p4Jq0M2Yt08j34c0p
	 
	 But the following is not valid:
	 
	 Content-Type: multipart/mixed; boundary=gc0pJq0M:08jU534c0p
	 
	 (because of the colon) and must instead be represented as
	 
	 Content-Type: multipart/mixed; boundary="

	"gc0pJq0M:08jU534c0p"

	"
	 
	 This Content-Type value indicates that the content consists of one or
	 more parts, each with a structure that is syntactically identical to
	 an RFC 822 message, except that the header area is allowed to be
	 completely empty, and that the parts are each preceded by the line
	 
	 --gc0pJq0M:08jU534c0p
	 
	 The boundary delimiter MUST occur at the beginning of a line, i.e.,
	 following a CRLF, and the initial CRLF is considered to be attached
	 to the boundary delimiter line rather than part of the preceding
	 part.  The boundary may be followed by zero or more characters of
	 linear whitespace. It is then terminated by either another CRLF and
	 the header fields for the next part, or by two CRLFs, in which case
	 there are no header fields for the next part.  If no Content-Type
	 field is present it is assumed to be 'message/rfc822' in a
	 'multipart/digest' and 'text/plain' otherwise.
	 
	 NOTE:  The CRLF preceding the boundary delimiter line is conceptually
	 attached to the boundary so that it is possible to have a part that
	 does not end with a CRLF (line  break).  Body parts that must be
	 considered to end with line breaks, therefore, must have two CRLFs
	 preceding the boundary delimiter line, the first of which is part of
	 the preceding body part, and the second of which is part of the
	 encapsulation boundary."

	<category: 'documentation'>
	
    ]

    MimeEntity class >> headerTypeFor: headerName [
	<category: 'parsing'>
	^HeaderField	"For now"
    ]

    MimeEntity class >> parser [
	<category: 'parsing'>
	^self scannerType new
    ]

    MimeEntity class >> parseFieldsFrom: stream [
	<category: 'parsing'>
	^self new parseFieldsFrom: (self parser on: stream)
    ]

    MimeEntity class >> readFrom: stream [
	<category: 'parsing'>
	^self new readFrom: (self parser on: stream)
    ]

    MimeEntity class >> readFrom: stream defaultType: type [
	<category: 'parsing'>
	^(self new)
	    fieldAt: 'content-type'
		put: (ContentTypeField fromLine: 'content-type: ' , type);
	    readFrom: (self parser on: stream);
	    yourself
    ]

    MimeEntity class >> readFrom: stream type: type [
	<category: 'parsing'>
	('message/*' match: type) ifTrue: [^self readFrom: stream].
	^(self new)
	    fieldAt: 'content-type'
		put: (ContentTypeField fromLine: 'content-type: ' , type);
	    parseBodyFrom: (self parser on: stream);
	    yourself
    ]

    MimeEntity class >> scannerType [
	<category: 'parsing'>
	^MimeScanner
    ]

    bcc [
	<category: 'accessing'>
	^self fieldAt: 'bcc'
    ]

    body [
	<category: 'accessing'>
	^body
    ]

    body: aValue [
	<category: 'accessing'>
	body := aValue
    ]

    boundary [
	<category: 'accessing'>
	^self contentTypeField boundary
    ]

    cc [
	<category: 'accessing'>
	^self fieldAt: 'cc'
    ]

    charset [
	<category: 'accessing'>
	^self contentTypeField charset
    ]

    contents [
	<category: 'accessing'>
	| handler |
	handler := ContentHandler classFor: self contentType.
	^(handler on: self body readStream) contents
    ]

    contentId [
	<category: 'accessing'>
	^(self fieldAt: 'content-id' ifAbsent: [^nil]) id
    ]

    contentType [
	<category: 'accessing'>
	^self contentTypeField contentType
    ]

    contentTypeField [
	<category: 'accessing'>
	^self fieldAt: 'content-type' ifAbsent: [self defaultContentTypeField]
    ]

    fields [
	<category: 'accessing'>
	^fields
    ]

    fields: aValue [
	<category: 'accessing'>
	fields := aValue
    ]

    from [
	<category: 'accessing'>
	^self fieldAt: 'from'
    ]

    parent [
	<category: 'accessing'>
	^parent
    ]

    parent: aMimeEntity [
	<category: 'accessing'>
	parent := aMimeEntity
    ]

    recipients [
	<category: 'accessing'>
	| recipients |
	recipients := #().
	self to isNil ifFalse: [recipients := recipients , self to addresses].
	self cc isNil ifFalse: [recipients := recipients , self cc addresses].
	self bcc isNil ifFalse: [recipients := recipients , self bcc addresses].
	^recipients
    ]

    replyTo [
	<category: 'accessing'>
	^self fieldAt: 'reply-to'
    ]

    sender [
	<category: 'accessing'>
	^self fieldAt: 'sender' ifAbsent: [self fieldAt: 'from']
    ]

    subject [
	<category: 'accessing'>
	^self fieldAt: 'subject'
    ]

    subtype [
	<category: 'accessing'>
	^self contentTypeField subtype
    ]

    to [
	<category: 'accessing'>
	^self fieldAt: 'to'
    ]

    type [
	<category: 'accessing'>
	^self contentTypeField type
    ]

    addField: field [
	"This method will check if the field exists already; if yes, if it can be merged into the existing field and, if yes, merge it. Otherwise, add as a new field"

	"Implement field merge"

	<category: 'accessing fields and body parts'>
	^self fieldAt: field name put: field
    ]

    bodyPartAt: index [
	<category: 'accessing fields and body parts'>
	^self body at: index
    ]

    bodyPartNamed: id [
	<category: 'accessing fields and body parts'>
	^self isMultipart 
	    ifTrue: [self body detect: [:part | part contentId = id]]
	    ifFalse: [nil]
    ]

    fieldAt: aString [
	<category: 'accessing fields and body parts'>
	^self fieldAt: aString asLowercase ifAbsent: [nil]
    ]

    fieldAt: aString ifAbsent: aNiladicBlock [
	<category: 'accessing fields and body parts'>
	^self fields at: aString asLowercase ifAbsent: aNiladicBlock
    ]

    fieldAt: aString ifAbsentPut: aNiladicBlock [
	<category: 'accessing fields and body parts'>
	^self fields at: aString asLowercase ifAbsentPut: aNiladicBlock
    ]

    fieldAt: aString put: aHeaderField [
	<category: 'accessing fields and body parts'>
	^self fields at: aString asLowercase put: aHeaderField
    ]

    asByteArray [
	<category: 'converting'>
	
    ]

    asStream [
	<category: 'converting'>
	
    ]

    asString [
	<category: 'converting'>
	
    ]

    asStringOrByteArray [
	<category: 'converting'>
	
    ]

    defaultContentType [
	<category: 'defaults'>
	^self defaultContentTypeField contentType
    ]

    defaultContentTypeField [
	<category: 'defaults'>
	^ContentTypeField default
    ]

    initialize [
	<category: 'initialization'>
	fields := Dictionary new: 4
    ]

    defaultContentTypeForNestedEntities [
	<category: 'parsing'>
	^(self type = 'multipart' and: [self subtype = 'digest']) 
	    ifTrue: ['content-type: message/rfc822']
	    ifFalse: ['text/plain; charset=US-ASCII']
    ]

    fieldFactory [
	"Answers object that can map field name to field type (class). It may and will be subclassed"

	<category: 'parsing'>
	^HeaderField
    ]

    parseBodyFrom: rfc822Stream [
	<category: 'parsing'>
	self isMultipart 
	    ifTrue: [self parseMultipartBodyFrom: rfc822Stream]
	    ifFalse: [self parseSimpleBodyFrom: rfc822Stream]
    ]

    parseFieldFrom: stream [
	<category: 'parsing'>
	| field |
	field := self fieldFactory readFrom: stream.
	self addField: field
    ]

    parseFieldsFrom: rfc822Stream [
	<category: 'parsing'>
	[rfc822Stream atEndOfLine] 
		whileFalse: [self parseFieldFrom: rfc822Stream].
        rfc822Stream next; skipEndOfLine
    ]

    parseMultipartBodyFrom: rfc822Stream [
	"Parse multi-part body. See more in 'documentation' category on the class side"

	<category: 'parsing'>
	| boundary parts partArray |
	(boundary := self boundary) notNil 
	    ifTrue: 
		[parts := (Array new: 2) writeStream.	"Skip to the first boundary, ignore text in between"
		partArray := rfc822Stream scanToBoundary: boundary].
	
	[partArray isNil 
	    ifTrue: [^self error: 'Missing boundary in multi-part body'].
	partArray := rfc822Stream scanToBoundary: boundary.
	partArray notNil ifTrue: [parts nextPut: partArray first].
	partArray notNil and: [partArray last ~~ #last]] 
		whileTrue.
	self 
	    body: (parts contents collect: 
			[:part | 
			MimeEntity readFrom: part readStream
			    defaultType: self defaultContentTypeForNestedEntities])
    ]

    parseSimpleBodyFrom: rfc822Stream [
	<category: 'parsing'>
	| stream |
	stream := (String new: 256) writeStream.
	self parseSimpleBodyFrom: rfc822Stream onto: stream.
	self body: stream contents
    ]

    parseSimpleBodyFrom: rfc822Stream onto: stream [
	<category: 'parsing'>
	| inStream |
	inStream := RemoveDotStream on: rfc822Stream.
	[inStream atEnd] whileFalse: 
		[stream
		    nextPutAll: inStream nextLine;
		    nl]
    ]

    readFrom: rfc822Stream [
	<category: 'parsing'>
	self parseFieldsFrom: rfc822Stream.
	self parseBodyFrom: rfc822Stream
    ]

    skipSimpleBodyFrom: rfc822Stream onto: stream [
	<category: 'parsing'>
	| inStream |
	inStream := RemoveDotStream on: rfc822Stream.
	[inStream atEnd] whileFalse: [inStream nextLine]
    ]

    printBodyOn: aStream [
	<category: 'printing'>
	self body isNil ifTrue: [^self].
	self body class == Array 
	    ifFalse: 
		[aStream nextPutAll: self body.
		^self].
	aStream nextPutAll: 'This is a MIME message.

'.
	self body do: 
		[:each | 
		aStream
		    nextPutAll: '--';
		    nextPutAll: self boundary.
		each printOn: aStream].
	aStream
	    nextPutAll: '--';
	    nextPutAll: self boundary;
	    nextPutAll: '--'
    ]

    printBodyOnClient: aClient [
	<category: 'printing'>
	| out |
	out := PrependDotStream to: aClient.
	self printBodyOn: out.
	out flush
    ]

    printHeaderOn: aStream [
	<category: 'printing'>
	self fields do: 
		[:each | 
		aStream
		    print: each;
		    nl]
    ]

    printHeaderOnClient: aClient [
	<category: 'printing'>
	| out |
	out := PrependDotStream to: aClient.
	self printHeaderOn: out.
	out flush
    ]

    printMessageOn: aStream [
	<category: 'printing'>
	self printHeaderOn: aStream.
	aStream nl.
	self printBodyOn: aStream
    ]

    printMessageOnClient: aClient [
	<category: 'printing'>
	| out |
	out := PrependDotStream to: aClient.
	self printMessageOn: out.
	out flush
    ]

    printOn: aStream [
	<category: 'printing'>
	self printMessageOn: aStream
    ]

    hasBoundary [
	<category: 'testing'>
	^(self fieldAt: 'boundary') notNil
    ]

    isMultipart [
	<category: 'testing'>
	^self contentTypeField isMultipart
    ]
]

]



Namespace current: NetClients.MIME [

MessageElement subclass: NetworkEntityDescriptor [
    | alias comment |
    
    <category: 'NetClients-MIME'>
    <comment: 'I am an abstract superclass for RFC822 mailbox and group descriptors. Each of these can have an associated alias (name) and comment 

Instance Variables:
    alias    <?type?>  comment
    comment    <?type?>  comment
'>

    NetworkEntityDescriptor class >> scannerType [
	<category: 'parsing'>
	^NetworkAddressParser
    ]

    alias [
	<category: 'accessing'>
	^alias
    ]

    alias: aValue [
	<category: 'accessing'>
	alias := aValue
    ]

    comment [
	<category: 'accessing'>
	^comment
    ]

    comment: aValue [
	<category: 'accessing'>
	comment := aValue
    ]

    scannerType [
	<category: 'parsing'>
	^self class scannerType
    ]

    printAliasOn: stream [
	<category: 'priniting'>
	alias notNil ifTrue: [stream nextPutAll: alias]
    ]

    printCanonicalValueOn: stream [
	<category: 'priniting'>
	self subclassResponsibility
    ]

    printCommentOn: stream [
	<category: 'priniting'>
	comment notNil 
	    ifTrue: 
		[stream nextPut: $(.
		comment do: 
			[:char | 
			(RFC822Scanner isCommentChar: char) ifFalse: [stream nextPut: $\].
			stream nextPut: char].
		stream nextPut: $)]
    ]

    printOn: stream [
	<category: 'priniting'>
	self printCanonicalValueOn: stream.
	comment notNil ifTrue: [self printCommentOn: stream]
    ]
]

]



Namespace current: NetClients.MIME [

MessageElement subclass: HeaderField [
    | name source |
    
    <category: 'NetClients-MIME'>
    <comment: 'This is base class for all header fields. Each header field has a name and a value. Each field also has the following responsibility:
    Represent its value; being able to answer and receive a value.
    Read its value from a (positionable) stream (parsing). Field''s value is terminated by new line (subject to line folding). There is no requirement now that field''s value terminates ate the end of the stream.
    Write its contents on a stream (composition)

When reading itself from a stream, the field will store its source. When this field is written on a stream and there is source already available, this source will be written instead of parsed field''s value. The reasoning is that all standards strongly discourage making any alterations to the fields if a message is being forwarded, resent, proxied, etc. Parsing and subsequent composition can change many aspects of a field such as, replace multiple spaces with a single space, removing nonessential white spece altogether, changing the order of the values, etc. So if a source is available, it is trusted more than the parsed value for writing on a stream. This necessitates resetting source to nil when any of the field''s aspects is modified. All setters should send change notification so that it is done transparently

This class can be used to parse/compose all nonstructured fields. For unstructured fields field''s value and source are the same, so #value answers source. Specific subclasses add more specific processing for field''s value, so they override methods #value, #value:.

Message parsing: Each field is responsible for knowing its underlying grammar. This included both lexical and grammar rules. Therefore, each subclass implements methods #scannerType and #parserOn: <stream>. These answer scanner class and new instance of parser for a given source stream. Method parse: parses and sets field''s value.

A conventional way of creating new instance of a stream from source field is 
    HeaderField readFrom: stream

This reads field''s name, find an appropriate field class for this name, creates an instance of this field and lets it read/parse field''s value.

Instance Variables:
    name    <String>  comment
    source    <String>  comment
'>

    HeaderField class >> name: aname [
	"Answer new instance of field corresponding to field's name. For now, treat all fields as unstructured"

	<category: 'instance creation'>
	^((self fieldClassForName: aname) new)
	    name: aname;
	    yourself
    ]

    HeaderField class >> defaultFieldClass [
	<category: 'parsing'>
	^HeaderField
    ]

    HeaderField class >> fieldClassForName: fieldName [
	"For now we scan all subclasses. Later I plan to use registry which is somewhat more flexible, especially if different protocols can have different formats for the same field"

	<category: 'parsing'>
	| fname |
	fname := fieldName asLowercase.
	^HeaderField allSubclasses detect: 
		[:each | 
		(each fieldNames detect: [:candidate | candidate asLowercase = fname]
		    ifNone: [nil]) notNil]
	    ifNone: [self defaultFieldClass]
    ]

    HeaderField class >> fieldNames [
	<category: 'parsing'>
	^#()
    ]

    HeaderField class >> fromLine: aString [
	"For compatibility with Swazoo"

	<category: 'parsing'>
	| rfc822Stream |
	rfc822Stream := self scannerOn: aString readStream.
	^(self name: (self readFieldNameFrom: rfc822Stream))
	    readFrom: rfc822Stream;
	    yourself
    ]

    HeaderField class >> readFieldNameFrom: rfc822Stream [
	<category: 'parsing'>
	| fname |
	fname := rfc822Stream scanFieldName.
	rfc822Stream mustMatch: $: notify: 'Invalid Field (Missing colon)'.
	rfc822Stream skipWhiteSpace.
	^fname asLowercase
    ]

    HeaderField class >> readFrom: rfc822Stream [
	"Reads and parses message header contents from the message stream; answers an instance of message header. rfc822Stream is RFC822MessageParser; it extends stream interface by providing message scanning/parsing services. At this point the stream is positioned right after semicolon that delimits header name"

	<category: 'parsing'>
	^(self name: (self readFieldNameFrom: rfc822Stream)) 
	    readFrom: rfc822Stream
    ]

    HeaderField class >> scannerType [
	<category: 'parsing'>
	^MimeScanner
    ]

    canonicalFieldName [
	<category: 'accessing'>
	| s |
	s := name copy.
	s isEmpty ifTrue: [^s].
	s at: 1 put: s first asUppercase.	"Capitalize first letter"
	^s
    ]

    canonicalValue [
	"Override as necessary"

	<category: 'accessing'>
	^self value
    ]

    name [
	<category: 'accessing'>
	^name
    ]

    name: aString [
	<category: 'accessing'>
	^name := aString
    ]

    source [
	<category: 'accessing'>
	^source
    ]

    source: anObject [
	<category: 'accessing'>
	source := anObject
    ]

    value [
	<category: 'accessing'>
	^self source
    ]

    value: aValue [
	<category: 'accessing'>
	self source: aValue
    ]

    parse: rfc822Stream [
	"Generic parser for unstructured fields. Copy everything up to CRLF. Scanner handles end of line rules and answers cr when end of line is seen. Scanner also folds linear white space answering space character in place of <CRLF space+>"

	<category: 'parsing'>
	self value: rfc822Stream nextLine
    ]

    readFrom: aStream [
	<category: 'parsing'>
	self source: aStream scanText.
	^self parse: (self scannerOn: self source readStream)
    ]

    printOn: aStream [
	<category: 'printing'>
	self printOn: aStream indent: 0
    ]

    printOn: aStream indent: level [
	<category: 'printing'>
	aStream
	    tab: level;
	    nextPutAll: self canonicalFieldName;
	    nextPut: $:;
	    space.
	self printValueOn: aStream
    ]

    printStructureOn: aStream [
	"Unstructured fields just print their value on a stream"

	<category: 'printing'>
	self printValueOn: aStream
    ]

    printValueOn: aStream [
	<category: 'printing'>
	| val |
	(val := self value) notNil ifTrue: [val displayOn: aStream]
    ]

    valueFrom: aString [
	"Swazoo compatibility"

	<category: 'private-initialize'>
	^self readFrom: aString readStream
    ]
]

]



Namespace current: NetClients.MIME [

SimpleScanner subclass: MimeEncodedWordCoDec [
    
    <category: 'NetClients-MIME'>
    <comment: 'I am responsible for scanning tokens for the presence of MIME ''encoded words''. MIME uses encoded word to allow non-ascii characters to be used in message headers. Encoded words can occur inside MIME extension fields (ones starting with X-) as well as in field bodies. An encoded word may occur everywhere in the body in place of text'', ''word'', ''comment'' or ''phrase'' token. Encoded word specifies charset, encoding mechanism and encoded text itself'>

    MimeEncodedWordCoDec class >> decode: word [
	<category: 'parsing'>
	^self decode: word using: (self encodingParametersOf: word)
    ]

    MimeEncodedWordCoDec class >> decode: word using: arr [
	<category: 'parsing'>
	^arr notNil 
	    ifTrue: 
		[self 
		    decodeEncodedWord: (arr at: 3)
		    charset: arr first
		    encoding: (arr at: 2)]
	    ifFalse: [word]
    ]

    MimeEncodedWordCoDec class >> decodeComment: commentString [
	<category: 'parsing'>
	^self new decodeComment: commentString
    ]

    MimeEncodedWordCoDec class >> decodePhrase: words [
	"decode phrase word by word; concatenate decoded words and answer concatenated string"

	<category: 'parsing'>
	| output |
	output := (String new: words size) writeStream.
	self decodePhrase: words printOn: output.
	^output contents
    ]

    MimeEncodedWordCoDec class >> decodePhrase: words printOn: stream [
	<category: 'parsing'>
	| params lastParams lastWord |
	lastWord := nil.
	words do: 
		[:word | 
		lastParams := params.
		params := self encodingParametersOf: word.
		(lastWord notNil and: [params isNil or: [lastParams isNil]]) 
		    ifTrue: [stream space].
		stream nextPutAll: (lastWord := self decode: word using: params)]
    ]

    MimeEncodedWordCoDec class >> decodeText: text [
	<category: 'parsing'>
	^self new decodeText: text
    ]

    MimeEncodedWordCoDec class >> encodingParametersOf: word [
	<category: 'parsing'>
	| mark1 mark2 |
	^(word first == $= and: 
		[word last == $= and: 
			[(word at: 2) == $? and: 
				[(word at: word size - 1) == $? and: 
					[(mark1 := word 
						    nextIndexOf: $?
						    from: 3
						    to: word size - 2) > 0 
					    and: 
						[(mark2 := word 
							    nextIndexOf: $?
							    from: mark1 + 1
							    to: word size - 2) > (mark1 + 1)]]]]]) 
	    ifTrue: 
		[Array 
		    with: (word copyFrom: 3 to: mark1 - 1) asLowercase
		    with: (word copyFrom: mark1 + 1 to: mark2 - 1) asLowercase
		    with: (word copyFrom: mark2 + 1 to: word size - 2)]
	    ifFalse: [nil]
    ]

    MimeEncodedWordCoDec class >> decodeEncodedWord: contents charset: charset encoding: encodingString [
	<category: 'text processing'>
	| encoding |
	encoding := encodingString asLowercase.
	(#('b' 'base64') includes: encoding) 
	    ifTrue: 
		[^MimeScanner 
		    decodeBase64From: 1
		    to: contents size
		    in: contents].
	(#('q' 'quoted-printable') includes: encoding) 
	    ifTrue: 
		[^self 
		    decodeQuotedPrintableFrom: 1
		    to: contents size
		    in: contents].
	(#('uue' 'uuencode' 'x-uue' 'x-uuencode') includes: encoding) 
	    ifTrue: 
		[^self 
		    decodeUUEncodedFrom: 1
		    to: contents size
		    in: contents].
	^nil	"Failed to decode"
    ]

    MimeEncodedWordCoDec class >> decodeQuotedPrintableFrom: startIndex to: endIndex in: aString [
	"Decode aString from startIndex to endIndex in quoted-printable."

	<category: 'text processing'>
	| input output char n1 n2 |
	input := ReadStream 
		    on: aString
		    from: startIndex
		    to: endIndex.
	output := (String new: endIndex - startIndex) writeStream.
	[input atEnd] whileFalse: 
		[char := input next.
		$= == char 
		    ifTrue: 
			[('0123456789ABCDEF' includes: (n1 := input next)) 
			    ifTrue: 
				[n2 := input next.
				output nextPut: ((n1 digitValue bitShift: 4) + n2 digitValue) asCharacter]]
		    ifFalse: [output nextPut: char]].
	^output contents
    ]

    MimeEncodedWordCoDec class >> decodeUUEncodedFrom: startIndex to: farEndIndex in: aString [
	"decode aString from startIndex to farEndIndex as uuencode-encoded"

	<category: 'text processing'>
	| endIndex i nl space output data |
	endIndex := farEndIndex - 2.
	
	[endIndex <= startIndex or: 
		[(aString at: endIndex + 1) = $e 
		    and: [(aString at: endIndex + 2) = $n and: [(aString at: endIndex + 3) = $d]]]] 
		whileFalse: [endIndex := endIndex - 1].
	i := (aString 
		    findString: 'begin'
		    startingAt: startIndex
		    ignoreCase: true
		    useWildcards: false) first.
	i = 0 ifTrue: [i := startIndex].
	nl := Character nl.
	space := Character space asInteger.
	output := (data := String new: (endIndex - startIndex) * 3 // 4) 
		    writeStream.
	
	[[i < endIndex and: [(aString at: i) ~= nl]] whileTrue: [i := i + 1].
	i < endIndex] 
		whileTrue: 
		    [| count |
		    count := (aString at: (i := i + 1)) asInteger - space bitAnd: 63.
		    i := i + 1.
		    count = 0 
			ifTrue: [i := endIndex]
			ifFalse: 
			    [[count > 0] whileTrue: 
				    [| m n o p |
				    m := (aString at: i) asInteger - space bitAnd: 63.
				    n := (aString at: i + 1) asInteger - space bitAnd: 63.
				    o := (aString at: i + 2) asInteger - space bitAnd: 63.
				    p := (aString at: i + 3) asInteger - space bitAnd: 63.
				    count >= 1 
					ifTrue: 
					    [output nextPut: (Character value: (m bitShift: 2) + (n bitShift: -4)).
					    count >= 2 
						ifTrue: 
						    [output 
							nextPut: (Character value: ((n bitShift: 4) + (o bitShift: -2) bitAnd: 255)).
						    count >= 3 
							ifTrue: [output nextPut: (Character value: ((o bitShift: 6) + p bitAnd: 255))]]].
				    i := i + 4.
				    count := count - 3]]].
	^data copyFrom: 1 to: output position
    ]

    decode: word [
	<category: 'parsing'>
	^self class decode: word
    ]

    decodeComment: text [
	<category: 'parsing'>
	"First, quick check if we possibly have an encoded word"

	| output word params spaces lastParams lastWord |
	(text indexOfSubCollection: '=?' startingAt: 1) = 0 ifTrue: [^text].	"We suspect there might be an encoded word inside, do the legwork"
	self on: text readStream.
	output := (String new: text size) writeStream.
	spaces := String new.
	params := lastWord := nil.
	
	[lastParams := params.
	self atEnd] whileFalse: 
		    [word := self scanWhile: [(self matchCharacterType: WhiteSpaceMask) not].
		    params := self class encodingParametersOf: word.
		    (lastWord notNil and: [params isNil or: [lastParams isNil]]) 
			ifTrue: [output nextPutAll: spaces].
		    output nextPutAll: (lastWord := self class decode: word using: params).
		    spaces := self scanWhile: [self matchCharacterType: WhiteSpaceMask]].
	^output contents
    ]

    decodePhrase: words [
	<category: 'parsing'>
	^self class decodePhrase: words
    ]

    decodeText: text [
	"Decoding of text is similar to decoding of comment, but RFC2047 requires that an encoded word that appears in in *text token MUST be separated from any adjacent encoded word or text by a linear-white-space"

	<category: 'parsing'>
	"First, quick check if we possibly have an encoded word"

	| output word |
	(text indexOfSubCollection: '=?' startingAt: 1) = 0 ifTrue: [^text].	"We suspect there might be an encoded word inside, do the legwork"
	self on: text readStream.
	output := (String new: text size) writeStream.
	[self atEnd] whileFalse: 
		[word := self scanWhile: [(self matchCharacterType: WhiteSpaceMask) not].
		output
		    nextPutAll: (self decode: word);
		    nextPutAll: (self scanWhile: [self matchCharacterType: WhiteSpaceMask])].
	^output contents
    ]

    encodingParametersOf: word [
	<category: 'parsing'>
	^self class encodingParametersOf: word
    ]
]

]



Namespace current: NetClients.MIME [

SimpleScanner subclass: MailScanner [
    
    <category: 'NetClients-MIME'>
    <comment: nil>

    MailScanner class >> printQuotedText: str on: stream [
	"Print word as either atom or quoted text"

	<category: 'printing'>
	(self shouldBeQuoted: str) 
	    ifTrue: 
		[stream
		    nextPut: $";
		    nextPutAll: str;
		    nextPut: $"]
	    ifFalse: [stream nextPutAll: str]
    ]

    MailScanner class >> printTokenList: list on: stream [
	<category: 'printing'>
	self 
	    printTokenList: list
	    on: stream
	    separatedBy: [stream space]
    ]

    MailScanner class >> printTokenList: list on: stream separatedBy: aBlock [
	<category: 'printing'>
	list do: [:assoc | self printToken: assoc on: stream] separatedBy: aBlock
    ]

    printAtom: atom on: stream [
	<category: 'printing'>
	self class printAtom: atom on: stream
    ]

    printQuotedText: qtext on: stream [
	<category: 'printing'>
	self class printQuotedText: qtext on: stream
    ]

    printText: qtext on: stream [
	<category: 'printing'>
	self class printText: qtext on: stream
    ]
]

]



Namespace current: NetClients.MIME [

NetworkEntityDescriptor subclass: NetworkAddressDescriptor [
    | domain localPart route |
    
    <category: 'NetClients-MIME'>
    <comment: nil>

    NetworkAddressDescriptor class >> readFrom: aString [
	<category: 'instance creation'>
	^self parser parse: aString
    ]

    NetworkAddressDescriptor class >> scannerType [
	<category: 'parsing'>
	^NetworkAddressParser
    ]

    NetworkAddressDescriptor class >> addressesFrom: stream [
	"self addressesFrom: 'kyasu@crl.fujixerox.co.jp' readStream."

	"self addressesFrom: 'Kazuki Yasumatsu <kyasu@crl.fujixerox.co.jp>' readStream."

	"self addressesFrom: 'kyasu@crl.fujixerox.co.jp (Kazuki Yasumatsu)' readStream."

	"self addressesFrom: ' kyasu1, kyasu2, Kazuki Yasumatsu <kyasu3>, kyasu4 (Kazuki Yasumatsu)' readStream."

	"self addressesFrom: ' foo bar, kyasu1, ,  Kazuki Yasumatsu <kyasu2> <kyasu3> (<foo> (foo bar), bar)' readStream."

	<category: 'utility'>
	^self scannerType addressesFrom: stream
    ]

    NetworkAddressDescriptor class >> addressFrom: aString [
	"self addressesFrom: 'kyasu@crl.fujixerox.co.jp'."

	"self addressesFrom: 'Kazuki Yasumatsu <kyasu@crl.fujixerox.co.jp>'."

	"self addressesFrom: 'kyasu@crl.fujixerox.co.jp (Kazuki Yasumatsu)'."

	"self addressesFrom: ' kyasu1, kyasu2, Kazuki Yasumatsu <kyasu3>, kyasu4 (Kazuki Yasumatsu)'."

	"self addressesFrom: ' foo bar, kyasu1, ,  Kazuki Yasumatsu <kyasu2> <kyasu3> (<foo> (foo bar), bar)'."

	<category: 'utility'>
	^self scannerType addressFrom: aString
    ]

    addressSpecString [
	<category: 'accessing'>
	^self printStringSelector: #printAddressSpecOn:
    ]

    aliasString [
	<category: 'accessing'>
	^self printStringSelector: #printAliasOn:
    ]

    commentString [
	<category: 'accessing'>
	^self printStringSelector: #printCommentOn:
    ]

    domain [
	<category: 'accessing'>
	^domain
    ]

    domain: aValue [
	<category: 'accessing'>
	domain := aValue
    ]

    domainString [
	<category: 'accessing'>
	^self printStringSelector: #printDomainOn:
    ]

    localPart [
	<category: 'accessing'>
	^localPart
    ]

    localPart: aValue [
	<category: 'accessing'>
	localPart := aValue
    ]

    localPartString [
	<category: 'accessing'>
	^self printStringSelector: #printLocalPartOn:
    ]

    route [
	<category: 'accessing'>
	^route
    ]

    route: aValue [
	<category: 'accessing'>
	route := aValue
    ]

    routeString [
	<category: 'accessing'>
	^self printStringSelector: #printRouteOn:
    ]

    initialize [
	<category: 'initialization'>
	localPart := Array new
    ]

    printAddressSpecOn: stream [
	<category: 'printing'>
	self hasAddressSpec 
	    ifTrue: 
		[self printLocalPartOn: stream.
		stream nextPut: $@.
		self printDomainOn: stream]
    ]

    printCanonicalValueOn: stream [
	<category: 'printing'>
	alias notNil 
	    ifTrue: [self printRouteAddressOn: stream]
	    ifFalse: [self printAddressSpecOn: stream]
    ]

    printDomainOn: stream [
	<category: 'printing'>
	self scannerType printDomain: domain on: stream
    ]

    printLocalPartOn: stream [
	<category: 'printing'>
	localPart do: [:token | self scannerType printWord: token on: stream]
	    separatedBy: [stream nextPut: $.]
    ]

    printRouteAddressOn: stream [
	<category: 'printing'>
	self printAliasOn: stream.
	(route notNil or: [self hasAddressSpec]) 
	    ifTrue: 
		[stream nextPut: $<.
		self
		    printRouteOn: stream;
		    printAddressSpecOn: stream.
		stream nextPut: $>]
    ]

    printRouteOn: stream [
	<category: 'printing'>
	(route notNil and: [route notEmpty]) 
	    ifTrue: 
		[route do: 
			[:domainx | 
			stream
			    space;
			    nextPut: $@.
			self scannerType printDomain: domainx on: stream.
			stream nextPut: $:].
		stream space]
    ]

    printStringSelector: sel [
	<category: 'private'>
	| stream |
	stream := (String new: 40) writeStream.
	self perform: sel with: stream.
	^stream contents
    ]

    hasAddressSpec [
	<category: 'testing'>
	^localPart notNil 
	    and: [localPart isEmpty not and: [domain notNil and: [domain isEmpty not]]]
    ]
]

]



Namespace current: NetClients.MIME [

HeaderField subclass: StructuredHeaderField [
    | parameters |
    
    <category: 'NetClients-MIME'>
    <comment: 'I am used as a base for all structured fields as defined by RFC822, MIME and HTTP. Structured fields consist of words rather than text. Therefore, structured fields can be tokenized using lexical scanner.
I am designed to be compatible with Swazoo. Swazoo uses this class to store parameters, so I provide both storage and compatible methods to parse parameters. Parameters are modifiers for the primary value for a field. Syntax of parameters is as follows:
    parameters = *( <;> <key> <=> <value>)

In the future we may reconsiders if providing parameter storage here is a good idea because it seems that only a few field types can have parameters

Instance Variables:
    parameters    <Dictionary>  Contains parsed parameter values as associations
'>

    canonicalValue [
	"Canonical value removes all white space and comments from the source"

	<category: 'accessing'>
	^self tokenizedValueFrom: (self scannerOn: self source readStream)
    ]

    parameterAt: aString [
	<category: 'accessing'>
	^self parameterAt: aString ifAbsent: [nil]
    ]

    parameterAt: aString ifAbsent: aBlock [
	<category: 'accessing'>
	^parameters at: aString ifAbsent: aBlock
    ]

    parameterAt: aString ifAbsentPut: aBlock [
	<category: 'accessing'>
	^self parameters at: aString ifAbsentPut: aBlock
    ]

    parameterAt: aString put: aBlock [
	<category: 'accessing'>
	^self parameters at: aString put: aBlock
    ]

    parameters [
	<category: 'accessing'>
	^parameters
    ]

    parameters: aCollection [
	<category: 'accessing'>
	parameters := aCollection
    ]

    parametersDo: aMonadicBlock [
	"aBlock is a one-argument block which will be evaluated for each parameter. Argument is an
	 association (parameter name, parameter value)"

	<category: 'accessing'>
	^self parameters 
	    keysAndValuesDo: [:nm :val | aMonadicBlock value: nm -> val]
    ]

    printParameter: assoc on: aStream [
	<category: 'printing'>
	aStream
	    nextPut: $;;
	    nextPutAll: assoc key;
	    nextPut: $=;
	    nextPutAll: assoc value
    ]

    printParametersOn: aStream [
	<category: 'printing'>
	self parametersDo: [:assoc | self printParameter: assoc on: aStream]
    ]

    printStructureOn: aStream [
	"Default implementation is the same as inherited. Subclasses can override it"

	<category: 'printing'>
	super printValueOn: aStream
    ]

    printValueOn: aStream [
	"The reasoning here is that if an instance was created by parsing input stream, it should be reconstructed verbatim rather than restored by us. We may alter the original in some ways and sometimes it may be undesirable"

	<category: 'printing'>
	self value notNil 
	    ifTrue: [super printValueOn: aStream]
	    ifFalse: [self printStructureOn: aStream]
    ]

    initialize [
	<category: 'private-initialize'>
	super initialize.
	parameters := Dictionary new
    ]

    readParametersFrom: rs [
	<category: 'private-utility'>
	| paramName paramValue |
	
	[rs
	    skipWhiteSpace;
	    atEnd] whileFalse: 
		    [rs mustMatch: $; notify: 'Invalid parameter'.
		    paramName := rs nextToken.
		    rs mustMatch: $= notify: 'Invalid parameter'.
		    paramValue := rs nextToken.
		    parameters at: paramName put: paramValue]
    ]

    tokenize: rfc822Stream [
	"Scan field value token by token. Answer an array of tokens"

	<category: 'private-utility'>
	| result token |
	result := (Array new: 2) writeStream.
	
	[rfc822Stream atEnd or: 
		[rfc822Stream peek == Character nl 
		    or: [(token := rfc822Stream nextToken) isNil]]] 
		whileFalse: [result nextPut: token].
	^result contents
    ]

    tokenizedValueFrom: rfc822Stream [
	"Scan field value token by token. Answer a string that is a concatenation of all elements in the array. One can view this as a canonicalized field value because this operation eliminates all white space and comments"

	<category: 'private-utility'>
	| result tokens |
	result := (String new: 20) writeStream.
	tokens := self tokenize: rfc822Stream.
	tokens do: 
		[:token | 
		token isString 
		    ifTrue: [result nextPutAll: token]
		    ifFalse: [result nextPut: token]].
	^result contents
    ]
]

]



Namespace current: NetClients.MIME [

NetworkEntityDescriptor subclass: MailGroupDescriptor [
    | addresses |
    
    <category: 'NetClients-MIME'>
    <comment: nil>

    addresses [
	<category: 'accessing'>
	^addresses
    ]

    addresses: anArray [
	<category: 'accessing'>
	addresses := anArray
    ]

    alias [
	<category: 'accessing'>
	^alias
    ]

    alias: aString [
	<category: 'accessing'>
	alias := aString
    ]

    initialize [
	<category: 'initialization'>
	addresses := Array new
    ]

    printCanonicalValueOn: stream [
	<category: 'printing'>
	self printAliasOn: stream.
	stream nextPut: $:.
	self addresses do: [:address | address printOn: stream]
	    separatedBy: [stream nextPut: $,].
	stream nextPut: $;
    ]
]

]



Namespace current: NetClients.MIME [

MailScanner subclass: RFC822Scanner [
    
    <category: 'NetClients-MIME'>
    <comment: nil>

    HeaderNameMask := nil.
    QuotedPairChar := nil.
    QuotedPairMask := nil.
    AtomMask := nil.
    QuotedTextMask := nil.
    CommentMask := nil.
    SimpleTimeZones := nil.
    DomainTextMask := nil.
    TextMask := nil.
    HeaderNameDelimiterChar := nil.
    TokenMask := nil.

    RFC822Scanner class >> specials [
	"Note that definition of this set varies from standard to standard, so this method needs to be overridden for specialized parsers"

	<category: 'character classification'>
	^'()<>@,;:\".[]'
    ]

    RFC822Scanner class >> tspecials [
	"tspecials in MIME and HTTP. It is derived from RCC822 specials with addition of </>, <?>, <=> and removal of <.>"

	<category: 'character classification'>
	^'()<>@,;:\"/[]?='
    ]

    RFC822Scanner class >> initClassificationTable [
	<category: 'class initialization'>
	super initClassificationTable.
	self initClassificationTableWith: HeaderNameMask
	    when: [:c | c > Character space and: [c ~~ $:]].
	self initClassificationTableWith: TextMask
	    when: [:c | c ~~ Character cr and: [c ~~ Character nl]].
	self initClassificationTableWith: AtomMask
	    when: [:c | c > Character space and: [(self specials includes: c) not]].
	self initClassificationTableWith: TokenMask
	    when: [:c | c > Character space and: [(self tspecials includes: c) not]].
	self initClassificationTableWith: QuotedTextMask
	    when: 
		[:c | 
		c ~~ $" and: [c ~~ $\ and: [c ~~ Character cr and: [c ~~ Character nl]]]].
	self initClassificationTableWith: DomainTextMask
	    when: 
		[:c | 
		('[]\' includes: c) not and: [c ~~ Character cr and: [c ~~ Character nl]]].
	self initClassificationTableWith: CommentMask
	    when: 
		[:c | 
		c ~~ $( and: 
			[c ~~ $) and: [c ~~ $\ and: [c ~~ Character cr and: [c ~~ Character nl]]]]]
    ]

    RFC822Scanner class >> initialize [
	"RFC822Scanner initialize"

	<category: 'class initialization'>
	self
	    initializeConstants;
	    initClassificationTable
    ]

    RFC822Scanner class >> initializeConstants [
	<category: 'class initialization'>
	AtomMask := 256.
	CommentMask := 512.
	DomainTextMask := 1024.
	HeaderNameMask := 2048.
	QuotedTextMask := 4096.
	TextMask := 8192.
	TokenMask := 16384.
	QuotedPairMask := (QuotedTextMask bitOr: CommentMask) 
		    bitOr: DomainTextMask.
	QuotedPairChar := $\.
	HeaderNameDelimiterChar := $:
    ]

    RFC822Scanner class >> dateAndTimeFrom: aString [
	"RFC822Scanner dateAndTimeFrom: '6 Dec 88 10:16:08 +0900 (Tuesday)'."

	"RFC822Scanner dateAndTimeFrom: '12 Dec 88 10:16:08 +0900 (Tuesday)'."

	"RFC822Scanner dateAndTimeFrom: 'Fri, 31 Mar 89 09:13:20 +0900'."

	"RFC822Scanner dateAndTimeFrom: 'Tue, 18 Apr 89 23:29:47 +0900'."

	"RFC822Scanner dateAndTimeFrom: 'Tue, 23 May 89 13:52:12 JST'."

	"RFC822Scanner dateAndTimeFrom: 'Thu, 1 Dec 88 17:13:27 jst'."

	"RFC822Scanner dateAndTimeFrom: 'Sat, 15 Jul 95 14:36:22 0900'."

	"RFC822Scanner dateAndTimeFrom: '2-Nov-86 10:43:42 PST'."

	"RFC822Scanner dateAndTimeFrom: 'Friday, 21-Jul-95 04:04:55 GMT'."

	"RFC822Scanner dateAndTimeFrom: 'Jul 10 11:06:40 1995'."

	"RFC822Scanner dateAndTimeFrom: 'Jul 10 11:06:40 JST 1995'."

	"RFC822Scanner dateAndTimeFrom: 'Mon Jul 10 11:06:40 1995'."

	"RFC822Scanner dateAndTimeFrom: 'Mon Jul 10 11:06:40 JST 1995'."

	"RFC822Scanner dateAndTimeFrom: '(6 December 1988 10:16:08 am )'."

	"RFC822Scanner dateAndTimeFrom: '(12 December 1988 10:16:08 am )'."

	"RFC822Scanner dateAndTimeFrom: ''."

	<category: 'from Network Clients'>
	| rfcString |
	aString size <= 10 
	    ifTrue: 
		["may be illegal format"

		^DateTime utcDateAndTimeNow].
	rfcString := self normalizeDateAndTimeString: aString.
	^self readRFC822DateAndTimeFrom: rfcString readStream
    ]

    RFC822Scanner class >> defaultTimeZoneDifference [
	<category: 'from Network Clients'>
	^DateTime now offset seconds
    ]

    RFC822Scanner class >> initializeTimeZones [
	"RFC822Scanner initializeTimeZones."

	"Install TimeZone constants."

	<category: 'from Network Clients'>
	SimpleTimeZones := Dictionary new.

	"Universal Time"
	SimpleTimeZones at: 'UT' put: 0.
	SimpleTimeZones at: 'GMT' put: 0.

	"For North America."
	SimpleTimeZones at: 'EST' put: -5.
	SimpleTimeZones at: 'EDT' put: -4.
	SimpleTimeZones at: 'CST' put: -6.
	SimpleTimeZones at: 'CDT' put: -5.
	SimpleTimeZones at: 'MST' put: -7.
	SimpleTimeZones at: 'MDT' put: -6.
	SimpleTimeZones at: 'PST' put: -8.
	SimpleTimeZones at: 'PDT' put: -7.

	"For Europe."
	SimpleTimeZones at: 'BST' put: 0.
	SimpleTimeZones at: 'WET' put: 0.
	SimpleTimeZones at: 'MET' put: 1.
	SimpleTimeZones at: 'EET' put: 2.

	"For Japan."
	SimpleTimeZones at: 'JST' put: 9
    ]

    RFC822Scanner class >> normalizeDateAndTimeString: aString [
	"RFC822 formats"

	"RFC822Scanner normalizeDateAndTimeString: '6 Dec 88 10:16:08 +0900 (Tuesday)'."

	"RFC822Scanner normalizeDateAndTimeString: 'Tue, 18 Apr 89 23:29:47 +0900'."

	"RFC822Scanner normalizeDateAndTimeString: 'Tue, 18 Apr 89 23:29:47 0900'."

	"RFC822Scanner normalizeDateAndTimeString: 'Tue, 23 May 89 13:52:12 JST'."

	"RFC822Scanner normalizeDateAndTimeString: '2-Nov-86 10:43:42 PST'."

	"Other formats"

	"RFC822Scanner normalizeDateAndTimeString: 'Jul 10 11:06:40 1995'."

	"RFC822Scanner normalizeDateAndTimeString: 'Jul 10 11:06:40 JST 1995'."

	"RFC822Scanner normalizeDateAndTimeString: 'Mon Jul 10 11:06:40 1995'."

	"RFC822Scanner normalizeDateAndTimeString: 'Mon Jul 10 11:06:40 JST 1995'."

	<category: 'from Network Clients'>
	| head tail read str1 str2 write |
	aString size < 6 ifTrue: [^aString].
	head := aString copyFrom: 1 to: aString size - 5.
	(head indexOf: $,) > 0 ifTrue: [^aString].
	tail := aString copyFrom: aString size - 4 to: aString size.
	read := tail readStream.
	(read next = Character space and: 
		[read next isDigit 
		    and: [read next isDigit and: [read next isDigit and: [read next isDigit]]]]) 
	    ifFalse: [^aString].
	read := head readStream.
	str1 := read upTo: Character space.
	str2 := read upTo: Character space.
	(str1 isEmpty or: [str2 isEmpty]) ifTrue: [^aString].
	str2 first isDigit 
	    ifFalse: 
		[str1 := str2.
		str2 := read upTo: Character space.
		(str2 isEmpty or: [str2 first isDigit not]) ifTrue: [^aString]].
	read atEnd ifTrue: [^aString].
	write := WriteStream on: (String new: 32).
	write
	    nextPutAll: str2;
	    nextPutAll: str1;
	    nextPutAll: (tail copyFrom: 4 to: 5);
	    space;
	    nextPutAll: read.
	^write contents
    ]

    RFC822Scanner class >> readDateFrom: aStream [
	"date    =  1*2DIGIT month 2DIGIT
	 month    =  'Jan'  /  'Feb' /  'Mar'  /  'Apr'
	 /  'May'  /  'Jun' /  'Jul'  /  'Aug'
	 /  'Sep'  /  'Oct' /  'Nov'  /  'Dec'"

	"RFC822Scanner readDateFrom: '01 Jan 95' readStream."

	"RFC822Scanner readDateFrom: '1 Jan 95' readStream."

	"RFC822Scanner readDateFrom: '23 Jan 95' readStream."

	"RFC822Scanner readDateFrom: '23-Jan-95' readStream."

	"RFC822Scanner readDateFrom: 'Jan 23 95' readStream."

	"RFC822Scanner readDateFrom: 'Jan 23 1995' readStream."

	<category: 'from Network Clients'>
	^Date readFrom: aStream
    ]

    RFC822Scanner class >> readRFC822DateAndTimeFrom: aStream [
	"date-time    =  [ day ',' ] date time
	 day            =  'Mon'  / 'Tue' /  'Wed'  / 'Thu'
	 /  'Fri'  / 'Sat' /  'Sun'"

	"RFC822Scanner readRFC822DateAndTimeFrom: '6 Dec 88 10:16:08 +0900 (Tuesday)' readStream."

	"RFC822Scanner readRFC822DateAndTimeFrom: '12 Dec 88 10:16:08 +0900 (Tuesday)' readStream."

	"RFC822Scanner readRFC822DateAndTimeFrom: 'Fri, 31 Mar 89 09:13:20 +0900' readStream."

	"RFC822Scanner readRFC822DateAndTimeFrom: 'Tue, 18 Apr 89 23:29:47 +0900' readStream."

	"RFC822Scanner readRFC822DateAndTimeFrom: 'Tue, 23 May 89 13:52:12 JST' readStream."

	"RFC822Scanner readRFC822DateAndTimeFrom: 'Thu, 1 Dec 88 17:13:27 jst' readStream."

	"RFC822Scanner readRFC822DateAndTimeFrom: '2-Nov-86 10:43:42 PST' readStream."

	"RFC822Scanner readRFC822DateAndTimeFrom: '(6 December 1988 10:16:08 am )' readStream."

	"RFC822Scanner readRFC822DateAndTimeFrom: '(12 December 1988 10:16:08 am )' readStream."

	<category: 'from Network Clients'>
	| char date time |
	[aStream atEnd or: 
		[char := aStream peek.
		char isDigit]] 
	    whileFalse: [aStream next].
	aStream atEnd ifTrue: [^DateTime utcDateAndTimeNow].
	date := self readDateFrom: aStream.
	aStream skipSeparators.
	time := self readTimeFrom: aStream.
	^Array with: date with: time
    ]

    RFC822Scanner class >> readTimeFrom: aStream [
	"time    =  hour zone
	 hour    =  2DIGIT ':' 2DIGIT [':' 2DIGIT]
	 zone    =  'UT'  / 'GMT'
	 /  'EST' / 'EDT'
	 /  'CST' / 'CDT'
	 /  'MST' / 'MDT'
	 /  'PST' / 'PDT'
	 /  1ALPHA
	 / ( ('+' / '-') 4DIGIT )"

	"RFC822Scanner readTimeFrom: '12:16:08 GMT' readStream."

	"RFC822Scanner readTimeFrom: '12:16:08 XXX' readStream."

	"RFC822Scanner readTimeFrom: '07:16:08 EST' readStream."

	"RFC822Scanner readTimeFrom: '07:16:08 -0500' readStream."

	"RFC822Scanner readTimeFrom: '21:16:08 JST' readStream."

	"RFC822Scanner readTimeFrom: '21:16:08 jst' readStream."

	"RFC822Scanner readTimeFrom: '21:16:08 +0900' readStream."

	"RFC822Scanner readTimeFrom: '21:16:08 0900' readStream."

	"RFC822Scanner readTimeFrom: '12:16:08 pm' readStream."

	"Smalltalk time"

	"RFC822Scanner readTimeFrom: '12:16' readStream."

	"No timezone"

	"RFC822Scanner readTimeFrom: '12:16:08' readStream."

	"No timezone"

	<category: 'from Network Clients'>
	| hour minute second write char timezone |
	hour := Integer readFrom: aStream.
	minute := 0.
	second := 0.
	(aStream peekFor: $:) 
	    ifTrue: 
		[minute := Integer readFrom: aStream.
		(aStream peekFor: $:) ifTrue: [second := Integer readFrom: aStream]].
	aStream skipSeparators.
	write := WriteStream on: (String new: 8).
	[aStream atEnd or: 
		[char := aStream next.
		char isSeparator]] 
	    whileFalse: [write nextPut: char].
	timezone := write contents asUppercase.
	(SimpleTimeZones at: timezone ifAbsent: [nil]) notNil 
	    ifTrue: [hour := hour - (SimpleTimeZones at: timezone)]
	    ifFalse: 
		[('+####' match: timezone) 
		    ifTrue: 
			[hour := hour - (timezone copyFrom: 2 to: 3) asNumber.
			minute := minute - (timezone copyFrom: 4 to: 5) asNumber]
		    ifFalse: 
			[('-####' match: timezone) 
			    ifTrue: 
				[hour := hour + (timezone copyFrom: 2 to: 3) asNumber.
				minute := minute + (timezone copyFrom: 4 to: 5) asNumber]
			    ifFalse: 
				['AM' = timezone 
				    ifTrue: 
					["Smalltalk time"

					hour = 12 ifTrue: [hour := 0]]
				    ifFalse: 
					['PM' = timezone 
					    ifTrue: 
						["Smalltalk time"

						hour = 12 ifTrue: [hour := 0].
						hour := hour + 12]
					    ifFalse: 
						["Using default time zone"

						hour := hour - (self defaultTimeZoneDifference // 3600)]]]]].
	^Time fromSeconds: 60 * (60 * hour + minute) + second
    ]

    RFC822Scanner class >> defaultTokenType [
	<category: 'printing'>
	^#word
    ]

    RFC822Scanner class >> nextPutComment: comment on: stream [
	<category: 'printing'>
	comment notNil 
	    ifTrue: 
		[stream nextPut: $(.
		comment do: 
			[:char | 
			(self isCommentChar: char) ifFalse: [stream nextPut: $\].
			stream nextPut: char].
		stream nextPut: $)]
    ]

    RFC822Scanner class >> printDomain: domainx on: stream [
	"Domainx is an array of domain segments"

	<category: 'printing'>
	domainx notNil 
	    ifTrue: 
		[domainx do: [:word | self printWord: word on: stream]
		    separatedBy: [stream nextPut: $.]]
    ]

    RFC822Scanner class >> printPhrase: phrase on: stream [
	<category: 'printing'>
	phrase do: [:word | stream nextPutAll: word] separatedBy: [stream space]
    ]

    RFC822Scanner class >> printWord: str on: stream [
	"Print word as either atom or quoted text"

	<category: 'printing'>
	(self shouldBeQuoted: str) 
	    ifTrue: 
		[stream
		    nextPut: $";
		    nextPutAll: str;
		    nextPut: $"]
	    ifFalse: [stream nextPutAll: str]
    ]

    RFC822Scanner class >> isAtomChar: char [
	<category: 'testing'>
	^((self classificationTable at: char asInteger + 1) bitAnd: AtomMask) ~= 0
    ]

    RFC822Scanner class >> isCommentChar: char [
	<category: 'testing'>
	^((self classificationTable at: char asInteger + 1) bitAnd: CommentMask) 
	    ~= 0
    ]

    RFC822Scanner class >> shouldBeQuoted: string [
	<category: 'testing'>
	^(string detect: [:char | (self isAtomChar: char) not] ifNone: [nil]) 
	    notNil
    ]

    phraseAsString: phrase [
	<category: 'converting'>
	| stream |
	stream := (String new: 40) writeStream.
	self class printPhrase: phrase on: stream.
	^stream contents
    ]

    scanAtom [
	"atom  =  1*<any CHAR except specials, SPACE and CTLs>"

	<category: 'multi-character scans'>
	token := self scanTokenMask: AtomMask.
	tokenType := #atom.
	^token
    ]

    scanComment [
	"collect comment"

	<category: 'multi-character scans'>
	| output |
	output := saveComments 
		    ifTrue: [(String new: 40) writeStream]
		    ifFalse: [nil].
	self scanCommentOn: output.
	output notNil 
	    ifTrue: 
		[currentComment isNil 
		    ifTrue: [currentComment := OrderedCollection with: output contents]
		    ifFalse: [currentComment add: output contents]].
	^token
    ]

    scanDomainText [
	"dtext = <any CHAR excluding <[>, <]>, <\> & CR, & including linear-white-space> ; => may be folded"

	<category: 'multi-character scans'>
	token := self 
		    scanToken: 
			[self
			    scanQuotedChar;
			    matchCharacterType: DomainTextMask]
		    delimitedBy: '[]'
		    notify: 'Malformed domain literal'.
	tokenType := #domainText.
	^token
    ]

    atEndOfLine [
	<category: 'multi-character scans'>
        self peek.
	^(self classificationMaskFor: lookahead) anyMask: CRLFMask
    ]

    skipEndOfLine [
	<category: 'multi-character scans'>
	hereChar == Character nl 
	    ifFalse: 
		[(source peekFor: Character nl) 
		    ifFalse: [^false]
		    ifTrue: [self sourceTrailNextPut: Character nl]].
        ^true
    ]

    scanEndOfLine [
	"Note: this will work only for RFC822 but not for HTTP. Needs more design work"

	<category: 'multi-character scans'>
        "Called after #step, so no need to peek to set the CRLFMask."
	(self matchCharacterType: CRLFMask) ifFalse: [^false].
	self skipEndOfLine ifFalse: [^self].
	self shouldFoldLine 
	    ifTrue: 
		[self hereChar: Character space.
		^self].

	"Otherwise we have an end-of-line condition -- set appropriate masks"
	classificationMask := (classificationMask bitClear: WhiteSpaceMask) 
		    bitOr: EndOfLineMask
    ]

    scanFieldName [
	"RFC822, p.9: field-name = 1*<any CHAR excluding CTLs, SPACE and ':'>"

	<category: 'multi-character scans'>
	^self scanTokenMask: HeaderNameMask
    ]

    scanPhrase [
	"RFC822: phrase = 1*word ; Sequence of words. At the end of scan the scanner has read the first token after phrase"

	<category: 'multi-character scans'>
	^self tokenizeWhile: [#(#quotedText #atom) includes: tokenType]
    ]

    scanQuotedChar [
	"Scan possible quoted character. If the current char is $\, read in next character and make it a quoted
	 string character"

	<category: 'multi-character scans'>
	^hereChar == QuotedPairChar 
	    ifTrue: 
		[self step.
		classificationMask := QuotedPairMask.
		true]
	    ifFalse: [false]
    ]

    scanQuotedText [
	"quoted-string = <"

	"> *(qtext/quoted-pair) <"

	">; Regular qtext or quoted chars.
	 qtext    =  <any CHAR excepting <"

	">, <\> & CR, and including linear-white-space>  ; => may be folded"

	"We are positioned at the first double quote character"

	<category: 'multi-character scans'>
	token := self 
		    scanToken: 
			[self
			    scanQuotedChar;
			    matchCharacterType: QuotedTextMask]
		    delimitedBy: '""'
		    notify: 'Unmatched quoted text'.
	tokenType := #quotedText.
	^token
    ]

    scanText [
	"RFC822: text = <Any CHAR, including bare CR & bare LF, but not including CRLF. This is a 'catchall' category and cannot be tokenized. Text is used only to read values of unstructured fields"

	<category: 'multi-character scans'>
	(self matchCharacterType: EndOfLineMask) ifTrue: [^String new].
	^self scanUntil: [self matchCharacterType: CRLFMask]
    ]

    scanWord [
	<category: 'multi-character scans'>
	self nextToken.
	(#(#quotedText #atom) includes: tokenType) 
	    ifFalse: [self error: 'Expecting word'].
	^token
    ]

    skipWhiteSpace [
	"It is inefficient because intermediate stream is created. Perhaps refactoring scanWhile: can help"

	<category: 'multi-character scans'>
	self scanWhile: 
		[hereChar == $( 
		    ifTrue: 
			[self
			    stepBack;
			    scanComment.
			true]
		    ifFalse: [self matchCharacterType: WhiteSpaceMask]]
    ]

    nextRFC822Token [
	<category: 'private'>
	| char |
	self skipWhiteSpace.
	char := self peek.
	char isNil 
	    ifTrue: 
		["end of input"

		tokenType := #doIt.
		^token := nil].
	char == $( 
	    ifTrue: 
		[^self
		    scanComment;
		    nextToken].
	char == $" ifTrue: [^self scanQuotedText].
	(self specials includes: char) 
	    ifTrue: 
		[tokenType := #special.	"Special character. Make it token value and set token type"
		^token := self next].
	(self matchCharacterType: AtomMask) ifTrue: [^self scanAtom].
	tokenType := #doIt.
	token := char.
	^token
    ]

    scanCommentOn: streamOrNil [
	"scan comment copying on specified stream"

	<category: 'private'>
	self step ~~ $( ifTrue: [self error: 'Unmatched comment'].	"Should never be the case"
	token := self scanUntil: 
			[((self
			    scanQuotedChar;
			    matchCharacterType: CommentMask) 
				ifTrue: 
				    [streamOrNil notNil ifTrue: [streamOrNil nextPut: hereChar].
				    true]
				ifFalse: 
				    [hereChar == $( 
					ifTrue: 
					    [streamOrNil notNil ifTrue: [streamOrNil space].
					    self
						stepBack;
						scanCommentOn: streamOrNil.
					    streamOrNil notNil ifTrue: [streamOrNil space].
					    true]
					ifFalse: [false]]) 
				not].
	hereChar ~~ $) ifTrue: [self error: 'Unmatched comment'].
	^token
    ]

    assertNoLookahead [
	"Fail if the parser has lookahead."

	<category: 'test'>

        lookahead isNil ifFalse: [ self error: 'unexpected parsing state' ]
    ]

    shouldFoldLine [
	"Answers true if next line is to be folded in, that is, if CRLF is followed by at least one white space"

	<category: 'private'>
	| char |
	self atEnd ifTrue: [^false].
	char := source peek.
	^((self classificationMaskFor: char) anyMask: WhiteSpaceMask) 
	    ifFalse: 
		[self resetToken; peek.
		false]
	    ifTrue: 
		[self sourceTrailNextPut: source next.
		true]
    ]

    step [
	<category: 'private'>
	super step.
	self scanEndOfLine.
	^hereChar
    ]

    isRFC822Scanner [
	<category: 'testing'>
	^true
    ]

    nextToken [
	<category: 'tokenization'>
	^self nextRFC822Token
    ]

    specials [
	"This method is provided to encapsulate lexical differences between RFC822 on one side, and MIME, HTTP on the other side. MIME definiton of 'tspecials' is the same as the RFC 822 definition of ''specials' with the addition of the three characters </>, <?>, and <=>, and the removal of <.>. To present uniform tokenization interface, this method is overridden in Mime scanner"

	<category: 'tokenization'>
	^self class specials
    ]
]

]



Namespace current: NetClients.MIME [

StructuredHeaderField subclass: ScalarField [
    | value |
    
    <category: 'NetClients-MIME'>
    <comment: 'I represent RFC822 structured header field that contains a single value. When parsing the field we would just sequentially read and concatenate all tokens. This will remove all ''noise'' such as white space and comments

Instance Variables:
    item    <String>  Parsed value of the item
'>

    ScalarField class >> fieldNames [
	<category: 'parsing'>
	^#('message-id' 'content-id' 'content-transfer-encoding' 'transfer-encoding' 'content-encoding')
    ]

    value [
	<category: 'accessing'>
	^value
    ]

    value: anObject [
	<category: 'accessing'>
	value := anObject
    ]

    parse: rfc822Stream [
	<category: 'parsing'>
	self value: (self tokenizedValueFrom: rfc822Stream)
    ]
]

]



Namespace current: NetClients.MIME [

RFC822Scanner subclass: MimeScanner [
    
    <category: 'NetClients-MIME'>
    <comment: nil>

    MimeScanner class >> decodeBase64From: startIndex to: endIndex in: aString [
	"Decode aString from startIndex to endIndex in base64."

	<category: 'text processing'>
	| codeChars decoder index nl endChars end padding data sz i outSize |
	codeChars := 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.
	decoder := (0 to: 255) 
		    collect: [:n | (codeChars indexOf: (n + 1) asCharacter) - 1].
	decoder replaceAll: -1 with: 0.
	index := startIndex.
	nl := Character nl.
	"There is padding at the end of a base64 message if the content is not a multiple of
	 3 bytes in length.  The padding is either two ='s to pad-out a trailing byte, 1 = to
	 pad out a trailing pair of bytes, or no padding.  Here we count the padding.  After
	 processing the message we cut-back by the amount of padding."
	end := endIndex min: (sz := aString size).
	endChars := codeChars , (String with: $=).
	
	[(endChars includes: (aString at: end)) 
	    and: [end = endIndex or: [(aString at: end + 1) = nl]]] 
		whileFalse: [end := end - 1].
	padding := 0.
	[(aString at: end - padding) == $=] whileTrue: 
		[padding := padding + 1].
	outSize := (end - startIndex + 1) * 3 // 4 - padding.
	data := String new: outSize.
	i := 1.
	[index <= end] whileTrue: 
		[| triple |
		triple := ((decoder at: (aString at: index) asInteger) bitShift: 18) 
			    + ((decoder at: (aString at: index + 1) asInteger) bitShift: 12) 
				+ ((decoder at: (aString at: index + 2) asInteger) bitShift: 6) 
				+ (decoder at: (aString at: index + 3) asInteger).
		padding := outSize - i.
		data at: i put: (Character value: (triple digitAt: 3)).
		padding > 0 ifTrue: [
			data at: i + 1 put: (Character value: (triple digitAt: 2))].
		padding > 1 ifTrue: [
			data at: i + 2 put: (Character value: (triple digitAt: 1))].

		i := i + 3.
		index := index + 4.
		[(index > sz or: [(aString at: index) = nl]) and: [index <= end]] 
		    whileTrue: [index := index + 1]].
	^data
    ]

    MimeScanner class >> decodeQuotedPrintableFrom: startIndex to: endIndex in: aString [
	"Decode aString from startIndex to endIndex in quoted-printable."

	<category: 'text processing'>
	| input output char n1 n2 |
	input := ReadStream 
		    on: aString
		    from: startIndex
		    to: endIndex.
	output := (String new: endIndex - startIndex) writeStream.
	[input atEnd] whileFalse: 
		[char := input next.
		$= == char 
		    ifTrue: 
			[('0123456789ABCDEF' includes: (n1 := input next)) 
			    ifTrue: 
				[n2 := input next.
				output nextPut: ((n1 digitValue bitShift: 4) + n2 digitValue) asCharacter]]
		    ifFalse: [output nextPut: char]].
	^output contents
    ]

    MimeScanner class >> decodeUUEncodedFrom: startIndex to: farEndIndex in: aString [
	"decode aString from startIndex to farEndIndex as uuencode-encoded"

	<category: 'text processing'>
	| endIndex i nl space output data |
	endIndex := farEndIndex - 2.
	
	[endIndex <= startIndex or: 
		[(aString at: endIndex + 1) = $e 
		    and: [(aString at: endIndex + 2) = $n and: [(aString at: endIndex + 3) = $d]]]] 
		whileFalse: [endIndex := endIndex - 1].
	i := (aString 
		    findString: 'begin'
		    startingAt: startIndex
		    ignoreCase: true
		    useWildcards: false) first.
	i = 0 ifTrue: [i := startIndex].
	nl := Character nl.
	space := Character space asInteger.
	output := (data := String new: (endIndex - startIndex) * 3 // 4) 
		    writeStream.
	
	[[i < endIndex and: [(aString at: i) ~= nl]] whileTrue: [i := i + 1].
	i < endIndex] 
		whileTrue: 
		    [| count |
		    count := (aString at: (i := i + 1)) asInteger - space bitAnd: 63.
		    i := i + 1.
		    count = 0 
			ifTrue: [i := endIndex]
			ifFalse: 
			    [[count > 0] whileTrue: 
				    [| m n o p |
				    m := (aString at: i) asInteger - space bitAnd: 63.
				    n := (aString at: i + 1) asInteger - space bitAnd: 63.
				    o := (aString at: i + 2) asInteger - space bitAnd: 63.
				    p := (aString at: i + 3) asInteger - space bitAnd: 63.
				    count >= 1 
					ifTrue: 
					    [output nextPut: (Character value: (m bitShift: 2) + (n bitShift: -4)).
					    count >= 2 
						ifTrue: 
						    [output 
							nextPut: (Character value: ((n bitShift: 4) + (o bitShift: -2) bitAnd: 255)).
						    count >= 3 
							ifTrue: [output nextPut: (Character value: ((o bitShift: 6) + p bitAnd: 255))]]].
				    i := i + 4.
				    count := count - 3]]].
	^data copyFrom: 1 to: output position
    ]

    scanText [
	"Parse text as defined in RFC822 grammar, then apply the rules of RFC2047 for encoded words in Text fields. An encoded word inside text field may appear immediately following a white space character"

	<category: 'multi-character scans'>
	| text |
	text := super scanText.
	^MimeEncodedWordCoDec decodeText: text
    ]

    scanToBoundary: boundary [
	"Scan for specified boundary (RFC2046, p5.1). Answer two-element array. First element is the scanned text from current position up to the beginning of the boundary. Second element is either #next or #last. #next means the boundary found is not the last one. #last means the boundary is the closing boundary for the multi-part body (that is, it looks like '--<boundary>--)"

	<category: 'multi-character scans'>
	| pattern string kind |
	pattern := (String with: Character nl) , '--' , boundary.
	string := self upToAll: pattern.
	kind := ((self peekFor: $-) and: [self peekFor: $-]) 
		    ifTrue: [#last]
		    ifFalse: [#next].
	self upTo: Character nl.
	^Array with: string with: kind
    ]

    scanToken [
	"MIME and HTTP: token  =  1*<any CHAR except tspecials, SPACE and CTLs>. That is, 'token' is analogous to RFC822 'atom' except set of Mime's set of tspecials characters includes three more characters as compared to set of 'specials' in RFC822"

	<category: 'multi-character scans'>
	token := self scanTokenMask: TokenMask.
	tokenType := #token.
	^token
    ]

    printPhrase: phrase on: stream [
	<category: 'printing'>
	MimeEncodedWordCoDec decodePhrase: phrase printOn: stream
    ]

    decodeCommentString: commentString [
	<category: 'private'>
	^MimeEncodedWordCoDec decodeComment: commentString
    ]

    nextMimeToken [
	<category: 'private'>
	| char |
	self skipWhiteSpace.
	char := self peek.
	char isNil 
	    ifTrue: 
		["end of input"

		tokenType := #doIt.
		^token := nil].
	char == $( 
	    ifTrue: 
		[^self
		    scanComment;
		    nextToken].
	char == $" ifTrue: [^self scanQuotedText].
	(self specials includes: char) 
	    ifTrue: 
		[tokenType := #special.	"Special character. Make it token value and set token type"
		^token := self next].
	(self matchCharacterType: TokenMask) ifTrue: [^self scanToken].
	tokenType := #doIt.
	token := char.
	^token
    ]

    scanCommentOn: streamOrNil [
	"scan comment copying on specified stream. Look for MIME 'encoded words' (RFC2047) and decoded them if identified"

	<category: 'private'>
	token := super scanCommentOn: streamOrNil.
	^self decodeCommentString: token
    ]

    nextToken [
	<category: 'tokenization'>
	^self nextMimeToken
    ]

    specials [
	"This method is provided to encapsulate lexical differences between RFC822 on one side, and MIME, HTTP on the other side. MIME definiton of 'tspecials' is the same as the RFC 822 definition of ''specials' with the addition of the three characters </>, <?>, and <=>, and the removal of <.>. To present uniform tokenization interface, this method is overridden in Mime scanner"

	<category: 'tokenization'>
	^self class tspecials
    ]
]

]



Namespace current: NetClients.MIME [

RFC822Scanner subclass: NetworkAddressParser [
    | descriptor |
    
    <category: 'NetClients-MIME'>
    <comment: 'This class parses mailbox and group addresses as well as address-spec as defined by RFC822 and MIME. Parsed results are placed in an instance of NetworkAddressDescriptor or MailGroupDescriptor. See utility methods.
RFC822 spec is word-based, so address is first tokenized, then parsed. MIME (RFC2045-2049) adds further interpretation to the address syntax. Once address is parsed, some parts of the address (namely ''phrase'' and ''comment'') can be further scanned for the presence of ''encoded words''. 
Note that MIME ''words'' are not the same as RFC822 ''words'', so the same expression may be tokenized differently in RFC822 and MIME. MIME states that mailbox and group addresses MUST be tokenized using RFC822 spec, then processed according to MIME rules. Therefore, we use #nextRFC822Token, not #nextToken like everybody else


Instance Variables:
    descriptor    <NetworkAddressDescriptor | MailGroupDescriptor>  comment
'>

    NetworkAddressParser class >> parse: string [
	<category: 'instance creation'>
	^self new parse: string
    ]

    NetworkAddressParser class >> addressesFrom: stream [
	"self addressesFrom: 'kyasu@crl.fujixerox.co.jp' readStream."

	"self addressesFrom: 'Kazuki Yasumatsu <kyasu@crl.fujixerox.co.jp>' readStream."

	"self addressesFrom: 'kyasu@crl.fujixerox.co.jp (Kazuki Yasumatsu)' readStream."

	"self addressesFrom: ' kyasu1, kyasu2, Kazuki Yasumatsu <kyasu3>, kyasu4 (Kazuki Yasumatsu)' readStream."

	"self addressesFrom: ' foo bar, kyasu1, ,  Kazuki Yasumatsu <kyasu2> <kyasu3> (<foo> (foo bar), bar)' readStream."

	<category: 'utility'>
	^(self on: stream) parseAddressesSeparatedBy: $,
    ]

    NetworkAddressParser class >> addressFrom: stream [
	"self addressFrom: 'kyasu@crl.fujixerox.co.jp'."

	"self addressFrom: 'Kazuki Yasumatsu <kyasu@crl.fujixerox.co.jp>'."

	"self addressFrom: 'kyasu@crl.fujixerox.co.jp (Kazuki Yasumatsu)'."

	<category: 'utility'>
	^(self on: stream) parseAddress
    ]

    descriptor [
	<category: 'accessing'>
	^descriptor
    ]

    descriptor: aValue [
	<category: 'accessing'>
	descriptor := aValue
    ]

    initialize [
	<category: 'initialize-release'>
	super initialize.
	descriptor := self newAddressDescriptor
    ]

    completeScanOfAddressSpecWith: partial [
	"addr-spec   =  local-part <@> domain        ; global address
	 local-part = word *(<.> word) ; uninterpreted, case-preserved
	 First local-part token was already scanned; we are now scanning *(<.> word) group and domain part.
	 Partial is an array of tokens already read"

	<category: 'private'>
	| stream pos |
	stream := partial readWriteStream.
	stream setToEnd.
	self descriptor localPart: (self scanLocalAddressPartTo: stream).
	pos := self position.
	self nextRFC822Token == $@ 
	    ifTrue: [self descriptor domain: self scanDomain]
	    ifFalse: [self position: pos]
    ]

    newAddressDescriptor [
	<category: 'private'>
	^NetworkAddressDescriptor new
    ]

    parseGroupSpecWith: phrase [
	"group = phrase <:> [#mailbox] <;>"

	<category: 'private'>
	| group mailboxes phrasex comment stream |
	mailboxes := self tokenizeList: [self parseAddress]
		    separatedBy: [token == $,].
	self nextRFC822Token == $; 
	    ifFalse: [^self notify: 'Group descriptor should be terminated by <:>'].
	group := MailGroupDescriptor new.

	"If phrase is non-empty, an alias was specified"
	phrasex := phrase isEmpty 
		    ifTrue: [nil]
		    ifFalse: [self phraseAsString: phrase].
	comment := currentComment isNil 
		    ifTrue: [nil]
		    ifFalse: 
			[stream := (String new: 40) writeStream.
			currentComment do: [:part | stream nextPutAll: part]
			    separatedBy: [stream space].
			stream contents].
	group
	    alias: phrasex;
	    addresses: mailboxes;
	    comment: comment.
	^group
    ]

    parseMailboxSpecWith: phrasex [
	"address     =  mailbox                      ; one addressee
	 /  group                        ; named list
	 group       =  phrase <:> [#mailbox] <;>
	 mailbox     =  addr-spec                    ; simple address
	 /  phrase route-addr            ; name & addr-spec
	 route-addr  =  <<> [route] addr-spec <>>
	 route       =  1#(<@> domain) <:>           ; path-relative"

	<category: 'private'>
	| phrase tok local stream comment |
	phrase := phrasex.
	tok := self nextRFC822Token.
	self descriptor: self newAddressDescriptor.

	"Variations of mailbox spec"
	tok = $< 
	    ifTrue: 
		["Phil Campbell<philc@acme.com>"

		self
		    stepBack;
		    scanRouteAndAddress]
	    ifFalse: 
		[('.@' includes: tok) 
		    ifTrue: 
			["These ones should have a non-empty local part to the left of delimiter"

			phrase isEmpty ifTrue: [self error: 'Invalid network address'].
			local := Array with: phrase last.
			phrase := phrase copyFrom: 1 to: phrase size - 1.	"Extract the part we already scanned"
			tok = $. 
			    ifTrue: 
				["phil.campbell.wise@acme.com>"

				self
				    stepBack;
				    completeScanOfAddressSpecWith: local].
			tok = $@ 
			    ifTrue: 
				["philc@acme.com>"

				self descriptor localPart: local.
				self descriptor domain: self scanDomain]]
		    ifFalse: [self stepBack]].
	"If phrase is non-empty, an alias was specified"
	phrase := phrase isEmpty 
		    ifTrue: [phrase := nil]
		    ifFalse: [self phraseAsString: phrase].
	self descriptor alias: phrase.
	comment := currentComment isNil 
		    ifTrue: [nil]
		    ifFalse: 
			[stream := (String new: 40) writeStream.
			currentComment do: [:part | stream nextPutAll: part]
			    separatedBy: [stream space].
			stream contents].
	self descriptor comment: comment.
	^self descriptor
    ]

    scanLocalAddressPartTo: stream [
	"local-part = word *(<.> word) ; uninterpreted, case-preserved
	 Part of local part may have been scanned already, it's in localPart of the descriptor"

	<category: 'private'>
	self tokenizeWhile: [token == $.] do: [stream nextPut: self scanWord].
	^stream contents
    ]

    tryScanSubdomain [
	<category: 'private'>
	self nextRFC822Token.
	tokenType = #atom ifTrue: [^true].
	token = $[ 
	    ifTrue: 
		[self
		    stepBack;
		    scanDomainText.
		^true].
	^false
    ]

    addressesFrom: stream [
	<category: 'public'>
	^(self on: stream) parseAddressesSeparatedBy: $,
    ]

    parse: aString [
	<category: 'public'>
	^self
	    on: aString readStream;
	    parseAddress
    ]

    parseAddress [
	"address     =  mailbox                      ; one addressee
	 /  group                        ; named list
	 group       =  phrase <:> [#mailbox] <;>
	 mailbox     =  addr-spec                    ; simple address
	 /  phrase route-addr            ; name & addr-spec
	 route-addr  =  <<> [route] addr-spec <>>
	 route       =  1#(<@> domain) <:>           ; path-relative"

	<category: 'public'>
	| phrase |
	phrase := self scanPhrase.
	^self nextRFC822Token = $: 
	    ifTrue: [self parseGroupSpecWith: phrase]
	    ifFalse: 
		[self
		    stepBack;
		    parseMailboxSpecWith: phrase]
    ]

    parseAddressesSeparatedBy: separatorChar [
	<category: 'public'>
	| addresses |
	addresses := self tokenizeList: [self parseAddress]
		    separatedBy: [token == separatorChar].
	^addresses
    ]

    scanDomain [
	"domain = sub-domain *(<.> sub-domain)"

	"Answers an array of domain seqments, from least significant to most significant"

	<category: 'public'>
	^self tokenizeList: 
		[self nextRFC822Token.
		tokenType = #atom 
		    ifTrue: [token]
		    ifFalse: 
			[token = $[ 
			    ifTrue: 
				[self
				    stepBack;
				    scanDomainText]
			    ifFalse: [^self notify: 'Invalid domain specification']]]
	    separatedBy: [token == $.]
    ]

    scanLocalAddress [
	"local-part = word *(<.> word) ; uninterpreted, case-preserved"

	<category: 'public'>
	^self tokenizeList: 
		[self nextRFC822Token.
		(#(#quotedText #atom) includes: tokenType) 
		    ifFalse: [^self notify: 'Local part can only include words'].
		token]
	    separatedBy: [token == $.]
    ]

    scanRoute [
	"route = 1#(<@> domain) <:> ; path-relative"

	<category: 'public'>
	| stream |
	stream := (Array new: 2) writeStream.
	[self nextRFC822Token == $@] whileTrue: 
		[stream nextPut: self scanDomain.
		self nextToken = $: ifFalse: [self error: 'Invalid route spec']].
	stream size = 0 ifTrue: [self error: 'Invalid route spec'].
	^stream contents
    ]

    scanRouteAndAddress [
	"route-addr  =  <<> [route] addr-spec <>>"

	<category: 'public'>
	self mustMatch: $< notify: 'Invalid route address spec'.
	self nextRFC822Token == $@ 
	    ifTrue: 
		[self stepBack.
		self descriptor route: self scanRoute].
	self completeScanOfAddressSpecWith: (Array with: token).
	self mustMatch: $> notify: 'Invalid route address spec'
    ]
]

]



Namespace current: NetClients.MIME [

StructuredHeaderField subclass: ContentTypeField [
    | type subtype |
    
    <category: 'NetClients-MIME'>
    <comment: 'This class represents MIME and HTTP Content-type header field. Format and semantics of this field are defined in the following documents:
    RFC2045: MIME, Part One: Format of Internet Message Bodies (ftp.uu.net/inet/rfc/rfc2045.Z)
    RFC2046: MIME, Part Two: Media Types (ftp.uu.net/inet/rfc/rfc2046.Z)
    RFC2068: Hyptertext Transfer Protocol -- HTTP/1.1 (ftp.uu.net/inet/rfc/rfc2068.Z)
As well as some other supplementary documents such as RFC2110 (ftp.uu.net/inet/rfc/rfc2110.Z)

The purpose of this field is to describe the data containing in the message body fully enough that the receiving side can pick an appropriate mechanism to handle the data in an appropriate manner. The value of this field is called a media type.

The value of media type consists of media type and subtype identifiers as well as auxiliary information required for certain media types. Auxiliary information is parsed and stored as field parameters. Utility methods are provided to simplify access to the most common parameters such as charset.

Currently defined top level media types are as follows:

    text, image, audio, video, multipart

Default is
    text/plain; charset=us-ascii

Instance Variables:
    type    <String>  Top level media type
    subtype    <String>  Media subtype
'>

    ContentTypeField class >> default [
	<category: 'defaults'>
	^self fromLine: 'content-type: text/plain; charset=us-ascii'
    ]

    ContentTypeField class >> defaultCharset [
	<category: 'defaults'>
	^'us-ascii'
    ]

    ContentTypeField class >> defaultContentType [
	<category: 'defaults'>
	^'text/plain'
    ]

    ContentTypeField class >> urlEncoded [
	<category: 'defaults'>
	^self 
	    fromLine: 'content-type: application/x-www-form-urlencoded; charset=us-ascii'
    ]

    ContentTypeField class >> fieldNames [
	<category: 'parsing'>
	^#('content-type')
    ]

    boundary [
	<category: 'accessing'>
	^self parameterAt: 'boundary'
    ]

    boundary: aString [
	<category: 'accessing'>
	^self parameterAt: 'boundary' put: aString
    ]

    charset [
	<category: 'accessing'>
	^(self parameterAt: 'charset' ifAbsent: [^self class defaultCharset]) 
	    asLowercase
    ]

    contentType [
	<category: 'accessing'>
	^type , '/' , subtype
    ]

    subtype [
	<category: 'accessing'>
	^subtype
    ]

    subtype: aString [
	<category: 'accessing'>
	subtype := aString
    ]

    type [
	<category: 'accessing'>
	^type
    ]

    type: aString [
	<category: 'accessing'>
	type := aString
    ]

    multipartType [
	<category: 'constants'>
	^'multipart'
    ]

    parse: rfc822Stream [
	"RFC2045: content := <Content-Type> <:> type </> subtype *(<;> parameter)"

	<category: 'parsing'>
	type := rfc822Stream nextToken asLowercase.
	rfc822Stream mustMatch: $/
	    notify: 'Content type must be specified as type/subtype'.
	subtype := rfc822Stream nextToken asLowercase.
	self readParametersFrom: rfc822Stream
    ]

    printStructureOn: aStream [
	<category: 'printing'>
	aStream nextPutAll: self contentType.
	self printParametersOn: aStream
    ]

    isMultipart [
	<category: 'testing'>
	^type = 'multipart'
    ]
]

]



Namespace current: NetClients.MIME [

ScalarField subclass: VersionField [
    | majorVersion minorVersion |
    
    <category: 'NetClients-MIME'>
    <comment: 'I represent version fields such as MIME or HTTP version field. My value has a form <major version><.><minor version>. Value of this field is its version strung; methods are provided to read (or construct version from) its constituent parts


Instance Variables:
    majorVersion    <String>    comment
    minorVersion    <String>  comment
'>

    VersionField class >> fieldNames [
	<category: 'parsing'>
	^#('mime-version' 'http-version')
    ]

    majorVersion [
	<category: 'accessing'>
	^majorVersion
    ]

    majorVersion: number [
	<category: 'accessing'>
	majorVersion := number
    ]

    minorVersion [
	<category: 'accessing'>
	^minorVersion
    ]

    minorVersion: number [
	<category: 'accessing'>
	minorVersion := number
    ]

    value [
	<category: 'accessing'>
	^self version
    ]

    value: string [
	<category: 'accessing'>
	self version: string
    ]

    version [
	<category: 'accessing'>
	^majorVersion , '.' , minorVersion
    ]

    version: string [
	<category: 'accessing'>
	| arr |
	arr := string subStrings: $..
	arr size < 2 
	    ifTrue: 
		[self 
		    notify: 'Version should be specified as <major version>.<minor version>'].
	self majorVersion: arr first.
	self minorVersion: arr last
    ]
]

]



Namespace current: NetClients.MIME [

ScalarField subclass: SingleMailboxField [
    
    <category: 'NetClients-MIME'>
    <comment: 'This class is used to represent RFC822 fields whose value is a single mailbox or network address. Value of this field is its mailbox descriptor. Examples of single mailbox field are ''Sender:'' and ''Resent-Sender''. Note that the absolute majority of address fields may contain multiple addresses and, therefore, are instantiated as MailBoxListFields.'>

    SingleMailboxField class >> fieldNames [
	<category: 'parsing'>
	^#('sender' 'resent-sender')
    ]

    address [
	<category: 'accessing'>
	^self value
    ]

    address: address [
	<category: 'accessing'>
	self value: address
    ]

    addresses [
	<category: 'accessing'>
	^{self address}
    ]

    addresses: aCollection [
	<category: 'accessing'>
	aCollection size = 1 
	    ifFalse: [self error: 'can only contain a single address'].
	aCollection do: [:theOnlyAddress | self value: theOnlyAddress]
    ]

    parse: rfc822Stream [
	"HeaderField fromLine: 'Sender :        Phil Campbell (The great) <philc@yahoo.com>'"

	<category: 'parsing'>
	self value: (NetworkAddressDescriptor addressFrom: rfc822Stream)
    ]
]

]



Namespace current: NetClients.MIME [

ScalarField subclass: MailboxListField [
    
    <category: 'NetClients-MIME'>
    <comment: 'I am used to represent most of RFC822 address fields. My value is a sequenceable collection of mailbox or mail group descriptors. Examples of this field are ''From'', ''To'', ''Cc'', ''Bcc'', etc'>

    MailboxListField class >> fieldNames [
	<category: 'parsing'>
	^#('from' 'to' 'reply-to' 'cc' 'bcc' 'resent-reply-to' 'resent-from' 'resent-to' 'resent-cc' 'resent-bcc')
    ]

    addAddress: address [
	<category: 'accessing'>
	^self addAddresses: (Array with: address)
    ]

    addAddresses: aCollection [
	<category: 'accessing'>
	self value addAll: aCollection
    ]

    address [
	<category: 'accessing'>
	self value first
    ]

    address: address [
	<category: 'accessing'>
	self value isEmpty ifTrue: [self value: (OrderedCollection new: 1)].
	self value at: 1 put: address
    ]

    addresses [
	<category: 'accessing'>
	^self value
    ]

    addresses: aCollection [
	<category: 'accessing'>
	self value: aCollection
    ]

    initialize [
	<category: 'initialization'>
	super initialize.
	value := OrderedCollection new
    ]

    parse: rfc822Stream [
	"HeaderField fromLine: 'To       :  George Jones <Group@Some-Reg.An-Org>,
	 Al.Neuman@MAD.Publisher'"

	<category: 'parsing'>
	self value: (NetworkAddressDescriptor addressesFrom: rfc822Stream)
    ]

    printValueOn: aStream [
	<category: 'printing'>
	| val |
	(val := self value) notNil 
	    ifTrue: 
		[val do: [:each | each printOn: aStream]
		    separatedBy: 
			[aStream
			    nextPutAll: ', ';
			    nl;
			    tab]]
    ]
]

]



Namespace current: NetClients.MIME [
    SimpleScanner initialize.
    RFC822Scanner initialize
]