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