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