Factor repeated code into function

There are 3 instance that were replaced, but 2 instances of variants of this
function exist and will be handled next (the extra parameter that isn't used
so far is in preparation for that):
- one in verify_child() where path_cnt constraint is handled too
- one in verify_top() where there is extra logic to skip parents that are
  expired or future, but only if there are better parents to be found
diff --git a/library/x509_crt.c b/library/x509_crt.c
index be5a87e..1913dd9 100644
--- a/library/x509_crt.c
+++ b/library/x509_crt.c
@@ -1894,6 +1894,30 @@
 }
 
 /*
+ * Find a suitable parent for child in candidates
+ */
+static mbedtls_x509_crt *x509_crt_find_parent( mbedtls_x509_crt *child,
+                                               mbedtls_x509_crt *candidates,
+                                               int top,
+                                               int path_cnt,
+                                               int self_cnt )
+{
+    mbedtls_x509_crt *parent;
+
+    (void) self_cnt;
+
+    for( parent = candidates; parent != NULL; parent = parent->next )
+    {
+        if( x509_crt_check_parent( child, parent, top, path_cnt == 0 ) != 0 )
+            continue;
+
+        break;
+    }
+
+    return parent;
+}
+
+/*
  * Verify a certificate no parent inside the chain
  * (either the parent is a trusted root, or there is no parent)
  *
@@ -2121,14 +2145,8 @@
 #endif
 
     /* Look for a grandparent in trusted CAs */
-    for( grandparent = trust_ca;
-         grandparent != NULL;
-         grandparent = grandparent->next )
-    {
-        if( x509_crt_check_parent( parent, grandparent,
-                                   1, path_cnt == 0 ) == 0 )
-            break;
-    }
+    /* path_cnt +1 because current step is not yet accounted for */
+    grandparent = x509_crt_find_parent( parent, trust_ca, 1, path_cnt + 1, self_cnt );
 
     if( grandparent != NULL )
     {
@@ -2315,11 +2333,7 @@
         *flags |= MBEDTLS_X509_BADCERT_BAD_KEY;
 
     /* Look for a parent in trusted CAs */
-    for( parent = trust_ca; parent != NULL; parent = parent->next )
-    {
-        if( x509_crt_check_parent( crt, parent, 1, pathlen == 0 ) == 0 )
-            break;
-    }
+    parent = x509_crt_find_parent( crt, trust_ca, 1, pathlen, 0 );
 
     if( parent != NULL )
     {
@@ -2331,9 +2345,7 @@
     else
     {
         /* Look for a parent upwards the chain */
-        for( parent = crt->next; parent != NULL; parent = parent->next )
-            if( x509_crt_check_parent( crt, parent, 0, pathlen == 0 ) == 0 )
-                break;
+        parent = x509_crt_find_parent( crt, crt->next, 0, pathlen, 0 );
 
         /* Are we part of the chain or at the top? */
         if( parent != NULL )