]> git.sur5r.net Git - openldap/blob - clients/tools/common.c
2177c652d980a32ae548165e03177212ba8e571f
[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                         break;
724                 case 'f':       /* read from file */
725                         if( infile != NULL ) {
726                                 fprintf( stderr, "%s: -f previously specified\n", prog );
727                                 exit( EXIT_FAILURE );
728                         }
729                         infile = ber_strdup( optarg );
730                         break;
731                 case 'h':       /* ldap host */
732                         if( ldaphost != NULL ) {
733                                 fprintf( stderr, "%s: -h previously specified\n", prog );
734                                 exit( EXIT_FAILURE );
735                         }
736                         ldaphost = ber_strdup( optarg );
737                         break;
738                 case 'H':       /* ldap URI */
739                         if( ldapuri != NULL ) {
740                                 fprintf( stderr, "%s: -H previously specified\n", prog );
741                                 exit( EXIT_FAILURE );
742                         }
743                         ldapuri = ber_strdup( optarg );
744                         break;
745                 case 'I':
746 #ifdef HAVE_CYRUS_SASL
747                         if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
748                                 fprintf( stderr, "%s: incompatible previous "
749                                         "authentication choice\n",
750                                         prog );
751                                 exit( EXIT_FAILURE );
752                         }
753                         authmethod = LDAP_AUTH_SASL;
754                         sasl_flags = LDAP_SASL_INTERACTIVE;
755                         break;
756 #else
757                         fprintf( stderr, "%s: was not compiled with SASL support\n",
758                                 prog );
759                         exit( EXIT_FAILURE );
760 #endif
761                 case 'M':
762                         /* enable Manage DSA IT */
763                         manageDSAit++;
764                         break;
765                 case 'n':       /* print operations, don't actually do them */
766                         dont++;
767                         break;
768                 case 'N':
769                         nocanon++;
770                         break;
771                 case 'o':
772                         control = ber_strdup( optarg );
773                         if ( (cvalue = strchr( control, '=' )) != NULL ) {
774                                 *cvalue++ = '\0';
775                         }
776
777                         if ( strcasecmp( control, "nettimeout" ) == 0 ) {
778                                 if( nettimeout.tv_sec != -1 ) {
779                                         fprintf( stderr, "nettimeout option previously specified\n");
780                                         exit( EXIT_FAILURE );
781                                 }
782                                 if( cvalue == NULL || cvalue[0] == '\0' ) {
783                                         fprintf( stderr, "nettimeout: option value expected\n" );
784                                         usage();
785                                 }
786                                 if ( strcasecmp( cvalue, "none" ) == 0 ) {
787                                         nettimeout.tv_sec = 0;
788                                 } else if ( strcasecmp( cvalue, "max" ) == 0 ) {
789                                         nettimeout.tv_sec = LDAP_MAXINT;
790                                 } else {
791                                         ival = strtol( cvalue, &next, 10 );
792                                         if ( next == NULL || next[0] != '\0' ) {
793                                                 fprintf( stderr,
794                                                         _("Unable to parse network timeout \"%s\"\n"), cvalue );
795                                                 exit( EXIT_FAILURE );
796                                         }
797                                         nettimeout.tv_sec = ival;
798                                 }
799                                 if( nettimeout.tv_sec < 0 || nettimeout.tv_sec > LDAP_MAXINT ) {
800                                         fprintf( stderr, _("%s: invalid network timeout (%ld) specified\n"),
801                                                 prog, (long)nettimeout.tv_sec );
802                                         exit( EXIT_FAILURE );
803                                 }
804
805                         } else if ( strcasecmp( control, "ldif-wrap" ) == 0 ) {
806                                 if ( cvalue == 0 ) {
807                                         ldif_wrap = LDIF_LINE_WIDTH;
808
809                                 } else if ( strcasecmp( cvalue, "no" ) == 0 ) {
810                                         ldif_wrap = LDIF_LINE_WIDTH_MAX;
811
812                                 } else {
813                                         unsigned int u;
814                                         if ( lutil_atou( &u, cvalue ) ) {
815                                                 fprintf( stderr,
816                                                         _("Unable to parse ldif-wrap=\"%s\"\n"), cvalue );
817                                                 exit( EXIT_FAILURE );
818                                         }
819                                         ldif_wrap = (ber_len_t)u;
820                                 }
821
822                         } else {
823                                 fprintf( stderr, "Invalid general option name: %s\n",
824                                         control );
825                                 usage();
826                         }
827                         ber_memfree(control);
828                         break;
829                 case 'O':
830 #ifdef HAVE_CYRUS_SASL
831                         if( sasl_secprops != NULL ) {
832                                 fprintf( stderr, "%s: -O previously specified\n", prog );
833                                 exit( EXIT_FAILURE );
834                         }
835                         if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
836                                 fprintf( stderr, "%s: incompatible previous "
837                                         "authentication choice\n", prog );
838                                 exit( EXIT_FAILURE );
839                         }
840                         authmethod = LDAP_AUTH_SASL;
841                         sasl_secprops = ber_strdup( optarg );
842 #else
843                         fprintf( stderr, "%s: not compiled with SASL support\n", prog );
844                         exit( EXIT_FAILURE );
845 #endif
846                         break;
847                 case 'p':
848                         if( ldapport ) {
849                                 fprintf( stderr, "%s: -p previously specified\n", prog );
850                                 exit( EXIT_FAILURE );
851                         }
852                         ival = strtol( optarg, &next, 10 );
853                         if ( next == NULL || next[0] != '\0' ) {
854                                 fprintf( stderr, "%s: unable to parse port number \"%s\"\n", prog, optarg );
855                                 exit( EXIT_FAILURE );
856                         }
857                         ldapport = ival;
858                         break;
859                 case 'P':
860                         ival = strtol( optarg, &next, 10 );
861                         if ( next == NULL || next[0] != '\0' ) {
862                                 fprintf( stderr, "%s: unable to parse protocol version \"%s\"\n", prog, optarg );
863                                 exit( EXIT_FAILURE );
864                         }
865                         switch( ival ) {
866                         case 2:
867                                 if( protocol == LDAP_VERSION3 ) {
868                                         fprintf( stderr, "%s: -P 2 incompatible with version %d\n",
869                                                 prog, protocol );
870                                         exit( EXIT_FAILURE );
871                                 }
872                                 protocol = LDAP_VERSION2;
873                                 break;
874                         case 3:
875                                 if( protocol == LDAP_VERSION2 ) {
876                                         fprintf( stderr, "%s: -P 2 incompatible with version %d\n",
877                                                 prog, protocol );
878                                         exit( EXIT_FAILURE );
879                                 }
880                                 protocol = LDAP_VERSION3;
881                                 break;
882                         default:
883                                 fprintf( stderr, "%s: protocol version should be 2 or 3\n",
884                                         prog );
885                                 usage();
886                         }
887                         break;
888                 case 'Q':
889 #ifdef HAVE_CYRUS_SASL
890                         if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
891                                 fprintf( stderr, "%s: incompatible previous "
892                                         "authentication choice\n",
893                                         prog );
894                                 exit( EXIT_FAILURE );
895                         }
896                         authmethod = LDAP_AUTH_SASL;
897                         sasl_flags = LDAP_SASL_QUIET;
898                         break;
899 #else
900                         fprintf( stderr, "%s: not compiled with SASL support\n",
901                                 prog );
902                         exit( EXIT_FAILURE );
903 #endif
904                 case 'R':
905 #ifdef HAVE_CYRUS_SASL
906                         if( sasl_realm != NULL ) {
907                                 fprintf( stderr, "%s: -R previously specified\n", prog );
908                                 exit( EXIT_FAILURE );
909                         }
910                         if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
911                                 fprintf( stderr, "%s: incompatible previous "
912                                         "authentication choice\n",
913                                         prog );
914                                 exit( EXIT_FAILURE );
915                         }
916                         authmethod = LDAP_AUTH_SASL;
917                         sasl_realm = ber_strdup( optarg );
918 #else
919                         fprintf( stderr, "%s: not compiled with SASL support\n",
920                                 prog );
921                         exit( EXIT_FAILURE );
922 #endif
923                         break;
924                 case 'U':
925 #ifdef HAVE_CYRUS_SASL
926                         if( sasl_authc_id != NULL ) {
927                                 fprintf( stderr, "%s: -U previously specified\n", prog );
928                                 exit( EXIT_FAILURE );
929                         }
930                         if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
931                                 fprintf( stderr, "%s: incompatible previous "
932                                         "authentication choice\n",
933                                         prog );
934                                 exit( EXIT_FAILURE );
935                         }
936                         authmethod = LDAP_AUTH_SASL;
937                         sasl_authc_id = ber_strdup( optarg );
938 #else
939                         fprintf( stderr, "%s: not compiled with SASL support\n",
940                                 prog );
941                         exit( EXIT_FAILURE );
942 #endif
943                         break;
944                 case 'v':       /* verbose mode */
945                         verbose++;
946                         break;
947                 case 'V':       /* version */
948                         version++;
949                         break;
950                 case 'w':       /* password */
951                         passwd.bv_val = ber_strdup( optarg );
952                         {
953                                 char* p;
954
955                                 for( p = optarg; *p != '\0'; p++ ) {
956                                         *p = '\0';
957                                 }
958                         }
959                         passwd.bv_len = strlen( passwd.bv_val );
960                         break;
961                 case 'W':
962                         want_bindpw++;
963                         break;
964                 case 'y':
965                         pw_file = optarg;
966                         break;
967                 case 'Y':
968 #ifdef HAVE_CYRUS_SASL
969                         if( sasl_mech != NULL ) {
970                                 fprintf( stderr, "%s: -Y previously specified\n", prog );
971                                 exit( EXIT_FAILURE );
972                         }
973                         if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
974                                 fprintf( stderr,
975                                         "%s: incompatible with authentication choice\n", prog );
976                                 exit( EXIT_FAILURE );
977                         }
978                         authmethod = LDAP_AUTH_SASL;
979                         sasl_mech = ber_strdup( optarg );
980 #else
981                         fprintf( stderr, "%s: not compiled with SASL support\n", prog );
982                         exit( EXIT_FAILURE );
983 #endif
984                         break;
985                 case 'x':
986                         if( authmethod != -1 && authmethod != LDAP_AUTH_SIMPLE ) {
987                                 fprintf( stderr, "%s: incompatible with previous "
988                                         "authentication choice\n", prog );
989                                 exit( EXIT_FAILURE );
990                         }
991                         authmethod = LDAP_AUTH_SIMPLE;
992                         break;
993                 case 'X':
994 #ifdef HAVE_CYRUS_SASL
995                         if( sasl_authz_id != NULL ) {
996                                 fprintf( stderr, "%s: -X previously specified\n", prog );
997                                 exit( EXIT_FAILURE );
998                         }
999                         if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
1000                                 fprintf( stderr, "%s: -X incompatible with "
1001                                         "authentication choice\n", prog );
1002                                 exit( EXIT_FAILURE );
1003                         }
1004                         authmethod = LDAP_AUTH_SASL;
1005                         sasl_authz_id = ber_strdup( optarg );
1006 #else
1007                         fprintf( stderr, "%s: not compiled with SASL support\n", prog );
1008                         exit( EXIT_FAILURE );
1009 #endif
1010                         break;
1011                 case 'Z':
1012 #ifdef HAVE_TLS
1013                         use_tls++;
1014 #else
1015                         fprintf( stderr, "%s: not compiled with TLS support\n", prog );
1016                         exit( EXIT_FAILURE );
1017 #endif
1018                         break;
1019                 default:
1020                         if( handle_private_option( i ) ) break;
1021                         fprintf( stderr, "%s: unrecognized option -%c\n",
1022                                 prog, optopt );
1023                         usage();
1024                 }
1025         }
1026
1027         {
1028                 /* prevent bad linking */
1029                 LDAPAPIInfo api;
1030                 api.ldapai_info_version = LDAP_API_INFO_VERSION;
1031
1032                 if ( ldap_get_option(NULL, LDAP_OPT_API_INFO, &api)
1033                         != LDAP_OPT_SUCCESS )
1034                 {
1035                         fprintf( stderr, "%s: ldap_get_option(API_INFO) failed\n", prog );
1036                         exit( EXIT_FAILURE );
1037                 }
1038
1039                 if (api.ldapai_info_version != LDAP_API_INFO_VERSION) {
1040                         fprintf( stderr, "LDAP APIInfo version mismatch: "
1041                                 "library %d, header %d\n",
1042                                 api.ldapai_info_version, LDAP_API_INFO_VERSION );
1043                         exit( EXIT_FAILURE );
1044                 }
1045
1046                 if( api.ldapai_api_version != LDAP_API_VERSION ) {
1047                         fprintf( stderr, "LDAP API version mismatch: "
1048                                 "library %d, header %d\n",
1049                                 api.ldapai_api_version, LDAP_API_VERSION );
1050                         exit( EXIT_FAILURE );
1051                 }
1052
1053                 if( strcmp(api.ldapai_vendor_name, LDAP_VENDOR_NAME ) != 0 ) {
1054                         fprintf( stderr, "LDAP vendor name mismatch: "
1055                                 "library %s, header %s\n",
1056                                 api.ldapai_vendor_name, LDAP_VENDOR_NAME );
1057                         exit( EXIT_FAILURE );
1058                 }
1059
1060                 if( api.ldapai_vendor_version != LDAP_VENDOR_VERSION ) {
1061                         fprintf( stderr, "LDAP vendor version mismatch: "
1062                                 "library %d, header %d\n",
1063                                 api.ldapai_vendor_version, LDAP_VENDOR_VERSION );
1064                         exit( EXIT_FAILURE );
1065                 }
1066
1067                 if (version) {
1068                         fprintf( stderr, "%s: %s\t(LDAP library: %s %d)\n",
1069                                 prog, __Version,
1070                                 LDAP_VENDOR_NAME, LDAP_VENDOR_VERSION );
1071                         if (version > 1) exit( EXIT_SUCCESS );
1072                 }
1073
1074                 ldap_memfree( api.ldapai_vendor_name );
1075                 ber_memvfree( (void **)api.ldapai_extensions );
1076         }
1077
1078         if (protocol == -1)
1079                 protocol = LDAP_VERSION3;
1080
1081         if (authmethod == -1 && protocol > LDAP_VERSION2) {
1082 #ifdef HAVE_CYRUS_SASL
1083                 if ( binddn != NULL ) {
1084                         authmethod = LDAP_AUTH_SIMPLE;
1085                 } else {
1086                         authmethod = LDAP_AUTH_SASL;
1087                 }
1088 #else
1089                 authmethod = LDAP_AUTH_SIMPLE;
1090 #endif
1091         }
1092
1093         if( ldapuri == NULL ) {
1094                 if( ldapport && ( ldaphost == NULL )) {
1095                         fprintf( stderr, "%s: -p without -h is invalid.\n", prog );
1096                         exit( EXIT_FAILURE );
1097                 }
1098         } else {
1099                 if( ldaphost != NULL ) {
1100                         fprintf( stderr, "%s: -H incompatible with -h\n", prog );
1101                         exit( EXIT_FAILURE );
1102                 }
1103                 if( ldapport ) {
1104                         fprintf( stderr, "%s: -H incompatible with -p\n", prog );
1105                         exit( EXIT_FAILURE );
1106                 }
1107         }
1108
1109         if( protocol == LDAP_VERSION2 ) {
1110                 if( assertctl || authzid || manageDIT || manageDSAit ||
1111 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
1112                         proxydn ||
1113 #endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
1114 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
1115                         chaining ||
1116 #endif
1117 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
1118                         sessionTracking ||
1119 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
1120                         noop || ppolicy || preread || postread )
1121                 {
1122                         fprintf( stderr, "%s: -e/-M incompatible with LDAPv2\n", prog );
1123                         exit( EXIT_FAILURE );
1124                 }
1125 #ifdef HAVE_TLS
1126                 if( use_tls ) {
1127                         fprintf( stderr, "%s: -Z incompatible with LDAPv2\n", prog );
1128                         exit( EXIT_FAILURE );
1129                 }
1130 #endif
1131 #ifdef HAVE_CYRUS_SASL
1132                 if( authmethod == LDAP_AUTH_SASL ) {
1133                         fprintf( stderr, "%s: -[IOQRUXY] incompatible with LDAPv2\n",
1134                                 prog );
1135                         exit( EXIT_FAILURE );
1136                 }
1137 #endif
1138         }
1139 }
1140
1141
1142 LDAP *
1143 tool_conn_setup( int dont, void (*private_setup)( LDAP * ) )
1144 {
1145         LDAP *ld = NULL;
1146
1147         if ( debug ) {
1148                 if( ber_set_option( NULL, LBER_OPT_DEBUG_LEVEL, &debug )
1149                         != LBER_OPT_SUCCESS )
1150                 {
1151                         fprintf( stderr,
1152                                 "Could not set LBER_OPT_DEBUG_LEVEL %d\n", debug );
1153                 }
1154                 if( ldap_set_option( NULL, LDAP_OPT_DEBUG_LEVEL, &debug )
1155                         != LDAP_OPT_SUCCESS )
1156                 {
1157                         fprintf( stderr,
1158                                 "Could not set LDAP_OPT_DEBUG_LEVEL %d\n", debug );
1159                 }
1160         }
1161
1162 #ifdef SIGPIPE
1163         (void) SIGNAL( SIGPIPE, SIG_IGN );
1164 #endif
1165
1166         if ( abcan ) {
1167                 SIGNAL( SIGINT, do_sig );
1168         }
1169
1170         if ( !dont ) {
1171                 int rc;
1172
1173                 if( ( ldaphost != NULL || ldapport ) && ( ldapuri == NULL ) ) {
1174                         /* construct URL */
1175                         LDAPURLDesc url;
1176                         memset( &url, 0, sizeof(url));
1177
1178                         url.lud_scheme = "ldap";
1179                         url.lud_host = ldaphost;
1180                         url.lud_port = ldapport;
1181                         url.lud_scope = LDAP_SCOPE_DEFAULT;
1182
1183                         ldapuri = ldap_url_desc2str( &url );
1184
1185                 } else if ( ldapuri != NULL ) {
1186                         LDAPURLDesc     *ludlist, **ludp;
1187                         char            **urls = NULL;
1188                         int             nurls = 0;
1189
1190                         rc = ldap_url_parselist( &ludlist, ldapuri );
1191                         if ( rc != LDAP_URL_SUCCESS ) {
1192                                 fprintf( stderr,
1193                                         "Could not parse LDAP URI(s)=%s (%d)\n",
1194                                         ldapuri, rc );
1195                                 exit( EXIT_FAILURE );
1196                         }
1197
1198                         for ( ludp = &ludlist; *ludp != NULL; ) {
1199                                 LDAPURLDesc     *lud = *ludp;
1200                                 char            **tmp;
1201
1202                                 if ( lud->lud_dn != NULL && lud->lud_dn[ 0 ] != '\0' &&
1203                                         ( lud->lud_host == NULL || lud->lud_host[0] == '\0' ) )
1204                                 {
1205                                         /* if no host but a DN is provided,
1206                                          * use DNS SRV to gather the host list
1207                                          * and turn it into a list of URIs
1208                                          * using the scheme provided */
1209                                         char    *domain = NULL,
1210                                                 *hostlist = NULL,
1211                                                 **hosts = NULL;
1212                                         int     i,
1213                                                 len_proto = strlen( lud->lud_scheme );
1214
1215                                         if ( ldap_dn2domain( lud->lud_dn, &domain )
1216                                                 || domain == NULL )
1217                                         {
1218                                                 fprintf( stderr,
1219                                                         "DNS SRV: Could not turn "
1220                                                         "DN=\"%s\" into a domain\n",
1221                                                         lud->lud_dn );
1222                                                 goto dnssrv_free;
1223                                         }
1224                                         
1225                                         rc = ldap_domain2hostlist( domain, &hostlist );
1226                                         if ( rc ) {
1227                                                 fprintf( stderr,
1228                                                         "DNS SRV: Could not turn "
1229                                                         "domain=%s into a hostlist\n",
1230                                                         domain );
1231                                                 goto dnssrv_free;
1232                                         }
1233
1234                                         hosts = ldap_str2charray( hostlist, " " );
1235                                         if ( hosts == NULL ) {
1236                                                 fprintf( stderr,
1237                                                         "DNS SRV: Could not parse "
1238                                                         "hostlist=\"%s\"\n",
1239                                                         hostlist );
1240                                                 goto dnssrv_free;
1241                                         }
1242
1243                                         for ( i = 0; hosts[ i ] != NULL; i++ )
1244                                                 /* count'em */ ;
1245
1246                                         tmp = (char **)ber_memrealloc( urls, sizeof( char * ) * ( nurls + i + 1 ) );
1247                                         if ( tmp == NULL ) {
1248                                                 fprintf( stderr,
1249                                                         "DNS SRV: out of memory?\n" );
1250                                                 goto dnssrv_free;
1251                                         }
1252                                         urls = tmp;
1253                                         urls[ nurls ] = NULL;
1254
1255                                         for ( i = 0; hosts[ i ] != NULL; i++ ) {
1256                                                 size_t  len = len_proto
1257                                                         + STRLENOF( "://" )
1258                                                         + strlen( hosts[ i ] )
1259                                                         + 1;
1260
1261                                                 urls[ nurls + i + 1 ] = NULL;
1262                                                 urls[ nurls + i ] = (char *)malloc( sizeof( char ) * len );
1263                                                 if ( urls[ nurls + i ] == NULL ) {
1264                                                         fprintf( stderr,
1265                                                                 "DNS SRV: out of memory?\n" );
1266                                                         goto dnssrv_free;
1267                                                 }
1268
1269                                                 snprintf( urls[ nurls + i ], len, "%s://%s",
1270                                                         lud->lud_scheme, hosts[ i ] );
1271                                         }
1272                                         nurls += i;
1273
1274 dnssrv_free:;
1275                                         ber_memvfree( (void **)hosts );
1276                                         ber_memfree( hostlist );
1277                                         ber_memfree( domain );
1278
1279                                 } else {
1280                                         tmp = (char **)ber_memrealloc( urls, sizeof( char * ) * ( nurls + 2 ) );
1281                                         if ( tmp == NULL ) {
1282                                                 fprintf( stderr,
1283                                                         "DNS SRV: out of memory?\n" );
1284                                                 break;
1285                                         }
1286                                         urls = tmp;
1287                                         urls[ nurls + 1 ] = NULL;
1288
1289                                         urls[ nurls ] = ldap_url_desc2str( lud );
1290                                         if ( urls[ nurls ] == NULL ) {
1291                                                 fprintf( stderr,
1292                                                         "DNS SRV: out of memory?\n" );
1293                                                 break;
1294                                         }
1295                                         nurls++;
1296                                 }
1297
1298                                 *ludp = lud->lud_next;
1299
1300                                 lud->lud_next = NULL;
1301                                 ldap_free_urldesc( lud );
1302                         }
1303
1304                         if ( ludlist != NULL ) {
1305                                 ldap_free_urllist( ludlist );
1306                                 exit( EXIT_FAILURE );
1307
1308                         } else if ( urls == NULL ) {
1309                                 exit( EXIT_FAILURE );
1310                         }
1311
1312                         ldap_memfree( ldapuri );
1313                         ldapuri = ldap_charray2str( urls, " " );
1314                         ber_memvfree( (void **)urls );
1315                 }
1316
1317                 if ( verbose ) {
1318                         fprintf( stderr, "ldap_initialize( %s )\n",
1319                                 ldapuri != NULL ? ldapuri : "<DEFAULT>" );
1320                 }
1321                 rc = ldap_initialize( &ld, ldapuri );
1322                 if( rc != LDAP_SUCCESS ) {
1323                         fprintf( stderr,
1324                                 "Could not create LDAP session handle for URI=%s (%d): %s\n",
1325                                 ldapuri, rc, ldap_err2string(rc) );
1326                         exit( EXIT_FAILURE );
1327                 }
1328
1329                 if( private_setup ) private_setup( ld );
1330
1331                 /* referrals */
1332                 if( ldap_set_option( ld, LDAP_OPT_REFERRALS,
1333                         referrals ? LDAP_OPT_ON : LDAP_OPT_OFF ) != LDAP_OPT_SUCCESS )
1334                 {
1335                         fprintf( stderr, "Could not set LDAP_OPT_REFERRALS %s\n",
1336                                 referrals ? "on" : "off" );
1337                         exit( EXIT_FAILURE );
1338                 }
1339
1340 #ifdef HAVE_CYRUS_SASL
1341                 /* canon */
1342                 if( ldap_set_option( ld, LDAP_OPT_X_SASL_NOCANON,
1343                         nocanon ? LDAP_OPT_ON : LDAP_OPT_OFF ) != LDAP_OPT_SUCCESS )
1344                 {
1345                         fprintf( stderr, "Could not set LDAP_OPT_X_SASL_NOCANON %s\n",
1346                                 nocanon ? "on" : "off" );
1347                         exit( EXIT_FAILURE );
1348                 }
1349 #endif
1350                 if( ldap_set_option( ld, LDAP_OPT_PROTOCOL_VERSION, &protocol )
1351                         != LDAP_OPT_SUCCESS )
1352                 {
1353                         fprintf( stderr, "Could not set LDAP_OPT_PROTOCOL_VERSION %d\n",
1354                                 protocol );
1355                         exit( EXIT_FAILURE );
1356                 }
1357
1358                 if ( use_tls ) {
1359                         rc = ldap_start_tls_s( ld, NULL, NULL );
1360                         if ( rc != LDAP_SUCCESS ) {
1361                                 char *msg=NULL;
1362                                 ldap_get_option( ld, LDAP_OPT_DIAGNOSTIC_MESSAGE, (void*)&msg);
1363                                 tool_perror( "ldap_start_tls", rc, NULL, NULL, msg, NULL );
1364                                 ldap_memfree(msg);
1365                                 if ( use_tls > 1 ) {
1366                                         exit( EXIT_FAILURE );
1367                                 }
1368                         }
1369                 }
1370
1371                 if ( nettimeout.tv_sec > 0 ) {
1372                         if ( ldap_set_option( ld, LDAP_OPT_NETWORK_TIMEOUT, (void *) &nettimeout )
1373                                 != LDAP_OPT_SUCCESS )
1374                         {
1375                                 fprintf( stderr, "Could not set LDAP_OPT_NETWORK_TIMEOUT %ld\n",
1376                                         (long)nettimeout.tv_sec );
1377                                 exit( EXIT_FAILURE );
1378                         }
1379                 }
1380         }
1381
1382         return ld;
1383 }
1384
1385
1386 void
1387 tool_bind( LDAP *ld )
1388 {
1389         LDAPControl     **sctrlsp = NULL;
1390         LDAPControl     *sctrls[4];
1391         LDAPControl     sctrl[3];
1392         int             nsctrls = 0;
1393
1394         int rc, msgid;
1395         LDAPMessage *result = NULL;
1396
1397         int err;
1398         char *matched = NULL;
1399         char *info = NULL;
1400         char **refs = NULL;
1401         LDAPControl **ctrls = NULL;
1402         char msgbuf[256];
1403
1404         msgbuf[0] = 0;
1405
1406 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
1407         if ( ppolicy ) {
1408                 LDAPControl c;
1409                 c.ldctl_oid = LDAP_CONTROL_PASSWORDPOLICYREQUEST;
1410                 c.ldctl_value.bv_val = NULL;
1411                 c.ldctl_value.bv_len = 0;
1412                 c.ldctl_iscritical = 0;
1413                 sctrl[nsctrls] = c;
1414                 sctrls[nsctrls] = &sctrl[nsctrls];
1415                 sctrls[++nsctrls] = NULL;
1416         }
1417 #endif
1418
1419 #ifdef LDAP_CONTROL_AUTHZID_REQUEST
1420         if ( bauthzid ) {
1421                 LDAPControl c;
1422
1423                 c.ldctl_oid = LDAP_CONTROL_AUTHZID_REQUEST;
1424                 c.ldctl_iscritical = bauthzid > 1;
1425                 BER_BVZERO( &c.ldctl_value );
1426
1427                 sctrl[nsctrls] = c;
1428                 sctrls[nsctrls] = &sctrl[nsctrls];
1429                 sctrls[++nsctrls] = NULL;
1430         }
1431 #endif /* LDAP_CONTROL_AUTHZID_REQUEST */
1432
1433 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
1434         if ( sessionTracking ) {
1435                 LDAPControl c;
1436
1437                 if (stValue.bv_val == NULL && st_value( ld, &stValue ) ) {
1438                         exit( EXIT_FAILURE );
1439                 }
1440
1441                 c.ldctl_oid = LDAP_CONTROL_X_SESSION_TRACKING;
1442                 c.ldctl_iscritical = 0;
1443                 ber_dupbv( &c.ldctl_value, &stValue );
1444
1445                 sctrl[nsctrls] = c;
1446                 sctrls[nsctrls] = &sctrl[nsctrls];
1447                 sctrls[++nsctrls] = NULL;
1448         }
1449 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
1450
1451         if ( nsctrls ) {
1452                 sctrlsp = sctrls;
1453         }
1454
1455         assert( nsctrls < (int) (sizeof(sctrls)/sizeof(sctrls[0])) );
1456
1457         if ( pw_file || want_bindpw ) {
1458                 assert( passwd.bv_val == NULL && passwd.bv_len == 0 );
1459
1460                 if ( pw_file ) {
1461                         if ( lutil_get_filed_password( pw_file, &passwd ) ) {
1462                                 exit( EXIT_FAILURE );
1463                         }
1464
1465                 } else {
1466                         char *pw = getpassphrase( _("Enter LDAP Password: ") );
1467                         if ( pw ) {
1468                                 passwd.bv_val = ber_strdup( pw );
1469                                 passwd.bv_len = strlen( passwd.bv_val );
1470                         }
1471                 }
1472         }
1473
1474         if ( authmethod == LDAP_AUTH_SASL ) {
1475 #ifdef HAVE_CYRUS_SASL
1476                 void *defaults;
1477                 const char *rmech = NULL;
1478
1479                 if( sasl_secprops != NULL ) {
1480                         rc = ldap_set_option( ld, LDAP_OPT_X_SASL_SECPROPS,
1481                                 (void *) sasl_secprops );
1482
1483                         if( rc != LDAP_OPT_SUCCESS ) {
1484                                 fprintf( stderr,
1485                                         "Could not set LDAP_OPT_X_SASL_SECPROPS: %s\n",
1486                                         sasl_secprops );
1487                                 exit( LDAP_LOCAL_ERROR );
1488                         }
1489                 }
1490
1491                 defaults = lutil_sasl_defaults( ld,
1492                         sasl_mech,
1493                         sasl_realm,
1494                         sasl_authc_id,
1495                         passwd.bv_val,
1496                         sasl_authz_id );
1497
1498                 do {
1499                         rc = ldap_sasl_interactive_bind( ld, binddn, sasl_mech,
1500                                 sctrlsp, NULL, sasl_flags, lutil_sasl_interact, defaults,
1501                                 result, &rmech, &msgid );
1502
1503                         if ( rc != LDAP_SASL_BIND_IN_PROGRESS )
1504                                 break;
1505
1506                         ldap_msgfree( result );
1507
1508                         if ( ldap_result( ld, msgid, LDAP_MSG_ALL, NULL, &result ) == -1 || !result ) {
1509                                 ldap_get_option( ld, LDAP_OPT_RESULT_CODE, (void*)&err );
1510                                 ldap_get_option( ld, LDAP_OPT_DIAGNOSTIC_MESSAGE, (void*)&info );
1511                                 tool_perror( "ldap_sasl_interactive_bind",
1512                                         err, NULL, NULL, info, NULL );
1513                                 ldap_memfree( info );
1514                                 exit( err );
1515                         }
1516                 } while ( rc == LDAP_SASL_BIND_IN_PROGRESS );
1517
1518                 lutil_sasl_freedefs( defaults );
1519
1520                 if ( rc != LDAP_SUCCESS ) {
1521                         ldap_get_option( ld, LDAP_OPT_DIAGNOSTIC_MESSAGE, (void*)&info );
1522                         tool_perror( "ldap_sasl_interactive_bind",
1523                                 rc, NULL, NULL, info, NULL );
1524                         ldap_memfree( info );
1525                         exit( rc );
1526                 }
1527 #else
1528                 fprintf( stderr, "%s: not compiled with SASL support\n", prog );
1529                 exit( LDAP_NOT_SUPPORTED );
1530 #endif
1531         } else {
1532                 /* simple bind */
1533                 rc = ldap_sasl_bind( ld, binddn, LDAP_SASL_SIMPLE, &passwd,
1534                         sctrlsp, NULL, &msgid );
1535                 if ( msgid == -1 ) {
1536                         tool_perror( "ldap_sasl_bind(SIMPLE)", rc,
1537                                 NULL, NULL, NULL, NULL );
1538                         exit( rc );
1539                 }
1540
1541                 rc = ldap_result( ld, msgid, LDAP_MSG_ALL, NULL, &result );
1542                 if ( rc == -1 ) {
1543                         tool_perror( "ldap_result", -1, NULL, NULL, NULL, NULL );
1544                         exit( LDAP_LOCAL_ERROR );
1545                 }
1546
1547                 if ( rc == 0 ) {
1548                         tool_perror( "ldap_result", LDAP_TIMEOUT, NULL, NULL, NULL, NULL );
1549                         exit( LDAP_LOCAL_ERROR );
1550                 }
1551         }
1552
1553         rc = ldap_parse_result( ld, result, &err, &matched, &info, &refs,
1554                 &ctrls, 1 );
1555         if ( rc != LDAP_SUCCESS ) {
1556                 tool_perror( "ldap_bind parse result", rc, NULL, matched, info, refs );
1557                 exit( LDAP_LOCAL_ERROR );
1558         }
1559
1560 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
1561         if ( ctrls && ppolicy ) {
1562                 LDAPControl *ctrl;
1563                 int expire, grace, len = 0;
1564                 LDAPPasswordPolicyError pErr = -1;
1565                 
1566                 ctrl = ldap_control_find( LDAP_CONTROL_PASSWORDPOLICYRESPONSE,
1567                         ctrls, NULL );
1568
1569                 if ( ctrl && ldap_parse_passwordpolicy_control( ld, ctrl,
1570                         &expire, &grace, &pErr ) == LDAP_SUCCESS )
1571                 {
1572                         if ( pErr != PP_noError ){
1573                                 msgbuf[0] = ';';
1574                                 msgbuf[1] = ' ';
1575                                 strcpy( msgbuf+2, ldap_passwordpolicy_err2txt( pErr ));
1576                                 len = strlen( msgbuf );
1577                         }
1578                         if ( expire >= 0 ) {
1579                                 sprintf( msgbuf+len,
1580                                         " (Password expires in %d seconds)",
1581                                         expire );
1582                         } else if ( grace >= 0 ) {
1583                                 sprintf( msgbuf+len,
1584                                         " (Password expired, %d grace logins remain)",
1585                                         grace );
1586                         }
1587                 }
1588         }
1589 #endif
1590
1591 #ifdef LDAP_CONTROL_AUTHZID_REQUEST
1592         if ( ctrls && bauthzid ) {
1593                 LDAPControl *ctrl;
1594                 
1595                 ctrl = ldap_control_find( LDAP_CONTROL_AUTHZID_RESPONSE,
1596                         ctrls, NULL );
1597                 if ( ctrl ) {
1598                         LDAPControl *ctmp[2];
1599                         ctmp[0] = ctrl;
1600                         ctmp[1] = NULL;
1601                         tool_print_ctrls( ld, ctmp );
1602                 }
1603         }
1604 #endif /* LDAP_CONTROL_AUTHZID_REQUEST */
1605
1606         if ( ctrls ) {
1607                 ldap_controls_free( ctrls );
1608         }
1609
1610         if ( err != LDAP_SUCCESS
1611                 || msgbuf[0]
1612                 || ( matched && matched[ 0 ] )
1613                 || ( info && info[ 0 ] )
1614                 || refs )
1615         {
1616                 tool_perror( "ldap_bind", err, msgbuf, matched, info, refs );
1617
1618                 if( matched ) ber_memfree( matched );
1619                 if( info ) ber_memfree( info );
1620                 if( refs ) ber_memvfree( (void **)refs );
1621
1622                 if ( err != LDAP_SUCCESS ) exit( err );
1623         }
1624 }
1625
1626 void
1627 tool_unbind( LDAP *ld )
1628 {
1629         int err = ldap_set_option( ld, LDAP_OPT_SERVER_CONTROLS, NULL );
1630
1631         if ( err != LDAP_OPT_SUCCESS ) {
1632                 fprintf( stderr, "Could not unset controls\n");
1633         }
1634
1635         (void) ldap_unbind_ext( ld, NULL, NULL );
1636 }
1637
1638
1639 /* Set server controls.  Add controls extra_c[0..count-1], if set. */
1640 void
1641 tool_server_controls( LDAP *ld, LDAPControl *extra_c, int count )
1642 {
1643         int i = 0, j, crit = 0, err;
1644         LDAPControl c[16], **ctrls;
1645
1646         if ( ! ( assertctl
1647                 || authzid
1648 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
1649                 || proxydn
1650 #endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
1651                 || manageDIT
1652                 || manageDSAit
1653                 || noop
1654 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
1655                 || ppolicy
1656 #endif
1657                 || preread
1658                 || postread
1659 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
1660                 || chaining
1661 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
1662 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
1663                 || sessionTracking
1664 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
1665                 || count
1666                 || unknown_ctrls_num ) )
1667         {
1668                 return;
1669         }
1670
1671         ctrls = (LDAPControl**) malloc(sizeof(c) + (count + unknown_ctrls_num + 1)*sizeof(LDAPControl*));
1672         if ( ctrls == NULL ) {
1673                 fprintf( stderr, "No memory\n" );
1674                 exit( EXIT_FAILURE );
1675         }
1676
1677         if ( assertctl ) {
1678                 if ( BER_BVISNULL( &assertionvalue ) ) {
1679                         err = ldap_create_assertion_control_value( ld,
1680                                 assertion, &assertionvalue );
1681                         if ( err ) {
1682                                 fprintf( stderr,
1683                                         "Unable to create assertion value "
1684                                         "\"%s\" (%d)\n", assertion, err );
1685                         }
1686                 }
1687
1688                 c[i].ldctl_oid = LDAP_CONTROL_ASSERT;
1689                 c[i].ldctl_value = assertionvalue;
1690                 c[i].ldctl_iscritical = assertctl > 1;
1691                 ctrls[i] = &c[i];
1692                 i++;
1693         }
1694
1695         if ( authzid ) {
1696                 c[i].ldctl_value.bv_val = authzid;
1697                 c[i].ldctl_value.bv_len = strlen( authzid );
1698                 c[i].ldctl_oid = LDAP_CONTROL_PROXY_AUTHZ;
1699                 c[i].ldctl_iscritical = authzcrit;
1700                 ctrls[i] = &c[i];
1701                 i++;
1702         }
1703
1704 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
1705         /* NOTE: doesn't need an extra count because it's incompatible
1706          * with authzid */
1707         if ( proxydn ) {
1708                 BerElementBuffer berbuf;
1709                 BerElement *ber = (BerElement *)&berbuf;
1710                 
1711                 ber_init2( ber, NULL, LBER_USE_DER );
1712
1713                 if ( ber_printf( ber, "s", proxydn ) == -1 ) {
1714                         exit( EXIT_FAILURE );
1715                 }
1716
1717                 if ( ber_flatten2( ber, &c[i].ldctl_value, 0 ) == -1 ) {
1718                         exit( EXIT_FAILURE );
1719                 }
1720
1721                 c[i].ldctl_oid = LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ;
1722                 c[i].ldctl_iscritical = authzcrit;
1723                 ctrls[i] = &c[i];
1724                 i++;
1725         }
1726 #endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
1727
1728         if ( manageDIT ) {
1729                 c[i].ldctl_oid = LDAP_CONTROL_MANAGEDIT;
1730                 BER_BVZERO( &c[i].ldctl_value );
1731                 c[i].ldctl_iscritical = manageDIT > 1;
1732                 ctrls[i] = &c[i];
1733                 i++;
1734         }
1735
1736         if ( manageDSAit ) {
1737                 c[i].ldctl_oid = LDAP_CONTROL_MANAGEDSAIT;
1738                 BER_BVZERO( &c[i].ldctl_value );
1739                 c[i].ldctl_iscritical = manageDSAit > 1;
1740                 ctrls[i] = &c[i];
1741                 i++;
1742         }
1743
1744         if ( noop ) {
1745                 c[i].ldctl_oid = LDAP_CONTROL_NOOP;
1746                 BER_BVZERO( &c[i].ldctl_value );
1747                 c[i].ldctl_iscritical = noop > 1;
1748                 ctrls[i] = &c[i];
1749                 i++;
1750         }
1751
1752 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
1753         if ( ppolicy ) {
1754                 c[i].ldctl_oid = LDAP_CONTROL_PASSWORDPOLICYREQUEST;
1755                 BER_BVZERO( &c[i].ldctl_value );
1756                 c[i].ldctl_iscritical = 0;
1757                 ctrls[i] = &c[i];
1758                 i++;
1759         }
1760 #endif
1761
1762         if ( preread ) {
1763                 BerElementBuffer berbuf;
1764                 BerElement *ber = (BerElement *)&berbuf;
1765                 char **attrs = NULL;
1766
1767                 if( preread_attrs ) {
1768                         attrs = ldap_str2charray( preread_attrs, "," );
1769                 }
1770
1771                 ber_init2( ber, NULL, LBER_USE_DER );
1772
1773                 if( ber_printf( ber, "{v}", attrs ) == -1 ) {
1774                         fprintf( stderr, "preread attrs encode failed.\n" );
1775                         exit( EXIT_FAILURE );
1776                 }
1777
1778                 err = ber_flatten2( ber, &c[i].ldctl_value, 0 );
1779                 if( err < 0 ) {
1780                         fprintf( stderr, "preread flatten failed (%d)\n", err );
1781                         exit( EXIT_FAILURE );
1782                 }
1783
1784                 c[i].ldctl_oid = LDAP_CONTROL_PRE_READ;
1785                 c[i].ldctl_iscritical = preread > 1;
1786                 ctrls[i] = &c[i];
1787                 i++;
1788
1789                 if( attrs ) ldap_charray_free( attrs );
1790         }
1791
1792         if ( postread ) {
1793                 BerElementBuffer berbuf;
1794                 BerElement *ber = (BerElement *)&berbuf;
1795                 char **attrs = NULL;
1796
1797                 if( postread_attrs ) {
1798                         attrs = ldap_str2charray( postread_attrs, "," );
1799                 }
1800
1801                 ber_init2( ber, NULL, LBER_USE_DER );
1802
1803                 if( ber_printf( ber, "{v}", attrs ) == -1 ) {
1804                         fprintf( stderr, "postread attrs encode failed.\n" );
1805                         exit( EXIT_FAILURE );
1806                 }
1807
1808                 err = ber_flatten2( ber, &c[i].ldctl_value, 0 );
1809                 if( err < 0 ) {
1810                         fprintf( stderr, "postread flatten failed (%d)\n", err );
1811                         exit( EXIT_FAILURE );
1812                 }
1813
1814                 c[i].ldctl_oid = LDAP_CONTROL_POST_READ;
1815                 c[i].ldctl_iscritical = postread > 1;
1816                 ctrls[i] = &c[i];
1817                 i++;
1818
1819                 if( attrs ) ldap_charray_free( attrs );
1820         }
1821
1822 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
1823         if ( chaining ) {
1824                 if ( chainingResolve > -1 ) {
1825                         BerElementBuffer berbuf;
1826                         BerElement *ber = (BerElement *)&berbuf;
1827
1828                         ber_init2( ber, NULL, LBER_USE_DER );
1829
1830                         err = ber_printf( ber, "{e" /* } */, chainingResolve );
1831                         if ( err == -1 ) {
1832                                 ber_free( ber, 1 );
1833                                 fprintf( stderr, _("Chaining behavior control encoding error!\n") );
1834                                 exit( EXIT_FAILURE );
1835                         }
1836
1837                         if ( chainingContinuation > -1 ) {
1838                                 err = ber_printf( ber, "e", chainingContinuation );
1839                                 if ( err == -1 ) {
1840                                         ber_free( ber, 1 );
1841                                         fprintf( stderr, _("Chaining behavior control encoding error!\n") );
1842                                         exit( EXIT_FAILURE );
1843                                 }
1844                         }
1845
1846                         err = ber_printf( ber, /* { */ "N}" );
1847                         if ( err == -1 ) {
1848                                 ber_free( ber, 1 );
1849                                 fprintf( stderr, _("Chaining behavior control encoding error!\n") );
1850                                 exit( EXIT_FAILURE );
1851                         }
1852
1853                         if ( ber_flatten2( ber, &c[i].ldctl_value, 0 ) == -1 ) {
1854                                 exit( EXIT_FAILURE );
1855                         }
1856
1857                 } else {
1858                         BER_BVZERO( &c[i].ldctl_value );
1859                 }
1860
1861                 c[i].ldctl_oid = LDAP_CONTROL_X_CHAINING_BEHAVIOR;
1862                 c[i].ldctl_iscritical = chaining > 1;
1863                 ctrls[i] = &c[i];
1864                 i++;
1865         }
1866 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
1867
1868 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
1869         if ( sessionTracking ) {
1870                 if ( stValue.bv_val == NULL && st_value( ld, &stValue ) ) {
1871                         exit( EXIT_FAILURE );
1872                 }
1873
1874                 c[i].ldctl_oid = LDAP_CONTROL_X_SESSION_TRACKING;
1875                 c[i].ldctl_iscritical = 0;
1876                 ber_dupbv( &c[i].ldctl_value, &stValue );
1877
1878                 ctrls[i] = &c[i];
1879                 i++;
1880         }
1881 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
1882
1883         while ( count-- ) {
1884                 ctrls[i++] = extra_c++;
1885         }
1886         for ( count = 0; count < unknown_ctrls_num; count++ ) {
1887                 ctrls[i++] = &unknown_ctrls[count];
1888         }
1889         ctrls[i] = NULL;
1890
1891         err = ldap_set_option( ld, LDAP_OPT_SERVER_CONTROLS, ctrls );
1892
1893         if ( err != LDAP_OPT_SUCCESS ) {
1894                 for ( j = 0; j < i; j++ ) {
1895                         if ( ctrls[j]->ldctl_iscritical ) crit = 1;
1896                 }
1897                 fprintf( stderr, "Could not set %scontrols\n",
1898                         crit ? "critical " : "" );
1899         }
1900
1901         free( ctrls );
1902         if ( crit ) {
1903                 exit( EXIT_FAILURE );
1904         }
1905 }
1906
1907 int
1908 tool_check_abandon( LDAP *ld, int msgid )
1909 {
1910         int     rc;
1911
1912         switch ( gotintr ) {
1913         case Intr_Cancel:
1914                 rc = ldap_cancel_s( ld, msgid, NULL, NULL );
1915                 fprintf( stderr, "got interrupt, cancel got %d: %s\n",
1916                                 rc, ldap_err2string( rc ) );
1917                 return -1;
1918
1919         case Intr_Abandon:
1920                 rc = ldap_abandon_ext( ld, msgid, NULL, NULL );
1921                 fprintf( stderr, "got interrupt, abandon got %d: %s\n",
1922                                 rc, ldap_err2string( rc ) );
1923                 return -1;
1924
1925         case Intr_Ignore:
1926                 /* just unbind, ignoring the request */
1927                 return -1;
1928         }
1929
1930         return 0;
1931 }
1932
1933 static int
1934 print_prepostread( LDAP *ld, LDAPControl *ctrl, struct berval *what)
1935 {
1936         BerElement      *ber;
1937         struct berval   bv;
1938
1939         tool_write_ldif( LDIF_PUT_COMMENT, "==> ",
1940                 what->bv_val, what->bv_len );
1941         ber = ber_init( &ctrl->ldctl_value );
1942         if ( ber == NULL ) {
1943                 /* error? */
1944                 return 1;
1945
1946         } else if ( ber_scanf( ber, "{m{" /*}}*/, &bv ) == LBER_ERROR ) {
1947                 /* error? */
1948                 return 1;
1949
1950         } else {
1951                 tool_write_ldif( LDIF_PUT_VALUE, "dn", bv.bv_val, bv.bv_len );
1952
1953                 while ( ber_scanf( ber, "{m" /*}*/, &bv ) != LBER_ERROR ) {
1954                         int             i;
1955                         BerVarray       vals = NULL;
1956
1957                         if ( ber_scanf( ber, "[W]", &vals ) == LBER_ERROR ||
1958                                 vals == NULL )
1959                         {
1960                                 /* error? */
1961                                 return 1;
1962                         }
1963                 
1964                         for ( i = 0; vals[ i ].bv_val != NULL; i++ ) {
1965                                 tool_write_ldif(
1966                                         ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1967                                         bv.bv_val, vals[ i ].bv_val, vals[ i ].bv_len );
1968                         }
1969
1970                         ber_bvarray_free( vals );
1971                 }
1972         }
1973
1974         if ( ber != NULL ) {
1975                 ber_free( ber, 1 );
1976         }
1977
1978         tool_write_ldif( LDIF_PUT_COMMENT, "<== ",
1979                 what->bv_val, what->bv_len );
1980
1981         return 0;
1982 }
1983
1984 static int
1985 print_preread( LDAP *ld, LDAPControl *ctrl )
1986 {
1987         static struct berval what = BER_BVC( "preread" );
1988
1989         return print_prepostread( ld, ctrl, &what );
1990 }
1991
1992 static int
1993 print_postread( LDAP *ld, LDAPControl *ctrl )
1994 {
1995         static struct berval what = BER_BVC( "postread" );
1996
1997         return print_prepostread( ld, ctrl, &what );
1998 }
1999
2000 static int
2001 print_paged_results( LDAP *ld, LDAPControl *ctrl )
2002 {
2003         ber_int_t estimate;
2004
2005         /* note: pr_cookie is being malloced; it's freed
2006          * the next time the control is sent, but the last
2007          * time it's not; we don't care too much, because
2008          * the last time an empty value is returned... */
2009         if ( ldap_parse_pageresponse_control( ld, ctrl, &estimate, &pr_cookie )
2010                 != LDAP_SUCCESS )
2011         {
2012                 /* error? */
2013                 return 1;
2014
2015         } else {
2016                 /* FIXME: check buffer overflow */
2017                 char    buf[ BUFSIZ ], *ptr = buf;
2018
2019                 if ( estimate > 0 ) {
2020                         ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
2021                                 "estimate=%d", estimate );
2022                 }
2023
2024                 if ( pr_cookie.bv_len > 0 ) {
2025                         struct berval   bv;
2026
2027                         bv.bv_len = LUTIL_BASE64_ENCODE_LEN(
2028                                 pr_cookie.bv_len ) + 1;
2029                         bv.bv_val = ber_memalloc( bv.bv_len + 1 );
2030
2031                         bv.bv_len = lutil_b64_ntop(
2032                                 (unsigned char *) pr_cookie.bv_val,
2033                                 pr_cookie.bv_len,
2034                                 bv.bv_val, bv.bv_len );
2035
2036                         ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
2037                                 "%scookie=%s", ptr == buf ? "" : " ",
2038                                 bv.bv_val );
2039
2040                         ber_memfree( bv.bv_val );
2041
2042                         pr_morePagedResults = 1;
2043
2044                 } else {
2045                         ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
2046                                 "%scookie=", ptr == buf ? "" : " " );
2047                 }
2048
2049                 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
2050                         "pagedresults", buf, ptr - buf );
2051         }
2052
2053         return 0;
2054 }
2055
2056 static int
2057 print_sss( LDAP *ld, LDAPControl *ctrl )
2058 {
2059         int rc;
2060         ber_int_t err;
2061         char *attr;
2062
2063         rc = ldap_parse_sortresponse_control( ld, ctrl, &err, &attr );
2064         if ( rc == LDAP_SUCCESS ) {
2065                 char buf[ BUFSIZ ];
2066                 rc = snprintf( buf, sizeof(buf), "(%d) %s%s%s",
2067                         err, ldap_err2string(err), attr ? " " : "", attr ? attr : "" );
2068
2069                 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
2070                         "sortResult", buf, rc );
2071         }
2072
2073         return rc;
2074 }
2075
2076 static int
2077 print_vlv( LDAP *ld, LDAPControl *ctrl )
2078 {
2079         int rc;
2080         ber_int_t err;
2081         struct berval bv;
2082
2083         rc = ldap_parse_vlvresponse_control( ld, ctrl, &vlvPos, &vlvCount,
2084                 &vlvContext, &err );
2085         if ( rc == LDAP_SUCCESS ) {
2086                 char buf[ BUFSIZ ];
2087
2088                 if ( vlvContext && vlvContext->bv_len > 0 ) {
2089                         bv.bv_len = LUTIL_BASE64_ENCODE_LEN(
2090                                 vlvContext->bv_len ) + 1;
2091                         bv.bv_val = ber_memalloc( bv.bv_len + 1 );
2092
2093                         bv.bv_len = lutil_b64_ntop(
2094                                 (unsigned char *) vlvContext->bv_val,
2095                                 vlvContext->bv_len,
2096                                 bv.bv_val, bv.bv_len );
2097                 } else {
2098                         bv.bv_val = "";
2099                         bv.bv_len = 0;
2100                 }
2101
2102                 rc = snprintf( buf, sizeof(buf), "pos=%d count=%d context=%s (%d) %s",
2103                         vlvPos, vlvCount, bv.bv_val,
2104                         err, ldap_err2string(err));
2105
2106                 if ( bv.bv_len )
2107                         ber_memfree( bv.bv_val );
2108
2109                 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
2110                         "vlvResult", buf, rc );
2111         }
2112
2113         return rc;
2114 }
2115
2116 #ifdef LDAP_CONTROL_X_DEREF
2117 static int
2118 print_deref( LDAP *ld, LDAPControl *ctrl )
2119 {
2120         LDAPDerefRes    *drhead = NULL, *dr;
2121         int             rc;
2122
2123         rc = ldap_parse_derefresponse_control( ld, ctrl, &drhead );
2124         if ( rc != LDAP_SUCCESS ) {
2125                 return rc;
2126         }
2127
2128         for ( dr = drhead; dr != NULL; dr = dr->next ) {
2129                 LDAPDerefVal    *dv;
2130                 ber_len_t       len;
2131                 char            *buf, *ptr;
2132
2133                 len = strlen( dr->derefAttr ) + STRLENOF(": ");
2134
2135                 for ( dv = dr->attrVals; dv != NULL; dv = dv->next ) {
2136                         if ( dv->vals != NULL ) {
2137                                 int j;
2138                                 ber_len_t tlen = strlen(dv->type);
2139
2140                                 for ( j = 0; dv->vals[ j ].bv_val != NULL; j++ ) {
2141                                         len += STRLENOF("<:=>;") + tlen + 4*((dv->vals[ j ].bv_len - 1)/3 + 1);
2142                                 }
2143                         }
2144                 }
2145                 len += dr->derefVal.bv_len + STRLENOF("\n");
2146                 buf = ldap_memalloc( len + 1 );
2147                 if ( buf == NULL ) {
2148                         rc = LDAP_NO_MEMORY;
2149                         goto done;
2150                 }
2151
2152                 ptr = buf;
2153                 ptr = lutil_strcopy( ptr, dr->derefAttr );
2154                 *ptr++ = ':';
2155                 *ptr++ = ' ';
2156                 for ( dv = dr->attrVals; dv != NULL; dv = dv->next ) {
2157                         if ( dv->vals != NULL ) {
2158                                 int j;
2159                                 for ( j = 0; dv->vals[ j ].bv_val != NULL; j++ ) {
2160                                         int k = ldif_is_not_printable( dv->vals[ j ].bv_val, dv->vals[ j ].bv_len );
2161
2162                                         *ptr++ = '<';
2163                                         ptr = lutil_strcopy( ptr, dv->type );
2164                                         if ( k ) {
2165                                                 *ptr++ = ':';
2166                                         }
2167                                         *ptr++ = '=';
2168                                         if ( k ) {
2169                                                 k = lutil_b64_ntop(
2170                                                         (unsigned char *) dv->vals[ j ].bv_val,
2171                                                         dv->vals[ j ].bv_len,
2172                                                         ptr, buf + len - ptr );
2173                                                 assert( k >= 0 );
2174                                                 ptr += k;
2175                                                 
2176                                         } else {
2177                                                 ptr = lutil_memcopy( ptr, dv->vals[ j ].bv_val, dv->vals[ j ].bv_len );
2178                                         }
2179                                         *ptr++ = '>';
2180                                         *ptr++ = ';';
2181                                 }
2182                         }
2183                 }
2184                 ptr = lutil_strncopy( ptr, dr->derefVal.bv_val, dr->derefVal.bv_len );
2185                 *ptr++ = '\n';
2186                 *ptr = '\0';
2187                 assert( ptr <= buf + len );
2188
2189                 tool_write_ldif( LDIF_PUT_COMMENT, NULL, buf, ptr - buf);
2190
2191                 ldap_memfree( buf );
2192         }
2193
2194         rc = LDAP_SUCCESS;
2195
2196 done:;
2197         ldap_derefresponse_free( drhead );
2198
2199         return rc;
2200 }
2201 #endif
2202
2203 #ifdef LDAP_CONTROL_X_WHATFAILED
2204 static int
2205 print_whatfailed( LDAP *ld, LDAPControl *ctrl )
2206 {
2207         BerElement *ber;
2208         ber_tag_t tag;
2209         ber_len_t siz;
2210         BerVarray bva = NULL;
2211
2212         /* Create a BerElement from the berval returned in the control. */
2213         ber = ber_init( &ctrl->ldctl_value );
2214
2215         if ( ber == NULL ) {
2216                 return LDAP_NO_MEMORY;
2217         }
2218
2219         siz = sizeof(struct berval);
2220         tag = ber_scanf( ber, "[M]", &bva, &siz, 0 );
2221         if ( tag != LBER_ERROR ) {
2222                 int i;
2223
2224                 tool_write_ldif( LDIF_PUT_COMMENT, " what failed:", NULL, 0 );
2225
2226                 for ( i = 0; bva[i].bv_val != NULL; i++ ) {
2227                         tool_write_ldif( LDIF_PUT_COMMENT, NULL, bva[i].bv_val, bva[i].bv_len );
2228                 }
2229
2230                 ldap_memfree( bva );
2231         }
2232
2233         ber_free( ber, 1 );
2234
2235
2236         return 0;
2237 }
2238 #endif
2239
2240 #ifdef LDAP_CONTROL_AUTHZID_RESPONSE
2241 static int
2242 print_authzid( LDAP *ld, LDAPControl *ctrl )
2243 {
2244     if (ctrl->ldctl_value.bv_len) {
2245             tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
2246                     "authzid", ctrl->ldctl_value.bv_val,  ctrl->ldctl_value.bv_len );
2247         } else {
2248             tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
2249                     "authzid", "anonymous",  sizeof("anonymous")-1);
2250         }
2251 }
2252 #endif
2253
2254 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
2255 static int
2256 print_ppolicy( LDAP *ld, LDAPControl *ctrl )
2257 {
2258         int expire = 0, grace = 0, rc;
2259         LDAPPasswordPolicyError pperr;
2260
2261         rc = ldap_parse_passwordpolicy_control( ld, ctrl,
2262                 &expire, &grace, &pperr );
2263         if ( rc == LDAP_SUCCESS ) {
2264                 char    buf[ BUFSIZ ], *ptr = buf;
2265
2266                 if ( expire != -1 ) {
2267                         ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
2268                                 "expire=%d", expire );
2269                 }
2270
2271                 if ( grace != -1 ) {
2272                         ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
2273                                 "%sgrace=%d", ptr == buf ? "" : " ", grace );
2274                 }
2275
2276                 if ( pperr != PP_noError ) {
2277                         ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
2278                                 "%serror=%d (%s)", ptr == buf ? "" : " ",
2279                                 pperr,
2280                                 ldap_passwordpolicy_err2txt( pperr ) );
2281                 }
2282
2283                 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
2284                         "ppolicy", buf, ptr - buf );
2285         }
2286
2287         return rc;
2288 }
2289 #endif
2290
2291 void tool_print_ctrls(
2292         LDAP            *ld,
2293         LDAPControl     **ctrls )
2294 {
2295         int     i;
2296         char    *ptr;
2297
2298         for ( i = 0; ctrls[i] != NULL; i++ ) {
2299                 /* control: OID criticality base64value */
2300                 struct berval b64 = BER_BVNULL;
2301                 ber_len_t len;
2302                 char *str;
2303                 int j;
2304
2305                 /* FIXME: there might be cases where a control has NULL OID;
2306                  * this makes little sense, especially when returned by the
2307                  * server, but libldap happily allows it */
2308                 if ( ctrls[i]->ldctl_oid == NULL ) {
2309                         continue;
2310                 }
2311
2312                 len = ldif ? 2 : 0;
2313                 len += strlen( ctrls[i]->ldctl_oid );
2314
2315                 /* add enough for space after OID and the critical value itself */
2316                 len += ctrls[i]->ldctl_iscritical
2317                         ? sizeof("true") : sizeof("false");
2318
2319                 /* convert to base64 */
2320                 if ( !BER_BVISNULL( &ctrls[i]->ldctl_value ) ) {
2321                         b64.bv_len = LUTIL_BASE64_ENCODE_LEN(
2322                                 ctrls[i]->ldctl_value.bv_len ) + 1;
2323                         b64.bv_val = ber_memalloc( b64.bv_len + 1 );
2324
2325                         b64.bv_len = lutil_b64_ntop(
2326                                 (unsigned char *) ctrls[i]->ldctl_value.bv_val,
2327                                 ctrls[i]->ldctl_value.bv_len,
2328                                 b64.bv_val, b64.bv_len );
2329                 }
2330
2331                 if ( b64.bv_len ) {
2332                         len += 1 + b64.bv_len;
2333                 }
2334
2335                 ptr = str = malloc( len + 1 );
2336                 if ( ldif ) {
2337                         ptr = lutil_strcopy( ptr, ": " );
2338                 }
2339                 ptr = lutil_strcopy( ptr, ctrls[i]->ldctl_oid );
2340                 ptr = lutil_strcopy( ptr, ctrls[i]->ldctl_iscritical
2341                         ? " true" : " false" );
2342
2343                 if ( b64.bv_len ) {
2344                         ptr = lutil_strcopy( ptr, " " );
2345                         ptr = lutil_strcopy( ptr, b64.bv_val );
2346                 }
2347
2348                 if ( ldif < 2 ) {
2349                         tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
2350                                 "control", str, len );
2351                 }
2352
2353                 free( str );
2354                 if ( b64.bv_len ) {
2355                         ber_memfree( b64.bv_val );
2356                 }
2357
2358                 /* known controls */
2359                 for ( j = 0; tool_ctrl_response[j].oid != NULL; j++ ) {
2360                         if ( strcmp( tool_ctrl_response[j].oid, ctrls[i]->ldctl_oid ) == 0 ) {
2361                                 if ( !tool_ctrl_response[j].mask & tool_type ) {
2362                                         /* this control should not appear
2363                                          * with this tool; warning? */
2364                                 }
2365                                 break;
2366                         }
2367                 }
2368
2369                 if ( tool_ctrl_response[j].oid != NULL && tool_ctrl_response[j].func ) {
2370                         (void)tool_ctrl_response[j].func( ld, ctrls[i] );
2371                 }
2372         }
2373 }
2374
2375 int
2376 tool_write_ldif( int type, char *name, char *value, ber_len_t vallen )
2377 {
2378         char    *ldif;
2379
2380         if (( ldif = ldif_put_wrap( type, name, value, vallen, ldif_wrap )) == NULL ) {
2381                 return( -1 );
2382         }
2383
2384         fputs( ldif, stdout );
2385         ber_memfree( ldif );
2386
2387         return( 0 );
2388 }
2389
2390 int
2391 tool_is_oid( const char *s )
2392 {
2393         int             first = 1;
2394
2395         if ( !isdigit( (unsigned char) s[ 0 ] ) ) {
2396                 return 0;
2397         }
2398
2399         for ( ; s[ 0 ]; s++ ) {
2400                 if ( s[ 0 ] == '.' ) {
2401                         if ( s[ 1 ] == '\0' ) {
2402                                 return 0;
2403                         }
2404                         first = 1;
2405                         continue;
2406                 }
2407
2408                 if ( !isdigit( (unsigned char) s[ 0 ] ) ) {
2409                         return 0;
2410                 }
2411
2412                 if ( first == 1 && s[ 0 ] == '0' && s[ 1 ] != '.' ) {
2413                         return 0;
2414                 }
2415                 first = 0;
2416         }
2417
2418         return 1;
2419 }
2420