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-2010 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;
99 /* support deprecated early version of proxyAuthz */
100 #define LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ "2.16.840.1.113730.3.4.12"
101 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
102 char *proxydn = NULL;
103 #endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
109 static char *preread_attrs = NULL;
111 static char *postread_attrs = NULL;
112 ber_int_t pr_morePagedResults = 1;
113 struct berval pr_cookie = { 0, NULL };
114 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
116 static int chainingResolve = -1;
117 static int chainingContinuation = -1;
118 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
119 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
120 static int sessionTracking = 0;
121 struct berval stValue;
122 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
125 struct berval *vlvContext;
127 LDAPControl *unknown_ctrls = NULL;
128 int unknown_ctrls_num = 0;
131 struct timeval nettimeout = { -1 , 0 };
133 typedef int (*print_ctrl_fn)( LDAP *ld, LDAPControl *ctrl );
135 static int print_preread( LDAP *ld, LDAPControl *ctrl );
136 static int print_postread( LDAP *ld, LDAPControl *ctrl );
137 static int print_paged_results( LDAP *ld, LDAPControl *ctrl );
138 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
139 static int print_ppolicy( LDAP *ld, LDAPControl *ctrl );
141 static int print_sss( LDAP *ld, LDAPControl *ctrl );
142 static int print_vlv( LDAP *ld, LDAPControl *ctrl );
143 #ifdef LDAP_CONTROL_X_DEREF
144 static int print_deref( LDAP *ld, LDAPControl *ctrl );
146 #ifdef LDAP_CONTROL_X_WHATFAILED
147 static int print_whatfailed( LDAP *ld, LDAPControl *ctrl );
150 static struct tool_ctrls_t {
154 } tool_ctrl_response[] = {
155 { LDAP_CONTROL_PRE_READ, TOOL_ALL, print_preread },
156 { LDAP_CONTROL_POST_READ, TOOL_ALL, print_postread },
157 { LDAP_CONTROL_PAGEDRESULTS, TOOL_SEARCH, print_paged_results },
158 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
159 { LDAP_CONTROL_PASSWORDPOLICYRESPONSE, TOOL_ALL, print_ppolicy },
161 { LDAP_CONTROL_SORTRESPONSE, TOOL_SEARCH, print_sss },
162 { LDAP_CONTROL_VLVRESPONSE, TOOL_SEARCH, print_vlv },
163 #ifdef LDAP_CONTROL_X_DEREF
164 { LDAP_CONTROL_X_DEREF, TOOL_SEARCH, print_deref },
166 #ifdef LDAP_CONTROL_X_WHATFAILED
167 { LDAP_CONTROL_X_WHATFAILED, TOOL_ALL, print_whatfailed },
173 enum { Intr_None = 0, Intr_Abandon, Intr_Cancel, Intr_Ignore };
174 static volatile sig_atomic_t gotintr, abcan;
177 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
179 st_value( LDAP *ld, struct berval *value )
181 char *ip = NULL, *name = NULL;
182 struct berval id = { 0 };
183 char namebuf[ MAXHOSTNAMELEN ];
185 if ( gethostname( namebuf, sizeof( namebuf ) ) == 0 ) {
191 h = gethostbyname( name );
193 AC_MEMCPY( &addr, h->h_addr, sizeof( addr ) );
194 ip = inet_ntoa( addr );
198 #ifdef HAVE_CYRUS_SASL
199 if ( sasl_authz_id != NULL ) {
200 ber_str2bv( sasl_authz_id, 0, 0, &id );
202 } else if ( sasl_authc_id != NULL ) {
203 ber_str2bv( sasl_authc_id, 0, 0, &id );
206 #endif /* HAVE_CYRUS_SASL */
207 if ( binddn != NULL ) {
208 ber_str2bv( binddn, 0, 0, &id );
211 if ( ldap_create_session_tracking_value( ld,
212 ip, name, LDAP_CONTROL_X_SESSION_TRACKING_USERNAME,
215 fprintf( stderr, _("Session tracking control encoding error!\n") );
221 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
230 tool_init( tool_type_t type )
233 ldap_pvt_setlocale(LC_MESSAGES, "");
234 ldap_pvt_bindtextdomain(OPENLDAP_PACKAGE, LDAP_LOCALEDIR);
235 ldap_pvt_textdomain(OPENLDAP_PACKAGE);
241 #ifdef HAVE_CYRUS_SASL
245 ldap_pvt_tls_destroy();
248 if ( ldapuri != NULL ) {
249 ber_memfree( ldapuri );
253 if ( pr_cookie.bv_val != NULL ) {
254 ber_memfree( pr_cookie.bv_val );
255 pr_cookie.bv_val = NULL;
256 pr_cookie.bv_len = 0;
259 if ( binddn != NULL ) {
260 ber_memfree( binddn );
264 if ( passwd.bv_val != NULL ) {
265 ber_memfree( passwd.bv_val );
271 tool_common_usage( void )
273 static const char *const descriptions[] = {
274 N_(" -d level set LDAP debugging level to `level'\n"),
275 N_(" -D binddn bind DN\n"),
276 N_(" -e [!]<ext>[=<extparam>] general extensions (! indicates criticality)\n")
277 N_(" [!]assert=<filter> (RFC 4528; a RFC 4515 Filter string)\n")
278 N_(" [!]authzid=<authzid> (RFC 4370; \"dn:<dn>\" or \"u:<user>\")\n")
279 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
281 /* non-advertized support for proxyDN */
282 N_(" [!]proxydn=<dn> (a RFC 4514 DN string)\n")
285 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
286 N_(" [!]chaining[=<resolveBehavior>[/<continuationBehavior>]]\n")
287 N_(" one of \"chainingPreferred\", \"chainingRequired\",\n")
288 N_(" \"referralsPreferred\", \"referralsRequired\"\n")
289 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
290 N_(" [!]manageDSAit (RFC 3296)\n")
292 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
295 N_(" [!]postread[=<attrs>] (RFC 4527; comma-separated attr list)\n")
296 N_(" [!]preread[=<attrs>] (RFC 4527; comma-separated attr list)\n")
298 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
299 N_(" [!]sessiontracking\n")
300 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
301 N_(" abandon, cancel, ignore (SIGINT sends abandon/cancel,\n"
302 " or ignores response; if critical, doesn't wait for SIGINT.\n"
303 " not really controls)\n")
304 N_(" -h host LDAP server\n"),
305 N_(" -H URI LDAP Uniform Resource Identifier(s)\n"),
306 N_(" -I use SASL Interactive mode\n"),
307 N_(" -n show what would be done but don't actually do it\n"),
308 N_(" -N do not use reverse DNS to canonicalize SASL host name\n"),
309 N_(" -O props SASL security properties\n"),
310 N_(" -o <opt>[=<optparam] general options\n"),
311 N_(" nettimeout=<timeout> (in seconds, or \"none\" or \"max\")\n"),
312 N_(" -p port port on LDAP server\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 if( 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" );
448 assert( authzid == NULL );
451 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
452 } else if ( strcasecmp( control, "proxydn" ) == 0 ) {
453 if( proxydn != NULL ) {
454 fprintf( stderr, "proxydn control previously specified\n");
455 exit( EXIT_FAILURE );
457 if( authzid != NULL ) {
458 fprintf( stderr, "proxydn control incompatible with authzid\n");
459 exit( EXIT_FAILURE );
461 if( cvalue == NULL ) {
462 fprintf( stderr, "proxydn: control value expected\n" );
466 fprintf( stderr, "proxydn: must be marked critical\n" );
470 assert( proxydn == NULL );
472 #endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
474 } else if ( ( strcasecmp( control, "relax" ) == 0 ) ||
475 ( strcasecmp( control, "manageDIT" ) == 0 ) )
479 "relax control previously specified\n");
480 exit( EXIT_FAILURE );
482 if( cvalue != NULL ) {
484 "relax: no control value expected\n" );
488 manageDIT = 1 + crit;
490 } else if ( strcasecmp( control, "manageDSAit" ) == 0 ) {
493 "manageDSAit control previously specified\n");
494 exit( EXIT_FAILURE );
496 if( cvalue != NULL ) {
498 "manageDSAit: no control value expected\n" );
502 manageDSAit = 1 + crit;
504 } else if ( strcasecmp( control, "noop" ) == 0 ) {
506 fprintf( stderr, "noop control previously specified\n");
507 exit( EXIT_FAILURE );
509 if( cvalue != NULL ) {
510 fprintf( stderr, "noop: no control value expected\n" );
516 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
517 } else if ( strcasecmp( control, "ppolicy" ) == 0 ) {
519 fprintf( stderr, "ppolicy control previously specified\n");
520 exit( EXIT_FAILURE );
522 if( cvalue != NULL ) {
523 fprintf( stderr, "ppolicy: no control value expected\n" );
527 fprintf( stderr, "ppolicy: critical flag not allowed\n" );
534 } else if ( strcasecmp( control, "preread" ) == 0 ) {
536 fprintf( stderr, "preread control previously specified\n");
537 exit( EXIT_FAILURE );
541 preread_attrs = cvalue;
543 } else if ( strcasecmp( control, "postread" ) == 0 ) {
545 fprintf( stderr, "postread control previously specified\n");
546 exit( EXIT_FAILURE );
550 postread_attrs = cvalue;
552 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
553 } else if ( strcasecmp( control, "chaining" ) == 0 ) {
556 if ( cvalue != NULL ) {
559 continuation = strchr( cvalue, '/' );
560 if ( continuation ) {
561 /* FIXME: this makes sense only in searches */
562 *continuation++ = '\0';
563 if ( strcasecmp( continuation, "chainingPreferred" ) == 0 ) {
564 chainingContinuation = LDAP_CHAINING_PREFERRED;
565 } else if ( strcasecmp( continuation, "chainingRequired" ) == 0 ) {
566 chainingContinuation = LDAP_CHAINING_REQUIRED;
567 } else if ( strcasecmp( continuation, "referralsPreferred" ) == 0 ) {
568 chainingContinuation = LDAP_REFERRALS_PREFERRED;
569 } else if ( strcasecmp( continuation, "referralsRequired" ) == 0 ) {
570 chainingContinuation = LDAP_REFERRALS_REQUIRED;
573 "chaining behavior control "
574 "continuation value \"%s\" invalid\n",
576 exit( EXIT_FAILURE );
580 if ( strcasecmp( cvalue, "chainingPreferred" ) == 0 ) {
581 chainingResolve = LDAP_CHAINING_PREFERRED;
582 } else if ( strcasecmp( cvalue, "chainingRequired" ) == 0 ) {
583 chainingResolve = LDAP_CHAINING_REQUIRED;
584 } else if ( strcasecmp( cvalue, "referralsPreferred" ) == 0 ) {
585 chainingResolve = LDAP_REFERRALS_PREFERRED;
586 } else if ( strcasecmp( cvalue, "referralsRequired" ) == 0 ) {
587 chainingResolve = LDAP_REFERRALS_REQUIRED;
590 "chaining behavior control "
591 "resolve value \"%s\" invalid\n",
593 exit( EXIT_FAILURE );
596 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
598 /* this shouldn't go here, really; but it's a feature... */
599 } else if ( strcasecmp( control, "abandon" ) == 0 ) {
600 abcan = Intr_Abandon;
605 } else if ( strcasecmp( control, "cancel" ) == 0 ) {
611 } else if ( strcasecmp( control, "ignore" ) == 0 ) {
617 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
618 } else if ( strcasecmp( control, "sessiontracking" ) == 0 ) {
619 if ( sessionTracking ) {
620 fprintf( stderr, "%s: session tracking can be only specified once\n", prog );
621 exit( EXIT_FAILURE );
624 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
626 } else if ( tool_is_oid( control ) ) {
627 LDAPControl *tmpctrls, ctrl;
629 tmpctrls = (LDAPControl *)ber_memrealloc( unknown_ctrls,
630 (unknown_ctrls_num + 1)*sizeof( LDAPControl ) );
631 if ( tmpctrls == NULL ) {
632 fprintf( stderr, "%s: no memory?\n", prog );
633 exit( EXIT_FAILURE );
635 unknown_ctrls = tmpctrls;
636 ctrl.ldctl_oid = control;
637 ctrl.ldctl_value.bv_val = NULL;
638 ctrl.ldctl_value.bv_len = 0;
639 ctrl.ldctl_iscritical = crit;
641 if ( cvalue != NULL ) {
643 size_t len = strlen( cvalue );
646 bv.bv_len = LUTIL_BASE64_DECODE_LEN( len );
647 bv.bv_val = ber_memalloc( bv.bv_len + 1 );
649 retcode = lutil_b64_pton( cvalue,
650 (unsigned char *)bv.bv_val,
653 if ( retcode == -1 || (unsigned) retcode > bv.bv_len ) {
654 fprintf( stderr, "Unable to parse value of general control %s\n",
660 ctrl.ldctl_value = bv;
663 unknown_ctrls[ unknown_ctrls_num ] = ctrl;
667 fprintf( stderr, "Invalid general control name: %s\n",
672 case 'f': /* read from file */
673 if( infile != NULL ) {
674 fprintf( stderr, "%s: -f previously specified\n", prog );
675 exit( EXIT_FAILURE );
677 infile = ber_strdup( optarg );
679 case 'h': /* ldap host */
680 if( ldaphost != NULL ) {
681 fprintf( stderr, "%s: -h previously specified\n", prog );
682 exit( EXIT_FAILURE );
684 ldaphost = ber_strdup( optarg );
686 case 'H': /* ldap URI */
687 if( ldapuri != NULL ) {
688 fprintf( stderr, "%s: -H previously specified\n", prog );
689 exit( EXIT_FAILURE );
691 ldapuri = ber_strdup( optarg );
694 #ifdef HAVE_CYRUS_SASL
695 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
696 fprintf( stderr, "%s: incompatible previous "
697 "authentication choice\n",
699 exit( EXIT_FAILURE );
701 authmethod = LDAP_AUTH_SASL;
702 sasl_flags = LDAP_SASL_INTERACTIVE;
705 fprintf( stderr, "%s: was not compiled with SASL support\n",
707 exit( EXIT_FAILURE );
710 /* enable Manage DSA IT */
713 case 'n': /* print operations, don't actually do them */
720 control = ber_strdup( optarg );
721 if ( (cvalue = strchr( control, '=' )) != NULL ) {
725 if ( strcasecmp( control, "nettimeout" ) == 0 ) {
726 if( nettimeout.tv_sec != -1 ) {
727 fprintf( stderr, "nettimeout option previously specified\n");
728 exit( EXIT_FAILURE );
730 if( cvalue == NULL || cvalue[0] == '\0' ) {
731 fprintf( stderr, "nettimeout: option value expected\n" );
734 if ( strcasecmp( cvalue, "none" ) == 0 ) {
735 nettimeout.tv_sec = 0;
736 } else if ( strcasecmp( cvalue, "max" ) == 0 ) {
737 nettimeout.tv_sec = LDAP_MAXINT;
739 ival = strtol( cvalue, &next, 10 );
740 if ( next == NULL || next[0] != '\0' ) {
742 _("Unable to parse network timeout \"%s\"\n"), cvalue );
743 exit( EXIT_FAILURE );
745 nettimeout.tv_sec = ival;
747 if( nettimeout.tv_sec < 0 || nettimeout.tv_sec > LDAP_MAXINT ) {
748 fprintf( stderr, _("%s: invalid network timeout (%ld) specified\n"),
749 prog, (long)nettimeout.tv_sec );
750 exit( EXIT_FAILURE );
753 fprintf( stderr, "Invalid general option name: %s\n",
759 #ifdef HAVE_CYRUS_SASL
760 if( sasl_secprops != NULL ) {
761 fprintf( stderr, "%s: -O previously specified\n", prog );
762 exit( EXIT_FAILURE );
764 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
765 fprintf( stderr, "%s: incompatible previous "
766 "authentication choice\n", prog );
767 exit( EXIT_FAILURE );
769 authmethod = LDAP_AUTH_SASL;
770 sasl_secprops = ber_strdup( optarg );
772 fprintf( stderr, "%s: not compiled with SASL support\n", prog );
773 exit( EXIT_FAILURE );
778 fprintf( stderr, "%s: -p previously specified\n", prog );
779 exit( EXIT_FAILURE );
781 ival = strtol( optarg, &next, 10 );
782 if ( next == NULL || next[0] != '\0' ) {
783 fprintf( stderr, "%s: unable to parse port number \"%s\"\n", prog, optarg );
784 exit( EXIT_FAILURE );
789 ival = strtol( optarg, &next, 10 );
790 if ( next == NULL || next[0] != '\0' ) {
791 fprintf( stderr, "%s: unable to parse protocol version \"%s\"\n", prog, optarg );
792 exit( EXIT_FAILURE );
796 if( protocol == LDAP_VERSION3 ) {
797 fprintf( stderr, "%s: -P 2 incompatible with version %d\n",
799 exit( EXIT_FAILURE );
801 protocol = LDAP_VERSION2;
804 if( protocol == LDAP_VERSION2 ) {
805 fprintf( stderr, "%s: -P 2 incompatible with version %d\n",
807 exit( EXIT_FAILURE );
809 protocol = LDAP_VERSION3;
812 fprintf( stderr, "%s: protocol version should be 2 or 3\n",
818 #ifdef HAVE_CYRUS_SASL
819 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
820 fprintf( stderr, "%s: incompatible previous "
821 "authentication choice\n",
823 exit( EXIT_FAILURE );
825 authmethod = LDAP_AUTH_SASL;
826 sasl_flags = LDAP_SASL_QUIET;
829 fprintf( stderr, "%s: not compiled with SASL support\n",
831 exit( EXIT_FAILURE );
834 #ifdef HAVE_CYRUS_SASL
835 if( sasl_realm != NULL ) {
836 fprintf( stderr, "%s: -R previously specified\n", prog );
837 exit( EXIT_FAILURE );
839 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
840 fprintf( stderr, "%s: incompatible previous "
841 "authentication choice\n",
843 exit( EXIT_FAILURE );
845 authmethod = LDAP_AUTH_SASL;
846 sasl_realm = ber_strdup( optarg );
848 fprintf( stderr, "%s: not compiled with SASL support\n",
850 exit( EXIT_FAILURE );
854 #ifdef HAVE_CYRUS_SASL
855 if( sasl_authc_id != NULL ) {
856 fprintf( stderr, "%s: -U previously specified\n", prog );
857 exit( EXIT_FAILURE );
859 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
860 fprintf( stderr, "%s: incompatible previous "
861 "authentication choice\n",
863 exit( EXIT_FAILURE );
865 authmethod = LDAP_AUTH_SASL;
866 sasl_authc_id = ber_strdup( optarg );
868 fprintf( stderr, "%s: not compiled with SASL support\n",
870 exit( EXIT_FAILURE );
873 case 'v': /* verbose mode */
876 case 'V': /* version */
879 case 'w': /* password */
880 passwd.bv_val = ber_strdup( optarg );
884 for( p = optarg; *p != '\0'; p++ ) {
888 passwd.bv_len = strlen( passwd.bv_val );
897 #ifdef HAVE_CYRUS_SASL
898 if( sasl_mech != NULL ) {
899 fprintf( stderr, "%s: -Y previously specified\n", prog );
900 exit( EXIT_FAILURE );
902 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
904 "%s: incompatible with authentication choice\n", prog );
905 exit( EXIT_FAILURE );
907 authmethod = LDAP_AUTH_SASL;
908 sasl_mech = ber_strdup( optarg );
910 fprintf( stderr, "%s: not compiled with SASL support\n", prog );
911 exit( EXIT_FAILURE );
915 if( authmethod != -1 && authmethod != LDAP_AUTH_SIMPLE ) {
916 fprintf( stderr, "%s: incompatible with previous "
917 "authentication choice\n", prog );
918 exit( EXIT_FAILURE );
920 authmethod = LDAP_AUTH_SIMPLE;
923 #ifdef HAVE_CYRUS_SASL
924 if( sasl_authz_id != NULL ) {
925 fprintf( stderr, "%s: -X previously specified\n", prog );
926 exit( EXIT_FAILURE );
928 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
929 fprintf( stderr, "%s: -X incompatible with "
930 "authentication choice\n", prog );
931 exit( EXIT_FAILURE );
933 authmethod = LDAP_AUTH_SASL;
934 sasl_authz_id = ber_strdup( optarg );
936 fprintf( stderr, "%s: not compiled with SASL support\n", prog );
937 exit( EXIT_FAILURE );
944 fprintf( stderr, "%s: not compiled with TLS support\n", prog );
945 exit( EXIT_FAILURE );
949 if( handle_private_option( i ) ) break;
950 fprintf( stderr, "%s: unrecognized option -%c\n",
957 /* prevent bad linking */
959 api.ldapai_info_version = LDAP_API_INFO_VERSION;
961 if ( ldap_get_option(NULL, LDAP_OPT_API_INFO, &api)
962 != LDAP_OPT_SUCCESS )
964 fprintf( stderr, "%s: ldap_get_option(API_INFO) failed\n", prog );
965 exit( EXIT_FAILURE );
968 if (api.ldapai_info_version != LDAP_API_INFO_VERSION) {
969 fprintf( stderr, "LDAP APIInfo version mismatch: "
970 "library %d, header %d\n",
971 api.ldapai_info_version, LDAP_API_INFO_VERSION );
972 exit( EXIT_FAILURE );
975 if( api.ldapai_api_version != LDAP_API_VERSION ) {
976 fprintf( stderr, "LDAP API version mismatch: "
977 "library %d, header %d\n",
978 api.ldapai_api_version, LDAP_API_VERSION );
979 exit( EXIT_FAILURE );
982 if( strcmp(api.ldapai_vendor_name, LDAP_VENDOR_NAME ) != 0 ) {
983 fprintf( stderr, "LDAP vendor name mismatch: "
984 "library %s, header %s\n",
985 api.ldapai_vendor_name, LDAP_VENDOR_NAME );
986 exit( EXIT_FAILURE );
989 if( api.ldapai_vendor_version != LDAP_VENDOR_VERSION ) {
990 fprintf( stderr, "LDAP vendor version mismatch: "
991 "library %d, header %d\n",
992 api.ldapai_vendor_version, LDAP_VENDOR_VERSION );
993 exit( EXIT_FAILURE );
997 fprintf( stderr, "%s: %s\t(LDAP library: %s %d)\n",
999 LDAP_VENDOR_NAME, LDAP_VENDOR_VERSION );
1000 if (version > 1) exit( EXIT_SUCCESS );
1003 ldap_memfree( api.ldapai_vendor_name );
1004 ber_memvfree( (void **)api.ldapai_extensions );
1008 protocol = LDAP_VERSION3;
1010 if (authmethod == -1 && protocol > LDAP_VERSION2) {
1011 #ifdef HAVE_CYRUS_SASL
1012 if ( binddn != NULL ) {
1013 authmethod = LDAP_AUTH_SIMPLE;
1015 authmethod = LDAP_AUTH_SASL;
1018 authmethod = LDAP_AUTH_SIMPLE;
1022 if( ldapuri == NULL ) {
1023 if( ldapport && ( ldaphost == NULL )) {
1024 fprintf( stderr, "%s: -p without -h is invalid.\n", prog );
1025 exit( EXIT_FAILURE );
1028 if( ldaphost != NULL ) {
1029 fprintf( stderr, "%s: -H incompatible with -h\n", prog );
1030 exit( EXIT_FAILURE );
1033 fprintf( stderr, "%s: -H incompatible with -p\n", prog );
1034 exit( EXIT_FAILURE );
1038 if( protocol == LDAP_VERSION2 ) {
1039 if( assertctl || authzid || manageDIT || manageDSAit ||
1040 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
1042 #endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
1043 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
1046 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
1048 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
1049 noop || ppolicy || preread || postread )
1051 fprintf( stderr, "%s: -e/-M incompatible with LDAPv2\n", prog );
1052 exit( EXIT_FAILURE );
1056 fprintf( stderr, "%s: -Z incompatible with LDAPv2\n", prog );
1057 exit( EXIT_FAILURE );
1060 #ifdef HAVE_CYRUS_SASL
1061 if( authmethod == LDAP_AUTH_SASL ) {
1062 fprintf( stderr, "%s: -[IOQRUXY] incompatible with LDAPv2\n",
1064 exit( EXIT_FAILURE );
1072 tool_conn_setup( int dont, void (*private_setup)( LDAP * ) )
1077 if( ber_set_option( NULL, LBER_OPT_DEBUG_LEVEL, &debug )
1078 != LBER_OPT_SUCCESS )
1081 "Could not set LBER_OPT_DEBUG_LEVEL %d\n", debug );
1083 if( ldap_set_option( NULL, LDAP_OPT_DEBUG_LEVEL, &debug )
1084 != LDAP_OPT_SUCCESS )
1087 "Could not set LDAP_OPT_DEBUG_LEVEL %d\n", debug );
1092 (void) SIGNAL( SIGPIPE, SIG_IGN );
1096 SIGNAL( SIGINT, do_sig );
1102 if( ( ldaphost != NULL || ldapport ) && ( ldapuri == NULL ) ) {
1105 memset( &url, 0, sizeof(url));
1107 url.lud_scheme = "ldap";
1108 url.lud_host = ldaphost;
1109 url.lud_port = ldapport;
1110 url.lud_scope = LDAP_SCOPE_DEFAULT;
1112 ldapuri = ldap_url_desc2str( &url );
1114 } else if ( ldapuri != NULL ) {
1115 LDAPURLDesc *ludlist, **ludp;
1119 rc = ldap_url_parselist( &ludlist, ldapuri );
1120 if ( rc != LDAP_URL_SUCCESS ) {
1122 "Could not parse LDAP URI(s)=%s (%d)\n",
1124 exit( EXIT_FAILURE );
1127 for ( ludp = &ludlist; *ludp != NULL; ) {
1128 LDAPURLDesc *lud = *ludp;
1131 if ( lud->lud_dn != NULL && lud->lud_dn[ 0 ] != '\0' &&
1132 ( lud->lud_host == NULL || lud->lud_host[0] == '\0' ) )
1134 /* if no host but a DN is provided,
1135 * use DNS SRV to gather the host list
1136 * and turn it into a list of URIs
1137 * using the scheme provided */
1138 char *domain = NULL,
1142 len_proto = strlen( lud->lud_scheme );
1144 if ( ldap_dn2domain( lud->lud_dn, &domain )
1148 "DNS SRV: Could not turn "
1149 "DN=\"%s\" into a domain\n",
1154 rc = ldap_domain2hostlist( domain, &hostlist );
1157 "DNS SRV: Could not turn "
1158 "domain=%s into a hostlist\n",
1163 hosts = ldap_str2charray( hostlist, " " );
1164 if ( hosts == NULL ) {
1166 "DNS SRV: Could not parse "
1167 "hostlist=\"%s\"\n",
1172 for ( i = 0; hosts[ i ] != NULL; i++ )
1175 tmp = (char **)ber_memrealloc( urls, sizeof( char * ) * ( nurls + i + 1 ) );
1176 if ( tmp == NULL ) {
1178 "DNS SRV: out of memory?\n" );
1182 urls[ nurls ] = NULL;
1184 for ( i = 0; hosts[ i ] != NULL; i++ ) {
1185 size_t len = len_proto
1187 + strlen( hosts[ i ] )
1190 urls[ nurls + i + 1 ] = NULL;
1191 urls[ nurls + i ] = (char *)malloc( sizeof( char ) * len );
1192 if ( urls[ nurls + i ] == NULL ) {
1194 "DNS SRV: out of memory?\n" );
1198 snprintf( urls[ nurls + i ], len, "%s://%s",
1199 lud->lud_scheme, hosts[ i ] );
1204 ber_memvfree( (void **)hosts );
1205 ber_memfree( hostlist );
1206 ber_memfree( domain );
1209 tmp = (char **)ber_memrealloc( urls, sizeof( char * ) * ( nurls + 2 ) );
1210 if ( tmp == NULL ) {
1212 "DNS SRV: out of memory?\n" );
1216 urls[ nurls + 1 ] = NULL;
1218 urls[ nurls ] = ldap_url_desc2str( lud );
1219 if ( urls[ nurls ] == NULL ) {
1221 "DNS SRV: out of memory?\n" );
1227 *ludp = lud->lud_next;
1229 lud->lud_next = NULL;
1230 ldap_free_urldesc( lud );
1233 if ( ludlist != NULL ) {
1234 ldap_free_urllist( ludlist );
1235 exit( EXIT_FAILURE );
1237 } else if ( urls == NULL ) {
1238 exit( EXIT_FAILURE );
1241 ldap_memfree( ldapuri );
1242 ldapuri = ldap_charray2str( urls, " " );
1243 ber_memvfree( (void **)urls );
1247 fprintf( stderr, "ldap_initialize( %s )\n",
1248 ldapuri != NULL ? ldapuri : "<DEFAULT>" );
1250 rc = ldap_initialize( &ld, ldapuri );
1251 if( rc != LDAP_SUCCESS ) {
1253 "Could not create LDAP session handle for URI=%s (%d): %s\n",
1254 ldapuri, rc, ldap_err2string(rc) );
1255 exit( EXIT_FAILURE );
1258 if( private_setup ) private_setup( ld );
1261 if( ldap_set_option( ld, LDAP_OPT_REFERRALS,
1262 referrals ? LDAP_OPT_ON : LDAP_OPT_OFF ) != LDAP_OPT_SUCCESS )
1264 fprintf( stderr, "Could not set LDAP_OPT_REFERRALS %s\n",
1265 referrals ? "on" : "off" );
1266 exit( EXIT_FAILURE );
1269 #ifdef HAVE_CYRUS_SASL
1271 if( ldap_set_option( ld, LDAP_OPT_X_SASL_NOCANON,
1272 nocanon ? LDAP_OPT_ON : LDAP_OPT_OFF ) != LDAP_OPT_SUCCESS )
1274 fprintf( stderr, "Could not set LDAP_OPT_X_SASL_NOCANON %s\n",
1275 nocanon ? "on" : "off" );
1276 exit( EXIT_FAILURE );
1279 if( ldap_set_option( ld, LDAP_OPT_PROTOCOL_VERSION, &protocol )
1280 != LDAP_OPT_SUCCESS )
1282 fprintf( stderr, "Could not set LDAP_OPT_PROTOCOL_VERSION %d\n",
1284 exit( EXIT_FAILURE );
1288 rc = ldap_start_tls_s( ld, NULL, NULL );
1289 if ( rc != LDAP_SUCCESS ) {
1291 ldap_get_option( ld, LDAP_OPT_DIAGNOSTIC_MESSAGE, (void*)&msg);
1292 tool_perror( "ldap_start_tls", rc, NULL, NULL, msg, NULL );
1294 if ( use_tls > 1 ) {
1295 exit( EXIT_FAILURE );
1300 if ( nettimeout.tv_sec > 0 ) {
1301 if ( ldap_set_option( ld, LDAP_OPT_NETWORK_TIMEOUT, (void *) &nettimeout )
1302 != LDAP_OPT_SUCCESS )
1304 fprintf( stderr, "Could not set LDAP_OPT_NETWORK_TIMEOUT %ld\n",
1305 (long)nettimeout.tv_sec );
1306 exit( EXIT_FAILURE );
1316 tool_bind( LDAP *ld )
1318 LDAPControl **sctrlsp = NULL;
1319 LDAPControl *sctrls[3];
1320 LDAPControl sctrl[3];
1323 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
1326 c.ldctl_oid = LDAP_CONTROL_PASSWORDPOLICYREQUEST;
1327 c.ldctl_value.bv_val = NULL;
1328 c.ldctl_value.bv_len = 0;
1329 c.ldctl_iscritical = 0;
1331 sctrls[nsctrls] = &sctrl[nsctrls];
1332 sctrls[++nsctrls] = NULL;
1336 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
1337 if ( sessionTracking ) {
1340 if (stValue.bv_val == NULL && st_value( ld, &stValue ) ) {
1341 exit( EXIT_FAILURE );
1344 c.ldctl_oid = LDAP_CONTROL_X_SESSION_TRACKING;
1345 c.ldctl_iscritical = 0;
1346 ber_dupbv( &c.ldctl_value, &stValue );
1349 sctrls[nsctrls] = &sctrl[nsctrls];
1350 sctrls[++nsctrls] = NULL;
1352 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
1358 assert( nsctrls < (int) (sizeof(sctrls)/sizeof(sctrls[0])) );
1360 if ( authmethod == LDAP_AUTH_SASL ) {
1361 #ifdef HAVE_CYRUS_SASL
1365 if( sasl_secprops != NULL ) {
1366 rc = ldap_set_option( ld, LDAP_OPT_X_SASL_SECPROPS,
1367 (void *) sasl_secprops );
1369 if( rc != LDAP_OPT_SUCCESS ) {
1371 "Could not set LDAP_OPT_X_SASL_SECPROPS: %s\n",
1373 exit( LDAP_LOCAL_ERROR );
1377 defaults = lutil_sasl_defaults( ld,
1384 rc = ldap_sasl_interactive_bind_s( ld, binddn, sasl_mech,
1386 NULL, sasl_flags, lutil_sasl_interact, defaults );
1388 lutil_sasl_freedefs( defaults );
1389 if( rc != LDAP_SUCCESS ) {
1391 ldap_get_option( ld, LDAP_OPT_DIAGNOSTIC_MESSAGE, (void*)&msg);
1392 tool_perror( "ldap_sasl_interactive_bind_s",
1393 rc, NULL, NULL, msg, NULL );
1398 fprintf( stderr, "%s: not compiled with SASL support\n", prog );
1399 exit( LDAP_NOT_SUPPORTED );
1403 LDAPMessage *result;
1404 LDAPControl **ctrls;
1406 char *matched = NULL;
1414 rc = ldap_sasl_bind( ld, binddn, LDAP_SASL_SIMPLE, &passwd,
1415 sctrlsp, NULL, &msgid );
1416 if ( msgid == -1 ) {
1417 tool_perror( "ldap_sasl_bind(SIMPLE)", rc,
1418 NULL, NULL, NULL, NULL );
1423 rc = ldap_result( ld, msgid, LDAP_MSG_ALL, NULL, &result );
1425 tool_perror( "ldap_result", -1, NULL, NULL, NULL, NULL );
1426 exit( LDAP_LOCAL_ERROR );
1430 tool_perror( "ldap_result", LDAP_TIMEOUT, NULL, NULL, NULL, NULL );
1431 exit( LDAP_LOCAL_ERROR );
1434 rc = ldap_parse_result( ld, result, &err, &matched, &info, &refs,
1436 if ( rc != LDAP_SUCCESS ) {
1437 tool_perror( "ldap_bind parse result", rc, NULL, matched, info, refs );
1438 exit( LDAP_LOCAL_ERROR );
1441 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
1442 if ( ctrls && ppolicy ) {
1444 int expire, grace, len = 0;
1445 LDAPPasswordPolicyError pErr = -1;
1447 ctrl = ldap_control_find( LDAP_CONTROL_PASSWORDPOLICYRESPONSE,
1450 if ( ctrl && ldap_parse_passwordpolicy_control( ld, ctrl,
1451 &expire, &grace, &pErr ) == LDAP_SUCCESS )
1453 if ( pErr != PP_noError ){
1456 strcpy( msgbuf+2, ldap_passwordpolicy_err2txt( pErr ));
1457 len = strlen( msgbuf );
1459 if ( expire >= 0 ) {
1460 sprintf( msgbuf+len,
1461 " (Password expires in %d seconds)",
1463 } else if ( grace >= 0 ) {
1464 sprintf( msgbuf+len,
1465 " (Password expired, %d grace logins remain)",
1473 ldap_controls_free( ctrls );
1476 if ( err != LDAP_SUCCESS
1478 || ( matched && matched[ 0 ] )
1479 || ( info && info[ 0 ] )
1482 tool_perror( "ldap_bind", err, msgbuf, matched, info, refs );
1484 if( matched ) ber_memfree( matched );
1485 if( info ) ber_memfree( info );
1486 if( refs ) ber_memvfree( (void **)refs );
1488 if ( err != LDAP_SUCCESS ) exit( err );
1494 tool_unbind( LDAP *ld )
1496 int err = ldap_set_option( ld, LDAP_OPT_SERVER_CONTROLS, NULL );
1498 if ( err != LDAP_OPT_SUCCESS ) {
1499 fprintf( stderr, "Could not unset controls\n");
1502 (void) ldap_unbind_ext( ld, NULL, NULL );
1506 /* Set server controls. Add controls extra_c[0..count-1], if set. */
1508 tool_server_controls( LDAP *ld, LDAPControl *extra_c, int count )
1510 int i = 0, j, crit = 0, err;
1511 LDAPControl c[16], **ctrls;
1515 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
1517 #endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
1521 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
1526 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
1528 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
1529 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
1531 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
1533 || unknown_ctrls_num ) )
1538 ctrls = (LDAPControl**) malloc(sizeof(c) + (count + unknown_ctrls_num + 1)*sizeof(LDAPControl*));
1539 if ( ctrls == NULL ) {
1540 fprintf( stderr, "No memory\n" );
1541 exit( EXIT_FAILURE );
1545 if ( BER_BVISNULL( &assertionvalue ) ) {
1546 err = ldap_create_assertion_control_value( ld,
1547 assertion, &assertionvalue );
1550 "Unable to create assertion value "
1551 "\"%s\" (%d)\n", assertion, err );
1555 c[i].ldctl_oid = LDAP_CONTROL_ASSERT;
1556 c[i].ldctl_value = assertionvalue;
1557 c[i].ldctl_iscritical = assertctl > 1;
1563 c[i].ldctl_value.bv_val = authzid;
1564 c[i].ldctl_value.bv_len = strlen( authzid );
1565 c[i].ldctl_oid = LDAP_CONTROL_PROXY_AUTHZ;
1566 c[i].ldctl_iscritical = 1;
1571 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
1572 /* NOTE: doesn't need an extra count because it's incompatible
1575 BerElementBuffer berbuf;
1576 BerElement *ber = (BerElement *)&berbuf;
1578 ber_init2( ber, NULL, LBER_USE_DER );
1580 if ( ber_printf( ber, "s", proxydn ) == -1 ) {
1581 exit( EXIT_FAILURE );
1584 if ( ber_flatten2( ber, &c[i].ldctl_value, 0 ) == -1 ) {
1585 exit( EXIT_FAILURE );
1588 c[i].ldctl_oid = LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ;
1589 c[i].ldctl_iscritical = 1;
1593 #endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
1596 c[i].ldctl_oid = LDAP_CONTROL_MANAGEDIT;
1597 BER_BVZERO( &c[i].ldctl_value );
1598 c[i].ldctl_iscritical = manageDIT > 1;
1603 if ( manageDSAit ) {
1604 c[i].ldctl_oid = LDAP_CONTROL_MANAGEDSAIT;
1605 BER_BVZERO( &c[i].ldctl_value );
1606 c[i].ldctl_iscritical = manageDSAit > 1;
1612 c[i].ldctl_oid = LDAP_CONTROL_NOOP;
1613 BER_BVZERO( &c[i].ldctl_value );
1614 c[i].ldctl_iscritical = noop > 1;
1619 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
1621 c[i].ldctl_oid = LDAP_CONTROL_PASSWORDPOLICYREQUEST;
1622 BER_BVZERO( &c[i].ldctl_value );
1623 c[i].ldctl_iscritical = 0;
1630 BerElementBuffer berbuf;
1631 BerElement *ber = (BerElement *)&berbuf;
1632 char **attrs = NULL;
1634 if( preread_attrs ) {
1635 attrs = ldap_str2charray( preread_attrs, "," );
1638 ber_init2( ber, NULL, LBER_USE_DER );
1640 if( ber_printf( ber, "{v}", attrs ) == -1 ) {
1641 fprintf( stderr, "preread attrs encode failed.\n" );
1642 exit( EXIT_FAILURE );
1645 err = ber_flatten2( ber, &c[i].ldctl_value, 0 );
1647 fprintf( stderr, "preread flatten failed (%d)\n", err );
1648 exit( EXIT_FAILURE );
1651 c[i].ldctl_oid = LDAP_CONTROL_PRE_READ;
1652 c[i].ldctl_iscritical = preread > 1;
1656 if( attrs ) ldap_charray_free( attrs );
1660 BerElementBuffer berbuf;
1661 BerElement *ber = (BerElement *)&berbuf;
1662 char **attrs = NULL;
1664 if( postread_attrs ) {
1665 attrs = ldap_str2charray( postread_attrs, "," );
1668 ber_init2( ber, NULL, LBER_USE_DER );
1670 if( ber_printf( ber, "{v}", attrs ) == -1 ) {
1671 fprintf( stderr, "postread attrs encode failed.\n" );
1672 exit( EXIT_FAILURE );
1675 err = ber_flatten2( ber, &c[i].ldctl_value, 0 );
1677 fprintf( stderr, "postread flatten failed (%d)\n", err );
1678 exit( EXIT_FAILURE );
1681 c[i].ldctl_oid = LDAP_CONTROL_POST_READ;
1682 c[i].ldctl_iscritical = postread > 1;
1686 if( attrs ) ldap_charray_free( attrs );
1689 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
1691 if ( chainingResolve > -1 ) {
1692 BerElementBuffer berbuf;
1693 BerElement *ber = (BerElement *)&berbuf;
1695 ber_init2( ber, NULL, LBER_USE_DER );
1697 err = ber_printf( ber, "{e" /* } */, chainingResolve );
1700 fprintf( stderr, _("Chaining behavior control encoding error!\n") );
1701 exit( EXIT_FAILURE );
1704 if ( chainingContinuation > -1 ) {
1705 err = ber_printf( ber, "e", chainingContinuation );
1708 fprintf( stderr, _("Chaining behavior control encoding error!\n") );
1709 exit( EXIT_FAILURE );
1713 err = ber_printf( ber, /* { */ "N}" );
1716 fprintf( stderr, _("Chaining behavior control encoding error!\n") );
1717 exit( EXIT_FAILURE );
1720 if ( ber_flatten2( ber, &c[i].ldctl_value, 0 ) == -1 ) {
1721 exit( EXIT_FAILURE );
1725 BER_BVZERO( &c[i].ldctl_value );
1728 c[i].ldctl_oid = LDAP_CONTROL_X_CHAINING_BEHAVIOR;
1729 c[i].ldctl_iscritical = chaining > 1;
1733 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
1735 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
1736 if ( sessionTracking ) {
1737 if ( stValue.bv_val == NULL && st_value( ld, &stValue ) ) {
1738 exit( EXIT_FAILURE );
1741 c[i].ldctl_oid = LDAP_CONTROL_X_SESSION_TRACKING;
1742 c[i].ldctl_iscritical = 0;
1743 ber_dupbv( &c[i].ldctl_value, &stValue );
1748 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
1751 ctrls[i++] = extra_c++;
1753 for ( count = 0; count < unknown_ctrls_num; count++ ) {
1754 ctrls[i++] = &unknown_ctrls[count];
1758 err = ldap_set_option( ld, LDAP_OPT_SERVER_CONTROLS, ctrls );
1760 if ( err != LDAP_OPT_SUCCESS ) {
1761 for ( j = 0; j < i; j++ ) {
1762 if ( ctrls[j]->ldctl_iscritical ) crit = 1;
1764 fprintf( stderr, "Could not set %scontrols\n",
1765 crit ? "critical " : "" );
1770 exit( EXIT_FAILURE );
1775 tool_check_abandon( LDAP *ld, int msgid )
1779 switch ( gotintr ) {
1781 rc = ldap_cancel_s( ld, msgid, NULL, NULL );
1782 fprintf( stderr, "got interrupt, cancel got %d: %s\n",
1783 rc, ldap_err2string( rc ) );
1787 rc = ldap_abandon_ext( ld, msgid, NULL, NULL );
1788 fprintf( stderr, "got interrupt, abandon got %d: %s\n",
1789 rc, ldap_err2string( rc ) );
1793 /* just unbind, ignoring the request */
1801 print_prepostread( LDAP *ld, LDAPControl *ctrl, struct berval *what)
1806 tool_write_ldif( LDIF_PUT_COMMENT, "==> ",
1807 what->bv_val, what->bv_len );
1808 ber = ber_init( &ctrl->ldctl_value );
1809 if ( ber == NULL ) {
1813 } else if ( ber_scanf( ber, "{m{" /*}}*/, &bv ) == LBER_ERROR ) {
1818 tool_write_ldif( LDIF_PUT_VALUE, "dn", bv.bv_val, bv.bv_len );
1820 while ( ber_scanf( ber, "{m" /*}*/, &bv ) != LBER_ERROR ) {
1822 BerVarray vals = NULL;
1824 if ( ber_scanf( ber, "[W]", &vals ) == LBER_ERROR ||
1831 for ( i = 0; vals[ i ].bv_val != NULL; i++ ) {
1833 ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1834 bv.bv_val, vals[ i ].bv_val, vals[ i ].bv_len );
1837 ber_bvarray_free( vals );
1841 if ( ber != NULL ) {
1845 tool_write_ldif( LDIF_PUT_COMMENT, "<== ",
1846 what->bv_val, what->bv_len );
1852 print_preread( LDAP *ld, LDAPControl *ctrl )
1854 static struct berval what = BER_BVC( "preread" );
1856 return print_prepostread( ld, ctrl, &what );
1860 print_postread( LDAP *ld, LDAPControl *ctrl )
1862 static struct berval what = BER_BVC( "postread" );
1864 return print_prepostread( ld, ctrl, &what );
1868 print_paged_results( LDAP *ld, LDAPControl *ctrl )
1872 /* note: pr_cookie is being malloced; it's freed
1873 * the next time the control is sent, but the last
1874 * time it's not; we don't care too much, because
1875 * the last time an empty value is returned... */
1876 if ( ldap_parse_pageresponse_control( ld, ctrl, &estimate, &pr_cookie )
1883 /* FIXME: check buffer overflow */
1884 char buf[ BUFSIZ ], *ptr = buf;
1886 if ( estimate > 0 ) {
1887 ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
1888 "estimate=%d", estimate );
1891 if ( pr_cookie.bv_len > 0 ) {
1894 bv.bv_len = LUTIL_BASE64_ENCODE_LEN(
1895 pr_cookie.bv_len ) + 1;
1896 bv.bv_val = ber_memalloc( bv.bv_len + 1 );
1898 bv.bv_len = lutil_b64_ntop(
1899 (unsigned char *) pr_cookie.bv_val,
1901 bv.bv_val, bv.bv_len );
1903 ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
1904 "%scookie=%s", ptr == buf ? "" : " ",
1907 ber_memfree( bv.bv_val );
1909 pr_morePagedResults = 1;
1912 ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
1913 "%scookie=", ptr == buf ? "" : " " );
1916 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1917 "pagedresults", buf, ptr - buf );
1924 print_sss( LDAP *ld, LDAPControl *ctrl )
1930 rc = ldap_parse_sortresponse_control( ld, ctrl, &err, &attr );
1931 if ( rc == LDAP_SUCCESS ) {
1933 rc = snprintf( buf, sizeof(buf), "(%d) %s%s%s",
1934 err, ldap_err2string(err), attr ? " " : "", attr ? attr : "" );
1936 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1937 "sortResult", buf, rc );
1944 print_vlv( LDAP *ld, LDAPControl *ctrl )
1950 rc = ldap_parse_vlvresponse_control( ld, ctrl, &vlvPos, &vlvCount,
1951 &vlvContext, &err );
1952 if ( rc == LDAP_SUCCESS ) {
1955 if ( vlvContext && vlvContext->bv_len > 0 ) {
1956 bv.bv_len = LUTIL_BASE64_ENCODE_LEN(
1957 vlvContext->bv_len ) + 1;
1958 bv.bv_val = ber_memalloc( bv.bv_len + 1 );
1960 bv.bv_len = lutil_b64_ntop(
1961 (unsigned char *) vlvContext->bv_val,
1963 bv.bv_val, bv.bv_len );
1969 rc = snprintf( buf, sizeof(buf), "pos=%d count=%d context=%s (%d) %s",
1970 vlvPos, vlvCount, bv.bv_val,
1971 err, ldap_err2string(err));
1974 ber_memfree( bv.bv_val );
1976 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1977 "vlvResult", buf, rc );
1983 #ifdef LDAP_CONTROL_X_DEREF
1985 print_deref( LDAP *ld, LDAPControl *ctrl )
1987 LDAPDerefRes *drhead = NULL, *dr;
1990 rc = ldap_parse_derefresponse_control( ld, ctrl, &drhead );
1991 if ( rc != LDAP_SUCCESS ) {
1995 for ( dr = drhead; dr != NULL; dr = dr->next ) {
2000 len = strlen( dr->derefAttr ) + STRLENOF(": ");
2002 for ( dv = dr->attrVals; dv != NULL; dv = dv->next ) {
2003 if ( dv->vals != NULL ) {
2005 ber_len_t tlen = strlen(dv->type);
2007 for ( j = 0; dv->vals[ j ].bv_val != NULL; j++ ) {
2008 len += STRLENOF("<:=>;") + tlen + 4*((dv->vals[ j ].bv_len - 1)/3 + 1);
2012 len += dr->derefVal.bv_len + STRLENOF("\n");
2013 buf = ldap_memalloc( len + 1 );
2014 if ( buf == NULL ) {
2015 rc = LDAP_NO_MEMORY;
2020 ptr = lutil_strcopy( ptr, dr->derefAttr );
2023 for ( dv = dr->attrVals; dv != NULL; dv = dv->next ) {
2024 if ( dv->vals != NULL ) {
2026 for ( j = 0; dv->vals[ j ].bv_val != NULL; j++ ) {
2027 int k = ldif_is_not_printable( dv->vals[ j ].bv_val, dv->vals[ j ].bv_len );
2030 ptr = lutil_strcopy( ptr, dv->type );
2037 (unsigned char *) dv->vals[ j ].bv_val,
2038 dv->vals[ j ].bv_len,
2039 ptr, buf + len - ptr );
2044 ptr = lutil_memcopy( ptr, dv->vals[ j ].bv_val, dv->vals[ j ].bv_len );
2051 ptr = lutil_strncopy( ptr, dr->derefVal.bv_val, dr->derefVal.bv_len );
2054 assert( ptr <= buf + len );
2056 tool_write_ldif( LDIF_PUT_COMMENT, NULL, buf, ptr - buf);
2058 ldap_memfree( buf );
2064 ldap_derefresponse_free( drhead );
2070 #ifdef LDAP_CONTROL_X_WHATFAILED
2072 print_whatfailed( LDAP *ld, LDAPControl *ctrl )
2077 BerVarray bva = NULL;
2079 /* Create a BerElement from the berval returned in the control. */
2080 ber = ber_init( &ctrl->ldctl_value );
2082 if ( ber == NULL ) {
2083 return LDAP_NO_MEMORY;
2086 siz = sizeof(struct berval);
2087 tag = ber_scanf( ber, "[M]", &bva, &siz, 0 );
2088 if ( tag != LBER_ERROR ) {
2091 tool_write_ldif( LDIF_PUT_COMMENT, " what failed:", NULL, 0 );
2093 for ( i = 0; bva[i].bv_val != NULL; i++ ) {
2094 tool_write_ldif( LDIF_PUT_COMMENT, NULL, bva[i].bv_val, bva[i].bv_len );
2097 ldap_memfree( bva );
2107 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
2109 print_ppolicy( LDAP *ld, LDAPControl *ctrl )
2111 int expire = 0, grace = 0, rc;
2112 LDAPPasswordPolicyError pperr;
2114 rc = ldap_parse_passwordpolicy_control( ld, ctrl,
2115 &expire, &grace, &pperr );
2116 if ( rc == LDAP_SUCCESS ) {
2117 char buf[ BUFSIZ ], *ptr = buf;
2119 if ( expire != -1 ) {
2120 ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
2121 "expire=%d", expire );
2124 if ( grace != -1 ) {
2125 ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
2126 "%sgrace=%d", ptr == buf ? "" : " ", grace );
2129 if ( pperr != PP_noError ) {
2130 ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
2131 "%serror=%d (%s)", ptr == buf ? "" : " ",
2133 ldap_passwordpolicy_err2txt( pperr ) );
2136 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
2137 "ppolicy", buf, ptr - buf );
2144 void tool_print_ctrls(
2146 LDAPControl **ctrls )
2151 for ( i = 0; ctrls[i] != NULL; i++ ) {
2152 /* control: OID criticality base64value */
2153 struct berval b64 = BER_BVNULL;
2158 /* FIXME: there might be cases where a control has NULL OID;
2159 * this makes little sense, especially when returned by the
2160 * server, but libldap happily allows it */
2161 if ( ctrls[i]->ldctl_oid == NULL ) {
2166 len += strlen( ctrls[i]->ldctl_oid );
2168 /* add enough for space after OID and the critical value itself */
2169 len += ctrls[i]->ldctl_iscritical
2170 ? sizeof("true") : sizeof("false");
2172 /* convert to base64 */
2173 if ( !BER_BVISNULL( &ctrls[i]->ldctl_value ) ) {
2174 b64.bv_len = LUTIL_BASE64_ENCODE_LEN(
2175 ctrls[i]->ldctl_value.bv_len ) + 1;
2176 b64.bv_val = ber_memalloc( b64.bv_len + 1 );
2178 b64.bv_len = lutil_b64_ntop(
2179 (unsigned char *) ctrls[i]->ldctl_value.bv_val,
2180 ctrls[i]->ldctl_value.bv_len,
2181 b64.bv_val, b64.bv_len );
2185 len += 1 + b64.bv_len;
2188 ptr = str = malloc( len + 1 );
2190 ptr = lutil_strcopy( ptr, ": " );
2192 ptr = lutil_strcopy( ptr, ctrls[i]->ldctl_oid );
2193 ptr = lutil_strcopy( ptr, ctrls[i]->ldctl_iscritical
2194 ? " true" : " false" );
2197 ptr = lutil_strcopy( ptr, " " );
2198 ptr = lutil_strcopy( ptr, b64.bv_val );
2202 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
2203 "control", str, len );
2208 ber_memfree( b64.bv_val );
2211 /* known controls */
2212 for ( j = 0; tool_ctrl_response[j].oid != NULL; j++ ) {
2213 if ( strcmp( tool_ctrl_response[j].oid, ctrls[i]->ldctl_oid ) == 0 ) {
2214 if ( !tool_ctrl_response[j].mask & tool_type ) {
2215 /* this control should not appear
2216 * with this tool; warning? */
2222 if ( tool_ctrl_response[j].oid != NULL && tool_ctrl_response[j].func ) {
2223 (void)tool_ctrl_response[j].func( ld, ctrls[i] );
2229 tool_write_ldif( int type, char *name, char *value, ber_len_t vallen )
2233 if (( ldif = ldif_put( type, name, value, vallen )) == NULL ) {
2237 fputs( ldif, stdout );
2238 ber_memfree( ldif );
2244 tool_is_oid( const char *s )
2248 if ( !isdigit( (unsigned char) s[ 0 ] ) ) {
2252 for ( ; s[ 0 ]; s++ ) {
2253 if ( s[ 0 ] == '.' ) {
2254 if ( s[ 1 ] == '\0' ) {
2261 if ( !isdigit( (unsigned char) s[ 0 ] ) ) {
2265 if ( first == 1 && s[ 0 ] == '0' && s[ 1 ] != '.' ) {