]> git.ipfire.org Git - thirdparty/openssl.git/blob - crypto/asn1/asn_mime.c
GH601: Various spelling fixes.
[thirdparty/openssl.git] / crypto / asn1 / asn_mime.c
1 /*
2 * Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
3 * project.
4 */
5 /* ====================================================================
6 * Copyright (c) 1999-2008 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 */
54
55 #include <stdio.h>
56 #include <ctype.h>
57 #include "internal/cryptlib.h"
58 #include <openssl/rand.h>
59 #include <openssl/x509.h>
60 #include <openssl/asn1.h>
61 #include <openssl/asn1t.h>
62 #include "internal/evp_int.h"
63 #include "asn1_locl.h"
64
65 /*
66 * Generalised MIME like utilities for streaming ASN1. Although many have a
67 * PKCS7/CMS like flavour others are more general purpose.
68 */
69
70 /*
71 * MIME format structures Note that all are translated to lower case apart
72 * from parameter values. Quotes are stripped off
73 */
74
75 struct mime_param_st {
76 char *param_name; /* Param name e.g. "micalg" */
77 char *param_value; /* Param value e.g. "sha1" */
78 };
79
80 struct mime_header_st {
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 };
85
86 static int asn1_output_data(BIO *out, BIO *data, ASN1_VALUE *val, int flags,
87 const ASN1_ITEM *it);
88 static char *strip_ends(char *name);
89 static char *strip_start(char *name);
90 static char *strip_end(char *name);
91 static MIME_HEADER *mime_hdr_new(char *name, char *value);
92 static int mime_hdr_addparam(MIME_HEADER *mhdr, char *name, char *value);
93 static STACK_OF(MIME_HEADER) *mime_parse_hdr(BIO *bio);
94 static int mime_hdr_cmp(const MIME_HEADER *const *a,
95 const MIME_HEADER *const *b);
96 static int mime_param_cmp(const MIME_PARAM *const *a,
97 const MIME_PARAM *const *b);
98 static void mime_param_free(MIME_PARAM *param);
99 static int mime_bound_check(char *line, int linelen, char *bound, int blen);
100 static int multi_split(BIO *bio, char *bound, STACK_OF(BIO) **ret);
101 static int strip_eol(char *linebuf, int *plen, int flags);
102 static MIME_HEADER *mime_hdr_find(STACK_OF(MIME_HEADER) *hdrs, char *name);
103 static MIME_PARAM *mime_param_find(MIME_HEADER *hdr, char *name);
104 static void mime_hdr_free(MIME_HEADER *hdr);
105
106 #define MAX_SMLEN 1024
107 #define mime_debug(x) /* x */
108
109 /* Output an ASN1 structure in BER format streaming if necessary */
110
111 int i2d_ASN1_bio_stream(BIO *out, ASN1_VALUE *val, BIO *in, int flags,
112 const ASN1_ITEM *it)
113 {
114 /* If streaming create stream BIO and copy all content through it */
115 if (flags & SMIME_STREAM) {
116 BIO *bio, *tbio;
117 bio = BIO_new_NDEF(out, val, it);
118 if (!bio) {
119 ASN1err(ASN1_F_I2D_ASN1_BIO_STREAM, ERR_R_MALLOC_FAILURE);
120 return 0;
121 }
122 SMIME_crlf_copy(in, bio, flags);
123 (void)BIO_flush(bio);
124 /* Free up successive BIOs until we hit the old output BIO */
125 do {
126 tbio = BIO_pop(bio);
127 BIO_free(bio);
128 bio = tbio;
129 } while (bio != out);
130 }
131 /*
132 * else just write out ASN1 structure which will have all content stored
133 * internally
134 */
135 else
136 ASN1_item_i2d_bio(it, out, val);
137 return 1;
138 }
139
140 /* Base 64 read and write of ASN1 structure */
141
142 static int B64_write_ASN1(BIO *out, ASN1_VALUE *val, BIO *in, int flags,
143 const ASN1_ITEM *it)
144 {
145 BIO *b64;
146 int r;
147 b64 = BIO_new(BIO_f_base64());
148 if (b64 == NULL) {
149 ASN1err(ASN1_F_B64_WRITE_ASN1, ERR_R_MALLOC_FAILURE);
150 return 0;
151 }
152 /*
153 * prepend the b64 BIO so all data is base64 encoded.
154 */
155 out = BIO_push(b64, out);
156 r = i2d_ASN1_bio_stream(out, val, in, flags, it);
157 (void)BIO_flush(out);
158 BIO_pop(out);
159 BIO_free(b64);
160 return r;
161 }
162
163 /* Streaming ASN1 PEM write */
164
165 int PEM_write_bio_ASN1_stream(BIO *out, ASN1_VALUE *val, BIO *in, int flags,
166 const char *hdr, const ASN1_ITEM *it)
167 {
168 int r;
169 BIO_printf(out, "-----BEGIN %s-----\n", hdr);
170 r = B64_write_ASN1(out, val, in, flags, it);
171 BIO_printf(out, "-----END %s-----\n", hdr);
172 return r;
173 }
174
175 static ASN1_VALUE *b64_read_asn1(BIO *bio, const ASN1_ITEM *it)
176 {
177 BIO *b64;
178 ASN1_VALUE *val;
179
180 if ((b64 = BIO_new(BIO_f_base64())) == NULL) {
181 ASN1err(ASN1_F_B64_READ_ASN1, ERR_R_MALLOC_FAILURE);
182 return 0;
183 }
184 bio = BIO_push(b64, bio);
185 val = ASN1_item_d2i_bio(it, bio, NULL);
186 if (!val)
187 ASN1err(ASN1_F_B64_READ_ASN1, ASN1_R_DECODE_ERROR);
188 (void)BIO_flush(bio);
189 bio = BIO_pop(bio);
190 BIO_free(b64);
191 return val;
192 }
193
194 /* Generate the MIME "micalg" parameter from RFC3851, RFC4490 */
195
196 static int asn1_write_micalg(BIO *out, STACK_OF(X509_ALGOR) *mdalgs)
197 {
198 const EVP_MD *md;
199 int i, have_unknown = 0, write_comma, ret = 0, md_nid;
200 have_unknown = 0;
201 write_comma = 0;
202 for (i = 0; i < sk_X509_ALGOR_num(mdalgs); i++) {
203 if (write_comma)
204 BIO_write(out, ",", 1);
205 write_comma = 1;
206 md_nid = OBJ_obj2nid(sk_X509_ALGOR_value(mdalgs, i)->algorithm);
207 md = EVP_get_digestbynid(md_nid);
208 if (md && md->md_ctrl) {
209 int rv;
210 char *micstr;
211 rv = md->md_ctrl(NULL, EVP_MD_CTRL_MICALG, 0, &micstr);
212 if (rv > 0) {
213 BIO_puts(out, micstr);
214 OPENSSL_free(micstr);
215 continue;
216 }
217 if (rv != -2)
218 goto err;
219 }
220 switch (md_nid) {
221 case NID_sha1:
222 BIO_puts(out, "sha1");
223 break;
224
225 case NID_md5:
226 BIO_puts(out, "md5");
227 break;
228
229 case NID_sha256:
230 BIO_puts(out, "sha-256");
231 break;
232
233 case NID_sha384:
234 BIO_puts(out, "sha-384");
235 break;
236
237 case NID_sha512:
238 BIO_puts(out, "sha-512");
239 break;
240
241 case NID_id_GostR3411_94:
242 BIO_puts(out, "gostr3411-94");
243 goto err;
244
245 default:
246 if (have_unknown)
247 write_comma = 0;
248 else {
249 BIO_puts(out, "unknown");
250 have_unknown = 1;
251 }
252 break;
253
254 }
255 }
256
257 ret = 1;
258 err:
259
260 return ret;
261
262 }
263
264 /* SMIME sender */
265
266 int SMIME_write_ASN1(BIO *bio, ASN1_VALUE *val, BIO *data, int flags,
267 int ctype_nid, int econt_nid,
268 STACK_OF(X509_ALGOR) *mdalgs, const ASN1_ITEM *it)
269 {
270 char bound[33], c;
271 int i;
272 const char *mime_prefix, *mime_eol, *cname = "smime.p7m";
273 const char *msg_type = NULL;
274 if (flags & SMIME_OLDMIME)
275 mime_prefix = "application/x-pkcs7-";
276 else
277 mime_prefix = "application/pkcs7-";
278
279 if (flags & SMIME_CRLFEOL)
280 mime_eol = "\r\n";
281 else
282 mime_eol = "\n";
283 if ((flags & SMIME_DETACHED) && data) {
284 /* We want multipart/signed */
285 /* Generate a random boundary */
286 if (RAND_bytes((unsigned char *)bound, 32) <= 0)
287 return 0;
288 for (i = 0; i < 32; i++) {
289 c = bound[i] & 0xf;
290 if (c < 10)
291 c += '0';
292 else
293 c += 'A' - 10;
294 bound[i] = c;
295 }
296 bound[32] = 0;
297 BIO_printf(bio, "MIME-Version: 1.0%s", mime_eol);
298 BIO_printf(bio, "Content-Type: multipart/signed;");
299 BIO_printf(bio, " protocol=\"%ssignature\";", mime_prefix);
300 BIO_puts(bio, " micalg=\"");
301 asn1_write_micalg(bio, mdalgs);
302 BIO_printf(bio, "\"; boundary=\"----%s\"%s%s",
303 bound, mime_eol, mime_eol);
304 BIO_printf(bio, "This is an S/MIME signed message%s%s",
305 mime_eol, mime_eol);
306 /* Now write out the first part */
307 BIO_printf(bio, "------%s%s", bound, mime_eol);
308 if (!asn1_output_data(bio, data, val, flags, it))
309 return 0;
310 BIO_printf(bio, "%s------%s%s", mime_eol, bound, mime_eol);
311
312 /* Headers for signature */
313
314 BIO_printf(bio, "Content-Type: %ssignature;", mime_prefix);
315 BIO_printf(bio, " name=\"smime.p7s\"%s", mime_eol);
316 BIO_printf(bio, "Content-Transfer-Encoding: base64%s", mime_eol);
317 BIO_printf(bio, "Content-Disposition: attachment;");
318 BIO_printf(bio, " filename=\"smime.p7s\"%s%s", mime_eol, mime_eol);
319 B64_write_ASN1(bio, val, NULL, 0, it);
320 BIO_printf(bio, "%s------%s--%s%s", mime_eol, bound,
321 mime_eol, mime_eol);
322 return 1;
323 }
324
325 /* Determine smime-type header */
326
327 if (ctype_nid == NID_pkcs7_enveloped)
328 msg_type = "enveloped-data";
329 else if (ctype_nid == NID_pkcs7_signed) {
330 if (econt_nid == NID_id_smime_ct_receipt)
331 msg_type = "signed-receipt";
332 else if (sk_X509_ALGOR_num(mdalgs) >= 0)
333 msg_type = "signed-data";
334 else
335 msg_type = "certs-only";
336 } else if (ctype_nid == NID_id_smime_ct_compressedData) {
337 msg_type = "compressed-data";
338 cname = "smime.p7z";
339 }
340 /* MIME headers */
341 BIO_printf(bio, "MIME-Version: 1.0%s", mime_eol);
342 BIO_printf(bio, "Content-Disposition: attachment;");
343 BIO_printf(bio, " filename=\"%s\"%s", cname, mime_eol);
344 BIO_printf(bio, "Content-Type: %smime;", mime_prefix);
345 if (msg_type)
346 BIO_printf(bio, " smime-type=%s;", msg_type);
347 BIO_printf(bio, " name=\"%s\"%s", cname, mime_eol);
348 BIO_printf(bio, "Content-Transfer-Encoding: base64%s%s",
349 mime_eol, mime_eol);
350 if (!B64_write_ASN1(bio, val, data, flags, it))
351 return 0;
352 BIO_printf(bio, "%s", mime_eol);
353 return 1;
354 }
355
356 /* Handle output of ASN1 data */
357
358 static int asn1_output_data(BIO *out, BIO *data, ASN1_VALUE *val, int flags,
359 const ASN1_ITEM *it)
360 {
361 BIO *tmpbio;
362 const ASN1_AUX *aux = it->funcs;
363 ASN1_STREAM_ARG sarg;
364 int rv = 1;
365
366 /*
367 * If data is not detached or resigning then the output BIO is already
368 * set up to finalise when it is written through.
369 */
370 if (!(flags & SMIME_DETACHED) || (flags & PKCS7_REUSE_DIGEST)) {
371 SMIME_crlf_copy(data, out, flags);
372 return 1;
373 }
374
375 if (!aux || !aux->asn1_cb) {
376 ASN1err(ASN1_F_ASN1_OUTPUT_DATA, ASN1_R_STREAMING_NOT_SUPPORTED);
377 return 0;
378 }
379
380 sarg.out = out;
381 sarg.ndef_bio = NULL;
382 sarg.boundary = NULL;
383
384 /* Let ASN1 code prepend any needed BIOs */
385
386 if (aux->asn1_cb(ASN1_OP_DETACHED_PRE, &val, it, &sarg) <= 0)
387 return 0;
388
389 /* Copy data across, passing through filter BIOs for processing */
390 SMIME_crlf_copy(data, sarg.ndef_bio, flags);
391
392 /* Finalize structure */
393 if (aux->asn1_cb(ASN1_OP_DETACHED_POST, &val, it, &sarg) <= 0)
394 rv = 0;
395
396 /* Now remove any digests prepended to the BIO */
397
398 while (sarg.ndef_bio != out) {
399 tmpbio = BIO_pop(sarg.ndef_bio);
400 BIO_free(sarg.ndef_bio);
401 sarg.ndef_bio = tmpbio;
402 }
403
404 return rv;
405
406 }
407
408 /*
409 * SMIME reader: handle multipart/signed and opaque signing. in multipart
410 * case the content is placed in a memory BIO pointed to by "bcont". In
411 * opaque this is set to NULL
412 */
413
414 ASN1_VALUE *SMIME_read_ASN1(BIO *bio, BIO **bcont, const ASN1_ITEM *it)
415 {
416 BIO *asnin;
417 STACK_OF(MIME_HEADER) *headers = NULL;
418 STACK_OF(BIO) *parts = NULL;
419 MIME_HEADER *hdr;
420 MIME_PARAM *prm;
421 ASN1_VALUE *val;
422 int ret;
423
424 if (bcont)
425 *bcont = NULL;
426
427 if ((headers = mime_parse_hdr(bio)) == NULL) {
428 ASN1err(ASN1_F_SMIME_READ_ASN1, ASN1_R_MIME_PARSE_ERROR);
429 return NULL;
430 }
431
432 if ((hdr = mime_hdr_find(headers, "content-type")) == NULL
433 || hdr->value == NULL) {
434 sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
435 ASN1err(ASN1_F_SMIME_READ_ASN1, ASN1_R_NO_CONTENT_TYPE);
436 return NULL;
437 }
438
439 /* Handle multipart/signed */
440
441 if (strcmp(hdr->value, "multipart/signed") == 0) {
442 /* Split into two parts */
443 prm = mime_param_find(hdr, "boundary");
444 if (!prm || !prm->param_value) {
445 sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
446 ASN1err(ASN1_F_SMIME_READ_ASN1, ASN1_R_NO_MULTIPART_BOUNDARY);
447 return NULL;
448 }
449 ret = multi_split(bio, prm->param_value, &parts);
450 sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
451 if (!ret || (sk_BIO_num(parts) != 2)) {
452 ASN1err(ASN1_F_SMIME_READ_ASN1, ASN1_R_NO_MULTIPART_BODY_FAILURE);
453 sk_BIO_pop_free(parts, BIO_vfree);
454 return NULL;
455 }
456
457 /* Parse the signature piece */
458 asnin = sk_BIO_value(parts, 1);
459
460 if ((headers = mime_parse_hdr(asnin)) == NULL) {
461 ASN1err(ASN1_F_SMIME_READ_ASN1, ASN1_R_MIME_SIG_PARSE_ERROR);
462 sk_BIO_pop_free(parts, BIO_vfree);
463 return NULL;
464 }
465
466 /* Get content type */
467
468 if ((hdr = mime_hdr_find(headers, "content-type")) == NULL
469 || hdr->value == NULL) {
470 sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
471 ASN1err(ASN1_F_SMIME_READ_ASN1, ASN1_R_NO_SIG_CONTENT_TYPE);
472 return NULL;
473 }
474
475 if (strcmp(hdr->value, "application/x-pkcs7-signature") &&
476 strcmp(hdr->value, "application/pkcs7-signature")) {
477 ASN1err(ASN1_F_SMIME_READ_ASN1, ASN1_R_SIG_INVALID_MIME_TYPE);
478 ERR_add_error_data(2, "type: ", hdr->value);
479 sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
480 sk_BIO_pop_free(parts, BIO_vfree);
481 return NULL;
482 }
483 sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
484 /* Read in ASN1 */
485 if ((val = b64_read_asn1(asnin, it)) == NULL) {
486 ASN1err(ASN1_F_SMIME_READ_ASN1, ASN1_R_ASN1_SIG_PARSE_ERROR);
487 sk_BIO_pop_free(parts, BIO_vfree);
488 return NULL;
489 }
490
491 if (bcont) {
492 *bcont = sk_BIO_value(parts, 0);
493 BIO_free(asnin);
494 sk_BIO_free(parts);
495 } else
496 sk_BIO_pop_free(parts, BIO_vfree);
497 return val;
498 }
499
500 /* OK, if not multipart/signed try opaque signature */
501
502 if (strcmp(hdr->value, "application/x-pkcs7-mime") &&
503 strcmp(hdr->value, "application/pkcs7-mime")) {
504 ASN1err(ASN1_F_SMIME_READ_ASN1, ASN1_R_INVALID_MIME_TYPE);
505 ERR_add_error_data(2, "type: ", hdr->value);
506 sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
507 return NULL;
508 }
509
510 sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
511
512 if ((val = b64_read_asn1(bio, it)) == NULL) {
513 ASN1err(ASN1_F_SMIME_READ_ASN1, ASN1_R_ASN1_PARSE_ERROR);
514 return NULL;
515 }
516 return val;
517
518 }
519
520 /* Copy text from one BIO to another making the output CRLF at EOL */
521 int SMIME_crlf_copy(BIO *in, BIO *out, int flags)
522 {
523 BIO *bf;
524 char eol;
525 int len;
526 char linebuf[MAX_SMLEN];
527 /*
528 * Buffer output so we don't write one line at a time. This is useful
529 * when streaming as we don't end up with one OCTET STRING per line.
530 */
531 bf = BIO_new(BIO_f_buffer());
532 if (bf == NULL)
533 return 0;
534 out = BIO_push(bf, out);
535 if (flags & SMIME_BINARY) {
536 while ((len = BIO_read(in, linebuf, MAX_SMLEN)) > 0)
537 BIO_write(out, linebuf, len);
538 } else {
539 int eolcnt = 0;
540 if (flags & SMIME_TEXT)
541 BIO_printf(out, "Content-Type: text/plain\r\n\r\n");
542 while ((len = BIO_gets(in, linebuf, MAX_SMLEN)) > 0) {
543 eol = strip_eol(linebuf, &len, flags);
544 if (len) {
545 /* Not EOF: write out all CRLF */
546 if (flags & SMIME_ASCIICRLF) {
547 int i;
548 for (i = 0; i < eolcnt; i++)
549 BIO_write(out, "\r\n", 2);
550 eolcnt = 0;
551 }
552 BIO_write(out, linebuf, len);
553 if (eol)
554 BIO_write(out, "\r\n", 2);
555 } else if (flags & SMIME_ASCIICRLF)
556 eolcnt++;
557 else if (eol)
558 BIO_write(out, "\r\n", 2);
559 }
560 }
561 (void)BIO_flush(out);
562 BIO_pop(out);
563 BIO_free(bf);
564 return 1;
565 }
566
567 /* Strip off headers if they are text/plain */
568 int SMIME_text(BIO *in, BIO *out)
569 {
570 char iobuf[4096];
571 int len;
572 STACK_OF(MIME_HEADER) *headers;
573 MIME_HEADER *hdr;
574
575 if ((headers = mime_parse_hdr(in)) == NULL) {
576 ASN1err(ASN1_F_SMIME_TEXT, ASN1_R_MIME_PARSE_ERROR);
577 return 0;
578 }
579 if ((hdr = mime_hdr_find(headers, "content-type")) == NULL
580 || hdr->value == NULL) {
581 ASN1err(ASN1_F_SMIME_TEXT, ASN1_R_MIME_NO_CONTENT_TYPE);
582 sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
583 return 0;
584 }
585 if (strcmp(hdr->value, "text/plain")) {
586 ASN1err(ASN1_F_SMIME_TEXT, ASN1_R_INVALID_MIME_TYPE);
587 ERR_add_error_data(2, "type: ", hdr->value);
588 sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
589 return 0;
590 }
591 sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
592 while ((len = BIO_read(in, iobuf, sizeof(iobuf))) > 0)
593 BIO_write(out, iobuf, len);
594 if (len < 0)
595 return 0;
596 return 1;
597 }
598
599 /*
600 * Split a multipart/XXX message body into component parts: result is
601 * canonical parts in a STACK of bios
602 */
603
604 static int multi_split(BIO *bio, char *bound, STACK_OF(BIO) **ret)
605 {
606 char linebuf[MAX_SMLEN];
607 int len, blen;
608 int eol = 0, next_eol = 0;
609 BIO *bpart = NULL;
610 STACK_OF(BIO) *parts;
611 char state, part, first;
612
613 blen = strlen(bound);
614 part = 0;
615 state = 0;
616 first = 1;
617 parts = sk_BIO_new_null();
618 *ret = parts;
619 if (*ret == NULL)
620 return 0;
621 while ((len = BIO_gets(bio, linebuf, MAX_SMLEN)) > 0) {
622 state = mime_bound_check(linebuf, len, bound, blen);
623 if (state == 1) {
624 first = 1;
625 part++;
626 } else if (state == 2) {
627 if (!sk_BIO_push(parts, bpart)) {
628 BIO_free(bpart);
629 return 0;
630 }
631 return 1;
632 } else if (part) {
633 /* Strip CR+LF from linebuf */
634 next_eol = strip_eol(linebuf, &len, 0);
635 if (first) {
636 first = 0;
637 if (bpart)
638 if (!sk_BIO_push(parts, bpart)) {
639 BIO_free(bpart);
640 return 0;
641 }
642 bpart = BIO_new(BIO_s_mem());
643 if (bpart == NULL)
644 return 0;
645 BIO_set_mem_eof_return(bpart, 0);
646 } else if (eol)
647 BIO_write(bpart, "\r\n", 2);
648 eol = next_eol;
649 if (len)
650 BIO_write(bpart, linebuf, len);
651 }
652 }
653 BIO_free(bpart);
654 return 0;
655 }
656
657 /* This is the big one: parse MIME header lines up to message body */
658
659 #define MIME_INVALID 0
660 #define MIME_START 1
661 #define MIME_TYPE 2
662 #define MIME_NAME 3
663 #define MIME_VALUE 4
664 #define MIME_QUOTE 5
665 #define MIME_COMMENT 6
666
667 static STACK_OF(MIME_HEADER) *mime_parse_hdr(BIO *bio)
668 {
669 char *p, *q, c;
670 char *ntmp;
671 char linebuf[MAX_SMLEN];
672 MIME_HEADER *mhdr = NULL;
673 STACK_OF(MIME_HEADER) *headers;
674 int len, state, save_state = 0;
675
676 headers = sk_MIME_HEADER_new(mime_hdr_cmp);
677 if (headers == NULL)
678 return NULL;
679 while ((len = BIO_gets(bio, linebuf, MAX_SMLEN)) > 0) {
680 /* If whitespace at line start then continuation line */
681 if (mhdr && isspace((unsigned char)linebuf[0]))
682 state = MIME_NAME;
683 else
684 state = MIME_START;
685 ntmp = NULL;
686 /* Go through all characters */
687 for (p = linebuf, q = linebuf; (c = *p) && (c != '\r') && (c != '\n');
688 p++) {
689
690 /*
691 * State machine to handle MIME headers if this looks horrible
692 * that's because it *is*
693 */
694
695 switch (state) {
696 case MIME_START:
697 if (c == ':') {
698 state = MIME_TYPE;
699 *p = 0;
700 ntmp = strip_ends(q);
701 q = p + 1;
702 }
703 break;
704
705 case MIME_TYPE:
706 if (c == ';') {
707 mime_debug("Found End Value\n");
708 *p = 0;
709 mhdr = mime_hdr_new(ntmp, strip_ends(q));
710 sk_MIME_HEADER_push(headers, mhdr);
711 ntmp = NULL;
712 q = p + 1;
713 state = MIME_NAME;
714 } else if (c == '(') {
715 save_state = state;
716 state = MIME_COMMENT;
717 }
718 break;
719
720 case MIME_COMMENT:
721 if (c == ')') {
722 state = save_state;
723 }
724 break;
725
726 case MIME_NAME:
727 if (c == '=') {
728 state = MIME_VALUE;
729 *p = 0;
730 ntmp = strip_ends(q);
731 q = p + 1;
732 }
733 break;
734
735 case MIME_VALUE:
736 if (c == ';') {
737 state = MIME_NAME;
738 *p = 0;
739 mime_hdr_addparam(mhdr, ntmp, strip_ends(q));
740 ntmp = NULL;
741 q = p + 1;
742 } else if (c == '"') {
743 mime_debug("Found Quote\n");
744 state = MIME_QUOTE;
745 } else if (c == '(') {
746 save_state = state;
747 state = MIME_COMMENT;
748 }
749 break;
750
751 case MIME_QUOTE:
752 if (c == '"') {
753 mime_debug("Found Match Quote\n");
754 state = MIME_VALUE;
755 }
756 break;
757 }
758 }
759
760 if (state == MIME_TYPE) {
761 mhdr = mime_hdr_new(ntmp, strip_ends(q));
762 sk_MIME_HEADER_push(headers, mhdr);
763 } else if (state == MIME_VALUE)
764 mime_hdr_addparam(mhdr, ntmp, strip_ends(q));
765 if (p == linebuf)
766 break; /* Blank line means end of headers */
767 }
768
769 return headers;
770
771 }
772
773 static char *strip_ends(char *name)
774 {
775 return strip_end(strip_start(name));
776 }
777
778 /* Strip a parameter of whitespace from start of param */
779 static char *strip_start(char *name)
780 {
781 char *p, c;
782 /* Look for first non white space or quote */
783 for (p = name; (c = *p); p++) {
784 if (c == '"') {
785 /* Next char is start of string if non null */
786 if (p[1])
787 return p + 1;
788 /* Else null string */
789 return NULL;
790 }
791 if (!isspace((unsigned char)c))
792 return p;
793 }
794 return NULL;
795 }
796
797 /* As above but strip from end of string : maybe should handle brackets? */
798 static char *strip_end(char *name)
799 {
800 char *p, c;
801 if (!name)
802 return NULL;
803 /* Look for first non white space or quote */
804 for (p = name + strlen(name) - 1; p >= name; p--) {
805 c = *p;
806 if (c == '"') {
807 if (p - 1 == name)
808 return NULL;
809 *p = 0;
810 return name;
811 }
812 if (isspace((unsigned char)c))
813 *p = 0;
814 else
815 return name;
816 }
817 return NULL;
818 }
819
820 static MIME_HEADER *mime_hdr_new(char *name, char *value)
821 {
822 MIME_HEADER *mhdr = NULL;
823 char *tmpname = NULL, *tmpval = NULL, *p;
824 int c;
825
826 if (name) {
827 if ((tmpname = OPENSSL_strdup(name)) == NULL)
828 return NULL;
829 for (p = tmpname; *p; p++) {
830 c = (unsigned char)*p;
831 if (isupper(c)) {
832 c = tolower(c);
833 *p = c;
834 }
835 }
836 }
837 if (value) {
838 if ((tmpval = OPENSSL_strdup(value)) == NULL)
839 goto err;
840 for (p = tmpval; *p; p++) {
841 c = (unsigned char)*p;
842 if (isupper(c)) {
843 c = tolower(c);
844 *p = c;
845 }
846 }
847 }
848 mhdr = OPENSSL_malloc(sizeof(*mhdr));
849 if (mhdr == NULL)
850 goto err;
851 mhdr->name = tmpname;
852 mhdr->value = tmpval;
853 if ((mhdr->params = sk_MIME_PARAM_new(mime_param_cmp)) == NULL)
854 goto err;
855 return mhdr;
856
857 err:
858 OPENSSL_free(tmpname);
859 OPENSSL_free(tmpval);
860 OPENSSL_free(mhdr);
861 return NULL;
862 }
863
864 static int mime_hdr_addparam(MIME_HEADER *mhdr, char *name, char *value)
865 {
866 char *tmpname = NULL, *tmpval = NULL, *p;
867 int c;
868 MIME_PARAM *mparam = NULL;
869 if (name) {
870 tmpname = OPENSSL_strdup(name);
871 if (!tmpname)
872 goto err;
873 for (p = tmpname; *p; p++) {
874 c = (unsigned char)*p;
875 if (isupper(c)) {
876 c = tolower(c);
877 *p = c;
878 }
879 }
880 }
881 if (value) {
882 tmpval = OPENSSL_strdup(value);
883 if (!tmpval)
884 goto err;
885 }
886 /* Parameter values are case sensitive so leave as is */
887 mparam = OPENSSL_malloc(sizeof(*mparam));
888 if (mparam == NULL)
889 goto err;
890 mparam->param_name = tmpname;
891 mparam->param_value = tmpval;
892 if (!sk_MIME_PARAM_push(mhdr->params, mparam))
893 goto err;
894 return 1;
895 err:
896 OPENSSL_free(tmpname);
897 OPENSSL_free(tmpval);
898 OPENSSL_free(mparam);
899 return 0;
900 }
901
902 static int mime_hdr_cmp(const MIME_HEADER *const *a,
903 const MIME_HEADER *const *b)
904 {
905 if (!(*a)->name || !(*b)->name)
906 return ! !(*a)->name - ! !(*b)->name;
907
908 return (strcmp((*a)->name, (*b)->name));
909 }
910
911 static int mime_param_cmp(const MIME_PARAM *const *a,
912 const MIME_PARAM *const *b)
913 {
914 if (!(*a)->param_name || !(*b)->param_name)
915 return ! !(*a)->param_name - ! !(*b)->param_name;
916 return (strcmp((*a)->param_name, (*b)->param_name));
917 }
918
919 /* Find a header with a given name (if possible) */
920
921 static MIME_HEADER *mime_hdr_find(STACK_OF(MIME_HEADER) *hdrs, char *name)
922 {
923 MIME_HEADER htmp;
924 int idx;
925 htmp.name = name;
926 idx = sk_MIME_HEADER_find(hdrs, &htmp);
927 if (idx < 0)
928 return NULL;
929 return sk_MIME_HEADER_value(hdrs, idx);
930 }
931
932 static MIME_PARAM *mime_param_find(MIME_HEADER *hdr, char *name)
933 {
934 MIME_PARAM param;
935 int idx;
936 param.param_name = name;
937 idx = sk_MIME_PARAM_find(hdr->params, &param);
938 if (idx < 0)
939 return NULL;
940 return sk_MIME_PARAM_value(hdr->params, idx);
941 }
942
943 static void mime_hdr_free(MIME_HEADER *hdr)
944 {
945 OPENSSL_free(hdr->name);
946 OPENSSL_free(hdr->value);
947 if (hdr->params)
948 sk_MIME_PARAM_pop_free(hdr->params, mime_param_free);
949 OPENSSL_free(hdr);
950 }
951
952 static void mime_param_free(MIME_PARAM *param)
953 {
954 OPENSSL_free(param->param_name);
955 OPENSSL_free(param->param_value);
956 OPENSSL_free(param);
957 }
958
959 /*-
960 * Check for a multipart boundary. Returns:
961 * 0 : no boundary
962 * 1 : part boundary
963 * 2 : final boundary
964 */
965 static int mime_bound_check(char *line, int linelen, char *bound, int blen)
966 {
967 if (linelen == -1)
968 linelen = strlen(line);
969 if (blen == -1)
970 blen = strlen(bound);
971 /* Quickly eliminate if line length too short */
972 if (blen + 2 > linelen)
973 return 0;
974 /* Check for part boundary */
975 if ((strncmp(line, "--", 2) == 0)
976 && strncmp(line + 2, bound, blen) == 0) {
977 if (strncmp(line + blen + 2, "--", 2) == 0)
978 return 2;
979 else
980 return 1;
981 }
982 return 0;
983 }
984
985 static int strip_eol(char *linebuf, int *plen, int flags)
986 {
987 int len = *plen;
988 char *p, c;
989 int is_eol = 0;
990 p = linebuf + len - 1;
991 for (p = linebuf + len - 1; len > 0; len--, p--) {
992 c = *p;
993 if (c == '\n')
994 is_eol = 1;
995 else if (is_eol && flags & SMIME_ASCIICRLF && c < 33)
996 continue;
997 else if (c != '\r')
998 break;
999 }
1000 *plen = len;
1001 return is_eol;
1002 }