Update copyright year
[openssl.git] / crypto / asn1 / asn_mime.c
1 /*
2  * Copyright 2008-2021 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #include <stdio.h>
11 #include "crypto/ctype.h"
12 #include "internal/cryptlib.h"
13 #include <openssl/rand.h>
14 #include <openssl/x509.h>
15 #include <openssl/asn1.h>
16 #include <openssl/asn1t.h>
17 #include <openssl/cms.h>
18 #include "crypto/evp.h"
19 #include "internal/bio.h"
20 #include "asn1_local.h"
21
22 /*
23  * Generalised MIME like utilities for streaming ASN1. Although many have a
24  * PKCS7/CMS like flavour others are more general purpose.
25  */
26
27 /*
28  * MIME format structures Note that all are translated to lower case apart
29  * from parameter values. Quotes are stripped off
30  */
31
32 struct mime_param_st {
33     char *param_name;           /* Param name e.g. "micalg" */
34     char *param_value;          /* Param value e.g. "sha1" */
35 };
36
37 struct mime_header_st {
38     char *name;                 /* Name of line e.g. "content-type" */
39     char *value;                /* Value of line e.g. "text/plain" */
40     STACK_OF(MIME_PARAM) *params; /* Zero or more parameters */
41 };
42
43 static int asn1_output_data(BIO *out, BIO *data, ASN1_VALUE *val, int flags,
44                             const ASN1_ITEM *it);
45 static char *strip_ends(char *name);
46 static char *strip_start(char *name);
47 static char *strip_end(char *name);
48 static MIME_HEADER *mime_hdr_new(const char *name, const char *value);
49 static int mime_hdr_addparam(MIME_HEADER *mhdr, const char *name, const char *value);
50 static STACK_OF(MIME_HEADER) *mime_parse_hdr(BIO *bio);
51 static int mime_hdr_cmp(const MIME_HEADER *const *a,
52                         const MIME_HEADER *const *b);
53 static int mime_param_cmp(const MIME_PARAM *const *a,
54                           const MIME_PARAM *const *b);
55 static void mime_param_free(MIME_PARAM *param);
56 static int mime_bound_check(char *line, int linelen, const char *bound, int blen);
57 static int multi_split(BIO *bio, int flags, const char *bound, STACK_OF(BIO) **ret);
58 static int strip_eol(char *linebuf, int *plen, int flags);
59 static MIME_HEADER *mime_hdr_find(STACK_OF(MIME_HEADER) *hdrs, const char *name);
60 static MIME_PARAM *mime_param_find(MIME_HEADER *hdr, const char *name);
61 static void mime_hdr_free(MIME_HEADER *hdr);
62
63 #define MAX_SMLEN 1024
64 #define mime_debug(x)           /* x */
65
66 /* Output an ASN1 structure in BER format streaming if necessary */
67
68 /* unfortunately cannot constify this due to CMS_stream() and PKCS7_stream() */
69 int i2d_ASN1_bio_stream(BIO *out, ASN1_VALUE *val, BIO *in, int flags,
70                         const ASN1_ITEM *it)
71 {
72     /* If streaming create stream BIO and copy all content through it */
73     if (flags & SMIME_STREAM) {
74         BIO *bio, *tbio;
75         bio = BIO_new_NDEF(out, val, it);
76         if (!bio) {
77             ERR_raise(ERR_LIB_ASN1, ERR_R_MALLOC_FAILURE);
78             return 0;
79         }
80         SMIME_crlf_copy(in, bio, flags);
81         (void)BIO_flush(bio);
82         /* Free up successive BIOs until we hit the old output BIO */
83         do {
84             tbio = BIO_pop(bio);
85             BIO_free(bio);
86             bio = tbio;
87         } while (bio != out);
88     }
89     /*
90      * else just write out ASN1 structure which will have all content stored
91      * internally
92      */
93     else
94         ASN1_item_i2d_bio(it, out, val);
95     return 1;
96 }
97
98 /* Base 64 read and write of ASN1 structure */
99
100 static int B64_write_ASN1(BIO *out, ASN1_VALUE *val, BIO *in, int flags,
101                           const ASN1_ITEM *it)
102 {
103     BIO *b64;
104     int r;
105     b64 = BIO_new(BIO_f_base64());
106     if (b64 == NULL) {
107         ERR_raise(ERR_LIB_ASN1, ERR_R_MALLOC_FAILURE);
108         return 0;
109     }
110     /*
111      * prepend the b64 BIO so all data is base64 encoded.
112      */
113     out = BIO_push(b64, out);
114     r = i2d_ASN1_bio_stream(out, val, in, flags, it);
115     (void)BIO_flush(out);
116     BIO_pop(out);
117     BIO_free(b64);
118     return r;
119 }
120
121 /* Streaming ASN1 PEM write */
122
123 int PEM_write_bio_ASN1_stream(BIO *out, ASN1_VALUE *val, BIO *in, int flags,
124                               const char *hdr, const ASN1_ITEM *it)
125 {
126     int r;
127     BIO_printf(out, "-----BEGIN %s-----\n", hdr);
128     r = B64_write_ASN1(out, val, in, flags, it);
129     BIO_printf(out, "-----END %s-----\n", hdr);
130     return r;
131 }
132
133 static ASN1_VALUE *b64_read_asn1(BIO *bio, const ASN1_ITEM *it, ASN1_VALUE **x)
134 {
135     BIO *b64;
136     ASN1_VALUE *val;
137
138     if ((b64 = BIO_new(BIO_f_base64())) == NULL) {
139         ERR_raise(ERR_LIB_ASN1, ERR_R_MALLOC_FAILURE);
140         return 0;
141     }
142     bio = BIO_push(b64, bio);
143     val = ASN1_item_d2i_bio(it, bio, x);
144     if (!val)
145         ERR_raise(ERR_LIB_ASN1, ASN1_R_DECODE_ERROR);
146     (void)BIO_flush(bio);
147     BIO_pop(bio);
148     BIO_free(b64);
149     return val;
150 }
151
152 /* Generate the MIME "micalg" parameter from RFC3851, RFC4490 */
153
154 static int asn1_write_micalg(BIO *out, STACK_OF(X509_ALGOR) *mdalgs)
155 {
156     const EVP_MD *md;
157     int i, have_unknown = 0, write_comma, ret = 0, md_nid;
158     have_unknown = 0;
159     write_comma = 0;
160     for (i = 0; i < sk_X509_ALGOR_num(mdalgs); i++) {
161         if (write_comma)
162             BIO_write(out, ",", 1);
163         write_comma = 1;
164         md_nid = OBJ_obj2nid(sk_X509_ALGOR_value(mdalgs, i)->algorithm);
165         md = EVP_get_digestbynid(md_nid);
166         if (md && md->md_ctrl) {
167             int rv;
168             char *micstr;
169             rv = md->md_ctrl(NULL, EVP_MD_CTRL_MICALG, 0, &micstr);
170             if (rv > 0) {
171                 BIO_puts(out, micstr);
172                 OPENSSL_free(micstr);
173                 continue;
174             }
175             if (rv != -2)
176                 goto err;
177         }
178         switch (md_nid) {
179         case NID_sha1:
180             BIO_puts(out, "sha1");
181             break;
182
183         case NID_md5:
184             BIO_puts(out, "md5");
185             break;
186
187         case NID_sha256:
188             BIO_puts(out, "sha-256");
189             break;
190
191         case NID_sha384:
192             BIO_puts(out, "sha-384");
193             break;
194
195         case NID_sha512:
196             BIO_puts(out, "sha-512");
197             break;
198
199         case NID_id_GostR3411_94:
200             BIO_puts(out, "gostr3411-94");
201             goto err;
202
203         case NID_id_GostR3411_2012_256:
204             BIO_puts(out, "gostr3411-2012-256");
205             goto err;
206
207         case NID_id_GostR3411_2012_512:
208             BIO_puts(out, "gostr3411-2012-512");
209             goto err;
210
211         default:
212             if (have_unknown) {
213                 write_comma = 0;
214             } else {
215                 BIO_puts(out, "unknown");
216                 have_unknown = 1;
217             }
218             break;
219
220         }
221     }
222
223     ret = 1;
224  err:
225
226     return ret;
227
228 }
229
230 /* SMIME sender */
231
232 int SMIME_write_ASN1_ex(BIO *bio, ASN1_VALUE *val, BIO *data, int flags,
233                         int ctype_nid, int econt_nid,
234                         STACK_OF(X509_ALGOR) *mdalgs, const ASN1_ITEM *it,
235                         OSSL_LIB_CTX *libctx, const char *propq)
236 {
237     char bound[33], c;
238     int i;
239     const char *mime_prefix, *mime_eol, *cname = "smime.p7m";
240     const char *msg_type = NULL;
241
242     if (flags & SMIME_OLDMIME)
243         mime_prefix = "application/x-pkcs7-";
244     else
245         mime_prefix = "application/pkcs7-";
246
247     if (flags & SMIME_CRLFEOL)
248         mime_eol = "\r\n";
249     else
250         mime_eol = "\n";
251     if ((flags & SMIME_DETACHED) && data) {
252         /* We want multipart/signed */
253         /* Generate a random boundary */
254         if (RAND_bytes_ex(libctx, (unsigned char *)bound, 32) <= 0)
255             return 0;
256         for (i = 0; i < 32; i++) {
257             c = bound[i] & 0xf;
258             if (c < 10)
259                 c += '0';
260             else
261                 c += 'A' - 10;
262             bound[i] = c;
263         }
264         bound[32] = 0;
265         BIO_printf(bio, "MIME-Version: 1.0%s", mime_eol);
266         BIO_printf(bio, "Content-Type: multipart/signed;");
267         BIO_printf(bio, " protocol=\"%ssignature\";", mime_prefix);
268         BIO_puts(bio, " micalg=\"");
269         asn1_write_micalg(bio, mdalgs);
270         BIO_printf(bio, "\"; boundary=\"----%s\"%s%s",
271                    bound, mime_eol, mime_eol);
272         BIO_printf(bio, "This is an S/MIME signed message%s%s",
273                    mime_eol, mime_eol);
274         /* Now write out the first part */
275         BIO_printf(bio, "------%s%s", bound, mime_eol);
276         if (!asn1_output_data(bio, data, val, flags, it))
277             return 0;
278         BIO_printf(bio, "%s------%s%s", mime_eol, bound, mime_eol);
279
280         /* Headers for signature */
281
282         BIO_printf(bio, "Content-Type: %ssignature;", mime_prefix);
283         BIO_printf(bio, " name=\"smime.p7s\"%s", mime_eol);
284         BIO_printf(bio, "Content-Transfer-Encoding: base64%s", mime_eol);
285         BIO_printf(bio, "Content-Disposition: attachment;");
286         BIO_printf(bio, " filename=\"smime.p7s\"%s%s", mime_eol, mime_eol);
287         B64_write_ASN1(bio, val, NULL, 0, it);
288         BIO_printf(bio, "%s------%s--%s%s", mime_eol, bound,
289                    mime_eol, mime_eol);
290         return 1;
291     }
292
293     /* Determine smime-type header */
294
295     if (ctype_nid == NID_pkcs7_enveloped) {
296         msg_type = "enveloped-data";
297     } else if (ctype_nid == NID_pkcs7_signed) {
298         if (econt_nid == NID_id_smime_ct_receipt)
299             msg_type = "signed-receipt";
300         else if (sk_X509_ALGOR_num(mdalgs) >= 0)
301             msg_type = "signed-data";
302         else
303             msg_type = "certs-only";
304     } else if (ctype_nid == NID_id_smime_ct_compressedData) {
305         msg_type = "compressed-data";
306         cname = "smime.p7z";
307     }
308     /* MIME headers */
309     BIO_printf(bio, "MIME-Version: 1.0%s", mime_eol);
310     BIO_printf(bio, "Content-Disposition: attachment;");
311     BIO_printf(bio, " filename=\"%s\"%s", cname, mime_eol);
312     BIO_printf(bio, "Content-Type: %smime;", mime_prefix);
313     if (msg_type)
314         BIO_printf(bio, " smime-type=%s;", msg_type);
315     BIO_printf(bio, " name=\"%s\"%s", cname, mime_eol);
316     BIO_printf(bio, "Content-Transfer-Encoding: base64%s%s",
317                mime_eol, mime_eol);
318     if (!B64_write_ASN1(bio, val, data, flags, it))
319         return 0;
320     BIO_printf(bio, "%s", mime_eol);
321     return 1;
322 }
323
324 int SMIME_write_ASN1(BIO *bio, ASN1_VALUE *val, BIO *data, int flags,
325                      int ctype_nid, int econt_nid,
326                      STACK_OF(X509_ALGOR) *mdalgs, const ASN1_ITEM *it)
327 {
328     return SMIME_write_ASN1_ex(bio, val, data, flags, ctype_nid, econt_nid,
329                                mdalgs, it, NULL, NULL);
330 }
331
332 /* Handle output of ASN1 data */
333
334 /* cannot constify val because of CMS_dataFinal() */
335 static int asn1_output_data(BIO *out, BIO *data, ASN1_VALUE *val, int flags,
336                             const ASN1_ITEM *it)
337 {
338     BIO *tmpbio;
339     const ASN1_AUX *aux = it->funcs;
340     ASN1_STREAM_ARG sarg;
341     int rv = 1;
342
343     /*
344      * If data is not detached or resigning then the output BIO is already
345      * set up to finalise when it is written through.
346      */
347     if (!(flags & SMIME_DETACHED) || (flags & PKCS7_REUSE_DIGEST)) {
348         SMIME_crlf_copy(data, out, flags);
349         return 1;
350     }
351
352     if (!aux || !aux->asn1_cb) {
353         ERR_raise(ERR_LIB_ASN1, ASN1_R_STREAMING_NOT_SUPPORTED);
354         return 0;
355     }
356
357     sarg.out = out;
358     sarg.ndef_bio = NULL;
359     sarg.boundary = NULL;
360
361     /* Let ASN1 code prepend any needed BIOs */
362
363     if (aux->asn1_cb(ASN1_OP_DETACHED_PRE, &val, it, &sarg) <= 0)
364         return 0;
365
366     /* Copy data across, passing through filter BIOs for processing */
367     SMIME_crlf_copy(data, sarg.ndef_bio, flags);
368
369     /* Finalize structure */
370     if (aux->asn1_cb(ASN1_OP_DETACHED_POST, &val, it, &sarg) <= 0)
371         rv = 0;
372
373     /* Now remove any digests prepended to the BIO */
374
375     while (sarg.ndef_bio != out) {
376         tmpbio = BIO_pop(sarg.ndef_bio);
377         BIO_free(sarg.ndef_bio);
378         sarg.ndef_bio = tmpbio;
379     }
380
381     return rv;
382
383 }
384
385 /*
386  * SMIME reader: handle multipart/signed and opaque signing. in multipart
387  * case the content is placed in a memory BIO pointed to by "bcont". In
388  * opaque this is set to NULL
389  */
390
391 ASN1_VALUE *SMIME_read_ASN1_ex(BIO *bio, int flags, BIO **bcont, const ASN1_ITEM *it,
392                                ASN1_VALUE **x)
393 {
394     BIO *asnin;
395     STACK_OF(MIME_HEADER) *headers = NULL;
396     STACK_OF(BIO) *parts = NULL;
397     MIME_HEADER *hdr;
398     MIME_PARAM *prm;
399     ASN1_VALUE *val;
400     int ret;
401
402     if (bcont)
403         *bcont = NULL;
404
405     if ((headers = mime_parse_hdr(bio)) == NULL) {
406         ERR_raise(ERR_LIB_ASN1, ASN1_R_MIME_PARSE_ERROR);
407         return NULL;
408     }
409
410     if ((hdr = mime_hdr_find(headers, "content-type")) == NULL
411         || hdr->value == NULL) {
412         sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
413         ERR_raise(ERR_LIB_ASN1, ASN1_R_NO_CONTENT_TYPE);
414         return NULL;
415     }
416
417     /* Handle multipart/signed */
418
419     if (strcmp(hdr->value, "multipart/signed") == 0) {
420         /* Split into two parts */
421         prm = mime_param_find(hdr, "boundary");
422         if (prm == NULL || prm->param_value == NULL) {
423             sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
424             ERR_raise(ERR_LIB_ASN1, ASN1_R_NO_MULTIPART_BOUNDARY);
425             return NULL;
426         }
427         ret = multi_split(bio, flags, prm->param_value, &parts);
428         sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
429         if (!ret || (sk_BIO_num(parts) != 2)) {
430             ERR_raise(ERR_LIB_ASN1, ASN1_R_NO_MULTIPART_BODY_FAILURE);
431             sk_BIO_pop_free(parts, BIO_vfree);
432             return NULL;
433         }
434
435         /* Parse the signature piece */
436         asnin = sk_BIO_value(parts, 1);
437
438         if ((headers = mime_parse_hdr(asnin)) == NULL) {
439             ERR_raise(ERR_LIB_ASN1, ASN1_R_MIME_SIG_PARSE_ERROR);
440             sk_BIO_pop_free(parts, BIO_vfree);
441             return NULL;
442         }
443
444         /* Get content type */
445
446         if ((hdr = mime_hdr_find(headers, "content-type")) == NULL
447             || hdr->value == NULL) {
448             sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
449             ERR_raise(ERR_LIB_ASN1, ASN1_R_NO_SIG_CONTENT_TYPE);
450             sk_BIO_pop_free(parts, BIO_vfree);
451             return NULL;
452         }
453
454         if (strcmp(hdr->value, "application/x-pkcs7-signature") &&
455             strcmp(hdr->value, "application/pkcs7-signature")) {
456             ERR_raise_data(ERR_LIB_ASN1, ASN1_R_SIG_INVALID_MIME_TYPE,
457                            "type: %s", hdr->value);
458             sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
459             sk_BIO_pop_free(parts, BIO_vfree);
460             return NULL;
461         }
462         sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
463         /* Read in ASN1 */
464         if ((val = b64_read_asn1(asnin, it, x)) == NULL) {
465             ERR_raise(ERR_LIB_ASN1, ASN1_R_ASN1_SIG_PARSE_ERROR);
466             sk_BIO_pop_free(parts, BIO_vfree);
467             return NULL;
468         }
469
470         if (bcont) {
471             *bcont = sk_BIO_value(parts, 0);
472             BIO_free(asnin);
473             sk_BIO_free(parts);
474         } else {
475             sk_BIO_pop_free(parts, BIO_vfree);
476         }
477         return val;
478     }
479
480     /* OK, if not multipart/signed try opaque signature */
481
482     if (strcmp(hdr->value, "application/x-pkcs7-mime") &&
483         strcmp(hdr->value, "application/pkcs7-mime")) {
484         ERR_raise_data(ERR_LIB_ASN1, ASN1_R_INVALID_MIME_TYPE,
485                        "type: %s", hdr->value);
486         sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
487         return NULL;
488     }
489
490     sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
491
492     if ((val = b64_read_asn1(bio, it, x)) == NULL) {
493         ERR_raise(ERR_LIB_ASN1, ASN1_R_ASN1_PARSE_ERROR);
494         return NULL;
495     }
496     return val;
497 }
498
499 ASN1_VALUE *SMIME_read_ASN1(BIO *bio, BIO **bcont, const ASN1_ITEM *it)
500 {
501     return SMIME_read_ASN1_ex(bio, 0, bcont, it, NULL);
502 }
503
504 /* Copy text from one BIO to another making the output CRLF at EOL */
505 int SMIME_crlf_copy(BIO *in, BIO *out, int flags)
506 {
507     BIO *bf;
508     char eol;
509     int len;
510     char linebuf[MAX_SMLEN];
511     /*
512      * Buffer output so we don't write one line at a time. This is useful
513      * when streaming as we don't end up with one OCTET STRING per line.
514      */
515     bf = BIO_new(BIO_f_buffer());
516     if (bf == NULL)
517         return 0;
518     out = BIO_push(bf, out);
519     if (flags & SMIME_BINARY) {
520         while ((len = BIO_read(in, linebuf, MAX_SMLEN)) > 0)
521             BIO_write(out, linebuf, len);
522     } else {
523         int eolcnt = 0;
524         if (flags & SMIME_TEXT)
525             BIO_printf(out, "Content-Type: text/plain\r\n\r\n");
526         while ((len = BIO_gets(in, linebuf, MAX_SMLEN)) > 0) {
527             eol = strip_eol(linebuf, &len, flags);
528             if (len > 0) {
529                 /* Not EOF: write out all CRLF */
530                 if (flags & SMIME_ASCIICRLF) {
531                     int i;
532                     for (i = 0; i < eolcnt; i++)
533                         BIO_write(out, "\r\n", 2);
534                     eolcnt = 0;
535                 }
536                 BIO_write(out, linebuf, len);
537                 if (eol)
538                     BIO_write(out, "\r\n", 2);
539             } else if (flags & SMIME_ASCIICRLF) {
540                 eolcnt++;
541             } else if (eol) {
542                 BIO_write(out, "\r\n", 2);
543             }
544         }
545     }
546     (void)BIO_flush(out);
547     BIO_pop(out);
548     BIO_free(bf);
549     return 1;
550 }
551
552 /* Strip off headers if they are text/plain */
553 int SMIME_text(BIO *in, BIO *out)
554 {
555     char iobuf[4096];
556     int len;
557     STACK_OF(MIME_HEADER) *headers;
558     MIME_HEADER *hdr;
559
560     if ((headers = mime_parse_hdr(in)) == NULL) {
561         ERR_raise(ERR_LIB_ASN1, ASN1_R_MIME_PARSE_ERROR);
562         return 0;
563     }
564     if ((hdr = mime_hdr_find(headers, "content-type")) == NULL
565         || hdr->value == NULL) {
566         ERR_raise(ERR_LIB_ASN1, ASN1_R_MIME_NO_CONTENT_TYPE);
567         sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
568         return 0;
569     }
570     if (strcmp(hdr->value, "text/plain")) {
571         ERR_raise_data(ERR_LIB_ASN1, ASN1_R_INVALID_MIME_TYPE,
572                        "type: %s", hdr->value);
573         sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
574         return 0;
575     }
576     sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
577     while ((len = BIO_read(in, iobuf, sizeof(iobuf))) > 0)
578         BIO_write(out, iobuf, len);
579     if (len < 0)
580         return 0;
581     return 1;
582 }
583
584 /*
585  * Split a multipart/XXX message body into component parts: result is
586  * canonical parts in a STACK of bios
587  */
588
589 static int multi_split(BIO *bio, int flags, const char *bound, STACK_OF(BIO) **ret)
590 {
591     char linebuf[MAX_SMLEN];
592     int len, blen;
593     int eol = 0, next_eol = 0;
594     BIO *bpart = NULL;
595     STACK_OF(BIO) *parts;
596     char state, part, first;
597
598     blen = strlen(bound);
599     part = 0;
600     state = 0;
601     first = 1;
602     parts = sk_BIO_new_null();
603     *ret = parts;
604     if (*ret == NULL)
605         return 0;
606     while ((len = BIO_get_line(bio, linebuf, MAX_SMLEN)) > 0) {
607         state = mime_bound_check(linebuf, len, bound, blen);
608         if (state == 1) {
609             first = 1;
610             part++;
611         } else if (state == 2) {
612             if (!sk_BIO_push(parts, bpart)) {
613                 BIO_free(bpart);
614                 return 0;
615             }
616             return 1;
617         } else if (part != 0) {
618             /* Strip (possibly CR +) LF from linebuf */
619             next_eol = strip_eol(linebuf, &len, flags);
620             if (first) {
621                 first = 0;
622                 if (bpart)
623                     if (!sk_BIO_push(parts, bpart)) {
624                         BIO_free(bpart);
625                         return 0;
626                     }
627                 bpart = BIO_new(BIO_s_mem());
628                 if (bpart == NULL)
629                     return 0;
630                 BIO_set_mem_eof_return(bpart, 0);
631             } else if (eol) {
632                 if (
633 #ifndef OPENSSL_NO_CMS
634                     (flags & CMS_BINARY) == 0
635 #else
636                     1
637 #endif
638                         || (flags & SMIME_CRLFEOL) != 0)
639                     BIO_write(bpart, "\r\n", 2);
640                 else
641                     BIO_write(bpart, "\n", 1);
642             }
643             eol = next_eol;
644             if (len > 0)
645                 BIO_write(bpart, linebuf, len);
646         }
647     }
648     BIO_free(bpart);
649     return 0;
650 }
651
652 /* This is the big one: parse MIME header lines up to message body */
653
654 #define MIME_INVALID    0
655 #define MIME_START      1
656 #define MIME_TYPE       2
657 #define MIME_NAME       3
658 #define MIME_VALUE      4
659 #define MIME_QUOTE      5
660 #define MIME_COMMENT    6
661
662 static STACK_OF(MIME_HEADER) *mime_parse_hdr(BIO *bio)
663 {
664     char *p, *q, c;
665     char *ntmp;
666     char linebuf[MAX_SMLEN];
667     MIME_HEADER *mhdr = NULL, *new_hdr = NULL;
668     STACK_OF(MIME_HEADER) *headers;
669     int len, state, save_state = 0;
670
671     headers = sk_MIME_HEADER_new(mime_hdr_cmp);
672     if (headers == NULL)
673         return NULL;
674     while ((len = BIO_gets(bio, linebuf, MAX_SMLEN)) > 0) {
675         /* If whitespace at line start then continuation line */
676         if (mhdr && ossl_isspace(linebuf[0]))
677             state = MIME_NAME;
678         else
679             state = MIME_START;
680         ntmp = NULL;
681         /* Go through all characters */
682         for (p = linebuf, q = linebuf; (c = *p) && (c != '\r') && (c != '\n');
683              p++) {
684
685             /*
686              * State machine to handle MIME headers if this looks horrible
687              * that's because it *is*
688              */
689
690             switch (state) {
691             case MIME_START:
692                 if (c == ':') {
693                     state = MIME_TYPE;
694                     *p = 0;
695                     ntmp = strip_ends(q);
696                     q = p + 1;
697                 }
698                 break;
699
700             case MIME_TYPE:
701                 if (c == ';') {
702                     mime_debug("Found End Value\n");
703                     *p = 0;
704                     new_hdr = mime_hdr_new(ntmp, strip_ends(q));
705                     if (new_hdr == NULL)
706                         goto err;
707                     if (!sk_MIME_HEADER_push(headers, new_hdr))
708                         goto err;
709                     mhdr = new_hdr;
710                     new_hdr = NULL;
711                     ntmp = NULL;
712                     q = p + 1;
713                     state = MIME_NAME;
714                 } else if (c == '(') {
715                     save_state = state;
716                     state = MIME_COMMENT;
717                 }
718                 break;
719
720             case MIME_COMMENT:
721                 if (c == ')') {
722                     state = save_state;
723                 }
724                 break;
725
726             case MIME_NAME:
727                 if (c == '=') {
728                     state = MIME_VALUE;
729                     *p = 0;
730                     ntmp = strip_ends(q);
731                     q = p + 1;
732                 }
733                 break;
734
735             case MIME_VALUE:
736                 if (c == ';') {
737                     state = MIME_NAME;
738                     *p = 0;
739                     mime_hdr_addparam(mhdr, ntmp, strip_ends(q));
740                     ntmp = NULL;
741                     q = p + 1;
742                 } else if (c == '"') {
743                     mime_debug("Found Quote\n");
744                     state = MIME_QUOTE;
745                 } else if (c == '(') {
746                     save_state = state;
747                     state = MIME_COMMENT;
748                 }
749                 break;
750
751             case MIME_QUOTE:
752                 if (c == '"') {
753                     mime_debug("Found Match Quote\n");
754                     state = MIME_VALUE;
755                 }
756                 break;
757             }
758         }
759
760         if (state == MIME_TYPE) {
761             new_hdr = mime_hdr_new(ntmp, strip_ends(q));
762             if (new_hdr == NULL)
763                 goto err;
764             if (!sk_MIME_HEADER_push(headers, new_hdr))
765                 goto err;
766             mhdr = new_hdr;
767             new_hdr = NULL;
768         } else if (state == MIME_VALUE) {
769             mime_hdr_addparam(mhdr, ntmp, strip_ends(q));
770         }
771         if (p == linebuf)
772             break;              /* Blank line means end of headers */
773     }
774
775     return headers;
776
777  err:
778     mime_hdr_free(new_hdr);
779     sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
780     return NULL;
781 }
782
783 static char *strip_ends(char *name)
784 {
785     return strip_end(strip_start(name));
786 }
787
788 /* Strip a parameter of whitespace from start of param */
789 static char *strip_start(char *name)
790 {
791     char *p, c;
792     /* Look for first non whitespace or quote */
793     for (p = name; (c = *p); p++) {
794         if (c == '"') {
795             /* Next char is start of string if non null */
796             if (p[1])
797                 return p + 1;
798             /* Else null string */
799             return NULL;
800         }
801         if (!ossl_isspace(c))
802             return p;
803     }
804     return NULL;
805 }
806
807 /* As above but strip from end of string : maybe should handle brackets? */
808 static char *strip_end(char *name)
809 {
810     char *p, c;
811     if (!name)
812         return NULL;
813     /* Look for first non whitespace or quote */
814     for (p = name + strlen(name) - 1; p >= name; p--) {
815         c = *p;
816         if (c == '"') {
817             if (p - 1 == name)
818                 return NULL;
819             *p = 0;
820             return name;
821         }
822         if (ossl_isspace(c))
823             *p = 0;
824         else
825             return name;
826     }
827     return NULL;
828 }
829
830 static MIME_HEADER *mime_hdr_new(const char *name, const char *value)
831 {
832     MIME_HEADER *mhdr = NULL;
833     char *tmpname = NULL, *tmpval = NULL, *p;
834
835     if (name) {
836         if ((tmpname = OPENSSL_strdup(name)) == NULL)
837             return NULL;
838         for (p = tmpname; *p; p++)
839             *p = ossl_tolower(*p);
840     }
841     if (value) {
842         if ((tmpval = OPENSSL_strdup(value)) == NULL)
843             goto err;
844         for (p = tmpval; *p; p++)
845             *p = ossl_tolower(*p);
846     }
847     mhdr = OPENSSL_malloc(sizeof(*mhdr));
848     if (mhdr == NULL)
849         goto err;
850     mhdr->name = tmpname;
851     mhdr->value = tmpval;
852     if ((mhdr->params = sk_MIME_PARAM_new(mime_param_cmp)) == NULL)
853         goto err;
854     return mhdr;
855
856  err:
857     OPENSSL_free(tmpname);
858     OPENSSL_free(tmpval);
859     OPENSSL_free(mhdr);
860     return NULL;
861 }
862
863 static int mime_hdr_addparam(MIME_HEADER *mhdr, const char *name, const char *value)
864 {
865     char *tmpname = NULL, *tmpval = NULL, *p;
866     MIME_PARAM *mparam = NULL;
867
868     if (name) {
869         tmpname = OPENSSL_strdup(name);
870         if (!tmpname)
871             goto err;
872         for (p = tmpname; *p; p++)
873             *p = ossl_tolower(*p);
874     }
875     if (value) {
876         tmpval = OPENSSL_strdup(value);
877         if (!tmpval)
878             goto err;
879     }
880     /* Parameter values are case sensitive so leave as is */
881     mparam = OPENSSL_malloc(sizeof(*mparam));
882     if (mparam == NULL)
883         goto err;
884     mparam->param_name = tmpname;
885     mparam->param_value = tmpval;
886     if (!sk_MIME_PARAM_push(mhdr->params, mparam))
887         goto err;
888     return 1;
889  err:
890     OPENSSL_free(tmpname);
891     OPENSSL_free(tmpval);
892     OPENSSL_free(mparam);
893     return 0;
894 }
895
896 static int mime_hdr_cmp(const MIME_HEADER *const *a,
897                         const MIME_HEADER *const *b)
898 {
899     if ((*a)->name == NULL || (*b)->name == NULL)
900         return ((*a)->name != NULL) - ((*b)->name != NULL);
901
902     return strcmp((*a)->name, (*b)->name);
903 }
904
905 static int mime_param_cmp(const MIME_PARAM *const *a,
906                           const MIME_PARAM *const *b)
907 {
908     if ((*a)->param_name == NULL || (*b)->param_name == NULL)
909         return ((*a)->param_name != NULL) - ((*b)->param_name != NULL);
910     return strcmp((*a)->param_name, (*b)->param_name);
911 }
912
913 /* Find a header with a given name (if possible) */
914
915 static MIME_HEADER *mime_hdr_find(STACK_OF(MIME_HEADER) *hdrs, const char *name)
916 {
917     MIME_HEADER htmp;
918     int idx;
919
920     htmp.name = (char *)name;
921     htmp.value = NULL;
922     htmp.params = NULL;
923
924     idx = sk_MIME_HEADER_find(hdrs, &htmp);
925     return sk_MIME_HEADER_value(hdrs, idx);
926 }
927
928 static MIME_PARAM *mime_param_find(MIME_HEADER *hdr, const char *name)
929 {
930     MIME_PARAM param;
931     int idx;
932
933     param.param_name = (char *)name;
934     param.param_value = NULL;
935     idx = sk_MIME_PARAM_find(hdr->params, &param);
936     return sk_MIME_PARAM_value(hdr->params, idx);
937 }
938
939 static void mime_hdr_free(MIME_HEADER *hdr)
940 {
941     if (hdr == NULL)
942         return;
943     OPENSSL_free(hdr->name);
944     OPENSSL_free(hdr->value);
945     if (hdr->params)
946         sk_MIME_PARAM_pop_free(hdr->params, mime_param_free);
947     OPENSSL_free(hdr);
948 }
949
950 static void mime_param_free(MIME_PARAM *param)
951 {
952     OPENSSL_free(param->param_name);
953     OPENSSL_free(param->param_value);
954     OPENSSL_free(param);
955 }
956
957 /*-
958  * Check for a multipart boundary. Returns:
959  * 0 : no boundary
960  * 1 : part boundary
961  * 2 : final boundary
962  */
963 static int mime_bound_check(char *line, int linelen, const char *bound, int blen)
964 {
965     if (linelen == -1)
966         linelen = strlen(line);
967     if (blen == -1)
968         blen = strlen(bound);
969     /* Quickly eliminate if line length too short */
970     if (blen + 2 > linelen)
971         return 0;
972     /* Check for part boundary */
973     if ((strncmp(line, "--", 2) == 0)
974         && strncmp(line + 2, bound, blen) == 0) {
975         if (strncmp(line + blen + 2, "--", 2) == 0)
976             return 2;
977         else
978             return 1;
979     }
980     return 0;
981 }
982
983 static int strip_eol(char *linebuf, int *plen, int flags)
984 {
985     int len = *plen;
986     char *p, c;
987     int is_eol = 0;
988
989 #ifndef OPENSSL_NO_CMS
990     if ((flags & CMS_BINARY) != 0) {
991         if (len <= 0 || linebuf[len - 1] != '\n')
992             return 0;
993         if ((flags & SMIME_CRLFEOL) != 0) {
994             if (len <= 1 || linebuf[len - 2] != '\r')
995                 return 0;
996             len--;
997         }
998         len--;
999         *plen = len;
1000         return 1;
1001     }
1002 #endif
1003
1004     for (p = linebuf + len - 1; len > 0; len--, p--) {
1005         c = *p;
1006         if (c == '\n') {
1007             is_eol = 1;
1008         } else if (is_eol && (flags & SMIME_ASCIICRLF) != 0 && c == 32) {
1009             /* Strip trailing space on a line; 32 == ASCII for ' ' */
1010             continue;
1011         } else if (c != '\r') {
1012             break;
1013         }
1014     }
1015     *plen = len;
1016     return is_eol;
1017 }