]> diplodocus.org Git - nmh/blob - uip/mhparse.c
0be13294926e323b671dfe567033d258a88fa51d
[nmh] / uip / mhparse.c
1 /* mhparse.c -- routines to parse the contents of MIME messages
2 *
3 * This code is Copyright (c) 2002, by the authors of nmh. See the
4 * COPYRIGHT file in the root directory of the nmh distribution for
5 * complete copyright information.
6 */
7
8 #include <h/mh.h>
9 #include <fcntl.h>
10 #include <h/md5.h>
11 #include <h/mts.h>
12 #include <h/tws.h>
13 #include <h/mime.h>
14 #include <h/mhparse.h>
15 #include <h/utils.h>
16 #include "../sbr/m_mktemp.h"
17 #include "mhfree.h"
18 #ifdef HAVE_ICONV
19 # include <iconv.h>
20 #endif /* HAVE_ICONV */
21
22
23 extern int debugsw;
24
25 /* cache policies */
26 extern int rcachesw; /* mhcachesbr.c */
27 extern int wcachesw; /* mhcachesbr.c */
28
29 int checksw = 0; /* check Content-MD5 field */
30
31 /*
32 * These are for mhfixmsg to:
33 * 1) Instruct parser not to detect invalid Content-Transfer-Encoding
34 * in a multipart.
35 * 2) Suppress the warning about bogus multipart content, and report it.
36 * 3) Suppress the warning about extraneous trailing ';' in header parameter
37 * lists.
38 */
39 int skip_mp_cte_check;
40 int suppress_bogus_mp_content_warning;
41 int bogus_mp_content;
42 int suppress_extraneous_trailing_semicolon_warning;
43
44 /*
45 * By default, suppress warning about multiple MIME-Version header fields.
46 */
47 int suppress_multiple_mime_version_warning = 1;
48
49 /* list of preferred type/subtype pairs, for -prefer */
50 char *preferred_types[NPREFS],
51 *preferred_subtypes[NPREFS];
52 int npreferred;
53
54
55 /*
56 * Structures for TEXT messages
57 */
58 struct k2v SubText[] = {
59 { "plain", TEXT_PLAIN },
60 { "richtext", TEXT_RICHTEXT }, /* defined in RFC 1341 */
61 { "enriched", TEXT_ENRICHED }, /* defined in RFC 1896 */
62 { NULL, TEXT_UNKNOWN } /* this one must be last! */
63 };
64
65 /* Charset[] removed -- yozo. Mon Oct 8 01:03:41 JST 2012 */
66
67 /*
68 * Structures for MULTIPART messages
69 */
70 struct k2v SubMultiPart[] = {
71 { "mixed", MULTI_MIXED },
72 { "alternative", MULTI_ALTERNATE },
73 { "digest", MULTI_DIGEST },
74 { "parallel", MULTI_PARALLEL },
75 { "related", MULTI_RELATED },
76 { NULL, MULTI_UNKNOWN } /* this one must be last! */
77 };
78
79 /*
80 * Structures for MESSAGE messages
81 */
82 struct k2v SubMessage[] = {
83 { "rfc822", MESSAGE_RFC822 },
84 { "partial", MESSAGE_PARTIAL },
85 { "external-body", MESSAGE_EXTERNAL },
86 { NULL, MESSAGE_UNKNOWN } /* this one must be last! */
87 };
88
89 /*
90 * Structure for APPLICATION messages
91 */
92 struct k2v SubApplication[] = {
93 { "octet-stream", APPLICATION_OCTETS },
94 { "postscript", APPLICATION_POSTSCRIPT },
95 { NULL, APPLICATION_UNKNOWN } /* this one must be last! */
96 };
97
98 /*
99 * Mapping of names of CTE types in mhbuild directives
100 */
101 static struct k2v EncodingType[] = {
102 { "8bit", CE_8BIT },
103 { "qp", CE_QUOTED },
104 { "q-p", CE_QUOTED },
105 { "quoted-printable", CE_QUOTED },
106 { "b64", CE_BASE64 },
107 { "base64", CE_BASE64 },
108 { NULL, 0 },
109 };
110
111
112 /* mhcachesbr.c */
113 int find_cache (CT, int, int *, char *, char *, int);
114
115 /* mhmisc.c */
116 int part_ok (CT);
117 int type_ok (CT, int);
118 void content_error (char *, CT, char *, ...);
119
120 /*
121 * static prototypes
122 */
123 static CT get_content (FILE *, char *, int);
124 static int get_comment (const char *, const char *, char **, char **);
125
126 static int InitGeneric (CT);
127 static int InitText (CT);
128 static int InitMultiPart (CT);
129 static void reverse_parts (CT);
130 static void prefer_parts(CT ct);
131 static int InitMessage (CT);
132 static int InitApplication (CT);
133 static int init_encoding (CT, OpenCEFunc);
134 static unsigned long size_encoding (CT);
135 static int InitBase64 (CT);
136 static int openBase64 (CT, char **);
137 static int InitQuoted (CT);
138 static int openQuoted (CT, char **);
139 static int Init7Bit (CT);
140 static int openExternal (CT, CT, CE, char **, int *);
141 static int InitFile (CT);
142 static int openFile (CT, char **);
143 static int InitFTP (CT);
144 static int openFTP (CT, char **);
145 static int InitMail (CT);
146 static int openMail (CT, char **);
147 static int readDigest (CT, char *);
148 static int get_leftover_mp_content (CT, int);
149 static int InitURL (CT);
150 static int openURL (CT, char **);
151 static int parse_header_attrs (const char *, const char *, char **, PM *,
152 PM *, char **);
153 static size_t param_len(PM, int, size_t, int *, int *, size_t *);
154 static size_t normal_param(PM, char *, size_t, size_t, size_t);
155 static int get_dispo (char *, CT, int);
156
157 struct str2init str2cts[] = {
158 { "application", CT_APPLICATION, InitApplication },
159 { "audio", CT_AUDIO, InitGeneric },
160 { "image", CT_IMAGE, InitGeneric },
161 { "message", CT_MESSAGE, InitMessage },
162 { "multipart", CT_MULTIPART, InitMultiPart },
163 { "text", CT_TEXT, InitText },
164 { "video", CT_VIDEO, InitGeneric },
165 { NULL, CT_EXTENSION, NULL }, /* these two must be last! */
166 { NULL, CT_UNKNOWN, NULL },
167 };
168
169 struct str2init str2ces[] = {
170 { "base64", CE_BASE64, InitBase64 },
171 { "quoted-printable", CE_QUOTED, InitQuoted },
172 { "8bit", CE_8BIT, Init7Bit },
173 { "7bit", CE_7BIT, Init7Bit },
174 { "binary", CE_BINARY, Init7Bit },
175 { NULL, CE_EXTENSION, NULL }, /* these two must be last! */
176 { NULL, CE_UNKNOWN, NULL },
177 };
178
179 /*
180 * NOTE WELL: si_key MUST NOT have value of NOTOK
181 *
182 * si_key is 1 if access method is anonymous.
183 */
184 struct str2init str2methods[] = {
185 { "afs", 1, InitFile },
186 { "anon-ftp", 1, InitFTP },
187 { "ftp", 0, InitFTP },
188 { "local-file", 0, InitFile },
189 { "mail-server", 0, InitMail },
190 { "url", 0, InitURL },
191 { NULL, 0, NULL }
192 };
193
194
195 /*
196 * Main entry point for parsing a MIME message or file.
197 * It returns the Content structure for the top level
198 * entity in the file.
199 */
200
201 CT
202 parse_mime (char *file)
203 {
204 int is_stdin;
205 char buffer[BUFSIZ];
206 FILE *fp;
207 CT ct;
208 size_t n;
209 struct stat statbuf;
210
211 bogus_mp_content = 0;
212
213 /*
214 * Check if file is actually standard input
215 */
216 if ((is_stdin = !(strcmp (file, "-")))) {
217 char *tfile = m_mktemp2(NULL, invo_name, NULL, &fp);
218 if (tfile == NULL) {
219 advise("mhparse", "unable to create temporary file in %s",
220 get_temp_dir());
221 return NULL;
222 }
223 file = mh_xstrdup(tfile);
224
225 while ((n = fread(buffer, 1, sizeof(buffer), stdin)) > 0) {
226 if (fwrite(buffer, 1, n, fp) != n) {
227 (void) m_unlink (file);
228 advise (file, "error copying to temporary file");
229 return NULL;
230 }
231 }
232 fflush (fp);
233
234 if (ferror (stdin)) {
235 (void) m_unlink (file);
236 advise ("stdin", "error reading");
237 return NULL;
238 }
239 if (ferror (fp)) {
240 (void) m_unlink (file);
241 advise (file, "error writing");
242 return NULL;
243 }
244 fseek (fp, 0L, SEEK_SET);
245 } else if (stat (file, &statbuf) == NOTOK) {
246 advise (file, "unable to stat");
247 return NULL;
248 } else if (S_ISDIR(statbuf.st_mode)) {
249 /* Don't try to parse a directory. */
250 inform("%s is a directory", file);
251 return NULL;
252 } else if ((fp = fopen (file, "r")) == NULL) {
253 advise (file, "unable to read");
254 return NULL;
255 }
256
257 if (!(ct = get_content (fp, file, 1))) {
258 if (is_stdin)
259 (void) m_unlink (file);
260 inform("unable to decode %s", file);
261 return NULL;
262 }
263
264 if (is_stdin)
265 ct->c_unlink = 1; /* temp file to remove */
266
267 ct->c_fp = NULL;
268
269 if (ct->c_end == 0L) {
270 fseek (fp, 0L, SEEK_END);
271 ct->c_end = ftell (fp);
272 }
273
274 if (ct->c_ctinitfnx && (*ct->c_ctinitfnx) (ct) == NOTOK) {
275 fclose (fp);
276 free_content (ct);
277 return NULL;
278 }
279
280 fclose (fp);
281 return ct;
282 }
283
284
285 /*
286 * Main routine for reading/parsing the headers
287 * of a message content.
288 *
289 * toplevel = 1 # we are at the top level of the message
290 * toplevel = 0 # we are inside message type or multipart type
291 * # other than multipart/digest
292 * toplevel = -1 # we are inside multipart/digest
293 * NB: on failure we will fclose(in)!
294 */
295
296 static CT
297 get_content (FILE *in, char *file, int toplevel)
298 {
299 int compnum, state;
300 char buf[NMH_BUFSIZ], name[NAMESZ];
301 char *np, *vp;
302 CT ct;
303 HF hp;
304 m_getfld_state_t gstate = 0;
305
306 /* allocate the content structure */
307 NEW0(ct);
308 ct->c_fp = in;
309 ct->c_file = add (file, NULL);
310 ct->c_begin = ftell (ct->c_fp) + 1;
311
312 /*
313 * Parse the header fields for this
314 * content into a linked list.
315 */
316 m_getfld_track_filepos (&gstate, in);
317 for (compnum = 1;;) {
318 int bufsz = sizeof buf;
319 switch (state = m_getfld (&gstate, name, buf, &bufsz, in)) {
320 case FLD:
321 case FLDPLUS:
322 compnum++;
323
324 /* get copies of the buffers */
325 np = mh_xstrdup(name);
326 vp = mh_xstrdup(buf);
327
328 /* if necessary, get rest of field */
329 while (state == FLDPLUS) {
330 bufsz = sizeof buf;
331 state = m_getfld (&gstate, name, buf, &bufsz, in);
332 vp = add (buf, vp); /* add to previous value */
333 }
334
335 /* Now add the header data to the list */
336 add_header (ct, np, vp);
337
338 /* continue, to see if this isn't the last header field */
339 ct->c_begin = ftell (in) + 1;
340 continue;
341
342 case BODY:
343 if (name[0] == ':') {
344 /* Special case: no blank line between header and body. The
345 file position indicator is on the newline at the end of the
346 line, but it needs to be one prior to the beginning of the
347 line. So subtract the length of the line, bufsz, plus 1. */
348 ct->c_begin = ftell (in) - (bufsz + 1);
349 } else {
350 ct->c_begin = ftell (in) - (bufsz - 1);
351 }
352 break;
353
354 case FILEEOF:
355 ct->c_begin = ftell (in);
356 break;
357
358 case LENERR:
359 case FMTERR:
360 adios (NULL, "message format error in component #%d", compnum);
361
362 default:
363 adios (NULL, "getfld() returned %d", state);
364 }
365
366 /* break out of the loop */
367 break;
368 }
369 m_getfld_state_destroy (&gstate);
370
371 /*
372 * Read the content headers. We will parse the
373 * MIME related header fields into their various
374 * structures and set internal flags related to
375 * content type/subtype, etc.
376 */
377
378 hp = ct->c_first_hf; /* start at first header field */
379 while (hp) {
380 /* Get MIME-Version field */
381 if (!strcasecmp (hp->name, VRSN_FIELD)) {
382 int ucmp;
383 char c, *cp, *dp;
384 char *vrsn;
385
386 vrsn = add (hp->value, NULL);
387
388 /* Now, cleanup this field */
389 cp = vrsn;
390
391 while (isspace ((unsigned char) *cp))
392 cp++;
393 for (dp = strchr(cp, '\n'); dp; dp = strchr(dp, '\n'))
394 *dp++ = ' ';
395 for (dp = cp + strlen (cp) - 1; dp >= cp; dp--)
396 if (!isspace ((unsigned char) *dp))
397 break;
398 *++dp = '\0';
399 if (debugsw)
400 fprintf (stderr, "%s: %s\n", VRSN_FIELD, cp);
401
402 if (*cp == '(' &&
403 get_comment (ct->c_file, VRSN_FIELD, &cp, NULL) == NOTOK)
404 goto out;
405
406 for (dp = cp; istoken (*dp); dp++)
407 continue;
408 c = *dp;
409 *dp = '\0';
410 ucmp = !strcasecmp (cp, VRSN_VALUE);
411 *dp = c;
412 if (!ucmp) {
413 inform("message %s has unknown value for %s: field (%s), continuing...",
414 ct->c_file, VRSN_FIELD, cp);
415 }
416 if (!ct->c_vrsn) {
417 ct->c_vrsn = vrsn;
418 } else {
419 if (! suppress_multiple_mime_version_warning)
420 inform("message %s has multiple %s: fields",
421 ct->c_file, VRSN_FIELD);
422 free(vrsn);
423 }
424 }
425 else if (!strcasecmp (hp->name, TYPE_FIELD)) {
426 /* Get Content-Type field */
427 struct str2init *s2i;
428 CI ci = &ct->c_ctinfo;
429
430 /* Check if we've already seen a Content-Type header */
431 if (ct->c_ctline) {
432 inform("message %s has multiple %s: fields",
433 ct->c_file, TYPE_FIELD);
434 goto next_header;
435 }
436
437 /* Parse the Content-Type field */
438 if (get_ctinfo (hp->value, ct, 0) == NOTOK)
439 goto out;
440
441 /*
442 * Set the Init function and the internal
443 * flag for this content type.
444 */
445 for (s2i = str2cts; s2i->si_key; s2i++)
446 if (!strcasecmp (ci->ci_type, s2i->si_key))
447 break;
448 if (!s2i->si_key && !uprf (ci->ci_type, "X-"))
449 s2i++;
450 ct->c_type = s2i->si_val;
451 ct->c_ctinitfnx = s2i->si_init;
452 }
453 else if (!strcasecmp (hp->name, ENCODING_FIELD)) {
454 /* Get Content-Transfer-Encoding field */
455 char c, *cp, *dp;
456 struct str2init *s2i;
457
458 /*
459 * Check if we've already seen the
460 * Content-Transfer-Encoding field
461 */
462 if (ct->c_celine) {
463 inform("message %s has multiple %s: fields",
464 ct->c_file, ENCODING_FIELD);
465 goto next_header;
466 }
467
468 /* get copy of this field */
469 ct->c_celine = cp = add (hp->value, NULL);
470
471 while (isspace ((unsigned char) *cp))
472 cp++;
473 for (dp = cp; istoken (*dp); dp++)
474 continue;
475 c = *dp;
476 *dp = '\0';
477
478 /*
479 * Find the internal flag and Init function
480 * for this transfer encoding.
481 */
482 for (s2i = str2ces; s2i->si_key; s2i++)
483 if (!strcasecmp (cp, s2i->si_key))
484 break;
485 if (!s2i->si_key && !uprf (cp, "X-"))
486 s2i++;
487 *dp = c;
488 ct->c_encoding = s2i->si_val;
489
490 /* Call the Init function for this encoding */
491 if (s2i->si_init && (*s2i->si_init) (ct) == NOTOK)
492 goto out;
493 }
494 else if (!strcasecmp (hp->name, MD5_FIELD)) {
495 /* Get Content-MD5 field */
496 char *cp, *dp, *ep;
497
498 if (!checksw)
499 goto next_header;
500
501 if (ct->c_digested) {
502 inform("message %s has multiple %s: fields",
503 ct->c_file, MD5_FIELD);
504 goto next_header;
505 }
506
507 ep = cp = add (hp->value, NULL); /* get a copy */
508
509 while (isspace ((unsigned char) *cp))
510 cp++;
511 for (dp = strchr(cp, '\n'); dp; dp = strchr(dp, '\n'))
512 *dp++ = ' ';
513 for (dp = cp + strlen (cp) - 1; dp >= cp; dp--)
514 if (!isspace ((unsigned char) *dp))
515 break;
516 *++dp = '\0';
517 if (debugsw)
518 fprintf (stderr, "%s: %s\n", MD5_FIELD, cp);
519
520 if (*cp == '(' &&
521 get_comment (ct->c_file, MD5_FIELD, &cp, NULL) == NOTOK) {
522 free (ep);
523 goto out;
524 }
525
526 for (dp = cp; *dp && !isspace ((unsigned char) *dp); dp++)
527 continue;
528 *dp = '\0';
529
530 readDigest (ct, cp);
531 free (ep);
532 ct->c_digested++;
533 }
534 else if (!strcasecmp (hp->name, ID_FIELD)) {
535 /* Get Content-ID field */
536 ct->c_id = add (hp->value, ct->c_id);
537 }
538 else if (!strcasecmp (hp->name, DESCR_FIELD)) {
539 /* Get Content-Description field */
540 ct->c_descr = add (hp->value, ct->c_descr);
541 }
542 else if (!strcasecmp (hp->name, DISPO_FIELD)) {
543 /* Get Content-Disposition field */
544 if (get_dispo(hp->value, ct, 0) == NOTOK)
545 goto out;
546 }
547
548 next_header:
549 hp = hp->next; /* next header field */
550 }
551
552 /*
553 * Check if we saw a Content-Type field.
554 * If not, then assign a default value for
555 * it, and the Init function.
556 */
557 if (!ct->c_ctline) {
558 /*
559 * If we are inside a multipart/digest message,
560 * so default type is message/rfc822
561 */
562 if (toplevel < 0) {
563 if (get_ctinfo ("message/rfc822", ct, 0) == NOTOK)
564 goto out;
565 ct->c_type = CT_MESSAGE;
566 ct->c_ctinitfnx = InitMessage;
567 } else {
568 /*
569 * Else default type is text/plain
570 */
571 if (get_ctinfo ("text/plain", ct, 0) == NOTOK)
572 goto out;
573 ct->c_type = CT_TEXT;
574 ct->c_ctinitfnx = InitText;
575 }
576 }
577
578 /* Use default Transfer-Encoding, if necessary */
579 if (!ct->c_celine) {
580 ct->c_encoding = CE_7BIT;
581 Init7Bit (ct);
582 }
583
584 return ct;
585
586 out:
587 free_content (ct);
588 return NULL;
589 }
590
591
592 /*
593 * small routine to add header field to list
594 */
595
596 int
597 add_header (CT ct, char *name, char *value)
598 {
599 HF hp;
600
601 /* allocate header field structure */
602 NEW(hp);
603
604 /* link data into header structure */
605 hp->name = name;
606 hp->value = value;
607 hp->next = NULL;
608
609 /* link header structure into the list */
610 if (ct->c_first_hf == NULL) {
611 ct->c_first_hf = hp; /* this is the first */
612 ct->c_last_hf = hp;
613 } else {
614 ct->c_last_hf->next = hp; /* add it to the end */
615 ct->c_last_hf = hp;
616 }
617
618 return 0;
619 }
620
621
622 /*
623 * Parse Content-Type line and (if `magic' is non-zero) mhbuild composition
624 * directives. Fills in the information of the CTinfo structure.
625 */
626 int
627 get_ctinfo (char *cp, CT ct, int magic)
628 {
629 char *dp;
630 char c;
631 CI ci;
632 int status;
633
634 ci = &ct->c_ctinfo;
635
636 /* store copy of Content-Type line */
637 cp = ct->c_ctline = add (cp, NULL);
638
639 while (isspace ((unsigned char) *cp)) /* trim leading spaces */
640 cp++;
641
642 /* change newlines to spaces */
643 for (dp = strchr(cp, '\n'); dp; dp = strchr(dp, '\n'))
644 *dp++ = ' ';
645
646 /* trim trailing spaces */
647 for (dp = cp + strlen (cp) - 1; dp >= cp; dp--)
648 if (!isspace ((unsigned char) *dp))
649 break;
650 *++dp = '\0';
651
652 if (debugsw)
653 fprintf (stderr, "%s: %s\n", TYPE_FIELD, cp);
654
655 if (*cp == '(' && get_comment (ct->c_file, TYPE_FIELD, &cp,
656 &ci->ci_comment) == NOTOK)
657 return NOTOK;
658
659 for (dp = cp; istoken (*dp); dp++)
660 continue;
661 c = *dp;
662 *dp = '\0';
663 ci->ci_type = mh_xstrdup(cp); /* store content type */
664 *dp = c;
665 cp = dp;
666
667 if (!*ci->ci_type) {
668 inform("invalid %s: field in message %s (empty type)",
669 TYPE_FIELD, ct->c_file);
670 return NOTOK;
671 }
672 to_lower(ci->ci_type);
673
674 while (isspace ((unsigned char) *cp))
675 cp++;
676
677 if (*cp == '(' && get_comment (ct->c_file, TYPE_FIELD, &cp,
678 &ci->ci_comment) == NOTOK)
679 return NOTOK;
680
681 if (*cp != '/') {
682 if (!magic)
683 ci->ci_subtype = mh_xstrdup("");
684 goto magic_skip;
685 }
686
687 cp++;
688 while (isspace ((unsigned char) *cp))
689 cp++;
690
691 if (*cp == '(' && get_comment (ct->c_file, TYPE_FIELD, &cp,
692 &ci->ci_comment) == NOTOK)
693 return NOTOK;
694
695 for (dp = cp; istoken (*dp); dp++)
696 continue;
697 c = *dp;
698 *dp = '\0';
699 ci->ci_subtype = mh_xstrdup(cp); /* store the content subtype */
700 *dp = c;
701 cp = dp;
702
703 if (!*ci->ci_subtype) {
704 inform("invalid %s: field in message %s (empty subtype for \"%s\")",
705 TYPE_FIELD, ct->c_file, ci->ci_type);
706 return NOTOK;
707 }
708 to_lower(ci->ci_subtype);
709
710 magic_skip:
711 while (isspace ((unsigned char) *cp))
712 cp++;
713
714 if (*cp == '(' && get_comment (ct->c_file, TYPE_FIELD, &cp,
715 &ci->ci_comment) == NOTOK)
716 return NOTOK;
717
718 if ((status = parse_header_attrs (ct->c_file, TYPE_FIELD, &cp,
719 &ci->ci_first_pm, &ci->ci_last_pm,
720 &ci->ci_comment)) != OK) {
721 return status == NOTOK ? NOTOK : OK;
722 }
723
724 /*
725 * Get any <Content-Id> given in buffer
726 */
727 if (magic && *cp == '<') {
728 mh_xfree(ct->c_id);
729 ct->c_id = NULL;
730 if (!(dp = strchr(ct->c_id = ++cp, '>'))) {
731 inform("invalid ID in message %s", ct->c_file);
732 return NOTOK;
733 }
734 c = *dp;
735 *dp = '\0';
736 if (*ct->c_id)
737 ct->c_id = concat ("<", ct->c_id, ">\n", NULL);
738 else
739 ct->c_id = NULL;
740 *dp++ = c;
741 cp = dp;
742
743 while (isspace ((unsigned char) *cp))
744 cp++;
745 }
746
747 /*
748 * Get any [Content-Description] given in buffer.
749 */
750 if (magic && *cp == '[') {
751 ct->c_descr = ++cp;
752 for (dp = cp + strlen (cp) - 1; dp >= cp; dp--)
753 if (*dp == ']')
754 break;
755 if (dp < cp) {
756 inform("invalid description in message %s", ct->c_file);
757 ct->c_descr = NULL;
758 return NOTOK;
759 }
760
761 c = *dp;
762 *dp = '\0';
763 if (*ct->c_descr)
764 ct->c_descr = concat (ct->c_descr, "\n", NULL);
765 else
766 ct->c_descr = NULL;
767 *dp++ = c;
768 cp = dp;
769
770 while (isspace ((unsigned char) *cp))
771 cp++;
772 }
773
774 /*
775 * Get any {Content-Disposition} given in buffer.
776 */
777 if (magic && *cp == '{') {
778 ++cp;
779 for (dp = cp + strlen (cp) - 1; dp >= cp; dp--)
780 if (*dp == '}')
781 break;
782 if (dp < cp) {
783 inform("invalid disposition in message %s", ct->c_file);
784 ct->c_dispo = NULL;
785 return NOTOK;
786 }
787
788 c = *dp;
789 *dp = '\0';
790
791 if (get_dispo(cp, ct, 1) != OK)
792 return NOTOK;
793
794 *dp++ = c;
795 cp = dp;
796
797 while (isspace ((unsigned char) *cp))
798 cp++;
799 }
800
801 /*
802 * Get any extension directives (right now just the content transfer
803 * encoding, but maybe others) that we care about.
804 */
805
806 if (magic && *cp == '*') {
807 /*
808 * See if it's a CTE we match on
809 */
810 struct k2v *kv;
811
812 dp = ++cp;
813 while (*cp != '\0' && ! isspace((unsigned char) *cp))
814 cp++;
815
816 if (dp == cp) {
817 inform("invalid null transfer encoding specification");
818 return NOTOK;
819 }
820
821 if (*cp != '\0')
822 *cp++ = '\0';
823
824 ct->c_reqencoding = CE_UNKNOWN;
825
826 for (kv = EncodingType; kv->kv_key; kv++) {
827 if (strcasecmp(kv->kv_key, dp) == 0) {
828 ct->c_reqencoding = kv->kv_value;
829 break;
830 }
831 }
832
833 if (ct->c_reqencoding == CE_UNKNOWN) {
834 inform("invalid CTE specification: \"%s\"", dp);
835 return NOTOK;
836 }
837
838 while (isspace ((unsigned char) *cp))
839 cp++;
840 }
841
842 /*
843 * Check if anything is left over
844 */
845 if (*cp) {
846 if (magic) {
847 ci->ci_magic = mh_xstrdup(cp);
848
849 /* If there is a Content-Disposition header and it doesn't
850 have a *filename=, extract it from the magic contents.
851 The r1bindex call skips any leading directory
852 components. */
853 if (ct->c_dispo_type &&
854 !get_param(ct->c_dispo_first, "filename", '_', 1)) {
855 add_param(&ct->c_dispo_first, &ct->c_dispo_last, "filename",
856 r1bindex(ci->ci_magic, '/'), 0);
857 }
858 }
859 else
860 inform("extraneous information in message %s's %s: field\n%*s(%s)",
861 ct->c_file, TYPE_FIELD, strlen(invo_name) + 2, "", cp);
862 }
863
864 return OK;
865 }
866
867
868 /*
869 * Parse out a Content-Disposition header. A lot of this is cribbed from
870 * get_ctinfo().
871 */
872 static int
873 get_dispo (char *cp, CT ct, int buildflag)
874 {
875 char *dp, *dispoheader;
876 char c;
877 int status;
878
879 /*
880 * Save the whole copy of the Content-Disposition header, unless we're
881 * processing a mhbuild directive. A NULL c_dispo will be a flag to
882 * mhbuild that the disposition header needs to be generated at that
883 * time.
884 */
885
886 dispoheader = cp = add(cp, NULL);
887
888 while (isspace ((unsigned char) *cp)) /* trim leading spaces */
889 cp++;
890
891 /* change newlines to spaces */
892 for (dp = strchr(cp, '\n'); dp; dp = strchr(dp, '\n'))
893 *dp++ = ' ';
894
895 /* trim trailing spaces */
896 for (dp = cp + strlen (cp) - 1; dp >= cp; dp--)
897 if (!isspace ((unsigned char) *dp))
898 break;
899 *++dp = '\0';
900
901 if (debugsw)
902 fprintf (stderr, "%s: %s\n", DISPO_FIELD, cp);
903
904 if (*cp == '(' && get_comment (ct->c_file, DISPO_FIELD, &cp, NULL) ==
905 NOTOK) {
906 free(dispoheader);
907 return NOTOK;
908 }
909
910 for (dp = cp; istoken (*dp); dp++)
911 continue;
912 c = *dp;
913 *dp = '\0';
914 ct->c_dispo_type = mh_xstrdup(cp); /* store disposition type */
915 *dp = c;
916 cp = dp;
917
918 if (*cp == '(' && get_comment (ct->c_file, DISPO_FIELD, &cp, NULL) == NOTOK)
919 return NOTOK;
920
921 if ((status = parse_header_attrs (ct->c_file, DISPO_FIELD, &cp,
922 &ct->c_dispo_first, &ct->c_dispo_last,
923 NULL)) != OK) {
924 if (status == NOTOK) {
925 free(dispoheader);
926 return NOTOK;
927 }
928 } else if (*cp) {
929 inform("extraneous information in message %s's %s: field\n%*s(%s)",
930 ct->c_file, DISPO_FIELD, strlen(invo_name) + 2, "", cp);
931 }
932
933 if (buildflag)
934 free(dispoheader);
935 else
936 ct->c_dispo = dispoheader;
937
938 return OK;
939 }
940
941
942 static int
943 get_comment (const char *filename, const char *fieldname, char **ap,
944 char **commentp)
945 {
946 int i;
947 char *bp, *cp;
948 char c, buffer[BUFSIZ], *dp;
949
950 cp = *ap;
951 bp = buffer;
952 cp++;
953
954 for (i = 0;;) {
955 switch (c = *cp++) {
956 case '\0':
957 invalid:
958 inform("invalid comment in message %s's %s: field",
959 filename, fieldname);
960 return NOTOK;
961
962 case '\\':
963 *bp++ = c;
964 if ((c = *cp++) == '\0')
965 goto invalid;
966 *bp++ = c;
967 continue;
968
969 case '(':
970 i++;
971 /* FALLTHRU */
972 default:
973 *bp++ = c;
974 continue;
975
976 case ')':
977 if (--i < 0)
978 break;
979 *bp++ = c;
980 continue;
981 }
982 break;
983 }
984 *bp = '\0';
985
986 if (commentp) {
987 if ((dp = *commentp)) {
988 *commentp = concat (dp, " ", buffer, NULL);
989 free (dp);
990 } else {
991 *commentp = mh_xstrdup(buffer);
992 }
993 }
994
995 while (isspace ((unsigned char) *cp))
996 cp++;
997
998 *ap = cp;
999 return OK;
1000 }
1001
1002
1003 /*
1004 * CONTENTS
1005 *
1006 * Handles content types audio, image, and video.
1007 * There's not much to do right here.
1008 */
1009
1010 static int
1011 InitGeneric (CT ct)
1012 {
1013 NMH_UNUSED (ct);
1014
1015 return OK; /* not much to do here */
1016 }
1017
1018
1019 /*
1020 * TEXT
1021 */
1022
1023 static int
1024 InitText (CT ct)
1025 {
1026 char buffer[BUFSIZ];
1027 char *chset = NULL;
1028 char *cp;
1029 PM pm;
1030 struct text *t;
1031 CI ci = &ct->c_ctinfo;
1032
1033 /* check for missing subtype */
1034 if (!*ci->ci_subtype)
1035 ci->ci_subtype = add ("plain", ci->ci_subtype);
1036
1037 /* match subtype */
1038 ct->c_subtype = ct_str_subtype (CT_TEXT, ci->ci_subtype);
1039
1040 /* allocate text character set structure */
1041 NEW0(t);
1042 ct->c_ctparams = (void *) t;
1043
1044 /* scan for charset parameter */
1045 for (pm = ci->ci_first_pm; pm; pm = pm->pm_next)
1046 if (!strcasecmp (pm->pm_name, "charset"))
1047 break;
1048
1049 /* check if content specified a character set */
1050 if (pm) {
1051 chset = pm->pm_value;
1052 t->tx_charset = CHARSET_SPECIFIED;
1053 } else {
1054 t->tx_charset = CHARSET_UNSPECIFIED;
1055 }
1056
1057 /*
1058 * If we can not handle character set natively,
1059 * then check profile for string to modify the
1060 * terminal or display method.
1061 *
1062 * termproc is for mhshow, though mhlist -debug prints it, too.
1063 */
1064 if (chset != NULL && !check_charset (chset, strlen (chset))) {
1065 snprintf (buffer, sizeof(buffer), "%s-charset-%s", invo_name, chset);
1066 if ((cp = context_find (buffer)))
1067 ct->c_termproc = mh_xstrdup(cp);
1068 }
1069
1070 return OK;
1071 }
1072
1073
1074 /*
1075 * MULTIPART
1076 */
1077
1078 static int
1079 InitMultiPart (CT ct)
1080 {
1081 int inout;
1082 long last, pos;
1083 char *cp, *dp;
1084 PM pm;
1085 char *bp;
1086 char *bufp = NULL;
1087 size_t buflen;
1088 ssize_t gotlen;
1089 struct multipart *m;
1090 struct part *part, **next;
1091 CI ci = &ct->c_ctinfo;
1092 CT p;
1093 FILE *fp;
1094
1095 /*
1096 * The encoding for multipart messages must be either
1097 * 7bit, 8bit, or binary (per RFC 2045).
1098 */
1099 if (! skip_mp_cte_check && ct->c_encoding != CE_7BIT &&
1100 ct->c_encoding != CE_8BIT && ct->c_encoding != CE_BINARY) {
1101 /* Copy the Content-Transfer-Encoding header field body so we can
1102 remove any trailing whitespace and leading blanks from it. */
1103 char *cte = mh_xstrdup(ct->c_celine ? ct->c_celine : "(null)");
1104
1105 bp = cte + strlen (cte) - 1;
1106 while (bp >= cte && isspace ((unsigned char) *bp)) *bp-- = '\0';
1107 for (bp = cte; *bp && isblank ((unsigned char) *bp); ++bp) continue;
1108
1109 inform("\"%s/%s\" type in message %s must be encoded in\n"
1110 "7bit, 8bit, or binary, per RFC 2045 (6.4). "
1111 "mhfixmsg -fixcte can fix it, or\n"
1112 "manually edit the file and change the \"%s\"\n"
1113 "Content-Transfer-Encoding to one of those. For now, continuing...",
1114 ci->ci_type, ci->ci_subtype, ct->c_file, bp);
1115 free (cte);
1116
1117 return NOTOK;
1118 }
1119
1120 /* match subtype */
1121 ct->c_subtype = ct_str_subtype (CT_MULTIPART, ci->ci_subtype);
1122
1123 /*
1124 * Check for "boundary" parameter, which is
1125 * required for multipart messages.
1126 */
1127 bp = 0;
1128 for (pm = ci->ci_first_pm; pm; pm = pm->pm_next) {
1129 if (!strcasecmp (pm->pm_name, "boundary")) {
1130 bp = pm->pm_value;
1131 break;
1132 }
1133 }
1134
1135 /* complain if boundary parameter is missing */
1136 if (!pm) {
1137 inform("a \"boundary\" parameter is mandatory for \"%s/%s\" type in message %s's %s: field",
1138 ci->ci_type, ci->ci_subtype, ct->c_file, TYPE_FIELD);
1139 return NOTOK;
1140 }
1141
1142 /* allocate primary structure for multipart info */
1143 NEW0(m);
1144 ct->c_ctparams = (void *) m;
1145
1146 /* check if boundary parameter contains only whitespace characters */
1147 for (cp = bp; isspace ((unsigned char) *cp); cp++)
1148 continue;
1149 if (!*cp) {
1150 inform("invalid \"boundary\" parameter for \"%s/%s\" type in message %s's %s: field",
1151 ci->ci_type, ci->ci_subtype, ct->c_file, TYPE_FIELD);
1152 return NOTOK;
1153 }
1154
1155 /* remove trailing whitespace from boundary parameter */
1156 for (cp = bp, dp = cp + strlen (cp) - 1; dp > cp; dp--)
1157 if (!isspace ((unsigned char) *dp))
1158 break;
1159 *++dp = '\0';
1160
1161 /* record boundary separators */
1162 m->mp_start = concat (bp, "\n", NULL);
1163 m->mp_stop = concat (bp, "--\n", NULL);
1164
1165 if (!ct->c_fp && (ct->c_fp = fopen (ct->c_file, "r")) == NULL) {
1166 advise (ct->c_file, "unable to open for reading");
1167 return NOTOK;
1168 }
1169
1170 fseek (fp = ct->c_fp, pos = ct->c_begin, SEEK_SET);
1171 last = ct->c_end;
1172 next = &m->mp_parts;
1173 part = NULL;
1174 inout = 1;
1175
1176 while ((gotlen = getline(&bufp, &buflen, fp)) != -1) {
1177 if (pos > last)
1178 break;
1179
1180 pos += gotlen;
1181 if (bufp[0] != '-' || bufp[1] != '-')
1182 continue;
1183 if (inout) {
1184 if (strcmp (bufp + 2, m->mp_start))
1185 continue;
1186 next_part:
1187 NEW0(part);
1188 *next = part;
1189 next = &part->mp_next;
1190
1191 if (!(p = get_content (fp, ct->c_file,
1192 ct->c_subtype == MULTI_DIGEST ? -1 : 0))) {
1193 free(bufp);
1194 ct->c_fp = NULL;
1195 return NOTOK;
1196 }
1197 p->c_fp = NULL;
1198 part->mp_part = p;
1199 pos = p->c_begin;
1200 fseek (fp, pos, SEEK_SET);
1201 inout = 0;
1202 } else {
1203 if (strcmp (bufp + 2, m->mp_start) == 0) {
1204 inout = 1;
1205 end_part:
1206 p = part->mp_part;
1207 p->c_end = ftell(fp) - (gotlen + 1);
1208 if (p->c_end < p->c_begin)
1209 p->c_begin = p->c_end;
1210 if (inout)
1211 goto next_part;
1212 goto last_part;
1213 }
1214 if (strcmp (bufp + 2, m->mp_stop) == 0)
1215 goto end_part;
1216 }
1217 }
1218
1219 if (! suppress_bogus_mp_content_warning) {
1220 inform("bogus multipart content in message %s", ct->c_file);
1221 }
1222 bogus_mp_content = 1;
1223
1224 if (!inout && part) {
1225 p = part->mp_part;
1226 p->c_end = ct->c_end;
1227
1228 if (p->c_begin >= p->c_end) {
1229 for (next = &m->mp_parts; *next != part;
1230 next = &((*next)->mp_next))
1231 continue;
1232 *next = NULL;
1233 free_content (p);
1234 free(part);
1235 }
1236 }
1237
1238 last_part:
1239 /* reverse the order of the parts for multipart/alternative */
1240 if (ct->c_subtype == MULTI_ALTERNATE) {
1241 reverse_parts (ct);
1242 prefer_parts (ct);
1243 }
1244
1245 /*
1246 * label all subparts with part number, and
1247 * then initialize the content of the subpart.
1248 */
1249 {
1250 int partnum;
1251 char *pp;
1252 char partnam[BUFSIZ];
1253
1254 if (ct->c_partno) {
1255 snprintf (partnam, sizeof(partnam), "%s.", ct->c_partno);
1256 pp = partnam + strlen (partnam);
1257 } else {
1258 pp = partnam;
1259 }
1260
1261 for (part = m->mp_parts, partnum = 1; part;
1262 part = part->mp_next, partnum++) {
1263 p = part->mp_part;
1264
1265 sprintf (pp, "%d", partnum);
1266 p->c_partno = mh_xstrdup(partnam);
1267
1268 /* initialize the content of the subparts */
1269 if (p->c_ctinitfnx && (*p->c_ctinitfnx) (p) == NOTOK) {
1270 free(bufp);
1271 fclose (ct->c_fp);
1272 ct->c_fp = NULL;
1273 return NOTOK;
1274 }
1275 }
1276 }
1277
1278 get_leftover_mp_content (ct, 1);
1279 get_leftover_mp_content (ct, 0);
1280
1281 free(bufp);
1282 fclose (ct->c_fp);
1283 ct->c_fp = NULL;
1284 return OK;
1285 }
1286
1287
1288 /*
1289 * reverse the order of the parts of a multipart/alternative,
1290 * presumably to put the "most favored" alternative first, for
1291 * ease of choosing/displaying it later on. from a mail message on
1292 * nmh-workers, from kenh:
1293 * "Stock" MH 6.8.5 did not have a reverse_parts() function, but I
1294 * see code in mhn that did the same thing... According to the RCS
1295 * logs, that code was around from the initial checkin of mhn.c by
1296 * John Romine in 1992, which is as far back as we have."
1297 */
1298 static void
1299 reverse_parts (CT ct)
1300 {
1301 struct multipart *m = (struct multipart *) ct->c_ctparams;
1302 struct part *part;
1303 struct part *next;
1304
1305 /* Reverse the order of its parts by walking the mp_parts list
1306 and pushing each node to the front. */
1307 for (part = m->mp_parts, m->mp_parts = NULL; part; part = next) {
1308 next = part->mp_next;
1309 part->mp_next = m->mp_parts;
1310 m->mp_parts = part;
1311 }
1312 }
1313
1314 static void
1315 move_preferred_part (CT ct, char *type, char *subtype)
1316 {
1317 struct multipart *m = (struct multipart *) ct->c_ctparams;
1318 struct part *part, *prev, *head, *nhead, *ntail;
1319 struct part h, n;
1320 CI ci;
1321
1322 /* move the matching part(s) to the head of the list: walk the
1323 * list of parts, move matching parts to a new list (maintaining
1324 * their order), and finally, concatenate the old list onto the
1325 * new.
1326 */
1327
1328 head = &h;
1329 nhead = &n;
1330
1331 head->mp_next = m->mp_parts;
1332 nhead->mp_next = NULL;
1333 ntail = nhead;
1334
1335 prev = head;
1336 part = head->mp_next;
1337 while (part != NULL) {
1338 ci = &part->mp_part->c_ctinfo;
1339 if (!strcasecmp(ci->ci_type, type) &&
1340 (!subtype || !strcasecmp(ci->ci_subtype, subtype))) {
1341 prev->mp_next = part->mp_next;
1342 part->mp_next = NULL;
1343 ntail->mp_next = part;
1344 ntail = part;
1345 part = prev->mp_next;
1346 } else {
1347 prev = part;
1348 part = prev->mp_next;
1349 }
1350 }
1351 ntail->mp_next = head->mp_next;
1352 m->mp_parts = nhead->mp_next;
1353
1354 }
1355
1356 /*
1357 * move parts that match the user's preferences (-prefer) to the head
1358 * of the line. process preferences in reverse so first one given
1359 * ends up first in line
1360 */
1361 static void
1362 prefer_parts(CT ct)
1363 {
1364 int i;
1365 for (i = npreferred-1; i >= 0; i--)
1366 move_preferred_part(ct, preferred_types[i], preferred_subtypes[i]);
1367 }
1368
1369
1370
1371 /* parse_mime() arranges alternates in reverse (priority) order. This
1372 function can be used to reverse them back. This will put, for
1373 example, a text/plain part before a text/html part in a
1374 multipart/alternative part, for example, where it belongs. */
1375 void
1376 reverse_alternative_parts (CT ct) {
1377 if (ct->c_type == CT_MULTIPART) {
1378 struct multipart *m = (struct multipart *) ct->c_ctparams;
1379 struct part *part;
1380
1381 if (ct->c_subtype == MULTI_ALTERNATE) {
1382 reverse_parts (ct);
1383 }
1384
1385 /* And call recursively on each part of a multipart. */
1386 for (part = m->mp_parts; part; part = part->mp_next) {
1387 reverse_alternative_parts (part->mp_part);
1388 }
1389 }
1390 }
1391
1392
1393 /*
1394 * MESSAGE
1395 */
1396
1397 static int
1398 InitMessage (CT ct)
1399 {
1400 CI ci = &ct->c_ctinfo;
1401
1402 if ((ct->c_encoding != CE_7BIT) && (ct->c_encoding != CE_8BIT)) {
1403 inform("\"%s/%s\" type in message %s should be encoded in "
1404 "7bit or 8bit, continuing...", ci->ci_type, ci->ci_subtype,
1405 ct->c_file);
1406 return NOTOK;
1407 }
1408
1409 /* check for missing subtype */
1410 if (!*ci->ci_subtype)
1411 ci->ci_subtype = add ("rfc822", ci->ci_subtype);
1412
1413 /* match subtype */
1414 ct->c_subtype = ct_str_subtype (CT_MESSAGE, ci->ci_subtype);
1415
1416 switch (ct->c_subtype) {
1417 case MESSAGE_RFC822:
1418 break;
1419
1420 case MESSAGE_PARTIAL:
1421 {
1422 PM pm;
1423 struct partial *p;
1424
1425 NEW0(p);
1426 ct->c_ctparams = (void *) p;
1427
1428 /* scan for parameters "id", "number", and "total" */
1429 for (pm = ci->ci_first_pm; pm; pm = pm->pm_next) {
1430 if (!strcasecmp (pm->pm_name, "id")) {
1431 p->pm_partid = add (pm->pm_value, NULL);
1432 continue;
1433 }
1434 if (!strcasecmp (pm->pm_name, "number")) {
1435 if (sscanf (pm->pm_value, "%d", &p->pm_partno) != 1
1436 || p->pm_partno < 1) {
1437 invalid_param:
1438 inform("invalid %s parameter for \"%s/%s\" type in message %s's %s field",
1439 pm->pm_name, ci->ci_type, ci->ci_subtype,
1440 ct->c_file, TYPE_FIELD);
1441 return NOTOK;
1442 }
1443 continue;
1444 }
1445 if (!strcasecmp (pm->pm_name, "total")) {
1446 if (sscanf (pm->pm_value, "%d", &p->pm_maxno) != 1
1447 || p->pm_maxno < 1)
1448 goto invalid_param;
1449 continue;
1450 }
1451 }
1452
1453 if (!p->pm_partid
1454 || !p->pm_partno
1455 || (p->pm_maxno && p->pm_partno > p->pm_maxno)) {
1456 inform("invalid parameters for \"%s/%s\" type in message %s's %s field",
1457 ci->ci_type, ci->ci_subtype, ct->c_file, TYPE_FIELD);
1458 return NOTOK;
1459 }
1460 }
1461 break;
1462
1463 case MESSAGE_EXTERNAL:
1464 {
1465 int exresult;
1466 struct exbody *e;
1467 CT p;
1468 FILE *fp;
1469
1470 NEW0(e);
1471 ct->c_ctparams = (void *) e;
1472
1473 if (!ct->c_fp
1474 && (ct->c_fp = fopen (ct->c_file, "r")) == NULL) {
1475 advise (ct->c_file, "unable to open for reading");
1476 return NOTOK;
1477 }
1478
1479 fseek (fp = ct->c_fp, ct->c_begin, SEEK_SET);
1480
1481 if (!(p = get_content (fp, ct->c_file, 0))) {
1482 ct->c_fp = NULL;
1483 return NOTOK;
1484 }
1485
1486 e->eb_parent = ct;
1487 e->eb_content = p;
1488 p->c_ctexbody = e;
1489 p->c_ceopenfnx = NULL;
1490 if ((exresult = params_external (ct, 0)) != NOTOK
1491 && p->c_ceopenfnx == openMail) {
1492 int cc, size;
1493 char *bp;
1494
1495 if ((size = ct->c_end - p->c_begin) <= 0) {
1496 if (!e->eb_subject)
1497 content_error (NULL, ct,
1498 "empty body for access-type=mail-server");
1499 goto no_body;
1500 }
1501
1502 e->eb_body = bp = mh_xmalloc ((unsigned) size);
1503 fseek (p->c_fp, p->c_begin, SEEK_SET);
1504 while (size > 0)
1505 switch (cc = fread (bp, sizeof(*bp), size, p->c_fp)) {
1506 case NOTOK:
1507 adios ("failed", "fread");
1508
1509 case OK:
1510 adios (NULL, "unexpected EOF from fread");
1511
1512 default:
1513 bp += cc, size -= cc;
1514 break;
1515 }
1516 *bp = 0;
1517 }
1518 no_body:
1519 p->c_fp = NULL;
1520 p->c_end = p->c_begin;
1521
1522 fclose (ct->c_fp);
1523 ct->c_fp = NULL;
1524
1525 if (exresult == NOTOK)
1526 return NOTOK;
1527 if (e->eb_flags == NOTOK)
1528 return OK;
1529
1530 switch (p->c_type) {
1531 case CT_MULTIPART:
1532 break;
1533
1534 case CT_MESSAGE:
1535 if (p->c_subtype != MESSAGE_RFC822)
1536 break;
1537 /* FALLTHRU */
1538 default:
1539 e->eb_partno = ct->c_partno;
1540 if (p->c_ctinitfnx)
1541 (*p->c_ctinitfnx) (p);
1542 break;
1543 }
1544 }
1545 break;
1546
1547 default:
1548 break;
1549 }
1550
1551 return OK;
1552 }
1553
1554
1555 int
1556 params_external (CT ct, int composing)
1557 {
1558 PM pm;
1559 struct exbody *e = (struct exbody *) ct->c_ctparams;
1560 CI ci = &ct->c_ctinfo;
1561
1562 ct->c_ceopenfnx = NULL;
1563 for (pm = ci->ci_first_pm; pm; pm = pm->pm_next) {
1564 if (!strcasecmp (pm->pm_name, "access-type")) {
1565 struct str2init *s2i;
1566 CT p = e->eb_content;
1567
1568 for (s2i = str2methods; s2i->si_key; s2i++)
1569 if (!strcasecmp (pm->pm_value, s2i->si_key))
1570 break;
1571 if (!s2i->si_key) {
1572 e->eb_access = pm->pm_value;
1573 e->eb_flags = NOTOK;
1574 p->c_encoding = CE_EXTERNAL;
1575 continue;
1576 }
1577 e->eb_access = s2i->si_key;
1578 e->eb_flags = s2i->si_val;
1579 p->c_encoding = CE_EXTERNAL;
1580
1581 /* Call the Init function for this external type */
1582 if ((*s2i->si_init)(p) == NOTOK)
1583 return NOTOK;
1584 continue;
1585 }
1586 if (!strcasecmp (pm->pm_name, "name")) {
1587 e->eb_name = pm->pm_value;
1588 continue;
1589 }
1590 if (!strcasecmp (pm->pm_name, "permission")) {
1591 e->eb_permission = pm->pm_value;
1592 continue;
1593 }
1594 if (!strcasecmp (pm->pm_name, "site")) {
1595 e->eb_site = pm->pm_value;
1596 continue;
1597 }
1598 if (!strcasecmp (pm->pm_name, "directory")) {
1599 e->eb_dir = pm->pm_value;
1600 continue;
1601 }
1602 if (!strcasecmp (pm->pm_name, "mode")) {
1603 e->eb_mode = pm->pm_value;
1604 continue;
1605 }
1606 if (!strcasecmp (pm->pm_name, "size")) {
1607 sscanf (pm->pm_value, "%lu", &e->eb_size);
1608 continue;
1609 }
1610 if (!strcasecmp (pm->pm_name, "server")) {
1611 e->eb_server = pm->pm_value;
1612 continue;
1613 }
1614 if (!strcasecmp (pm->pm_name, "subject")) {
1615 e->eb_subject = pm->pm_value;
1616 continue;
1617 }
1618 if (!strcasecmp (pm->pm_name, "url")) {
1619 /*
1620 * According to RFC 2017, we have to remove all whitespace from
1621 * the URL
1622 */
1623
1624 char *u, *p = pm->pm_value;
1625 e->eb_url = u = mh_xmalloc(strlen(pm->pm_value) + 1);
1626
1627 for (; *p != '\0'; p++) {
1628 if (! isspace((unsigned char) *p))
1629 *u++ = *p;
1630 }
1631
1632 *u = '\0';
1633 continue;
1634 }
1635 if (composing && !strcasecmp (pm->pm_name, "body")) {
1636 e->eb_body = getcpy (pm->pm_value);
1637 continue;
1638 }
1639 }
1640
1641 if (!e->eb_access) {
1642 inform("invalid parameters for \"%s/%s\" type in message %s's %s field",
1643 ci->ci_type, ci->ci_subtype, ct->c_file, TYPE_FIELD);
1644 return NOTOK;
1645 }
1646
1647 return OK;
1648 }
1649
1650
1651 /*
1652 * APPLICATION
1653 */
1654
1655 static int
1656 InitApplication (CT ct)
1657 {
1658 CI ci = &ct->c_ctinfo;
1659
1660 /* match subtype */
1661 ct->c_subtype = ct_str_subtype (CT_APPLICATION, ci->ci_subtype);
1662
1663 return OK;
1664 }
1665
1666
1667 /*
1668 * TRANSFER ENCODINGS
1669 */
1670
1671 static int
1672 init_encoding (CT ct, OpenCEFunc openfnx)
1673 {
1674 ct->c_ceopenfnx = openfnx;
1675 ct->c_ceclosefnx = close_encoding;
1676 ct->c_cesizefnx = size_encoding;
1677
1678 return OK;
1679 }
1680
1681
1682 void
1683 close_encoding (CT ct)
1684 {
1685 CE ce = &ct->c_cefile;
1686
1687 if (ce->ce_fp) {
1688 fclose (ce->ce_fp);
1689 ce->ce_fp = NULL;
1690 }
1691 }
1692
1693
1694 static unsigned long
1695 size_encoding (CT ct)
1696 {
1697 int fd;
1698 unsigned long size;
1699 char *file;
1700 CE ce = &ct->c_cefile;
1701 struct stat st;
1702
1703 if (ce->ce_fp && fstat (fileno (ce->ce_fp), &st) != NOTOK)
1704 return (long) st.st_size;
1705
1706 if (ce->ce_file) {
1707 if (stat (ce->ce_file, &st) != NOTOK)
1708 return (long) st.st_size;
1709 return 0L;
1710 }
1711
1712 if (ct->c_encoding == CE_EXTERNAL)
1713 return (ct->c_end - ct->c_begin);
1714
1715 file = NULL;
1716 if ((fd = (*ct->c_ceopenfnx) (ct, &file)) == NOTOK)
1717 return (ct->c_end - ct->c_begin);
1718
1719 if (fstat (fd, &st) != NOTOK)
1720 size = (long) st.st_size;
1721 else
1722 size = 0L;
1723
1724 (*ct->c_ceclosefnx) (ct);
1725 return size;
1726 }
1727
1728
1729 /*
1730 * BASE64
1731 */
1732
1733 static int
1734 InitBase64 (CT ct)
1735 {
1736 return init_encoding (ct, openBase64);
1737 }
1738
1739
1740 static int
1741 openBase64 (CT ct, char **file)
1742 {
1743 ssize_t cc, len;
1744 int fd, own_ct_fp = 0;
1745 char *cp, *buffer = NULL;
1746 /* sbeck -- handle suffixes */
1747 CI ci;
1748 CE ce = &ct->c_cefile;
1749 unsigned char *decoded;
1750 size_t decoded_len;
1751 unsigned char digest[16];
1752
1753 if (ce->ce_fp) {
1754 fseek (ce->ce_fp, 0L, SEEK_SET);
1755 goto ready_to_go;
1756 }
1757
1758 if (ce->ce_file) {
1759 if ((ce->ce_fp = fopen (ce->ce_file, "r")) == NULL) {
1760 content_error (ce->ce_file, ct, "unable to fopen for reading");
1761 return NOTOK;
1762 }
1763 goto ready_to_go;
1764 }
1765
1766 if (*file == NULL) {
1767 ce->ce_unlink = 1;
1768 } else {
1769 ce->ce_file = mh_xstrdup(*file);
1770 ce->ce_unlink = 0;
1771 }
1772
1773 /* sbeck@cise.ufl.edu -- handle suffixes */
1774 ci = &ct->c_ctinfo;
1775 if ((cp = context_find_by_type ("suffix", ci->ci_type, ci->ci_subtype))) {
1776 if (ce->ce_unlink) {
1777 /* Create temporary file with filename extension. */
1778 if ((ce->ce_file = m_mktemps(invo_name, cp, NULL, NULL)) == NULL) {
1779 adios(NULL, "unable to create temporary file in %s",
1780 get_temp_dir());
1781 }
1782 } else {
1783 ce->ce_file = add (cp, ce->ce_file);
1784 }
1785 } else if (*file == NULL) {
1786 char *tempfile;
1787 if ((tempfile = m_mktemp2(NULL, invo_name, NULL, NULL)) == NULL) {
1788 adios(NULL, "unable to create temporary file in %s",
1789 get_temp_dir());
1790 }
1791 ce->ce_file = mh_xstrdup(tempfile);
1792 }
1793
1794 if ((ce->ce_fp = fopen (ce->ce_file, "w+")) == NULL) {
1795 content_error (ce->ce_file, ct, "unable to fopen for reading/writing");
1796 return NOTOK;
1797 }
1798
1799 if ((len = ct->c_end - ct->c_begin) < 0)
1800 adios (NULL, "internal error(1)");
1801
1802 buffer = mh_xmalloc (len + 1);
1803
1804 if (! ct->c_fp) {
1805 if ((ct->c_fp = fopen (ct->c_file, "r")) == NULL) {
1806 content_error (ct->c_file, ct, "unable to open for reading");
1807 return NOTOK;
1808 }
1809 own_ct_fp = 1;
1810 }
1811
1812 lseek (fd = fileno (ct->c_fp), (off_t) ct->c_begin, SEEK_SET);
1813 cp = buffer;
1814 while (len > 0) {
1815 switch (cc = read (fd, cp, len)) {
1816 case NOTOK:
1817 content_error (ct->c_file, ct, "error reading from");
1818 goto clean_up;
1819
1820 case OK:
1821 content_error (NULL, ct, "premature eof");
1822 goto clean_up;
1823
1824 default:
1825 if (cc > len)
1826 cc = len;
1827 len -= cc;
1828 cp += cc;
1829 }
1830 }
1831
1832 /* decodeBase64() requires null-terminated input. */
1833 *cp = '\0';
1834
1835 if (decodeBase64 (buffer, &decoded, &decoded_len, ct->c_type == CT_TEXT,
1836 ct->c_digested ? digest : NULL) == OK) {
1837 size_t i;
1838 unsigned char *decoded_p = decoded;
1839 for (i = 0; i < decoded_len; ++i) {
1840 putc (*decoded_p++, ce->ce_fp);
1841 }
1842 free(decoded);
1843 if (ferror (ce->ce_fp)) {
1844 content_error (ce->ce_file, ct, "error writing to");
1845 goto clean_up;
1846 }
1847
1848 if (ct->c_digested) {
1849 if (memcmp(digest, ct->c_digest,
1850 sizeof(digest) / sizeof(digest[0]))) {
1851 content_error (NULL, ct,
1852 "content integrity suspect (digest mismatch) -- continuing");
1853 } else {
1854 if (debugsw) {
1855 fprintf (stderr, "content integrity confirmed\n");
1856 }
1857 }
1858 }
1859 } else {
1860 goto clean_up;
1861 }
1862
1863 fseek (ct->c_fp, 0L, SEEK_SET);
1864
1865 if (fflush (ce->ce_fp)) {
1866 content_error (ce->ce_file, ct, "error writing to");
1867 goto clean_up;
1868 }
1869
1870 fseek (ce->ce_fp, 0L, SEEK_SET);
1871
1872 ready_to_go:
1873 *file = ce->ce_file;
1874 if (own_ct_fp) {
1875 fclose (ct->c_fp);
1876 ct->c_fp = NULL;
1877 }
1878 free (buffer);
1879 return fileno (ce->ce_fp);
1880
1881 clean_up:
1882 if (own_ct_fp) {
1883 fclose (ct->c_fp);
1884 ct->c_fp = NULL;
1885 }
1886 free_encoding (ct, 0);
1887 free (buffer);
1888 return NOTOK;
1889 }
1890
1891
1892 /*
1893 * QUOTED PRINTABLE
1894 */
1895
1896 static char hex2nib[0x80] = {
1897 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1898 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1899 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1900 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1901 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1902 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1903 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
1904 0x08, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1905 0x00, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x00,
1906 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1907 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1908 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1909 0x00, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x00,
1910 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1911 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1912 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
1913 };
1914
1915
1916 static int
1917 InitQuoted (CT ct)
1918 {
1919 return init_encoding (ct, openQuoted);
1920 }
1921
1922
1923 static int
1924 openQuoted (CT ct, char **file)
1925 {
1926 int cc, digested, len, quoted, own_ct_fp = 0;
1927 char *cp, *ep;
1928 char *bufp = NULL;
1929 size_t buflen;
1930 ssize_t gotlen;
1931 unsigned char mask;
1932 CE ce = &ct->c_cefile;
1933 /* sbeck -- handle suffixes */
1934 CI ci;
1935 MD5_CTX mdContext;
1936
1937 if (ce->ce_fp) {
1938 fseek (ce->ce_fp, 0L, SEEK_SET);
1939 goto ready_to_go;
1940 }
1941
1942 if (ce->ce_file) {
1943 if ((ce->ce_fp = fopen (ce->ce_file, "r")) == NULL) {
1944 content_error (ce->ce_file, ct, "unable to fopen for reading");
1945 return NOTOK;
1946 }
1947 goto ready_to_go;
1948 }
1949
1950 if (*file == NULL) {
1951 ce->ce_unlink = 1;
1952 } else {
1953 ce->ce_file = mh_xstrdup(*file);
1954 ce->ce_unlink = 0;
1955 }
1956
1957 /* sbeck@cise.ufl.edu -- handle suffixes */
1958 ci = &ct->c_ctinfo;
1959 if ((cp = context_find_by_type ("suffix", ci->ci_type, ci->ci_subtype))) {
1960 if (ce->ce_unlink) {
1961 /* Create temporary file with filename extension. */
1962 if ((ce->ce_file = m_mktemps(invo_name, cp, NULL, NULL)) == NULL) {
1963 adios(NULL, "unable to create temporary file in %s",
1964 get_temp_dir());
1965 }
1966 } else {
1967 ce->ce_file = add (cp, ce->ce_file);
1968 }
1969 } else if (*file == NULL) {
1970 char *tempfile;
1971 if ((tempfile = m_mktemp2(NULL, invo_name, NULL, NULL)) == NULL) {
1972 adios(NULL, "unable to create temporary file in %s",
1973 get_temp_dir());
1974 }
1975 ce->ce_file = mh_xstrdup(tempfile);
1976 }
1977
1978 if ((ce->ce_fp = fopen (ce->ce_file, "w+")) == NULL) {
1979 content_error (ce->ce_file, ct, "unable to fopen for reading/writing");
1980 return NOTOK;
1981 }
1982
1983 if ((len = ct->c_end - ct->c_begin) < 0)
1984 adios (NULL, "internal error(2)");
1985
1986 if (! ct->c_fp) {
1987 if ((ct->c_fp = fopen (ct->c_file, "r")) == NULL) {
1988 content_error (ct->c_file, ct, "unable to open for reading");
1989 return NOTOK;
1990 }
1991 own_ct_fp = 1;
1992 }
1993
1994 if ((digested = ct->c_digested))
1995 MD5Init (&mdContext);
1996
1997 quoted = 0;
1998 #ifdef lint
1999 mask = 0;
2000 #endif
2001
2002 fseek (ct->c_fp, ct->c_begin, SEEK_SET);
2003 while (len > 0) {
2004 if ((gotlen = getline(&bufp, &buflen, ct->c_fp)) == -1) {
2005 content_error (NULL, ct, "premature eof");
2006 goto clean_up;
2007 }
2008
2009 if ((cc = gotlen) > len)
2010 cc = len;
2011 len -= cc;
2012
2013 for (ep = (cp = bufp) + cc - 1; cp <= ep; ep--)
2014 if (!isspace ((unsigned char) *ep))
2015 break;
2016 *++ep = '\n';
2017 ep++;
2018
2019 for (; cp < ep; cp++) {
2020 if (quoted > 0) {
2021 /* in an escape sequence */
2022 if (quoted == 1) {
2023 /* at byte 1 of an escape sequence */
2024 mask = hex2nib[((unsigned char) *cp) & 0x7f];
2025 /* next is byte 2 */
2026 quoted = 2;
2027 } else {
2028 /* at byte 2 of an escape sequence */
2029 mask <<= 4;
2030 mask |= hex2nib[((unsigned char) *cp) & 0x7f];
2031 putc (mask, ce->ce_fp);
2032 if (digested)
2033 MD5Update (&mdContext, &mask, 1);
2034 if (ferror (ce->ce_fp)) {
2035 content_error (ce->ce_file, ct, "error writing to");
2036 goto clean_up;
2037 }
2038 /* finished escape sequence; next may be literal or a new
2039 * escape sequence */
2040 quoted = 0;
2041 }
2042 /* on to next byte */
2043 continue;
2044 }
2045
2046 /* not in an escape sequence */
2047 if (*cp == '=') {
2048 /* starting an escape sequence, or invalid '='? */
2049 if (cp + 1 < ep && cp[1] == '\n') {
2050 /* "=\n" soft line break, eat the \n */
2051 cp++;
2052 continue;
2053 }
2054 if (cp + 1 >= ep || cp + 2 >= ep) {
2055 /* We don't have 2 bytes left, so this is an invalid
2056 * escape sequence; just show the raw bytes (below). */
2057 } else if (isxdigit ((unsigned char) cp[1]) &&
2058 isxdigit ((unsigned char) cp[2])) {
2059 /* Next 2 bytes are hex digits, making this a valid escape
2060 * sequence; let's decode it (above). */
2061 quoted = 1;
2062 continue;
2063 }
2064 /* One or both of the next 2 is out of range, making this
2065 * an invalid escape sequence; just show the raw bytes
2066 * (below). */
2067 }
2068
2069 /* Just show the raw byte. */
2070 putc (*cp, ce->ce_fp);
2071 if (digested) {
2072 if (*cp == '\n') {
2073 MD5Update (&mdContext, (unsigned char *) "\r\n",2);
2074 } else {
2075 MD5Update (&mdContext, (unsigned char *) cp, 1);
2076 }
2077 }
2078 if (ferror (ce->ce_fp)) {
2079 content_error (ce->ce_file, ct, "error writing to");
2080 goto clean_up;
2081 }
2082 }
2083 }
2084 if (quoted) {
2085 content_error (NULL, ct,
2086 "invalid QUOTED-PRINTABLE encoding -- end-of-content while still quoting");
2087 goto clean_up;
2088 }
2089
2090 fseek (ct->c_fp, 0L, SEEK_SET);
2091
2092 if (fflush (ce->ce_fp)) {
2093 content_error (ce->ce_file, ct, "error writing to");
2094 goto clean_up;
2095 }
2096
2097 if (digested) {
2098 unsigned char digest[16];
2099
2100 MD5Final (digest, &mdContext);
2101 if (memcmp((char *) digest, (char *) ct->c_digest,
2102 sizeof(digest) / sizeof(digest[0])))
2103 content_error (NULL, ct,
2104 "content integrity suspect (digest mismatch) -- continuing");
2105 else
2106 if (debugsw)
2107 fprintf (stderr, "content integrity confirmed\n");
2108 }
2109
2110 fseek (ce->ce_fp, 0L, SEEK_SET);
2111
2112 ready_to_go:
2113 *file = ce->ce_file;
2114 if (own_ct_fp) {
2115 fclose (ct->c_fp);
2116 ct->c_fp = NULL;
2117 }
2118 free (bufp);
2119 return fileno (ce->ce_fp);
2120
2121 clean_up:
2122 free_encoding (ct, 0);
2123 if (own_ct_fp) {
2124 fclose (ct->c_fp);
2125 ct->c_fp = NULL;
2126 }
2127 free (bufp);
2128 return NOTOK;
2129 }
2130
2131
2132 /*
2133 * 7BIT
2134 */
2135
2136 static int
2137 Init7Bit (CT ct)
2138 {
2139 if (init_encoding (ct, open7Bit) == NOTOK)
2140 return NOTOK;
2141
2142 ct->c_cesizefnx = NULL; /* no need to decode for real size */
2143 return OK;
2144 }
2145
2146
2147 int
2148 open7Bit (CT ct, char **file)
2149 {
2150 int cc, fd, len, own_ct_fp = 0;
2151 char buffer[BUFSIZ];
2152 /* sbeck -- handle suffixes */
2153 char *cp;
2154 CI ci;
2155 CE ce = &ct->c_cefile;
2156
2157 if (ce->ce_fp) {
2158 fseek (ce->ce_fp, 0L, SEEK_SET);
2159 goto ready_to_go;
2160 }
2161
2162 if (ce->ce_file) {
2163 if ((ce->ce_fp = fopen (ce->ce_file, "r")) == NULL) {
2164 content_error (ce->ce_file, ct, "unable to fopen for reading");
2165 return NOTOK;
2166 }
2167 goto ready_to_go;
2168 }
2169
2170 if (*file == NULL) {
2171 ce->ce_unlink = 1;
2172 } else {
2173 ce->ce_file = mh_xstrdup(*file);
2174 ce->ce_unlink = 0;
2175 }
2176
2177 /* sbeck@cise.ufl.edu -- handle suffixes */
2178 ci = &ct->c_ctinfo;
2179 if ((cp = context_find_by_type ("suffix", ci->ci_type, ci->ci_subtype))) {
2180 if (ce->ce_unlink) {
2181 /* Create temporary file with filename extension. */
2182 if ((ce->ce_file = m_mktemps(invo_name, cp, NULL, NULL)) == NULL) {
2183 adios(NULL, "unable to create temporary file in %s",
2184 get_temp_dir());
2185 }
2186 } else {
2187 ce->ce_file = add (cp, ce->ce_file);
2188 }
2189 } else if (*file == NULL) {
2190 char *tempfile;
2191 if ((tempfile = m_mktemp2(NULL, invo_name, NULL, NULL)) == NULL) {
2192 adios(NULL, "unable to create temporary file in %s",
2193 get_temp_dir());
2194 }
2195 ce->ce_file = mh_xstrdup(tempfile);
2196 }
2197
2198 if ((ce->ce_fp = fopen (ce->ce_file, "w+")) == NULL) {
2199 content_error (ce->ce_file, ct, "unable to fopen for reading/writing");
2200 return NOTOK;
2201 }
2202
2203 if (ct->c_type == CT_MULTIPART) {
2204 CI ci = &ct->c_ctinfo;
2205 char *buffer;
2206
2207 len = 0;
2208 fprintf (ce->ce_fp, "%s: %s/%s", TYPE_FIELD, ci->ci_type, ci->ci_subtype);
2209 len += strlen (TYPE_FIELD) + 2 + strlen (ci->ci_type)
2210 + 1 + strlen (ci->ci_subtype);
2211 buffer = output_params(len, ci->ci_first_pm, &len, 0);
2212
2213 if (buffer) {
2214 fputs (buffer, ce->ce_fp);
2215 free(buffer);
2216 }
2217
2218 if (ci->ci_comment) {
2219 if (len + 1 + (cc = 2 + strlen (ci->ci_comment)) >= CPERLIN) {
2220 fputs ("\n\t", ce->ce_fp);
2221 len = 8;
2222 }
2223 else {
2224 putc (' ', ce->ce_fp);
2225 len++;
2226 }
2227 fprintf (ce->ce_fp, "(%s)", ci->ci_comment);
2228 len += cc;
2229 }
2230 fprintf (ce->ce_fp, "\n");
2231 if (ct->c_id)
2232 fprintf (ce->ce_fp, "%s:%s", ID_FIELD, ct->c_id);
2233 if (ct->c_descr)
2234 fprintf (ce->ce_fp, "%s:%s", DESCR_FIELD, ct->c_descr);
2235 if (ct->c_dispo)
2236 fprintf (ce->ce_fp, "%s:%s", DISPO_FIELD, ct->c_dispo);
2237 fprintf (ce->ce_fp, "\n");
2238 }
2239
2240 if ((len = ct->c_end - ct->c_begin) < 0)
2241 adios (NULL, "internal error(3)");
2242
2243 if (! ct->c_fp) {
2244 if ((ct->c_fp = fopen (ct->c_file, "r")) == NULL) {
2245 content_error (ct->c_file, ct, "unable to open for reading");
2246 return NOTOK;
2247 }
2248 own_ct_fp = 1;
2249 }
2250
2251 lseek (fd = fileno (ct->c_fp), (off_t) ct->c_begin, SEEK_SET);
2252 while (len > 0)
2253 switch (cc = read (fd, buffer, sizeof(buffer) - 1)) {
2254 case NOTOK:
2255 content_error (ct->c_file, ct, "error reading from");
2256 goto clean_up;
2257
2258 case OK:
2259 content_error (NULL, ct, "premature eof");
2260 goto clean_up;
2261
2262 default:
2263 if (cc > len)
2264 cc = len;
2265 len -= cc;
2266
2267 if ((int) fwrite (buffer, sizeof(*buffer), cc, ce->ce_fp) < cc) {
2268 advise ("open7Bit", "fwrite");
2269 }
2270 if (ferror (ce->ce_fp)) {
2271 content_error (ce->ce_file, ct, "error writing to");
2272 goto clean_up;
2273 }
2274 }
2275
2276 fseek (ct->c_fp, 0L, SEEK_SET);
2277
2278 if (fflush (ce->ce_fp)) {
2279 content_error (ce->ce_file, ct, "error writing to");
2280 goto clean_up;
2281 }
2282
2283 fseek (ce->ce_fp, 0L, SEEK_SET);
2284
2285 ready_to_go:
2286 *file = ce->ce_file;
2287 if (own_ct_fp) {
2288 fclose (ct->c_fp);
2289 ct->c_fp = NULL;
2290 }
2291 return fileno (ce->ce_fp);
2292
2293 clean_up:
2294 free_encoding (ct, 0);
2295 if (own_ct_fp) {
2296 fclose (ct->c_fp);
2297 ct->c_fp = NULL;
2298 }
2299 return NOTOK;
2300 }
2301
2302
2303 /*
2304 * External
2305 */
2306
2307 static int
2308 openExternal (CT ct, CT cb, CE ce, char **file, int *fd)
2309 {
2310 char cachefile[BUFSIZ];
2311
2312 if (ce->ce_fp) {
2313 fseek (ce->ce_fp, 0L, SEEK_SET);
2314 goto ready_already;
2315 }
2316
2317 if (ce->ce_file) {
2318 if ((ce->ce_fp = fopen (ce->ce_file, "r")) == NULL) {
2319 content_error (ce->ce_file, ct, "unable to fopen for reading");
2320 return NOTOK;
2321 }
2322 goto ready_already;
2323 }
2324
2325 if (find_cache (ct, rcachesw, (int *) 0, cb->c_id,
2326 cachefile, sizeof(cachefile)) != NOTOK) {
2327 if ((ce->ce_fp = fopen (cachefile, "r"))) {
2328 ce->ce_file = mh_xstrdup(cachefile);
2329 ce->ce_unlink = 0;
2330 goto ready_already;
2331 }
2332 admonish (cachefile, "unable to fopen for reading");
2333 }
2334
2335 *fd = fileno (ce->ce_fp);
2336 return OK;
2337
2338 ready_already:
2339 *file = ce->ce_file;
2340 *fd = fileno (ce->ce_fp);
2341 return DONE;
2342 }
2343
2344 /*
2345 * File
2346 */
2347
2348 static int
2349 InitFile (CT ct)
2350 {
2351 return init_encoding (ct, openFile);
2352 }
2353
2354
2355 static int
2356 openFile (CT ct, char **file)
2357 {
2358 int fd, cachetype;
2359 char cachefile[BUFSIZ];
2360 struct exbody *e = ct->c_ctexbody;
2361 CE ce = &ct->c_cefile;
2362
2363 switch (openExternal (e->eb_parent, e->eb_content, ce, file, &fd)) {
2364 case NOTOK:
2365 return NOTOK;
2366
2367 case OK:
2368 break;
2369
2370 case DONE:
2371 return fd;
2372 }
2373
2374 if (!e->eb_name) {
2375 content_error (NULL, ct, "missing name parameter");
2376 return NOTOK;
2377 }
2378
2379 ce->ce_file = mh_xstrdup(e->eb_name);
2380 ce->ce_unlink = 0;
2381
2382 if ((ce->ce_fp = fopen (ce->ce_file, "r")) == NULL) {
2383 content_error (ce->ce_file, ct, "unable to fopen for reading");
2384 return NOTOK;
2385 }
2386
2387 if ((!e->eb_permission || strcasecmp (e->eb_permission, "read-write"))
2388 && find_cache (NULL, wcachesw, &cachetype, e->eb_content->c_id,
2389 cachefile, sizeof(cachefile)) != NOTOK) {
2390 int mask;
2391 FILE *fp;
2392
2393 mask = umask (cachetype ? ~m_gmprot () : 0222);
2394 if ((fp = fopen (cachefile, "w"))) {
2395 int cc;
2396 char buffer[BUFSIZ];
2397 FILE *gp = ce->ce_fp;
2398
2399 fseek (gp, 0L, SEEK_SET);
2400
2401 while ((cc = fread (buffer, sizeof(*buffer), sizeof(buffer), gp))
2402 > 0)
2403 if ((int) fwrite (buffer, sizeof(*buffer), cc, fp) < cc) {
2404 advise ("openFile", "fwrite");
2405 }
2406 fflush (fp);
2407
2408 if (ferror (gp)) {
2409 admonish (ce->ce_file, "error reading");
2410 (void) m_unlink (cachefile);
2411 }
2412 else
2413 if (ferror (fp)) {
2414 admonish (cachefile, "error writing");
2415 (void) m_unlink (cachefile);
2416 }
2417 fclose (fp);
2418 }
2419 umask (mask);
2420 }
2421
2422 fseek (ce->ce_fp, 0L, SEEK_SET);
2423 *file = ce->ce_file;
2424 return fileno (ce->ce_fp);
2425 }
2426
2427 /*
2428 * FTP
2429 */
2430
2431 static int
2432 InitFTP (CT ct)
2433 {
2434 return init_encoding (ct, openFTP);
2435 }
2436
2437
2438 static int
2439 openFTP (CT ct, char **file)
2440 {
2441 int cachetype, caching, fd;
2442 int len, buflen;
2443 char *bp, *ftp, *user, *pass;
2444 char buffer[BUFSIZ], cachefile[BUFSIZ];
2445 struct exbody *e;
2446 CE ce = &ct->c_cefile;
2447 static char *username = NULL;
2448 static char *password = NULL;
2449
2450 e = ct->c_ctexbody;
2451
2452 if ((ftp = context_find (nmhaccessftp)) && !*ftp)
2453 ftp = NULL;
2454
2455 if (!ftp)
2456 return NOTOK;
2457
2458 switch (openExternal (e->eb_parent, e->eb_content, ce, file, &fd)) {
2459 case NOTOK:
2460 return NOTOK;
2461
2462 case OK:
2463 break;
2464
2465 case DONE:
2466 return fd;
2467 }
2468
2469 if (!e->eb_name || !e->eb_site) {
2470 content_error (NULL, ct, "missing %s parameter",
2471 e->eb_name ? "site": "name");
2472 return NOTOK;
2473 }
2474
2475 /* Get the buffer ready to go */
2476 bp = buffer;
2477 buflen = sizeof(buffer);
2478
2479 /*
2480 * Construct the query message for user
2481 */
2482 snprintf (bp, buflen, "Retrieve %s", e->eb_name);
2483 len = strlen (bp);
2484 bp += len;
2485 buflen -= len;
2486
2487 if (e->eb_partno) {
2488 snprintf (bp, buflen, " (content %s)", e->eb_partno);
2489 len = strlen (bp);
2490 bp += len;
2491 buflen -= len;
2492 }
2493
2494 snprintf (bp, buflen, "\n using %sFTP from site %s",
2495 e->eb_flags ? "anonymous " : "", e->eb_site);
2496 len = strlen (bp);
2497 bp += len;
2498 buflen -= len;
2499
2500 if (e->eb_size > 0) {
2501 snprintf (bp, buflen, " (%lu octets)", e->eb_size);
2502 len = strlen (bp);
2503 bp += len;
2504 buflen -= len;
2505 }
2506 snprintf (bp, buflen, "? ");
2507
2508 /*
2509 * Now, check the answer
2510 */
2511 if (!read_yes_or_no_if_tty (buffer))
2512 return NOTOK;
2513
2514 if (e->eb_flags) {
2515 user = "anonymous";
2516 snprintf (buffer, sizeof(buffer), "%s@%s", getusername (),
2517 LocalName (1));
2518 pass = buffer;
2519 } else {
2520 ruserpass (e->eb_site, &username, &password, 0);
2521 user = username;
2522 pass = password;
2523 }
2524
2525 ce->ce_unlink = (*file == NULL);
2526 caching = 0;
2527 cachefile[0] = '\0';
2528 if ((!e->eb_permission || strcasecmp (e->eb_permission, "read-write"))
2529 && find_cache (NULL, wcachesw, &cachetype, e->eb_content->c_id,
2530 cachefile, sizeof(cachefile)) != NOTOK) {
2531 if (*file == NULL) {
2532 ce->ce_unlink = 0;
2533 caching = 1;
2534 }
2535 }
2536
2537 if (*file)
2538 ce->ce_file = mh_xstrdup(*file);
2539 else if (caching)
2540 ce->ce_file = mh_xstrdup(cachefile);
2541 else {
2542 char *tempfile;
2543 if ((tempfile = m_mktemp2(NULL, invo_name, NULL, NULL)) == NULL) {
2544 adios(NULL, "unable to create temporary file in %s",
2545 get_temp_dir());
2546 }
2547 ce->ce_file = mh_xstrdup(tempfile);
2548 }
2549
2550 if ((ce->ce_fp = fopen (ce->ce_file, "w+")) == NULL) {
2551 content_error (ce->ce_file, ct, "unable to fopen for reading/writing");
2552 return NOTOK;
2553 }
2554
2555 {
2556 int child_id, i, vecp;
2557 char *vec[9];
2558
2559 vecp = 0;
2560 vec[vecp++] = r1bindex (ftp, '/');
2561 vec[vecp++] = e->eb_site;
2562 vec[vecp++] = user;
2563 vec[vecp++] = pass;
2564 vec[vecp++] = e->eb_dir;
2565 vec[vecp++] = e->eb_name;
2566 vec[vecp++] = ce->ce_file,
2567 vec[vecp++] = e->eb_mode && !strcasecmp (e->eb_mode, "ascii")
2568 ? "ascii" : "binary";
2569 vec[vecp] = NULL;
2570
2571 fflush (stdout);
2572
2573 for (i = 0; (child_id = fork()) == NOTOK && i < 5; i++)
2574 sleep (5);
2575 switch (child_id) {
2576 case NOTOK:
2577 adios ("fork", "unable to");
2578 /* NOTREACHED */
2579
2580 case OK:
2581 close (fileno (ce->ce_fp));
2582 execvp (ftp, vec);
2583 fprintf (stderr, "unable to exec ");
2584 perror (ftp);
2585 _exit (-1);
2586 /* NOTREACHED */
2587
2588 default:
2589 if (pidXwait (child_id, NULL)) {
2590 username = password = NULL;
2591 ce->ce_unlink = 1;
2592 return NOTOK;
2593 }
2594 break;
2595 }
2596 }
2597
2598 if (cachefile[0]) {
2599 if (caching)
2600 chmod (cachefile, cachetype ? m_gmprot () : 0444);
2601 else {
2602 int mask;
2603 FILE *fp;
2604
2605 mask = umask (cachetype ? ~m_gmprot () : 0222);
2606 if ((fp = fopen (cachefile, "w"))) {
2607 int cc;
2608 FILE *gp = ce->ce_fp;
2609
2610 fseek (gp, 0L, SEEK_SET);
2611
2612 while ((cc= fread (buffer, sizeof(*buffer), sizeof(buffer), gp))
2613 > 0)
2614 if ((int) fwrite (buffer, sizeof(*buffer), cc, fp) < cc) {
2615 advise ("openFTP", "fwrite");
2616 }
2617 fflush (fp);
2618
2619 if (ferror (gp)) {
2620 admonish (ce->ce_file, "error reading");
2621 (void) m_unlink (cachefile);
2622 }
2623 else
2624 if (ferror (fp)) {
2625 admonish (cachefile, "error writing");
2626 (void) m_unlink (cachefile);
2627 }
2628 fclose (fp);
2629 }
2630 umask (mask);
2631 }
2632 }
2633
2634 fseek (ce->ce_fp, 0L, SEEK_SET);
2635 *file = ce->ce_file;
2636 return fileno (ce->ce_fp);
2637 }
2638
2639
2640 /*
2641 * Mail
2642 */
2643
2644 static int
2645 InitMail (CT ct)
2646 {
2647 return init_encoding (ct, openMail);
2648 }
2649
2650
2651 static int
2652 openMail (CT ct, char **file)
2653 {
2654 int child_id, fd, i, vecp;
2655 int len, buflen;
2656 char *bp, buffer[BUFSIZ], *vec[7];
2657 struct exbody *e = ct->c_ctexbody;
2658 CE ce = &ct->c_cefile;
2659
2660 switch (openExternal (e->eb_parent, e->eb_content, ce, file, &fd)) {
2661 case NOTOK:
2662 return NOTOK;
2663
2664 case OK:
2665 break;
2666
2667 case DONE:
2668 return fd;
2669 }
2670
2671 if (!e->eb_server) {
2672 content_error (NULL, ct, "missing server parameter");
2673 return NOTOK;
2674 }
2675
2676 /* Get buffer ready to go */
2677 bp = buffer;
2678 buflen = sizeof(buffer);
2679
2680 /* Now, construct query message */
2681 snprintf (bp, buflen, "Retrieve content");
2682 len = strlen (bp);
2683 bp += len;
2684 buflen -= len;
2685
2686 if (e->eb_partno) {
2687 snprintf (bp, buflen, " %s", e->eb_partno);
2688 len = strlen (bp);
2689 bp += len;
2690 buflen -= len;
2691 }
2692
2693 snprintf (bp, buflen, " by asking %s\n\n%s\n? ",
2694 e->eb_server,
2695 e->eb_subject ? e->eb_subject : e->eb_body);
2696
2697 /* Now, check answer */
2698 if (!read_yes_or_no_if_tty (buffer))
2699 return NOTOK;
2700
2701 vecp = 0;
2702 vec[vecp++] = r1bindex (mailproc, '/');
2703 vec[vecp++] = e->eb_server;
2704 vec[vecp++] = "-subject";
2705 vec[vecp++] = e->eb_subject ? e->eb_subject : "mail-server request";
2706 vec[vecp++] = "-body";
2707 vec[vecp++] = e->eb_body;
2708 vec[vecp] = NULL;
2709
2710 for (i = 0; (child_id = fork()) == NOTOK && i < 5; i++)
2711 sleep (5);
2712 switch (child_id) {
2713 case NOTOK:
2714 advise ("fork", "unable to");
2715 return NOTOK;
2716
2717 case OK:
2718 execvp (mailproc, vec);
2719 fprintf (stderr, "unable to exec ");
2720 perror (mailproc);
2721 _exit (-1);
2722 /* NOTREACHED */
2723
2724 default:
2725 if (pidXwait (child_id, NULL) == OK)
2726 inform("request sent");
2727 break;
2728 }
2729
2730 if (*file == NULL) {
2731 char *tempfile;
2732 if ((tempfile = m_mktemp2(NULL, invo_name, NULL, NULL)) == NULL) {
2733 adios(NULL, "unable to create temporary file in %s",
2734 get_temp_dir());
2735 }
2736 ce->ce_file = mh_xstrdup(tempfile);
2737 ce->ce_unlink = 1;
2738 } else {
2739 ce->ce_file = mh_xstrdup(*file);
2740 ce->ce_unlink = 0;
2741 }
2742
2743 if ((ce->ce_fp = fopen (ce->ce_file, "w+")) == NULL) {
2744 content_error (ce->ce_file, ct, "unable to fopen for reading/writing");
2745 return NOTOK;
2746 }
2747
2748 /* showproc is for mhshow and mhstore, though mhlist -debug
2749 * prints it, too. */
2750 mh_xfree(ct->c_showproc);
2751 ct->c_showproc = mh_xstrdup("true");
2752
2753 fseek (ce->ce_fp, 0L, SEEK_SET);
2754 *file = ce->ce_file;
2755 return fileno (ce->ce_fp);
2756 }
2757
2758
2759 /*
2760 * URL
2761 */
2762
2763 static int
2764 InitURL (CT ct)
2765 {
2766 return init_encoding (ct, openURL);
2767 }
2768
2769
2770 static int
2771 openURL (CT ct, char **file)
2772 {
2773 struct exbody *e = ct->c_ctexbody;
2774 CE ce = &ct->c_cefile;
2775 char *urlprog, *program;
2776 char buffer[BUFSIZ], cachefile[BUFSIZ];
2777 int fd, caching, cachetype;
2778 struct msgs_array args = { 0, 0, NULL};
2779 pid_t child_id;
2780
2781 if ((urlprog = context_find(nmhaccessurl)) && *urlprog == '\0')
2782 urlprog = NULL;
2783
2784 if (! urlprog) {
2785 content_error(NULL, ct, "No entry for nmh-access-url in profile");
2786 return NOTOK;
2787 }
2788
2789 switch (openExternal(e->eb_parent, e->eb_content, ce, file, &fd)) {
2790 case NOTOK:
2791 return NOTOK;
2792
2793 case OK:
2794 break;
2795
2796 case DONE:
2797 return fd;
2798 }
2799
2800 if (!e->eb_url) {
2801 content_error(NULL, ct, "missing url parameter");
2802 return NOTOK;
2803 }
2804
2805 ce->ce_unlink = (*file == NULL);
2806 caching = 0;
2807 cachefile[0] = '\0';
2808
2809 if (find_cache(NULL, wcachesw, &cachetype, e->eb_content->c_id,
2810 cachefile, sizeof(cachefile)) != NOTOK) {
2811 if (*file == NULL) {
2812 ce->ce_unlink = 0;
2813 caching = 1;
2814 }
2815 }
2816
2817 if (*file)
2818 ce->ce_file = mh_xstrdup(*file);
2819 else if (caching)
2820 ce->ce_file = mh_xstrdup(cachefile);
2821 else {
2822 char *tempfile;
2823 if ((tempfile = m_mktemp2(NULL, invo_name, NULL, NULL)) == NULL) {
2824 adios(NULL, "unable to create temporary file in %s",
2825 get_temp_dir());
2826 }
2827 ce->ce_file = mh_xstrdup(tempfile);
2828 }
2829
2830 if ((ce->ce_fp = fopen(ce->ce_file, "w+")) == NULL) {
2831 content_error(ce->ce_file, ct, "unable to fopen for read/writing");
2832 return NOTOK;
2833 }
2834
2835 switch (child_id = fork()) {
2836 case NOTOK:
2837 adios ("fork", "unable to");
2838 /* NOTREACHED */
2839
2840 case OK:
2841 argsplit_msgarg(&args, urlprog, &program);
2842 app_msgarg(&args, e->eb_url);
2843 app_msgarg(&args, NULL);
2844 dup2(fileno(ce->ce_fp), 1);
2845 close(fileno(ce->ce_fp));
2846 execvp(program, args.msgs);
2847 fprintf(stderr, "Unable to exec ");
2848 perror(program);
2849 _exit(-1);
2850 /* NOTREACHED */
2851
2852 default:
2853 if (pidXwait(child_id, NULL)) {
2854 ce->ce_unlink = 1;
2855 return NOTOK;
2856 }
2857 }
2858
2859 if (cachefile[0]) {
2860 if (caching)
2861 chmod(cachefile, cachetype ? m_gmprot() : 0444);
2862 else {
2863 int mask;
2864 FILE *fp;
2865
2866 mask = umask (cachetype ? ~m_gmprot() : 0222);
2867 if ((fp = fopen(cachefile, "w"))) {
2868 int cc;
2869 FILE *gp = ce->ce_fp;
2870
2871 fseeko(gp, 0, SEEK_SET);
2872
2873 while ((cc = fread(buffer, sizeof(*buffer),
2874 sizeof(buffer), gp)) > 0)
2875 if ((int) fwrite(buffer, sizeof(*buffer), cc, fp) < cc) {
2876 advise ("openURL", "fwrite");
2877 }
2878
2879 fflush(fp);
2880
2881 if (ferror(gp)) {
2882 admonish(ce->ce_file, "error reading");
2883 (void) m_unlink (cachefile);
2884 }
2885 }
2886 umask(mask);
2887 }
2888 }
2889
2890 fseeko(ce->ce_fp, 0, SEEK_SET);
2891 *file = ce->ce_file;
2892 return fd;
2893 }
2894
2895
2896 /*
2897 * Stores MD5 digest (in cp, from Content-MD5 header) in ct->c_digest. It
2898 * has to be base64 decoded.
2899 */
2900 static int
2901 readDigest (CT ct, char *cp)
2902 {
2903 unsigned char *digest;
2904
2905 size_t len;
2906 if (decodeBase64 (cp, &digest, &len, 0, NULL) == OK) {
2907 const size_t maxlen = sizeof ct->c_digest / sizeof ct->c_digest[0];
2908
2909 if (strlen ((char *) digest) <= maxlen) {
2910 memcpy (ct->c_digest, digest, maxlen);
2911
2912 if (debugsw) {
2913 size_t i;
2914
2915 fprintf (stderr, "MD5 digest=");
2916 for (i = 0; i < maxlen; ++i) {
2917 fprintf (stderr, "%02x", ct->c_digest[i] & 0xff);
2918 }
2919 fprintf (stderr, "\n");
2920 }
2921
2922 return OK;
2923 }
2924 if (debugsw) {
2925 fprintf (stderr, "invalid MD5 digest (got %d octets)\n",
2926 (int) strlen ((char *) digest));
2927 }
2928
2929 return NOTOK;
2930 }
2931
2932 return NOTOK;
2933 }
2934
2935
2936 /* Multipart parts might have content before the first subpart and/or
2937 after the last subpart that hasn't been stored anywhere else, so do
2938 that. */
2939 int
2940 get_leftover_mp_content (CT ct, int before /* or after */)
2941 {
2942 struct multipart *m = (struct multipart *) ct->c_ctparams;
2943 char *boundary;
2944 int found_boundary = 0;
2945 int max = BUFSIZ;
2946 char *bufp = NULL;
2947 size_t buflen;
2948 ssize_t gotlen;
2949 int read = 0;
2950 char *content = NULL;
2951
2952 if (! m) return NOTOK;
2953
2954 if (before) {
2955 if (! m->mp_parts || ! m->mp_parts->mp_part) return NOTOK;
2956
2957 /* Isolate the beginning of this part to the beginning of the
2958 first subpart and save any content between them. */
2959 fseeko (ct->c_fp, ct->c_begin, SEEK_SET);
2960 max = m->mp_parts->mp_part->c_begin - ct->c_begin;
2961 boundary = concat ("--", m->mp_start, NULL);
2962 } else {
2963 struct part *last_subpart = NULL;
2964 struct part *subpart;
2965
2966 /* Go to the last subpart to get its end position. */
2967 for (subpart = m->mp_parts; subpart; subpart = subpart->mp_next) {
2968 last_subpart = subpart;
2969 }
2970
2971 if (last_subpart == NULL) return NOTOK;
2972
2973 /* Isolate the end of the last subpart to the end of this part
2974 and save any content between them. */
2975 fseeko (ct->c_fp, last_subpart->mp_part->c_end, SEEK_SET);
2976 max = ct->c_end - last_subpart->mp_part->c_end;
2977 boundary = concat ("--", m->mp_stop, NULL);
2978 }
2979
2980 /* Back up by 1 to pick up the newline. */
2981 while ((gotlen = getline(&bufp, &buflen, ct->c_fp)) != -1) {
2982 read += gotlen;
2983 /* Don't look beyond beginning of first subpart (before) or
2984 next part (after). */
2985 if (read > max) bufp[read-max] = '\0';
2986
2987 if (before) {
2988 if (! strcmp (bufp, boundary)) {
2989 found_boundary = 1;
2990 }
2991 } else {
2992 if (! found_boundary && ! strcmp (bufp, boundary)) {
2993 found_boundary = 1;
2994 continue;
2995 }
2996 }
2997
2998 if ((before && ! found_boundary) || (! before && found_boundary)) {
2999 if (content) {
3000 char *old_content = content;
3001 content = concat (content, bufp, NULL);
3002 free (old_content);
3003 } else {
3004 content = before
3005 ? concat ("\n", bufp, NULL)
3006 : concat (bufp, NULL);
3007 }
3008 }
3009
3010 if (before) {
3011 if (found_boundary || read > max) break;
3012 } else {
3013 if (read > max) break;
3014 }
3015 }
3016
3017 /* Skip the newline if that's all there is. */
3018 if (content) {
3019 char *cp;
3020
3021 /* Remove trailing newline, except at EOF. */
3022 if ((before || ! feof (ct->c_fp)) &&
3023 (cp = content + strlen (content)) > content &&
3024 *--cp == '\n') {
3025 *cp = '\0';
3026 }
3027
3028 if (strlen (content) > 1) {
3029 if (before) {
3030 m->mp_content_before = content;
3031 } else {
3032 m->mp_content_after = content;
3033 }
3034 } else {
3035 free (content);
3036 }
3037 }
3038
3039 free (boundary);
3040 free (bufp);
3041
3042 return OK;
3043 }
3044
3045
3046 char *
3047 ct_type_str (int type) {
3048 switch (type) {
3049 case CT_APPLICATION:
3050 return "application";
3051 case CT_AUDIO:
3052 return "audio";
3053 case CT_IMAGE:
3054 return "image";
3055 case CT_MESSAGE:
3056 return "message";
3057 case CT_MULTIPART:
3058 return "multipart";
3059 case CT_TEXT:
3060 return "text";
3061 case CT_VIDEO:
3062 return "video";
3063 case CT_EXTENSION:
3064 return "extension";
3065 default:
3066 return "unknown_type";
3067 }
3068 }
3069
3070
3071 char *
3072 ct_subtype_str (int type, int subtype) {
3073 switch (type) {
3074 case CT_APPLICATION:
3075 switch (subtype) {
3076 case APPLICATION_OCTETS:
3077 return "octets";
3078 case APPLICATION_POSTSCRIPT:
3079 return "postscript";
3080 default:
3081 return "unknown_app_subtype";
3082 }
3083 case CT_MESSAGE:
3084 switch (subtype) {
3085 case MESSAGE_RFC822:
3086 return "rfc822";
3087 case MESSAGE_PARTIAL:
3088 return "partial";
3089 case MESSAGE_EXTERNAL:
3090 return "external";
3091 default:
3092 return "unknown_msg_subtype";
3093 }
3094 case CT_MULTIPART:
3095 switch (subtype) {
3096 case MULTI_MIXED:
3097 return "mixed";
3098 case MULTI_ALTERNATE:
3099 return "alternative";
3100 case MULTI_DIGEST:
3101 return "digest";
3102 case MULTI_PARALLEL:
3103 return "parallel";
3104 case MULTI_RELATED:
3105 return "related";
3106 default:
3107 return "unknown_multipart_subtype";
3108 }
3109 case CT_TEXT:
3110 switch (subtype) {
3111 case TEXT_PLAIN:
3112 return "plain";
3113 case TEXT_RICHTEXT:
3114 return "richtext";
3115 case TEXT_ENRICHED:
3116 return "enriched";
3117 default:
3118 return "unknown_text_subtype";
3119 }
3120 default:
3121 return "unknown_type";
3122 }
3123 }
3124
3125
3126 int
3127 ct_str_type (const char *type) {
3128 struct str2init *s2i;
3129
3130 for (s2i = str2cts; s2i->si_key; ++s2i) {
3131 if (! strcasecmp (type, s2i->si_key)) {
3132 break;
3133 }
3134 }
3135 if (! s2i->si_key && ! uprf (type, "X-")) {
3136 ++s2i;
3137 }
3138
3139 return s2i->si_val;
3140 }
3141
3142
3143 int
3144 ct_str_subtype (int type, const char *subtype) {
3145 struct k2v *kv;
3146
3147 switch (type) {
3148 case CT_APPLICATION:
3149 for (kv = SubApplication; kv->kv_key; ++kv) {
3150 if (! strcasecmp (subtype, kv->kv_key)) {
3151 break;
3152 }
3153 }
3154 return kv->kv_value;
3155 case CT_MESSAGE:
3156 for (kv = SubMessage; kv->kv_key; ++kv) {
3157 if (! strcasecmp (subtype, kv->kv_key)) {
3158 break;
3159 }
3160 }
3161 return kv->kv_value;
3162 case CT_MULTIPART:
3163 for (kv = SubMultiPart; kv->kv_key; ++kv) {
3164 if (! strcasecmp (subtype, kv->kv_key)) {
3165 break;
3166 }
3167 }
3168 return kv->kv_value;
3169 case CT_TEXT:
3170 for (kv = SubText; kv->kv_key; ++kv) {
3171 if (! strcasecmp (subtype, kv->kv_key)) {
3172 break;
3173 }
3174 }
3175 return kv->kv_value;
3176 default:
3177 return 0;
3178 }
3179 }
3180
3181
3182 /* Find the content type and InitFunc for the CT. */
3183 const struct str2init *
3184 get_ct_init (int type) {
3185 const struct str2init *sp;
3186
3187 for (sp = str2cts; sp->si_key; ++sp) {
3188 if (type == sp->si_val) {
3189 return sp;
3190 }
3191 }
3192
3193 return NULL;
3194 }
3195
3196 const char *
3197 ce_str (int encoding) {
3198 switch (encoding) {
3199 case CE_BASE64:
3200 return "base64";
3201 case CE_QUOTED:
3202 return "quoted-printable";
3203 case CE_8BIT:
3204 return "8bit";
3205 case CE_7BIT:
3206 return "7bit";
3207 case CE_BINARY:
3208 return "binary";
3209 case CE_EXTENSION:
3210 return "extension";
3211 case CE_EXTERNAL:
3212 return "external";
3213 default:
3214 return "unknown";
3215 }
3216 }
3217
3218 /* Find the content type and InitFunc for the content encoding method. */
3219 const struct str2init *
3220 get_ce_method (const char *method) {
3221 struct str2init *sp;
3222
3223 for (sp = str2ces; sp->si_key; ++sp) {
3224 if (! strcasecmp (method, sp->si_key)) {
3225 return sp;
3226 }
3227 }
3228
3229 return NULL;
3230 }
3231
3232 /*
3233 * Parse a series of MIME attributes (or parameters) given a header as
3234 * input.
3235 *
3236 * Arguments include:
3237 *
3238 * filename - Name of input file (for error messages)
3239 * fieldname - Name of field being processed
3240 * headerp - Pointer to pointer of the beginning of the MIME attributes.
3241 * Updated to point to end of attributes when finished.
3242 * param_head - Pointer to head of parameter list
3243 * param_tail - Pointer to tail of parameter list
3244 * commentp - Pointer to header comment pointer (may be NULL)
3245 *
3246 * Returns OK if parsing was successful, NOTOK if parsing failed, and
3247 * DONE to indicate a benign error (minor parsing error, but the program
3248 * should continue).
3249 */
3250
3251 static int
3252 parse_header_attrs (const char *filename, const char *fieldname,
3253 char **header_attrp, PM *param_head, PM *param_tail,
3254 char **commentp)
3255 {
3256 char *cp = *header_attrp;
3257 PM pm;
3258 struct sectlist {
3259 char *value;
3260 int index;
3261 int len;
3262 struct sectlist *next;
3263 } *sp, *sp2;
3264 struct parmlist {
3265 char *name;
3266 char *charset;
3267 char *lang;
3268 struct sectlist *sechead;
3269 struct parmlist *next;
3270 } *pp, *pp2, *phead = NULL;
3271
3272 while (*cp == ';') {
3273 char *dp, *vp, *up, *nameptr, *valptr, *charset = NULL, *lang = NULL;
3274 int encoded = 0, partial = 0, len = 0, index = 0;
3275
3276 cp++;
3277 while (isspace ((unsigned char) *cp))
3278 cp++;
3279
3280 if (*cp == '(' &&
3281 get_comment (filename, fieldname, &cp, commentp) == NOTOK) {
3282 return NOTOK;
3283 }
3284
3285 if (*cp == 0) {
3286 if (! suppress_extraneous_trailing_semicolon_warning) {
3287 inform("extraneous trailing ';' in message %s's %s: "
3288 "parameter list", filename, fieldname);
3289 }
3290 return DONE;
3291 }
3292
3293 /* down case the attribute name */
3294 for (dp = cp; istoken ((unsigned char) *dp); dp++)
3295 *dp = tolower ((unsigned char) *dp);
3296
3297 for (up = dp; isspace ((unsigned char) *dp);)
3298 dp++;
3299 if (dp == cp || *dp != '=') {
3300 inform("invalid parameter in message %s's %s: "
3301 "field\n%*sparameter %s (error detected at offset %d)",
3302 filename, fieldname, strlen(invo_name) + 2, "",cp, dp - cp);
3303 return NOTOK;
3304 }
3305
3306 /*
3307 * To handle RFC 2231, we have to deal with the following extensions:
3308 *
3309 * name*=encoded-value
3310 * name*<N>=part-N-of-a-parameter-value
3311 * name*<N>*=encoded-part-N-of-a-parameter-value
3312 *
3313 * So the rule is:
3314 * If there's a * right before the equal sign, it's encoded.
3315 * If there's a * and one or more digits, then it's section N.
3316 *
3317 * Remember we can have one or the other, or both. cp points to
3318 * beginning of name, up points past the last character in the
3319 * parameter name.
3320 */
3321
3322 for (vp = cp; vp < up; vp++) {
3323 if (*vp == '*' && vp < up - 1) {
3324 partial = 1;
3325 continue;
3326 }
3327 if (*vp == '*' && vp == up - 1) {
3328 encoded = 1;
3329 } else if (partial) {
3330 if (isdigit((unsigned char) *vp))
3331 index = *vp - '0' + index * 10;
3332 else {
3333 inform("invalid parameter index in message %s's "
3334 "%s: field\n%*s(parameter %s)", filename,
3335 fieldname, strlen(invo_name) + 2, "", cp);
3336 return NOTOK;
3337 }
3338 } else {
3339 len++;
3340 }
3341 }
3342
3343 /*
3344 * Break out the parameter name and value sections and allocate
3345 * memory for each.
3346 */
3347
3348 nameptr = mh_xmalloc(len + 1);
3349 strncpy(nameptr, cp, len);
3350 nameptr[len] = '\0';
3351
3352 for (dp++; isspace ((unsigned char) *dp);)
3353 dp++;
3354
3355 if (encoded) {
3356 /*
3357 * Single quotes delimit the character set and language tag.
3358 * They are required on the first section (or a complete
3359 * parameter).
3360 */
3361 if (index == 0) {
3362 vp = dp;
3363 while (*vp != '\'' && !isspace((unsigned char) *vp) &&
3364 *vp != '\0')
3365 vp++;
3366 if (*vp == '\'') {
3367 if (vp != dp) {
3368 len = vp - dp;
3369 charset = mh_xmalloc(len + 1);
3370 strncpy(charset, dp, len);
3371 charset[len] = '\0';
3372 } else {
3373 charset = NULL;
3374 }
3375 vp++;
3376 } else {
3377 inform("missing charset in message %s's %s: "
3378 "field\n%*s(parameter %s)", filename, fieldname,
3379 strlen(invo_name) + 2, "", nameptr);
3380 free(nameptr);
3381 return NOTOK;
3382 }
3383 dp = vp;
3384
3385 while (*vp != '\'' && !isspace((unsigned char) *vp) &&
3386 *vp != '\0')
3387 vp++;
3388
3389 if (*vp == '\'') {
3390 if (vp != dp) {
3391 len = vp - dp;
3392 lang = mh_xmalloc(len + 1);
3393 strncpy(lang, dp, len);
3394 lang[len] = '\0';
3395 } else {
3396 lang = NULL;
3397 }
3398 vp++;
3399 } else {
3400 inform("missing language tag in message %s's %s: "
3401 "field\n%*s(parameter %s)", filename, fieldname,
3402 strlen(invo_name) + 2, "", nameptr);
3403 free(nameptr);
3404 mh_xfree(charset);
3405 return NOTOK;
3406 }
3407
3408 dp = vp;
3409 }
3410
3411 /*
3412 * At this point vp should be pointing at the beginning
3413 * of the encoded value/section. Continue until we reach
3414 * the end or get whitespace. But first, calculate the
3415 * length so we can allocate the correct buffer size.
3416 */
3417
3418 for (vp = dp, len = 0; istoken(*vp); vp++) {
3419 if (*vp == '%') {
3420 if (*(vp + 1) == '\0' ||
3421 !isxdigit((unsigned char) *(vp + 1)) ||
3422 *(vp + 2) == '\0' ||
3423 !isxdigit((unsigned char) *(vp + 2))) {
3424 inform("invalid encoded sequence in message "
3425 "%s's %s: field\n%*s(parameter %s)",
3426 filename, fieldname, strlen(invo_name) + 2,
3427 "", nameptr);
3428 free(nameptr);
3429 mh_xfree(charset);
3430 mh_xfree(lang);
3431 return NOTOK;
3432 }
3433 vp += 2;
3434 }
3435 len++;
3436 }
3437
3438 up = valptr = mh_xmalloc(len + 1);
3439
3440 for (vp = dp; istoken(*vp); vp++) {
3441 if (*vp == '%') {
3442 *up++ = decode_qp(*(vp + 1), *(vp + 2));
3443 vp += 2;
3444 } else {
3445 *up++ = *vp;
3446 }
3447 }
3448
3449 *up = '\0';
3450 cp = vp;
3451 } else {
3452 /*
3453 * A "normal" string. If it's got a leading quote, then we
3454 * strip the quotes out. Otherwise go until we reach the end
3455 * or get whitespace. Note we scan it twice; once to get the
3456 * length, then the second time copies it into the destination
3457 * buffer.
3458 */
3459
3460 len = 0;
3461
3462 if (*dp == '"') {
3463 for (cp = dp + 1;;) {
3464 switch (*cp++) {
3465 case '\0':
3466 bad_quote:
3467 inform("invalid quoted-string in message %s's %s: "
3468 "field\n%*s(parameter %s)", filename,
3469 fieldname, strlen(invo_name) + 2, "", nameptr);
3470 free(nameptr);
3471 mh_xfree(charset);
3472 mh_xfree(lang);
3473 return NOTOK;
3474 case '"':
3475 break;
3476
3477 case '\\':
3478 if (*++cp == '\0')
3479 goto bad_quote;
3480 /* FALLTHRU */
3481 default:
3482 len++;
3483 continue;
3484 }
3485 break;
3486 }
3487
3488 } else {
3489 for (cp = dp; istoken (*cp); cp++) {
3490 len++;
3491 }
3492 }
3493
3494 valptr = mh_xmalloc(len + 1);
3495
3496 if (*dp == '"') {
3497 int i;
3498 for (cp = dp + 1, vp = valptr, i = 0; i < len; i++) {
3499 if (*cp == '\\') {
3500 cp++;
3501 }
3502 *vp++ = *cp++;
3503 }
3504 cp++;
3505 } else {
3506 strncpy(valptr, cp = dp, len);
3507 cp += len;
3508 }
3509
3510 valptr[len] = '\0';
3511 }
3512
3513 /*
3514 * If 'partial' is set, we don't allocate a parameter now. We
3515 * put it on the parameter linked list to be reassembled later.
3516 *
3517 * "phead" points to a list of all parameters we need to reassemble.
3518 * Each parameter has a list of sections. We insert the sections in
3519 * order.
3520 */
3521
3522 if (partial) {
3523 for (pp = phead; pp != NULL; pp = pp->next) {
3524 if (strcasecmp(nameptr, pp->name) == 0) {
3525 free (nameptr);
3526 nameptr = pp->name;
3527 break;
3528 }
3529 }
3530
3531 if (pp == NULL) {
3532 NEW0(pp);
3533 pp->name = nameptr;
3534 pp->next = phead;
3535 phead = pp;
3536 }
3537
3538 /*
3539 * Insert this into the section linked list
3540 */
3541
3542 NEW0(sp);
3543 sp->value = valptr;
3544 sp->index = index;
3545 sp->len = len;
3546
3547 if (pp->sechead == NULL || pp->sechead->index > index) {
3548 sp->next = pp->sechead;
3549 pp->sechead = sp;
3550 } else {
3551 for (sp2 = pp->sechead; sp2 != NULL; sp2 = sp2->next) {
3552 if (sp2->index == sp->index) {
3553 inform("duplicate index (%d) in message "
3554 "%s's %s: field\n%*s(parameter %s)", sp->index,
3555 filename, fieldname, strlen(invo_name) + 2, "",
3556 nameptr);
3557 return NOTOK;
3558 }
3559 if (sp2->index < sp->index &&
3560 (sp2->next == NULL || sp2->next->index > sp->index)) {
3561 sp->next = sp2->next;
3562 sp2->next = sp;
3563 break;
3564 }
3565 }
3566
3567 if (sp2 == NULL) {
3568 inform("Internal error: cannot insert partial "
3569 "param in message %s's %s: field\n%*s(parameter %s)",
3570 filename, fieldname, strlen(invo_name) + 2, "",
3571 nameptr);
3572 return NOTOK;
3573 }
3574 }
3575
3576 /*
3577 * Save our charset and lang tags.
3578 */
3579
3580 if (index == 0 && encoded) {
3581 mh_xfree(pp->charset);
3582 pp->charset = charset;
3583 mh_xfree(pp->lang);
3584 pp->lang = lang;
3585 }
3586 } else {
3587 pm = add_param(param_head, param_tail, nameptr, valptr, 1);
3588 pm->pm_charset = charset;
3589 pm->pm_lang = lang;
3590 }
3591
3592 while (isspace ((unsigned char) *cp))
3593 cp++;
3594
3595 if (*cp == '(' &&
3596 get_comment (filename, fieldname, &cp, commentp) == NOTOK) {
3597 return NOTOK;
3598 }
3599 }
3600
3601 /*
3602 * Now that we're done, reassemble all of the partial parameters.
3603 */
3604
3605 for (pp = phead; pp != NULL; ) {
3606 char *p, *q;
3607 size_t tlen = 0;
3608 int pindex = 0;
3609 for (sp = pp->sechead; sp != NULL; sp = sp->next) {
3610 if (sp->index != pindex++) {
3611 inform("missing section %d for parameter in "
3612 "message %s's %s: field\n%*s(parameter %s)", pindex - 1,
3613 filename, fieldname, strlen(invo_name) + 2, "",
3614 pp->name);
3615 return NOTOK;
3616 }
3617 tlen += sp->len;
3618 }
3619
3620 p = q = mh_xmalloc(tlen + 1);
3621 for (sp = pp->sechead; sp != NULL; ) {
3622 memcpy(q, sp->value, sp->len);
3623 q += sp->len;
3624 free(sp->value);
3625 sp2 = sp->next;
3626 free(sp);
3627 sp = sp2;
3628 }
3629
3630 p[tlen] = '\0';
3631
3632 pm = add_param(param_head, param_tail, pp->name, p, 1);
3633 pm->pm_charset = pp->charset;
3634 pm->pm_lang = pp->lang;
3635 pp2 = pp->next;
3636 free(pp);
3637 pp = pp2;
3638 }
3639
3640 *header_attrp = cp;
3641 return OK;
3642 }
3643
3644 /*
3645 * Return the charset for a particular content type.
3646 */
3647
3648 char *
3649 content_charset (CT ct) {
3650 char *ret_charset = NULL;
3651
3652 ret_charset = get_param(ct->c_ctinfo.ci_first_pm, "charset", '?', 0);
3653
3654 return ret_charset ? ret_charset : mh_xstrdup("US-ASCII");
3655 }
3656
3657
3658 /*
3659 * Create a string based on a list of output parameters. Assume that this
3660 * parameter string will be appended to an existing header, so start out
3661 * with the separator (;). Perform RFC 2231 encoding when necessary.
3662 */
3663
3664 char *
3665 output_params(size_t initialwidth, PM params, int *offsetout, int external)
3666 {
3667 char *paramout = NULL;
3668 char line[CPERLIN * 2], *q;
3669 int curlen, index, cont, encode, i;
3670 size_t valoff, numchars;
3671
3672 while (params != NULL) {
3673 encode = 0;
3674 index = 0;
3675 valoff = 0;
3676 q = line;
3677
3678 if (external && strcasecmp(params->pm_name, "body") == 0)
3679 continue;
3680
3681 if (strlen(params->pm_name) > CPERLIN) {
3682 inform("Parameter name \"%s\" is too long", params->pm_name);
3683 mh_xfree(paramout);
3684 return NULL;
3685 }
3686
3687 curlen = param_len(params, index, valoff, &encode, &cont, &numchars);
3688
3689 /*
3690 * Loop until we get a parameter that fits within a line. We
3691 * assume new lines start with a tab, so check our overflow based
3692 * on that.
3693 */
3694
3695 while (cont) {
3696 *q++ = ';';
3697 *q++ = '\n';
3698 *q++ = '\t';
3699
3700 /*
3701 * At this point we're definitely continuing the line, so
3702 * be sure to include the parameter name and section index.
3703 */
3704
3705 q += snprintf(q, sizeof(line) - (q - line), "%s*%d",
3706 params->pm_name, index);
3707
3708 /*
3709 * Both of these functions do a NUL termination
3710 */
3711
3712 if (encode)
3713 i = encode_param(params, q, sizeof(line) - (q - line),
3714 numchars, valoff, index);
3715 else
3716 i = normal_param(params, q, sizeof(line) - (q - line),
3717 numchars, valoff);
3718
3719 if (i == 0) {
3720 mh_xfree(paramout);
3721 return NULL;
3722 }
3723
3724 valoff += numchars;
3725 index++;
3726 curlen = param_len(params, index, valoff, &encode, &cont,
3727 &numchars);
3728 q = line;
3729
3730 /*
3731 * "line" starts with a ;\n\t, so that doesn't count against
3732 * the length. But add 8 since it starts with a tab; that's
3733 * how we end up with 5.
3734 */
3735
3736 initialwidth = strlen(line) + 5;
3737
3738 /*
3739 * At this point the line should be built, so add it to our
3740 * current output buffer.
3741 */
3742
3743 paramout = add(line, paramout);
3744 }
3745
3746 /*
3747 * If this won't fit on the line, start a new one. Save room in
3748 * case we need a semicolon on the end
3749 */
3750
3751 if (initialwidth + curlen > CPERLIN - 1) {
3752 *q++ = ';';
3753 *q++ = '\n';
3754 *q++ = '\t';
3755 initialwidth = 8;
3756 } else {
3757 *q++ = ';';
3758 *q++ = ' ';
3759 initialwidth += 2;
3760 }
3761
3762 /*
3763 * At this point, we're either finishing a continued parameter, or
3764 * we're working on a new one.
3765 */
3766
3767 if (index > 0) {
3768 q += snprintf(q, sizeof(line) - (q - line), "%s*%d",
3769 params->pm_name, index);
3770 } else {
3771 strncpy(q, params->pm_name, sizeof(line) - (q - line));
3772 q += strlen(q);
3773 }
3774
3775 if (encode)
3776 i = encode_param(params, q, sizeof(line) - (q - line),
3777 strlen(params->pm_value + valoff), valoff, index);
3778 else
3779 i = normal_param(params, q, sizeof(line) - (q - line),
3780 strlen(params->pm_value + valoff), valoff);
3781
3782 if (i == 0) {
3783 mh_xfree(paramout);
3784 return NULL;
3785 }
3786
3787 paramout = add(line, paramout);
3788 initialwidth += strlen(line);
3789
3790 params = params->pm_next;
3791 }
3792
3793 if (offsetout)
3794 *offsetout = initialwidth;
3795
3796 return paramout;
3797 }
3798
3799 /*
3800 * Calculate the size of a parameter.
3801 *
3802 * Arguments include
3803 *
3804 * pm - The parameter being output
3805 * index - If continuing the parameter, the index of the section
3806 * we're on.
3807 * valueoff - The current offset into the parameter value that we're
3808 * working on (previous sections have consumed valueoff bytes).
3809 * encode - Set if we should perform encoding on this parameter section
3810 * (given that we're consuming bytesfit bytes).
3811 * cont - Set if the remaining data in value will not fit on a single
3812 * line and will need to be continued.
3813 * bytesfit - The number of bytes that we can consume from the parameter
3814 * value and still fit on a completely new line. The
3815 * calculation assumes the new line starts with a tab,
3816 * includes the parameter name and any encoding, and fits
3817 * within CPERLIN bytes. Will always be at least 1.
3818 */
3819
3820 static size_t
3821 param_len(PM pm, int index, size_t valueoff, int *encode, int *cont,
3822 size_t *bytesfit)
3823 {
3824 char *start = pm->pm_value + valueoff, *p, indexchar[32];
3825 size_t len = 0, fit = 0;
3826 int fitlimit = 0, eightbit, maxfit;
3827
3828 *encode = 0;
3829
3830 /*
3831 * Add up the length. First, start with the parameter name.
3832 */
3833
3834 len = strlen(pm->pm_name);
3835
3836 /*
3837 * Scan the parameter value and see if we need to do encoding for this
3838 * section.
3839 */
3840
3841 eightbit = contains8bit(start, NULL);
3842
3843 /*
3844 * Determine if we need to encode this section. Encoding is necessary if:
3845 *
3846 * - There are any 8-bit characters at all and we're on the first
3847 * section.
3848 * - There are 8-bit characters within N bytes of our section start.
3849 * N is calculated based on the number of bytes it would take to
3850 * reach CPERLIN. Specifically:
3851 * 8 (starting tab) +
3852 * strlen(param name) +
3853 * 4 ('* for section marker, '=', opening/closing '"')
3854 * strlen (index)
3855 * is the number of bytes used by everything that isn't part of the
3856 * value. So that gets subtracted from CPERLIN.
3857 */
3858
3859 snprintf(indexchar, sizeof(indexchar), "%d", index);
3860 maxfit = CPERLIN - (12 + len + strlen(indexchar));
3861 if ((eightbit && index == 0) || contains8bit(start, start + maxfit)) {
3862 *encode = 1;
3863 }
3864
3865 len++; /* Add in equal sign */
3866
3867 if (*encode) {
3868 /*
3869 * We're using maxfit as a marker for how many characters we can
3870 * fit into the line. Bump it by two because we're not using quotes
3871 * when encoding.
3872 */
3873
3874 maxfit += 2;
3875
3876 /*
3877 * If we don't have a charset or language tag in this parameter,
3878 * add them now.
3879 */
3880
3881 if (! pm->pm_charset) {
3882 pm->pm_charset = mh_xstrdup(write_charset_8bit());
3883 if (strcasecmp(pm->pm_charset, "US-ASCII") == 0)
3884 adios(NULL, "8-bit characters in parameter \"%s\", but "
3885 "local character set is US-ASCII", pm->pm_name);
3886 }
3887 if (! pm->pm_lang)
3888 pm->pm_lang = mh_xstrdup(""); /* Default to a blank lang tag */
3889
3890 len++; /* For the encoding marker */
3891 maxfit--;
3892 if (index == 0) {
3893 int enclen = strlen(pm->pm_charset) + strlen(pm->pm_lang) + 2;
3894 len += enclen;
3895 maxfit-= enclen;
3896 } else {
3897 /*
3898 * We know we definitely need to include an index. maxfit already
3899 * includes the section marker.
3900 */
3901 len += strlen(indexchar);
3902 }
3903 for (p = start; *p != '\0'; p++) {
3904 if (isparamencode(*p)) {
3905 len += 3;
3906 maxfit -= 3;
3907 } else {
3908 len++;
3909 maxfit--;
3910 }
3911 /*
3912 * Just so there's no confusion: maxfit is counting OUTPUT
3913 * characters (post-encoding). fit is counting INPUT characters.
3914 */
3915 if (! fitlimit && maxfit >= 0)
3916 fit++;
3917 else if (! fitlimit)
3918 fitlimit++;
3919 }
3920 } else {
3921 /*
3922 * Calculate the string length, but add room for quoting \
3923 * and " if necessary. Also account for quotes at beginning
3924 * and end.
3925 */
3926 for (p = start; *p != '\0'; p++) {
3927 switch (*p) {
3928 case '"':
3929 case '\\':
3930 len++;
3931 maxfit--;
3932 /* FALLTHRU */
3933 default:
3934 len++;
3935 maxfit--;
3936 }
3937 if (! fitlimit && maxfit >= 0)
3938 fit++;
3939 else if (! fitlimit)
3940 fitlimit++;
3941 }
3942
3943 len += 2;
3944 }
3945
3946 if (fit < 1)
3947 fit = 1;
3948
3949 *cont = fitlimit;
3950 *bytesfit = fit;
3951
3952 return len;
3953 }
3954
3955 /*
3956 * Output an encoded parameter string.
3957 */
3958
3959 size_t
3960 encode_param(PM pm, char *output, size_t len, size_t valuelen,
3961 size_t valueoff, int index)
3962 {
3963 size_t outlen = 0, n;
3964 char *endptr = output + len, *p;
3965
3966 /*
3967 * First, output the marker for an encoded string.
3968 */
3969
3970 *output++ = '*';
3971 *output++ = '=';
3972 outlen += 2;
3973
3974 /*
3975 * If the index is 0, output the character set and language tag.
3976 * If theses were NULL, they should have already been filled in
3977 * by param_len().
3978 */
3979
3980 if (index == 0) {
3981 n = snprintf(output, len - outlen, "%s'%s'", pm->pm_charset,
3982 pm->pm_lang);
3983 output += n;
3984 outlen += n;
3985 if (output > endptr) {
3986 inform("Internal error: parameter buffer overflow");
3987 return 0;
3988 }
3989 }
3990
3991 /*
3992 * Copy over the value, encoding if necessary
3993 */
3994
3995 p = pm->pm_value + valueoff;
3996 while (valuelen-- > 0) {
3997 if (isparamencode(*p)) {
3998 n = snprintf(output, len - outlen, "%%%02X", (unsigned char) *p++);
3999 output += n;
4000 outlen += n;
4001 } else {
4002 *output++ = *p++;
4003 outlen++;
4004 }
4005 if (output > endptr) {
4006 inform("Internal error: parameter buffer overflow");
4007 return 0;
4008 }
4009 }
4010
4011 *output = '\0';
4012
4013 return outlen;
4014 }
4015
4016 /*
4017 * Output a "normal" parameter, without encoding. Be sure to escape
4018 * quotes and backslashes if necessary.
4019 */
4020
4021 static size_t
4022 normal_param(PM pm, char *output, size_t len, size_t valuelen,
4023 size_t valueoff)
4024 {
4025 size_t outlen = 0;
4026 char *endptr = output + len, *p;
4027
4028 *output++ = '=';
4029 *output++ = '"';
4030 outlen += 2;
4031
4032 p = pm->pm_value + valueoff;
4033
4034 while (valuelen-- > 0) {
4035 switch (*p) {
4036 case '\\':
4037 case '"':
4038 *output++ = '\\';
4039 outlen++;
4040 /* FALLTHRU */
4041 default:
4042 *output++ = *p++;
4043 outlen++;
4044 }
4045 if (output > endptr) {
4046 inform("Internal error: parameter buffer overflow");
4047 return 0;
4048 }
4049 }
4050
4051 if (output - 2 > endptr) {
4052 inform("Internal error: parameter buffer overflow");
4053 return 0;
4054 }
4055
4056 *output++ = '"';
4057 *output++ = '\0';
4058
4059 return outlen + 1;
4060 }
4061
4062 /*
4063 * Add a parameter to the parameter linked list
4064 */
4065
4066 PM
4067 add_param(PM *first, PM *last, char *name, char *value, int nocopy)
4068 {
4069 PM pm;
4070
4071 NEW0(pm);
4072 pm->pm_name = nocopy ? name : getcpy(name);
4073 pm->pm_value = nocopy ? value : getcpy(value);
4074
4075 if (*first) {
4076 (*last)->pm_next = pm;
4077 *last = pm;
4078 } else {
4079 *first = pm;
4080 *last = pm;
4081 }
4082
4083 return pm;
4084 }
4085
4086 /*
4087 * Either replace a current parameter with a new value, or add the parameter
4088 * to the parameter linked list.
4089 */
4090
4091 PM
4092 replace_param(PM *first, PM *last, char *name, char *value, int nocopy)
4093 {
4094 PM pm;
4095
4096 for (pm = *first; pm != NULL; pm = pm->pm_next) {
4097 if (strcasecmp(name, pm->pm_name) == 0) {
4098 /*
4099 * If nocopy is set, it's assumed that we own both name
4100 * and value. We don't need name, so we discard it now.
4101 */
4102 if (nocopy)
4103 free(name);
4104 free(pm->pm_value);
4105 pm->pm_value = nocopy ? value : getcpy(value);
4106 return pm;
4107 }
4108 }
4109
4110 return add_param(first, last, name, value, nocopy);
4111 }
4112
4113 /*
4114 * Retrieve a parameter value from a parameter linked list. If the parameter
4115 * value needs converted to the local character set, do that now.
4116 */
4117
4118 char *
4119 get_param(PM first, const char *name, char replace, int fetchonly)
4120 {
4121 while (first != NULL) {
4122 if (strcasecmp(name, first->pm_name) == 0) {
4123 if (fetchonly)
4124 return first->pm_value;
4125 return getcpy(get_param_value(first, replace));
4126 }
4127 first = first->pm_next;
4128 }
4129
4130 return NULL;
4131 }
4132
4133 /*
4134 * Return a parameter value, converting to the local character set if
4135 * necessary
4136 */
4137
4138 char *get_param_value(PM pm, char replace)
4139 {
4140 static char buffer[4096]; /* I hope no parameters are larger */
4141 size_t bufsize = sizeof(buffer);
4142 #ifdef HAVE_ICONV
4143 size_t inbytes;
4144 int utf8;
4145 iconv_t cd;
4146 ICONV_CONST char *p;
4147 #else /* HAVE_ICONV */
4148 char *p;
4149 #endif /* HAVE_ICONV */
4150
4151 char *q;
4152
4153 /*
4154 * If we don't have a character set indicated, it's assumed to be
4155 * US-ASCII. If it matches our character set, we don't need to convert
4156 * anything.
4157 */
4158
4159 if (!pm->pm_charset || check_charset(pm->pm_charset,
4160 strlen(pm->pm_charset))) {
4161 return pm->pm_value;
4162 }
4163
4164 /*
4165 * In this case, we need to convert. If we have iconv support, use
4166 * that. Otherwise, go through and simply replace every non-ASCII
4167 * character with the substitution character.
4168 */
4169
4170 #ifdef HAVE_ICONV
4171 q = buffer;
4172 bufsize = sizeof(buffer);
4173 utf8 = strcasecmp(pm->pm_charset, "UTF-8") == 0;
4174
4175 cd = iconv_open(get_charset(), pm->pm_charset);
4176 if (cd == (iconv_t) -1) {
4177 goto noiconv;
4178 }
4179
4180 inbytes = strlen(pm->pm_value);
4181 p = pm->pm_value;
4182
4183 while (inbytes) {
4184 if (iconv(cd, &p, &inbytes, &q, &bufsize) == (size_t)-1) {
4185 if (errno != EILSEQ) {
4186 iconv_close(cd);
4187 goto noiconv;
4188 }
4189 /*
4190 * Reset shift state, substitute our character,
4191 * try to restart conversion.
4192 */
4193
4194 iconv(cd, NULL, NULL, &q, &bufsize);
4195
4196 if (bufsize == 0) {
4197 iconv_close(cd);
4198 goto noiconv;
4199 }
4200 *q++ = replace;
4201 bufsize--;
4202 if (bufsize == 0) {
4203 iconv_close(cd);
4204 goto noiconv;
4205 }
4206 if (utf8) {
4207 for (++p, --inbytes;
4208 inbytes > 0 && (((unsigned char) *p) & 0xc0) == 0x80;
4209 ++p, --inbytes)
4210 continue;
4211 } else {
4212 p++;
4213 inbytes--;
4214 }
4215 }
4216 }
4217
4218 iconv_close(cd);
4219
4220 if (bufsize == 0)
4221 q--;
4222 *q = '\0';
4223
4224 return buffer;
4225
4226 noiconv:
4227 #endif /* HAVE_ICONV */
4228
4229 /*
4230 * Take everything non-ASCII and substitute the replacement character
4231 */
4232
4233 q = buffer;
4234 bufsize = sizeof(buffer);
4235 for (p = pm->pm_value; *p != '\0' && bufsize > 1; p++, q++, bufsize--) {
4236 if (isascii((unsigned char) *p) && isprint((unsigned char) *p))
4237 *q = *p;
4238 else
4239 *q = replace;
4240 }
4241
4242 *q = '\0';
4243
4244 return buffer;
4245 }