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