Changes to support node.js's use of PKCS#12.

node.js uses a memory BIO in the wrong mode which, for now, we work
around. It also passes in NULL (rather than empty) strings and a
non-NULL out-arg for |d2i_PKCS12_bio|.

Change-Id: Ib565b4a202775bb32fdcb76db8a4e8c54268c052
Reviewed-on: https://boringssl-review.googlesource.com/7012
Reviewed-by: Adam Langley <agl@google.com>
diff --git a/crypto/pkcs8/pkcs8.c b/crypto/pkcs8/pkcs8.c
index 31a34a7..ac13faf 100644
--- a/crypto/pkcs8/pkcs8.c
+++ b/crypto/pkcs8/pkcs8.c
@@ -975,7 +975,7 @@
 
   ctx.out_key = out_key;
   ctx.out_certs = out_certs;
-  if (!ascii_to_ucs2(password, strlen(password), &ctx.password,
+  if (!ascii_to_ucs2(password, password ? strlen(password) : 0, &ctx.password,
                      &ctx.password_len)) {
     OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_DECODE_ERROR);
     goto err;
@@ -1066,9 +1066,6 @@
 PKCS12* d2i_PKCS12(PKCS12 **out_p12, const uint8_t **ber_bytes, size_t ber_len) {
   PKCS12 *p12;
 
-  /* out_p12 must be NULL because we don't export the PKCS12 structure. */
-  assert(out_p12 == NULL);
-
   p12 = OPENSSL_malloc(sizeof(PKCS12));
   if (!p12) {
     return NULL;
@@ -1084,6 +1081,12 @@
   p12->ber_len = ber_len;
   *ber_bytes += ber_len;
 
+  if (out_p12) {
+    PKCS12_free(*out_p12);
+
+    *out_p12 = p12;
+  }
+
   return p12;
 }
 
@@ -1105,7 +1108,12 @@
   for (;;) {
     int n = BIO_read(bio, &buf->data[used], buf->length - used);
     if (n < 0) {
-      goto out;
+      if (used == 0) {
+        goto out;
+      }
+      /* Workaround a bug in node.js. It uses a memory BIO for this in the wrong
+       * mode. */
+      n = 0;
     }
 
     if (n == 0) {
@@ -1212,6 +1220,9 @@
 }
 
 void PKCS12_free(PKCS12 *p12) {
+  if (p12 == NULL) {
+    return;
+  }
   OPENSSL_free(p12->ber_bytes);
   OPENSSL_free(p12);
 }
diff --git a/include/openssl/pkcs8.h b/include/openssl/pkcs8.h
index 6b51f85..28cf6ac 100644
--- a/include/openssl/pkcs8.h
+++ b/include/openssl/pkcs8.h
@@ -139,12 +139,16 @@
 OPENSSL_EXPORT void PKCS12_PBE_add(void);
 
 /* d2i_PKCS12 is a dummy function that copies |*ber_bytes| into a
- * |PKCS12| structure. The |out_p12| argument must be NULL. On exit,
+ * |PKCS12| structure. The |out_p12| argument should be NULL(✝). On exit,
  * |*ber_bytes| will be advanced by |ber_len|. It returns a fresh |PKCS12|
  * structure or NULL on error.
  *
  * Note: unlike other d2i functions, |d2i_PKCS12| will always consume |ber_len|
- * bytes.*/
+ * bytes.
+ *
+ * (✝) If |out_p12| is not NULL and the function is successful, |*out_p12| will
+ * be freed if not NULL itself and the result will be written to |*out_p12|.
+ * New code should not depend on this. */
 OPENSSL_EXPORT PKCS12 *d2i_PKCS12(PKCS12 **out_p12, const uint8_t **ber_bytes,
                                   size_t ber_len);