Add OpenSSL 0.9.7d.
[dragonfly.git] / crypto / openssl-0.9.7d / crypto / pkcs7 / pk7_mime.c
1 /* pk7_mime.c */
2 /* Written by Dr Stephen N Henson (shenson@bigfoot.com) for the OpenSSL
3  * project 1999.
4  */
5 /* ====================================================================
6  * Copyright (c) 1999-2003 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 B64_write_PKCS7(BIO *bio, PKCS7 *p7);
90 static PKCS7 *B64_read_PKCS7(BIO *bio);
91 static char * strip_ends(char *name);
92 static char * strip_start(char *name);
93 static char * strip_end(char *name);
94 static MIME_HEADER *mime_hdr_new(char *name, char *value);
95 static int mime_hdr_addparam(MIME_HEADER *mhdr, char *name, char *value);
96 static STACK_OF(MIME_HEADER) *mime_parse_hdr(BIO *bio);
97 static int mime_hdr_cmp(const MIME_HEADER * const *a,
98                         const MIME_HEADER * const *b);
99 static int mime_param_cmp(const MIME_PARAM * const *a,
100                         const MIME_PARAM * const *b);
101 static void mime_param_free(MIME_PARAM *param);
102 static int mime_bound_check(char *line, int linelen, char *bound, int blen);
103 static int multi_split(BIO *bio, char *bound, STACK_OF(BIO) **ret);
104 static int strip_eol(char *linebuf, int *plen);
105 static MIME_HEADER *mime_hdr_find(STACK_OF(MIME_HEADER) *hdrs, char *name);
106 static MIME_PARAM *mime_param_find(MIME_HEADER *hdr, char *name);
107 static void mime_hdr_free(MIME_HEADER *hdr);
108
109 #define MAX_SMLEN 1024
110 #define mime_debug(x) /* x */
111
112
113 typedef void (*stkfree)();
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         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         BIO_flush(bio);
144         bio = BIO_pop(bio);
145         BIO_free(b64);
146         return p7;
147 }
148
149 /* SMIME sender */
150
151 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;
156         if (flags & PKCS7_NOOLDMIMETYPE)
157                 mime_prefix = "application/pkcs7-";
158         else
159                 mime_prefix = "application/x-pkcs7-";
160         if (flags & PKCS7_CRLFEOL)
161                 mime_eol = "\r\n";
162         else
163                 mime_eol = "\n";
164         if((flags & PKCS7_DETACHED) && data) {
165         /* We want multipart/signed */
166                 /* Generate a random boundary */
167                 RAND_pseudo_bytes((unsigned char *)bound, 32);
168                 for(i = 0; i < 32; i++) {
169                         c = bound[i] & 0xf;
170                         if(c < 10) c += '0';
171                         else c += 'A' - 10;
172                         bound[i] = c;
173                 }
174                 bound[32] = 0;
175                 BIO_printf(bio, "MIME-Version: 1.0%s", mime_eol);
176                 BIO_printf(bio, "Content-Type: multipart/signed;");
177                 BIO_printf(bio, " protocol=\"%ssignature\";", mime_prefix);
178                 BIO_printf(bio, " micalg=sha1; boundary=\"----%s\"%s%s",
179                                                 bound, mime_eol, mime_eol);
180                 BIO_printf(bio, "This is an S/MIME signed message%s%s",
181                                                 mime_eol, mime_eol);
182                 /* Now write out the first part */
183                 BIO_printf(bio, "------%s%s", bound, mime_eol);
184                 SMIME_crlf_copy(data, bio, flags);
185                 BIO_printf(bio, "%s------%s%s", mime_eol, bound, mime_eol);
186
187                 /* Headers for signature */
188
189                 BIO_printf(bio, "Content-Type: %ssignature;", mime_prefix); 
190                 BIO_printf(bio, " name=\"smime.p7s\"%s", mime_eol);
191                 BIO_printf(bio, "Content-Transfer-Encoding: base64%s",
192                                                                 mime_eol);
193                 BIO_printf(bio, "Content-Disposition: attachment;");
194                 BIO_printf(bio, " filename=\"smime.p7s\"%s%s",
195                                                         mime_eol, mime_eol);
196                 B64_write_PKCS7(bio, p7);
197                 BIO_printf(bio,"%s------%s--%s%s", mime_eol, bound,
198                                                 mime_eol, mime_eol);
199                 return 1;
200         }
201         /* MIME headers */
202         BIO_printf(bio, "MIME-Version: 1.0%s", mime_eol);
203         BIO_printf(bio, "Content-Disposition: attachment;");
204         BIO_printf(bio, " filename=\"smime.p7m\"%s", mime_eol);
205         BIO_printf(bio, "Content-Type: %smime;", mime_prefix);
206         BIO_printf(bio, " name=\"smime.p7m\"%s", mime_eol);
207         BIO_printf(bio, "Content-Transfer-Encoding: base64%s%s",
208                                                 mime_eol, mime_eol);
209         B64_write_PKCS7(bio, p7);
210         BIO_printf(bio, "%s", mime_eol);
211         return 1;
212 }
213
214 /* SMIME reader: handle multipart/signed and opaque signing.
215  * in multipart case the content is placed in a memory BIO
216  * pointed to by "bcont". In opaque this is set to NULL
217  */
218
219 PKCS7 *SMIME_read_PKCS7(BIO *bio, BIO **bcont)
220 {
221         BIO *p7in;
222         STACK_OF(MIME_HEADER) *headers = NULL;
223         STACK_OF(BIO) *parts = NULL;
224         MIME_HEADER *hdr;
225         MIME_PARAM *prm;
226         PKCS7 *p7;
227         int ret;
228
229         if(bcont) *bcont = NULL;
230
231         if (!(headers = mime_parse_hdr(bio))) {
232                 PKCS7err(PKCS7_F_SMIME_READ_PKCS7,PKCS7_R_MIME_PARSE_ERROR);
233                 return NULL;
234         }
235
236         if(!(hdr = mime_hdr_find(headers, "content-type")) || !hdr->value) {
237                 sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
238                 PKCS7err(PKCS7_F_SMIME_READ_PKCS7, PKCS7_R_NO_CONTENT_TYPE);
239                 return NULL;
240         }
241
242         /* Handle multipart/signed */
243
244         if(!strcmp(hdr->value, "multipart/signed")) {
245                 /* Split into two parts */
246                 prm = mime_param_find(hdr, "boundary");
247                 if(!prm || !prm->param_value) {
248                         sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
249                         PKCS7err(PKCS7_F_SMIME_READ_PKCS7, PKCS7_R_NO_MULTIPART_BOUNDARY);
250                         return NULL;
251                 }
252                 ret = multi_split(bio, prm->param_value, &parts);
253                 sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
254                 if(!ret || (sk_BIO_num(parts) != 2) ) {
255                         PKCS7err(PKCS7_F_SMIME_READ_PKCS7, PKCS7_R_NO_MULTIPART_BODY_FAILURE);
256                         sk_BIO_pop_free(parts, BIO_vfree);
257                         return NULL;
258                 }
259
260                 /* Parse the signature piece */
261                 p7in = sk_BIO_value(parts, 1);
262
263                 if (!(headers = mime_parse_hdr(p7in))) {
264                         PKCS7err(PKCS7_F_SMIME_READ_PKCS7,PKCS7_R_MIME_SIG_PARSE_ERROR);
265                         sk_BIO_pop_free(parts, BIO_vfree);
266                         return NULL;
267                 }
268
269                 /* Get content type */
270
271                 if(!(hdr = mime_hdr_find(headers, "content-type")) ||
272                                                                  !hdr->value) {
273                         sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
274                         PKCS7err(PKCS7_F_SMIME_READ_PKCS7, PKCS7_R_NO_SIG_CONTENT_TYPE);
275                         return NULL;
276                 }
277
278                 if(strcmp(hdr->value, "application/x-pkcs7-signature") &&
279                         strcmp(hdr->value, "application/pkcs7-signature")) {
280                         sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
281                         PKCS7err(PKCS7_F_SMIME_READ_PKCS7,PKCS7_R_SIG_INVALID_MIME_TYPE);
282                         ERR_add_error_data(2, "type: ", hdr->value);
283                         sk_BIO_pop_free(parts, BIO_vfree);
284                         return NULL;
285                 }
286                 sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
287                 /* Read in PKCS#7 */
288                 if(!(p7 = B64_read_PKCS7(p7in))) {
289                         PKCS7err(PKCS7_F_SMIME_READ_PKCS7,PKCS7_R_PKCS7_SIG_PARSE_ERROR);
290                         sk_BIO_pop_free(parts, BIO_vfree);
291                         return NULL;
292                 }
293
294                 if(bcont) {
295                         *bcont = sk_BIO_value(parts, 0);
296                         BIO_free(p7in);
297                         sk_BIO_free(parts);
298                 } else sk_BIO_pop_free(parts, BIO_vfree);
299                 return p7;
300         }
301                 
302         /* OK, if not multipart/signed try opaque signature */
303
304         if (strcmp (hdr->value, "application/x-pkcs7-mime") &&
305             strcmp (hdr->value, "application/pkcs7-mime")) {
306                 PKCS7err(PKCS7_F_SMIME_READ_PKCS7,PKCS7_R_INVALID_MIME_TYPE);
307                 ERR_add_error_data(2, "type: ", hdr->value);
308                 sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
309                 return NULL;
310         }
311
312         sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
313         
314         if(!(p7 = B64_read_PKCS7(bio))) {
315                 PKCS7err(PKCS7_F_SMIME_READ_PKCS7, PKCS7_R_PKCS7_PARSE_ERROR);
316                 return NULL;
317         }
318         return p7;
319
320 }
321
322 /* Copy text from one BIO to another making the output CRLF at EOL */
323 int SMIME_crlf_copy(BIO *in, BIO *out, int flags)
324 {
325         char eol;
326         int len;
327         char linebuf[MAX_SMLEN];
328         if(flags & PKCS7_BINARY) {
329                 while((len = BIO_read(in, linebuf, MAX_SMLEN)) > 0)
330                                                 BIO_write(out, linebuf, len);
331                 return 1;
332         }
333         if(flags & PKCS7_TEXT) BIO_printf(out, "Content-Type: text/plain\r\n\r\n");
334         while ((len = BIO_gets(in, linebuf, MAX_SMLEN)) > 0) {
335                 eol = strip_eol(linebuf, &len);
336                 if (len)
337                         BIO_write(out, linebuf, len);
338                 if(eol) BIO_write(out, "\r\n", 2);
339         }
340         return 1;
341 }
342
343 /* Strip off headers if they are text/plain */
344 int SMIME_text(BIO *in, BIO *out)
345 {
346         char iobuf[4096];
347         int len;
348         STACK_OF(MIME_HEADER) *headers;
349         MIME_HEADER *hdr;
350
351         if (!(headers = mime_parse_hdr(in))) {
352                 PKCS7err(PKCS7_F_SMIME_TEXT,PKCS7_R_MIME_PARSE_ERROR);
353                 return 0;
354         }
355         if(!(hdr = mime_hdr_find(headers, "content-type")) || !hdr->value) {
356                 PKCS7err(PKCS7_F_SMIME_TEXT,PKCS7_R_MIME_NO_CONTENT_TYPE);
357                 sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
358                 return 0;
359         }
360         if (strcmp (hdr->value, "text/plain")) {
361                 PKCS7err(PKCS7_F_SMIME_TEXT,PKCS7_R_INVALID_MIME_TYPE);
362                 ERR_add_error_data(2, "type: ", hdr->value);
363                 sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
364                 return 0;
365         }
366         sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
367         while ((len = BIO_read(in, iobuf, sizeof(iobuf))) > 0)
368                                                 BIO_write(out, iobuf, len);
369         return 1;
370 }
371
372 /* Split a multipart/XXX message body into component parts: result is
373  * canonical parts in a STACK of bios
374  */
375
376 static int multi_split(BIO *bio, char *bound, STACK_OF(BIO) **ret)
377 {
378         char linebuf[MAX_SMLEN];
379         int len, blen;
380         int eol = 0, next_eol = 0;
381         BIO *bpart = NULL;
382         STACK_OF(BIO) *parts;
383         char state, part, first;
384
385         blen = strlen(bound);
386         part = 0;
387         state = 0;
388         first = 1;
389         parts = sk_BIO_new_null();
390         *ret = parts;
391         while ((len = BIO_gets(bio, linebuf, MAX_SMLEN)) > 0) {
392                 state = mime_bound_check(linebuf, len, bound, blen);
393                 if(state == 1) {
394                         first = 1;
395                         part++;
396                 } else if(state == 2) {
397                         sk_BIO_push(parts, bpart);
398                         return 1;
399                 } else if(part) {
400                         /* Strip CR+LF from linebuf */
401                         next_eol = strip_eol(linebuf, &len);
402                         if(first) {
403                                 first = 0;
404                                 if(bpart) sk_BIO_push(parts, bpart);
405                                 bpart = BIO_new(BIO_s_mem());
406                                 BIO_set_mem_eof_return(bpart, 0);
407                         } else if (eol)
408                                 BIO_write(bpart, "\r\n", 2);
409                         eol = next_eol;
410                         if (len)
411                                 BIO_write(bpart, linebuf, len);
412                 }
413         }
414         return 0;
415 }
416
417 /* This is the big one: parse MIME header lines up to message body */
418
419 #define MIME_INVALID    0
420 #define MIME_START      1
421 #define MIME_TYPE       2
422 #define MIME_NAME       3
423 #define MIME_VALUE      4
424 #define MIME_QUOTE      5
425 #define MIME_COMMENT    6
426
427
428 static STACK_OF(MIME_HEADER) *mime_parse_hdr(BIO *bio)
429 {
430         char *p, *q, c;
431         char *ntmp;
432         char linebuf[MAX_SMLEN];
433         MIME_HEADER *mhdr = NULL;
434         STACK_OF(MIME_HEADER) *headers;
435         int len, state, save_state = 0;
436
437         headers = sk_MIME_HEADER_new(mime_hdr_cmp);
438         while ((len = BIO_gets(bio, linebuf, MAX_SMLEN)) > 0) {
439         /* If whitespace at line start then continuation line */
440         if(mhdr && isspace((unsigned char)linebuf[0])) state = MIME_NAME;
441         else state = MIME_START;
442         ntmp = NULL;
443         /* Go through all characters */
444         for(p = linebuf, q = linebuf; (c = *p) && (c!='\r') && (c!='\n'); p++) {
445
446         /* State machine to handle MIME headers
447          * if this looks horrible that's because it *is*
448          */
449
450                 switch(state) {
451                         case MIME_START:
452                         if(c == ':') {
453                                 state = MIME_TYPE;
454                                 *p = 0;
455                                 ntmp = strip_ends(q);
456                                 q = p + 1;
457                         }
458                         break;
459
460                         case MIME_TYPE:
461                         if(c == ';') {
462                                 mime_debug("Found End Value\n");
463                                 *p = 0;
464                                 mhdr = mime_hdr_new(ntmp, strip_ends(q));
465                                 sk_MIME_HEADER_push(headers, mhdr);
466                                 ntmp = NULL;
467                                 q = p + 1;
468                                 state = MIME_NAME;
469                         } else if(c == '(') {
470                                 save_state = state;
471                                 state = MIME_COMMENT;
472                         }
473                         break;
474
475                         case MIME_COMMENT:
476                         if(c == ')') {
477                                 state = save_state;
478                         }
479                         break;
480
481                         case MIME_NAME:
482                         if(c == '=') {
483                                 state = MIME_VALUE;
484                                 *p = 0;
485                                 ntmp = strip_ends(q);
486                                 q = p + 1;
487                         }
488                         break ;
489
490                         case MIME_VALUE:
491                         if(c == ';') {
492                                 state = MIME_NAME;
493                                 *p = 0;
494                                 mime_hdr_addparam(mhdr, ntmp, strip_ends(q));
495                                 ntmp = NULL;
496                                 q = p + 1;
497                         } else if (c == '"') {
498                                 mime_debug("Found Quote\n");
499                                 state = MIME_QUOTE;
500                         } else if(c == '(') {
501                                 save_state = state;
502                                 state = MIME_COMMENT;
503                         }
504                         break;
505
506                         case MIME_QUOTE:
507                         if(c == '"') {
508                                 mime_debug("Found Match Quote\n");
509                                 state = MIME_VALUE;
510                         }
511                         break;
512                 }
513         }
514
515         if(state == MIME_TYPE) {
516                 mhdr = mime_hdr_new(ntmp, strip_ends(q));
517                 sk_MIME_HEADER_push(headers, mhdr);
518         } else if(state == MIME_VALUE)
519                          mime_hdr_addparam(mhdr, ntmp, strip_ends(q));
520         if(p == linebuf) break; /* Blank line means end of headers */
521 }
522
523 return headers;
524
525 }
526
527 static char *strip_ends(char *name)
528 {
529         return strip_end(strip_start(name));
530 }
531
532 /* Strip a parameter of whitespace from start of param */
533 static char *strip_start(char *name)
534 {
535         char *p, c;
536         /* Look for first non white space or quote */
537         for(p = name; (c = *p) ;p++) {
538                 if(c == '"') {
539                         /* Next char is start of string if non null */
540                         if(p[1]) return p + 1;
541                         /* Else null string */
542                         return NULL;
543                 }
544                 if(!isspace((unsigned char)c)) return p;
545         }
546         return NULL;
547 }
548
549 /* As above but strip from end of string : maybe should handle brackets? */
550 static char *strip_end(char *name)
551 {
552         char *p, c;
553         if(!name) return NULL;
554         /* Look for first non white space or quote */
555         for(p = name + strlen(name) - 1; p >= name ;p--) {
556                 c = *p;
557                 if(c == '"') {
558                         if(p - 1 == name) return NULL;
559                         *p = 0;
560                         return name;
561                 }
562                 if(isspace((unsigned char)c)) *p = 0;   
563                 else return name;
564         }
565         return NULL;
566 }
567
568 static MIME_HEADER *mime_hdr_new(char *name, char *value)
569 {
570         MIME_HEADER *mhdr;
571         char *tmpname, *tmpval, *p;
572         int c;
573         if(name) {
574                 if(!(tmpname = BUF_strdup(name))) return NULL;
575                 for(p = tmpname ; *p; p++) {
576                         c = *p;
577                         if(isupper(c)) {
578                                 c = tolower(c);
579                                 *p = c;
580                         }
581                 }
582         } else tmpname = NULL;
583         if(value) {
584                 if(!(tmpval = BUF_strdup(value))) return NULL;
585                 for(p = tmpval ; *p; p++) {
586                         c = *p;
587                         if(isupper(c)) {
588                                 c = tolower(c);
589                                 *p = c;
590                         }
591                 }
592         } else tmpval = NULL;
593         mhdr = (MIME_HEADER *) OPENSSL_malloc(sizeof(MIME_HEADER));
594         if(!mhdr) return NULL;
595         mhdr->name = tmpname;
596         mhdr->value = tmpval;
597         if(!(mhdr->params = sk_MIME_PARAM_new(mime_param_cmp))) return NULL;
598         return mhdr;
599 }
600                 
601 static int mime_hdr_addparam(MIME_HEADER *mhdr, char *name, char *value)
602 {
603         char *tmpname, *tmpval, *p;
604         int c;
605         MIME_PARAM *mparam;
606         if(name) {
607                 tmpname = BUF_strdup(name);
608                 if(!tmpname) return 0;
609                 for(p = tmpname ; *p; p++) {
610                         c = *p;
611                         if(isupper(c)) {
612                                 c = tolower(c);
613                                 *p = c;
614                         }
615                 }
616         } else tmpname = NULL;
617         if(value) {
618                 tmpval = BUF_strdup(value);
619                 if(!tmpval) return 0;
620         } else tmpval = NULL;
621         /* Parameter values are case sensitive so leave as is */
622         mparam = (MIME_PARAM *) OPENSSL_malloc(sizeof(MIME_PARAM));
623         if(!mparam) return 0;
624         mparam->param_name = tmpname;
625         mparam->param_value = tmpval;
626         sk_MIME_PARAM_push(mhdr->params, mparam);
627         return 1;
628 }
629
630 static int mime_hdr_cmp(const MIME_HEADER * const *a,
631                         const MIME_HEADER * const *b)
632 {
633         return(strcmp((*a)->name, (*b)->name));
634 }
635
636 static int mime_param_cmp(const MIME_PARAM * const *a,
637                         const MIME_PARAM * const *b)
638 {
639         return(strcmp((*a)->param_name, (*b)->param_name));
640 }
641
642 /* Find a header with a given name (if possible) */
643
644 static MIME_HEADER *mime_hdr_find(STACK_OF(MIME_HEADER) *hdrs, char *name)
645 {
646         MIME_HEADER htmp;
647         int idx;
648         htmp.name = name;
649         idx = sk_MIME_HEADER_find(hdrs, &htmp);
650         if(idx < 0) return NULL;
651         return sk_MIME_HEADER_value(hdrs, idx);
652 }
653
654 static MIME_PARAM *mime_param_find(MIME_HEADER *hdr, char *name)
655 {
656         MIME_PARAM param;
657         int idx;
658         param.param_name = name;
659         idx = sk_MIME_PARAM_find(hdr->params, &param);
660         if(idx < 0) return NULL;
661         return sk_MIME_PARAM_value(hdr->params, idx);
662 }
663
664 static void mime_hdr_free(MIME_HEADER *hdr)
665 {
666         if(hdr->name) OPENSSL_free(hdr->name);
667         if(hdr->value) OPENSSL_free(hdr->value);
668         if(hdr->params) sk_MIME_PARAM_pop_free(hdr->params, mime_param_free);
669         OPENSSL_free(hdr);
670 }
671
672 static void mime_param_free(MIME_PARAM *param)
673 {
674         if(param->param_name) OPENSSL_free(param->param_name);
675         if(param->param_value) OPENSSL_free(param->param_value);
676         OPENSSL_free(param);
677 }
678
679 /* Check for a multipart boundary. Returns:
680  * 0 : no boundary
681  * 1 : part boundary
682  * 2 : final boundary
683  */
684 static int mime_bound_check(char *line, int linelen, char *bound, int blen)
685 {
686         if(linelen == -1) linelen = strlen(line);
687         if(blen == -1) blen = strlen(bound);
688         /* Quickly eliminate if line length too short */
689         if(blen + 2 > linelen) return 0;
690         /* Check for part boundary */
691         if(!strncmp(line, "--", 2) && !strncmp(line + 2, bound, blen)) {
692                 if(!strncmp(line + blen + 2, "--", 2)) return 2;
693                 else return 1;
694         }
695         return 0;
696 }
697
698 static int strip_eol(char *linebuf, int *plen)
699         {
700         int len = *plen;
701         char *p, c;
702         int is_eol = 0;
703         p = linebuf + len - 1;
704         for (p = linebuf + len - 1; len > 0; len--, p--)
705                 {
706                 c = *p;
707                 if (c == '\n')
708                         is_eol = 1;
709                 else if (c != '\r')
710                         break;
711                 }
712         *plen = len;
713         return is_eol;
714         }