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