]> git.sur5r.net Git - openldap/blob - clients/tools/ldapsearch.c
Factor out common client code to file common.c
[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      *ber = NULL;
365         struct berval   *sebvalp = NULL, *vrbvalp = NULL;
366         struct berval   *prbvalp = NULL;
367
368         npagedresponses = npagedentries = npagedreferences =
369                 npagedextended = npagedpartial = 0;
370
371         prog = lutil_progname( "ldapsearch", argc, argv );
372
373         lutil_log_initialize(argc, argv);
374
375         if((def_tmpdir = getenv("TMPDIR")) == NULL &&
376            (def_tmpdir = getenv("TMP")) == NULL &&
377            (def_tmpdir = getenv("TEMP")) == NULL )
378         {
379                 def_tmpdir = LDAP_TMPDIR;
380         }
381
382         if ( !*def_tmpdir )
383                 def_tmpdir = LDAP_TMPDIR;
384
385         def_urlpre = malloc( sizeof("file:////") + strlen(def_tmpdir) );
386
387         if( def_urlpre == NULL ) {
388                 perror( "malloc" );
389                 return EXIT_FAILURE;
390         }
391
392         sprintf( def_urlpre, "file:///%s/",
393                 def_tmpdir[0] == *LDAP_DIRSEP ? &def_tmpdir[1] : def_tmpdir );
394
395         urlize( def_urlpre );
396
397         tool_args( argc, argv );
398
399         if (( argc - optind < 1 ) ||
400                 ( *argv[optind] != '(' /*')'*/ &&
401                 ( strchr( argv[optind], '=' ) == NULL ) ) )
402         {
403                 filtpattern = "(objectclass=*)";
404         } else {
405                 filtpattern = strdup( argv[optind++] );
406         }
407
408         if ( argv[optind] != NULL ) {
409                 attrs = &argv[optind];
410         }
411
412         if ( infile != NULL ) {
413                 if ( infile[0] == '-' && infile[1] == '\0' ) {
414                         fp = stdin;
415                 } else if (( fp = fopen( infile, "r" )) == NULL ) {
416                         perror( infile );
417                         return EXIT_FAILURE;
418                 }
419         }
420
421         if ( tmpdir == NULL ) {
422                 tmpdir = def_tmpdir;
423
424                 if ( urlpre == NULL )
425                         urlpre = def_urlpre;
426         }
427
428         if( urlpre == NULL ) {
429                 urlpre = malloc( sizeof("file:////") + strlen(tmpdir) );
430
431                 if( urlpre == NULL ) {
432                         perror( "malloc" );
433                         return EXIT_FAILURE;
434                 }
435
436                 sprintf( urlpre, "file:///%s/",
437                         tmpdir[0] == *LDAP_DIRSEP ? &tmpdir[1] : tmpdir );
438
439                 urlize( urlpre );
440         }
441
442         if ( debug )
443                 ldif_debug = debug;
444
445         ld = tool_conn_setup( 0, &private_conn_setup );
446
447         if ( pw_file || want_bindpw ) {
448                 if ( pw_file ) {
449                         rc = lutil_get_filed_password( pw_file, &passwd );
450                         if( rc ) return EXIT_FAILURE;
451                 } else {
452                         passwd.bv_val = getpassphrase( "Enter LDAP Password: " );
453                         passwd.bv_len = passwd.bv_val ? strlen( passwd.bv_val ) : 0;
454                 }
455         }
456
457         tool_bind( ld );
458
459 getNextPage:
460         if ( manageDSAit || noop || subentries
461                 || valuesReturnFilter || pageSize )
462         {
463                 int err;
464                 int i=0;
465                 LDAPControl c[3];
466
467 #ifdef LDAP_CONTROL_SUBENTRIES
468                 if ( subentries ) {
469                 if (( ber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
470                                 return EXIT_FAILURE;
471                         }
472
473                         err = ber_printf( ber, "{b}", abs(subentries) == 1 ? 0 : 1 );
474                 if ( err == LBER_ERROR ) {
475                                 ber_free( ber, 1 );
476                                 fprintf( stderr, "Subentries control encoding error!\n" );
477                                 return EXIT_FAILURE;
478                         }
479
480                         if ( ber_flatten( ber, &sebvalp ) == LBER_ERROR ) {
481                                 return EXIT_FAILURE;
482                         }
483
484                         c[i].ldctl_oid = LDAP_CONTROL_SUBENTRIES;
485                         c[i].ldctl_value=(*sebvalp);
486                         c[i].ldctl_iscritical = subentries < 1;
487                         i++;
488                 }
489 #endif
490
491                 if ( valuesReturnFilter ) {
492                 if (( ber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
493                                 return EXIT_FAILURE;
494                         }
495
496                 if ( ( err = ldap_put_vrFilter( ber, vrFilter ) ) == -1 ) {
497                                 ber_free( ber, 1 );
498                                 fprintf( stderr, "Bad ValuesReturnFilter: %s\n", vrFilter );
499                                 return EXIT_FAILURE;
500                         }
501
502                         if ( ber_flatten( ber, &vrbvalp ) == LBER_ERROR ) {
503                                 return EXIT_FAILURE;
504                         }
505
506                         ber_free( ber, 1 );
507
508                         c[i].ldctl_oid = LDAP_CONTROL_VALUESRETURNFILTER;
509                         c[i].ldctl_value=(*vrbvalp);
510                         c[i].ldctl_iscritical = valuesReturnFilter > 1;
511                         i++;
512                 }
513
514                 if ( pagedResults ) {
515                         if (( ber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
516                                 return EXIT_FAILURE;
517                         }
518
519                         ber_printf( ber, "{iO}", pageSize, &cookie );
520                         if ( ber_flatten( ber, &prbvalp ) == LBER_ERROR ) {
521                                 return EXIT_FAILURE;
522                         }
523                         
524                         ber_free( ber, 1 );
525
526                         c[i].ldctl_oid = LDAP_CONTROL_PAGEDRESULTS;
527                         c[i].ldctl_value=(*prbvalp);
528                         c[i].ldctl_iscritical = pagedResults > 1;
529                         i++;
530                 }
531
532                 tool_server_controls( ld, c, i );
533
534                 ber_bvfree( sebvalp );
535                 ber_bvfree( vrbvalp );
536                 ber_bvfree( prbvalp );
537         }
538         
539         if ( verbose ) {
540                 fprintf( stderr, "filter%s: %s\nrequesting: ",
541                         infile != NULL ? " pattern" : "",
542                         filtpattern );
543
544                 if ( attrs == NULL ) {
545                         fprintf( stderr, "ALL" );
546                 } else {
547                         for ( i = 0; attrs[ i ] != NULL; ++i ) {
548                                 fprintf( stderr, "%s ", attrs[ i ] );
549                         }
550                 }
551                 fprintf( stderr, "\n" );
552         }
553
554         if ( ldif == 0 ) {
555                 printf( "# extended LDIF\n" );
556         } else if ( ldif < 3 ) {
557                 printf( "version: %d\n\n", 1 );
558         }
559
560         if (ldif < 2 ) {
561                 printf( "#\n"
562                         "# LDAPv%d\n"
563                         "# base <%s> with scope %s\n"
564                         "# filter%s: %s\n"
565                         "# requesting: ",
566                         version,
567                         base ? base : "", (scope == LDAP_SCOPE_BASE) ? "base"
568                                 : ((scope == LDAP_SCOPE_ONELEVEL) ? "one" : "sub"),
569                         infile != NULL ? " pattern" : "",
570                         filtpattern );
571
572                 if ( attrs == NULL ) {
573                         printf( "ALL" );
574                 } else {
575                         for ( i = 0; attrs[ i ] != NULL; ++i ) {
576                                 printf( "%s ", attrs[ i ] );
577                         }
578                 }
579
580                 if ( manageDSAit ) {
581                         printf("\n# with manageDSAit %scontrol",
582                                 manageDSAit > 1 ? "critical " : "" );
583                 }
584                 if ( noop ) {
585                         printf("\n# with noop %scontrol",
586                                 noop > 1 ? "critical " : "" );
587                 }
588                 if ( subentries ) {
589                         printf("\n# with subentries %scontrol: %s",
590                                 subentries < 0 ? "critical " : "",
591                                 abs(subentries) == 1 ? "false" : "true" );
592                 }
593                 if ( valuesReturnFilter ) {
594                         printf("\n# with valuesReturnFilter %scontrol: %s",
595                                 valuesReturnFilter > 1 ? "critical " : "", vrFilter );
596                 }
597                 if ( pageSize ) {
598                         printf("\n# with pagedResults %scontrol: size=%d",
599                                 (pagedResults > 1) ? "critical " : "", 
600                                 pageSize );
601                 }
602
603                 printf( "\n#\n\n" );
604         }
605
606         if ( infile == NULL ) {
607                 rc = dosearch( ld, base, scope, NULL, filtpattern,
608                         attrs, attrsonly, NULL, NULL, NULL, -1 );
609
610         } else {
611                 rc = 0;
612                 first = 1;
613                 while ( rc == 0 && fgets( line, sizeof( line ), fp ) != NULL ) { 
614                         line[ strlen( line ) - 1 ] = '\0';
615                         if ( !first ) {
616                                 putchar( '\n' );
617                         } else {
618                                 first = 0;
619                         }
620                         rc = dosearch( ld, base, scope, filtpattern, line,
621                                 attrs, attrsonly, NULL, NULL, NULL, -1 );
622                 }
623                 if ( fp != stdin ) {
624                         fclose( fp );
625                 }
626         }
627
628         if ( ( pageSize != 0 ) && ( morePagedResults != 0 ) ) { 
629                 char    buf[6];
630                 int     i, moreEntries, tmpSize;
631
632                 /* Loop to get the next pages when 
633                  * enter is pressed on the terminal.
634                  */
635                 if ( entriesLeft > 0 ) {
636                         printf( "Estimate entries: %d\n", entriesLeft );
637                 }
638                 printf( "Press [size] Enter for the next {%d|size} entries.\n",
639                         (int)pageSize ); 
640                 i = 0;
641                 moreEntries = getchar();
642                 while ( moreEntries != EOF && moreEntries != '\n' ) { 
643                         if ( i < sizeof(buf) - 1 ) {
644                                 buf[i] = moreEntries;
645                                 i++;
646                         }
647                         moreEntries = getchar();
648                 }
649                 buf[i] = '\0';
650
651                 if ( i > 0 && isdigit( buf[0] ) ) {
652                         int num = sscanf( buf, "%d", &tmpSize );
653                         if ( num != 1 ) {
654                                 fprintf( stderr, "Invalid value for PagedResultsControl, %s.\n", buf);
655                                 return EXIT_FAILURE;
656
657                         }
658                         pageSize = (ber_int_t)tmpSize;
659                 }
660
661                 goto getNextPage;       
662         }
663
664         ldap_unbind( ld );
665         return( rc );
666 }
667
668
669 static int dosearch(
670         LDAP    *ld,
671         char    *base,
672         int             scope,
673         char    *filtpatt,
674         char    *value,
675         char    **attrs,
676         int             attrsonly,
677         LDAPControl **sctrls,
678         LDAPControl **cctrls,
679         struct timeval *timeout,
680         int sizelimit )
681 {
682         char                    *filter;
683         int                     rc;
684         int                     nresponses;
685         int                     nentries;
686         int                     nreferences;
687         int                     nextended;
688         int                     npartial;
689         LDAPMessage             *res, *msg;
690         ber_int_t       msgid;
691
692         if( filtpatt != NULL ) {
693                 filter = malloc( strlen( filtpatt ) + strlen( value ) );
694                 if( filter == NULL ) {
695                         perror( "malloc" );
696                         return EXIT_FAILURE;
697                 }
698
699                 sprintf( filter, filtpatt, value );
700
701                 if ( verbose ) {
702                         fprintf( stderr, "filter: %s\n", filter );
703                 }
704
705                 if( ldif < 2 ) {
706                         printf( "#\n# filter: %s\n#\n", filter );
707                 }
708
709         } else {
710                 filter = value;
711         }
712
713         if ( not ) {
714                 return LDAP_SUCCESS;
715         }
716
717         rc = ldap_search_ext( ld, base, scope, filter, attrs, attrsonly,
718                 sctrls, cctrls, timeout, sizelimit, &msgid );
719
720         if ( filtpatt != NULL ) {
721                 free( filter );
722         }
723
724         if( rc != LDAP_SUCCESS ) {
725                 fprintf( stderr, "%s: ldap_search_ext: %s (%d)\n",
726                         prog, ldap_err2string( rc ), rc );
727                 return( rc );
728         }
729
730         nresponses = nentries = nreferences = nextended = npartial = 0;
731
732         res = NULL;
733
734         while ((rc = ldap_result( ld, LDAP_RES_ANY,
735                 sortattr ? LDAP_MSG_ALL : LDAP_MSG_ONE,
736                 NULL, &res )) > 0 )
737         {
738                 if( sortattr ) {
739                         (void) ldap_sort_entries( ld, &res,
740                                 ( *sortattr == '\0' ) ? NULL : sortattr, strcasecmp );
741                 }
742
743                 for ( msg = ldap_first_message( ld, res );
744                         msg != NULL;
745                         msg = ldap_next_message( ld, msg ) )
746                 {
747                         if( nresponses++ ) putchar('\n');
748
749                         switch( ldap_msgtype( msg ) ) {
750                         case LDAP_RES_SEARCH_ENTRY:
751                                 nentries++;
752                                 print_entry( ld, msg, attrsonly );
753                                 break;
754
755                         case LDAP_RES_SEARCH_REFERENCE:
756                                 nreferences++;
757                                 print_reference( ld, msg );
758                                 break;
759
760                         case LDAP_RES_EXTENDED:
761                                 nextended++;
762                                 print_extended( ld, msg );
763
764                                 if( ldap_msgid( msg ) == 0 ) {
765                                         /* unsolicited extended operation */
766                                         goto done;
767                                 }
768                                 break;
769
770                         case LDAP_RES_EXTENDED_PARTIAL:
771                                 npartial++;
772                                 print_partial( ld, msg );
773                                 break;
774
775                         case LDAP_RES_SEARCH_RESULT:
776                                 rc = print_result( ld, msg, 1 );
777                                 if ( pageSize != 0 ) { 
778                                         rc = parse_page_control( ld, msg, &cookie );
779                                 }
780                                 goto done;
781                         }
782                 }
783
784                 ldap_msgfree( res );
785         }
786
787         if ( rc == -1 ) {
788                 ldap_perror( ld, "ldap_result" );
789                 return( rc );
790         }
791
792 done:
793         if ( pageSize != 0 ) { 
794                 npagedresponses = npagedresponses + nresponses;
795                 npagedentries = npagedentries + nentries;
796                 npagedreferences = npagedreferences + nreferences;
797                 npagedextended = npagedextended + nextended;
798                 npagedpartial = npagedpartial + npartial;
799                 if ( ( morePagedResults == 0 ) && ( ldif < 2 ) ) {
800                         printf( "\n# numResponses: %d\n", npagedresponses );
801                         if( nentries ) printf( "# numEntries: %d\n", npagedentries );
802                         if( nextended ) printf( "# numExtended: %d\n", npagedextended );
803                         if( npartial ) printf( "# numPartial: %d\n", npagedpartial );
804                         if( nreferences ) printf( "# numReferences: %d\n", npagedreferences );
805                 }
806         } else if ( ldif < 2 ) {
807                 printf( "\n# numResponses: %d\n", nresponses );
808                 if( nentries ) printf( "# numEntries: %d\n", nentries );
809                 if( nextended ) printf( "# numExtended: %d\n", nextended );
810                 if( npartial ) printf( "# numPartial: %d\n", npartial );
811                 if( nreferences ) printf( "# numReferences: %d\n", nreferences );
812         }
813
814         return( rc );
815 }
816
817 #if 1
818 /* This is the original version, the old way of doing things. */
819 static void
820 print_entry(
821         LDAP    *ld,
822         LDAPMessage     *entry,
823         int             attrsonly)
824 {
825         char            *a, *dn, *ufn;
826         char    tmpfname[ 256 ];
827         char    url[ 256 ];
828         int                     i, rc;
829         BerElement              *ber = NULL;
830         struct berval   **bvals;
831         LDAPControl **ctrls = NULL;
832         FILE            *tmpfp;
833
834         dn = ldap_get_dn( ld, entry );
835         ufn = NULL;
836
837         if ( ldif < 2 ) {
838                 ufn = ldap_dn2ufn( dn );
839                 write_ldif( LDIF_PUT_COMMENT, NULL, ufn, ufn ? strlen( ufn ) : 0 );
840         }
841         write_ldif( LDIF_PUT_VALUE, "dn", dn, dn ? strlen( dn ) : 0);
842
843         rc = ldap_get_entry_controls( ld, entry, &ctrls );
844
845         if( rc != LDAP_SUCCESS ) {
846                 fprintf(stderr, "print_entry: %d\n", rc );
847                 ldap_perror( ld, "ldap_get_entry_controls" );
848                 exit( EXIT_FAILURE );
849         }
850
851         if( ctrls ) {
852                 print_ctrls( ctrls );
853                 ldap_controls_free( ctrls );
854         }
855
856         if ( includeufn ) {
857                 if( ufn == NULL ) {
858                         ufn = ldap_dn2ufn( dn );
859                 }
860                 write_ldif( LDIF_PUT_VALUE, "ufn", ufn, ufn ? strlen( ufn ) : 0 );
861         }
862
863         if( ufn != NULL ) ldap_memfree( ufn );
864         ldap_memfree( dn );
865
866         for ( a = ldap_first_attribute( ld, entry, &ber ); a != NULL;
867                 a = ldap_next_attribute( ld, entry, ber ) )
868         {
869                 if ( attrsonly ) {
870                         write_ldif( LDIF_PUT_NOVALUE, a, NULL, 0 );
871
872                 } else if (( bvals = ldap_get_values_len( ld, entry, a )) != NULL ) {
873                         for ( i = 0; bvals[i] != NULL; i++ ) {
874                                 if ( vals2tmp > 1 || ( vals2tmp
875                                         && ldif_is_not_printable( bvals[i]->bv_val, bvals[i]->bv_len ) ))
876                                 {
877                                         int tmpfd;
878                                         /* write value to file */
879                                         snprintf( tmpfname, sizeof tmpfname,
880                                                 "%s" LDAP_DIRSEP "ldapsearch-%s-XXXXXX",
881                                                 tmpdir, a );
882                                         tmpfp = NULL;
883
884                                         tmpfd = mkstemp( tmpfname );
885
886                                         if ( tmpfd < 0  ) {
887                                                 perror( tmpfname );
888                                                 continue;
889                                         }
890
891                                         if (( tmpfp = fdopen( tmpfd, "w")) == NULL ) {
892                                                 perror( tmpfname );
893                                                 continue;
894                                         }
895
896                                         if ( fwrite( bvals[ i ]->bv_val,
897                                                 bvals[ i ]->bv_len, 1, tmpfp ) == 0 )
898                                         {
899                                                 perror( tmpfname );
900                                                 fclose( tmpfp );
901                                                 continue;
902                                         }
903
904                                         fclose( tmpfp );
905
906                                         snprintf( url, sizeof url, "%s%s", urlpre,
907                                                 &tmpfname[strlen(tmpdir) + sizeof(LDAP_DIRSEP) - 1] );
908
909                                         urlize( url );
910                                         write_ldif( LDIF_PUT_URL, a, url, strlen( url ));
911
912                                 } else {
913                                         write_ldif( LDIF_PUT_VALUE, a,
914                                                 bvals[ i ]->bv_val, bvals[ i ]->bv_len );
915                                 }
916                         }
917                         ber_bvecfree( bvals );
918                 }
919                 ldap_memfree( a );
920         }
921
922         if( ber != NULL ) {
923                 ber_free( ber, 0 );
924         }
925 }
926 #else
927 /* This is the proposed new way of doing things.
928  * It is more efficient, but the API is non-standard.
929  */
930 static void
931 print_entry(
932         LDAP    *ld,
933         LDAPMessage     *entry,
934         int             attrsonly)
935 {
936         char            *ufn = NULL;
937         char    tmpfname[ 256 ];
938         char    url[ 256 ];
939         int                     i, rc;
940         BerElement              *ber = NULL;
941         struct berval           bv, *bvals, **bvp = &bvals;
942         LDAPControl **ctrls = NULL;
943         FILE            *tmpfp;
944
945         rc = ldap_get_dn_ber( ld, entry, &ber, &bv );
946
947         if ( ldif < 2 ) {
948                 ufn = ldap_dn2ufn( bv.bv_val );
949                 write_ldif( LDIF_PUT_COMMENT, NULL, ufn, ufn ? strlen( ufn ) : 0 );
950         }
951         write_ldif( LDIF_PUT_VALUE, "dn", bv.bv_val, bv.bv_len );
952
953         rc = ldap_int_get_controls( ber, &ctrls );
954
955         if( rc != LDAP_SUCCESS ) {
956                 fprintf(stderr, "print_entry: %d\n", rc );
957                 ldap_perror( ld, "ldap_get_entry_controls" );
958                 exit( EXIT_FAILURE );
959         }
960
961         if( ctrls ) {
962                 print_ctrls( ctrls );
963                 ldap_controls_free( ctrls );
964         }
965
966         if ( includeufn ) {
967                 if( ufn == NULL ) {
968                         ufn = ldap_dn2ufn( bv.bv_val );
969                 }
970                 write_ldif( LDIF_PUT_VALUE, "ufn", ufn, ufn ? strlen( ufn ) : 0 );
971         }
972
973         if( ufn != NULL ) ldap_memfree( ufn );
974
975         if ( attrsonly ) bvp = NULL;
976
977         for ( rc = ldap_get_attribute_ber( ld, entry, ber, &bv, bvp );
978                 rc == LDAP_SUCCESS;
979                 rc = ldap_get_attribute_ber( ld, entry, ber, &bv, bvp ) )
980         {
981                 if (bv.bv_val == NULL) break;
982
983                 if ( attrsonly ) {
984                         write_ldif( LDIF_PUT_NOVALUE, bv.bv_val, NULL, 0 );
985
986                 } else {
987                         for ( i = 0; bvals[i].bv_val != NULL; i++ ) {
988                                 if ( vals2tmp > 1 || ( vals2tmp
989                                         && ldif_is_not_printable( bvals[i].bv_val, bvals[i].bv_len ) ))
990                                 {
991                                         int tmpfd;
992                                         /* write value to file */
993                                         snprintf( tmpfname, sizeof tmpfname,
994                                                 "%s" LDAP_DIRSEP "ldapsearch-%s-XXXXXX",
995                                                 tmpdir, bv.bv_val );
996                                         tmpfp = NULL;
997
998                                         tmpfd = mkstemp( tmpfname );
999
1000                                         if ( tmpfd < 0  ) {
1001                                                 perror( tmpfname );
1002                                                 continue;
1003                                         }
1004
1005                                         if (( tmpfp = fdopen( tmpfd, "w")) == NULL ) {
1006                                                 perror( tmpfname );
1007                                                 continue;
1008                                         }
1009
1010                                         if ( fwrite( bvals[ i ].bv_val,
1011                                                 bvals[ i ].bv_len, 1, tmpfp ) == 0 )
1012                                         {
1013                                                 perror( tmpfname );
1014                                                 fclose( tmpfp );
1015                                                 continue;
1016                                         }
1017
1018                                         fclose( tmpfp );
1019
1020                                         snprintf( url, sizeof url, "%s%s", urlpre,
1021                                                 &tmpfname[strlen(tmpdir) + sizeof(LDAP_DIRSEP) - 1] );
1022
1023                                         urlize( url );
1024                                         write_ldif( LDIF_PUT_URL, bv.bv_val, url, strlen( url ));
1025
1026                                 } else {
1027                                         write_ldif( LDIF_PUT_VALUE, bv.bv_val,
1028                                                 bvals[ i ].bv_val, bvals[ i ].bv_len );
1029                                 }
1030                         }
1031                         ber_memfree( bvals );
1032                 }
1033         }
1034
1035         if( ber != NULL ) {
1036                 ber_free( ber, 0 );
1037         }
1038 }
1039 #endif
1040
1041 static void print_reference(
1042         LDAP *ld,
1043         LDAPMessage *reference )
1044 {
1045         int rc;
1046         char **refs = NULL;
1047         LDAPControl **ctrls;
1048
1049         if( ldif < 2 ) {
1050                 printf("# search reference\n");
1051         }
1052
1053         rc = ldap_parse_reference( ld, reference, &refs, &ctrls, 0 );
1054
1055         if( rc != LDAP_SUCCESS ) {
1056                 ldap_perror(ld, "ldap_parse_reference");
1057                 exit( EXIT_FAILURE );
1058         }
1059
1060         if( refs ) {
1061                 int i;
1062                 for( i=0; refs[i] != NULL; i++ ) {
1063                         write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1064                                 "ref", refs[i], strlen(refs[i]) );
1065                 }
1066                 ber_memvfree( (void **) refs );
1067         }
1068
1069         if( ctrls ) {
1070                 print_ctrls( ctrls );
1071                 ldap_controls_free( ctrls );
1072         }
1073 }
1074
1075 static void print_extended(
1076         LDAP *ld,
1077         LDAPMessage *extended )
1078 {
1079         int rc;
1080         char *retoid = NULL;
1081         struct berval *retdata = NULL;
1082
1083         if( ldif < 2 ) {
1084                 printf("# extended result response\n");
1085         }
1086
1087         rc = ldap_parse_extended_result( ld, extended,
1088                 &retoid, &retdata, 0 );
1089
1090         if( rc != LDAP_SUCCESS ) {
1091                 ldap_perror(ld, "ldap_parse_extended_result");
1092                 exit( EXIT_FAILURE );
1093         }
1094
1095         if ( ldif < 2 ) {
1096                 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1097                         "extended", retoid, retoid ? strlen(retoid) : 0 );
1098         }
1099         ber_memfree( retoid );
1100
1101         if(retdata) {
1102                 if ( ldif < 2 ) {
1103                         write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1104                                 "data", retdata->bv_val, retdata->bv_len );
1105                 }
1106                 ber_bvfree( retdata );
1107         }
1108
1109         print_result( ld, extended, 0 );
1110 }
1111
1112 static void print_partial(
1113         LDAP *ld,
1114         LDAPMessage *partial )
1115 {
1116         int rc;
1117         char *retoid = NULL;
1118         struct berval *retdata = NULL;
1119         LDAPControl **ctrls = NULL;
1120
1121         if( ldif < 2 ) {
1122                 printf("# extended partial response\n");
1123         }
1124
1125         rc = ldap_parse_extended_partial( ld, partial,
1126                 &retoid, &retdata, &ctrls, 0 );
1127
1128         if( rc != LDAP_SUCCESS ) {
1129                 ldap_perror(ld, "ldap_parse_extended_partial");
1130                 exit( EXIT_FAILURE );
1131         }
1132
1133         if ( ldif < 2 ) {
1134                 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1135                         "partial", retoid, retoid ? strlen(retoid) : 0 );
1136         }
1137
1138         ber_memfree( retoid );
1139
1140         if( retdata ) {
1141                 if ( ldif < 2 ) {
1142                         write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1143                                 "data", retdata->bv_val, retdata->bv_len );
1144                 }
1145
1146                 ber_bvfree( retdata );
1147         }
1148
1149         if( ctrls ) {
1150                 print_ctrls( ctrls );
1151                 ldap_controls_free( ctrls );
1152         }
1153 }
1154
1155 static int print_result(
1156         LDAP *ld,
1157         LDAPMessage *result, int search )
1158 {
1159         int rc;
1160         int err;
1161         char *matcheddn = NULL;
1162         char *text = NULL;
1163         char **refs = NULL;
1164         LDAPControl **ctrls = NULL;
1165
1166         if( search ) {
1167                 if ( ldif < 2 ) {
1168                         printf("# search result\n");
1169                 }
1170                 if ( ldif < 1 ) {
1171                         printf("%s: %d\n", "search", ldap_msgid(result) );
1172                 }
1173         }
1174
1175         rc = ldap_parse_result( ld, result,
1176                 &err, &matcheddn, &text, &refs, &ctrls, 0 );
1177
1178         if( rc != LDAP_SUCCESS ) {
1179                 ldap_perror(ld, "ldap_parse_result");
1180                 exit( EXIT_FAILURE );
1181         }
1182
1183
1184         if( !ldif ) {
1185                 printf( "result: %d %s\n", err, ldap_err2string(err) );
1186
1187         } else if ( err != LDAP_SUCCESS ) {
1188                 fprintf( stderr, "%s (%d)\n", ldap_err2string(err), err );
1189         }
1190
1191         if( matcheddn && *matcheddn ) {
1192                 if( !ldif ) {
1193                         write_ldif( LDIF_PUT_VALUE,
1194                                 "matchedDN", matcheddn, strlen(matcheddn) );
1195                 } else {
1196                         fprintf( stderr, "Matched DN: %s\n", matcheddn );
1197                 }
1198
1199                 ber_memfree( matcheddn );
1200         }
1201
1202         if( text && *text ) {
1203                 if( !ldif ) {
1204                         write_ldif( LDIF_PUT_TEXT, "text",
1205                                 text, strlen(text) );
1206                 } else {
1207                         fprintf( stderr, "Additional information: %s\n", text );
1208                 }
1209
1210                 ber_memfree( text );
1211         }
1212
1213         if( refs ) {
1214                 int i;
1215                 for( i=0; refs[i] != NULL; i++ ) {
1216                         if( !ldif ) {
1217                                 write_ldif( LDIF_PUT_VALUE, "ref", refs[i], strlen(refs[i]) );
1218                         } else {
1219                                 fprintf( stderr, "Referral: %s\n", refs[i] );
1220                         }
1221                 }
1222
1223                 ber_memvfree( (void **) refs );
1224         }
1225
1226         if( ctrls ) {
1227                 print_ctrls( ctrls );
1228                 ldap_controls_free( ctrls );
1229         }
1230
1231         return err;
1232 }
1233
1234 static void print_ctrls(
1235         LDAPControl **ctrls )
1236 {
1237         int i;
1238         for(i=0; ctrls[i] != NULL; i++ ) {
1239                 /* control: OID criticality base64value */
1240                 struct berval *b64 = NULL;
1241                 ber_len_t len;
1242                 char *str;
1243
1244                 len = ldif ? 2 : 0;
1245                 len += strlen( ctrls[i]->ldctl_oid );
1246
1247                 /* add enough for space after OID and the critical value itself */
1248                 len += ctrls[i]->ldctl_iscritical
1249                         ? sizeof("true") : sizeof("false");
1250
1251                 /* convert to base64 */
1252                 if( ctrls[i]->ldctl_value.bv_len ) {
1253                         b64 = ber_memalloc( sizeof(struct berval) );
1254                         
1255                         b64->bv_len = LUTIL_BASE64_ENCODE_LEN(
1256                                 ctrls[i]->ldctl_value.bv_len ) + 1;
1257                         b64->bv_val = ber_memalloc( b64->bv_len + 1 );
1258
1259                         b64->bv_len = lutil_b64_ntop(
1260                                 ctrls[i]->ldctl_value.bv_val, ctrls[i]->ldctl_value.bv_len,
1261                                 b64->bv_val, b64->bv_len );
1262                 }
1263
1264                 if( b64 ) {
1265                         len += 1 + b64->bv_len;
1266                 }
1267
1268                 str = malloc( len + 1 );
1269                 if ( ldif ) {
1270                         strcpy( str, ": " );
1271                 } else {
1272                         str[0] = '\0';
1273                 }
1274                 strcat( str, ctrls[i]->ldctl_oid );
1275                 strcat( str, ctrls[i]->ldctl_iscritical
1276                         ? " true" : " false" );
1277
1278                 if( b64 ) {
1279                         strcat(str, " ");
1280                         strcat(str, b64->bv_val );
1281                 }
1282
1283                 if ( ldif < 2 ) {
1284                         write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1285                                 "control", str, len );
1286                 }
1287
1288                 free( str );
1289                 ber_bvfree( b64 );
1290         }
1291 }
1292
1293 static int
1294 write_ldif( int type, char *name, char *value, ber_len_t vallen )
1295 {
1296         char    *ldif;
1297
1298         if (( ldif = ldif_put( type, name, value, vallen )) == NULL ) {
1299                 return( -1 );
1300         }
1301
1302         fputs( ldif, stdout );
1303         ber_memfree( ldif );
1304
1305         return( 0 );
1306 }
1307
1308
1309 static int 
1310 parse_page_control(
1311         LDAP *ld,
1312         LDAPMessage *result,
1313         struct berval *cookie )
1314 {
1315         int rc;
1316         int err;
1317         LDAPControl **ctrl = NULL;
1318         LDAPControl *ctrlp = NULL;
1319         BerElement *ber;
1320         ber_tag_t tag;
1321         struct berval servercookie = { 0, NULL };
1322
1323
1324         rc = ldap_parse_result( ld, result,
1325                 &err, NULL, NULL, NULL, &ctrl, 0 );
1326
1327         if( rc != LDAP_SUCCESS ) {
1328                 ldap_perror(ld, "ldap_parse_result");
1329                 exit( EXIT_FAILURE );
1330         }
1331
1332         if ( err != LDAP_SUCCESS ) {
1333                 fprintf( stderr, "%s (%d)\n", ldap_err2string(err), err );
1334         }
1335
1336         if( ctrl ) {
1337                 /* Parse the control value
1338                  * searchResult ::= SEQUENCE {
1339                  *              size    INTEGER (0..maxInt),
1340                  *                              -- result set size estimate from server - unused
1341                  *              cookie  OCTET STRING
1342                  */
1343                 ctrlp = *ctrl;
1344                 ber = ber_init( &ctrlp->ldctl_value );
1345                 if ( ber == NULL ) {
1346                         fprintf( stderr, "Internal error.\n" );
1347                         return EXIT_FAILURE;
1348                 }
1349
1350                 tag = ber_scanf( ber, "{im}", &entriesLeft, &servercookie );
1351                 ber_dupbv( cookie, &servercookie );
1352                 (void) ber_free( ber, 1 );
1353
1354                 if( tag == LBER_ERROR ) {
1355                         fprintf( stderr, "Paged results response control could not be decoded.\n" );
1356                         return EXIT_FAILURE;
1357                 }
1358
1359                 if( entriesLeft < 0 ) {
1360                         fprintf( stderr, "Invalid entries estimate in paged results response.\n" );
1361                         return EXIT_FAILURE;
1362                 }
1363
1364
1365                 ldap_controls_free( ctrl );
1366         } else {
1367                 morePagedResults = 0;
1368         }
1369
1370         return err;
1371 }