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