]> git.sur5r.net Git - openldap/blobdiff - clients/tools/ldapsearch.c
Added ldapsearch bad filter pattern check (ITS#4647)
[openldap] / clients / tools / ldapsearch.c
index d1a0bd471a0e9bd1c1c89dce01c8805a835aa5aa..5496fbf1ae0f43547937f19eb0caeb20251caf64 100644 (file)
@@ -1,7 +1,39 @@
+/* ldapsearch -- a tool for searching LDAP directories */
 /* $OpenLDAP$ */
-/*
- * Copyright 1998-2002 The OpenLDAP Foundation, All Rights Reserved.
- * COPYING RESTRICTIONS APPLY, see COPYRIGHT file
+/* This work is part of OpenLDAP Software <http://www.openldap.org/>.
+ *
+ * Copyright 1998-2006 The OpenLDAP Foundation.
+ * Portions Copyright 1998-2003 Kurt D. Zeilenga.
+ * Portions Copyright 1998-2001 Net Boolean Incorporated.
+ * Portions Copyright 2001-2003 IBM Corporation.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted only as authorized by the OpenLDAP
+ * Public License.
+ *
+ * A copy of this license is available in the file LICENSE in the
+ * top-level directory of the distribution or, alternatively, at
+ * <http://www.OpenLDAP.org/license.html>.
+ */
+/* Portions Copyright (c) 1992-1996 Regents of the University of Michigan.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms are permitted
+ * provided that this notice is preserved and that due credit is given
+ * to the University of Michigan at Ann Arbor.  The name of the
+ * University may not be used to endorse or promote products derived
+ * from this software without specific prior written permission.  This
+ * software is provided ``as is'' without express or implied warranty.
+ */
+/* ACKNOWLEDGEMENTS:
+ * This work was originally developed by the University of Michigan
+ * (as part of U-MICH LDAP).  Additional significant contributors
+ * include:
+ *   Jong Hyuk Choi
+ *   Lynn Moss
+ *   Mikhail Sahalaev
+ *   Kurt D. Zeilenga
  */
 
 #include "portable.h"
 #include <ac/stdlib.h>
 
 #include <ac/ctype.h>
-#include <ac/signal.h>
 #include <ac/string.h>
 #include <ac/unistd.h>
 #include <ac/errno.h>
 #include <sys/stat.h>
 
+#include <ac/signal.h>
+
 #ifdef HAVE_FCNTL_H
 #include <fcntl.h>
 #endif
 #include "lutil_ldap.h"
 #include "ldap_defaults.h"
 #include "ldap_log.h"
+#include "ldap_pvt.h"
+
+#include "common.h"
+
+
+static int scope = LDAP_SCOPE_SUBTREE;
+static int deref = -1;
+static int attrsonly;
+static int timelimit = -1;
+static int sizelimit = -1;
 
 static char *def_tmpdir;
 static char *def_urlpre;
 
-static void
-usage( const char *s )
+#if defined(__CYGWIN__) || defined(__MINGW32__)
+/* Turn off commandline globbing, otherwise you cannot search for
+ * attribute '*'
+ */
+int _CRT_glob = 0;
+#endif
+
+void
+usage( void )
 {
-       fprintf( stderr,
-"usage: %s [options] [filter [attributes...]]\nwhere:\n"
-"  filter\tRFC-2254 compliant LDAP search filter\n"
-"  attributes\twhitespace-separated list of attribute descriptions\n"
-"    which may include:\n"
-"      1.1   no attributes\n"
-"      *     all user attributes\n"
-"      +     all operational attributes\n"
-
-"Search options:\n"
-"  -a deref   one of never (default), always, search, or find\n"
-"  -A         retrieve attribute names only (no values)\n"
-"  -b basedn  base dn for search\n"
-"  -E [!]<ctrl>[=<ctrlparam>] search controls (! indicates criticality)\n"
-"             [!]mv=<filter>              (matched values filter)\n"
-"             [!]pr=<size>                (paged results)\n"
+       fprintf( stderr, _("usage: %s [options] [filter [attributes...]]\nwhere:\n"), prog);
+       fprintf( stderr, _("  filter\tRFC-2254 compliant LDAP search filter\n"));
+       fprintf( stderr, _("  attributes\twhitespace-separated list of attribute descriptions\n"));
+       fprintf( stderr, _("    which may include:\n"));
+       fprintf( stderr, _("      1.1   no attributes\n"));
+       fprintf( stderr, _("      *     all user attributes\n"));
+       fprintf( stderr, _("      +     all operational attributes\n"));
+
+
+       fprintf( stderr, _("Search options:\n"));
+       fprintf( stderr, _("  -a deref   one of never (default), always, search, or find\n"));
+       fprintf( stderr, _("  -A         retrieve attribute names only (no values)\n"));
+       fprintf( stderr, _("  -b basedn  base dn for search\n"));
+       fprintf( stderr, _("  -E [!]<ext>[=<extparam>] search extensions (! indicates criticality)\n"));
+#ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
+       fprintf( stderr, _("             [!]domainScope              (domain scope)\n"));
+#endif
+       fprintf( stderr, _("             [!]mv=<filter>              (matched values filter)\n"));
+#ifdef LDAP_CONTROL_PAGEDRESULTS
+       fprintf( stderr, _("             [!]pr=<size>[/prompt|noprompt]   (paged results/prompt)\n"));
+#endif
 #ifdef LDAP_CONTROL_SUBENTRIES
-"             [!]subentries[=true|false]  (subentries)\n"
+       fprintf( stderr, _("             [!]subentries[=true|false]  (subentries)\n"));
 #endif
-"  -F prefix  URL prefix for files (default: %s)\n"
-"  -l limit   time limit (in seconds) for search\n"
-"  -L         print responses in LDIFv1 format\n"
-"  -LL        print responses in LDIF format without comments\n"
-"  -LLL       print responses in LDIF format without comments\n"
-"             and version\n"
-"  -s scope   one of base, one, or sub (search scope)\n"
-"  -S attr    sort the results by attribute `attr'\n"
-"  -t         write binary values to files in temporary directory\n"
-"  -tt        write all values to files in temporary directory\n"
-"  -T path    write files to directory specified by path (default: %s)\n"
-"  -u         include User Friendly entry names in the output\n"
-"  -z limit   size limit (in entries) for search\n"
-
-"Common options:\n"
-"  -d level   set LDAP debugging level to `level'\n"
-"  -D binddn  bind DN\n"
-"  -e [!]<ctrl>[=<ctrlparam>] general controls (! indicates criticality)\n"
-"             [!]authzid=<authzid> (\"dn:<dn>\" or \"u:<user>\")\n"
-"             [!]manageDSAit       (alternate form, see -M)\n"
-"             [!]noop\n"
-"  -f file    read operations from `file'\n"
-"  -h host    LDAP server\n"
-"  -H URI     LDAP Uniform Resource Indentifier(s)\n"
-"  -I         use SASL Interactive mode\n"
-"  -k         use Kerberos authentication\n"
-"  -K         like -k, but do only step 1 of the Kerberos bind\n"
-"  -M         enable Manage DSA IT control (-MM to make critical)\n"
-"  -n         show what would be done but don't actually search\n"
-"  -O props   SASL security properties\n"
-"  -p port    port on LDAP server\n"
-"  -P version procotol version (default: 3)\n"
-"  -Q         use SASL Quiet mode\n"
-"  -R realm   SASL realm\n"
-"  -U authcid SASL authentication identity\n"
-"  -v         run in verbose mode (diagnostics to standard output)\n"
-"  -w passwd  bind passwd (for simple authentication)\n"
-"  -W         prompt for bind passwd\n"
-"  -x         Simple authentication\n"
-"  -X authzid SASL authorization identity (\"dn:<dn>\" or \"u:<user>\")\n"
-"  -y file    Read passwd from file\n"
-"  -Y mech    SASL mechanism\n"
-"  -Z         Start TLS request (-ZZ to require successful response)\n"
-, s, def_urlpre, def_tmpdir );
-
+       fprintf( stderr, _("             [!]sync=ro[/<cookie>]            (LDAP Sync refreshOnly)\n"));
+       fprintf( stderr, _("                     rp[/<cookie>][/<slimit>] (LDAP Sync refreshAndPersist)\n"));
+       fprintf( stderr, _("  -F prefix  URL prefix for files (default: %s)\n"), def_urlpre);
+       fprintf( stderr, _("  -l limit   time limit (in seconds, or \"none\" or \"max\") for search\n"));
+       fprintf( stderr, _("  -L         print responses in LDIFv1 format\n"));
+       fprintf( stderr, _("  -LL        print responses in LDIF format without comments\n"));
+       fprintf( stderr, _("  -LLL       print responses in LDIF format without comments\n"));
+       fprintf( stderr, _("             and version\n"));
+#ifdef LDAP_SCOPE_SUBORDINATE
+       fprintf( stderr, _("  -s scope   one of base, one, sub or children (search scope)\n"));
+#else /* ! LDAP_SCOPE_SUBORDINATE */
+       fprintf( stderr, _("  -s scope   one of base, one, or sub (search scope)\n"));
+#endif /* ! LDAP_SCOPE_SUBORDINATE */
+       fprintf( stderr, _("  -S attr    sort the results by attribute `attr'\n"));
+       fprintf( stderr, _("  -t         write binary values to files in temporary directory\n"));
+       fprintf( stderr, _("  -tt        write all values to files in temporary directory\n"));
+       fprintf( stderr, _("  -T path    write files to directory specified by path (default: %s)\n"), def_tmpdir);
+       fprintf( stderr, _("  -u         include User Friendly entry names in the output\n"));
+       fprintf( stderr, _("  -z limit   size limit (in entries, or \"none\" or \"max\") for search\n"));
+       tool_common_usage();
        exit( EXIT_FAILURE );
 }
 
@@ -154,30 +184,28 @@ static int dosearch LDAP_P((
 
 static char *tmpdir = NULL;
 static char *urlpre = NULL;
-static char *prog = NULL;
-static char    *binddn = NULL;
-static struct berval passwd = { 0, NULL };
 static char    *base = NULL;
-static char    *ldaphost = NULL;
-static char *ldapuri = NULL;
-static int     ldapport = 0;
-#ifdef HAVE_CYRUS_SASL
-static unsigned sasl_flags = LDAP_SASL_AUTOMATIC;
-static char    *sasl_realm = NULL;
-static char    *sasl_authc_id = NULL;
-static char    *sasl_authz_id = NULL;
-static char    *sasl_mech = NULL;
-static char    *sasl_secprops = NULL;
-#endif
-static int     use_tls = 0;
 static char    *sortattr = NULL;
-static int     verbose, not, includeufn, vals2tmp, ldif;
+static int  includeufn, vals2tmp = 0, ldif = 0;
+
+static int subentries = 0, valuesReturnFilter = 0;
+static char    *vrFilter = NULL;
+
+#ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
+static int domainScope = 0;
+#endif
+
+static int ldapsync = 0;
+static struct berval sync_cookie = { 0, NULL };
+static int sync_slimit = -1;
 
+#ifdef LDAP_CONTROL_PAGEDRESULTS
 static int pagedResults = 0;
+static int pagePrompt = 1;
 static ber_int_t pageSize = 0;
 static ber_int_t entriesLeft = 0;
 static ber_int_t morePagedResults = 1;
-static struct berval cookie = { 0, NULL };
+static struct berval page_cookie = { 0, NULL };
 static int npagedresponses;
 static int npagedentries;
 static int npagedreferences;
@@ -188,6 +216,7 @@ static int parse_page_control(
        LDAP *ld,
        LDAPMessage *result,
        struct berval *cookie );
+#endif
 
 static void
 urlize(char *url)
@@ -202,93 +231,42 @@ urlize(char *url)
        }
 }
 
-int
-main( int argc, char **argv )
-{
-       char            *infile, *filtpattern, **attrs = NULL, line[BUFSIZ];
-       FILE            *fp = NULL;
-       int                     rc, i, first, scope, deref, attrsonly, manageDSAit, noop, crit;
-       int                     referrals, timelimit, sizelimit, debug;
-       int             authmethod, version, want_bindpw;
-       LDAP            *ld = NULL;
-       BerElement      *ber = NULL;
-       char    *control = NULL, *cvalue;
-       int             subentries, valuesReturnFilter;
-       struct berval   *sebvalp = NULL, *vrbvalp = NULL;
-       char    *vrFilter  = NULL;
-       char    *pw_file = NULL;
-       char    *authzid = NULL;
-       struct berval   *prbvalp = NULL;
-
-       infile = NULL;
-       debug = verbose = not = vals2tmp = referrals =
-               subentries = valuesReturnFilter =
-               attrsonly = manageDSAit = noop = ldif = want_bindpw = 0;
-
-       npagedresponses = npagedentries = npagedreferences =
-               npagedextended = npagedpartial = 0;
-
-       prog = lutil_progname( "ldapsearch", argc, argv );
-
-       lutil_log_initialize(argc, argv);
 
-       deref = sizelimit = timelimit = version = -1;
+const char options[] = "a:Ab:cE:F:l:Ls:S:tT:uz:"
+       "Cd:D:e:f:h:H:IkKMnO:p:P:QR:U:vVw:WxX:y:Y:Z";
 
-       scope = LDAP_SCOPE_SUBTREE;
-       authmethod = -1;
-
-       if((def_tmpdir = getenv("TMPDIR")) == NULL &&
-          (def_tmpdir = getenv("TMP")) == NULL &&
-          (def_tmpdir = getenv("TEMP")) == NULL )
-       {
-               def_tmpdir = LDAP_TMPDIR;
-       }
-
-       if ( !*def_tmpdir )
-               def_tmpdir = LDAP_TMPDIR;
-
-       def_urlpre = malloc( sizeof("file:////") + strlen(def_tmpdir) );
-
-       if( def_urlpre == NULL ) {
-               perror( "malloc" );
-               return EXIT_FAILURE;
-       }
-
-       sprintf( def_urlpre, "file:///%s/",
-               def_tmpdir[0] == *LDAP_DIRSEP ? &def_tmpdir[1] : def_tmpdir );
-
-       urlize( def_urlpre );
-
-       while (( i = getopt( argc, argv, "Aa:b:E:F:f:Ll:S:s:T:tuz:"
-               "Cd:e:D:h:H:IkKMnO:p:P:QR:U:vw:WxX:y:Y:Z")) != EOF )
-       {
-       switch( i ) {
-       /* Search Options */
+int
+handle_private_option( int i )
+{
+       int crit, ival;
+       char *control, *cvalue, *next;
+       switch ( i ) {
        case 'a':       /* set alias deref option */
                if ( strcasecmp( optarg, "never" ) == 0 ) {
-               deref = LDAP_DEREF_NEVER;
+                       deref = LDAP_DEREF_NEVER;
                } else if ( strncasecmp( optarg, "search", sizeof("search")-1 ) == 0 ) {
-               deref = LDAP_DEREF_SEARCHING;
+                       deref = LDAP_DEREF_SEARCHING;
                } else if ( strncasecmp( optarg, "find", sizeof("find")-1 ) == 0 ) {
-               deref = LDAP_DEREF_FINDING;
+                       deref = LDAP_DEREF_FINDING;
                } else if ( strcasecmp( optarg, "always" ) == 0 ) {
-               deref = LDAP_DEREF_ALWAYS;
+                       deref = LDAP_DEREF_ALWAYS;
                } else {
-               fprintf( stderr, "alias deref should be never, search, find, or always\n" );
-               usage(prog);
+                       fprintf( stderr,
+                               _("alias deref should be never, search, find, or always\n") );
+                       usage();
                }
                break;
        case 'A':       /* retrieve attribute names only -- no values */
                ++attrsonly;
                break;
        case 'b': /* search base */
-               base = strdup( optarg );
+               base = ber_strdup( optarg );
                break;
-       case 'E': /* search controls */
-               if( version == LDAP_VERSION2 ) {
-                       fprintf( stderr, "%s: -E incompatible with LDAPv%d\n",
-                               prog, version );
-                       return EXIT_FAILURE;
+       case 'E': /* search extensions */
+               if( protocol == LDAP_VERSION2 ) {
+                       fprintf( stderr, _("%s: -E incompatible with LDAPv%d\n"),
+                               prog, protocol );
+                       exit( EXIT_FAILURE );
                }
 
                /* should be extended to support comma separated list of
@@ -302,7 +280,7 @@ main( int argc, char **argv )
                        optarg++;
                }
 
-               control = strdup( optarg );
+               control = ber_strdup( optarg );
                if ( (cvalue = strchr( control, '=' )) != NULL ) {
                        *cvalue++ = '\0';
                }
@@ -310,42 +288,85 @@ main( int argc, char **argv )
                if ( strcasecmp( control, "mv" ) == 0 ) {
                        /* ValuesReturnFilter control */
                        if( valuesReturnFilter ) {
-                               fprintf( stderr, "ValuesReturnFilter previously specified\n");
-                               return EXIT_FAILURE;
+                               fprintf( stderr,
+                                       _("ValuesReturnFilter previously specified\n"));
+                               exit( EXIT_FAILURE );
                        }
                        valuesReturnFilter= 1 + crit;
 
                        if ( cvalue == NULL ) {
                                fprintf( stderr,
-                                       "missing filter in ValuesReturnFilter control\n");
-                               return EXIT_FAILURE;
+                                       _("missing filter in ValuesReturnFilter control\n"));
+                               exit( EXIT_FAILURE );
                        }
 
                        vrFilter = cvalue;
-                       version = LDAP_VERSION3;
+                       protocol = LDAP_VERSION3;
 
+#ifdef LDAP_CONTROL_PAGEDRESULTS
                } else if ( strcasecmp( control, "pr" ) == 0 ) {
                        int num, tmp;
                        /* PagedResults control */
                        if ( pagedResults != 0 ) {
-                               fprintf( stderr, "PagedResultsControl previously specified\n" );
-                               return EXIT_FAILURE;
+                               fprintf( stderr,
+                                       _("PagedResultsControl previously specified\n") );
+                               exit( EXIT_FAILURE );
                        }
-                       
-                       num = sscanf( cvalue, "%d", &tmp );
-                       if ( num != 1 ) {
-                               fprintf( stderr, "Invalid value for PagedResultsControl, %s.\n", cvalue);
-                               return EXIT_FAILURE;
 
+                       if( cvalue != NULL ) {
+                               char *promptp;
+
+                               promptp = strchr( cvalue, '/' );
+                               if ( promptp != NULL ) {
+                                       *promptp++ = '\0';
+                                       if ( strcasecmp( promptp, "prompt" ) == 0 ) {
+                                               pagePrompt = 1;
+                                       } else if ( strcasecmp( promptp, "noprompt" ) == 0) {
+                                               pagePrompt = 0;
+                                       } else {
+                                               fprintf( stderr,
+                                                       _("Invalid value for PagedResultsControl,"
+                                                       " %s/%s.\n"), cvalue, promptp );
+                                               exit( EXIT_FAILURE );
+                                       }
+                               }
+                               num = sscanf( cvalue, "%d", &tmp );
+                               if ( num != 1 ) {
+                                       fprintf( stderr,
+                                               _("Invalid value for PagedResultsControl, %s.\n"),
+                                               cvalue );
+                                       exit( EXIT_FAILURE );
+                               }
+                       } else {
+                               fprintf(stderr, _("Invalid value for PagedResultsControl.\n"));
+                               exit( EXIT_FAILURE );
                        }
                        pageSize = (ber_int_t) tmp;
                        pagedResults = 1 + crit;
 
+#endif
+#ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
+               } else if ( strcasecmp( control, "domainScope" ) == 0 ) {
+                       if( domainScope ) {
+                               fprintf( stderr,
+                                       _("domainScope control previously specified\n"));
+                               exit( EXIT_FAILURE );
+                       }
+                       if( cvalue != NULL ) {
+                               fprintf( stderr,
+                                _("domainScope: no control value expected\n") );
+                               usage();
+                       }
+
+                       domainScope = 1 + crit;
+#endif
+
 #ifdef LDAP_CONTROL_SUBENTRIES
                } else if ( strcasecmp( control, "subentries" ) == 0 ) {
                        if( subentries ) {
-                               fprintf( stderr, "subentries control previously specified\n");
-                               return EXIT_FAILURE;
+                               fprintf( stderr,
+                                       _("subentries control previously specified\n"));
+                               exit( EXIT_FAILURE );
                        }
                        if( cvalue == NULL || strcasecmp( cvalue, "true") == 0 ) {
                                subentries = 2;
@@ -353,59 +374,117 @@ main( int argc, char **argv )
                                subentries = 1;
                        } else {
                                fprintf( stderr,
-                                       "subentries control value \"%s\" invalid\n");
-                               return EXIT_FAILURE;
+                                       _("subentries control value \"%s\" invalid\n"),
+                                       cvalue );
+                               exit( EXIT_FAILURE );
                        }
                        if( crit ) subentries *= -1;
 #endif
 
-               } else {
-                       fprintf( stderr, "Invalid control name: %s\n", control );
-                       usage(prog);
-                       return EXIT_FAILURE;
-               }
-               break;
+               } else if ( strcasecmp( control, "sync" ) == 0 ) {
+                       char *cookiep;
+                       char *slimitp;
+                       if ( ldapsync ) {
+                               fprintf( stderr, _("sync control previously specified\n") );
+                               exit( EXIT_FAILURE );
+                       }
+                       if ( cvalue == NULL ) {
+                               fprintf( stderr, _("missing specification of sync control\n"));
+                               exit( EXIT_FAILURE );
+                       }
+                       if ( strncasecmp( cvalue, "ro", 2 ) == 0 ) {
+                               ldapsync = LDAP_SYNC_REFRESH_ONLY;
+                               cookiep = strchr( cvalue, '/' );
+                               if ( cookiep != NULL ) {
+                                       cookiep++;
+                                       if ( *cookiep != '\0' ) {
+                                               ber_str2bv( cookiep, 0, 0, &sync_cookie );
+                                       }
+                               }
+                       } else if ( strncasecmp( cvalue, "rp", 2 ) == 0 ) {
+                               ldapsync = LDAP_SYNC_REFRESH_AND_PERSIST;
+                               cookiep = strchr( cvalue, '/' );
+                               if ( cookiep != NULL ) {
+                                       *cookiep++ = '\0';      
+                                       cvalue = cookiep;
+                               }
+                               slimitp = strchr( cvalue, '/' );
+                               if ( slimitp != NULL ) {
+                                       *slimitp++ = '\0';
+                               }
+                               if ( cookiep != NULL && *cookiep != '\0' )
+                                       ber_str2bv( cookiep, 0, 0, &sync_cookie );
+                               if ( slimitp != NULL && *slimitp != '\0' ) {
+                                       ival = strtol( slimitp, &next, 10 );
+                                       if ( next == NULL || next[0] != '\0' ) {
+                                               fprintf( stderr, _("Unable to parse sync control value \"%s\"\n"), slimitp );
+                                               exit( EXIT_FAILURE );
+                                       }
+                                       sync_slimit = ival;
+                               }
+                       } else {
+                               fprintf( stderr, _("sync control value \"%s\" invalid\n"),
+                                       cvalue );
+                               exit( EXIT_FAILURE );
+                       }
+                       if ( crit ) ldapsync *= -1;
 
-       case 'f':       /* input file */
-               if( infile != NULL ) {
-                       fprintf( stderr, "%s: -f previously specified\n", prog );
-                       return EXIT_FAILURE;
+               } else {
+                       fprintf( stderr, _("Invalid search extension name: %s\n"),
+                               control );
+                       usage();
                }
-               infile = strdup( optarg );
                break;
        case 'F':       /* uri prefix */
                if( urlpre ) free( urlpre );
                urlpre = strdup( optarg );
                break;
        case 'l':       /* time limit */
-               timelimit = atoi( optarg );
-               if( timelimit < 0 ) {
-                       fprintf( stderr, "%s: invalid timelimit (%d) specified\n",
+               if ( strcasecmp( optarg, "none" ) == 0 ) {
+                       timelimit = 0;
+
+               } else if ( strcasecmp( optarg, "max" ) == 0 ) {
+                       timelimit = LDAP_MAXINT;
+
+               } else {
+                       ival = strtol( optarg, &next, 10 );
+                       if ( next == NULL || next[0] != '\0' ) {
+                               fprintf( stderr,
+                                       _("Unable to parse time limit \"%s\"\n"), optarg );
+                               exit( EXIT_FAILURE );
+                       }
+                       timelimit = ival;
+               }
+               if( timelimit < 0 || timelimit > LDAP_MAXINT ) {
+                       fprintf( stderr, _("%s: invalid timelimit (%d) specified\n"),
                                prog, timelimit );
-                       return EXIT_FAILURE;
+                       exit( EXIT_FAILURE );
                }
                break;
        case 'L':       /* print entries in LDIF format */
                ++ldif;
                break;
        case 's':       /* search scope */
-               if ( strcasecmp( optarg, "base" ) == 0 ) {
-               scope = LDAP_SCOPE_BASE;
+               if ( strncasecmp( optarg, "base", sizeof("base")-1 ) == 0 ) {
+                       scope = LDAP_SCOPE_BASE;
                } else if ( strncasecmp( optarg, "one", sizeof("one")-1 ) == 0 ) {
-               scope = LDAP_SCOPE_ONELEVEL;
+                       scope = LDAP_SCOPE_ONELEVEL;
+#ifdef LDAP_SCOPE_SUBORDINATE
+               } else if (( strcasecmp( optarg, "subordinate" ) == 0 )
+                       || ( strcasecmp( optarg, "children" ) == 0 ))
+               {
+                       scope = LDAP_SCOPE_SUBORDINATE;
+#endif
                } else if ( strncasecmp( optarg, "sub", sizeof("sub")-1 ) == 0 ) {
-               scope = LDAP_SCOPE_SUBTREE;
+                       scope = LDAP_SCOPE_SUBTREE;
                } else {
-               fprintf( stderr, "scope should be base, one, or sub\n" );
-               usage(prog);
+                       fprintf( stderr, _("scope should be base, one, or sub\n") );
+                       usage();
                }
                break;
        case 'S':       /* sort attribute */
                sortattr = strdup( optarg );
                break;
-       case 'u':       /* include UFN */
-               ++includeufn;
-               break;
        case 't':       /* write attribute values to TMPDIR files */
                ++vals2tmp;
                break;
@@ -413,446 +492,118 @@ main( int argc, char **argv )
                if( tmpdir ) free( tmpdir );
                tmpdir = strdup( optarg );
                break;
-       case 'z':       /* size limit */
-               sizelimit = atoi( optarg );
-               break;
-
-       /* Common Options */
-       case 'C':
-               referrals++;
+       case 'u':       /* include UFN */
+               ++includeufn;
                break;
-       case 'd':
-           debug |= atoi( optarg );
-           break;
-       case 'D':       /* bind DN */
-               if( binddn != NULL ) {
-                       fprintf( stderr, "%s: -D previously specified\n", prog );
-                       return EXIT_FAILURE;
-               }
-           binddn = strdup( optarg );
-           break;
-       case 'e': /* general controls */
-               if( version == LDAP_VERSION2 ) {
-                       fprintf( stderr, "%s: -e incompatible with LDAPv%d\n",
-                               prog, version );
-                       return EXIT_FAILURE;
-               }
+       case 'z':       /* size limit */
+               if ( strcasecmp( optarg, "none" ) == 0 ) {
+                       sizelimit = 0;
 
-               /* should be extended to support comma separated list of
-                *      [!]key[=value] parameters, e.g.  -e !foo,bar=567
-                */
+               } else if ( strcasecmp( optarg, "max" ) == 0 ) {
+                       sizelimit = LDAP_MAXINT;
 
-               crit = 0;
-               cvalue = NULL;
-               if( optarg[0] == '!' ) {
-                       crit = 1;
-                       optarg++;
+               } else {
+                       ival = strtol( optarg, &next, 10 );
+                       if ( next == NULL || next[0] != '\0' ) {
+                               fprintf( stderr,
+                                       _("Unable to parse size limit \"%s\"\n"), optarg );
+                               exit( EXIT_FAILURE );
+                       }
+                       sizelimit = ival;
                }
-
-               control = strdup( optarg );
-               if ( (cvalue = strchr( control, '=' )) != NULL ) {
-                       *cvalue++ = '\0';
+               if( sizelimit < 0 || sizelimit > LDAP_MAXINT ) {
+                       fprintf( stderr, _("%s: invalid sizelimit (%d) specified\n"),
+                               prog, sizelimit );
+                       exit( EXIT_FAILURE );
                }
+               break;
+       default:
+               return 0;
+       }
+       return 1;
+}
 
-               if ( strcasecmp( control, "authzid" ) == 0 ) {
-                       if( authzid != NULL ) {
-                               fprintf( stderr, "authzid control previously specified");
-                               return EXIT_FAILURE;
-                       }
-                       if( cvalue == NULL ) {
-                               fprintf( stderr, "authzid: control value expected" );
-                               usage(prog);
-                               return EXIT_FAILURE;
-                       }
-                       if( !crit ) {
-                               fprintf( stderr, "authzid: must be marked critical" );
-                               usage(prog);
-                               return EXIT_FAILURE;
-                       }
-
-                       assert( authzid == NULL );
-                       authzid = cvalue;
 
-               } else if ( strcasecmp( control, "manageDSAit" ) == 0 ) {
-                       if( manageDSAit ) {
-                               fprintf( stderr, "manageDSAit control previously specified");
-                               return EXIT_FAILURE;
-                       }
-                       if( cvalue != NULL ) {
-                               fprintf( stderr, "manageDSAit: no control value expected" );
-                               usage(prog);
-                               return EXIT_FAILURE;
-                       }
+static void
+private_conn_setup( LDAP *ld )
+{
+       if (deref != -1 &&
+               ldap_set_option( ld, LDAP_OPT_DEREF, (void *) &deref )
+                       != LDAP_OPT_SUCCESS )
+       {
+               fprintf( stderr, _("Could not set LDAP_OPT_DEREF %d\n"), deref );
+               exit( EXIT_FAILURE );
+       }
+       if (timelimit > 0 &&
+               ldap_set_option( ld, LDAP_OPT_TIMELIMIT, (void *) &timelimit )
+                       != LDAP_OPT_SUCCESS )
+       {
+               fprintf( stderr,
+                       _("Could not set LDAP_OPT_TIMELIMIT %d\n"), timelimit );
+               exit( EXIT_FAILURE );
+       }
+       if (sizelimit > 0 &&
+               ldap_set_option( ld, LDAP_OPT_SIZELIMIT, (void *) &sizelimit )
+                       != LDAP_OPT_SUCCESS )
+       {
+               fprintf( stderr,
+                       _("Could not set LDAP_OPT_SIZELIMIT %d\n"), sizelimit );
+               exit( EXIT_FAILURE );
+       }
+}
 
-                       manageDSAit = 1 + crit;
+int
+main( int argc, char **argv )
+{
+       char            *filtpattern, **attrs = NULL, line[BUFSIZ];
+       FILE            *fp = NULL;
+       int                     rc, i, first;
+       LDAP            *ld = NULL;
+       BerElement      *seber = NULL, *vrber = NULL, *prber = NULL;
 
-               } else if ( strcasecmp( control, "noop" ) == 0 ) {
-                       if( noop ) {
-                               fprintf( stderr, "noop control previously specified");
-                               return EXIT_FAILURE;
-                       }
-                       if( cvalue != NULL ) {
-                               fprintf( stderr, "noop: no control value expected" );
-                               usage(prog);
-                               return EXIT_FAILURE;
-                       }
+       BerElement      *syncber = NULL;
+       struct berval   *syncbvalp = NULL;
 
-                       noop = 1 + crit;
+       tool_init();
 
-               } else {
-                       fprintf( stderr, "Invalid general control name: %s\n", control );
-                       usage(prog);
-                       return EXIT_FAILURE;
-               }
-               break;
-       case 'h':       /* ldap host */
-               if( ldapuri != NULL ) {
-                       fprintf( stderr, "%s: -h incompatible with -H\n", prog );
-                       return EXIT_FAILURE;
-               }
-               if( ldaphost != NULL ) {
-                       fprintf( stderr, "%s: -h previously specified\n", prog );
-                       return EXIT_FAILURE;
-               }
-           ldaphost = strdup( optarg );
-           break;
-       case 'H':       /* ldap URI */
-               if( ldaphost != NULL ) {
-                       fprintf( stderr, "%s: -H incompatible with -h\n", prog );
-                       return EXIT_FAILURE;
-               }
-               if( ldapport ) {
-                       fprintf( stderr, "%s: -H incompatible with -p\n", prog );
-                       return EXIT_FAILURE;
-               }
-               if( ldapuri != NULL ) {
-                       fprintf( stderr, "%s: -H previously specified\n", prog );
-                       return EXIT_FAILURE;
-               }
-           ldapuri = strdup( optarg );
-           break;
-       case 'I':
-#ifdef HAVE_CYRUS_SASL
-               if( version == LDAP_VERSION2 ) {
-                       fprintf( stderr, "%s: -I incompatible with version %d\n",
-                               prog, version );
-                       return EXIT_FAILURE;
-               }
-               if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
-                       fprintf( stderr, "%s: incompatible previous "
-                               "authentication choice\n",
-                               prog );
-                       return EXIT_FAILURE;
-               }
-               authmethod = LDAP_AUTH_SASL;
-               version = LDAP_VERSION3;
-               sasl_flags = LDAP_SASL_INTERACTIVE;
-               break;
-#else
-               fprintf( stderr, "%s: was not compiled with SASL support\n",
-                       prog );
-               return( EXIT_FAILURE );
-#endif
-       case 'k':       /* kerberos bind */
-#ifdef LDAP_API_FEATURE_X_OPENLDAP_V2_KBIND
-               if( version > LDAP_VERSION2 ) {
-                       fprintf( stderr, "%s: -k incompatible with LDAPv%d\n",
-                               prog, version );
-                       return EXIT_FAILURE;
-               }
-
-               if( authmethod != -1 ) {
-                       fprintf( stderr, "%s: -k incompatible with previous "
-                               "authentication choice\n", prog );
-                       return EXIT_FAILURE;
-               }
-                       
-               authmethod = LDAP_AUTH_KRBV4;
-#else
-               fprintf( stderr, "%s: not compiled with Kerberos support\n", prog );
-               return EXIT_FAILURE;
+#ifdef LDAP_CONTROL_PAGEDRESULTS
+       npagedresponses = npagedentries = npagedreferences =
+               npagedextended = npagedpartial = 0;
 #endif
-           break;
-       case 'K':       /* kerberos bind, part one only */
-#ifdef LDAP_API_FEATURE_X_OPENLDAP_V2_KBIND
-               if( version > LDAP_VERSION2 ) {
-                       fprintf( stderr, "%s: -k incompatible with LDAPv%d\n",
-                               prog, version );
-                       return EXIT_FAILURE;
-               }
-               if( authmethod != -1 ) {
-                       fprintf( stderr, "%s: incompatible with previous "
-                               "authentication choice\n", prog );
-                       return EXIT_FAILURE;
-               }
 
-               authmethod = LDAP_AUTH_KRBV41;
-#else
-               fprintf( stderr, "%s: not compiled with Kerberos support\n", prog );
-               return( EXIT_FAILURE );
-#endif
-           break;
-       case 'M':
-               /* enable Manage DSA IT */
-               if( version == LDAP_VERSION2 ) {
-                       fprintf( stderr, "%s: -M incompatible with LDAPv%d\n",
-                               prog, version );
-                       return EXIT_FAILURE;
-               }
-               manageDSAit++;
-               version = LDAP_VERSION3;
-               break;
-       case 'n':       /* print deletes, don't actually do them */
-           ++not;
-           break;
-       case 'O':
-#ifdef HAVE_CYRUS_SASL
-               if( sasl_secprops != NULL ) {
-                       fprintf( stderr, "%s: -O previously specified\n", prog );
-                       return EXIT_FAILURE;
-               }
-               if( version == LDAP_VERSION2 ) {
-                       fprintf( stderr, "%s: -O incompatible with LDAPv%d\n",
-                               prog, version );
-                       return EXIT_FAILURE;
-               }
-               if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
-                       fprintf( stderr, "%s: incompatible previous "
-                               "authentication choice\n", prog );
-                       return EXIT_FAILURE;
-               }
-               authmethod = LDAP_AUTH_SASL;
-               version = LDAP_VERSION3;
-               sasl_secprops = strdup( optarg );
-#else
-               fprintf( stderr, "%s: not compiled with SASL support\n",
-                       prog );
-               return( EXIT_FAILURE );
-#endif
-               break;
-       case 'p':
-               if( ldapport ) {
-                       fprintf( stderr, "%s: -p previously specified\n", prog );
-                       return EXIT_FAILURE;
-               }
-           ldapport = atoi( optarg );
-           break;
-       case 'P':
-               switch( atoi(optarg) ) {
-               case 2:
-                       if( version == LDAP_VERSION3 ) {
-                               fprintf( stderr, "%s: -P 2 incompatible with version %d\n",
-                                       prog, version );
-                               return EXIT_FAILURE;
-                       }
-                       version = LDAP_VERSION2;
-                       break;
-               case 3:
-                       if( version == LDAP_VERSION2 ) {
-                               fprintf( stderr, "%s: -P 2 incompatible with version %d\n",
-                                       prog, version );
-                               return EXIT_FAILURE;
-                       }
-                       version = LDAP_VERSION3;
-                       break;
-               default:
-                       fprintf( stderr, "%s: protocol version should be 2 or 3\n",
-                               prog );
-                       usage( prog );
-                       return( EXIT_FAILURE );
-               }
-               break;
-       case 'Q':
-#ifdef HAVE_CYRUS_SASL
-               if( version == LDAP_VERSION2 ) {
-                       fprintf( stderr, "%s: -Q incompatible with version %d\n",
-                               prog, version );
-                       return EXIT_FAILURE;
-               }
-               if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
-                       fprintf( stderr, "%s: incompatible previous "
-                               "authentication choice\n",
-                               prog );
-                       return EXIT_FAILURE;
-               }
-               authmethod = LDAP_AUTH_SASL;
-               version = LDAP_VERSION3;
-               sasl_flags = LDAP_SASL_QUIET;
-               break;
-#else
-               fprintf( stderr, "%s: not compiled with SASL support\n",
-                       prog );
-               return( EXIT_FAILURE );
-#endif
-       case 'R':
-#ifdef HAVE_CYRUS_SASL
-               if( sasl_realm != NULL ) {
-                       fprintf( stderr, "%s: -R previously specified\n", prog );
-                       return EXIT_FAILURE;
-               }
-               if( version == LDAP_VERSION2 ) {
-                       fprintf( stderr, "%s: -R incompatible with version %d\n",
-                               prog, version );
-                       return EXIT_FAILURE;
-               }
-               if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
-                       fprintf( stderr, "%s: incompatible previous "
-                               "authentication choice\n",
-                               prog );
-                       return EXIT_FAILURE;
-               }
-               authmethod = LDAP_AUTH_SASL;
-               version = LDAP_VERSION3;
-               sasl_realm = strdup( optarg );
-#else
-               fprintf( stderr, "%s: not compiled with SASL support\n",
-                       prog );
-               return( EXIT_FAILURE );
-#endif
-               break;
-       case 'U':
-#ifdef HAVE_CYRUS_SASL
-               if( sasl_authc_id != NULL ) {
-                       fprintf( stderr, "%s: -U previously specified\n", prog );
-                       return EXIT_FAILURE;
-               }
-               if( version == LDAP_VERSION2 ) {
-                       fprintf( stderr, "%s: -U incompatible with version %d\n",
-                               prog, version );
-                       return EXIT_FAILURE;
-               }
-               if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
-                       fprintf( stderr, "%s: incompatible previous "
-                               "authentication choice\n",
-                               prog );
-                       return EXIT_FAILURE;
-               }
-               authmethod = LDAP_AUTH_SASL;
-               version = LDAP_VERSION3;
-               sasl_authc_id = strdup( optarg );
-#else
-               fprintf( stderr, "%s: not compiled with SASL support\n",
-                       prog );
-               return( EXIT_FAILURE );
-#endif
-               break;
-       case 'v':       /* verbose mode */
-           verbose++;
-           break;
-       case 'w':       /* password */
-           passwd.bv_val = strdup( optarg );
-               {
-                       char* p;
+       prog = lutil_progname( "ldapsearch", argc, argv );
 
-                       for( p = optarg; *p != '\0'; p++ ) {
-                               *p = '\0';
-                       }
-               }
-               passwd.bv_len = strlen( passwd.bv_val );
-           break;
-       case 'W':
-               want_bindpw++;
-               break;
-       case 'y':
-               pw_file = optarg;
-               break;
-       case 'Y':
-#ifdef HAVE_CYRUS_SASL
-               if( sasl_mech != NULL ) {
-                       fprintf( stderr, "%s: -Y previously specified\n", prog );
-                       return EXIT_FAILURE;
-               }
-               if( version == LDAP_VERSION2 ) {
-                       fprintf( stderr, "%s: -Y incompatible with version %d\n",
-                               prog, version );
-                       return EXIT_FAILURE;
-               }
-               if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
-                       fprintf( stderr, "%s: incompatible with authentication choice\n", prog );
-                       return EXIT_FAILURE;
-               }
-               authmethod = LDAP_AUTH_SASL;
-               version = LDAP_VERSION3;
-               sasl_mech = strdup( optarg );
-#else
-               fprintf( stderr, "%s: not compiled with SASL support\n",
-                       prog );
-               return( EXIT_FAILURE );
-#endif
-               break;
-       case 'x':
-               if( authmethod != -1 && authmethod != LDAP_AUTH_SIMPLE ) {
-                       fprintf( stderr, "%s: incompatible with previous "
-                               "authentication choice\n", prog );
-                       return EXIT_FAILURE;
-               }
-               authmethod = LDAP_AUTH_SIMPLE;
-               break;
-       case 'X':
-#ifdef HAVE_CYRUS_SASL
-               if( sasl_authz_id != NULL ) {
-                       fprintf( stderr, "%s: -X previously specified\n", prog );
-                       return EXIT_FAILURE;
-               }
-               if( version == LDAP_VERSION2 ) {
-                       fprintf( stderr, "%s: -X incompatible with LDAPv%d\n",
-                               prog, version );
-                       return EXIT_FAILURE;
-               }
-               if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
-                       fprintf( stderr, "%s: -X incompatible with "
-                               "authentication choice\n", prog );
-                       return EXIT_FAILURE;
-               }
-               authmethod = LDAP_AUTH_SASL;
-               version = LDAP_VERSION3;
-               sasl_authz_id = strdup( optarg );
-#else
-               fprintf( stderr, "%s: not compiled with SASL support\n",
-                       prog );
-               return( EXIT_FAILURE );
-#endif
-               break;
-       case 'Z':
-#ifdef HAVE_TLS
-               if( version == LDAP_VERSION2 ) {
-                       fprintf( stderr, "%s: -Z incompatible with version %d\n",
-                               prog, version );
-                       return EXIT_FAILURE;
-               }
-               version = LDAP_VERSION3;
-               use_tls++;
-#else
-               fprintf( stderr, "%s: not compiled with TLS support\n",
-                       prog );
-               return( EXIT_FAILURE );
-#endif
-               break;
-       default:
-               fprintf( stderr, "%s: unrecognized option -%c\n",
-                       prog, optopt );
-               usage(prog);
-       }
+       if((def_tmpdir = getenv("TMPDIR")) == NULL &&
+          (def_tmpdir = getenv("TMP")) == NULL &&
+          (def_tmpdir = getenv("TEMP")) == NULL )
+       {
+               def_tmpdir = LDAP_TMPDIR;
        }
 
-       if (version == -1) {
-               version = LDAP_VERSION3;
-       }
-       if (authmethod == -1 && version > LDAP_VERSION2) {
-#ifdef HAVE_CYRUS_SASL
-               authmethod = LDAP_AUTH_SASL;
-#else
-               authmethod = LDAP_AUTH_SIMPLE;
-#endif
+       if ( !*def_tmpdir )
+               def_tmpdir = LDAP_TMPDIR;
+
+       def_urlpre = malloc( sizeof("file:////") + strlen(def_tmpdir) );
+
+       if( def_urlpre == NULL ) {
+               perror( "malloc" );
+               return EXIT_FAILURE;
        }
 
+       sprintf( def_urlpre, "file:///%s/",
+               def_tmpdir[0] == *LDAP_DIRSEP ? &def_tmpdir[1] : def_tmpdir );
+
+       urlize( def_urlpre );
+
+       tool_args( argc, argv );
+
        if (( argc - optind < 1 ) ||
                ( *argv[optind] != '(' /*')'*/ &&
                ( strchr( argv[optind], '=' ) == NULL ) ) )
        {
                filtpattern = "(objectclass=*)";
        } else {
-               filtpattern = strdup( argv[optind++] );
+               filtpattern = argv[optind++];
        }
 
        if ( argv[optind] != NULL ) {
@@ -860,12 +611,32 @@ main( int argc, char **argv )
        }
 
        if ( infile != NULL ) {
+               int percent = 0;
+       
                if ( infile[0] == '-' && infile[1] == '\0' ) {
                        fp = stdin;
                } else if (( fp = fopen( infile, "r" )) == NULL ) {
                        perror( infile );
                        return EXIT_FAILURE;
                }
+
+               for( i=0 ; filtpattern[i] ; i++ ) {
+                       if( filtpattern[i] == '%' ) {
+                               if( percent ) {
+                                       fprintf( stderr, _("Bad filter pattern \"%s\"\n"),
+                                               filtpattern );
+                                       return EXIT_FAILURE;
+                               }
+
+                               percent++;
+
+                               if( filtpattern[i+1] != 's' ) {
+                                       fprintf( stderr, _("Bad filter pattern \"%s\"\n"),
+                                               filtpattern );
+                                       return EXIT_FAILURE;
+                               }
+                       }
+               }
        }
 
        if ( tmpdir == NULL ) {
@@ -889,287 +660,161 @@ main( int argc, char **argv )
                urlize( urlpre );
        }
 
-       if ( debug ) {
-               if( ber_set_option( NULL, LBER_OPT_DEBUG_LEVEL, &debug ) != LBER_OPT_SUCCESS ) {
-                       fprintf( stderr, "Could not set LBER_OPT_DEBUG_LEVEL %d\n", debug );
-               }
-               if( ldap_set_option( NULL, LDAP_OPT_DEBUG_LEVEL, &debug ) != LDAP_OPT_SUCCESS ) {
-                       fprintf( stderr, "Could not set LDAP_OPT_DEBUG_LEVEL %d\n", debug );
-               }
+       if ( debug )
                ldif_debug = debug;
-       }
-
-#ifdef SIGPIPE
-       (void) SIGNAL( SIGPIPE, SIG_IGN );
-#endif
-
-       if( ( ldaphost != NULL || ldapport ) && ( ldapuri == NULL ) ) {
-               if ( verbose ) {
-                       fprintf( stderr, "ldap_init( %s, %d )\n",
-                               ldaphost != NULL ? ldaphost : "<DEFAULT>",
-                               ldapport );
-               }
-
-               ld = ldap_init( ldaphost, ldapport );
-               if( ld == NULL ) {
-                       perror("ldapsearch: ldap_init");
-                       return EXIT_FAILURE;
-               }
-
-       } else {
-               if ( verbose ) {
-                       fprintf( stderr, "ldap_initialize( %s )\n",
-                               ldapuri != NULL ? ldapuri : "<DEFAULT>" );
-               }
-
-               rc = ldap_initialize( &ld, ldapuri );
-               if( rc != LDAP_SUCCESS ) {
-                       fprintf( stderr, "Could not create LDAP session handle (%d): %s\n",
-                               rc, ldap_err2string(rc) );
-                       return EXIT_FAILURE;
-               }
-       }
-
-       if (deref != -1 &&
-               ldap_set_option( ld, LDAP_OPT_DEREF, (void *) &deref ) != LDAP_OPT_SUCCESS )
-       {
-               fprintf( stderr, "Could not set LDAP_OPT_DEREF %d\n", deref );
-               return EXIT_FAILURE;
-       }
-       if (timelimit != -1 &&
-               ldap_set_option( ld, LDAP_OPT_TIMELIMIT, (void *) &timelimit ) != LDAP_OPT_SUCCESS )
-       {
-               fprintf( stderr, "Could not set LDAP_OPT_TIMELIMIT %d\n", timelimit );
-               return EXIT_FAILURE;
-       }
-       if (sizelimit != -1 &&
-               ldap_set_option( ld, LDAP_OPT_SIZELIMIT, (void *) &sizelimit ) != LDAP_OPT_SUCCESS )
-       {
-               fprintf( stderr, "Could not set LDAP_OPT_SIZELIMIT %d\n", sizelimit );
-               return EXIT_FAILURE;
-       }
-
-       /* referrals */
-       if (ldap_set_option( ld, LDAP_OPT_REFERRALS,
-               referrals ? LDAP_OPT_ON : LDAP_OPT_OFF ) != LDAP_OPT_SUCCESS )
-       {
-               fprintf( stderr, "Could not set LDAP_OPT_REFERRALS %s\n",
-                       referrals ? "on" : "off" );
-               return EXIT_FAILURE;
-       }
-
-       if (version == -1 ) {
-               version = LDAP_VERSION3;
-       }
-
-       if( ldap_set_option( ld, LDAP_OPT_PROTOCOL_VERSION, &version )
-               != LDAP_OPT_SUCCESS )
-       {
-               fprintf( stderr, "Could not set LDAP_OPT_PROTOCOL_VERSION %d\n",
-                       version );
-               return EXIT_FAILURE;
-       }
 
-       if ( use_tls && ( ldap_start_tls_s( ld, NULL, NULL ) != LDAP_SUCCESS )) {
-               ldap_perror( ld, "ldap_start_tls" );
-               if ( use_tls > 1 ) {
-                       return EXIT_FAILURE;
-               }
-       }
+       ld = tool_conn_setup( 0, &private_conn_setup );
 
        if ( pw_file || want_bindpw ) {
                if ( pw_file ) {
                        rc = lutil_get_filed_password( pw_file, &passwd );
                        if( rc ) return EXIT_FAILURE;
                } else {
-                       passwd.bv_val = getpassphrase( "Enter LDAP Password: " );
+                       passwd.bv_val = getpassphrase( _("Enter LDAP Password: ") );
                        passwd.bv_len = passwd.bv_val ? strlen( passwd.bv_val ) : 0;
                }
        }
 
-       if ( authmethod == LDAP_AUTH_SASL ) {
-#ifdef HAVE_CYRUS_SASL
-               void *defaults;
-
-               if( sasl_secprops != NULL ) {
-                       rc = ldap_set_option( ld, LDAP_OPT_X_SASL_SECPROPS,
-                               (void *) sasl_secprops );
-                       
-                       if( rc != LDAP_OPT_SUCCESS ) {
-                               fprintf( stderr,
-                                       "Could not set LDAP_OPT_X_SASL_SECPROPS: %s\n",
-                                       sasl_secprops );
-                               return( EXIT_FAILURE );
-                       }
-               }
-               
-               defaults = lutil_sasl_defaults( ld,
-                       sasl_mech,
-                       sasl_realm,
-                       sasl_authc_id,
-                       passwd.bv_val,
-                       sasl_authz_id );
-
-               rc = ldap_sasl_interactive_bind_s( ld, binddn,
-                       sasl_mech, NULL, NULL,
-                       sasl_flags, lutil_sasl_interact, defaults );
-
-               if( rc != LDAP_SUCCESS ) {
-                       ldap_perror( ld, "ldap_sasl_interactive_bind_s" );
-                       return( EXIT_FAILURE );
-               }
-#else
-               fprintf( stderr, "%s: not compiled with SASL support\n",
-                       prog);
-               return( EXIT_FAILURE );
-#endif
-       } else {
-               if ( ldap_bind_s( ld, binddn, passwd.bv_val, authmethod )
-                               != LDAP_SUCCESS ) {
-                       ldap_perror( ld, "ldap_bind" );
-                       return( EXIT_FAILURE );
-               }
-       }
+       tool_bind( ld );
 
 getNextPage:
-       if ( manageDSAit || noop || subentries
-               || valuesReturnFilter || pageSize )
+       if ( assertion || authzid || manageDSAit || noop
+#ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
+               || domainScope
+#endif
+#ifdef LDAP_CONTROL_PAGEDRESULTS
+               || pagedResults
+#endif
+#ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
+               || chaining
+#endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
+               || ldapsync
+               || subentries || valuesReturnFilter )
        {
                int err;
                int i=0;
-               int crit = 0;
-               LDAPControl c[6];
-               LDAPControl *ctrls[7];
-               
-               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_iscritical = 1;
-
-                       if( c[i].ldctl_iscritical ) crit++;
-                       ctrls[i] = &c[i];
-                       ctrls[++i] = NULL;
-               }
-
-               if ( manageDSAit ) {
-                       c[i].ldctl_oid = LDAP_CONTROL_MANAGEDSAIT;
-                       c[i].ldctl_value.bv_val = NULL;
-                       c[i].ldctl_value.bv_len = 0;
-                       c[i].ldctl_iscritical = manageDSAit > 1;
-
-                       if( c[i].ldctl_iscritical ) crit++;
-                       ctrls[i] = &c[i];
-                       ctrls[++i] = NULL;
-               }
+               LDAPControl c[10];
 
-               if ( noop ) {
-                       c[i].ldctl_oid = LDAP_CONTROL_NOOP;
+#ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
+               if ( domainScope ) {
+                       c[i].ldctl_oid = LDAP_CONTROL_X_DOMAIN_SCOPE;
                        c[i].ldctl_value.bv_val = NULL;
                        c[i].ldctl_value.bv_len = 0;
-                       c[i].ldctl_iscritical = noop > 1;
-
-                       if( c[i].ldctl_iscritical ) crit++;
-                       ctrls[i] = &c[i];
-                       ctrls[++i] = NULL;
+                       c[i].ldctl_iscritical = domainScope > 1;
+                       i++;
                }
+#endif
 
 #ifdef LDAP_CONTROL_SUBENTRIES
                if ( subentries ) {
-               if (( ber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
+                       if (( seber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
                                return EXIT_FAILURE;
                        }
 
-                       err = ber_printf( ber, "{b}", abs(subentries) == 1 ? 0 : 1 );
-               if ( err == LBER_ERROR ) {
-                               ber_free( ber, 1 );
-                               fprintf( stderr, "Subentries control encoding error!\n" );
+                       err = ber_printf( seber, "b", abs(subentries) == 1 ? 0 : 1 );
+                       if ( err == -1 ) {
+                               ber_free( seber, 1 );
+                               fprintf( stderr, _("Subentries control encoding error!\n") );
                                return EXIT_FAILURE;
                        }
 
-                       if ( ber_flatten( ber, &sebvalp ) == LBER_ERROR ) {
+                       if ( ber_flatten2( seber, &c[i].ldctl_value, 0 ) == -1 ) {
                                return EXIT_FAILURE;
                        }
 
                        c[i].ldctl_oid = LDAP_CONTROL_SUBENTRIES;
-                       c[i].ldctl_value=(*sebvalp);
                        c[i].ldctl_iscritical = subentries < 1;
-
-                       if( c[i].ldctl_iscritical ) crit++;
-                       ctrls[i] = &c[i];
-                       ctrls[++i] = NULL;
+                       i++;
                }
 #endif
 
-               if ( valuesReturnFilter ) {
-               if (( ber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
+               if ( ldapsync ) {
+                       if (( syncber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
+                               return EXIT_FAILURE;
+                       }
+
+                       if ( sync_cookie.bv_len == 0 ) {
+                               err = ber_printf( syncber, "{e}", abs(ldapsync) );
+                       } else {
+                               err = ber_printf( syncber, "{eO}", abs(ldapsync),
+                                                       &sync_cookie );
+                       }
+
+                       if ( err == LBER_ERROR ) {
+                               ber_free( syncber, 1 );
+                               fprintf( stderr, _("ldap sync control encoding error!\n") );
                                return EXIT_FAILURE;
                        }
 
-               if ( ( err = ldap_put_vrFilter( ber, vrFilter ) ) == -1 ) {
-                               ber_free( ber, 1 );
-                               fprintf( stderr, "Bad ValuesReturnFilter: %s\n", vrFilter );
+                       if ( ber_flatten( syncber, &syncbvalp ) == LBER_ERROR ) {
+                               return EXIT_FAILURE;
+                       }
+
+                       c[i].ldctl_oid = LDAP_CONTROL_SYNC;
+                       c[i].ldctl_value = (*syncbvalp);
+                       c[i].ldctl_iscritical = ldapsync < 0;
+                       i++;
+               }
+
+               if ( valuesReturnFilter ) {
+               if (( vrber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
                                return EXIT_FAILURE;
                        }
 
-                       if ( ber_flatten( ber, &vrbvalp ) == LBER_ERROR ) {
+               if ( ( err = ldap_put_vrFilter( vrber, vrFilter ) ) == -1 ) {
+                               ber_free( vrber, 1 );
+                               fprintf( stderr, _("Bad ValuesReturnFilter: %s\n"), vrFilter );
                                return EXIT_FAILURE;
                        }
 
-                       ber_free( ber, 1 );
+                       if ( ber_flatten2( vrber, &c[i].ldctl_value, 0 ) == -1 ) {
+                               return EXIT_FAILURE;
+                       }
 
                        c[i].ldctl_oid = LDAP_CONTROL_VALUESRETURNFILTER;
-                       c[i].ldctl_value=(*vrbvalp);
                        c[i].ldctl_iscritical = valuesReturnFilter > 1;
-
-                       if( c[i].ldctl_iscritical ) crit++;
-                       ctrls[i] = &c[i];
-                       ctrls[++i] = NULL;
+                       i++;
                }
 
+#ifdef LDAP_CONTROL_PAGEDRESULTS
                if ( pagedResults ) {
-                       if (( ber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
+                       if (( prber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
                                return EXIT_FAILURE;
                        }
 
-                       ber_printf( ber, "{iO}", pageSize, &cookie );
-                       if ( ber_flatten( ber, &prbvalp ) == LBER_ERROR ) {
+                       ber_printf( prber, "{iO}", pageSize, &page_cookie );
+                       if ( ber_flatten2( prber, &c[i].ldctl_value, 0 ) == -1 ) {
                                return EXIT_FAILURE;
                        }
+                       if ( page_cookie.bv_val != NULL ) {
+                               ber_memfree( page_cookie.bv_val );
+                               page_cookie.bv_val = NULL;
+                       }
                        
-                       ber_free( ber, 1 );
-
                        c[i].ldctl_oid = LDAP_CONTROL_PAGEDRESULTS;
-                       c[i].ldctl_value=(*prbvalp);
                        c[i].ldctl_iscritical = pagedResults > 1;
-
-                       if( c[i].ldctl_iscritical ) crit++;
-                       ctrls[i] = &c[i];
-                       ctrls[++i] = NULL;
+                       i++;
                }
+#endif
 
-               err = ldap_set_option( ld, LDAP_OPT_SERVER_CONTROLS, ctrls );
-
-               if( err != LDAP_OPT_SUCCESS ) {
-                       fprintf( stderr, "Could not set %scontrols\n",
-                               crit ? "critical " : "" );
-                       if( crit ) {
-                               return EXIT_FAILURE;
-                       }
-               }
+               tool_server_controls( ld, c, i );
 
-               ber_bvfree( sebvalp );
-               ber_bvfree( vrbvalp );
-               ber_bvfree( prbvalp );
+#ifdef LDAP_CONTROL_SUBENTRIES
+               ber_free( seber, 1 );
+#endif
+               ber_free( vrber, 1 );
+#ifdef LDAP_CONTROL_PAGEDRESULTS
+               ber_free( prber, 1 );
+#endif
        }
        
        if ( verbose ) {
-               fprintf( stderr, "filter%s: %s\nrequesting: ",
-                       infile != NULL ? " pattern" : "",
+               fprintf( stderr, _("filter%s: %s\nrequesting: "),
+                       infile != NULL ? _(" pattern") : "",
                        filtpattern );
 
                if ( attrs == NULL ) {
-                       fprintf( stderr, "ALL" );
+                       fprintf( stderr, _("All userApplication attributes") );
                } else {
                        for ( i = 0; attrs[ i ] != NULL; ++i ) {
                                fprintf( stderr, "%s ", attrs[ i ] );
@@ -1179,25 +824,32 @@ getNextPage:
        }
 
        if ( ldif == 0 ) {
-               printf( "# extended LDIF\n" );
+               printf( _("# extended LDIF\n") );
        } else if ( ldif < 3 ) {
-               printf( "version: %d\n\n", 1 );
+               printf( _("version: %d\n\n"), 1 );
        }
 
        if (ldif < 2 ) {
-               printf( "#\n"
-                       "# LDAPv%d\n"
-                       "# base <%s> with scope %s\n"
-                       "# filter%s: %s\n"
-                       "# requesting: ",
-                       version,
-                       base, (scope == LDAP_SCOPE_BASE) ? "base"
-                               : ((scope == LDAP_SCOPE_ONELEVEL) ? "one" : "sub"),
-                       infile != NULL ? " pattern" : "",
-                       filtpattern );
+               printf( "#\n" );
+               printf(_("# LDAPv%d\n"), protocol);
+               printf(_("# base <%s> with scope %s\n"),
+                       base ? base : "",
+                       ((scope == LDAP_SCOPE_BASE) ? "baseObject"
+                               : ((scope == LDAP_SCOPE_ONELEVEL) ? "oneLevel"
+#ifdef LDAP_SCOPE_SUBORDINATE
+                               : ((scope == LDAP_SCOPE_SUBORDINATE) ? "children"
+#endif
+                               : "subtree"
+#ifdef LDAP_SCOPE_SUBORDINATE
+                               )
+#endif
+                               )));
+               printf(_("# filter%s: %s\n"), infile != NULL ? _(" pattern") : "",
+                      filtpattern);
+               printf(_("# requesting: "));
 
                if ( attrs == NULL ) {
-                       printf( "ALL" );
+                       printf( _("ALL") );
                } else {
                        for ( i = 0; attrs[ i ] != NULL; ++i ) {
                                printf( "%s ", attrs[ i ] );
@@ -1205,29 +857,31 @@ getNextPage:
                }
 
                if ( manageDSAit ) {
-                       printf("\n# with manageDSAit %scontrol",
-                               manageDSAit > 1 ? "critical " : "" );
+                       printf(_("\n# with manageDSAit %scontrol"),
+                               manageDSAit > 1 ? _("critical ") : "" );
                }
                if ( noop ) {
-                       printf("\n# with noop %scontrol",
-                               noop > 1 ? "critical " : "" );
+                       printf(_("\n# with noop %scontrol"),
+                               noop > 1 ? _("critical ") : "" );
                }
                if ( subentries ) {
-                       printf("\n# with subentries %scontrol: %s",
-                               subentries < 0 ? "critical " : "",
+                       printf(_("\n# with subentries %scontrol: %s"),
+                               subentries < 0 ? _("critical ") : "",
                                abs(subentries) == 1 ? "false" : "true" );
                }
                if ( valuesReturnFilter ) {
-                       printf("\n# with valuesReturnFilter %scontrol: %s",
-                               valuesReturnFilter > 1 ? "critical " : "", vrFilter );
+                       printf(_("\n# with valuesReturnFilter %scontrol: %s"),
+                               valuesReturnFilter > 1 ? _("critical ") : "", vrFilter );
                }
-               if ( pageSize ) {
-                       printf("\n# with pagedResults %scontrol: size=%d",
-                               (pagedResults > 1) ? "critical " : "", 
+#ifdef LDAP_CONTROL_PAGEDRESULTS
+               if ( pagedResults ) {
+                       printf(_("\n# with pagedResults %scontrol: size=%d"),
+                               (pagedResults > 1) ? _("critical ") : "", 
                                pageSize );
                }
+#endif
 
-               printf( "\n#\n\n" );
+               printf( _("\n#\n\n") );
        }
 
        if ( infile == NULL ) {
@@ -1252,43 +906,48 @@ getNextPage:
                }
        }
 
-       if ( ( pageSize != 0 ) && ( morePagedResults != 0 ) ) { 
+#ifdef LDAP_CONTROL_PAGEDRESULTS
+       if ( ( rc == LDAP_SUCCESS ) &&  ( pageSize != 0 ) && ( morePagedResults != 0 ) ) {
                char    buf[6];
                int     i, moreEntries, tmpSize;
 
                /* Loop to get the next pages when 
                 * enter is pressed on the terminal.
                 */
-               if ( entriesLeft > 0 ) {
-                       printf( "Estimate entries: %d\n", entriesLeft );
-               }
-               printf( "Press [size] Enter for the next {%d|size} entries.\n",
-                       (int)pageSize ); 
-               i = 0;
-               moreEntries = getchar();
-               while ( moreEntries != EOF && moreEntries != '\n' ) { 
-                       if ( i < sizeof(buf) - 1 ) {
-                               buf[i] = moreEntries;
-                               i++;
+               if ( pagePrompt != 0 ) {
+                       if ( entriesLeft > 0 ) {
+                               printf( _("Estimate entries: %d\n"), entriesLeft );
                        }
+                       printf( _("Press [size] Enter for the next {%d|size} entries.\n"),
+                               (int)pageSize );
+                       i = 0;
                        moreEntries = getchar();
-               }
-               buf[i] = '\0';
-
-               if ( i > 0 && isdigit( buf[0] ) ) {
-                       int num = sscanf( buf, "%d", &tmpSize );
-                       if ( num != 1 ) {
-                               fprintf( stderr, "Invalid value for PagedResultsControl, %s.\n", buf);
-                               return EXIT_FAILURE;
+                       while ( moreEntries != EOF && moreEntries != '\n' ) { 
+                               if ( i < (int)sizeof(buf) - 1 ) {
+                                       buf[i] = moreEntries;
+                                       i++;
+                               }
+                               moreEntries = getchar();
+                       }
+                       buf[i] = '\0';
 
+                       if ( i > 0 && isdigit( (unsigned char)buf[0] ) ) {
+                               int num = sscanf( buf, "%d", &tmpSize );
+                               if ( num != 1 ) {
+                                       fprintf( stderr, _("Invalid value for PagedResultsControl, %s.\n"), buf);
+                                       return EXIT_FAILURE;
+       
+                               }
+                               pageSize = (ber_int_t)tmpSize;
                        }
-                       pageSize = (ber_int_t)tmpSize;
                }
 
-               goto getNextPage;       
+               goto getNextPage;
        }
+#endif
 
-       ldap_unbind( ld );
+       tool_unbind( ld );
+       tool_destroy();
        return( rc );
 }
 
@@ -1314,7 +973,11 @@ static int dosearch(
        int                     nextended;
        int                     npartial;
        LDAPMessage             *res, *msg;
-       ber_int_t       msgid;
+       ber_int_t               msgid;
+       char                    *retoid = NULL;
+       struct berval           *retdata = NULL;
+       int                     nresponses_psearch = -1;
+       int                     cancel_msgid = -1;
 
        if( filtpatt != NULL ) {
                filter = malloc( strlen( filtpatt ) + strlen( value ) );
@@ -1326,11 +989,11 @@ static int dosearch(
                sprintf( filter, filtpatt, value );
 
                if ( verbose ) {
-                       fprintf( stderr, "filter: %s\n", filter );
+                       fprintf( stderr, _("filter: %s\n"), filter );
                }
 
                if( ldif < 2 ) {
-                       printf( "#\n# filter: %s\n#\n", filter );
+                       printf( _("#\n# filter: %s\n#\n"), filter );
                }
 
        } else {
@@ -1349,7 +1012,7 @@ static int dosearch(
        }
 
        if( rc != LDAP_SUCCESS ) {
-               fprintf( stderr, "%s: ldap_search_ext: %s (%d)\n",
+               fprintf( stderr, _("%s: ldap_search_ext: %s (%d)\n"),
                        prog, ldap_err2string( rc ), rc );
                return( rc );
        }
@@ -1362,6 +1025,11 @@ static int dosearch(
                sortattr ? LDAP_MSG_ALL : LDAP_MSG_ONE,
                NULL, &res )) > 0 )
        {
+               rc = tool_check_abandon( ld, msgid );
+               if ( rc ) {
+                       return rc;
+               }
+
                if( sortattr ) {
                        (void) ldap_sort_entries( ld, &res,
                                ( *sortattr == '\0' ) ? NULL : sortattr, strcasecmp );
@@ -1371,7 +1039,9 @@ static int dosearch(
                        msg != NULL;
                        msg = ldap_next_message( ld, msg ) )
                {
-                       if( nresponses++ ) putchar('\n');
+                       if ( nresponses++ ) putchar('\n');
+                       if ( nresponses_psearch >= 0 ) 
+                               nresponses_psearch++;
 
                        switch( ldap_msgtype( msg ) ) {
                        case LDAP_RES_SEARCH_ENTRY:
@@ -1392,164 +1062,105 @@ static int dosearch(
                                        /* unsolicited extended operation */
                                        goto done;
                                }
-                               break;
 
-                       case LDAP_RES_EXTENDED_PARTIAL:
-                               npartial++;
-                               print_partial( ld, msg );
+                               if ( cancel_msgid != -1 &&
+                                               cancel_msgid == ldap_msgid( msg ) ) {
+                                       printf(_("Cancelled \n"));
+                                       printf(_("cancel_msgid = %d\n"), cancel_msgid);
+                                       goto done;
+                               }
                                break;
 
                        case LDAP_RES_SEARCH_RESULT:
                                rc = print_result( ld, msg, 1 );
-                               if ( pageSize != 0 ) { 
-                                       rc = parse_page_control( ld, msg, &cookie );
+#ifdef LDAP_CONTROL_PAGEDRESULTS
+                               if ( pageSize != 0 ) {
+                                       if ( rc == LDAP_SUCCESS ) {
+                                               rc = parse_page_control( ld, msg, &page_cookie );
+                                       } else {
+                                               morePagedResults = 0;
+                                       }
+                               } else {
+                                       morePagedResults = 0;
+                               }
+#endif
+
+                               if ( ldapsync == LDAP_SYNC_REFRESH_AND_PERSIST ) {
+                                       break;
+                               }
+
+                               goto done;
+
+                       case LDAP_RES_INTERMEDIATE:
+                               npartial++;
+                               ldap_parse_intermediate( ld, msg,
+                                       &retoid, &retdata, NULL, 0 );
+
+                               nresponses_psearch = 0;
+
+                               if ( strcmp( retoid, LDAP_SYNC_INFO ) == 0 ) {
+                                       printf(_("SyncInfo Received\n"));
+                                       ldap_memfree( retoid );
+                                       ber_bvfree( retdata );
+                                       break;
                                }
+
+                               print_partial( ld, msg );
+                               ldap_memfree( retoid );
+                               ber_bvfree( retdata );
                                goto done;
                        }
+
+                       if ( ldapsync && sync_slimit != -1 &&
+                                       nresponses_psearch >= sync_slimit ) {
+                               BerElement *msgidber = NULL;
+                               struct berval *msgidvalp = NULL;
+                               msgidber = ber_alloc_t(LBER_USE_DER);
+                               ber_printf(msgidber, "{i}", msgid);
+                               ber_flatten(msgidber, &msgidvalp);
+                               ldap_extended_operation(ld, LDAP_EXOP_X_CANCEL,
+                                               msgidvalp, NULL, NULL, &cancel_msgid);
+                               nresponses_psearch = -1;
+                       }
                }
 
                ldap_msgfree( res );
        }
 
+done:
        if ( rc == -1 ) {
                ldap_perror( ld, "ldap_result" );
                return( rc );
        }
 
-done:
-       if ( pageSize != 0 ) { 
-               npagedresponses = npagedresponses + nresponses;
-               npagedentries = npagedentries + nentries;
-               npagedreferences = npagedreferences + nreferences;
-               npagedextended = npagedextended + nextended;
-               npagedpartial = npagedpartial + npartial;
+       ldap_msgfree( res );
+#ifdef LDAP_CONTROL_PAGEDRESULTS
+       if ( pagedResults ) { 
+               npagedresponses += nresponses;
+               npagedentries += nentries;
+               npagedextended += nextended;
+               npagedpartial += npartial;
+               npagedreferences += nreferences;
                if ( ( morePagedResults == 0 ) && ( ldif < 2 ) ) {
-                       printf( "\n# numResponses: %d\n", npagedresponses );
-                       if( nentries ) printf( "# numEntries: %d\n", npagedentries );
-                       if( nextended ) printf( "# numExtended: %d\n", npagedextended );
-                       if( npartial ) printf( "# numPartial: %d\n", npagedpartial );
-                       if( nreferences ) printf( "# numReferences: %d\n", npagedreferences );
+                       printf( _("\n# numResponses: %d\n"), npagedresponses );
+                       if( npagedentries ) printf( _("# numEntries: %d\n"), npagedentries );
+                       if( npagedextended ) printf( _("# numExtended: %d\n"), npagedextended );
+                       if( npagedpartial ) printf( _("# numPartial: %d\n"), npagedpartial );
+                       if( npagedreferences ) printf( _("# numReferences: %d\n"), npagedreferences );
                }
-       } else if ( ldif < 2 ) {
-               printf( "\n# numResponses: %d\n", nresponses );
-               if( nentries ) printf( "# numEntries: %d\n", nentries );
-               if( nextended ) printf( "# numExtended: %d\n", nextended );
-               if( npartial ) printf( "# numPartial: %d\n", npartial );
-               if( nreferences ) printf( "# numReferences: %d\n", nreferences );
+       } else
+#endif
+       if ( ldif < 2 ) {
+               printf( _("\n# numResponses: %d\n"), nresponses );
+               if( nentries ) printf( _("# numEntries: %d\n"), nentries );
+               if( nextended ) printf( _("# numExtended: %d\n"), nextended );
+               if( npartial ) printf( _("# numPartial: %d\n"), npartial );
+               if( nreferences ) printf( _("# numReferences: %d\n"), nreferences );
        }
 
        return( rc );
 }
 
-#if 1
-/* This is the original version, the old way of doing things. */
-static void
-print_entry(
-       LDAP    *ld,
-       LDAPMessage     *entry,
-       int             attrsonly)
-{
-       char            *a, *dn, *ufn;
-       char    tmpfname[ 256 ];
-       char    url[ 256 ];
-       int                     i, rc;
-       BerElement              *ber = NULL;
-       struct berval   **bvals;
-       LDAPControl **ctrls = NULL;
-       FILE            *tmpfp;
-
-       dn = ldap_get_dn( ld, entry );
-       ufn = NULL;
-
-       if ( ldif < 2 ) {
-               ufn = ldap_dn2ufn( dn );
-               write_ldif( LDIF_PUT_COMMENT, NULL, ufn, ufn ? strlen( ufn ) : 0 );
-       }
-       write_ldif( LDIF_PUT_VALUE, "dn", dn, dn ? strlen( dn ) : 0);
-
-       rc = ldap_get_entry_controls( ld, entry, &ctrls );
-
-       if( rc != LDAP_SUCCESS ) {
-               fprintf(stderr, "print_entry: %d\n", rc );
-               ldap_perror( ld, "ldap_get_entry_controls" );
-               exit( EXIT_FAILURE );
-       }
-
-       if( ctrls ) {
-               print_ctrls( ctrls );
-               ldap_controls_free( ctrls );
-       }
-
-       if ( includeufn ) {
-               if( ufn == NULL ) {
-                       ufn = ldap_dn2ufn( dn );
-               }
-               write_ldif( LDIF_PUT_VALUE, "ufn", ufn, ufn ? strlen( ufn ) : 0 );
-       }
-
-       if( ufn != NULL ) ldap_memfree( ufn );
-       ldap_memfree( dn );
-
-       for ( a = ldap_first_attribute( ld, entry, &ber ); a != NULL;
-               a = ldap_next_attribute( ld, entry, ber ) )
-       {
-               if ( attrsonly ) {
-                       write_ldif( LDIF_PUT_NOVALUE, a, NULL, 0 );
-
-               } else if (( bvals = ldap_get_values_len( ld, entry, a )) != NULL ) {
-                       for ( i = 0; bvals[i] != NULL; i++ ) {
-                               if ( vals2tmp > 1 || ( vals2tmp
-                                       && ldif_is_not_printable( bvals[i]->bv_val, bvals[i]->bv_len ) ))
-                               {
-                                       int tmpfd;
-                                       /* write value to file */
-                                       snprintf( tmpfname, sizeof tmpfname,
-                                               "%s" LDAP_DIRSEP "ldapsearch-%s-XXXXXX",
-                                               tmpdir, a );
-                                       tmpfp = NULL;
-
-                                       tmpfd = mkstemp( tmpfname );
-
-                                       if ( tmpfd < 0  ) {
-                                               perror( tmpfname );
-                                               continue;
-                                       }
-
-                                       if (( tmpfp = fdopen( tmpfd, "w")) == NULL ) {
-                                               perror( tmpfname );
-                                               continue;
-                                       }
-
-                                       if ( fwrite( bvals[ i ]->bv_val,
-                                               bvals[ i ]->bv_len, 1, tmpfp ) == 0 )
-                                       {
-                                               perror( tmpfname );
-                                               fclose( tmpfp );
-                                               continue;
-                                       }
-
-                                       fclose( tmpfp );
-
-                                       snprintf( url, sizeof url, "%s%s", urlpre,
-                                               &tmpfname[strlen(tmpdir) + sizeof(LDAP_DIRSEP) - 1] );
-
-                                       urlize( url );
-                                       write_ldif( LDIF_PUT_URL, a, url, strlen( url ));
-
-                               } else {
-                                       write_ldif( LDIF_PUT_VALUE, a,
-                                               bvals[ i ]->bv_val, bvals[ i ]->bv_len );
-                               }
-                       }
-                       ber_bvecfree( bvals );
-               }
-       }
-
-       if( ber != NULL ) {
-               ber_free( ber, 0 );
-       }
-}
-#else
 /* This is the proposed new way of doing things.
  * It is more efficient, but the API is non-standard.
  */
@@ -1576,10 +1187,9 @@ print_entry(
        }
        write_ldif( LDIF_PUT_VALUE, "dn", bv.bv_val, bv.bv_len );
 
-       rc = ldap_int_get_controls( ber, &ctrls );
-
+       rc = ldap_get_entry_controls( ld, entry, &ctrls );
        if( rc != LDAP_SUCCESS ) {
-               fprintf(stderr, "print_entry: %d\n", rc );
+               fprintf(stderr, _("print_entry: %d\n"), rc );
                ldap_perror( ld, "ldap_get_entry_controls" );
                exit( EXIT_FAILURE );
        }
@@ -1609,10 +1219,10 @@ print_entry(
                if ( attrsonly ) {
                        write_ldif( LDIF_PUT_NOVALUE, bv.bv_val, NULL, 0 );
 
-               } else {
+               } else if ( bvals ) {
                        for ( i = 0; bvals[i].bv_val != NULL; i++ ) {
-                               if ( vals2tmp > 1 || ( vals2tmp
-                                       && ldif_is_not_printable( bvals[i].bv_val, bvals[i].bv_len ) ))
+                               if ( vals2tmp > 1 || ( vals2tmp &&
+                                       ldif_is_not_printable( bvals[i].bv_val, bvals[i].bv_len )))
                                {
                                        int tmpfd;
                                        /* write value to file */
@@ -1662,7 +1272,6 @@ print_entry(
                ber_free( ber, 0 );
        }
 }
-#endif
 
 static void print_reference(
        LDAP *ld,
@@ -1673,7 +1282,7 @@ static void print_reference(
        LDAPControl **ctrls;
 
        if( ldif < 2 ) {
-               printf("# search reference\n");
+               printf(_("# search reference\n"));
        }
 
        rc = ldap_parse_reference( ld, reference, &refs, &ctrls, 0 );
@@ -1707,7 +1316,7 @@ static void print_extended(
        struct berval *retdata = NULL;
 
        if( ldif < 2 ) {
-               printf("# extended result response\n");
+               printf(_("# extended result response\n"));
        }
 
        rc = ldap_parse_extended_result( ld, extended,
@@ -1745,14 +1354,14 @@ static void print_partial(
        LDAPControl **ctrls = NULL;
 
        if( ldif < 2 ) {
-               printf("# extended partial response\n");
+               printf(_("# extended partial response\n"));
        }
 
-       rc = ldap_parse_extended_partial( ld, partial,
+       rc = ldap_parse_intermediate( ld, partial,
                &retoid, &retdata, &ctrls, 0 );
 
        if( rc != LDAP_SUCCESS ) {
-               ldap_perror(ld, "ldap_parse_extended_partial");
+               ldap_perror(ld, "ldap_parse_intermediate");
                exit( EXIT_FAILURE );
        }
 
@@ -1791,10 +1400,10 @@ static int print_result(
 
        if( search ) {
                if ( ldif < 2 ) {
-                       printf("# search result\n");
+                       printf(_("# search result\n"));
                }
                if ( ldif < 1 ) {
-                       printf("%s: %d\n", "search", ldap_msgid(result) );
+                       printf("%s: %d\n", _("search"), ldap_msgid(result) );
                }
        }
 
@@ -1808,29 +1417,33 @@ static int print_result(
 
 
        if( !ldif ) {
-               printf( "result: %d %s\n", err, ldap_err2string(err) );
+               printf( _("result: %d %s\n"), err, ldap_err2string(err) );
 
        } else if ( err != LDAP_SUCCESS ) {
                fprintf( stderr, "%s (%d)\n", ldap_err2string(err), err );
        }
 
-       if( matcheddn && *matcheddn ) {
+       if( matcheddn ) {
+               if( *matcheddn ) {
                if( !ldif ) {
                        write_ldif( LDIF_PUT_VALUE,
                                "matchedDN", matcheddn, strlen(matcheddn) );
                } else {
-                       fprintf( stderr, "Matched DN: %s\n", matcheddn );
+                       fprintf( stderr, _("Matched DN: %s\n"), matcheddn );
+               }
                }
 
                ber_memfree( matcheddn );
        }
 
-       if( text && *text ) {
+       if( text ) {
+               if( *text ) {
                if( !ldif ) {
                        write_ldif( LDIF_PUT_TEXT, "text",
                                text, strlen(text) );
                } else {
-                       fprintf( stderr, "Additional information: %s\n", text );
+                       fprintf( stderr, _("Additional information: %s\n"), text );
+               }
                }
 
                ber_memfree( text );
@@ -1842,7 +1455,7 @@ static int print_result(
                        if( !ldif ) {
                                write_ldif( LDIF_PUT_VALUE, "ref", refs[i], strlen(refs[i]) );
                        } else {
-                               fprintf( stderr, "Referral: %s\n", refs[i] );
+                               fprintf( stderr, _("Referral: %s\n"), refs[i] );
                        }
                }
 
@@ -1883,7 +1496,8 @@ static void print_ctrls(
                        b64->bv_val = ber_memalloc( b64->bv_len + 1 );
 
                        b64->bv_len = lutil_b64_ntop(
-                               ctrls[i]->ldctl_value.bv_val, ctrls[i]->ldctl_value.bv_len,
+                               (unsigned char *) ctrls[i]->ldctl_value.bv_val,
+                               ctrls[i]->ldctl_value.bv_len,
                                b64->bv_val, b64->bv_len );
                }
 
@@ -1932,6 +1546,7 @@ write_ldif( int type, char *name, char *value, ber_len_t vallen )
 }
 
 
+#ifdef LDAP_CONTROL_PAGEDRESULTS
 static int 
 parse_page_control(
        LDAP *ld,
@@ -1944,8 +1559,6 @@ parse_page_control(
        LDAPControl *ctrlp = NULL;
        BerElement *ber;
        ber_tag_t tag;
-       struct berval servercookie = { 0, NULL };
-
 
        rc = ldap_parse_result( ld, result,
                &err, NULL, NULL, NULL, &ctrl, 0 );
@@ -1959,39 +1572,51 @@ parse_page_control(
                fprintf( stderr, "%s (%d)\n", ldap_err2string(err), err );
        }
 
-       if( ctrl ) {
+       if ( ctrl ) {
+               /* There might be others, e.g. ppolicy... */
+               ctrlp = ldap_find_control( LDAP_CONTROL_PAGEDRESULTS, ctrl );
+       }
+
+       if ( ctrlp ) {
                /* Parse the control value
                 * searchResult ::= SEQUENCE {
                 *              size    INTEGER (0..maxInt),
                 *                              -- result set size estimate from server - unused
                 *              cookie  OCTET STRING
+                * }
                 */
                ctrlp = *ctrl;
                ber = ber_init( &ctrlp->ldctl_value );
                if ( ber == NULL ) {
-                       fprintf( stderr, "Internal error.\n" );
+                       fprintf( stderr, _("Internal error.\n") );
                        return EXIT_FAILURE;
                }
 
-               tag = ber_scanf( ber, "{im}", &entriesLeft, &servercookie );
-               ber_dupbv( cookie, &servercookie );
+               tag = ber_scanf( ber, "{io}", &entriesLeft, cookie );
                (void) ber_free( ber, 1 );
 
                if( tag == LBER_ERROR ) {
-                       fprintf( stderr, "Paged results response control could not be decoded.\n" );
+                       fprintf( stderr,
+                               _("Paged results response control could not be decoded.\n") );
                        return EXIT_FAILURE;
                }
 
                if( entriesLeft < 0 ) {
-                       fprintf( stderr, "Invalid entries estimate in paged results response.\n" );
+                       fprintf( stderr,
+                               _("Invalid entries estimate in paged results response.\n") );
                        return EXIT_FAILURE;
                }
 
+               if ( cookie->bv_len == 0 ) {
+                       morePagedResults = 0;
+               }
 
                ldap_controls_free( ctrl );
+
        } else {
                morePagedResults = 0;
        }
 
        return err;
 }
+#endif