File: mime.c

package info (click to toggle)
slrn 1.0.3+dfsg-3
  • links: PTS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 6,412 kB
  • sloc: ansic: 39,852; sh: 3,777; perl: 467; makefile: 229; sed: 24
file content (2077 lines) | stat: -rw-r--r-- 46,153 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
/* -*- mode: C; mode: fold -*- */
/* MIME handling routines.
 *
 * Author: Michael Elkins <elkins@aero.org>
 * Modified by John E. Davis <jed@jedsoft.org>
 * Modified by Thomas Schultz <tststs@gmx.de>
 *
 * Change Log:
 * Aug 20, 1997 patch from "Byrial Jensen" <byrial@post3.tele.dk>
 *   added.  Apparantly RFC2047 requires the whitespace separating
 *   multiple encoded words in headers to be ignored.
 *   Status: unchecked
 */

#include "config.h"
#ifndef SLRNPULL_CODE
#include "slrnfeat.h"
#endif

#include <stdio.h>
#include <string.h>

#ifdef HAVE_STDLIB_H
# include <stdlib.h>
#endif

#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif

#include <ctype.h>

#if defined(__os2__) || defined(__NT__)
# include <process.h>
#endif

#include <slang.h>
#include "jdmacros.h"

#include "slrn.h"
#include "misc.h"
#include "slrn.h"
#include "group.h"
#include "art.h"
#include "util.h"
#include "strutil.h"
#include "server.h"
#include "snprintf.h"
#include "mime.h"
#include "charset.h"
#include "common.h"
#include "hdrutils.h"
#include "parse2822.h"

int Slrn_Use_Meta_Mail = 1;
int Slrn_Fold_Headers = 1;
char *Slrn_MetaMail_Cmd;

#ifndef SLRNPULL_CODE
#define CONTENT_TYPE_TEXT		0x01
#define CONTENT_TYPE_MESSAGE		0x02
#define CONTENT_TYPE_MULTIPART		0x03
#define CONTENT_TYPE_UNSUPPORTED	0x10

#define CONTENT_SUBTYPE_PLAIN		0x01
#define CONTENT_SUBTYPE_UNKNOWN		0x02
#define CONTENT_SUBTYPE_UNSUPPORTED	0x10

#endif /* NOT SLRNPULL_CODE */

#ifndef SLRNPULL_CODE
/*
 * Returns 0 for supported Content-Types:
 *   text/plain
 *   message/
 *   multipart/
 * Otherwise it returns -1.
 */
static int parse_content_type_line (Slrn_Article_Type *a)/*{{{*/
{
   char *b;
   Slrn_Article_Line_Type *line;

   if (a == NULL)
     return -1;
   line = a->lines;

   if (NULL == (line = slrn_find_header_line (a, "Content-Type:")))
     return 0;

   b = slrn_skip_whitespace (line->buf + 13);

   if (0 == slrn_case_strncmp (b, "text/", 5))
     {
	a->mime.content_type = CONTENT_TYPE_TEXT;
	b += 5;
	if (0 != slrn_case_strncmp (b, "plain", 5))
	  {
	     a->mime.content_subtype = CONTENT_SUBTYPE_UNSUPPORTED;
	     return -1;
	  }
	else
	  {
	     a->mime.content_subtype = CONTENT_SUBTYPE_PLAIN;
	  }
	b += 5;
     }
   else if (0 == slrn_case_strncmp (b, "message/", 8))
     {
	a->mime.content_type = CONTENT_TYPE_MESSAGE;
	a->mime.content_subtype = CONTENT_SUBTYPE_UNKNOWN;
	b += 8;
     }
   else if (0 == slrn_case_strncmp (b, "multipart/", 10))
     {
	a->mime.content_type = CONTENT_TYPE_MULTIPART;
	a->mime.content_subtype = CONTENT_SUBTYPE_UNKNOWN;
	b += 10;
     }
   else
     {
	a->mime.content_type = CONTENT_TYPE_UNSUPPORTED;
	return -1;
     }

   do
     {
	while (NULL != (b = slrn_strbyte (b, ';')))
	  {
	     char *charset;
	     unsigned int len;
	     int quote_seen;

	     b = slrn_skip_whitespace (b + 1);

	     if (0 != slrn_case_strncmp (b, "charset", 7))
	       continue;

	     b = slrn_skip_whitespace (b + 7);
	     while (*b == 0)
	       {
		  line = line->next;
		  if ((line == NULL)
		      || ((line->flags & HEADER_LINE) == 0)
		      || ((*(b = line->buf) != ' ') && (*b == '\t')))
		    return -1;
		  b = slrn_skip_whitespace (b);
	       }

	     if (*b != '=') continue;
	     b++;
	     quote_seen = 0;
	     if (*b == '"')
	       {
		  b++;
		  quote_seen = 1;
	       }

	     charset = b;
	     if (quote_seen)
	       {
		  while (*b && (*b != '\n') && (*b != '"'))
		    b++;
	       }
	     else
	       {
		  while (*b && (*b != ';')
			 && (*b != ' ') && (*b != '\t') && (*b != '\n')
			 && (*b != '"'))
		    b++;
	       }

	     len = b - charset;

	     a->mime.charset = slrn_safe_strnmalloc (charset, len);
	     return 0;
	  }
	line = line->next;
     }
   while ((line != NULL)
	  && (line->flags & HEADER_LINE)
	  && ((*(b = line->buf) == ' ') || (*b == '\t')));

   return 0;
}

/*}}}*/
#define ENCODED_RAW			0
#define ENCODED_7BIT			1
#define ENCODED_8BIT			2
#define ENCODED_QUOTED			3
#define ENCODED_BASE64			4
#define ENCODED_BINARY			5
#define ENCODED_UNSUPPORTED		6
static int parse_content_transfer_encoding_line (Slrn_Article_Type *a)/*{{{*/
{
   Slrn_Article_Line_Type *line;
   char *buf;

   if (a == NULL)
     return -1;

   line = slrn_find_header_line (a, "Content-Transfer-Encoding:");
   if (line == NULL) return ENCODED_RAW;

   buf = slrn_skip_whitespace (line->buf + 26);
   if (*buf == '"') buf++;

   if (0 == slrn_case_strncmp (buf,  "7bit", 4))
	return ENCODED_7BIT;
   else if (0 == slrn_case_strncmp (buf,  "8bit", 4))
	return ENCODED_8BIT;
   else if (0 == slrn_case_strncmp (buf,  "base64", 6))
	return ENCODED_BASE64;
   else if (0 == slrn_case_strncmp (buf,  "quoted-printable", 16))
	return ENCODED_QUOTED;
   else if (0 == slrn_case_strncmp (buf,  "binary", 6))
	return ENCODED_BINARY;
   return ENCODED_UNSUPPORTED;
}

/*}}}*/
#endif /* NOT SLRNPULL_CODE*/

static int Index_Hex[128] =/*{{{*/
{
   -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
     -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
     -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
     0, 1, 2, 3,  4, 5, 6, 7,  8, 9,-1,-1, -1,-1,-1,-1,
     -1,10,11,12, 13,14,15,-1, -1,-1,-1,-1, -1,-1,-1,-1,
     -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
     -1,10,11,12, 13,14,15,-1, -1,-1,-1,-1, -1,-1,-1,-1,
     -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1
};

/*}}}*/
#define HEX(c) (Index_Hex[(unsigned char)(c) & 0x7F])

static char *decode_quoted_printable (char *dest,/*{{{*/
				      char *src, char *srcmax,
				      int treat_underscore_as_space,
				      int keep_nl, int convert_null)
{
   char *allowed_in_qp = "0123456789ABCDEFabcdef";
   unsigned char ch;
/*
#ifndef SLRNPULL_CODE
   if (strip_8bit && (NULL == Char_Set))
     mask = 0x80;
#else
   (void) strip_8bit;
#endif*/
   while (src < srcmax)
     {
	ch = (unsigned char) *src++;
	if (ch == '=')
	  {
	     if ((src + 1 < srcmax)
		 && (NULL != slrn_strbyte (allowed_in_qp, src[0]))
		 && (NULL != slrn_strbyte (allowed_in_qp, src[1])))
	       {
		  ch = (16 * HEX(src[0])) + HEX(src[1]);
		  if ((ch == '\n') && (keep_nl == 0))
		    ch = '?';
		  *dest++ = (char) ch;
		  src += 2;
	       }
	     else if ((src < srcmax) && (*src == '\n'))
	       {
		  src++;
		  continue;/* = at the end of a line-- skip it */
	       }
	     else *dest++ = ch;
	  }
	else if ((ch == '_') && treat_underscore_as_space)
	  {
	     *dest++ = ' ';
	  }
	else if ((ch == '\n') && (keep_nl == 0))
	  *dest++ = '?';
	else if ((ch == 0) && convert_null)
	  *dest++ = '?';
	else
	  *dest++ = (char) ch;
     }
   return dest;
}

/*}}}*/

static int Index_64[128] =/*{{{*/
{
   -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
     -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
     -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,62, -1,-1,-1,63,
     52,53,54,55, 56,57,58,59, 60,61,-1,-1, -1,-1,-1,-1,
     -1, 0, 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,-1, -1,-1,-1,-1,
     -1,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,-1, -1,-1,-1,-1
};
/*}}}*/
#define BASE64(c) (Index_64[(unsigned char)(c) & 0x7F])

static char *decode_base64 (char *dest, char *src, char *srcmax, int keep_nl, int convert_null) /*{{{*/
{
   while (src + 3 < srcmax)
     {
	char ch = (BASE64(src[0]) << 2) | (BASE64(src[1]) >> 4);
	if ((ch == '\n') && (keep_nl == 0)) ch = '?';
	else if ((ch == 0) && convert_null) ch = '?';
	*dest++ = ch;

	if (src[2] == '=') break;
	ch = ((BASE64(src[1]) & 0xf) << 4) | (BASE64(src[2]) >> 2);
	if ((ch == '\n') && (keep_nl == 0)) ch = '?';
	else if ((ch == 0) && convert_null) ch = '?';
	*dest++ = ch;

	if (src[3] == '=') break;
	ch = ((BASE64(src[2]) & 0x3) << 6) | BASE64(src[3]);
	if ((ch == '\n') && (keep_nl == 0)) ch = '?';
	else if ((ch == 0) && convert_null) ch = '?';
	*dest++ = ch;

	src += 4;
     }
   return dest;
}

/*}}}*/

/* This function decodes the base64 string in place.  It returns a pointer to
 * the END of the decoded text.
 */
char *slrn_decode_base64 (char *str)
{
   char *s, *s0;
   char ch;
   /* Remove any characters not in the base64 alphabet */
   s = s0 = str;
   while (1)
     {
	ch = *s++;
	if (ch == 0)
	  {
	     *s0 = ch;
	     break;
	  }
	if ((ch & 0x80) || (-1 == Index_64[(unsigned char)(ch)]))
	  {
	     if (ch != '=')
	       continue;
	  }
	*s0++ = ch;
     }
   s = decode_base64 (str, str, s0, 1, 0);
   return s;
}

/* returns a pointer to the end of the decoded string.  It decodes in-place */
char *slrn_decode_qp (char *str)
{
   return decode_quoted_printable (str, str, str+strlen(str), 0, 1, 0);
}

/* Warning: It must be ok to free *s_ptr and replace it with the converted
 * string */
int slrn_rfc1522_decode_string (char **s_ptr, unsigned int start_offset )/*{{{*/
{
   char *s1, *s2, ch, *s;
   char *charset, method, *txt;
   char *after_last_encoded_word;
   char *after_whitespace;
   unsigned int count;
   unsigned int len;
   int keep_nl = 0;

   count = 0;
   after_whitespace = NULL;
   after_last_encoded_word = NULL;
   charset = NULL;
   s= *s_ptr;

   s = s + start_offset;
   while (1)
     {
	char *decoded_start, *decoded_end;

	while ((NULL != (s = slrn_strbyte (s, '=')))
	       && (s[1] != '?')) s++;
	if (s == NULL) break;

	s1 = s;

	charset = s = s1 + 2;
	while (((ch = *s) != 0)
	       && (ch != '?') && (ch != ' ') && (ch != '\t') && (ch != '\n'))
	  s++;

	if (ch != '?')
	  {
	     s = s1 + 2;
	     charset = NULL;
	     continue;
	  }

	charset = s1 + 2;
	len = s - charset;
	charset=slrn_strnmalloc (charset, len, 1);

	s++;			       /* skip ? */
	method = *s++;		       /* skip B,Q */
	/* works in utf8 mode and else */
	if (method == 'b') method = 'B';
	if (method == 'q') method = 'Q';

	if ((charset == NULL) || ((method != 'B') && (method != 'Q'))
	    || (*s != '?'))
	  {
	     s = s1 + 2;
	     slrn_free(charset);
	     charset = NULL;
	     continue;
	  }
	/* Now look for the final ?= after encoded test */
	s++;			       /* skip ? */
	txt = s;

	while ((ch = *s) != 0)
	  {
	     /* Appararantly some programs do not convert ' ' to '_' in
	      * quoted printable.  Sigh.
	      */
	     if (((ch == ' ') && (method != 'Q'))
		 || (ch == '\t') || (ch == '\n'))
	       break;
	     if ((ch == '?') && (s[1] == '='))
	       break;

	     s++;
	  }

	if ((ch != '?') || (s[1] != '='))
	  {
	     s = s1 + 2;
	     slrn_free(charset);
	     charset = NULL;
	     continue;
	  }

	if (s1 == after_whitespace)
	  s1 = after_last_encoded_word;

        /* Note: these functions return a pointer to the END of the decoded
	 * text.
	 */
	s2 = s1;

	decoded_start = s1;

	if (method == 'B')
	  s1 = decode_base64 (s1, txt, s, keep_nl, 1);
	else s1 = decode_quoted_printable (s1, txt, s, 1, keep_nl, 1);

	decoded_end = s1;

	/* Now move everything over */
	s2 = s + 2;		       /* skip final ?= */
	s = s1;			       /* start from here next loop */
	while ((ch = *s2++) != 0) *s1++ = ch;
	*s1 = 0;

	count++;

	if (slrn_case_strncmp(Slrn_Display_Charset,
			   charset,
			   (strlen(Slrn_Display_Charset) <= len) ? strlen(Slrn_Display_Charset) : len) != 0)
	  {
	     /* We really need the position _after_ the decoded word, so we
	      * split the remainder of the string for charset conversion and
	      * put it back together afterward. */
	     char ch1;
	     unsigned int offset = decoded_start - *s_ptr;
	     unsigned int substr_len = decoded_end - decoded_start;

	     ch1 = *decoded_end;
	     *decoded_end = 0;
	     s2 = slrn_convert_substring(*s_ptr, offset, substr_len, Slrn_Display_Charset, charset, 0);
	     *decoded_end = ch1;

	     if (s2 != NULL)
	       {
		  /* FIXME --- currently slrn_strdup_strcat will exit */
		  s = slrn_strdup_strcat (s2, decoded_end, NULL);
		  if (s == NULL)
		    {
		    }

		  slrn_free(*s_ptr);
		  *s_ptr = s;
		  s += strlen(s2);
		  slrn_free(s2);
	       }
           }

	slrn_free(charset);
	charset=NULL;

	after_last_encoded_word = s;
	s = slrn_skip_whitespace (s);
	after_whitespace = s;
     }
   if (charset!=NULL)
	slrn_free(charset);
   return count;
}

/*}}}*/

#ifndef SLRNPULL_CODE /* rest of the file in this ifdef */

/* Decode everything after the colon */
static int rfc1522_decode_header_generic (char **hdr, unsigned int start_offset)
{
   return slrn_rfc1522_decode_string (hdr, start_offset);
}

static int rfc1522_decode_header_email (char **hdr, unsigned int start_offset)
{
   char *encodemap;
   char *header, *addr;
   char *errmsg;
   unsigned int i0, last_i0, imax;
   char *new_header = NULL;
   unsigned int new_header_len;
   int status;

   header = *hdr;
   addr = header + start_offset;

   if (NULL == slrn_strbyte (addr, '?'))
     return 0;

   if (NULL == (encodemap = slrn_parse_rfc2822_addr (addr, &errmsg)))
     {
	slrn_error ("%s", errmsg);
	return -1;
     }

   imax = strlen (encodemap);
   i0 = 0;
   while ((i0 < imax)
	  && (encodemap[i0] == ' '))
     i0++;

   status = 0;
   if (i0 == imax)
     {
	slrn_free (encodemap);
	return 0;
     }

   new_header_len = i0 + start_offset;
   new_header = slrn_strnmalloc (header, new_header_len, 1);
   if (new_header == NULL)
     goto return_error;

   status = 0;
   last_i0 = i0;
   while (1)
     {
	char *tmp, *str;
	unsigned int i1, dlen;
	int dstatus;

	if ((i0 < imax)
	    && (encodemap[i0] == ' '))
	  {
	     i0++;
	     continue;
	  }

	tmp = slrn_substrjoin (new_header, new_header+new_header_len,
			       addr + last_i0, addr + i0,
			       NULL);
	if (tmp == NULL)
	  goto return_error;

	slrn_free (new_header);
	new_header = tmp;
	new_header_len += i0 - last_i0;

	if (i0 == imax)
	  break;

	i1 = i0 + 1;
	while ((i1 < imax)
	       && (encodemap[i1] != ' '))
	  i1++;

	str = slrn_strnmalloc (addr + i0, i1-i0, 1);
	if (str == NULL)
	  goto return_error;

	if (-1 == (dstatus = slrn_rfc1522_decode_string (&str, 0)))
	  {
	     slrn_free (str);
	     goto return_error;
	  }
	status = status || (dstatus != 0);

	dlen = strlen (str);
	tmp = slrn_substrjoin (new_header, new_header + new_header_len,
			       str, str + dlen, NULL);
	slrn_free (str);

	if (tmp == NULL)
	  goto return_error;

	slrn_free (new_header);
	new_header = tmp;
	new_header_len += dlen;

	last_i0 = i0 = i1;
     }

   slrn_free (encodemap);
   slrn_free (*hdr);
   *hdr = new_header;
   return status;

return_error:
   if (new_header != NULL)
     slrn_free (new_header);
   if (encodemap != NULL)
     slrn_free (encodemap);

   return -1;
}

typedef struct
{
   char *header;
   unsigned int header_len;
   int (*decode_func)(char **, unsigned int);
}
Header_Decode_Type;

static Header_Decode_Type Header_Decode_Table[] =
{
   {"Message-ID", 10, NULL},
   {"Followup-To", 11, NULL},
   {"Newsgroups", 10, NULL},
   {"References", 10, NULL},
   {"Received", 10, NULL},
   {"Xref", 10, NULL},
   {"Cc", 2, rfc1522_decode_header_email},
   {"To", 2, rfc1522_decode_header_email},
   {"Reply-To", 8, rfc1522_decode_header_email},
   {"Mail-Copies-To", 14, rfc1522_decode_header_email},
   {"From", 4, rfc1522_decode_header_email},
   {NULL, 0, NULL}
};

static Header_Decode_Type *find_header_decode_info (char *header, unsigned int len)
{
   Header_Decode_Type *hdt;

   hdt = Header_Decode_Table;

   while (hdt->header != NULL)
     {
	if ((hdt->header_len == len)
	    && (0 == slrn_case_strncmp (hdt->header, header, len)))
	  return hdt;

	hdt++;
     }
   return NULL;
}

/* Warning: It must be ok to free *s_ptr and replace it with the converted
 * string */
int slrn_rfc1522_decode_header (char *name, char **hdrp)
{
   char *header;
   unsigned int len, start_offset;
   Header_Decode_Type *hdt;
   int (*decode_func)(char **, unsigned int);

   header = *hdrp;
   if (slrn_string_nonascii (header))
     {
       /* Only ascii is allowed in headers, if we find unencoded 8 bit chars
        * convert them with the fallback charset.
	*/
	char *s = header;

	if (NULL == (s = slrn_convert_string (NULL, s, s+strlen(s),
					      Slrn_Display_Charset, 0)))
	  return -1;

	slrn_free (header);
	header = s;
	*hdrp = header;
     }

   if (name == NULL)
     {
	char *colon;

	if (NULL == (colon = strchr (header, ':')))
	  return 0;
	len = colon - header;
	name = header;
	start_offset = len + 1;
     }
   else
     {
	len = strlen (name);
	start_offset = 0;
     }

   if (NULL == (hdt = find_header_decode_info (name, len)))
     decode_func = rfc1522_decode_header_generic;
   else
     {
	decode_func = hdt->decode_func;
	if (decode_func == NULL)
	  return 0;
     }

   return (*decode_func)(hdrp, start_offset);
}

static void rfc1522_decode_headers (Slrn_Article_Type *a)/*{{{*/
{
   Slrn_Article_Line_Type *line;

   if (a == NULL)
     return;

   line = a->lines;

   while ((line != NULL) && (line->flags & HEADER_LINE))
     {
	if (1 == slrn_rfc1522_decode_header (NULL, &line->buf))
	  {
	     a->is_modified = 1;
	     a->mime.was_modified = 1;
	  }
	line = line->next;
     }
}

/*}}}*/

static void decode_mime_base64 (Slrn_Article_Type *a)/*{{{*/
{
   Slrn_Article_Line_Type *l;
   Slrn_Article_Line_Type *body_start, *next;
   char *buf_src, *buf_dest, *buf_pos, *buf_end;
   char *base;
   int keep_nl = 1;
   int len;

   if (a == NULL) return;

   l = a->lines;

   /* skip header and separator */
   while ((l != NULL) && ((l->flags & HEADER_LINE) || l->buf[0] == '\0'))
     l = l->next;

   if (l == NULL) return;

   body_start = l;

   /* let's calculate how much space we need... */
   len = 0;
   while (l != NULL)
     {
	len += strlen(l->buf);
	l = l->next;
     }

   /* get some memory */
   buf_src = slrn_safe_malloc (len + 1);
   buf_dest = slrn_safe_malloc (len + 1);

   /* collect all base64 encoded lines into buf_src */
   l = body_start;
   buf_pos = buf_src;
   while (l != NULL)
     {
	strcpy (buf_pos, l->buf); /* safe */
	buf_pos += strlen(l->buf);
	l = l->next;
     }

   /* put decoded article into buf_dest */
   buf_pos = decode_base64 (buf_dest, buf_src, buf_src+len, keep_nl, 1);
   *buf_pos = '\0';

   if (a->mime.charset == NULL)
     {
	buf_pos = buf_dest;
	while (*buf_pos)
	  {
	     if (*buf_pos & 0x80) *buf_pos = '?';
	     buf_pos++;
	  }
     }

   l = body_start;
   body_start = body_start->prev;

   /* free old body */
   while (l != NULL)
     {
	slrn_free(l->buf);
	next = l->next;
	slrn_free((char *)l);
	l = next;
     }
   body_start->next = NULL;

   a->is_modified = 1;
   a->mime.was_modified = 1;

   l = body_start;
   base = buf_dest;
   buf_pos = buf_dest;
   buf_end = buf_dest + strlen (buf_dest);
   /* put decoded article back into article structure */

   while (buf_dest < buf_end)
     {
	if (NULL == (buf_pos = slrn_strbyte(buf_dest, '\n')))
	  buf_pos = buf_end;

	len = buf_pos - buf_dest;

	next = (Slrn_Article_Line_Type *) slrn_malloc(sizeof(Slrn_Article_Line_Type), 1, 1);
	if ((next == NULL)
	    || (NULL == (next->buf = slrn_malloc(sizeof(char) * len + 1, 0, 1))))
	  {
	     slrn_free ((char *) next);/* NULL ok */
	     goto return_error;
	  }
	next->next = NULL; /* Unnecessary since slrn_malloc as used
			    * above will guarantee that next->next is NULL.
			    */
	next->prev = l;
	l->next = next;
	l = next;

	strncpy(l->buf, buf_dest, len);
	/* terminate string and strip '\r' if necessary */
	if (len && (l->buf[len-1] == '\r'))
	  len--;

	l->buf[len] = 0;

	buf_dest = buf_pos + 1;
     }

   /* drop */

return_error:

   slrn_free(buf_src);
   slrn_free(base);
}

/*}}}*/

/* This function checks if the last character on curr_line is an = and
 * if it is, then it merges curr_line and curr_line->next. See RFC1341,
 * section 5.1 (Quoted-Printable Content-Transfer-Encoding) rule #5.
 * [csp@ohm.york.ac.uk]
 */
static int merge_if_soft_linebreak (Slrn_Article_Line_Type *curr_line)/*{{{*/
{
   Slrn_Article_Line_Type *next_line;
   char *b;

   while ((next_line = curr_line->next) != NULL)
     {
	unsigned int len;

	b = curr_line->buf;
	len = (unsigned int) (slrn_bskip_whitespace (b) - b);
	if (len == 0) return 0;

	len--;
	if (b[len] != '=') return 0;

	/* Remove the excess = character... */
	b[len] = '\0';

	if (NULL == (b = (char *) SLrealloc (b, 1 + len + strlen (next_line->buf))))
	  return -1;

	curr_line->buf = b;

	strcpy (b + len, next_line->buf); /* safe */

	/* Unlink next_line from the linked list of lines in the article... */
	curr_line->next = next_line->next;
	if (next_line->next != NULL)
	  next_line->next->prev = curr_line;

	SLFREE (next_line->buf);
	SLFREE (next_line);
     }

   /* In case the last line ends with a soft linebreak: */
   b = slrn_bskip_whitespace (curr_line->buf);
   if (b != curr_line->buf)
     {
	b--;
	if (*b == '=')
	  *b = 0;
     }

   return 0;
}

/*}}}*/

static int split_qp_lines (Slrn_Article_Type *a)
{
   Slrn_Article_Line_Type *line;

   line = a->lines;

   /* skip header lines */
   while ((line != NULL)
	  && (line->flags & HEADER_LINE))
     line=line->next;

   while (line != NULL)
     {
	Slrn_Article_Line_Type *new_line, *next;
	char *p = line->buf;
	char *buf0, *buf1;
	char ch;

	next = line->next;

	while ((0 != (ch = *p)) && (ch != '\n'))
	  p++;

	if (ch == 0)
	  {
	     line = next;
	     continue;
	  }
	*p++ = 0;

	new_line = (Slrn_Article_Line_Type *) slrn_malloc (sizeof(Slrn_Article_Line_Type), 1, 1);
	if (new_line == NULL)
	  return -1;

	if (NULL == (buf1 = slrn_strmalloc (p, 1)))
	  {
	     slrn_free ((char *) new_line);
	     return -1;
	  }

	if (NULL == (buf0 = slrn_realloc (line->buf, p - line->buf, 1)))
	  {
	     slrn_free ((char *) new_line);
	     slrn_free (buf1);
	     return -1;
	  }
	line->buf = buf0;

	new_line->buf = buf1;
	new_line->flags = line->flags;
	if (line->flags & QUOTE_LINE)
	  new_line->v.quote_level = line->v.quote_level;

	new_line->next = next;
	new_line->prev = line;
	if (next != NULL)
	  next->prev = new_line;
	line->next = new_line;

	line = new_line;
     }

   return 0;
}

static int decode_mime_quoted_printable (Slrn_Article_Type *a)/*{{{*/
{
   Slrn_Article_Line_Type *line;
   int keep_nl = 1;

   if (a == NULL)
     return -1;

   line = a->lines;

   /* skip to body */
   while ((line != NULL) && (line->flags & HEADER_LINE))
     line = line->next;

   if (line == NULL)
     return 0;

   while (line != NULL)
     {
	char *b;
	unsigned int len;

	b = line->buf;
	len = (unsigned int) (slrn_bskip_whitespace (b) - b);
	if (len && (b[len - 1] == '=')
	    && (line->next != NULL))
	  {
	     (void) merge_if_soft_linebreak (line);
	     b = line->buf;
	     len = strlen (b);
	  }

	b = decode_quoted_printable (b, b, b + len, 0, keep_nl, 1);
	if (b < line->buf + len)
	  {
	     *b = 0;
	     a->is_modified = 1;
	     a->mime.was_modified = 1;
	  }

	line = line->next;
     }

   return split_qp_lines (a);
}

/*}}}*/

void slrn_mime_init (Slrn_Mime_Type *m)/*{{{*/
{
   m->was_modified = 0;
   m->was_parsed = 0;
   m->needs_metamail = 0;
   m->charset = NULL;
   m->content_type = 0;
   m->content_subtype = 0;
}

/*}}}*/

void slrn_mime_free (Slrn_Mime_Type *m)/*{{{*/
{
  if (m->charset != NULL)
    {
       slrn_free(m->charset);
    }
}

/*}}}*/

Slrn_Mime_Error_Obj *slrn_add_mime_error(Slrn_Mime_Error_Obj *list, /*{{{*/
					 char *msg, char *line, int lineno, int critical)
{
   Slrn_Mime_Error_Obj *err, *last;

   err = (Slrn_Mime_Error_Obj *)slrn_safe_malloc (sizeof (Slrn_Mime_Error_Obj));

   if (msg != NULL)
     err->msg = slrn_safe_strmalloc (msg);
   else
     err->msg = NULL;

   if (line != NULL)
     err->err_str = slrn_safe_strmalloc(line);
   else
     err->err_str = NULL;

   err->lineno=lineno;
   err->critical=critical;
   err->next = NULL;
   err->prev = NULL;

   if (list == NULL)
     return err;

   last = list;

   while (last->next != NULL)
     last = last->next;

   last->next = err;
   err->prev = last;

   return list;
}

/*}}}*/

Slrn_Mime_Error_Obj *slrn_mime_error (char *msg, char *line, int lineno, int critical)
{
   return slrn_add_mime_error (NULL, msg, line, lineno, critical);
}

Slrn_Mime_Error_Obj *slrn_mime_concat_errors (Slrn_Mime_Error_Obj *a, Slrn_Mime_Error_Obj *b)
{
   if (a == NULL)
     return b;

   if (b != NULL)
     {
	Slrn_Mime_Error_Obj *next = a;

	while (next->next != NULL)
	  next = next->next;

	next->next = b;
	b->prev = next;
     }
   return a;
}

void slrn_free_mime_error(Slrn_Mime_Error_Obj *obj) /*{{{*/
{
   Slrn_Mime_Error_Obj *tmp;

   while (obj != NULL)
     {
	tmp = obj->next;
	if (obj->err_str != NULL)
	  slrn_free(obj->err_str);
	if (obj->msg != NULL)
	  slrn_free (obj->msg);

	slrn_free((char *) obj);
	obj=tmp;
     }
}

/*}}}*/

static char *guess_body_charset (Slrn_Article_Type *a)
{
   Slrn_Article_Line_Type *line;

   /* FIXME: Add a hook here for the user to specify a character set */

   line = a->lines;

   /* Skip header */
   while ((line != NULL) && (line->flags & HEADER_LINE))
     line = line->next;

   while (line != NULL)
     {
	char *p, ch;

	p = line->buf;
	while (((ch = *p) != 0) && ((ch & 0x80) == 0))
	  p++;

	if (ch == 0)
	  {
	     line = line->next;
	     continue;
	  }

	return slrn_guess_charset (p, p + strlen(p));
     }

   return slrn_strmalloc ("us-ascii", 1);
}

int slrn_mime_process_article (Slrn_Article_Type *a)/*{{{*/
{
   if (a == NULL)
     return -1;

   if (a->mime.was_parsed)
     return 0;

   a->mime.was_parsed = 1;	       /* or will be */

/* Is there a reason to use the following line? */
/*   if (NULL == find_header_line (a, "Mime-Version:")) return;*/
/*   if ((-1 == parse_content_type_line (a))
       || (-1 == parse_content_transfer_encoding_line (a)))*/
#if 1 /* moved */
   rfc1522_decode_headers (a);
#endif
   if (-1 == parse_content_type_line (a))
     {
	a->mime.needs_metamail = 1;
	return 0;
     }

   if ((a->mime.charset == NULL)
       && (NULL == (a->mime.charset = guess_body_charset (a))))
     return -1;
#if 0  /* moved */
   rfc1522_decode_headers (a);
#endif
   switch (parse_content_transfer_encoding_line (a))
     {
      case ENCODED_RAW:
	/*return 0;*/
	/* Now falls through to the identity encoding. */

      case ENCODED_7BIT:
      case ENCODED_8BIT:
      case ENCODED_BINARY:
	/* Already done. */
	break;

      case ENCODED_BASE64:
	decode_mime_base64 (a);
	break;

      case ENCODED_QUOTED:
	if (-1 == decode_mime_quoted_printable (a))
	  return -1;
	break;

      default:
	a->mime.needs_metamail = 1;
	return 0;
     }

   if ((a->mime.needs_metamail == 0) &&
	(slrn_case_strncmp("us-ascii",
			   a->mime.charset,8) != 0) &&
	(slrn_case_strcmp(Slrn_Display_Charset,
			   a->mime.charset) != 0))
     {
	if (-1 == slrn_convert_article(a, Slrn_Display_Charset, a->mime.charset))
	  {
	  }
     }
   return 0;
}

/*}}}*/

#ifndef MAXPATHLEN
#define MAXPATHLEN 1024
#endif

int slrn_mime_call_metamail (void)/*{{{*/
{
#ifdef VMS
   return 0;
#else
   int init = Slrn_TT_Initialized;
   char tempfile [SLRN_MAX_PATH_LEN];
   Slrn_Article_Line_Type *ptr;
   FILE *fp;
   char *tmp, *mm, *cmd;

   if (NULL == Slrn_Current_Article)
     return -1;
   ptr = Slrn_Current_Article->lines;

   if ((Slrn_Use_Meta_Mail == 0)
       || Slrn_Batch
       || (slrn_get_yesno (1, _("Process this MIME article with metamail")) <= 0))
     return 0;

# if defined(__os2__) || defined(__NT__)
   if (NULL == (tmp = getenv ("TMP")))
     tmp = ".";
# else
   tmp = "/tmp";
# endif

   fp = slrn_open_tmpfile_in_dir (tmp, tempfile, sizeof (tempfile));

   if (fp == NULL)
     {
	slrn_error (_("Unable to open tmp file for metamail."));
	return 0;
     }

   while (ptr)
     {
	fputs(ptr->buf, fp);
	putc('\n', fp);
	ptr = ptr->next;
     }
   slrn_fclose(fp);

   mm = Slrn_MetaMail_Cmd;

   if ((mm == NULL)
       || (*mm == 0)
       || (strlen (mm) > SLRN_MAX_PATH_LEN))
     mm = "metamail";

   cmd = slrn_strdup_strcat (mm, " ", tempfile, NULL);

   /* Make sure that metamail has a normal environment */
   slrn_set_display_state (0);

   slrn_posix_system(cmd, 0);
   slrn_delete_file (tempfile);
   slrn_free (cmd);

   printf(_("Press return to continue ..."));
   getchar();
   fflush(stdin); /* get rid of any pending input! */

   slrn_set_display_state (init);
   return 1;
#endif  /* NOT VMS */
}

/*}}}*/

/* -------------------------------------------------------------------------
 * MIME encoding routines.
 * -------------------------------------------------------------------------*/

#define MIME_MEM_ERROR(s) \
   slrn_mime_error(_("Out of memory."), (s), 0, MIME_ERROR_CRIT)
#define MIME_UNKNOWN_ERROR(s) \
   slrn_mime_error(_("Unknown Error."), (s), 0, MIME_ERROR_CRIT)

static void steal_raw_lines (Slrn_Article_Type *a, Slrn_Article_Line_Type *line)
{
   Slrn_Article_Line_Type *rline;

   rline = a->raw_lines;
   line->next = rline;
   if (rline != NULL)
     {
	rline->prev = line;
     }
   a->raw_lines=NULL;
}

/* When this function gets called, the header is already encoded and is in
 * a->lines, whereas the body is in a->raw_lines.  Clearly this needs to be
 * corrected.
 */
Slrn_Mime_Error_Obj *slrn_mime_encode_article (Slrn_Article_Type *a, char *from_charset) /*{{{*/
{
   Slrn_Article_Line_Type *header_sep, *rline;
   int eightbit = 0;
   char *charset;
   unsigned int n, len;

   rline = a->raw_lines;
   while (rline != NULL)
     {
	if (slrn_string_nonascii(rline->buf))
	  {
	     eightbit = 1;
	     rline->flags |= LINE_HAS_8BIT_FLAG;
	  }
	rline = rline->next;
     }

   /* Append header separator line */
   if (NULL == (header_sep = slrn_append_to_header (a, NULL, 0)))
     return MIME_MEM_ERROR("Header separation line");

   if (eightbit == 0)
     {
#if 0
	/* These are unnecessary */
	if ((NULL == slrn_append_header_keyval (a, "Mime-Version", "1.0"))
	    || (NULL == slrn_append_header_keyval (a, "Content-Type", "text/plain; charset=us-ascii"))
	    || (NULL == slrn_append_header_keyval (a, "Content-Transfer-Encoding", "7bit")))
	  return MIME_MEM_ERROR("Mime Headers");
#endif
	steal_raw_lines (a, header_sep);
	return NULL;
     }

   len = 1 + strlen (Slrn_Outgoing_Charset);
   if (NULL == (charset = slrn_malloc (len, 0, 1)))
     return MIME_MEM_ERROR("Mime Headers");

   n = 0;
   while (1)
     {
	int status;
	char *badline = NULL;

	if (-1 == SLextract_list_element (Slrn_Outgoing_Charset, n, ',', charset, len))
	  {
	     slrn_free (charset);
	     return slrn_add_mime_error(NULL, _("Can't determine suitable charset for body"), badline, -1 , MIME_ERROR_CRIT);
	  }

	if (0 == slrn_case_strcmp (charset, from_charset))
	  break; /* No recoding needed */

	status = slrn_test_convert_lines (a->raw_lines, charset, from_charset, &badline);
	if (status == -1)
	  {
	     slrn_free (charset);
	     /* This error message may not be correct */
	     return slrn_add_mime_error(NULL, _("Error encountered while encoding body"), badline, -1, MIME_ERROR_CRIT);
	  }

	if (status == 1)
	  break;		       /* converted ok */

	n++;
     }

   steal_raw_lines (a, header_sep);

   if (((NULL == slrn_find_header_line (a, "Mime-Version"))
	&& (NULL == slrn_append_header_keyval (a, "Mime-Version", "1.0")))
       || ((NULL == slrn_find_header_line (a, "Content-Type"))
	   && (NULL == slrn_append_to_header (a, slrn_strdup_printf ("Content-Type: text/plain; charset=%s", charset),1)))
       || ((NULL == slrn_find_header_line (a, "Content-Transfer-Encoding"))
	   && (NULL == slrn_append_header_keyval (a, "Content-Transfer-Encoding", "8bit"))))
     {
	slrn_free (charset);
	return MIME_MEM_ERROR("Mime Headers");
     }

   slrn_free (charset);
   return NULL;
}

/*}}}*/

#define MAX_CONTINUED_HEADER_SIZE 77   /* does not include leading space char */
#define MAX_RFC2047_WORD_SIZE	75

static char *skip_ascii_whitespace (char *s, char *smax)
{
   while (s < smax)
     {
	char ch = *s;
	if ((ch != ' ') && (ch != '\t') && (ch != '\n'))
	  break;
	s++;
     }
   return s;
}

static char *skip_non_ascii_whitespace (char *s, char *smax)
{
   while (s < smax)
     {
	char ch = *s;
	if ((ch == ' ') || (ch == '\t') || (ch == '\n'))
	  break;
	s++;
     }
   return s;
}

static Slrn_Mime_Error_Obj *fold_line (char **s_ptr, int warn)/*{{{*/
{
   char *s0, *s, *smax;
   int long_words = 0;
   char *folded_text;
   unsigned int line_len;

   s0 = *s_ptr;
   smax = s0 + strlen (s0);

   if (s0 + MAX_CONTINUED_HEADER_SIZE + 1 >= smax)
     return NULL;

   /* skip the first word */
   s = skip_non_ascii_whitespace (s0, smax);
   s = skip_ascii_whitespace (s, smax);

   /* (folding after the keyword is not allowed) */
   /* I'm not sure about that FS */
   /* Play it safe for now */
   s = skip_non_ascii_whitespace (s, smax);

   line_len = s - s0;
   if (line_len >= MAX_CONTINUED_HEADER_SIZE)
     long_words++;

   if (NULL == (folded_text = slrn_strnmalloc (s0, line_len, 1)))
     return MIME_MEM_ERROR(*s_ptr);

   /* Note: RFC-822 states:
    *    Unfolding is accomplished by regarding CRLF immediately
    *    followed by a LWSP-char as equivalent to the LWSP-char.
    * This suggests that we can simply insert newlines before the linear
    * whitespace character.
    */
   s0 = s;
   while (s < smax)
     {
	unsigned int dlen, new_line_len;
	char *tmp, *sep;

	s = skip_ascii_whitespace (s, smax);
	s = skip_non_ascii_whitespace (s, smax);

	dlen = s - s0;
	new_line_len = line_len + dlen;

	if (new_line_len >= MAX_CONTINUED_HEADER_SIZE)
	  {
	     sep = "\n";
	     line_len = 0;
	  }
	else
	  sep = "";

	tmp = slrn_substrjoin (folded_text, NULL, s0, s, sep);
	if (tmp == NULL)
	  {
	     slrn_free (folded_text);
	     return MIME_MEM_ERROR(*s_ptr);
	  }
	slrn_free (folded_text);
	folded_text = tmp;

	s0 = s;
	line_len += dlen;

	if (line_len >= MAX_CONTINUED_HEADER_SIZE)
	  long_words++;
     }

   slrn_free (*s_ptr);
   *s_ptr = folded_text;
   if (long_words && warn)
     return slrn_add_mime_error(NULL, _("One word of the header is too long to get folded."), *s_ptr, 0, MIME_ERROR_WARN);
   else
     return NULL;
}

/*}}}*/

static char *
  rfc1522_encode_word (char *from_charset, char *str, char *strmax,
		       unsigned int max_encoded_size)
{
   /* For a simple single-byte character set, a character is exactly one byte.
    * In such a case, encoding exactly one character is simple.  For a
    * multibyte character set, it is not as simple to determine how many bytes
    * constitute a single character.  For UTF-8, the SLutf8* functions are
    * available for this.  For other charactersets, something like mbrlen
    * would have to be used, but that may not be available on all systems.
    *
    * For this reason, UTF-8 will be used for the character set.
    */
   char *charset = "UTF-8";
   unsigned int max_nbytes;
   unsigned int len_charset;
   char buf[MAX_RFC2047_WORD_SIZE + 1], *b, *b0, *bmax;
   SLuchar_Type *ustr, *u, *ustrmax;
   char *encoded_word = NULL;
   char *tmp;

   if ((NULL == (ustr = (SLuchar_Type *) slrn_convert_string (from_charset, str, strmax, charset, 1))))
     return NULL;

   len_charset = strlen (charset);

   /* The encoding looks like: "=?UTF-8?Q?xx...x?=".  This encoded word has to
    * be less than max_encoded_size.  This means that at most N bytes can be
    * put in the FIRST word where N is given by:
    *
    *    max_encoded_size = 2 + strlen(charset) + 3 + N + 2
    */
   max_nbytes = 7 + len_charset;
   if (max_nbytes + 12 > MAX_RFC2047_WORD_SIZE)
     {
	slrn_error (_("Character set name set is too long."));
	slrn_free ((char *)ustr);
	return NULL;
     }
   /* This will leave 12 bytes to represent a character,
    * which is ok since UTF-8 will use at most 6.
    */
   if (max_nbytes >= max_encoded_size)
     max_nbytes = max_encoded_size;
   max_nbytes = max_encoded_size - max_nbytes;

   (void) SLsnprintf (buf, sizeof(buf), "=?%s?Q?", charset);
   b0 = buf + strlen (buf);

   b = b0;
   bmax = b0 + max_nbytes;

   u = ustr;
   ustrmax = ustr + strlen ((char *)ustr);

   while (u < ustrmax)
     {
	SLuchar_Type ch, *u1;
	unsigned int dnum;
	unsigned int dnbytes;

	ch = *u;
	u1 = SLutf8_skip_chars (u, ustrmax, 1, &dnum, 0);

	dnum = u1 - u;
	if (dnum == 0)
	  break; /* should not happen */

	if (dnum == 1)
	  {
	     dnbytes = 1;
	     if (ch & 0x80) ch = '?';  /* should not have happened */
	     else if (ch == ' ')
	       ch = '_';
	     else if (0 == isalnum (ch))
	       dnbytes = 3;
	  }
	else dnbytes = 3 * dnum;

	if (b + dnbytes >= bmax)
	  {
	     *b++ = '?'; *b++ = '='; *b++ = 0;
	     tmp = slrn_strjoin (encoded_word, buf, " ");
	     if (tmp == NULL)
	       goto return_error;

	     slrn_free (encoded_word);
	     encoded_word = tmp;

	     max_nbytes = MAX_RFC2047_WORD_SIZE - (len_charset+7);
	     b = b0;
	     bmax = b0 + max_nbytes;
	  }

	if (dnbytes == 1)
	  {
	     *b++ = ch;
	     u = u1;
	     continue;
	  }

	while (u < u1)
	  {
	     sprintf (b, "=%02X", (int) *u);
	     b += 3;
	     u++;
	  }
     }

   *b++ = '?'; *b++ = '=';  *b++ = 0;

   if (NULL == (tmp = slrn_strjoin (encoded_word, buf, " ")))
     goto return_error;
   slrn_free ((char *)ustr);
   slrn_free (encoded_word);
   return tmp;

return_error:
   slrn_free ((char *)ustr);
   slrn_free (encoded_word);
   return NULL;
}

/* In this function, encode str between s0 and strmax.  The first word
 * should not be encoded to more than encode_len bytes.  If encode_len is
 * 0, then MAX_RFC2047_WORD_SIZE will be used.
 */
static char *rfc1522_encode_string (char *charset,
				    char *str, char *s0, char *strmax,
				    unsigned int encode_len)
{
   char *s, *encoded_str;
   int encode, last_word_was_encoded;

   if (NULL == (encoded_str = slrn_strnmalloc (str, s0-str, 1)))
     return NULL;

   if (encode_len == 0)
     encode_len = MAX_RFC2047_WORD_SIZE;

   encode = 0;
   last_word_was_encoded = 0;
   s = s0;
   /* Here, whitespace is preserved if possible.
    * Suppose the line looks like:
    *   www eee eee www eee www
    * where www represents a word that will not be encoded, and eee represents
    * one that will be.  The above will be encoded as
    *   WWW "EEE" "_EEE" www "EEE" www
    */
   while (1)
     {
	char ch;

	if ((s == strmax)
	    || ((ch = *s) == ' ') || (ch == '\t') || (ch == '\n'))
	  {
	     char *word, *tmp, *sep = "";

	     if (encode || (s > s0 + encode_len))
	       {
		  word = rfc1522_encode_word (charset, s0, s, encode_len);
		  if (last_word_was_encoded)
		    sep = " ";
		  s0 = s;
		  s = skip_ascii_whitespace (s, strmax);
		  last_word_was_encoded = 1;
		  encode = 0;
	       }
	     else
	       {
		  s = skip_ascii_whitespace (s, strmax);
		  word = slrn_strnmalloc (s0, s-s0, 1);
		  s0 = s;
		  last_word_was_encoded = 0;
	       }

	     if (word == NULL)
	       {
		  slrn_free (encoded_str);
		  return NULL;
	       }

	     tmp = slrn_strjoin (encoded_str, word, sep);
	     slrn_free (word);
	     slrn_free (encoded_str);
	     if (tmp == NULL)
	       return NULL;

	     encoded_str = tmp;
	     encode_len = MAX_RFC2047_WORD_SIZE;

	     if (s0 == strmax)
	       {
		  /* Append the rest of the string */
		  if (*strmax != 0)
		    {
		       tmp = slrn_strjoin (encoded_str, strmax, "");
		       slrn_free (encoded_str);
		       if (tmp == NULL)
			 return NULL;
		       encoded_str = tmp;
		    }
		  break;
	       }

	     continue;
	  }

	if (ch & 0x80)
	  encode = 1;
	s++;
     }

   return encoded_str;
}

/* This function encodes a header, i.e.,  HeaderName: value.... */
/* Try to cause minimal overhead when encoding. */
static Slrn_Mime_Error_Obj *min_encode (char **s_ptr, char *from_charset) /*{{{*/
{
   char *str, *encoded_str, *strmax;
   char *s0, *s, *s1;
   unsigned int encode_len;
   int encode;

   /* This is a quick hack until something more sophisticated comes along */

   str = *s_ptr;
   strmax = str + strlen (str);

   /* Find the start of the field --- no detailed syntax check is performed here */
   s = str;
   while ((s < strmax) && (*s != ':'))
     s++;

   if (s == strmax)
     return slrn_mime_error (_("Header line lacks a colon"), str, 0, MIME_ERROR_CRIT);

   s++; /* skip colon */

   /* And skip leading whitespace */
   s = skip_ascii_whitespace (s, strmax);
   if (s == strmax)
     return NULL;

   if ((s - str) + 12 > MAX_RFC2047_WORD_SIZE)
     encode_len = MAX_RFC2047_WORD_SIZE;
   else
     encode_len = MAX_RFC2047_WORD_SIZE - (s-str);

   s0 = s;			       /* start of keyword-value */

   /* Determine whether or not to decode.  Encode if there are long ascii words
    * or if there are 8-bit characters
    */

   /* Find the size of the first word */
   s1 = skip_non_ascii_whitespace (s0, strmax);

   encode = 0;

   if (s1 >= s0 + encode_len)
     encode = 1;
   else
     {
	/* Look at all the other words */
	while ((s1 < strmax) && (encode == 0))
	  {
	     s = skip_ascii_whitespace (s1, strmax);
	     s1 = skip_non_ascii_whitespace (s, strmax);
	     if (s - s1 > MAX_CONTINUED_HEADER_SIZE)
	       encode = 1;
	  }
     }

   /* Now look for non-ascii characters */
   if (encode == 0)
     {
	s = s0;
	while (s < strmax)
	  {
	     if (*s & 0x80)
	       {
		  encode = 1;
		  break;
	       }
	     s++;
	  }
	if (encode == 0)
	  return NULL;
     }

   if (NULL != (encoded_str = rfc1522_encode_string (from_charset, str, s0, strmax, encode_len)))
     {
	slrn_free (*s_ptr);
	*s_ptr = encoded_str;
	return NULL;
     }

   if (SLang_get_error () == SL_Malloc_Error)
     return MIME_MEM_ERROR(str);

   return MIME_UNKNOWN_ERROR(str);
}
/*}}}*/

static Slrn_Mime_Error_Obj *from_encode (char **s_ptr, char *from_charset)
{
   unsigned int start_offset;
   char *encodemap;
   char *header, *addr, ch;
   char *errmsg;
   unsigned int i0, last_i0, imax;
   char *new_header = NULL;
   unsigned int new_header_len;

   header = *s_ptr;
   start_offset = 0;
   while ((0 != (ch = header[start_offset]))
	  && (ch != ':'))
     start_offset++;

   if (ch != ':')
     return slrn_mime_error (_("A colon is missing from the address header"), *s_ptr, 0, MIME_ERROR_CRIT);

   start_offset++;		       /* skip colon */

   addr = header + start_offset;

   if (NULL == (encodemap = slrn_parse_rfc2822_addr (addr, &errmsg)))
     return slrn_mime_error (errmsg, header, 0, MIME_ERROR_CRIT);

   imax = strlen (encodemap);
   i0 = 0;
   while ((i0 < imax)
	  && (encodemap[i0] == ' '))
     i0++;

   if (i0 == imax)
     {
	slrn_free (encodemap);
	return NULL;
     }

   new_header_len = i0 + start_offset;
   new_header = slrn_strnmalloc (header, new_header_len, 1);
   if (new_header == NULL)
     goto return_error;

   last_i0 = i0;
   while (1)
     {
	char *tmp, *encoded_str, *str;
	unsigned int i1, dlen;

	if ((i0 < imax)
	    && (encodemap[i0] == ' '))
	  {
	     i0++;
	     continue;
	  }

	tmp = slrn_substrjoin (new_header, new_header+new_header_len,
			       addr + last_i0, addr + i0,
			       NULL);
	if (tmp == NULL)
	  goto return_error;

	slrn_free (new_header);
	new_header = tmp;
	new_header_len += i0 - last_i0;

	if (i0 == imax)
	  break;

	i1 = i0 + 1;
	while ((i1 < imax)
	       && (encodemap[i1] != ' '))
	  i1++;

	str = slrn_strnmalloc (addr + i0, i1-i0, 1);
	if (str == NULL)
	  goto return_error;

	encoded_str = rfc1522_encode_string (from_charset, str, str, str+(i1-i0), 0);
	slrn_free (str);

	if (encoded_str == NULL)
	  goto return_error;

	dlen = strlen (encoded_str);
	tmp = slrn_substrjoin (new_header, new_header + new_header_len,
			       encoded_str, encoded_str + dlen, NULL);
	slrn_free (encoded_str);

	if (tmp == NULL)
	  goto return_error;

	slrn_free (new_header);
	new_header = tmp;
	new_header_len += dlen;

	last_i0 = i0 = i1;
     }

   slrn_free (encodemap);
   slrn_free (*s_ptr);
   *s_ptr = new_header;
   return NULL;

return_error:
   if (new_header != NULL)
     slrn_free (new_header);
   if (encodemap != NULL)
     slrn_free (encodemap);

   if (SLang_get_error () == SL_Malloc_Error)
     return MIME_MEM_ERROR(header);

   return MIME_UNKNOWN_ERROR(header);
}

static Slrn_Mime_Error_Obj *fold_xface (char **s_ptr, int warn)
{
   char *s0, *smax;
   char *folded_text;
   unsigned int len;

   (void) warn;

   s0 = *s_ptr;
   len = strlen (s0);
   if (len <= MAX_CONTINUED_HEADER_SIZE)
     return NULL;

   smax = s0 + len;

   len = MAX_CONTINUED_HEADER_SIZE;

   if (NULL == (folded_text = slrn_strnmalloc (s0, len, 1)))
     return MIME_MEM_ERROR(*s_ptr);
   s0 += len;

   while (s0 < smax)
     {
	char *tmp;
	char *s = s0 + len;

	if (s >= smax)
	  s = smax;

	tmp = slrn_substrjoin (folded_text, NULL, s0, s, "\n ");
	if (tmp == NULL)
	  {
	     slrn_free (folded_text);
	     return MIME_MEM_ERROR(*s_ptr);
	  }
	slrn_free (folded_text);
	folded_text = tmp;

	s0 = s;
     }

   slrn_free (*s_ptr);
   *s_ptr = folded_text;
   return NULL;
}

typedef struct
{
   char *keyword;
   Slrn_Mime_Error_Obj *(*encode)(char **, char *);
   Slrn_Mime_Error_Obj *(*fold) (char **, int);
   int warn;
}
Header_Encode_Info_Type;

Header_Encode_Info_Type Header_Encode_Table [] =
{
   {"Newsgroups: ", NULL, fold_line, 1},
   {"Followup-To: ", NULL, fold_line, 1},
   {"Message-ID: ", NULL, fold_line, 1},
   /* Do not warn about long msg-ids in the references.  There is nothing the
    * user can do about it.
    */
   {"References: ", NULL, fold_line, 0},
   {"In-Reply-To: ", NULL, fold_line, 0},

   {"From: ", from_encode, fold_line, 1},
   {"Cc: ", from_encode, fold_line, 1},
   {"To: ", from_encode, fold_line, 1},
   {"Reply-To: ", from_encode, fold_line, 1},
   {"Mail-Copies-To: ", from_encode, fold_line, 1},
   {"X-Face: ", NULL, fold_xface, 1},

   /* This must be the last entry.  It serves as a default */
   {"", min_encode, fold_line, 1},
};

Slrn_Mime_Error_Obj *slrn_mime_header_encode (char **s_ptr, char *from_charset) /*{{{*/
{
   Header_Encode_Info_Type *h;
   char *s = *s_ptr;

   h = Header_Encode_Table;
   while (*h->keyword != 0)
     {
	if (0 == slrn_case_strncmp (s, h->keyword, strlen (h->keyword)))
	  break;
	h++;
     }

   if (h->encode != NULL)
     {
	Slrn_Mime_Error_Obj *err = (*h->encode)(s_ptr, from_charset);
	if (err != NULL)
	  return err;
     }

   if (slrn_string_nonascii (*s_ptr))
     return slrn_mime_error (_("This header contains eight bit characters after encoding"), *s_ptr, 0, MIME_ERROR_CRIT);

   if (h->fold != NULL)
     return (*h->fold) (s_ptr, h->warn);

   return NULL;
}

/*}}}*/

#endif /* NOT SLRNPULL_CODE */