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