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-2017 The OpenLDAP Foundation.
6 * Portions Copyright 2003 Kurt D. Zeilenga.
7 * Portions Copyright 2003 IBM Corporation.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted only as authorized by the OpenLDAP
14 * A copy of this license is available in the file LICENSE in the
15 * top-level directory of the distribution or, alternatively, at
16 * <http://www.OpenLDAP.org/license.html>.
19 * This file was initially created by Hallvard B. Furuseth based (in
20 * part) upon argument parsing code for individual tools located in
21 * this directory. Additional contributors include:
22 * Kurt D. Zeilenga (additional common argument and control support)
29 #include <ac/stdlib.h>
30 #include <ac/signal.h>
31 #include <ac/string.h>
33 #include <ac/unistd.h>
36 #include <ac/socket.h>
38 #ifdef HAVE_CYRUS_SASL
39 #ifdef HAVE_SASL_SASL_H
40 #include <sasl/sasl.h>
50 #include "lutil_ldap.h"
51 #include "ldap_defaults.h"
57 /* input-related vars */
59 /* misc. parameters */
60 tool_type_t tool_type;
69 ber_len_t ldif_wrap = 0;
74 char *ldaphost = NULL;
84 struct berval passwd = { 0, NULL };
86 #ifdef HAVE_CYRUS_SASL
87 unsigned sasl_flags = LDAP_SASL_AUTOMATIC;
88 char *sasl_realm = NULL;
89 char *sasl_authc_id = NULL;
90 char *sasl_authz_id = NULL;
91 char *sasl_mech = NULL;
92 char *sasl_secprops = NULL;
97 char *assertion = NULL;
98 struct berval assertionvalue = BER_BVNULL;
100 /* support deprecated early version of proxyAuthz */
101 #define LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ "2.16.840.1.113730.3.4.12"
102 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
103 char *proxydn = NULL;
104 #endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
110 static char *preread_attrs = NULL;
112 static char *postread_attrs = NULL;
113 ber_int_t pr_morePagedResults = 1;
114 struct berval pr_cookie = { 0, NULL };
115 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
117 static int chainingResolve = -1;
118 static int chainingContinuation = -1;
119 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
120 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
121 static int sessionTracking = 0;
122 struct berval stValue;
123 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
126 struct berval *vlvContext;
128 LDAPControl *unknown_ctrls = NULL;
129 int unknown_ctrls_num = 0;
132 struct timeval nettimeout = { -1 , 0 };
134 typedef int (*print_ctrl_fn)( LDAP *ld, LDAPControl *ctrl );
136 static int print_preread( LDAP *ld, LDAPControl *ctrl );
137 static int print_postread( LDAP *ld, LDAPControl *ctrl );
138 static int print_paged_results( LDAP *ld, LDAPControl *ctrl );
139 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
140 static int print_ppolicy( LDAP *ld, LDAPControl *ctrl );
142 static int print_sss( LDAP *ld, LDAPControl *ctrl );
143 static int print_vlv( LDAP *ld, LDAPControl *ctrl );
144 #ifdef LDAP_CONTROL_X_DEREF
145 static int print_deref( LDAP *ld, LDAPControl *ctrl );
147 #ifdef LDAP_CONTROL_X_WHATFAILED
148 static int print_whatfailed( LDAP *ld, LDAPControl *ctrl );
151 static struct tool_ctrls_t {
155 } tool_ctrl_response[] = {
156 { LDAP_CONTROL_PRE_READ, TOOL_ALL, print_preread },
157 { LDAP_CONTROL_POST_READ, TOOL_ALL, print_postread },
158 { LDAP_CONTROL_PAGEDRESULTS, TOOL_SEARCH, print_paged_results },
159 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
160 { LDAP_CONTROL_PASSWORDPOLICYRESPONSE, TOOL_ALL, print_ppolicy },
162 { LDAP_CONTROL_SORTRESPONSE, TOOL_SEARCH, print_sss },
163 { LDAP_CONTROL_VLVRESPONSE, TOOL_SEARCH, print_vlv },
164 #ifdef LDAP_CONTROL_X_DEREF
165 { LDAP_CONTROL_X_DEREF, TOOL_SEARCH, print_deref },
167 #ifdef LDAP_CONTROL_X_WHATFAILED
168 { LDAP_CONTROL_X_WHATFAILED, TOOL_ALL, print_whatfailed },
174 enum { Intr_None = 0, Intr_Abandon, Intr_Cancel, Intr_Ignore };
175 static volatile sig_atomic_t gotintr, abcan;
178 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
180 st_value( LDAP *ld, struct berval *value )
182 char *ip = NULL, *name = NULL;
183 struct berval id = { 0 };
184 char namebuf[ MAXHOSTNAMELEN ];
186 if ( gethostname( namebuf, sizeof( namebuf ) ) == 0 ) {
192 h = gethostbyname( name );
194 AC_MEMCPY( &addr, h->h_addr, sizeof( addr ) );
195 ip = inet_ntoa( addr );
199 #ifdef HAVE_CYRUS_SASL
200 if ( sasl_authz_id != NULL ) {
201 ber_str2bv( sasl_authz_id, 0, 0, &id );
203 } else if ( sasl_authc_id != NULL ) {
204 ber_str2bv( sasl_authc_id, 0, 0, &id );
207 #endif /* HAVE_CYRUS_SASL */
208 if ( binddn != NULL ) {
209 ber_str2bv( binddn, 0, 0, &id );
212 if ( ldap_create_session_tracking_value( ld,
213 ip, name, LDAP_CONTROL_X_SESSION_TRACKING_USERNAME,
216 fprintf( stderr, _("Session tracking control encoding error!\n") );
222 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
231 tool_init( tool_type_t type )
234 ldap_pvt_setlocale(LC_MESSAGES, "");
235 ldap_pvt_bindtextdomain(OPENLDAP_PACKAGE, LDAP_LOCALEDIR);
236 ldap_pvt_textdomain(OPENLDAP_PACKAGE);
242 static int destroyed;
246 #ifdef HAVE_CYRUS_SASL
250 ldap_pvt_tls_destroy();
253 if ( ldapuri != NULL ) {
254 ber_memfree( ldapuri );
258 if ( pr_cookie.bv_val != NULL ) {
259 ber_memfree( pr_cookie.bv_val );
260 BER_BVZERO( &pr_cookie );
263 if ( binddn != NULL ) {
264 ber_memfree( binddn );
268 if ( passwd.bv_val != NULL ) {
269 ber_memfree( passwd.bv_val );
270 BER_BVZERO( &passwd );
273 if ( infile != NULL ) {
274 ber_memfree( infile );
279 ber_memfree( assertion );
284 ber_memfree( authzid );
289 ber_memfree( proxydn );
293 if ( preread_attrs ) {
294 ber_memfree( preread_attrs );
295 preread_attrs = NULL;
298 if ( postread_attrs ) {
299 ber_memfree( postread_attrs );
300 postread_attrs = NULL;
305 tool_common_usage( void )
307 static const char *const descriptions[] = {
308 N_(" -d level set LDAP debugging level to `level'\n"),
309 N_(" -D binddn bind DN\n"),
310 N_(" -e [!]<ext>[=<extparam>] general extensions (! indicates criticality)\n")
311 N_(" [!]assert=<filter> (RFC 4528; a RFC 4515 Filter string)\n")
312 N_(" [!]authzid=<authzid> (RFC 4370; \"dn:<dn>\" or \"u:<user>\")\n")
313 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
315 /* non-advertized support for proxyDN */
316 N_(" [!]proxydn=<dn> (a RFC 4514 DN string)\n")
319 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
320 N_(" [!]chaining[=<resolveBehavior>[/<continuationBehavior>]]\n")
321 N_(" one of \"chainingPreferred\", \"chainingRequired\",\n")
322 N_(" \"referralsPreferred\", \"referralsRequired\"\n")
323 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
324 N_(" [!]manageDSAit (RFC 3296)\n")
326 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
329 N_(" [!]postread[=<attrs>] (RFC 4527; comma-separated attr list)\n")
330 N_(" [!]preread[=<attrs>] (RFC 4527; comma-separated attr list)\n")
332 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
333 N_(" [!]sessiontracking\n")
334 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
335 N_(" abandon, cancel, ignore (SIGINT sends abandon/cancel,\n"
336 " or ignores response; if critical, doesn't wait for SIGINT.\n"
337 " not really controls)\n")
338 N_(" -h host LDAP server\n"),
339 N_(" -H URI LDAP Uniform Resource Identifier(s)\n"),
340 N_(" -I use SASL Interactive mode\n"),
341 N_(" -n show what would be done but don't actually do it\n"),
342 N_(" -N do not use reverse DNS to canonicalize SASL host name\n"),
343 N_(" -O props SASL security properties\n"),
344 N_(" -o <opt>[=<optparam>] general options\n"),
345 N_(" nettimeout=<timeout> (in seconds, or \"none\" or \"max\")\n"),
346 N_(" ldif-wrap=<width> (in columns, or \"no\" for no wrapping)\n"),
347 N_(" -p port port on LDAP server\n"),
348 N_(" -Q use SASL Quiet mode\n"),
349 N_(" -R realm SASL realm\n"),
350 N_(" -U authcid SASL authentication identity\n"),
351 N_(" -v run in verbose mode (diagnostics to standard output)\n"),
352 N_(" -V print version info (-VV only)\n"),
353 N_(" -w passwd bind password (for simple authentication)\n"),
354 N_(" -W prompt for bind password\n"),
355 N_(" -x Simple authentication\n"),
356 N_(" -X authzid SASL authorization identity (\"dn:<dn>\" or \"u:<user>\")\n"),
357 N_(" -y file Read password from file\n"),
358 N_(" -Y mech SASL mechanism\n"),
359 N_(" -Z Start TLS request (-ZZ to require successful response)\n"),
362 const char *const *cpp;
364 fputs( _("Common options:\n"), stderr );
365 for( cpp = descriptions; *cpp != NULL; cpp++ ) {
366 if( strchr( options, (*cpp)[3] ) || (*cpp)[3] == ' ' ) {
367 fputs( _(*cpp), stderr );
382 fprintf( stderr, "%s: %s (%d)%s\n",
383 func, ldap_err2string( err ), err, extra ? extra : "" );
385 if ( matched && *matched ) {
386 fprintf( stderr, _("\tmatched DN: %s\n"), matched );
389 if ( info && *info ) {
390 fprintf( stderr, _("\tadditional info: %s\n"), info );
393 if ( refs && *refs ) {
395 fprintf( stderr, _("\treferrals:\n") );
396 for( i=0; refs[i]; i++ ) {
397 fprintf( stderr, "\t\t%s\n", refs[i] );
404 tool_args( int argc, char **argv )
408 while (( i = getopt( argc, argv, options )) != EOF ) {
410 char *control, *cvalue, *next;
412 case 'c': /* continuous operation mode */
415 case 'C': /* referrals: obsolete */
419 ival = strtol( optarg, &next, 10 );
420 if (next == NULL || next[0] != '\0') {
421 fprintf( stderr, "%s: unable to parse debug value \"%s\"\n", prog, optarg);
426 case 'D': /* bind DN */
427 if( binddn != NULL ) {
428 fprintf( stderr, "%s: -D previously specified\n", prog );
429 exit( EXIT_FAILURE );
431 binddn = ber_strdup( optarg );
433 case 'e': /* general extensions (controls and such) */
434 /* should be extended to support comma separated list of
435 * [!]key[=value] parameters, e.g. -e !foo,bar=567
440 if( optarg[0] == '!' ) {
445 control = ber_strdup( optarg );
446 if ( (cvalue = strchr( control, '=' )) != NULL ) {
450 if ( strcasecmp( control, "assert" ) == 0 ) {
452 fprintf( stderr, "assert control previously specified\n");
453 exit( EXIT_FAILURE );
455 if( cvalue == NULL ) {
456 fprintf( stderr, "assert: control value expected\n" );
460 assertctl = 1 + crit;
462 assert( assertion == NULL );
463 assertion = ber_strdup( cvalue );
465 } else if ( strcasecmp( control, "authzid" ) == 0 ) {
466 if( authzid != NULL ) {
467 fprintf( stderr, "authzid control previously specified\n");
468 exit( EXIT_FAILURE );
470 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
471 if( proxydn != NULL ) {
472 fprintf( stderr, "authzid control incompatible with proxydn\n");
473 exit( EXIT_FAILURE );
475 #endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
476 if( cvalue == NULL ) {
477 fprintf( stderr, "authzid: control value expected\n" );
481 fprintf( stderr, "authzid: must be marked critical\n" );
485 assert( authzid == NULL );
486 authzid = ber_strdup( cvalue );
488 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
489 } else if ( strcasecmp( control, "proxydn" ) == 0 ) {
490 if( proxydn != NULL ) {
491 fprintf( stderr, "proxydn control previously specified\n");
492 exit( EXIT_FAILURE );
494 if( authzid != NULL ) {
495 fprintf( stderr, "proxydn control incompatible with authzid\n");
496 exit( EXIT_FAILURE );
498 if( cvalue == NULL ) {
499 fprintf( stderr, "proxydn: control value expected\n" );
503 fprintf( stderr, "proxydn: must be marked critical\n" );
507 assert( proxydn == NULL );
508 proxydn = ber_strdup( cvalue );
509 #endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
511 } else if ( ( strcasecmp( control, "relax" ) == 0 ) ||
512 ( strcasecmp( control, "manageDIT" ) == 0 ) )
516 "relax control previously specified\n");
517 exit( EXIT_FAILURE );
519 if( cvalue != NULL ) {
521 "relax: no control value expected\n" );
525 manageDIT = 1 + crit;
527 } else if ( strcasecmp( control, "manageDSAit" ) == 0 ) {
530 "manageDSAit control previously specified\n");
531 exit( EXIT_FAILURE );
533 if( cvalue != NULL ) {
535 "manageDSAit: no control value expected\n" );
539 manageDSAit = 1 + crit;
541 } else if ( strcasecmp( control, "noop" ) == 0 ) {
543 fprintf( stderr, "noop control previously specified\n");
544 exit( EXIT_FAILURE );
546 if( cvalue != NULL ) {
547 fprintf( stderr, "noop: no control value expected\n" );
553 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
554 } else if ( strcasecmp( control, "ppolicy" ) == 0 ) {
556 fprintf( stderr, "ppolicy control previously specified\n");
557 exit( EXIT_FAILURE );
559 if( cvalue != NULL ) {
560 fprintf( stderr, "ppolicy: no control value expected\n" );
564 fprintf( stderr, "ppolicy: critical flag not allowed\n" );
571 } else if ( strcasecmp( control, "preread" ) == 0 ) {
573 fprintf( stderr, "preread control previously specified\n");
574 exit( EXIT_FAILURE );
578 preread_attrs = ber_strdup( cvalue );
580 } else if ( strcasecmp( control, "postread" ) == 0 ) {
582 fprintf( stderr, "postread control previously specified\n");
583 exit( EXIT_FAILURE );
587 postread_attrs = ber_strdup( cvalue );
589 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
590 } else if ( strcasecmp( control, "chaining" ) == 0 ) {
593 if ( cvalue != NULL ) {
596 continuation = strchr( cvalue, '/' );
597 if ( continuation ) {
598 /* FIXME: this makes sense only in searches */
599 *continuation++ = '\0';
600 if ( strcasecmp( continuation, "chainingPreferred" ) == 0 ) {
601 chainingContinuation = LDAP_CHAINING_PREFERRED;
602 } else if ( strcasecmp( continuation, "chainingRequired" ) == 0 ) {
603 chainingContinuation = LDAP_CHAINING_REQUIRED;
604 } else if ( strcasecmp( continuation, "referralsPreferred" ) == 0 ) {
605 chainingContinuation = LDAP_REFERRALS_PREFERRED;
606 } else if ( strcasecmp( continuation, "referralsRequired" ) == 0 ) {
607 chainingContinuation = LDAP_REFERRALS_REQUIRED;
610 "chaining behavior control "
611 "continuation value \"%s\" invalid\n",
613 exit( EXIT_FAILURE );
617 if ( strcasecmp( cvalue, "chainingPreferred" ) == 0 ) {
618 chainingResolve = LDAP_CHAINING_PREFERRED;
619 } else if ( strcasecmp( cvalue, "chainingRequired" ) == 0 ) {
620 chainingResolve = LDAP_CHAINING_REQUIRED;
621 } else if ( strcasecmp( cvalue, "referralsPreferred" ) == 0 ) {
622 chainingResolve = LDAP_REFERRALS_PREFERRED;
623 } else if ( strcasecmp( cvalue, "referralsRequired" ) == 0 ) {
624 chainingResolve = LDAP_REFERRALS_REQUIRED;
627 "chaining behavior control "
628 "resolve value \"%s\" invalid\n",
630 exit( EXIT_FAILURE );
633 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
635 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
636 } else if ( strcasecmp( control, "sessiontracking" ) == 0 ) {
637 if ( sessionTracking ) {
638 fprintf( stderr, "%s: session tracking can be only specified once\n", prog );
639 exit( EXIT_FAILURE );
643 fprintf( stderr, "sessiontracking: critical flag not allowed\n" );
646 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
648 /* this shouldn't go here, really; but it's a feature... */
649 } else if ( strcasecmp( control, "abandon" ) == 0 ) {
650 abcan = Intr_Abandon;
655 } else if ( strcasecmp( control, "cancel" ) == 0 ) {
661 } else if ( strcasecmp( control, "ignore" ) == 0 ) {
667 } else if ( tool_is_oid( control ) ) {
668 LDAPControl *tmpctrls, ctrl;
670 tmpctrls = (LDAPControl *)ber_memrealloc( unknown_ctrls,
671 (unknown_ctrls_num + 1)*sizeof( LDAPControl ) );
672 if ( tmpctrls == NULL ) {
673 fprintf( stderr, "%s: no memory?\n", prog );
674 exit( EXIT_FAILURE );
676 unknown_ctrls = tmpctrls;
677 ctrl.ldctl_oid = control;
680 ctrl.ldctl_value.bv_val = NULL;
681 ctrl.ldctl_value.bv_len = 0;
682 ctrl.ldctl_iscritical = crit;
684 if ( cvalue != NULL ) {
686 size_t len = strlen( cvalue );
689 bv.bv_len = LUTIL_BASE64_DECODE_LEN( len );
690 bv.bv_val = ber_memalloc( bv.bv_len + 1 );
692 retcode = lutil_b64_pton( cvalue,
693 (unsigned char *)bv.bv_val,
696 if ( retcode == -1 || (unsigned) retcode > bv.bv_len ) {
697 fprintf( stderr, "Unable to parse value of general control %s\n",
703 ctrl.ldctl_value = bv;
706 unknown_ctrls[ unknown_ctrls_num ] = ctrl;
710 fprintf( stderr, "Invalid general control name: %s\n",
715 ber_memfree( control );
719 case 'f': /* read from file */
720 if( infile != NULL ) {
721 fprintf( stderr, "%s: -f previously specified\n", prog );
722 exit( EXIT_FAILURE );
724 infile = ber_strdup( optarg );
726 case 'h': /* ldap host */
727 if( ldaphost != NULL ) {
728 fprintf( stderr, "%s: -h previously specified\n", prog );
729 exit( EXIT_FAILURE );
731 ldaphost = ber_strdup( optarg );
733 case 'H': /* ldap URI */
734 if( ldapuri != NULL ) {
735 fprintf( stderr, "%s: -H previously specified\n", prog );
736 exit( EXIT_FAILURE );
738 ldapuri = ber_strdup( optarg );
741 #ifdef HAVE_CYRUS_SASL
742 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
743 fprintf( stderr, "%s: incompatible previous "
744 "authentication choice\n",
746 exit( EXIT_FAILURE );
748 authmethod = LDAP_AUTH_SASL;
749 sasl_flags = LDAP_SASL_INTERACTIVE;
752 fprintf( stderr, "%s: was not compiled with SASL support\n",
754 exit( EXIT_FAILURE );
757 /* enable Manage DSA IT */
760 case 'n': /* print operations, don't actually do them */
767 control = ber_strdup( optarg );
768 if ( (cvalue = strchr( control, '=' )) != NULL ) {
772 if ( strcasecmp( control, "nettimeout" ) == 0 ) {
773 if( nettimeout.tv_sec != -1 ) {
774 fprintf( stderr, "nettimeout option previously specified\n");
775 exit( EXIT_FAILURE );
777 if( cvalue == NULL || cvalue[0] == '\0' ) {
778 fprintf( stderr, "nettimeout: option value expected\n" );
781 if ( strcasecmp( cvalue, "none" ) == 0 ) {
782 nettimeout.tv_sec = 0;
783 } else if ( strcasecmp( cvalue, "max" ) == 0 ) {
784 nettimeout.tv_sec = LDAP_MAXINT;
786 ival = strtol( cvalue, &next, 10 );
787 if ( next == NULL || next[0] != '\0' ) {
789 _("Unable to parse network timeout \"%s\"\n"), cvalue );
790 exit( EXIT_FAILURE );
792 nettimeout.tv_sec = ival;
794 if( nettimeout.tv_sec < 0 || nettimeout.tv_sec > LDAP_MAXINT ) {
795 fprintf( stderr, _("%s: invalid network timeout (%ld) specified\n"),
796 prog, (long)nettimeout.tv_sec );
797 exit( EXIT_FAILURE );
800 } else if ( strcasecmp( control, "ldif-wrap" ) == 0 ) {
802 ldif_wrap = LDIF_LINE_WIDTH;
804 } else if ( strcasecmp( cvalue, "no" ) == 0 ) {
805 ldif_wrap = LDIF_LINE_WIDTH_MAX;
809 if ( lutil_atou( &u, cvalue ) ) {
811 _("Unable to parse ldif-wrap=\"%s\"\n"), cvalue );
812 exit( EXIT_FAILURE );
814 ldif_wrap = (ber_len_t)u;
818 fprintf( stderr, "Invalid general option name: %s\n",
822 ber_memfree(control);
825 #ifdef HAVE_CYRUS_SASL
826 if( sasl_secprops != NULL ) {
827 fprintf( stderr, "%s: -O previously specified\n", prog );
828 exit( EXIT_FAILURE );
830 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
831 fprintf( stderr, "%s: incompatible previous "
832 "authentication choice\n", prog );
833 exit( EXIT_FAILURE );
835 authmethod = LDAP_AUTH_SASL;
836 sasl_secprops = ber_strdup( optarg );
838 fprintf( stderr, "%s: not compiled with SASL support\n", prog );
839 exit( EXIT_FAILURE );
844 fprintf( stderr, "%s: -p previously specified\n", prog );
845 exit( EXIT_FAILURE );
847 ival = strtol( optarg, &next, 10 );
848 if ( next == NULL || next[0] != '\0' ) {
849 fprintf( stderr, "%s: unable to parse port number \"%s\"\n", prog, optarg );
850 exit( EXIT_FAILURE );
855 ival = strtol( optarg, &next, 10 );
856 if ( next == NULL || next[0] != '\0' ) {
857 fprintf( stderr, "%s: unable to parse protocol version \"%s\"\n", prog, optarg );
858 exit( EXIT_FAILURE );
862 if( protocol == LDAP_VERSION3 ) {
863 fprintf( stderr, "%s: -P 2 incompatible with version %d\n",
865 exit( EXIT_FAILURE );
867 protocol = LDAP_VERSION2;
870 if( protocol == LDAP_VERSION2 ) {
871 fprintf( stderr, "%s: -P 2 incompatible with version %d\n",
873 exit( EXIT_FAILURE );
875 protocol = LDAP_VERSION3;
878 fprintf( stderr, "%s: protocol version should be 2 or 3\n",
884 #ifdef HAVE_CYRUS_SASL
885 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
886 fprintf( stderr, "%s: incompatible previous "
887 "authentication choice\n",
889 exit( EXIT_FAILURE );
891 authmethod = LDAP_AUTH_SASL;
892 sasl_flags = LDAP_SASL_QUIET;
895 fprintf( stderr, "%s: not compiled with SASL support\n",
897 exit( EXIT_FAILURE );
900 #ifdef HAVE_CYRUS_SASL
901 if( sasl_realm != NULL ) {
902 fprintf( stderr, "%s: -R previously specified\n", prog );
903 exit( EXIT_FAILURE );
905 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
906 fprintf( stderr, "%s: incompatible previous "
907 "authentication choice\n",
909 exit( EXIT_FAILURE );
911 authmethod = LDAP_AUTH_SASL;
912 sasl_realm = ber_strdup( optarg );
914 fprintf( stderr, "%s: not compiled with SASL support\n",
916 exit( EXIT_FAILURE );
920 #ifdef HAVE_CYRUS_SASL
921 if( sasl_authc_id != NULL ) {
922 fprintf( stderr, "%s: -U previously specified\n", prog );
923 exit( EXIT_FAILURE );
925 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
926 fprintf( stderr, "%s: incompatible previous "
927 "authentication choice\n",
929 exit( EXIT_FAILURE );
931 authmethod = LDAP_AUTH_SASL;
932 sasl_authc_id = ber_strdup( optarg );
934 fprintf( stderr, "%s: not compiled with SASL support\n",
936 exit( EXIT_FAILURE );
939 case 'v': /* verbose mode */
942 case 'V': /* version */
945 case 'w': /* password */
946 passwd.bv_val = ber_strdup( optarg );
950 for( p = optarg; *p != '\0'; p++ ) {
954 passwd.bv_len = strlen( passwd.bv_val );
963 #ifdef HAVE_CYRUS_SASL
964 if( sasl_mech != NULL ) {
965 fprintf( stderr, "%s: -Y previously specified\n", prog );
966 exit( EXIT_FAILURE );
968 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
970 "%s: incompatible with authentication choice\n", prog );
971 exit( EXIT_FAILURE );
973 authmethod = LDAP_AUTH_SASL;
974 sasl_mech = ber_strdup( optarg );
976 fprintf( stderr, "%s: not compiled with SASL support\n", prog );
977 exit( EXIT_FAILURE );
981 if( authmethod != -1 && authmethod != LDAP_AUTH_SIMPLE ) {
982 fprintf( stderr, "%s: incompatible with previous "
983 "authentication choice\n", prog );
984 exit( EXIT_FAILURE );
986 authmethod = LDAP_AUTH_SIMPLE;
989 #ifdef HAVE_CYRUS_SASL
990 if( sasl_authz_id != NULL ) {
991 fprintf( stderr, "%s: -X previously specified\n", prog );
992 exit( EXIT_FAILURE );
994 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
995 fprintf( stderr, "%s: -X incompatible with "
996 "authentication choice\n", prog );
997 exit( EXIT_FAILURE );
999 authmethod = LDAP_AUTH_SASL;
1000 sasl_authz_id = ber_strdup( optarg );
1002 fprintf( stderr, "%s: not compiled with SASL support\n", prog );
1003 exit( EXIT_FAILURE );
1010 fprintf( stderr, "%s: not compiled with TLS support\n", prog );
1011 exit( EXIT_FAILURE );
1015 if( handle_private_option( i ) ) break;
1016 fprintf( stderr, "%s: unrecognized option -%c\n",
1023 /* prevent bad linking */
1025 api.ldapai_info_version = LDAP_API_INFO_VERSION;
1027 if ( ldap_get_option(NULL, LDAP_OPT_API_INFO, &api)
1028 != LDAP_OPT_SUCCESS )
1030 fprintf( stderr, "%s: ldap_get_option(API_INFO) failed\n", prog );
1031 exit( EXIT_FAILURE );
1034 if (api.ldapai_info_version != LDAP_API_INFO_VERSION) {
1035 fprintf( stderr, "LDAP APIInfo version mismatch: "
1036 "library %d, header %d\n",
1037 api.ldapai_info_version, LDAP_API_INFO_VERSION );
1038 exit( EXIT_FAILURE );
1041 if( api.ldapai_api_version != LDAP_API_VERSION ) {
1042 fprintf( stderr, "LDAP API version mismatch: "
1043 "library %d, header %d\n",
1044 api.ldapai_api_version, LDAP_API_VERSION );
1045 exit( EXIT_FAILURE );
1048 if( strcmp(api.ldapai_vendor_name, LDAP_VENDOR_NAME ) != 0 ) {
1049 fprintf( stderr, "LDAP vendor name mismatch: "
1050 "library %s, header %s\n",
1051 api.ldapai_vendor_name, LDAP_VENDOR_NAME );
1052 exit( EXIT_FAILURE );
1055 if( api.ldapai_vendor_version != LDAP_VENDOR_VERSION ) {
1056 fprintf( stderr, "LDAP vendor version mismatch: "
1057 "library %d, header %d\n",
1058 api.ldapai_vendor_version, LDAP_VENDOR_VERSION );
1059 exit( EXIT_FAILURE );
1063 fprintf( stderr, "%s: %s\t(LDAP library: %s %d)\n",
1065 LDAP_VENDOR_NAME, LDAP_VENDOR_VERSION );
1066 if (version > 1) exit( EXIT_SUCCESS );
1069 ldap_memfree( api.ldapai_vendor_name );
1070 ber_memvfree( (void **)api.ldapai_extensions );
1074 protocol = LDAP_VERSION3;
1076 if (authmethod == -1 && protocol > LDAP_VERSION2) {
1077 #ifdef HAVE_CYRUS_SASL
1078 if ( binddn != NULL ) {
1079 authmethod = LDAP_AUTH_SIMPLE;
1081 authmethod = LDAP_AUTH_SASL;
1084 authmethod = LDAP_AUTH_SIMPLE;
1088 if( ldapuri == NULL ) {
1089 if( ldapport && ( ldaphost == NULL )) {
1090 fprintf( stderr, "%s: -p without -h is invalid.\n", prog );
1091 exit( EXIT_FAILURE );
1094 if( ldaphost != NULL ) {
1095 fprintf( stderr, "%s: -H incompatible with -h\n", prog );
1096 exit( EXIT_FAILURE );
1099 fprintf( stderr, "%s: -H incompatible with -p\n", prog );
1100 exit( EXIT_FAILURE );
1104 if( protocol == LDAP_VERSION2 ) {
1105 if( assertctl || authzid || manageDIT || manageDSAit ||
1106 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
1108 #endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
1109 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
1112 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
1114 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
1115 noop || ppolicy || preread || postread )
1117 fprintf( stderr, "%s: -e/-M incompatible with LDAPv2\n", prog );
1118 exit( EXIT_FAILURE );
1122 fprintf( stderr, "%s: -Z incompatible with LDAPv2\n", prog );
1123 exit( EXIT_FAILURE );
1126 #ifdef HAVE_CYRUS_SASL
1127 if( authmethod == LDAP_AUTH_SASL ) {
1128 fprintf( stderr, "%s: -[IOQRUXY] incompatible with LDAPv2\n",
1130 exit( EXIT_FAILURE );
1135 if ( ( pw_file || want_bindpw ) && !BER_BVISNULL( &passwd ) ) {
1136 fprintf( stderr, "%s: -%c incompatible with -w\n",
1137 prog, ( pw_file ? 'y' : 'W' ) );
1138 exit( EXIT_FAILURE );
1144 tool_conn_setup( int dont, void (*private_setup)( LDAP * ) )
1149 if( ber_set_option( NULL, LBER_OPT_DEBUG_LEVEL, &debug )
1150 != LBER_OPT_SUCCESS )
1153 "Could not set LBER_OPT_DEBUG_LEVEL %d\n", debug );
1155 if( ldap_set_option( NULL, LDAP_OPT_DEBUG_LEVEL, &debug )
1156 != LDAP_OPT_SUCCESS )
1159 "Could not set LDAP_OPT_DEBUG_LEVEL %d\n", debug );
1164 (void) SIGNAL( SIGPIPE, SIG_IGN );
1168 SIGNAL( SIGINT, do_sig );
1174 if( ( ldaphost != NULL || ldapport ) && ( ldapuri == NULL ) ) {
1177 memset( &url, 0, sizeof(url));
1179 url.lud_scheme = "ldap";
1180 url.lud_host = ldaphost;
1181 url.lud_port = ldapport;
1182 url.lud_scope = LDAP_SCOPE_DEFAULT;
1184 ldapuri = ldap_url_desc2str( &url );
1186 } else if ( ldapuri != NULL ) {
1187 LDAPURLDesc *ludlist, **ludp;
1191 rc = ldap_url_parselist( &ludlist, ldapuri );
1192 if ( rc != LDAP_URL_SUCCESS ) {
1194 "Could not parse LDAP URI(s)=%s (%d)\n",
1196 exit( EXIT_FAILURE );
1199 for ( ludp = &ludlist; *ludp != NULL; ) {
1200 LDAPURLDesc *lud = *ludp;
1203 if ( lud->lud_dn != NULL && lud->lud_dn[ 0 ] != '\0' &&
1204 ( lud->lud_host == NULL || lud->lud_host[0] == '\0' ) )
1206 /* if no host but a DN is provided,
1207 * use DNS SRV to gather the host list
1208 * and turn it into a list of URIs
1209 * using the scheme provided */
1210 char *domain = NULL,
1214 len_proto = strlen( lud->lud_scheme );
1216 if ( ldap_dn2domain( lud->lud_dn, &domain )
1220 "DNS SRV: Could not turn "
1221 "DN=\"%s\" into a domain\n",
1226 rc = ldap_domain2hostlist( domain, &hostlist );
1229 "DNS SRV: Could not turn "
1230 "domain=%s into a hostlist\n",
1235 hosts = ldap_str2charray( hostlist, " " );
1236 if ( hosts == NULL ) {
1238 "DNS SRV: Could not parse "
1239 "hostlist=\"%s\"\n",
1244 for ( i = 0; hosts[ i ] != NULL; i++ )
1247 tmp = (char **)ber_memrealloc( urls, sizeof( char * ) * ( nurls + i + 1 ) );
1248 if ( tmp == NULL ) {
1250 "DNS SRV: out of memory?\n" );
1254 urls[ nurls ] = NULL;
1256 for ( i = 0; hosts[ i ] != NULL; i++ ) {
1257 size_t len = len_proto
1259 + strlen( hosts[ i ] )
1262 urls[ nurls + i + 1 ] = NULL;
1263 urls[ nurls + i ] = (char *)malloc( sizeof( char ) * len );
1264 if ( urls[ nurls + i ] == NULL ) {
1266 "DNS SRV: out of memory?\n" );
1270 snprintf( urls[ nurls + i ], len, "%s://%s",
1271 lud->lud_scheme, hosts[ i ] );
1276 ber_memvfree( (void **)hosts );
1277 ber_memfree( hostlist );
1278 ber_memfree( domain );
1281 tmp = (char **)ber_memrealloc( urls, sizeof( char * ) * ( nurls + 2 ) );
1282 if ( tmp == NULL ) {
1284 "DNS SRV: out of memory?\n" );
1288 urls[ nurls + 1 ] = NULL;
1290 urls[ nurls ] = ldap_url_desc2str( lud );
1291 if ( urls[ nurls ] == NULL ) {
1293 "DNS SRV: out of memory?\n" );
1299 *ludp = lud->lud_next;
1301 lud->lud_next = NULL;
1302 ldap_free_urldesc( lud );
1305 if ( ludlist != NULL ) {
1306 ldap_free_urllist( ludlist );
1307 exit( EXIT_FAILURE );
1309 } else if ( urls == NULL ) {
1310 exit( EXIT_FAILURE );
1313 ldap_memfree( ldapuri );
1314 ldapuri = ldap_charray2str( urls, " " );
1315 ber_memvfree( (void **)urls );
1319 fprintf( stderr, "ldap_initialize( %s )\n",
1320 ldapuri != NULL ? ldapuri : "<DEFAULT>" );
1322 rc = ldap_initialize( &ld, ldapuri );
1323 if( rc != LDAP_SUCCESS ) {
1325 "Could not create LDAP session handle for URI=%s (%d): %s\n",
1326 ldapuri, rc, ldap_err2string(rc) );
1327 exit( EXIT_FAILURE );
1330 if( private_setup ) private_setup( ld );
1332 /* referrals: obsolete */
1333 if( ldap_set_option( ld, LDAP_OPT_REFERRALS,
1334 referrals ? LDAP_OPT_ON : LDAP_OPT_OFF ) != LDAP_OPT_SUCCESS )
1336 fprintf( stderr, "Could not set LDAP_OPT_REFERRALS %s\n",
1337 referrals ? "on" : "off" );
1338 tool_exit( ld, EXIT_FAILURE );
1341 #ifdef HAVE_CYRUS_SASL
1344 if( ldap_set_option( ld, LDAP_OPT_X_SASL_NOCANON,
1345 LDAP_OPT_ON ) != LDAP_OPT_SUCCESS )
1347 fprintf( stderr, "Could not set LDAP_OPT_X_SASL_NOCANON on\n" );
1348 tool_exit( ld, EXIT_FAILURE );
1352 if( ldap_set_option( ld, LDAP_OPT_PROTOCOL_VERSION, &protocol )
1353 != LDAP_OPT_SUCCESS )
1355 fprintf( stderr, "Could not set LDAP_OPT_PROTOCOL_VERSION %d\n",
1357 tool_exit( ld, EXIT_FAILURE );
1361 rc = ldap_start_tls_s( ld, NULL, NULL );
1362 if ( rc != LDAP_SUCCESS ) {
1364 ldap_get_option( ld, LDAP_OPT_DIAGNOSTIC_MESSAGE, (void*)&msg);
1365 tool_perror( "ldap_start_tls", rc, NULL, NULL, msg, NULL );
1367 if ( use_tls > 1 ) {
1368 tool_exit( ld, EXIT_FAILURE );
1373 if ( nettimeout.tv_sec > 0 ) {
1374 if ( ldap_set_option( ld, LDAP_OPT_NETWORK_TIMEOUT, (void *) &nettimeout )
1375 != LDAP_OPT_SUCCESS )
1377 fprintf( stderr, "Could not set LDAP_OPT_NETWORK_TIMEOUT %ld\n",
1378 (long)nettimeout.tv_sec );
1379 tool_exit( ld, EXIT_FAILURE );
1389 tool_bind( LDAP *ld )
1391 LDAPControl **sctrlsp = NULL;
1392 LDAPControl *sctrls[3];
1393 LDAPControl sctrl[3];
1396 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
1399 c.ldctl_oid = LDAP_CONTROL_PASSWORDPOLICYREQUEST;
1400 c.ldctl_value.bv_val = NULL;
1401 c.ldctl_value.bv_len = 0;
1402 c.ldctl_iscritical = 0;
1404 sctrls[nsctrls] = &sctrl[nsctrls];
1405 sctrls[++nsctrls] = NULL;
1409 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
1410 if ( sessionTracking ) {
1413 if ( BER_BVISNULL( &stValue) && st_value( ld, &stValue ) ) {
1414 tool_exit( ld, EXIT_FAILURE );
1417 c.ldctl_oid = LDAP_CONTROL_X_SESSION_TRACKING;
1418 c.ldctl_iscritical = 0;
1419 ber_dupbv( &c.ldctl_value, &stValue );
1422 sctrls[nsctrls] = &sctrl[nsctrls];
1423 sctrls[++nsctrls] = NULL;
1425 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
1431 assert( nsctrls < (int) (sizeof(sctrls)/sizeof(sctrls[0])) );
1433 if ( pw_file || want_bindpw ) {
1434 assert( passwd.bv_val == NULL && passwd.bv_len == 0 );
1437 if ( lutil_get_filed_password( pw_file, &passwd ) ) {
1438 tool_exit( ld, EXIT_FAILURE );
1442 char *pw = getpassphrase( _("Enter LDAP Password: ") );
1444 passwd.bv_val = ber_strdup( pw );
1445 passwd.bv_len = strlen( passwd.bv_val );
1450 if ( authmethod == LDAP_AUTH_SASL ) {
1451 #ifdef HAVE_CYRUS_SASL
1455 if( sasl_secprops != NULL ) {
1456 rc = ldap_set_option( ld, LDAP_OPT_X_SASL_SECPROPS,
1457 (void *) sasl_secprops );
1459 if( rc != LDAP_OPT_SUCCESS ) {
1461 "Could not set LDAP_OPT_X_SASL_SECPROPS: %s\n",
1463 tool_exit( ld, LDAP_LOCAL_ERROR );
1467 defaults = lutil_sasl_defaults( ld,
1474 rc = ldap_sasl_interactive_bind_s( ld, binddn, sasl_mech,
1476 NULL, sasl_flags, lutil_sasl_interact, defaults );
1478 lutil_sasl_freedefs( defaults );
1479 if( rc != LDAP_SUCCESS ) {
1481 ldap_get_option( ld, LDAP_OPT_DIAGNOSTIC_MESSAGE, (void*)&msg);
1482 tool_perror( "ldap_sasl_interactive_bind_s",
1483 rc, NULL, NULL, msg, NULL );
1485 tool_exit( ld, rc );
1488 fprintf( stderr, "%s: not compiled with SASL support\n", prog );
1489 tool_exit( ld, LDAP_NOT_SUPPORTED );
1493 LDAPMessage *result;
1494 LDAPControl **ctrls;
1496 char *matched = NULL;
1504 rc = ldap_sasl_bind( ld, binddn, LDAP_SASL_SIMPLE, &passwd,
1505 sctrlsp, NULL, &msgid );
1506 if ( msgid == -1 ) {
1507 tool_perror( "ldap_sasl_bind(SIMPLE)", rc,
1508 NULL, NULL, NULL, NULL );
1509 tool_exit( ld, rc );
1513 rc = ldap_result( ld, msgid, LDAP_MSG_ALL, NULL, &result );
1515 tool_perror( "ldap_result", -1, NULL, NULL, NULL, NULL );
1516 tool_exit( ld, LDAP_LOCAL_ERROR );
1520 tool_perror( "ldap_result", LDAP_TIMEOUT, NULL, NULL, NULL, NULL );
1521 tool_exit( ld, LDAP_LOCAL_ERROR );
1525 rc = ldap_parse_result( ld, result, &err, &matched, &info, &refs,
1527 if ( rc != LDAP_SUCCESS ) {
1528 tool_perror( "ldap_bind parse result", rc, NULL, matched, info, refs );
1529 tool_exit( ld, LDAP_LOCAL_ERROR );
1533 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
1534 if ( ctrls && ppolicy ) {
1536 int expire, grace, len = 0;
1537 LDAPPasswordPolicyError pErr = -1;
1539 ctrl = ldap_control_find( LDAP_CONTROL_PASSWORDPOLICYRESPONSE,
1542 if ( ctrl && ldap_parse_passwordpolicy_control( ld, ctrl,
1543 &expire, &grace, &pErr ) == LDAP_SUCCESS )
1545 if ( pErr != PP_noError ){
1548 strcpy( msgbuf+2, ldap_passwordpolicy_err2txt( pErr ));
1549 len = strlen( msgbuf );
1551 if ( expire >= 0 ) {
1552 sprintf( msgbuf+len,
1553 " (Password expires in %d seconds)",
1555 } else if ( grace >= 0 ) {
1556 sprintf( msgbuf+len,
1557 " (Password expired, %d grace logins remain)",
1565 ldap_controls_free( ctrls );
1568 if ( err != LDAP_SUCCESS
1570 || ( matched && matched[ 0 ] )
1571 || ( info && info[ 0 ] )
1574 tool_perror( "ldap_bind", err, msgbuf, matched, info, refs );
1576 if( matched ) ber_memfree( matched );
1577 if( info ) ber_memfree( info );
1578 if( refs ) ber_memvfree( (void **)refs );
1580 if ( err != LDAP_SUCCESS ) tool_exit( ld, err );
1586 tool_unbind( LDAP *ld )
1588 int err = ldap_set_option( ld, LDAP_OPT_SERVER_CONTROLS, NULL );
1590 if ( err != LDAP_OPT_SUCCESS ) {
1591 fprintf( stderr, "Could not unset controls\n");
1594 (void) ldap_unbind_ext( ld, NULL, NULL );
1598 tool_exit( LDAP *ld, int status )
1608 /* Set server controls. Add controls extra_c[0..count-1], if set. */
1610 tool_server_controls( LDAP *ld, LDAPControl *extra_c, int count )
1612 int i = 0, j, crit = 0, err;
1613 LDAPControl c[16], **ctrls;
1617 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
1619 #endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
1623 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
1628 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
1630 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
1631 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
1633 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
1635 || unknown_ctrls_num ) )
1640 ctrls = (LDAPControl**) malloc(sizeof(c) + (count + unknown_ctrls_num + 1)*sizeof(LDAPControl*));
1641 if ( ctrls == NULL ) {
1642 fprintf( stderr, "No memory\n" );
1643 tool_exit( ld, EXIT_FAILURE );
1647 if ( BER_BVISNULL( &assertionvalue ) ) {
1648 err = ldap_create_assertion_control_value( ld,
1649 assertion, &assertionvalue );
1652 "Unable to create assertion value "
1653 "\"%s\" (%d)\n", assertion, err );
1657 c[i].ldctl_oid = LDAP_CONTROL_ASSERT;
1658 c[i].ldctl_value = assertionvalue;
1659 c[i].ldctl_iscritical = assertctl > 1;
1665 c[i].ldctl_value.bv_val = authzid;
1666 c[i].ldctl_value.bv_len = strlen( authzid );
1667 c[i].ldctl_oid = LDAP_CONTROL_PROXY_AUTHZ;
1668 c[i].ldctl_iscritical = 1;
1673 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
1674 /* NOTE: doesn't need an extra count because it's incompatible
1677 BerElementBuffer berbuf;
1678 BerElement *ber = (BerElement *)&berbuf;
1680 ber_init2( ber, NULL, LBER_USE_DER );
1682 if ( ber_printf( ber, "s", proxydn ) == -1 ) {
1683 tool_exit( ld, EXIT_FAILURE );
1686 if ( ber_flatten2( ber, &c[i].ldctl_value, 0 ) == -1 ) {
1687 tool_exit( ld, EXIT_FAILURE );
1690 c[i].ldctl_oid = LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ;
1691 c[i].ldctl_iscritical = 1;
1695 #endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
1698 c[i].ldctl_oid = LDAP_CONTROL_MANAGEDIT;
1699 BER_BVZERO( &c[i].ldctl_value );
1700 c[i].ldctl_iscritical = manageDIT > 1;
1705 if ( manageDSAit ) {
1706 c[i].ldctl_oid = LDAP_CONTROL_MANAGEDSAIT;
1707 BER_BVZERO( &c[i].ldctl_value );
1708 c[i].ldctl_iscritical = manageDSAit > 1;
1714 c[i].ldctl_oid = LDAP_CONTROL_NOOP;
1715 BER_BVZERO( &c[i].ldctl_value );
1716 c[i].ldctl_iscritical = noop > 1;
1721 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
1723 c[i].ldctl_oid = LDAP_CONTROL_PASSWORDPOLICYREQUEST;
1724 BER_BVZERO( &c[i].ldctl_value );
1725 c[i].ldctl_iscritical = 0;
1732 BerElementBuffer berbuf;
1733 BerElement *ber = (BerElement *)&berbuf;
1734 char **attrs = NULL;
1736 if( preread_attrs ) {
1737 attrs = ldap_str2charray( preread_attrs, "," );
1740 ber_init2( ber, NULL, LBER_USE_DER );
1742 if( ber_printf( ber, "{v}", attrs ) == -1 ) {
1743 fprintf( stderr, "preread attrs encode failed.\n" );
1744 tool_exit( ld, EXIT_FAILURE );
1747 err = ber_flatten2( ber, &c[i].ldctl_value, 0 );
1749 fprintf( stderr, "preread flatten failed (%d)\n", err );
1750 tool_exit( ld, EXIT_FAILURE );
1753 c[i].ldctl_oid = LDAP_CONTROL_PRE_READ;
1754 c[i].ldctl_iscritical = preread > 1;
1758 if( attrs ) ldap_charray_free( attrs );
1762 BerElementBuffer berbuf;
1763 BerElement *ber = (BerElement *)&berbuf;
1764 char **attrs = NULL;
1766 if( postread_attrs ) {
1767 attrs = ldap_str2charray( postread_attrs, "," );
1770 ber_init2( ber, NULL, LBER_USE_DER );
1772 if( ber_printf( ber, "{v}", attrs ) == -1 ) {
1773 fprintf( stderr, "postread attrs encode failed.\n" );
1774 tool_exit( ld, EXIT_FAILURE );
1777 err = ber_flatten2( ber, &c[i].ldctl_value, 0 );
1779 fprintf( stderr, "postread flatten failed (%d)\n", err );
1780 tool_exit( ld, EXIT_FAILURE );
1783 c[i].ldctl_oid = LDAP_CONTROL_POST_READ;
1784 c[i].ldctl_iscritical = postread > 1;
1788 if( attrs ) ldap_charray_free( attrs );
1791 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
1793 if ( chainingResolve > -1 ) {
1794 BerElementBuffer berbuf;
1795 BerElement *ber = (BerElement *)&berbuf;
1797 ber_init2( ber, NULL, LBER_USE_DER );
1799 err = ber_printf( ber, "{e" /* } */, chainingResolve );
1802 fprintf( stderr, _("Chaining behavior control encoding error!\n") );
1803 tool_exit( ld, EXIT_FAILURE );
1806 if ( chainingContinuation > -1 ) {
1807 err = ber_printf( ber, "e", chainingContinuation );
1810 fprintf( stderr, _("Chaining behavior control encoding error!\n") );
1811 tool_exit( ld, EXIT_FAILURE );
1815 err = ber_printf( ber, /* { */ "N}" );
1818 fprintf( stderr, _("Chaining behavior control encoding error!\n") );
1819 tool_exit( ld, EXIT_FAILURE );
1822 if ( ber_flatten2( ber, &c[i].ldctl_value, 0 ) == -1 ) {
1823 tool_exit( ld, EXIT_FAILURE );
1827 BER_BVZERO( &c[i].ldctl_value );
1830 c[i].ldctl_oid = LDAP_CONTROL_X_CHAINING_BEHAVIOR;
1831 c[i].ldctl_iscritical = chaining > 1;
1835 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
1837 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
1838 if ( sessionTracking ) {
1839 if ( BER_BVISNULL( &stValue ) && st_value( ld, &stValue ) ) {
1840 tool_exit( ld, EXIT_FAILURE );
1843 c[i].ldctl_oid = LDAP_CONTROL_X_SESSION_TRACKING;
1844 c[i].ldctl_iscritical = 0;
1845 ber_dupbv( &c[i].ldctl_value, &stValue );
1850 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
1853 ctrls[i++] = extra_c++;
1855 for ( count = 0; count < unknown_ctrls_num; count++ ) {
1856 ctrls[i++] = &unknown_ctrls[count];
1860 err = ldap_set_option( ld, LDAP_OPT_SERVER_CONTROLS, ctrls );
1862 if ( err != LDAP_OPT_SUCCESS ) {
1863 for ( j = 0; j < i; j++ ) {
1864 if ( ctrls[j]->ldctl_iscritical ) crit = 1;
1866 fprintf( stderr, "Could not set %scontrols\n",
1867 crit ? "critical " : "" );
1872 tool_exit( ld, EXIT_FAILURE );
1877 tool_check_abandon( LDAP *ld, int msgid )
1881 switch ( gotintr ) {
1883 rc = ldap_cancel_s( ld, msgid, NULL, NULL );
1884 fprintf( stderr, "got interrupt, cancel got %d: %s\n",
1885 rc, ldap_err2string( rc ) );
1889 rc = ldap_abandon_ext( ld, msgid, NULL, NULL );
1890 fprintf( stderr, "got interrupt, abandon got %d: %s\n",
1891 rc, ldap_err2string( rc ) );
1895 /* just unbind, ignoring the request */
1903 print_prepostread( LDAP *ld, LDAPControl *ctrl, struct berval *what)
1908 tool_write_ldif( LDIF_PUT_COMMENT, "==> ",
1909 what->bv_val, what->bv_len );
1910 ber = ber_init( &ctrl->ldctl_value );
1911 if ( ber == NULL ) {
1915 } else if ( ber_scanf( ber, "{m{" /*}}*/, &bv ) == LBER_ERROR ) {
1920 tool_write_ldif( LDIF_PUT_VALUE, "dn", bv.bv_val, bv.bv_len );
1922 while ( ber_scanf( ber, "{m" /*}*/, &bv ) != LBER_ERROR ) {
1924 BerVarray vals = NULL;
1927 if ( ber_scanf( ber, "[W]", &vals ) == LBER_ERROR ||
1937 str = malloc( bv.bv_len + STRLENOF(": ") + 1 );
1940 ptr = lutil_strncopy( ptr, bv.bv_val, bv.bv_len );
1941 ptr = lutil_strcopy( ptr, ": " );
1944 for ( i = 0; vals[ i ].bv_val != NULL; i++ ) {
1946 ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1947 ldif ? str : bv.bv_val, vals[ i ].bv_val, vals[ i ].bv_len );
1950 ber_bvarray_free( vals );
1951 if ( str ) free( str );
1955 if ( ber != NULL ) {
1959 tool_write_ldif( LDIF_PUT_COMMENT, "<== ",
1960 what->bv_val, what->bv_len );
1966 print_preread( LDAP *ld, LDAPControl *ctrl )
1968 static struct berval what = BER_BVC( "preread" );
1970 return print_prepostread( ld, ctrl, &what );
1974 print_postread( LDAP *ld, LDAPControl *ctrl )
1976 static struct berval what = BER_BVC( "postread" );
1978 return print_prepostread( ld, ctrl, &what );
1982 print_paged_results( LDAP *ld, LDAPControl *ctrl )
1986 /* note: pr_cookie is being malloced; it's freed
1987 * the next time the control is sent, but the last
1988 * time it's not; we don't care too much, because
1989 * the last time an empty value is returned... */
1990 if ( ldap_parse_pageresponse_control( ld, ctrl, &estimate, &pr_cookie )
1997 /* FIXME: check buffer overflow */
1998 char buf[ BUFSIZ ], *ptr = buf;
2000 if ( estimate > 0 ) {
2001 ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
2002 "estimate=%d", estimate );
2005 if ( pr_cookie.bv_len > 0 ) {
2008 bv.bv_len = LUTIL_BASE64_ENCODE_LEN(
2009 pr_cookie.bv_len ) + 1;
2010 bv.bv_val = ber_memalloc( bv.bv_len + 1 );
2012 bv.bv_len = lutil_b64_ntop(
2013 (unsigned char *) pr_cookie.bv_val,
2015 bv.bv_val, bv.bv_len );
2017 ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
2018 "%scookie=%s", ptr == buf ? "" : " ",
2021 ber_memfree( bv.bv_val );
2023 pr_morePagedResults = 1;
2026 ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
2027 "%scookie=", ptr == buf ? "" : " " );
2030 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
2031 ldif ? "pagedresults: " : "pagedresults",
2039 print_sss( LDAP *ld, LDAPControl *ctrl )
2045 rc = ldap_parse_sortresponse_control( ld, ctrl, &err, &attr );
2046 if ( rc == LDAP_SUCCESS ) {
2048 rc = snprintf( buf, sizeof(buf), "(%d) %s%s%s",
2049 err, ldap_err2string(err), attr ? " " : "", attr ? attr : "" );
2051 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
2052 ldif ? "sortResult: " : "sortResult", buf, rc );
2059 print_vlv( LDAP *ld, LDAPControl *ctrl )
2065 rc = ldap_parse_vlvresponse_control( ld, ctrl, &vlvPos, &vlvCount,
2066 &vlvContext, &err );
2067 if ( rc == LDAP_SUCCESS ) {
2070 if ( vlvContext && vlvContext->bv_len > 0 ) {
2071 bv.bv_len = LUTIL_BASE64_ENCODE_LEN(
2072 vlvContext->bv_len ) + 1;
2073 bv.bv_val = ber_memalloc( bv.bv_len + 1 );
2075 bv.bv_len = lutil_b64_ntop(
2076 (unsigned char *) vlvContext->bv_val,
2078 bv.bv_val, bv.bv_len );
2084 rc = snprintf( buf, sizeof(buf), "pos=%d count=%d context=%s (%d) %s",
2085 vlvPos, vlvCount, bv.bv_val,
2086 err, ldap_err2string(err));
2089 ber_memfree( bv.bv_val );
2091 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
2092 ldif ? "vlvResult" : "vlvResult", buf, rc );
2098 #ifdef LDAP_CONTROL_X_DEREF
2100 print_deref( LDAP *ld, LDAPControl *ctrl )
2102 LDAPDerefRes *drhead = NULL, *dr;
2105 rc = ldap_parse_derefresponse_control( ld, ctrl, &drhead );
2106 if ( rc != LDAP_SUCCESS ) {
2110 for ( dr = drhead; dr != NULL; dr = dr->next ) {
2115 len = strlen( dr->derefAttr ) + STRLENOF(": ");
2117 for ( dv = dr->attrVals; dv != NULL; dv = dv->next ) {
2118 if ( dv->vals != NULL ) {
2120 ber_len_t tlen = strlen(dv->type);
2122 for ( j = 0; dv->vals[ j ].bv_val != NULL; j++ ) {
2123 len += STRLENOF("<:=>;") + tlen + 4*((dv->vals[ j ].bv_len - 1)/3 + 1);
2127 len += dr->derefVal.bv_len + STRLENOF("\n");
2128 buf = ldap_memalloc( len + 1 );
2129 if ( buf == NULL ) {
2130 rc = LDAP_NO_MEMORY;
2135 ptr = lutil_strcopy( ptr, dr->derefAttr );
2138 for ( dv = dr->attrVals; dv != NULL; dv = dv->next ) {
2139 if ( dv->vals != NULL ) {
2141 for ( j = 0; dv->vals[ j ].bv_val != NULL; j++ ) {
2142 int k = ldif_is_not_printable( dv->vals[ j ].bv_val, dv->vals[ j ].bv_len );
2145 ptr = lutil_strcopy( ptr, dv->type );
2152 (unsigned char *) dv->vals[ j ].bv_val,
2153 dv->vals[ j ].bv_len,
2154 ptr, buf + len - ptr );
2159 ptr = lutil_memcopy( ptr, dv->vals[ j ].bv_val, dv->vals[ j ].bv_len );
2166 ptr = lutil_strncopy( ptr, dr->derefVal.bv_val, dr->derefVal.bv_len );
2169 assert( ptr <= buf + len );
2171 tool_write_ldif( LDIF_PUT_COMMENT, NULL, buf, ptr - buf);
2173 ldap_memfree( buf );
2179 ldap_derefresponse_free( drhead );
2185 #ifdef LDAP_CONTROL_X_WHATFAILED
2187 print_whatfailed( LDAP *ld, LDAPControl *ctrl )
2192 BerVarray bva = NULL;
2194 /* Create a BerElement from the berval returned in the control. */
2195 ber = ber_init( &ctrl->ldctl_value );
2197 if ( ber == NULL ) {
2198 return LDAP_NO_MEMORY;
2201 siz = sizeof(struct berval);
2202 tag = ber_scanf( ber, "[M]", &bva, &siz, 0 );
2203 if ( tag != LBER_ERROR ) {
2206 tool_write_ldif( LDIF_PUT_COMMENT, " what failed:", NULL, 0 );
2208 for ( i = 0; bva[i].bv_val != NULL; i++ ) {
2209 tool_write_ldif( LDIF_PUT_COMMENT, NULL, bva[i].bv_val, bva[i].bv_len );
2212 ldap_memfree( bva );
2222 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
2224 print_ppolicy( LDAP *ld, LDAPControl *ctrl )
2226 int expire = 0, grace = 0, rc;
2227 LDAPPasswordPolicyError pperr;
2229 rc = ldap_parse_passwordpolicy_control( ld, ctrl,
2230 &expire, &grace, &pperr );
2231 if ( rc == LDAP_SUCCESS ) {
2232 char buf[ BUFSIZ ], *ptr = buf;
2234 if ( expire != -1 ) {
2235 ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
2236 "expire=%d", expire );
2239 if ( grace != -1 ) {
2240 ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
2241 "%sgrace=%d", ptr == buf ? "" : " ", grace );
2244 if ( pperr != PP_noError ) {
2245 ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
2246 "%serror=%d (%s)", ptr == buf ? "" : " ",
2248 ldap_passwordpolicy_err2txt( pperr ) );
2251 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
2252 ldif ? "ppolicy: " : "ppolicy", buf, ptr - buf );
2259 void tool_print_ctrls(
2261 LDAPControl **ctrls )
2266 for ( i = 0; ctrls[i] != NULL; i++ ) {
2267 /* control: OID criticality base64value */
2268 struct berval b64 = BER_BVNULL;
2273 /* FIXME: there might be cases where a control has NULL OID;
2274 * this makes little sense, especially when returned by the
2275 * server, but libldap happily allows it */
2276 if ( ctrls[i]->ldctl_oid == NULL ) {
2281 len += strlen( ctrls[i]->ldctl_oid );
2283 /* add enough for space after OID and the critical value itself */
2284 len += ctrls[i]->ldctl_iscritical
2285 ? sizeof("true") : sizeof("false");
2287 /* convert to base64 */
2288 if ( !BER_BVISNULL( &ctrls[i]->ldctl_value ) ) {
2289 b64.bv_len = LUTIL_BASE64_ENCODE_LEN(
2290 ctrls[i]->ldctl_value.bv_len ) + 1;
2291 b64.bv_val = ber_memalloc( b64.bv_len + 1 );
2293 b64.bv_len = lutil_b64_ntop(
2294 (unsigned char *) ctrls[i]->ldctl_value.bv_val,
2295 ctrls[i]->ldctl_value.bv_len,
2296 b64.bv_val, b64.bv_len );
2300 len += 1 + b64.bv_len;
2303 ptr = str = malloc( len + 1 );
2305 ptr = lutil_strcopy( ptr, ": " );
2307 ptr = lutil_strcopy( ptr, ctrls[i]->ldctl_oid );
2308 ptr = lutil_strcopy( ptr, ctrls[i]->ldctl_iscritical
2309 ? " true" : " false" );
2312 ptr = lutil_strcopy( ptr, " " );
2313 ptr = lutil_strcopy( ptr, b64.bv_val );
2317 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
2318 "control", str, len );
2323 ber_memfree( b64.bv_val );
2326 /* known controls */
2327 for ( j = 0; tool_ctrl_response[j].oid != NULL; j++ ) {
2328 if ( strcmp( tool_ctrl_response[j].oid, ctrls[i]->ldctl_oid ) == 0 ) {
2329 if ( !tool_ctrl_response[j].mask & tool_type ) {
2330 /* this control should not appear
2331 * with this tool; warning? */
2337 if ( tool_ctrl_response[j].oid != NULL && tool_ctrl_response[j].func ) {
2338 (void)tool_ctrl_response[j].func( ld, ctrls[i] );
2344 tool_write_ldif( int type, char *name, char *value, ber_len_t vallen )
2348 if (( ldif = ldif_put_wrap( type, name, value, vallen, ldif_wrap )) == NULL ) {
2352 fputs( ldif, stdout );
2353 ber_memfree( ldif );
2359 tool_is_oid( const char *s )
2363 if ( !isdigit( (unsigned char) s[ 0 ] ) ) {
2367 for ( ; s[ 0 ]; s++ ) {
2368 if ( s[ 0 ] == '.' ) {
2369 if ( s[ 1 ] == '\0' ) {
2376 if ( !isdigit( (unsigned char) s[ 0 ] ) ) {
2380 if ( first == 1 && s[ 0 ] == '0' && s[ 1 ] != '.' ) {