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