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