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