Output MIME parameter micalg according to RFC3851 and RFC4490 instead of hard
[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);
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 /* Base 64 read and write of PKCS#7 structure */
114
115 static int B64_write_PKCS7(BIO *bio, PKCS7 *p7)
116 {
117         BIO *b64;
118         if(!(b64 = BIO_new(BIO_f_base64()))) {
119                 PKCS7err(PKCS7_F_B64_WRITE_PKCS7,ERR_R_MALLOC_FAILURE);
120                 return 0;
121         }
122         bio = BIO_push(b64, bio);
123         i2d_PKCS7_bio(bio, p7);
124         BIO_flush(bio);
125         bio = BIO_pop(bio);
126         BIO_free(b64);
127         return 1;
128 }
129
130 static PKCS7 *B64_read_PKCS7(BIO *bio)
131 {
132         BIO *b64;
133         PKCS7 *p7;
134         if(!(b64 = BIO_new(BIO_f_base64()))) {
135                 PKCS7err(PKCS7_F_B64_READ_PKCS7,ERR_R_MALLOC_FAILURE);
136                 return 0;
137         }
138         bio = BIO_push(b64, bio);
139         if(!(p7 = d2i_PKCS7_bio(bio, NULL))) 
140                 PKCS7err(PKCS7_F_B64_READ_PKCS7,PKCS7_R_DECODE_ERROR);
141         BIO_flush(bio);
142         bio = BIO_pop(bio);
143         BIO_free(b64);
144         return p7;
145 }
146
147 /* Generate the MIME "micalg" parameter from RFC3851, RFC4490 */
148
149 static int pk7_write_micalg(BIO *out, PKCS7 *p7)
150         {
151         STACK_OF(X509_ALGOR) *mdalgs;
152         STACK *mic_sk;
153         int i, have_unknown = 0, ret = 0;
154         mdalgs = p7->d.sign->md_algs;
155         mic_sk = sk_new_null();
156         if (!mic_sk)
157                 goto err;
158         have_unknown = 0;
159         for (i = 0; i < sk_X509_ALGOR_num(mdalgs); i++)
160                 {
161                 switch(OBJ_obj2nid(sk_X509_ALGOR_value(mdalgs, i)->algorithm))
162                         {
163                         case NID_sha1:
164                         if (!sk_push(mic_sk, "sha1"))
165                                 goto err;
166                         break;
167
168                         case NID_md5:
169                         if (!sk_push(mic_sk, "md5"))
170                                 goto err;
171                         break;
172
173                         case NID_sha256:
174                         if (!sk_push(mic_sk, "sha-256"))
175                                 goto err;
176                         break;
177
178                         case NID_sha384:
179                         if (!sk_push(mic_sk, "sha-384"))
180                                 goto err;
181                         break;
182
183                         case NID_sha512:
184                         if (!sk_push(mic_sk, "sha-512"))
185                                 goto err;
186                         break;
187
188                         case NID_id_GostR3411_94:
189                         if (!sk_push(mic_sk, "gostr3411-94"))
190                                 goto err;
191                         break;
192
193                         default:
194                         if (!have_unknown)
195                                 {
196                                 if (!sk_push(mic_sk, "unknown"))
197                                         goto err;
198                                 have_unknown = 1;
199                                 }
200                         break;
201
202                         }
203                 }
204
205         for (i = 0; i < sk_num(mic_sk); i++)
206                 {
207                 BIO_puts(out, sk_value(mic_sk, i));
208                 if (i > 0)
209                         BIO_write(out, ",", 1);
210                 }
211         ret = 1;
212         err:
213
214         if (mic_sk)
215                 sk_free(mic_sk);        
216
217         return ret;
218
219         }
220
221
222
223
224 /* SMIME sender */
225
226 int SMIME_write_PKCS7(BIO *bio, PKCS7 *p7, BIO *data, int flags)
227 {
228         char bound[33], c;
229         int i;
230         char *mime_prefix, *mime_eol, *msg_type=NULL;
231         if (flags & PKCS7_NOOLDMIMETYPE)
232                 mime_prefix = "application/pkcs7-";
233         else
234                 mime_prefix = "application/x-pkcs7-";
235
236         if (flags & PKCS7_CRLFEOL)
237                 mime_eol = "\r\n";
238         else
239                 mime_eol = "\n";
240         if((flags & PKCS7_DETACHED) && data) {
241         /* We want multipart/signed */
242                 /* Generate a random boundary */
243                 RAND_pseudo_bytes((unsigned char *)bound, 32);
244                 for(i = 0; i < 32; i++) {
245                         c = bound[i] & 0xf;
246                         if(c < 10) c += '0';
247                         else c += 'A' - 10;
248                         bound[i] = c;
249                 }
250                 bound[32] = 0;
251                 BIO_printf(bio, "MIME-Version: 1.0%s", mime_eol);
252                 BIO_printf(bio, "Content-Type: multipart/signed;");
253                 BIO_printf(bio, " protocol=\"%ssignature\";", mime_prefix);
254                 BIO_puts(bio, " micalg=\"");
255                 pk7_write_micalg(bio, p7);
256                 BIO_printf(bio, "\"; boundary=\"----%s\"%s%s",
257                                                 bound, mime_eol, mime_eol);
258                 BIO_printf(bio, "This is an S/MIME signed message%s%s",
259                                                 mime_eol, mime_eol);
260                 /* Now write out the first part */
261                 BIO_printf(bio, "------%s%s", bound, mime_eol);
262                 pkcs7_output_data(bio, data, p7, flags);
263                 BIO_printf(bio, "%s------%s%s", mime_eol, bound, mime_eol);
264
265                 /* Headers for signature */
266
267                 BIO_printf(bio, "Content-Type: %ssignature;", mime_prefix); 
268                 BIO_printf(bio, " name=\"smime.p7s\"%s", mime_eol);
269                 BIO_printf(bio, "Content-Transfer-Encoding: base64%s",
270                                                                 mime_eol);
271                 BIO_printf(bio, "Content-Disposition: attachment;");
272                 BIO_printf(bio, " filename=\"smime.p7s\"%s%s",
273                                                         mime_eol, mime_eol);
274                 B64_write_PKCS7(bio, p7);
275                 BIO_printf(bio,"%s------%s--%s%s", mime_eol, bound,
276                                                         mime_eol, mime_eol);
277                 return 1;
278         }
279
280         /* Determine smime-type header */
281
282         if (PKCS7_type_is_enveloped(p7))
283                 msg_type = "enveloped-data";
284         else if (PKCS7_type_is_signed(p7))
285                 {
286                 /* If we have any signers it is signed-data otherwise 
287                  * certs-only.
288                  */
289                 STACK_OF(PKCS7_SIGNER_INFO) *sinfos;
290                 sinfos = PKCS7_get_signer_info(p7);
291                 if (sk_PKCS7_SIGNER_INFO_num(sinfos) > 0)
292                         msg_type = "signed-data";
293                 else
294                         msg_type = "certs-only";
295                 }
296         /* MIME headers */
297         BIO_printf(bio, "MIME-Version: 1.0%s", mime_eol);
298         BIO_printf(bio, "Content-Disposition: attachment;");
299         BIO_printf(bio, " filename=\"smime.p7m\"%s", mime_eol);
300         BIO_printf(bio, "Content-Type: %smime;", mime_prefix);
301         if (msg_type)
302                 BIO_printf(bio, " smime-type=%s;", msg_type);
303         BIO_printf(bio, " name=\"smime.p7m\"%s", mime_eol);
304         BIO_printf(bio, "Content-Transfer-Encoding: base64%s%s",
305                                                 mime_eol, mime_eol);
306         B64_write_PKCS7(bio, p7);
307         BIO_printf(bio, "%s", mime_eol);
308         return 1;
309 }
310
311 /* Handle output of PKCS#7 data */
312
313
314 static int pkcs7_output_data(BIO *out, BIO *data, PKCS7 *p7, int flags)
315         {
316         BIO *tmpbio, *p7bio;
317
318         if (!(flags & PKCS7_STREAM))
319                 {
320                 SMIME_crlf_copy(data, out, flags);
321                 return 1;
322                 }
323
324         /* Partial sign operation */
325
326         /* Initialize sign operation */
327         p7bio = PKCS7_dataInit(p7, out);
328
329         /* Copy data across, computing digests etc */
330         SMIME_crlf_copy(data, p7bio, flags);
331
332         /* Must be detached */
333         PKCS7_set_detached(p7, 1);
334
335         /* Finalize signatures */
336         PKCS7_dataFinal(p7, p7bio);
337
338         /* Now remove any digests prepended to the BIO */
339
340         while (p7bio != out)
341                 {
342                 tmpbio = BIO_pop(p7bio);
343                 BIO_free(p7bio);
344                 p7bio = tmpbio;
345                 }
346
347         return 1;
348
349         }
350
351 /* SMIME reader: handle multipart/signed and opaque signing.
352  * in multipart case the content is placed in a memory BIO
353  * pointed to by "bcont". In opaque this is set to NULL
354  */
355
356 PKCS7 *SMIME_read_PKCS7(BIO *bio, BIO **bcont)
357 {
358         BIO *p7in;
359         STACK_OF(MIME_HEADER) *headers = NULL;
360         STACK_OF(BIO) *parts = NULL;
361         MIME_HEADER *hdr;
362         MIME_PARAM *prm;
363         PKCS7 *p7;
364         int ret;
365
366         if(bcont) *bcont = NULL;
367
368         if (!(headers = mime_parse_hdr(bio))) {
369                 PKCS7err(PKCS7_F_SMIME_READ_PKCS7,PKCS7_R_MIME_PARSE_ERROR);
370                 return NULL;
371         }
372
373         if(!(hdr = mime_hdr_find(headers, "content-type")) || !hdr->value) {
374                 sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
375                 PKCS7err(PKCS7_F_SMIME_READ_PKCS7, PKCS7_R_NO_CONTENT_TYPE);
376                 return NULL;
377         }
378
379         /* Handle multipart/signed */
380
381         if(!strcmp(hdr->value, "multipart/signed")) {
382                 /* Split into two parts */
383                 prm = mime_param_find(hdr, "boundary");
384                 if(!prm || !prm->param_value) {
385                         sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
386                         PKCS7err(PKCS7_F_SMIME_READ_PKCS7, PKCS7_R_NO_MULTIPART_BOUNDARY);
387                         return NULL;
388                 }
389                 ret = multi_split(bio, prm->param_value, &parts);
390                 sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
391                 if(!ret || (sk_BIO_num(parts) != 2) ) {
392                         PKCS7err(PKCS7_F_SMIME_READ_PKCS7, PKCS7_R_NO_MULTIPART_BODY_FAILURE);
393                         sk_BIO_pop_free(parts, BIO_vfree);
394                         return NULL;
395                 }
396
397                 /* Parse the signature piece */
398                 p7in = sk_BIO_value(parts, 1);
399
400                 if (!(headers = mime_parse_hdr(p7in))) {
401                         PKCS7err(PKCS7_F_SMIME_READ_PKCS7,PKCS7_R_MIME_SIG_PARSE_ERROR);
402                         sk_BIO_pop_free(parts, BIO_vfree);
403                         return NULL;
404                 }
405
406                 /* Get content type */
407
408                 if(!(hdr = mime_hdr_find(headers, "content-type")) ||
409                                                                  !hdr->value) {
410                         sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
411                         PKCS7err(PKCS7_F_SMIME_READ_PKCS7, PKCS7_R_NO_SIG_CONTENT_TYPE);
412                         return NULL;
413                 }
414
415                 if(strcmp(hdr->value, "application/x-pkcs7-signature") &&
416                         strcmp(hdr->value, "application/pkcs7-signature")) {
417                         sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
418                         PKCS7err(PKCS7_F_SMIME_READ_PKCS7,PKCS7_R_SIG_INVALID_MIME_TYPE);
419                         ERR_add_error_data(2, "type: ", hdr->value);
420                         sk_BIO_pop_free(parts, BIO_vfree);
421                         return NULL;
422                 }
423                 sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
424                 /* Read in PKCS#7 */
425                 if(!(p7 = B64_read_PKCS7(p7in))) {
426                         PKCS7err(PKCS7_F_SMIME_READ_PKCS7,PKCS7_R_PKCS7_SIG_PARSE_ERROR);
427                         sk_BIO_pop_free(parts, BIO_vfree);
428                         return NULL;
429                 }
430
431                 if(bcont) {
432                         *bcont = sk_BIO_value(parts, 0);
433                         BIO_free(p7in);
434                         sk_BIO_free(parts);
435                 } else sk_BIO_pop_free(parts, BIO_vfree);
436                 return p7;
437         }
438                 
439         /* OK, if not multipart/signed try opaque signature */
440
441         if (strcmp (hdr->value, "application/x-pkcs7-mime") &&
442             strcmp (hdr->value, "application/pkcs7-mime")) {
443                 PKCS7err(PKCS7_F_SMIME_READ_PKCS7,PKCS7_R_INVALID_MIME_TYPE);
444                 ERR_add_error_data(2, "type: ", hdr->value);
445                 sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
446                 return NULL;
447         }
448
449         sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
450         
451         if(!(p7 = B64_read_PKCS7(bio))) {
452                 PKCS7err(PKCS7_F_SMIME_READ_PKCS7, PKCS7_R_PKCS7_PARSE_ERROR);
453                 return NULL;
454         }
455         return p7;
456
457 }
458
459 /* Copy text from one BIO to another making the output CRLF at EOL */
460 int SMIME_crlf_copy(BIO *in, BIO *out, int flags)
461 {
462         char eol;
463         int len;
464         char linebuf[MAX_SMLEN];
465         if(flags & PKCS7_BINARY) {
466                 while((len = BIO_read(in, linebuf, MAX_SMLEN)) > 0)
467                                                 BIO_write(out, linebuf, len);
468                 return 1;
469         }
470         if(flags & PKCS7_TEXT)
471                 BIO_printf(out, "Content-Type: text/plain\r\n\r\n");
472         while ((len = BIO_gets(in, linebuf, MAX_SMLEN)) > 0) {
473                 eol = strip_eol(linebuf, &len);
474                 if (len)
475                         BIO_write(out, linebuf, len);
476                 if(eol) BIO_write(out, "\r\n", 2);
477         }
478         return 1;
479 }
480
481 /* Strip off headers if they are text/plain */
482 int SMIME_text(BIO *in, BIO *out)
483 {
484         char iobuf[4096];
485         int len;
486         STACK_OF(MIME_HEADER) *headers;
487         MIME_HEADER *hdr;
488
489         if (!(headers = mime_parse_hdr(in))) {
490                 PKCS7err(PKCS7_F_SMIME_TEXT,PKCS7_R_MIME_PARSE_ERROR);
491                 return 0;
492         }
493         if(!(hdr = mime_hdr_find(headers, "content-type")) || !hdr->value) {
494                 PKCS7err(PKCS7_F_SMIME_TEXT,PKCS7_R_MIME_NO_CONTENT_TYPE);
495                 sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
496                 return 0;
497         }
498         if (strcmp (hdr->value, "text/plain")) {
499                 PKCS7err(PKCS7_F_SMIME_TEXT,PKCS7_R_INVALID_MIME_TYPE);
500                 ERR_add_error_data(2, "type: ", hdr->value);
501                 sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
502                 return 0;
503         }
504         sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
505         while ((len = BIO_read(in, iobuf, sizeof(iobuf))) > 0)
506                                                 BIO_write(out, iobuf, len);
507         return 1;
508 }
509
510 /* Split a multipart/XXX message body into component parts: result is
511  * canonical parts in a STACK of bios
512  */
513
514 static int multi_split(BIO *bio, char *bound, STACK_OF(BIO) **ret)
515 {
516         char linebuf[MAX_SMLEN];
517         int len, blen;
518         int eol = 0, next_eol = 0;
519         BIO *bpart = NULL;
520         STACK_OF(BIO) *parts;
521         char state, part, first;
522
523         blen = strlen(bound);
524         part = 0;
525         state = 0;
526         first = 1;
527         parts = sk_BIO_new_null();
528         *ret = parts;
529         while ((len = BIO_gets(bio, linebuf, MAX_SMLEN)) > 0) {
530                 state = mime_bound_check(linebuf, len, bound, blen);
531                 if(state == 1) {
532                         first = 1;
533                         part++;
534                 } else if(state == 2) {
535                         sk_BIO_push(parts, bpart);
536                         return 1;
537                 } else if(part) {
538                         /* Strip CR+LF from linebuf */
539                         next_eol = strip_eol(linebuf, &len);
540                         if(first) {
541                                 first = 0;
542                                 if(bpart) sk_BIO_push(parts, bpart);
543                                 bpart = BIO_new(BIO_s_mem());
544                                 BIO_set_mem_eof_return(bpart, 0);
545                         } else if (eol)
546                                 BIO_write(bpart, "\r\n", 2);
547                         eol = next_eol;
548                         if (len)
549                                 BIO_write(bpart, linebuf, len);
550                 }
551         }
552         return 0;
553 }
554
555 /* This is the big one: parse MIME header lines up to message body */
556
557 #define MIME_INVALID    0
558 #define MIME_START      1
559 #define MIME_TYPE       2
560 #define MIME_NAME       3
561 #define MIME_VALUE      4
562 #define MIME_QUOTE      5
563 #define MIME_COMMENT    6
564
565
566 static STACK_OF(MIME_HEADER) *mime_parse_hdr(BIO *bio)
567 {
568         char *p, *q, c;
569         char *ntmp;
570         char linebuf[MAX_SMLEN];
571         MIME_HEADER *mhdr = NULL;
572         STACK_OF(MIME_HEADER) *headers;
573         int len, state, save_state = 0;
574
575         headers = sk_MIME_HEADER_new(mime_hdr_cmp);
576         while ((len = BIO_gets(bio, linebuf, MAX_SMLEN)) > 0) {
577         /* If whitespace at line start then continuation line */
578         if(mhdr && isspace((unsigned char)linebuf[0])) state = MIME_NAME;
579         else state = MIME_START;
580         ntmp = NULL;
581         /* Go through all characters */
582         for(p = linebuf, q = linebuf; (c = *p) && (c!='\r') && (c!='\n'); p++) {
583
584         /* State machine to handle MIME headers
585          * if this looks horrible that's because it *is*
586          */
587
588                 switch(state) {
589                         case MIME_START:
590                         if(c == ':') {
591                                 state = MIME_TYPE;
592                                 *p = 0;
593                                 ntmp = strip_ends(q);
594                                 q = p + 1;
595                         }
596                         break;
597
598                         case MIME_TYPE:
599                         if(c == ';') {
600                                 mime_debug("Found End Value\n");
601                                 *p = 0;
602                                 mhdr = mime_hdr_new(ntmp, strip_ends(q));
603                                 sk_MIME_HEADER_push(headers, mhdr);
604                                 ntmp = NULL;
605                                 q = p + 1;
606                                 state = MIME_NAME;
607                         } else if(c == '(') {
608                                 save_state = state;
609                                 state = MIME_COMMENT;
610                         }
611                         break;
612
613                         case MIME_COMMENT:
614                         if(c == ')') {
615                                 state = save_state;
616                         }
617                         break;
618
619                         case MIME_NAME:
620                         if(c == '=') {
621                                 state = MIME_VALUE;
622                                 *p = 0;
623                                 ntmp = strip_ends(q);
624                                 q = p + 1;
625                         }
626                         break ;
627
628                         case MIME_VALUE:
629                         if(c == ';') {
630                                 state = MIME_NAME;
631                                 *p = 0;
632                                 mime_hdr_addparam(mhdr, ntmp, strip_ends(q));
633                                 ntmp = NULL;
634                                 q = p + 1;
635                         } else if (c == '"') {
636                                 mime_debug("Found Quote\n");
637                                 state = MIME_QUOTE;
638                         } else if(c == '(') {
639                                 save_state = state;
640                                 state = MIME_COMMENT;
641                         }
642                         break;
643
644                         case MIME_QUOTE:
645                         if(c == '"') {
646                                 mime_debug("Found Match Quote\n");
647                                 state = MIME_VALUE;
648                         }
649                         break;
650                 }
651         }
652
653         if(state == MIME_TYPE) {
654                 mhdr = mime_hdr_new(ntmp, strip_ends(q));
655                 sk_MIME_HEADER_push(headers, mhdr);
656         } else if(state == MIME_VALUE)
657                          mime_hdr_addparam(mhdr, ntmp, strip_ends(q));
658         if(p == linebuf) break; /* Blank line means end of headers */
659 }
660
661 return headers;
662
663 }
664
665 static char *strip_ends(char *name)
666 {
667         return strip_end(strip_start(name));
668 }
669
670 /* Strip a parameter of whitespace from start of param */
671 static char *strip_start(char *name)
672 {
673         char *p, c;
674         /* Look for first non white space or quote */
675         for(p = name; (c = *p) ;p++) {
676                 if(c == '"') {
677                         /* Next char is start of string if non null */
678                         if(p[1]) return p + 1;
679                         /* Else null string */
680                         return NULL;
681                 }
682                 if(!isspace((unsigned char)c)) return p;
683         }
684         return NULL;
685 }
686
687 /* As above but strip from end of string : maybe should handle brackets? */
688 static char *strip_end(char *name)
689 {
690         char *p, c;
691         if(!name) return NULL;
692         /* Look for first non white space or quote */
693         for(p = name + strlen(name) - 1; p >= name ;p--) {
694                 c = *p;
695                 if(c == '"') {
696                         if(p - 1 == name) return NULL;
697                         *p = 0;
698                         return name;
699                 }
700                 if(isspace((unsigned char)c)) *p = 0;   
701                 else return name;
702         }
703         return NULL;
704 }
705
706 static MIME_HEADER *mime_hdr_new(char *name, char *value)
707 {
708         MIME_HEADER *mhdr;
709         char *tmpname, *tmpval, *p;
710         int c;
711         if(name) {
712                 if(!(tmpname = BUF_strdup(name))) return NULL;
713                 for(p = tmpname ; *p; p++) {
714                         c = *p;
715                         if(isupper(c)) {
716                                 c = tolower(c);
717                                 *p = c;
718                         }
719                 }
720         } else tmpname = NULL;
721         if(value) {
722                 if(!(tmpval = BUF_strdup(value))) return NULL;
723                 for(p = tmpval ; *p; p++) {
724                         c = *p;
725                         if(isupper(c)) {
726                                 c = tolower(c);
727                                 *p = c;
728                         }
729                 }
730         } else tmpval = NULL;
731         mhdr = (MIME_HEADER *) OPENSSL_malloc(sizeof(MIME_HEADER));
732         if(!mhdr) return NULL;
733         mhdr->name = tmpname;
734         mhdr->value = tmpval;
735         if(!(mhdr->params = sk_MIME_PARAM_new(mime_param_cmp))) return NULL;
736         return mhdr;
737 }
738                 
739 static int mime_hdr_addparam(MIME_HEADER *mhdr, char *name, char *value)
740 {
741         char *tmpname, *tmpval, *p;
742         int c;
743         MIME_PARAM *mparam;
744         if(name) {
745                 tmpname = BUF_strdup(name);
746                 if(!tmpname) return 0;
747                 for(p = tmpname ; *p; p++) {
748                         c = *p;
749                         if(isupper(c)) {
750                                 c = tolower(c);
751                                 *p = c;
752                         }
753                 }
754         } else tmpname = NULL;
755         if(value) {
756                 tmpval = BUF_strdup(value);
757                 if(!tmpval) return 0;
758         } else tmpval = NULL;
759         /* Parameter values are case sensitive so leave as is */
760         mparam = (MIME_PARAM *) OPENSSL_malloc(sizeof(MIME_PARAM));
761         if(!mparam) return 0;
762         mparam->param_name = tmpname;
763         mparam->param_value = tmpval;
764         sk_MIME_PARAM_push(mhdr->params, mparam);
765         return 1;
766 }
767
768 static int mime_hdr_cmp(const MIME_HEADER * const *a,
769                         const MIME_HEADER * const *b)
770 {
771         return(strcmp((*a)->name, (*b)->name));
772 }
773
774 static int mime_param_cmp(const MIME_PARAM * const *a,
775                         const MIME_PARAM * const *b)
776 {
777         return(strcmp((*a)->param_name, (*b)->param_name));
778 }
779
780 /* Find a header with a given name (if possible) */
781
782 static MIME_HEADER *mime_hdr_find(STACK_OF(MIME_HEADER) *hdrs, char *name)
783 {
784         MIME_HEADER htmp;
785         int idx;
786         htmp.name = name;
787         idx = sk_MIME_HEADER_find(hdrs, &htmp);
788         if(idx < 0) return NULL;
789         return sk_MIME_HEADER_value(hdrs, idx);
790 }
791
792 static MIME_PARAM *mime_param_find(MIME_HEADER *hdr, char *name)
793 {
794         MIME_PARAM param;
795         int idx;
796         param.param_name = name;
797         idx = sk_MIME_PARAM_find(hdr->params, &param);
798         if(idx < 0) return NULL;
799         return sk_MIME_PARAM_value(hdr->params, idx);
800 }
801
802 static void mime_hdr_free(MIME_HEADER *hdr)
803 {
804         if(hdr->name) OPENSSL_free(hdr->name);
805         if(hdr->value) OPENSSL_free(hdr->value);
806         if(hdr->params) sk_MIME_PARAM_pop_free(hdr->params, mime_param_free);
807         OPENSSL_free(hdr);
808 }
809
810 static void mime_param_free(MIME_PARAM *param)
811 {
812         if(param->param_name) OPENSSL_free(param->param_name);
813         if(param->param_value) OPENSSL_free(param->param_value);
814         OPENSSL_free(param);
815 }
816
817 /* Check for a multipart boundary. Returns:
818  * 0 : no boundary
819  * 1 : part boundary
820  * 2 : final boundary
821  */
822 static int mime_bound_check(char *line, int linelen, char *bound, int blen)
823 {
824         if(linelen == -1) linelen = strlen(line);
825         if(blen == -1) blen = strlen(bound);
826         /* Quickly eliminate if line length too short */
827         if(blen + 2 > linelen) return 0;
828         /* Check for part boundary */
829         if(!strncmp(line, "--", 2) && !strncmp(line + 2, bound, blen)) {
830                 if(!strncmp(line + blen + 2, "--", 2)) return 2;
831                 else return 1;
832         }
833         return 0;
834 }
835
836 static int strip_eol(char *linebuf, int *plen)
837         {
838         int len = *plen;
839         char *p, c;
840         int is_eol = 0;
841         p = linebuf + len - 1;
842         for (p = linebuf + len - 1; len > 0; len--, p--)
843                 {
844                 c = *p;
845                 if (c == '\n')
846                         is_eol = 1;
847                 else if (c != '\r')
848                         break;
849                 }
850         *plen = len;
851         return is_eol;
852         }