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