]> git.sur5r.net Git - openldap/blob - clients/tools/common.c
add "What Failed?" LDAP control (ITS#5784)
[openldap] / clients / tools / common.c
1 /* common.c - common routines for the ldap client tools */
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 2003 Kurt D. Zeilenga.
7  * Portions Copyright 2003 IBM Corporation.
8  * All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted only as authorized by the OpenLDAP
12  * Public License.
13  *
14  * A copy of this license is available in the file LICENSE in the
15  * top-level directory of the distribution or, alternatively, at
16  * <http://www.OpenLDAP.org/license.html>.
17  */
18 /* ACKNOWLEDGEMENTS:
19  * This file was initially created by Hallvard B. Furuseth based (in
20  * part) upon argument parsing code for individual tools located in
21  * this directory.   Additional contributors include:
22  *   Kurt D. Zeilenga (additional common argument and control support)
23  */
24
25 #include "portable.h"
26
27 #include <stdio.h>
28
29 #include <ac/stdlib.h>
30 #include <ac/signal.h>
31 #include <ac/string.h>
32 #include <ac/ctype.h>
33 #include <ac/unistd.h>
34 #include <ac/errno.h>
35 #include <ac/time.h>
36 #include <ac/socket.h>
37
38 #ifdef HAVE_CYRUS_SASL
39 #ifdef HAVE_SASL_SASL_H
40 #include <sasl/sasl.h>
41 #else
42 #include <sasl.h>
43 #endif
44 #endif
45
46 #include <ldap.h>
47
48 #include "ldif.h"
49 #include "lutil.h"
50 #include "lutil_ldap.h"
51 #include "ldap_defaults.h"
52 #include "ldap_pvt.h"
53 #include "lber_pvt.h"
54
55 #include "common.h"
56
57 /* input-related vars */
58
59 /* misc. parameters */
60 tool_type_t     tool_type;
61 int             contoper = 0;
62 int             debug = 0;
63 char            *infile = NULL;
64 int             dont = 0;
65 int             referrals = 0;
66 int             verbose = 0;
67 int             ldif = 0;
68 char            *prog = NULL;
69
70 /* connection */
71 char            *ldapuri = NULL;
72 char            *ldaphost = NULL;
73 int             ldapport = 0;
74 int             use_tls = 0;
75 int             protocol = -1;
76 int             version = 0;
77
78 /* authc/authz */
79 int             authmethod = -1;
80 char            *binddn = NULL;
81 int             want_bindpw = 0;
82 struct berval   passwd = { 0, NULL };
83 char            *pw_file = NULL;
84 #ifdef HAVE_CYRUS_SASL
85 unsigned        sasl_flags = LDAP_SASL_AUTOMATIC;
86 char            *sasl_realm = NULL;
87 char            *sasl_authc_id = NULL;
88 char            *sasl_authz_id = NULL;
89 char            *sasl_mech = NULL;
90 char            *sasl_secprops = NULL;
91 #endif
92
93 /* controls */
94 int             assertctl;
95 char            *assertion = NULL;
96 struct berval   assertionvalue = BER_BVNULL;
97 char            *authzid = NULL;
98 /* support deprecated early version of proxyAuthz */
99 #define LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ       "2.16.840.1.113730.3.4.12"
100 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
101 char            *proxydn = NULL;
102 #endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
103 int             manageDIT = 0;
104 int             manageDSAit = 0;
105 int             noop = 0;
106 int             ppolicy = 0;
107 int             preread = 0;
108 static char     *preread_attrs = NULL;
109 int             postread = 0;
110 static char     *postread_attrs = NULL;
111 ber_int_t       pr_morePagedResults = 1;
112 struct berval   pr_cookie = { 0, NULL };
113 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
114 int             chaining = 0;
115 static int      chainingResolve = -1;
116 static int      chainingContinuation = -1;
117 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
118 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
119 static int      sessionTracking = 0;
120 struct berval   stValue;
121 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
122
123 LDAPControl     *unknown_ctrls = NULL;
124 int             unknown_ctrls_num = 0;
125
126 /* options */
127 struct timeval  nettimeout = { -1 , 0 };
128
129 typedef int (*print_ctrl_fn)( LDAP *ld, LDAPControl *ctrl );
130
131 static int print_preread( LDAP *ld, LDAPControl *ctrl );
132 static int print_postread( LDAP *ld, LDAPControl *ctrl );
133 static int print_paged_results( LDAP *ld, LDAPControl *ctrl );
134 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
135 static int print_ppolicy( LDAP *ld, LDAPControl *ctrl );
136 #endif
137 static int print_sss( LDAP *ld, LDAPControl *ctrl );
138 #ifdef LDAP_CONTROL_X_DEREF
139 static int print_deref( LDAP *ld, LDAPControl *ctrl );
140 #endif
141 #ifdef LDAP_CONTROL_X_WHATFAILED
142 static int print_whatfailed( LDAP *ld, LDAPControl *ctrl );
143 #endif
144
145 static struct tool_ctrls_t {
146         const char      *oid;
147         unsigned        mask;
148         print_ctrl_fn   func;
149 } tool_ctrl_response[] = {
150         { LDAP_CONTROL_PRE_READ,                        TOOL_ALL,       print_preread },
151         { LDAP_CONTROL_POST_READ,                       TOOL_ALL,       print_postread },
152         { LDAP_CONTROL_PAGEDRESULTS,                    TOOL_SEARCH,    print_paged_results },
153 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
154         { LDAP_CONTROL_PASSWORDPOLICYRESPONSE,          TOOL_ALL,       print_ppolicy },
155 #endif
156         { LDAP_CONTROL_SORTRESPONSE,    TOOL_SEARCH,    print_sss },
157 #ifdef LDAP_CONTROL_X_DEREF
158         { LDAP_CONTROL_X_DEREF,                         TOOL_SEARCH,    print_deref },
159 #endif
160 #ifdef LDAP_CONTROL_X_WHATFAILED
161         { LDAP_CONTROL_X_WHATFAILED,                    TOOL_ALL,       print_whatfailed },
162 #endif
163         { NULL,                                         0,              NULL }
164 };
165
166 /* "features" */
167 enum { Intr_None = 0, Intr_Abandon, Intr_Cancel, Intr_Ignore }; 
168 static volatile sig_atomic_t    gotintr, abcan;
169
170
171 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
172 static int
173 st_value( LDAP *ld, struct berval *value )
174 {
175         char            *ip = NULL, *name = NULL;
176         struct berval   id = { 0 };
177         char            namebuf[ MAXHOSTNAMELEN ];
178
179         if ( gethostname( namebuf, sizeof( namebuf ) ) == 0 ) {
180                 struct hostent  *h;
181                 struct in_addr  addr;
182
183                 name = namebuf;
184
185                 h = gethostbyname( name );
186                 if ( h != NULL ) {
187                         AC_MEMCPY( &addr, h->h_addr, sizeof( addr ) );
188                         ip = inet_ntoa( addr );
189                 }
190         }
191
192 #ifdef HAVE_CYRUS_SASL
193         if ( sasl_authz_id != NULL ) {
194                 ber_str2bv( sasl_authz_id, 0, 0, &id );
195
196         } else if ( sasl_authc_id != NULL ) {
197                 ber_str2bv( sasl_authc_id, 0, 0, &id );
198
199         } else 
200 #endif /* HAVE_CYRUS_SASL */
201         if ( binddn != NULL ) {
202                 ber_str2bv( binddn, 0, 0, &id );
203         }
204
205         if ( ldap_create_session_tracking_value( ld,
206                 ip, name, LDAP_CONTROL_X_SESSION_TRACKING_USERNAME,
207                 &id, &stValue ) )
208         {
209                 fprintf( stderr, _("Session tracking control encoding error!\n") );
210                 return -1;
211         }
212
213         return 0;
214 }
215 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
216
217 RETSIGTYPE
218 do_sig( int sig )
219 {
220         gotintr = abcan;
221 }
222
223 void
224 tool_init( tool_type_t type )
225 {
226         tool_type = type;
227         ldap_pvt_setlocale(LC_MESSAGES, "");
228         ldap_pvt_bindtextdomain(OPENLDAP_PACKAGE, LDAP_LOCALEDIR);
229         ldap_pvt_textdomain(OPENLDAP_PACKAGE);
230 }
231
232 void
233 tool_destroy( void )
234 {
235 #ifdef HAVE_CYRUS_SASL
236         sasl_done();
237 #endif
238 #ifdef HAVE_TLS
239         ldap_pvt_tls_destroy();
240 #endif
241
242         if ( ldapuri != NULL ) {
243                 ber_memfree( ldapuri );
244                 ldapuri = NULL;
245         }
246
247         if ( pr_cookie.bv_val != NULL ) {
248                 ber_memfree( pr_cookie.bv_val );
249                 pr_cookie.bv_val = NULL;
250                 pr_cookie.bv_len = 0;
251         }
252 }
253
254 void
255 tool_common_usage( void )
256 {
257         static const char *const descriptions[] = {
258 N_("  -c         continuous operation mode (do not stop on errors)\n"),
259 N_("  -d level   set LDAP debugging level to `level'\n"),
260 N_("  -D binddn  bind DN\n"),
261 N_("  -e [!]<ext>[=<extparam>] general extensions (! indicates criticality)\n")
262 N_("             [!]assert=<filter>     (RFC 4528; a RFC 4515 Filter string)\n")
263 N_("             [!]authzid=<authzid>   (RFC 4370; \"dn:<dn>\" or \"u:<user>\")\n")
264 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
265 #if 0
266                  /* non-advertized support for proxyDN */
267 N_("             [!]proxydn=<dn>        (a RFC 4514 DN string)\n")
268 #endif
269 #endif
270 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
271 N_("             [!]chaining[=<resolveBehavior>[/<continuationBehavior>]]\n")
272 N_("                     one of \"chainingPreferred\", \"chainingRequired\",\n")
273 N_("                     \"referralsPreferred\", \"referralsRequired\"\n")
274 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
275 N_("             [!]manageDSAit         (RFC 3296)\n")
276 N_("             [!]noop\n")
277 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
278 N_("             ppolicy\n")
279 #endif
280 N_("             [!]postread[=<attrs>]  (RFC 4527; comma-separated attr list)\n")
281 N_("             [!]preread[=<attrs>]   (RFC 4527; comma-separated attr list)\n")
282 N_("             [!]relax\n")
283 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
284 N_("             [!]sessiontracking\n")
285 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
286 N_("             abandon, cancel, ignore (SIGINT sends abandon/cancel,\n"
287    "             or ignores response; if critical, doesn't wait for SIGINT.\n"
288    "             not really controls)\n")
289 N_("  -f file    read operations from `file'\n"),
290 N_("  -h host    LDAP server\n"),
291 N_("  -H URI     LDAP Uniform Resource Identifier(s)\n"),
292 N_("  -I         use SASL Interactive mode\n"),
293 N_("  -M         enable Manage DSA IT control (-MM to make critical)\n"),
294 N_("  -n         show what would be done but don't actually do it\n"),
295 N_("  -O props   SASL security properties\n"),
296 N_("  -o <opt>[=<optparam] general options\n"),
297 N_("             nettimeout=<timeout> (in seconds, or \"none\" or \"max\")\n"),
298 N_("  -p port    port on LDAP server\n"),
299 N_("  -P version protocol version (default: 3)\n"),
300 N_("  -Q         use SASL Quiet mode\n"),
301 N_("  -R realm   SASL realm\n"),
302 N_("  -U authcid SASL authentication identity\n"),
303 N_("  -v         run in verbose mode (diagnostics to standard output)\n"),
304 N_("  -V         print version info (-VV only)\n"),
305 N_("  -w passwd  bind password (for simple authentication)\n"),
306 N_("  -W         prompt for bind password\n"),
307 N_("  -x         Simple authentication\n"),
308 N_("  -X authzid SASL authorization identity (\"dn:<dn>\" or \"u:<user>\")\n"),
309 N_("  -y file    Read password from file\n"),
310 N_("  -Y mech    SASL mechanism\n"),
311 N_("  -Z         Start TLS request (-ZZ to require successful response)\n"),
312 NULL
313         };
314         const char *const *cpp;
315
316         fputs( _("Common options:\n"), stderr );
317         for( cpp = descriptions; *cpp != NULL; cpp++ ) {
318                 if( strchr( options, (*cpp)[3] ) || (*cpp)[3] == ' ' ) {
319                         fputs( _(*cpp), stderr );
320                 }
321         }
322 }
323
324 void tool_perror(
325         const char *func,
326         int err,
327         const char *extra,
328         const char *matched,
329         const char *info,
330         char **refs )
331 {
332         fprintf( stderr, "%s: %s (%d)%s\n",
333                 func, ldap_err2string( err ), err, extra ? extra : "" );
334
335         if ( matched && *matched ) {
336                 fprintf( stderr, _("\tmatched DN: %s\n"), matched );
337         }
338
339         if ( info && *info ) {
340                 fprintf( stderr, _("\tadditional info: %s\n"), info );
341         }
342
343         if ( refs && *refs ) {
344                 int i;
345                 fprintf( stderr, _("\treferrals:\n") );
346                 for( i=0; refs[i]; i++ ) {
347                         fprintf( stderr, "\t\t%s\n", refs[i] );
348                 }
349         }
350 }
351
352
353 void
354 tool_args( int argc, char **argv )
355 {
356         int i;
357
358         while (( i = getopt( argc, argv, options )) != EOF ) {
359                 int crit, ival;
360                 char *control, *cvalue, *next;
361                 switch( i ) {
362                 case 'c':       /* continuous operation mode */
363                         contoper++;
364                         break;
365                 case 'C':
366                         referrals++;
367                         break;
368                 case 'd':
369                         ival = strtol( optarg, &next, 10 );
370                         if (next == NULL || next[0] != '\0') {
371                                 fprintf( stderr, "%s: unable to parse debug value \"%s\"\n", prog, optarg);
372                                 exit(EXIT_FAILURE);
373                         }
374                         debug |= ival;
375                         break;
376                 case 'D':       /* bind DN */
377                         if( binddn != NULL ) {
378                                 fprintf( stderr, "%s: -D previously specified\n", prog );
379                                 exit( EXIT_FAILURE );
380                         }
381                         binddn = ber_strdup( optarg );
382                         break;
383                 case 'e':       /* general extensions (controls and such) */
384                         /* should be extended to support comma separated list of
385                          *      [!]key[=value] parameters, e.g.  -e !foo,bar=567
386                          */
387
388                         crit = 0;
389                         cvalue = NULL;
390                         if( optarg[0] == '!' ) {
391                                 crit = 1;
392                                 optarg++;
393                         }
394
395                         control = ber_strdup( optarg );
396                         if ( (cvalue = strchr( control, '=' )) != NULL ) {
397                                 *cvalue++ = '\0';
398                         }
399
400                         if ( strcasecmp( control, "assert" ) == 0 ) {
401                                 if( assertctl ) {
402                                         fprintf( stderr, "assert control previously specified\n");
403                                         exit( EXIT_FAILURE );
404                                 }
405                                 if( cvalue == NULL ) {
406                                         fprintf( stderr, "assert: control value expected\n" );
407                                         usage();
408                                 }
409
410                                 assertctl = 1 + crit;
411
412                                 assert( assertion == NULL );
413                                 assertion = cvalue;
414
415                         } else if ( strcasecmp( control, "authzid" ) == 0 ) {
416                                 if( authzid != NULL ) {
417                                         fprintf( stderr, "authzid control previously specified\n");
418                                         exit( EXIT_FAILURE );
419                                 }
420 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
421                                 if( proxydn != NULL ) {
422                                         fprintf( stderr, "authzid control incompatible with proxydn\n");
423                                         exit( EXIT_FAILURE );
424                                 }
425 #endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
426                                 if( cvalue == NULL ) {
427                                         fprintf( stderr, "authzid: control value expected\n" );
428                                         usage();
429                                 }
430                                 if( !crit ) {
431                                         fprintf( stderr, "authzid: must be marked critical\n" );
432                                         usage();
433                                 }
434
435                                 assert( authzid == NULL );
436                                 authzid = cvalue;
437
438 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
439                         } else if ( strcasecmp( control, "proxydn" ) == 0 ) {
440                                 if( proxydn != NULL ) {
441                                         fprintf( stderr, "proxydn control previously specified\n");
442                                         exit( EXIT_FAILURE );
443                                 }
444                                 if( authzid != NULL ) {
445                                         fprintf( stderr, "proxydn control incompatible with authzid\n");
446                                         exit( EXIT_FAILURE );
447                                 }
448                                 if( cvalue == NULL ) {
449                                         fprintf( stderr, "proxydn: control value expected\n" );
450                                         usage();
451                                 }
452                                 if( !crit ) {
453                                         fprintf( stderr, "proxydn: must be marked critical\n" );
454                                         usage();
455                                 }
456
457                                 assert( proxydn == NULL );
458                                 proxydn = cvalue;
459 #endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
460
461                         } else if ( ( strcasecmp( control, "relax" ) == 0 ) ||
462                                 ( strcasecmp( control, "manageDIT" ) == 0 ) )
463                         {
464                                 if( manageDIT ) {
465                                         fprintf( stderr,
466                                                 "relax control previously specified\n");
467                                         exit( EXIT_FAILURE );
468                                 }
469                                 if( cvalue != NULL ) {
470                                         fprintf( stderr,
471                                                 "relax: no control value expected\n" );
472                                         usage();
473                                 }
474
475                                 manageDIT = 1 + crit;
476
477                         } else if ( strcasecmp( control, "manageDSAit" ) == 0 ) {
478                                 if( manageDSAit ) {
479                                         fprintf( stderr,
480                                                 "manageDSAit control previously specified\n");
481                                         exit( EXIT_FAILURE );
482                                 }
483                                 if( cvalue != NULL ) {
484                                         fprintf( stderr,
485                                                 "manageDSAit: no control value expected\n" );
486                                         usage();
487                                 }
488
489                                 manageDSAit = 1 + crit;
490
491                         } else if ( strcasecmp( control, "noop" ) == 0 ) {
492                                 if( noop ) {
493                                         fprintf( stderr, "noop control previously specified\n");
494                                         exit( EXIT_FAILURE );
495                                 }
496                                 if( cvalue != NULL ) {
497                                         fprintf( stderr, "noop: no control value expected\n" );
498                                         usage();
499                                 }
500
501                                 noop = 1 + crit;
502
503 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
504                         } else if ( strcasecmp( control, "ppolicy" ) == 0 ) {
505                                 if( ppolicy ) {
506                                         fprintf( stderr, "ppolicy control previously specified\n");
507                                         exit( EXIT_FAILURE );
508                                 }
509                                 if( cvalue != NULL ) {
510                                         fprintf( stderr, "ppolicy: no control value expected\n" );
511                                         usage();
512                                 }
513                                 if( crit ) {
514                                         fprintf( stderr, "ppolicy: critical flag not allowed\n" );
515                                         usage();
516                                 }
517
518                                 ppolicy = 1;
519 #endif
520
521                         } else if ( strcasecmp( control, "preread" ) == 0 ) {
522                                 if( preread ) {
523                                         fprintf( stderr, "preread control previously specified\n");
524                                         exit( EXIT_FAILURE );
525                                 }
526
527                                 preread = 1 + crit;
528                                 preread_attrs = cvalue;
529
530                         } else if ( strcasecmp( control, "postread" ) == 0 ) {
531                                 if( postread ) {
532                                         fprintf( stderr, "postread control previously specified\n");
533                                         exit( EXIT_FAILURE );
534                                 }
535
536                                 postread = 1 + crit;
537                                 postread_attrs = cvalue;
538
539 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
540                         } else if ( strcasecmp( control, "chaining" ) == 0 ) {
541                                 chaining = 1 + crit;
542
543                                 if ( cvalue != NULL ) {
544                                         char    *continuation;
545
546                                         continuation = strchr( cvalue, '/' );
547                                         if ( continuation ) {
548                                                 /* FIXME: this makes sense only in searches */
549                                                 *continuation++ = '\0';
550                                                 if ( strcasecmp( continuation, "chainingPreferred" ) == 0 ) {
551                                                         chainingContinuation = LDAP_CHAINING_PREFERRED;
552                                                 } else if ( strcasecmp( continuation, "chainingRequired" ) == 0 ) {
553                                                         chainingContinuation = LDAP_CHAINING_REQUIRED;
554                                                 } else if ( strcasecmp( continuation, "referralsPreferred" ) == 0 ) {
555                                                         chainingContinuation = LDAP_REFERRALS_PREFERRED;
556                                                 } else if ( strcasecmp( continuation, "referralsRequired" ) == 0 ) {
557                                                         chainingContinuation = LDAP_REFERRALS_REQUIRED;
558                                                 } else {
559                                                         fprintf( stderr,
560                                                                 "chaining behavior control "
561                                                                 "continuation value \"%s\" invalid\n",
562                                                                 continuation );
563                                                         exit( EXIT_FAILURE );
564                                                 }
565                                         }
566         
567                                         if ( strcasecmp( cvalue, "chainingPreferred" ) == 0 ) {
568                                                 chainingResolve = LDAP_CHAINING_PREFERRED;
569                                         } else if ( strcasecmp( cvalue, "chainingRequired" ) == 0 ) {
570                                                 chainingResolve = LDAP_CHAINING_REQUIRED;
571                                         } else if ( strcasecmp( cvalue, "referralsPreferred" ) == 0 ) {
572                                                 chainingResolve = LDAP_REFERRALS_PREFERRED;
573                                         } else if ( strcasecmp( cvalue, "referralsRequired" ) == 0 ) {
574                                                 chainingResolve = LDAP_REFERRALS_REQUIRED;
575                                         } else {
576                                                 fprintf( stderr,
577                                                         "chaining behavior control "
578                                                         "resolve value \"%s\" invalid\n",
579                                                         cvalue);
580                                                 exit( EXIT_FAILURE );
581                                         }
582                                 }
583 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
584
585                         /* this shouldn't go here, really; but it's a feature... */
586                         } else if ( strcasecmp( control, "abandon" ) == 0 ) {
587                                 abcan = Intr_Abandon;
588                                 if ( crit ) {
589                                         gotintr = abcan;
590                                 }
591
592                         } else if ( strcasecmp( control, "cancel" ) == 0 ) {
593                                 abcan = Intr_Cancel;
594                                 if ( crit ) {
595                                         gotintr = abcan;
596                                 }
597
598                         } else if ( strcasecmp( control, "ignore" ) == 0 ) {
599                                 abcan = Intr_Ignore;
600                                 if ( crit ) {
601                                         gotintr = abcan;
602                                 }
603
604 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
605                         } else if ( strcasecmp( control, "sessiontracking" ) == 0 ) {
606                                 if ( sessionTracking ) {
607                                         fprintf( stderr, "%s: session tracking can be only specified once\n", prog );
608                                         exit( EXIT_FAILURE );
609                                 }
610                                 sessionTracking = 1;
611 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
612
613                         } else if ( tool_is_oid( control ) ) {
614                                 LDAPControl     *tmpctrls, ctrl;
615
616                                 tmpctrls = (LDAPControl *)realloc( unknown_ctrls,
617                                         (unknown_ctrls_num + 1)*sizeof( LDAPControl ) );
618                                 if ( tmpctrls == NULL ) {
619                                         fprintf( stderr, "%s: no memory?\n", prog );
620                                         exit( EXIT_FAILURE );
621                                 }
622                                 unknown_ctrls = tmpctrls;
623                                 ctrl.ldctl_oid = control;
624                                 ctrl.ldctl_value.bv_val = NULL;
625                                 ctrl.ldctl_value.bv_len = 0;
626                                 ctrl.ldctl_iscritical = crit;
627
628                                 if ( cvalue != NULL ) {
629                                         struct berval   bv;
630                                         size_t          len = strlen( cvalue );
631                                         int             retcode;
632
633                                         bv.bv_len = LUTIL_BASE64_DECODE_LEN( len );
634                                         bv.bv_val = ber_memalloc( bv.bv_len + 1 );
635
636                                         retcode = lutil_b64_pton( cvalue,
637                                                 (unsigned char *)bv.bv_val,
638                                                 bv.bv_len );
639
640                                         if ( retcode == -1 || (unsigned) retcode > bv.bv_len ) {
641                                                 fprintf( stderr, "Unable to parse value of general control %s\n",
642                                                         control );
643                                                 usage();
644                                         }
645
646                                         bv.bv_len = retcode;
647                                         ctrl.ldctl_value = bv;
648                                 }
649
650                                 unknown_ctrls[ unknown_ctrls_num ] = ctrl;
651                                 unknown_ctrls_num++;
652
653                         } else {
654                                 fprintf( stderr, "Invalid general control name: %s\n",
655                                         control );
656                                 usage();
657                         }
658                         break;
659                 case 'f':       /* read from file */
660                         if( infile != NULL ) {
661                                 fprintf( stderr, "%s: -f previously specified\n", prog );
662                                 exit( EXIT_FAILURE );
663                         }
664                         infile = ber_strdup( optarg );
665                         break;
666                 case 'h':       /* ldap host */
667                         if( ldaphost != NULL ) {
668                                 fprintf( stderr, "%s: -h previously specified\n", prog );
669                                 exit( EXIT_FAILURE );
670                         }
671                         ldaphost = ber_strdup( optarg );
672                         break;
673                 case 'H':       /* ldap URI */
674                         if( ldapuri != NULL ) {
675                                 fprintf( stderr, "%s: -H previously specified\n", prog );
676                                 exit( EXIT_FAILURE );
677                         }
678                         ldapuri = ber_strdup( optarg );
679                         break;
680                 case 'I':
681 #ifdef HAVE_CYRUS_SASL
682                         if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
683                                 fprintf( stderr, "%s: incompatible previous "
684                                         "authentication choice\n",
685                                         prog );
686                                 exit( EXIT_FAILURE );
687                         }
688                         authmethod = LDAP_AUTH_SASL;
689                         sasl_flags = LDAP_SASL_INTERACTIVE;
690                         break;
691 #else
692                         fprintf( stderr, "%s: was not compiled with SASL support\n",
693                                 prog );
694                         exit( EXIT_FAILURE );
695 #endif
696                 case 'M':
697                         /* enable Manage DSA IT */
698                         manageDSAit++;
699                         break;
700                 case 'n':       /* print operations, don't actually do them */
701                         dont++;
702                         break;
703                 case 'o':
704                         control = ber_strdup( optarg );
705                         if ( (cvalue = strchr( control, '=' )) != NULL ) {
706                                 *cvalue++ = '\0';
707                         }
708
709                         if ( strcasecmp( control, "nettimeout" ) == 0 ) {
710                                 if( nettimeout.tv_sec != -1 ) {
711                                         fprintf( stderr, "nettimeout option previously specified\n");
712                                         exit( EXIT_FAILURE );
713                                 }
714                                 if( cvalue == NULL || cvalue[0] == '\0' ) {
715                                         fprintf( stderr, "nettimeout: option value expected\n" );
716                                         usage();
717                                 }
718                                 if ( strcasecmp( cvalue, "none" ) == 0 ) {
719                                         nettimeout.tv_sec = 0;
720                                 } else if ( strcasecmp( cvalue, "max" ) == 0 ) {
721                                         nettimeout.tv_sec = LDAP_MAXINT;
722                                 } else {
723                                         ival = strtol( cvalue, &next, 10 );
724                                         if ( next == NULL || next[0] != '\0' ) {
725                                                 fprintf( stderr,
726                                                         _("Unable to parse network timeout \"%s\"\n"), cvalue );
727                                                 exit( EXIT_FAILURE );
728                                         }
729                                         nettimeout.tv_sec = ival;
730                                 }
731                                 if( nettimeout.tv_sec < 0 || nettimeout.tv_sec > LDAP_MAXINT ) {
732                                         fprintf( stderr, _("%s: invalid network timeout (%ld) specified\n"),
733                                                 prog, (long)nettimeout.tv_sec );
734                                         exit( EXIT_FAILURE );
735                                 }
736                         } else {
737                                 fprintf( stderr, "Invalid general option name: %s\n",
738                                         control );
739                                 usage();
740                         }
741                         break;
742                 case 'O':
743 #ifdef HAVE_CYRUS_SASL
744                         if( sasl_secprops != NULL ) {
745                                 fprintf( stderr, "%s: -O previously specified\n", prog );
746                                 exit( EXIT_FAILURE );
747                         }
748                         if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
749                                 fprintf( stderr, "%s: incompatible previous "
750                                         "authentication choice\n", prog );
751                                 exit( EXIT_FAILURE );
752                         }
753                         authmethod = LDAP_AUTH_SASL;
754                         sasl_secprops = ber_strdup( optarg );
755 #else
756                         fprintf( stderr, "%s: not compiled with SASL support\n", prog );
757                         exit( EXIT_FAILURE );
758 #endif
759                         break;
760                 case 'p':
761                         if( ldapport ) {
762                                 fprintf( stderr, "%s: -p previously specified\n", prog );
763                                 exit( EXIT_FAILURE );
764                         }
765                         ival = strtol( optarg, &next, 10 );
766                         if ( next == NULL || next[0] != '\0' ) {
767                                 fprintf( stderr, "%s: unable to parse port number \"%s\"\n", prog, optarg );
768                                 exit( EXIT_FAILURE );
769                         }
770                         ldapport = ival;
771                         break;
772                 case 'P':
773                         ival = strtol( optarg, &next, 10 );
774                         if ( next == NULL || next[0] != '\0' ) {
775                                 fprintf( stderr, "%s: unable to parse protocol version \"%s\"\n", prog, optarg );
776                                 exit( EXIT_FAILURE );
777                         }
778                         switch( ival ) {
779                         case 2:
780                                 if( protocol == LDAP_VERSION3 ) {
781                                         fprintf( stderr, "%s: -P 2 incompatible with version %d\n",
782                                                 prog, protocol );
783                                         exit( EXIT_FAILURE );
784                                 }
785                                 protocol = LDAP_VERSION2;
786                                 break;
787                         case 3:
788                                 if( protocol == LDAP_VERSION2 ) {
789                                         fprintf( stderr, "%s: -P 2 incompatible with version %d\n",
790                                                 prog, protocol );
791                                         exit( EXIT_FAILURE );
792                                 }
793                                 protocol = LDAP_VERSION3;
794                                 break;
795                         default:
796                                 fprintf( stderr, "%s: protocol version should be 2 or 3\n",
797                                         prog );
798                                 usage();
799                         }
800                         break;
801                 case 'Q':
802 #ifdef HAVE_CYRUS_SASL
803                         if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
804                                 fprintf( stderr, "%s: incompatible previous "
805                                         "authentication choice\n",
806                                         prog );
807                                 exit( EXIT_FAILURE );
808                         }
809                         authmethod = LDAP_AUTH_SASL;
810                         sasl_flags = LDAP_SASL_QUIET;
811                         break;
812 #else
813                         fprintf( stderr, "%s: not compiled with SASL support\n",
814                                 prog );
815                         exit( EXIT_FAILURE );
816 #endif
817                 case 'R':
818 #ifdef HAVE_CYRUS_SASL
819                         if( sasl_realm != NULL ) {
820                                 fprintf( stderr, "%s: -R previously specified\n", prog );
821                                 exit( EXIT_FAILURE );
822                         }
823                         if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
824                                 fprintf( stderr, "%s: incompatible previous "
825                                         "authentication choice\n",
826                                         prog );
827                                 exit( EXIT_FAILURE );
828                         }
829                         authmethod = LDAP_AUTH_SASL;
830                         sasl_realm = ber_strdup( optarg );
831 #else
832                         fprintf( stderr, "%s: not compiled with SASL support\n",
833                                 prog );
834                         exit( EXIT_FAILURE );
835 #endif
836                         break;
837                 case 'U':
838 #ifdef HAVE_CYRUS_SASL
839                         if( sasl_authc_id != NULL ) {
840                                 fprintf( stderr, "%s: -U previously specified\n", prog );
841                                 exit( EXIT_FAILURE );
842                         }
843                         if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
844                                 fprintf( stderr, "%s: incompatible previous "
845                                         "authentication choice\n",
846                                         prog );
847                                 exit( EXIT_FAILURE );
848                         }
849                         authmethod = LDAP_AUTH_SASL;
850                         sasl_authc_id = ber_strdup( optarg );
851 #else
852                         fprintf( stderr, "%s: not compiled with SASL support\n",
853                                 prog );
854                         exit( EXIT_FAILURE );
855 #endif
856                         break;
857                 case 'v':       /* verbose mode */
858                         verbose++;
859                         break;
860                 case 'V':       /* version */
861                         version++;
862                         break;
863                 case 'w':       /* password */
864                         passwd.bv_val = ber_strdup( optarg );
865                         {
866                                 char* p;
867
868                                 for( p = optarg; *p != '\0'; p++ ) {
869                                         *p = '\0';
870                                 }
871                         }
872                         passwd.bv_len = strlen( passwd.bv_val );
873                         break;
874                 case 'W':
875                         want_bindpw++;
876                         break;
877                 case 'y':
878                         pw_file = optarg;
879                         break;
880                 case 'Y':
881 #ifdef HAVE_CYRUS_SASL
882                         if( sasl_mech != NULL ) {
883                                 fprintf( stderr, "%s: -Y previously specified\n", prog );
884                                 exit( EXIT_FAILURE );
885                         }
886                         if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
887                                 fprintf( stderr,
888                                         "%s: incompatible with authentication choice\n", prog );
889                                 exit( EXIT_FAILURE );
890                         }
891                         authmethod = LDAP_AUTH_SASL;
892                         sasl_mech = ber_strdup( optarg );
893 #else
894                         fprintf( stderr, "%s: not compiled with SASL support\n", prog );
895                         exit( EXIT_FAILURE );
896 #endif
897                         break;
898                 case 'x':
899                         if( authmethod != -1 && authmethod != LDAP_AUTH_SIMPLE ) {
900                                 fprintf( stderr, "%s: incompatible with previous "
901                                         "authentication choice\n", prog );
902                                 exit( EXIT_FAILURE );
903                         }
904                         authmethod = LDAP_AUTH_SIMPLE;
905                         break;
906                 case 'X':
907 #ifdef HAVE_CYRUS_SASL
908                         if( sasl_authz_id != NULL ) {
909                                 fprintf( stderr, "%s: -X previously specified\n", prog );
910                                 exit( EXIT_FAILURE );
911                         }
912                         if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
913                                 fprintf( stderr, "%s: -X incompatible with "
914                                         "authentication choice\n", prog );
915                                 exit( EXIT_FAILURE );
916                         }
917                         authmethod = LDAP_AUTH_SASL;
918                         sasl_authz_id = ber_strdup( optarg );
919 #else
920                         fprintf( stderr, "%s: not compiled with SASL support\n", prog );
921                         exit( EXIT_FAILURE );
922 #endif
923                         break;
924                 case 'Z':
925 #ifdef HAVE_TLS
926                         use_tls++;
927 #else
928                         fprintf( stderr, "%s: not compiled with TLS support\n", prog );
929                         exit( EXIT_FAILURE );
930 #endif
931                         break;
932                 default:
933                         if( handle_private_option( i ) ) break;
934                         fprintf( stderr, "%s: unrecognized option -%c\n",
935                                 prog, optopt );
936                         usage();
937                 }
938         }
939
940         {
941                 /* prevent bad linking */
942                 LDAPAPIInfo api;
943                 api.ldapai_info_version = LDAP_API_INFO_VERSION;
944
945                 if ( ldap_get_option(NULL, LDAP_OPT_API_INFO, &api)
946                         != LDAP_OPT_SUCCESS )
947                 {
948                         fprintf( stderr, "%s: ldap_get_option(API_INFO) failed\n", prog );
949                         exit( EXIT_FAILURE );
950                 }
951
952                 if (api.ldapai_info_version != LDAP_API_INFO_VERSION) {
953                         fprintf( stderr, "LDAP APIInfo version mismatch: "
954                                 "library %d, header %d\n",
955                                 api.ldapai_info_version, LDAP_API_INFO_VERSION );
956                         exit( EXIT_FAILURE );
957                 }
958
959                 if( api.ldapai_api_version != LDAP_API_VERSION ) {
960                         fprintf( stderr, "LDAP API version mismatch: "
961                                 "library %d, header %d\n",
962                                 api.ldapai_api_version, LDAP_API_VERSION );
963                         exit( EXIT_FAILURE );
964                 }
965
966                 if( strcmp(api.ldapai_vendor_name, LDAP_VENDOR_NAME ) != 0 ) {
967                         fprintf( stderr, "LDAP vendor name mismatch: "
968                                 "library %s, header %s\n",
969                                 api.ldapai_vendor_name, LDAP_VENDOR_NAME );
970                         exit( EXIT_FAILURE );
971                 }
972
973                 if( api.ldapai_vendor_version != LDAP_VENDOR_VERSION ) {
974                         fprintf( stderr, "LDAP vendor version mismatch: "
975                                 "library %d, header %d\n",
976                                 api.ldapai_vendor_version, LDAP_VENDOR_VERSION );
977                         exit( EXIT_FAILURE );
978                 }
979
980                 if (version) {
981                         fprintf( stderr, "%s: %s\t(LDAP library: %s %d)\n",
982                                 prog, __Version,
983                                 LDAP_VENDOR_NAME, LDAP_VENDOR_VERSION );
984                         if (version > 1) exit( EXIT_SUCCESS );
985                 }
986
987                 ldap_memfree( api.ldapai_vendor_name );
988                 ber_memvfree( (void **)api.ldapai_extensions );
989         }
990
991         if (protocol == -1)
992                 protocol = LDAP_VERSION3;
993
994         if (authmethod == -1 && protocol > LDAP_VERSION2) {
995 #ifdef HAVE_CYRUS_SASL
996                 if ( binddn != NULL ) {
997                         authmethod = LDAP_AUTH_SIMPLE;
998                 } else {
999                         authmethod = LDAP_AUTH_SASL;
1000                 }
1001 #else
1002                 authmethod = LDAP_AUTH_SIMPLE;
1003 #endif
1004         }
1005
1006         if( ldapuri == NULL ) {
1007                 if( ldapport && ( ldaphost == NULL )) {
1008                         fprintf( stderr, "%s: -p without -h is invalid.\n", prog );
1009                         exit( EXIT_FAILURE );
1010                 }
1011         } else {
1012                 if( ldaphost != NULL ) {
1013                         fprintf( stderr, "%s: -H incompatible with -h\n", prog );
1014                         exit( EXIT_FAILURE );
1015                 }
1016                 if( ldapport ) {
1017                         fprintf( stderr, "%s: -H incompatible with -p\n", prog );
1018                         exit( EXIT_FAILURE );
1019                 }
1020         }
1021
1022         if( protocol == LDAP_VERSION2 ) {
1023                 if( assertctl || authzid || manageDIT || manageDSAit ||
1024 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
1025                         proxydn ||
1026 #endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
1027 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
1028                         chaining ||
1029 #endif
1030 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
1031                         sessionTracking ||
1032 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
1033                         noop || ppolicy || preread || postread )
1034                 {
1035                         fprintf( stderr, "%s: -e/-M incompatible with LDAPv2\n", prog );
1036                         exit( EXIT_FAILURE );
1037                 }
1038 #ifdef HAVE_TLS
1039                 if( use_tls ) {
1040                         fprintf( stderr, "%s: -Z incompatible with LDAPv2\n", prog );
1041                         exit( EXIT_FAILURE );
1042                 }
1043 #endif
1044 #ifdef HAVE_CYRUS_SASL
1045                 if( authmethod == LDAP_AUTH_SASL ) {
1046                         fprintf( stderr, "%s: -[IOQRUXY] incompatible with LDAPv2\n",
1047                                 prog );
1048                         exit( EXIT_FAILURE );
1049                 }
1050 #endif
1051         }
1052 }
1053
1054
1055 LDAP *
1056 tool_conn_setup( int dont, void (*private_setup)( LDAP * ) )
1057 {
1058         LDAP *ld = NULL;
1059
1060         if ( debug ) {
1061                 if( ber_set_option( NULL, LBER_OPT_DEBUG_LEVEL, &debug )
1062                         != LBER_OPT_SUCCESS )
1063                 {
1064                         fprintf( stderr,
1065                                 "Could not set LBER_OPT_DEBUG_LEVEL %d\n", debug );
1066                 }
1067                 if( ldap_set_option( NULL, LDAP_OPT_DEBUG_LEVEL, &debug )
1068                         != LDAP_OPT_SUCCESS )
1069                 {
1070                         fprintf( stderr,
1071                                 "Could not set LDAP_OPT_DEBUG_LEVEL %d\n", debug );
1072                 }
1073         }
1074
1075 #ifdef SIGPIPE
1076         (void) SIGNAL( SIGPIPE, SIG_IGN );
1077 #endif
1078
1079         if ( abcan ) {
1080                 SIGNAL( SIGINT, do_sig );
1081         }
1082
1083         if ( !dont ) {
1084                 int rc;
1085
1086                 if( ( ldaphost != NULL || ldapport ) && ( ldapuri == NULL ) ) {
1087                         /* construct URL */
1088                         LDAPURLDesc url;
1089                         memset( &url, 0, sizeof(url));
1090
1091                         url.lud_scheme = "ldap";
1092                         url.lud_host = ldaphost;
1093                         url.lud_port = ldapport;
1094                         url.lud_scope = LDAP_SCOPE_DEFAULT;
1095
1096                         ldapuri = ldap_url_desc2str( &url );
1097
1098                 } else if ( ldapuri != NULL ) {
1099                         LDAPURLDesc     *ludlist, **ludp;
1100                         char            **urls = NULL;
1101                         int             nurls = 0;
1102
1103                         rc = ldap_url_parselist( &ludlist, ldapuri );
1104                         if ( rc != LDAP_URL_SUCCESS ) {
1105                                 fprintf( stderr,
1106                                         "Could not parse LDAP URI(s)=%s (%d)\n",
1107                                         ldapuri, rc );
1108                                 exit( EXIT_FAILURE );
1109                         }
1110
1111                         for ( ludp = &ludlist; *ludp != NULL; ) {
1112                                 LDAPURLDesc     *lud = *ludp;
1113                                 char            **tmp;
1114
1115                                 if ( lud->lud_dn != NULL && lud->lud_dn[ 0 ] != '\0' &&
1116                                         ( lud->lud_host == NULL || lud->lud_host[0] == '\0' ) )
1117                                 {
1118                                         /* if no host but a DN is provided,
1119                                          * use DNS SRV to gather the host list
1120                                          * and turn it into a list of URIs
1121                                          * using the scheme provided */
1122                                         char    *domain = NULL,
1123                                                 *hostlist = NULL,
1124                                                 **hosts = NULL;
1125                                         int     i,
1126                                                 len_proto = strlen( lud->lud_scheme );
1127
1128                                         if ( ldap_dn2domain( lud->lud_dn, &domain )
1129                                                 || domain == NULL )
1130                                         {
1131                                                 fprintf( stderr,
1132                                                         "DNS SRV: Could not turn "
1133                                                         "DN=\"%s\" into a domain\n",
1134                                                         lud->lud_dn );
1135                                                 goto dnssrv_free;
1136                                         }
1137                                         
1138                                         rc = ldap_domain2hostlist( domain, &hostlist );
1139                                         if ( rc ) {
1140                                                 fprintf( stderr,
1141                                                         "DNS SRV: Could not turn "
1142                                                         "domain=%s into a hostlist\n",
1143                                                         domain );
1144                                                 goto dnssrv_free;
1145                                         }
1146
1147                                         hosts = ldap_str2charray( hostlist, " " );
1148                                         if ( hosts == NULL ) {
1149                                                 fprintf( stderr,
1150                                                         "DNS SRV: Could not parse "
1151                                                         "hostlist=\"%s\"\n",
1152                                                         hostlist );
1153                                                 goto dnssrv_free;
1154                                         }
1155
1156                                         for ( i = 0; hosts[ i ] != NULL; i++ )
1157                                                 /* count'em */ ;
1158
1159                                         tmp = (char **)realloc( urls, sizeof( char * ) * ( nurls + i + 1 ) );
1160                                         if ( tmp == NULL ) {
1161                                                 fprintf( stderr,
1162                                                         "DNS SRV: out of memory?\n" );
1163                                                 goto dnssrv_free;
1164                                         }
1165                                         urls = tmp;
1166                                         urls[ nurls ] = NULL;
1167
1168                                         for ( i = 0; hosts[ i ] != NULL; i++ ) {
1169                                                 size_t  len = len_proto
1170                                                         + STRLENOF( "://" )
1171                                                         + strlen( hosts[ i ] )
1172                                                         + 1;
1173
1174                                                 urls[ nurls + i + 1 ] = NULL;
1175                                                 urls[ nurls + i ] = (char *)malloc( sizeof( char ) * len );
1176                                                 if ( urls[ nurls + i ] == NULL ) {
1177                                                         fprintf( stderr,
1178                                                                 "DNS SRV: out of memory?\n" );
1179                                                         goto dnssrv_free;
1180                                                 }
1181
1182                                                 snprintf( urls[ nurls + i ], len, "%s://%s",
1183                                                         lud->lud_scheme, hosts[ i ] );
1184                                         }
1185                                         nurls += i;
1186
1187 dnssrv_free:;
1188                                         ber_memvfree( (void **)hosts );
1189                                         ber_memfree( hostlist );
1190                                         ber_memfree( domain );
1191
1192                                 } else {
1193                                         tmp = (char **)realloc( urls, sizeof( char * ) * ( nurls + 2 ) );
1194                                         if ( tmp == NULL ) {
1195                                                 fprintf( stderr,
1196                                                         "DNS SRV: out of memory?\n" );
1197                                                 break;
1198                                         }
1199                                         urls = tmp;
1200                                         urls[ nurls + 1 ] = NULL;
1201
1202                                         urls[ nurls ] = ldap_url_desc2str( lud );
1203                                         if ( urls[ nurls ] == NULL ) {
1204                                                 fprintf( stderr,
1205                                                         "DNS SRV: out of memory?\n" );
1206                                                 break;
1207                                         }
1208                                         nurls++;
1209                                 }
1210
1211                                 *ludp = lud->lud_next;
1212
1213                                 lud->lud_next = NULL;
1214                                 ldap_free_urldesc( lud );
1215                         }
1216
1217                         if ( ludlist != NULL ) {
1218                                 ldap_free_urllist( ludlist );
1219                                 exit( EXIT_FAILURE );
1220
1221                         } else if ( urls == NULL ) {
1222                                 exit( EXIT_FAILURE );
1223                         }
1224
1225                         ldap_memfree( ldapuri );
1226                         ldapuri = ldap_charray2str( urls, " " );
1227                         ber_memvfree( (void **)urls );
1228                 }
1229
1230                 if ( verbose ) {
1231                         fprintf( stderr, "ldap_initialize( %s )\n",
1232                                 ldapuri != NULL ? ldapuri : "<DEFAULT>" );
1233                 }
1234                 rc = ldap_initialize( &ld, ldapuri );
1235                 if( rc != LDAP_SUCCESS ) {
1236                         fprintf( stderr,
1237                                 "Could not create LDAP session handle for URI=%s (%d): %s\n",
1238                                 ldapuri, rc, ldap_err2string(rc) );
1239                         exit( EXIT_FAILURE );
1240                 }
1241
1242                 if( private_setup ) private_setup( ld );
1243
1244                 /* referrals */
1245                 if( ldap_set_option( ld, LDAP_OPT_REFERRALS,
1246                         referrals ? LDAP_OPT_ON : LDAP_OPT_OFF ) != LDAP_OPT_SUCCESS )
1247                 {
1248                         fprintf( stderr, "Could not set LDAP_OPT_REFERRALS %s\n",
1249                                 referrals ? "on" : "off" );
1250                         exit( EXIT_FAILURE );
1251                 }
1252
1253                 if( ldap_set_option( ld, LDAP_OPT_PROTOCOL_VERSION, &protocol )
1254                         != LDAP_OPT_SUCCESS )
1255                 {
1256                         fprintf( stderr, "Could not set LDAP_OPT_PROTOCOL_VERSION %d\n",
1257                                 protocol );
1258                         exit( EXIT_FAILURE );
1259                 }
1260
1261                 if ( use_tls ) {
1262                         rc = ldap_start_tls_s( ld, NULL, NULL );
1263                         if ( rc != LDAP_SUCCESS ) {
1264                                 tool_perror( "ldap_start_tls", rc, NULL, NULL, NULL, NULL );
1265                                 if ( use_tls > 1 ) {
1266                                         exit( EXIT_FAILURE );
1267                                 }
1268                         }
1269                 }
1270
1271                 if ( nettimeout.tv_sec > 0 ) {
1272                         if ( ldap_set_option( ld, LDAP_OPT_NETWORK_TIMEOUT, (void *) &nettimeout )
1273                                 != LDAP_OPT_SUCCESS )
1274                         {
1275                                 fprintf( stderr, "Could not set LDAP_OPT_NETWORK_TIMEOUT %ld\n",
1276                                         (long)nettimeout.tv_sec );
1277                                 exit( EXIT_FAILURE );
1278                         }
1279                 }
1280         }
1281
1282         return ld;
1283 }
1284
1285
1286 void
1287 tool_bind( LDAP *ld )
1288 {
1289         LDAPControl     **sctrlsp = NULL;
1290         LDAPControl     *sctrls[3];
1291         LDAPControl     sctrl[3];
1292         int             nsctrls = 0;
1293
1294 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
1295         if ( ppolicy ) {
1296                 LDAPControl c;
1297                 c.ldctl_oid = LDAP_CONTROL_PASSWORDPOLICYREQUEST;
1298                 c.ldctl_value.bv_val = NULL;
1299                 c.ldctl_value.bv_len = 0;
1300                 c.ldctl_iscritical = 0;
1301                 sctrl[nsctrls] = c;
1302                 sctrls[nsctrls] = &sctrl[nsctrls];
1303                 sctrls[++nsctrls] = NULL;
1304         }
1305 #endif
1306
1307 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
1308         if ( sessionTracking ) {
1309                 LDAPControl c;
1310
1311                 if (stValue.bv_val == NULL && st_value( ld, &stValue ) ) {
1312                         exit( EXIT_FAILURE );
1313                 }
1314
1315                 c.ldctl_oid = LDAP_CONTROL_X_SESSION_TRACKING;
1316                 c.ldctl_iscritical = 0;
1317                 ber_dupbv( &c.ldctl_value, &stValue );
1318
1319                 sctrl[nsctrls] = c;
1320                 sctrls[nsctrls] = &sctrl[nsctrls];
1321                 sctrls[++nsctrls] = NULL;
1322         }
1323 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
1324
1325         if ( nsctrls ) {
1326                 sctrlsp = sctrls;
1327         }
1328
1329         assert( nsctrls < (int) (sizeof(sctrls)/sizeof(sctrls[0])) );
1330
1331         if ( authmethod == LDAP_AUTH_SASL ) {
1332 #ifdef HAVE_CYRUS_SASL
1333                 void *defaults;
1334                 int rc;
1335
1336                 if( sasl_secprops != NULL ) {
1337                         rc = ldap_set_option( ld, LDAP_OPT_X_SASL_SECPROPS,
1338                                 (void *) sasl_secprops );
1339
1340                         if( rc != LDAP_OPT_SUCCESS ) {
1341                                 fprintf( stderr,
1342                                         "Could not set LDAP_OPT_X_SASL_SECPROPS: %s\n",
1343                                         sasl_secprops );
1344                                 exit( LDAP_LOCAL_ERROR );
1345                         }
1346                 }
1347
1348                 defaults = lutil_sasl_defaults( ld,
1349                         sasl_mech,
1350                         sasl_realm,
1351                         sasl_authc_id,
1352                         passwd.bv_val,
1353                         sasl_authz_id );
1354
1355                 rc = ldap_sasl_interactive_bind_s( ld, binddn, sasl_mech,
1356                         sctrlsp,
1357                         NULL, sasl_flags, lutil_sasl_interact, defaults );
1358
1359                 lutil_sasl_freedefs( defaults );
1360                 if( rc != LDAP_SUCCESS ) {
1361                         tool_perror( "ldap_sasl_interactive_bind_s",
1362                                 rc, NULL, NULL, NULL, NULL );
1363                         exit( rc );
1364                 }
1365 #else
1366                 fprintf( stderr, "%s: not compiled with SASL support\n", prog );
1367                 exit( LDAP_NOT_SUPPORTED );
1368 #endif
1369         } else {
1370                 int msgid, err, rc;
1371                 LDAPMessage *result;
1372                 LDAPControl **ctrls;
1373                 char msgbuf[256];
1374                 char *matched = NULL;
1375                 char *info = NULL;
1376                 char **refs = NULL;
1377
1378                 msgbuf[0] = 0;
1379
1380                 {
1381                         /* simple bind */
1382                         rc = ldap_sasl_bind( ld, binddn, LDAP_SASL_SIMPLE, &passwd,
1383                                 sctrlsp, NULL, &msgid );
1384                         if ( msgid == -1 ) {
1385                                 tool_perror( "ldap_sasl_bind(SIMPLE)", rc,
1386                                         NULL, NULL, NULL, NULL );
1387                                 exit( rc );
1388                         }
1389                 }
1390
1391                 if ( ldap_result( ld, msgid, LDAP_MSG_ALL, NULL, &result ) == -1 ) {
1392                         tool_perror( "ldap_result", -1, NULL, NULL, NULL, NULL );
1393                         exit( LDAP_LOCAL_ERROR );
1394                 }
1395
1396                 rc = ldap_parse_result( ld, result, &err, &matched, &info, &refs,
1397                         &ctrls, 1 );
1398                 if ( rc != LDAP_SUCCESS ) {
1399                         tool_perror( "ldap_bind parse result", rc, NULL, matched, info, refs );
1400                         exit( LDAP_LOCAL_ERROR );
1401                 }
1402
1403 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
1404                 if ( ctrls && ppolicy ) {
1405                         LDAPControl *ctrl;
1406                         int expire, grace, len = 0;
1407                         LDAPPasswordPolicyError pErr = -1;
1408                         
1409                         ctrl = ldap_control_find( LDAP_CONTROL_PASSWORDPOLICYRESPONSE,
1410                                 ctrls, NULL );
1411
1412                         if ( ctrl && ldap_parse_passwordpolicy_control( ld, ctrl,
1413                                 &expire, &grace, &pErr ) == LDAP_SUCCESS )
1414                         {
1415                                 if ( pErr != PP_noError ){
1416                                         msgbuf[0] = ';';
1417                                         msgbuf[1] = ' ';
1418                                         strcpy( msgbuf+2, ldap_passwordpolicy_err2txt( pErr ));
1419                                         len = strlen( msgbuf );
1420                                 }
1421                                 if ( expire >= 0 ) {
1422                                         sprintf( msgbuf+len,
1423                                                 " (Password expires in %d seconds)",
1424                                                 expire );
1425                                 } else if ( grace >= 0 ) {
1426                                         sprintf( msgbuf+len,
1427                                                 " (Password expired, %d grace logins remain)",
1428                                                 grace );
1429                                 }
1430                         }
1431                 }
1432 #endif
1433
1434                 if ( ctrls ) {
1435                         ldap_controls_free( ctrls );
1436                 }
1437
1438                 if ( err != LDAP_SUCCESS
1439                         || msgbuf[0]
1440                         || ( matched && matched[ 0 ] )
1441                         || ( info && info[ 0 ] )
1442                         || refs )
1443                 {
1444                         tool_perror( "ldap_bind", err, msgbuf, matched, info, refs );
1445
1446                         if( matched ) ber_memfree( matched );
1447                         if( info ) ber_memfree( info );
1448                         if( refs ) ber_memvfree( (void **)refs );
1449
1450                         if ( err != LDAP_SUCCESS ) exit( err );
1451                 }
1452         }
1453 }
1454
1455 void
1456 tool_unbind( LDAP *ld )
1457 {
1458         int err = ldap_set_option( ld, LDAP_OPT_SERVER_CONTROLS, NULL );
1459
1460         if ( err != LDAP_OPT_SUCCESS ) {
1461                 fprintf( stderr, "Could not unset controls\n");
1462         }
1463
1464         (void) ldap_unbind_ext( ld, NULL, NULL );
1465 }
1466
1467
1468 /* Set server controls.  Add controls extra_c[0..count-1], if set. */
1469 void
1470 tool_server_controls( LDAP *ld, LDAPControl *extra_c, int count )
1471 {
1472         int i = 0, j, crit = 0, err;
1473         LDAPControl c[16], **ctrls;
1474
1475         if ( ! ( assertctl
1476                 || authzid
1477 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
1478                 || proxydn
1479 #endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
1480                 || manageDIT
1481                 || manageDSAit
1482                 || noop
1483 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
1484                 || ppolicy
1485 #endif
1486                 || preread
1487                 || postread
1488 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
1489                 || chaining
1490 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
1491 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
1492                 || sessionTracking
1493 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
1494                 || count
1495                 || unknown_ctrls_num ) )
1496         {
1497                 return;
1498         }
1499
1500         ctrls = (LDAPControl**) malloc(sizeof(c) + (count + unknown_ctrls_num + 1)*sizeof(LDAPControl*));
1501         if ( ctrls == NULL ) {
1502                 fprintf( stderr, "No memory\n" );
1503                 exit( EXIT_FAILURE );
1504         }
1505
1506         if ( assertctl ) {
1507                 if ( BER_BVISNULL( &assertionvalue ) ) {
1508                         err = ldap_create_assertion_control_value( ld,
1509                                 assertion, &assertionvalue );
1510                         if ( err ) {
1511                                 fprintf( stderr,
1512                                         "Unable to create assertion value "
1513                                         "\"%s\" (%d)\n", assertion, err );
1514                         }
1515                 }
1516
1517                 c[i].ldctl_oid = LDAP_CONTROL_ASSERT;
1518                 c[i].ldctl_value = assertionvalue;
1519                 c[i].ldctl_iscritical = assertctl > 1;
1520                 ctrls[i] = &c[i];
1521                 i++;
1522         }
1523
1524         if ( authzid ) {
1525                 c[i].ldctl_value.bv_val = authzid;
1526                 c[i].ldctl_value.bv_len = strlen( authzid );
1527                 c[i].ldctl_oid = LDAP_CONTROL_PROXY_AUTHZ;
1528                 c[i].ldctl_iscritical = 1;
1529                 ctrls[i] = &c[i];
1530                 i++;
1531         }
1532
1533 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
1534         /* NOTE: doesn't need an extra count because it's incompatible
1535          * with authzid */
1536         if ( proxydn ) {
1537                 BerElementBuffer berbuf;
1538                 BerElement *ber = (BerElement *)&berbuf;
1539                 
1540                 ber_init2( ber, NULL, LBER_USE_DER );
1541
1542                 if ( ber_printf( ber, "s", proxydn ) == -1 ) {
1543                         exit( EXIT_FAILURE );
1544                 }
1545
1546                 if ( ber_flatten2( ber, &c[i].ldctl_value, 0 ) == -1 ) {
1547                         exit( EXIT_FAILURE );
1548                 }
1549
1550                 c[i].ldctl_oid = LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ;
1551                 c[i].ldctl_iscritical = 1;
1552                 ctrls[i] = &c[i];
1553                 i++;
1554         }
1555 #endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
1556
1557         if ( manageDIT ) {
1558                 c[i].ldctl_oid = LDAP_CONTROL_MANAGEDIT;
1559                 BER_BVZERO( &c[i].ldctl_value );
1560                 c[i].ldctl_iscritical = manageDIT > 1;
1561                 ctrls[i] = &c[i];
1562                 i++;
1563         }
1564
1565         if ( manageDSAit ) {
1566                 c[i].ldctl_oid = LDAP_CONTROL_MANAGEDSAIT;
1567                 BER_BVZERO( &c[i].ldctl_value );
1568                 c[i].ldctl_iscritical = manageDSAit > 1;
1569                 ctrls[i] = &c[i];
1570                 i++;
1571         }
1572
1573         if ( noop ) {
1574                 c[i].ldctl_oid = LDAP_CONTROL_NOOP;
1575                 BER_BVZERO( &c[i].ldctl_value );
1576                 c[i].ldctl_iscritical = noop > 1;
1577                 ctrls[i] = &c[i];
1578                 i++;
1579         }
1580
1581 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
1582         if ( ppolicy ) {
1583                 c[i].ldctl_oid = LDAP_CONTROL_PASSWORDPOLICYREQUEST;
1584                 BER_BVZERO( &c[i].ldctl_value );
1585                 c[i].ldctl_iscritical = 0;
1586                 ctrls[i] = &c[i];
1587                 i++;
1588         }
1589 #endif
1590
1591         if ( preread ) {
1592                 BerElementBuffer berbuf;
1593                 BerElement *ber = (BerElement *)&berbuf;
1594                 char **attrs = NULL;
1595
1596                 if( preread_attrs ) {
1597                         attrs = ldap_str2charray( preread_attrs, "," );
1598                 }
1599
1600                 ber_init2( ber, NULL, LBER_USE_DER );
1601
1602                 if( ber_printf( ber, "{v}", attrs ) == -1 ) {
1603                         fprintf( stderr, "preread attrs encode failed.\n" );
1604                         exit( EXIT_FAILURE );
1605                 }
1606
1607                 err = ber_flatten2( ber, &c[i].ldctl_value, 0 );
1608                 if( err < 0 ) {
1609                         fprintf( stderr, "preread flatten failed (%d)\n", err );
1610                         exit( EXIT_FAILURE );
1611                 }
1612
1613                 c[i].ldctl_oid = LDAP_CONTROL_PRE_READ;
1614                 c[i].ldctl_iscritical = preread > 1;
1615                 ctrls[i] = &c[i];
1616                 i++;
1617
1618                 if( attrs ) ldap_charray_free( attrs );
1619         }
1620
1621         if ( postread ) {
1622                 BerElementBuffer berbuf;
1623                 BerElement *ber = (BerElement *)&berbuf;
1624                 char **attrs = NULL;
1625
1626                 if( postread_attrs ) {
1627                         attrs = ldap_str2charray( postread_attrs, "," );
1628                 }
1629
1630                 ber_init2( ber, NULL, LBER_USE_DER );
1631
1632                 if( ber_printf( ber, "{v}", attrs ) == -1 ) {
1633                         fprintf( stderr, "postread attrs encode failed.\n" );
1634                         exit( EXIT_FAILURE );
1635                 }
1636
1637                 err = ber_flatten2( ber, &c[i].ldctl_value, 0 );
1638                 if( err < 0 ) {
1639                         fprintf( stderr, "postread flatten failed (%d)\n", err );
1640                         exit( EXIT_FAILURE );
1641                 }
1642
1643                 c[i].ldctl_oid = LDAP_CONTROL_POST_READ;
1644                 c[i].ldctl_iscritical = postread > 1;
1645                 ctrls[i] = &c[i];
1646                 i++;
1647
1648                 if( attrs ) ldap_charray_free( attrs );
1649         }
1650
1651 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
1652         if ( chaining ) {
1653                 if ( chainingResolve > -1 ) {
1654                         BerElementBuffer berbuf;
1655                         BerElement *ber = (BerElement *)&berbuf;
1656
1657                         ber_init2( ber, NULL, LBER_USE_DER );
1658
1659                         err = ber_printf( ber, "{e" /* } */, chainingResolve );
1660                         if ( err == -1 ) {
1661                                 ber_free( ber, 1 );
1662                                 fprintf( stderr, _("Chaining behavior control encoding error!\n") );
1663                                 exit( EXIT_FAILURE );
1664                         }
1665
1666                         if ( chainingContinuation > -1 ) {
1667                                 err = ber_printf( ber, "e", chainingContinuation );
1668                                 if ( err == -1 ) {
1669                                         ber_free( ber, 1 );
1670                                         fprintf( stderr, _("Chaining behavior control encoding error!\n") );
1671                                         exit( EXIT_FAILURE );
1672                                 }
1673                         }
1674
1675                         err = ber_printf( ber, /* { */ "N}" );
1676                         if ( err == -1 ) {
1677                                 ber_free( ber, 1 );
1678                                 fprintf( stderr, _("Chaining behavior control encoding error!\n") );
1679                                 exit( EXIT_FAILURE );
1680                         }
1681
1682                         if ( ber_flatten2( ber, &c[i].ldctl_value, 0 ) == -1 ) {
1683                                 exit( EXIT_FAILURE );
1684                         }
1685
1686                 } else {
1687                         BER_BVZERO( &c[i].ldctl_value );
1688                 }
1689
1690                 c[i].ldctl_oid = LDAP_CONTROL_X_CHAINING_BEHAVIOR;
1691                 c[i].ldctl_iscritical = chaining > 1;
1692                 ctrls[i] = &c[i];
1693                 i++;
1694         }
1695 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
1696
1697 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
1698         if ( sessionTracking ) {
1699                 if ( stValue.bv_val == NULL && st_value( ld, &stValue ) ) {
1700                         exit( EXIT_FAILURE );
1701                 }
1702
1703                 c[i].ldctl_oid = LDAP_CONTROL_X_SESSION_TRACKING;
1704                 c[i].ldctl_iscritical = 0;
1705                 ber_dupbv( &c[i].ldctl_value, &stValue );
1706
1707                 ctrls[i] = &c[i];
1708                 i++;
1709         }
1710 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
1711
1712         while ( count-- ) {
1713                 ctrls[i++] = extra_c++;
1714         }
1715         for ( count = 0; count < unknown_ctrls_num; count++ ) {
1716                 ctrls[i++] = &unknown_ctrls[count];
1717         }
1718         ctrls[i] = NULL;
1719
1720         err = ldap_set_option( ld, LDAP_OPT_SERVER_CONTROLS, ctrls );
1721
1722         if ( err != LDAP_OPT_SUCCESS ) {
1723                 for ( j = 0; j < i; j++ ) {
1724                         if ( ctrls[j]->ldctl_iscritical ) crit = 1;
1725                 }
1726                 fprintf( stderr, "Could not set %scontrols\n",
1727                         crit ? "critical " : "" );
1728         }
1729
1730         free( ctrls );
1731         if ( crit ) {
1732                 exit( EXIT_FAILURE );
1733         }
1734 }
1735
1736 int
1737 tool_check_abandon( LDAP *ld, int msgid )
1738 {
1739         int     rc;
1740
1741         switch ( gotintr ) {
1742         case Intr_Cancel:
1743                 rc = ldap_cancel_s( ld, msgid, NULL, NULL );
1744                 fprintf( stderr, "got interrupt, cancel got %d: %s\n",
1745                                 rc, ldap_err2string( rc ) );
1746                 return -1;
1747
1748         case Intr_Abandon:
1749                 rc = ldap_abandon_ext( ld, msgid, NULL, NULL );
1750                 fprintf( stderr, "got interrupt, abandon got %d: %s\n",
1751                                 rc, ldap_err2string( rc ) );
1752                 return -1;
1753
1754         case Intr_Ignore:
1755                 /* just unbind, ignoring the request */
1756                 return -1;
1757         }
1758
1759         return 0;
1760 }
1761
1762 static int
1763 print_prepostread( LDAP *ld, LDAPControl *ctrl, struct berval *what)
1764 {
1765         BerElement      *ber;
1766         struct berval   bv;
1767
1768         tool_write_ldif( LDIF_PUT_COMMENT, "==> ",
1769                 what->bv_val, what->bv_len );
1770         ber = ber_init( &ctrl->ldctl_value );
1771         if ( ber == NULL ) {
1772                 /* error? */
1773                 return 1;
1774
1775         } else if ( ber_scanf( ber, "{m{" /*}}*/, &bv ) == LBER_ERROR ) {
1776                 /* error? */
1777                 return 1;
1778
1779         } else {
1780                 tool_write_ldif( LDIF_PUT_VALUE, "dn", bv.bv_val, bv.bv_len );
1781
1782                 while ( ber_scanf( ber, "{m" /*}*/, &bv ) != LBER_ERROR ) {
1783                         int             i;
1784                         BerVarray       vals = NULL;
1785
1786                         if ( ber_scanf( ber, "[W]", &vals ) == LBER_ERROR ||
1787                                 vals == NULL )
1788                         {
1789                                 /* error? */
1790                                 return 1;
1791                         }
1792                 
1793                         for ( i = 0; vals[ i ].bv_val != NULL; i++ ) {
1794                                 tool_write_ldif(
1795                                         ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1796                                         bv.bv_val, vals[ i ].bv_val, vals[ i ].bv_len );
1797                         }
1798
1799                         ber_bvarray_free( vals );
1800                 }
1801         }
1802
1803         if ( ber != NULL ) {
1804                 ber_free( ber, 1 );
1805         }
1806
1807         tool_write_ldif( LDIF_PUT_COMMENT, "<== ",
1808                 what->bv_val, what->bv_len );
1809
1810         return 0;
1811 }
1812
1813 static int
1814 print_preread( LDAP *ld, LDAPControl *ctrl )
1815 {
1816         static struct berval what = BER_BVC( "preread" );
1817
1818         return print_prepostread( ld, ctrl, &what );
1819 }
1820
1821 static int
1822 print_postread( LDAP *ld, LDAPControl *ctrl )
1823 {
1824         static struct berval what = BER_BVC( "postread" );
1825
1826         return print_prepostread( ld, ctrl, &what );
1827 }
1828
1829 static int
1830 print_paged_results( LDAP *ld, LDAPControl *ctrl )
1831 {
1832         ber_int_t estimate;
1833
1834         /* note: pr_cookie is being malloced; it's freed
1835          * the next time the control is sent, but the last
1836          * time it's not; we don't care too much, because
1837          * the last time an empty value is returned... */
1838         if ( ldap_parse_pageresponse_control( ld, ctrl, &estimate, &pr_cookie )
1839                 != LDAP_SUCCESS )
1840         {
1841                 /* error? */
1842                 return 1;
1843
1844         } else {
1845                 /* FIXME: check buffer overflow */
1846                 char    buf[ BUFSIZ ], *ptr = buf;
1847
1848                 if ( estimate > 0 ) {
1849                         ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
1850                                 "estimate=%d", estimate );
1851                 }
1852
1853                 if ( pr_cookie.bv_len > 0 ) {
1854                         struct berval   bv;
1855
1856                         bv.bv_len = LUTIL_BASE64_ENCODE_LEN(
1857                                 pr_cookie.bv_len ) + 1;
1858                         bv.bv_val = ber_memalloc( bv.bv_len + 1 );
1859
1860                         bv.bv_len = lutil_b64_ntop(
1861                                 (unsigned char *) pr_cookie.bv_val,
1862                                 pr_cookie.bv_len,
1863                                 bv.bv_val, bv.bv_len );
1864
1865                         ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
1866                                 "%scookie=%s", ptr == buf ? "" : " ",
1867                                 bv.bv_val );
1868
1869                         ber_memfree( bv.bv_val );
1870
1871                         pr_morePagedResults = 1;
1872
1873                 } else {
1874                         ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
1875                                 "%scookie=", ptr == buf ? "" : " " );
1876                 }
1877
1878                 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1879                         "pagedresults", buf, ptr - buf );
1880         }
1881
1882         return 0;
1883 }
1884
1885 static int
1886 print_sss( LDAP *ld, LDAPControl *ctrl )
1887 {
1888         int rc;
1889         ber_int_t err;
1890         char *attr;
1891
1892         rc = ldap_parse_sortresponse_control( ld, ctrl, &err, &attr );
1893         if ( rc == LDAP_SUCCESS ) {
1894                 char buf[ BUFSIZ ];
1895                 rc = snprintf( buf, sizeof(buf), "(%d) %s %s",
1896                         err, ldap_err2string(err), attr ? attr : "" );
1897
1898                 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1899                         "sortResult", buf, rc );
1900         }
1901
1902         return rc;
1903 }
1904
1905 #ifdef LDAP_CONTROL_X_DEREF
1906 static int
1907 print_deref( LDAP *ld, LDAPControl *ctrl )
1908 {
1909         LDAPDerefRes    *drhead = NULL, *dr;
1910         int             rc;
1911
1912         rc = ldap_parse_derefresponse_control( ld, ctrl, &drhead );
1913         if ( rc != LDAP_SUCCESS ) {
1914                 return rc;
1915         }
1916
1917         for ( dr = drhead; dr != NULL; dr = dr->next ) {
1918                 LDAPDerefVal    *dv;
1919                 ber_len_t       len;
1920                 char            *buf, *ptr;
1921
1922                 len = strlen( dr->derefAttr ) + STRLENOF(": ");
1923
1924                 for ( dv = dr->attrVals; dv != NULL; dv = dv->next ) {
1925                         if ( dv->vals != NULL ) {
1926                                 int j;
1927                                 ber_len_t tlen = strlen(dv->type);
1928
1929                                 for ( j = 0; dv->vals[ j ].bv_val != NULL; j++ ) {
1930                                         len += STRLENOF("<=>;") + tlen + dv->vals[ j ].bv_len;
1931                                 }
1932                         }
1933                 }
1934                 len += dr->derefVal.bv_len;
1935                 buf = ldap_memalloc( len + 1 );
1936                 if ( buf == NULL ) {
1937                         rc = LDAP_NO_MEMORY;
1938                         goto done;
1939                 }
1940
1941                 ptr = buf;
1942                 ptr = lutil_strcopy( ptr, dr->derefAttr );
1943                 *ptr++ = ':';
1944                 *ptr++ = ' ';
1945                 for ( dv = dr->attrVals; dv != NULL; dv = dv->next ) {
1946                         if ( dv->vals != NULL ) {
1947                                 int j;
1948                                 for ( j = 0; dv->vals[ j ].bv_val != NULL; j++ ) {
1949                                         *ptr++ = '<';
1950                                         ptr = lutil_strcopy( ptr, dv->type );
1951                                         *ptr++ = '=';
1952                                         ptr = lutil_strncopy( ptr, dv->vals[ j ].bv_val, dv->vals[ j ].bv_len );
1953                                         *ptr++ = '>';
1954                                         *ptr++ = ';';
1955                                 }
1956                         }
1957                 }
1958                 ptr = lutil_strncopy( ptr, dr->derefVal.bv_val, dr->derefVal.bv_len );
1959                 *ptr++ = '\0';
1960
1961                 tool_write_ldif( LDIF_PUT_COMMENT, NULL, buf, len );
1962
1963                 ldap_memfree( buf );
1964         }
1965
1966         rc = LDAP_SUCCESS;
1967
1968 done:;
1969         ldap_derefresponse_free( drhead );
1970
1971         return rc;
1972 }
1973 #endif
1974
1975 #ifdef LDAP_CONTROL_X_WHATFAILED
1976 static int
1977 print_whatfailed( LDAP *ld, LDAPControl *ctrl )
1978 {
1979         BerElement *ber;
1980         ber_tag_t tag;
1981         ber_len_t siz;
1982         BerVarray bva = NULL;
1983
1984         /* Create a BerElement from the berval returned in the control. */
1985         ber = ber_init( &ctrl->ldctl_value );
1986
1987         if ( ber == NULL ) {
1988                 return LDAP_NO_MEMORY;
1989         }
1990
1991         siz = sizeof(struct berval);
1992         tag = ber_scanf( ber, "[M]", &bva, &siz, 0 );
1993         if ( tag != LBER_ERROR ) {
1994                 int i;
1995
1996                 tool_write_ldif( LDIF_PUT_COMMENT, " what failed:", NULL, 0 );
1997
1998                 for ( i = 0; bva[i].bv_val != NULL; i++ ) {
1999                         tool_write_ldif( LDIF_PUT_COMMENT, NULL, bva[i].bv_val, bva[i].bv_len );
2000                 }
2001
2002                 ldap_memfree( bva );
2003         }
2004
2005         ber_free( ber, 1 );
2006
2007
2008         return 0;
2009 }
2010 #endif
2011
2012 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
2013 static int
2014 print_ppolicy( LDAP *ld, LDAPControl *ctrl )
2015 {
2016         int expire = 0, grace = 0, rc;
2017         LDAPPasswordPolicyError pperr;
2018
2019         rc = ldap_parse_passwordpolicy_control( ld, ctrl,
2020                 &expire, &grace, &pperr );
2021         if ( rc == LDAP_SUCCESS ) {
2022                 char    buf[ BUFSIZ ], *ptr = buf;
2023
2024                 if ( expire != -1 ) {
2025                         ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
2026                                 "expire=%d", expire );
2027                 }
2028
2029                 if ( grace != -1 ) {
2030                         ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
2031                                 "%sgrace=%d", ptr == buf ? "" : " ", grace );
2032                 }
2033
2034                 if ( pperr != PP_noError ) {
2035                         ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
2036                                 "%serror=%d (%s)", ptr == buf ? "" : " ",
2037                                 pperr,
2038                                 ldap_passwordpolicy_err2txt( pperr ) );
2039                 }
2040
2041                 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
2042                         "ppolicy", buf, ptr - buf );
2043         }
2044
2045         return rc;
2046 }
2047 #endif
2048
2049 void tool_print_ctrls(
2050         LDAP            *ld,
2051         LDAPControl     **ctrls )
2052 {
2053         int     i;
2054         char    *ptr;
2055
2056         for ( i = 0; ctrls[i] != NULL; i++ ) {
2057                 /* control: OID criticality base64value */
2058                 struct berval b64 = BER_BVNULL;
2059                 ber_len_t len;
2060                 char *str;
2061                 int j;
2062
2063                 /* FIXME: there might be cases where a control has NULL OID;
2064                  * this makes little sense, especially when returned by the
2065                  * server, but libldap happily allows it */
2066                 if ( ctrls[i]->ldctl_oid == NULL ) {
2067                         continue;
2068                 }
2069
2070                 len = ldif ? 2 : 0;
2071                 len += strlen( ctrls[i]->ldctl_oid );
2072
2073                 /* add enough for space after OID and the critical value itself */
2074                 len += ctrls[i]->ldctl_iscritical
2075                         ? sizeof("true") : sizeof("false");
2076
2077                 /* convert to base64 */
2078                 if ( !BER_BVISNULL( &ctrls[i]->ldctl_value ) ) {
2079                         b64.bv_len = LUTIL_BASE64_ENCODE_LEN(
2080                                 ctrls[i]->ldctl_value.bv_len ) + 1;
2081                         b64.bv_val = ber_memalloc( b64.bv_len + 1 );
2082
2083                         b64.bv_len = lutil_b64_ntop(
2084                                 (unsigned char *) ctrls[i]->ldctl_value.bv_val,
2085                                 ctrls[i]->ldctl_value.bv_len,
2086                                 b64.bv_val, b64.bv_len );
2087                 }
2088
2089                 if ( b64.bv_len ) {
2090                         len += 1 + b64.bv_len;
2091                 }
2092
2093                 ptr = str = malloc( len + 1 );
2094                 if ( ldif ) {
2095                         ptr = lutil_strcopy( ptr, ": " );
2096                 }
2097                 ptr = lutil_strcopy( ptr, ctrls[i]->ldctl_oid );
2098                 ptr = lutil_strcopy( ptr, ctrls[i]->ldctl_iscritical
2099                         ? " true" : " false" );
2100
2101                 if ( b64.bv_len ) {
2102                         ptr = lutil_strcopy( ptr, " " );
2103                         ptr = lutil_strcopy( ptr, b64.bv_val );
2104                 }
2105
2106                 if ( ldif < 2 ) {
2107                         tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
2108                                 "control", str, len );
2109                 }
2110
2111                 free( str );
2112                 if ( b64.bv_len ) {
2113                         ber_memfree( b64.bv_val );
2114                 }
2115
2116                 /* known controls */
2117                 for ( j = 0; tool_ctrl_response[j].oid != NULL; j++ ) {
2118                         if ( strcmp( tool_ctrl_response[j].oid, ctrls[i]->ldctl_oid ) == 0 ) {
2119                                 if ( !tool_ctrl_response[j].mask & tool_type ) {
2120                                         /* this control should not appear
2121                                          * with this tool; warning? */
2122                                 }
2123                                 break;
2124                         }
2125                 }
2126
2127                 if ( tool_ctrl_response[j].oid != NULL && tool_ctrl_response[j].func ) {
2128                         (void)tool_ctrl_response[j].func( ld, ctrls[i] );
2129                 }
2130         }
2131 }
2132
2133 int
2134 tool_write_ldif( int type, char *name, char *value, ber_len_t vallen )
2135 {
2136         char    *ldif;
2137
2138         if (( ldif = ldif_put( type, name, value, vallen )) == NULL ) {
2139                 return( -1 );
2140         }
2141
2142         fputs( ldif, stdout );
2143         ber_memfree( ldif );
2144
2145         return( 0 );
2146 }
2147
2148 int
2149 tool_is_oid( const char *s )
2150 {
2151         int             first = 1;
2152
2153         if ( !isdigit( (unsigned char) s[ 0 ] ) ) {
2154                 return 0;
2155         }
2156
2157         for ( ; s[ 0 ]; s++ ) {
2158                 if ( s[ 0 ] == '.' ) {
2159                         if ( s[ 1 ] == '\0' ) {
2160                                 return 0;
2161                         }
2162                         first = 1;
2163                         continue;
2164                 }
2165
2166                 if ( !isdigit( (unsigned char) s[ 0 ] ) ) {
2167                         return 0;
2168                 }
2169
2170                 if ( first == 1 && s[ 0 ] == '0' && s[ 1 ] != '.' ) {
2171                         return 0;
2172                 }
2173                 first = 0;
2174         }
2175
2176         return 1;
2177 }
2178