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