]> git.sur5r.net Git - openldap/blob - clients/tools/ldapsearch.c
c56c82956f568401282a450ab73d77de4d6ec623
[openldap] / clients / tools / ldapsearch.c
1 /* ldapsearch -- a tool for searching LDAP directories */
2 /* $OpenLDAP$ */
3 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
4  *
5  * Copyright 1998-2007 The OpenLDAP Foundation.
6  * Portions Copyright 1998-2003 Kurt D. Zeilenga.
7  * Portions Copyright 1998-2001 Net Boolean Incorporated.
8  * Portions Copyright 2001-2003 IBM Corporation.
9  * All rights reserved.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted only as authorized by the OpenLDAP
13  * Public License.
14  *
15  * A copy of this license is available in the file LICENSE in the
16  * top-level directory of the distribution or, alternatively, at
17  * <http://www.OpenLDAP.org/license.html>.
18  */
19 /* Portions Copyright (c) 1992-1996 Regents of the University of Michigan.
20  * All rights reserved.
21  *
22  * Redistribution and use in source and binary forms are permitted
23  * provided that this notice is preserved and that due credit is given
24  * to the University of Michigan at Ann Arbor.  The name of the
25  * University may not be used to endorse or promote products derived
26  * from this software without specific prior written permission.  This
27  * software is provided ``as is'' without express or implied warranty.
28  */
29 /* ACKNOWLEDGEMENTS:
30  * This work was originally developed by the University of Michigan
31  * (as part of U-MICH LDAP).  Additional significant contributors
32  * include:
33  *   Jong Hyuk Choi
34  *   Lynn Moss
35  *   Mikhail Sahalaev
36  *   Kurt D. Zeilenga
37  */
38
39 #include "portable.h"
40
41 #include <stdio.h>
42
43 #include <ac/stdlib.h>
44
45 #include <ac/ctype.h>
46 #include <ac/string.h>
47 #include <ac/unistd.h>
48 #include <ac/errno.h>
49 #include <sys/stat.h>
50
51 #include <ac/signal.h>
52
53 #ifdef HAVE_FCNTL_H
54 #include <fcntl.h>
55 #endif
56 #ifdef HAVE_SYS_TYPES_H
57 #include <sys/types.h>
58 #endif
59 #ifdef HAVE_IO_H
60 #include <io.h>
61 #endif
62
63 #include <ldap.h>
64
65 #include "ldif.h"
66 #include "lutil.h"
67 #include "lutil_ldap.h"
68 #include "ldap_defaults.h"
69 #include "ldap_log.h"
70 #include "ldap_pvt.h"
71
72 #include "common.h"
73
74
75 static int scope = LDAP_SCOPE_SUBTREE;
76 static int deref = -1;
77 static int attrsonly;
78 static int timelimit = -1;
79 static int sizelimit = -1;
80
81 static char *def_tmpdir;
82 static char *def_urlpre;
83
84 #if defined(__CYGWIN__) || defined(__MINGW32__)
85 /* Turn off commandline globbing, otherwise you cannot search for
86  * attribute '*'
87  */
88 int _CRT_glob = 0;
89 #endif
90
91 void
92 usage( void )
93 {
94         fprintf( stderr, _("usage: %s [options] [filter [attributes...]]\nwhere:\n"), prog);
95         fprintf( stderr, _("  filter\tRFC-2254 compliant LDAP search filter\n"));
96         fprintf( stderr, _("  attributes\twhitespace-separated list of attribute descriptions\n"));
97         fprintf( stderr, _("    which may include:\n"));
98         fprintf( stderr, _("      1.1   no attributes\n"));
99         fprintf( stderr, _("      *     all user attributes\n"));
100         fprintf( stderr, _("      +     all operational attributes\n"));
101
102
103         fprintf( stderr, _("Search options:\n"));
104         fprintf( stderr, _("  -a deref   one of never (default), always, search, or find\n"));
105         fprintf( stderr, _("  -A         retrieve attribute names only (no values)\n"));
106         fprintf( stderr, _("  -b basedn  base dn for search\n"));
107         fprintf( stderr, _("  -E [!]<ext>[=<extparam>] search extensions (! indicates criticality)\n"));
108 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
109         fprintf( stderr, _("             [!]domainScope              (domain scope)\n"));
110 #endif
111         fprintf( stderr, _("             [!]mv=<filter>              (matched values filter)\n"));
112 #ifdef LDAP_CONTROL_PAGEDRESULTS
113         fprintf( stderr, _("             [!]pr=<size>[/prompt|noprompt]   (paged results/prompt)\n"));
114 #endif
115 #ifdef LDAP_CONTROL_SUBENTRIES
116         fprintf( stderr, _("             [!]subentries[=true|false]  (subentries)\n"));
117 #endif
118         fprintf( stderr, _("             [!]sync=ro[/<cookie>]            (LDAP Sync refreshOnly)\n"));
119         fprintf( stderr, _("                     rp[/<cookie>][/<slimit>] (LDAP Sync refreshAndPersist)\n"));
120         fprintf( stderr, _("  -F prefix  URL prefix for files (default: %s)\n"), def_urlpre);
121         fprintf( stderr, _("  -l limit   time limit (in seconds, or \"none\" or \"max\") for search\n"));
122         fprintf( stderr, _("  -L         print responses in LDIFv1 format\n"));
123         fprintf( stderr, _("  -LL        print responses in LDIF format without comments\n"));
124         fprintf( stderr, _("  -LLL       print responses in LDIF format without comments\n"));
125         fprintf( stderr, _("             and version\n"));
126 #ifdef LDAP_SCOPE_SUBORDINATE
127         fprintf( stderr, _("  -s scope   one of base, one, sub or children (search scope)\n"));
128 #else /* ! LDAP_SCOPE_SUBORDINATE */
129         fprintf( stderr, _("  -s scope   one of base, one, or sub (search scope)\n"));
130 #endif /* ! LDAP_SCOPE_SUBORDINATE */
131         fprintf( stderr, _("  -S attr    sort the results by attribute `attr'\n"));
132         fprintf( stderr, _("  -t         write binary values to files in temporary directory\n"));
133         fprintf( stderr, _("  -tt        write all values to files in temporary directory\n"));
134         fprintf( stderr, _("  -T path    write files to directory specified by path (default: %s)\n"), def_tmpdir);
135         fprintf( stderr, _("  -u         include User Friendly entry names in the output\n"));
136         fprintf( stderr, _("  -z limit   size limit (in entries, or \"none\" or \"max\") for search\n"));
137         tool_common_usage();
138         exit( EXIT_FAILURE );
139 }
140
141 static void print_entry LDAP_P((
142         LDAP    *ld,
143         LDAPMessage     *entry,
144         int             attrsonly));
145
146 static void print_reference(
147         LDAP *ld,
148         LDAPMessage *reference );
149
150 static void print_extended(
151         LDAP *ld,
152         LDAPMessage *extended );
153
154 static void print_partial(
155         LDAP *ld,
156         LDAPMessage *partial );
157
158 static int print_result(
159         LDAP *ld,
160         LDAPMessage *result,
161         int search );
162
163 static void print_ctrls(
164         LDAPControl **ctrls );
165
166 static int write_ldif LDAP_P((
167         int type,
168         char *name,
169         char *value,
170         ber_len_t vallen ));
171
172 static int dosearch LDAP_P((
173         LDAP    *ld,
174         char    *base,
175         int             scope,
176         char    *filtpatt,
177         char    *value,
178         char    **attrs,
179         int             attrsonly,
180         LDAPControl **sctrls,
181         LDAPControl **cctrls,
182         struct timeval *timeout,
183         int     sizelimit ));
184
185 static char *tmpdir = NULL;
186 static char *urlpre = NULL;
187 static char     *base = NULL;
188 static char     *sortattr = NULL;
189 static int  includeufn, vals2tmp = 0, ldif = 0;
190
191 static int subentries = 0, valuesReturnFilter = 0;
192 static char     *vrFilter = NULL;
193
194 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
195 static int domainScope = 0;
196 #endif
197
198 static int ldapsync = 0;
199 static struct berval sync_cookie = { 0, NULL };
200 static int sync_slimit = -1;
201
202 #ifdef LDAP_CONTROL_PAGEDRESULTS
203 static int pagedResults = 0;
204 static int pagePrompt = 1;
205 static ber_int_t pageSize = 0;
206 static ber_int_t entriesLeft = 0;
207 static ber_int_t morePagedResults = 1;
208 static struct berval page_cookie = { 0, NULL };
209 static int npagedresponses;
210 static int npagedentries;
211 static int npagedreferences;
212 static int npagedextended;
213 static int npagedpartial;
214
215 static int parse_page_control(
216         LDAP *ld,
217         LDAPMessage *result,
218         struct berval *cookie );
219 #endif
220
221 static void
222 urlize(char *url)
223 {
224         char *p;
225
226         if (*LDAP_DIRSEP != '/') {
227                 for (p = url; *p; p++) {
228                         if (*p == *LDAP_DIRSEP)
229                                 *p = '/';
230                 }
231         }
232 }
233
234
235 const char options[] = "a:Ab:cE:F:l:Ls:S:tT:uz:"
236         "Cd:D:e:f:h:H:IkKMnO:p:P:QR:U:vVw:WxX:y:Y:Z";
237
238 int
239 handle_private_option( int i )
240 {
241         int crit, ival;
242         char *control, *cvalue, *next;
243         switch ( i ) {
244         case 'a':       /* set alias deref option */
245                 if ( strcasecmp( optarg, "never" ) == 0 ) {
246                         deref = LDAP_DEREF_NEVER;
247                 } else if ( strncasecmp( optarg, "search", sizeof("search")-1 ) == 0 ) {
248                         deref = LDAP_DEREF_SEARCHING;
249                 } else if ( strncasecmp( optarg, "find", sizeof("find")-1 ) == 0 ) {
250                         deref = LDAP_DEREF_FINDING;
251                 } else if ( strcasecmp( optarg, "always" ) == 0 ) {
252                         deref = LDAP_DEREF_ALWAYS;
253                 } else {
254                         fprintf( stderr,
255                                 _("alias deref should be never, search, find, or always\n") );
256                         usage();
257                 }
258                 break;
259         case 'A':       /* retrieve attribute names only -- no values */
260                 ++attrsonly;
261                 break;
262         case 'b': /* search base */
263                 base = ber_strdup( optarg );
264                 break;
265         case 'E': /* search extensions */
266                 if( protocol == LDAP_VERSION2 ) {
267                         fprintf( stderr, _("%s: -E incompatible with LDAPv%d\n"),
268                                 prog, protocol );
269                         exit( EXIT_FAILURE );
270                 }
271
272                 /* should be extended to support comma separated list of
273                  *      [!]key[=value] parameters, e.g.  -E !foo,bar=567
274                  */
275
276                 crit = 0;
277                 cvalue = NULL;
278                 if( optarg[0] == '!' ) {
279                         crit = 1;
280                         optarg++;
281                 }
282
283                 control = ber_strdup( optarg );
284                 if ( (cvalue = strchr( control, '=' )) != NULL ) {
285                         *cvalue++ = '\0';
286                 }
287
288                 if ( strcasecmp( control, "mv" ) == 0 ) {
289                         /* ValuesReturnFilter control */
290                         if( valuesReturnFilter ) {
291                                 fprintf( stderr,
292                                         _("ValuesReturnFilter previously specified\n"));
293                                 exit( EXIT_FAILURE );
294                         }
295                         valuesReturnFilter= 1 + crit;
296
297                         if ( cvalue == NULL ) {
298                                 fprintf( stderr,
299                                         _("missing filter in ValuesReturnFilter control\n"));
300                                 exit( EXIT_FAILURE );
301                         }
302
303                         vrFilter = cvalue;
304                         protocol = LDAP_VERSION3;
305
306 #ifdef LDAP_CONTROL_PAGEDRESULTS
307                 } else if ( strcasecmp( control, "pr" ) == 0 ) {
308                         int num, tmp;
309                         /* PagedResults control */
310                         if ( pagedResults != 0 ) {
311                                 fprintf( stderr,
312                                         _("PagedResultsControl previously specified\n") );
313                                 exit( EXIT_FAILURE );
314                         }
315
316                         if( cvalue != NULL ) {
317                                 char *promptp;
318
319                                 promptp = strchr( cvalue, '/' );
320                                 if ( promptp != NULL ) {
321                                         *promptp++ = '\0';
322                                         if ( strcasecmp( promptp, "prompt" ) == 0 ) {
323                                                 pagePrompt = 1;
324                                         } else if ( strcasecmp( promptp, "noprompt" ) == 0) {
325                                                 pagePrompt = 0;
326                                         } else {
327                                                 fprintf( stderr,
328                                                         _("Invalid value for PagedResultsControl,"
329                                                         " %s/%s.\n"), cvalue, promptp );
330                                                 exit( EXIT_FAILURE );
331                                         }
332                                 }
333                                 num = sscanf( cvalue, "%d", &tmp );
334                                 if ( num != 1 ) {
335                                         fprintf( stderr,
336                                                 _("Invalid value for PagedResultsControl, %s.\n"),
337                                                 cvalue );
338                                         exit( EXIT_FAILURE );
339                                 }
340                         } else {
341                                 fprintf(stderr, _("Invalid value for PagedResultsControl.\n"));
342                                 exit( EXIT_FAILURE );
343                         }
344                         pageSize = (ber_int_t) tmp;
345                         pagedResults = 1 + crit;
346
347 #endif
348 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
349                 } else if ( strcasecmp( control, "domainScope" ) == 0 ) {
350                         if( domainScope ) {
351                                 fprintf( stderr,
352                                         _("domainScope control previously specified\n"));
353                                 exit( EXIT_FAILURE );
354                         }
355                         if( cvalue != NULL ) {
356                                 fprintf( stderr,
357                                  _("domainScope: no control value expected\n") );
358                                 usage();
359                         }
360
361                         domainScope = 1 + crit;
362 #endif
363
364 #ifdef LDAP_CONTROL_SUBENTRIES
365                 } else if ( strcasecmp( control, "subentries" ) == 0 ) {
366                         if( subentries ) {
367                                 fprintf( stderr,
368                                         _("subentries control previously specified\n"));
369                                 exit( EXIT_FAILURE );
370                         }
371                         if( cvalue == NULL || strcasecmp( cvalue, "true") == 0 ) {
372                                 subentries = 2;
373                         } else if ( strcasecmp( cvalue, "false") == 0 ) {
374                                 subentries = 1;
375                         } else {
376                                 fprintf( stderr,
377                                         _("subentries control value \"%s\" invalid\n"),
378                                         cvalue );
379                                 exit( EXIT_FAILURE );
380                         }
381                         if( crit ) subentries *= -1;
382 #endif
383
384                 } else if ( strcasecmp( control, "sync" ) == 0 ) {
385                         char *cookiep;
386                         char *slimitp;
387                         if ( ldapsync ) {
388                                 fprintf( stderr, _("sync control previously specified\n") );
389                                 exit( EXIT_FAILURE );
390                         }
391                         if ( cvalue == NULL ) {
392                                 fprintf( stderr, _("missing specification of sync control\n"));
393                                 exit( EXIT_FAILURE );
394                         }
395                         if ( strncasecmp( cvalue, "ro", 2 ) == 0 ) {
396                                 ldapsync = LDAP_SYNC_REFRESH_ONLY;
397                                 cookiep = strchr( cvalue, '/' );
398                                 if ( cookiep != NULL ) {
399                                         cookiep++;
400                                         if ( *cookiep != '\0' ) {
401                                                 ber_str2bv( cookiep, 0, 0, &sync_cookie );
402                                         }
403                                 }
404                         } else if ( strncasecmp( cvalue, "rp", 2 ) == 0 ) {
405                                 ldapsync = LDAP_SYNC_REFRESH_AND_PERSIST;
406                                 cookiep = strchr( cvalue, '/' );
407                                 if ( cookiep != NULL ) {
408                                         *cookiep++ = '\0';      
409                                         cvalue = cookiep;
410                                 }
411                                 slimitp = strchr( cvalue, '/' );
412                                 if ( slimitp != NULL ) {
413                                         *slimitp++ = '\0';
414                                 }
415                                 if ( cookiep != NULL && *cookiep != '\0' )
416                                         ber_str2bv( cookiep, 0, 0, &sync_cookie );
417                                 if ( slimitp != NULL && *slimitp != '\0' ) {
418                                         ival = strtol( slimitp, &next, 10 );
419                                         if ( next == NULL || next[0] != '\0' ) {
420                                                 fprintf( stderr, _("Unable to parse sync control value \"%s\"\n"), slimitp );
421                                                 exit( EXIT_FAILURE );
422                                         }
423                                         sync_slimit = ival;
424                                 }
425                         } else {
426                                 fprintf( stderr, _("sync control value \"%s\" invalid\n"),
427                                         cvalue );
428                                 exit( EXIT_FAILURE );
429                         }
430                         if ( crit ) ldapsync *= -1;
431
432                 } else {
433                         fprintf( stderr, _("Invalid search extension name: %s\n"),
434                                 control );
435                         usage();
436                 }
437                 break;
438         case 'F':       /* uri prefix */
439                 if( urlpre ) free( urlpre );
440                 urlpre = strdup( optarg );
441                 break;
442         case 'l':       /* time limit */
443                 if ( strcasecmp( optarg, "none" ) == 0 ) {
444                         timelimit = 0;
445
446                 } else if ( strcasecmp( optarg, "max" ) == 0 ) {
447                         timelimit = LDAP_MAXINT;
448
449                 } else {
450                         ival = strtol( optarg, &next, 10 );
451                         if ( next == NULL || next[0] != '\0' ) {
452                                 fprintf( stderr,
453                                         _("Unable to parse time limit \"%s\"\n"), optarg );
454                                 exit( EXIT_FAILURE );
455                         }
456                         timelimit = ival;
457                 }
458                 if( timelimit < 0 || timelimit > LDAP_MAXINT ) {
459                         fprintf( stderr, _("%s: invalid timelimit (%d) specified\n"),
460                                 prog, timelimit );
461                         exit( EXIT_FAILURE );
462                 }
463                 break;
464         case 'L':       /* print entries in LDIF format */
465                 ++ldif;
466                 break;
467         case 's':       /* search scope */
468                 if ( strncasecmp( optarg, "base", sizeof("base")-1 ) == 0 ) {
469                         scope = LDAP_SCOPE_BASE;
470                 } else if ( strncasecmp( optarg, "one", sizeof("one")-1 ) == 0 ) {
471                         scope = LDAP_SCOPE_ONELEVEL;
472 #ifdef LDAP_SCOPE_SUBORDINATE
473                 } else if (( strcasecmp( optarg, "subordinate" ) == 0 )
474                         || ( strcasecmp( optarg, "children" ) == 0 ))
475                 {
476                         scope = LDAP_SCOPE_SUBORDINATE;
477 #endif
478                 } else if ( strncasecmp( optarg, "sub", sizeof("sub")-1 ) == 0 ) {
479                         scope = LDAP_SCOPE_SUBTREE;
480                 } else {
481                         fprintf( stderr, _("scope should be base, one, or sub\n") );
482                         usage();
483                 }
484                 break;
485         case 'S':       /* sort attribute */
486                 sortattr = strdup( optarg );
487                 break;
488         case 't':       /* write attribute values to TMPDIR files */
489                 ++vals2tmp;
490                 break;
491         case 'T':       /* tmpdir */
492                 if( tmpdir ) free( tmpdir );
493                 tmpdir = strdup( optarg );
494                 break;
495         case 'u':       /* include UFN */
496                 ++includeufn;
497                 break;
498         case 'z':       /* size limit */
499                 if ( strcasecmp( optarg, "none" ) == 0 ) {
500                         sizelimit = 0;
501
502                 } else if ( strcasecmp( optarg, "max" ) == 0 ) {
503                         sizelimit = LDAP_MAXINT;
504
505                 } else {
506                         ival = strtol( optarg, &next, 10 );
507                         if ( next == NULL || next[0] != '\0' ) {
508                                 fprintf( stderr,
509                                         _("Unable to parse size limit \"%s\"\n"), optarg );
510                                 exit( EXIT_FAILURE );
511                         }
512                         sizelimit = ival;
513                 }
514                 if( sizelimit < 0 || sizelimit > LDAP_MAXINT ) {
515                         fprintf( stderr, _("%s: invalid sizelimit (%d) specified\n"),
516                                 prog, sizelimit );
517                         exit( EXIT_FAILURE );
518                 }
519                 break;
520         default:
521                 return 0;
522         }
523         return 1;
524 }
525
526
527 static void
528 private_conn_setup( LDAP *ld )
529 {
530         if (deref != -1 &&
531                 ldap_set_option( ld, LDAP_OPT_DEREF, (void *) &deref )
532                         != LDAP_OPT_SUCCESS )
533         {
534                 fprintf( stderr, _("Could not set LDAP_OPT_DEREF %d\n"), deref );
535                 exit( EXIT_FAILURE );
536         }
537         if (timelimit > 0 &&
538                 ldap_set_option( ld, LDAP_OPT_TIMELIMIT, (void *) &timelimit )
539                         != LDAP_OPT_SUCCESS )
540         {
541                 fprintf( stderr,
542                         _("Could not set LDAP_OPT_TIMELIMIT %d\n"), timelimit );
543                 exit( EXIT_FAILURE );
544         }
545         if (sizelimit > 0 &&
546                 ldap_set_option( ld, LDAP_OPT_SIZELIMIT, (void *) &sizelimit )
547                         != LDAP_OPT_SUCCESS )
548         {
549                 fprintf( stderr,
550                         _("Could not set LDAP_OPT_SIZELIMIT %d\n"), sizelimit );
551                 exit( EXIT_FAILURE );
552         }
553 }
554
555 int
556 main( int argc, char **argv )
557 {
558         char            *filtpattern, **attrs = NULL, line[BUFSIZ];
559         FILE            *fp = NULL;
560         int                     rc, i, first;
561         LDAP            *ld = NULL;
562         BerElement      *seber = NULL, *vrber = NULL, *prber = NULL;
563
564         BerElement      *syncber = NULL;
565         struct berval   *syncbvalp = NULL;
566
567         tool_init();
568
569 #ifdef LDAP_CONTROL_PAGEDRESULTS
570         npagedresponses = npagedentries = npagedreferences =
571                 npagedextended = npagedpartial = 0;
572 #endif
573
574         prog = lutil_progname( "ldapsearch", argc, argv );
575
576         if((def_tmpdir = getenv("TMPDIR")) == NULL &&
577            (def_tmpdir = getenv("TMP")) == NULL &&
578            (def_tmpdir = getenv("TEMP")) == NULL )
579         {
580                 def_tmpdir = LDAP_TMPDIR;
581         }
582
583         if ( !*def_tmpdir )
584                 def_tmpdir = LDAP_TMPDIR;
585
586         def_urlpre = malloc( sizeof("file:////") + strlen(def_tmpdir) );
587
588         if( def_urlpre == NULL ) {
589                 perror( "malloc" );
590                 return EXIT_FAILURE;
591         }
592
593         sprintf( def_urlpre, "file:///%s/",
594                 def_tmpdir[0] == *LDAP_DIRSEP ? &def_tmpdir[1] : def_tmpdir );
595
596         urlize( def_urlpre );
597
598         tool_args( argc, argv );
599
600         if (( argc - optind < 1 ) ||
601                 ( *argv[optind] != '(' /*')'*/ &&
602                 ( strchr( argv[optind], '=' ) == NULL ) ) )
603         {
604                 filtpattern = "(objectclass=*)";
605         } else {
606                 filtpattern = argv[optind++];
607         }
608
609         if ( argv[optind] != NULL ) {
610                 attrs = &argv[optind];
611         }
612
613         if ( infile != NULL ) {
614                 int percent = 0;
615         
616                 if ( infile[0] == '-' && infile[1] == '\0' ) {
617                         fp = stdin;
618                 } else if (( fp = fopen( infile, "r" )) == NULL ) {
619                         perror( infile );
620                         return EXIT_FAILURE;
621                 }
622
623                 for( i=0 ; filtpattern[i] ; i++ ) {
624                         if( filtpattern[i] == '%' ) {
625                                 if( percent ) {
626                                         fprintf( stderr, _("Bad filter pattern \"%s\"\n"),
627                                                 filtpattern );
628                                         return EXIT_FAILURE;
629                                 }
630
631                                 percent++;
632
633                                 if( filtpattern[i+1] != 's' ) {
634                                         fprintf( stderr, _("Bad filter pattern \"%s\"\n"),
635                                                 filtpattern );
636                                         return EXIT_FAILURE;
637                                 }
638                         }
639                 }
640         }
641
642         if ( tmpdir == NULL ) {
643                 tmpdir = def_tmpdir;
644
645                 if ( urlpre == NULL )
646                         urlpre = def_urlpre;
647         }
648
649         if( urlpre == NULL ) {
650                 urlpre = malloc( sizeof("file:////") + strlen(tmpdir) );
651
652                 if( urlpre == NULL ) {
653                         perror( "malloc" );
654                         return EXIT_FAILURE;
655                 }
656
657                 sprintf( urlpre, "file:///%s/",
658                         tmpdir[0] == *LDAP_DIRSEP ? &tmpdir[1] : tmpdir );
659
660                 urlize( urlpre );
661         }
662
663         if ( debug )
664                 ldif_debug = debug;
665
666         ld = tool_conn_setup( 0, &private_conn_setup );
667
668         if ( pw_file || want_bindpw ) {
669                 if ( pw_file ) {
670                         rc = lutil_get_filed_password( pw_file, &passwd );
671                         if( rc ) return EXIT_FAILURE;
672                 } else {
673                         passwd.bv_val = getpassphrase( _("Enter LDAP Password: ") );
674                         passwd.bv_len = passwd.bv_val ? strlen( passwd.bv_val ) : 0;
675                 }
676         }
677
678         tool_bind( ld );
679
680 getNextPage:
681         if ( assertion || authzid || manageDSAit || noop
682 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
683                 || domainScope
684 #endif
685 #ifdef LDAP_CONTROL_PAGEDRESULTS
686                 || pagedResults
687 #endif
688 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
689                 || chaining
690 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
691                 || ldapsync
692                 || subentries || valuesReturnFilter )
693         {
694                 int err;
695                 int i=0;
696                 LDAPControl c[10];
697
698 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
699                 if ( domainScope ) {
700                         c[i].ldctl_oid = LDAP_CONTROL_X_DOMAIN_SCOPE;
701                         c[i].ldctl_value.bv_val = NULL;
702                         c[i].ldctl_value.bv_len = 0;
703                         c[i].ldctl_iscritical = domainScope > 1;
704                         i++;
705                 }
706 #endif
707
708 #ifdef LDAP_CONTROL_SUBENTRIES
709                 if ( subentries ) {
710                         if (( seber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
711                                 return EXIT_FAILURE;
712                         }
713
714                         err = ber_printf( seber, "b", abs(subentries) == 1 ? 0 : 1 );
715                         if ( err == -1 ) {
716                                 ber_free( seber, 1 );
717                                 fprintf( stderr, _("Subentries control encoding error!\n") );
718                                 return EXIT_FAILURE;
719                         }
720
721                         if ( ber_flatten2( seber, &c[i].ldctl_value, 0 ) == -1 ) {
722                                 return EXIT_FAILURE;
723                         }
724
725                         c[i].ldctl_oid = LDAP_CONTROL_SUBENTRIES;
726                         c[i].ldctl_iscritical = subentries < 1;
727                         i++;
728                 }
729 #endif
730
731                 if ( ldapsync ) {
732                         if (( syncber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
733                                 return EXIT_FAILURE;
734                         }
735
736                         if ( sync_cookie.bv_len == 0 ) {
737                                 err = ber_printf( syncber, "{e}", abs(ldapsync) );
738                         } else {
739                                 err = ber_printf( syncber, "{eO}", abs(ldapsync),
740                                                         &sync_cookie );
741                         }
742
743                         if ( err == LBER_ERROR ) {
744                                 ber_free( syncber, 1 );
745                                 fprintf( stderr, _("ldap sync control encoding error!\n") );
746                                 return EXIT_FAILURE;
747                         }
748
749                         if ( ber_flatten( syncber, &syncbvalp ) == LBER_ERROR ) {
750                                 return EXIT_FAILURE;
751                         }
752
753                         c[i].ldctl_oid = LDAP_CONTROL_SYNC;
754                         c[i].ldctl_value = (*syncbvalp);
755                         c[i].ldctl_iscritical = ldapsync < 0;
756                         i++;
757                 }
758
759                 if ( valuesReturnFilter ) {
760                 if (( vrber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
761                                 return EXIT_FAILURE;
762                         }
763
764                 if ( ( err = ldap_put_vrFilter( vrber, vrFilter ) ) == -1 ) {
765                                 ber_free( vrber, 1 );
766                                 fprintf( stderr, _("Bad ValuesReturnFilter: %s\n"), vrFilter );
767                                 return EXIT_FAILURE;
768                         }
769
770                         if ( ber_flatten2( vrber, &c[i].ldctl_value, 0 ) == -1 ) {
771                                 return EXIT_FAILURE;
772                         }
773
774                         c[i].ldctl_oid = LDAP_CONTROL_VALUESRETURNFILTER;
775                         c[i].ldctl_iscritical = valuesReturnFilter > 1;
776                         i++;
777                 }
778
779 #ifdef LDAP_CONTROL_PAGEDRESULTS
780                 if ( pagedResults ) {
781                         if (( prber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
782                                 return EXIT_FAILURE;
783                         }
784
785                         ber_printf( prber, "{iO}", pageSize, &page_cookie );
786                         if ( ber_flatten2( prber, &c[i].ldctl_value, 0 ) == -1 ) {
787                                 return EXIT_FAILURE;
788                         }
789                         if ( page_cookie.bv_val != NULL ) {
790                                 ber_memfree( page_cookie.bv_val );
791                                 page_cookie.bv_val = NULL;
792                         }
793                         
794                         c[i].ldctl_oid = LDAP_CONTROL_PAGEDRESULTS;
795                         c[i].ldctl_iscritical = pagedResults > 1;
796                         i++;
797                 }
798 #endif
799
800                 tool_server_controls( ld, c, i );
801
802 #ifdef LDAP_CONTROL_SUBENTRIES
803                 ber_free( seber, 1 );
804 #endif
805                 ber_free( vrber, 1 );
806 #ifdef LDAP_CONTROL_PAGEDRESULTS
807                 ber_free( prber, 1 );
808 #endif
809         }
810         
811         if ( verbose ) {
812                 fprintf( stderr, _("filter%s: %s\nrequesting: "),
813                         infile != NULL ? _(" pattern") : "",
814                         filtpattern );
815
816                 if ( attrs == NULL ) {
817                         fprintf( stderr, _("All userApplication attributes") );
818                 } else {
819                         for ( i = 0; attrs[ i ] != NULL; ++i ) {
820                                 fprintf( stderr, "%s ", attrs[ i ] );
821                         }
822                 }
823                 fprintf( stderr, "\n" );
824         }
825
826         if ( ldif == 0 ) {
827                 printf( _("# extended LDIF\n") );
828         } else if ( ldif < 3 ) {
829                 printf( _("version: %d\n\n"), 1 );
830         }
831
832         if (ldif < 2 ) {
833                 printf( "#\n" );
834                 printf(_("# LDAPv%d\n"), protocol);
835                 printf(_("# base <%s> with scope %s\n"),
836                         base ? base : "",
837                         ((scope == LDAP_SCOPE_BASE) ? "baseObject"
838                                 : ((scope == LDAP_SCOPE_ONELEVEL) ? "oneLevel"
839 #ifdef LDAP_SCOPE_SUBORDINATE
840                                 : ((scope == LDAP_SCOPE_SUBORDINATE) ? "children"
841 #endif
842                                 : "subtree"
843 #ifdef LDAP_SCOPE_SUBORDINATE
844                                 )
845 #endif
846                                 )));
847                 printf(_("# filter%s: %s\n"), infile != NULL ? _(" pattern") : "",
848                        filtpattern);
849                 printf(_("# requesting: "));
850
851                 if ( attrs == NULL ) {
852                         printf( _("ALL") );
853                 } else {
854                         for ( i = 0; attrs[ i ] != NULL; ++i ) {
855                                 printf( "%s ", attrs[ i ] );
856                         }
857                 }
858
859                 if ( manageDSAit ) {
860                         printf(_("\n# with manageDSAit %scontrol"),
861                                 manageDSAit > 1 ? _("critical ") : "" );
862                 }
863                 if ( noop ) {
864                         printf(_("\n# with noop %scontrol"),
865                                 noop > 1 ? _("critical ") : "" );
866                 }
867                 if ( subentries ) {
868                         printf(_("\n# with subentries %scontrol: %s"),
869                                 subentries < 0 ? _("critical ") : "",
870                                 abs(subentries) == 1 ? "false" : "true" );
871                 }
872                 if ( valuesReturnFilter ) {
873                         printf(_("\n# with valuesReturnFilter %scontrol: %s"),
874                                 valuesReturnFilter > 1 ? _("critical ") : "", vrFilter );
875                 }
876 #ifdef LDAP_CONTROL_PAGEDRESULTS
877                 if ( pagedResults ) {
878                         printf(_("\n# with pagedResults %scontrol: size=%d"),
879                                 (pagedResults > 1) ? _("critical ") : "", 
880                                 pageSize );
881                 }
882 #endif
883
884                 printf( _("\n#\n\n") );
885         }
886
887         if ( infile == NULL ) {
888                 rc = dosearch( ld, base, scope, NULL, filtpattern,
889                         attrs, attrsonly, NULL, NULL, NULL, -1 );
890
891         } else {
892                 rc = 0;
893                 first = 1;
894                 while ( rc == 0 && fgets( line, sizeof( line ), fp ) != NULL ) { 
895                         line[ strlen( line ) - 1 ] = '\0';
896                         if ( !first ) {
897                                 putchar( '\n' );
898                         } else {
899                                 first = 0;
900                         }
901                         rc = dosearch( ld, base, scope, filtpattern, line,
902                                 attrs, attrsonly, NULL, NULL, NULL, -1 );
903                 }
904                 if ( fp != stdin ) {
905                         fclose( fp );
906                 }
907         }
908
909 #ifdef LDAP_CONTROL_PAGEDRESULTS
910         if ( ( rc == LDAP_SUCCESS ) &&  ( pageSize != 0 ) && ( morePagedResults != 0 ) ) {
911                 char    buf[6];
912                 int     i, moreEntries, tmpSize;
913
914                 /* Loop to get the next pages when 
915                  * enter is pressed on the terminal.
916                  */
917                 if ( pagePrompt != 0 ) {
918                         if ( entriesLeft > 0 ) {
919                                 printf( _("Estimate entries: %d\n"), entriesLeft );
920                         }
921                         printf( _("Press [size] Enter for the next {%d|size} entries.\n"),
922                                 (int)pageSize );
923                         i = 0;
924                         moreEntries = getchar();
925                         while ( moreEntries != EOF && moreEntries != '\n' ) { 
926                                 if ( i < (int)sizeof(buf) - 1 ) {
927                                         buf[i] = moreEntries;
928                                         i++;
929                                 }
930                                 moreEntries = getchar();
931                         }
932                         buf[i] = '\0';
933
934                         if ( i > 0 && isdigit( (unsigned char)buf[0] ) ) {
935                                 int num = sscanf( buf, "%d", &tmpSize );
936                                 if ( num != 1 ) {
937                                         fprintf( stderr, _("Invalid value for PagedResultsControl, %s.\n"), buf);
938                                         return EXIT_FAILURE;
939         
940                                 }
941                                 pageSize = (ber_int_t)tmpSize;
942                         }
943                 }
944
945                 goto getNextPage;
946         }
947 #endif
948
949         tool_unbind( ld );
950         tool_destroy();
951         return( rc );
952 }
953
954
955 static int dosearch(
956         LDAP    *ld,
957         char    *base,
958         int             scope,
959         char    *filtpatt,
960         char    *value,
961         char    **attrs,
962         int             attrsonly,
963         LDAPControl **sctrls,
964         LDAPControl **cctrls,
965         struct timeval *timeout,
966         int sizelimit )
967 {
968         char                    *filter;
969         int                     rc;
970         int                     nresponses;
971         int                     nentries;
972         int                     nreferences;
973         int                     nextended;
974         int                     npartial;
975         LDAPMessage             *res, *msg;
976         ber_int_t               msgid;
977         char                    *retoid = NULL;
978         struct berval           *retdata = NULL;
979         int                     nresponses_psearch = -1;
980         int                     cancel_msgid = -1;
981
982         if( filtpatt != NULL ) {
983                 filter = malloc( strlen( filtpatt ) + strlen( value ) );
984                 if( filter == NULL ) {
985                         perror( "malloc" );
986                         return EXIT_FAILURE;
987                 }
988
989                 sprintf( filter, filtpatt, value );
990
991                 if ( verbose ) {
992                         fprintf( stderr, _("filter: %s\n"), filter );
993                 }
994
995                 if( ldif < 2 ) {
996                         printf( _("#\n# filter: %s\n#\n"), filter );
997                 }
998
999         } else {
1000                 filter = value;
1001         }
1002
1003         if ( not ) {
1004                 return LDAP_SUCCESS;
1005         }
1006
1007         rc = ldap_search_ext( ld, base, scope, filter, attrs, attrsonly,
1008                 sctrls, cctrls, timeout, sizelimit, &msgid );
1009
1010         if ( filtpatt != NULL ) {
1011                 free( filter );
1012         }
1013
1014         if( rc != LDAP_SUCCESS ) {
1015                 fprintf( stderr, _("%s: ldap_search_ext: %s (%d)\n"),
1016                         prog, ldap_err2string( rc ), rc );
1017                 return( rc );
1018         }
1019
1020         nresponses = nentries = nreferences = nextended = npartial = 0;
1021
1022         res = NULL;
1023
1024         while ((rc = ldap_result( ld, LDAP_RES_ANY,
1025                 sortattr ? LDAP_MSG_ALL : LDAP_MSG_ONE,
1026                 NULL, &res )) > 0 )
1027         {
1028                 rc = tool_check_abandon( ld, msgid );
1029                 if ( rc ) {
1030                         return rc;
1031                 }
1032
1033                 if( sortattr ) {
1034                         (void) ldap_sort_entries( ld, &res,
1035                                 ( *sortattr == '\0' ) ? NULL : sortattr, strcasecmp );
1036                 }
1037
1038                 for ( msg = ldap_first_message( ld, res );
1039                         msg != NULL;
1040                         msg = ldap_next_message( ld, msg ) )
1041                 {
1042                         if ( nresponses++ ) putchar('\n');
1043                         if ( nresponses_psearch >= 0 ) 
1044                                 nresponses_psearch++;
1045
1046                         switch( ldap_msgtype( msg ) ) {
1047                         case LDAP_RES_SEARCH_ENTRY:
1048                                 nentries++;
1049                                 print_entry( ld, msg, attrsonly );
1050                                 break;
1051
1052                         case LDAP_RES_SEARCH_REFERENCE:
1053                                 nreferences++;
1054                                 print_reference( ld, msg );
1055                                 break;
1056
1057                         case LDAP_RES_EXTENDED:
1058                                 nextended++;
1059                                 print_extended( ld, msg );
1060
1061                                 if( ldap_msgid( msg ) == 0 ) {
1062                                         /* unsolicited extended operation */
1063                                         goto done;
1064                                 }
1065
1066                                 if ( cancel_msgid != -1 &&
1067                                                 cancel_msgid == ldap_msgid( msg ) ) {
1068                                         printf(_("Cancelled \n"));
1069                                         printf(_("cancel_msgid = %d\n"), cancel_msgid);
1070                                         goto done;
1071                                 }
1072                                 break;
1073
1074                         case LDAP_RES_SEARCH_RESULT:
1075                                 rc = print_result( ld, msg, 1 );
1076 #ifdef LDAP_CONTROL_PAGEDRESULTS
1077                                 if ( pageSize != 0 ) {
1078                                         if ( rc == LDAP_SUCCESS ) {
1079                                                 rc = parse_page_control( ld, msg, &page_cookie );
1080                                         } else {
1081                                                 morePagedResults = 0;
1082                                         }
1083                                 } else {
1084                                         morePagedResults = 0;
1085                                 }
1086 #endif
1087
1088                                 if ( ldapsync == LDAP_SYNC_REFRESH_AND_PERSIST ) {
1089                                         break;
1090                                 }
1091
1092                                 goto done;
1093
1094                         case LDAP_RES_INTERMEDIATE:
1095                                 npartial++;
1096                                 ldap_parse_intermediate( ld, msg,
1097                                         &retoid, &retdata, NULL, 0 );
1098
1099                                 nresponses_psearch = 0;
1100
1101                                 if ( strcmp( retoid, LDAP_SYNC_INFO ) == 0 ) {
1102                                         printf(_("SyncInfo Received\n"));
1103                                         ldap_memfree( retoid );
1104                                         ber_bvfree( retdata );
1105                                         break;
1106                                 }
1107
1108                                 print_partial( ld, msg );
1109                                 ldap_memfree( retoid );
1110                                 ber_bvfree( retdata );
1111                                 goto done;
1112                         }
1113
1114                         if ( ldapsync && sync_slimit != -1 &&
1115                                         nresponses_psearch >= sync_slimit ) {
1116                                 BerElement *msgidber = NULL;
1117                                 struct berval *msgidvalp = NULL;
1118                                 msgidber = ber_alloc_t(LBER_USE_DER);
1119                                 ber_printf(msgidber, "{i}", msgid);
1120                                 ber_flatten(msgidber, &msgidvalp);
1121                                 ldap_extended_operation(ld, LDAP_EXOP_X_CANCEL,
1122                                                 msgidvalp, NULL, NULL, &cancel_msgid);
1123                                 nresponses_psearch = -1;
1124                         }
1125                 }
1126
1127                 ldap_msgfree( res );
1128         }
1129
1130 done:
1131         if ( rc == -1 ) {
1132                 ldap_perror( ld, "ldap_result" );
1133                 return( rc );
1134         }
1135
1136         ldap_msgfree( res );
1137 #ifdef LDAP_CONTROL_PAGEDRESULTS
1138         if ( pagedResults ) { 
1139                 npagedresponses += nresponses;
1140                 npagedentries += nentries;
1141                 npagedextended += nextended;
1142                 npagedpartial += npartial;
1143                 npagedreferences += nreferences;
1144                 if ( ( morePagedResults == 0 ) && ( ldif < 2 ) ) {
1145                         printf( _("\n# numResponses: %d\n"), npagedresponses );
1146                         if( npagedentries ) printf( _("# numEntries: %d\n"), npagedentries );
1147                         if( npagedextended ) printf( _("# numExtended: %d\n"), npagedextended );
1148                         if( npagedpartial ) printf( _("# numPartial: %d\n"), npagedpartial );
1149                         if( npagedreferences ) printf( _("# numReferences: %d\n"), npagedreferences );
1150                 }
1151         } else
1152 #endif
1153         if ( ldif < 2 ) {
1154                 printf( _("\n# numResponses: %d\n"), nresponses );
1155                 if( nentries ) printf( _("# numEntries: %d\n"), nentries );
1156                 if( nextended ) printf( _("# numExtended: %d\n"), nextended );
1157                 if( npartial ) printf( _("# numPartial: %d\n"), npartial );
1158                 if( nreferences ) printf( _("# numReferences: %d\n"), nreferences );
1159         }
1160
1161         return( rc );
1162 }
1163
1164 /* This is the proposed new way of doing things.
1165  * It is more efficient, but the API is non-standard.
1166  */
1167 static void
1168 print_entry(
1169         LDAP    *ld,
1170         LDAPMessage     *entry,
1171         int             attrsonly)
1172 {
1173         char            *ufn = NULL;
1174         char    tmpfname[ 256 ];
1175         char    url[ 256 ];
1176         int                     i, rc;
1177         BerElement              *ber = NULL;
1178         struct berval           bv, *bvals, **bvp = &bvals;
1179         LDAPControl **ctrls = NULL;
1180         FILE            *tmpfp;
1181
1182         rc = ldap_get_dn_ber( ld, entry, &ber, &bv );
1183
1184         if ( ldif < 2 ) {
1185                 ufn = ldap_dn2ufn( bv.bv_val );
1186                 write_ldif( LDIF_PUT_COMMENT, NULL, ufn, ufn ? strlen( ufn ) : 0 );
1187         }
1188         write_ldif( LDIF_PUT_VALUE, "dn", bv.bv_val, bv.bv_len );
1189
1190         rc = ldap_get_entry_controls( ld, entry, &ctrls );
1191         if( rc != LDAP_SUCCESS ) {
1192                 fprintf(stderr, _("print_entry: %d\n"), rc );
1193                 ldap_perror( ld, "ldap_get_entry_controls" );
1194                 exit( EXIT_FAILURE );
1195         }
1196
1197         if( ctrls ) {
1198                 print_ctrls( ctrls );
1199                 ldap_controls_free( ctrls );
1200         }
1201
1202         if ( includeufn ) {
1203                 if( ufn == NULL ) {
1204                         ufn = ldap_dn2ufn( bv.bv_val );
1205                 }
1206                 write_ldif( LDIF_PUT_VALUE, "ufn", ufn, ufn ? strlen( ufn ) : 0 );
1207         }
1208
1209         if( ufn != NULL ) ldap_memfree( ufn );
1210
1211         if ( attrsonly ) bvp = NULL;
1212
1213         for ( rc = ldap_get_attribute_ber( ld, entry, ber, &bv, bvp );
1214                 rc == LDAP_SUCCESS;
1215                 rc = ldap_get_attribute_ber( ld, entry, ber, &bv, bvp ) )
1216         {
1217                 if (bv.bv_val == NULL) break;
1218
1219                 if ( attrsonly ) {
1220                         write_ldif( LDIF_PUT_NOVALUE, bv.bv_val, NULL, 0 );
1221
1222                 } else if ( bvals ) {
1223                         for ( i = 0; bvals[i].bv_val != NULL; i++ ) {
1224                                 if ( vals2tmp > 1 || ( vals2tmp &&
1225                                         ldif_is_not_printable( bvals[i].bv_val, bvals[i].bv_len )))
1226                                 {
1227                                         int tmpfd;
1228                                         /* write value to file */
1229                                         snprintf( tmpfname, sizeof tmpfname,
1230                                                 "%s" LDAP_DIRSEP "ldapsearch-%s-XXXXXX",
1231                                                 tmpdir, bv.bv_val );
1232                                         tmpfp = NULL;
1233
1234                                         tmpfd = mkstemp( tmpfname );
1235
1236                                         if ( tmpfd < 0  ) {
1237                                                 perror( tmpfname );
1238                                                 continue;
1239                                         }
1240
1241                                         if (( tmpfp = fdopen( tmpfd, "w")) == NULL ) {
1242                                                 perror( tmpfname );
1243                                                 continue;
1244                                         }
1245
1246                                         if ( fwrite( bvals[ i ].bv_val,
1247                                                 bvals[ i ].bv_len, 1, tmpfp ) == 0 )
1248                                         {
1249                                                 perror( tmpfname );
1250                                                 fclose( tmpfp );
1251                                                 continue;
1252                                         }
1253
1254                                         fclose( tmpfp );
1255
1256                                         snprintf( url, sizeof url, "%s%s", urlpre,
1257                                                 &tmpfname[strlen(tmpdir) + sizeof(LDAP_DIRSEP) - 1] );
1258
1259                                         urlize( url );
1260                                         write_ldif( LDIF_PUT_URL, bv.bv_val, url, strlen( url ));
1261
1262                                 } else {
1263                                         write_ldif( LDIF_PUT_VALUE, bv.bv_val,
1264                                                 bvals[ i ].bv_val, bvals[ i ].bv_len );
1265                                 }
1266                         }
1267                         ber_memfree( bvals );
1268                 }
1269         }
1270
1271         if( ber != NULL ) {
1272                 ber_free( ber, 0 );
1273         }
1274 }
1275
1276 static void print_reference(
1277         LDAP *ld,
1278         LDAPMessage *reference )
1279 {
1280         int rc;
1281         char **refs = NULL;
1282         LDAPControl **ctrls;
1283
1284         if( ldif < 2 ) {
1285                 printf(_("# search reference\n"));
1286         }
1287
1288         rc = ldap_parse_reference( ld, reference, &refs, &ctrls, 0 );
1289
1290         if( rc != LDAP_SUCCESS ) {
1291                 ldap_perror(ld, "ldap_parse_reference");
1292                 exit( EXIT_FAILURE );
1293         }
1294
1295         if( refs ) {
1296                 int i;
1297                 for( i=0; refs[i] != NULL; i++ ) {
1298                         write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1299                                 "ref", refs[i], strlen(refs[i]) );
1300                 }
1301                 ber_memvfree( (void **) refs );
1302         }
1303
1304         if( ctrls ) {
1305                 print_ctrls( ctrls );
1306                 ldap_controls_free( ctrls );
1307         }
1308 }
1309
1310 static void print_extended(
1311         LDAP *ld,
1312         LDAPMessage *extended )
1313 {
1314         int rc;
1315         char *retoid = NULL;
1316         struct berval *retdata = NULL;
1317
1318         if( ldif < 2 ) {
1319                 printf(_("# extended result response\n"));
1320         }
1321
1322         rc = ldap_parse_extended_result( ld, extended,
1323                 &retoid, &retdata, 0 );
1324
1325         if( rc != LDAP_SUCCESS ) {
1326                 ldap_perror(ld, "ldap_parse_extended_result");
1327                 exit( EXIT_FAILURE );
1328         }
1329
1330         if ( ldif < 2 ) {
1331                 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1332                         "extended", retoid, retoid ? strlen(retoid) : 0 );
1333         }
1334         ber_memfree( retoid );
1335
1336         if(retdata) {
1337                 if ( ldif < 2 ) {
1338                         write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1339                                 "data", retdata->bv_val, retdata->bv_len );
1340                 }
1341                 ber_bvfree( retdata );
1342         }
1343
1344         print_result( ld, extended, 0 );
1345 }
1346
1347 static void print_partial(
1348         LDAP *ld,
1349         LDAPMessage *partial )
1350 {
1351         int rc;
1352         char *retoid = NULL;
1353         struct berval *retdata = NULL;
1354         LDAPControl **ctrls = NULL;
1355
1356         if( ldif < 2 ) {
1357                 printf(_("# extended partial response\n"));
1358         }
1359
1360         rc = ldap_parse_intermediate( ld, partial,
1361                 &retoid, &retdata, &ctrls, 0 );
1362
1363         if( rc != LDAP_SUCCESS ) {
1364                 ldap_perror(ld, "ldap_parse_intermediate");
1365                 exit( EXIT_FAILURE );
1366         }
1367
1368         if ( ldif < 2 ) {
1369                 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1370                         "partial", retoid, retoid ? strlen(retoid) : 0 );
1371         }
1372
1373         ber_memfree( retoid );
1374
1375         if( retdata ) {
1376                 if ( ldif < 2 ) {
1377                         write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1378                                 "data", retdata->bv_val, retdata->bv_len );
1379                 }
1380
1381                 ber_bvfree( retdata );
1382         }
1383
1384         if( ctrls ) {
1385                 print_ctrls( ctrls );
1386                 ldap_controls_free( ctrls );
1387         }
1388 }
1389
1390 static int print_result(
1391         LDAP *ld,
1392         LDAPMessage *result, int search )
1393 {
1394         int rc;
1395         int err;
1396         char *matcheddn = NULL;
1397         char *text = NULL;
1398         char **refs = NULL;
1399         LDAPControl **ctrls = NULL;
1400
1401         if( search ) {
1402                 if ( ldif < 2 ) {
1403                         printf(_("# search result\n"));
1404                 }
1405                 if ( ldif < 1 ) {
1406                         printf("%s: %d\n", _("search"), ldap_msgid(result) );
1407                 }
1408         }
1409
1410         rc = ldap_parse_result( ld, result,
1411                 &err, &matcheddn, &text, &refs, &ctrls, 0 );
1412
1413         if( rc != LDAP_SUCCESS ) {
1414                 ldap_perror(ld, "ldap_parse_result");
1415                 exit( EXIT_FAILURE );
1416         }
1417
1418
1419         if( !ldif ) {
1420                 printf( _("result: %d %s\n"), err, ldap_err2string(err) );
1421
1422         } else if ( err != LDAP_SUCCESS ) {
1423                 fprintf( stderr, "%s (%d)\n", ldap_err2string(err), err );
1424         }
1425
1426         if( matcheddn ) {
1427                 if( *matcheddn ) {
1428                 if( !ldif ) {
1429                         write_ldif( LDIF_PUT_VALUE,
1430                                 "matchedDN", matcheddn, strlen(matcheddn) );
1431                 } else {
1432                         fprintf( stderr, _("Matched DN: %s\n"), matcheddn );
1433                 }
1434                 }
1435
1436                 ber_memfree( matcheddn );
1437         }
1438
1439         if( text ) {
1440                 if( *text ) {
1441                 if( !ldif ) {
1442                         write_ldif( LDIF_PUT_TEXT, "text",
1443                                 text, strlen(text) );
1444                 } else {
1445                         fprintf( stderr, _("Additional information: %s\n"), text );
1446                 }
1447                 }
1448
1449                 ber_memfree( text );
1450         }
1451
1452         if( refs ) {
1453                 int i;
1454                 for( i=0; refs[i] != NULL; i++ ) {
1455                         if( !ldif ) {
1456                                 write_ldif( LDIF_PUT_VALUE, "ref", refs[i], strlen(refs[i]) );
1457                         } else {
1458                                 fprintf( stderr, _("Referral: %s\n"), refs[i] );
1459                         }
1460                 }
1461
1462                 ber_memvfree( (void **) refs );
1463         }
1464
1465         if( ctrls ) {
1466                 print_ctrls( ctrls );
1467                 ldap_controls_free( ctrls );
1468         }
1469
1470         return err;
1471 }
1472
1473 static void print_ctrls(
1474         LDAPControl **ctrls )
1475 {
1476         int i;
1477         for(i=0; ctrls[i] != NULL; i++ ) {
1478                 /* control: OID criticality base64value */
1479                 struct berval *b64 = NULL;
1480                 ber_len_t len;
1481                 char *str;
1482
1483                 len = ldif ? 2 : 0;
1484                 len += strlen( ctrls[i]->ldctl_oid );
1485
1486                 /* add enough for space after OID and the critical value itself */
1487                 len += ctrls[i]->ldctl_iscritical
1488                         ? sizeof("true") : sizeof("false");
1489
1490                 /* convert to base64 */
1491                 if( ctrls[i]->ldctl_value.bv_len ) {
1492                         b64 = ber_memalloc( sizeof(struct berval) );
1493                         
1494                         b64->bv_len = LUTIL_BASE64_ENCODE_LEN(
1495                                 ctrls[i]->ldctl_value.bv_len ) + 1;
1496                         b64->bv_val = ber_memalloc( b64->bv_len + 1 );
1497
1498                         b64->bv_len = lutil_b64_ntop(
1499                                 (unsigned char *) ctrls[i]->ldctl_value.bv_val,
1500                                 ctrls[i]->ldctl_value.bv_len,
1501                                 b64->bv_val, b64->bv_len );
1502                 }
1503
1504                 if( b64 ) {
1505                         len += 1 + b64->bv_len;
1506                 }
1507
1508                 str = malloc( len + 1 );
1509                 if ( ldif ) {
1510                         strcpy( str, ": " );
1511                 } else {
1512                         str[0] = '\0';
1513                 }
1514                 strcat( str, ctrls[i]->ldctl_oid );
1515                 strcat( str, ctrls[i]->ldctl_iscritical
1516                         ? " true" : " false" );
1517
1518                 if( b64 ) {
1519                         strcat(str, " ");
1520                         strcat(str, b64->bv_val );
1521                 }
1522
1523                 if ( ldif < 2 ) {
1524                         write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1525                                 "control", str, len );
1526                 }
1527
1528                 free( str );
1529                 ber_bvfree( b64 );
1530         }
1531 }
1532
1533 static int
1534 write_ldif( int type, char *name, char *value, ber_len_t vallen )
1535 {
1536         char    *ldif;
1537
1538         if (( ldif = ldif_put( type, name, value, vallen )) == NULL ) {
1539                 return( -1 );
1540         }
1541
1542         fputs( ldif, stdout );
1543         ber_memfree( ldif );
1544
1545         return( 0 );
1546 }
1547
1548
1549 #ifdef LDAP_CONTROL_PAGEDRESULTS
1550 static int 
1551 parse_page_control(
1552         LDAP *ld,
1553         LDAPMessage *result,
1554         struct berval *cookie )
1555 {
1556         int rc;
1557         int err;
1558         LDAPControl **ctrl = NULL;
1559         LDAPControl *ctrlp = NULL;
1560         BerElement *ber;
1561         ber_tag_t tag;
1562
1563         rc = ldap_parse_result( ld, result,
1564                 &err, NULL, NULL, NULL, &ctrl, 0 );
1565
1566         if( rc != LDAP_SUCCESS ) {
1567                 ldap_perror(ld, "ldap_parse_result");
1568                 exit( EXIT_FAILURE );
1569         }
1570
1571         if ( err != LDAP_SUCCESS ) {
1572                 fprintf( stderr, "%s (%d)\n", ldap_err2string(err), err );
1573         }
1574
1575         if ( ctrl ) {
1576                 /* There might be others, e.g. ppolicy... */
1577                 ctrlp = ldap_find_control( LDAP_CONTROL_PAGEDRESULTS, ctrl );
1578         }
1579
1580         if ( ctrlp ) {
1581                 /* Parse the control value
1582                  * searchResult ::= SEQUENCE {
1583                  *              size    INTEGER (0..maxInt),
1584                  *                              -- result set size estimate from server - unused
1585                  *              cookie  OCTET STRING
1586                  * }
1587                  */
1588                 ctrlp = *ctrl;
1589                 ber = ber_init( &ctrlp->ldctl_value );
1590                 if ( ber == NULL ) {
1591                         fprintf( stderr, _("Internal error.\n") );
1592                         return EXIT_FAILURE;
1593                 }
1594
1595                 tag = ber_scanf( ber, "{io}", &entriesLeft, cookie );
1596                 (void) ber_free( ber, 1 );
1597
1598                 if( tag == LBER_ERROR ) {
1599                         fprintf( stderr,
1600                                 _("Paged results response control could not be decoded.\n") );
1601                         return EXIT_FAILURE;
1602                 }
1603
1604                 if( entriesLeft < 0 ) {
1605                         fprintf( stderr,
1606                                 _("Invalid entries estimate in paged results response.\n") );
1607                         return EXIT_FAILURE;
1608                 }
1609
1610                 if ( cookie->bv_len == 0 ) {
1611                         morePagedResults = 0;
1612                 }
1613
1614                 ldap_controls_free( ctrl );
1615
1616         } else {
1617                 morePagedResults = 0;
1618         }
1619
1620         return err;
1621 }
1622 #endif