/*
* Copyright 2008-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include "internal/cryptlib.h"
#include <openssl/asn1t.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include <openssl/err.h>
#include <openssl/cms.h>
#include "cms_local.h"
#include "crypto/asn1.h"
static BIO *cms_get_text_bio(BIO *out, unsigned int flags)
{
BIO *rbio;
if (out == NULL)
rbio = BIO_new(BIO_s_null());
else if (flags & CMS_TEXT) {
rbio = BIO_new(BIO_s_mem());
BIO_set_mem_eof_return(rbio, 0);
} else
rbio = out;
return rbio;
}
static int cms_copy_content(BIO *out, BIO *in, unsigned int flags)
{
unsigned char buf[4096];
int r = 0, i;
BIO *tmpout;
tmpout = cms_get_text_bio(out, flags);
if (tmpout == NULL) {
ERR_raise(ERR_LIB_CMS, ERR_R_CMS_LIB);
goto err;
}
/* Read all content through chain to process digest, decrypt etc */
for (;;) {
i = BIO_read(in, buf, sizeof(buf));
if (i <= 0) {
if (BIO_method_type(in) == BIO_TYPE_CIPHER) {
if (BIO_get_cipher_status(in) <= 0)
goto err;
}
if (i < 0)
goto err;
break;
}
if (tmpout != NULL && (BIO_write(tmpout, buf, i) != i))
goto err;
}
if (flags & CMS_TEXT) {
if (!SMIME_text(tmpout, out)) {
ERR_raise(ERR_LIB_CMS, CMS_R_SMIME_TEXT_ERROR);
goto err;
}
}
r = 1;
err:
if (tmpout != out)
BIO_free(tmpout);
return r;
}
static int check_content(CMS_ContentInfo *cms)
{
ASN1_OCTET_STRING **pos = CMS_get0_content(cms);
if (pos == NULL || *pos == NULL) {
ERR_raise(ERR_LIB_CMS, CMS_R_NO_CONTENT);
return 0;
}
return 1;
}
static void do_free_upto(BIO *f, BIO *upto)
{
if (upto != NULL) {
BIO *tbio;
do {
tbio = BIO_pop(f);
BIO_free(f);
f = tbio;
} while (f != NULL && f != upto);
} else {
BIO_free_all(f);
}
}
int CMS_data(CMS_ContentInfo *cms, BIO *out, unsigned int flags)
{
BIO *cont;
int r;
if (OBJ_obj2nid(CMS_get0_type(cms)) != NID_pkcs7_data) {
ERR_raise(ERR_LIB_CMS, CMS_R_TYPE_NOT_DATA);
return 0;
}
cont = CMS_dataInit(cms, NULL);
if (cont == NULL)
return 0;
r = cms_copy_content(out, cont, flags);
BIO_free_all(cont);
return r;
}
CMS_ContentInfo *CMS_data_create_ex(BIO *in, unsigned int flags,
OSSL_LIB_CTX *libctx, const char *propq)
{
CMS_ContentInfo *cms = ossl_cms_Data_create(libctx, propq);
if (cms == NULL)
return NULL;
if ((flags & CMS_STREAM) || CMS_final(cms, in, NULL, flags))
return cms;
CMS_ContentInfo_free(cms);