Fix segfault with empty fields as last in the config.

(Imported from upstream's 2747d73c1466c487daf64a1234b6fe2e8a62ac75.)

Also fix up some stylistic issues in conf.c and clarify empty case in
documentation.

Change-Id: Ibacabfab2339d7566d51db4b3ac4579aec0d1fbf
Reviewed-on: https://boringssl-review.googlesource.com/3023
Reviewed-by: Adam Langley <agl@google.com>
diff --git a/crypto/conf/conf.c b/crypto/conf/conf.c
index 520416a..b8dab95 100644
--- a/crypto/conf/conf.c
+++ b/crypto/conf/conf.c
@@ -715,27 +715,32 @@
   lstart = list;
   for (;;) {
     if (remove_whitespace) {
-      while (*lstart && isspace((unsigned char)*lstart))
+      while (*lstart && isspace((unsigned char)*lstart)) {
         lstart++;
+      }
     }
     p = strchr(lstart, sep);
-    if (p == lstart || !*lstart)
+    if (p == lstart || !*lstart) {
       ret = list_cb(NULL, 0, arg);
-    else {
-      if (p)
+    } else {
+      if (p) {
         tmpend = p - 1;
-      else
+      } else {
         tmpend = lstart + strlen(lstart) - 1;
+      }
       if (remove_whitespace) {
-        while (isspace((unsigned char)*tmpend))
+        while (isspace((unsigned char)*tmpend)) {
           tmpend--;
+        }
       }
       ret = list_cb(lstart, tmpend - lstart + 1, arg);
     }
-    if (ret <= 0)
+    if (ret <= 0) {
       return ret;
-    if (p == NULL)
+    }
+    if (p == NULL) {
       return 1;
+    }
     lstart = p + 1;
   }
 }
diff --git a/crypto/x509/asn1_gen.c b/crypto/x509/asn1_gen.c
index 6fcae7b..9246b93 100644
--- a/crypto/x509/asn1_gen.c
+++ b/crypto/x509/asn1_gen.c
@@ -287,6 +287,9 @@
 
 	int tmp_tag, tmp_class;
 
+	if (elem == NULL)
+		return 0;
+
 	for(i = 0, p = elem; i < len; p++, i++)
 		{
 		/* Look for the ':' in name value pairs */
diff --git a/include/openssl/conf.h b/include/openssl/conf.h
index c67e023..0918c0c 100644
--- a/include/openssl/conf.h
+++ b/include/openssl/conf.h
@@ -120,7 +120,8 @@
  * the start and length of each member, optionally stripping leading and
  * trailing whitespace. This can be used to parse comma separated lists for
  * example. If |list_cb| returns <= 0, then the iteration is halted and that
- * value is returned immediately. Otherwise it returns one. */
+ * value is returned immediately. Otherwise it returns one. Note that |list_cb|
+ * may be called on an empty member. */
 int CONF_parse_list(const char *list, char sep, int remove_whitespace,
                     int (*list_cb)(const char *elem, int len, void *usr),
                     void *arg);