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 */
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 #ifdef HAVE_CYRUS_SASL
246 ldap_pvt_tls_destroy();
249 if ( ldapuri != NULL ) {
250 ber_memfree( ldapuri );
254 if ( pr_cookie.bv_val != NULL ) {
255 ber_memfree( pr_cookie.bv_val );
256 pr_cookie.bv_val = NULL;
257 pr_cookie.bv_len = 0;
260 if ( binddn != NULL ) {
261 ber_memfree( binddn );
265 if ( passwd.bv_val != NULL ) {
266 ber_memfree( passwd.bv_val );
272 tool_common_usage( void )
274 static const char *const descriptions[] = {
275 N_(" -d level set LDAP debugging level to `level'\n"),
276 N_(" -D binddn bind DN\n"),
277 N_(" -e [!]<ext>[=<extparam>] general extensions (! indicates criticality)\n")
278 N_(" [!]assert=<filter> (RFC 4528; a RFC 4515 Filter string)\n")
279 N_(" [!]authzid=<authzid> (RFC 4370; \"dn:<dn>\" or \"u:<user>\")\n")
280 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
282 /* non-advertized support for proxyDN */
283 N_(" [!]proxydn=<dn> (a RFC 4514 DN string)\n")
286 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
287 N_(" [!]chaining[=<resolveBehavior>[/<continuationBehavior>]]\n")
288 N_(" one of \"chainingPreferred\", \"chainingRequired\",\n")
289 N_(" \"referralsPreferred\", \"referralsRequired\"\n")
290 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
291 N_(" [!]manageDSAit (RFC 3296)\n")
293 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
296 N_(" [!]postread[=<attrs>] (RFC 4527; comma-separated attr list)\n")
297 N_(" [!]preread[=<attrs>] (RFC 4527; comma-separated attr list)\n")
299 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
300 N_(" [!]sessiontracking\n")
301 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
302 N_(" abandon, cancel, ignore (SIGINT sends abandon/cancel,\n"
303 " or ignores response; if critical, doesn't wait for SIGINT.\n"
304 " not really controls)\n")
305 N_(" -h host LDAP server\n"),
306 N_(" -H URI LDAP Uniform Resource Identifier(s)\n"),
307 N_(" -I use SASL Interactive mode\n"),
308 N_(" -n show what would be done but don't actually do it\n"),
309 N_(" -N do not use reverse DNS to canonicalize SASL host name\n"),
310 N_(" -O props SASL security properties\n"),
311 N_(" -o <opt>[=<optparam] general options\n"),
312 N_(" nettimeout=<timeout> (in seconds, or \"none\" or \"max\")\n"),
313 N_(" -p port port on LDAP server\n"),
314 N_(" -Q use SASL Quiet mode\n"),
315 N_(" -R realm SASL realm\n"),
316 N_(" -U authcid SASL authentication identity\n"),
317 N_(" -v run in verbose mode (diagnostics to standard output)\n"),
318 N_(" -V print version info (-VV only)\n"),
319 N_(" -w passwd bind password (for simple authentication)\n"),
320 N_(" -W prompt for bind password\n"),
321 N_(" -x Simple authentication\n"),
322 N_(" -X authzid SASL authorization identity (\"dn:<dn>\" or \"u:<user>\")\n"),
323 N_(" -y file Read password from file\n"),
324 N_(" -Y mech SASL mechanism\n"),
325 N_(" -Z Start TLS request (-ZZ to require successful response)\n"),
328 const char *const *cpp;
330 fputs( _("Common options:\n"), stderr );
331 for( cpp = descriptions; *cpp != NULL; cpp++ ) {
332 if( strchr( options, (*cpp)[3] ) || (*cpp)[3] == ' ' ) {
333 fputs( _(*cpp), stderr );
346 fprintf( stderr, "%s: %s (%d)%s\n",
347 func, ldap_err2string( err ), err, extra ? extra : "" );
349 if ( matched && *matched ) {
350 fprintf( stderr, _("\tmatched DN: %s\n"), matched );
353 if ( info && *info ) {
354 fprintf( stderr, _("\tadditional info: %s\n"), info );
357 if ( refs && *refs ) {
359 fprintf( stderr, _("\treferrals:\n") );
360 for( i=0; refs[i]; i++ ) {
361 fprintf( stderr, "\t\t%s\n", refs[i] );
368 tool_args( int argc, char **argv )
372 while (( i = getopt( argc, argv, options )) != EOF ) {
374 char *control, *cvalue, *next;
376 case 'c': /* continuous operation mode */
383 ival = strtol( optarg, &next, 10 );
384 if (next == NULL || next[0] != '\0') {
385 fprintf( stderr, "%s: unable to parse debug value \"%s\"\n", prog, optarg);
390 case 'D': /* bind DN */
391 if( binddn != NULL ) {
392 fprintf( stderr, "%s: -D previously specified\n", prog );
393 exit( EXIT_FAILURE );
395 binddn = ber_strdup( optarg );
397 case 'e': /* general extensions (controls and such) */
398 /* should be extended to support comma separated list of
399 * [!]key[=value] parameters, e.g. -e !foo,bar=567
404 while ( optarg[0] == '!' ) {
409 control = ber_strdup( optarg );
410 if ( (cvalue = strchr( control, '=' )) != NULL ) {
414 if ( strcasecmp( control, "assert" ) == 0 ) {
416 fprintf( stderr, "assert control previously specified\n");
417 exit( EXIT_FAILURE );
419 if( cvalue == NULL ) {
420 fprintf( stderr, "assert: control value expected\n" );
424 assertctl = 1 + crit;
426 assert( assertion == NULL );
429 } else if ( strcasecmp( control, "authzid" ) == 0 ) {
430 if( authzid != NULL ) {
431 fprintf( stderr, "authzid control previously specified\n");
432 exit( EXIT_FAILURE );
434 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
435 if( proxydn != NULL ) {
436 fprintf( stderr, "authzid control incompatible with proxydn\n");
437 exit( EXIT_FAILURE );
439 #endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
440 if( cvalue == NULL ) {
441 fprintf( stderr, "authzid: control value expected\n" );
445 fprintf( stderr, "authzid: must be marked critical\n" );
447 } else if ( crit > 1 ) {
448 /* purposely flag proxied authorization
449 * as non-critical, to test DSA */
453 assert( authzid == NULL );
456 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
457 } else if ( strcasecmp( control, "proxydn" ) == 0 ) {
458 if( proxydn != NULL ) {
459 fprintf( stderr, "proxydn control previously specified\n");
460 exit( EXIT_FAILURE );
462 if( authzid != NULL ) {
463 fprintf( stderr, "proxydn control incompatible with authzid\n");
464 exit( EXIT_FAILURE );
466 if( cvalue == NULL ) {
467 fprintf( stderr, "proxydn: control value expected\n" );
471 fprintf( stderr, "proxydn: must be marked critical\n" );
473 } else if ( crit > 1 ) {
474 /* purposely flag proxied authorization
475 * as non-critical, to test DSA */
479 assert( proxydn == NULL );
481 #endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
483 } else if ( ( strcasecmp( control, "relax" ) == 0 ) ||
484 ( strcasecmp( control, "manageDIT" ) == 0 ) )
488 "relax control previously specified\n");
489 exit( EXIT_FAILURE );
491 if( cvalue != NULL ) {
493 "relax: no control value expected\n" );
497 manageDIT = 1 + crit;
499 } else if ( strcasecmp( control, "manageDSAit" ) == 0 ) {
502 "manageDSAit control previously specified\n");
503 exit( EXIT_FAILURE );
505 if( cvalue != NULL ) {
507 "manageDSAit: no control value expected\n" );
511 manageDSAit = 1 + crit;
513 } else if ( strcasecmp( control, "noop" ) == 0 ) {
515 fprintf( stderr, "noop control previously specified\n");
516 exit( EXIT_FAILURE );
518 if( cvalue != NULL ) {
519 fprintf( stderr, "noop: no control value expected\n" );
525 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
526 } else if ( strcasecmp( control, "ppolicy" ) == 0 ) {
528 fprintf( stderr, "ppolicy control previously specified\n");
529 exit( EXIT_FAILURE );
531 if( cvalue != NULL ) {
532 fprintf( stderr, "ppolicy: no control value expected\n" );
536 fprintf( stderr, "ppolicy: critical flag not allowed\n" );
543 } else if ( strcasecmp( control, "preread" ) == 0 ) {
545 fprintf( stderr, "preread control previously specified\n");
546 exit( EXIT_FAILURE );
550 preread_attrs = cvalue;
552 } else if ( strcasecmp( control, "postread" ) == 0 ) {
554 fprintf( stderr, "postread control previously specified\n");
555 exit( EXIT_FAILURE );
559 postread_attrs = cvalue;
561 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
562 } else if ( strcasecmp( control, "chaining" ) == 0 ) {
564 fprintf( stderr, "chaining control previously specified\n");
565 exit( EXIT_FAILURE );
570 if ( cvalue != NULL ) {
573 continuation = strchr( cvalue, '/' );
574 if ( continuation ) {
575 /* FIXME: this makes sense only in searches */
576 *continuation++ = '\0';
577 if ( strcasecmp( continuation, "chainingPreferred" ) == 0 ) {
578 chainingContinuation = LDAP_CHAINING_PREFERRED;
579 } else if ( strcasecmp( continuation, "chainingRequired" ) == 0 ) {
580 chainingContinuation = LDAP_CHAINING_REQUIRED;
581 } else if ( strcasecmp( continuation, "referralsPreferred" ) == 0 ) {
582 chainingContinuation = LDAP_REFERRALS_PREFERRED;
583 } else if ( strcasecmp( continuation, "referralsRequired" ) == 0 ) {
584 chainingContinuation = LDAP_REFERRALS_REQUIRED;
587 "chaining behavior control "
588 "continuation value \"%s\" invalid\n",
590 exit( EXIT_FAILURE );
594 if ( strcasecmp( cvalue, "chainingPreferred" ) == 0 ) {
595 chainingResolve = LDAP_CHAINING_PREFERRED;
596 } else if ( strcasecmp( cvalue, "chainingRequired" ) == 0 ) {
597 chainingResolve = LDAP_CHAINING_REQUIRED;
598 } else if ( strcasecmp( cvalue, "referralsPreferred" ) == 0 ) {
599 chainingResolve = LDAP_REFERRALS_PREFERRED;
600 } else if ( strcasecmp( cvalue, "referralsRequired" ) == 0 ) {
601 chainingResolve = LDAP_REFERRALS_REQUIRED;
604 "chaining behavior control "
605 "resolve value \"%s\" invalid\n",
607 exit( EXIT_FAILURE );
610 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
612 /* this shouldn't go here, really; but it's a feature... */
613 } else if ( strcasecmp( control, "abandon" ) == 0 ) {
614 abcan = Intr_Abandon;
619 } else if ( strcasecmp( control, "cancel" ) == 0 ) {
625 } else if ( strcasecmp( control, "ignore" ) == 0 ) {
631 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
632 } else if ( strcasecmp( control, "sessiontracking" ) == 0 ) {
633 if ( sessionTracking ) {
634 fprintf( stderr, "%s: session tracking can be only specified once\n", prog );
635 exit( EXIT_FAILURE );
638 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
640 } else if ( tool_is_oid( control ) ) {
641 LDAPControl *tmpctrls, ctrl;
643 if ( unknown_ctrls != NULL ) {
645 for ( i = 0; unknown_ctrls[ i ].ldctl_oid != NULL; i++ ) {
646 if ( strcmp( control, unknown_ctrls[ i ].ldctl_oid ) == 0 ) {
647 fprintf( stderr, "%s control previously specified\n", control );
648 exit( EXIT_FAILURE );
653 tmpctrls = (LDAPControl *)ber_memrealloc( unknown_ctrls,
654 (unknown_ctrls_num + 1)*sizeof( LDAPControl ) );
655 if ( tmpctrls == NULL ) {
656 fprintf( stderr, "%s: no memory?\n", prog );
657 exit( EXIT_FAILURE );
659 unknown_ctrls = tmpctrls;
660 ctrl.ldctl_oid = control;
661 ctrl.ldctl_value.bv_val = NULL;
662 ctrl.ldctl_value.bv_len = 0;
663 ctrl.ldctl_iscritical = crit;
665 if ( cvalue != NULL ) {
667 size_t len = strlen( cvalue );
670 bv.bv_len = LUTIL_BASE64_DECODE_LEN( len );
671 bv.bv_val = ber_memalloc( bv.bv_len + 1 );
673 retcode = lutil_b64_pton( cvalue,
674 (unsigned char *)bv.bv_val,
677 if ( retcode == -1 || (unsigned) retcode > bv.bv_len ) {
678 fprintf( stderr, "Unable to parse value of general control %s\n",
684 ctrl.ldctl_value = bv;
687 unknown_ctrls[ unknown_ctrls_num ] = ctrl;
691 fprintf( stderr, "Invalid general control name: %s\n",
696 case 'f': /* read from file */
697 if( infile != NULL ) {
698 fprintf( stderr, "%s: -f previously specified\n", prog );
699 exit( EXIT_FAILURE );
701 infile = ber_strdup( optarg );
703 case 'h': /* ldap host */
704 if( ldaphost != NULL ) {
705 fprintf( stderr, "%s: -h previously specified\n", prog );
706 exit( EXIT_FAILURE );
708 ldaphost = ber_strdup( optarg );
710 case 'H': /* ldap URI */
711 if( ldapuri != NULL ) {
712 fprintf( stderr, "%s: -H previously specified\n", prog );
713 exit( EXIT_FAILURE );
715 ldapuri = ber_strdup( optarg );
718 #ifdef HAVE_CYRUS_SASL
719 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
720 fprintf( stderr, "%s: incompatible previous "
721 "authentication choice\n",
723 exit( EXIT_FAILURE );
725 authmethod = LDAP_AUTH_SASL;
726 sasl_flags = LDAP_SASL_INTERACTIVE;
729 fprintf( stderr, "%s: was not compiled with SASL support\n",
731 exit( EXIT_FAILURE );
734 /* enable Manage DSA IT */
737 case 'n': /* print operations, don't actually do them */
744 control = ber_strdup( optarg );
745 if ( (cvalue = strchr( control, '=' )) != NULL ) {
749 if ( strcasecmp( control, "nettimeout" ) == 0 ) {
750 if( nettimeout.tv_sec != -1 ) {
751 fprintf( stderr, "nettimeout option previously specified\n");
752 exit( EXIT_FAILURE );
754 if( cvalue == NULL || cvalue[0] == '\0' ) {
755 fprintf( stderr, "nettimeout: option value expected\n" );
758 if ( strcasecmp( cvalue, "none" ) == 0 ) {
759 nettimeout.tv_sec = 0;
760 } else if ( strcasecmp( cvalue, "max" ) == 0 ) {
761 nettimeout.tv_sec = LDAP_MAXINT;
763 ival = strtol( cvalue, &next, 10 );
764 if ( next == NULL || next[0] != '\0' ) {
766 _("Unable to parse network timeout \"%s\"\n"), cvalue );
767 exit( EXIT_FAILURE );
769 nettimeout.tv_sec = ival;
771 if( nettimeout.tv_sec < 0 || nettimeout.tv_sec > LDAP_MAXINT ) {
772 fprintf( stderr, _("%s: invalid network timeout (%ld) specified\n"),
773 prog, (long)nettimeout.tv_sec );
774 exit( EXIT_FAILURE );
777 fprintf( stderr, "Invalid general option name: %s\n",
783 #ifdef HAVE_CYRUS_SASL
784 if( sasl_secprops != NULL ) {
785 fprintf( stderr, "%s: -O previously specified\n", prog );
786 exit( EXIT_FAILURE );
788 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
789 fprintf( stderr, "%s: incompatible previous "
790 "authentication choice\n", prog );
791 exit( EXIT_FAILURE );
793 authmethod = LDAP_AUTH_SASL;
794 sasl_secprops = ber_strdup( optarg );
796 fprintf( stderr, "%s: not compiled with SASL support\n", prog );
797 exit( EXIT_FAILURE );
802 fprintf( stderr, "%s: -p previously specified\n", prog );
803 exit( EXIT_FAILURE );
805 ival = strtol( optarg, &next, 10 );
806 if ( next == NULL || next[0] != '\0' ) {
807 fprintf( stderr, "%s: unable to parse port number \"%s\"\n", prog, optarg );
808 exit( EXIT_FAILURE );
813 ival = strtol( optarg, &next, 10 );
814 if ( next == NULL || next[0] != '\0' ) {
815 fprintf( stderr, "%s: unable to parse protocol version \"%s\"\n", prog, optarg );
816 exit( EXIT_FAILURE );
820 if( protocol == LDAP_VERSION3 ) {
821 fprintf( stderr, "%s: -P 2 incompatible with version %d\n",
823 exit( EXIT_FAILURE );
825 protocol = LDAP_VERSION2;
828 if( protocol == LDAP_VERSION2 ) {
829 fprintf( stderr, "%s: -P 2 incompatible with version %d\n",
831 exit( EXIT_FAILURE );
833 protocol = LDAP_VERSION3;
836 fprintf( stderr, "%s: protocol version should be 2 or 3\n",
842 #ifdef HAVE_CYRUS_SASL
843 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
844 fprintf( stderr, "%s: incompatible previous "
845 "authentication choice\n",
847 exit( EXIT_FAILURE );
849 authmethod = LDAP_AUTH_SASL;
850 sasl_flags = LDAP_SASL_QUIET;
853 fprintf( stderr, "%s: not compiled with SASL support\n",
855 exit( EXIT_FAILURE );
858 #ifdef HAVE_CYRUS_SASL
859 if( sasl_realm != NULL ) {
860 fprintf( stderr, "%s: -R previously specified\n", prog );
861 exit( EXIT_FAILURE );
863 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
864 fprintf( stderr, "%s: incompatible previous "
865 "authentication choice\n",
867 exit( EXIT_FAILURE );
869 authmethod = LDAP_AUTH_SASL;
870 sasl_realm = ber_strdup( optarg );
872 fprintf( stderr, "%s: not compiled with SASL support\n",
874 exit( EXIT_FAILURE );
878 #ifdef HAVE_CYRUS_SASL
879 if( sasl_authc_id != NULL ) {
880 fprintf( stderr, "%s: -U previously specified\n", prog );
881 exit( EXIT_FAILURE );
883 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
884 fprintf( stderr, "%s: incompatible previous "
885 "authentication choice\n",
887 exit( EXIT_FAILURE );
889 authmethod = LDAP_AUTH_SASL;
890 sasl_authc_id = ber_strdup( optarg );
892 fprintf( stderr, "%s: not compiled with SASL support\n",
894 exit( EXIT_FAILURE );
897 case 'v': /* verbose mode */
900 case 'V': /* version */
903 case 'w': /* password */
904 passwd.bv_val = ber_strdup( optarg );
908 for( p = optarg; *p != '\0'; p++ ) {
912 passwd.bv_len = strlen( passwd.bv_val );
921 #ifdef HAVE_CYRUS_SASL
922 if( sasl_mech != NULL ) {
923 fprintf( stderr, "%s: -Y previously specified\n", prog );
924 exit( EXIT_FAILURE );
926 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
928 "%s: incompatible with authentication choice\n", prog );
929 exit( EXIT_FAILURE );
931 authmethod = LDAP_AUTH_SASL;
932 sasl_mech = ber_strdup( optarg );
934 fprintf( stderr, "%s: not compiled with SASL support\n", prog );
935 exit( EXIT_FAILURE );
939 if( authmethod != -1 && authmethod != LDAP_AUTH_SIMPLE ) {
940 fprintf( stderr, "%s: incompatible with previous "
941 "authentication choice\n", prog );
942 exit( EXIT_FAILURE );
944 authmethod = LDAP_AUTH_SIMPLE;
947 #ifdef HAVE_CYRUS_SASL
948 if( sasl_authz_id != NULL ) {
949 fprintf( stderr, "%s: -X previously specified\n", prog );
950 exit( EXIT_FAILURE );
952 if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
953 fprintf( stderr, "%s: -X incompatible with "
954 "authentication choice\n", prog );
955 exit( EXIT_FAILURE );
957 authmethod = LDAP_AUTH_SASL;
958 sasl_authz_id = ber_strdup( optarg );
960 fprintf( stderr, "%s: not compiled with SASL support\n", prog );
961 exit( EXIT_FAILURE );
968 fprintf( stderr, "%s: not compiled with TLS support\n", prog );
969 exit( EXIT_FAILURE );
973 if( handle_private_option( i ) ) break;
974 fprintf( stderr, "%s: unrecognized option -%c\n",
981 /* prevent bad linking */
983 api.ldapai_info_version = LDAP_API_INFO_VERSION;
985 if ( ldap_get_option(NULL, LDAP_OPT_API_INFO, &api)
986 != LDAP_OPT_SUCCESS )
988 fprintf( stderr, "%s: ldap_get_option(API_INFO) failed\n", prog );
989 exit( EXIT_FAILURE );
992 if (api.ldapai_info_version != LDAP_API_INFO_VERSION) {
993 fprintf( stderr, "LDAP APIInfo version mismatch: "
994 "library %d, header %d\n",
995 api.ldapai_info_version, LDAP_API_INFO_VERSION );
996 exit( EXIT_FAILURE );
999 if( api.ldapai_api_version != LDAP_API_VERSION ) {
1000 fprintf( stderr, "LDAP API version mismatch: "
1001 "library %d, header %d\n",
1002 api.ldapai_api_version, LDAP_API_VERSION );
1003 exit( EXIT_FAILURE );
1006 if( strcmp(api.ldapai_vendor_name, LDAP_VENDOR_NAME ) != 0 ) {
1007 fprintf( stderr, "LDAP vendor name mismatch: "
1008 "library %s, header %s\n",
1009 api.ldapai_vendor_name, LDAP_VENDOR_NAME );
1010 exit( EXIT_FAILURE );
1013 if( api.ldapai_vendor_version != LDAP_VENDOR_VERSION ) {
1014 fprintf( stderr, "LDAP vendor version mismatch: "
1015 "library %d, header %d\n",
1016 api.ldapai_vendor_version, LDAP_VENDOR_VERSION );
1017 exit( EXIT_FAILURE );
1021 fprintf( stderr, "%s: %s\t(LDAP library: %s %d)\n",
1023 LDAP_VENDOR_NAME, LDAP_VENDOR_VERSION );
1024 if (version > 1) exit( EXIT_SUCCESS );
1027 ldap_memfree( api.ldapai_vendor_name );
1028 ber_memvfree( (void **)api.ldapai_extensions );
1032 protocol = LDAP_VERSION3;
1034 if (authmethod == -1 && protocol > LDAP_VERSION2) {
1035 #ifdef HAVE_CYRUS_SASL
1036 if ( binddn != NULL ) {
1037 authmethod = LDAP_AUTH_SIMPLE;
1039 authmethod = LDAP_AUTH_SASL;
1042 authmethod = LDAP_AUTH_SIMPLE;
1046 if( ldapuri == NULL ) {
1047 if( ldapport && ( ldaphost == NULL )) {
1048 fprintf( stderr, "%s: -p without -h is invalid.\n", prog );
1049 exit( EXIT_FAILURE );
1052 if( ldaphost != NULL ) {
1053 fprintf( stderr, "%s: -H incompatible with -h\n", prog );
1054 exit( EXIT_FAILURE );
1057 fprintf( stderr, "%s: -H incompatible with -p\n", prog );
1058 exit( EXIT_FAILURE );
1062 if( protocol == LDAP_VERSION2 ) {
1063 if( assertctl || authzid || manageDIT || manageDSAit ||
1064 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
1066 #endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
1067 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
1070 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
1072 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
1073 noop || ppolicy || preread || postread )
1075 fprintf( stderr, "%s: -e/-M incompatible with LDAPv2\n", prog );
1076 exit( EXIT_FAILURE );
1080 fprintf( stderr, "%s: -Z incompatible with LDAPv2\n", prog );
1081 exit( EXIT_FAILURE );
1084 #ifdef HAVE_CYRUS_SASL
1085 if( authmethod == LDAP_AUTH_SASL ) {
1086 fprintf( stderr, "%s: -[IOQRUXY] incompatible with LDAPv2\n",
1088 exit( EXIT_FAILURE );
1096 tool_conn_setup( int dont, void (*private_setup)( LDAP * ) )
1101 if( ber_set_option( NULL, LBER_OPT_DEBUG_LEVEL, &debug )
1102 != LBER_OPT_SUCCESS )
1105 "Could not set LBER_OPT_DEBUG_LEVEL %d\n", debug );
1107 if( ldap_set_option( NULL, LDAP_OPT_DEBUG_LEVEL, &debug )
1108 != LDAP_OPT_SUCCESS )
1111 "Could not set LDAP_OPT_DEBUG_LEVEL %d\n", debug );
1116 (void) SIGNAL( SIGPIPE, SIG_IGN );
1120 SIGNAL( SIGINT, do_sig );
1126 if( ( ldaphost != NULL || ldapport ) && ( ldapuri == NULL ) ) {
1129 memset( &url, 0, sizeof(url));
1131 url.lud_scheme = "ldap";
1132 url.lud_host = ldaphost;
1133 url.lud_port = ldapport;
1134 url.lud_scope = LDAP_SCOPE_DEFAULT;
1136 ldapuri = ldap_url_desc2str( &url );
1138 } else if ( ldapuri != NULL ) {
1139 LDAPURLDesc *ludlist, **ludp;
1143 rc = ldap_url_parselist( &ludlist, ldapuri );
1144 if ( rc != LDAP_URL_SUCCESS ) {
1146 "Could not parse LDAP URI(s)=%s (%d)\n",
1148 exit( EXIT_FAILURE );
1151 for ( ludp = &ludlist; *ludp != NULL; ) {
1152 LDAPURLDesc *lud = *ludp;
1155 if ( lud->lud_dn != NULL && lud->lud_dn[ 0 ] != '\0' &&
1156 ( lud->lud_host == NULL || lud->lud_host[0] == '\0' ) )
1158 /* if no host but a DN is provided,
1159 * use DNS SRV to gather the host list
1160 * and turn it into a list of URIs
1161 * using the scheme provided */
1162 char *domain = NULL,
1166 len_proto = strlen( lud->lud_scheme );
1168 if ( ldap_dn2domain( lud->lud_dn, &domain )
1172 "DNS SRV: Could not turn "
1173 "DN=\"%s\" into a domain\n",
1178 rc = ldap_domain2hostlist( domain, &hostlist );
1181 "DNS SRV: Could not turn "
1182 "domain=%s into a hostlist\n",
1187 hosts = ldap_str2charray( hostlist, " " );
1188 if ( hosts == NULL ) {
1190 "DNS SRV: Could not parse "
1191 "hostlist=\"%s\"\n",
1196 for ( i = 0; hosts[ i ] != NULL; i++ )
1199 tmp = (char **)ber_memrealloc( urls, sizeof( char * ) * ( nurls + i + 1 ) );
1200 if ( tmp == NULL ) {
1202 "DNS SRV: out of memory?\n" );
1206 urls[ nurls ] = NULL;
1208 for ( i = 0; hosts[ i ] != NULL; i++ ) {
1209 size_t len = len_proto
1211 + strlen( hosts[ i ] )
1214 urls[ nurls + i + 1 ] = NULL;
1215 urls[ nurls + i ] = (char *)malloc( sizeof( char ) * len );
1216 if ( urls[ nurls + i ] == NULL ) {
1218 "DNS SRV: out of memory?\n" );
1222 snprintf( urls[ nurls + i ], len, "%s://%s",
1223 lud->lud_scheme, hosts[ i ] );
1228 ber_memvfree( (void **)hosts );
1229 ber_memfree( hostlist );
1230 ber_memfree( domain );
1233 tmp = (char **)ber_memrealloc( urls, sizeof( char * ) * ( nurls + 2 ) );
1234 if ( tmp == NULL ) {
1236 "DNS SRV: out of memory?\n" );
1240 urls[ nurls + 1 ] = NULL;
1242 urls[ nurls ] = ldap_url_desc2str( lud );
1243 if ( urls[ nurls ] == NULL ) {
1245 "DNS SRV: out of memory?\n" );
1251 *ludp = lud->lud_next;
1253 lud->lud_next = NULL;
1254 ldap_free_urldesc( lud );
1257 if ( ludlist != NULL ) {
1258 ldap_free_urllist( ludlist );
1259 exit( EXIT_FAILURE );
1261 } else if ( urls == NULL ) {
1262 exit( EXIT_FAILURE );
1265 ldap_memfree( ldapuri );
1266 ldapuri = ldap_charray2str( urls, " " );
1267 ber_memvfree( (void **)urls );
1271 fprintf( stderr, "ldap_initialize( %s )\n",
1272 ldapuri != NULL ? ldapuri : "<DEFAULT>" );
1274 rc = ldap_initialize( &ld, ldapuri );
1275 if( rc != LDAP_SUCCESS ) {
1277 "Could not create LDAP session handle for URI=%s (%d): %s\n",
1278 ldapuri, rc, ldap_err2string(rc) );
1279 exit( EXIT_FAILURE );
1282 if( private_setup ) private_setup( ld );
1285 if( ldap_set_option( ld, LDAP_OPT_REFERRALS,
1286 referrals ? LDAP_OPT_ON : LDAP_OPT_OFF ) != LDAP_OPT_SUCCESS )
1288 fprintf( stderr, "Could not set LDAP_OPT_REFERRALS %s\n",
1289 referrals ? "on" : "off" );
1290 exit( EXIT_FAILURE );
1293 #ifdef HAVE_CYRUS_SASL
1295 if( ldap_set_option( ld, LDAP_OPT_X_SASL_NOCANON,
1296 nocanon ? LDAP_OPT_ON : LDAP_OPT_OFF ) != LDAP_OPT_SUCCESS )
1298 fprintf( stderr, "Could not set LDAP_OPT_X_SASL_NOCANON %s\n",
1299 nocanon ? "on" : "off" );
1300 exit( EXIT_FAILURE );
1303 if( ldap_set_option( ld, LDAP_OPT_PROTOCOL_VERSION, &protocol )
1304 != LDAP_OPT_SUCCESS )
1306 fprintf( stderr, "Could not set LDAP_OPT_PROTOCOL_VERSION %d\n",
1308 exit( EXIT_FAILURE );
1312 rc = ldap_start_tls_s( ld, NULL, NULL );
1313 if ( rc != LDAP_SUCCESS ) {
1315 ldap_get_option( ld, LDAP_OPT_DIAGNOSTIC_MESSAGE, (void*)&msg);
1316 tool_perror( "ldap_start_tls", rc, NULL, NULL, msg, NULL );
1318 if ( use_tls > 1 ) {
1319 exit( EXIT_FAILURE );
1324 if ( nettimeout.tv_sec > 0 ) {
1325 if ( ldap_set_option( ld, LDAP_OPT_NETWORK_TIMEOUT, (void *) &nettimeout )
1326 != LDAP_OPT_SUCCESS )
1328 fprintf( stderr, "Could not set LDAP_OPT_NETWORK_TIMEOUT %ld\n",
1329 (long)nettimeout.tv_sec );
1330 exit( EXIT_FAILURE );
1340 tool_bind( LDAP *ld )
1342 LDAPControl **sctrlsp = NULL;
1343 LDAPControl *sctrls[3];
1344 LDAPControl sctrl[3];
1347 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
1350 c.ldctl_oid = LDAP_CONTROL_PASSWORDPOLICYREQUEST;
1351 c.ldctl_value.bv_val = NULL;
1352 c.ldctl_value.bv_len = 0;
1353 c.ldctl_iscritical = 0;
1355 sctrls[nsctrls] = &sctrl[nsctrls];
1356 sctrls[++nsctrls] = NULL;
1360 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
1361 if ( sessionTracking ) {
1364 if (stValue.bv_val == NULL && st_value( ld, &stValue ) ) {
1365 exit( EXIT_FAILURE );
1368 c.ldctl_oid = LDAP_CONTROL_X_SESSION_TRACKING;
1369 c.ldctl_iscritical = 0;
1370 ber_dupbv( &c.ldctl_value, &stValue );
1373 sctrls[nsctrls] = &sctrl[nsctrls];
1374 sctrls[++nsctrls] = NULL;
1376 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
1382 assert( nsctrls < (int) (sizeof(sctrls)/sizeof(sctrls[0])) );
1384 if ( authmethod == LDAP_AUTH_SASL ) {
1385 #ifdef HAVE_CYRUS_SASL
1389 if( sasl_secprops != NULL ) {
1390 rc = ldap_set_option( ld, LDAP_OPT_X_SASL_SECPROPS,
1391 (void *) sasl_secprops );
1393 if( rc != LDAP_OPT_SUCCESS ) {
1395 "Could not set LDAP_OPT_X_SASL_SECPROPS: %s\n",
1397 exit( LDAP_LOCAL_ERROR );
1401 defaults = lutil_sasl_defaults( ld,
1408 rc = ldap_sasl_interactive_bind_s( ld, binddn, sasl_mech,
1410 NULL, sasl_flags, lutil_sasl_interact, defaults );
1412 lutil_sasl_freedefs( defaults );
1413 if( rc != LDAP_SUCCESS ) {
1415 ldap_get_option( ld, LDAP_OPT_DIAGNOSTIC_MESSAGE, (void*)&msg);
1416 tool_perror( "ldap_sasl_interactive_bind_s",
1417 rc, NULL, NULL, msg, NULL );
1422 fprintf( stderr, "%s: not compiled with SASL support\n", prog );
1423 exit( LDAP_NOT_SUPPORTED );
1427 LDAPMessage *result;
1428 LDAPControl **ctrls;
1430 char *matched = NULL;
1438 rc = ldap_sasl_bind( ld, binddn, LDAP_SASL_SIMPLE, &passwd,
1439 sctrlsp, NULL, &msgid );
1440 if ( msgid == -1 ) {
1441 tool_perror( "ldap_sasl_bind(SIMPLE)", rc,
1442 NULL, NULL, NULL, NULL );
1447 rc = ldap_result( ld, msgid, LDAP_MSG_ALL, NULL, &result );
1449 tool_perror( "ldap_result", -1, NULL, NULL, NULL, NULL );
1450 exit( LDAP_LOCAL_ERROR );
1454 tool_perror( "ldap_result", LDAP_TIMEOUT, NULL, NULL, NULL, NULL );
1455 exit( LDAP_LOCAL_ERROR );
1458 rc = ldap_parse_result( ld, result, &err, &matched, &info, &refs,
1460 if ( rc != LDAP_SUCCESS ) {
1461 tool_perror( "ldap_bind parse result", rc, NULL, matched, info, refs );
1462 exit( LDAP_LOCAL_ERROR );
1465 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
1466 if ( ctrls && ppolicy ) {
1468 int expire, grace, len = 0;
1469 LDAPPasswordPolicyError pErr = -1;
1471 ctrl = ldap_control_find( LDAP_CONTROL_PASSWORDPOLICYRESPONSE,
1474 if ( ctrl && ldap_parse_passwordpolicy_control( ld, ctrl,
1475 &expire, &grace, &pErr ) == LDAP_SUCCESS )
1477 if ( pErr != PP_noError ){
1480 strcpy( msgbuf+2, ldap_passwordpolicy_err2txt( pErr ));
1481 len = strlen( msgbuf );
1483 if ( expire >= 0 ) {
1484 sprintf( msgbuf+len,
1485 " (Password expires in %d seconds)",
1487 } else if ( grace >= 0 ) {
1488 sprintf( msgbuf+len,
1489 " (Password expired, %d grace logins remain)",
1497 ldap_controls_free( ctrls );
1500 if ( err != LDAP_SUCCESS
1502 || ( matched && matched[ 0 ] )
1503 || ( info && info[ 0 ] )
1506 tool_perror( "ldap_bind", err, msgbuf, matched, info, refs );
1508 if( matched ) ber_memfree( matched );
1509 if( info ) ber_memfree( info );
1510 if( refs ) ber_memvfree( (void **)refs );
1512 if ( err != LDAP_SUCCESS ) exit( err );
1518 tool_unbind( LDAP *ld )
1520 int err = ldap_set_option( ld, LDAP_OPT_SERVER_CONTROLS, NULL );
1522 if ( err != LDAP_OPT_SUCCESS ) {
1523 fprintf( stderr, "Could not unset controls\n");
1526 (void) ldap_unbind_ext( ld, NULL, NULL );
1530 /* Set server controls. Add controls extra_c[0..count-1], if set. */
1532 tool_server_controls( LDAP *ld, LDAPControl *extra_c, int count )
1534 int i = 0, j, crit = 0, err;
1535 LDAPControl c[16], **ctrls;
1539 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
1541 #endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
1545 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
1550 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
1552 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
1553 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
1555 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
1557 || unknown_ctrls_num ) )
1562 ctrls = (LDAPControl**) malloc(sizeof(c) + (count + unknown_ctrls_num + 1)*sizeof(LDAPControl*));
1563 if ( ctrls == NULL ) {
1564 fprintf( stderr, "No memory\n" );
1565 exit( EXIT_FAILURE );
1569 if ( BER_BVISNULL( &assertionvalue ) ) {
1570 err = ldap_create_assertion_control_value( ld,
1571 assertion, &assertionvalue );
1574 "Unable to create assertion value "
1575 "\"%s\" (%d)\n", assertion, err );
1579 c[i].ldctl_oid = LDAP_CONTROL_ASSERT;
1580 c[i].ldctl_value = assertionvalue;
1581 c[i].ldctl_iscritical = assertctl > 1;
1587 c[i].ldctl_value.bv_val = authzid;
1588 c[i].ldctl_value.bv_len = strlen( authzid );
1589 c[i].ldctl_oid = LDAP_CONTROL_PROXY_AUTHZ;
1590 c[i].ldctl_iscritical = authzcrit;
1595 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
1596 /* NOTE: doesn't need an extra count because it's incompatible
1599 BerElementBuffer berbuf;
1600 BerElement *ber = (BerElement *)&berbuf;
1602 ber_init2( ber, NULL, LBER_USE_DER );
1604 if ( ber_printf( ber, "s", proxydn ) == -1 ) {
1605 exit( EXIT_FAILURE );
1608 if ( ber_flatten2( ber, &c[i].ldctl_value, 0 ) == -1 ) {
1609 exit( EXIT_FAILURE );
1612 c[i].ldctl_oid = LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ;
1613 c[i].ldctl_iscritical = authzcrit;
1617 #endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
1620 c[i].ldctl_oid = LDAP_CONTROL_MANAGEDIT;
1621 BER_BVZERO( &c[i].ldctl_value );
1622 c[i].ldctl_iscritical = manageDIT > 1;
1627 if ( manageDSAit ) {
1628 c[i].ldctl_oid = LDAP_CONTROL_MANAGEDSAIT;
1629 BER_BVZERO( &c[i].ldctl_value );
1630 c[i].ldctl_iscritical = manageDSAit > 1;
1636 c[i].ldctl_oid = LDAP_CONTROL_NOOP;
1637 BER_BVZERO( &c[i].ldctl_value );
1638 c[i].ldctl_iscritical = noop > 1;
1643 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
1645 c[i].ldctl_oid = LDAP_CONTROL_PASSWORDPOLICYREQUEST;
1646 BER_BVZERO( &c[i].ldctl_value );
1647 c[i].ldctl_iscritical = 0;
1654 BerElementBuffer berbuf;
1655 BerElement *ber = (BerElement *)&berbuf;
1656 char **attrs = NULL;
1658 if( preread_attrs ) {
1659 attrs = ldap_str2charray( preread_attrs, "," );
1662 ber_init2( ber, NULL, LBER_USE_DER );
1664 if( ber_printf( ber, "{v}", attrs ) == -1 ) {
1665 fprintf( stderr, "preread attrs encode failed.\n" );
1666 exit( EXIT_FAILURE );
1669 err = ber_flatten2( ber, &c[i].ldctl_value, 0 );
1671 fprintf( stderr, "preread flatten failed (%d)\n", err );
1672 exit( EXIT_FAILURE );
1675 c[i].ldctl_oid = LDAP_CONTROL_PRE_READ;
1676 c[i].ldctl_iscritical = preread > 1;
1680 if( attrs ) ldap_charray_free( attrs );
1684 BerElementBuffer berbuf;
1685 BerElement *ber = (BerElement *)&berbuf;
1686 char **attrs = NULL;
1688 if( postread_attrs ) {
1689 attrs = ldap_str2charray( postread_attrs, "," );
1692 ber_init2( ber, NULL, LBER_USE_DER );
1694 if( ber_printf( ber, "{v}", attrs ) == -1 ) {
1695 fprintf( stderr, "postread attrs encode failed.\n" );
1696 exit( EXIT_FAILURE );
1699 err = ber_flatten2( ber, &c[i].ldctl_value, 0 );
1701 fprintf( stderr, "postread flatten failed (%d)\n", err );
1702 exit( EXIT_FAILURE );
1705 c[i].ldctl_oid = LDAP_CONTROL_POST_READ;
1706 c[i].ldctl_iscritical = postread > 1;
1710 if( attrs ) ldap_charray_free( attrs );
1713 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
1715 if ( chainingResolve > -1 ) {
1716 BerElementBuffer berbuf;
1717 BerElement *ber = (BerElement *)&berbuf;
1719 ber_init2( ber, NULL, LBER_USE_DER );
1721 err = ber_printf( ber, "{e" /* } */, chainingResolve );
1724 fprintf( stderr, _("Chaining behavior control encoding error!\n") );
1725 exit( EXIT_FAILURE );
1728 if ( chainingContinuation > -1 ) {
1729 err = ber_printf( ber, "e", chainingContinuation );
1732 fprintf( stderr, _("Chaining behavior control encoding error!\n") );
1733 exit( EXIT_FAILURE );
1737 err = ber_printf( ber, /* { */ "N}" );
1740 fprintf( stderr, _("Chaining behavior control encoding error!\n") );
1741 exit( EXIT_FAILURE );
1744 if ( ber_flatten2( ber, &c[i].ldctl_value, 0 ) == -1 ) {
1745 exit( EXIT_FAILURE );
1749 BER_BVZERO( &c[i].ldctl_value );
1752 c[i].ldctl_oid = LDAP_CONTROL_X_CHAINING_BEHAVIOR;
1753 c[i].ldctl_iscritical = chaining > 1;
1757 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
1759 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
1760 if ( sessionTracking ) {
1761 if ( stValue.bv_val == NULL && st_value( ld, &stValue ) ) {
1762 exit( EXIT_FAILURE );
1765 c[i].ldctl_oid = LDAP_CONTROL_X_SESSION_TRACKING;
1766 c[i].ldctl_iscritical = 0;
1767 ber_dupbv( &c[i].ldctl_value, &stValue );
1772 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
1775 ctrls[i++] = extra_c++;
1777 for ( count = 0; count < unknown_ctrls_num; count++ ) {
1778 ctrls[i++] = &unknown_ctrls[count];
1782 err = ldap_set_option( ld, LDAP_OPT_SERVER_CONTROLS, ctrls );
1784 if ( err != LDAP_OPT_SUCCESS ) {
1785 for ( j = 0; j < i; j++ ) {
1786 if ( ctrls[j]->ldctl_iscritical ) crit = 1;
1788 fprintf( stderr, "Could not set %scontrols\n",
1789 crit ? "critical " : "" );
1794 exit( EXIT_FAILURE );
1799 tool_check_abandon( LDAP *ld, int msgid )
1803 switch ( gotintr ) {
1805 rc = ldap_cancel_s( ld, msgid, NULL, NULL );
1806 fprintf( stderr, "got interrupt, cancel got %d: %s\n",
1807 rc, ldap_err2string( rc ) );
1811 rc = ldap_abandon_ext( ld, msgid, NULL, NULL );
1812 fprintf( stderr, "got interrupt, abandon got %d: %s\n",
1813 rc, ldap_err2string( rc ) );
1817 /* just unbind, ignoring the request */
1825 print_prepostread( LDAP *ld, LDAPControl *ctrl, struct berval *what)
1830 tool_write_ldif( LDIF_PUT_COMMENT, "==> ",
1831 what->bv_val, what->bv_len );
1832 ber = ber_init( &ctrl->ldctl_value );
1833 if ( ber == NULL ) {
1837 } else if ( ber_scanf( ber, "{m{" /*}}*/, &bv ) == LBER_ERROR ) {
1842 tool_write_ldif( LDIF_PUT_VALUE, "dn", bv.bv_val, bv.bv_len );
1844 while ( ber_scanf( ber, "{m" /*}*/, &bv ) != LBER_ERROR ) {
1846 BerVarray vals = NULL;
1848 if ( ber_scanf( ber, "[W]", &vals ) == LBER_ERROR ||
1855 for ( i = 0; vals[ i ].bv_val != NULL; i++ ) {
1857 ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1858 bv.bv_val, vals[ i ].bv_val, vals[ i ].bv_len );
1861 ber_bvarray_free( vals );
1865 if ( ber != NULL ) {
1869 tool_write_ldif( LDIF_PUT_COMMENT, "<== ",
1870 what->bv_val, what->bv_len );
1876 print_preread( LDAP *ld, LDAPControl *ctrl )
1878 static struct berval what = BER_BVC( "preread" );
1880 return print_prepostread( ld, ctrl, &what );
1884 print_postread( LDAP *ld, LDAPControl *ctrl )
1886 static struct berval what = BER_BVC( "postread" );
1888 return print_prepostread( ld, ctrl, &what );
1892 print_paged_results( LDAP *ld, LDAPControl *ctrl )
1896 /* note: pr_cookie is being malloced; it's freed
1897 * the next time the control is sent, but the last
1898 * time it's not; we don't care too much, because
1899 * the last time an empty value is returned... */
1900 if ( ldap_parse_pageresponse_control( ld, ctrl, &estimate, &pr_cookie )
1907 /* FIXME: check buffer overflow */
1908 char buf[ BUFSIZ ], *ptr = buf;
1910 if ( estimate > 0 ) {
1911 ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
1912 "estimate=%d", estimate );
1915 if ( pr_cookie.bv_len > 0 ) {
1918 bv.bv_len = LUTIL_BASE64_ENCODE_LEN(
1919 pr_cookie.bv_len ) + 1;
1920 bv.bv_val = ber_memalloc( bv.bv_len + 1 );
1922 bv.bv_len = lutil_b64_ntop(
1923 (unsigned char *) pr_cookie.bv_val,
1925 bv.bv_val, bv.bv_len );
1927 ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
1928 "%scookie=%s", ptr == buf ? "" : " ",
1931 ber_memfree( bv.bv_val );
1933 pr_morePagedResults = 1;
1936 ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
1937 "%scookie=", ptr == buf ? "" : " " );
1940 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1941 "pagedresults", buf, ptr - buf );
1948 print_sss( LDAP *ld, LDAPControl *ctrl )
1954 rc = ldap_parse_sortresponse_control( ld, ctrl, &err, &attr );
1955 if ( rc == LDAP_SUCCESS ) {
1957 rc = snprintf( buf, sizeof(buf), "(%d) %s%s%s",
1958 err, ldap_err2string(err), attr ? " " : "", attr ? attr : "" );
1960 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1961 "sortResult", buf, rc );
1968 print_vlv( LDAP *ld, LDAPControl *ctrl )
1974 rc = ldap_parse_vlvresponse_control( ld, ctrl, &vlvPos, &vlvCount,
1975 &vlvContext, &err );
1976 if ( rc == LDAP_SUCCESS ) {
1979 if ( vlvContext && vlvContext->bv_len > 0 ) {
1980 bv.bv_len = LUTIL_BASE64_ENCODE_LEN(
1981 vlvContext->bv_len ) + 1;
1982 bv.bv_val = ber_memalloc( bv.bv_len + 1 );
1984 bv.bv_len = lutil_b64_ntop(
1985 (unsigned char *) vlvContext->bv_val,
1987 bv.bv_val, bv.bv_len );
1993 rc = snprintf( buf, sizeof(buf), "pos=%d count=%d context=%s (%d) %s",
1994 vlvPos, vlvCount, bv.bv_val,
1995 err, ldap_err2string(err));
1998 ber_memfree( bv.bv_val );
2000 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
2001 "vlvResult", buf, rc );
2007 #ifdef LDAP_CONTROL_X_DEREF
2009 print_deref( LDAP *ld, LDAPControl *ctrl )
2011 LDAPDerefRes *drhead = NULL, *dr;
2014 rc = ldap_parse_derefresponse_control( ld, ctrl, &drhead );
2015 if ( rc != LDAP_SUCCESS ) {
2019 for ( dr = drhead; dr != NULL; dr = dr->next ) {
2024 len = strlen( dr->derefAttr ) + STRLENOF(": ");
2026 for ( dv = dr->attrVals; dv != NULL; dv = dv->next ) {
2027 if ( dv->vals != NULL ) {
2029 ber_len_t tlen = strlen(dv->type);
2031 for ( j = 0; dv->vals[ j ].bv_val != NULL; j++ ) {
2032 len += STRLENOF("<:=>;") + tlen + 4*((dv->vals[ j ].bv_len - 1)/3 + 1);
2036 len += dr->derefVal.bv_len + STRLENOF("\n");
2037 buf = ldap_memalloc( len + 1 );
2038 if ( buf == NULL ) {
2039 rc = LDAP_NO_MEMORY;
2044 ptr = lutil_strcopy( ptr, dr->derefAttr );
2047 for ( dv = dr->attrVals; dv != NULL; dv = dv->next ) {
2048 if ( dv->vals != NULL ) {
2050 for ( j = 0; dv->vals[ j ].bv_val != NULL; j++ ) {
2051 int k = ldif_is_not_printable( dv->vals[ j ].bv_val, dv->vals[ j ].bv_len );
2054 ptr = lutil_strcopy( ptr, dv->type );
2061 (unsigned char *) dv->vals[ j ].bv_val,
2062 dv->vals[ j ].bv_len,
2063 ptr, buf + len - ptr );
2068 ptr = lutil_memcopy( ptr, dv->vals[ j ].bv_val, dv->vals[ j ].bv_len );
2075 ptr = lutil_strncopy( ptr, dr->derefVal.bv_val, dr->derefVal.bv_len );
2078 assert( ptr <= buf + len );
2080 tool_write_ldif( LDIF_PUT_COMMENT, NULL, buf, ptr - buf);
2082 ldap_memfree( buf );
2088 ldap_derefresponse_free( drhead );
2094 #ifdef LDAP_CONTROL_X_WHATFAILED
2096 print_whatfailed( LDAP *ld, LDAPControl *ctrl )
2101 BerVarray bva = NULL;
2103 /* Create a BerElement from the berval returned in the control. */
2104 ber = ber_init( &ctrl->ldctl_value );
2106 if ( ber == NULL ) {
2107 return LDAP_NO_MEMORY;
2110 siz = sizeof(struct berval);
2111 tag = ber_scanf( ber, "[M]", &bva, &siz, 0 );
2112 if ( tag != LBER_ERROR ) {
2115 tool_write_ldif( LDIF_PUT_COMMENT, " what failed:", NULL, 0 );
2117 for ( i = 0; bva[i].bv_val != NULL; i++ ) {
2118 tool_write_ldif( LDIF_PUT_COMMENT, NULL, bva[i].bv_val, bva[i].bv_len );
2121 ldap_memfree( bva );
2131 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
2133 print_ppolicy( LDAP *ld, LDAPControl *ctrl )
2135 int expire = 0, grace = 0, rc;
2136 LDAPPasswordPolicyError pperr;
2138 rc = ldap_parse_passwordpolicy_control( ld, ctrl,
2139 &expire, &grace, &pperr );
2140 if ( rc == LDAP_SUCCESS ) {
2141 char buf[ BUFSIZ ], *ptr = buf;
2143 if ( expire != -1 ) {
2144 ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
2145 "expire=%d", expire );
2148 if ( grace != -1 ) {
2149 ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
2150 "%sgrace=%d", ptr == buf ? "" : " ", grace );
2153 if ( pperr != PP_noError ) {
2154 ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
2155 "%serror=%d (%s)", ptr == buf ? "" : " ",
2157 ldap_passwordpolicy_err2txt( pperr ) );
2160 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
2161 "ppolicy", buf, ptr - buf );
2168 void tool_print_ctrls(
2170 LDAPControl **ctrls )
2175 for ( i = 0; ctrls[i] != NULL; i++ ) {
2176 /* control: OID criticality base64value */
2177 struct berval b64 = BER_BVNULL;
2182 /* FIXME: there might be cases where a control has NULL OID;
2183 * this makes little sense, especially when returned by the
2184 * server, but libldap happily allows it */
2185 if ( ctrls[i]->ldctl_oid == NULL ) {
2190 len += strlen( ctrls[i]->ldctl_oid );
2192 /* add enough for space after OID and the critical value itself */
2193 len += ctrls[i]->ldctl_iscritical
2194 ? sizeof("true") : sizeof("false");
2196 /* convert to base64 */
2197 if ( !BER_BVISNULL( &ctrls[i]->ldctl_value ) ) {
2198 b64.bv_len = LUTIL_BASE64_ENCODE_LEN(
2199 ctrls[i]->ldctl_value.bv_len ) + 1;
2200 b64.bv_val = ber_memalloc( b64.bv_len + 1 );
2202 b64.bv_len = lutil_b64_ntop(
2203 (unsigned char *) ctrls[i]->ldctl_value.bv_val,
2204 ctrls[i]->ldctl_value.bv_len,
2205 b64.bv_val, b64.bv_len );
2209 len += 1 + b64.bv_len;
2212 ptr = str = malloc( len + 1 );
2214 ptr = lutil_strcopy( ptr, ": " );
2216 ptr = lutil_strcopy( ptr, ctrls[i]->ldctl_oid );
2217 ptr = lutil_strcopy( ptr, ctrls[i]->ldctl_iscritical
2218 ? " true" : " false" );
2221 ptr = lutil_strcopy( ptr, " " );
2222 ptr = lutil_strcopy( ptr, b64.bv_val );
2226 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
2227 "control", str, len );
2232 ber_memfree( b64.bv_val );
2235 /* known controls */
2236 for ( j = 0; tool_ctrl_response[j].oid != NULL; j++ ) {
2237 if ( strcmp( tool_ctrl_response[j].oid, ctrls[i]->ldctl_oid ) == 0 ) {
2238 if ( !tool_ctrl_response[j].mask & tool_type ) {
2239 /* this control should not appear
2240 * with this tool; warning? */
2246 if ( tool_ctrl_response[j].oid != NULL && tool_ctrl_response[j].func ) {
2247 (void)tool_ctrl_response[j].func( ld, ctrls[i] );
2253 tool_write_ldif( int type, char *name, char *value, ber_len_t vallen )
2257 if (( ldif = ldif_put( type, name, value, vallen )) == NULL ) {
2261 fputs( ldif, stdout );
2262 ber_memfree( ldif );
2268 tool_is_oid( const char *s )
2272 if ( !isdigit( (unsigned char) s[ 0 ] ) ) {
2276 for ( ; s[ 0 ]; s++ ) {
2277 if ( s[ 0 ] == '.' ) {
2278 if ( s[ 1 ] == '\0' ) {
2285 if ( !isdigit( (unsigned char) s[ 0 ] ) ) {
2289 if ( first == 1 && s[ 0 ] == '0' && s[ 1 ] != '.' ) {