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