Skip to content

Commit cc3f1af

Browse files
committed
pkcs7: refactor error handling in PKCS7#add_data
Raise an exception right after an OpenSSL function returns an error. Checking ERR_peek_error() is not reliable way to see if an error has occurred or not, as OpenSSL functions do not always populate the error queue.
1 parent 58f0022 commit cc3f1af

File tree

1 file changed

+20
-17
lines changed

1 file changed

+20
-17
lines changed

ext/openssl/ossl_pkcs7.c

Lines changed: 20 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -838,30 +838,33 @@ ossl_pkcs7_add_data(VALUE self, VALUE data)
838838
PKCS7 *pkcs7;
839839
BIO *out, *in;
840840
char buf[4096];
841-
int len;
841+
int len, ret;
842842

843843
GetPKCS7(self, pkcs7);
844-
if(PKCS7_type_is_signed(pkcs7)){
845-
if(!PKCS7_content_new(pkcs7, NID_pkcs7_data))
846-
ossl_raise(ePKCS7Error, NULL);
844+
if (PKCS7_type_is_signed(pkcs7)) {
845+
if (!PKCS7_content_new(pkcs7, NID_pkcs7_data))
846+
ossl_raise(ePKCS7Error, "PKCS7_content_new");
847847
}
848848
in = ossl_obj2bio(&data);
849-
if(!(out = PKCS7_dataInit(pkcs7, NULL))) goto err;
850-
for(;;){
851-
if((len = BIO_read(in, buf, sizeof(buf))) <= 0)
852-
break;
853-
if(BIO_write(out, buf, len) != len)
854-
goto err;
849+
if (!(out = PKCS7_dataInit(pkcs7, NULL))) {
850+
BIO_free(in);
851+
ossl_raise(ePKCS7Error, "PKCS7_dataInit");
855852
}
856-
if(!PKCS7_dataFinal(pkcs7, out)) goto err;
857-
ossl_pkcs7_set_data(self, Qnil);
858-
859-
err:
853+
for (;;) {
854+
if ((len = BIO_read(in, buf, sizeof(buf))) <= 0)
855+
break;
856+
if (BIO_write(out, buf, len) != len) {
857+
BIO_free_all(out);
858+
BIO_free(in);
859+
ossl_raise(ePKCS7Error, "BIO_write");
860+
}
861+
}
862+
ret = PKCS7_dataFinal(pkcs7, out);
860863
BIO_free_all(out);
861864
BIO_free(in);
862-
if(ERR_peek_error()){
863-
ossl_raise(ePKCS7Error, NULL);
864-
}
865+
if (!ret)
866+
ossl_raise(ePKCS7Error, "PKCS7_dataFinal");
867+
ossl_pkcs7_set_data(self, Qnil);
865868

866869
return data;
867870
}

0 commit comments

Comments
 (0)