1 /* common.c - common routines for the ldap client tools */
3 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
5 * Copyright 1998-2011 The OpenLDAP Foundation.
6 * Portions Copyright 2003 Kurt D. Zeilenga.
7 * Portions Copyright 2003 IBM Corporation.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted only as authorized by the OpenLDAP
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>.
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)
29 #include <ac/stdlib.h>
30 #include <ac/signal.h>
31 #include <ac/string.h>
33 #include <ac/unistd.h>
36 #include <ac/socket.h>
38 #ifdef HAVE_CYRUS_SASL
39 #ifdef HAVE_SASL_SASL_H
40 #include <sasl/sasl.h>
50 #include "lutil_ldap.h"
51 #include "ldap_defaults.h"
57 /* input-related vars */
59 /* misc. parameters */
60 tool_type_t tool_type;
69 ber_len_t ldif_wrap = LDIF_LINE_WIDTH;
74 char *ldaphost = NULL;
84 struct berval passwd = { 0, NULL };
86 #ifdef HAVE_CYRUS_SASL
87 unsigned sasl_flags = LDAP_SASL_AUTOMATIC;
88 char *sasl_realm = NULL;
89 char *sasl_authc_id = NULL;
90 char *sasl_authz_id = NULL;
91 char *sasl_mech = NULL;
92 char *sasl_secprops = NULL;
97 char *assertion = NULL;
98 struct berval assertionvalue = BER_BVNULL;
100 /* support deprecated early version of proxyAuthz */
101 #define LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ "2.16.840.1.113730.3.4.12"
102 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
103 char *proxydn = NULL;
104 #endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
110 static char *preread_attrs = NULL;
112 static char *postread_attrs = NULL;
113 ber_int_t pr_morePagedResults = 1;
114 struct berval pr_cookie = { 0, NULL };
115 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
117 static int chainingResolve = -1;
118 static int chainingContinuation = -1;
119 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
120 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
121 static int sessionTracking = 0;
122 struct berval stValue;
123 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
126 struct berval *vlvContext;
128 LDAPControl *unknown_ctrls = NULL;
129 int unknown_ctrls_num = 0;
132 struct timeval nettimeout = { -1 , 0 };
134 typedef int (*print_ctrl_fn)( LDAP *ld, LDAPControl *ctrl );
136 static int print_preread( LDAP *ld, LDAPControl *ctrl );
137 static int print_postread( LDAP *ld, LDAPControl *ctrl );
138 static int print_paged_results( LDAP *ld, LDAPControl *ctrl );
139 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
140 static int print_ppolicy( LDAP *ld, LDAPControl *ctrl );
142 static int print_sss( LDAP *ld, LDAPControl *ctrl );
143 static int print_vlv( LDAP *ld, LDAPControl *ctrl );
144 #ifdef LDAP_CONTROL_X_DEREF
145 static int print_deref( LDAP *ld, LDAPControl *ctrl );
147 #ifdef LDAP_CONTROL_X_WHATFAILED
148 static int print_whatfailed( LDAP *ld, LDAPControl *ctrl );
151 static struct tool_ctrls_t {
155 } tool_ctrl_response[] = {
156 { LDAP_CONTROL_PRE_READ, TOOL_ALL, print_preread },
157 { LDAP_CONTROL_POST_READ, TOOL_ALL, print_postread },
158 { LDAP_CONTROL_PAGEDRESULTS, TOOL_SEARCH, print_paged_results },
159 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
160 { LDAP_CONTROL_PASSWORDPOLICYRESPONSE, TOOL_ALL, print_ppolicy },
162 { LDAP_CONTROL_SORTRESPONSE, TOOL_SEARCH, print_sss },
163 { LDAP_CONTROL_VLVRESPONSE, TOOL_SEARCH, print_vlv },
164 #ifdef LDAP_CONTROL_X_DEREF
165 { LDAP_CONTROL_X_DEREF, TOOL_SEARCH, print_deref },
167 #ifdef LDAP_CONTROL_X_WHATFAILED
168 { LDAP_CONTROL_X_WHATFAILED, TOOL_ALL, print_whatfailed },
174 enum { Intr_None = 0, Intr_Abandon, Intr_Cancel, Intr_Ignore };
175 static volatile sig_atomic_t gotintr, abcan;
178 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
180 st_value( LDAP *ld, struct berval *value )
182 char *ip = NULL, *name = NULL;
183 struct berval id = { 0 };
184 char namebuf[ MAXHOSTNAMELEN ];
186 if ( gethostname( namebuf, sizeof( namebuf ) ) == 0 ) {
192 h = gethostbyname( name );
194 AC_MEMCPY( &addr, h->h_addr, sizeof( addr ) );
195 ip = inet_ntoa( addr );
199 #ifdef HAVE_CYRUS_SASL
200 if ( sasl_authz_id != NULL ) {
201 ber_str2bv( sasl_authz_id, 0, 0, &id );
203 } else if ( sasl_authc_id != NULL ) {
204 ber_str2bv( sasl_authc_id, 0, 0, &id );
207 #endif /* HAVE_CYRUS_SASL */
208 if ( binddn != NULL ) {
209 ber_str2bv( binddn, 0, 0, &id );
212 if ( ldap_create_session_tracking_value( ld,
213 ip, name, LDAP_CONTROL_X_SESSION_TRACKING_USERNAME,
216 fprintf( stderr, _("Session tracking control encoding error!\n") );
222 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
231 tool_init( tool_type_t type )
234 ldap_pvt_setlocale(LC_MESSAGES, "");
235 ldap_pvt_bindtextdomain(OPENLDAP_PACKAGE, LDAP_LOCALEDIR);
236 ldap_pvt_textdomain(OPENLDAP_PACKAGE);
242 #ifdef HAVE_CYRUS_SASL
246 ldap_pvt_tls_destroy();
249 if ( ldapuri != NULL ) {
250 ber_memfree( ldapuri );
254 if ( pr_cookie.bv_val != NULL ) {
255 ber_memfree( pr_cookie.bv_val );
256 BER_BVZERO( &pr_cookie );
259 if ( binddn != NULL ) {
260 ber_memfree( binddn );
264 if ( passwd.bv_val != NULL ) {
265 ber_memfree( passwd.bv_val );
266 BER_BVZERO( &passwd );
269 if ( infile != NULL ) {
270 ber_memfree( infile );
275 ber_memfree( assertion );
280 ber_memfree( authzid );
285 ber_memfree( proxydn );
289 if ( preread_attrs ) {
290 ber_memfree( preread_attrs );
291 preread_attrs = NULL;
294 if ( postread_attrs ) {
295 ber_memfree( postread_attrs );
296 postread_attrs = NULL;
301 tool_common_usage( void )
303 static const char *const descriptions[] = {
304 N_(" -d level set LDAP debugging level to `level'\n"),
305 N_(" -D binddn bind DN\n"),
306 N_(" -e [!]<ext>[=<extparam>] general extensions (! indicates criticality)\n")
307 N_(" [!]assert=<filter> (RFC 4528; a RFC 4515 Filter string)\n")
308 N_(" [!]authzid=<authzid> (RFC 4370; \"dn:<dn>\" or \"u:<user>\")\n")
309 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
311 /* non-advertized support for proxyDN */
312 N_(" [!]proxydn=<dn> (a RFC 4514 DN string)\n")
315 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
316 N_(" [!]chaining[=<resolveBehavior>[/<continuationBehavior>]]\n")
317 N_(" one of \"chainingPreferred\", \"chainingRequired\",\n")
318 N_(" \"referralsPreferred\", \"referralsRequired\"\n")
319 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
320 N_(" [!]manageDSAit (RFC 3296)\n")
322 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
325 N_(" [!]postread[=<attrs>] (RFC 4527; comma-separated attr list)\n")
326 N_(" [!]preread[=<attrs>] (RFC 4527; comma-separated attr list)\n")
328 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
329 N_(" [!]sessiontracking\n")
330 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
331 N_(" abandon, cancel, ignore (SIGINT sends abandon/cancel,\n"
332 " or ignores response; if critical, doesn't wait for SIGINT.\n"
333 " not really controls)\n")
334 N_(" -h host LDAP server\n"),
335 N_(" -H URI LDAP Uniform Resource Identifier(s)\n"),
336 N_(" -I use SASL Interactive mode\n"),
337 N_(" -n show what would be done but don't actually do it\n"),
338 N_(" -N do not use reverse DNS to canonicalize SASL host name\n"),
339 N_(" -O props SASL security properties\n"),
340 N_(" -o <opt>[=<optparam] general options\n"),
341 N_(" nettimeout=<timeout> (in seconds, or \"none\" or \"max\")\n"),
342 N_(" ldif-wrap=<width> (in columns, or \"no\" for no wrapping)\n"),
343 N_(" -p port port on LDAP server\n"),
344 N_(" -Q use SASL Quiet mode\n"),
345 N_(" -R realm SASL realm\n"),
346 N_(" -U authcid SASL authentication identity\n"),
347 N_(" -v run in verbose mode (diagnostics to standard output)\n"),
348 N_(" -V print version info (-VV only)\n"),
349 N_(" -w passwd bind password (for simple authentication)\n"),
350 N_(" -W prompt for bind password\n"),
351 N_(" -x Simple authentication\n"),
352 N_(" -X authzid SASL authorization identity (\"dn:<dn>\" or \"u:<user>\")\n"),
353 N_(" -y file Read password from file\n"),
354 N_(" -Y mech SASL mechanism\n"),
355 N_(" -Z Start TLS request (-ZZ to require successful response)\n"),
358 const char *const *cpp;
360 fputs( _("Common options:\n"), stderr );
361 for( cpp = descriptions; *cpp != NULL; cpp++ ) {
362 if( strchr( options, (*cpp)[3] ) || (*cpp)[3] == ' ' ) {
363 fputs( _(*cpp), stderr );
376 fprintf( stderr, "%s: %s (%d)%s\n",
377 func, ldap_err2string( err ), err, extra ? extra : "" );
379 if ( matched && *matched ) {
380 fprintf( stderr, _("\tmatched DN: %s\n"), matched );
383 if ( info && *info ) {
384 fprintf( stderr, _("\tadditional info: %s\n"), info );
387 if ( refs && *refs ) {
389 fprintf( stderr, _("\treferrals:\n") );
390 for( i=0; refs[i]; i++ ) {
391 fprintf( stderr, "\t\t%s\n", refs[i] );
398 tool_args( int argc, char **argv )
402 while (( i = getopt( argc, argv, options )) != EOF ) {
404 char *control, *cvalue, *next;
406 case 'c': /* continuous operation mode */
413 ival = strtol( optarg, &next, 10 );
414 if (next == NULL || next[0] != '\0') {
415 fprintf( stderr, "%s: unable to parse debug value \"%s\"\n", prog, optarg);
420 case 'D': /* bind DN */
421 if( binddn != NULL ) {
422 fprintf( stderr, "%s: -D previously specified\n", prog );
423 exit( EXIT_FAILURE );
425 binddn = ber_strdup( optarg );
427 case 'e': /* general extensions (controls and such) */
428 /* should be extended to support comma separated list of
429 * [!]key[=value] parameters, e.g. -e !foo,bar=567
434 if( optarg[0] == '!' ) {
439 control = ber_strdup( optarg );
440 if ( (cvalue = strchr( control, '=' )) != NULL ) {
444 if ( strcasecmp( control, "assert" ) == 0 ) {
446 fprintf( stderr, "assert control previously specified\n");
447 exit( EXIT_FAILURE );
449 if( cvalue == NULL ) {
450 fprintf( stderr, "assert: control value expected\n" );
454 assertctl = 1 + crit;
456 assert( assertion == NULL );
457 assertion = ber_strdup( cvalue );
459 } else if ( strcasecmp( control, "authzid" ) == 0 ) {
460 if( authzid != NULL ) {
461 fprintf( stderr, "authzid control previously specified\n");
462 exit( EXIT_FAILURE );
464 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
465 if( proxydn != NULL ) {
466 fprintf( stderr, "authzid control incompatible with proxydn\n");
467 exit( EXIT_FAILURE );
469 #endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
470 if( cvalue == NULL ) {
471 fprintf( stderr, "authzid: control value expected\n" );
475 fprintf( stderr, "authzid: must be marked critical\n" );
479 assert( authzid == NULL );
480 authzid = ber_strdup( cvalue );
482 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
483 } else if ( strcasecmp( control, "proxydn" ) == 0 ) {
484 if( proxydn != NULL ) {
485 fprintf( stderr, "proxydn control previously specified\n");
486 exit( EXIT_FAILURE );
488 if( authzid != NULL ) {
489 fprintf( stderr, "proxydn control incompatible with authzid\n");
490 exit( EXIT_FAILURE );
492 if( cvalue == NULL ) {
493 fprintf( stderr, "proxydn: control value expected\n" );
497 fprintf( stderr, "proxydn: must be marked critical\n" );
501 assert( proxydn == NULL );
502 proxydn = ber_strdup( cvalue );
503 #endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
505 } else if ( ( strcasecmp( control, "relax" ) == 0 ) ||
506 ( strcasecmp( control, "manageDIT" ) == 0 ) )
510 "relax control previously specified\n");
511 exit( EXIT_FAILURE );
513 if( cvalue != NULL ) {
515 "relax: no control value expected\n" );
519 manageDIT = 1 + crit;
521 } else if ( strcasecmp( control, "manageDSAit" ) == 0 ) {
524 "manageDSAit control previously specified\n");
525 exit( EXIT_FAILURE );
527 if( cvalue != NULL ) {
529 "manageDSAit: no control value expected\n" );
533 manageDSAit = 1 + crit;
535 } else if ( strcasecmp( control, "noop" ) == 0 ) {
537 fprintf( stderr, "noop control previously specified\n");
538 exit( EXIT_FAILURE );
540 if( cvalue != NULL ) {
541 fprintf( stderr, "noop: no control value expected\n" );
547 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
548 } else if ( strcasecmp( control, "ppolicy" ) == 0 ) {
550 fprintf( stderr, "ppolicy control previously specified\n");
551 exit( EXIT_FAILURE );
553 if( cvalue != NULL ) {
554 fprintf( stderr, "ppolicy: no control value expected\n" );
558 fprintf( stderr, "ppolicy: critical flag not allowed\n" );
565 } else if ( strcasecmp( control, "preread" ) == 0 ) {
567 fprintf( stderr, "preread control previously specified\n");
568 exit( EXIT_FAILURE );
572 preread_attrs = ber_strdup( cvalue );
574 } else if ( strcasecmp( control, "postread" ) == 0 ) {
576 fprintf( stderr, "postread control previously specified\n");
577 exit( EXIT_FAILURE );
581 postread_attrs = ber_strdup( cvalue );
583 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
584 } else if ( strcasecmp( control, "chaining" ) == 0 ) {
587 if ( cvalue != NULL ) {
590 continuation = strchr( cvalue, '/' );
591 if ( continuation ) {
592 /* FIXME: this makes sense only in searches */
593 *continuation++ = '\0';
594 if ( strcasecmp( continuation, "chainingPreferred" ) == 0 ) {
595 chainingContinuation = LDAP_CHAINING_PREFERRED;
596 } else if ( strcasecmp( continuation, "chainingRequired" ) == 0 ) {
597 chainingContinuation = LDAP_CHAINING_REQUIRED;
598 } else if ( strcasecmp( continuation, "referralsPreferred" ) == 0 ) {
599 chainingContinuation = LDAP_REFERRALS_PREFERRED;
600 } else if ( strcasecmp( continuation, "referralsRequired" ) == 0 ) {
601 chainingContinuation = LDAP_REFERRALS_REQUIRED;
604 "chaining behavior control "
605 "continuation value \"%s\" invalid\n",
607 exit( EXIT_FAILURE );
611 if ( strcasecmp( cvalue, "chainingPreferred" ) == 0 ) {
612 chainingResolve = LDAP_CHAINING_PREFERRED;
613 } else if ( strcasecmp( cvalue, "chainingRequired" ) == 0 ) {
614 chainingResolve = LDAP_CHAINING_REQUIRED;
615 } else if ( strcasecmp( cvalue, "referralsPreferred" ) == 0 ) {
616 chainingResolve = LDAP_REFERRALS_PREFERRED;
617 } else if ( strcasecmp( cvalue, "referralsRequired" ) == 0 ) {
618 chainingResolve = LDAP_REFERRALS_REQUIRED;
621 "chaining behavior control "
622 "resolve value \"%s\" invalid\n",
624 exit( EXIT_FAILURE );
627 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
629 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
630 } else if ( strcasecmp( control, "sessiontracking" ) == 0 ) {
631 if ( sessionTracking ) {
632 fprintf( stderr, "%s: session tracking can be only specified once\n", prog );
633 exit( EXIT_FAILURE );
637 fprintf( stderr, "sessiontracking: critical flag not allowed\n" );
640 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
642 /* this shouldn't go here, really; but it's a feature... */
643 } else if ( strcasecmp( control, "abandon" ) == 0 ) {
644 abcan = Intr_Abandon;
649 } else if ( strcasecmp( control, "cancel" ) == 0 ) {
655 } else if ( strcasecmp( control, "ignore" ) == 0 ) {
661 } else if ( tool_is_oid( control ) ) {
662 LDAPControl *tmpctrls, ctrl;
664 tmpctrls = (LDAPControl *)ber_memrealloc( unknown_ctrls,
665 (unknown_ctrls_num + 1)*sizeof( LDAPControl ) );
666 if ( tmpctrls == NULL ) {
667 fprintf( stderr, "%s: no memory?\n", prog );
668 exit( EXIT_FAILURE );
670 unknown_ctrls = tmpctrls;
671 ctrl.ldctl_oid = control;
674 ctrl.ldctl_value.bv_val = NULL;
675 ctrl.ldctl_value.bv_len = 0;
676 ctrl.ldctl_iscritical = crit;
678 if ( cvalue != NULL ) {
680 size_t len = strlen( cvalue );
683 bv.bv_len = LUTIL_BASE64_DECODE_LEN( len );
684 bv.bv_val = ber_memalloc( bv.bv_len + 1 );
686 retcode = lutil_b64_pton( cvalue,
687 (unsigned char *)bv.bv_val,
690 if ( retcode == -1 || (unsigned) retcode > bv.bv_len ) {
691 fprintf( stderr, "Unable to parse value of general control %s\n",
697 ctrl.ldctl_value = bv;
700 unknown_ctrls[ unknown_ctrls_num ] = ctrl;
704 fprintf( stderr, "Invalid general control name: %s\n",
709 ber_memfree( control );
713 case 'f': /* read from file */
714 if( infile != NULL ) {
715 fprintf( stderr, "%s: -f previously specified\n", prog );
716 exit( EXIT_FAILURE );
718 infile = ber_strdup( optarg );
720 case 'h': /* ldap host */
721 if( ldaphost != NULL ) {
722 fprintf( stderr, "%s: -h previously specified\n", prog );
723 exit( EXIT_FAILURE );
725 ldaphost = ber_strdup( optarg );
727 case 'H': /* ldap URI */
728 if( ldapuri != NULL ) {
729 fprintf( stderr, "%s: -H previously specified\n", prog );
730 exit( EXIT_FAILURE );
732 ldapuri = ber_strdup( optarg );
735 #ifdef HAVE_CYRUS_SASL
736 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
737 fprintf( stderr, "%s: incompatible previous "
738 "authentication choice\n",
740 exit( EXIT_FAILURE );
742 authmethod = LDAP_AUTH_SASL;
743 sasl_flags = LDAP_SASL_INTERACTIVE;
746 fprintf( stderr, "%s: was not compiled with SASL support\n",
748 exit( EXIT_FAILURE );
751 /* enable Manage DSA IT */
754 case 'n': /* print operations, don't actually do them */
761 control = ber_strdup( optarg );
762 if ( (cvalue = strchr( control, '=' )) != NULL ) {
766 if ( strcasecmp( control, "nettimeout" ) == 0 ) {
767 if( nettimeout.tv_sec != -1 ) {
768 fprintf( stderr, "nettimeout option previously specified\n");
769 exit( EXIT_FAILURE );
771 if( cvalue == NULL || cvalue[0] == '\0' ) {
772 fprintf( stderr, "nettimeout: option value expected\n" );
775 if ( strcasecmp( cvalue, "none" ) == 0 ) {
776 nettimeout.tv_sec = 0;
777 } else if ( strcasecmp( cvalue, "max" ) == 0 ) {
778 nettimeout.tv_sec = LDAP_MAXINT;
780 ival = strtol( cvalue, &next, 10 );
781 if ( next == NULL || next[0] != '\0' ) {
783 _("Unable to parse network timeout \"%s\"\n"), cvalue );
784 exit( EXIT_FAILURE );
786 nettimeout.tv_sec = ival;
788 if( nettimeout.tv_sec < 0 || nettimeout.tv_sec > LDAP_MAXINT ) {
789 fprintf( stderr, _("%s: invalid network timeout (%ld) specified\n"),
790 prog, (long)nettimeout.tv_sec );
791 exit( EXIT_FAILURE );
794 } else if ( strcasecmp( control, "ldif-wrap" ) == 0 ) {
796 ldif_wrap = LDIF_LINE_WIDTH;
798 } else if ( strcasecmp( cvalue, "no" ) == 0 ) {
799 ldif_wrap = LDIF_LINE_WIDTH_MAX;
803 if ( lutil_atou( &u, cvalue ) ) {
805 _("Unable to parse ldif-wrap=\"%s\"\n"), cvalue );
806 exit( EXIT_FAILURE );
808 ldif_wrap = (ber_len_t)u;
812 fprintf( stderr, "Invalid general option name: %s\n",
816 ber_memfree(control);
819 #ifdef HAVE_CYRUS_SASL
820 if( sasl_secprops != NULL ) {
821 fprintf( stderr, "%s: -O previously specified\n", prog );
822 exit( EXIT_FAILURE );
824 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
825 fprintf( stderr, "%s: incompatible previous "
826 "authentication choice\n", prog );
827 exit( EXIT_FAILURE );
829 authmethod = LDAP_AUTH_SASL;
830 sasl_secprops = ber_strdup( optarg );
832 fprintf( stderr, "%s: not compiled with SASL support\n", prog );
833 exit( EXIT_FAILURE );
838 fprintf( stderr, "%s: -p previously specified\n", prog );
839 exit( EXIT_FAILURE );
841 ival = strtol( optarg, &next, 10 );
842 if ( next == NULL || next[0] != '\0' ) {
843 fprintf( stderr, "%s: unable to parse port number \"%s\"\n", prog, optarg );
844 exit( EXIT_FAILURE );
849 ival = strtol( optarg, &next, 10 );
850 if ( next == NULL || next[0] != '\0' ) {
851 fprintf( stderr, "%s: unable to parse protocol version \"%s\"\n", prog, optarg );
852 exit( EXIT_FAILURE );
856 if( protocol == LDAP_VERSION3 ) {
857 fprintf( stderr, "%s: -P 2 incompatible with version %d\n",
859 exit( EXIT_FAILURE );
861 protocol = LDAP_VERSION2;
864 if( protocol == LDAP_VERSION2 ) {
865 fprintf( stderr, "%s: -P 2 incompatible with version %d\n",
867 exit( EXIT_FAILURE );
869 protocol = LDAP_VERSION3;
872 fprintf( stderr, "%s: protocol version should be 2 or 3\n",
878 #ifdef HAVE_CYRUS_SASL
879 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
880 fprintf( stderr, "%s: incompatible previous "
881 "authentication choice\n",
883 exit( EXIT_FAILURE );
885 authmethod = LDAP_AUTH_SASL;
886 sasl_flags = LDAP_SASL_QUIET;
889 fprintf( stderr, "%s: not compiled with SASL support\n",
891 exit( EXIT_FAILURE );
894 #ifdef HAVE_CYRUS_SASL
895 if( sasl_realm != NULL ) {
896 fprintf( stderr, "%s: -R previously specified\n", prog );
897 exit( EXIT_FAILURE );
899 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
900 fprintf( stderr, "%s: incompatible previous "
901 "authentication choice\n",
903 exit( EXIT_FAILURE );
905 authmethod = LDAP_AUTH_SASL;
906 sasl_realm = ber_strdup( optarg );
908 fprintf( stderr, "%s: not compiled with SASL support\n",
910 exit( EXIT_FAILURE );
914 #ifdef HAVE_CYRUS_SASL
915 if( sasl_authc_id != NULL ) {
916 fprintf( stderr, "%s: -U previously specified\n", prog );
917 exit( EXIT_FAILURE );
919 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
920 fprintf( stderr, "%s: incompatible previous "
921 "authentication choice\n",
923 exit( EXIT_FAILURE );
925 authmethod = LDAP_AUTH_SASL;
926 sasl_authc_id = ber_strdup( optarg );
928 fprintf( stderr, "%s: not compiled with SASL support\n",
930 exit( EXIT_FAILURE );
933 case 'v': /* verbose mode */
936 case 'V': /* version */
939 case 'w': /* password */
940 passwd.bv_val = ber_strdup( optarg );
944 for( p = optarg; *p != '\0'; p++ ) {
948 passwd.bv_len = strlen( passwd.bv_val );
957 #ifdef HAVE_CYRUS_SASL
958 if( sasl_mech != NULL ) {
959 fprintf( stderr, "%s: -Y previously specified\n", prog );
960 exit( EXIT_FAILURE );
962 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
964 "%s: incompatible with authentication choice\n", prog );
965 exit( EXIT_FAILURE );
967 authmethod = LDAP_AUTH_SASL;
968 sasl_mech = ber_strdup( optarg );
970 fprintf( stderr, "%s: not compiled with SASL support\n", prog );
971 exit( EXIT_FAILURE );
975 if( authmethod != -1 && authmethod != LDAP_AUTH_SIMPLE ) {
976 fprintf( stderr, "%s: incompatible with previous "
977 "authentication choice\n", prog );
978 exit( EXIT_FAILURE );
980 authmethod = LDAP_AUTH_SIMPLE;
983 #ifdef HAVE_CYRUS_SASL
984 if( sasl_authz_id != NULL ) {
985 fprintf( stderr, "%s: -X previously specified\n", prog );
986 exit( EXIT_FAILURE );
988 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
989 fprintf( stderr, "%s: -X incompatible with "
990 "authentication choice\n", prog );
991 exit( EXIT_FAILURE );
993 authmethod = LDAP_AUTH_SASL;
994 sasl_authz_id = ber_strdup( optarg );
996 fprintf( stderr, "%s: not compiled with SASL support\n", prog );
997 exit( EXIT_FAILURE );
1004 fprintf( stderr, "%s: not compiled with TLS support\n", prog );
1005 exit( EXIT_FAILURE );
1009 if( handle_private_option( i ) ) break;
1010 fprintf( stderr, "%s: unrecognized option -%c\n",
1017 /* prevent bad linking */
1019 api.ldapai_info_version = LDAP_API_INFO_VERSION;
1021 if ( ldap_get_option(NULL, LDAP_OPT_API_INFO, &api)
1022 != LDAP_OPT_SUCCESS )
1024 fprintf( stderr, "%s: ldap_get_option(API_INFO) failed\n", prog );
1025 exit( EXIT_FAILURE );
1028 if (api.ldapai_info_version != LDAP_API_INFO_VERSION) {
1029 fprintf( stderr, "LDAP APIInfo version mismatch: "
1030 "library %d, header %d\n",
1031 api.ldapai_info_version, LDAP_API_INFO_VERSION );
1032 exit( EXIT_FAILURE );
1035 if( api.ldapai_api_version != LDAP_API_VERSION ) {
1036 fprintf( stderr, "LDAP API version mismatch: "
1037 "library %d, header %d\n",
1038 api.ldapai_api_version, LDAP_API_VERSION );
1039 exit( EXIT_FAILURE );
1042 if( strcmp(api.ldapai_vendor_name, LDAP_VENDOR_NAME ) != 0 ) {
1043 fprintf( stderr, "LDAP vendor name mismatch: "
1044 "library %s, header %s\n",
1045 api.ldapai_vendor_name, LDAP_VENDOR_NAME );
1046 exit( EXIT_FAILURE );
1049 if( api.ldapai_vendor_version != LDAP_VENDOR_VERSION ) {
1050 fprintf( stderr, "LDAP vendor version mismatch: "
1051 "library %d, header %d\n",
1052 api.ldapai_vendor_version, LDAP_VENDOR_VERSION );
1053 exit( EXIT_FAILURE );
1057 fprintf( stderr, "%s: %s\t(LDAP library: %s %d)\n",
1059 LDAP_VENDOR_NAME, LDAP_VENDOR_VERSION );
1060 if (version > 1) exit( EXIT_SUCCESS );
1063 ldap_memfree( api.ldapai_vendor_name );
1064 ber_memvfree( (void **)api.ldapai_extensions );
1068 protocol = LDAP_VERSION3;
1070 if (authmethod == -1 && protocol > LDAP_VERSION2) {
1071 #ifdef HAVE_CYRUS_SASL
1072 if ( binddn != NULL ) {
1073 authmethod = LDAP_AUTH_SIMPLE;
1075 authmethod = LDAP_AUTH_SASL;
1078 authmethod = LDAP_AUTH_SIMPLE;
1082 if( ldapuri == NULL ) {
1083 if( ldapport && ( ldaphost == NULL )) {
1084 fprintf( stderr, "%s: -p without -h is invalid.\n", prog );
1085 exit( EXIT_FAILURE );
1088 if( ldaphost != NULL ) {
1089 fprintf( stderr, "%s: -H incompatible with -h\n", prog );
1090 exit( EXIT_FAILURE );
1093 fprintf( stderr, "%s: -H incompatible with -p\n", prog );
1094 exit( EXIT_FAILURE );
1098 if( protocol == LDAP_VERSION2 ) {
1099 if( assertctl || authzid || manageDIT || manageDSAit ||
1100 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
1102 #endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
1103 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
1106 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
1108 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
1109 noop || ppolicy || preread || postread )
1111 fprintf( stderr, "%s: -e/-M incompatible with LDAPv2\n", prog );
1112 exit( EXIT_FAILURE );
1116 fprintf( stderr, "%s: -Z incompatible with LDAPv2\n", prog );
1117 exit( EXIT_FAILURE );
1120 #ifdef HAVE_CYRUS_SASL
1121 if( authmethod == LDAP_AUTH_SASL ) {
1122 fprintf( stderr, "%s: -[IOQRUXY] incompatible with LDAPv2\n",
1124 exit( EXIT_FAILURE );
1132 tool_conn_setup( int dont, void (*private_setup)( LDAP * ) )
1137 if( ber_set_option( NULL, LBER_OPT_DEBUG_LEVEL, &debug )
1138 != LBER_OPT_SUCCESS )
1141 "Could not set LBER_OPT_DEBUG_LEVEL %d\n", debug );
1143 if( ldap_set_option( NULL, LDAP_OPT_DEBUG_LEVEL, &debug )
1144 != LDAP_OPT_SUCCESS )
1147 "Could not set LDAP_OPT_DEBUG_LEVEL %d\n", debug );
1152 (void) SIGNAL( SIGPIPE, SIG_IGN );
1156 SIGNAL( SIGINT, do_sig );
1162 if( ( ldaphost != NULL || ldapport ) && ( ldapuri == NULL ) ) {
1165 memset( &url, 0, sizeof(url));
1167 url.lud_scheme = "ldap";
1168 url.lud_host = ldaphost;
1169 url.lud_port = ldapport;
1170 url.lud_scope = LDAP_SCOPE_DEFAULT;
1172 ldapuri = ldap_url_desc2str( &url );
1174 } else if ( ldapuri != NULL ) {
1175 LDAPURLDesc *ludlist, **ludp;
1179 rc = ldap_url_parselist( &ludlist, ldapuri );
1180 if ( rc != LDAP_URL_SUCCESS ) {
1182 "Could not parse LDAP URI(s)=%s (%d)\n",
1184 exit( EXIT_FAILURE );
1187 for ( ludp = &ludlist; *ludp != NULL; ) {
1188 LDAPURLDesc *lud = *ludp;
1191 if ( lud->lud_dn != NULL && lud->lud_dn[ 0 ] != '\0' &&
1192 ( lud->lud_host == NULL || lud->lud_host[0] == '\0' ) )
1194 /* if no host but a DN is provided,
1195 * use DNS SRV to gather the host list
1196 * and turn it into a list of URIs
1197 * using the scheme provided */
1198 char *domain = NULL,
1202 len_proto = strlen( lud->lud_scheme );
1204 if ( ldap_dn2domain( lud->lud_dn, &domain )
1208 "DNS SRV: Could not turn "
1209 "DN=\"%s\" into a domain\n",
1214 rc = ldap_domain2hostlist( domain, &hostlist );
1217 "DNS SRV: Could not turn "
1218 "domain=%s into a hostlist\n",
1223 hosts = ldap_str2charray( hostlist, " " );
1224 if ( hosts == NULL ) {
1226 "DNS SRV: Could not parse "
1227 "hostlist=\"%s\"\n",
1232 for ( i = 0; hosts[ i ] != NULL; i++ )
1235 tmp = (char **)ber_memrealloc( urls, sizeof( char * ) * ( nurls + i + 1 ) );
1236 if ( tmp == NULL ) {
1238 "DNS SRV: out of memory?\n" );
1242 urls[ nurls ] = NULL;
1244 for ( i = 0; hosts[ i ] != NULL; i++ ) {
1245 size_t len = len_proto
1247 + strlen( hosts[ i ] )
1250 urls[ nurls + i + 1 ] = NULL;
1251 urls[ nurls + i ] = (char *)malloc( sizeof( char ) * len );
1252 if ( urls[ nurls + i ] == NULL ) {
1254 "DNS SRV: out of memory?\n" );
1258 snprintf( urls[ nurls + i ], len, "%s://%s",
1259 lud->lud_scheme, hosts[ i ] );
1264 ber_memvfree( (void **)hosts );
1265 ber_memfree( hostlist );
1266 ber_memfree( domain );
1269 tmp = (char **)ber_memrealloc( urls, sizeof( char * ) * ( nurls + 2 ) );
1270 if ( tmp == NULL ) {
1272 "DNS SRV: out of memory?\n" );
1276 urls[ nurls + 1 ] = NULL;
1278 urls[ nurls ] = ldap_url_desc2str( lud );
1279 if ( urls[ nurls ] == NULL ) {
1281 "DNS SRV: out of memory?\n" );
1287 *ludp = lud->lud_next;
1289 lud->lud_next = NULL;
1290 ldap_free_urldesc( lud );
1293 if ( ludlist != NULL ) {
1294 ldap_free_urllist( ludlist );
1295 exit( EXIT_FAILURE );
1297 } else if ( urls == NULL ) {
1298 exit( EXIT_FAILURE );
1301 ldap_memfree( ldapuri );
1302 ldapuri = ldap_charray2str( urls, " " );
1303 ber_memvfree( (void **)urls );
1307 fprintf( stderr, "ldap_initialize( %s )\n",
1308 ldapuri != NULL ? ldapuri : "<DEFAULT>" );
1310 rc = ldap_initialize( &ld, ldapuri );
1311 if( rc != LDAP_SUCCESS ) {
1313 "Could not create LDAP session handle for URI=%s (%d): %s\n",
1314 ldapuri, rc, ldap_err2string(rc) );
1315 exit( EXIT_FAILURE );
1318 if( private_setup ) private_setup( ld );
1321 if( ldap_set_option( ld, LDAP_OPT_REFERRALS,
1322 referrals ? LDAP_OPT_ON : LDAP_OPT_OFF ) != LDAP_OPT_SUCCESS )
1324 fprintf( stderr, "Could not set LDAP_OPT_REFERRALS %s\n",
1325 referrals ? "on" : "off" );
1326 exit( EXIT_FAILURE );
1329 #ifdef HAVE_CYRUS_SASL
1331 if( ldap_set_option( ld, LDAP_OPT_X_SASL_NOCANON,
1332 nocanon ? LDAP_OPT_ON : LDAP_OPT_OFF ) != LDAP_OPT_SUCCESS )
1334 fprintf( stderr, "Could not set LDAP_OPT_X_SASL_NOCANON %s\n",
1335 nocanon ? "on" : "off" );
1336 exit( EXIT_FAILURE );
1339 if( ldap_set_option( ld, LDAP_OPT_PROTOCOL_VERSION, &protocol )
1340 != LDAP_OPT_SUCCESS )
1342 fprintf( stderr, "Could not set LDAP_OPT_PROTOCOL_VERSION %d\n",
1344 exit( EXIT_FAILURE );
1348 rc = ldap_start_tls_s( ld, NULL, NULL );
1349 if ( rc != LDAP_SUCCESS ) {
1351 ldap_get_option( ld, LDAP_OPT_DIAGNOSTIC_MESSAGE, (void*)&msg);
1352 tool_perror( "ldap_start_tls", rc, NULL, NULL, msg, NULL );
1354 if ( use_tls > 1 ) {
1355 exit( EXIT_FAILURE );
1360 if ( nettimeout.tv_sec > 0 ) {
1361 if ( ldap_set_option( ld, LDAP_OPT_NETWORK_TIMEOUT, (void *) &nettimeout )
1362 != LDAP_OPT_SUCCESS )
1364 fprintf( stderr, "Could not set LDAP_OPT_NETWORK_TIMEOUT %ld\n",
1365 (long)nettimeout.tv_sec );
1366 exit( EXIT_FAILURE );
1376 tool_bind( LDAP *ld )
1378 LDAPControl **sctrlsp = NULL;
1379 LDAPControl *sctrls[3];
1380 LDAPControl sctrl[3];
1383 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
1386 c.ldctl_oid = LDAP_CONTROL_PASSWORDPOLICYREQUEST;
1387 c.ldctl_value.bv_val = NULL;
1388 c.ldctl_value.bv_len = 0;
1389 c.ldctl_iscritical = 0;
1391 sctrls[nsctrls] = &sctrl[nsctrls];
1392 sctrls[++nsctrls] = NULL;
1396 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
1397 if ( sessionTracking ) {
1400 if (stValue.bv_val == NULL && st_value( ld, &stValue ) ) {
1401 exit( EXIT_FAILURE );
1404 c.ldctl_oid = LDAP_CONTROL_X_SESSION_TRACKING;
1405 c.ldctl_iscritical = 0;
1406 ber_dupbv( &c.ldctl_value, &stValue );
1409 sctrls[nsctrls] = &sctrl[nsctrls];
1410 sctrls[++nsctrls] = NULL;
1412 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
1418 assert( nsctrls < (int) (sizeof(sctrls)/sizeof(sctrls[0])) );
1420 if ( pw_file || want_bindpw ) {
1421 assert( passwd.bv_val == NULL && passwd.bv_len == 0 );
1424 if ( lutil_get_filed_password( pw_file, &passwd ) ) {
1425 exit( EXIT_FAILURE );
1429 char *pw = getpassphrase( _("Enter LDAP Password: ") );
1431 passwd.bv_val = ber_strdup( pw );
1432 passwd.bv_len = strlen( passwd.bv_val );
1437 if ( authmethod == LDAP_AUTH_SASL ) {
1438 #ifdef HAVE_CYRUS_SASL
1442 if( sasl_secprops != NULL ) {
1443 rc = ldap_set_option( ld, LDAP_OPT_X_SASL_SECPROPS,
1444 (void *) sasl_secprops );
1446 if( rc != LDAP_OPT_SUCCESS ) {
1448 "Could not set LDAP_OPT_X_SASL_SECPROPS: %s\n",
1450 exit( LDAP_LOCAL_ERROR );
1454 defaults = lutil_sasl_defaults( ld,
1461 rc = ldap_sasl_interactive_bind_s( ld, binddn, sasl_mech,
1463 NULL, sasl_flags, lutil_sasl_interact, defaults );
1465 lutil_sasl_freedefs( defaults );
1466 if( rc != LDAP_SUCCESS ) {
1468 ldap_get_option( ld, LDAP_OPT_DIAGNOSTIC_MESSAGE, (void*)&msg);
1469 tool_perror( "ldap_sasl_interactive_bind_s",
1470 rc, NULL, NULL, msg, NULL );
1475 fprintf( stderr, "%s: not compiled with SASL support\n", prog );
1476 exit( LDAP_NOT_SUPPORTED );
1480 LDAPMessage *result;
1481 LDAPControl **ctrls;
1483 char *matched = NULL;
1491 rc = ldap_sasl_bind( ld, binddn, LDAP_SASL_SIMPLE, &passwd,
1492 sctrlsp, NULL, &msgid );
1493 if ( msgid == -1 ) {
1494 tool_perror( "ldap_sasl_bind(SIMPLE)", rc,
1495 NULL, NULL, NULL, NULL );
1500 rc = ldap_result( ld, msgid, LDAP_MSG_ALL, NULL, &result );
1502 tool_perror( "ldap_result", -1, NULL, NULL, NULL, NULL );
1503 exit( LDAP_LOCAL_ERROR );
1507 tool_perror( "ldap_result", LDAP_TIMEOUT, NULL, NULL, NULL, NULL );
1508 exit( LDAP_LOCAL_ERROR );
1511 rc = ldap_parse_result( ld, result, &err, &matched, &info, &refs,
1513 if ( rc != LDAP_SUCCESS ) {
1514 tool_perror( "ldap_bind parse result", rc, NULL, matched, info, refs );
1515 exit( LDAP_LOCAL_ERROR );
1518 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
1519 if ( ctrls && ppolicy ) {
1521 int expire, grace, len = 0;
1522 LDAPPasswordPolicyError pErr = -1;
1524 ctrl = ldap_control_find( LDAP_CONTROL_PASSWORDPOLICYRESPONSE,
1527 if ( ctrl && ldap_parse_passwordpolicy_control( ld, ctrl,
1528 &expire, &grace, &pErr ) == LDAP_SUCCESS )
1530 if ( pErr != PP_noError ){
1533 strcpy( msgbuf+2, ldap_passwordpolicy_err2txt( pErr ));
1534 len = strlen( msgbuf );
1536 if ( expire >= 0 ) {
1537 sprintf( msgbuf+len,
1538 " (Password expires in %d seconds)",
1540 } else if ( grace >= 0 ) {
1541 sprintf( msgbuf+len,
1542 " (Password expired, %d grace logins remain)",
1550 ldap_controls_free( ctrls );
1553 if ( err != LDAP_SUCCESS
1555 || ( matched && matched[ 0 ] )
1556 || ( info && info[ 0 ] )
1559 tool_perror( "ldap_bind", err, msgbuf, matched, info, refs );
1561 if( matched ) ber_memfree( matched );
1562 if( info ) ber_memfree( info );
1563 if( refs ) ber_memvfree( (void **)refs );
1565 if ( err != LDAP_SUCCESS ) exit( err );
1571 tool_unbind( LDAP *ld )
1573 int err = ldap_set_option( ld, LDAP_OPT_SERVER_CONTROLS, NULL );
1575 if ( err != LDAP_OPT_SUCCESS ) {
1576 fprintf( stderr, "Could not unset controls\n");
1579 (void) ldap_unbind_ext( ld, NULL, NULL );
1583 /* Set server controls. Add controls extra_c[0..count-1], if set. */
1585 tool_server_controls( LDAP *ld, LDAPControl *extra_c, int count )
1587 int i = 0, j, crit = 0, err;
1588 LDAPControl c[16], **ctrls;
1592 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
1594 #endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
1598 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
1603 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
1605 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
1606 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
1608 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
1610 || unknown_ctrls_num ) )
1615 ctrls = (LDAPControl**) malloc(sizeof(c) + (count + unknown_ctrls_num + 1)*sizeof(LDAPControl*));
1616 if ( ctrls == NULL ) {
1617 fprintf( stderr, "No memory\n" );
1618 exit( EXIT_FAILURE );
1622 if ( BER_BVISNULL( &assertionvalue ) ) {
1623 err = ldap_create_assertion_control_value( ld,
1624 assertion, &assertionvalue );
1627 "Unable to create assertion value "
1628 "\"%s\" (%d)\n", assertion, err );
1632 c[i].ldctl_oid = LDAP_CONTROL_ASSERT;
1633 c[i].ldctl_value = assertionvalue;
1634 c[i].ldctl_iscritical = assertctl > 1;
1640 c[i].ldctl_value.bv_val = authzid;
1641 c[i].ldctl_value.bv_len = strlen( authzid );
1642 c[i].ldctl_oid = LDAP_CONTROL_PROXY_AUTHZ;
1643 c[i].ldctl_iscritical = 1;
1648 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
1649 /* NOTE: doesn't need an extra count because it's incompatible
1652 BerElementBuffer berbuf;
1653 BerElement *ber = (BerElement *)&berbuf;
1655 ber_init2( ber, NULL, LBER_USE_DER );
1657 if ( ber_printf( ber, "s", proxydn ) == -1 ) {
1658 exit( EXIT_FAILURE );
1661 if ( ber_flatten2( ber, &c[i].ldctl_value, 0 ) == -1 ) {
1662 exit( EXIT_FAILURE );
1665 c[i].ldctl_oid = LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ;
1666 c[i].ldctl_iscritical = 1;
1670 #endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
1673 c[i].ldctl_oid = LDAP_CONTROL_MANAGEDIT;
1674 BER_BVZERO( &c[i].ldctl_value );
1675 c[i].ldctl_iscritical = manageDIT > 1;
1680 if ( manageDSAit ) {
1681 c[i].ldctl_oid = LDAP_CONTROL_MANAGEDSAIT;
1682 BER_BVZERO( &c[i].ldctl_value );
1683 c[i].ldctl_iscritical = manageDSAit > 1;
1689 c[i].ldctl_oid = LDAP_CONTROL_NOOP;
1690 BER_BVZERO( &c[i].ldctl_value );
1691 c[i].ldctl_iscritical = noop > 1;
1696 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
1698 c[i].ldctl_oid = LDAP_CONTROL_PASSWORDPOLICYREQUEST;
1699 BER_BVZERO( &c[i].ldctl_value );
1700 c[i].ldctl_iscritical = 0;
1707 BerElementBuffer berbuf;
1708 BerElement *ber = (BerElement *)&berbuf;
1709 char **attrs = NULL;
1711 if( preread_attrs ) {
1712 attrs = ldap_str2charray( preread_attrs, "," );
1715 ber_init2( ber, NULL, LBER_USE_DER );
1717 if( ber_printf( ber, "{v}", attrs ) == -1 ) {
1718 fprintf( stderr, "preread attrs encode failed.\n" );
1719 exit( EXIT_FAILURE );
1722 err = ber_flatten2( ber, &c[i].ldctl_value, 0 );
1724 fprintf( stderr, "preread flatten failed (%d)\n", err );
1725 exit( EXIT_FAILURE );
1728 c[i].ldctl_oid = LDAP_CONTROL_PRE_READ;
1729 c[i].ldctl_iscritical = preread > 1;
1733 if( attrs ) ldap_charray_free( attrs );
1737 BerElementBuffer berbuf;
1738 BerElement *ber = (BerElement *)&berbuf;
1739 char **attrs = NULL;
1741 if( postread_attrs ) {
1742 attrs = ldap_str2charray( postread_attrs, "," );
1745 ber_init2( ber, NULL, LBER_USE_DER );
1747 if( ber_printf( ber, "{v}", attrs ) == -1 ) {
1748 fprintf( stderr, "postread attrs encode failed.\n" );
1749 exit( EXIT_FAILURE );
1752 err = ber_flatten2( ber, &c[i].ldctl_value, 0 );
1754 fprintf( stderr, "postread flatten failed (%d)\n", err );
1755 exit( EXIT_FAILURE );
1758 c[i].ldctl_oid = LDAP_CONTROL_POST_READ;
1759 c[i].ldctl_iscritical = postread > 1;
1763 if( attrs ) ldap_charray_free( attrs );
1766 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
1768 if ( chainingResolve > -1 ) {
1769 BerElementBuffer berbuf;
1770 BerElement *ber = (BerElement *)&berbuf;
1772 ber_init2( ber, NULL, LBER_USE_DER );
1774 err = ber_printf( ber, "{e" /* } */, chainingResolve );
1777 fprintf( stderr, _("Chaining behavior control encoding error!\n") );
1778 exit( EXIT_FAILURE );
1781 if ( chainingContinuation > -1 ) {
1782 err = ber_printf( ber, "e", chainingContinuation );
1785 fprintf( stderr, _("Chaining behavior control encoding error!\n") );
1786 exit( EXIT_FAILURE );
1790 err = ber_printf( ber, /* { */ "N}" );
1793 fprintf( stderr, _("Chaining behavior control encoding error!\n") );
1794 exit( EXIT_FAILURE );
1797 if ( ber_flatten2( ber, &c[i].ldctl_value, 0 ) == -1 ) {
1798 exit( EXIT_FAILURE );
1802 BER_BVZERO( &c[i].ldctl_value );
1805 c[i].ldctl_oid = LDAP_CONTROL_X_CHAINING_BEHAVIOR;
1806 c[i].ldctl_iscritical = chaining > 1;
1810 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
1812 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
1813 if ( sessionTracking ) {
1814 if ( stValue.bv_val == NULL && st_value( ld, &stValue ) ) {
1815 exit( EXIT_FAILURE );
1818 c[i].ldctl_oid = LDAP_CONTROL_X_SESSION_TRACKING;
1819 c[i].ldctl_iscritical = 0;
1820 ber_dupbv( &c[i].ldctl_value, &stValue );
1825 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
1828 ctrls[i++] = extra_c++;
1830 for ( count = 0; count < unknown_ctrls_num; count++ ) {
1831 ctrls[i++] = &unknown_ctrls[count];
1835 err = ldap_set_option( ld, LDAP_OPT_SERVER_CONTROLS, ctrls );
1837 if ( err != LDAP_OPT_SUCCESS ) {
1838 for ( j = 0; j < i; j++ ) {
1839 if ( ctrls[j]->ldctl_iscritical ) crit = 1;
1841 fprintf( stderr, "Could not set %scontrols\n",
1842 crit ? "critical " : "" );
1847 exit( EXIT_FAILURE );
1852 tool_check_abandon( LDAP *ld, int msgid )
1856 switch ( gotintr ) {
1858 rc = ldap_cancel_s( ld, msgid, NULL, NULL );
1859 fprintf( stderr, "got interrupt, cancel got %d: %s\n",
1860 rc, ldap_err2string( rc ) );
1864 rc = ldap_abandon_ext( ld, msgid, NULL, NULL );
1865 fprintf( stderr, "got interrupt, abandon got %d: %s\n",
1866 rc, ldap_err2string( rc ) );
1870 /* just unbind, ignoring the request */
1878 print_prepostread( LDAP *ld, LDAPControl *ctrl, struct berval *what)
1883 tool_write_ldif( LDIF_PUT_COMMENT, "==> ",
1884 what->bv_val, what->bv_len );
1885 ber = ber_init( &ctrl->ldctl_value );
1886 if ( ber == NULL ) {
1890 } else if ( ber_scanf( ber, "{m{" /*}}*/, &bv ) == LBER_ERROR ) {
1895 tool_write_ldif( LDIF_PUT_VALUE, "dn", bv.bv_val, bv.bv_len );
1897 while ( ber_scanf( ber, "{m" /*}*/, &bv ) != LBER_ERROR ) {
1899 BerVarray vals = NULL;
1902 if ( ber_scanf( ber, "[W]", &vals ) == LBER_ERROR ||
1912 str = malloc( bv.bv_len + STRLENOF(": ") + 1 );
1915 ptr = lutil_strncopy( ptr, bv.bv_val, bv.bv_len );
1916 ptr = lutil_strcopy( ptr, ": " );
1919 for ( i = 0; vals[ i ].bv_val != NULL; i++ ) {
1921 ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1922 ldif ? str : bv.bv_val, vals[ i ].bv_val, vals[ i ].bv_len );
1925 ber_bvarray_free( vals );
1926 if ( str ) free( str );
1930 if ( ber != NULL ) {
1934 tool_write_ldif( LDIF_PUT_COMMENT, "<== ",
1935 what->bv_val, what->bv_len );
1941 print_preread( LDAP *ld, LDAPControl *ctrl )
1943 static struct berval what = BER_BVC( "preread" );
1945 return print_prepostread( ld, ctrl, &what );
1949 print_postread( LDAP *ld, LDAPControl *ctrl )
1951 static struct berval what = BER_BVC( "postread" );
1953 return print_prepostread( ld, ctrl, &what );
1957 print_paged_results( LDAP *ld, LDAPControl *ctrl )
1961 /* note: pr_cookie is being malloced; it's freed
1962 * the next time the control is sent, but the last
1963 * time it's not; we don't care too much, because
1964 * the last time an empty value is returned... */
1965 if ( ldap_parse_pageresponse_control( ld, ctrl, &estimate, &pr_cookie )
1972 /* FIXME: check buffer overflow */
1973 char buf[ BUFSIZ ], *ptr = buf;
1975 if ( estimate > 0 ) {
1976 ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
1977 "estimate=%d", estimate );
1980 if ( pr_cookie.bv_len > 0 ) {
1983 bv.bv_len = LUTIL_BASE64_ENCODE_LEN(
1984 pr_cookie.bv_len ) + 1;
1985 bv.bv_val = ber_memalloc( bv.bv_len + 1 );
1987 bv.bv_len = lutil_b64_ntop(
1988 (unsigned char *) pr_cookie.bv_val,
1990 bv.bv_val, bv.bv_len );
1992 ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
1993 "%scookie=%s", ptr == buf ? "" : " ",
1996 ber_memfree( bv.bv_val );
1998 pr_morePagedResults = 1;
2001 ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
2002 "%scookie=", ptr == buf ? "" : " " );
2005 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
2006 ldif ? "pagedresults: " : "pagedresults",
2014 print_sss( LDAP *ld, LDAPControl *ctrl )
2020 rc = ldap_parse_sortresponse_control( ld, ctrl, &err, &attr );
2021 if ( rc == LDAP_SUCCESS ) {
2023 rc = snprintf( buf, sizeof(buf), "(%d) %s%s%s",
2024 err, ldap_err2string(err), attr ? " " : "", attr ? attr : "" );
2026 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
2027 ldif ? "sortResult: " : "sortResult", buf, rc );
2034 print_vlv( LDAP *ld, LDAPControl *ctrl )
2040 rc = ldap_parse_vlvresponse_control( ld, ctrl, &vlvPos, &vlvCount,
2041 &vlvContext, &err );
2042 if ( rc == LDAP_SUCCESS ) {
2045 if ( vlvContext && vlvContext->bv_len > 0 ) {
2046 bv.bv_len = LUTIL_BASE64_ENCODE_LEN(
2047 vlvContext->bv_len ) + 1;
2048 bv.bv_val = ber_memalloc( bv.bv_len + 1 );
2050 bv.bv_len = lutil_b64_ntop(
2051 (unsigned char *) vlvContext->bv_val,
2053 bv.bv_val, bv.bv_len );
2059 rc = snprintf( buf, sizeof(buf), "pos=%d count=%d context=%s (%d) %s",
2060 vlvPos, vlvCount, bv.bv_val,
2061 err, ldap_err2string(err));
2064 ber_memfree( bv.bv_val );
2066 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
2067 ldif ? "vlvResult" : "vlvResult", buf, rc );
2073 #ifdef LDAP_CONTROL_X_DEREF
2075 print_deref( LDAP *ld, LDAPControl *ctrl )
2077 LDAPDerefRes *drhead = NULL, *dr;
2080 rc = ldap_parse_derefresponse_control( ld, ctrl, &drhead );
2081 if ( rc != LDAP_SUCCESS ) {
2085 for ( dr = drhead; dr != NULL; dr = dr->next ) {
2090 len = strlen( dr->derefAttr ) + STRLENOF(": ");
2092 for ( dv = dr->attrVals; dv != NULL; dv = dv->next ) {
2093 if ( dv->vals != NULL ) {
2095 ber_len_t tlen = strlen(dv->type);
2097 for ( j = 0; dv->vals[ j ].bv_val != NULL; j++ ) {
2098 len += STRLENOF("<:=>;") + tlen + 4*((dv->vals[ j ].bv_len - 1)/3 + 1);
2102 len += dr->derefVal.bv_len + STRLENOF("\n");
2103 buf = ldap_memalloc( len + 1 );
2104 if ( buf == NULL ) {
2105 rc = LDAP_NO_MEMORY;
2110 ptr = lutil_strcopy( ptr, dr->derefAttr );
2113 for ( dv = dr->attrVals; dv != NULL; dv = dv->next ) {
2114 if ( dv->vals != NULL ) {
2116 for ( j = 0; dv->vals[ j ].bv_val != NULL; j++ ) {
2117 int k = ldif_is_not_printable( dv->vals[ j ].bv_val, dv->vals[ j ].bv_len );
2120 ptr = lutil_strcopy( ptr, dv->type );
2127 (unsigned char *) dv->vals[ j ].bv_val,
2128 dv->vals[ j ].bv_len,
2129 ptr, buf + len - ptr );
2134 ptr = lutil_memcopy( ptr, dv->vals[ j ].bv_val, dv->vals[ j ].bv_len );
2141 ptr = lutil_strncopy( ptr, dr->derefVal.bv_val, dr->derefVal.bv_len );
2144 assert( ptr <= buf + len );
2146 tool_write_ldif( LDIF_PUT_COMMENT, NULL, buf, ptr - buf);
2148 ldap_memfree( buf );
2154 ldap_derefresponse_free( drhead );
2160 #ifdef LDAP_CONTROL_X_WHATFAILED
2162 print_whatfailed( LDAP *ld, LDAPControl *ctrl )
2167 BerVarray bva = NULL;
2169 /* Create a BerElement from the berval returned in the control. */
2170 ber = ber_init( &ctrl->ldctl_value );
2172 if ( ber == NULL ) {
2173 return LDAP_NO_MEMORY;
2176 siz = sizeof(struct berval);
2177 tag = ber_scanf( ber, "[M]", &bva, &siz, 0 );
2178 if ( tag != LBER_ERROR ) {
2181 tool_write_ldif( LDIF_PUT_COMMENT, " what failed:", NULL, 0 );
2183 for ( i = 0; bva[i].bv_val != NULL; i++ ) {
2184 tool_write_ldif( LDIF_PUT_COMMENT, NULL, bva[i].bv_val, bva[i].bv_len );
2187 ldap_memfree( bva );
2197 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
2199 print_ppolicy( LDAP *ld, LDAPControl *ctrl )
2201 int expire = 0, grace = 0, rc;
2202 LDAPPasswordPolicyError pperr;
2204 rc = ldap_parse_passwordpolicy_control( ld, ctrl,
2205 &expire, &grace, &pperr );
2206 if ( rc == LDAP_SUCCESS ) {
2207 char buf[ BUFSIZ ], *ptr = buf;
2209 if ( expire != -1 ) {
2210 ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
2211 "expire=%d", expire );
2214 if ( grace != -1 ) {
2215 ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
2216 "%sgrace=%d", ptr == buf ? "" : " ", grace );
2219 if ( pperr != PP_noError ) {
2220 ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
2221 "%serror=%d (%s)", ptr == buf ? "" : " ",
2223 ldap_passwordpolicy_err2txt( pperr ) );
2226 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
2227 ldif ? "ppolicy: " : "ppolicy", buf, ptr - buf );
2234 void tool_print_ctrls(
2236 LDAPControl **ctrls )
2241 for ( i = 0; ctrls[i] != NULL; i++ ) {
2242 /* control: OID criticality base64value */
2243 struct berval b64 = BER_BVNULL;
2248 /* FIXME: there might be cases where a control has NULL OID;
2249 * this makes little sense, especially when returned by the
2250 * server, but libldap happily allows it */
2251 if ( ctrls[i]->ldctl_oid == NULL ) {
2256 len += strlen( ctrls[i]->ldctl_oid );
2258 /* add enough for space after OID and the critical value itself */
2259 len += ctrls[i]->ldctl_iscritical
2260 ? sizeof("true") : sizeof("false");
2262 /* convert to base64 */
2263 if ( !BER_BVISNULL( &ctrls[i]->ldctl_value ) ) {
2264 b64.bv_len = LUTIL_BASE64_ENCODE_LEN(
2265 ctrls[i]->ldctl_value.bv_len ) + 1;
2266 b64.bv_val = ber_memalloc( b64.bv_len + 1 );
2268 b64.bv_len = lutil_b64_ntop(
2269 (unsigned char *) ctrls[i]->ldctl_value.bv_val,
2270 ctrls[i]->ldctl_value.bv_len,
2271 b64.bv_val, b64.bv_len );
2275 len += 1 + b64.bv_len;
2278 ptr = str = malloc( len + 1 );
2280 ptr = lutil_strcopy( ptr, ": " );
2282 ptr = lutil_strcopy( ptr, ctrls[i]->ldctl_oid );
2283 ptr = lutil_strcopy( ptr, ctrls[i]->ldctl_iscritical
2284 ? " true" : " false" );
2287 ptr = lutil_strcopy( ptr, " " );
2288 ptr = lutil_strcopy( ptr, b64.bv_val );
2292 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
2293 "control", str, len );
2298 ber_memfree( b64.bv_val );
2301 /* known controls */
2302 for ( j = 0; tool_ctrl_response[j].oid != NULL; j++ ) {
2303 if ( strcmp( tool_ctrl_response[j].oid, ctrls[i]->ldctl_oid ) == 0 ) {
2304 if ( !tool_ctrl_response[j].mask & tool_type ) {
2305 /* this control should not appear
2306 * with this tool; warning? */
2312 if ( tool_ctrl_response[j].oid != NULL && tool_ctrl_response[j].func ) {
2313 (void)tool_ctrl_response[j].func( ld, ctrls[i] );
2319 tool_write_ldif( int type, char *name, char *value, ber_len_t vallen )
2323 if (( ldif = ldif_put_wrap( type, name, value, vallen, ldif_wrap )) == NULL ) {
2327 fputs( ldif, stdout );
2328 ber_memfree( ldif );
2334 tool_is_oid( const char *s )
2338 if ( !isdigit( (unsigned char) s[ 0 ] ) ) {
2342 for ( ; s[ 0 ]; s++ ) {
2343 if ( s[ 0 ] == '.' ) {
2344 if ( s[ 1 ] == '\0' ) {
2351 if ( !isdigit( (unsigned char) s[ 0 ] ) ) {
2355 if ( first == 1 && s[ 0 ] == '0' && s[ 1 ] != '.' ) {