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