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