+void
+ldap_free_request( LDAP *ld, LDAPRequest *lr )
+{
+#ifdef LDAP_R_COMPILE
+ LDAP_PVT_THREAD_ASSERT_MUTEX_OWNER( &ld->ld_req_mutex );
+#endif
+
+ Debug( LDAP_DEBUG_TRACE, "ldap_free_request (origid %d, msgid %d)\n",
+ lr->lr_origid, lr->lr_msgid, 0 );
+
+ /* free all referrals (child requests) */
+ while ( lr->lr_child ) {
+ ldap_free_request( ld, lr->lr_child );
+ }
+
+ if ( lr->lr_parent != NULL ) {
+ LDAPRequest **lrp;
+
+ --lr->lr_parent->lr_outrefcnt;
+ for ( lrp = &lr->lr_parent->lr_child;
+ *lrp && *lrp != lr;
+ lrp = &(*lrp)->lr_refnext );
+
+ if ( *lrp == lr ) {
+ *lrp = lr->lr_refnext;
+ }
+ }
+ ldap_free_request_int( ld, lr );
+}
+
+/*
+ * call first time with *cntp = -1
+ * when returns *cntp == -1, no referrals are left
+ *
+ * NOTE: may replace *refsp, or shuffle the contents
+ * of the original array.
+ */
+static int ldap_int_nextref(
+ LDAP *ld,
+ char ***refsp,
+ int *cntp,
+ void *params )
+{
+ assert( refsp != NULL );
+ assert( *refsp != NULL );
+ assert( cntp != NULL );
+
+ if ( *cntp < -1 ) {
+ *cntp = -1;
+ return -1;
+ }
+
+ (*cntp)++;
+
+ if ( (*refsp)[ *cntp ] == NULL ) {
+ *cntp = -1;
+ }
+
+ return 0;
+}
+