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