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