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