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-2008 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;
73 char *ldaphost = NULL;
83 struct berval passwd = { 0, NULL };
85 #ifdef HAVE_CYRUS_SASL
86 unsigned sasl_flags = LDAP_SASL_AUTOMATIC;
87 char *sasl_realm = NULL;
88 char *sasl_authc_id = NULL;
89 char *sasl_authz_id = NULL;
90 char *sasl_mech = NULL;
91 char *sasl_secprops = NULL;
96 char *assertion = NULL;
97 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 */
125 LDAPControl *unknown_ctrls = NULL;
126 int unknown_ctrls_num = 0;
129 struct timeval nettimeout = { -1 , 0 };
131 typedef int (*print_ctrl_fn)( LDAP *ld, LDAPControl *ctrl );
133 static int print_preread( LDAP *ld, LDAPControl *ctrl );
134 static int print_postread( LDAP *ld, LDAPControl *ctrl );
135 static int print_paged_results( LDAP *ld, LDAPControl *ctrl );
136 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
137 static int print_ppolicy( LDAP *ld, LDAPControl *ctrl );
139 static int print_sss( LDAP *ld, LDAPControl *ctrl );
140 #ifdef LDAP_CONTROL_X_DEREF
141 static int print_deref( LDAP *ld, LDAPControl *ctrl );
143 #ifdef LDAP_CONTROL_X_WHATFAILED
144 static int print_whatfailed( LDAP *ld, LDAPControl *ctrl );
147 static struct tool_ctrls_t {
151 } tool_ctrl_response[] = {
152 { LDAP_CONTROL_PRE_READ, TOOL_ALL, print_preread },
153 { LDAP_CONTROL_POST_READ, TOOL_ALL, print_postread },
154 { LDAP_CONTROL_PAGEDRESULTS, TOOL_SEARCH, print_paged_results },
155 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
156 { LDAP_CONTROL_PASSWORDPOLICYRESPONSE, TOOL_ALL, print_ppolicy },
158 { LDAP_CONTROL_SORTRESPONSE, TOOL_SEARCH, print_sss },
159 #ifdef LDAP_CONTROL_X_DEREF
160 { LDAP_CONTROL_X_DEREF, TOOL_SEARCH, print_deref },
162 #ifdef LDAP_CONTROL_X_WHATFAILED
163 { LDAP_CONTROL_X_WHATFAILED, TOOL_ALL, print_whatfailed },
169 enum { Intr_None = 0, Intr_Abandon, Intr_Cancel, Intr_Ignore };
170 static volatile sig_atomic_t gotintr, abcan;
173 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
175 st_value( LDAP *ld, struct berval *value )
177 char *ip = NULL, *name = NULL;
178 struct berval id = { 0 };
179 char namebuf[ MAXHOSTNAMELEN ];
181 if ( gethostname( namebuf, sizeof( namebuf ) ) == 0 ) {
187 h = gethostbyname( name );
189 AC_MEMCPY( &addr, h->h_addr, sizeof( addr ) );
190 ip = inet_ntoa( addr );
194 #ifdef HAVE_CYRUS_SASL
195 if ( sasl_authz_id != NULL ) {
196 ber_str2bv( sasl_authz_id, 0, 0, &id );
198 } else if ( sasl_authc_id != NULL ) {
199 ber_str2bv( sasl_authc_id, 0, 0, &id );
202 #endif /* HAVE_CYRUS_SASL */
203 if ( binddn != NULL ) {
204 ber_str2bv( binddn, 0, 0, &id );
207 if ( ldap_create_session_tracking_value( ld,
208 ip, name, LDAP_CONTROL_X_SESSION_TRACKING_USERNAME,
211 fprintf( stderr, _("Session tracking control encoding error!\n") );
217 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
226 tool_init( tool_type_t type )
229 ldap_pvt_setlocale(LC_MESSAGES, "");
230 ldap_pvt_bindtextdomain(OPENLDAP_PACKAGE, LDAP_LOCALEDIR);
231 ldap_pvt_textdomain(OPENLDAP_PACKAGE);
237 #ifdef HAVE_CYRUS_SASL
241 ldap_pvt_tls_destroy();
244 if ( ldapuri != NULL ) {
245 ber_memfree( ldapuri );
249 if ( pr_cookie.bv_val != NULL ) {
250 ber_memfree( pr_cookie.bv_val );
251 pr_cookie.bv_val = NULL;
252 pr_cookie.bv_len = 0;
257 tool_common_usage( void )
259 static const char *const descriptions[] = {
260 N_(" -c continuous operation mode (do not stop on errors)\n"),
261 N_(" -d level set LDAP debugging level to `level'\n"),
262 N_(" -D binddn bind DN\n"),
263 N_(" -e [!]<ext>[=<extparam>] general extensions (! indicates criticality)\n")
264 N_(" [!]assert=<filter> (RFC 4528; a RFC 4515 Filter string)\n")
265 N_(" [!]authzid=<authzid> (RFC 4370; \"dn:<dn>\" or \"u:<user>\")\n")
266 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
268 /* non-advertized support for proxyDN */
269 N_(" [!]proxydn=<dn> (a RFC 4514 DN string)\n")
272 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
273 N_(" [!]chaining[=<resolveBehavior>[/<continuationBehavior>]]\n")
274 N_(" one of \"chainingPreferred\", \"chainingRequired\",\n")
275 N_(" \"referralsPreferred\", \"referralsRequired\"\n")
276 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
277 N_(" [!]manageDSAit (RFC 3296)\n")
279 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
282 N_(" [!]postread[=<attrs>] (RFC 4527; comma-separated attr list)\n")
283 N_(" [!]preread[=<attrs>] (RFC 4527; comma-separated attr list)\n")
285 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
286 N_(" [!]sessiontracking\n")
287 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
288 N_(" abandon, cancel, ignore (SIGINT sends abandon/cancel,\n"
289 " or ignores response; if critical, doesn't wait for SIGINT.\n"
290 " not really controls)\n")
291 N_(" -f file read operations from `file'\n"),
292 N_(" -h host LDAP server\n"),
293 N_(" -H URI LDAP Uniform Resource Identifier(s)\n"),
294 N_(" -I use SASL Interactive mode\n"),
295 N_(" -M enable Manage DSA IT control (-MM to make critical)\n"),
296 N_(" -n show what would be done but don't actually do it\n"),
297 N_(" -N do not use reverse DNS to canonicalize SASL host name\n"),
298 N_(" -O props SASL security properties\n"),
299 N_(" -o <opt>[=<optparam] general options\n"),
300 N_(" nettimeout=<timeout> (in seconds, or \"none\" or \"max\")\n"),
301 N_(" -p port port on LDAP server\n"),
302 N_(" -P version protocol version (default: 3)\n"),
303 N_(" -Q use SASL Quiet mode\n"),
304 N_(" -R realm SASL realm\n"),
305 N_(" -U authcid SASL authentication identity\n"),
306 N_(" -v run in verbose mode (diagnostics to standard output)\n"),
307 N_(" -V print version info (-VV only)\n"),
308 N_(" -w passwd bind password (for simple authentication)\n"),
309 N_(" -W prompt for bind password\n"),
310 N_(" -x Simple authentication\n"),
311 N_(" -X authzid SASL authorization identity (\"dn:<dn>\" or \"u:<user>\")\n"),
312 N_(" -y file Read password from file\n"),
313 N_(" -Y mech SASL mechanism\n"),
314 N_(" -Z Start TLS request (-ZZ to require successful response)\n"),
317 const char *const *cpp;
319 fputs( _("Common options:\n"), stderr );
320 for( cpp = descriptions; *cpp != NULL; cpp++ ) {
321 if( strchr( options, (*cpp)[3] ) || (*cpp)[3] == ' ' ) {
322 fputs( _(*cpp), stderr );
335 fprintf( stderr, "%s: %s (%d)%s\n",
336 func, ldap_err2string( err ), err, extra ? extra : "" );
338 if ( matched && *matched ) {
339 fprintf( stderr, _("\tmatched DN: %s\n"), matched );
342 if ( info && *info ) {
343 fprintf( stderr, _("\tadditional info: %s\n"), info );
346 if ( refs && *refs ) {
348 fprintf( stderr, _("\treferrals:\n") );
349 for( i=0; refs[i]; i++ ) {
350 fprintf( stderr, "\t\t%s\n", refs[i] );
357 tool_args( int argc, char **argv )
361 while (( i = getopt( argc, argv, options )) != EOF ) {
363 char *control, *cvalue, *next;
365 case 'c': /* continuous operation mode */
372 ival = strtol( optarg, &next, 10 );
373 if (next == NULL || next[0] != '\0') {
374 fprintf( stderr, "%s: unable to parse debug value \"%s\"\n", prog, optarg);
379 case 'D': /* bind DN */
380 if( binddn != NULL ) {
381 fprintf( stderr, "%s: -D previously specified\n", prog );
382 exit( EXIT_FAILURE );
384 binddn = ber_strdup( optarg );
386 case 'e': /* general extensions (controls and such) */
387 /* should be extended to support comma separated list of
388 * [!]key[=value] parameters, e.g. -e !foo,bar=567
393 while ( optarg[0] == '!' ) {
398 control = ber_strdup( optarg );
399 if ( (cvalue = strchr( control, '=' )) != NULL ) {
403 if ( strcasecmp( control, "assert" ) == 0 ) {
405 fprintf( stderr, "assert control previously specified\n");
406 exit( EXIT_FAILURE );
408 if( cvalue == NULL ) {
409 fprintf( stderr, "assert: control value expected\n" );
413 assertctl = 1 + crit;
415 assert( assertion == NULL );
418 } else if ( strcasecmp( control, "authzid" ) == 0 ) {
419 if( authzid != NULL ) {
420 fprintf( stderr, "authzid control previously specified\n");
421 exit( EXIT_FAILURE );
423 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
424 if( proxydn != NULL ) {
425 fprintf( stderr, "authzid control incompatible with proxydn\n");
426 exit( EXIT_FAILURE );
428 #endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
429 if( cvalue == NULL ) {
430 fprintf( stderr, "authzid: control value expected\n" );
434 fprintf( stderr, "authzid: must be marked critical\n" );
436 } else if ( crit > 1 ) {
437 /* purposely flag proxied authorization
438 * as non-critical, to test DSA */
442 assert( authzid == NULL );
445 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
446 } else if ( strcasecmp( control, "proxydn" ) == 0 ) {
447 if( proxydn != NULL ) {
448 fprintf( stderr, "proxydn control previously specified\n");
449 exit( EXIT_FAILURE );
451 if( authzid != NULL ) {
452 fprintf( stderr, "proxydn control incompatible with authzid\n");
453 exit( EXIT_FAILURE );
455 if( cvalue == NULL ) {
456 fprintf( stderr, "proxydn: control value expected\n" );
460 fprintf( stderr, "proxydn: must be marked critical\n" );
462 } else if ( crit > 1 ) {
463 /* purposely flag proxied authorization
464 * as non-critical, to test DSA */
468 assert( proxydn == NULL );
470 #endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
472 } else if ( ( strcasecmp( control, "relax" ) == 0 ) ||
473 ( strcasecmp( control, "manageDIT" ) == 0 ) )
477 "relax control previously specified\n");
478 exit( EXIT_FAILURE );
480 if( cvalue != NULL ) {
482 "relax: no control value expected\n" );
486 manageDIT = 1 + crit;
488 } else if ( strcasecmp( control, "manageDSAit" ) == 0 ) {
491 "manageDSAit control previously specified\n");
492 exit( EXIT_FAILURE );
494 if( cvalue != NULL ) {
496 "manageDSAit: no control value expected\n" );
500 manageDSAit = 1 + crit;
502 } else if ( strcasecmp( control, "noop" ) == 0 ) {
504 fprintf( stderr, "noop control previously specified\n");
505 exit( EXIT_FAILURE );
507 if( cvalue != NULL ) {
508 fprintf( stderr, "noop: no control value expected\n" );
514 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
515 } else if ( strcasecmp( control, "ppolicy" ) == 0 ) {
517 fprintf( stderr, "ppolicy control previously specified\n");
518 exit( EXIT_FAILURE );
520 if( cvalue != NULL ) {
521 fprintf( stderr, "ppolicy: no control value expected\n" );
525 fprintf( stderr, "ppolicy: critical flag not allowed\n" );
532 } else if ( strcasecmp( control, "preread" ) == 0 ) {
534 fprintf( stderr, "preread control previously specified\n");
535 exit( EXIT_FAILURE );
539 preread_attrs = cvalue;
541 } else if ( strcasecmp( control, "postread" ) == 0 ) {
543 fprintf( stderr, "postread control previously specified\n");
544 exit( EXIT_FAILURE );
548 postread_attrs = cvalue;
550 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
551 } else if ( strcasecmp( control, "chaining" ) == 0 ) {
553 fprintf( stderr, "chaining control previously specified\n");
554 exit( EXIT_FAILURE );
559 if ( cvalue != NULL ) {
562 continuation = strchr( cvalue, '/' );
563 if ( continuation ) {
564 /* FIXME: this makes sense only in searches */
565 *continuation++ = '\0';
566 if ( strcasecmp( continuation, "chainingPreferred" ) == 0 ) {
567 chainingContinuation = LDAP_CHAINING_PREFERRED;
568 } else if ( strcasecmp( continuation, "chainingRequired" ) == 0 ) {
569 chainingContinuation = LDAP_CHAINING_REQUIRED;
570 } else if ( strcasecmp( continuation, "referralsPreferred" ) == 0 ) {
571 chainingContinuation = LDAP_REFERRALS_PREFERRED;
572 } else if ( strcasecmp( continuation, "referralsRequired" ) == 0 ) {
573 chainingContinuation = LDAP_REFERRALS_REQUIRED;
576 "chaining behavior control "
577 "continuation value \"%s\" invalid\n",
579 exit( EXIT_FAILURE );
583 if ( strcasecmp( cvalue, "chainingPreferred" ) == 0 ) {
584 chainingResolve = LDAP_CHAINING_PREFERRED;
585 } else if ( strcasecmp( cvalue, "chainingRequired" ) == 0 ) {
586 chainingResolve = LDAP_CHAINING_REQUIRED;
587 } else if ( strcasecmp( cvalue, "referralsPreferred" ) == 0 ) {
588 chainingResolve = LDAP_REFERRALS_PREFERRED;
589 } else if ( strcasecmp( cvalue, "referralsRequired" ) == 0 ) {
590 chainingResolve = LDAP_REFERRALS_REQUIRED;
593 "chaining behavior control "
594 "resolve value \"%s\" invalid\n",
596 exit( EXIT_FAILURE );
599 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
601 /* this shouldn't go here, really; but it's a feature... */
602 } else if ( strcasecmp( control, "abandon" ) == 0 ) {
603 abcan = Intr_Abandon;
608 } else if ( strcasecmp( control, "cancel" ) == 0 ) {
614 } else if ( strcasecmp( control, "ignore" ) == 0 ) {
620 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
621 } else if ( strcasecmp( control, "sessiontracking" ) == 0 ) {
622 if ( sessionTracking ) {
623 fprintf( stderr, "%s: session tracking can be only specified once\n", prog );
624 exit( EXIT_FAILURE );
627 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
629 } else if ( tool_is_oid( control ) ) {
630 LDAPControl *tmpctrls, ctrl;
632 if ( unknown_ctrls != NULL ) {
634 for ( i = 0; unknown_ctrls[ i ].ldctl_oid != NULL; i++ ) {
635 if ( strcmp( control, unknown_ctrls[ i ].ldctl_oid ) == 0 ) {
636 fprintf( stderr, "%s control previously specified\n", control );
637 exit( EXIT_FAILURE );
642 tmpctrls = (LDAPControl *)realloc( unknown_ctrls,
643 (unknown_ctrls_num + 1)*sizeof( LDAPControl ) );
644 if ( tmpctrls == NULL ) {
645 fprintf( stderr, "%s: no memory?\n", prog );
646 exit( EXIT_FAILURE );
648 unknown_ctrls = tmpctrls;
649 ctrl.ldctl_oid = control;
650 ctrl.ldctl_value.bv_val = NULL;
651 ctrl.ldctl_value.bv_len = 0;
652 ctrl.ldctl_iscritical = crit;
654 if ( cvalue != NULL ) {
656 size_t len = strlen( cvalue );
659 bv.bv_len = LUTIL_BASE64_DECODE_LEN( len );
660 bv.bv_val = ber_memalloc( bv.bv_len + 1 );
662 retcode = lutil_b64_pton( cvalue,
663 (unsigned char *)bv.bv_val,
666 if ( retcode == -1 || (unsigned) retcode > bv.bv_len ) {
667 fprintf( stderr, "Unable to parse value of general control %s\n",
673 ctrl.ldctl_value = bv;
676 unknown_ctrls[ unknown_ctrls_num ] = ctrl;
680 fprintf( stderr, "Invalid general control name: %s\n",
685 case 'f': /* read from file */
686 if( infile != NULL ) {
687 fprintf( stderr, "%s: -f previously specified\n", prog );
688 exit( EXIT_FAILURE );
690 infile = ber_strdup( optarg );
692 case 'h': /* ldap host */
693 if( ldaphost != NULL ) {
694 fprintf( stderr, "%s: -h previously specified\n", prog );
695 exit( EXIT_FAILURE );
697 ldaphost = ber_strdup( optarg );
699 case 'H': /* ldap URI */
700 if( ldapuri != NULL ) {
701 fprintf( stderr, "%s: -H previously specified\n", prog );
702 exit( EXIT_FAILURE );
704 ldapuri = ber_strdup( optarg );
707 #ifdef HAVE_CYRUS_SASL
708 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
709 fprintf( stderr, "%s: incompatible previous "
710 "authentication choice\n",
712 exit( EXIT_FAILURE );
714 authmethod = LDAP_AUTH_SASL;
715 sasl_flags = LDAP_SASL_INTERACTIVE;
718 fprintf( stderr, "%s: was not compiled with SASL support\n",
720 exit( EXIT_FAILURE );
723 /* enable Manage DSA IT */
726 case 'n': /* print operations, don't actually do them */
733 control = ber_strdup( optarg );
734 if ( (cvalue = strchr( control, '=' )) != NULL ) {
738 if ( strcasecmp( control, "nettimeout" ) == 0 ) {
739 if( nettimeout.tv_sec != -1 ) {
740 fprintf( stderr, "nettimeout option previously specified\n");
741 exit( EXIT_FAILURE );
743 if( cvalue == NULL || cvalue[0] == '\0' ) {
744 fprintf( stderr, "nettimeout: option value expected\n" );
747 if ( strcasecmp( cvalue, "none" ) == 0 ) {
748 nettimeout.tv_sec = 0;
749 } else if ( strcasecmp( cvalue, "max" ) == 0 ) {
750 nettimeout.tv_sec = LDAP_MAXINT;
752 ival = strtol( cvalue, &next, 10 );
753 if ( next == NULL || next[0] != '\0' ) {
755 _("Unable to parse network timeout \"%s\"\n"), cvalue );
756 exit( EXIT_FAILURE );
758 nettimeout.tv_sec = ival;
760 if( nettimeout.tv_sec < 0 || nettimeout.tv_sec > LDAP_MAXINT ) {
761 fprintf( stderr, _("%s: invalid network timeout (%ld) specified\n"),
762 prog, (long)nettimeout.tv_sec );
763 exit( EXIT_FAILURE );
766 fprintf( stderr, "Invalid general option name: %s\n",
772 #ifdef HAVE_CYRUS_SASL
773 if( sasl_secprops != NULL ) {
774 fprintf( stderr, "%s: -O previously specified\n", prog );
775 exit( EXIT_FAILURE );
777 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
778 fprintf( stderr, "%s: incompatible previous "
779 "authentication choice\n", prog );
780 exit( EXIT_FAILURE );
782 authmethod = LDAP_AUTH_SASL;
783 sasl_secprops = ber_strdup( optarg );
785 fprintf( stderr, "%s: not compiled with SASL support\n", prog );
786 exit( EXIT_FAILURE );
791 fprintf( stderr, "%s: -p previously specified\n", prog );
792 exit( EXIT_FAILURE );
794 ival = strtol( optarg, &next, 10 );
795 if ( next == NULL || next[0] != '\0' ) {
796 fprintf( stderr, "%s: unable to parse port number \"%s\"\n", prog, optarg );
797 exit( EXIT_FAILURE );
802 ival = strtol( optarg, &next, 10 );
803 if ( next == NULL || next[0] != '\0' ) {
804 fprintf( stderr, "%s: unable to parse protocol version \"%s\"\n", prog, optarg );
805 exit( EXIT_FAILURE );
809 if( protocol == LDAP_VERSION3 ) {
810 fprintf( stderr, "%s: -P 2 incompatible with version %d\n",
812 exit( EXIT_FAILURE );
814 protocol = LDAP_VERSION2;
817 if( protocol == LDAP_VERSION2 ) {
818 fprintf( stderr, "%s: -P 2 incompatible with version %d\n",
820 exit( EXIT_FAILURE );
822 protocol = LDAP_VERSION3;
825 fprintf( stderr, "%s: protocol version should be 2 or 3\n",
831 #ifdef HAVE_CYRUS_SASL
832 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
833 fprintf( stderr, "%s: incompatible previous "
834 "authentication choice\n",
836 exit( EXIT_FAILURE );
838 authmethod = LDAP_AUTH_SASL;
839 sasl_flags = LDAP_SASL_QUIET;
842 fprintf( stderr, "%s: not compiled with SASL support\n",
844 exit( EXIT_FAILURE );
847 #ifdef HAVE_CYRUS_SASL
848 if( sasl_realm != NULL ) {
849 fprintf( stderr, "%s: -R previously specified\n", prog );
850 exit( EXIT_FAILURE );
852 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
853 fprintf( stderr, "%s: incompatible previous "
854 "authentication choice\n",
856 exit( EXIT_FAILURE );
858 authmethod = LDAP_AUTH_SASL;
859 sasl_realm = ber_strdup( optarg );
861 fprintf( stderr, "%s: not compiled with SASL support\n",
863 exit( EXIT_FAILURE );
867 #ifdef HAVE_CYRUS_SASL
868 if( sasl_authc_id != NULL ) {
869 fprintf( stderr, "%s: -U previously specified\n", prog );
870 exit( EXIT_FAILURE );
872 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
873 fprintf( stderr, "%s: incompatible previous "
874 "authentication choice\n",
876 exit( EXIT_FAILURE );
878 authmethod = LDAP_AUTH_SASL;
879 sasl_authc_id = ber_strdup( optarg );
881 fprintf( stderr, "%s: not compiled with SASL support\n",
883 exit( EXIT_FAILURE );
886 case 'v': /* verbose mode */
889 case 'V': /* version */
892 case 'w': /* password */
893 passwd.bv_val = ber_strdup( optarg );
897 for( p = optarg; *p != '\0'; p++ ) {
901 passwd.bv_len = strlen( passwd.bv_val );
910 #ifdef HAVE_CYRUS_SASL
911 if( sasl_mech != NULL ) {
912 fprintf( stderr, "%s: -Y previously specified\n", prog );
913 exit( EXIT_FAILURE );
915 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
917 "%s: incompatible with authentication choice\n", prog );
918 exit( EXIT_FAILURE );
920 authmethod = LDAP_AUTH_SASL;
921 sasl_mech = ber_strdup( optarg );
923 fprintf( stderr, "%s: not compiled with SASL support\n", prog );
924 exit( EXIT_FAILURE );
928 if( authmethod != -1 && authmethod != LDAP_AUTH_SIMPLE ) {
929 fprintf( stderr, "%s: incompatible with previous "
930 "authentication choice\n", prog );
931 exit( EXIT_FAILURE );
933 authmethod = LDAP_AUTH_SIMPLE;
936 #ifdef HAVE_CYRUS_SASL
937 if( sasl_authz_id != NULL ) {
938 fprintf( stderr, "%s: -X previously specified\n", prog );
939 exit( EXIT_FAILURE );
941 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
942 fprintf( stderr, "%s: -X incompatible with "
943 "authentication choice\n", prog );
944 exit( EXIT_FAILURE );
946 authmethod = LDAP_AUTH_SASL;
947 sasl_authz_id = ber_strdup( optarg );
949 fprintf( stderr, "%s: not compiled with SASL support\n", prog );
950 exit( EXIT_FAILURE );
957 fprintf( stderr, "%s: not compiled with TLS support\n", prog );
958 exit( EXIT_FAILURE );
962 if( handle_private_option( i ) ) break;
963 fprintf( stderr, "%s: unrecognized option -%c\n",
970 /* prevent bad linking */
972 api.ldapai_info_version = LDAP_API_INFO_VERSION;
974 if ( ldap_get_option(NULL, LDAP_OPT_API_INFO, &api)
975 != LDAP_OPT_SUCCESS )
977 fprintf( stderr, "%s: ldap_get_option(API_INFO) failed\n", prog );
978 exit( EXIT_FAILURE );
981 if (api.ldapai_info_version != LDAP_API_INFO_VERSION) {
982 fprintf( stderr, "LDAP APIInfo version mismatch: "
983 "library %d, header %d\n",
984 api.ldapai_info_version, LDAP_API_INFO_VERSION );
985 exit( EXIT_FAILURE );
988 if( api.ldapai_api_version != LDAP_API_VERSION ) {
989 fprintf( stderr, "LDAP API version mismatch: "
990 "library %d, header %d\n",
991 api.ldapai_api_version, LDAP_API_VERSION );
992 exit( EXIT_FAILURE );
995 if( strcmp(api.ldapai_vendor_name, LDAP_VENDOR_NAME ) != 0 ) {
996 fprintf( stderr, "LDAP vendor name mismatch: "
997 "library %s, header %s\n",
998 api.ldapai_vendor_name, LDAP_VENDOR_NAME );
999 exit( EXIT_FAILURE );
1002 if( api.ldapai_vendor_version != LDAP_VENDOR_VERSION ) {
1003 fprintf( stderr, "LDAP vendor version mismatch: "
1004 "library %d, header %d\n",
1005 api.ldapai_vendor_version, LDAP_VENDOR_VERSION );
1006 exit( EXIT_FAILURE );
1010 fprintf( stderr, "%s: %s\t(LDAP library: %s %d)\n",
1012 LDAP_VENDOR_NAME, LDAP_VENDOR_VERSION );
1013 if (version > 1) exit( EXIT_SUCCESS );
1016 ldap_memfree( api.ldapai_vendor_name );
1017 ber_memvfree( (void **)api.ldapai_extensions );
1021 protocol = LDAP_VERSION3;
1023 if (authmethod == -1 && protocol > LDAP_VERSION2) {
1024 #ifdef HAVE_CYRUS_SASL
1025 if ( binddn != NULL ) {
1026 authmethod = LDAP_AUTH_SIMPLE;
1028 authmethod = LDAP_AUTH_SASL;
1031 authmethod = LDAP_AUTH_SIMPLE;
1035 if( ldapuri == NULL ) {
1036 if( ldapport && ( ldaphost == NULL )) {
1037 fprintf( stderr, "%s: -p without -h is invalid.\n", prog );
1038 exit( EXIT_FAILURE );
1041 if( ldaphost != NULL ) {
1042 fprintf( stderr, "%s: -H incompatible with -h\n", prog );
1043 exit( EXIT_FAILURE );
1046 fprintf( stderr, "%s: -H incompatible with -p\n", prog );
1047 exit( EXIT_FAILURE );
1051 if( protocol == LDAP_VERSION2 ) {
1052 if( assertctl || authzid || manageDIT || manageDSAit ||
1053 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
1055 #endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
1056 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
1059 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
1061 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
1062 noop || ppolicy || preread || postread )
1064 fprintf( stderr, "%s: -e/-M incompatible with LDAPv2\n", prog );
1065 exit( EXIT_FAILURE );
1069 fprintf( stderr, "%s: -Z incompatible with LDAPv2\n", prog );
1070 exit( EXIT_FAILURE );
1073 #ifdef HAVE_CYRUS_SASL
1074 if( authmethod == LDAP_AUTH_SASL ) {
1075 fprintf( stderr, "%s: -[IOQRUXY] incompatible with LDAPv2\n",
1077 exit( EXIT_FAILURE );
1085 tool_conn_setup( int dont, void (*private_setup)( LDAP * ) )
1090 if( ber_set_option( NULL, LBER_OPT_DEBUG_LEVEL, &debug )
1091 != LBER_OPT_SUCCESS )
1094 "Could not set LBER_OPT_DEBUG_LEVEL %d\n", debug );
1096 if( ldap_set_option( NULL, LDAP_OPT_DEBUG_LEVEL, &debug )
1097 != LDAP_OPT_SUCCESS )
1100 "Could not set LDAP_OPT_DEBUG_LEVEL %d\n", debug );
1105 (void) SIGNAL( SIGPIPE, SIG_IGN );
1109 SIGNAL( SIGINT, do_sig );
1115 if( ( ldaphost != NULL || ldapport ) && ( ldapuri == NULL ) ) {
1118 memset( &url, 0, sizeof(url));
1120 url.lud_scheme = "ldap";
1121 url.lud_host = ldaphost;
1122 url.lud_port = ldapport;
1123 url.lud_scope = LDAP_SCOPE_DEFAULT;
1125 ldapuri = ldap_url_desc2str( &url );
1127 } else if ( ldapuri != NULL ) {
1128 LDAPURLDesc *ludlist, **ludp;
1132 rc = ldap_url_parselist( &ludlist, ldapuri );
1133 if ( rc != LDAP_URL_SUCCESS ) {
1135 "Could not parse LDAP URI(s)=%s (%d)\n",
1137 exit( EXIT_FAILURE );
1140 for ( ludp = &ludlist; *ludp != NULL; ) {
1141 LDAPURLDesc *lud = *ludp;
1144 if ( lud->lud_dn != NULL && lud->lud_dn[ 0 ] != '\0' &&
1145 ( lud->lud_host == NULL || lud->lud_host[0] == '\0' ) )
1147 /* if no host but a DN is provided,
1148 * use DNS SRV to gather the host list
1149 * and turn it into a list of URIs
1150 * using the scheme provided */
1151 char *domain = NULL,
1155 len_proto = strlen( lud->lud_scheme );
1157 if ( ldap_dn2domain( lud->lud_dn, &domain )
1161 "DNS SRV: Could not turn "
1162 "DN=\"%s\" into a domain\n",
1167 rc = ldap_domain2hostlist( domain, &hostlist );
1170 "DNS SRV: Could not turn "
1171 "domain=%s into a hostlist\n",
1176 hosts = ldap_str2charray( hostlist, " " );
1177 if ( hosts == NULL ) {
1179 "DNS SRV: Could not parse "
1180 "hostlist=\"%s\"\n",
1185 for ( i = 0; hosts[ i ] != NULL; i++ )
1188 tmp = (char **)realloc( urls, sizeof( char * ) * ( nurls + i + 1 ) );
1189 if ( tmp == NULL ) {
1191 "DNS SRV: out of memory?\n" );
1195 urls[ nurls ] = NULL;
1197 for ( i = 0; hosts[ i ] != NULL; i++ ) {
1198 size_t len = len_proto
1200 + strlen( hosts[ i ] )
1203 urls[ nurls + i + 1 ] = NULL;
1204 urls[ nurls + i ] = (char *)malloc( sizeof( char ) * len );
1205 if ( urls[ nurls + i ] == NULL ) {
1207 "DNS SRV: out of memory?\n" );
1211 snprintf( urls[ nurls + i ], len, "%s://%s",
1212 lud->lud_scheme, hosts[ i ] );
1217 ber_memvfree( (void **)hosts );
1218 ber_memfree( hostlist );
1219 ber_memfree( domain );
1222 tmp = (char **)realloc( urls, sizeof( char * ) * ( nurls + 2 ) );
1223 if ( tmp == NULL ) {
1225 "DNS SRV: out of memory?\n" );
1229 urls[ nurls + 1 ] = NULL;
1231 urls[ nurls ] = ldap_url_desc2str( lud );
1232 if ( urls[ nurls ] == NULL ) {
1234 "DNS SRV: out of memory?\n" );
1240 *ludp = lud->lud_next;
1242 lud->lud_next = NULL;
1243 ldap_free_urldesc( lud );
1246 if ( ludlist != NULL ) {
1247 ldap_free_urllist( ludlist );
1248 exit( EXIT_FAILURE );
1250 } else if ( urls == NULL ) {
1251 exit( EXIT_FAILURE );
1254 ldap_memfree( ldapuri );
1255 ldapuri = ldap_charray2str( urls, " " );
1256 ber_memvfree( (void **)urls );
1260 fprintf( stderr, "ldap_initialize( %s )\n",
1261 ldapuri != NULL ? ldapuri : "<DEFAULT>" );
1263 rc = ldap_initialize( &ld, ldapuri );
1264 if( rc != LDAP_SUCCESS ) {
1266 "Could not create LDAP session handle for URI=%s (%d): %s\n",
1267 ldapuri, rc, ldap_err2string(rc) );
1268 exit( EXIT_FAILURE );
1271 if( private_setup ) private_setup( ld );
1274 if( ldap_set_option( ld, LDAP_OPT_REFERRALS,
1275 referrals ? LDAP_OPT_ON : LDAP_OPT_OFF ) != LDAP_OPT_SUCCESS )
1277 fprintf( stderr, "Could not set LDAP_OPT_REFERRALS %s\n",
1278 referrals ? "on" : "off" );
1279 exit( EXIT_FAILURE );
1283 if( ldap_set_option( ld, LDAP_OPT_X_SASL_NOCANON,
1284 nocanon ? LDAP_OPT_ON : LDAP_OPT_OFF ) != LDAP_OPT_SUCCESS )
1286 fprintf( stderr, "Could not set LDAP_OPT_X_SASL_NOCANON %s\n",
1287 nocanon ? "on" : "off" );
1288 exit( EXIT_FAILURE );
1290 if( ldap_set_option( ld, LDAP_OPT_PROTOCOL_VERSION, &protocol )
1291 != LDAP_OPT_SUCCESS )
1293 fprintf( stderr, "Could not set LDAP_OPT_PROTOCOL_VERSION %d\n",
1295 exit( EXIT_FAILURE );
1299 rc = ldap_start_tls_s( ld, NULL, NULL );
1300 if ( rc != LDAP_SUCCESS ) {
1301 tool_perror( "ldap_start_tls", rc, NULL, NULL, NULL, NULL );
1302 if ( use_tls > 1 ) {
1303 exit( EXIT_FAILURE );
1308 if ( nettimeout.tv_sec > 0 ) {
1309 if ( ldap_set_option( ld, LDAP_OPT_NETWORK_TIMEOUT, (void *) &nettimeout )
1310 != LDAP_OPT_SUCCESS )
1312 fprintf( stderr, "Could not set LDAP_OPT_NETWORK_TIMEOUT %ld\n",
1313 (long)nettimeout.tv_sec );
1314 exit( EXIT_FAILURE );
1324 tool_bind( LDAP *ld )
1326 LDAPControl **sctrlsp = NULL;
1327 LDAPControl *sctrls[3];
1328 LDAPControl sctrl[3];
1331 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
1334 c.ldctl_oid = LDAP_CONTROL_PASSWORDPOLICYREQUEST;
1335 c.ldctl_value.bv_val = NULL;
1336 c.ldctl_value.bv_len = 0;
1337 c.ldctl_iscritical = 0;
1339 sctrls[nsctrls] = &sctrl[nsctrls];
1340 sctrls[++nsctrls] = NULL;
1344 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
1345 if ( sessionTracking ) {
1348 if (stValue.bv_val == NULL && st_value( ld, &stValue ) ) {
1349 exit( EXIT_FAILURE );
1352 c.ldctl_oid = LDAP_CONTROL_X_SESSION_TRACKING;
1353 c.ldctl_iscritical = 0;
1354 ber_dupbv( &c.ldctl_value, &stValue );
1357 sctrls[nsctrls] = &sctrl[nsctrls];
1358 sctrls[++nsctrls] = NULL;
1360 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
1366 assert( nsctrls < (int) (sizeof(sctrls)/sizeof(sctrls[0])) );
1368 if ( authmethod == LDAP_AUTH_SASL ) {
1369 #ifdef HAVE_CYRUS_SASL
1373 if( sasl_secprops != NULL ) {
1374 rc = ldap_set_option( ld, LDAP_OPT_X_SASL_SECPROPS,
1375 (void *) sasl_secprops );
1377 if( rc != LDAP_OPT_SUCCESS ) {
1379 "Could not set LDAP_OPT_X_SASL_SECPROPS: %s\n",
1381 exit( LDAP_LOCAL_ERROR );
1385 defaults = lutil_sasl_defaults( ld,
1392 rc = ldap_sasl_interactive_bind_s( ld, binddn, sasl_mech,
1394 NULL, sasl_flags, lutil_sasl_interact, defaults );
1396 lutil_sasl_freedefs( defaults );
1397 if( rc != LDAP_SUCCESS ) {
1398 tool_perror( "ldap_sasl_interactive_bind_s",
1399 rc, NULL, NULL, NULL, NULL );
1403 fprintf( stderr, "%s: not compiled with SASL support\n", prog );
1404 exit( LDAP_NOT_SUPPORTED );
1408 LDAPMessage *result;
1409 LDAPControl **ctrls;
1411 char *matched = NULL;
1419 rc = ldap_sasl_bind( ld, binddn, LDAP_SASL_SIMPLE, &passwd,
1420 sctrlsp, NULL, &msgid );
1421 if ( msgid == -1 ) {
1422 tool_perror( "ldap_sasl_bind(SIMPLE)", rc,
1423 NULL, NULL, NULL, NULL );
1428 if ( ldap_result( ld, msgid, LDAP_MSG_ALL, NULL, &result ) == -1 ) {
1429 tool_perror( "ldap_result", -1, NULL, NULL, NULL, NULL );
1430 exit( LDAP_LOCAL_ERROR );
1433 rc = ldap_parse_result( ld, result, &err, &matched, &info, &refs,
1435 if ( rc != LDAP_SUCCESS ) {
1436 tool_perror( "ldap_bind parse result", rc, NULL, matched, info, refs );
1437 exit( LDAP_LOCAL_ERROR );
1440 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
1441 if ( ctrls && ppolicy ) {
1443 int expire, grace, len = 0;
1444 LDAPPasswordPolicyError pErr = -1;
1446 ctrl = ldap_control_find( LDAP_CONTROL_PASSWORDPOLICYRESPONSE,
1449 if ( ctrl && ldap_parse_passwordpolicy_control( ld, ctrl,
1450 &expire, &grace, &pErr ) == LDAP_SUCCESS )
1452 if ( pErr != PP_noError ){
1455 strcpy( msgbuf+2, ldap_passwordpolicy_err2txt( pErr ));
1456 len = strlen( msgbuf );
1458 if ( expire >= 0 ) {
1459 sprintf( msgbuf+len,
1460 " (Password expires in %d seconds)",
1462 } else if ( grace >= 0 ) {
1463 sprintf( msgbuf+len,
1464 " (Password expired, %d grace logins remain)",
1472 ldap_controls_free( ctrls );
1475 if ( err != LDAP_SUCCESS
1477 || ( matched && matched[ 0 ] )
1478 || ( info && info[ 0 ] )
1481 tool_perror( "ldap_bind", err, msgbuf, matched, info, refs );
1483 if( matched ) ber_memfree( matched );
1484 if( info ) ber_memfree( info );
1485 if( refs ) ber_memvfree( (void **)refs );
1487 if ( err != LDAP_SUCCESS ) exit( err );
1493 tool_unbind( LDAP *ld )
1495 int err = ldap_set_option( ld, LDAP_OPT_SERVER_CONTROLS, NULL );
1497 if ( err != LDAP_OPT_SUCCESS ) {
1498 fprintf( stderr, "Could not unset controls\n");
1501 (void) ldap_unbind_ext( ld, NULL, NULL );
1505 /* Set server controls. Add controls extra_c[0..count-1], if set. */
1507 tool_server_controls( LDAP *ld, LDAPControl *extra_c, int count )
1509 int i = 0, j, crit = 0, err;
1510 LDAPControl c[16], **ctrls;
1514 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
1516 #endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
1520 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
1525 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
1527 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
1528 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
1530 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
1532 || unknown_ctrls_num ) )
1537 ctrls = (LDAPControl**) malloc(sizeof(c) + (count + unknown_ctrls_num + 1)*sizeof(LDAPControl*));
1538 if ( ctrls == NULL ) {
1539 fprintf( stderr, "No memory\n" );
1540 exit( EXIT_FAILURE );
1544 if ( BER_BVISNULL( &assertionvalue ) ) {
1545 err = ldap_create_assertion_control_value( ld,
1546 assertion, &assertionvalue );
1549 "Unable to create assertion value "
1550 "\"%s\" (%d)\n", assertion, err );
1554 c[i].ldctl_oid = LDAP_CONTROL_ASSERT;
1555 c[i].ldctl_value = assertionvalue;
1556 c[i].ldctl_iscritical = assertctl > 1;
1562 c[i].ldctl_value.bv_val = authzid;
1563 c[i].ldctl_value.bv_len = strlen( authzid );
1564 c[i].ldctl_oid = LDAP_CONTROL_PROXY_AUTHZ;
1565 c[i].ldctl_iscritical = authzcrit;
1570 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
1571 /* NOTE: doesn't need an extra count because it's incompatible
1574 BerElementBuffer berbuf;
1575 BerElement *ber = (BerElement *)&berbuf;
1577 ber_init2( ber, NULL, LBER_USE_DER );
1579 if ( ber_printf( ber, "s", proxydn ) == -1 ) {
1580 exit( EXIT_FAILURE );
1583 if ( ber_flatten2( ber, &c[i].ldctl_value, 0 ) == -1 ) {
1584 exit( EXIT_FAILURE );
1587 c[i].ldctl_oid = LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ;
1588 c[i].ldctl_iscritical = authzcrit;
1592 #endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
1595 c[i].ldctl_oid = LDAP_CONTROL_MANAGEDIT;
1596 BER_BVZERO( &c[i].ldctl_value );
1597 c[i].ldctl_iscritical = manageDIT > 1;
1602 if ( manageDSAit ) {
1603 c[i].ldctl_oid = LDAP_CONTROL_MANAGEDSAIT;
1604 BER_BVZERO( &c[i].ldctl_value );
1605 c[i].ldctl_iscritical = manageDSAit > 1;
1611 c[i].ldctl_oid = LDAP_CONTROL_NOOP;
1612 BER_BVZERO( &c[i].ldctl_value );
1613 c[i].ldctl_iscritical = noop > 1;
1618 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
1620 c[i].ldctl_oid = LDAP_CONTROL_PASSWORDPOLICYREQUEST;
1621 BER_BVZERO( &c[i].ldctl_value );
1622 c[i].ldctl_iscritical = 0;
1629 BerElementBuffer berbuf;
1630 BerElement *ber = (BerElement *)&berbuf;
1631 char **attrs = NULL;
1633 if( preread_attrs ) {
1634 attrs = ldap_str2charray( preread_attrs, "," );
1637 ber_init2( ber, NULL, LBER_USE_DER );
1639 if( ber_printf( ber, "{v}", attrs ) == -1 ) {
1640 fprintf( stderr, "preread attrs encode failed.\n" );
1641 exit( EXIT_FAILURE );
1644 err = ber_flatten2( ber, &c[i].ldctl_value, 0 );
1646 fprintf( stderr, "preread flatten failed (%d)\n", err );
1647 exit( EXIT_FAILURE );
1650 c[i].ldctl_oid = LDAP_CONTROL_PRE_READ;
1651 c[i].ldctl_iscritical = preread > 1;
1655 if( attrs ) ldap_charray_free( attrs );
1659 BerElementBuffer berbuf;
1660 BerElement *ber = (BerElement *)&berbuf;
1661 char **attrs = NULL;
1663 if( postread_attrs ) {
1664 attrs = ldap_str2charray( postread_attrs, "," );
1667 ber_init2( ber, NULL, LBER_USE_DER );
1669 if( ber_printf( ber, "{v}", attrs ) == -1 ) {
1670 fprintf( stderr, "postread attrs encode failed.\n" );
1671 exit( EXIT_FAILURE );
1674 err = ber_flatten2( ber, &c[i].ldctl_value, 0 );
1676 fprintf( stderr, "postread flatten failed (%d)\n", err );
1677 exit( EXIT_FAILURE );
1680 c[i].ldctl_oid = LDAP_CONTROL_POST_READ;
1681 c[i].ldctl_iscritical = postread > 1;
1685 if( attrs ) ldap_charray_free( attrs );
1688 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
1690 if ( chainingResolve > -1 ) {
1691 BerElementBuffer berbuf;
1692 BerElement *ber = (BerElement *)&berbuf;
1694 ber_init2( ber, NULL, LBER_USE_DER );
1696 err = ber_printf( ber, "{e" /* } */, chainingResolve );
1699 fprintf( stderr, _("Chaining behavior control encoding error!\n") );
1700 exit( EXIT_FAILURE );
1703 if ( chainingContinuation > -1 ) {
1704 err = ber_printf( ber, "e", chainingContinuation );
1707 fprintf( stderr, _("Chaining behavior control encoding error!\n") );
1708 exit( EXIT_FAILURE );
1712 err = ber_printf( ber, /* { */ "N}" );
1715 fprintf( stderr, _("Chaining behavior control encoding error!\n") );
1716 exit( EXIT_FAILURE );
1719 if ( ber_flatten2( ber, &c[i].ldctl_value, 0 ) == -1 ) {
1720 exit( EXIT_FAILURE );
1724 BER_BVZERO( &c[i].ldctl_value );
1727 c[i].ldctl_oid = LDAP_CONTROL_X_CHAINING_BEHAVIOR;
1728 c[i].ldctl_iscritical = chaining > 1;
1732 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
1734 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
1735 if ( sessionTracking ) {
1736 if ( stValue.bv_val == NULL && st_value( ld, &stValue ) ) {
1737 exit( EXIT_FAILURE );
1740 c[i].ldctl_oid = LDAP_CONTROL_X_SESSION_TRACKING;
1741 c[i].ldctl_iscritical = 0;
1742 ber_dupbv( &c[i].ldctl_value, &stValue );
1747 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
1750 ctrls[i++] = extra_c++;
1752 for ( count = 0; count < unknown_ctrls_num; count++ ) {
1753 ctrls[i++] = &unknown_ctrls[count];
1757 err = ldap_set_option( ld, LDAP_OPT_SERVER_CONTROLS, ctrls );
1759 if ( err != LDAP_OPT_SUCCESS ) {
1760 for ( j = 0; j < i; j++ ) {
1761 if ( ctrls[j]->ldctl_iscritical ) crit = 1;
1763 fprintf( stderr, "Could not set %scontrols\n",
1764 crit ? "critical " : "" );
1769 exit( EXIT_FAILURE );
1774 tool_check_abandon( LDAP *ld, int msgid )
1778 switch ( gotintr ) {
1780 rc = ldap_cancel_s( ld, msgid, NULL, NULL );
1781 fprintf( stderr, "got interrupt, cancel got %d: %s\n",
1782 rc, ldap_err2string( rc ) );
1786 rc = ldap_abandon_ext( ld, msgid, NULL, NULL );
1787 fprintf( stderr, "got interrupt, abandon got %d: %s\n",
1788 rc, ldap_err2string( rc ) );
1792 /* just unbind, ignoring the request */
1800 print_prepostread( LDAP *ld, LDAPControl *ctrl, struct berval *what)
1805 tool_write_ldif( LDIF_PUT_COMMENT, "==> ",
1806 what->bv_val, what->bv_len );
1807 ber = ber_init( &ctrl->ldctl_value );
1808 if ( ber == NULL ) {
1812 } else if ( ber_scanf( ber, "{m{" /*}}*/, &bv ) == LBER_ERROR ) {
1817 tool_write_ldif( LDIF_PUT_VALUE, "dn", bv.bv_val, bv.bv_len );
1819 while ( ber_scanf( ber, "{m" /*}*/, &bv ) != LBER_ERROR ) {
1821 BerVarray vals = NULL;
1823 if ( ber_scanf( ber, "[W]", &vals ) == LBER_ERROR ||
1830 for ( i = 0; vals[ i ].bv_val != NULL; i++ ) {
1832 ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1833 bv.bv_val, vals[ i ].bv_val, vals[ i ].bv_len );
1836 ber_bvarray_free( vals );
1840 if ( ber != NULL ) {
1844 tool_write_ldif( LDIF_PUT_COMMENT, "<== ",
1845 what->bv_val, what->bv_len );
1851 print_preread( LDAP *ld, LDAPControl *ctrl )
1853 static struct berval what = BER_BVC( "preread" );
1855 return print_prepostread( ld, ctrl, &what );
1859 print_postread( LDAP *ld, LDAPControl *ctrl )
1861 static struct berval what = BER_BVC( "postread" );
1863 return print_prepostread( ld, ctrl, &what );
1867 print_paged_results( LDAP *ld, LDAPControl *ctrl )
1871 /* note: pr_cookie is being malloced; it's freed
1872 * the next time the control is sent, but the last
1873 * time it's not; we don't care too much, because
1874 * the last time an empty value is returned... */
1875 if ( ldap_parse_pageresponse_control( ld, ctrl, &estimate, &pr_cookie )
1882 /* FIXME: check buffer overflow */
1883 char buf[ BUFSIZ ], *ptr = buf;
1885 if ( estimate > 0 ) {
1886 ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
1887 "estimate=%d", estimate );
1890 if ( pr_cookie.bv_len > 0 ) {
1893 bv.bv_len = LUTIL_BASE64_ENCODE_LEN(
1894 pr_cookie.bv_len ) + 1;
1895 bv.bv_val = ber_memalloc( bv.bv_len + 1 );
1897 bv.bv_len = lutil_b64_ntop(
1898 (unsigned char *) pr_cookie.bv_val,
1900 bv.bv_val, bv.bv_len );
1902 ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
1903 "%scookie=%s", ptr == buf ? "" : " ",
1906 ber_memfree( bv.bv_val );
1908 pr_morePagedResults = 1;
1911 ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
1912 "%scookie=", ptr == buf ? "" : " " );
1915 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1916 "pagedresults", buf, ptr - buf );
1923 print_sss( LDAP *ld, LDAPControl *ctrl )
1929 rc = ldap_parse_sortresponse_control( ld, ctrl, &err, &attr );
1930 if ( rc == LDAP_SUCCESS ) {
1932 rc = snprintf( buf, sizeof(buf), "(%d) %s %s",
1933 err, ldap_err2string(err), attr ? attr : "" );
1935 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1936 "sortResult", buf, rc );
1942 #ifdef LDAP_CONTROL_X_DEREF
1944 print_deref( LDAP *ld, LDAPControl *ctrl )
1946 LDAPDerefRes *drhead = NULL, *dr;
1949 rc = ldap_parse_derefresponse_control( ld, ctrl, &drhead );
1950 if ( rc != LDAP_SUCCESS ) {
1954 for ( dr = drhead; dr != NULL; dr = dr->next ) {
1959 len = strlen( dr->derefAttr ) + STRLENOF(": ");
1961 for ( dv = dr->attrVals; dv != NULL; dv = dv->next ) {
1962 if ( dv->vals != NULL ) {
1964 ber_len_t tlen = strlen(dv->type);
1966 for ( j = 0; dv->vals[ j ].bv_val != NULL; j++ ) {
1967 len += STRLENOF("<:=>;") + tlen + 4*((dv->vals[ j ].bv_len - 1)/3 + 1);
1971 len += dr->derefVal.bv_len + STRLENOF("\n");
1972 buf = ldap_memalloc( len + 1 );
1973 if ( buf == NULL ) {
1974 rc = LDAP_NO_MEMORY;
1979 ptr = lutil_strcopy( ptr, dr->derefAttr );
1982 for ( dv = dr->attrVals; dv != NULL; dv = dv->next ) {
1983 if ( dv->vals != NULL ) {
1985 for ( j = 0; dv->vals[ j ].bv_val != NULL; j++ ) {
1988 for ( k = 0; k < dv->vals[ j ].bv_len; k++ ) {
1989 if ( !isprint( dv->vals[ j ].bv_val[k] ) ) {
1996 ptr = lutil_strcopy( ptr, dv->type );
2002 k = lutil_b64_ntop( dv->vals[ j ].bv_val, dv->vals[ j ].bv_len, ptr, buf + len - ptr );
2007 ptr = lutil_memcopy( ptr, dv->vals[ j ].bv_val, dv->vals[ j ].bv_len );
2014 ptr = lutil_strncopy( ptr, dr->derefVal.bv_val, dr->derefVal.bv_len );
2017 assert( ptr <= buf + len );
2019 tool_write_ldif( LDIF_PUT_COMMENT, NULL, buf, ptr - buf);
2021 ldap_memfree( buf );
2027 ldap_derefresponse_free( drhead );
2033 #ifdef LDAP_CONTROL_X_WHATFAILED
2035 print_whatfailed( LDAP *ld, LDAPControl *ctrl )
2040 BerVarray bva = NULL;
2042 /* Create a BerElement from the berval returned in the control. */
2043 ber = ber_init( &ctrl->ldctl_value );
2045 if ( ber == NULL ) {
2046 return LDAP_NO_MEMORY;
2049 siz = sizeof(struct berval);
2050 tag = ber_scanf( ber, "[M]", &bva, &siz, 0 );
2051 if ( tag != LBER_ERROR ) {
2054 tool_write_ldif( LDIF_PUT_COMMENT, " what failed:", NULL, 0 );
2056 for ( i = 0; bva[i].bv_val != NULL; i++ ) {
2057 tool_write_ldif( LDIF_PUT_COMMENT, NULL, bva[i].bv_val, bva[i].bv_len );
2060 ldap_memfree( bva );
2070 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
2072 print_ppolicy( LDAP *ld, LDAPControl *ctrl )
2074 int expire = 0, grace = 0, rc;
2075 LDAPPasswordPolicyError pperr;
2077 rc = ldap_parse_passwordpolicy_control( ld, ctrl,
2078 &expire, &grace, &pperr );
2079 if ( rc == LDAP_SUCCESS ) {
2080 char buf[ BUFSIZ ], *ptr = buf;
2082 if ( expire != -1 ) {
2083 ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
2084 "expire=%d", expire );
2087 if ( grace != -1 ) {
2088 ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
2089 "%sgrace=%d", ptr == buf ? "" : " ", grace );
2092 if ( pperr != PP_noError ) {
2093 ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
2094 "%serror=%d (%s)", ptr == buf ? "" : " ",
2096 ldap_passwordpolicy_err2txt( pperr ) );
2099 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
2100 "ppolicy", buf, ptr - buf );
2107 void tool_print_ctrls(
2109 LDAPControl **ctrls )
2114 for ( i = 0; ctrls[i] != NULL; i++ ) {
2115 /* control: OID criticality base64value */
2116 struct berval b64 = BER_BVNULL;
2121 /* FIXME: there might be cases where a control has NULL OID;
2122 * this makes little sense, especially when returned by the
2123 * server, but libldap happily allows it */
2124 if ( ctrls[i]->ldctl_oid == NULL ) {
2129 len += strlen( ctrls[i]->ldctl_oid );
2131 /* add enough for space after OID and the critical value itself */
2132 len += ctrls[i]->ldctl_iscritical
2133 ? sizeof("true") : sizeof("false");
2135 /* convert to base64 */
2136 if ( !BER_BVISNULL( &ctrls[i]->ldctl_value ) ) {
2137 b64.bv_len = LUTIL_BASE64_ENCODE_LEN(
2138 ctrls[i]->ldctl_value.bv_len ) + 1;
2139 b64.bv_val = ber_memalloc( b64.bv_len + 1 );
2141 b64.bv_len = lutil_b64_ntop(
2142 (unsigned char *) ctrls[i]->ldctl_value.bv_val,
2143 ctrls[i]->ldctl_value.bv_len,
2144 b64.bv_val, b64.bv_len );
2148 len += 1 + b64.bv_len;
2151 ptr = str = malloc( len + 1 );
2153 ptr = lutil_strcopy( ptr, ": " );
2155 ptr = lutil_strcopy( ptr, ctrls[i]->ldctl_oid );
2156 ptr = lutil_strcopy( ptr, ctrls[i]->ldctl_iscritical
2157 ? " true" : " false" );
2160 ptr = lutil_strcopy( ptr, " " );
2161 ptr = lutil_strcopy( ptr, b64.bv_val );
2165 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
2166 "control", str, len );
2171 ber_memfree( b64.bv_val );
2174 /* known controls */
2175 for ( j = 0; tool_ctrl_response[j].oid != NULL; j++ ) {
2176 if ( strcmp( tool_ctrl_response[j].oid, ctrls[i]->ldctl_oid ) == 0 ) {
2177 if ( !tool_ctrl_response[j].mask & tool_type ) {
2178 /* this control should not appear
2179 * with this tool; warning? */
2185 if ( tool_ctrl_response[j].oid != NULL && tool_ctrl_response[j].func ) {
2186 (void)tool_ctrl_response[j].func( ld, ctrls[i] );
2192 tool_write_ldif( int type, char *name, char *value, ber_len_t vallen )
2196 if (( ldif = ldif_put( type, name, value, vallen )) == NULL ) {
2200 fputs( ldif, stdout );
2201 ber_memfree( ldif );
2207 tool_is_oid( const char *s )
2211 if ( !isdigit( (unsigned char) s[ 0 ] ) ) {
2215 for ( ; s[ 0 ]; s++ ) {
2216 if ( s[ 0 ] == '.' ) {
2217 if ( s[ 1 ] == '\0' ) {
2224 if ( !isdigit( (unsigned char) s[ 0 ] ) ) {
2228 if ( first == 1 && s[ 0 ] == '0' && s[ 1 ] != '.' ) {