]> git.sur5r.net Git - openldap/blobdiff - clients/tools/common.c
ITS#6915 fix op timestamps
[openldap] / clients / tools / common.c
index cb0135e909d46195837253435b7c74e38b7df924..262631e4cad1ca904c684786ff9fc4d33cdadbe9 100644 (file)
@@ -2,7 +2,7 @@
 /* $OpenLDAP$ */
 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
  *
- * Copyright 1998-2006 The OpenLDAP Foundation.
+ * Copyright 1998-2011 The OpenLDAP Foundation.
  * Portions Copyright 2003 Kurt D. Zeilenga.
  * Portions Copyright 2003 IBM Corporation.
  * All rights reserved.
@@ -32,6 +32,8 @@
 #include <ac/ctype.h>
 #include <ac/unistd.h>
 #include <ac/errno.h>
+#include <ac/time.h>
+#include <ac/socket.h>
 
 #ifdef HAVE_CYRUS_SASL
 #ifdef HAVE_SASL_SASL_H
 
 #include "common.h"
 
-#ifdef LDAP_API_FEATURE_X_OPENLDAP_V2_KBIND
-#if !LDAP_DEPRECATED
-/* Necessary for old LDAPv2 Kerberos Bind methods */
-LDAP_F( int )
-ldap_bind LDAP_P((     /* deprecated */
-       LDAP *ld,
-       LDAP_CONST char *who,
-       LDAP_CONST char *passwd,
-       int authmethod ));
-#endif
-#endif
-
 /* input-related vars */
 
 /* misc. parameters */
@@ -72,9 +62,11 @@ int          contoper = 0;
 int            debug = 0;
 char           *infile = NULL;
 int            dont = 0;
+int            nocanon = 0;
 int            referrals = 0;
 int            verbose = 0;
 int            ldif = 0;
+ber_len_t      ldif_wrap = LDIF_LINE_WIDTH;
 char           *prog = NULL;
 
 /* connection */
@@ -103,7 +95,9 @@ char         *sasl_secprops = NULL;
 /* controls */
 int            assertctl;
 char           *assertion = NULL;
+struct berval  assertionvalue = BER_BVNULL;
 char           *authzid = NULL;
+int            authzcrit = 1;
 /* 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
@@ -124,15 +118,41 @@ int               chaining = 0;
 static int     chainingResolve = -1;
 static int     chainingContinuation = -1;
 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
+#ifdef LDAP_CONTROL_X_SESSION_TRACKING
+static int     sessionTracking = 0;
+static char    *sessionTrackingName;
+struct berval  stValue;
+#endif /* LDAP_CONTROL_X_SESSION_TRACKING */
+ber_int_t vlvPos;
+ber_int_t vlvCount;
+struct berval *vlvContext;
+static int     bauthzid;
+
+LDAPControl    *unknown_ctrls = NULL;
+int            unknown_ctrls_num = 0;
+
+/* 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_AUTHZID_RESPONSE
+static int print_authzid( LDAP *ld, LDAPControl *ctrl );
+#endif
 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
 static int print_ppolicy( LDAP *ld, LDAPControl *ctrl );
 #endif
+static int print_sss( LDAP *ld, LDAPControl *ctrl );
+static int print_vlv( LDAP *ld, LDAPControl *ctrl );
+#ifdef LDAP_CONTROL_X_DEREF
+static int print_deref( LDAP *ld, LDAPControl *ctrl );
+#endif
+#ifdef LDAP_CONTROL_X_WHATFAILED
+static int print_whatfailed( LDAP *ld, LDAPControl *ctrl );
+#endif
 
 static struct tool_ctrls_t {
        const char      *oid;
@@ -142,15 +162,77 @@ static struct tool_ctrls_t {
        { 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_AUTHZID_RESPONSE
+       /* this is generally deprecated in favor of LDAP WhoAmI? operation, hence only supported as a VC inner control */
+       { LDAP_CONTROL_AUTHZID_RESPONSE,                TOOL_VC,        print_authzid },
+#endif
 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
        { LDAP_CONTROL_PASSWORDPOLICYRESPONSE,          TOOL_ALL,       print_ppolicy },
+#endif
+       { LDAP_CONTROL_SORTRESPONSE,    TOOL_SEARCH,    print_sss },
+       { LDAP_CONTROL_VLVRESPONSE,             TOOL_SEARCH,    print_vlv },
+#ifdef LDAP_CONTROL_X_DEREF
+       { LDAP_CONTROL_X_DEREF,                         TOOL_SEARCH,    print_deref },
+#endif
+#ifdef LDAP_CONTROL_X_WHATFAILED
+       { LDAP_CONTROL_X_WHATFAILED,                    TOOL_ALL,       print_whatfailed },
 #endif
        { NULL,                                         0,              NULL }
 };
 
 /* "features" */
-static int     gotintr;
-static int     abcan;
+enum { Intr_None = 0, Intr_Abandon, Intr_Cancel, Intr_Ignore }; 
+static volatile sig_atomic_t   gotintr, abcan;
+
+
+#ifdef LDAP_CONTROL_X_SESSION_TRACKING
+static int
+st_value( LDAP *ld, struct berval *value )
+{
+       char            *ip = NULL, *name = NULL;
+       struct berval   id = { 0 };
+       char            namebuf[ MAXHOSTNAMELEN ];
+
+       if ( gethostname( namebuf, sizeof( namebuf ) ) == 0 ) {
+               struct hostent  *h;
+               struct in_addr  addr;
+
+               name = namebuf;
+
+               h = gethostbyname( name );
+               if ( h != NULL ) {
+                       AC_MEMCPY( &addr, h->h_addr, sizeof( addr ) );
+                       ip = inet_ntoa( addr );
+               }
+       }
+
+       if ( sessionTrackingName != NULL ) {
+               ber_str2bv( sessionTrackingName , 0, 0, &id );
+       } else
+#ifdef HAVE_CYRUS_SASL
+       if ( sasl_authz_id != NULL ) {
+               ber_str2bv( sasl_authz_id, 0, 0, &id );
+
+       } else if ( sasl_authc_id != NULL ) {
+               ber_str2bv( sasl_authc_id, 0, 0, &id );
+
+       } else 
+#endif /* HAVE_CYRUS_SASL */
+       if ( binddn != NULL ) {
+               ber_str2bv( binddn, 0, 0, &id );
+       }
+
+       if ( ldap_create_session_tracking_value( ld,
+               ip, name, LDAP_CONTROL_X_SESSION_TRACKING_USERNAME,
+               &id, &stValue ) )
+       {
+               fprintf( stderr, _("Session tracking control encoding error!\n") );
+               return -1;
+       }
+
+       return 0;
+}
+#endif /* LDAP_CONTROL_X_SESSION_TRACKING */
 
 RETSIGTYPE
 do_sig( int sig )
@@ -176,19 +258,87 @@ tool_destroy( void )
 #ifdef HAVE_TLS
        ldap_pvt_tls_destroy();
 #endif
+
+       if ( ldapuri != NULL ) {
+               ber_memfree( ldapuri );
+               ldapuri = NULL;
+       }
+
+       if ( pr_cookie.bv_val != NULL ) {
+               ber_memfree( pr_cookie.bv_val );
+               BER_BVZERO( &pr_cookie );
+       }
+
+       if ( binddn != NULL ) {
+               ber_memfree( binddn );
+               binddn = NULL;
+       }
+
+       if ( passwd.bv_val != NULL ) {
+               ber_memfree( passwd.bv_val );
+               BER_BVZERO( &passwd );
+       }
+
+#ifdef HAVE_CYRUS_SASL
+       if ( sasl_mech != NULL ) {
+               ber_memfree( sasl_mech );
+               sasl_mech = NULL;
+       }
+#endif /* HAVE_CYRUS_SASL */
+
+       if ( infile != NULL ) {
+               ber_memfree( infile );
+               infile = NULL;
+       }
+
+       if ( assertion ) {
+               ber_memfree( assertion );
+               assertion = NULL;
+       }
+
+       if ( authzid ) {
+               ber_memfree( authzid );
+               authzid = NULL;
+       }
+
+       if ( proxydn ) {
+               ber_memfree( proxydn );
+               proxydn = NULL;
+       }
+
+       if ( preread_attrs ) {
+               ber_memfree( preread_attrs );
+               preread_attrs = NULL;
+       }
+
+       if ( postread_attrs ) {
+               ber_memfree( postread_attrs );
+               postread_attrs = NULL;
+       }
+
+#ifdef LDAP_CONTROL_X_SESSION_TRACKING
+       if ( !BER_BVISNULL( &stValue ) ) {
+               ber_memfree( stValue.bv_val );
+               BER_BVZERO( &stValue );
+       }
+
+       if ( sessionTrackingName ) {
+               ber_memfree( sessionTrackingName );
+               sessionTrackingName = NULL;
+       }
+#endif /* LDAP_CONTROL_X_SESSION_TRACKING */
 }
 
 void
 tool_common_usage( void )
 {
        static const char *const descriptions[] = {
-N_("  -c         continuous operation mode (do not stop on errors)\n"),
-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>     (a RFC 4515 Filter string)\n")
-N_("             [!]authzid=<authzid>   (\"dn:<dn>\" or \"u:<user>\")\n")
+N_("             [!]assert=<filter>     (RFC 4528; a RFC 4515 Filter string)\n")
+N_("             [!]authzid=<authzid>   (RFC 4370; \"dn:<dn>\" or \"u:<user>\")\n")
+N_("             [!]bauthzid            (RFC 3829)\n")
 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
 #if 0
                  /* non-advertized support for proxyDN */
@@ -200,28 +350,30 @@ N_("             [!]chaining[=<resolveBehavior>[/<continuationBehavior>]]\n")
 N_("                     one of \"chainingPreferred\", \"chainingRequired\",\n")
 N_("                     \"referralsPreferred\", \"referralsRequired\"\n")
 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
-#ifdef LDAP_DEVEL
-N_("             [!]manageDIT\n")
-#endif
-N_("             [!]manageDSAit\n")
+N_("             [!]manageDSAit         (RFC 3296)\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_("             abandon, cancel (SIGINT sends abandon/cancel; not really controls)\n")
-N_("  -f file    read operations from `file'\n"),
+N_("             [!]postread[=<attrs>]  (RFC 4527; comma-separated attr list)\n")
+N_("             [!]preread[=<attrs>]   (RFC 4527; comma-separated attr list)\n")
+N_("             [!]relax\n")
+#ifdef LDAP_CONTROL_X_SESSION_TRACKING
+N_("             [!]sessiontracking[=<username>]\n")
+#endif /* LDAP_CONTROL_X_SESSION_TRACKING */
+N_("             abandon, cancel, ignore (SIGINT sends abandon/cancel,\n"
+   "             or ignores response; if critical, doesn't wait for SIGINT.\n"
+   "             not really controls)\n")
 N_("  -h host    LDAP server\n"),
-N_("  -H URI     LDAP Uniform Resource Indentifier(s)\n"),
+N_("  -H URI     LDAP Uniform Resource Identifier(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_("  -N         do not use reverse DNS to canonicalize SASL host name\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_("             ldif-wrap=<width> (in columns, or \"no\" for no wrapping)\n"),
 N_("  -p port    port on LDAP server\n"),
-N_("  -P version procotol version (default: 3)\n"),
 N_("  -Q         use SASL Quiet mode\n"),
 N_("  -R realm   SASL realm\n"),
 N_("  -U authcid SASL authentication identity\n"),
@@ -244,6 +396,8 @@ NULL
                        fputs( _(*cpp), stderr );
                }
        }
+
+       tool_destroy();
 }
 
 void tool_perror(
@@ -305,15 +459,15 @@ tool_args( int argc, char **argv )
                        }
                        binddn = ber_strdup( optarg );
                        break;
-               case 'e': /* general extensions (controls and such) */
+               case 'e':       /* general extensions (controls and such) */
                        /* should be extended to support comma separated list of
                         *      [!]key[=value] parameters, e.g.  -e !foo,bar=567
                         */
 
                        crit = 0;
                        cvalue = NULL;
-                       if( optarg[0] == '!' ) {
-                               crit = 1;
+                       while ( optarg[0] == '!' ) {
+                               crit++;
                                optarg++;
                        }
 
@@ -335,7 +489,7 @@ tool_args( int argc, char **argv )
                                assertctl = 1 + crit;
 
                                assert( assertion == NULL );
-                               assertion = cvalue;
+                               assertion = ber_strdup( cvalue );
 
                        } else if ( strcasecmp( control, "authzid" ) == 0 ) {
                                if( authzid != NULL ) {
@@ -355,10 +509,14 @@ tool_args( int argc, char **argv )
                                if( !crit ) {
                                        fprintf( stderr, "authzid: must be marked critical\n" );
                                        usage();
+                               } else if ( crit > 1 ) {
+                                       /* purposely flag proxied authorization
+                                        * as non-critical, to test DSA */
+                                       authzcrit = 0;
                                }
 
                                assert( authzid == NULL );
-                               authzid = cvalue;
+                               authzid = ber_strdup( cvalue );
 
 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
                        } else if ( strcasecmp( control, "proxydn" ) == 0 ) {
@@ -377,21 +535,38 @@ tool_args( int argc, char **argv )
                                if( !crit ) {
                                        fprintf( stderr, "proxydn: must be marked critical\n" );
                                        usage();
+                               } else if ( crit > 1 ) {
+                                       /* purposely flag proxied authorization
+                                        * as non-critical, to test DSA */
+                                       authzcrit = 0;
                                }
 
                                assert( proxydn == NULL );
-                               proxydn = cvalue;
+                               proxydn = ber_strdup( cvalue );
 #endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
 
-                       } else if ( strcasecmp( control, "manageDIT" ) == 0 ) {
+                       } else if ( strcasecmp( control, "bauthzid" ) == 0 ) {
+                               if( bauthzid ) {
+                                       fprintf( stderr, "bauthzid control previously specified\n");
+                                       exit( EXIT_FAILURE );
+                               }
+                               if( cvalue != NULL ) {
+                                       fprintf( stderr, "bauthzid: no control value expected\n" );
+                                       usage();
+                               }
+                               bauthzid = 1 + crit;
+
+                       } else if ( ( strcasecmp( control, "relax" ) == 0 ) ||
+                               ( strcasecmp( control, "manageDIT" ) == 0 ) )
+                       {
                                if( manageDIT ) {
                                        fprintf( stderr,
-                                               "manageDIT control previously specified\n");
+                                               "relax control previously specified\n");
                                        exit( EXIT_FAILURE );
                                }
                                if( cvalue != NULL ) {
                                        fprintf( stderr,
-                                               "manageDIT: no control value expected\n" );
+                                               "relax: no control value expected\n" );
                                        usage();
                                }
 
@@ -448,7 +623,7 @@ tool_args( int argc, char **argv )
                                }
 
                                preread = 1 + crit;
-                               preread_attrs = cvalue;
+                               preread_attrs = ber_strdup( cvalue );
 
                        } else if ( strcasecmp( control, "postread" ) == 0 ) {
                                if( postread ) {
@@ -457,10 +632,15 @@ tool_args( int argc, char **argv )
                                }
 
                                postread = 1 + crit;
-                               postread_attrs = cvalue;
+                               postread_attrs = ber_strdup( cvalue );
 
 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
                        } else if ( strcasecmp( control, "chaining" ) == 0 ) {
+                               if ( chaining ) {
+                                       fprintf( stderr, "chaining control previously specified\n");
+                                       exit( EXIT_FAILURE );
+                               }
+
                                chaining = 1 + crit;
 
                                if ( cvalue != NULL ) {
@@ -505,18 +685,102 @@ tool_args( int argc, char **argv )
                                }
 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
 
+#ifdef LDAP_CONTROL_X_SESSION_TRACKING
+                       } else if ( strcasecmp( control, "sessiontracking" ) == 0 ) {
+                               if ( sessionTracking ) {
+                                       fprintf( stderr, "%s: session tracking can be only specified once\n", prog );
+                                       exit( EXIT_FAILURE );
+                               }
+                               sessionTracking = 1;
+                               if ( crit ) {
+                                       fprintf( stderr, "sessiontracking: critical flag not allowed\n" );
+                                       usage();
+                               }
+                               if ( cvalue ) {
+                                       sessionTrackingName = ber_strdup( cvalue );
+                               }
+#endif /* LDAP_CONTROL_X_SESSION_TRACKING */
+
                        /* this shouldn't go here, really; but it's a feature... */
                        } else if ( strcasecmp( control, "abandon" ) == 0 ) {
-                               abcan = LDAP_REQ_ABANDON;
+                               abcan = Intr_Abandon;
+                               if ( crit ) {
+                                       gotintr = abcan;
+                               }
 
                        } else if ( strcasecmp( control, "cancel" ) == 0 ) {
-                               abcan = LDAP_REQ_EXTENDED;
+                               abcan = Intr_Cancel;
+                               if ( crit ) {
+                                       gotintr = abcan;
+                               }
+
+                       } else if ( strcasecmp( control, "ignore" ) == 0 ) {
+                               abcan = Intr_Ignore;
+                               if ( crit ) {
+                                       gotintr = abcan;
+                               }
+
+                       } else if ( tool_is_oid( control ) ) {
+                               LDAPControl     *tmpctrls, ctrl;
+
+                               if ( unknown_ctrls != NULL ) {
+                                       int i;
+                                       for ( i = 0; unknown_ctrls[ i ].ldctl_oid != NULL; i++ ) {
+                                               if ( strcmp( control, unknown_ctrls[ i ].ldctl_oid ) == 0 ) {
+                                                       fprintf( stderr, "%s control previously specified\n", control );
+                                                       exit( EXIT_FAILURE );
+                                               }
+                                       }
+                               }
+
+                               tmpctrls = (LDAPControl *)ber_memrealloc( unknown_ctrls,
+                                       (unknown_ctrls_num + 1)*sizeof( LDAPControl ) );
+                               if ( tmpctrls == NULL ) {
+                                       fprintf( stderr, "%s: no memory?\n", prog );
+                                       exit( EXIT_FAILURE );
+                               }
+                               unknown_ctrls = tmpctrls;
+                               ctrl.ldctl_oid = control;
+                               /* don't free it */
+                               control = NULL;
+                               ctrl.ldctl_value.bv_val = NULL;
+                               ctrl.ldctl_value.bv_len = 0;
+                               ctrl.ldctl_iscritical = crit;
+
+                               if ( cvalue != NULL ) {
+                                       struct berval   bv;
+                                       size_t          len = strlen( cvalue );
+                                       int             retcode;
+
+                                       bv.bv_len = LUTIL_BASE64_DECODE_LEN( len );
+                                       bv.bv_val = ber_memalloc( bv.bv_len + 1 );
+
+                                       retcode = lutil_b64_pton( cvalue,
+                                               (unsigned char *)bv.bv_val,
+                                               bv.bv_len );
+
+                                       if ( retcode == -1 || (unsigned) retcode > bv.bv_len ) {
+                                               fprintf( stderr, "Unable to parse value of general control %s\n",
+                                                       control );
+                                               usage();
+                                       }
+
+                                       bv.bv_len = retcode;
+                                       ctrl.ldctl_value = bv;
+                               }
+
+                               unknown_ctrls[ unknown_ctrls_num ] = ctrl;
+                               unknown_ctrls_num++;
 
                        } else {
                                fprintf( stderr, "Invalid general control name: %s\n",
                                        control );
                                usage();
                        }
+                       if ( control ) {
+                               ber_memfree( control );  
+                               control = NULL;
+                       }
                        break;
                case 'f':       /* read from file */
                        if( infile != NULL ) {
@@ -555,32 +819,6 @@ 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++;
@@ -588,6 +826,67 @@ tool_args( int argc, char **argv )
                case 'n':       /* print operations, don't actually do them */
                        dont++;
                        break;
+               case 'N':
+                       nocanon++;
+                       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 if ( strcasecmp( control, "ldif-wrap" ) == 0 ) {
+                               if ( cvalue == 0 ) {
+                                       ldif_wrap = LDIF_LINE_WIDTH;
+
+                               } else if ( strcasecmp( cvalue, "no" ) == 0 ) {
+                                       ldif_wrap = LDIF_LINE_WIDTH_MAX;
+
+                               } else {
+                                       unsigned int u;
+                                       if ( lutil_atou( &u, cvalue ) ) {
+                                               fprintf( stderr,
+                                                       _("Unable to parse ldif-wrap=\"%s\"\n"), cvalue );
+                                               exit( EXIT_FAILURE );
+                                       }
+                                       ldif_wrap = (ber_len_t)u;
+                               }
+
+                       } else {
+                               fprintf( stderr, "Invalid general option name: %s\n",
+                                       control );
+                               usage();
+                       }
+                       ber_memfree(control);
+                       break;
                case 'O':
 #ifdef HAVE_CYRUS_SASL
                        if( sasl_secprops != NULL ) {
@@ -621,7 +920,7 @@ tool_args( int argc, char **argv )
                case 'P':
                        ival = strtol( optarg, &next, 10 );
                        if ( next == NULL || next[0] != '\0' ) {
-                               fprintf( stderr, "%s: unabel to parse protocol version \"%s\"\n", prog, optarg );
+                               fprintf( stderr, "%s: unable to parse protocol version \"%s\"\n", prog, optarg );
                                exit( EXIT_FAILURE );
                        }
                        switch( ival ) {
@@ -842,7 +1141,11 @@ tool_args( int argc, char **argv )
 
        if (authmethod == -1 && protocol > LDAP_VERSION2) {
 #ifdef HAVE_CYRUS_SASL
-               authmethod = LDAP_AUTH_SASL;
+               if ( binddn != NULL ) {
+                       authmethod = LDAP_AUTH_SIMPLE;
+               } else {
+                       authmethod = LDAP_AUTH_SASL;
+               }
 #else
                authmethod = LDAP_AUTH_SIMPLE;
 #endif
@@ -872,6 +1175,9 @@ tool_args( int argc, char **argv )
 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
                        chaining ||
 #endif
+#ifdef LDAP_CONTROL_X_SESSION_TRACKING
+                       sessionTracking ||
+#endif /* LDAP_CONTROL_X_SESSION_TRACKING */
                        noop || ppolicy || preread || postread )
                {
                        fprintf( stderr, "%s: -e/-M incompatible with LDAPv2\n", prog );
@@ -890,15 +1196,12 @@ tool_args( int argc, char **argv )
                        exit( EXIT_FAILURE );
                }
 #endif
+       }
 
-#ifdef LDAP_API_FEATURE_X_OPENLDAP_V2_KBIND
-       } else {
-               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
+       if ( ( pw_file || want_bindpw ) && !BER_BVISNULL( &passwd ) ) {
+               fprintf( stderr, "%s: -%c incompatible with -w\n",
+                       prog, ( pw_file ? 'y' : 'W' ) );
+               exit( EXIT_FAILURE );
        }
 }
 
@@ -945,6 +1248,137 @@ tool_conn_setup( int dont, void (*private_setup)( LDAP * ) )
                        url.lud_scope = LDAP_SCOPE_DEFAULT;
 
                        ldapuri = ldap_url_desc2str( &url );
+
+               } else if ( ldapuri != NULL ) {
+                       LDAPURLDesc     *ludlist, **ludp;
+                       char            **urls = NULL;
+                       int             nurls = 0;
+
+                       rc = ldap_url_parselist( &ludlist, ldapuri );
+                       if ( rc != LDAP_URL_SUCCESS ) {
+                               fprintf( stderr,
+                                       "Could not parse LDAP URI(s)=%s (%d)\n",
+                                       ldapuri, rc );
+                               exit( EXIT_FAILURE );
+                       }
+
+                       for ( ludp = &ludlist; *ludp != NULL; ) {
+                               LDAPURLDesc     *lud = *ludp;
+                               char            **tmp;
+
+                               if ( lud->lud_dn != NULL && lud->lud_dn[ 0 ] != '\0' &&
+                                       ( lud->lud_host == NULL || lud->lud_host[0] == '\0' ) )
+                               {
+                                       /* if no host but a DN is provided,
+                                        * use DNS SRV to gather the host list
+                                        * and turn it into a list of URIs
+                                        * using the scheme provided */
+                                       char    *domain = NULL,
+                                               *hostlist = NULL,
+                                               **hosts = NULL;
+                                       int     i,
+                                               len_proto = strlen( lud->lud_scheme );
+
+                                       if ( ldap_dn2domain( lud->lud_dn, &domain )
+                                               || domain == NULL )
+                                       {
+                                               fprintf( stderr,
+                                                       "DNS SRV: Could not turn "
+                                                       "DN=\"%s\" into a domain\n",
+                                                       lud->lud_dn );
+                                               goto dnssrv_free;
+                                       }
+                                       
+                                       rc = ldap_domain2hostlist( domain, &hostlist );
+                                       if ( rc ) {
+                                               fprintf( stderr,
+                                                       "DNS SRV: Could not turn "
+                                                       "domain=%s into a hostlist\n",
+                                                       domain );
+                                               goto dnssrv_free;
+                                       }
+
+                                       hosts = ldap_str2charray( hostlist, " " );
+                                       if ( hosts == NULL ) {
+                                               fprintf( stderr,
+                                                       "DNS SRV: Could not parse "
+                                                       "hostlist=\"%s\"\n",
+                                                       hostlist );
+                                               goto dnssrv_free;
+                                       }
+
+                                       for ( i = 0; hosts[ i ] != NULL; i++ )
+                                               /* count'em */ ;
+
+                                       tmp = (char **)ber_memrealloc( urls, sizeof( char * ) * ( nurls + i + 1 ) );
+                                       if ( tmp == NULL ) {
+                                               fprintf( stderr,
+                                                       "DNS SRV: out of memory?\n" );
+                                               goto dnssrv_free;
+                                       }
+                                       urls = tmp;
+                                       urls[ nurls ] = NULL;
+
+                                       for ( i = 0; hosts[ i ] != NULL; i++ ) {
+                                               size_t  len = len_proto
+                                                       + STRLENOF( "://" )
+                                                       + strlen( hosts[ i ] )
+                                                       + 1;
+
+                                               urls[ nurls + i + 1 ] = NULL;
+                                               urls[ nurls + i ] = (char *)malloc( sizeof( char ) * len );
+                                               if ( urls[ nurls + i ] == NULL ) {
+                                                       fprintf( stderr,
+                                                               "DNS SRV: out of memory?\n" );
+                                                       goto dnssrv_free;
+                                               }
+
+                                               snprintf( urls[ nurls + i ], len, "%s://%s",
+                                                       lud->lud_scheme, hosts[ i ] );
+                                       }
+                                       nurls += i;
+
+dnssrv_free:;
+                                       ber_memvfree( (void **)hosts );
+                                       ber_memfree( hostlist );
+                                       ber_memfree( domain );
+
+                               } else {
+                                       tmp = (char **)ber_memrealloc( urls, sizeof( char * ) * ( nurls + 2 ) );
+                                       if ( tmp == NULL ) {
+                                               fprintf( stderr,
+                                                       "DNS SRV: out of memory?\n" );
+                                               break;
+                                       }
+                                       urls = tmp;
+                                       urls[ nurls + 1 ] = NULL;
+
+                                       urls[ nurls ] = ldap_url_desc2str( lud );
+                                       if ( urls[ nurls ] == NULL ) {
+                                               fprintf( stderr,
+                                                       "DNS SRV: out of memory?\n" );
+                                               break;
+                                       }
+                                       nurls++;
+                               }
+
+                               *ludp = lud->lud_next;
+
+                               lud->lud_next = NULL;
+                               ldap_free_urldesc( lud );
+                       }
+
+                       if ( ludlist != NULL ) {
+                               ldap_free_urllist( ludlist );
+                               exit( EXIT_FAILURE );
+
+                       } else if ( urls == NULL ) {
+                               exit( EXIT_FAILURE );
+                       }
+
+                       ldap_memfree( ldapuri );
+                       ldapuri = ldap_charray2str( urls, " " );
+                       ber_memvfree( (void **)urls );
                }
 
                if ( verbose ) {
@@ -970,6 +1404,16 @@ tool_conn_setup( int dont, void (*private_setup)( LDAP * ) )
                        exit( EXIT_FAILURE );
                }
 
+#ifdef HAVE_CYRUS_SASL
+               /* canon */
+               if( ldap_set_option( ld, LDAP_OPT_X_SASL_NOCANON,
+                       nocanon ? LDAP_OPT_ON : LDAP_OPT_OFF ) != LDAP_OPT_SUCCESS )
+               {
+                       fprintf( stderr, "Could not set LDAP_OPT_X_SASL_NOCANON %s\n",
+                               nocanon ? "on" : "off" );
+                       exit( EXIT_FAILURE );
+               }
+#endif
                if( ldap_set_option( ld, LDAP_OPT_PROTOCOL_VERSION, &protocol )
                        != LDAP_OPT_SUCCESS )
                {
@@ -981,12 +1425,25 @@ tool_conn_setup( int dont, void (*private_setup)( LDAP * ) )
                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 );
+                               char *msg=NULL;
+                               ldap_get_option( ld, LDAP_OPT_DIAGNOSTIC_MESSAGE, (void*)&msg);
+                               tool_perror( "ldap_start_tls", rc, NULL, NULL, msg, NULL );
+                               ldap_memfree(msg);
                                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 );
+                       }
+               }
        }
 
        return ld;
@@ -997,31 +1454,92 @@ void
 tool_bind( LDAP *ld )
 {
        LDAPControl     **sctrlsp = NULL;
-       LDAPControl     *sctrls[2];
+       LDAPControl     *sctrls[4];
+       LDAPControl     sctrl[3];
        int             nsctrls = 0;
 
+       int rc, msgid;
+       LDAPMessage *result = NULL;
+
+       int err;
+       char *matched = NULL;
+       char *info = NULL;
+       char **refs = NULL;
+       LDAPControl **ctrls = NULL;
+       char msgbuf[256];
+
+       msgbuf[0] = 0;
+
 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
-       LDAPControl c;
        if ( ppolicy ) {
+               LDAPControl c;
                c.ldctl_oid = LDAP_CONTROL_PASSWORDPOLICYREQUEST;
                c.ldctl_value.bv_val = NULL;
                c.ldctl_value.bv_len = 0;
                c.ldctl_iscritical = 0;
-               sctrls[nsctrls] = &c;
+               sctrl[nsctrls] = c;
+               sctrls[nsctrls] = &sctrl[nsctrls];
                sctrls[++nsctrls] = NULL;
        }
 #endif
 
+       if ( bauthzid ) {
+               LDAPControl c;
+
+               c.ldctl_oid = LDAP_CONTROL_AUTHZID_REQUEST;
+               c.ldctl_iscritical = bauthzid > 1;
+               BER_BVZERO( &c.ldctl_value );
+
+               sctrl[nsctrls] = c;
+               sctrls[nsctrls] = &sctrl[nsctrls];
+               sctrls[++nsctrls] = NULL;
+       }
+
+#ifdef LDAP_CONTROL_X_SESSION_TRACKING
+       if ( sessionTracking ) {
+               LDAPControl c;
+
+               if ( BER_BVISNULL( &stValue) && st_value( ld, &stValue ) ) {
+                       exit( EXIT_FAILURE );
+               }
+
+               c.ldctl_oid = LDAP_CONTROL_X_SESSION_TRACKING;
+               c.ldctl_iscritical = 0;
+               c.ldctl_value = stValue;
+
+               sctrl[nsctrls] = c;
+               sctrls[nsctrls] = &sctrl[nsctrls];
+               sctrls[++nsctrls] = NULL;
+       }
+#endif /* LDAP_CONTROL_X_SESSION_TRACKING */
+
        if ( nsctrls ) {
                sctrlsp = sctrls;
        }
 
-       assert( nsctrls < sizeof(sctrls)/sizeof(sctrls[0]) );
+       assert( nsctrls < (int) (sizeof(sctrls)/sizeof(sctrls[0])) );
+
+       if ( pw_file || want_bindpw ) {
+               assert( passwd.bv_val == NULL && passwd.bv_len == 0 );
+
+               if ( pw_file ) {
+                       if ( lutil_get_filed_password( pw_file, &passwd ) ) {
+                               exit( EXIT_FAILURE );
+                       }
+
+               } else {
+                       char *pw = getpassphrase( _("Enter LDAP Password: ") );
+                       if ( pw ) {
+                               passwd.bv_val = ber_strdup( pw );
+                               passwd.bv_len = strlen( passwd.bv_val );
+                       }
+               }
+       }
 
        if ( authmethod == LDAP_AUTH_SASL ) {
 #ifdef HAVE_CYRUS_SASL
                void *defaults;
-               int rc;
+               const char *rmech = NULL;
 
                if( sasl_secprops != NULL ) {
                        rc = ldap_set_option( ld, LDAP_OPT_X_SASL_SECPROPS,
@@ -1042,14 +1560,33 @@ tool_bind( LDAP *ld )
                        passwd.bv_val,
                        sasl_authz_id );
 
-               rc = ldap_sasl_interactive_bind_s( ld, binddn, sasl_mech,
-                       sctrlsp,
-                       NULL, sasl_flags, lutil_sasl_interact, defaults );
+               do {
+                       rc = ldap_sasl_interactive_bind( ld, binddn, sasl_mech,
+                               sctrlsp, NULL, sasl_flags, lutil_sasl_interact, defaults,
+                               result, &rmech, &msgid );
+
+                       if ( rc != LDAP_SASL_BIND_IN_PROGRESS )
+                               break;
+
+                       ldap_msgfree( result );
+
+                       if ( ldap_result( ld, msgid, LDAP_MSG_ALL, NULL, &result ) == -1 || !result ) {
+                               ldap_get_option( ld, LDAP_OPT_RESULT_CODE, (void*)&err );
+                               ldap_get_option( ld, LDAP_OPT_DIAGNOSTIC_MESSAGE, (void*)&info );
+                               tool_perror( "ldap_sasl_interactive_bind",
+                                       err, NULL, NULL, info, NULL );
+                               ldap_memfree( info );
+                               exit( err );
+                       }
+               } while ( rc == LDAP_SASL_BIND_IN_PROGRESS );
 
                lutil_sasl_freedefs( defaults );
-               if( rc != LDAP_SUCCESS ) {
-                       tool_perror( "ldap_sasl_interactive_bind_s",
-                               rc, NULL, NULL, NULL, NULL );
+
+               if ( rc != LDAP_SUCCESS ) {
+                       ldap_get_option( ld, LDAP_OPT_DIAGNOSTIC_MESSAGE, (void*)&info );
+                       tool_perror( "ldap_sasl_interactive_bind",
+                               rc, NULL, NULL, info, NULL );
+                       ldap_memfree( info );
                        exit( rc );
                }
 #else
@@ -1057,98 +1594,95 @@ tool_bind( LDAP *ld )
                exit( LDAP_NOT_SUPPORTED );
 #endif
        } else {
-               int msgid, err, rc;
-               LDAPMessage *result;
-               LDAPControl **ctrls;
-               char msgbuf[256];
-               char *matched = NULL;
-               char *info = NULL;
-               char **refs = NULL;
-
-               msgbuf[0] = 0;
-
-#ifdef LDAP_API_FEATURE_X_OPENLDAP_V2_KBIND
-               if ( authmethod == LDAP_AUTH_KRBV4 || authmethod == LDAP_AUTH_KRBV41 ) {
-                       msgid = ldap_bind( ld, binddn, passwd.bv_val, authmethod );
-                       if ( msgid == -1 ) {
-                               tool_perror( "ldap_bind", -1, NULL, NULL, NULL, NULL );
-                               exit( LDAP_LOCAL_ERROR );
-                       }
-               } else
-#endif
-               {
-                       /* 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 );
-                       }
+               /* 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, LDAP_MSG_ALL, NULL, &result ) == -1 ) {
+               rc = ldap_result( ld, msgid, LDAP_MSG_ALL, NULL, &result );
+               if ( rc == -1 ) {
                        tool_perror( "ldap_result", -1, NULL, NULL, NULL, NULL );
                        exit( LDAP_LOCAL_ERROR );
                }
 
-               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 );
+               if ( rc == 0 ) {
+                       tool_perror( "ldap_result", LDAP_TIMEOUT, NULL, NULL, NULL, NULL );
                        exit( LDAP_LOCAL_ERROR );
                }
+       }
+
+       rc = ldap_parse_result( ld, result, &err, &matched, &info, &refs,
+               &ctrls, 1 );
+       if ( rc != LDAP_SUCCESS ) {
+               tool_perror( "ldap_bind parse result", rc, NULL, matched, info, refs );
+               exit( LDAP_LOCAL_ERROR );
+       }
 
 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
-               if ( ctrls && ppolicy ) {
-                       LDAPControl *ctrl;
-                       int expire, grace, len = 0;
-                       LDAPPasswordPolicyError pErr = -1;
-                       
-                       ctrl = ldap_find_control( LDAP_CONTROL_PASSWORDPOLICYRESPONSE,
-                               ctrls );
-
-                       if ( ctrl && ldap_parse_passwordpolicy_control( ld, ctrl,
-                               &expire, &grace, &pErr ) == LDAP_SUCCESS )
-                       {
-                               if ( pErr != PP_noError ){
-                                       msgbuf[0] = ';';
-                                       msgbuf[1] = ' ';
-                                       strcpy( msgbuf+2, ldap_passwordpolicy_err2txt( pErr ));
-                                       len = strlen( msgbuf );
-                               }
-                               if ( expire >= 0 ) {
-                                       sprintf( msgbuf+len,
-                                               " (Password expires in %d seconds)",
-                                               expire );
-                               } else if ( grace >= 0 ) {
-                                       sprintf( msgbuf+len,
-                                               " (Password expired, %d grace logins remain)",
-                                               grace );
-                               }
+       if ( ctrls && ppolicy ) {
+               LDAPControl *ctrl;
+               int expire, grace, len = 0;
+               LDAPPasswordPolicyError pErr = -1;
+               
+               ctrl = ldap_control_find( LDAP_CONTROL_PASSWORDPOLICYRESPONSE,
+                       ctrls, NULL );
+
+               if ( ctrl && ldap_parse_passwordpolicy_control( ld, ctrl,
+                       &expire, &grace, &pErr ) == LDAP_SUCCESS )
+               {
+                       if ( pErr != PP_noError ){
+                               msgbuf[0] = ';';
+                               msgbuf[1] = ' ';
+                               strcpy( msgbuf+2, ldap_passwordpolicy_err2txt( pErr ));
+                               len = strlen( msgbuf );
+                       }
+                       if ( expire >= 0 ) {
+                               sprintf( msgbuf+len,
+                                       " (Password expires in %d seconds)",
+                                       expire );
+                       } else if ( grace >= 0 ) {
+                               sprintf( msgbuf+len,
+                                       " (Password expired, %d grace logins remain)",
+                                       grace );
                        }
                }
+       }
 #endif
 
-               if ( ctrls ) {
-                       ldap_controls_free( ctrls );
+       if ( ctrls && bauthzid ) {
+               LDAPControl *ctrl;
+               
+               ctrl = ldap_control_find( LDAP_CONTROL_AUTHZID_RESPONSE,
+                       ctrls, NULL );
+               if ( ctrl ) {
+                       LDAPControl *ctmp[2];
+                       ctmp[0] = ctrl;
+                       ctmp[1] = NULL;
+                       tool_print_ctrls( ld, ctmp );
                }
+       }
 
-               if ( err != LDAP_SUCCESS
-                       || msgbuf[0]
-                       || ( matched && matched[ 0 ] )
-                       || ( info && info[ 0 ] )
-                       || refs )
-               {
-                       tool_perror( "ldap_bind", err, msgbuf, matched, info, refs );
+       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( matched ) ber_memfree( matched );
+               if( info ) ber_memfree( info );
+               if( refs ) ber_memvfree( (void **)refs );
 
-                       if ( err != LDAP_SUCCESS ) exit( err );
-               }
+               if ( err != LDAP_SUCCESS ) exit( err );
        }
 }
 
@@ -1170,7 +1704,7 @@ void
 tool_server_controls( LDAP *ld, LDAPControl *extra_c, int count )
 {
        int i = 0, j, crit = 0, err;
-       LDAPControl c[10], **ctrls;
+       LDAPControl c[16], **ctrls;
 
        if ( ! ( assertctl
                || authzid
@@ -1180,46 +1714,42 @@ tool_server_controls( LDAP *ld, LDAPControl *extra_c, int count )
                || manageDIT
                || manageDSAit
                || noop
+#ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
+               || ppolicy
+#endif
                || preread
                || postread
 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
                || chaining
 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
-               || count ) )
+#ifdef LDAP_CONTROL_X_SESSION_TRACKING
+               || sessionTracking
+#endif /* LDAP_CONTROL_X_SESSION_TRACKING */
+               || count
+               || unknown_ctrls_num ) )
        {
                return;
        }
 
-       ctrls = (LDAPControl**) malloc(sizeof(c) + (count+1)*sizeof(LDAPControl*));
+       ctrls = (LDAPControl**) malloc(sizeof(c) + (count + unknown_ctrls_num + 1)*sizeof(LDAPControl*));
        if ( ctrls == NULL ) {
                fprintf( stderr, "No memory\n" );
                exit( EXIT_FAILURE );
        }
 
        if ( assertctl ) {
-               BerElementBuffer berbuf;
-               BerElement *ber = (BerElement *)&berbuf;
-               
-               if( assertion == NULL || *assertion == '\0' ) {
-                       fprintf( stderr, "Assertion=<empty>\n" );
-                       exit( EXIT_FAILURE );
-               }
-
-               ber_init2( ber, NULL, LBER_USE_DER );
-
-               err = ldap_pvt_put_filter( ber, assertion );
-               if( err < 0 ) {
-                       fprintf( stderr, "assertion encode failed (%d)\n", err );
-                       exit( EXIT_FAILURE );
-               }
-
-               err = ber_flatten2( ber, &c[i].ldctl_value, 0 );
-               if( err < 0 ) {
-                       fprintf( stderr, "assertion flatten failed (%d)\n", err );
-                       exit( EXIT_FAILURE );
+               if ( BER_BVISNULL( &assertionvalue ) ) {
+                       err = ldap_create_assertion_control_value( ld,
+                               assertion, &assertionvalue );
+                       if ( err ) {
+                               fprintf( stderr,
+                                       "Unable to create assertion value "
+                                       "\"%s\" (%d)\n", assertion, err );
+                       }
                }
 
                c[i].ldctl_oid = LDAP_CONTROL_ASSERT;
+               c[i].ldctl_value = assertionvalue;
                c[i].ldctl_iscritical = assertctl > 1;
                ctrls[i] = &c[i];
                i++;
@@ -1229,7 +1759,7 @@ tool_server_controls( LDAP *ld, LDAPControl *extra_c, int count )
                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;
+               c[i].ldctl_iscritical = authzcrit;
                ctrls[i] = &c[i];
                i++;
        }
@@ -1243,7 +1773,7 @@ tool_server_controls( LDAP *ld, LDAPControl *extra_c, int count )
                
                ber_init2( ber, NULL, LBER_USE_DER );
 
-               if ( ber_printf( ber, "s", proxydn ) == LBER_ERROR ) {
+               if ( ber_printf( ber, "s", proxydn ) == -1 ) {
                        exit( EXIT_FAILURE );
                }
 
@@ -1252,7 +1782,7 @@ tool_server_controls( LDAP *ld, LDAPControl *extra_c, int count )
                }
 
                c[i].ldctl_oid = LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ;
-               c[i].ldctl_iscritical = 1;
+               c[i].ldctl_iscritical = authzcrit;
                ctrls[i] = &c[i];
                i++;
        }
@@ -1282,9 +1812,19 @@ tool_server_controls( LDAP *ld, LDAPControl *extra_c, int count )
                i++;
        }
 
+#ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
+       if ( ppolicy ) {
+               c[i].ldctl_oid = LDAP_CONTROL_PASSWORDPOLICYREQUEST;
+               BER_BVZERO( &c[i].ldctl_value );
+               c[i].ldctl_iscritical = 0;
+               ctrls[i] = &c[i];
+               i++;
+       }
+#endif
+
        if ( preread ) {
-               char berbuf[LBER_ELEMENT_SIZEOF];
-               BerElement *ber = (BerElement *)berbuf;
+               BerElementBuffer berbuf;
+               BerElement *ber = (BerElement *)&berbuf;
                char **attrs = NULL;
 
                if( preread_attrs ) {
@@ -1313,8 +1853,8 @@ tool_server_controls( LDAP *ld, LDAPControl *extra_c, int count )
        }
 
        if ( postread ) {
-               char berbuf[LBER_ELEMENT_SIZEOF];
-               BerElement *ber = (BerElement *)berbuf;
+               BerElementBuffer berbuf;
+               BerElement *ber = (BerElement *)&berbuf;
                char **attrs = NULL;
 
                if( postread_attrs ) {
@@ -1388,9 +1928,27 @@ tool_server_controls( LDAP *ld, LDAPControl *extra_c, int count )
        }
 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
 
+#ifdef LDAP_CONTROL_X_SESSION_TRACKING
+       if ( sessionTracking ) {
+               if ( BER_BVISNULL( &stValue ) && st_value( ld, &stValue ) ) {
+                       exit( EXIT_FAILURE );
+               }
+
+               c[i].ldctl_oid = LDAP_CONTROL_X_SESSION_TRACKING;
+               c[i].ldctl_iscritical = 0;
+               c[i].ldctl_value = stValue;
+
+               ctrls[i] = &c[i];
+               i++;
+       }
+#endif /* LDAP_CONTROL_X_SESSION_TRACKING */
+
        while ( count-- ) {
                ctrls[i++] = extra_c++;
        }
+       for ( count = 0; count < unknown_ctrls_num; count++ ) {
+               ctrls[i++] = &unknown_ctrls[count];
+       }
        ctrls[i] = NULL;
 
        err = ldap_set_option( ld, LDAP_OPT_SERVER_CONTROLS, ctrls );
@@ -1415,17 +1973,21 @@ tool_check_abandon( LDAP *ld, int msgid )
        int     rc;
 
        switch ( gotintr ) {
-       case LDAP_REQ_EXTENDED:
+       case Intr_Cancel:
                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:
+       case Intr_Abandon:
                rc = ldap_abandon_ext( ld, msgid, NULL, NULL );
                fprintf( stderr, "got interrupt, abandon got %d: %s\n",
                                rc, ldap_err2string( rc ) );
                return -1;
+
+       case Intr_Ignore:
+               /* just unbind, ignoring the request */
+               return -1;
        }
 
        return 0;
@@ -1454,6 +2016,7 @@ print_prepostread( LDAP *ld, LDAPControl *ctrl, struct berval *what)
                while ( ber_scanf( ber, "{m" /*}*/, &bv ) != LBER_ERROR ) {
                        int             i;
                        BerVarray       vals = NULL;
+                       char            *str = NULL;
 
                        if ( ber_scanf( ber, "[W]", &vals ) == LBER_ERROR ||
                                vals == NULL )
@@ -1461,14 +2024,25 @@ print_prepostread( LDAP *ld, LDAPControl *ctrl, struct berval *what)
                                /* error? */
                                return 1;
                        }
+
+                       if ( ldif ) {
+                               char *ptr;
+
+                               str = malloc( bv.bv_len + STRLENOF(": ") + 1 );
+
+                               ptr = str;
+                               ptr = lutil_strncopy( ptr, bv.bv_val, bv.bv_len );
+                               ptr = lutil_strcopy( ptr, ": " );
+                       }
                
                        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 );
+                                       ldif ? str : bv.bv_val, vals[ i ].bv_val, vals[ i ].bv_len );
                        }
 
                        ber_bvarray_free( vals );
+                       if ( str ) free( str );
                }
        }
 
@@ -1548,11 +2122,214 @@ print_paged_results( LDAP *ld, LDAPControl *ctrl )
                }
 
                tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
-                       "pagedresults", buf, ptr - buf );
+                       ldif ? "pagedresults: " : "pagedresults",
+                       buf, ptr - buf );
+       }
+
+       return 0;
+}
+
+static int
+print_sss( LDAP *ld, LDAPControl *ctrl )
+{
+       int rc;
+       ber_int_t err;
+       char *attr;
+
+       rc = ldap_parse_sortresponse_control( ld, ctrl, &err, &attr );
+       if ( rc == LDAP_SUCCESS ) {
+               char buf[ BUFSIZ ];
+               rc = snprintf( buf, sizeof(buf), "(%d) %s%s%s",
+                       err, ldap_err2string(err), attr ? " " : "", attr ? attr : "" );
+
+               tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
+                       ldif ? "sortResult: " : "sortResult", buf, rc );
+       }
+
+       return rc;
+}
+
+static int
+print_vlv( LDAP *ld, LDAPControl *ctrl )
+{
+       int rc;
+       ber_int_t err;
+       struct berval bv;
+
+       rc = ldap_parse_vlvresponse_control( ld, ctrl, &vlvPos, &vlvCount,
+               &vlvContext, &err );
+       if ( rc == LDAP_SUCCESS ) {
+               char buf[ BUFSIZ ];
+
+               if ( vlvContext && vlvContext->bv_len > 0 ) {
+                       bv.bv_len = LUTIL_BASE64_ENCODE_LEN(
+                               vlvContext->bv_len ) + 1;
+                       bv.bv_val = ber_memalloc( bv.bv_len + 1 );
+
+                       bv.bv_len = lutil_b64_ntop(
+                               (unsigned char *) vlvContext->bv_val,
+                               vlvContext->bv_len,
+                               bv.bv_val, bv.bv_len );
+               } else {
+                       bv.bv_val = "";
+                       bv.bv_len = 0;
+               }
+
+               rc = snprintf( buf, sizeof(buf), "pos=%d count=%d context=%s (%d) %s",
+                       vlvPos, vlvCount, bv.bv_val,
+                       err, ldap_err2string(err));
+
+               if ( bv.bv_len )
+                       ber_memfree( bv.bv_val );
+
+               tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
+                       ldif ? "vlvResult" : "vlvResult", buf, rc );
+       }
+
+       return rc;
+}
+
+#ifdef LDAP_CONTROL_X_DEREF
+static int
+print_deref( LDAP *ld, LDAPControl *ctrl )
+{
+       LDAPDerefRes    *drhead = NULL, *dr;
+       int             rc;
+
+       rc = ldap_parse_derefresponse_control( ld, ctrl, &drhead );
+       if ( rc != LDAP_SUCCESS ) {
+               return rc;
+       }
+
+       for ( dr = drhead; dr != NULL; dr = dr->next ) {
+               LDAPDerefVal    *dv;
+               ber_len_t       len;
+               char            *buf, *ptr;
+
+               len = strlen( dr->derefAttr ) + STRLENOF(": ");
+
+               for ( dv = dr->attrVals; dv != NULL; dv = dv->next ) {
+                       if ( dv->vals != NULL ) {
+                               int j;
+                               ber_len_t tlen = strlen(dv->type);
+
+                               for ( j = 0; dv->vals[ j ].bv_val != NULL; j++ ) {
+                                       len += STRLENOF("<:=>;") + tlen + 4*((dv->vals[ j ].bv_len - 1)/3 + 1);
+                               }
+                       }
+               }
+               len += dr->derefVal.bv_len + STRLENOF("\n");
+               buf = ldap_memalloc( len + 1 );
+               if ( buf == NULL ) {
+                       rc = LDAP_NO_MEMORY;
+                       goto done;
+               }
+
+               ptr = buf;
+               ptr = lutil_strcopy( ptr, dr->derefAttr );
+               *ptr++ = ':';
+               *ptr++ = ' ';
+               for ( dv = dr->attrVals; dv != NULL; dv = dv->next ) {
+                       if ( dv->vals != NULL ) {
+                               int j;
+                               for ( j = 0; dv->vals[ j ].bv_val != NULL; j++ ) {
+                                       int k = ldif_is_not_printable( dv->vals[ j ].bv_val, dv->vals[ j ].bv_len );
+
+                                       *ptr++ = '<';
+                                       ptr = lutil_strcopy( ptr, dv->type );
+                                       if ( k ) {
+                                               *ptr++ = ':';
+                                       }
+                                       *ptr++ = '=';
+                                       if ( k ) {
+                                               k = lutil_b64_ntop(
+                                                       (unsigned char *) dv->vals[ j ].bv_val,
+                                                       dv->vals[ j ].bv_len,
+                                                       ptr, buf + len - ptr );
+                                               assert( k >= 0 );
+                                               ptr += k;
+                                               
+                                       } else {
+                                               ptr = lutil_memcopy( ptr, dv->vals[ j ].bv_val, dv->vals[ j ].bv_len );
+                                       }
+                                       *ptr++ = '>';
+                                       *ptr++ = ';';
+                               }
+                       }
+               }
+               ptr = lutil_strncopy( ptr, dr->derefVal.bv_val, dr->derefVal.bv_len );
+               *ptr++ = '\n';
+               *ptr = '\0';
+               assert( ptr <= buf + len );
+
+               tool_write_ldif( LDIF_PUT_COMMENT, NULL, buf, ptr - buf);
+
+               ldap_memfree( buf );
+       }
+
+       rc = LDAP_SUCCESS;
+
+done:;
+       ldap_derefresponse_free( drhead );
+
+       return rc;
+}
+#endif
+
+#ifdef LDAP_CONTROL_X_WHATFAILED
+static int
+print_whatfailed( LDAP *ld, LDAPControl *ctrl )
+{
+       BerElement *ber;
+       ber_tag_t tag;
+       ber_len_t siz;
+       BerVarray bva = NULL;
+
+       /* Create a BerElement from the berval returned in the control. */
+       ber = ber_init( &ctrl->ldctl_value );
+
+       if ( ber == NULL ) {
+               return LDAP_NO_MEMORY;
+       }
+
+       siz = sizeof(struct berval);
+       tag = ber_scanf( ber, "[M]", &bva, &siz, 0 );
+       if ( tag != LBER_ERROR ) {
+               int i;
+
+               tool_write_ldif( LDIF_PUT_COMMENT, " what failed:", NULL, 0 );
+
+               for ( i = 0; bva[i].bv_val != NULL; i++ ) {
+                       tool_write_ldif( LDIF_PUT_COMMENT, NULL, bva[i].bv_val, bva[i].bv_len );
+               }
+
+               ldap_memfree( bva );
+       }
+
+        ber_free( ber, 1 );
+
+
+       return 0;
+}
+#endif
+
+#ifdef LDAP_CONTROL_AUTHZID_RESPONSE
+static int
+print_authzid( LDAP *ld, LDAPControl *ctrl )
+{
+       if ( ctrl->ldctl_value.bv_len ) {
+               tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
+                       ldif ? "authzid: " : "authzid",
+               ctrl->ldctl_value.bv_val, ctrl->ldctl_value.bv_len );
+       } else {
+               tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
+                       ldif ? "authzid: " : "authzid",
+                       "anonymous",  STRLENOF("anonymous") );
        }
 
        return 0;
 }
+#endif
 
 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
 static int
@@ -1578,12 +2355,13 @@ print_ppolicy( LDAP *ld, LDAPControl *ctrl )
 
                if ( pperr != PP_noError ) {
                        ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
-                               "%serror=%s", ptr == buf ? "" : " ",
+                               "%serror=%d (%s)", ptr == buf ? "" : " ",
+                               pperr,
                                ldap_passwordpolicy_err2txt( pperr ) );
                }
 
                tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
-                       "ppolicy", buf, ptr - buf );
+                       ldif ? "ppolicy: " : "ppolicy", buf, ptr - buf );
        }
 
        return rc;
@@ -1604,6 +2382,13 @@ void tool_print_ctrls(
                char *str;
                int j;
 
+               /* FIXME: there might be cases where a control has NULL OID;
+                * this makes little sense, especially when returned by the
+                * server, but libldap happily allows it */
+               if ( ctrls[i]->ldctl_oid == NULL ) {
+                       continue;
+               }
+
                len = ldif ? 2 : 0;
                len += strlen( ctrls[i]->ldctl_oid );
 
@@ -1612,7 +2397,7 @@ void tool_print_ctrls(
                        ? sizeof("true") : sizeof("false");
 
                /* convert to base64 */
-               if ( ctrls[i]->ldctl_value.bv_len ) {
+               if ( !BER_BVISNULL( &ctrls[i]->ldctl_value ) ) {
                        b64.bv_len = LUTIL_BASE64_ENCODE_LEN(
                                ctrls[i]->ldctl_value.bv_len ) + 1;
                        b64.bv_val = ber_memalloc( b64.bv_len + 1 );
@@ -1672,7 +2457,7 @@ tool_write_ldif( int type, char *name, char *value, ber_len_t vallen )
 {
        char    *ldif;
 
-       if (( ldif = ldif_put( type, name, value, vallen )) == NULL ) {
+       if (( ldif = ldif_put_wrap( type, name, value, vallen, ldif_wrap )) == NULL ) {
                return( -1 );
        }