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