]> git.sur5r.net Git - openldap/blobdiff - clients/tools/common.c
cleanup
[openldap] / clients / tools / common.c
index 21a818106107f17705d236ec1007764f2d2bd68c..4cf7edcd401aa8dcd99b07ad869f212a3f41ca9d 100644 (file)
@@ -2,7 +2,7 @@
 /* $OpenLDAP$ */
 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
  *
- * Copyright 1998-2004 The OpenLDAP Foundation.
+ * Copyright 1998-2007 The OpenLDAP Foundation.
  * Portions Copyright 2003 Kurt D. Zeilenga.
  * Portions Copyright 2003 IBM Corporation.
  * All rights reserved.
 #include <ac/stdlib.h>
 #include <ac/signal.h>
 #include <ac/string.h>
+#include <ac/ctype.h>
 #include <ac/unistd.h>
 #include <ac/errno.h>
+#include <ac/time.h>
+
+#ifdef HAVE_CYRUS_SASL
+#ifdef HAVE_SASL_SASL_H
+#include <sasl/sasl.h>
+#else
+#include <sasl.h>
+#endif
+#endif
 
 #include <ldap.h>
 
+#include "ldif.h"
+#include "lutil.h"
 #include "lutil_ldap.h"
 #include "ldap_defaults.h"
 #include "ldap_pvt.h"
 
 #include "common.h"
 
-
-int   authmethod = -1;
-char *binddn = NULL;
-int   contoper = 0;
-int   debug = 0;
-char *infile = NULL;
-char *ldapuri = NULL;
-char *ldaphost = NULL;
-int   ldapport = 0;
+/* input-related vars */
+
+/* misc. parameters */
+tool_type_t    tool_type;
+int            contoper = 0;
+int            debug = 0;
+char           *infile = NULL;
+int            dont = 0;
+int            referrals = 0;
+int            verbose = 0;
+int            ldif = 0;
+char           *prog = NULL;
+
+/* connection */
+char           *ldapuri = NULL;
+char           *ldaphost = NULL;
+int            ldapport = 0;
+int            use_tls = 0;
+int            protocol = -1;
+int            version = 0;
+
+/* authc/authz */
+int            authmethod = -1;
+char           *binddn = NULL;
+int            want_bindpw = 0;
+struct berval  passwd = { 0, NULL };
+char           *pw_file = NULL;
 #ifdef HAVE_CYRUS_SASL
-unsigned sasl_flags = LDAP_SASL_AUTOMATIC;
-char   *sasl_realm = NULL;
-char   *sasl_authc_id = NULL;
-char   *sasl_authz_id = NULL;
-char   *sasl_mech = NULL;
-char   *sasl_secprops = NULL;
+unsigned       sasl_flags = LDAP_SASL_AUTOMATIC;
+char           *sasl_realm = NULL;
+char           *sasl_authc_id = NULL;
+char           *sasl_authz_id = NULL;
+char           *sasl_mech = NULL;
+char           *sasl_secprops = NULL;
 #endif
-int   use_tls = 0;
-
-int      assertctl;
-char *assertion = NULL;
-char *authzid = NULL;
-int   manageDSAit = 0;
-int   noop = 0;
-int   ppolicy = 0;
-int   preread = 0;
-char *preread_attrs = NULL;
-int   postread = 0;
-char *postread_attrs = NULL;
-
-int   not = 0;
-int   want_bindpw = 0;
-struct berval passwd = { 0, NULL };
-char *pw_file = NULL;
-int   referrals = 0;
-int   protocol = -1;
-int   verbose = 0;
-int   version = 0;
-
-/* Set in main() */
-char *prog = NULL;
+
+/* controls */
+int            assertctl;
+char           *assertion = NULL;
+char           *authzid = NULL;
+/* support deprecated early version of proxyAuthz */
+#define LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ      "2.16.840.1.113730.3.4.12"
+#ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
+char           *proxydn = NULL;
+#endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
+int            manageDIT = 0;
+int            manageDSAit = 0;
+int            noop = 0;
+int            ppolicy = 0;
+int            preread = 0;
+static char    *preread_attrs = NULL;
+int            postread = 0;
+static char    *postread_attrs = NULL;
+ber_int_t      pr_morePagedResults = 1;
+struct berval  pr_cookie = { 0, NULL };
+#ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
+int            chaining = 0;
+static int     chainingResolve = -1;
+static int     chainingContinuation = -1;
+#endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
+
+/* options */
+struct timeval nettimeout = { -1 , 0 };
+
+typedef int (*print_ctrl_fn)( LDAP *ld, LDAPControl *ctrl );
+
+static int print_preread( LDAP *ld, LDAPControl *ctrl );
+static int print_postread( LDAP *ld, LDAPControl *ctrl );
+static int print_paged_results( LDAP *ld, LDAPControl *ctrl );
+#ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
+static int print_ppolicy( LDAP *ld, LDAPControl *ctrl );
+#endif
+
+static struct tool_ctrls_t {
+       const char      *oid;
+       unsigned        mask;
+       print_ctrl_fn   func;
+} tool_ctrl_response[] = {
+       { LDAP_CONTROL_PRE_READ,                        TOOL_ALL,       print_preread },
+       { LDAP_CONTROL_POST_READ,                       TOOL_ALL,       print_postread },
+       { LDAP_CONTROL_PAGEDRESULTS,                    TOOL_SEARCH,    print_paged_results },
+#ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
+       { LDAP_CONTROL_PASSWORDPOLICYRESPONSE,          TOOL_ALL,       print_ppolicy },
+#endif
+       { NULL,                                         0,              NULL }
+};
+
+/* "features" */
+static int     gotintr;
+static int     abcan;
+
+RETSIGTYPE
+do_sig( int sig )
+{
+       gotintr = abcan;
+}
 
 void
-tool_init( void )
+tool_init( tool_type_t type )
 {
+       tool_type = type;
        ldap_pvt_setlocale(LC_MESSAGES, "");
        ldap_pvt_bindtextdomain(OPENLDAP_PACKAGE, LDAP_LOCALEDIR);
        ldap_pvt_textdomain(OPENLDAP_PACKAGE);
 }
 
+void
+tool_destroy( void )
+{
+#ifdef HAVE_CYRUS_SASL
+       sasl_done();
+#endif
+#ifdef HAVE_TLS
+       ldap_pvt_tls_destroy();
+#endif
+}
+
 void
 tool_common_usage( void )
 {
@@ -100,24 +179,39 @@ N_("  -C         chase referrals (anonymously)\n"),
 N_("  -d level   set LDAP debugging level to `level'\n"),
 N_("  -D binddn  bind DN\n"),
 N_("  -e [!]<ext>[=<extparam>] general extensions (! indicates criticality)\n")
-N_("             [!]assert=<filter>     (an RFC 2254 Filter)\n")
+N_("             [!]assert=<filter>     (a RFC 4515 Filter string)\n")
 N_("             [!]authzid=<authzid>   (\"dn:<dn>\" or \"u:<user>\")\n")
+#ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
+#if 0
+                 /* non-advertized support for proxyDN */
+N_("             [!]proxydn=<dn>        (a RFC 4514 DN string)\n")
+#endif
+#endif
+#ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
+N_("             [!]chaining[=<resolveBehavior>[/<continuationBehavior>]]\n")
+N_("                     one of \"chainingPreferred\", \"chainingRequired\",\n")
+N_("                     \"referralsPreferred\", \"referralsRequired\"\n")
+#endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
 N_("             [!]manageDSAit\n")
 N_("             [!]noop\n")
 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
 N_("             ppolicy\n")
 #endif
 N_("             [!]postread[=<attrs>]  (a comma-separated attribute list)\n")
-N_("             [!]preread[=<attrs>]   (a comma-separated attribute list)\n"),
+N_("             [!]preread[=<attrs>]   (a comma-separated attribute list)\n")
+#ifdef LDAP_DEVEL
+N_("             [!]relax\n")
+#endif
+N_("             abandon, cancel (SIGINT sends abandon/cancel; not really controls)\n"),
 N_("  -f file    read operations from `file'\n"),
 N_("  -h host    LDAP server\n"),
 N_("  -H URI     LDAP Uniform Resource Indentifier(s)\n"),
 N_("  -I         use SASL Interactive mode\n"),
-N_("  -k         use Kerberos authentication\n"),
-N_("  -K         like -k, but do only step 1 of the Kerberos bind\n"),
 N_("  -M         enable Manage DSA IT control (-MM to make critical)\n"),
 N_("  -n         show what would be done but don't actually do it\n"),
 N_("  -O props   SASL security properties\n"),
+N_("  -o <opt>[=<optparam] general options\n"),
+N_("             nettimeout=<timeout> (in seconds, or \"none\" or \"max\")\n"),
 N_("  -p port    port on LDAP server\n"),
 N_("  -P version procotol version (default: 3)\n"),
 N_("  -Q         use SASL Quiet mode\n"),
@@ -144,6 +238,34 @@ NULL
        }
 }
 
+void tool_perror(
+       const char *func,
+       int err,
+       const char *extra,
+       const char *matched,
+       const char *info,
+       char **refs )
+{
+       fprintf( stderr, "%s: %s (%d)%s\n",
+               func, ldap_err2string( err ), err, extra ? extra : "" );
+
+       if ( matched && *matched ) {
+               fprintf( stderr, _("\tmatched DN: %s\n"), matched );
+       }
+
+       if ( info && *info ) {
+               fprintf( stderr, _("\tadditional info: %s\n"), info );
+       }
+
+       if ( refs && *refs ) {
+               int i;
+               fprintf( stderr, _("\treferrals:\n") );
+               for( i=0; refs[i]; i++ ) {
+                       fprintf( stderr, "\t\t%s\n", refs[i] );
+               }
+       }
+}
+
 
 void
 tool_args( int argc, char **argv )
@@ -212,6 +334,12 @@ tool_args( int argc, char **argv )
                                        fprintf( stderr, "authzid control previously specified\n");
                                        exit( EXIT_FAILURE );
                                }
+#ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
+                               if( proxydn != NULL ) {
+                                       fprintf( stderr, "authzid control incompatible with proxydn\n");
+                                       exit( EXIT_FAILURE );
+                               }
+#endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
                                if( cvalue == NULL ) {
                                        fprintf( stderr, "authzid: control value expected\n" );
                                        usage();
@@ -224,6 +352,45 @@ tool_args( int argc, char **argv )
                                assert( authzid == NULL );
                                authzid = cvalue;
 
+#ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
+                       } else if ( strcasecmp( control, "proxydn" ) == 0 ) {
+                               if( proxydn != NULL ) {
+                                       fprintf( stderr, "proxydn control previously specified\n");
+                                       exit( EXIT_FAILURE );
+                               }
+                               if( authzid != NULL ) {
+                                       fprintf( stderr, "proxydn control incompatible with authzid\n");
+                                       exit( EXIT_FAILURE );
+                               }
+                               if( cvalue == NULL ) {
+                                       fprintf( stderr, "proxydn: control value expected\n" );
+                                       usage();
+                               }
+                               if( !crit ) {
+                                       fprintf( stderr, "proxydn: must be marked critical\n" );
+                                       usage();
+                               }
+
+                               assert( proxydn == NULL );
+                               proxydn = cvalue;
+#endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
+
+                       } else if ( ( strcasecmp( control, "relax" ) == 0 ) ||
+                               ( strcasecmp( control, "manageDIT" ) == 0 ) )
+                       {
+                               if( manageDIT ) {
+                                       fprintf( stderr,
+                                               "relax control previously specified\n");
+                                       exit( EXIT_FAILURE );
+                               }
+                               if( cvalue != NULL ) {
+                                       fprintf( stderr,
+                                               "relax: no control value expected\n" );
+                                       usage();
+                               }
+
+                               manageDIT = 1 + crit;
+
                        } else if ( strcasecmp( control, "manageDSAit" ) == 0 ) {
                                if( manageDSAit ) {
                                        fprintf( stderr,
@@ -286,6 +453,59 @@ tool_args( int argc, char **argv )
                                postread = 1 + crit;
                                postread_attrs = cvalue;
 
+#ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
+                       } else if ( strcasecmp( control, "chaining" ) == 0 ) {
+                               chaining = 1 + crit;
+
+                               if ( cvalue != NULL ) {
+                                       char    *continuation;
+
+                                       continuation = strchr( cvalue, '/' );
+                                       if ( continuation ) {
+                                               /* FIXME: this makes sense only in searches */
+                                               *continuation++ = '\0';
+                                               if ( strcasecmp( continuation, "chainingPreferred" ) == 0 ) {
+                                                       chainingContinuation = LDAP_CHAINING_PREFERRED;
+                                               } else if ( strcasecmp( continuation, "chainingRequired" ) == 0 ) {
+                                                       chainingContinuation = LDAP_CHAINING_REQUIRED;
+                                               } else if ( strcasecmp( continuation, "referralsPreferred" ) == 0 ) {
+                                                       chainingContinuation = LDAP_REFERRALS_PREFERRED;
+                                               } else if ( strcasecmp( continuation, "referralsRequired" ) == 0 ) {
+                                                       chainingContinuation = LDAP_REFERRALS_REQUIRED;
+                                               } else {
+                                                       fprintf( stderr,
+                                                               "chaining behavior control "
+                                                               "continuation value \"%s\" invalid\n",
+                                                               continuation );
+                                                       exit( EXIT_FAILURE );
+                                               }
+                                       }
+       
+                                       if ( strcasecmp( cvalue, "chainingPreferred" ) == 0 ) {
+                                               chainingResolve = LDAP_CHAINING_PREFERRED;
+                                       } else if ( strcasecmp( cvalue, "chainingRequired" ) == 0 ) {
+                                               chainingResolve = LDAP_CHAINING_REQUIRED;
+                                       } else if ( strcasecmp( cvalue, "referralsPreferred" ) == 0 ) {
+                                               chainingResolve = LDAP_REFERRALS_PREFERRED;
+                                       } else if ( strcasecmp( cvalue, "referralsRequired" ) == 0 ) {
+                                               chainingResolve = LDAP_REFERRALS_REQUIRED;
+                                       } else {
+                                               fprintf( stderr,
+                                                       "chaining behavior control "
+                                                       "resolve value \"%s\" invalid\n",
+                                                       cvalue);
+                                               exit( EXIT_FAILURE );
+                                       }
+                               }
+#endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
+
+                       /* this shouldn't go here, really; but it's a feature... */
+                       } else if ( strcasecmp( control, "abandon" ) == 0 ) {
+                               abcan = LDAP_REQ_ABANDON;
+
+                       } else if ( strcasecmp( control, "cancel" ) == 0 ) {
+                               abcan = LDAP_REQ_EXTENDED;
+
                        } else {
                                fprintf( stderr, "Invalid general control name: %s\n",
                                        control );
@@ -329,38 +549,51 @@ tool_args( int argc, char **argv )
                                prog );
                        exit( EXIT_FAILURE );
 #endif
-               case 'k':       /* kerberos bind */
-#ifdef LDAP_API_FEATURE_X_OPENLDAP_V2_KBIND
-                       if( authmethod != -1 ) {
-                               fprintf( stderr, "%s: -k incompatible with previous "
-                                       "authentication choice\n", prog );
-                               exit( EXIT_FAILURE );
-                       }
-                       authmethod = LDAP_AUTH_KRBV4;
-#else
-                       fprintf( stderr, "%s: not compiled with Kerberos support\n", prog );
-                       exit( EXIT_FAILURE );
-#endif
-                       break;
-               case 'K':       /* kerberos bind, part one only */
-#ifdef LDAP_API_FEATURE_X_OPENLDAP_V2_KBIND
-                       if( authmethod != -1 ) {
-                               fprintf( stderr, "%s: incompatible with previous "
-                                       "authentication choice\n", prog );
-                               exit( EXIT_FAILURE );
-                       }
-                       authmethod = LDAP_AUTH_KRBV41;
-#else
-                       fprintf( stderr, "%s: not compiled with Kerberos support\n", prog );
-                       exit( EXIT_FAILURE );
-#endif
-                       break;
                case 'M':
                        /* enable Manage DSA IT */
                        manageDSAit++;
                        break;
                case 'n':       /* print operations, don't actually do them */
-                       not++;
+                       dont++;
+                       break;
+               case 'o':
+                       control = ber_strdup( optarg );
+                       if ( (cvalue = strchr( control, '=' )) != NULL ) {
+                               *cvalue++ = '\0';
+                       }
+
+                       if ( strcasecmp( control, "nettimeout" ) == 0 ) {
+                               if( nettimeout.tv_sec != -1 ) {
+                                       fprintf( stderr, "nettimeout option previously specified\n");
+                                       exit( EXIT_FAILURE );
+                               }
+                               if( cvalue == NULL || cvalue[0] == '\0' ) {
+                                       fprintf( stderr, "nettimeout: option value expected\n" );
+                                       usage();
+                               }
+                               if ( strcasecmp( cvalue, "none" ) == 0 ) {
+                                       nettimeout.tv_sec = 0;
+                               } else if ( strcasecmp( cvalue, "max" ) == 0 ) {
+                                       nettimeout.tv_sec = LDAP_MAXINT;
+                               } else {
+                                       ival = strtol( cvalue, &next, 10 );
+                                       if ( next == NULL || next[0] != '\0' ) {
+                                               fprintf( stderr,
+                                                       _("Unable to parse network timeout \"%s\"\n"), cvalue );
+                                               exit( EXIT_FAILURE );
+                                       }
+                                       nettimeout.tv_sec = ival;
+                               }
+                               if( nettimeout.tv_sec < 0 || nettimeout.tv_sec > LDAP_MAXINT ) {
+                                       fprintf( stderr, _("%s: invalid network timeout (%ld) specified\n"),
+                                               prog, (long)nettimeout.tv_sec );
+                                       exit( EXIT_FAILURE );
+                               }
+                       } else {
+                               fprintf( stderr, "Invalid general option name: %s\n",
+                                       control );
+                               usage();
+                       }
                        break;
                case 'O':
 #ifdef HAVE_CYRUS_SASL
@@ -574,28 +807,28 @@ tool_args( int argc, char **argv )
 
                if (api.ldapai_info_version != LDAP_API_INFO_VERSION) {
                        fprintf( stderr, "LDAP APIInfo version mismatch: "
-                               "got %d, expected %d\n",
+                               "library %d, header %d\n",
                                api.ldapai_info_version, LDAP_API_INFO_VERSION );
                        exit( EXIT_FAILURE );
                }
 
                if( api.ldapai_api_version != LDAP_API_VERSION ) {
                        fprintf( stderr, "LDAP API version mismatch: "
-                               "got %d, expected %d\n",
+                               "library %d, header %d\n",
                                api.ldapai_api_version, LDAP_API_VERSION );
                        exit( EXIT_FAILURE );
                }
 
                if( strcmp(api.ldapai_vendor_name, LDAP_VENDOR_NAME ) != 0 ) {
                        fprintf( stderr, "LDAP vendor name mismatch: "
-                               "got %s, expected %s\n",
+                               "library %s, header %s\n",
                                api.ldapai_vendor_name, LDAP_VENDOR_NAME );
                        exit( EXIT_FAILURE );
                }
 
                if( api.ldapai_vendor_version != LDAP_VENDOR_VERSION ) {
                        fprintf( stderr, "LDAP vendor version mismatch: "
-                               "got %d, expected %d\n",
+                               "library %d, header %d\n",
                                api.ldapai_vendor_version, LDAP_VENDOR_VERSION );
                        exit( EXIT_FAILURE );
                }
@@ -606,6 +839,9 @@ tool_args( int argc, char **argv )
                                LDAP_VENDOR_NAME, LDAP_VENDOR_VERSION );
                        if (version > 1) exit( EXIT_SUCCESS );
                }
+
+               ldap_memfree( api.ldapai_vendor_name );
+               ber_memvfree( (void **)api.ldapai_extensions );
        }
 
        if (protocol == -1)
@@ -634,8 +870,17 @@ tool_args( int argc, char **argv )
                        exit( EXIT_FAILURE );
                }
        }
+
        if( protocol == LDAP_VERSION2 ) {
-               if( authzid || manageDSAit || noop || ppolicy ) {
+               if( assertctl || authzid || manageDIT || manageDSAit ||
+#ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
+                       proxydn ||
+#endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
+#ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
+                       chaining ||
+#endif
+                       noop || ppolicy || preread || postread )
+               {
                        fprintf( stderr, "%s: -e/-M incompatible with LDAPv2\n", prog );
                        exit( EXIT_FAILURE );
                }
@@ -651,21 +896,13 @@ tool_args( int argc, char **argv )
                                prog );
                        exit( EXIT_FAILURE );
                }
-#endif
-       } else {
-#ifdef LDAP_API_FEATURE_X_OPENLDAP_V2_KBIND
-               if ( authmethod == LDAP_AUTH_KRBV4 || authmethod == LDAP_AUTH_KRBV41 ) {
-                       fprintf( stderr, "%s: -k/-K incompatible with LDAPv%d\n",
-                               prog, protocol );
-                       exit( EXIT_FAILURE );
-               }
 #endif
        }
 }
 
 
 LDAP *
-tool_conn_setup( int not, void (*private_setup)( LDAP * ) )
+tool_conn_setup( int dont, void (*private_setup)( LDAP * ) )
 {
        LDAP *ld = NULL;
 
@@ -688,7 +925,11 @@ tool_conn_setup( int not, void (*private_setup)( LDAP * ) )
        (void) SIGNAL( SIGPIPE, SIG_IGN );
 #endif
 
-       if ( !not ) {
+       if ( abcan ) {
+               SIGNAL( SIGINT, do_sig );
+       }
+
+       if ( !dont ) {
                int rc;
 
                if( ( ldaphost != NULL || ldapport ) && ( ldapuri == NULL ) ) {
@@ -735,12 +976,23 @@ tool_conn_setup( int not, void (*private_setup)( LDAP * ) )
                        exit( EXIT_FAILURE );
                }
 
-               if ( use_tls &&
-                       ( ldap_start_tls_s( ld, NULL, NULL ) != LDAP_SUCCESS ))
-               {
-                       ldap_perror( ld, "ldap_start_tls" );
-                       if ( use_tls > 1 ) {
-                               exit( EXIT_FAILURE );
+               if ( use_tls ) {
+                       rc = ldap_start_tls_s( ld, NULL, NULL );
+                       if ( rc != LDAP_SUCCESS ) {
+                               tool_perror( "ldap_start_tls", rc, NULL, NULL, NULL, NULL );
+                               if ( use_tls > 1 ) {
+                                       exit( EXIT_FAILURE );
+                               }
+                       }
+               }
+
+               if ( nettimeout.tv_sec > 0 ) {
+                       if ( ldap_set_option( ld, LDAP_OPT_NETWORK_TIMEOUT, (void *) &nettimeout )
+                               != LDAP_OPT_SUCCESS )
+                       {
+                               fprintf( stderr, "Could not set LDAP_OPT_NETWORK_TIMEOUT %ld\n",
+                                       (long)nettimeout.tv_sec );
+                               exit( EXIT_FAILURE );
                        }
                }
        }
@@ -752,19 +1004,28 @@ tool_conn_setup( int not, void (*private_setup)( LDAP * ) )
 void
 tool_bind( LDAP *ld )
 {
+       LDAPControl     **sctrlsp = NULL;
+       LDAPControl     *sctrls[2];
+       int             nsctrls = 0;
+
 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
+       LDAPControl c;
        if ( ppolicy ) {
-               LDAPControl *ctrls[2], c;
                c.ldctl_oid = LDAP_CONTROL_PASSWORDPOLICYREQUEST;
                c.ldctl_value.bv_val = NULL;
                c.ldctl_value.bv_len = 0;
                c.ldctl_iscritical = 0;
-               ctrls[0] = &c;
-               ctrls[1] = NULL;
-               ldap_set_option( ld, LDAP_OPT_SERVER_CONTROLS, ctrls );
+               sctrls[nsctrls] = &c;
+               sctrls[++nsctrls] = NULL;
        }
 #endif
 
+       if ( nsctrls ) {
+               sctrlsp = sctrls;
+       }
+
+       assert( nsctrls < sizeof(sctrls)/sizeof(sctrls[0]) );
+
        if ( authmethod == LDAP_AUTH_SASL ) {
 #ifdef HAVE_CYRUS_SASL
                void *defaults;
@@ -778,7 +1039,7 @@ tool_bind( LDAP *ld )
                                fprintf( stderr,
                                        "Could not set LDAP_OPT_X_SASL_SECPROPS: %s\n",
                                        sasl_secprops );
-                               exit( EXIT_FAILURE );
+                               exit( LDAP_LOCAL_ERROR );
                        }
                }
 
@@ -789,43 +1050,52 @@ tool_bind( LDAP *ld )
                        passwd.bv_val,
                        sasl_authz_id );
 
-               rc = ldap_sasl_interactive_bind_s( ld, binddn,
-                       sasl_mech, NULL, NULL,
-                       sasl_flags, lutil_sasl_interact, defaults );
+               rc = ldap_sasl_interactive_bind_s( ld, binddn, sasl_mech,
+                       sctrlsp,
+                       NULL, sasl_flags, lutil_sasl_interact, defaults );
 
                lutil_sasl_freedefs( defaults );
                if( rc != LDAP_SUCCESS ) {
-                       ldap_perror( ld, "ldap_sasl_interactive_bind_s" );
-                       exit( EXIT_FAILURE );
+                       tool_perror( "ldap_sasl_interactive_bind_s",
+                               rc, NULL, NULL, NULL, NULL );
+                       exit( rc );
                }
 #else
-               fprintf( stderr, "%s: not compiled with SASL support\n",
-                       prog );
-               exit( EXIT_FAILURE );
+               fprintf( stderr, "%s: not compiled with SASL support\n", prog );
+               exit( LDAP_NOT_SUPPORTED );
 #endif
        } else {
-               int msgid, err;
+               int msgid, err, rc;
                LDAPMessage *result;
                LDAPControl **ctrls;
                char msgbuf[256];
+               char *matched = NULL;
+               char *info = NULL;
+               char **refs = NULL;
 
                msgbuf[0] = 0;
 
-               if (( msgid = ldap_bind( ld, binddn, passwd.bv_val, authmethod )) == -1 )
                {
-                       ldap_perror( ld, "ldap_bind" );
-                       exit( EXIT_FAILURE );
+                       /* simple bind */
+                       rc = ldap_sasl_bind( ld, binddn, LDAP_SASL_SIMPLE, &passwd,
+                               sctrlsp, NULL, &msgid );
+                       if ( msgid == -1 ) {
+                               tool_perror( "ldap_sasl_bind(SIMPLE)", rc,
+                                       NULL, NULL, NULL, NULL );
+                               exit( rc );
+                       }
                }
 
-               if ( ldap_result( ld, msgid, 1, NULL, &result ) == -1 ) {
-                       ldap_perror( ld, "ldap_result" );
-                       exit( EXIT_FAILURE );
+               if ( ldap_result( ld, msgid, LDAP_MSG_ALL, NULL, &result ) == -1 ) {
+                       tool_perror( "ldap_result", -1, NULL, NULL, NULL, NULL );
+                       exit( LDAP_LOCAL_ERROR );
                }
 
-               if ( ldap_parse_result( ld, result, &err, NULL, NULL, NULL,
-                       &ctrls, 1 ) != LDAP_SUCCESS ) {
-                       ldap_perror( ld, "ldap_bind parse result" );
-                       exit( EXIT_FAILURE );
+               rc = ldap_parse_result( ld, result, &err, &matched, &info, &refs,
+                       &ctrls, 1 );
+               if ( rc != LDAP_SUCCESS ) {
+                       tool_perror( "ldap_bind parse result", rc, NULL, NULL, NULL, NULL );
+                       exit( LDAP_LOCAL_ERROR );
                }
 
 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
@@ -834,9 +1104,12 @@ tool_bind( LDAP *ld )
                        int expire, grace, len = 0;
                        LDAPPasswordPolicyError pErr = -1;
                        
-                       ctrl = ldap_find_control( LDAP_CONTROL_PASSWORDPOLICYRESPONSE, ctrls );
+                       ctrl = ldap_find_control( LDAP_CONTROL_PASSWORDPOLICYRESPONSE,
+                               ctrls );
+
                        if ( ctrl && ldap_parse_passwordpolicy_control( ld, ctrl,
-                               &expire, &grace, &pErr ) == LDAP_SUCCESS ) {
+                               &expire, &grace, &pErr ) == LDAP_SUCCESS )
+                       {
                                if ( pErr != PP_noError ){
                                        msgbuf[0] = ';';
                                        msgbuf[1] = ' ';
@@ -844,21 +1117,49 @@ tool_bind( LDAP *ld )
                                        len = strlen( msgbuf );
                                }
                                if ( expire >= 0 ) {
-                                       sprintf( msgbuf+len, " (Password expires in %d seconds)", expire );
+                                       sprintf( msgbuf+len,
+                                               " (Password expires in %d seconds)",
+                                               expire );
                                } else if ( grace >= 0 ) {
-                                       sprintf( msgbuf+len, " (Password expired, %d grace logins remain)", grace );
+                                       sprintf( msgbuf+len,
+                                               " (Password expired, %d grace logins remain)",
+                                               grace );
                                }
                        }
                }
 #endif
-               if ( err != LDAP_SUCCESS || msgbuf[0] ) {
-                       fprintf( stderr, "ldap_bind: %s%s\n", ldap_err2string( err ),
-                               msgbuf );
-                       if ( err != LDAP_SUCCESS ) {
-                               exit( EXIT_FAILURE );
-                       }
+
+               if ( ctrls ) {
+                       ldap_controls_free( ctrls );
                }
+
+               if ( err != LDAP_SUCCESS
+                       || msgbuf[0]
+                       || ( matched && matched[ 0 ] )
+                       || ( info && info[ 0 ] )
+                       || refs )
+               {
+                       tool_perror( "ldap_bind", err, msgbuf, matched, info, refs );
+
+                       if( matched ) ber_memfree( matched );
+                       if( info ) ber_memfree( info );
+                       if( refs ) ber_memvfree( (void **)refs );
+
+                       if ( err != LDAP_SUCCESS ) exit( err );
+               }
+       }
+}
+
+void
+tool_unbind( LDAP *ld )
+{
+       int err = ldap_set_option( ld, LDAP_OPT_SERVER_CONTROLS, NULL );
+
+       if ( err != LDAP_OPT_SUCCESS ) {
+               fprintf( stderr, "Could not unset controls\n");
        }
+
+       (void) ldap_unbind_ext( ld, NULL, NULL );
 }
 
 
@@ -867,7 +1168,25 @@ void
 tool_server_controls( LDAP *ld, LDAPControl *extra_c, int count )
 {
        int i = 0, j, crit = 0, err;
-       LDAPControl c[8], **ctrls;
+       LDAPControl c[10], **ctrls;
+
+       if ( ! ( assertctl
+               || authzid
+#ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
+               || proxydn
+#endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
+               || manageDIT
+               || manageDSAit
+               || noop
+               || preread
+               || postread
+#ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
+               || chaining
+#endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
+               || count ) )
+       {
+               return;
+       }
 
        ctrls = (LDAPControl**) malloc(sizeof(c) + (count+1)*sizeof(LDAPControl*));
        if ( ctrls == NULL ) {
@@ -905,18 +1224,49 @@ tool_server_controls( LDAP *ld, LDAPControl *extra_c, int count )
        }
 
        if ( authzid ) {
-               c[i].ldctl_oid = LDAP_CONTROL_PROXY_AUTHZ;
                c[i].ldctl_value.bv_val = authzid;
                c[i].ldctl_value.bv_len = strlen( authzid );
+               c[i].ldctl_oid = LDAP_CONTROL_PROXY_AUTHZ;
+               c[i].ldctl_iscritical = 1;
+               ctrls[i] = &c[i];
+               i++;
+       }
+
+#ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
+       /* NOTE: doesn't need an extra count because it's incompatible
+        * with authzid */
+       if ( proxydn ) {
+               BerElementBuffer berbuf;
+               BerElement *ber = (BerElement *)&berbuf;
+               
+               ber_init2( ber, NULL, LBER_USE_DER );
+
+               if ( ber_printf( ber, "s", proxydn ) == LBER_ERROR ) {
+                       exit( EXIT_FAILURE );
+               }
+
+               if ( ber_flatten2( ber, &c[i].ldctl_value, 0 ) == -1 ) {
+                       exit( EXIT_FAILURE );
+               }
+
+               c[i].ldctl_oid = LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ;
                c[i].ldctl_iscritical = 1;
                ctrls[i] = &c[i];
                i++;
        }
+#endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
+
+       if ( manageDIT ) {
+               c[i].ldctl_oid = LDAP_CONTROL_MANAGEDIT;
+               BER_BVZERO( &c[i].ldctl_value );
+               c[i].ldctl_iscritical = manageDIT > 1;
+               ctrls[i] = &c[i];
+               i++;
+       }
 
        if ( manageDSAit ) {
                c[i].ldctl_oid = LDAP_CONTROL_MANAGEDSAIT;
-               c[i].ldctl_value.bv_val = NULL;
-               c[i].ldctl_value.bv_len = 0;
+               BER_BVZERO( &c[i].ldctl_value );
                c[i].ldctl_iscritical = manageDSAit > 1;
                ctrls[i] = &c[i];
                i++;
@@ -924,8 +1274,7 @@ tool_server_controls( LDAP *ld, LDAPControl *extra_c, int count )
 
        if ( noop ) {
                c[i].ldctl_oid = LDAP_CONTROL_NOOP;
-               c[i].ldctl_value.bv_val = NULL;
-               c[i].ldctl_value.bv_len = 0;
+               BER_BVZERO( &c[i].ldctl_value );
                c[i].ldctl_iscritical = noop > 1;
                ctrls[i] = &c[i];
                i++;
@@ -991,6 +1340,52 @@ tool_server_controls( LDAP *ld, LDAPControl *extra_c, int count )
                if( attrs ) ldap_charray_free( attrs );
        }
 
+#ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
+       if ( chaining ) {
+               if ( chainingResolve > -1 ) {
+                       BerElementBuffer berbuf;
+                       BerElement *ber = (BerElement *)&berbuf;
+
+                       ber_init2( ber, NULL, LBER_USE_DER );
+
+                       err = ber_printf( ber, "{e" /* } */, chainingResolve );
+                       if ( err == -1 ) {
+                               ber_free( ber, 1 );
+                               fprintf( stderr, _("Chaining behavior control encoding error!\n") );
+                               exit( EXIT_FAILURE );
+                       }
+
+                       if ( chainingContinuation > -1 ) {
+                               err = ber_printf( ber, "e", chainingContinuation );
+                               if ( err == -1 ) {
+                                       ber_free( ber, 1 );
+                                       fprintf( stderr, _("Chaining behavior control encoding error!\n") );
+                                       exit( EXIT_FAILURE );
+                               }
+                       }
+
+                       err = ber_printf( ber, /* { */ "N}" );
+                       if ( err == -1 ) {
+                               ber_free( ber, 1 );
+                               fprintf( stderr, _("Chaining behavior control encoding error!\n") );
+                               exit( EXIT_FAILURE );
+                       }
+
+                       if ( ber_flatten2( ber, &c[i].ldctl_value, 0 ) == -1 ) {
+                               exit( EXIT_FAILURE );
+                       }
+
+               } else {
+                       BER_BVZERO( &c[i].ldctl_value );
+               }
+
+               c[i].ldctl_oid = LDAP_CONTROL_X_CHAINING_BEHAVIOR;
+               c[i].ldctl_iscritical = chaining > 1;
+               ctrls[i] = &c[i];
+               i++;
+       }
+#endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
+
        while ( count-- ) {
                ctrls[i++] = extra_c++;
        }
@@ -1011,3 +1406,308 @@ tool_server_controls( LDAP *ld, LDAPControl *extra_c, int count )
                exit( EXIT_FAILURE );
        }
 }
+
+int
+tool_check_abandon( LDAP *ld, int msgid )
+{
+       int     rc;
+
+       switch ( gotintr ) {
+       case LDAP_REQ_EXTENDED:
+               rc = ldap_cancel_s( ld, msgid, NULL, NULL );
+               fprintf( stderr, "got interrupt, cancel got %d: %s\n",
+                               rc, ldap_err2string( rc ) );
+               return -1;
+
+       case LDAP_REQ_ABANDON:
+               rc = ldap_abandon_ext( ld, msgid, NULL, NULL );
+               fprintf( stderr, "got interrupt, abandon got %d: %s\n",
+                               rc, ldap_err2string( rc ) );
+               return -1;
+       }
+
+       return 0;
+}
+
+static int
+print_prepostread( LDAP *ld, LDAPControl *ctrl, struct berval *what)
+{
+       BerElement      *ber;
+       struct berval   bv;
+
+       tool_write_ldif( LDIF_PUT_COMMENT, "==> ",
+               what->bv_val, what->bv_len );
+       ber = ber_init( &ctrl->ldctl_value );
+       if ( ber == NULL ) {
+               /* error? */
+               return 1;
+
+       } else if ( ber_scanf( ber, "{m{" /*}}*/, &bv ) == LBER_ERROR ) {
+               /* error? */
+               return 1;
+
+       } else {
+               tool_write_ldif( LDIF_PUT_VALUE, "dn", bv.bv_val, bv.bv_len );
+
+               while ( ber_scanf( ber, "{m" /*}*/, &bv ) != LBER_ERROR ) {
+                       int             i;
+                       BerVarray       vals = NULL;
+
+                       if ( ber_scanf( ber, "[W]", &vals ) == LBER_ERROR ||
+                               vals == NULL )
+                       {
+                               /* error? */
+                               return 1;
+                       }
+               
+                       for ( i = 0; vals[ i ].bv_val != NULL; i++ ) {
+                               tool_write_ldif(
+                                       ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
+                                       bv.bv_val, vals[ i ].bv_val, vals[ i ].bv_len );
+                       }
+
+                       ber_bvarray_free( vals );
+               }
+       }
+
+       if ( ber != NULL ) {
+               ber_free( ber, 1 );
+       }
+
+       tool_write_ldif( LDIF_PUT_COMMENT, "<== ",
+               what->bv_val, what->bv_len );
+
+       return 0;
+}
+
+static int
+print_preread( LDAP *ld, LDAPControl *ctrl )
+{
+       static struct berval what = BER_BVC( "preread" );
+
+       return print_prepostread( ld, ctrl, &what );
+}
+
+static int
+print_postread( LDAP *ld, LDAPControl *ctrl )
+{
+       static struct berval what = BER_BVC( "postread" );
+
+       return print_prepostread( ld, ctrl, &what );
+}
+
+static int
+print_paged_results( LDAP *ld, LDAPControl *ctrl )
+{
+       ber_int_t estimate;
+
+       /* note: pr_cookie is being malloced; it's freed
+        * the next time the control is sent, but the last
+        * time it's not; we don't care too much, because
+        * the last time an empty value is returned... */
+       if ( ldap_parse_pageresponse_control( ld, ctrl, &estimate, &pr_cookie )
+               != LDAP_SUCCESS )
+       {
+               /* error? */
+               return 1;
+
+       } else {
+               /* FIXME: check buffer overflow */
+               char    buf[ BUFSIZ ], *ptr = buf;
+
+               if ( estimate > 0 ) {
+                       ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
+                               "estimate=%d", estimate );
+               }
+
+               if ( pr_cookie.bv_len > 0 ) {
+                       struct berval   bv;
+
+                       bv.bv_len = LUTIL_BASE64_ENCODE_LEN(
+                               pr_cookie.bv_len ) + 1;
+                       bv.bv_val = ber_memalloc( bv.bv_len + 1 );
+
+                       bv.bv_len = lutil_b64_ntop(
+                               (unsigned char *) pr_cookie.bv_val,
+                               pr_cookie.bv_len,
+                               bv.bv_val, bv.bv_len );
+
+                       ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
+                               "%scookie=%s", ptr == buf ? "" : " ",
+                               bv.bv_val );
+
+                       ber_memfree( bv.bv_val );
+
+                       pr_morePagedResults = 1;
+
+               } else {
+                       ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
+                               "%scookie=", ptr == buf ? "" : " " );
+               }
+
+               tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
+                       "pagedresults", buf, ptr - buf );
+       }
+
+       return 0;
+}
+
+#ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
+static int
+print_ppolicy( LDAP *ld, LDAPControl *ctrl )
+{
+       int expire = 0, grace = 0, rc;
+       LDAPPasswordPolicyError pperr;
+
+       rc = ldap_parse_passwordpolicy_control( ld, ctrl,
+               &expire, &grace, &pperr );
+       if ( rc == LDAP_SUCCESS ) {
+               char    buf[ BUFSIZ ], *ptr = buf;
+
+               if ( expire != -1 ) {
+                       ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
+                               "expire=%d", expire );
+               }
+
+               if ( grace != -1 ) {
+                       ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
+                               "%sgrace=%d", ptr == buf ? "" : " ", grace );
+               }
+
+               if ( pperr != PP_noError ) {
+                       ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
+                               "%serror=%s", ptr == buf ? "" : " ",
+                               ldap_passwordpolicy_err2txt( pperr ) );
+               }
+
+               tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
+                       "ppolicy", buf, ptr - buf );
+       }
+
+       return rc;
+}
+#endif
+
+void tool_print_ctrls(
+       LDAP            *ld,
+       LDAPControl     **ctrls )
+{
+       int     i;
+       char    *ptr;
+
+       for ( i = 0; ctrls[i] != NULL; i++ ) {
+               /* control: OID criticality base64value */
+               struct berval b64 = BER_BVNULL;
+               ber_len_t len;
+               char *str;
+               int j;
+
+               len = ldif ? 2 : 0;
+               len += strlen( ctrls[i]->ldctl_oid );
+
+               /* add enough for space after OID and the critical value itself */
+               len += ctrls[i]->ldctl_iscritical
+                       ? sizeof("true") : sizeof("false");
+
+               /* convert to base64 */
+               if ( ctrls[i]->ldctl_value.bv_len ) {
+                       b64.bv_len = LUTIL_BASE64_ENCODE_LEN(
+                               ctrls[i]->ldctl_value.bv_len ) + 1;
+                       b64.bv_val = ber_memalloc( b64.bv_len + 1 );
+
+                       b64.bv_len = lutil_b64_ntop(
+                               (unsigned char *) ctrls[i]->ldctl_value.bv_val,
+                               ctrls[i]->ldctl_value.bv_len,
+                               b64.bv_val, b64.bv_len );
+               }
+
+               if ( b64.bv_len ) {
+                       len += 1 + b64.bv_len;
+               }
+
+               ptr = str = malloc( len + 1 );
+               if ( ldif ) {
+                       ptr = lutil_strcopy( ptr, ": " );
+               }
+               ptr = lutil_strcopy( ptr, ctrls[i]->ldctl_oid );
+               ptr = lutil_strcopy( ptr, ctrls[i]->ldctl_iscritical
+                       ? " true" : " false" );
+
+               if ( b64.bv_len ) {
+                       ptr = lutil_strcopy( ptr, " " );
+                       ptr = lutil_strcopy( ptr, b64.bv_val );
+               }
+
+               if ( ldif < 2 ) {
+                       tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
+                               "control", str, len );
+               }
+
+               free( str );
+               if ( b64.bv_len ) {
+                       ber_memfree( b64.bv_val );
+               }
+
+               /* known controls */
+               for ( j = 0; tool_ctrl_response[j].oid != NULL; j++ ) {
+                       if ( strcmp( tool_ctrl_response[j].oid, ctrls[i]->ldctl_oid ) == 0 ) {
+                               if ( !tool_ctrl_response[j].mask & tool_type ) {
+                                       /* this control should not appear
+                                        * with this tool; warning? */
+                               }
+                               break;
+                       }
+               }
+
+               if ( tool_ctrl_response[j].oid != NULL && tool_ctrl_response[j].func ) {
+                       (void)tool_ctrl_response[j].func( ld, ctrls[i] );
+               }
+       }
+}
+
+int
+tool_write_ldif( int type, char *name, char *value, ber_len_t vallen )
+{
+       char    *ldif;
+
+       if (( ldif = ldif_put( type, name, value, vallen )) == NULL ) {
+               return( -1 );
+       }
+
+       fputs( ldif, stdout );
+       ber_memfree( ldif );
+
+       return( 0 );
+}
+
+int
+tool_is_oid( const char *s )
+{
+       int             first = 1;
+
+       if ( !isdigit( (unsigned char) s[ 0 ] ) ) {
+               return 0;
+       }
+
+       for ( ; s[ 0 ]; s++ ) {
+               if ( s[ 0 ] == '.' ) {
+                       if ( s[ 1 ] == '\0' ) {
+                               return 0;
+                       }
+                       first = 1;
+                       continue;
+               }
+
+               if ( !isdigit( (unsigned char) s[ 0 ] ) ) {
+                       return 0;
+               }
+
+               if ( first == 1 && s[ 0 ] == '0' && s[ 1 ] != '.' ) {
+                       return 0;
+               }
+               first = 0;
+       }
+
+       return 1;
+}
+