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