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