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