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 );
259 if ( passwd.bv_val != NULL ) {
260 ber_memfree( passwd.bv_val );
265 tool_common_usage( void )
267 static const char *const descriptions[] = {
268 N_(" -c continuous operation mode (do not stop on errors)\n"),
269 N_(" -d level set LDAP debugging level to `level'\n"),
270 N_(" -D binddn bind DN\n"),
271 N_(" -e [!]<ext>[=<extparam>] general extensions (! indicates criticality)\n")
272 N_(" [!]assert=<filter> (RFC 4528; a RFC 4515 Filter string)\n")
273 N_(" [!]authzid=<authzid> (RFC 4370; \"dn:<dn>\" or \"u:<user>\")\n")
274 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
276 /* non-advertized support for proxyDN */
277 N_(" [!]proxydn=<dn> (a RFC 4514 DN string)\n")
280 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
281 N_(" [!]chaining[=<resolveBehavior>[/<continuationBehavior>]]\n")
282 N_(" one of \"chainingPreferred\", \"chainingRequired\",\n")
283 N_(" \"referralsPreferred\", \"referralsRequired\"\n")
284 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
285 N_(" [!]manageDSAit (RFC 3296)\n")
287 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
290 N_(" [!]postread[=<attrs>] (RFC 4527; comma-separated attr list)\n")
291 N_(" [!]preread[=<attrs>] (RFC 4527; comma-separated attr list)\n")
293 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
294 N_(" [!]sessiontracking\n")
295 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
296 N_(" abandon, cancel, ignore (SIGINT sends abandon/cancel,\n"
297 " or ignores response; if critical, doesn't wait for SIGINT.\n"
298 " not really controls)\n")
299 N_(" -f file read operations from `file'\n"),
300 N_(" -h host LDAP server\n"),
301 N_(" -H URI LDAP Uniform Resource Identifier(s)\n"),
302 N_(" -I use SASL Interactive mode\n"),
303 N_(" -M enable Manage DSA IT control (-MM to make critical)\n"),
304 N_(" -n show what would be done but don't actually do it\n"),
305 N_(" -N do not use reverse DNS to canonicalize SASL host name\n"),
306 N_(" -O props SASL security properties\n"),
307 N_(" -o <opt>[=<optparam] general options\n"),
308 N_(" nettimeout=<timeout> (in seconds, or \"none\" or \"max\")\n"),
309 N_(" -p port port on LDAP server\n"),
310 N_(" -P version protocol version (default: 3)\n"),
311 N_(" -Q use SASL Quiet mode\n"),
312 N_(" -R realm SASL realm\n"),
313 N_(" -U authcid SASL authentication identity\n"),
314 N_(" -v run in verbose mode (diagnostics to standard output)\n"),
315 N_(" -V print version info (-VV only)\n"),
316 N_(" -w passwd bind password (for simple authentication)\n"),
317 N_(" -W prompt for bind password\n"),
318 N_(" -x Simple authentication\n"),
319 N_(" -X authzid SASL authorization identity (\"dn:<dn>\" or \"u:<user>\")\n"),
320 N_(" -y file Read password from file\n"),
321 N_(" -Y mech SASL mechanism\n"),
322 N_(" -Z Start TLS request (-ZZ to require successful response)\n"),
325 const char *const *cpp;
327 fputs( _("Common options:\n"), stderr );
328 for( cpp = descriptions; *cpp != NULL; cpp++ ) {
329 if( strchr( options, (*cpp)[3] ) || (*cpp)[3] == ' ' ) {
330 fputs( _(*cpp), stderr );
343 fprintf( stderr, "%s: %s (%d)%s\n",
344 func, ldap_err2string( err ), err, extra ? extra : "" );
346 if ( matched && *matched ) {
347 fprintf( stderr, _("\tmatched DN: %s\n"), matched );
350 if ( info && *info ) {
351 fprintf( stderr, _("\tadditional info: %s\n"), info );
354 if ( refs && *refs ) {
356 fprintf( stderr, _("\treferrals:\n") );
357 for( i=0; refs[i]; i++ ) {
358 fprintf( stderr, "\t\t%s\n", refs[i] );
365 tool_args( int argc, char **argv )
369 while (( i = getopt( argc, argv, options )) != EOF ) {
371 char *control, *cvalue, *next;
373 case 'c': /* continuous operation mode */
380 ival = strtol( optarg, &next, 10 );
381 if (next == NULL || next[0] != '\0') {
382 fprintf( stderr, "%s: unable to parse debug value \"%s\"\n", prog, optarg);
387 case 'D': /* bind DN */
388 if( binddn != NULL ) {
389 fprintf( stderr, "%s: -D previously specified\n", prog );
390 exit( EXIT_FAILURE );
392 binddn = ber_strdup( optarg );
394 case 'e': /* general extensions (controls and such) */
395 /* should be extended to support comma separated list of
396 * [!]key[=value] parameters, e.g. -e !foo,bar=567
401 while ( optarg[0] == '!' ) {
406 control = ber_strdup( optarg );
407 if ( (cvalue = strchr( control, '=' )) != NULL ) {
411 if ( strcasecmp( control, "assert" ) == 0 ) {
413 fprintf( stderr, "assert control previously specified\n");
414 exit( EXIT_FAILURE );
416 if( cvalue == NULL ) {
417 fprintf( stderr, "assert: control value expected\n" );
421 assertctl = 1 + crit;
423 assert( assertion == NULL );
426 } else if ( strcasecmp( control, "authzid" ) == 0 ) {
427 if( authzid != NULL ) {
428 fprintf( stderr, "authzid control previously specified\n");
429 exit( EXIT_FAILURE );
431 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
432 if( proxydn != NULL ) {
433 fprintf( stderr, "authzid control incompatible with proxydn\n");
434 exit( EXIT_FAILURE );
436 #endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
437 if( cvalue == NULL ) {
438 fprintf( stderr, "authzid: control value expected\n" );
442 fprintf( stderr, "authzid: must be marked critical\n" );
444 } else if ( crit > 1 ) {
445 /* purposely flag proxied authorization
446 * as non-critical, to test DSA */
450 assert( authzid == NULL );
453 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
454 } else if ( strcasecmp( control, "proxydn" ) == 0 ) {
455 if( proxydn != NULL ) {
456 fprintf( stderr, "proxydn control previously specified\n");
457 exit( EXIT_FAILURE );
459 if( authzid != NULL ) {
460 fprintf( stderr, "proxydn control incompatible with authzid\n");
461 exit( EXIT_FAILURE );
463 if( cvalue == NULL ) {
464 fprintf( stderr, "proxydn: control value expected\n" );
468 fprintf( stderr, "proxydn: must be marked critical\n" );
470 } else if ( crit > 1 ) {
471 /* purposely flag proxied authorization
472 * as non-critical, to test DSA */
476 assert( proxydn == NULL );
478 #endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
480 } else if ( ( strcasecmp( control, "relax" ) == 0 ) ||
481 ( strcasecmp( control, "manageDIT" ) == 0 ) )
485 "relax control previously specified\n");
486 exit( EXIT_FAILURE );
488 if( cvalue != NULL ) {
490 "relax: no control value expected\n" );
494 manageDIT = 1 + crit;
496 } else if ( strcasecmp( control, "manageDSAit" ) == 0 ) {
499 "manageDSAit control previously specified\n");
500 exit( EXIT_FAILURE );
502 if( cvalue != NULL ) {
504 "manageDSAit: no control value expected\n" );
508 manageDSAit = 1 + crit;
510 } else if ( strcasecmp( control, "noop" ) == 0 ) {
512 fprintf( stderr, "noop control previously specified\n");
513 exit( EXIT_FAILURE );
515 if( cvalue != NULL ) {
516 fprintf( stderr, "noop: no control value expected\n" );
522 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
523 } else if ( strcasecmp( control, "ppolicy" ) == 0 ) {
525 fprintf( stderr, "ppolicy control previously specified\n");
526 exit( EXIT_FAILURE );
528 if( cvalue != NULL ) {
529 fprintf( stderr, "ppolicy: no control value expected\n" );
533 fprintf( stderr, "ppolicy: critical flag not allowed\n" );
540 } else if ( strcasecmp( control, "preread" ) == 0 ) {
542 fprintf( stderr, "preread control previously specified\n");
543 exit( EXIT_FAILURE );
547 preread_attrs = cvalue;
549 } else if ( strcasecmp( control, "postread" ) == 0 ) {
551 fprintf( stderr, "postread control previously specified\n");
552 exit( EXIT_FAILURE );
556 postread_attrs = cvalue;
558 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
559 } else if ( strcasecmp( control, "chaining" ) == 0 ) {
561 fprintf( stderr, "chaining control previously specified\n");
562 exit( EXIT_FAILURE );
567 if ( cvalue != NULL ) {
570 continuation = strchr( cvalue, '/' );
571 if ( continuation ) {
572 /* FIXME: this makes sense only in searches */
573 *continuation++ = '\0';
574 if ( strcasecmp( continuation, "chainingPreferred" ) == 0 ) {
575 chainingContinuation = LDAP_CHAINING_PREFERRED;
576 } else if ( strcasecmp( continuation, "chainingRequired" ) == 0 ) {
577 chainingContinuation = LDAP_CHAINING_REQUIRED;
578 } else if ( strcasecmp( continuation, "referralsPreferred" ) == 0 ) {
579 chainingContinuation = LDAP_REFERRALS_PREFERRED;
580 } else if ( strcasecmp( continuation, "referralsRequired" ) == 0 ) {
581 chainingContinuation = LDAP_REFERRALS_REQUIRED;
584 "chaining behavior control "
585 "continuation value \"%s\" invalid\n",
587 exit( EXIT_FAILURE );
591 if ( strcasecmp( cvalue, "chainingPreferred" ) == 0 ) {
592 chainingResolve = LDAP_CHAINING_PREFERRED;
593 } else if ( strcasecmp( cvalue, "chainingRequired" ) == 0 ) {
594 chainingResolve = LDAP_CHAINING_REQUIRED;
595 } else if ( strcasecmp( cvalue, "referralsPreferred" ) == 0 ) {
596 chainingResolve = LDAP_REFERRALS_PREFERRED;
597 } else if ( strcasecmp( cvalue, "referralsRequired" ) == 0 ) {
598 chainingResolve = LDAP_REFERRALS_REQUIRED;
601 "chaining behavior control "
602 "resolve value \"%s\" invalid\n",
604 exit( EXIT_FAILURE );
607 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
609 /* this shouldn't go here, really; but it's a feature... */
610 } else if ( strcasecmp( control, "abandon" ) == 0 ) {
611 abcan = Intr_Abandon;
616 } else if ( strcasecmp( control, "cancel" ) == 0 ) {
622 } else if ( strcasecmp( control, "ignore" ) == 0 ) {
628 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
629 } else if ( strcasecmp( control, "sessiontracking" ) == 0 ) {
630 if ( sessionTracking ) {
631 fprintf( stderr, "%s: session tracking can be only specified once\n", prog );
632 exit( EXIT_FAILURE );
635 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
637 } else if ( tool_is_oid( control ) ) {
638 LDAPControl *tmpctrls, ctrl;
640 if ( unknown_ctrls != NULL ) {
642 for ( i = 0; unknown_ctrls[ i ].ldctl_oid != NULL; i++ ) {
643 if ( strcmp( control, unknown_ctrls[ i ].ldctl_oid ) == 0 ) {
644 fprintf( stderr, "%s control previously specified\n", control );
645 exit( EXIT_FAILURE );
650 tmpctrls = (LDAPControl *)realloc( unknown_ctrls,
651 (unknown_ctrls_num + 1)*sizeof( LDAPControl ) );
652 if ( tmpctrls == NULL ) {
653 fprintf( stderr, "%s: no memory?\n", prog );
654 exit( EXIT_FAILURE );
656 unknown_ctrls = tmpctrls;
657 ctrl.ldctl_oid = control;
658 ctrl.ldctl_value.bv_val = NULL;
659 ctrl.ldctl_value.bv_len = 0;
660 ctrl.ldctl_iscritical = crit;
662 if ( cvalue != NULL ) {
664 size_t len = strlen( cvalue );
667 bv.bv_len = LUTIL_BASE64_DECODE_LEN( len );
668 bv.bv_val = ber_memalloc( bv.bv_len + 1 );
670 retcode = lutil_b64_pton( cvalue,
671 (unsigned char *)bv.bv_val,
674 if ( retcode == -1 || (unsigned) retcode > bv.bv_len ) {
675 fprintf( stderr, "Unable to parse value of general control %s\n",
681 ctrl.ldctl_value = bv;
684 unknown_ctrls[ unknown_ctrls_num ] = ctrl;
688 fprintf( stderr, "Invalid general control name: %s\n",
693 case 'f': /* read from file */
694 if( infile != NULL ) {
695 fprintf( stderr, "%s: -f previously specified\n", prog );
696 exit( EXIT_FAILURE );
698 infile = ber_strdup( optarg );
700 case 'h': /* ldap host */
701 if( ldaphost != NULL ) {
702 fprintf( stderr, "%s: -h previously specified\n", prog );
703 exit( EXIT_FAILURE );
705 ldaphost = ber_strdup( optarg );
707 case 'H': /* ldap URI */
708 if( ldapuri != NULL ) {
709 fprintf( stderr, "%s: -H previously specified\n", prog );
710 exit( EXIT_FAILURE );
712 ldapuri = ber_strdup( optarg );
715 #ifdef HAVE_CYRUS_SASL
716 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
717 fprintf( stderr, "%s: incompatible previous "
718 "authentication choice\n",
720 exit( EXIT_FAILURE );
722 authmethod = LDAP_AUTH_SASL;
723 sasl_flags = LDAP_SASL_INTERACTIVE;
726 fprintf( stderr, "%s: was not compiled with SASL support\n",
728 exit( EXIT_FAILURE );
731 /* enable Manage DSA IT */
734 case 'n': /* print operations, don't actually do them */
741 control = ber_strdup( optarg );
742 if ( (cvalue = strchr( control, '=' )) != NULL ) {
746 if ( strcasecmp( control, "nettimeout" ) == 0 ) {
747 if( nettimeout.tv_sec != -1 ) {
748 fprintf( stderr, "nettimeout option previously specified\n");
749 exit( EXIT_FAILURE );
751 if( cvalue == NULL || cvalue[0] == '\0' ) {
752 fprintf( stderr, "nettimeout: option value expected\n" );
755 if ( strcasecmp( cvalue, "none" ) == 0 ) {
756 nettimeout.tv_sec = 0;
757 } else if ( strcasecmp( cvalue, "max" ) == 0 ) {
758 nettimeout.tv_sec = LDAP_MAXINT;
760 ival = strtol( cvalue, &next, 10 );
761 if ( next == NULL || next[0] != '\0' ) {
763 _("Unable to parse network timeout \"%s\"\n"), cvalue );
764 exit( EXIT_FAILURE );
766 nettimeout.tv_sec = ival;
768 if( nettimeout.tv_sec < 0 || nettimeout.tv_sec > LDAP_MAXINT ) {
769 fprintf( stderr, _("%s: invalid network timeout (%ld) specified\n"),
770 prog, (long)nettimeout.tv_sec );
771 exit( EXIT_FAILURE );
774 fprintf( stderr, "Invalid general option name: %s\n",
780 #ifdef HAVE_CYRUS_SASL
781 if( sasl_secprops != NULL ) {
782 fprintf( stderr, "%s: -O previously specified\n", prog );
783 exit( EXIT_FAILURE );
785 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
786 fprintf( stderr, "%s: incompatible previous "
787 "authentication choice\n", prog );
788 exit( EXIT_FAILURE );
790 authmethod = LDAP_AUTH_SASL;
791 sasl_secprops = ber_strdup( optarg );
793 fprintf( stderr, "%s: not compiled with SASL support\n", prog );
794 exit( EXIT_FAILURE );
799 fprintf( stderr, "%s: -p previously specified\n", prog );
800 exit( EXIT_FAILURE );
802 ival = strtol( optarg, &next, 10 );
803 if ( next == NULL || next[0] != '\0' ) {
804 fprintf( stderr, "%s: unable to parse port number \"%s\"\n", prog, optarg );
805 exit( EXIT_FAILURE );
810 ival = strtol( optarg, &next, 10 );
811 if ( next == NULL || next[0] != '\0' ) {
812 fprintf( stderr, "%s: unable to parse protocol version \"%s\"\n", prog, optarg );
813 exit( EXIT_FAILURE );
817 if( protocol == LDAP_VERSION3 ) {
818 fprintf( stderr, "%s: -P 2 incompatible with version %d\n",
820 exit( EXIT_FAILURE );
822 protocol = LDAP_VERSION2;
825 if( protocol == LDAP_VERSION2 ) {
826 fprintf( stderr, "%s: -P 2 incompatible with version %d\n",
828 exit( EXIT_FAILURE );
830 protocol = LDAP_VERSION3;
833 fprintf( stderr, "%s: protocol version should be 2 or 3\n",
839 #ifdef HAVE_CYRUS_SASL
840 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
841 fprintf( stderr, "%s: incompatible previous "
842 "authentication choice\n",
844 exit( EXIT_FAILURE );
846 authmethod = LDAP_AUTH_SASL;
847 sasl_flags = LDAP_SASL_QUIET;
850 fprintf( stderr, "%s: not compiled with SASL support\n",
852 exit( EXIT_FAILURE );
855 #ifdef HAVE_CYRUS_SASL
856 if( sasl_realm != NULL ) {
857 fprintf( stderr, "%s: -R previously specified\n", prog );
858 exit( EXIT_FAILURE );
860 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
861 fprintf( stderr, "%s: incompatible previous "
862 "authentication choice\n",
864 exit( EXIT_FAILURE );
866 authmethod = LDAP_AUTH_SASL;
867 sasl_realm = ber_strdup( optarg );
869 fprintf( stderr, "%s: not compiled with SASL support\n",
871 exit( EXIT_FAILURE );
875 #ifdef HAVE_CYRUS_SASL
876 if( sasl_authc_id != NULL ) {
877 fprintf( stderr, "%s: -U previously specified\n", prog );
878 exit( EXIT_FAILURE );
880 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
881 fprintf( stderr, "%s: incompatible previous "
882 "authentication choice\n",
884 exit( EXIT_FAILURE );
886 authmethod = LDAP_AUTH_SASL;
887 sasl_authc_id = ber_strdup( optarg );
889 fprintf( stderr, "%s: not compiled with SASL support\n",
891 exit( EXIT_FAILURE );
894 case 'v': /* verbose mode */
897 case 'V': /* version */
900 case 'w': /* password */
901 passwd.bv_val = ber_strdup( optarg );
905 for( p = optarg; *p != '\0'; p++ ) {
909 passwd.bv_len = strlen( passwd.bv_val );
918 #ifdef HAVE_CYRUS_SASL
919 if( sasl_mech != NULL ) {
920 fprintf( stderr, "%s: -Y previously specified\n", prog );
921 exit( EXIT_FAILURE );
923 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
925 "%s: incompatible with authentication choice\n", prog );
926 exit( EXIT_FAILURE );
928 authmethod = LDAP_AUTH_SASL;
929 sasl_mech = ber_strdup( optarg );
931 fprintf( stderr, "%s: not compiled with SASL support\n", prog );
932 exit( EXIT_FAILURE );
936 if( authmethod != -1 && authmethod != LDAP_AUTH_SIMPLE ) {
937 fprintf( stderr, "%s: incompatible with previous "
938 "authentication choice\n", prog );
939 exit( EXIT_FAILURE );
941 authmethod = LDAP_AUTH_SIMPLE;
944 #ifdef HAVE_CYRUS_SASL
945 if( sasl_authz_id != NULL ) {
946 fprintf( stderr, "%s: -X previously specified\n", prog );
947 exit( EXIT_FAILURE );
949 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
950 fprintf( stderr, "%s: -X incompatible with "
951 "authentication choice\n", prog );
952 exit( EXIT_FAILURE );
954 authmethod = LDAP_AUTH_SASL;
955 sasl_authz_id = ber_strdup( optarg );
957 fprintf( stderr, "%s: not compiled with SASL support\n", prog );
958 exit( EXIT_FAILURE );
965 fprintf( stderr, "%s: not compiled with TLS support\n", prog );
966 exit( EXIT_FAILURE );
970 if( handle_private_option( i ) ) break;
971 fprintf( stderr, "%s: unrecognized option -%c\n",
978 /* prevent bad linking */
980 api.ldapai_info_version = LDAP_API_INFO_VERSION;
982 if ( ldap_get_option(NULL, LDAP_OPT_API_INFO, &api)
983 != LDAP_OPT_SUCCESS )
985 fprintf( stderr, "%s: ldap_get_option(API_INFO) failed\n", prog );
986 exit( EXIT_FAILURE );
989 if (api.ldapai_info_version != LDAP_API_INFO_VERSION) {
990 fprintf( stderr, "LDAP APIInfo version mismatch: "
991 "library %d, header %d\n",
992 api.ldapai_info_version, LDAP_API_INFO_VERSION );
993 exit( EXIT_FAILURE );
996 if( api.ldapai_api_version != LDAP_API_VERSION ) {
997 fprintf( stderr, "LDAP API version mismatch: "
998 "library %d, header %d\n",
999 api.ldapai_api_version, LDAP_API_VERSION );
1000 exit( EXIT_FAILURE );
1003 if( strcmp(api.ldapai_vendor_name, LDAP_VENDOR_NAME ) != 0 ) {
1004 fprintf( stderr, "LDAP vendor name mismatch: "
1005 "library %s, header %s\n",
1006 api.ldapai_vendor_name, LDAP_VENDOR_NAME );
1007 exit( EXIT_FAILURE );
1010 if( api.ldapai_vendor_version != LDAP_VENDOR_VERSION ) {
1011 fprintf( stderr, "LDAP vendor version mismatch: "
1012 "library %d, header %d\n",
1013 api.ldapai_vendor_version, LDAP_VENDOR_VERSION );
1014 exit( EXIT_FAILURE );
1018 fprintf( stderr, "%s: %s\t(LDAP library: %s %d)\n",
1020 LDAP_VENDOR_NAME, LDAP_VENDOR_VERSION );
1021 if (version > 1) exit( EXIT_SUCCESS );
1024 ldap_memfree( api.ldapai_vendor_name );
1025 ber_memvfree( (void **)api.ldapai_extensions );
1029 protocol = LDAP_VERSION3;
1031 if (authmethod == -1 && protocol > LDAP_VERSION2) {
1032 #ifdef HAVE_CYRUS_SASL
1033 if ( binddn != NULL ) {
1034 authmethod = LDAP_AUTH_SIMPLE;
1036 authmethod = LDAP_AUTH_SASL;
1039 authmethod = LDAP_AUTH_SIMPLE;
1043 if( ldapuri == NULL ) {
1044 if( ldapport && ( ldaphost == NULL )) {
1045 fprintf( stderr, "%s: -p without -h is invalid.\n", prog );
1046 exit( EXIT_FAILURE );
1049 if( ldaphost != NULL ) {
1050 fprintf( stderr, "%s: -H incompatible with -h\n", prog );
1051 exit( EXIT_FAILURE );
1054 fprintf( stderr, "%s: -H incompatible with -p\n", prog );
1055 exit( EXIT_FAILURE );
1059 if( protocol == LDAP_VERSION2 ) {
1060 if( assertctl || authzid || manageDIT || manageDSAit ||
1061 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
1063 #endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
1064 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
1067 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
1069 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
1070 noop || ppolicy || preread || postread )
1072 fprintf( stderr, "%s: -e/-M incompatible with LDAPv2\n", prog );
1073 exit( EXIT_FAILURE );
1077 fprintf( stderr, "%s: -Z incompatible with LDAPv2\n", prog );
1078 exit( EXIT_FAILURE );
1081 #ifdef HAVE_CYRUS_SASL
1082 if( authmethod == LDAP_AUTH_SASL ) {
1083 fprintf( stderr, "%s: -[IOQRUXY] incompatible with LDAPv2\n",
1085 exit( EXIT_FAILURE );
1093 tool_conn_setup( int dont, void (*private_setup)( LDAP * ) )
1098 if( ber_set_option( NULL, LBER_OPT_DEBUG_LEVEL, &debug )
1099 != LBER_OPT_SUCCESS )
1102 "Could not set LBER_OPT_DEBUG_LEVEL %d\n", debug );
1104 if( ldap_set_option( NULL, LDAP_OPT_DEBUG_LEVEL, &debug )
1105 != LDAP_OPT_SUCCESS )
1108 "Could not set LDAP_OPT_DEBUG_LEVEL %d\n", debug );
1113 (void) SIGNAL( SIGPIPE, SIG_IGN );
1117 SIGNAL( SIGINT, do_sig );
1123 if( ( ldaphost != NULL || ldapport ) && ( ldapuri == NULL ) ) {
1126 memset( &url, 0, sizeof(url));
1128 url.lud_scheme = "ldap";
1129 url.lud_host = ldaphost;
1130 url.lud_port = ldapport;
1131 url.lud_scope = LDAP_SCOPE_DEFAULT;
1133 ldapuri = ldap_url_desc2str( &url );
1135 } else if ( ldapuri != NULL ) {
1136 LDAPURLDesc *ludlist, **ludp;
1140 rc = ldap_url_parselist( &ludlist, ldapuri );
1141 if ( rc != LDAP_URL_SUCCESS ) {
1143 "Could not parse LDAP URI(s)=%s (%d)\n",
1145 exit( EXIT_FAILURE );
1148 for ( ludp = &ludlist; *ludp != NULL; ) {
1149 LDAPURLDesc *lud = *ludp;
1152 if ( lud->lud_dn != NULL && lud->lud_dn[ 0 ] != '\0' &&
1153 ( lud->lud_host == NULL || lud->lud_host[0] == '\0' ) )
1155 /* if no host but a DN is provided,
1156 * use DNS SRV to gather the host list
1157 * and turn it into a list of URIs
1158 * using the scheme provided */
1159 char *domain = NULL,
1163 len_proto = strlen( lud->lud_scheme );
1165 if ( ldap_dn2domain( lud->lud_dn, &domain )
1169 "DNS SRV: Could not turn "
1170 "DN=\"%s\" into a domain\n",
1175 rc = ldap_domain2hostlist( domain, &hostlist );
1178 "DNS SRV: Could not turn "
1179 "domain=%s into a hostlist\n",
1184 hosts = ldap_str2charray( hostlist, " " );
1185 if ( hosts == NULL ) {
1187 "DNS SRV: Could not parse "
1188 "hostlist=\"%s\"\n",
1193 for ( i = 0; hosts[ i ] != NULL; i++ )
1196 tmp = (char **)realloc( urls, sizeof( char * ) * ( nurls + i + 1 ) );
1197 if ( tmp == NULL ) {
1199 "DNS SRV: out of memory?\n" );
1203 urls[ nurls ] = NULL;
1205 for ( i = 0; hosts[ i ] != NULL; i++ ) {
1206 size_t len = len_proto
1208 + strlen( hosts[ i ] )
1211 urls[ nurls + i + 1 ] = NULL;
1212 urls[ nurls + i ] = (char *)malloc( sizeof( char ) * len );
1213 if ( urls[ nurls + i ] == NULL ) {
1215 "DNS SRV: out of memory?\n" );
1219 snprintf( urls[ nurls + i ], len, "%s://%s",
1220 lud->lud_scheme, hosts[ i ] );
1225 ber_memvfree( (void **)hosts );
1226 ber_memfree( hostlist );
1227 ber_memfree( domain );
1230 tmp = (char **)realloc( urls, sizeof( char * ) * ( nurls + 2 ) );
1231 if ( tmp == NULL ) {
1233 "DNS SRV: out of memory?\n" );
1237 urls[ nurls + 1 ] = NULL;
1239 urls[ nurls ] = ldap_url_desc2str( lud );
1240 if ( urls[ nurls ] == NULL ) {
1242 "DNS SRV: out of memory?\n" );
1248 *ludp = lud->lud_next;
1250 lud->lud_next = NULL;
1251 ldap_free_urldesc( lud );
1254 if ( ludlist != NULL ) {
1255 ldap_free_urllist( ludlist );
1256 exit( EXIT_FAILURE );
1258 } else if ( urls == NULL ) {
1259 exit( EXIT_FAILURE );
1262 ldap_memfree( ldapuri );
1263 ldapuri = ldap_charray2str( urls, " " );
1264 ber_memvfree( (void **)urls );
1268 fprintf( stderr, "ldap_initialize( %s )\n",
1269 ldapuri != NULL ? ldapuri : "<DEFAULT>" );
1271 rc = ldap_initialize( &ld, ldapuri );
1272 if( rc != LDAP_SUCCESS ) {
1274 "Could not create LDAP session handle for URI=%s (%d): %s\n",
1275 ldapuri, rc, ldap_err2string(rc) );
1276 exit( EXIT_FAILURE );
1279 if( private_setup ) private_setup( ld );
1282 if( ldap_set_option( ld, LDAP_OPT_REFERRALS,
1283 referrals ? LDAP_OPT_ON : LDAP_OPT_OFF ) != LDAP_OPT_SUCCESS )
1285 fprintf( stderr, "Could not set LDAP_OPT_REFERRALS %s\n",
1286 referrals ? "on" : "off" );
1287 exit( EXIT_FAILURE );
1290 #ifdef HAVE_CYRUS_SASL
1292 if( ldap_set_option( ld, LDAP_OPT_X_SASL_NOCANON,
1293 nocanon ? LDAP_OPT_ON : LDAP_OPT_OFF ) != LDAP_OPT_SUCCESS )
1295 fprintf( stderr, "Could not set LDAP_OPT_X_SASL_NOCANON %s\n",
1296 nocanon ? "on" : "off" );
1297 exit( EXIT_FAILURE );
1300 if( ldap_set_option( ld, LDAP_OPT_PROTOCOL_VERSION, &protocol )
1301 != LDAP_OPT_SUCCESS )
1303 fprintf( stderr, "Could not set LDAP_OPT_PROTOCOL_VERSION %d\n",
1305 exit( EXIT_FAILURE );
1309 rc = ldap_start_tls_s( ld, NULL, NULL );
1310 if ( rc != LDAP_SUCCESS ) {
1311 tool_perror( "ldap_start_tls", rc, NULL, NULL, NULL, NULL );
1312 if ( use_tls > 1 ) {
1313 exit( EXIT_FAILURE );
1318 if ( nettimeout.tv_sec > 0 ) {
1319 if ( ldap_set_option( ld, LDAP_OPT_NETWORK_TIMEOUT, (void *) &nettimeout )
1320 != LDAP_OPT_SUCCESS )
1322 fprintf( stderr, "Could not set LDAP_OPT_NETWORK_TIMEOUT %ld\n",
1323 (long)nettimeout.tv_sec );
1324 exit( EXIT_FAILURE );
1334 tool_bind( LDAP *ld )
1336 LDAPControl **sctrlsp = NULL;
1337 LDAPControl *sctrls[3];
1338 LDAPControl sctrl[3];
1341 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
1344 c.ldctl_oid = LDAP_CONTROL_PASSWORDPOLICYREQUEST;
1345 c.ldctl_value.bv_val = NULL;
1346 c.ldctl_value.bv_len = 0;
1347 c.ldctl_iscritical = 0;
1349 sctrls[nsctrls] = &sctrl[nsctrls];
1350 sctrls[++nsctrls] = NULL;
1354 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
1355 if ( sessionTracking ) {
1358 if (stValue.bv_val == NULL && st_value( ld, &stValue ) ) {
1359 exit( EXIT_FAILURE );
1362 c.ldctl_oid = LDAP_CONTROL_X_SESSION_TRACKING;
1363 c.ldctl_iscritical = 0;
1364 ber_dupbv( &c.ldctl_value, &stValue );
1367 sctrls[nsctrls] = &sctrl[nsctrls];
1368 sctrls[++nsctrls] = NULL;
1370 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
1376 assert( nsctrls < (int) (sizeof(sctrls)/sizeof(sctrls[0])) );
1378 if ( authmethod == LDAP_AUTH_SASL ) {
1379 #ifdef HAVE_CYRUS_SASL
1383 if( sasl_secprops != NULL ) {
1384 rc = ldap_set_option( ld, LDAP_OPT_X_SASL_SECPROPS,
1385 (void *) sasl_secprops );
1387 if( rc != LDAP_OPT_SUCCESS ) {
1389 "Could not set LDAP_OPT_X_SASL_SECPROPS: %s\n",
1391 exit( LDAP_LOCAL_ERROR );
1395 defaults = lutil_sasl_defaults( ld,
1402 rc = ldap_sasl_interactive_bind_s( ld, binddn, sasl_mech,
1404 NULL, sasl_flags, lutil_sasl_interact, defaults );
1406 lutil_sasl_freedefs( defaults );
1407 if( rc != LDAP_SUCCESS ) {
1408 tool_perror( "ldap_sasl_interactive_bind_s",
1409 rc, NULL, NULL, NULL, NULL );
1413 fprintf( stderr, "%s: not compiled with SASL support\n", prog );
1414 exit( LDAP_NOT_SUPPORTED );
1418 LDAPMessage *result;
1419 LDAPControl **ctrls;
1421 char *matched = NULL;
1429 rc = ldap_sasl_bind( ld, binddn, LDAP_SASL_SIMPLE, &passwd,
1430 sctrlsp, NULL, &msgid );
1431 if ( msgid == -1 ) {
1432 tool_perror( "ldap_sasl_bind(SIMPLE)", rc,
1433 NULL, NULL, NULL, NULL );
1438 if ( ldap_result( ld, msgid, LDAP_MSG_ALL, NULL, &result ) == -1 ) {
1439 tool_perror( "ldap_result", -1, NULL, NULL, NULL, NULL );
1440 exit( LDAP_LOCAL_ERROR );
1443 rc = ldap_parse_result( ld, result, &err, &matched, &info, &refs,
1445 if ( rc != LDAP_SUCCESS ) {
1446 tool_perror( "ldap_bind parse result", rc, NULL, matched, info, refs );
1447 exit( LDAP_LOCAL_ERROR );
1450 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
1451 if ( ctrls && ppolicy ) {
1453 int expire, grace, len = 0;
1454 LDAPPasswordPolicyError pErr = -1;
1456 ctrl = ldap_control_find( LDAP_CONTROL_PASSWORDPOLICYRESPONSE,
1459 if ( ctrl && ldap_parse_passwordpolicy_control( ld, ctrl,
1460 &expire, &grace, &pErr ) == LDAP_SUCCESS )
1462 if ( pErr != PP_noError ){
1465 strcpy( msgbuf+2, ldap_passwordpolicy_err2txt( pErr ));
1466 len = strlen( msgbuf );
1468 if ( expire >= 0 ) {
1469 sprintf( msgbuf+len,
1470 " (Password expires in %d seconds)",
1472 } else if ( grace >= 0 ) {
1473 sprintf( msgbuf+len,
1474 " (Password expired, %d grace logins remain)",
1482 ldap_controls_free( ctrls );
1485 if ( err != LDAP_SUCCESS
1487 || ( matched && matched[ 0 ] )
1488 || ( info && info[ 0 ] )
1491 tool_perror( "ldap_bind", err, msgbuf, matched, info, refs );
1493 if( matched ) ber_memfree( matched );
1494 if( info ) ber_memfree( info );
1495 if( refs ) ber_memvfree( (void **)refs );
1497 if ( err != LDAP_SUCCESS ) exit( err );
1503 tool_unbind( LDAP *ld )
1505 int err = ldap_set_option( ld, LDAP_OPT_SERVER_CONTROLS, NULL );
1507 if ( err != LDAP_OPT_SUCCESS ) {
1508 fprintf( stderr, "Could not unset controls\n");
1511 (void) ldap_unbind_ext( ld, NULL, NULL );
1515 /* Set server controls. Add controls extra_c[0..count-1], if set. */
1517 tool_server_controls( LDAP *ld, LDAPControl *extra_c, int count )
1519 int i = 0, j, crit = 0, err;
1520 LDAPControl c[16], **ctrls;
1524 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
1526 #endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
1530 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
1535 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
1537 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
1538 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
1540 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
1542 || unknown_ctrls_num ) )
1547 ctrls = (LDAPControl**) malloc(sizeof(c) + (count + unknown_ctrls_num + 1)*sizeof(LDAPControl*));
1548 if ( ctrls == NULL ) {
1549 fprintf( stderr, "No memory\n" );
1550 exit( EXIT_FAILURE );
1554 if ( BER_BVISNULL( &assertionvalue ) ) {
1555 err = ldap_create_assertion_control_value( ld,
1556 assertion, &assertionvalue );
1559 "Unable to create assertion value "
1560 "\"%s\" (%d)\n", assertion, err );
1564 c[i].ldctl_oid = LDAP_CONTROL_ASSERT;
1565 c[i].ldctl_value = assertionvalue;
1566 c[i].ldctl_iscritical = assertctl > 1;
1572 c[i].ldctl_value.bv_val = authzid;
1573 c[i].ldctl_value.bv_len = strlen( authzid );
1574 c[i].ldctl_oid = LDAP_CONTROL_PROXY_AUTHZ;
1575 c[i].ldctl_iscritical = authzcrit;
1580 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
1581 /* NOTE: doesn't need an extra count because it's incompatible
1584 BerElementBuffer berbuf;
1585 BerElement *ber = (BerElement *)&berbuf;
1587 ber_init2( ber, NULL, LBER_USE_DER );
1589 if ( ber_printf( ber, "s", proxydn ) == -1 ) {
1590 exit( EXIT_FAILURE );
1593 if ( ber_flatten2( ber, &c[i].ldctl_value, 0 ) == -1 ) {
1594 exit( EXIT_FAILURE );
1597 c[i].ldctl_oid = LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ;
1598 c[i].ldctl_iscritical = authzcrit;
1602 #endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
1605 c[i].ldctl_oid = LDAP_CONTROL_MANAGEDIT;
1606 BER_BVZERO( &c[i].ldctl_value );
1607 c[i].ldctl_iscritical = manageDIT > 1;
1612 if ( manageDSAit ) {
1613 c[i].ldctl_oid = LDAP_CONTROL_MANAGEDSAIT;
1614 BER_BVZERO( &c[i].ldctl_value );
1615 c[i].ldctl_iscritical = manageDSAit > 1;
1621 c[i].ldctl_oid = LDAP_CONTROL_NOOP;
1622 BER_BVZERO( &c[i].ldctl_value );
1623 c[i].ldctl_iscritical = noop > 1;
1628 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
1630 c[i].ldctl_oid = LDAP_CONTROL_PASSWORDPOLICYREQUEST;
1631 BER_BVZERO( &c[i].ldctl_value );
1632 c[i].ldctl_iscritical = 0;
1639 BerElementBuffer berbuf;
1640 BerElement *ber = (BerElement *)&berbuf;
1641 char **attrs = NULL;
1643 if( preread_attrs ) {
1644 attrs = ldap_str2charray( preread_attrs, "," );
1647 ber_init2( ber, NULL, LBER_USE_DER );
1649 if( ber_printf( ber, "{v}", attrs ) == -1 ) {
1650 fprintf( stderr, "preread attrs encode failed.\n" );
1651 exit( EXIT_FAILURE );
1654 err = ber_flatten2( ber, &c[i].ldctl_value, 0 );
1656 fprintf( stderr, "preread flatten failed (%d)\n", err );
1657 exit( EXIT_FAILURE );
1660 c[i].ldctl_oid = LDAP_CONTROL_PRE_READ;
1661 c[i].ldctl_iscritical = preread > 1;
1665 if( attrs ) ldap_charray_free( attrs );
1669 BerElementBuffer berbuf;
1670 BerElement *ber = (BerElement *)&berbuf;
1671 char **attrs = NULL;
1673 if( postread_attrs ) {
1674 attrs = ldap_str2charray( postread_attrs, "," );
1677 ber_init2( ber, NULL, LBER_USE_DER );
1679 if( ber_printf( ber, "{v}", attrs ) == -1 ) {
1680 fprintf( stderr, "postread attrs encode failed.\n" );
1681 exit( EXIT_FAILURE );
1684 err = ber_flatten2( ber, &c[i].ldctl_value, 0 );
1686 fprintf( stderr, "postread flatten failed (%d)\n", err );
1687 exit( EXIT_FAILURE );
1690 c[i].ldctl_oid = LDAP_CONTROL_POST_READ;
1691 c[i].ldctl_iscritical = postread > 1;
1695 if( attrs ) ldap_charray_free( attrs );
1698 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
1700 if ( chainingResolve > -1 ) {
1701 BerElementBuffer berbuf;
1702 BerElement *ber = (BerElement *)&berbuf;
1704 ber_init2( ber, NULL, LBER_USE_DER );
1706 err = ber_printf( ber, "{e" /* } */, chainingResolve );
1709 fprintf( stderr, _("Chaining behavior control encoding error!\n") );
1710 exit( EXIT_FAILURE );
1713 if ( chainingContinuation > -1 ) {
1714 err = ber_printf( ber, "e", chainingContinuation );
1717 fprintf( stderr, _("Chaining behavior control encoding error!\n") );
1718 exit( EXIT_FAILURE );
1722 err = ber_printf( ber, /* { */ "N}" );
1725 fprintf( stderr, _("Chaining behavior control encoding error!\n") );
1726 exit( EXIT_FAILURE );
1729 if ( ber_flatten2( ber, &c[i].ldctl_value, 0 ) == -1 ) {
1730 exit( EXIT_FAILURE );
1734 BER_BVZERO( &c[i].ldctl_value );
1737 c[i].ldctl_oid = LDAP_CONTROL_X_CHAINING_BEHAVIOR;
1738 c[i].ldctl_iscritical = chaining > 1;
1742 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
1744 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
1745 if ( sessionTracking ) {
1746 if ( stValue.bv_val == NULL && st_value( ld, &stValue ) ) {
1747 exit( EXIT_FAILURE );
1750 c[i].ldctl_oid = LDAP_CONTROL_X_SESSION_TRACKING;
1751 c[i].ldctl_iscritical = 0;
1752 ber_dupbv( &c[i].ldctl_value, &stValue );
1757 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
1760 ctrls[i++] = extra_c++;
1762 for ( count = 0; count < unknown_ctrls_num; count++ ) {
1763 ctrls[i++] = &unknown_ctrls[count];
1767 err = ldap_set_option( ld, LDAP_OPT_SERVER_CONTROLS, ctrls );
1769 if ( err != LDAP_OPT_SUCCESS ) {
1770 for ( j = 0; j < i; j++ ) {
1771 if ( ctrls[j]->ldctl_iscritical ) crit = 1;
1773 fprintf( stderr, "Could not set %scontrols\n",
1774 crit ? "critical " : "" );
1779 exit( EXIT_FAILURE );
1784 tool_check_abandon( LDAP *ld, int msgid )
1788 switch ( gotintr ) {
1790 rc = ldap_cancel_s( ld, msgid, NULL, NULL );
1791 fprintf( stderr, "got interrupt, cancel got %d: %s\n",
1792 rc, ldap_err2string( rc ) );
1796 rc = ldap_abandon_ext( ld, msgid, NULL, NULL );
1797 fprintf( stderr, "got interrupt, abandon got %d: %s\n",
1798 rc, ldap_err2string( rc ) );
1802 /* just unbind, ignoring the request */
1810 print_prepostread( LDAP *ld, LDAPControl *ctrl, struct berval *what)
1815 tool_write_ldif( LDIF_PUT_COMMENT, "==> ",
1816 what->bv_val, what->bv_len );
1817 ber = ber_init( &ctrl->ldctl_value );
1818 if ( ber == NULL ) {
1822 } else if ( ber_scanf( ber, "{m{" /*}}*/, &bv ) == LBER_ERROR ) {
1827 tool_write_ldif( LDIF_PUT_VALUE, "dn", bv.bv_val, bv.bv_len );
1829 while ( ber_scanf( ber, "{m" /*}*/, &bv ) != LBER_ERROR ) {
1831 BerVarray vals = NULL;
1833 if ( ber_scanf( ber, "[W]", &vals ) == LBER_ERROR ||
1840 for ( i = 0; vals[ i ].bv_val != NULL; i++ ) {
1842 ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1843 bv.bv_val, vals[ i ].bv_val, vals[ i ].bv_len );
1846 ber_bvarray_free( vals );
1850 if ( ber != NULL ) {
1854 tool_write_ldif( LDIF_PUT_COMMENT, "<== ",
1855 what->bv_val, what->bv_len );
1861 print_preread( LDAP *ld, LDAPControl *ctrl )
1863 static struct berval what = BER_BVC( "preread" );
1865 return print_prepostread( ld, ctrl, &what );
1869 print_postread( LDAP *ld, LDAPControl *ctrl )
1871 static struct berval what = BER_BVC( "postread" );
1873 return print_prepostread( ld, ctrl, &what );
1877 print_paged_results( LDAP *ld, LDAPControl *ctrl )
1881 /* note: pr_cookie is being malloced; it's freed
1882 * the next time the control is sent, but the last
1883 * time it's not; we don't care too much, because
1884 * the last time an empty value is returned... */
1885 if ( ldap_parse_pageresponse_control( ld, ctrl, &estimate, &pr_cookie )
1892 /* FIXME: check buffer overflow */
1893 char buf[ BUFSIZ ], *ptr = buf;
1895 if ( estimate > 0 ) {
1896 ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
1897 "estimate=%d", estimate );
1900 if ( pr_cookie.bv_len > 0 ) {
1903 bv.bv_len = LUTIL_BASE64_ENCODE_LEN(
1904 pr_cookie.bv_len ) + 1;
1905 bv.bv_val = ber_memalloc( bv.bv_len + 1 );
1907 bv.bv_len = lutil_b64_ntop(
1908 (unsigned char *) pr_cookie.bv_val,
1910 bv.bv_val, bv.bv_len );
1912 ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
1913 "%scookie=%s", ptr == buf ? "" : " ",
1916 ber_memfree( bv.bv_val );
1918 pr_morePagedResults = 1;
1921 ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
1922 "%scookie=", ptr == buf ? "" : " " );
1925 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1926 "pagedresults", buf, ptr - buf );
1933 print_sss( LDAP *ld, LDAPControl *ctrl )
1939 rc = ldap_parse_sortresponse_control( ld, ctrl, &err, &attr );
1940 if ( rc == LDAP_SUCCESS ) {
1942 rc = snprintf( buf, sizeof(buf), "(%d) %s %s",
1943 err, ldap_err2string(err), attr ? attr : "" );
1945 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1946 "sortResult", buf, rc );
1952 #ifdef LDAP_CONTROL_X_DEREF
1954 print_deref( LDAP *ld, LDAPControl *ctrl )
1956 LDAPDerefRes *drhead = NULL, *dr;
1959 rc = ldap_parse_derefresponse_control( ld, ctrl, &drhead );
1960 if ( rc != LDAP_SUCCESS ) {
1964 for ( dr = drhead; dr != NULL; dr = dr->next ) {
1969 len = strlen( dr->derefAttr ) + STRLENOF(": ");
1971 for ( dv = dr->attrVals; dv != NULL; dv = dv->next ) {
1972 if ( dv->vals != NULL ) {
1974 ber_len_t tlen = strlen(dv->type);
1976 for ( j = 0; dv->vals[ j ].bv_val != NULL; j++ ) {
1977 len += STRLENOF("<:=>;") + tlen + 4*((dv->vals[ j ].bv_len - 1)/3 + 1);
1981 len += dr->derefVal.bv_len + STRLENOF("\n");
1982 buf = ldap_memalloc( len + 1 );
1983 if ( buf == NULL ) {
1984 rc = LDAP_NO_MEMORY;
1989 ptr = lutil_strcopy( ptr, dr->derefAttr );
1992 for ( dv = dr->attrVals; dv != NULL; dv = dv->next ) {
1993 if ( dv->vals != NULL ) {
1995 for ( j = 0; dv->vals[ j ].bv_val != NULL; j++ ) {
1998 for ( k = 0; k < dv->vals[ j ].bv_len; k++ ) {
1999 if ( !isprint( dv->vals[ j ].bv_val[k] ) ) {
2006 ptr = lutil_strcopy( ptr, dv->type );
2012 k = lutil_b64_ntop( dv->vals[ j ].bv_val, dv->vals[ j ].bv_len, ptr, buf + len - ptr );
2017 ptr = lutil_memcopy( ptr, dv->vals[ j ].bv_val, dv->vals[ j ].bv_len );
2024 ptr = lutil_strncopy( ptr, dr->derefVal.bv_val, dr->derefVal.bv_len );
2027 assert( ptr <= buf + len );
2029 tool_write_ldif( LDIF_PUT_COMMENT, NULL, buf, ptr - buf);
2031 ldap_memfree( buf );
2037 ldap_derefresponse_free( drhead );
2043 #ifdef LDAP_CONTROL_X_WHATFAILED
2045 print_whatfailed( LDAP *ld, LDAPControl *ctrl )
2050 BerVarray bva = NULL;
2052 /* Create a BerElement from the berval returned in the control. */
2053 ber = ber_init( &ctrl->ldctl_value );
2055 if ( ber == NULL ) {
2056 return LDAP_NO_MEMORY;
2059 siz = sizeof(struct berval);
2060 tag = ber_scanf( ber, "[M]", &bva, &siz, 0 );
2061 if ( tag != LBER_ERROR ) {
2064 tool_write_ldif( LDIF_PUT_COMMENT, " what failed:", NULL, 0 );
2066 for ( i = 0; bva[i].bv_val != NULL; i++ ) {
2067 tool_write_ldif( LDIF_PUT_COMMENT, NULL, bva[i].bv_val, bva[i].bv_len );
2070 ldap_memfree( bva );
2080 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
2082 print_ppolicy( LDAP *ld, LDAPControl *ctrl )
2084 int expire = 0, grace = 0, rc;
2085 LDAPPasswordPolicyError pperr;
2087 rc = ldap_parse_passwordpolicy_control( ld, ctrl,
2088 &expire, &grace, &pperr );
2089 if ( rc == LDAP_SUCCESS ) {
2090 char buf[ BUFSIZ ], *ptr = buf;
2092 if ( expire != -1 ) {
2093 ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
2094 "expire=%d", expire );
2097 if ( grace != -1 ) {
2098 ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
2099 "%sgrace=%d", ptr == buf ? "" : " ", grace );
2102 if ( pperr != PP_noError ) {
2103 ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
2104 "%serror=%d (%s)", ptr == buf ? "" : " ",
2106 ldap_passwordpolicy_err2txt( pperr ) );
2109 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
2110 "ppolicy", buf, ptr - buf );
2117 void tool_print_ctrls(
2119 LDAPControl **ctrls )
2124 for ( i = 0; ctrls[i] != NULL; i++ ) {
2125 /* control: OID criticality base64value */
2126 struct berval b64 = BER_BVNULL;
2131 /* FIXME: there might be cases where a control has NULL OID;
2132 * this makes little sense, especially when returned by the
2133 * server, but libldap happily allows it */
2134 if ( ctrls[i]->ldctl_oid == NULL ) {
2139 len += strlen( ctrls[i]->ldctl_oid );
2141 /* add enough for space after OID and the critical value itself */
2142 len += ctrls[i]->ldctl_iscritical
2143 ? sizeof("true") : sizeof("false");
2145 /* convert to base64 */
2146 if ( !BER_BVISNULL( &ctrls[i]->ldctl_value ) ) {
2147 b64.bv_len = LUTIL_BASE64_ENCODE_LEN(
2148 ctrls[i]->ldctl_value.bv_len ) + 1;
2149 b64.bv_val = ber_memalloc( b64.bv_len + 1 );
2151 b64.bv_len = lutil_b64_ntop(
2152 (unsigned char *) ctrls[i]->ldctl_value.bv_val,
2153 ctrls[i]->ldctl_value.bv_len,
2154 b64.bv_val, b64.bv_len );
2158 len += 1 + b64.bv_len;
2161 ptr = str = malloc( len + 1 );
2163 ptr = lutil_strcopy( ptr, ": " );
2165 ptr = lutil_strcopy( ptr, ctrls[i]->ldctl_oid );
2166 ptr = lutil_strcopy( ptr, ctrls[i]->ldctl_iscritical
2167 ? " true" : " false" );
2170 ptr = lutil_strcopy( ptr, " " );
2171 ptr = lutil_strcopy( ptr, b64.bv_val );
2175 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
2176 "control", str, len );
2181 ber_memfree( b64.bv_val );
2184 /* known controls */
2185 for ( j = 0; tool_ctrl_response[j].oid != NULL; j++ ) {
2186 if ( strcmp( tool_ctrl_response[j].oid, ctrls[i]->ldctl_oid ) == 0 ) {
2187 if ( !tool_ctrl_response[j].mask & tool_type ) {
2188 /* this control should not appear
2189 * with this tool; warning? */
2195 if ( tool_ctrl_response[j].oid != NULL && tool_ctrl_response[j].func ) {
2196 (void)tool_ctrl_response[j].func( ld, ctrls[i] );
2202 tool_write_ldif( int type, char *name, char *value, ber_len_t vallen )
2206 if (( ldif = ldif_put( type, name, value, vallen )) == NULL ) {
2210 fputs( ldif, stdout );
2211 ber_memfree( ldif );
2217 tool_is_oid( const char *s )
2221 if ( !isdigit( (unsigned char) s[ 0 ] ) ) {
2225 for ( ; s[ 0 ]; s++ ) {
2226 if ( s[ 0 ] == '.' ) {
2227 if ( s[ 1 ] == '\0' ) {
2234 if ( !isdigit( (unsigned char) s[ 0 ] ) ) {
2238 if ( first == 1 && s[ 0 ] == '0' && s[ 1 ] != '.' ) {