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