From 4934e6471b98b7e87bee2ade909f64750448562c Mon Sep 17 00:00:00 2001
From: Daniel Stenberg <daniel@haxx.se>
Date: Tue, 10 Aug 2004 08:06:43 +0000
Subject: [PATCH] In OpenSSL 0.9.7d and earlier, ASN1_STRING_to_UTF8 fails if
 the input is already UTF-8 encoded. We check for this case and copy the raw
 string manually to avoid the problem. This code can be made conditional in
 the future when OpenSSL has been fixed. Work-around brought by Alexis S. L.
 Carvalho.

---
 lib/ssluse.c | 22 +++++++++++++++++++---
 1 file changed, 19 insertions(+), 3 deletions(-)

diff --git a/lib/ssluse.c b/lib/ssluse.c
index e17c329ff..7e438caa9 100644
--- a/lib/ssluse.c
+++ b/lib/ssluse.c
@@ -921,9 +921,25 @@ static CURLcode verifyhost(struct connectdata *conn,
        UTF8 etc. */
 
     if (i>=0) {
-      j = ASN1_STRING_to_UTF8(&peer_CN,
-                              X509_NAME_ENTRY_get_data(
-                                X509_NAME_get_entry(name,i)));
+      ASN1_STRING *tmp = X509_NAME_ENTRY_get_data(X509_NAME_get_entry(name,i));
+
+      /* In OpenSSL 0.9.7d and earlier, ASN1_STRING_to_UTF8 fails if the input
+         is already UTF-8 encoded. We check for this case and copy the raw
+         string manually to avoid the problem. This code can be made
+         conditional in the future when OpenSSL has been fixed. Work-around
+         brought by Alexis S. L. Carvalho. */
+      if (tmp && ASN1_STRING_type(tmp) == V_ASN1_UTF8STRING) {
+        j = ASN1_STRING_length(tmp);
+        if (j >= 0) {
+          peer_CN = OPENSSL_malloc(j+1);
+          if (peer_CN) {
+            memcpy(peer_CN, ASN1_STRING_data(tmp), j);
+            peer_CN[j] = '\0';
+          }
+        }
+      }
+      else /* not a UTF8 name */
+        j = ASN1_STRING_to_UTF8(&peer_CN, tmp);
     }
 
     if (peer_CN == nulstr)