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-2009 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;
255 if ( binddn != NULL ) {
256 ber_memfree( binddn );
260 if ( passwd.bv_val != NULL ) {
261 ber_memfree( passwd.bv_val );
267 tool_common_usage( void )
269 static const char *const descriptions[] = {
270 N_(" -c continuous operation mode (do not stop on errors)\n"),
271 N_(" -d level set LDAP debugging level to `level'\n"),
272 N_(" -D binddn bind DN\n"),
273 N_(" -e [!]<ext>[=<extparam>] general extensions (! indicates criticality)\n")
274 N_(" [!]assert=<filter> (RFC 4528; a RFC 4515 Filter string)\n")
275 N_(" [!]authzid=<authzid> (RFC 4370; \"dn:<dn>\" or \"u:<user>\")\n")
276 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
278 /* non-advertized support for proxyDN */
279 N_(" [!]proxydn=<dn> (a RFC 4514 DN string)\n")
282 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
283 N_(" [!]chaining[=<resolveBehavior>[/<continuationBehavior>]]\n")
284 N_(" one of \"chainingPreferred\", \"chainingRequired\",\n")
285 N_(" \"referralsPreferred\", \"referralsRequired\"\n")
286 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
287 N_(" [!]manageDSAit (RFC 3296)\n")
289 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
292 N_(" [!]postread[=<attrs>] (RFC 4527; comma-separated attr list)\n")
293 N_(" [!]preread[=<attrs>] (RFC 4527; comma-separated attr list)\n")
295 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
296 N_(" [!]sessiontracking\n")
297 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
298 N_(" abandon, cancel, ignore (SIGINT sends abandon/cancel,\n"
299 " or ignores response; if critical, doesn't wait for SIGINT.\n"
300 " not really controls)\n")
301 N_(" -f file read operations from `file'\n"),
302 N_(" -h host LDAP server\n"),
303 N_(" -H URI LDAP Uniform Resource Identifier(s)\n"),
304 N_(" -I use SASL Interactive mode\n"),
305 N_(" -M enable Manage DSA IT control (-MM to make critical)\n"),
306 N_(" -n show what would be done but don't actually do it\n"),
307 N_(" -N do not use reverse DNS to canonicalize SASL host name\n"),
308 N_(" -O props SASL security properties\n"),
309 N_(" -o <opt>[=<optparam] general options\n"),
310 N_(" nettimeout=<timeout> (in seconds, or \"none\" or \"max\")\n"),
311 N_(" -p port port on LDAP server\n"),
312 N_(" -P version protocol version (default: 3)\n"),
313 N_(" -Q use SASL Quiet mode\n"),
314 N_(" -R realm SASL realm\n"),
315 N_(" -U authcid SASL authentication identity\n"),
316 N_(" -v run in verbose mode (diagnostics to standard output)\n"),
317 N_(" -V print version info (-VV only)\n"),
318 N_(" -w passwd bind password (for simple authentication)\n"),
319 N_(" -W prompt for bind password\n"),
320 N_(" -x Simple authentication\n"),
321 N_(" -X authzid SASL authorization identity (\"dn:<dn>\" or \"u:<user>\")\n"),
322 N_(" -y file Read password from file\n"),
323 N_(" -Y mech SASL mechanism\n"),
324 N_(" -Z Start TLS request (-ZZ to require successful response)\n"),
327 const char *const *cpp;
329 fputs( _("Common options:\n"), stderr );
330 for( cpp = descriptions; *cpp != NULL; cpp++ ) {
331 if( strchr( options, (*cpp)[3] ) || (*cpp)[3] == ' ' ) {
332 fputs( _(*cpp), stderr );
345 fprintf( stderr, "%s: %s (%d)%s\n",
346 func, ldap_err2string( err ), err, extra ? extra : "" );
348 if ( matched && *matched ) {
349 fprintf( stderr, _("\tmatched DN: %s\n"), matched );
352 if ( info && *info ) {
353 fprintf( stderr, _("\tadditional info: %s\n"), info );
356 if ( refs && *refs ) {
358 fprintf( stderr, _("\treferrals:\n") );
359 for( i=0; refs[i]; i++ ) {
360 fprintf( stderr, "\t\t%s\n", refs[i] );
367 tool_args( int argc, char **argv )
371 while (( i = getopt( argc, argv, options )) != EOF ) {
373 char *control, *cvalue, *next;
375 case 'c': /* continuous operation mode */
382 ival = strtol( optarg, &next, 10 );
383 if (next == NULL || next[0] != '\0') {
384 fprintf( stderr, "%s: unable to parse debug value \"%s\"\n", prog, optarg);
389 case 'D': /* bind DN */
390 if( binddn != NULL ) {
391 fprintf( stderr, "%s: -D previously specified\n", prog );
392 exit( EXIT_FAILURE );
394 binddn = ber_strdup( optarg );
396 case 'e': /* general extensions (controls and such) */
397 /* should be extended to support comma separated list of
398 * [!]key[=value] parameters, e.g. -e !foo,bar=567
403 while ( optarg[0] == '!' ) {
408 control = ber_strdup( optarg );
409 if ( (cvalue = strchr( control, '=' )) != NULL ) {
413 if ( strcasecmp( control, "assert" ) == 0 ) {
415 fprintf( stderr, "assert control previously specified\n");
416 exit( EXIT_FAILURE );
418 if( cvalue == NULL ) {
419 fprintf( stderr, "assert: control value expected\n" );
423 assertctl = 1 + crit;
425 assert( assertion == NULL );
428 } else if ( strcasecmp( control, "authzid" ) == 0 ) {
429 if( authzid != NULL ) {
430 fprintf( stderr, "authzid control previously specified\n");
431 exit( EXIT_FAILURE );
433 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
434 if( proxydn != NULL ) {
435 fprintf( stderr, "authzid control incompatible with proxydn\n");
436 exit( EXIT_FAILURE );
438 #endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
439 if( cvalue == NULL ) {
440 fprintf( stderr, "authzid: control value expected\n" );
444 fprintf( stderr, "authzid: must be marked critical\n" );
446 } else if ( crit > 1 ) {
447 /* purposely flag proxied authorization
448 * as non-critical, to test DSA */
452 assert( authzid == NULL );
455 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
456 } else if ( strcasecmp( control, "proxydn" ) == 0 ) {
457 if( proxydn != NULL ) {
458 fprintf( stderr, "proxydn control previously specified\n");
459 exit( EXIT_FAILURE );
461 if( authzid != NULL ) {
462 fprintf( stderr, "proxydn control incompatible with authzid\n");
463 exit( EXIT_FAILURE );
465 if( cvalue == NULL ) {
466 fprintf( stderr, "proxydn: control value expected\n" );
470 fprintf( stderr, "proxydn: must be marked critical\n" );
472 } else if ( crit > 1 ) {
473 /* purposely flag proxied authorization
474 * as non-critical, to test DSA */
478 assert( proxydn == NULL );
480 #endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
482 } else if ( ( strcasecmp( control, "relax" ) == 0 ) ||
483 ( strcasecmp( control, "manageDIT" ) == 0 ) )
487 "relax control previously specified\n");
488 exit( EXIT_FAILURE );
490 if( cvalue != NULL ) {
492 "relax: no control value expected\n" );
496 manageDIT = 1 + crit;
498 } else if ( strcasecmp( control, "manageDSAit" ) == 0 ) {
501 "manageDSAit control previously specified\n");
502 exit( EXIT_FAILURE );
504 if( cvalue != NULL ) {
506 "manageDSAit: no control value expected\n" );
510 manageDSAit = 1 + crit;
512 } else if ( strcasecmp( control, "noop" ) == 0 ) {
514 fprintf( stderr, "noop control previously specified\n");
515 exit( EXIT_FAILURE );
517 if( cvalue != NULL ) {
518 fprintf( stderr, "noop: no control value expected\n" );
524 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
525 } else if ( strcasecmp( control, "ppolicy" ) == 0 ) {
527 fprintf( stderr, "ppolicy control previously specified\n");
528 exit( EXIT_FAILURE );
530 if( cvalue != NULL ) {
531 fprintf( stderr, "ppolicy: no control value expected\n" );
535 fprintf( stderr, "ppolicy: critical flag not allowed\n" );
542 } else if ( strcasecmp( control, "preread" ) == 0 ) {
544 fprintf( stderr, "preread control previously specified\n");
545 exit( EXIT_FAILURE );
549 preread_attrs = cvalue;
551 } else if ( strcasecmp( control, "postread" ) == 0 ) {
553 fprintf( stderr, "postread control previously specified\n");
554 exit( EXIT_FAILURE );
558 postread_attrs = cvalue;
560 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
561 } else if ( strcasecmp( control, "chaining" ) == 0 ) {
563 fprintf( stderr, "chaining control previously specified\n");
564 exit( EXIT_FAILURE );
569 if ( cvalue != NULL ) {
572 continuation = strchr( cvalue, '/' );
573 if ( continuation ) {
574 /* FIXME: this makes sense only in searches */
575 *continuation++ = '\0';
576 if ( strcasecmp( continuation, "chainingPreferred" ) == 0 ) {
577 chainingContinuation = LDAP_CHAINING_PREFERRED;
578 } else if ( strcasecmp( continuation, "chainingRequired" ) == 0 ) {
579 chainingContinuation = LDAP_CHAINING_REQUIRED;
580 } else if ( strcasecmp( continuation, "referralsPreferred" ) == 0 ) {
581 chainingContinuation = LDAP_REFERRALS_PREFERRED;
582 } else if ( strcasecmp( continuation, "referralsRequired" ) == 0 ) {
583 chainingContinuation = LDAP_REFERRALS_REQUIRED;
586 "chaining behavior control "
587 "continuation value \"%s\" invalid\n",
589 exit( EXIT_FAILURE );
593 if ( strcasecmp( cvalue, "chainingPreferred" ) == 0 ) {
594 chainingResolve = LDAP_CHAINING_PREFERRED;
595 } else if ( strcasecmp( cvalue, "chainingRequired" ) == 0 ) {
596 chainingResolve = LDAP_CHAINING_REQUIRED;
597 } else if ( strcasecmp( cvalue, "referralsPreferred" ) == 0 ) {
598 chainingResolve = LDAP_REFERRALS_PREFERRED;
599 } else if ( strcasecmp( cvalue, "referralsRequired" ) == 0 ) {
600 chainingResolve = LDAP_REFERRALS_REQUIRED;
603 "chaining behavior control "
604 "resolve value \"%s\" invalid\n",
606 exit( EXIT_FAILURE );
609 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
611 /* this shouldn't go here, really; but it's a feature... */
612 } else if ( strcasecmp( control, "abandon" ) == 0 ) {
613 abcan = Intr_Abandon;
618 } else if ( strcasecmp( control, "cancel" ) == 0 ) {
624 } else if ( strcasecmp( control, "ignore" ) == 0 ) {
630 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
631 } else if ( strcasecmp( control, "sessiontracking" ) == 0 ) {
632 if ( sessionTracking ) {
633 fprintf( stderr, "%s: session tracking can be only specified once\n", prog );
634 exit( EXIT_FAILURE );
637 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
639 } else if ( tool_is_oid( control ) ) {
640 LDAPControl *tmpctrls, ctrl;
642 if ( unknown_ctrls != NULL ) {
644 for ( i = 0; unknown_ctrls[ i ].ldctl_oid != NULL; i++ ) {
645 if ( strcmp( control, unknown_ctrls[ i ].ldctl_oid ) == 0 ) {
646 fprintf( stderr, "%s control previously specified\n", control );
647 exit( EXIT_FAILURE );
652 tmpctrls = (LDAPControl *)ber_memrealloc( unknown_ctrls,
653 (unknown_ctrls_num + 1)*sizeof( LDAPControl ) );
654 if ( tmpctrls == NULL ) {
655 fprintf( stderr, "%s: no memory?\n", prog );
656 exit( EXIT_FAILURE );
658 unknown_ctrls = tmpctrls;
659 ctrl.ldctl_oid = control;
660 ctrl.ldctl_value.bv_val = NULL;
661 ctrl.ldctl_value.bv_len = 0;
662 ctrl.ldctl_iscritical = crit;
664 if ( cvalue != NULL ) {
666 size_t len = strlen( cvalue );
669 bv.bv_len = LUTIL_BASE64_DECODE_LEN( len );
670 bv.bv_val = ber_memalloc( bv.bv_len + 1 );
672 retcode = lutil_b64_pton( cvalue,
673 (unsigned char *)bv.bv_val,
676 if ( retcode == -1 || (unsigned) retcode > bv.bv_len ) {
677 fprintf( stderr, "Unable to parse value of general control %s\n",
683 ctrl.ldctl_value = bv;
686 unknown_ctrls[ unknown_ctrls_num ] = ctrl;
690 fprintf( stderr, "Invalid general control name: %s\n",
695 case 'f': /* read from file */
696 if( infile != NULL ) {
697 fprintf( stderr, "%s: -f previously specified\n", prog );
698 exit( EXIT_FAILURE );
700 infile = ber_strdup( optarg );
702 case 'h': /* ldap host */
703 if( ldaphost != NULL ) {
704 fprintf( stderr, "%s: -h previously specified\n", prog );
705 exit( EXIT_FAILURE );
707 ldaphost = ber_strdup( optarg );
709 case 'H': /* ldap URI */
710 if( ldapuri != NULL ) {
711 fprintf( stderr, "%s: -H previously specified\n", prog );
712 exit( EXIT_FAILURE );
714 ldapuri = ber_strdup( optarg );
717 #ifdef HAVE_CYRUS_SASL
718 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
719 fprintf( stderr, "%s: incompatible previous "
720 "authentication choice\n",
722 exit( EXIT_FAILURE );
724 authmethod = LDAP_AUTH_SASL;
725 sasl_flags = LDAP_SASL_INTERACTIVE;
728 fprintf( stderr, "%s: was not compiled with SASL support\n",
730 exit( EXIT_FAILURE );
733 /* enable Manage DSA IT */
736 case 'n': /* print operations, don't actually do them */
743 control = ber_strdup( optarg );
744 if ( (cvalue = strchr( control, '=' )) != NULL ) {
748 if ( strcasecmp( control, "nettimeout" ) == 0 ) {
749 if( nettimeout.tv_sec != -1 ) {
750 fprintf( stderr, "nettimeout option previously specified\n");
751 exit( EXIT_FAILURE );
753 if( cvalue == NULL || cvalue[0] == '\0' ) {
754 fprintf( stderr, "nettimeout: option value expected\n" );
757 if ( strcasecmp( cvalue, "none" ) == 0 ) {
758 nettimeout.tv_sec = 0;
759 } else if ( strcasecmp( cvalue, "max" ) == 0 ) {
760 nettimeout.tv_sec = LDAP_MAXINT;
762 ival = strtol( cvalue, &next, 10 );
763 if ( next == NULL || next[0] != '\0' ) {
765 _("Unable to parse network timeout \"%s\"\n"), cvalue );
766 exit( EXIT_FAILURE );
768 nettimeout.tv_sec = ival;
770 if( nettimeout.tv_sec < 0 || nettimeout.tv_sec > LDAP_MAXINT ) {
771 fprintf( stderr, _("%s: invalid network timeout (%ld) specified\n"),
772 prog, (long)nettimeout.tv_sec );
773 exit( EXIT_FAILURE );
776 fprintf( stderr, "Invalid general option name: %s\n",
782 #ifdef HAVE_CYRUS_SASL
783 if( sasl_secprops != NULL ) {
784 fprintf( stderr, "%s: -O previously specified\n", prog );
785 exit( EXIT_FAILURE );
787 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
788 fprintf( stderr, "%s: incompatible previous "
789 "authentication choice\n", prog );
790 exit( EXIT_FAILURE );
792 authmethod = LDAP_AUTH_SASL;
793 sasl_secprops = ber_strdup( optarg );
795 fprintf( stderr, "%s: not compiled with SASL support\n", prog );
796 exit( EXIT_FAILURE );
801 fprintf( stderr, "%s: -p previously specified\n", prog );
802 exit( EXIT_FAILURE );
804 ival = strtol( optarg, &next, 10 );
805 if ( next == NULL || next[0] != '\0' ) {
806 fprintf( stderr, "%s: unable to parse port number \"%s\"\n", prog, optarg );
807 exit( EXIT_FAILURE );
812 ival = strtol( optarg, &next, 10 );
813 if ( next == NULL || next[0] != '\0' ) {
814 fprintf( stderr, "%s: unable to parse protocol version \"%s\"\n", prog, optarg );
815 exit( EXIT_FAILURE );
819 if( protocol == LDAP_VERSION3 ) {
820 fprintf( stderr, "%s: -P 2 incompatible with version %d\n",
822 exit( EXIT_FAILURE );
824 protocol = LDAP_VERSION2;
827 if( protocol == LDAP_VERSION2 ) {
828 fprintf( stderr, "%s: -P 2 incompatible with version %d\n",
830 exit( EXIT_FAILURE );
832 protocol = LDAP_VERSION3;
835 fprintf( stderr, "%s: protocol version should be 2 or 3\n",
841 #ifdef HAVE_CYRUS_SASL
842 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
843 fprintf( stderr, "%s: incompatible previous "
844 "authentication choice\n",
846 exit( EXIT_FAILURE );
848 authmethod = LDAP_AUTH_SASL;
849 sasl_flags = LDAP_SASL_QUIET;
852 fprintf( stderr, "%s: not compiled with SASL support\n",
854 exit( EXIT_FAILURE );
857 #ifdef HAVE_CYRUS_SASL
858 if( sasl_realm != NULL ) {
859 fprintf( stderr, "%s: -R previously specified\n", prog );
860 exit( EXIT_FAILURE );
862 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
863 fprintf( stderr, "%s: incompatible previous "
864 "authentication choice\n",
866 exit( EXIT_FAILURE );
868 authmethod = LDAP_AUTH_SASL;
869 sasl_realm = ber_strdup( optarg );
871 fprintf( stderr, "%s: not compiled with SASL support\n",
873 exit( EXIT_FAILURE );
877 #ifdef HAVE_CYRUS_SASL
878 if( sasl_authc_id != NULL ) {
879 fprintf( stderr, "%s: -U previously specified\n", prog );
880 exit( EXIT_FAILURE );
882 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
883 fprintf( stderr, "%s: incompatible previous "
884 "authentication choice\n",
886 exit( EXIT_FAILURE );
888 authmethod = LDAP_AUTH_SASL;
889 sasl_authc_id = ber_strdup( optarg );
891 fprintf( stderr, "%s: not compiled with SASL support\n",
893 exit( EXIT_FAILURE );
896 case 'v': /* verbose mode */
899 case 'V': /* version */
902 case 'w': /* password */
903 passwd.bv_val = ber_strdup( optarg );
907 for( p = optarg; *p != '\0'; p++ ) {
911 passwd.bv_len = strlen( passwd.bv_val );
920 #ifdef HAVE_CYRUS_SASL
921 if( sasl_mech != NULL ) {
922 fprintf( stderr, "%s: -Y previously specified\n", prog );
923 exit( EXIT_FAILURE );
925 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
927 "%s: incompatible with authentication choice\n", prog );
928 exit( EXIT_FAILURE );
930 authmethod = LDAP_AUTH_SASL;
931 sasl_mech = ber_strdup( optarg );
933 fprintf( stderr, "%s: not compiled with SASL support\n", prog );
934 exit( EXIT_FAILURE );
938 if( authmethod != -1 && authmethod != LDAP_AUTH_SIMPLE ) {
939 fprintf( stderr, "%s: incompatible with previous "
940 "authentication choice\n", prog );
941 exit( EXIT_FAILURE );
943 authmethod = LDAP_AUTH_SIMPLE;
946 #ifdef HAVE_CYRUS_SASL
947 if( sasl_authz_id != NULL ) {
948 fprintf( stderr, "%s: -X previously specified\n", prog );
949 exit( EXIT_FAILURE );
951 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
952 fprintf( stderr, "%s: -X incompatible with "
953 "authentication choice\n", prog );
954 exit( EXIT_FAILURE );
956 authmethod = LDAP_AUTH_SASL;
957 sasl_authz_id = ber_strdup( optarg );
959 fprintf( stderr, "%s: not compiled with SASL support\n", prog );
960 exit( EXIT_FAILURE );
967 fprintf( stderr, "%s: not compiled with TLS support\n", prog );
968 exit( EXIT_FAILURE );
972 if( handle_private_option( i ) ) break;
973 fprintf( stderr, "%s: unrecognized option -%c\n",
980 /* prevent bad linking */
982 api.ldapai_info_version = LDAP_API_INFO_VERSION;
984 if ( ldap_get_option(NULL, LDAP_OPT_API_INFO, &api)
985 != LDAP_OPT_SUCCESS )
987 fprintf( stderr, "%s: ldap_get_option(API_INFO) failed\n", prog );
988 exit( EXIT_FAILURE );
991 if (api.ldapai_info_version != LDAP_API_INFO_VERSION) {
992 fprintf( stderr, "LDAP APIInfo version mismatch: "
993 "library %d, header %d\n",
994 api.ldapai_info_version, LDAP_API_INFO_VERSION );
995 exit( EXIT_FAILURE );
998 if( api.ldapai_api_version != LDAP_API_VERSION ) {
999 fprintf( stderr, "LDAP API version mismatch: "
1000 "library %d, header %d\n",
1001 api.ldapai_api_version, LDAP_API_VERSION );
1002 exit( EXIT_FAILURE );
1005 if( strcmp(api.ldapai_vendor_name, LDAP_VENDOR_NAME ) != 0 ) {
1006 fprintf( stderr, "LDAP vendor name mismatch: "
1007 "library %s, header %s\n",
1008 api.ldapai_vendor_name, LDAP_VENDOR_NAME );
1009 exit( EXIT_FAILURE );
1012 if( api.ldapai_vendor_version != LDAP_VENDOR_VERSION ) {
1013 fprintf( stderr, "LDAP vendor version mismatch: "
1014 "library %d, header %d\n",
1015 api.ldapai_vendor_version, LDAP_VENDOR_VERSION );
1016 exit( EXIT_FAILURE );
1020 fprintf( stderr, "%s: %s\t(LDAP library: %s %d)\n",
1022 LDAP_VENDOR_NAME, LDAP_VENDOR_VERSION );
1023 if (version > 1) exit( EXIT_SUCCESS );
1026 ldap_memfree( api.ldapai_vendor_name );
1027 ber_memvfree( (void **)api.ldapai_extensions );
1031 protocol = LDAP_VERSION3;
1033 if (authmethod == -1 && protocol > LDAP_VERSION2) {
1034 #ifdef HAVE_CYRUS_SASL
1035 if ( binddn != NULL ) {
1036 authmethod = LDAP_AUTH_SIMPLE;
1038 authmethod = LDAP_AUTH_SASL;
1041 authmethod = LDAP_AUTH_SIMPLE;
1045 if( ldapuri == NULL ) {
1046 if( ldapport && ( ldaphost == NULL )) {
1047 fprintf( stderr, "%s: -p without -h is invalid.\n", prog );
1048 exit( EXIT_FAILURE );
1051 if( ldaphost != NULL ) {
1052 fprintf( stderr, "%s: -H incompatible with -h\n", prog );
1053 exit( EXIT_FAILURE );
1056 fprintf( stderr, "%s: -H incompatible with -p\n", prog );
1057 exit( EXIT_FAILURE );
1061 if( protocol == LDAP_VERSION2 ) {
1062 if( assertctl || authzid || manageDIT || manageDSAit ||
1063 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
1065 #endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
1066 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
1069 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
1071 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
1072 noop || ppolicy || preread || postread )
1074 fprintf( stderr, "%s: -e/-M incompatible with LDAPv2\n", prog );
1075 exit( EXIT_FAILURE );
1079 fprintf( stderr, "%s: -Z incompatible with LDAPv2\n", prog );
1080 exit( EXIT_FAILURE );
1083 #ifdef HAVE_CYRUS_SASL
1084 if( authmethod == LDAP_AUTH_SASL ) {
1085 fprintf( stderr, "%s: -[IOQRUXY] incompatible with LDAPv2\n",
1087 exit( EXIT_FAILURE );
1095 tool_conn_setup( int dont, void (*private_setup)( LDAP * ) )
1100 if( ber_set_option( NULL, LBER_OPT_DEBUG_LEVEL, &debug )
1101 != LBER_OPT_SUCCESS )
1104 "Could not set LBER_OPT_DEBUG_LEVEL %d\n", debug );
1106 if( ldap_set_option( NULL, LDAP_OPT_DEBUG_LEVEL, &debug )
1107 != LDAP_OPT_SUCCESS )
1110 "Could not set LDAP_OPT_DEBUG_LEVEL %d\n", debug );
1115 (void) SIGNAL( SIGPIPE, SIG_IGN );
1119 SIGNAL( SIGINT, do_sig );
1125 if( ( ldaphost != NULL || ldapport ) && ( ldapuri == NULL ) ) {
1128 memset( &url, 0, sizeof(url));
1130 url.lud_scheme = "ldap";
1131 url.lud_host = ldaphost;
1132 url.lud_port = ldapport;
1133 url.lud_scope = LDAP_SCOPE_DEFAULT;
1135 ldapuri = ldap_url_desc2str( &url );
1137 } else if ( ldapuri != NULL ) {
1138 LDAPURLDesc *ludlist, **ludp;
1142 rc = ldap_url_parselist( &ludlist, ldapuri );
1143 if ( rc != LDAP_URL_SUCCESS ) {
1145 "Could not parse LDAP URI(s)=%s (%d)\n",
1147 exit( EXIT_FAILURE );
1150 for ( ludp = &ludlist; *ludp != NULL; ) {
1151 LDAPURLDesc *lud = *ludp;
1154 if ( lud->lud_dn != NULL && lud->lud_dn[ 0 ] != '\0' &&
1155 ( lud->lud_host == NULL || lud->lud_host[0] == '\0' ) )
1157 /* if no host but a DN is provided,
1158 * use DNS SRV to gather the host list
1159 * and turn it into a list of URIs
1160 * using the scheme provided */
1161 char *domain = NULL,
1165 len_proto = strlen( lud->lud_scheme );
1167 if ( ldap_dn2domain( lud->lud_dn, &domain )
1171 "DNS SRV: Could not turn "
1172 "DN=\"%s\" into a domain\n",
1177 rc = ldap_domain2hostlist( domain, &hostlist );
1180 "DNS SRV: Could not turn "
1181 "domain=%s into a hostlist\n",
1186 hosts = ldap_str2charray( hostlist, " " );
1187 if ( hosts == NULL ) {
1189 "DNS SRV: Could not parse "
1190 "hostlist=\"%s\"\n",
1195 for ( i = 0; hosts[ i ] != NULL; i++ )
1198 tmp = (char **)ber_memrealloc( urls, sizeof( char * ) * ( nurls + i + 1 ) );
1199 if ( tmp == NULL ) {
1201 "DNS SRV: out of memory?\n" );
1205 urls[ nurls ] = NULL;
1207 for ( i = 0; hosts[ i ] != NULL; i++ ) {
1208 size_t len = len_proto
1210 + strlen( hosts[ i ] )
1213 urls[ nurls + i + 1 ] = NULL;
1214 urls[ nurls + i ] = (char *)malloc( sizeof( char ) * len );
1215 if ( urls[ nurls + i ] == NULL ) {
1217 "DNS SRV: out of memory?\n" );
1221 snprintf( urls[ nurls + i ], len, "%s://%s",
1222 lud->lud_scheme, hosts[ i ] );
1227 ber_memvfree( (void **)hosts );
1228 ber_memfree( hostlist );
1229 ber_memfree( domain );
1232 tmp = (char **)ber_memrealloc( urls, sizeof( char * ) * ( nurls + 2 ) );
1233 if ( tmp == NULL ) {
1235 "DNS SRV: out of memory?\n" );
1239 urls[ nurls + 1 ] = NULL;
1241 urls[ nurls ] = ldap_url_desc2str( lud );
1242 if ( urls[ nurls ] == NULL ) {
1244 "DNS SRV: out of memory?\n" );
1250 *ludp = lud->lud_next;
1252 lud->lud_next = NULL;
1253 ldap_free_urldesc( lud );
1256 if ( ludlist != NULL ) {
1257 ldap_free_urllist( ludlist );
1258 exit( EXIT_FAILURE );
1260 } else if ( urls == NULL ) {
1261 exit( EXIT_FAILURE );
1264 ldap_memfree( ldapuri );
1265 ldapuri = ldap_charray2str( urls, " " );
1266 ber_memvfree( (void **)urls );
1270 fprintf( stderr, "ldap_initialize( %s )\n",
1271 ldapuri != NULL ? ldapuri : "<DEFAULT>" );
1273 rc = ldap_initialize( &ld, ldapuri );
1274 if( rc != LDAP_SUCCESS ) {
1276 "Could not create LDAP session handle for URI=%s (%d): %s\n",
1277 ldapuri, rc, ldap_err2string(rc) );
1278 exit( EXIT_FAILURE );
1281 if( private_setup ) private_setup( ld );
1284 if( ldap_set_option( ld, LDAP_OPT_REFERRALS,
1285 referrals ? LDAP_OPT_ON : LDAP_OPT_OFF ) != LDAP_OPT_SUCCESS )
1287 fprintf( stderr, "Could not set LDAP_OPT_REFERRALS %s\n",
1288 referrals ? "on" : "off" );
1289 exit( EXIT_FAILURE );
1292 #ifdef HAVE_CYRUS_SASL
1294 if( ldap_set_option( ld, LDAP_OPT_X_SASL_NOCANON,
1295 nocanon ? LDAP_OPT_ON : LDAP_OPT_OFF ) != LDAP_OPT_SUCCESS )
1297 fprintf( stderr, "Could not set LDAP_OPT_X_SASL_NOCANON %s\n",
1298 nocanon ? "on" : "off" );
1299 exit( EXIT_FAILURE );
1302 if( ldap_set_option( ld, LDAP_OPT_PROTOCOL_VERSION, &protocol )
1303 != LDAP_OPT_SUCCESS )
1305 fprintf( stderr, "Could not set LDAP_OPT_PROTOCOL_VERSION %d\n",
1307 exit( EXIT_FAILURE );
1311 rc = ldap_start_tls_s( ld, NULL, NULL );
1312 if ( rc != LDAP_SUCCESS ) {
1313 tool_perror( "ldap_start_tls", rc, NULL, NULL, NULL, NULL );
1314 if ( use_tls > 1 ) {
1315 exit( EXIT_FAILURE );
1320 if ( nettimeout.tv_sec > 0 ) {
1321 if ( ldap_set_option( ld, LDAP_OPT_NETWORK_TIMEOUT, (void *) &nettimeout )
1322 != LDAP_OPT_SUCCESS )
1324 fprintf( stderr, "Could not set LDAP_OPT_NETWORK_TIMEOUT %ld\n",
1325 (long)nettimeout.tv_sec );
1326 exit( EXIT_FAILURE );
1336 tool_bind( LDAP *ld )
1338 LDAPControl **sctrlsp = NULL;
1339 LDAPControl *sctrls[3];
1340 LDAPControl sctrl[3];
1343 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
1346 c.ldctl_oid = LDAP_CONTROL_PASSWORDPOLICYREQUEST;
1347 c.ldctl_value.bv_val = NULL;
1348 c.ldctl_value.bv_len = 0;
1349 c.ldctl_iscritical = 0;
1351 sctrls[nsctrls] = &sctrl[nsctrls];
1352 sctrls[++nsctrls] = NULL;
1356 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
1357 if ( sessionTracking ) {
1360 if (stValue.bv_val == NULL && st_value( ld, &stValue ) ) {
1361 exit( EXIT_FAILURE );
1364 c.ldctl_oid = LDAP_CONTROL_X_SESSION_TRACKING;
1365 c.ldctl_iscritical = 0;
1366 ber_dupbv( &c.ldctl_value, &stValue );
1369 sctrls[nsctrls] = &sctrl[nsctrls];
1370 sctrls[++nsctrls] = NULL;
1372 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
1378 assert( nsctrls < (int) (sizeof(sctrls)/sizeof(sctrls[0])) );
1380 if ( authmethod == LDAP_AUTH_SASL ) {
1381 #ifdef HAVE_CYRUS_SASL
1385 if( sasl_secprops != NULL ) {
1386 rc = ldap_set_option( ld, LDAP_OPT_X_SASL_SECPROPS,
1387 (void *) sasl_secprops );
1389 if( rc != LDAP_OPT_SUCCESS ) {
1391 "Could not set LDAP_OPT_X_SASL_SECPROPS: %s\n",
1393 exit( LDAP_LOCAL_ERROR );
1397 defaults = lutil_sasl_defaults( ld,
1404 rc = ldap_sasl_interactive_bind_s( ld, binddn, sasl_mech,
1406 NULL, sasl_flags, lutil_sasl_interact, defaults );
1408 lutil_sasl_freedefs( defaults );
1409 if( rc != LDAP_SUCCESS ) {
1410 tool_perror( "ldap_sasl_interactive_bind_s",
1411 rc, NULL, NULL, NULL, NULL );
1415 fprintf( stderr, "%s: not compiled with SASL support\n", prog );
1416 exit( LDAP_NOT_SUPPORTED );
1420 LDAPMessage *result;
1421 LDAPControl **ctrls;
1423 char *matched = NULL;
1431 rc = ldap_sasl_bind( ld, binddn, LDAP_SASL_SIMPLE, &passwd,
1432 sctrlsp, NULL, &msgid );
1433 if ( msgid == -1 ) {
1434 tool_perror( "ldap_sasl_bind(SIMPLE)", rc,
1435 NULL, NULL, NULL, NULL );
1440 if ( ldap_result( ld, msgid, LDAP_MSG_ALL, NULL, &result ) == -1 ) {
1441 tool_perror( "ldap_result", -1, NULL, NULL, NULL, NULL );
1442 exit( LDAP_LOCAL_ERROR );
1445 rc = ldap_parse_result( ld, result, &err, &matched, &info, &refs,
1447 if ( rc != LDAP_SUCCESS ) {
1448 tool_perror( "ldap_bind parse result", rc, NULL, matched, info, refs );
1449 exit( LDAP_LOCAL_ERROR );
1452 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
1453 if ( ctrls && ppolicy ) {
1455 int expire, grace, len = 0;
1456 LDAPPasswordPolicyError pErr = -1;
1458 ctrl = ldap_control_find( LDAP_CONTROL_PASSWORDPOLICYRESPONSE,
1461 if ( ctrl && ldap_parse_passwordpolicy_control( ld, ctrl,
1462 &expire, &grace, &pErr ) == LDAP_SUCCESS )
1464 if ( pErr != PP_noError ){
1467 strcpy( msgbuf+2, ldap_passwordpolicy_err2txt( pErr ));
1468 len = strlen( msgbuf );
1470 if ( expire >= 0 ) {
1471 sprintf( msgbuf+len,
1472 " (Password expires in %d seconds)",
1474 } else if ( grace >= 0 ) {
1475 sprintf( msgbuf+len,
1476 " (Password expired, %d grace logins remain)",
1484 ldap_controls_free( ctrls );
1487 if ( err != LDAP_SUCCESS
1489 || ( matched && matched[ 0 ] )
1490 || ( info && info[ 0 ] )
1493 tool_perror( "ldap_bind", err, msgbuf, matched, info, refs );
1495 if( matched ) ber_memfree( matched );
1496 if( info ) ber_memfree( info );
1497 if( refs ) ber_memvfree( (void **)refs );
1499 if ( err != LDAP_SUCCESS ) exit( err );
1505 tool_unbind( LDAP *ld )
1507 int err = ldap_set_option( ld, LDAP_OPT_SERVER_CONTROLS, NULL );
1509 if ( err != LDAP_OPT_SUCCESS ) {
1510 fprintf( stderr, "Could not unset controls\n");
1513 (void) ldap_unbind_ext( ld, NULL, NULL );
1517 /* Set server controls. Add controls extra_c[0..count-1], if set. */
1519 tool_server_controls( LDAP *ld, LDAPControl *extra_c, int count )
1521 int i = 0, j, crit = 0, err;
1522 LDAPControl c[16], **ctrls;
1526 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
1528 #endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
1532 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
1537 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
1539 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
1540 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
1542 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
1544 || unknown_ctrls_num ) )
1549 ctrls = (LDAPControl**) malloc(sizeof(c) + (count + unknown_ctrls_num + 1)*sizeof(LDAPControl*));
1550 if ( ctrls == NULL ) {
1551 fprintf( stderr, "No memory\n" );
1552 exit( EXIT_FAILURE );
1556 if ( BER_BVISNULL( &assertionvalue ) ) {
1557 err = ldap_create_assertion_control_value( ld,
1558 assertion, &assertionvalue );
1561 "Unable to create assertion value "
1562 "\"%s\" (%d)\n", assertion, err );
1566 c[i].ldctl_oid = LDAP_CONTROL_ASSERT;
1567 c[i].ldctl_value = assertionvalue;
1568 c[i].ldctl_iscritical = assertctl > 1;
1574 c[i].ldctl_value.bv_val = authzid;
1575 c[i].ldctl_value.bv_len = strlen( authzid );
1576 c[i].ldctl_oid = LDAP_CONTROL_PROXY_AUTHZ;
1577 c[i].ldctl_iscritical = authzcrit;
1582 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
1583 /* NOTE: doesn't need an extra count because it's incompatible
1586 BerElementBuffer berbuf;
1587 BerElement *ber = (BerElement *)&berbuf;
1589 ber_init2( ber, NULL, LBER_USE_DER );
1591 if ( ber_printf( ber, "s", proxydn ) == -1 ) {
1592 exit( EXIT_FAILURE );
1595 if ( ber_flatten2( ber, &c[i].ldctl_value, 0 ) == -1 ) {
1596 exit( EXIT_FAILURE );
1599 c[i].ldctl_oid = LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ;
1600 c[i].ldctl_iscritical = authzcrit;
1604 #endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
1607 c[i].ldctl_oid = LDAP_CONTROL_MANAGEDIT;
1608 BER_BVZERO( &c[i].ldctl_value );
1609 c[i].ldctl_iscritical = manageDIT > 1;
1614 if ( manageDSAit ) {
1615 c[i].ldctl_oid = LDAP_CONTROL_MANAGEDSAIT;
1616 BER_BVZERO( &c[i].ldctl_value );
1617 c[i].ldctl_iscritical = manageDSAit > 1;
1623 c[i].ldctl_oid = LDAP_CONTROL_NOOP;
1624 BER_BVZERO( &c[i].ldctl_value );
1625 c[i].ldctl_iscritical = noop > 1;
1630 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
1632 c[i].ldctl_oid = LDAP_CONTROL_PASSWORDPOLICYREQUEST;
1633 BER_BVZERO( &c[i].ldctl_value );
1634 c[i].ldctl_iscritical = 0;
1641 BerElementBuffer berbuf;
1642 BerElement *ber = (BerElement *)&berbuf;
1643 char **attrs = NULL;
1645 if( preread_attrs ) {
1646 attrs = ldap_str2charray( preread_attrs, "," );
1649 ber_init2( ber, NULL, LBER_USE_DER );
1651 if( ber_printf( ber, "{v}", attrs ) == -1 ) {
1652 fprintf( stderr, "preread attrs encode failed.\n" );
1653 exit( EXIT_FAILURE );
1656 err = ber_flatten2( ber, &c[i].ldctl_value, 0 );
1658 fprintf( stderr, "preread flatten failed (%d)\n", err );
1659 exit( EXIT_FAILURE );
1662 c[i].ldctl_oid = LDAP_CONTROL_PRE_READ;
1663 c[i].ldctl_iscritical = preread > 1;
1667 if( attrs ) ldap_charray_free( attrs );
1671 BerElementBuffer berbuf;
1672 BerElement *ber = (BerElement *)&berbuf;
1673 char **attrs = NULL;
1675 if( postread_attrs ) {
1676 attrs = ldap_str2charray( postread_attrs, "," );
1679 ber_init2( ber, NULL, LBER_USE_DER );
1681 if( ber_printf( ber, "{v}", attrs ) == -1 ) {
1682 fprintf( stderr, "postread attrs encode failed.\n" );
1683 exit( EXIT_FAILURE );
1686 err = ber_flatten2( ber, &c[i].ldctl_value, 0 );
1688 fprintf( stderr, "postread flatten failed (%d)\n", err );
1689 exit( EXIT_FAILURE );
1692 c[i].ldctl_oid = LDAP_CONTROL_POST_READ;
1693 c[i].ldctl_iscritical = postread > 1;
1697 if( attrs ) ldap_charray_free( attrs );
1700 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
1702 if ( chainingResolve > -1 ) {
1703 BerElementBuffer berbuf;
1704 BerElement *ber = (BerElement *)&berbuf;
1706 ber_init2( ber, NULL, LBER_USE_DER );
1708 err = ber_printf( ber, "{e" /* } */, chainingResolve );
1711 fprintf( stderr, _("Chaining behavior control encoding error!\n") );
1712 exit( EXIT_FAILURE );
1715 if ( chainingContinuation > -1 ) {
1716 err = ber_printf( ber, "e", chainingContinuation );
1719 fprintf( stderr, _("Chaining behavior control encoding error!\n") );
1720 exit( EXIT_FAILURE );
1724 err = ber_printf( ber, /* { */ "N}" );
1727 fprintf( stderr, _("Chaining behavior control encoding error!\n") );
1728 exit( EXIT_FAILURE );
1731 if ( ber_flatten2( ber, &c[i].ldctl_value, 0 ) == -1 ) {
1732 exit( EXIT_FAILURE );
1736 BER_BVZERO( &c[i].ldctl_value );
1739 c[i].ldctl_oid = LDAP_CONTROL_X_CHAINING_BEHAVIOR;
1740 c[i].ldctl_iscritical = chaining > 1;
1744 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
1746 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
1747 if ( sessionTracking ) {
1748 if ( stValue.bv_val == NULL && st_value( ld, &stValue ) ) {
1749 exit( EXIT_FAILURE );
1752 c[i].ldctl_oid = LDAP_CONTROL_X_SESSION_TRACKING;
1753 c[i].ldctl_iscritical = 0;
1754 ber_dupbv( &c[i].ldctl_value, &stValue );
1759 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
1762 ctrls[i++] = extra_c++;
1764 for ( count = 0; count < unknown_ctrls_num; count++ ) {
1765 ctrls[i++] = &unknown_ctrls[count];
1769 err = ldap_set_option( ld, LDAP_OPT_SERVER_CONTROLS, ctrls );
1771 if ( err != LDAP_OPT_SUCCESS ) {
1772 for ( j = 0; j < i; j++ ) {
1773 if ( ctrls[j]->ldctl_iscritical ) crit = 1;
1775 fprintf( stderr, "Could not set %scontrols\n",
1776 crit ? "critical " : "" );
1781 exit( EXIT_FAILURE );
1786 tool_check_abandon( LDAP *ld, int msgid )
1790 switch ( gotintr ) {
1792 rc = ldap_cancel_s( ld, msgid, NULL, NULL );
1793 fprintf( stderr, "got interrupt, cancel got %d: %s\n",
1794 rc, ldap_err2string( rc ) );
1798 rc = ldap_abandon_ext( ld, msgid, NULL, NULL );
1799 fprintf( stderr, "got interrupt, abandon got %d: %s\n",
1800 rc, ldap_err2string( rc ) );
1804 /* just unbind, ignoring the request */
1812 print_prepostread( LDAP *ld, LDAPControl *ctrl, struct berval *what)
1817 tool_write_ldif( LDIF_PUT_COMMENT, "==> ",
1818 what->bv_val, what->bv_len );
1819 ber = ber_init( &ctrl->ldctl_value );
1820 if ( ber == NULL ) {
1824 } else if ( ber_scanf( ber, "{m{" /*}}*/, &bv ) == LBER_ERROR ) {
1829 tool_write_ldif( LDIF_PUT_VALUE, "dn", bv.bv_val, bv.bv_len );
1831 while ( ber_scanf( ber, "{m" /*}*/, &bv ) != LBER_ERROR ) {
1833 BerVarray vals = NULL;
1835 if ( ber_scanf( ber, "[W]", &vals ) == LBER_ERROR ||
1842 for ( i = 0; vals[ i ].bv_val != NULL; i++ ) {
1844 ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1845 bv.bv_val, vals[ i ].bv_val, vals[ i ].bv_len );
1848 ber_bvarray_free( vals );
1852 if ( ber != NULL ) {
1856 tool_write_ldif( LDIF_PUT_COMMENT, "<== ",
1857 what->bv_val, what->bv_len );
1863 print_preread( LDAP *ld, LDAPControl *ctrl )
1865 static struct berval what = BER_BVC( "preread" );
1867 return print_prepostread( ld, ctrl, &what );
1871 print_postread( LDAP *ld, LDAPControl *ctrl )
1873 static struct berval what = BER_BVC( "postread" );
1875 return print_prepostread( ld, ctrl, &what );
1879 print_paged_results( LDAP *ld, LDAPControl *ctrl )
1883 /* note: pr_cookie is being malloced; it's freed
1884 * the next time the control is sent, but the last
1885 * time it's not; we don't care too much, because
1886 * the last time an empty value is returned... */
1887 if ( ldap_parse_pageresponse_control( ld, ctrl, &estimate, &pr_cookie )
1894 /* FIXME: check buffer overflow */
1895 char buf[ BUFSIZ ], *ptr = buf;
1897 if ( estimate > 0 ) {
1898 ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
1899 "estimate=%d", estimate );
1902 if ( pr_cookie.bv_len > 0 ) {
1905 bv.bv_len = LUTIL_BASE64_ENCODE_LEN(
1906 pr_cookie.bv_len ) + 1;
1907 bv.bv_val = ber_memalloc( bv.bv_len + 1 );
1909 bv.bv_len = lutil_b64_ntop(
1910 (unsigned char *) pr_cookie.bv_val,
1912 bv.bv_val, bv.bv_len );
1914 ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
1915 "%scookie=%s", ptr == buf ? "" : " ",
1918 ber_memfree( bv.bv_val );
1920 pr_morePagedResults = 1;
1923 ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
1924 "%scookie=", ptr == buf ? "" : " " );
1927 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1928 "pagedresults", buf, ptr - buf );
1935 print_sss( LDAP *ld, LDAPControl *ctrl )
1941 rc = ldap_parse_sortresponse_control( ld, ctrl, &err, &attr );
1942 if ( rc == LDAP_SUCCESS ) {
1944 rc = snprintf( buf, sizeof(buf), "(%d) %s %s",
1945 err, ldap_err2string(err), attr ? attr : "" );
1947 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1948 "sortResult", buf, rc );
1954 #ifdef LDAP_CONTROL_X_DEREF
1956 print_deref( LDAP *ld, LDAPControl *ctrl )
1958 LDAPDerefRes *drhead = NULL, *dr;
1961 rc = ldap_parse_derefresponse_control( ld, ctrl, &drhead );
1962 if ( rc != LDAP_SUCCESS ) {
1966 for ( dr = drhead; dr != NULL; dr = dr->next ) {
1971 len = strlen( dr->derefAttr ) + STRLENOF(": ");
1973 for ( dv = dr->attrVals; dv != NULL; dv = dv->next ) {
1974 if ( dv->vals != NULL ) {
1976 ber_len_t tlen = strlen(dv->type);
1978 for ( j = 0; dv->vals[ j ].bv_val != NULL; j++ ) {
1979 len += STRLENOF("<:=>;") + tlen + 4*((dv->vals[ j ].bv_len - 1)/3 + 1);
1983 len += dr->derefVal.bv_len + STRLENOF("\n");
1984 buf = ldap_memalloc( len + 1 );
1985 if ( buf == NULL ) {
1986 rc = LDAP_NO_MEMORY;
1991 ptr = lutil_strcopy( ptr, dr->derefAttr );
1994 for ( dv = dr->attrVals; dv != NULL; dv = dv->next ) {
1995 if ( dv->vals != NULL ) {
1997 for ( j = 0; dv->vals[ j ].bv_val != NULL; j++ ) {
2000 for ( k = 0; k < dv->vals[ j ].bv_len; k++ ) {
2001 if ( !isprint( dv->vals[ j ].bv_val[k] ) ) {
2008 ptr = lutil_strcopy( ptr, dv->type );
2015 (unsigned char *) dv->vals[ j ].bv_val,
2016 dv->vals[ j ].bv_len,
2017 ptr, buf + len - ptr );
2022 ptr = lutil_memcopy( ptr, dv->vals[ j ].bv_val, dv->vals[ j ].bv_len );
2029 ptr = lutil_strncopy( ptr, dr->derefVal.bv_val, dr->derefVal.bv_len );
2032 assert( ptr <= buf + len );
2034 tool_write_ldif( LDIF_PUT_COMMENT, NULL, buf, ptr - buf);
2036 ldap_memfree( buf );
2042 ldap_derefresponse_free( drhead );
2048 #ifdef LDAP_CONTROL_X_WHATFAILED
2050 print_whatfailed( LDAP *ld, LDAPControl *ctrl )
2055 BerVarray bva = NULL;
2057 /* Create a BerElement from the berval returned in the control. */
2058 ber = ber_init( &ctrl->ldctl_value );
2060 if ( ber == NULL ) {
2061 return LDAP_NO_MEMORY;
2064 siz = sizeof(struct berval);
2065 tag = ber_scanf( ber, "[M]", &bva, &siz, 0 );
2066 if ( tag != LBER_ERROR ) {
2069 tool_write_ldif( LDIF_PUT_COMMENT, " what failed:", NULL, 0 );
2071 for ( i = 0; bva[i].bv_val != NULL; i++ ) {
2072 tool_write_ldif( LDIF_PUT_COMMENT, NULL, bva[i].bv_val, bva[i].bv_len );
2075 ldap_memfree( bva );
2085 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
2087 print_ppolicy( LDAP *ld, LDAPControl *ctrl )
2089 int expire = 0, grace = 0, rc;
2090 LDAPPasswordPolicyError pperr;
2092 rc = ldap_parse_passwordpolicy_control( ld, ctrl,
2093 &expire, &grace, &pperr );
2094 if ( rc == LDAP_SUCCESS ) {
2095 char buf[ BUFSIZ ], *ptr = buf;
2097 if ( expire != -1 ) {
2098 ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
2099 "expire=%d", expire );
2102 if ( grace != -1 ) {
2103 ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
2104 "%sgrace=%d", ptr == buf ? "" : " ", grace );
2107 if ( pperr != PP_noError ) {
2108 ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
2109 "%serror=%d (%s)", ptr == buf ? "" : " ",
2111 ldap_passwordpolicy_err2txt( pperr ) );
2114 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
2115 "ppolicy", buf, ptr - buf );
2122 void tool_print_ctrls(
2124 LDAPControl **ctrls )
2129 for ( i = 0; ctrls[i] != NULL; i++ ) {
2130 /* control: OID criticality base64value */
2131 struct berval b64 = BER_BVNULL;
2136 /* FIXME: there might be cases where a control has NULL OID;
2137 * this makes little sense, especially when returned by the
2138 * server, but libldap happily allows it */
2139 if ( ctrls[i]->ldctl_oid == NULL ) {
2144 len += strlen( ctrls[i]->ldctl_oid );
2146 /* add enough for space after OID and the critical value itself */
2147 len += ctrls[i]->ldctl_iscritical
2148 ? sizeof("true") : sizeof("false");
2150 /* convert to base64 */
2151 if ( !BER_BVISNULL( &ctrls[i]->ldctl_value ) ) {
2152 b64.bv_len = LUTIL_BASE64_ENCODE_LEN(
2153 ctrls[i]->ldctl_value.bv_len ) + 1;
2154 b64.bv_val = ber_memalloc( b64.bv_len + 1 );
2156 b64.bv_len = lutil_b64_ntop(
2157 (unsigned char *) ctrls[i]->ldctl_value.bv_val,
2158 ctrls[i]->ldctl_value.bv_len,
2159 b64.bv_val, b64.bv_len );
2163 len += 1 + b64.bv_len;
2166 ptr = str = malloc( len + 1 );
2168 ptr = lutil_strcopy( ptr, ": " );
2170 ptr = lutil_strcopy( ptr, ctrls[i]->ldctl_oid );
2171 ptr = lutil_strcopy( ptr, ctrls[i]->ldctl_iscritical
2172 ? " true" : " false" );
2175 ptr = lutil_strcopy( ptr, " " );
2176 ptr = lutil_strcopy( ptr, b64.bv_val );
2180 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
2181 "control", str, len );
2186 ber_memfree( b64.bv_val );
2189 /* known controls */
2190 for ( j = 0; tool_ctrl_response[j].oid != NULL; j++ ) {
2191 if ( strcmp( tool_ctrl_response[j].oid, ctrls[i]->ldctl_oid ) == 0 ) {
2192 if ( !tool_ctrl_response[j].mask & tool_type ) {
2193 /* this control should not appear
2194 * with this tool; warning? */
2200 if ( tool_ctrl_response[j].oid != NULL && tool_ctrl_response[j].func ) {
2201 (void)tool_ctrl_response[j].func( ld, ctrls[i] );
2207 tool_write_ldif( int type, char *name, char *value, ber_len_t vallen )
2211 if (( ldif = ldif_put( type, name, value, vallen )) == NULL ) {
2215 fputs( ldif, stdout );
2216 ber_memfree( ldif );
2222 tool_is_oid( const char *s )
2226 if ( !isdigit( (unsigned char) s[ 0 ] ) ) {
2230 for ( ; s[ 0 ]; s++ ) {
2231 if ( s[ 0 ] == '.' ) {
2232 if ( s[ 1 ] == '\0' ) {
2239 if ( !isdigit( (unsigned char) s[ 0 ] ) ) {
2243 if ( first == 1 && s[ 0 ] == '0' && s[ 1 ] != '.' ) {