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