File: mimedecode.c

package info (click to toggle)
mimedecode 1.9-2
  • links: PTS
  • area: main
  • in suites: sarge, woody
  • size: 92 kB
  • ctags: 59
  • sloc: ansic: 989; makefile: 34; sh: 3
file content (1371 lines) | stat: -rw-r--r-- 32,940 bytes parent folder | download
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
/* 
   Copyright (C) 1996 Frederik H. Andersen
                 2002 Darren Salt <linux@youmustbejoking.demon.co.uk>

   This program is free software; you can redistribute it and/or
   modify it under the terms of the GNU General Public License as
   published by the Free Software Foundation; either version 2 of the
   License, or (at your option) any later version.

   This program 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
   General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software Foundation,
   Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. 
*/

/*
 * The original mimedecode came with this license:
 *
 * This program comes with absolutely no guarantees and may
 * be used for whatever purpose,
 *
 * 	Frederik H. Andersen - 1996
 *	Dansk Data Elektronik A/S
 *
 *	fha@dde.dk
 *
 */



/*
 * This program performs the decoding of transfer encoded text type
 * mime messages. The message in its entirety is read from stdin.
 * The decoded message is written to stdout; hence, this program
 * behaves as a filter which may be placed wherever convenient.
 * I particular like it in front of my slocal command in my .forward
 * file.
 *
 * It is assumed that the message has reached its point of final
 * delivery and at that point 8-bit text types can be handled
 * natively. Hence, the need for transfer-encodings is not present
 * any more.
 *
 * Only some cases are handled:
 *      - encoded header fields are decoded from QP or B encoding.
 *        The charset is assumed to be iso-8859-1
 * 	- part or subparts of content-type text only are decoded
 *      - all other content-types are passed transparently
 */

#define USAGE "mimedecode [-h | -d <debug level>] < encoded_msg > decoded_msg"

#include <assert.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>

/* Some defines. Should have gone into a file by itself.
 */
#define MIMED_VERSION "mimedecode version 1.8"

#define FALSE 0
#define TRUE  1

#define lower(c)        ( isupper(c) ? tolower(c) : (c) )

typedef struct boundary_list {
    char *boundary;
    struct boundary_list *next;
} blist;

struct mime_header {
    int content_type;
    int transfer_encoding;
    char *boundary;
};

/* content types: */
#define UNDEF	0
#define TEXT	1
#define MULT    2
#define MESG    3

/* transfer encodings: */
#define QP	1
#define B64	2
#define BIT7	3
#define BIT8	4

#define UN 255

static const unsigned char b64_map[256] =
{
    UN,UN,UN,UN, UN,UN,UN,UN, UN,UN,UN,UN, UN,UN,UN,UN, /* 0x00 - 0x0f, NUL - SI */
    UN,UN,UN,UN, UN,UN,UN,UN, UN,UN,UN,UN, UN,UN,UN,UN, /* 0x10 - 0x1f, DLE - US */
    UN,UN,UN,UN, UN,UN,UN,UN, UN,UN,UN,62, UN,UN,UN,63, /* 0x20 - 0x2f, SP  - / */
    52,53,54,55, 56,57,58,59, 60,61,UN,UN, UN,0x3d,UN,UN, /* 0x30 - 0x3f, 0   - ? */
    UN, 0, 1, 2,  3, 4, 5, 6,  7, 8, 9,10, 11,12,13,14, /* 0x40 - 0x4f, @   - O */
    15,16,17,18, 19,20,21,22, 23,24,25,UN, UN,UN,UN,UN, /* 0x50 - 0x5f, P   - _ */
    UN,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40, /* 0x60 - 0x6f, `   - o */
    41,42,43,44, 45,46,47,48, 49,50,51,UN, UN,UN,UN,UN, /* 0x70 - 0x7f, p   - DEL */

    UN,UN,UN,UN, UN,UN,UN,UN, UN,UN,UN,UN, UN,UN,UN,UN, /* 0x80 - 0x8f */
    UN,UN,UN,UN, UN,UN,UN,UN, UN,UN,UN,UN, UN,UN,UN,UN, /* 0x90 - 0x9f */
    UN,UN,UN,UN, UN,UN,UN,UN, UN,UN,UN,UN, UN,UN,UN,UN, /* 0xA0 - 0xAf */
    UN,UN,UN,UN, UN,UN,UN,UN, UN,UN,UN,UN, UN,UN,UN,UN, /* 0xB0 - 0xBf */
    UN,UN,UN,UN, UN,UN,UN,UN, UN,UN,UN,UN, UN,UN,UN,UN, /* 0xC0 - 0xCf */
    UN,UN,UN,UN, UN,UN,UN,UN, UN,UN,UN,UN, UN,UN,UN,UN, /* 0xD0 - 0xDf */
    UN,UN,UN,UN, UN,UN,UN,UN, UN,UN,UN,UN, UN,UN,UN,UN, /* 0xE0 - 0xEf */
    UN,UN,UN,UN, UN,UN,UN,UN, UN,UN,UN,UN, UN,UN,UN,UN, /* 0xF0 - 0xFf */
};

extern void exit(int);
extern char *optarg;

static int parse_message(char *); 
static int parse_body(int, int, char *);
static int parse_header(struct mime_header *);
static char *decode_header_line(char *);
static void print_state(int);
static int casncmp(const char *, const char *, int);
static int valid_charset(char *, int);
static int decode_quoted_printable(FILE *, FILE *);
static int nextgetc(FILE *);
static int decode_base64(FILE *, FILE *);
static void write_cte(int, int);
static blist *add_to_boundary_list(blist *list, char *boundary);
static int getstr (char **, size_t *, FILE *);

static int debug = 0;
static int header_logging  = FALSE;
static blist *M_boundary_list = NULL;

/*******************************************************************/
int     main(int argc, char *argv[])
/*******************************************************************/
{
     int   c;
     int   ret;

     while((c=getopt(argc, argv, "hd:")) >= 0) {
	switch (c) {
	case    'd':    /* Switch on debugging on stderr */
	    fprintf(stderr, "*** %s ***\n", MIMED_VERSION);
	    debug = atoi(optarg);
	    fprintf(stderr, "Processing with debug: %d\n", debug);
	    fprintf(stderr, "(This might produce voluminous output on stderr.)\n\n");
	    break;

	case	'h':	/* Switch on header logging */
	    header_logging = TRUE;
	    break;

	default:
	    fprintf(stderr,"%s \n", USAGE);
	    exit(1);
	}
     }


     if ((ret = parse_message(0)) != 0) {
	if (debug) fprintf(stderr,"parse of message failed: %d\n", ret);
	exit(1);
     } else
	if (debug) fprintf(stderr,"parse of message complete\n");

     exit(0);
}


static int is_line_end (line)
const char *line;
{
  return line[0] == '\n' || (line[0] == '\r' && line[1] == '\n');
}


static int is_dash_dash_lf (line)
const char *line;
{
  return line[0] == '-' && line[1] == '-' && is_line_end (line + 2);
}

static void dump_blist(blist *list)
{
    blist *ptr = list;
    
    fprintf(stderr, "Boundary list now contains:\n");
    while (ptr)
    {
	fprintf(stderr, "%s\n", ptr->boundary);
	ptr = ptr->next;
    }
}

static blist *add_to_boundary_list(blist *list, char *boundary)
{
    blist *new;
    new = calloc(1, sizeof(blist));
    if(!new)
    {
	fprintf(stderr, "Malloc failed!\n");
	exit(1);
    }
    if(boundary)
	new->boundary = strdup(boundary);
    else
	new->boundary = strdup("");
    new->next = list;

    if(debug > 4)
	dump_blist(new);
    
    return new;
}   

static int compare_boundary(char *linebuf)
{
    blist *ptr = M_boundary_list;

    while(ptr)
    {
	if (debug > 3)
	    fprintf(stderr, "Comparing %s to %s\n", linebuf+2, ptr->boundary);
	if (!strncmp(linebuf+2, ptr->boundary, strlen(ptr->boundary)))
	{
	    if (debug > 3)
		fprintf(stderr, "  matched string\n");
	    return 0;
	}
	if (debug > 3)
	    fprintf(stderr, "  no...\n");
	ptr = ptr->next;
    }
    return 1;
}

/*******************************************************************/
static int parse_message(boundary)
/*******************************************************************/
char   *boundary;
{
    char *linebuf = NULL;
    int lb_alloc = 0;
    struct mime_header mhead;
    int ret;

    if (debug) fprintf(stderr," - Entry parse_message - \n");

    /* parse header */
    if ((ret = parse_header(&mhead)) != 0) {
	if (debug)
	    fprintf(stderr,"parse of message header failed: %d\n", ret);

	return(1);
    }

    /* output the header-body separator: */
    putc('\n', stdout);

    if (mhead.content_type == MULT)
    {
	if (debug >=2 )
	{
	    fprintf(stderr,"message is multipart\n");
	    fprintf(stderr,"search header boundary line: %s\n", mhead.boundary);
	}

	M_boundary_list = add_to_boundary_list(M_boundary_list, mhead.boundary);

	/* search for the boundary line before parsing further */

	while (getstr (&linebuf, &lb_alloc, stdin) != EOF)
	{

		fprintf(stdout,"%s",linebuf);

		if ((linebuf[0] != '-') || (linebuf[1] != '-'))
		    continue;

		if (!compare_boundary(linebuf))
		{
		    if (debug >=2)
		        fprintf(stderr,"header boundary line found\n");

		    break;
		}
	}
	free (linebuf);

	/* When the message is of type multipart we have to handle each
	 * part as an individual message.
	 * We use the boundary to identify the beginning of each part
	 */
	parse_message(mhead.boundary);
    }
    else if(mhead.content_type == MESG)
    {
	/* When message is type message we have to handle the body as
	 * an individual message.
	 */
	parse_message((char *)0);
    }
    else
    {
	if (parse_body(mhead.content_type, mhead.transfer_encoding, boundary)) 
	    parse_message(boundary);
    }
    free (mhead.boundary);
    return(0);
}



/*******************************************************************/
static int parse_body(type, encoding, boundary)
/*******************************************************************/
int  type, encoding;
char *boundary;
{
    int c;
    char *linebuf = 0;
    int lb_alloc = 0;
    int ret = 0;
    int ll = 0;
	
    if (debug) 
	fprintf(stderr," -- Entry parse_body -- \n");
    if (debug >=2) 
	fprintf(stderr," -- type: %d, enc: %d\n",type, encoding);

    if ((type == TEXT) && ((encoding == QP) || (encoding == B64)))
    {
        if (boundary)
        {
	    if (debug >= 2) 
		fprintf(stderr," %d -- with boundary: %s\n",__LINE__,boundary);
	    if (encoding == QP)
	        ret = decode_quoted_printable(stdin, stdout);
	    else if (encoding == B64)
		ret = decode_base64(stdin, stdout);

	    if (ret) 
		return(1);

	    while (getstr (&linebuf, &lb_alloc, stdin) != EOF)
	    {
		    fprintf(stdout,"%s",linebuf);
		    ll = strlen(linebuf);
		    
		    if ((linebuf[0] != '-') || (linebuf[1] != '-'))
		        continue;
		    else if (!compare_boundary(linebuf))
		    {
			if (is_line_end (linebuf + ll - 1) || is_line_end (linebuf + ll - 2))
			{
			    free (linebuf);
			    return(1);
			}
			if (is_dash_dash_lf (linebuf + ll - 3) || is_dash_dash_lf (linebuf + ll -4))
		        {
			    free (linebuf);
		            if (debug >=2 )
		                fprintf(stderr," -- end boundary line found\n");
			    return(2);	/* end boundary found */
		        }
		    }
            }
        }
	else /* no boundary */
	{
	    if (encoding == QP)
	        decode_quoted_printable(stdin, stdout);
	    else if (encoding == B64)
		decode_base64(stdin, stdout);
            return(0);
	}
    }
    else if (boundary)
    {
	if (debug >=2 ) 
	    fprintf(stderr," %d -- with boundary: %s\n",__LINE__,boundary);
	while (getstr (&linebuf, &lb_alloc, stdin) != EOF)
	{
		fprintf(stdout,"%s",linebuf);
		ll = strlen(linebuf);

		if ((linebuf[0] != '-') || (linebuf[1] != '-'))
		    continue;
		else if (!compare_boundary(linebuf))
		{
		    if (is_line_end (linebuf + ll - 1) || is_line_end (linebuf + ll - 2))
		    {
			free (linebuf);
			return(1);
		    }
		    if (is_dash_dash_lf (linebuf + ll - 3) || is_dash_dash_lf (linebuf + ll -4))
		    {
			free (linebuf);
		        if (debug >=2 )
		            fprintf(stderr," -- end boundary line found\n");
			return(2);	/* end boundary found */
		    }
		}
		continue;
        }
        free (linebuf);
    }
    else 
    {
        while ( (c = getc(stdin)) != EOF )
	    putc(c, stdout);
    }
    return(0);
}



/*******************************************************************/
static int parse_header(mhp)
/*******************************************************************/
struct mime_header *mhp;
{
	char *linebuf = NULL;
	int lb_alloc = 0;
	char *nlbp;
	int c;
	char *cp;
	int ct_read;		/* Content-type field read */
	int cte_read;		/* Content-transfer-encoding read */
	int cte_written;	/* Content-transfer-encoding written */


        if (debug) fprintf(stderr," -- Entry parse_header -- \n");

	mhp->content_type = UNDEF;
	mhp->transfer_encoding = UNDEF;
	mhp->boundary = NULL;
	cte_read = FALSE;
	cte_written = FALSE;
	ct_read = FALSE;

again:
	while (getstr (&linebuf, &lb_alloc, stdin) != EOF)
	{
		    if (debug >= 4 )
			fprintf(stderr,"linebuf: %s\n", linebuf);

		    if (!casncmp(linebuf,"content-type:",13))
		    {
			ct_read = TRUE;

			/* we are only doing decoding of text types */
			if (strstr(linebuf, "text/") || strstr(linebuf, "Text/"))
			{
			    if (debug >=3 )
				fprintf(stderr,"Content IS text\n");

			    mhp->content_type = TEXT;
			}
			else if (  strstr(linebuf, "multipart/"))
			{
			    mhp->content_type = MULT;

			    /* search for the boundary parameter */
			    if ((cp = strchr(linebuf, ';')))
                            {
			        /* skip ; and remove white space */
			        cp++;
                                while (*cp == ' ' || *cp == '\t') cp++;
				if (!casncmp(cp,"boundary=",9))
				{
				    char *cp2;
				    cp += 9;
				    if (*cp == '"')
					/* hmm, what about \" ? */
					cp2 = strchr (++cp, '"');
				    else
					cp2 = strchr (cp, ';');
				    if (!cp2)
				    {
					cp2 = cp;
					while (!iscntrl (*cp2) && !isspace (*cp2))
					    cp2++;
				    }
				    mhp->boundary = malloc (cp2 - cp + 1);
				    if (!mhp)
				    {
					free (linebuf);
					return 1;
				    }
				    memcpy (mhp->boundary, cp, cp2 - cp);
				    mhp->boundary[cp2 - cp] = '\0';
				}
			    }
			}
			else if (  strstr(linebuf, "message/"))
			{
			    mhp->content_type = MESG;
			}
		        nlbp = linebuf;
		    } else if (!casncmp(linebuf,"content-transfer-encoding:", 26))
		    {
			cte_read = TRUE;

			/* Remember the encoding in mhp! */
			if ((cp = strchr(linebuf, ':')))
                        {
			    /* skip : and remove white space */
			    cp++;
                            while (*cp == ' ' || *cp == '\t') cp++;

                            if (!casncmp(cp,"quoted-printable",16))
                            {
                                if (debug >= 3)
                                    fprintf(stderr,"Transfer-encoding IS QP\n");
                                mhp->transfer_encoding = QP;
                            }
			    else if (!casncmp(cp,"base64",6))
                            {
                                if (debug >= 3)
                                    fprintf(stderr,"Transfer-encoding IS B64\n");
                                mhp->transfer_encoding = B64;
                            }
			    else if (!casncmp(cp,"7bit",4))
                            {
                                if (debug >= 3)
                                    fprintf(stderr,"Transfer-encoding IS 7bit\n");
                                mhp->transfer_encoding = BIT7;
                            }
			    else if (!casncmp(cp,"8bit",4))
                            {
                                if (debug >= 3)
                                    fprintf(stderr,"Transfer-encoding IS 8bit\n");
                                mhp->transfer_encoding = BIT8;
                            }
                            else {
                                if (debug >= 3)
                                    fprintf(stderr,"Transfer-encoding IS UNKNOWN\n");
				mhp->transfer_encoding = UNDEF;
                            }
                        }
			nlbp = NULL;
	            }
		    else if ((mhp->content_type == MULT) 
			     && strstr(linebuf, "boundary="))
		    {
			char *cp2;
			cp = strstr (linebuf, "boundary=");
			cp += 9;
			if (*cp == '"')
			    /* hmm, what about \" ? */
			    cp2 = strchr (++cp, '"');
			else
			    cp2 = strchr (cp, ';');
			if (!cp2)
			{
			    cp2 = cp;
			    while (!iscntrl (*cp2) && !isspace (*cp2))
				cp2++;
			}
			mhp->boundary = malloc (cp2 - cp + 1);
			if (!mhp)
			{
			    free (linebuf);
			    return 1;
			}
			memcpy (mhp->boundary, cp, cp2 - cp);
			mhp->boundary[cp2 - cp] = '\0';
		        nlbp = linebuf;
		    }
		    else
		    {
		        nlbp = decode_header_line(linebuf);
			if (!nlbp)
			{
			    free (linebuf);
			    return 1;
			}
		    }

		    if (debug >=4)
			fprintf(stderr,"decoded line: %s\n", nlbp);

/* Generally, we will output _all_ lines as they are read (and
 * decoded).  The exception is the Content-transfer-encoding (cte)
 * header line:
 * We will only output cte when the Content-type has been read or
 * when the header/body boundary have been reached.
 */
		    if (nlbp) fprintf(stdout, "%s", nlbp);

		    /* Have we reached the header/body boundary? */
		    if ((c = getc(stdin)) == '\n')
		    {
			/* yes we have! */

			if (debug >= 2)
			    fprintf(stderr,"body reached\n");

			if ( cte_read && !cte_written)
			{
			    if ( !ct_read )
			    {
			        /* Content-type field is missing!! 
			         * Assume text/plain!
			         */
			        if ( debug >=3 )
			           fprintf(stderr,"Content-type field is missing!!\n");
                                fprintf(stdout,"X-Content-type: missing\n");

			        ct_read = TRUE;
			        mhp->content_type = TEXT;
			    }

			    write_cte(mhp->transfer_encoding, mhp->content_type);
                            cte_written = TRUE;
			}
			/* should we output the '\n' here? */
			free (linebuf);
		        return(0);
		    }

		    /* 
		     * We have _not_ reached the header/body boundary
		     */
		    ungetc (c, stdin);
		    if ( ct_read && cte_read & !cte_written )
		    {
			write_cte(mhp->transfer_encoding, mhp->content_type);
                        cte_written = TRUE;
		    }

		    goto again;
	}
	free (linebuf);
	return(1);
}



/*
 * General format of an encoded header field:
 *
 * header_field: <text>=?<charset>?<encoding>?<encoded_chars>?=<text>
 *
 * Disclaimer: We only handle charset of iso-8859-1
 *
 */

#define HUNT	0
#define START	1
#define CHARS	2
#define ENCD	3
#define Q_FIELD	4
#define DEC1	5
#define DEC2	6
#define B_FIELD	7
#define END	8


#define binhex(c) ( (c > '9') ? c-'A'+10 : c-'0')

static char *retbuf = 0;

/*******************************************************************/
static char *decode_header_line(buf)
/*******************************************************************/
char *buf;
{
    int state = HUNT;
    int c, c1, c2, b1, b2, tmp;
    char *charset = 0;
    char *charp = 0;
    char *encoding = 0;
    char *encp = 0;
    int buflen = strlen (buf);
    char *retp = retbuf = realloc (retbuf, buflen + 1);

    if (!retbuf)
	return 0;

    c1 = b1 = 0;
    while ( (c = *buf++) != '\0' ) {
	if ( header_logging == TRUE) print_state(state);

	if (state == HUNT)
	{
		if (c == ' ' || c == '\t' || c == '(') {
			state = START;
			*retp++ = c;
			continue;
		}
	}

	switch (c)	{
		case '=':
		{
			switch (state)	{
			case START:
				if ((tmp = *buf++) == '?') {
					state = CHARS;
					charp = charset = buf;
				} else {
					*retp++ = c;
					*retp++ = tmp;
					state = HUNT;
				}
				continue;

			case CHARS:
				*retp++ = '=';
				*retp++ = '?';
				while (charset < charp) *retp++ = *charset++;
				*retp++ = '=';

				state = HUNT;
				continue;

			case Q_FIELD:
				state = DEC1;
				continue;

			case DEC1:
				*retp++ = '=';
				continue;
			
			case B_FIELD:
				/* padding */
				continue;

			case END:
				state = HUNT;
				continue;
			}
		}
		break;

		case '?':
		{
			switch(state)	{
			case START:
				*retp++ = c;
				state = HUNT;
				continue;

			case CHARS:
				/* we ignore the charset specification, assuming
				 * iso-8859-1
				 */
				if (!valid_charset(charset,charp-charset)) {
					*retp++ = '=';
					*retp++ = '?';
					while (charset < charp) *retp++ = *charset++;
					*retp++ = '?';

					charp = charset;
					state = HUNT;
					continue;
				}

				if (header_logging)
					fprintf(stderr,"charset: %s\n", charset);

				encp = encoding = buf;
				state = ENCD;
				continue;

			case ENCD:
				if (header_logging)
				{
					char ce = *encp;
					*encp = 0;
					fprintf(stderr,"encoding: %s\n",encoding);
					*encp = ce;
				}

				if ((*encoding == 'q') || (*encoding == 'Q'))
				{
					state = Q_FIELD;
				}
				else if ((*encoding == 'b') || (*encoding == 'B'))
				{
				    int c1, c2, c3, c4;

				    state = B_FIELD;

				    while ((*buf != '\0') && (*buf != '\?'))
				    {
					/* find first valid c1 */
					while ((*buf != '\0') && ((c1 = b64_map[(unsigned int)*buf]) == UN))
					    buf++;
					c1 = *buf;

					if (*buf != '\0') buf++;

					/* find second valid c2 */
					while ((*buf != '\0') && ((c2 = b64_map[(unsigned int)*buf]) == UN)) 
					    buf++;
					c2 = *buf;

					if (*buf != '\0') buf++;

					/* find third valid c3 */
					while ((*buf != '\0') && ((c3 = b64_map[(unsigned int)*buf]) == UN)) 
					    buf++;
					c3 = *buf;

					if (*buf != '\0') buf++;

					/* find fourth valid c4 */
					while ((*buf != '\0') && ((c4 = b64_map[(unsigned int)*buf]) == UN)) 
					    buf++;
					c4 = *buf;

					if (*buf != '\0') buf++;

					if ((c1 == '=') || (c2 == '=') || (c1 == '\0') || (c2 == '\0'))
					    {
					    break;
					    }

					*retp++ = ((unsigned int)b64_map[c1] << 2) | (((unsigned int)b64_map[c2]&0x30) >> 4);

					if ((c3 == '=') || (c3 == '\0'))
					    {
					    break;
					    }

					*retp++ = (((unsigned int)b64_map[c2]&0xF) << 4) | (((unsigned int)b64_map[c3]&0x3C) >> 2);

					if ((c4 == '=') || (c4 == '\0'))
					    {
					    break;
					    }

					*retp++ = (((unsigned int)b64_map[c3]&0x3) << 6) | ((unsigned int)b64_map[c4]);
				    }

				    *retp = '\0';
				    if (header_logging)
				    {
					fprintf(stderr,"retbuf: %s\n",retbuf);
				    }
				}
				continue;

			case B_FIELD:
			case Q_FIELD:
				state = END;
				continue;

			case DEC1:
				/* output the consumed char */
				*retp++ = '=';
				state = END;
				continue;

			case DEC2:
				/* output the consumed chars */
				*retp++ = '=';
				*retp++ = c1;
				state = END;
				continue;
			}
		}
		break;

		default:
		{
			if (state == START) {
				*retp++ = c;
				state = HUNT;
				continue;
			}

			if (state == CHARS) {
				charp++;
				continue;
			}

			if (state == ENCD) {
				encp++;
				continue;
			}
			
			if ((state == Q_FIELD) && (c == '_')) {
				*retp++ = ' ';
				continue;
			}

			if (state == DEC1) {
				if (isxdigit(c)) {
					c1 = c;
					c = toupper(c1);
					b1 = binhex(c);
					state = DEC2;
					continue;
				} else {
					*retp++ = '=';
					state = Q_FIELD;
				}
				break;
			}

			if (state == DEC2) {
				if (isxdigit(c)) {
					c2 = toupper(c);
					b2 = binhex(c2);
					c = b1 << 4 | b2;
					*retp++ = c;
					state = Q_FIELD;
					continue;
				} else {
					*retp++ = c1;
					state = Q_FIELD;
				}
				break;
			}

			if (state == END) {
				state = HUNT;
			}
		}
		break;
	}
 	*retp++ = c; 
    }
    if (state != HUNT) {

	*retp++ = '=';
	*retp++ = '?';
	while (*charset) *retp++ = *charset++;
    }
    *retp = '\0';	/* remember the '\0' terminator */
    assert ((retp - retbuf) <= buflen);
    return(retbuf);
}



/*******************************************************************/
static void print_state(state)
/*******************************************************************/
int	state;
{
	switch(state) {
	case	HUNT:
		fprintf(stderr,"state HUNT\n");
		break;

	case	START:
		fprintf(stderr,"state START\n");
		break;

	case	CHARS:
		fprintf(stderr,"state CHARS\n");
		break;

	case	ENCD:
		fprintf(stderr,"state ENCD\n");
		break;

	case	Q_FIELD:
		fprintf(stderr,"state Q_FIELD\n");
		break;

	case	B_FIELD:
		fprintf(stderr,"state B_FIELD\n");
		break;

	case	DEC1:
		fprintf(stderr,"state DEC1\n");
		break;

	case	DEC2:
		fprintf(stderr,"state DEC2\n");
		break;

	case	END:
		fprintf(stderr,"state END\n");
		break;

	default:
		fprintf(stderr,"unknown state; %d\n", state);
		break;
	}
}



/*******************************************************************/
static int casncmp(s1, s2, n)
/*******************************************************************/
register const char *s1, *s2;
register int n;
{
	if (s1 == s2)
		return(0);
	while ((--n >= 0) && (lower(*s1) == lower(*s2))) {
		s2++;
		if (*s1++ == '\0')
			return (0);
	}
	return ((n < 0) ? 0 : (lower(*s1) - lower(*s2)));
}



/*******************************************************************/
static int valid_charset(s,n)
/*******************************************************************/
char *s;
int  n;
{
	if (n < 8) return(0);

	if (n > 8) n=8;

	if (!casncmp(s,"iso-8859", n)) return(1);
	if (!casncmp(s,"us-ascii", n)) return(1);

	return(0);
}



/*******************************************************************/
static int decode_quoted_printable(infp, outfp)
/*******************************************************************/
FILE *infp;
FILE *outfp;
{
    char *linebuf = 0;
    int lb_alloc = 0;
    int c;

    if (debug) 
	fprintf(stderr," --- Entry decode_quoted_print --- \n");

    while (getstr (&linebuf, &lb_alloc, stdin) != EOF)
    {
	    const char *lbp = linebuf;
	    if ((linebuf[0] == '-') && (linebuf[1] == '-'))
	    {
		if (!compare_boundary(linebuf))
		{
		    if (debug >=2)
			fprintf(stderr,"header boundary line found\n");
		    fprintf(stdout,"%s",linebuf);
		    free (linebuf);
		    return(1);
		}
	    }

	    while( (c = *lbp++) != 0)
	    {
                if ( c == '=')	{	/* c == '=' */
                    int c1 = *lbp++;
                    int c2;

                    if (c1 == '\0')
                        break;

                    c2 = *lbp++;
                    if (c2 == '\0')
                        break;


                    /* check for soft CRLF */
                    if (c1 == '\r') {
                       /* this is an error? : c2 = getc(infp); */
                        if (c2 != '\n')         /* not a CRLF */
                            lbp--;   /* put back the char after the =<CR> */
                        break;
                    }

                    /* check for soft newline */
                    if (c1 == '\n')
                        break;

                    /* check for == -> = */
                    if (c1 == '=') {
                        putc(c1, outfp);
                        lbp--;       /* put back the char after the == */
                        continue;
                    }

                    /* make sure it's =XX */
                    if (!isxdigit(c1) || !isxdigit(c2))
                        continue;

                    /* we have two hex digits, so decode them */
                    if (isdigit(c1))
                        c1 -= '0';
                    else if (islower(c1)) {
                        c1 -= 'a';
                        c1 += 10;
                    }
                    else {
                        c1 -= 'A';
                        c1 += 10;
                    }
                    if (isdigit(c2))
                        c2 -= '0';
                    else if (islower(c2)) {
                        c2 -= 'a';
                        c2 += 10;
                    }
                    else {
                        c2 -= 'A';
                        c2 += 10;
                    }
                    putc(((c1 << 4) | c2), outfp);
                }
	        else
	            putc(c, outfp);
            }	/* end while */
    }
    free (linebuf);
    return(0);
}





/*******************************************************************/
static int nextgetc(infp)
/*******************************************************************/
FILE *infp;
{
    int c;
    while ((c = getc(infp)) != EOF)
    {
	if (c == '-')
	{
	    c = getc(infp);
	    if (c == '-')
	    {
		/* Two '-'s in a row - must be a boundary! */
		if (debug >= 2)
		    fprintf(stderr," ----- boundary line found\n");
		return(127);
	    }
	}

        if (b64_map[c] != UN)
            break;
    }
    return c;
}



/*******************************************************************/
static int decode_base64(infp, outfp)
/*******************************************************************/
FILE *infp;
FILE *outfp;
{
    int c1, c2, c3, c4;
    int ret;

    c1 = c2 = c3 = c4 = 0;

    if (debug) fprintf(stderr," --- Entry decode_base64 --- \n");

    for (;;)
    {
	ret = 0;

	if (((c1 = nextgetc(infp)) == 127)
	 || ((c2 = nextgetc(infp)) == 127)
	 || ((c3 = nextgetc(infp)) == 127)
	 || ((c4 = nextgetc(infp)) == 127))
	{
	    if (debug >=2)
		fprintf(stderr," --- header boundary line found: %d\n", ret);
	    putc('-', outfp); putc('-', outfp);
	    return(1);
	}

        if ((c1 == '=') || (c2 == '=') || (c1 == EOF) || (c2 == EOF))
	{
            break;
	}

        putc((((unsigned int)b64_map[c1]<<2) | (((unsigned int)b64_map[c2]&0x30) >>4)), outfp);
        if ((c3 == '=') || (c3 == EOF))
	{
            break;
	}

        putc(((((unsigned int)b64_map[c2]&0XF) << 4) | (((unsigned int)b64_map[c3]&0x3C) >> 2)), outfp);

        if ((c4 == '=') || (c4 == EOF))
	{
            break;
	}

        putc(((((unsigned int)b64_map[c3]&0x03) <<6) | (unsigned int)b64_map[c4]), outfp);
    }
    if (debug >=2)
	fprintf(stderr," --- returned: %d\n", ret);
    return(ret);
}



/*******************************************************************/
static void write_cte(transfer_encoding, content_type)
/*******************************************************************/
int transfer_encoding, content_type;
{
    if (content_type == TEXT)
    {
        switch (transfer_encoding) {
	case QP:
	    fprintf(stdout,"X-Content-transfer-encoding: fixed from quoted-printable\n");
	    fprintf(stdout,"Content-Transfer-Encoding: 8bit\n");
	    break;

	case B64:
	    fprintf(stdout,"X-Content-transfer-encoding: fixed from base64\n");
	    fprintf(stdout,"Content-Transfer-Encoding: 8bit\n");
	    break;

	case BIT7:
	    fprintf(stdout,"Content-Transfer-Encoding: 7bit\n");
	    break;

	case BIT8:
	    fprintf(stdout,"Content-Transfer-Encoding: 8bit\n");
	    break;

	default:
	    if (debug >= 3)
		fprintf(stderr,"Transfer-encoding is UNKNOWN\n");
	    break;
	}
    } else /* ! TEXT */
    {
	/* remember to output the Content-transfer-encoding
	 * header field in case type is NOT text.
	 */
	switch (transfer_encoding) {
	case QP:
	    fprintf(stdout,"Content-Transfer-Encoding: quoted-printable\n");
	    break;

	case B64:
	    fprintf(stdout,"Content-Transfer-Encoding: base64\n");
	    break;

	case BIT7:
	    fprintf(stdout,"Content-Transfer-Encoding: 7bit\n");
	    break;

	case BIT8:
	    fprintf(stdout,"Content-Transfer-Encoding: 8bit\n");
	    break;
	}
    }
}


/* The following is adapted from getstr() (textutils). */
/* getstr.c -- core function for GNU C library getline replacement function

   Copyright (C) 1993, 1996-2001 Free Software Foundation, Inc.

   This program is free software; you can redistribute it and/or
   modify it under the terms of the GNU General Public License as
   published by the Free Software Foundation; either version 2 of the
   License, or (at your option) any later version.

   This program 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
   General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software Foundation,
   Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

   Written by Jan Brittenson, bson@gnu.ai.mit.edu.  */

#define MIN_CHUNK 64

/* Read up to end of line from STREAM into *LINEPTR (and NUL-terminate it).
   *LINEPTR is a pointer returned from malloc (or NULL), pointing to *N
   characters of space. It is realloc'd as necessary. Return the number of
   characters read (not including the NUL terminator), or -1 on error or EOF.
 */

static int
getstr (char **lineptr, size_t *n, FILE *stream)
{
  int nchars_avail;		/* Allocated but unused chars in *LINEPTR.  */
  char *read_pos;		/* Where we're reading into *LINEPTR. */
  int ret;

  if (!lineptr || !n || !stream)
    return -1;

  if (!*lineptr)
    {
      *n = MIN_CHUNK;
      *lineptr = malloc (*n);
      if (!*lineptr)
	return -1;
    }

  nchars_avail = *n;
  read_pos = *lineptr;

  for (;;)
    {
      register int c = getc (stream);

      /* We always want at least one char left in the buffer, since we
	 always (unless we get an error while reading the first char)
	 NUL-terminate the line buffer.  */

      assert(*n - nchars_avail == read_pos - *lineptr);
      if (nchars_avail < 2)
	{
	  if (*n > MIN_CHUNK)
	    *n *= 2;
	  else
	    *n += MIN_CHUNK;

	  nchars_avail = *n + *lineptr - read_pos;
	  *lineptr = realloc (*lineptr, *n);
	  if (!*lineptr)
	    return -1;
	  read_pos = *n - nchars_avail + *lineptr;
	  assert(*n - nchars_avail == read_pos - *lineptr);
	}

      if (c == EOF || ferror (stream))
	{
	  /* Return partial line, if any.  */
	  if (read_pos == *lineptr)
	    return -1;
	  else
	    break;
	}

      *read_pos++ = c;
      nchars_avail--;

      if (c == '\n')
        /* Return the line.  */
	break;
    }

  /* Done - NUL terminate and return the number of chars read.  */
  *read_pos = '\0';

  ret = read_pos - *lineptr;
  return ret;
}