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