]> git.sur5r.net Git - openldap/blob - clients/tools/common.c
tool_bind(): Do not use pointer to out-of-scope variable (ITS#4434, ppolicy)
[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-2006 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
36 #ifdef HAVE_CYRUS_SASL
37 #ifdef HAVE_SASL_SASL_H
38 #include <sasl/sasl.h>
39 #else
40 #include <sasl.h>
41 #endif
42 #endif
43
44 #include <ldap.h>
45
46 #include "ldif.h"
47 #include "lutil.h"
48 #include "lutil_ldap.h"
49 #include "ldap_defaults.h"
50 #include "ldap_pvt.h"
51 #include "lber_pvt.h"
52
53 #include "common.h"
54
55 #ifdef LDAP_API_FEATURE_X_OPENLDAP_V2_KBIND
56 #if !LDAP_DEPRECATED
57 /* Necessary for old LDAPv2 Kerberos Bind methods */
58 LDAP_F( int )
59 ldap_bind LDAP_P((      /* deprecated */
60         LDAP *ld,
61         LDAP_CONST char *who,
62         LDAP_CONST char *passwd,
63         int authmethod ));
64 #endif
65 #endif
66
67 /* input-related vars */
68
69 /* misc. parameters */
70 tool_type_t     tool_type;
71 int             contoper = 0;
72 int             debug = 0;
73 char            *infile = NULL;
74 int             dont = 0;
75 int             referrals = 0;
76 int             verbose = 0;
77 int             ldif = 0;
78 char            *prog = NULL;
79
80 /* connection */
81 char            *ldapuri = NULL;
82 char            *ldaphost = NULL;
83 int             ldapport = 0;
84 int             use_tls = 0;
85 int             protocol = -1;
86 int             version = 0;
87
88 /* authc/authz */
89 int             authmethod = -1;
90 char            *binddn = NULL;
91 int             want_bindpw = 0;
92 struct berval   passwd = { 0, NULL };
93 char            *pw_file = NULL;
94 #ifdef HAVE_CYRUS_SASL
95 unsigned        sasl_flags = LDAP_SASL_AUTOMATIC;
96 char            *sasl_realm = NULL;
97 char            *sasl_authc_id = NULL;
98 char            *sasl_authz_id = NULL;
99 char            *sasl_mech = NULL;
100 char            *sasl_secprops = NULL;
101 #endif
102
103 /* controls */
104 int             assertctl;
105 char            *assertion = NULL;
106 char            *authzid = NULL;
107 /* support deprecated early version of proxyAuthz */
108 #define LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ       "2.16.840.1.113730.3.4.12"
109 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
110 char            *proxydn = NULL;
111 #endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
112 int             manageDIT = 0;
113 int             manageDSAit = 0;
114 int             noop = 0;
115 int             ppolicy = 0;
116 int             preread = 0;
117 static char     *preread_attrs = NULL;
118 int             postread = 0;
119 static char     *postread_attrs = NULL;
120 ber_int_t       pr_morePagedResults = 1;
121 struct berval   pr_cookie = { 0, NULL };
122 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
123 int             chaining = 0;
124 static int      chainingResolve = -1;
125 static int      chainingContinuation = -1;
126 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
127
128 typedef int (*print_ctrl_fn)( LDAP *ld, LDAPControl *ctrl );
129
130 static int print_preread( LDAP *ld, LDAPControl *ctrl );
131 static int print_postread( LDAP *ld, LDAPControl *ctrl );
132 static int print_paged_results( LDAP *ld, LDAPControl *ctrl );
133 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
134 static int print_ppolicy( LDAP *ld, LDAPControl *ctrl );
135 #endif
136
137 static struct tool_ctrls_t {
138         const char      *oid;
139         unsigned        mask;
140         print_ctrl_fn   func;
141 } tool_ctrl_response[] = {
142         { LDAP_CONTROL_PRE_READ,                        TOOL_ALL,       print_preread },
143         { LDAP_CONTROL_POST_READ,                       TOOL_ALL,       print_postread },
144         { LDAP_CONTROL_PAGEDRESULTS,                    TOOL_SEARCH,    print_paged_results },
145 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
146         { LDAP_CONTROL_PASSWORDPOLICYRESPONSE,          TOOL_ALL,       print_ppolicy },
147 #endif
148         { NULL,                                         0,              NULL }
149 };
150
151 /* "features" */
152 static int      gotintr;
153 static int      abcan;
154
155 RETSIGTYPE
156 do_sig( int sig )
157 {
158         gotintr = abcan;
159 }
160
161 void
162 tool_init( tool_type_t type )
163 {
164         tool_type = type;
165         ldap_pvt_setlocale(LC_MESSAGES, "");
166         ldap_pvt_bindtextdomain(OPENLDAP_PACKAGE, LDAP_LOCALEDIR);
167         ldap_pvt_textdomain(OPENLDAP_PACKAGE);
168 }
169
170 void
171 tool_destroy( void )
172 {
173 #ifdef HAVE_CYRUS_SASL
174         sasl_done();
175 #endif
176 #ifdef HAVE_TLS
177         ldap_pvt_tls_destroy();
178 #endif
179 }
180
181 void
182 tool_common_usage( void )
183 {
184         static const char *const descriptions[] = {
185 N_("  -c         continuous operation mode (do not stop on errors)\n"),
186 N_("  -C         chase referrals (anonymously)\n"),
187 N_("  -d level   set LDAP debugging level to `level'\n"),
188 N_("  -D binddn  bind DN\n"),
189 N_("  -e [!]<ext>[=<extparam>] general extensions (! indicates criticality)\n")
190 N_("             [!]assert=<filter>     (an RFC 2254 Filter)\n")
191 N_("             [!]authzid=<authzid>   (\"dn:<dn>\" or \"u:<user>\")\n")
192 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
193 #if 0
194                  /* non-advertized support for proxyDN */
195 N_("             [!]proxydn=<dn>        (an RFC 2253 DN)\n")
196 #endif
197 #endif
198 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
199 N_("             [!]chaining[=<resolveBehavior>[/<continuationBehavior>]]\n")
200 N_("                     one of \"chainingPreferred\", \"chainingRequired\",\n")
201 N_("                     \"referralsPreferred\", \"referralsRequired\"\n")
202 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
203 #ifdef LDAP_DEVEL
204 N_("             [!]manageDIT\n")
205 #endif
206 N_("             [!]manageDSAit\n")
207 N_("             [!]noop\n")
208 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
209 N_("             ppolicy\n")
210 #endif
211 N_("             [!]postread[=<attrs>]  (a comma-separated attribute list)\n")
212 N_("             [!]preread[=<attrs>]   (a comma-separated attribute list)\n"),
213 N_("             abandon, cancel (SIGINT sends abandon/cancel; not really controls)\n")
214 N_("  -f file    read operations from `file'\n"),
215 N_("  -h host    LDAP server\n"),
216 N_("  -H URI     LDAP Uniform Resource Indentifier(s)\n"),
217 N_("  -I         use SASL Interactive mode\n"),
218 N_("  -k         use Kerberos authentication\n"),
219 N_("  -K         like -k, but do only step 1 of the Kerberos bind\n"),
220 N_("  -M         enable Manage DSA IT control (-MM to make critical)\n"),
221 N_("  -n         show what would be done but don't actually do it\n"),
222 N_("  -O props   SASL security properties\n"),
223 N_("  -p port    port on LDAP server\n"),
224 N_("  -P version procotol version (default: 3)\n"),
225 N_("  -Q         use SASL Quiet mode\n"),
226 N_("  -R realm   SASL realm\n"),
227 N_("  -U authcid SASL authentication identity\n"),
228 N_("  -v         run in verbose mode (diagnostics to standard output)\n"),
229 N_("  -V         print version info (-VV only)\n"),
230 N_("  -w passwd  bind password (for simple authentication)\n"),
231 N_("  -W         prompt for bind password\n"),
232 N_("  -x         Simple authentication\n"),
233 N_("  -X authzid SASL authorization identity (\"dn:<dn>\" or \"u:<user>\")\n"),
234 N_("  -y file    Read password from file\n"),
235 N_("  -Y mech    SASL mechanism\n"),
236 N_("  -Z         Start TLS request (-ZZ to require successful response)\n"),
237 NULL
238         };
239         const char *const *cpp;
240
241         fputs( _("Common options:\n"), stderr );
242         for( cpp = descriptions; *cpp != NULL; cpp++ ) {
243                 if( strchr( options, (*cpp)[3] ) || (*cpp)[3] == ' ' ) {
244                         fputs( _(*cpp), stderr );
245                 }
246         }
247 }
248
249 void tool_perror(
250         const char *func,
251         int err,
252         const char *extra,
253         const char *matched,
254         const char *info,
255         char **refs )
256 {
257         fprintf( stderr, "%s: %s (%d)%s\n",
258                 func, ldap_err2string( err ), err, extra ? extra : "" );
259
260         if ( matched && *matched ) {
261                 fprintf( stderr, _("\tmatched DN: %s\n"), matched );
262         }
263
264         if ( info && *info ) {
265                 fprintf( stderr, _("\tadditional info: %s\n"), info );
266         }
267
268         if ( refs && *refs ) {
269                 int i;
270                 fprintf( stderr, _("\treferrals:\n") );
271                 for( i=0; refs[i]; i++ ) {
272                         fprintf( stderr, "\t\t%s\n", refs[i] );
273                 }
274         }
275 }
276
277
278 void
279 tool_args( int argc, char **argv )
280 {
281         int i;
282
283         while (( i = getopt( argc, argv, options )) != EOF ) {
284                 int crit, ival;
285                 char *control, *cvalue, *next;
286                 switch( i ) {
287                 case 'c':       /* continuous operation mode */
288                         contoper++;
289                         break;
290                 case 'C':
291                         referrals++;
292                         break;
293                 case 'd':
294                         ival = strtol( optarg, &next, 10 );
295                         if (next == NULL || next[0] != '\0') {
296                                 fprintf( stderr, "%s: unable to parse debug value \"%s\"\n", prog, optarg);
297                                 exit(EXIT_FAILURE);
298                         }
299                         debug |= ival;
300                         break;
301                 case 'D':       /* bind DN */
302                         if( binddn != NULL ) {
303                                 fprintf( stderr, "%s: -D previously specified\n", prog );
304                                 exit( EXIT_FAILURE );
305                         }
306                         binddn = ber_strdup( optarg );
307                         break;
308                 case 'e': /* general extensions (controls and such) */
309                         /* should be extended to support comma separated list of
310                          *      [!]key[=value] parameters, e.g.  -e !foo,bar=567
311                          */
312
313                         crit = 0;
314                         cvalue = NULL;
315                         if( optarg[0] == '!' ) {
316                                 crit = 1;
317                                 optarg++;
318                         }
319
320                         control = ber_strdup( optarg );
321                         if ( (cvalue = strchr( control, '=' )) != NULL ) {
322                                 *cvalue++ = '\0';
323                         }
324
325                         if ( strcasecmp( control, "assert" ) == 0 ) {
326                                 if( assertctl ) {
327                                         fprintf( stderr, "assert control previously specified\n");
328                                         exit( EXIT_FAILURE );
329                                 }
330                                 if( cvalue == NULL ) {
331                                         fprintf( stderr, "assert: control value expected\n" );
332                                         usage();
333                                 }
334
335                                 assertctl = 1 + crit;
336
337                                 assert( assertion == NULL );
338                                 assertion = cvalue;
339
340                         } else if ( strcasecmp( control, "authzid" ) == 0 ) {
341                                 if( authzid != NULL ) {
342                                         fprintf( stderr, "authzid control previously specified\n");
343                                         exit( EXIT_FAILURE );
344                                 }
345 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
346                                 if( proxydn != NULL ) {
347                                         fprintf( stderr, "authzid control incompatible with proxydn\n");
348                                         exit( EXIT_FAILURE );
349                                 }
350 #endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
351                                 if( cvalue == NULL ) {
352                                         fprintf( stderr, "authzid: control value expected\n" );
353                                         usage();
354                                 }
355                                 if( !crit ) {
356                                         fprintf( stderr, "authzid: must be marked critical\n" );
357                                         usage();
358                                 }
359
360                                 assert( authzid == NULL );
361                                 authzid = cvalue;
362
363 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
364                         } else if ( strcasecmp( control, "proxydn" ) == 0 ) {
365                                 if( proxydn != NULL ) {
366                                         fprintf( stderr, "proxydn control previously specified\n");
367                                         exit( EXIT_FAILURE );
368                                 }
369                                 if( authzid != NULL ) {
370                                         fprintf( stderr, "proxydn control incompatible with authzid\n");
371                                         exit( EXIT_FAILURE );
372                                 }
373                                 if( cvalue == NULL ) {
374                                         fprintf( stderr, "proxydn: control value expected\n" );
375                                         usage();
376                                 }
377                                 if( !crit ) {
378                                         fprintf( stderr, "proxydn: must be marked critical\n" );
379                                         usage();
380                                 }
381
382                                 assert( proxydn == NULL );
383                                 proxydn = cvalue;
384 #endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
385
386                         } else if ( strcasecmp( control, "manageDIT" ) == 0 ) {
387                                 if( manageDIT ) {
388                                         fprintf( stderr,
389                                                 "manageDIT control previously specified\n");
390                                         exit( EXIT_FAILURE );
391                                 }
392                                 if( cvalue != NULL ) {
393                                         fprintf( stderr,
394                                                 "manageDIT: no control value expected\n" );
395                                         usage();
396                                 }
397
398                                 manageDIT = 1 + crit;
399
400                         } else if ( strcasecmp( control, "manageDSAit" ) == 0 ) {
401                                 if( manageDSAit ) {
402                                         fprintf( stderr,
403                                                 "manageDSAit control previously specified\n");
404                                         exit( EXIT_FAILURE );
405                                 }
406                                 if( cvalue != NULL ) {
407                                         fprintf( stderr,
408                                                 "manageDSAit: no control value expected\n" );
409                                         usage();
410                                 }
411
412                                 manageDSAit = 1 + crit;
413
414                         } else if ( strcasecmp( control, "noop" ) == 0 ) {
415                                 if( noop ) {
416                                         fprintf( stderr, "noop control previously specified\n");
417                                         exit( EXIT_FAILURE );
418                                 }
419                                 if( cvalue != NULL ) {
420                                         fprintf( stderr, "noop: no control value expected\n" );
421                                         usage();
422                                 }
423
424                                 noop = 1 + crit;
425
426 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
427                         } else if ( strcasecmp( control, "ppolicy" ) == 0 ) {
428                                 if( ppolicy ) {
429                                         fprintf( stderr, "ppolicy control previously specified\n");
430                                         exit( EXIT_FAILURE );
431                                 }
432                                 if( cvalue != NULL ) {
433                                         fprintf( stderr, "ppolicy: no control value expected\n" );
434                                         usage();
435                                 }
436                                 if( crit ) {
437                                         fprintf( stderr, "ppolicy: critical flag not allowed\n" );
438                                         usage();
439                                 }
440
441                                 ppolicy = 1;
442 #endif
443
444                         } else if ( strcasecmp( control, "preread" ) == 0 ) {
445                                 if( preread ) {
446                                         fprintf( stderr, "preread control previously specified\n");
447                                         exit( EXIT_FAILURE );
448                                 }
449
450                                 preread = 1 + crit;
451                                 preread_attrs = cvalue;
452
453                         } else if ( strcasecmp( control, "postread" ) == 0 ) {
454                                 if( postread ) {
455                                         fprintf( stderr, "postread control previously specified\n");
456                                         exit( EXIT_FAILURE );
457                                 }
458
459                                 postread = 1 + crit;
460                                 postread_attrs = cvalue;
461
462 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
463                         } else if ( strcasecmp( control, "chaining" ) == 0 ) {
464                                 chaining = 1 + crit;
465
466                                 if ( cvalue != NULL ) {
467                                         char    *continuation;
468
469                                         continuation = strchr( cvalue, '/' );
470                                         if ( continuation ) {
471                                                 /* FIXME: this makes sense only in searches */
472                                                 *continuation++ = '\0';
473                                                 if ( strcasecmp( continuation, "chainingPreferred" ) == 0 ) {
474                                                         chainingContinuation = LDAP_CHAINING_PREFERRED;
475                                                 } else if ( strcasecmp( continuation, "chainingRequired" ) == 0 ) {
476                                                         chainingContinuation = LDAP_CHAINING_REQUIRED;
477                                                 } else if ( strcasecmp( continuation, "referralsPreferred" ) == 0 ) {
478                                                         chainingContinuation = LDAP_REFERRALS_PREFERRED;
479                                                 } else if ( strcasecmp( continuation, "referralsRequired" ) == 0 ) {
480                                                         chainingContinuation = LDAP_REFERRALS_REQUIRED;
481                                                 } else {
482                                                         fprintf( stderr,
483                                                                 "chaining behavior control "
484                                                                 "continuation value \"%s\" invalid\n",
485                                                                 continuation );
486                                                         exit( EXIT_FAILURE );
487                                                 }
488                                         }
489         
490                                         if ( strcasecmp( cvalue, "chainingPreferred" ) == 0 ) {
491                                                 chainingResolve = LDAP_CHAINING_PREFERRED;
492                                         } else if ( strcasecmp( cvalue, "chainingRequired" ) == 0 ) {
493                                                 chainingResolve = LDAP_CHAINING_REQUIRED;
494                                         } else if ( strcasecmp( cvalue, "referralsPreferred" ) == 0 ) {
495                                                 chainingResolve = LDAP_REFERRALS_PREFERRED;
496                                         } else if ( strcasecmp( cvalue, "referralsRequired" ) == 0 ) {
497                                                 chainingResolve = LDAP_REFERRALS_REQUIRED;
498                                         } else {
499                                                 fprintf( stderr,
500                                                         "chaining behavior control "
501                                                         "resolve value \"%s\" invalid\n",
502                                                         cvalue);
503                                                 exit( EXIT_FAILURE );
504                                         }
505                                 }
506 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
507
508                         /* this shouldn't go here, really; but it's a feature... */
509                         } else if ( strcasecmp( control, "abandon" ) == 0 ) {
510                                 abcan = LDAP_REQ_ABANDON;
511
512                         } else if ( strcasecmp( control, "cancel" ) == 0 ) {
513                                 abcan = LDAP_REQ_EXTENDED;
514
515                         } else {
516                                 fprintf( stderr, "Invalid general control name: %s\n",
517                                         control );
518                                 usage();
519                         }
520                         break;
521                 case 'f':       /* read from file */
522                         if( infile != NULL ) {
523                                 fprintf( stderr, "%s: -f previously specified\n", prog );
524                                 exit( EXIT_FAILURE );
525                         }
526                         infile = ber_strdup( optarg );
527                         break;
528                 case 'h':       /* ldap host */
529                         if( ldaphost != NULL ) {
530                                 fprintf( stderr, "%s: -h previously specified\n", prog );
531                                 exit( EXIT_FAILURE );
532                         }
533                         ldaphost = ber_strdup( optarg );
534                         break;
535                 case 'H':       /* ldap URI */
536                         if( ldapuri != NULL ) {
537                                 fprintf( stderr, "%s: -H previously specified\n", prog );
538                                 exit( EXIT_FAILURE );
539                         }
540                         ldapuri = ber_strdup( optarg );
541                         break;
542                 case 'I':
543 #ifdef HAVE_CYRUS_SASL
544                         if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
545                                 fprintf( stderr, "%s: incompatible previous "
546                                         "authentication choice\n",
547                                         prog );
548                                 exit( EXIT_FAILURE );
549                         }
550                         authmethod = LDAP_AUTH_SASL;
551                         sasl_flags = LDAP_SASL_INTERACTIVE;
552                         break;
553 #else
554                         fprintf( stderr, "%s: was not compiled with SASL support\n",
555                                 prog );
556                         exit( EXIT_FAILURE );
557 #endif
558                 case 'k':       /* kerberos bind */
559 #ifdef LDAP_API_FEATURE_X_OPENLDAP_V2_KBIND
560                         if( authmethod != -1 ) {
561                                 fprintf( stderr, "%s: -k incompatible with previous "
562                                         "authentication choice\n", prog );
563                                 exit( EXIT_FAILURE );
564                         }
565                         authmethod = LDAP_AUTH_KRBV4;
566 #else
567                         fprintf( stderr, "%s: not compiled with Kerberos support\n", prog );
568                         exit( EXIT_FAILURE );
569 #endif
570                         break;
571                 case 'K':       /* kerberos bind, part one only */
572 #ifdef LDAP_API_FEATURE_X_OPENLDAP_V2_KBIND
573                         if( authmethod != -1 ) {
574                                 fprintf( stderr, "%s: incompatible with previous "
575                                         "authentication choice\n", prog );
576                                 exit( EXIT_FAILURE );
577                         }
578                         authmethod = LDAP_AUTH_KRBV41;
579 #else
580                         fprintf( stderr, "%s: not compiled with Kerberos support\n", prog );
581                         exit( EXIT_FAILURE );
582 #endif
583                         break;
584                 case 'M':
585                         /* enable Manage DSA IT */
586                         manageDSAit++;
587                         break;
588                 case 'n':       /* print operations, don't actually do them */
589                         dont++;
590                         break;
591                 case 'O':
592 #ifdef HAVE_CYRUS_SASL
593                         if( sasl_secprops != NULL ) {
594                                 fprintf( stderr, "%s: -O previously specified\n", prog );
595                                 exit( EXIT_FAILURE );
596                         }
597                         if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
598                                 fprintf( stderr, "%s: incompatible previous "
599                                         "authentication choice\n", prog );
600                                 exit( EXIT_FAILURE );
601                         }
602                         authmethod = LDAP_AUTH_SASL;
603                         sasl_secprops = ber_strdup( optarg );
604 #else
605                         fprintf( stderr, "%s: not compiled with SASL support\n", prog );
606                         exit( EXIT_FAILURE );
607 #endif
608                         break;
609                 case 'p':
610                         if( ldapport ) {
611                                 fprintf( stderr, "%s: -p previously specified\n", prog );
612                                 exit( EXIT_FAILURE );
613                         }
614                         ival = strtol( optarg, &next, 10 );
615                         if ( next == NULL || next[0] != '\0' ) {
616                                 fprintf( stderr, "%s: unable to parse port number \"%s\"\n", prog, optarg );
617                                 exit( EXIT_FAILURE );
618                         }
619                         ldapport = ival;
620                         break;
621                 case 'P':
622                         ival = strtol( optarg, &next, 10 );
623                         if ( next == NULL || next[0] != '\0' ) {
624                                 fprintf( stderr, "%s: unabel to parse protocol version \"%s\"\n", prog, optarg );
625                                 exit( EXIT_FAILURE );
626                         }
627                         switch( ival ) {
628                         case 2:
629                                 if( protocol == LDAP_VERSION3 ) {
630                                         fprintf( stderr, "%s: -P 2 incompatible with version %d\n",
631                                                 prog, protocol );
632                                         exit( EXIT_FAILURE );
633                                 }
634                                 protocol = LDAP_VERSION2;
635                                 break;
636                         case 3:
637                                 if( protocol == LDAP_VERSION2 ) {
638                                         fprintf( stderr, "%s: -P 2 incompatible with version %d\n",
639                                                 prog, protocol );
640                                         exit( EXIT_FAILURE );
641                                 }
642                                 protocol = LDAP_VERSION3;
643                                 break;
644                         default:
645                                 fprintf( stderr, "%s: protocol version should be 2 or 3\n",
646                                         prog );
647                                 usage();
648                         }
649                         break;
650                 case 'Q':
651 #ifdef HAVE_CYRUS_SASL
652                         if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
653                                 fprintf( stderr, "%s: incompatible previous "
654                                         "authentication choice\n",
655                                         prog );
656                                 exit( EXIT_FAILURE );
657                         }
658                         authmethod = LDAP_AUTH_SASL;
659                         sasl_flags = LDAP_SASL_QUIET;
660                         break;
661 #else
662                         fprintf( stderr, "%s: not compiled with SASL support\n",
663                                 prog );
664                         exit( EXIT_FAILURE );
665 #endif
666                 case 'R':
667 #ifdef HAVE_CYRUS_SASL
668                         if( sasl_realm != NULL ) {
669                                 fprintf( stderr, "%s: -R previously specified\n", prog );
670                                 exit( EXIT_FAILURE );
671                         }
672                         if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
673                                 fprintf( stderr, "%s: incompatible previous "
674                                         "authentication choice\n",
675                                         prog );
676                                 exit( EXIT_FAILURE );
677                         }
678                         authmethod = LDAP_AUTH_SASL;
679                         sasl_realm = ber_strdup( optarg );
680 #else
681                         fprintf( stderr, "%s: not compiled with SASL support\n",
682                                 prog );
683                         exit( EXIT_FAILURE );
684 #endif
685                         break;
686                 case 'U':
687 #ifdef HAVE_CYRUS_SASL
688                         if( sasl_authc_id != NULL ) {
689                                 fprintf( stderr, "%s: -U previously specified\n", prog );
690                                 exit( EXIT_FAILURE );
691                         }
692                         if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
693                                 fprintf( stderr, "%s: incompatible previous "
694                                         "authentication choice\n",
695                                         prog );
696                                 exit( EXIT_FAILURE );
697                         }
698                         authmethod = LDAP_AUTH_SASL;
699                         sasl_authc_id = ber_strdup( optarg );
700 #else
701                         fprintf( stderr, "%s: not compiled with SASL support\n",
702                                 prog );
703                         exit( EXIT_FAILURE );
704 #endif
705                         break;
706                 case 'v':       /* verbose mode */
707                         verbose++;
708                         break;
709                 case 'V':       /* version */
710                         version++;
711                         break;
712                 case 'w':       /* password */
713                         passwd.bv_val = ber_strdup( optarg );
714                         {
715                                 char* p;
716
717                                 for( p = optarg; *p != '\0'; p++ ) {
718                                         *p = '\0';
719                                 }
720                         }
721                         passwd.bv_len = strlen( passwd.bv_val );
722                         break;
723                 case 'W':
724                         want_bindpw++;
725                         break;
726                 case 'y':
727                         pw_file = optarg;
728                         break;
729                 case 'Y':
730 #ifdef HAVE_CYRUS_SASL
731                         if( sasl_mech != NULL ) {
732                                 fprintf( stderr, "%s: -Y previously specified\n", prog );
733                                 exit( EXIT_FAILURE );
734                         }
735                         if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
736                                 fprintf( stderr,
737                                         "%s: incompatible with authentication choice\n", prog );
738                                 exit( EXIT_FAILURE );
739                         }
740                         authmethod = LDAP_AUTH_SASL;
741                         sasl_mech = ber_strdup( optarg );
742 #else
743                         fprintf( stderr, "%s: not compiled with SASL support\n", prog );
744                         exit( EXIT_FAILURE );
745 #endif
746                         break;
747                 case 'x':
748                         if( authmethod != -1 && authmethod != LDAP_AUTH_SIMPLE ) {
749                                 fprintf( stderr, "%s: incompatible with previous "
750                                         "authentication choice\n", prog );
751                                 exit( EXIT_FAILURE );
752                         }
753                         authmethod = LDAP_AUTH_SIMPLE;
754                         break;
755                 case 'X':
756 #ifdef HAVE_CYRUS_SASL
757                         if( sasl_authz_id != NULL ) {
758                                 fprintf( stderr, "%s: -X previously specified\n", prog );
759                                 exit( EXIT_FAILURE );
760                         }
761                         if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
762                                 fprintf( stderr, "%s: -X incompatible with "
763                                         "authentication choice\n", prog );
764                                 exit( EXIT_FAILURE );
765                         }
766                         authmethod = LDAP_AUTH_SASL;
767                         sasl_authz_id = ber_strdup( optarg );
768 #else
769                         fprintf( stderr, "%s: not compiled with SASL support\n", prog );
770                         exit( EXIT_FAILURE );
771 #endif
772                         break;
773                 case 'Z':
774 #ifdef HAVE_TLS
775                         use_tls++;
776 #else
777                         fprintf( stderr, "%s: not compiled with TLS support\n", prog );
778                         exit( EXIT_FAILURE );
779 #endif
780                         break;
781                 default:
782                         if( handle_private_option( i ) ) break;
783                         fprintf( stderr, "%s: unrecognized option -%c\n",
784                                 prog, optopt );
785                         usage();
786                 }
787         }
788
789         {
790                 /* prevent bad linking */
791                 LDAPAPIInfo api;
792                 api.ldapai_info_version = LDAP_API_INFO_VERSION;
793
794                 if ( ldap_get_option(NULL, LDAP_OPT_API_INFO, &api)
795                         != LDAP_OPT_SUCCESS )
796                 {
797                         fprintf( stderr, "%s: ldap_get_option(API_INFO) failed\n", prog );
798                         exit( EXIT_FAILURE );
799                 }
800
801                 if (api.ldapai_info_version != LDAP_API_INFO_VERSION) {
802                         fprintf( stderr, "LDAP APIInfo version mismatch: "
803                                 "library %d, header %d\n",
804                                 api.ldapai_info_version, LDAP_API_INFO_VERSION );
805                         exit( EXIT_FAILURE );
806                 }
807
808                 if( api.ldapai_api_version != LDAP_API_VERSION ) {
809                         fprintf( stderr, "LDAP API version mismatch: "
810                                 "library %d, header %d\n",
811                                 api.ldapai_api_version, LDAP_API_VERSION );
812                         exit( EXIT_FAILURE );
813                 }
814
815                 if( strcmp(api.ldapai_vendor_name, LDAP_VENDOR_NAME ) != 0 ) {
816                         fprintf( stderr, "LDAP vendor name mismatch: "
817                                 "library %s, header %s\n",
818                                 api.ldapai_vendor_name, LDAP_VENDOR_NAME );
819                         exit( EXIT_FAILURE );
820                 }
821
822                 if( api.ldapai_vendor_version != LDAP_VENDOR_VERSION ) {
823                         fprintf( stderr, "LDAP vendor version mismatch: "
824                                 "library %d, header %d\n",
825                                 api.ldapai_vendor_version, LDAP_VENDOR_VERSION );
826                         exit( EXIT_FAILURE );
827                 }
828
829                 if (version) {
830                         fprintf( stderr, "%s: %s\t(LDAP library: %s %d)\n",
831                                 prog, __Version,
832                                 LDAP_VENDOR_NAME, LDAP_VENDOR_VERSION );
833                         if (version > 1) exit( EXIT_SUCCESS );
834                 }
835
836                 ldap_memfree( api.ldapai_vendor_name );
837                 ber_memvfree( (void **)api.ldapai_extensions );
838         }
839
840         if (protocol == -1)
841                 protocol = LDAP_VERSION3;
842
843         if (authmethod == -1 && protocol > LDAP_VERSION2) {
844 #ifdef HAVE_CYRUS_SASL
845                 authmethod = LDAP_AUTH_SASL;
846 #else
847                 authmethod = LDAP_AUTH_SIMPLE;
848 #endif
849         }
850
851         if( ldapuri == NULL ) {
852                 if( ldapport && ( ldaphost == NULL )) {
853                         fprintf( stderr, "%s: -p without -h is invalid.\n", prog );
854                         exit( EXIT_FAILURE );
855                 }
856         } else {
857                 if( ldaphost != NULL ) {
858                         fprintf( stderr, "%s: -H incompatible with -h\n", prog );
859                         exit( EXIT_FAILURE );
860                 }
861                 if( ldapport ) {
862                         fprintf( stderr, "%s: -H incompatible with -p\n", prog );
863                         exit( EXIT_FAILURE );
864                 }
865         }
866
867         if( protocol == LDAP_VERSION2 ) {
868                 if( assertctl || authzid || manageDIT || manageDSAit ||
869 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
870                         proxydn ||
871 #endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
872 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
873                         chaining ||
874 #endif
875                         noop || ppolicy || preread || postread )
876                 {
877                         fprintf( stderr, "%s: -e/-M incompatible with LDAPv2\n", prog );
878                         exit( EXIT_FAILURE );
879                 }
880 #ifdef HAVE_TLS
881                 if( use_tls ) {
882                         fprintf( stderr, "%s: -Z incompatible with LDAPv2\n", prog );
883                         exit( EXIT_FAILURE );
884                 }
885 #endif
886 #ifdef HAVE_CYRUS_SASL
887                 if( authmethod == LDAP_AUTH_SASL ) {
888                         fprintf( stderr, "%s: -[IOQRUXY] incompatible with LDAPv2\n",
889                                 prog );
890                         exit( EXIT_FAILURE );
891                 }
892 #endif
893
894 #ifdef LDAP_API_FEATURE_X_OPENLDAP_V2_KBIND
895         } else {
896                 if ( authmethod == LDAP_AUTH_KRBV4 || authmethod == LDAP_AUTH_KRBV41 ) {
897                         fprintf( stderr, "%s: -k/-K incompatible with LDAPv%d\n",
898                                 prog, protocol );
899                         exit( EXIT_FAILURE );
900                 }
901 #endif
902         }
903 }
904
905
906 LDAP *
907 tool_conn_setup( int dont, void (*private_setup)( LDAP * ) )
908 {
909         LDAP *ld = NULL;
910
911         if ( debug ) {
912                 if( ber_set_option( NULL, LBER_OPT_DEBUG_LEVEL, &debug )
913                         != LBER_OPT_SUCCESS )
914                 {
915                         fprintf( stderr,
916                                 "Could not set LBER_OPT_DEBUG_LEVEL %d\n", debug );
917                 }
918                 if( ldap_set_option( NULL, LDAP_OPT_DEBUG_LEVEL, &debug )
919                         != LDAP_OPT_SUCCESS )
920                 {
921                         fprintf( stderr,
922                                 "Could not set LDAP_OPT_DEBUG_LEVEL %d\n", debug );
923                 }
924         }
925
926 #ifdef SIGPIPE
927         (void) SIGNAL( SIGPIPE, SIG_IGN );
928 #endif
929
930         if ( abcan ) {
931                 SIGNAL( SIGINT, do_sig );
932         }
933
934         if ( !dont ) {
935                 int rc;
936
937                 if( ( ldaphost != NULL || ldapport ) && ( ldapuri == NULL ) ) {
938                         /* construct URL */
939                         LDAPURLDesc url;
940                         memset( &url, 0, sizeof(url));
941
942                         url.lud_scheme = "ldap";
943                         url.lud_host = ldaphost;
944                         url.lud_port = ldapport;
945                         url.lud_scope = LDAP_SCOPE_DEFAULT;
946
947                         ldapuri = ldap_url_desc2str( &url );
948                 }
949
950                 if ( verbose ) {
951                         fprintf( stderr, "ldap_initialize( %s )\n",
952                                 ldapuri != NULL ? ldapuri : "<DEFAULT>" );
953                 }
954                 rc = ldap_initialize( &ld, ldapuri );
955                 if( rc != LDAP_SUCCESS ) {
956                         fprintf( stderr,
957                                 "Could not create LDAP session handle for URI=%s (%d): %s\n",
958                                 ldapuri, rc, ldap_err2string(rc) );
959                         exit( EXIT_FAILURE );
960                 }
961
962                 if( private_setup ) private_setup( ld );
963
964                 /* referrals */
965                 if( ldap_set_option( ld, LDAP_OPT_REFERRALS,
966                         referrals ? LDAP_OPT_ON : LDAP_OPT_OFF ) != LDAP_OPT_SUCCESS )
967                 {
968                         fprintf( stderr, "Could not set LDAP_OPT_REFERRALS %s\n",
969                                 referrals ? "on" : "off" );
970                         exit( EXIT_FAILURE );
971                 }
972
973                 if( ldap_set_option( ld, LDAP_OPT_PROTOCOL_VERSION, &protocol )
974                         != LDAP_OPT_SUCCESS )
975                 {
976                         fprintf( stderr, "Could not set LDAP_OPT_PROTOCOL_VERSION %d\n",
977                                 protocol );
978                         exit( EXIT_FAILURE );
979                 }
980
981                 if ( use_tls ) {
982                         rc = ldap_start_tls_s( ld, NULL, NULL );
983                         if ( rc != LDAP_SUCCESS ) {
984                                 tool_perror( "ldap_start_tls", rc, NULL, NULL, NULL, NULL );
985                                 if ( use_tls > 1 ) {
986                                         exit( EXIT_FAILURE );
987                                 }
988                         }
989                 }
990         }
991
992         return ld;
993 }
994
995
996 void
997 tool_bind( LDAP *ld )
998 {
999         LDAPControl     **sctrlsp = NULL;
1000         LDAPControl     *sctrls[2];
1001         int             nsctrls = 0;
1002
1003 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
1004         LDAPControl c;
1005         if ( ppolicy ) {
1006                 c.ldctl_oid = LDAP_CONTROL_PASSWORDPOLICYREQUEST;
1007                 c.ldctl_value.bv_val = NULL;
1008                 c.ldctl_value.bv_len = 0;
1009                 c.ldctl_iscritical = 0;
1010                 sctrls[nsctrls] = &c;
1011                 sctrls[++nsctrls] = NULL;
1012         }
1013 #endif
1014
1015         if ( nsctrls ) {
1016                 sctrlsp = sctrls;
1017         }
1018
1019         assert( nsctrls < sizeof(sctrls)/sizeof(sctrls[0]) );
1020
1021         if ( authmethod == LDAP_AUTH_SASL ) {
1022 #ifdef HAVE_CYRUS_SASL
1023                 void *defaults;
1024                 int rc;
1025
1026                 if( sasl_secprops != NULL ) {
1027                         rc = ldap_set_option( ld, LDAP_OPT_X_SASL_SECPROPS,
1028                                 (void *) sasl_secprops );
1029
1030                         if( rc != LDAP_OPT_SUCCESS ) {
1031                                 fprintf( stderr,
1032                                         "Could not set LDAP_OPT_X_SASL_SECPROPS: %s\n",
1033                                         sasl_secprops );
1034                                 exit( LDAP_LOCAL_ERROR );
1035                         }
1036                 }
1037
1038                 defaults = lutil_sasl_defaults( ld,
1039                         sasl_mech,
1040                         sasl_realm,
1041                         sasl_authc_id,
1042                         passwd.bv_val,
1043                         sasl_authz_id );
1044
1045                 rc = ldap_sasl_interactive_bind_s( ld, binddn, sasl_mech,
1046                         sctrlsp,
1047                         NULL, sasl_flags, lutil_sasl_interact, defaults );
1048
1049                 lutil_sasl_freedefs( defaults );
1050                 if( rc != LDAP_SUCCESS ) {
1051                         tool_perror( "ldap_sasl_interactive_bind_s",
1052                                 rc, NULL, NULL, NULL, NULL );
1053                         exit( rc );
1054                 }
1055 #else
1056                 fprintf( stderr, "%s: not compiled with SASL support\n", prog );
1057                 exit( LDAP_NOT_SUPPORTED );
1058 #endif
1059         } else {
1060                 int msgid, err, rc;
1061                 LDAPMessage *result;
1062                 LDAPControl **ctrls;
1063                 char msgbuf[256];
1064                 char *matched = NULL;
1065                 char *info = NULL;
1066                 char **refs = NULL;
1067
1068                 msgbuf[0] = 0;
1069
1070 #ifdef LDAP_API_FEATURE_X_OPENLDAP_V2_KBIND
1071                 if ( authmethod == LDAP_AUTH_KRBV4 || authmethod == LDAP_AUTH_KRBV41 ) {
1072                         msgid = ldap_bind( ld, binddn, passwd.bv_val, authmethod );
1073                         if ( msgid == -1 ) {
1074                                 tool_perror( "ldap_bind", -1, NULL, NULL, NULL, NULL );
1075                                 exit( LDAP_LOCAL_ERROR );
1076                         }
1077                 } else
1078 #endif
1079                 {
1080                         /* simple bind */
1081                         rc = ldap_sasl_bind( ld, binddn, LDAP_SASL_SIMPLE, &passwd,
1082                                 sctrlsp,
1083                                 NULL, &msgid );
1084                         if ( msgid == -1 ) {
1085                                 tool_perror( "ldap_sasl_bind(SIMPLE)", rc,
1086                                         NULL, NULL, NULL, NULL );
1087                                 exit( rc );
1088                         }
1089                 }
1090
1091                 if ( ldap_result( ld, msgid, LDAP_MSG_ALL, NULL, &result ) == -1 ) {
1092                         tool_perror( "ldap_result", -1, NULL, NULL, NULL, NULL );
1093                         exit( LDAP_LOCAL_ERROR );
1094                 }
1095
1096                 rc = ldap_parse_result( ld, result, &err, &matched, &info, &refs,
1097                         &ctrls, 1 );
1098                 if ( rc != LDAP_SUCCESS ) {
1099                         tool_perror( "ldap_bind parse result", rc, NULL, NULL, NULL, NULL );
1100                         exit( LDAP_LOCAL_ERROR );
1101                 }
1102
1103 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
1104                 if ( ctrls && ppolicy ) {
1105                         LDAPControl *ctrl;
1106                         int expire, grace, len = 0;
1107                         LDAPPasswordPolicyError pErr = -1;
1108                         
1109                         ctrl = ldap_find_control( LDAP_CONTROL_PASSWORDPOLICYRESPONSE,
1110                                 ctrls );
1111
1112                         if ( ctrl && ldap_parse_passwordpolicy_control( ld, ctrl,
1113                                 &expire, &grace, &pErr ) == LDAP_SUCCESS )
1114                         {
1115                                 if ( pErr != PP_noError ){
1116                                         msgbuf[0] = ';';
1117                                         msgbuf[1] = ' ';
1118                                         strcpy( msgbuf+2, ldap_passwordpolicy_err2txt( pErr ));
1119                                         len = strlen( msgbuf );
1120                                 }
1121                                 if ( expire >= 0 ) {
1122                                         sprintf( msgbuf+len,
1123                                                 " (Password expires in %d seconds)",
1124                                                 expire );
1125                                 } else if ( grace >= 0 ) {
1126                                         sprintf( msgbuf+len,
1127                                                 " (Password expired, %d grace logins remain)",
1128                                                 grace );
1129                                 }
1130                         }
1131                 }
1132 #endif
1133
1134                 if ( ctrls ) {
1135                         ldap_controls_free( ctrls );
1136                 }
1137
1138                 if ( err != LDAP_SUCCESS
1139                         || msgbuf[0]
1140                         || ( matched && matched[ 0 ] )
1141                         || ( info && info[ 0 ] )
1142                         || refs )
1143                 {
1144                         tool_perror( "ldap_bind", err, msgbuf, matched, info, refs );
1145
1146                         if( matched ) ber_memfree( matched );
1147                         if( info ) ber_memfree( info );
1148                         if( refs ) ber_memvfree( (void **)refs );
1149
1150                         if ( err != LDAP_SUCCESS ) exit( err );
1151                 }
1152         }
1153 }
1154
1155 void
1156 tool_unbind( LDAP *ld )
1157 {
1158         int err = ldap_set_option( ld, LDAP_OPT_SERVER_CONTROLS, NULL );
1159
1160         if ( err != LDAP_OPT_SUCCESS ) {
1161                 fprintf( stderr, "Could not unset controls\n");
1162         }
1163
1164         (void) ldap_unbind_ext( ld, NULL, NULL );
1165 }
1166
1167
1168 /* Set server controls.  Add controls extra_c[0..count-1], if set. */
1169 void
1170 tool_server_controls( LDAP *ld, LDAPControl *extra_c, int count )
1171 {
1172         int i = 0, j, crit = 0, err;
1173         LDAPControl c[10], **ctrls;
1174
1175         if ( ! ( assertctl
1176                 || authzid
1177 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
1178                 || proxydn
1179 #endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
1180                 || manageDIT
1181                 || manageDSAit
1182                 || noop
1183                 || preread
1184                 || postread
1185 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
1186                 || chaining
1187 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
1188                 || count ) )
1189         {
1190                 return;
1191         }
1192
1193         ctrls = (LDAPControl**) malloc(sizeof(c) + (count+1)*sizeof(LDAPControl*));
1194         if ( ctrls == NULL ) {
1195                 fprintf( stderr, "No memory\n" );
1196                 exit( EXIT_FAILURE );
1197         }
1198
1199         if ( assertctl ) {
1200                 BerElementBuffer berbuf;
1201                 BerElement *ber = (BerElement *)&berbuf;
1202                 
1203                 if( assertion == NULL || *assertion == '\0' ) {
1204                         fprintf( stderr, "Assertion=<empty>\n" );
1205                         exit( EXIT_FAILURE );
1206                 }
1207
1208                 ber_init2( ber, NULL, LBER_USE_DER );
1209
1210                 err = ldap_pvt_put_filter( ber, assertion );
1211                 if( err < 0 ) {
1212                         fprintf( stderr, "assertion encode failed (%d)\n", err );
1213                         exit( EXIT_FAILURE );
1214                 }
1215
1216                 err = ber_flatten2( ber, &c[i].ldctl_value, 0 );
1217                 if( err < 0 ) {
1218                         fprintf( stderr, "assertion flatten failed (%d)\n", err );
1219                         exit( EXIT_FAILURE );
1220                 }
1221
1222                 c[i].ldctl_oid = LDAP_CONTROL_ASSERT;
1223                 c[i].ldctl_iscritical = assertctl > 1;
1224                 ctrls[i] = &c[i];
1225                 i++;
1226         }
1227
1228         if ( authzid ) {
1229                 c[i].ldctl_value.bv_val = authzid;
1230                 c[i].ldctl_value.bv_len = strlen( authzid );
1231                 c[i].ldctl_oid = LDAP_CONTROL_PROXY_AUTHZ;
1232                 c[i].ldctl_iscritical = 1;
1233                 ctrls[i] = &c[i];
1234                 i++;
1235         }
1236
1237 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
1238         /* NOTE: doesn't need an extra count because it's incompatible
1239          * with authzid */
1240         if ( proxydn ) {
1241                 BerElementBuffer berbuf;
1242                 BerElement *ber = (BerElement *)&berbuf;
1243                 
1244                 ber_init2( ber, NULL, LBER_USE_DER );
1245
1246                 if ( ber_printf( ber, "s", proxydn ) == LBER_ERROR ) {
1247                         exit( EXIT_FAILURE );
1248                 }
1249
1250                 if ( ber_flatten2( ber, &c[i].ldctl_value, 0 ) == -1 ) {
1251                         exit( EXIT_FAILURE );
1252                 }
1253
1254                 c[i].ldctl_oid = LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ;
1255                 c[i].ldctl_iscritical = 1;
1256                 ctrls[i] = &c[i];
1257                 i++;
1258         }
1259 #endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
1260
1261         if ( manageDIT ) {
1262                 c[i].ldctl_oid = LDAP_CONTROL_MANAGEDIT;
1263                 BER_BVZERO( &c[i].ldctl_value );
1264                 c[i].ldctl_iscritical = manageDIT > 1;
1265                 ctrls[i] = &c[i];
1266                 i++;
1267         }
1268
1269         if ( manageDSAit ) {
1270                 c[i].ldctl_oid = LDAP_CONTROL_MANAGEDSAIT;
1271                 BER_BVZERO( &c[i].ldctl_value );
1272                 c[i].ldctl_iscritical = manageDSAit > 1;
1273                 ctrls[i] = &c[i];
1274                 i++;
1275         }
1276
1277         if ( noop ) {
1278                 c[i].ldctl_oid = LDAP_CONTROL_NOOP;
1279                 BER_BVZERO( &c[i].ldctl_value );
1280                 c[i].ldctl_iscritical = noop > 1;
1281                 ctrls[i] = &c[i];
1282                 i++;
1283         }
1284
1285         if ( preread ) {
1286                 char berbuf[LBER_ELEMENT_SIZEOF];
1287                 BerElement *ber = (BerElement *)berbuf;
1288                 char **attrs = NULL;
1289
1290                 if( preread_attrs ) {
1291                         attrs = ldap_str2charray( preread_attrs, "," );
1292                 }
1293
1294                 ber_init2( ber, NULL, LBER_USE_DER );
1295
1296                 if( ber_printf( ber, "{v}", attrs ) == -1 ) {
1297                         fprintf( stderr, "preread attrs encode failed.\n" );
1298                         exit( EXIT_FAILURE );
1299                 }
1300
1301                 err = ber_flatten2( ber, &c[i].ldctl_value, 0 );
1302                 if( err < 0 ) {
1303                         fprintf( stderr, "preread flatten failed (%d)\n", err );
1304                         exit( EXIT_FAILURE );
1305                 }
1306
1307                 c[i].ldctl_oid = LDAP_CONTROL_PRE_READ;
1308                 c[i].ldctl_iscritical = preread > 1;
1309                 ctrls[i] = &c[i];
1310                 i++;
1311
1312                 if( attrs ) ldap_charray_free( attrs );
1313         }
1314
1315         if ( postread ) {
1316                 char berbuf[LBER_ELEMENT_SIZEOF];
1317                 BerElement *ber = (BerElement *)berbuf;
1318                 char **attrs = NULL;
1319
1320                 if( postread_attrs ) {
1321                         attrs = ldap_str2charray( postread_attrs, "," );
1322                 }
1323
1324                 ber_init2( ber, NULL, LBER_USE_DER );
1325
1326                 if( ber_printf( ber, "{v}", attrs ) == -1 ) {
1327                         fprintf( stderr, "postread attrs encode failed.\n" );
1328                         exit( EXIT_FAILURE );
1329                 }
1330
1331                 err = ber_flatten2( ber, &c[i].ldctl_value, 0 );
1332                 if( err < 0 ) {
1333                         fprintf( stderr, "postread flatten failed (%d)\n", err );
1334                         exit( EXIT_FAILURE );
1335                 }
1336
1337                 c[i].ldctl_oid = LDAP_CONTROL_POST_READ;
1338                 c[i].ldctl_iscritical = postread > 1;
1339                 ctrls[i] = &c[i];
1340                 i++;
1341
1342                 if( attrs ) ldap_charray_free( attrs );
1343         }
1344
1345 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
1346         if ( chaining ) {
1347                 if ( chainingResolve > -1 ) {
1348                         BerElementBuffer berbuf;
1349                         BerElement *ber = (BerElement *)&berbuf;
1350
1351                         ber_init2( ber, NULL, LBER_USE_DER );
1352
1353                         err = ber_printf( ber, "{e" /* } */, chainingResolve );
1354                         if ( err == -1 ) {
1355                                 ber_free( ber, 1 );
1356                                 fprintf( stderr, _("Chaining behavior control encoding error!\n") );
1357                                 exit( EXIT_FAILURE );
1358                         }
1359
1360                         if ( chainingContinuation > -1 ) {
1361                                 err = ber_printf( ber, "e", chainingContinuation );
1362                                 if ( err == -1 ) {
1363                                         ber_free( ber, 1 );
1364                                         fprintf( stderr, _("Chaining behavior control encoding error!\n") );
1365                                         exit( EXIT_FAILURE );
1366                                 }
1367                         }
1368
1369                         err = ber_printf( ber, /* { */ "N}" );
1370                         if ( err == -1 ) {
1371                                 ber_free( ber, 1 );
1372                                 fprintf( stderr, _("Chaining behavior control encoding error!\n") );
1373                                 exit( EXIT_FAILURE );
1374                         }
1375
1376                         if ( ber_flatten2( ber, &c[i].ldctl_value, 0 ) == -1 ) {
1377                                 exit( EXIT_FAILURE );
1378                         }
1379
1380                 } else {
1381                         BER_BVZERO( &c[i].ldctl_value );
1382                 }
1383
1384                 c[i].ldctl_oid = LDAP_CONTROL_X_CHAINING_BEHAVIOR;
1385                 c[i].ldctl_iscritical = chaining > 1;
1386                 ctrls[i] = &c[i];
1387                 i++;
1388         }
1389 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
1390
1391         while ( count-- ) {
1392                 ctrls[i++] = extra_c++;
1393         }
1394         ctrls[i] = NULL;
1395
1396         err = ldap_set_option( ld, LDAP_OPT_SERVER_CONTROLS, ctrls );
1397
1398         if ( err != LDAP_OPT_SUCCESS ) {
1399                 for ( j = 0; j < i; j++ ) {
1400                         if ( ctrls[j]->ldctl_iscritical ) crit = 1;
1401                 }
1402                 fprintf( stderr, "Could not set %scontrols\n",
1403                         crit ? "critical " : "" );
1404         }
1405
1406         free( ctrls );
1407         if ( crit ) {
1408                 exit( EXIT_FAILURE );
1409         }
1410 }
1411
1412 int
1413 tool_check_abandon( LDAP *ld, int msgid )
1414 {
1415         int     rc;
1416
1417         switch ( gotintr ) {
1418         case LDAP_REQ_EXTENDED:
1419                 rc = ldap_cancel_s( ld, msgid, NULL, NULL );
1420                 fprintf( stderr, "got interrupt, cancel got %d: %s\n",
1421                                 rc, ldap_err2string( rc ) );
1422                 return -1;
1423
1424         case LDAP_REQ_ABANDON:
1425                 rc = ldap_abandon_ext( ld, msgid, NULL, NULL );
1426                 fprintf( stderr, "got interrupt, abandon got %d: %s\n",
1427                                 rc, ldap_err2string( rc ) );
1428                 return -1;
1429         }
1430
1431         return 0;
1432 }
1433
1434 static int
1435 print_prepostread( LDAP *ld, LDAPControl *ctrl, struct berval *what)
1436 {
1437         BerElement      *ber;
1438         struct berval   bv;
1439
1440         tool_write_ldif( LDIF_PUT_COMMENT, "==> ",
1441                 what->bv_val, what->bv_len );
1442         ber = ber_init( &ctrl->ldctl_value );
1443         if ( ber == NULL ) {
1444                 /* error? */
1445                 return 1;
1446
1447         } else if ( ber_scanf( ber, "{m{" /*}}*/, &bv ) == LBER_ERROR ) {
1448                 /* error? */
1449                 return 1;
1450
1451         } else {
1452                 tool_write_ldif( LDIF_PUT_VALUE, "dn", bv.bv_val, bv.bv_len );
1453
1454                 while ( ber_scanf( ber, "{m" /*}*/, &bv ) != LBER_ERROR ) {
1455                         int             i;
1456                         BerVarray       vals = NULL;
1457
1458                         if ( ber_scanf( ber, "[W]", &vals ) == LBER_ERROR ||
1459                                 vals == NULL )
1460                         {
1461                                 /* error? */
1462                                 return 1;
1463                         }
1464                 
1465                         for ( i = 0; vals[ i ].bv_val != NULL; i++ ) {
1466                                 tool_write_ldif(
1467                                         ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1468                                         bv.bv_val, vals[ i ].bv_val, vals[ i ].bv_len );
1469                         }
1470
1471                         ber_bvarray_free( vals );
1472                 }
1473         }
1474
1475         if ( ber != NULL ) {
1476                 ber_free( ber, 1 );
1477         }
1478
1479         tool_write_ldif( LDIF_PUT_COMMENT, "<== ",
1480                 what->bv_val, what->bv_len );
1481
1482         return 0;
1483 }
1484
1485 static int
1486 print_preread( LDAP *ld, LDAPControl *ctrl )
1487 {
1488         static struct berval what = BER_BVC( "preread" );
1489
1490         return print_prepostread( ld, ctrl, &what );
1491 }
1492
1493 static int
1494 print_postread( LDAP *ld, LDAPControl *ctrl )
1495 {
1496         static struct berval what = BER_BVC( "postread" );
1497
1498         return print_prepostread( ld, ctrl, &what );
1499 }
1500
1501 static int
1502 print_paged_results( LDAP *ld, LDAPControl *ctrl )
1503 {
1504         ber_int_t estimate;
1505
1506         /* note: pr_cookie is being malloced; it's freed
1507          * the next time the control is sent, but the last
1508          * time it's not; we don't care too much, because
1509          * the last time an empty value is returned... */
1510         if ( ldap_parse_pageresponse_control( ld, ctrl, &estimate, &pr_cookie )
1511                 != LDAP_SUCCESS )
1512         {
1513                 /* error? */
1514                 return 1;
1515
1516         } else {
1517                 /* FIXME: check buffer overflow */
1518                 char    buf[ BUFSIZ ], *ptr = buf;
1519
1520                 if ( estimate > 0 ) {
1521                         ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
1522                                 "estimate=%d", estimate );
1523                 }
1524
1525                 if ( pr_cookie.bv_len > 0 ) {
1526                         struct berval   bv;
1527
1528                         bv.bv_len = LUTIL_BASE64_ENCODE_LEN(
1529                                 pr_cookie.bv_len ) + 1;
1530                         bv.bv_val = ber_memalloc( bv.bv_len + 1 );
1531
1532                         bv.bv_len = lutil_b64_ntop(
1533                                 (unsigned char *) pr_cookie.bv_val,
1534                                 pr_cookie.bv_len,
1535                                 bv.bv_val, bv.bv_len );
1536
1537                         ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
1538                                 "%scookie=%s", ptr == buf ? "" : " ",
1539                                 bv.bv_val );
1540
1541                         ber_memfree( bv.bv_val );
1542
1543                         pr_morePagedResults = 1;
1544
1545                 } else {
1546                         ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
1547                                 "%scookie=", ptr == buf ? "" : " " );
1548                 }
1549
1550                 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1551                         "pagedresults", buf, ptr - buf );
1552         }
1553
1554         return 0;
1555 }
1556
1557 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
1558 static int
1559 print_ppolicy( LDAP *ld, LDAPControl *ctrl )
1560 {
1561         int expire = 0, grace = 0, rc;
1562         LDAPPasswordPolicyError pperr;
1563
1564         rc = ldap_parse_passwordpolicy_control( ld, ctrl,
1565                 &expire, &grace, &pperr );
1566         if ( rc == LDAP_SUCCESS ) {
1567                 char    buf[ BUFSIZ ], *ptr = buf;
1568
1569                 if ( expire != -1 ) {
1570                         ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
1571                                 "expire=%d", expire );
1572                 }
1573
1574                 if ( grace != -1 ) {
1575                         ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
1576                                 "%sgrace=%d", ptr == buf ? "" : " ", grace );
1577                 }
1578
1579                 if ( pperr != PP_noError ) {
1580                         ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
1581                                 "%serror=%s", ptr == buf ? "" : " ",
1582                                 ldap_passwordpolicy_err2txt( pperr ) );
1583                 }
1584
1585                 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1586                         "ppolicy", buf, ptr - buf );
1587         }
1588
1589         return rc;
1590 }
1591 #endif
1592
1593 void tool_print_ctrls(
1594         LDAP            *ld,
1595         LDAPControl     **ctrls )
1596 {
1597         int     i;
1598         char    *ptr;
1599
1600         for ( i = 0; ctrls[i] != NULL; i++ ) {
1601                 /* control: OID criticality base64value */
1602                 struct berval b64 = BER_BVNULL;
1603                 ber_len_t len;
1604                 char *str;
1605                 int j;
1606
1607                 len = ldif ? 2 : 0;
1608                 len += strlen( ctrls[i]->ldctl_oid );
1609
1610                 /* add enough for space after OID and the critical value itself */
1611                 len += ctrls[i]->ldctl_iscritical
1612                         ? sizeof("true") : sizeof("false");
1613
1614                 /* convert to base64 */
1615                 if ( ctrls[i]->ldctl_value.bv_len ) {
1616                         b64.bv_len = LUTIL_BASE64_ENCODE_LEN(
1617                                 ctrls[i]->ldctl_value.bv_len ) + 1;
1618                         b64.bv_val = ber_memalloc( b64.bv_len + 1 );
1619
1620                         b64.bv_len = lutil_b64_ntop(
1621                                 (unsigned char *) ctrls[i]->ldctl_value.bv_val,
1622                                 ctrls[i]->ldctl_value.bv_len,
1623                                 b64.bv_val, b64.bv_len );
1624                 }
1625
1626                 if ( b64.bv_len ) {
1627                         len += 1 + b64.bv_len;
1628                 }
1629
1630                 ptr = str = malloc( len + 1 );
1631                 if ( ldif ) {
1632                         ptr = lutil_strcopy( ptr, ": " );
1633                 }
1634                 ptr = lutil_strcopy( ptr, ctrls[i]->ldctl_oid );
1635                 ptr = lutil_strcopy( ptr, ctrls[i]->ldctl_iscritical
1636                         ? " true" : " false" );
1637
1638                 if ( b64.bv_len ) {
1639                         ptr = lutil_strcopy( ptr, " " );
1640                         ptr = lutil_strcopy( ptr, b64.bv_val );
1641                 }
1642
1643                 if ( ldif < 2 ) {
1644                         tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1645                                 "control", str, len );
1646                 }
1647
1648                 free( str );
1649                 if ( b64.bv_len ) {
1650                         ber_memfree( b64.bv_val );
1651                 }
1652
1653                 /* known controls */
1654                 for ( j = 0; tool_ctrl_response[j].oid != NULL; j++ ) {
1655                         if ( strcmp( tool_ctrl_response[j].oid, ctrls[i]->ldctl_oid ) == 0 ) {
1656                                 if ( !tool_ctrl_response[j].mask & tool_type ) {
1657                                         /* this control should not appear
1658                                          * with this tool; warning? */
1659                                 }
1660                                 break;
1661                         }
1662                 }
1663
1664                 if ( tool_ctrl_response[j].oid != NULL && tool_ctrl_response[j].func ) {
1665                         (void)tool_ctrl_response[j].func( ld, ctrls[i] );
1666                 }
1667         }
1668 }
1669
1670 int
1671 tool_write_ldif( int type, char *name, char *value, ber_len_t vallen )
1672 {
1673         char    *ldif;
1674
1675         if (( ldif = ldif_put( type, name, value, vallen )) == NULL ) {
1676                 return( -1 );
1677         }
1678
1679         fputs( ldif, stdout );
1680         ber_memfree( ldif );
1681
1682         return( 0 );
1683 }
1684
1685 int
1686 tool_is_oid( const char *s )
1687 {
1688         int             first = 1;
1689
1690         if ( !isdigit( (unsigned char) s[ 0 ] ) ) {
1691                 return 0;
1692         }
1693
1694         for ( ; s[ 0 ]; s++ ) {
1695                 if ( s[ 0 ] == '.' ) {
1696                         if ( s[ 1 ] == '\0' ) {
1697                                 return 0;
1698                         }
1699                         first = 1;
1700                         continue;
1701                 }
1702
1703                 if ( !isdigit( (unsigned char) s[ 0 ] ) ) {
1704                         return 0;
1705                 }
1706
1707                 if ( first == 1 && s[ 0 ] == '0' && s[ 1 ] != '.' ) {
1708                         return 0;
1709                 }
1710                 first = 0;
1711         }
1712
1713         return 1;
1714 }
1715