コード例 #1
0
ファイル: ldap_realm.c プロジェクト: b055man/krb5
krb5_error_code
krb5_ldap_create_krbcontainer(krb5_context context, const char *dn)
{
    LDAP                        *ld=NULL;
    char                        *strval[2]={NULL}, **rdns=NULL;
    LDAPMod                     **mods = NULL;
    krb5_error_code             st=0;
    kdb5_dal_handle             *dal_handle=NULL;
    krb5_ldap_context           *ldap_context=NULL;
    krb5_ldap_server_handle     *ldap_server_handle=NULL;

    SETUP_CONTEXT ();

    /* get ldap handle */
    GET_HANDLE ();

    if (dn == NULL) {
        st = EINVAL;
        k5_setmsg(context, st, _("Kerberos Container information is missing"));
        goto cleanup;
    }

    strval[0] = "krbContainer";
    strval[1] = NULL;
    if ((st=krb5_add_str_mem_ldap_mod(&mods, "objectclass", LDAP_MOD_ADD, strval)) != 0)
        goto cleanup;

    rdns = ldap_explode_dn(dn, 1);
    if (rdns == NULL) {
        st = EINVAL;
        k5_setmsg(context, st, _("Invalid Kerberos container DN"));
        goto cleanup;
    }

    strval[0] = rdns[0];
    strval[1] = NULL;
    if ((st=krb5_add_str_mem_ldap_mod(&mods, "cn", LDAP_MOD_ADD, strval)) != 0)
        goto cleanup;

    /* create the kerberos container */
    st = ldap_add_ext_s(ld, dn, mods, NULL, NULL);
    if (st == LDAP_ALREADY_EXISTS)
        st = LDAP_SUCCESS;
    if (st != LDAP_SUCCESS) {
        int ost = st;
        st = translate_ldap_error (st, OP_ADD);
        k5_setmsg(context, st, _("Kerberos Container create FAILED: %s"),
                  ldap_err2string(ost));
        goto cleanup;
    }

cleanup:

    if (rdns)
        ldap_value_free (rdns);

    ldap_mods_free(mods, 1);
    krb5_ldap_put_handle_to_pool(ldap_context, ldap_server_handle);
    return(st);
}
コード例 #2
0
ファイル: ol_ldap.c プロジェクト: hww3/pexts
/*
 **| method: array(string) explode_dn ( string dn );
 **| alt: array(string) explode_dn ( string dn, int notypes );
 **|  Takes a DN and converts it into an array of its components,
 **|  called RDN (Relative Distinguished Name).
 **
 **| arg: string dn
 **|  The DN to explode.
 **
 **| arg: int notypes
 **|  If != 0 then the types of the DN components will be ignored and
 **|  *not present in the output. Defaults to 1.
 **
 **| returns: an array of RDN entries.
 */
static void
f_ldap_explode_dn(INT32 args)
{
    struct pike_string       *dn;
    char                    **edn;
    int                       notypes = 1;    

    switch (args) {
        case 2:
            if (ARG(2).type != T_INT)
                Pike_error("OpenLDAP.Client->explode_dn(): argument 2 must be an integer\n");
            notypes = ARG(2).u.integer;
            /* fall through */
            
        case 1:
            if (ARG(1).type != T_STRING)
                Pike_error("OpenLDAP.Client->explode_dn(): argument 1 must be an integer\n");
            dn = ARG(1).u.string;
            break;
            
        default:
            Pike_error("OpenLDAP.Client->explode_dn(): expects at most 2 and at least 1 argument\n");
            break;
    }

    pop_n_elems(args);
    edn = ldap_explode_dn(dn->str, notypes);
    if (!edn) {
        push_int(0);
        return;
    }

    push_array(make_pike_array(edn));
    ldap_value_free(edn);
}
コード例 #3
0
ファイル: ldap.c プロジェクト: afbroman/ruby-ldap
VALUE
rb_ldap_explode_dn (VALUE self, VALUE dn, VALUE notypes)
{
    char **c_arr, **p;
    char *c_dn;
    VALUE ary;

    if (dn == Qnil) 
    {
        return Qnil;
    }

    c_dn = StringValueCStr (dn);
    if ((c_arr = ldap_explode_dn (c_dn, RTEST (notypes) ? 1 : 0)))
    {
        ary = rb_ary_new ();
        for (p = c_arr; *p != NULL; p++)
        {
            rb_ary_push (ary, rb_tainted_str_new2 (*p));
        }
        ldap_value_free (c_arr);

        return ary;
    } 
    else 
    {
        return Qnil;
    }
}
コード例 #4
0
ファイル: sort.c プロジェクト: ysangkok/pgp-unix-6.5.8
int
ldap_sort_entries(
    LDAP	*ld,
    LDAPMessage	**chain,
    char	*attr,		/* NULL => sort by DN */
    int		(*cmp)(const void *a, const void *b)
)
{
	int			i, count;
	struct entrything	*et;
	LDAPMessage		*e, *last;
	LDAPMessage		**ep;

	count = ldap_count_entries( ld, *chain );

	if ( (et = (struct entrything *) malloc( count *
	    sizeof(struct entrything) )) == NULL ) {
		ld->ld_errno = LDAP_NO_MEMORY;
		return( -1 );
	}

	e = *chain;
	for ( i = 0; i < count; i++ ) {
		et[i].et_msg = e;
		if ( attr == NULL ) {
			char	*dn;

			dn = ldap_get_dn( ld, e );
			et[i].et_vals = ldap_explode_dn( dn, 1 );
			free( dn );
		} else {
			et[i].et_vals = ldap_get_values( ld, e, attr );
		}

		e = e->lm_chain;
	}
	last = e;

	et_cmp_fn = cmp;
	qsort( et, count, sizeof(struct entrything), (void *) et_cmp );

	ep = chain;
	for ( i = 0; i < count; i++ ) {
		*ep = et[i].et_msg;
		ep = &(*ep)->lm_chain;

		ldap_value_free( et[i].et_vals );
	}
	*ep = last;
	free( (char *) et );

	return( 0 );
}
コード例 #5
0
ファイル: net_ads.c プロジェクト: niubl/camera_project
static int ads_user_info(int argc, const char **argv)
{
	ADS_STRUCT *ads;
	ADS_STATUS rc;
	void *res;
	const char *attrs[] = {"memberOf", NULL};
	char *searchstring=NULL;
	char **grouplist;
	char *escaped_user = escape_ldap_string_alloc(argv[0]);

	if (argc < 1) {
		return net_ads_user_usage(argc, argv);
	}
	
	if (!(ads = ads_startup())) {
		return -1;
	}

	if (!escaped_user) {
		d_printf("ads_user_info: failed to escape user %s\n", argv[0]);
		ads_destroy(&ads);
	 	return -1;
	}

	asprintf(&searchstring, "(sAMAccountName=%s)", escaped_user);
	rc = ads_search(ads, &res, searchstring, attrs);
	safe_free(searchstring);

	if (!ADS_ERR_OK(rc)) {
		d_printf("ads_search: %s\n", ads_errstr(rc));
		ads_destroy(&ads);
		return -1;
	}
	
	grouplist = ldap_get_values(ads->ld, res, "memberOf");

	if (grouplist) {
		int i;
		char **groupname;
		for (i=0;grouplist[i];i++) {
			groupname = ldap_explode_dn(grouplist[i], 1);
			d_printf("%s\n", groupname[0]);
			ldap_value_free(groupname);
		}
		ldap_value_free(grouplist);
	}
	
	ads_msgfree(ads, res);
	ads_destroy(&ads);
	return 0;
}
コード例 #6
0
/* 
  move a user to another container
  sets userprincipalname based on the destination container
	return AD_SUCCESS on success 
*/
int ad_move_user(char *current_dn, char *new_container) {
	LDAP *ds;
	int result;
	char **exdn;
	char **username, *domain, *upn;

	ds=ad_login();
	if(!ds) return ad_error_code;

	username=ad_get_attribute(current_dn, "sAMAccountName");;
	if(username==NULL) {
		snprintf(ad_error_msg, MAX_ERR_LENGTH,
		"Error getting username for dn %s for ad_move_user\n",
		current_dn);
		ad_error_code=AD_INVALID_DN;
		return ad_error_code;
	}
	domain=dn2domain(new_container);
	upn=malloc(strlen(username[0])+strlen(domain)+2);
	sprintf(upn, "%s@%s", username[0], domain);
	free(domain);
	result=ad_mod_replace(current_dn, "userPrincipalName", upn);
	free(upn);
	if(!result) return ad_error_code;

	exdn=ldap_explode_dn(current_dn, 0);
	if(exdn==NULL) {
		snprintf(ad_error_msg, MAX_ERR_LENGTH,
		"Error exploding dn %s for ad_move_user\n",
		current_dn);
		ad_error_code=AD_INVALID_DN;
		return ad_error_code;
	}

	result=ldap_rename_s(ds, current_dn, exdn[0], new_container,
				1, NULL, NULL);
	ldap_memfree(exdn);
	if(result!=LDAP_SUCCESS) {
		snprintf(ad_error_msg, MAX_ERR_LENGTH,
		"Error in ldap_rename_s for ad_move_user: %s\n",
		ldap_err2string(result));
		ad_error_code=AD_LDAP_OPERATION_FAILURE;
	} else {
		ad_error_code=AD_SUCCESS;
	}
	return ad_error_code;
}
コード例 #7
0
ファイル: ldap_printer.c プロジェクト: AIdrifter/samba
/*
  find a printer given the name and the hostname
    Note that results "res" may be allocated on return so that the
    results can be used.  It should be freed using ads_msgfree.
*/
 ADS_STATUS ads_find_printer_on_server(ADS_STRUCT *ads, LDAPMessage **res,
				       const char *printer,
				       const char *servername)
{
	ADS_STATUS status;
	char *srv_dn, **srv_cn, *s = NULL;
	const char *attrs[] = {"*", "nTSecurityDescriptor", NULL};

	status = ads_find_machine_acct(ads, res, servername);
	if (!ADS_ERR_OK(status)) {
		DEBUG(1, ("ads_find_printer_on_server: cannot find host %s in ads\n",
			  servername));
		return status;
	}
	if (ads_count_replies(ads, *res) != 1) {
		ads_msgfree(ads, *res);
		*res = NULL;
		return ADS_ERROR(LDAP_NO_SUCH_OBJECT);
	}
	srv_dn = ldap_get_dn(ads->ldap.ld, *res);
	if (srv_dn == NULL) {
		ads_msgfree(ads, *res);
		*res = NULL;
		return ADS_ERROR(LDAP_NO_MEMORY);
	}
	srv_cn = ldap_explode_dn(srv_dn, 1);
	if (srv_cn == NULL) {
		ldap_memfree(srv_dn);
		ads_msgfree(ads, *res);
		*res = NULL;
		return ADS_ERROR(LDAP_INVALID_DN_SYNTAX);
	}
	ads_msgfree(ads, *res);
	*res = NULL;

	if (asprintf(&s, "(cn=%s-%s)", srv_cn[0], printer) == -1) {
		ldap_memfree(srv_dn);
		return ADS_ERROR(LDAP_NO_MEMORY);
	}
	status = ads_search(ads, res, s, attrs);

	ldap_memfree(srv_dn);
	ldap_value_free(srv_cn);
	SAFE_FREE(s);
	return status;	
}
コード例 #8
0
ファイル: LDAPQuery.cpp プロジェクト: Maqentaer/LDAPQuery
STDMETHODIMP CLDAPQuery::explodeDn(
	/* [in] */ BSTR str,
	/* [in] */ ULONG notypes,
	/* [retval][out] */ SAFEARRAY **result)
{
	PTCHAR *vals = ldap_explode_dn(CComBSTR(str), notypes);
	m_errorCode = LdapGetLastError();
	if(vals)
	{
		CComSafeArray<VARIANT> dnValues;
		for(LONG i = 0L; vals[i]!=NULL; i++)
		{
			dnValues.Add(CComVariant(vals[i]));
		}
		ldap_value_free(vals);
		*result = dnValues.Detach();
	}
	return S_OK;
}
コード例 #9
0
ファイル: dn.c プロジェクト: MichaelMcDonnell/wine
/***********************************************************************
 *      ldap_explode_dnW     (WLDAP32.@)
 *
 * Break up a DN into its components.
 *
 * PARAMS
 *  dn       [I] DN to break up.
 *  notypes  [I] Remove attribute type information from the components.
 *
 * RETURNS
 *  Success: Pointer to a NULL-terminated array that contains the DN
 *           components. 
 *  Failure: NULL
 *
 * NOTES
 *  Free the string array with ldap_value_free.
 */
PWCHAR * CDECL ldap_explode_dnW( PWCHAR dn, ULONG notypes )
{
    PWCHAR *ret = NULL;
#ifdef HAVE_LDAP
    char *dnU, **retU;

    TRACE( "(%s, 0x%08x)\n", debugstr_w(dn), notypes );

    dnU = strWtoU( dn );
    if (!dnU) return NULL;

    retU = ldap_explode_dn( dnU, notypes );
    ret = strarrayUtoW( retU );

    strfreeU( dnU );
    ldap_memvfree( (void **)retU );

#endif
    return ret;
}
コード例 #10
0
/* 
convert a distinguished name into the domain controller
dns domain, eg: "ou=users,dc=example,dc=com" returns
"example.com".
memory allocated should be returned with free()
*/
char *dn2domain(char *dn) {
	char **exp_dn;
	int i;
	char *dc;

	dc=malloc(1024);
	dc[0]='\0';
	exp_dn=ldap_explode_dn(dn, 0);
	for(i=0; exp_dn[i]!=NULL; i++) {
		if(!strncasecmp("dc=", exp_dn[i], 3)) {
			strncat(dc, exp_dn[i]+3, 1024);
			strncat(dc, ".", 1024);
		}
	}
	ldap_value_free(exp_dn);
	i=strlen(dc);
	if(i>0) dc[i-1]='\0';
	for(i=0; dc[i]!='\0'; i++) dc[i]=tolower(dc[i]);
	return dc;
}
コード例 #11
0
ファイル: tmplout.c プロジェクト: andreiw/polaris
static int
output_dn( char *buf, char *dn, int width, int rdncount,
	writeptype writeproc, void *writeparm, char *eol, char *urlprefix )
{
    char	**dnrdns;
    int		i;

    if (( dnrdns = ldap_explode_dn( dn, 1 )) == NULL ) {
	return( -1 );
    }

    if ( urlprefix != NULL ) {
	sprintf( buf, "<DD><A HREF=\"%s", urlprefix );
	strcat_escaped( buf, dn );
	strcat( buf, "\">" );
    } else if ( width > 0 ) {
	sprintf( buf, "%-*s", width, " " );
    } else {
	*buf = '\0';
    }

    for ( i = 0; dnrdns[ i ] != NULL && ( rdncount == 0 || i < rdncount );
	    ++i ) {
	if ( i > 0 ) {
	    strcat( buf, ", " );
	}
	strcat( buf, dnrdns[ i ] );
    }

    if ( urlprefix != NULL ) {
	strcat( buf, "</A><BR>" );
    }

    ldap_value_free( dnrdns );

    strcat( buf, eol );

    return ((*writeproc)( writeparm, buf, strlen( buf )));
}
コード例 #12
0
ファイル: ldap_realm.c プロジェクト: mihais/krb5
krb5_error_code
krb5_ldap_create_krbcontainer(krb5_context context,
                              const
                              krb5_ldap_krbcontainer_params *krbcontparams)
{
    LDAP                        *ld=NULL;
    char                        *strval[2]={NULL}, *kerberoscontdn=NULL, **rdns=NULL;
    int                         pmask=0;
    LDAPMod                     **mods = NULL;
    krb5_error_code             st=0;
    kdb5_dal_handle             *dal_handle=NULL;
    krb5_ldap_context           *ldap_context=NULL;
    krb5_ldap_server_handle     *ldap_server_handle=NULL;

    SETUP_CONTEXT ();

    /* get ldap handle */
    GET_HANDLE ();

    if (krbcontparams != NULL && krbcontparams->DN != NULL) {
        kerberoscontdn = krbcontparams->DN;
    } else {
        st = EINVAL;
        krb5_set_error_message(context, st,
                               _("Kerberos Container information is missing"));
        goto cleanup;
    }

    strval[0] = "krbContainer";
    strval[1] = NULL;
    if ((st=krb5_add_str_mem_ldap_mod(&mods, "objectclass", LDAP_MOD_ADD, strval)) != 0)
        goto cleanup;

    rdns = ldap_explode_dn(kerberoscontdn, 1);
    if (rdns == NULL) {
        st = EINVAL;
        krb5_set_error_message(context, st,
                               _("Invalid Kerberos container DN"));
        goto cleanup;
    }

    strval[0] = rdns[0];
    strval[1] = NULL;
    if ((st=krb5_add_str_mem_ldap_mod(&mods, "cn", LDAP_MOD_ADD, strval)) != 0)
        goto cleanup;

    /* check if the policy reference value exists and is of krbticketpolicyreference object class */
    if (krbcontparams && krbcontparams->policyreference) {
        st = checkattributevalue(ld, krbcontparams->policyreference, "objectclass", policyclass,
                                 &pmask);
        CHECK_CLASS_VALIDITY(st, pmask, _("ticket policy object value: "));

        strval[0] = krbcontparams->policyreference;
        strval[1] = NULL;
        if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbticketpolicyreference", LDAP_MOD_ADD,
                                          strval)) != 0)
            goto cleanup;
    }

    /* create the kerberos container */
    if ((st = ldap_add_ext_s(ld, kerberoscontdn, mods, NULL, NULL)) != LDAP_SUCCESS) {
        int ost = st;
        st = translate_ldap_error (st, OP_ADD);
        krb5_set_error_message(context, st,
                               _("Kerberos Container create FAILED: %s"),
                               ldap_err2string(ost));
        goto cleanup;
    }

cleanup:

    if (rdns)
        ldap_value_free (rdns);

    ldap_mods_free(mods, 1);
    krb5_ldap_put_handle_to_pool(ldap_context, ldap_server_handle);
    return(st);
}
コード例 #13
0
ファイル: dntest.c プロジェクト: vmware/lightwave
int
main( int argc, char *argv[] )
{
	int 		rc, i, debug = 0, f2 = 0;
	unsigned 	flags[ 2 ] = { 0U, 0 };
	char		*strin, *str = NULL, buf[ 1024 ];
	LDAPDN		dn, dn2 = NULL;

	while ( 1 ) {
		int opt = getopt( argc, argv, "d:" );

		if ( opt == EOF ) {
			break;
		}

		switch ( opt ) {
		case 'd':
			debug = atoi( optarg );
			break;
		}
	}

	optind--;
	argc -= optind;
	argv += optind;

	if ( argc < 2 ) {
		fprintf( stderr, "usage: dntest <dn> [flags-in[,...]] [flags-out[,...]]\n\n" );
		fprintf( stderr, "\tflags-in:   V3,V2,DCE,<flags>\n" );
		fprintf( stderr, "\tflags-out:  V3,V2,UFN,DCE,AD,<flags>\n\n" );
		fprintf( stderr, "\t<flags>: PRETTY,PEDANTIC,NOSPACES,NOONESPACE\n\n" );
		return( 0 );
	}

	if ( ber_set_option( NULL, LBER_OPT_DEBUG_LEVEL, &debug ) != LBER_OPT_SUCCESS ) {
		fprintf( stderr, "Could not set LBER_OPT_DEBUG_LEVEL %d\n", debug );
	}
	if ( ldap_set_option( NULL, LDAP_OPT_DEBUG_LEVEL, &debug ) != LDAP_OPT_SUCCESS ) {
		fprintf( stderr, "Could not set LDAP_OPT_DEBUG_LEVEL %d\n", debug );
	}

	if ( strcmp( argv[ 1 ], "-" ) == 0 ) {
		size_t len = fgets( buf, sizeof( buf ), stdin ) ? strlen( buf ) : 0;

		if ( len == 0 || buf[ --len ] == '\n' ) {
			buf[ len ] = '\0';
		}
		strin = buf;
	} else {
		strin = argv[ 1 ];
	}

	if ( argc >= 3 ) {
		for ( i = 0; i < argc - 2; i++ ) {
			char *s, *e;
			for ( s = argv[ 2 + i ]; s; s = e ) {
				e = strchr( s, ',' );
				if ( e != NULL ) {
					e[ 0 ] = '\0';
					e++;
				}
	
				if ( !strcasecmp( s, "V3" ) ) {
					flags[ i ] |= LDAP_DN_FORMAT_LDAPV3;
				} else if ( !strcasecmp( s, "V2" ) ) {
					flags[ i ] |= LDAP_DN_FORMAT_LDAPV2;
				} else if ( !strcasecmp( s, "DCE" ) ) {
					flags[ i ] |= LDAP_DN_FORMAT_DCE;
				} else if ( !strcasecmp( s, "UFN" ) ) {
					flags[ i ] |= LDAP_DN_FORMAT_UFN;
				} else if ( !strcasecmp( s, "AD" ) ) {
					flags[ i ] |= LDAP_DN_FORMAT_AD_CANONICAL;
				} else if ( !strcasecmp( s, "PRETTY" ) ) {
					flags[ i ] |= LDAP_DN_PRETTY;
				} else if ( !strcasecmp( s, "PEDANTIC" ) ) {
					flags[ i ] |= LDAP_DN_PEDANTIC;
				} else if ( !strcasecmp( s, "NOSPACES" ) ) {
					flags[ i ] |= LDAP_DN_P_NOLEADTRAILSPACES;
				} else if ( !strcasecmp( s, "NOONESPACE" ) ) {
					flags[ i ] |= LDAP_DN_P_NOSPACEAFTERRDN;
				}
			}
		}
	}

	if ( flags[ 1 ] == 0 )
		flags[ 1 ] = LDAP_DN_FORMAT_LDAPV3;

	f2 = 1;

	rc = ldap_str2dn( strin, &dn, flags[ 0 ] );

	if ( rc == LDAP_SUCCESS ) {
		int i;
		if ( dn ) {
			for ( i = 0; dn[ i ]; i++ ) {
				LDAPRDN		rdn = dn[ i ];
				char		*rstr = NULL;

				if ( ldap_rdn2str( rdn, &rstr, flags[ f2 ] ) ) {
					fprintf( stdout, "\tldap_rdn2str() failed\n" );
					continue;
				}

				fprintf( stdout, "\tldap_rdn2str() = \"%s\"\n", rstr );
				ldap_memfree( rstr );
			}
		} else {
			fprintf( stdout, "\tempty DN\n" );
		}
	}

	str = NULL;
	if ( rc == LDAP_SUCCESS &&
		ldap_dn2str( dn, &str, flags[ f2 ] ) == LDAP_SUCCESS )
	{
		char	**values, *tmp, *tmp2, *str2 = NULL;
		int	n;
		
		fprintf( stdout, "\nldap_dn2str(ldap_str2dn(\"%s\"))\n"
				"\t= \"%s\"\n", strin, str );
			
		switch ( flags[ f2 ] & LDAP_DN_FORMAT_MASK ) {
		case LDAP_DN_FORMAT_UFN:
		case LDAP_DN_FORMAT_AD_CANONICAL:
			return( 0 );

		case LDAP_DN_FORMAT_LDAPV3:
		case LDAP_DN_FORMAT_LDAPV2:
			n = ldap_dn2domain( strin, &tmp );
			if ( n ) {
				fprintf( stdout, "\nldap_dn2domain(\"%s\") FAILED\n", strin );
			} else {
				fprintf( stdout, "\nldap_dn2domain(\"%s\")\n"
					"\t= \"%s\"\n", strin, tmp ? tmp : "" );
			}
			ldap_memfree( tmp );

			tmp = ldap_dn2ufn( strin );
			fprintf( stdout, "\nldap_dn2ufn(\"%s\")\n"
					"\t= \"%s\"\n", strin, tmp ? tmp : "" );
			ldap_memfree( tmp );

			tmp = ldap_dn2dcedn( strin );
			fprintf( stdout, "\nldap_dn2dcedn(\"%s\")\n"
					"\t= \"%s\"\n", strin, tmp ? tmp : "" );
			tmp2 = ldap_dcedn2dn( tmp );
			fprintf( stdout, "\nldap_dcedn2dn(\"%s\")\n"
					"\t= \"%s\"\n",
					tmp ? tmp : "", tmp2 ? tmp2 : "" );
			ldap_memfree( tmp );
			ldap_memfree( tmp2 );

			tmp = ldap_dn2ad_canonical( strin );
			fprintf( stdout, "\nldap_dn2ad_canonical(\"%s\")\n"
					"\t= \"%s\"\n", strin, tmp ? tmp : "" );
			ldap_memfree( tmp );

			fprintf( stdout, "\nldap_explode_dn(\"%s\"):\n", str );
			values = ldap_explode_dn( str, 0 );
			for ( n = 0; values && values[ n ]; n++ ) {
				char	**vv;
				int	nn;
				
				fprintf( stdout, "\t\"%s\"\n", values[ n ] );

				fprintf( stdout, "\tldap_explode_rdn(\"%s\")\n",
						values[ n ] );
				vv = ldap_explode_rdn( values[ n ], 0 );
				for ( nn = 0; vv && vv[ nn ]; nn++ ) {
					fprintf( stdout, "\t\t'%s'\n", 
							vv[ nn ] );
				}
				LDAP_VFREE( vv );

				fprintf( stdout, "\tldap_explode_rdn(\"%s\")"
					       " (no types)\n", values[ n ] );
				vv = ldap_explode_rdn( values[ n ], 1 );
				for ( nn = 0; vv && vv[ nn ]; nn++ ) {
					fprintf( stdout, "\t\t\t\"%s\"\n", 
							vv[ nn ] );
				}
				LDAP_VFREE( vv );
				
			}
			LDAP_VFREE( values );

			fprintf( stdout, "\nldap_explode_dn(\"%s\")"
					" (no types):\n", str );
			values = ldap_explode_dn( str, 1 );
			for ( n = 0; values && values[ n ]; n++ ) {
				fprintf( stdout, "\t\"%s\"\n", values[ n ] );
			}
			LDAP_VFREE( values );

			break;
		}

		dn2 = NULL;	
		rc = ldap_str2dn( str, &dn2, flags[ f2 ] );
		str2 = NULL;
		if ( rc == LDAP_SUCCESS && 
				ldap_dn2str( dn2, &str2, flags[ f2 ] )
				== LDAP_SUCCESS ) {
			int 	iRDN;
			
			fprintf( stdout, "\n\"%s\"\n\t == \"%s\" ? %s\n", 
				str, str2, 
				strcmp( str, str2 ) == 0 ? "yes" : "no" );

			if( dn != NULL && dn2 == NULL ) {
				fprintf( stdout, "dn mismatch\n" );
			} else if (( dn != NULL ) && (dn2 != NULL))
				for ( iRDN = 0; dn[ iRDN ] && dn2[ iRDN ]; iRDN++ )
			{
				LDAPRDN 	r = dn[ iRDN ];
				LDAPRDN 	r2 = dn2[ iRDN ];
				int 		iAVA;
				
				for ( iAVA = 0; r[ iAVA ] && r2[ iAVA ]; iAVA++ ) {
					LDAPAVA		*a = r[ iAVA ];
					LDAPAVA		*a2 = r2[ iAVA ];

					if ( a->la_attr.bv_len != a2->la_attr.bv_len ) {
						fprintf( stdout, "ava(%d), rdn(%d) attr len mismatch (%ld->%ld)\n", 
								iAVA + 1, iRDN + 1,
								a->la_attr.bv_len, a2->la_attr.bv_len );
					} else if ( memcmp( a->la_attr.bv_val, a2->la_attr.bv_val, a->la_attr.bv_len ) ) {
						fprintf( stdout, "ava(%d), rdn(%d) attr mismatch\n", 
								iAVA + 1, iRDN + 1 );
					} else if ( a->la_flags != a2->la_flags ) {
						fprintf( stdout, "ava(%d), rdn(%d) flag mismatch (%x->%x)\n", 
								iAVA + 1, iRDN + 1, a->la_flags, a2->la_flags );
					} else if ( a->la_value.bv_len != a2->la_value.bv_len ) {
						fprintf( stdout, "ava(%d), rdn(%d) value len mismatch (%ld->%ld)\n", 
								iAVA + 1, iRDN + 1, 
								a->la_value.bv_len, a2->la_value.bv_len );
					} else if ( memcmp( a->la_value.bv_val, a2->la_value.bv_val, a->la_value.bv_len ) ) {
						fprintf( stdout, "ava(%d), rdn(%d) value mismatch\n", 
								iAVA + 1, iRDN + 1 );
					}
				}
			}
			
			ldap_dnfree( dn2 );
			ldap_memfree( str2 );
		}
		ldap_memfree( str );
	}
	ldap_dnfree( dn );

	/* note: dn is not freed */

	return( 0 );
}
コード例 #14
0
ファイル: parseldif.c プロジェクト: wtsi-hgi/ldapvi
/*
 * Lies die erste Zeile eines beliebigen Records nach position `offset' in `s'.
 * Setze *pos (falls pos != 0).
 * Liefere 0 bei Erfolg, -1 sonst.
 * Bei Erfolg:
 *   - pos ist die exakte Anfangsposition.
 *   - Setze *key auf den Schluessel (falls key != 0).
 *   - Setze *dn auf den Distinguished Name (falls dn != 0).
 * EOF ist kein Fehler und liefert *key = 0 (falls key != 0);
 *
 * Der Schluessel ist dabei
 *   "delete" fuer "changetype: delete"
 *   "modify" fuer "changetype: modify"
 *   "rename" fuer "changetype: moddn" und "changetype: modrdn",
 *   "add" fuer "changetype: add" erlauben wir mal ganz frech ebenfalls
 * oder andernfalls der Wert von "ldapvi-key: ...", das als erste
 * Zeile im attrval-record erscheinen muss.
 */
static int
ldif_read_header(GString *tmp1, GString *tmp2,
		 FILE *s, long offset, char **key, char **dn, long *pos)
{
	char **rdns = 0;
	char *k;
	char *d;
	long pos2;

	if (offset != -1)
		if (fseek(s, offset, SEEK_SET) == -1) syserr();
	do {
		if (pos)
			if ( (*pos = ftell(s)) == -1) syserr();
		if (ldif_read_line(s, tmp1, tmp2) == -1) return -1;
		if (tmp1->len == 0 && feof(s)) {
			if (key) *key = 0;
			return 0;
		}
		if (!strcmp(tmp1->str, "version")) {
			if (strcmp(tmp2->str, "1")) {
				fputs("Error: Invalid file format.\n", stderr);
				return -1;
			}
			tmp1->len = 0;
		}
	} while (!tmp1->len);

	rdns = ldap_explode_dn(tmp2->str, 0);
	if (!rdns) {
		fputs("Error: Invalid distinguished name string.\n", stderr);
		return -1;
	}
	if (dn)
		d = xdup(tmp2->str);

	if ( (pos2 = ftell(s)) == -1) syserr();

	if (ldif_read_line(s, tmp1, tmp2) == -1) {
		if (dn) free(d);
		return -1;
	}
	if (!strcmp(tmp1->str, "ldapvi-key"))
		k = tmp2->str;
	else if (!strcmp(tmp1->str, "changetype")) {
		if (!strcmp(tmp2->str, "modrdn"))
			k = "rename";
		else if (!strcmp(tmp2->str, "moddn"))
			k = "rename";
		else if (!strcmp(tmp2->str, "delete")
			 || !strcmp(tmp2->str, "modify")
			 || !strcmp(tmp2->str, "add"))
			k = tmp2->str;
		else {
			fputs("Error: invalid changetype.\n", stderr);
			if (dn) free(d);
			return -1;
		}
	} else if (!strcmp(tmp1->str, "control")) {
		fputs("Error: Sorry, 'control:' not supported.\n", stderr);
		if (dn) free(d);
		return -1;
	} else {
		k = "add";
		if (fseek(s, pos2, SEEK_SET) == -1) syserr();
	}

	if (key) *key = xdup(k);
	if (dn) *dn = d;
	ldap_value_free(rdns);
	return 0;
}
コード例 #15
0
ファイル: nt_printing_ads.c プロジェクト: Arkhont/samba
static WERROR nt_printer_publish_ads(struct messaging_context *msg_ctx,
				     ADS_STRUCT *ads,
				     struct spoolss_PrinterInfo2 *pinfo2)
{
	ADS_STATUS ads_rc;
	LDAPMessage *res;
	char *prt_dn = NULL, *srv_dn, *srv_cn_0, *srv_cn_escaped, *sharename_escaped;
	char *srv_dn_utf8, **srv_cn_utf8;
	TALLOC_CTX *ctx;
	ADS_MODLIST mods;
	const char *attrs[] = {"objectGUID", NULL};
	struct GUID guid;
	WERROR win_rc = WERR_OK;
	size_t converted_size;
	const char *printer = pinfo2->sharename;

	/* build the ads mods */
	ctx = talloc_init("nt_printer_publish_ads");
	if (ctx == NULL) {
		return WERR_NOMEM;
	}

	DEBUG(5, ("publishing printer %s\n", printer));

	/* figure out where to publish */
	ads_find_machine_acct(ads, &res, lp_netbios_name());

	/* We use ldap_get_dn here as we need the answer
	 * in utf8 to call ldap_explode_dn(). JRA. */

	srv_dn_utf8 = ldap_get_dn((LDAP *)ads->ldap.ld, (LDAPMessage *)res);
	if (!srv_dn_utf8) {
		TALLOC_FREE(ctx);
		return WERR_SERVER_UNAVAILABLE;
	}
	ads_msgfree(ads, res);
	srv_cn_utf8 = ldap_explode_dn(srv_dn_utf8, 1);
	if (!srv_cn_utf8) {
		TALLOC_FREE(ctx);
		ldap_memfree(srv_dn_utf8);
		return WERR_SERVER_UNAVAILABLE;
	}
	/* Now convert to CH_UNIX. */
	if (!pull_utf8_talloc(ctx, &srv_dn, srv_dn_utf8, &converted_size)) {
		TALLOC_FREE(ctx);
		ldap_memfree(srv_dn_utf8);
		ldap_memfree(srv_cn_utf8);
		return WERR_SERVER_UNAVAILABLE;
	}
	if (!pull_utf8_talloc(ctx, &srv_cn_0, srv_cn_utf8[0], &converted_size)) {
		TALLOC_FREE(ctx);
		ldap_memfree(srv_dn_utf8);
		ldap_memfree(srv_cn_utf8);
		TALLOC_FREE(srv_dn);
		return WERR_SERVER_UNAVAILABLE;
	}

	ldap_memfree(srv_dn_utf8);
	ldap_memfree(srv_cn_utf8);

	srv_cn_escaped = escape_rdn_val_string_alloc(srv_cn_0);
	if (!srv_cn_escaped) {
		TALLOC_FREE(ctx);
		return WERR_SERVER_UNAVAILABLE;
	}
	sharename_escaped = escape_rdn_val_string_alloc(printer);
	if (!sharename_escaped) {
		SAFE_FREE(srv_cn_escaped);
		TALLOC_FREE(ctx);
		return WERR_SERVER_UNAVAILABLE;
	}

	prt_dn = talloc_asprintf(ctx, "cn=%s-%s,%s", srv_cn_escaped, sharename_escaped, srv_dn);

	SAFE_FREE(srv_cn_escaped);
	SAFE_FREE(sharename_escaped);

	mods = ads_init_mods(ctx);

	if (mods == NULL) {
		SAFE_FREE(prt_dn);
		TALLOC_FREE(ctx);
		return WERR_NOMEM;
	}

	ads_mod_str(ctx, &mods, SPOOL_REG_PRINTERNAME, printer);

	/* publish it */
	ads_rc = ads_mod_printer_entry(ads, prt_dn, ctx, &mods);
	if (ads_rc.err.rc == LDAP_NO_SUCH_OBJECT) {
		int i;
		for (i=0; mods[i] != 0; i++)
			;
		mods[i] = (LDAPMod *)-1;
		ads_rc = ads_add_printer_entry(ads, prt_dn, ctx, &mods);
	}

	if (!ADS_ERR_OK(ads_rc)) {
		DEBUG(3, ("error publishing %s: %s\n",
			  printer, ads_errstr(ads_rc)));
	}

	/* retreive the guid and store it locally */
	if (ADS_ERR_OK(ads_search_dn(ads, &res, prt_dn, attrs))) {
		bool guid_ok;
		ZERO_STRUCT(guid);
		guid_ok = ads_pull_guid(ads, res, &guid);
		ads_msgfree(ads, res);
		if (guid_ok) {
			store_printer_guid(msg_ctx, printer, guid);
		}
	}
	TALLOC_FREE(ctx);

	return win_rc;
}
コード例 #16
0
ファイル: ldap.c プロジェクト: vmware/lightwave
DWORD
VMCADNToRDNArray(
    PCSTR       pcszDN,
    BOOLEAN     bNoTypes,
    PDWORD      pdwCount,
    PSTR        **pppszRDNArray
    )
{
    DWORD       dwError = 0;
    DWORD       dwCount = 0;
    PSTR        *ppszTemp = NULL;
    PSTR        *ppszRDNArrayLocal = NULL;
    PSTR        *ppszRDNArray = NULL;

    if (IsNullOrEmptyString(pcszDN) ||
        !pdwCount ||
        !pppszRDNArray)
    {
        dwError = ERROR_INVALID_PARAMETER;
        BAIL_ON_VMCA_ERROR(dwError);
    }

    if (bNoTypes)
    {
        ppszRDNArrayLocal = ldap_explode_dn(pcszDN, 1);
    }
    else
    {
        ppszRDNArrayLocal = ldap_explode_dn(pcszDN, 0);
    }

    if (!ppszRDNArrayLocal)
    {
        dwError = VMCA_ERROR_INVALID_ENTRY;
        BAIL_ON_VMCA_ERROR(dwError);
    }

    for (ppszTemp = ppszRDNArrayLocal; *ppszTemp; ++ppszTemp)
    {
        ++dwCount;
    }

    dwError = VMCACopyStringArrayA(
                        &ppszRDNArray,
                        dwCount,
                        ppszRDNArrayLocal,
                        dwCount);
    BAIL_ON_VMCA_ERROR(dwError);


    *pdwCount = dwCount;
    *pppszRDNArray = ppszRDNArray;

cleanup:

    ldap_value_free(ppszRDNArrayLocal);

    return dwError;

error:

    if (pdwCount)
    {
        *pdwCount = 0;
    }
    VMCAFreeStringArrayA(ppszRDNArray, dwCount);
    if (pppszRDNArray)
    {
        *pppszRDNArray = NULL;
    }

    goto cleanup;
}
コード例 #17
0
ファイル: sort.c プロジェクト: FarazShaikh/LikewiseSMB2
int
ldap_sort_entries(
    LDAP	*ld,
    LDAPMessage	**chain,
    LDAP_CONST char	*attr,		/* NULL => sort by DN */
    int		(*cmp) (LDAP_CONST  char *, LDAP_CONST char *)
)
{
	int			i, count = 0;
	struct entrything	*et;
	LDAPMessage		*e, *ehead = NULL, *etail = NULL;
	LDAPMessage		*ohead = NULL, *otail = NULL;
	LDAPMessage		**ep;

	assert( ld != NULL );

	/* Separate entries from non-entries */
	for ( e = *chain; e; e=e->lm_chain ) {
		if ( e->lm_msgtype == LDAP_RES_SEARCH_ENTRY ) {
			count++;
			if ( !ehead ) ehead = e;
			if ( etail ) etail->lm_chain = e;
			etail = e;
		} else {
			if ( !ohead ) ohead = e;
			if ( otail ) otail->lm_chain = e;
			otail = e;
		}
	}

	if ( count < 2 ) {
		/* zero or one entries -- already sorted! */
		if ( ehead ) {
			etail->lm_chain = ohead;
			*chain = ehead;
		} else {
			*chain = ohead;
		}
		return 0;
	}

	if ( (et = (struct entrything *) LDAP_MALLOC( count *
	    sizeof(struct entrything) )) == NULL ) {
		ld->ld_errno = LDAP_NO_MEMORY;
		return( -1 );
	}

	e = ehead;
	for ( i = 0; i < count; i++ ) {
		et[i].et_cmp_fn = cmp;
		et[i].et_msg = e;
		if ( attr == NULL ) {
			char	*dn;

			dn = ldap_get_dn( ld, e );
			et[i].et_vals = ldap_explode_dn( dn, 1 );
			LDAP_FREE( dn );
		} else {
			et[i].et_vals = ldap_get_values( ld, e, attr );
		}

		e = e->lm_chain;
	}

	qsort( et, count, sizeof(struct entrything), et_cmp );

	ep = chain;
	for ( i = 0; i < count; i++ ) {
		*ep = et[i].et_msg;
		ep = &(*ep)->lm_chain;

		LDAP_VFREE( et[i].et_vals );
	}
	*ep = ohead;
	(*chain)->lm_chain_tail = otail ? otail : etail;

	LDAP_FREE( (char *) et );

	return( 0 );
}
コード例 #18
0
ファイル: tmplout.c プロジェクト: andreiw/polaris
static int
do_entry2text(
	LDAP			*ld,
	char			*buf,		/* NULL for use-internal */
	char			*base,		/* used for search actions */
	LDAPMessage		*entry,
	struct ldap_disptmpl	*tmpl,
	char			**defattrs,
	char			***defvals,
	writeptype		writeproc,
	void			*writeparm,
	char			*eol,
	int			rdncount,
	unsigned int		opts,
	char			*urlprefix	/* if non-NULL, do HTML */
)
{
    int				i, err, html, show, labelwidth;
    int				freebuf,  freevals;
    char			*dn, **vals;
    struct ldap_tmplitem	*rowp, *colp;

    if (( dn = ldap_get_dn( ld, entry )) == NULL ) {
	return( ld->ld_errno );
    }

    if ( buf == NULL ) {
	if (( buf = malloc( LDAP_DTMPL_BUFSIZ )) == NULL ) {
	    ld->ld_errno = LDAP_NO_MEMORY;
	    free( dn );
	    return( ld->ld_errno );
	}
	freebuf = 1;
    } else {
	freebuf = 0;
    }

    html = ( urlprefix != NULL );

    if ( html ) {
	/*
	 * add HTML intro. and title
	 */
	if (!(( opts & LDAP_DISP_OPT_HTMLBODYONLY ) != 0 )) {
	    sprintf( buf, "<HTML>%s<HEAD>%s<TITLE>%s%s - ", eol, eol, eol,
		    ( tmpl == NULL ) ? "Entry" : tmpl->dt_name );
	    (*writeproc)( writeparm, buf, strlen( buf ));
	    output_dn( buf, dn, 0, rdncount, writeproc, writeparm, "", NULL );
	    sprintf( buf, "%s</TITLE>%s</HEAD>%s<BODY>%s<H3>%s - ", eol, eol,
		    eol, eol, ( tmpl == NULL ) ? "Entry" : tmpl->dt_name );
	    (*writeproc)( writeparm, buf, strlen( buf ));
	    output_dn( buf, dn, 0, rdncount, writeproc, writeparm, "", NULL );
	    sprintf( buf, "</H3>%s", eol );
	    (*writeproc)( writeparm, buf, strlen( buf ));
	}

	if (( opts & LDAP_DISP_OPT_NONLEAF ) != 0 &&
		( vals = ldap_explode_dn( dn, 0 )) != NULL ) {
	    char	*untagged;

	    /*
	     * add "Move Up" link
	     */
	    sprintf( buf, "<A HREF=\"%s", urlprefix );
	    for ( i = 1; vals[ i ] != NULL; ++i ) {
		if ( i > 1 ) {
		     strcat_escaped( buf, ", " );
		}
		strcat_escaped( buf, vals[ i ] );
	    }
	    if ( vals[ 1 ] != NULL ) {
		untagged = strchr( vals[ 1 ], '=' );
	    } else {
		untagged = "=The World";
	    }
	    sprintf( buf + strlen( buf ),
		    "%s\">Move Up To <EM>%s</EM></A>%s<BR>",
		    ( vals[ 1 ] == NULL ) ? "??one" : "",
		    ( untagged != NULL ) ? untagged + 1 : vals[ 1 ], eol, eol );
	    (*writeproc)( writeparm, buf, strlen( buf ));

	    /*
	     * add "Browse" link
	     */
	    untagged = strchr( vals[ 0 ], '=' );
	    sprintf( buf, "<A HREF=\"%s", urlprefix );
	    strcat_escaped( buf, dn );
	    sprintf( buf + strlen( buf ), "??one?(!(objectClass=dsa))\">Browse Below <EM>%s</EM></A>%s%s",
		    ( untagged != NULL ) ? untagged + 1 : vals[ 0 ], eol, eol );
	    (*writeproc)( writeparm, buf, strlen( buf ));

	    ldap_value_free( vals );
	}

	(*writeproc)( writeparm, "<HR>", 4 );	/* horizontal rule */
    } else {
	(*writeproc)( writeparm, "\"", 1 );
	output_dn( buf, dn, 0, rdncount, writeproc, writeparm, "", NULL );
	sprintf( buf, "\"%s", eol );
	(*writeproc)( writeparm, buf, strlen( buf ));
    }

    if ( tmpl != NULL && ( opts & LDAP_DISP_OPT_AUTOLABELWIDTH ) != 0 ) {
	labelwidth = max_label_len( tmpl ) + 3;
    } else {
	labelwidth = DEF_LABEL_WIDTH;;
    }

    err = LDAP_SUCCESS;

    if ( tmpl == NULL ) {
	BerElement	*ber;
	char		*attr;

	ber = NULL;
	for ( attr = ldap_first_attribute( ld, entry, &ber );
		NONFATAL_LDAP_ERR( err ) && attr != NULL;
		attr = ldap_next_attribute( ld, entry, ber )) {
	    if (( vals = ldap_get_values( ld, entry, attr )) == NULL ) {
		freevals = 0;
		if ( defattrs != NULL ) {
		    for ( i = 0; defattrs[ i ] != NULL; ++i ) {
			if ( strcasecmp( attr, defattrs[ i ] ) == 0 ) {
			    break;
			}
		    }
		    if ( defattrs[ i ] != NULL ) {
			vals = defvals[ i ];
		    }
		}
	    } else {
		freevals = 1;
	    }

	    if ( islower( *attr )) {	/* cosmetic -- upcase attr. name */
		*attr = toupper( *attr );
	    }

	    err = do_vals2text( ld, buf, vals, attr, labelwidth,
		    LDAP_SYN_CASEIGNORESTR, writeproc, writeparm, eol, 
		    rdncount, urlprefix );
	    if ( freevals ) {
		ldap_value_free( vals );
	    }
	}
    } else {
	for ( rowp = ldap_first_tmplrow( tmpl );
		NONFATAL_LDAP_ERR( err ) && rowp != NULLTMPLITEM;
		rowp = ldap_next_tmplrow( tmpl, rowp )) {
	    for ( colp = ldap_first_tmplcol( tmpl, rowp ); colp != NULLTMPLITEM;
		    colp = ldap_next_tmplcol( tmpl, rowp, colp )) {
		vals = NULL;
		if ( colp->ti_attrname == NULL || ( vals = ldap_get_values( ld,
			entry, colp->ti_attrname )) == NULL ) {
		    freevals = 0;
		    if ( !LDAP_IS_TMPLITEM_OPTION_SET( colp,
			    LDAP_DITEM_OPT_HIDEIFEMPTY ) && defattrs != NULL
			    && colp->ti_attrname != NULL ) {
			for ( i = 0; defattrs[ i ] != NULL; ++i ) {
			    if ( strcasecmp( colp->ti_attrname, defattrs[ i ] )
				    == 0 ) {
				break;
			    }
			}
			if ( defattrs[ i ] != NULL ) {
			    vals = defvals[ i ];
			}
		    }
		} else {
		    freevals = 1;
		    if ( LDAP_IS_TMPLITEM_OPTION_SET( colp,
			    LDAP_DITEM_OPT_SORTVALUES ) && vals[ 0 ] != NULL
			    && vals[ 1 ] != NULL ) {
			ldap_sort_values( ld, vals, ldap_sort_strcasecmp );
		    }
		}

		/*
		 * don't bother even calling do_vals2text() if no values
		 * or boolean with value false and "hide if false" option set
		 */
		show = ( vals != NULL && vals[ 0 ] != NULL );
		if ( show && LDAP_GET_SYN_TYPE( colp->ti_syntaxid )
			== LDAP_SYN_TYPE_BOOLEAN && LDAP_IS_TMPLITEM_OPTION_SET(
			colp, LDAP_DITEM_OPT_HIDEIFFALSE ) &&
			toupper( vals[ 0 ][ 0 ] ) != 'T' ) {
		    show = 0;
		}

		if ( colp->ti_syntaxid == LDAP_SYN_SEARCHACTION ) {
		    if (( opts & LDAP_DISP_OPT_DOSEARCHACTIONS ) != 0 ) {
			if ( colp->ti_attrname == NULL || ( show &&
				toupper( vals[ 0 ][ 0 ] ) == 'T' )) {
			    err = searchaction( ld, buf, base, entry, dn, colp,
				    labelwidth, rdncount, writeproc,
				    writeparm, eol, urlprefix );
			}
		    }
		    show = 0;
		}

		if ( show ) {
		    err = do_vals2text( ld, buf, vals, colp->ti_label,
			labelwidth, colp->ti_syntaxid, writeproc, writeparm,
			eol, rdncount, urlprefix );
		}

		if ( freevals ) {
		    ldap_value_free( vals );
		}
	    }
	}
    }

    if ( html  && !(( opts & LDAP_DISP_OPT_HTMLBODYONLY ) != 0 )) {
	sprintf( buf, "</BODY>%s</HTML>%s", eol, eol );
	(*writeproc)( writeparm, buf, strlen( buf ));
    }

    free( dn );
    if ( freebuf ) {
	free( buf );
    }

    return( err );
}
コード例 #19
0
static WERROR nt_printer_dn_lookup(TALLOC_CTX *mem_ctx,
				   ADS_STRUCT *ads,
				   const char *printer,
				   char **pprinter_dn)
{
	char *printer_dn = NULL;
	char *srv_dn = NULL;
	char *srv_cn_0 = NULL;
	char *srv_cn_escaped = NULL;
	char *sharename_escaped = NULL;
	char *srv_dn_utf8 = NULL;
	char **srv_cn_utf8 = NULL;
	size_t converted_size;
	ADS_STATUS ads_status;
	LDAPMessage *res;
	WERROR result;
	bool ok;

	ads_status = ads_find_machine_acct(ads, &res, lp_netbios_name());
	if (!ADS_ERR_OK(ads_status)) {
		DEBUG(2, ("Failed to find machine account for %s\n",
			  lp_netbios_name()));
		result = WERR_NOT_FOUND;
		goto err_out;
	}

	/*
	 * We use ldap_get_dn here as we need the answer in utf8 to call
	 * ldap_explode_dn(). JRA.
	 */
	srv_dn_utf8 = ldap_get_dn((LDAP *)ads->ldap.ld, (LDAPMessage *)res);
	ads_msgfree(ads, res);
	if (srv_dn_utf8 == NULL) {
		result = WERR_SERVER_UNAVAILABLE;
		goto err_out;
	}

	srv_cn_utf8 = ldap_explode_dn(srv_dn_utf8, 1);
	if (srv_cn_utf8 == NULL) {
		ldap_memfree(srv_dn_utf8);
		result = WERR_SERVER_UNAVAILABLE;
		goto err_out;
	}

	/* Now convert to CH_UNIX. */
	ok = pull_utf8_talloc(mem_ctx, &srv_dn, srv_dn_utf8, &converted_size);
	ldap_memfree(srv_dn_utf8);
	if (!ok) {
		ldap_memfree(srv_cn_utf8);
		result = WERR_SERVER_UNAVAILABLE;
		goto err_out;
	}

	ok = pull_utf8_talloc(mem_ctx, &srv_cn_0, srv_cn_utf8[0], &converted_size);
	ldap_memfree(srv_cn_utf8);
	if (!ok) {
		result = WERR_SERVER_UNAVAILABLE;
		goto err_out;
	}

	srv_cn_escaped = escape_rdn_val_string_alloc(srv_cn_0);
	if (srv_cn_escaped == NULL) {
		result = WERR_SERVER_UNAVAILABLE;
		goto err_out;
	}

	sharename_escaped = escape_rdn_val_string_alloc(printer);
	if (sharename_escaped == NULL) {
		result = WERR_SERVER_UNAVAILABLE;
		goto err_out;
	}

	printer_dn = talloc_asprintf(mem_ctx,
				     "cn=%s-%s,%s",
				     srv_cn_escaped,
				     sharename_escaped,
				     srv_dn);
	if (printer_dn == NULL) {
		result = WERR_NOMEM;
		goto err_out;
	}

	*pprinter_dn = printer_dn;

	result = WERR_OK;
err_out:
	SAFE_FREE(sharename_escaped);
	SAFE_FREE(srv_cn_escaped);
	TALLOC_FREE(srv_cn_0);
	TALLOC_FREE(srv_dn);
	return result;
}
コード例 #20
0
ファイル: ldap.c プロジェクト: vmware/lightwave
/*
 * convert DN to a list of RDN.
 *
 * say dc=lwraft,dc=local
 * if bNotypes == false, {"dc=vmdir", "dc=local"} is returned;
 * otherwise {"vmdir", "local"} is returned.
 */
DWORD
LwCADNToRDNArray(
    PCSTR               pcszDN,
    BOOLEAN             bNotypes,
    PLWCA_STRING_ARRAY* ppRDNStrArray
    )
{
    DWORD               dwError = 0;
    DWORD               dwCount = 0;
    PLWCA_STRING_ARRAY  pStrArray = NULL;
    PSTR*               ppszRDN = NULL;
    PSTR*               ppszTmp = NULL;
    DWORD               iEntry = 0;

    if (IsNullOrEmptyString(pcszDN) || !ppRDNStrArray)
    {
        dwError = LWCA_ERROR_INVALID_PARAMETER;
        BAIL_ON_LWCA_ERROR(dwError);
    }

    if (bNotypes)
    {
        ppszRDN = ldap_explode_dn(pcszDN, 1);
    }
    else
    {
        ppszRDN = ldap_explode_dn(pcszDN, 0);
    }

    if (!ppszRDN)
    {
        dwError = LWCA_ERROR_INVALID_DN;
        BAIL_ON_LWCA_ERROR(dwError);
    }

    for (ppszTmp = ppszRDN; *ppszTmp; ppszTmp++)
    {
        dwCount++;
    }

    dwError = LwCAAllocateMemory(sizeof(LWCA_STRING_ARRAY), (PVOID*)&pStrArray);
    BAIL_ON_LWCA_ERROR(dwError);

    dwError = LwCAAllocateMemory(sizeof(PSTR) * dwCount, (PVOID*)&pStrArray->ppData);
    BAIL_ON_LWCA_ERROR(dwError);

    pStrArray->dwCount = dwCount;

    for (ppszTmp = ppszRDN; *ppszTmp; ppszTmp++)
    {
        dwError = LwCAAllocateStringA(*ppszTmp, &pStrArray->ppData[iEntry++]);
        BAIL_ON_LWCA_ERROR(dwError);
    }

    *ppRDNStrArray = pStrArray;

cleanup:
    if (ppszRDN)
    {
        ldap_value_free(ppszRDN);
    }

    return dwError;

error:
    LwCAFreeStringArray(pStrArray);
    if (ppRDNStrArray)
    {
        *ppRDNStrArray = NULL;
    }

    goto cleanup;
}
コード例 #21
0
ファイル: net_ads.c プロジェクト: niubl/camera_project
static int net_ads_printer_publish(int argc, const char **argv)
{
        ADS_STRUCT *ads;
        ADS_STATUS rc;
	const char *servername, *printername;
	struct cli_state *cli;
	struct in_addr 		server_ip;
	NTSTATUS nt_status;
	TALLOC_CTX *mem_ctx = talloc_init("net_ads_printer_publish");
	ADS_MODLIST mods = ads_init_mods(mem_ctx);
	char *prt_dn, *srv_dn, **srv_cn;
	void *res = NULL;

	if (!(ads = ads_startup())) {
		return -1;
	}

	if (argc < 1) {
		return net_ads_printer_usage(argc, argv);
	}
	
	printername = argv[0];

	if (argc == 2) {
		servername = argv[1];
	} else {
		servername = global_myname();
	}
		
	/* Get printer data from SPOOLSS */

	resolve_name(servername, &server_ip, 0x20);

	nt_status = cli_full_connection(&cli, global_myname(), servername, 
					&server_ip, 0,
					"IPC$", "IPC",  
					opt_user_name, opt_workgroup,
					opt_password ? opt_password : "", 
					CLI_FULL_CONNECTION_USE_KERBEROS, 
					Undefined, NULL);

	if (NT_STATUS_IS_ERR(nt_status)) {
		d_printf("Unable to open a connnection to %s to obtain data "
			 "for %s\n", servername, printername);
		ads_destroy(&ads);
		return -1;
	}

	/* Publish on AD server */

	ads_find_machine_acct(ads, &res, servername);

	if (ads_count_replies(ads, res) == 0) {
		d_printf("Could not find machine account for server %s\n", 
			 servername);
		ads_destroy(&ads);
		return -1;
	}

	srv_dn = ldap_get_dn(ads->ld, res);
	srv_cn = ldap_explode_dn(srv_dn, 1);

	asprintf(&prt_dn, "cn=%s-%s,%s", srv_cn[0], printername, srv_dn);

	cli_nt_session_open(cli, PI_SPOOLSS);
	get_remote_printer_publishing_data(cli, mem_ctx, &mods, printername);

        rc = ads_add_printer_entry(ads, prt_dn, mem_ctx, &mods);
        if (!ADS_ERR_OK(rc)) {
                d_printf("ads_publish_printer: %s\n", ads_errstr(rc));
		ads_destroy(&ads);
                return -1;
        }
 
        d_printf("published printer\n");
	ads_destroy(&ads);
 
	return 0;
}
コード例 #22
0
ファイル: test.c プロジェクト: cptaffe/openldap
int
main( int argc, char **argv )
{
	LDAP		*ld = NULL;
	int		i, c, port, errflg, method, id, msgtype;
	char		line[256], command1, command2, command3;
	char		passwd[64], dn[256], rdn[64], attr[64], value[256];
	char		filter[256], *host, **types;
	char		**exdn;
	static const char usage[] =
		"usage: %s [-u] [-h host] [-d level] [-s dnsuffix] [-p port] [-t file] [-T file]\n";
	int		bound, all, scope, attrsonly;
	LDAPMessage	*res;
	LDAPMod		**mods, **attrs;
	struct timeval	timeout;
	char		*copyfname = NULL;
	int		copyoptions = 0;
	LDAPURLDesc	*ludp;

	host = NULL;
	port = LDAP_PORT;
	dnsuffix = "";
	errflg = 0;

	while (( c = getopt( argc, argv, "h:d:s:p:t:T:" )) != -1 ) {
		switch( c ) {
		case 'd':
#ifdef LDAP_DEBUG
			ldap_debug = atoi( optarg );
#ifdef LBER_DEBUG
			if ( ldap_debug & LDAP_DEBUG_PACKETS ) {
				ber_set_option( NULL, LBER_OPT_DEBUG_LEVEL, &ldap_debug );
			}
#endif
#else
			printf( "Compile with -DLDAP_DEBUG for debugging\n" );
#endif
			break;

		case 'h':
			host = optarg;
			break;

		case 's':
			dnsuffix = optarg;
			break;

		case 'p':
			port = atoi( optarg );
			break;

		case 't':	/* copy ber's to given file */
			copyfname = strdup( optarg );
/*			copyoptions = LBER_TO_FILE; */
			break;

		case 'T':	/* only output ber's to given file */
			copyfname = strdup( optarg );
/*			copyoptions = (LBER_TO_FILE | LBER_TO_FILE_ONLY); */
			break;

		default:
		    ++errflg;
		}
	}

	if ( host == NULL && optind == argc - 1 ) {
		host = argv[ optind ];
		++optind;
	}

	if ( errflg || optind < argc - 1 ) {
		fprintf( stderr, usage, argv[ 0 ] );
		exit( EXIT_FAILURE );
	}
	
	printf( "ldap_init( %s, %d )\n",
		host == NULL ? "(null)" : host, port );

	ld = ldap_init( host, port );

	if ( ld == NULL ) {
		perror( "ldap_init" );
		exit( EXIT_FAILURE );
	}

	if ( copyfname != NULL ) {
		if ( ( ld->ld_sb->sb_fd = open( copyfname, O_WRONLY|O_CREAT|O_EXCL,
		    0600 ))  == -1 ) {
			perror( copyfname );
			exit ( EXIT_FAILURE );
		}
		ld->ld_sb->sb_options = copyoptions;
	}

	bound = 0;
	timeout.tv_sec = 0;
	timeout.tv_usec = 0;

	(void) memset( line, '\0', sizeof(line) );
	while ( get_line( line, sizeof(line), stdin, "\ncommand? " ) != NULL ) {
		command1 = line[0];
		command2 = line[1];
		command3 = line[2];

		switch ( command1 ) {
		case 'a':	/* add or abandon */
			switch ( command2 ) {
			case 'd':	/* add */
				get_line( dn, sizeof(dn), stdin, "dn? " );
				strcat( dn, dnsuffix );
				if ( (attrs = get_modlist( NULL, "attr? ",
				    "value? " )) == NULL )
					break;
				if ( (id = ldap_add( ld, dn, attrs )) == -1 )
					ldap_perror( ld, "ldap_add" );
				else
					printf( "Add initiated with id %d\n",
					    id );
				break;

			case 'b':	/* abandon */
				get_line( line, sizeof(line), stdin, "msgid? " );
				id = atoi( line );
				if ( ldap_abandon( ld, id ) != 0 )
					ldap_perror( ld, "ldap_abandon" );
				else
					printf( "Abandon successful\n" );
				break;
			default:
				printf( "Possibilities: [ad]d, [ab]ort\n" );
			}
			break;

		case 'b':	/* asynch bind */
			method = LDAP_AUTH_SIMPLE;
			get_line( dn, sizeof(dn), stdin, "dn? " );
			strcat( dn, dnsuffix );

			if ( method == LDAP_AUTH_SIMPLE && dn[0] != '\0' )
				get_line( passwd, sizeof(passwd), stdin,
				    "password? " );
			else
				passwd[0] = '\0';

			if ( ldap_bind( ld, dn, passwd, method ) == -1 ) {
				fprintf( stderr, "ldap_bind failed\n" );
				ldap_perror( ld, "ldap_bind" );
			} else {
				printf( "Bind initiated\n" );
				bound = 1;
			}
			break;

		case 'B':	/* synch bind */
			method = LDAP_AUTH_SIMPLE;
			get_line( dn, sizeof(dn), stdin, "dn? " );
			strcat( dn, dnsuffix );

			if ( dn[0] != '\0' )
				get_line( passwd, sizeof(passwd), stdin,
				    "password? " );
			else
				passwd[0] = '\0';

			if ( ldap_bind_s( ld, dn, passwd, method ) !=
			    LDAP_SUCCESS ) {
				fprintf( stderr, "ldap_bind_s failed\n" );
				ldap_perror( ld, "ldap_bind_s" );
			} else {
				printf( "Bind successful\n" );
				bound = 1;
			}
			break;

		case 'c':	/* compare */
			get_line( dn, sizeof(dn), stdin, "dn? " );
			strcat( dn, dnsuffix );
			get_line( attr, sizeof(attr), stdin, "attr? " );
			get_line( value, sizeof(value), stdin, "value? " );

			if ( (id = ldap_compare( ld, dn, attr, value )) == -1 )
				ldap_perror( ld, "ldap_compare" );
			else
				printf( "Compare initiated with id %d\n", id );
			break;

		case 'd':	/* turn on debugging */
#ifdef LDAP_DEBUG
			get_line( line, sizeof(line), stdin, "debug level? " );
			ldap_debug = atoi( line );
#ifdef LBER_DEBUG
			if ( ldap_debug & LDAP_DEBUG_PACKETS ) {
				ber_set_option( NULL, LBER_OPT_DEBUG_LEVEL, &ldap_debug );
			}
#endif
#else
			printf( "Compile with -DLDAP_DEBUG for debugging\n" );
#endif
			break;

		case 'E':	/* explode a dn */
			get_line( line, sizeof(line), stdin, "dn? " );
			exdn = ldap_explode_dn( line, 0 );
			for ( i = 0; exdn != NULL && exdn[i] != NULL; i++ ) {
				printf( "\t%s\n", exdn[i] );
			}
			break;

		case 'g':	/* set next msgid */
			get_line( line, sizeof(line), stdin, "msgid? " );
			ld->ld_msgid = atoi( line );
			break;

		case 'v':	/* set version number */
			get_line( line, sizeof(line), stdin, "version? " );
			ld->ld_version = atoi( line );
			break;

		case 'm':	/* modify or modifyrdn */
			if ( strncmp( line, "modify", 4 ) == 0 ) {
				get_line( dn, sizeof(dn), stdin, "dn? " );
				strcat( dn, dnsuffix );
				if ( (mods = get_modlist(
				    "mod (0=>add, 1=>delete, 2=>replace -1=>done)? ",
				    "attribute type? ", "attribute value? " ))
				    == NULL )
					break;
				if ( (id = ldap_modify( ld, dn, mods )) == -1 )
					ldap_perror( ld, "ldap_modify" );
				else
					printf( "Modify initiated with id %d\n",
					    id );
			} else if ( strncmp( line, "modrdn", 4 ) == 0 ) {
				get_line( dn, sizeof(dn), stdin, "dn? " );
				strcat( dn, dnsuffix );
				get_line( rdn, sizeof(rdn), stdin, "newrdn? " );
				if ( (id = ldap_modrdn( ld, dn, rdn )) == -1 )
					ldap_perror( ld, "ldap_modrdn" );
				else
					printf( "Modrdn initiated with id %d\n",
					    id );
			} else {
				printf( "Possibilities: [modi]fy, [modr]dn\n" );
			}
			break;

		case 'q':	/* quit */
			ldap_unbind( ld );
			exit( EXIT_SUCCESS );
			break;

		case 'r':	/* result or remove */
			switch ( command3 ) {
			case 's':	/* result */
				get_line( line, sizeof(line), stdin,
				    "msgid (-1=>any)? " );
				if ( line[0] == '\0' )
					id = -1;
				else
					id = atoi( line );
				get_line( line, sizeof(line), stdin,
				    "all (0=>any, 1=>all)? " );
				if ( line[0] == '\0' )
					all = 1;
				else
					all = atoi( line );
				if (( msgtype = ldap_result( ld, id, all,
				    &timeout, &res )) < 1 ) {
					ldap_perror( ld, "ldap_result" );
					break;
				}
				printf( "\nresult: msgtype %d msgid %d\n",
				    msgtype, res->lm_msgid );
				handle_result( ld, res );
				res = NULL;
				break;

			case 'm':	/* remove */
				get_line( dn, sizeof(dn), stdin, "dn? " );
				strcat( dn, dnsuffix );
				if ( (id = ldap_delete( ld, dn )) == -1 )
					ldap_perror( ld, "ldap_delete" );
				else
					printf( "Remove initiated with id %d\n",
					    id );
				break;

			default:
				printf( "Possibilities: [rem]ove, [res]ult\n" );
				break;
			}
			break;

		case 's':	/* search */
			get_line( dn, sizeof(dn), stdin, "searchbase? " );
			strcat( dn, dnsuffix );
			get_line( line, sizeof(line), stdin,
			    "scope (0=baseObject, 1=oneLevel, 2=subtree, 3=children)? " );
			scope = atoi( line );
			get_line( filter, sizeof(filter), stdin,
			    "search filter (e.g. sn=jones)? " );
			types = get_list( "attrs to return? " );
			get_line( line, sizeof(line), stdin,
			    "attrsonly (0=attrs&values, 1=attrs only)? " );
			attrsonly = atoi( line );

			    if (( id = ldap_search( ld, dn, scope, filter,
				    types, attrsonly  )) == -1 ) {
				ldap_perror( ld, "ldap_search" );
			    } else {
				printf( "Search initiated with id %d\n", id );
			    }
			free_list( types );
			break;

		case 't':	/* set timeout value */
			get_line( line, sizeof(line), stdin, "timeout? " );
			timeout.tv_sec = atoi( line );
			break;

		case 'p':	/* parse LDAP URL */
			get_line( line, sizeof(line), stdin, "LDAP URL? " );
			if (( i = ldap_url_parse( line, &ludp )) != 0 ) {
			    fprintf( stderr, "ldap_url_parse: error %d\n", i );
			} else {
			    printf( "\t  host: " );
			    if ( ludp->lud_host == NULL ) {
				printf( "DEFAULT\n" );
			    } else {
				printf( "<%s>\n", ludp->lud_host );
			    }
			    printf( "\t  port: " );
			    if ( ludp->lud_port == 0 ) {
				printf( "DEFAULT\n" );
			    } else {
				printf( "%d\n", ludp->lud_port );
			    }
			    printf( "\t    dn: <%s>\n", ludp->lud_dn );
			    printf( "\t attrs:" );
			    if ( ludp->lud_attrs == NULL ) {
				printf( " ALL" );
			    } else {
				for ( i = 0; ludp->lud_attrs[ i ] != NULL; ++i ) {
				    printf( " <%s>", ludp->lud_attrs[ i ] );
				}
			    }
			    printf( "\n\t scope: %s\n",
					ludp->lud_scope == LDAP_SCOPE_BASE ? "baseObject"
					: ludp->lud_scope == LDAP_SCOPE_ONELEVEL ? "oneLevel"
					: ludp->lud_scope == LDAP_SCOPE_SUBTREE ? "subtree"
#ifdef LDAP_SCOPE_SUBORDINATE
					: ludp->lud_scope == LDAP_SCOPE_SUBORDINATE ? "children"
#endif
					: "**invalid**" );
			    printf( "\tfilter: <%s>\n", ludp->lud_filter );
			    ldap_free_urldesc( ludp );
			}
			    break;

		case 'n':	/* set dn suffix, for convenience */
			get_line( line, sizeof(line), stdin, "DN suffix? " );
			strcpy( dnsuffix, line );
			break;

		case 'o':	/* set ldap options */
			get_line( line, sizeof(line), stdin, "alias deref (0=never, 1=searching, 2=finding, 3=always)?" );
			ld->ld_deref = atoi( line );
			get_line( line, sizeof(line), stdin, "timelimit?" );
			ld->ld_timelimit = atoi( line );
			get_line( line, sizeof(line), stdin, "sizelimit?" );
			ld->ld_sizelimit = atoi( line );

			LDAP_BOOL_ZERO(&ld->ld_options);

			get_line( line, sizeof(line), stdin,
				"Recognize and chase referrals (0=no, 1=yes)?" );
			if ( atoi( line ) != 0 ) {
				LDAP_BOOL_SET(&ld->ld_options, LDAP_BOOL_REFERRALS);
				get_line( line, sizeof(line), stdin,
					"Prompt for bind credentials when chasing referrals (0=no, 1=yes)?" );
				if ( atoi( line ) != 0 ) {
					ldap_set_rebind_proc( ld, bind_prompt, NULL );
				}
			}
			break;

		case '?':	/* help */
			printf(
"Commands: [ad]d         [ab]andon         [b]ind\n"
"          [B]ind async  [c]ompare\n"
"          [modi]fy      [modr]dn          [rem]ove\n"
"          [res]ult      [s]earch          [q]uit/unbind\n\n"
"          [d]ebug       set ms[g]id\n"
"          d[n]suffix    [t]imeout         [v]ersion\n"
"          [?]help       [o]ptions"
"          [E]xplode dn  [p]arse LDAP URL\n" );
			break;

		default:
			printf( "Invalid command.  Type ? for help.\n" );
			break;
		}

		(void) memset( line, '\0', sizeof(line) );
	}

	return( 0 );
}
コード例 #23
0
ファイル: ldap_misc.c プロジェクト: Akasurde/krb5
/* Extract a name from policy_dn, which must be directly under the realm
 * container. */
krb5_error_code
krb5_ldap_policydn_to_name(krb5_context context, const char *policy_dn,
                           char **name_out)
{
    size_t len1, len2, plen;
    krb5_error_code ret;
    kdb5_dal_handle *dal_handle;
    krb5_ldap_context *ldap_context;
    const char *realmdn;

    *name_out = NULL;
    SETUP_CONTEXT();

    realmdn = ldap_context->lrparams->realmdn;
    if (realmdn == NULL)
        return EINVAL;

    /* policyn_dn should be "cn=<policyname>,<realmdn>". */
    len1 = strlen(realmdn);
    len2 = strlen(policy_dn);
    if (len1 == 0 || len2 == 0 || len1 + 1 >= len2)
        return EINVAL;
    plen = len2 - len1 - 1;
    if (policy_dn[plen] != ',' || strcmp(realmdn, policy_dn + plen + 1) != 0)
        return EINVAL;

#if defined HAVE_LDAP_STR2DN
    {
        char *rdn;
        LDAPDN dn;

        rdn = k5memdup0(policy_dn, plen, &ret);
        if (rdn == NULL)
            return ret;
        ret = ldap_str2dn(rdn, &dn, LDAP_DN_FORMAT_LDAPV3 | LDAP_DN_PEDANTIC);
        free(rdn);
        if (ret)
            return EINVAL;
        if (dn[0] == NULL || dn[1] != NULL ||
            dn[0][0]->la_attr.bv_len != 2 ||
            strncasecmp(dn[0][0]->la_attr.bv_val, "cn", 2) != 0) {
            ret = EINVAL;
        } else {
            *name_out = k5memdup0(dn[0][0]->la_value.bv_val,
                                  dn[0][0]->la_value.bv_len, &ret);
        }
        ldap_dnfree(dn);
        return ret;
    }
#elif defined HAVE_LDAP_EXPLODE_DN
    {
        char **parsed_dn;

        /* 1 = return DN components without type prefix */
        parsed_dn = ldap_explode_dn(policy_dn, 1);
        if (parsed_dn == NULL)
            return EINVAL;
        *name_out = strdup(parsed_dn[0]);
        if (*name_out == NULL)
            return ENOMEM;
        ldap_value_free(parsed_dn);
        return 0;
    }
#else
    return EINVAL;
#endif
}
コード例 #24
0
ファイル: test.c プロジェクト: ysangkok/pgp-unix-6.5.8
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#ifdef MACOS
#include <stdlib.h>
#ifdef THINK_C
#include <console.h>
#include <unix.h>
#include <fcntl.h>
#endif /* THINK_C */
#include "macos.h"
#else /* MACOS */
#if defined( DOS ) || defined( _WIN32 )
#ifdef DOS
#include "msdos.h"
#endif
#if defined( WINSOCK ) || defined( _WIN32 )
#include "console.h"
#endif /* WINSOCK */
#else /* DOS */
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <sys/file.h>
#ifndef VMS
#include <fcntl.h>
#include <unistd.h>
#endif /* VMS */
#endif /* DOS */
#endif /* MACOS */

#include "lber.h"
#include "ldap.h"

#if !defined( PCNFS ) && !defined( WINSOCK ) && !defined( MACOS )
#define MOD_USE_BVALS
#endif /* !PCNFS && !WINSOCK && !MACOS */

#ifdef NEEDPROTOS
static void handle_result( LDAP *ld, LDAPMessage *lm );
static void print_ldap_result( LDAP *ld, LDAPMessage *lm, char *s );
static void print_search_entry( LDAP *ld, LDAPMessage *res );
static void free_list( char **list );
#else
static void handle_result();
static void print_ldap_result();
static void print_search_entry();
static void free_list();
#endif /* NEEDPROTOS */

#define NOCACHEERRMSG \
		"don't compile with -DNO_CACHE if you desire local caching"

char *dnsuffix;

#ifndef WINSOCK
static char *
getline( char *line, int len, FILE *fp, char *prompt )
{
    printf(prompt);

    if ( fgets( line, len, fp ) == NULL )
        return( NULL );

    line[ strlen( line ) - 1 ] = '\0';

    return( line );
}
#endif /* WINSOCK */

static char **
get_list( char *prompt )
{
    static char	buf[256];
    int		num;
    char		**result;

    num = 0;
    result = (char **) 0;
    while ( 1 ) {
        getline( buf, sizeof(buf), stdin, prompt );

        if ( *buf == '\0' )
            break;

        if ( result == (char **) 0 )
            result = (char **) malloc( sizeof(char *) );
        else
            result = (char **) realloc( result,
                                        sizeof(char *) * (num + 1) );

        result[num++] = (char *) strdup( buf );
    }
    if ( result == (char **) 0 )
        return( NULL );
    result = (char **) realloc( result, sizeof(char *) * (num + 1) );
    result[num] = NULL;

    return( result );
}


static void
free_list( char **list )
{
    int	i;

    if ( list != NULL ) {
        for ( i = 0; list[ i ] != NULL; ++i ) {
            free( list[ i ] );
        }
        free( (char *)list );
    }
}


#ifdef MOD_USE_BVALS
static int
file_read( char *path, struct berval *bv )
{
    FILE		*fp;
    long		rlen;
    int		eof;

    if (( fp = fopen( path, "r" )) == NULL ) {
        perror( path );
        return( -1 );
    }

    if ( fseek( fp, 0L, SEEK_END ) != 0 ) {
        perror( path );
        fclose( fp );
        return( -1 );
    }

    bv->bv_len = ftell( fp );

    if (( bv->bv_val = (char *)malloc( bv->bv_len )) == NULL ) {
        perror( "malloc" );
        fclose( fp );
        return( -1 );
    }

    if ( fseek( fp, 0L, SEEK_SET ) != 0 ) {
        perror( path );
        fclose( fp );
        return( -1 );
    }

    rlen = fread( bv->bv_val, 1, bv->bv_len, fp );
    eof = feof( fp );
    fclose( fp );

    if ( rlen != bv->bv_len ) {
        perror( path );
        free( bv->bv_val );
        return( -1 );
    }

    return( bv->bv_len );
}
#endif /* MOD_USE_BVALS */


static LDAPMod **
get_modlist( char *prompt1, char *prompt2, char *prompt3 )
{
    static char	buf[256];
    int		num;
    LDAPMod		tmp;
    LDAPMod		**result;
#ifdef MOD_USE_BVALS
    struct berval	**bvals;
#endif /* MOD_USE_BVALS */

    num = 0;
    result = NULL;
    while ( 1 ) {
        if ( prompt1 ) {
            getline( buf, sizeof(buf), stdin, prompt1 );
            tmp.mod_op = atoi( buf );

            if ( tmp.mod_op == -1 || buf[0] == '\0' )
                break;
        }

        getline( buf, sizeof(buf), stdin, prompt2 );
        if ( buf[0] == '\0' )
            break;
        tmp.mod_type = strdup( buf );

        tmp.mod_values = get_list( prompt3 );
#ifdef MOD_USE_BVALS
        if ( tmp.mod_values != NULL ) {
            int	i;

            for ( i = 0; tmp.mod_values[i] != NULL; ++i )
                ;
            bvals = (struct berval **)calloc( i + 1,
                                              sizeof( struct berval *));
            for ( i = 0; tmp.mod_values[i] != NULL; ++i ) {
                bvals[i] = (struct berval *)malloc(
                               sizeof( struct berval ));
                if ( strncmp( tmp.mod_values[i], "{FILE}",
                              6 ) == 0 ) {
                    if ( file_read( tmp.mod_values[i] + 6,
                                    bvals[i] ) < 0 ) {
                        return( NULL );
                    }
                } else {
                    bvals[i]->bv_val = tmp.mod_values[i];
                    bvals[i]->bv_len =
                        strlen( tmp.mod_values[i] );
                }
            }
            tmp.mod_bvalues = bvals;
            tmp.mod_op |= LDAP_MOD_BVALUES;
        }
#endif /* MOD_USE_BVALS */

        if ( result == NULL )
            result = (LDAPMod **) malloc( sizeof(LDAPMod *) );
        else
            result = (LDAPMod **) realloc( result,
                                           sizeof(LDAPMod *) * (num + 1) );

        result[num] = (LDAPMod *) malloc( sizeof(LDAPMod) );
        *(result[num]) = tmp;	/* struct copy */
        num++;
    }
    if ( result == NULL )
        return( NULL );
    result = (LDAPMod **) realloc( result, sizeof(LDAPMod *) * (num + 1) );
    result[num] = NULL;

    return( result );
}


#ifdef LDAP_REFERRALS
int
bind_prompt( LDAP *ld, char **dnp, char **passwdp, int *authmethodp,
             int freeit )
{
    static char	dn[256], passwd[256];

    if ( !freeit ) {
#ifdef KERBEROS
        getline( dn, sizeof(dn), stdin, "re-bind method (0->simple, "
                 "1->krbv41, 2->krbv42, 3->krbv41&2)? " );
        if (( *authmethodp = atoi( dn )) == 3 ) {
            *authmethodp = LDAP_AUTH_KRBV4;
        } else {
            *authmethodp |= 0x80;
        }
#else /* KERBEROS */
        *authmethodp = LDAP_AUTH_SIMPLE;
#endif /* KERBEROS */

        getline( dn, sizeof(dn), stdin, "re-bind dn? " );
        strcat( dn, dnsuffix );
        *dnp = dn;

        if ( *authmethodp == LDAP_AUTH_SIMPLE && dn[0] != '\0' ) {
            getline( passwd, sizeof(passwd), stdin,
                     "re-bind password? " );
        } else {
            passwd[0] = '\0';
        }
        *passwdp = passwd;
    }

    return( LDAP_SUCCESS );
}
#endif /* LDAP_REFERRALS */


int
#ifdef WINSOCK
ldapmain(
#else /* WINSOCK */
main(
#endif /* WINSOCK */
    int argc, char **argv )
{
    LDAP		*ld;
    int		i, c, port, cldapflg, errflg, method, id, msgtype;
    char		line[256], command1, command2, command3;
    char		passwd[64], dn[256], rdn[64], attr[64], value[256];
    char		filter[256], *host, **types;
    char		**exdn;
    char		*usage = "usage: %s [-u] [-h host] [-d level] "
                         "[-s dnsuffix] [-p port] [-t file] [-T file]\n";
    int		bound, all, scope, attrsonly;
    LDAPMessage	*res;
    LDAPMod		**mods, **attrs;
    struct timeval	timeout;
    char		*copyfname = NULL;
    int		copyoptions = 0;
    LDAPURLDesc	*ludp;

    extern char	*optarg;
    extern int	optind;

#ifdef MACOS
    if (( argv = get_list( "cmd line arg?" )) == NULL ) {
        exit( 1 );
    }
    for ( argc = 0; argv[ argc ] != NULL; ++argc ) {
        ;
    }
#endif /* MACOS */

    host = NULL;
    port = LDAP_PORT;
    dnsuffix = "";
    cldapflg = errflg = 0;

    while (( c = getopt( argc, argv, "uh:d:s:p:t:T:" )) != -1 ) {
        switch( c ) {
        case 'u':
#ifdef CLDAP
            cldapflg++;
#else /* CLDAP */
            printf( "Compile with -DCLDAP for UDP support\n" );
#endif /* CLDAP */
            break;

        case 'd':
#ifdef LDAP_DEBUG
            ldap_debug = atoi( optarg );
            if ( ldap_debug & LDAP_DEBUG_PACKETS ) {
                lber_debug = ldap_debug;
            }
#else
            printf( "Compile with -DLDAP_DEBUG for debugging\n" );
#endif
            break;

        case 'h':
            host = optarg;
            break;

        case 's':
            dnsuffix = optarg;
            break;

        case 'p':
            port = atoi( optarg );
            break;

#if !defined(MACOS) && !defined(DOS)
        case 't':	/* copy ber's to given file */
            copyfname = strdup( optarg );
            copyoptions = LBER_TO_FILE;
            break;

        case 'T':	/* only output ber's to given file */
            copyfname = strdup( optarg );
            copyoptions = (LBER_TO_FILE | LBER_TO_FILE_ONLY);
            break;
#endif

        default:
            ++errflg;
        }
    }

    if ( host == NULL && optind == argc - 1 ) {
        host = argv[ optind ];
        ++optind;
    }

    if ( errflg || optind < argc - 1 ) {
        fprintf( stderr, usage, argv[ 0 ] );
        exit( 1 );
    }

    printf( "%sldap_open( %s, %d )\n", cldapflg ? "c" : "",
            host == NULL ? "(null)" : host, port );

    if ( cldapflg ) {
#ifdef CLDAP
        ld = cldap_open( host, port );
#endif /* CLDAP */
    } else {
        ld = ldap_open( host, port );
    }

    if ( ld == NULL ) {
        perror( "ldap_open" );
        exit(1);
    }

#if !defined(MACOS) && !defined(DOS)
    if ( copyfname != NULL ) {
        if ( (ld->ld_sb.sb_fd = open( copyfname, O_WRONLY | O_CREAT,
                                      0600 ))  == -1 ) {
            perror( copyfname );
            exit ( 1 );
        }
        ld->ld_sb.sb_options = copyoptions;
    }
#endif

    bound = 0;
    timeout.tv_sec = 0;
    timeout.tv_usec = 0;

    (void) memset( line, '\0', sizeof(line) );
    while ( getline( line, sizeof(line), stdin, "\ncommand? " ) != NULL ) {
        command1 = line[0];
        command2 = line[1];
        command3 = line[2];

        switch ( command1 ) {
        case 'a':	/* add or abandon */
            switch ( command2 ) {
            case 'd':	/* add */
                getline( dn, sizeof(dn), stdin, "dn? " );
                strcat( dn, dnsuffix );
                if ( (attrs = get_modlist( NULL, "attr? ",
                                           "value? " )) == NULL )
                    break;
                if ( (id = ldap_add( ld, dn, attrs )) == -1 )
                    ldap_perror( ld, "ldap_add" );
                else
                    printf( "Add initiated with id %d\n",
                            id );
                break;

            case 'b':	/* abandon */
                getline( line, sizeof(line), stdin, "msgid? " );
                id = atoi( line );
                if ( ldap_abandon( ld, id ) != 0 )
                    ldap_perror( ld, "ldap_abandon" );
                else
                    printf( "Abandon successful\n" );
                break;
            default:
                printf( "Possibilities: [ad]d, [ab]ort\n" );
            }
            break;

        case 'b':	/* asynch bind */
#ifdef KERBEROS
            getline( line, sizeof(line), stdin,
                     "method (0->simple, 1->krbv41, 2->krbv42)? " );
            method = atoi( line ) | 0x80;
#else /* KERBEROS */
            method = LDAP_AUTH_SIMPLE;
#endif /* KERBEROS */
            getline( dn, sizeof(dn), stdin, "dn? " );
            strcat( dn, dnsuffix );

            if ( method == LDAP_AUTH_SIMPLE && dn[0] != '\0' )
                getline( passwd, sizeof(passwd), stdin,
                         "password? " );
            else
                passwd[0] = '\0';

            if ( ldap_bind( ld, dn, passwd, method ) == -1 ) {
                fprintf( stderr, "ldap_bind failed\n" );
                ldap_perror( ld, "ldap_bind" );
            } else {
                printf( "Bind initiated\n" );
                bound = 1;
            }
            break;

        case 'B':	/* synch bind */
#ifdef KERBEROS
            getline( line, sizeof(line), stdin,
                     "method 0->simple 1->krbv41 2->krbv42 3->krb? " );
            method = atoi( line );
            if ( method == 3 )
                method = LDAP_AUTH_KRBV4;
            else
                method = method | 0x80;
#else /* KERBEROS */
            method = LDAP_AUTH_SIMPLE;
#endif /* KERBEROS */
            getline( dn, sizeof(dn), stdin, "dn? " );
            strcat( dn, dnsuffix );

            if ( dn[0] != '\0' )
                getline( passwd, sizeof(passwd), stdin,
                         "password? " );
            else
                passwd[0] = '\0';

            if ( ldap_bind_s( ld, dn, passwd, method ) !=
                    LDAP_SUCCESS ) {
                fprintf( stderr, "ldap_bind_s failed\n" );
                ldap_perror( ld, "ldap_bind_s" );
            } else {
                printf( "Bind successful\n" );
                bound = 1;
            }
            break;

        case 'c':	/* compare */
            getline( dn, sizeof(dn), stdin, "dn? " );
            strcat( dn, dnsuffix );
            getline( attr, sizeof(attr), stdin, "attr? " );
            getline( value, sizeof(value), stdin, "value? " );

            if ( (id = ldap_compare( ld, dn, attr, value )) == -1 )
                ldap_perror( ld, "ldap_compare" );
            else
                printf( "Compare initiated with id %d\n", id );
            break;

        case 'd':	/* turn on debugging */
#ifdef LDAP_DEBUG
            getline( line, sizeof(line), stdin, "debug level? " );
            ldap_debug = atoi( line );
            if ( ldap_debug & LDAP_DEBUG_PACKETS ) {
                lber_debug = ldap_debug;
            }
#else
            printf( "Compile with -DLDAP_DEBUG for debugging\n" );
#endif
            break;

        case 'E':	/* explode a dn */
            getline( line, sizeof(line), stdin, "dn? " );
            exdn = ldap_explode_dn( line, 0 );
            for ( i = 0; exdn != NULL && exdn[i] != NULL; i++ ) {
                printf( "\t%s\n", exdn[i] );
            }
            break;

        case 'g':	/* set next msgid */
            getline( line, sizeof(line), stdin, "msgid? " );
            ld->ld_msgid = atoi( line );
            break;

        case 'v':	/* set version number */
            getline( line, sizeof(line), stdin, "version? " );
            ld->ld_version = atoi( line );
            break;

        case 'm':	/* modify or modifyrdn */
            if ( strncmp( line, "modify", 4 ) == 0 ) {
                getline( dn, sizeof(dn), stdin, "dn? " );
                strcat( dn, dnsuffix );
                if ( (mods = get_modlist(
                                 "mod (0=>add, 1=>delete, 2=>replace -1=>done)? ",
                                 "attribute type? ", "attribute value? " ))
                        == NULL )
                    break;
                if ( (id = ldap_modify( ld, dn, mods )) == -1 )
                    ldap_perror( ld, "ldap_modify" );
                else
                    printf( "Modify initiated with id %d\n",
                            id );
            } else if ( strncmp( line, "modrdn", 4 ) == 0 ) {
                getline( dn, sizeof(dn), stdin, "dn? " );
                strcat( dn, dnsuffix );
                getline( rdn, sizeof(rdn), stdin, "newrdn? " );
                if ( (id = ldap_modrdn( ld, dn, rdn )) == -1 )
                    ldap_perror( ld, "ldap_modrdn" );
                else
                    printf( "Modrdn initiated with id %d\n",
                            id );
            } else {
                printf( "Possibilities: [modi]fy, [modr]dn\n" );
            }
            break;

        case 'q':	/* quit */
#ifdef CLDAP
            if ( cldapflg )
                cldap_close( ld );
#endif /* CLDAP */
#ifdef LDAP_REFERRALS
            if ( !cldapflg )
#else /* LDAP_REFERRALS */
            if ( !cldapflg && bound )
#endif /* LDAP_REFERRALS */
                ldap_unbind( ld );
            exit( 0 );
            break;

        case 'r':	/* result or remove */
            switch ( command3 ) {
            case 's':	/* result */
                getline( line, sizeof(line), stdin,
                         "msgid (-1=>any)? " );
                if ( line[0] == '\0' )
                    id = -1;
                else
                    id = atoi( line );
                getline( line, sizeof(line), stdin,
                         "all (0=>any, 1=>all)? " );
                if ( line[0] == '\0' )
                    all = 1;
                else
                    all = atoi( line );
                if (( msgtype = ldap_result( ld, id, all,
                                             &timeout, &res )) < 1 ) {
                    ldap_perror( ld, "ldap_result" );
                    break;
                }
                printf( "\nresult: msgtype %d msgid %d\n",
                        msgtype, res->lm_msgid );
                handle_result( ld, res );
                res = NULLMSG;
                break;

            case 'm':	/* remove */
                getline( dn, sizeof(dn), stdin, "dn? " );
                strcat( dn, dnsuffix );
                if ( (id = ldap_delete( ld, dn )) == -1 )
                    ldap_perror( ld, "ldap_delete" );
                else
                    printf( "Remove initiated with id %d\n",
                            id );
                break;

            default:
                printf( "Possibilities: [rem]ove, [res]ult\n" );
                break;
            }
            break;

        case 's':	/* search */
            getline( dn, sizeof(dn), stdin, "searchbase? " );
            strcat( dn, dnsuffix );
            getline( line, sizeof(line), stdin,
                     "scope (0=Base, 1=One Level, 2=Subtree)? " );
            scope = atoi( line );
            getline( filter, sizeof(filter), stdin,
                     "search filter (e.g. sn=jones)? " );
            types = get_list( "attrs to return? " );
            getline( line, sizeof(line), stdin,
                     "attrsonly (0=attrs&values, 1=attrs only)? " );
            attrsonly = atoi( line );

            if ( cldapflg ) {
#ifdef CLDAP
                getline( line, sizeof(line), stdin,
                         "Requestor DN (for logging)? " );
                if ( cldap_search_s( ld, dn, scope, filter, types,
                                     attrsonly, &res, line ) != 0 ) {
                    ldap_perror( ld, "cldap_search_s" );
                } else {
                    printf( "\nresult: msgid %d\n",
                            res->lm_msgid );
                    handle_result( ld, res );
                    res = NULLMSG;
                }
#endif /* CLDAP */
            } else {
                if (( id = ldap_search( ld, dn, scope, filter,
                                        types, attrsonly  )) == -1 ) {
                    ldap_perror( ld, "ldap_search" );
                } else {
                    printf( "Search initiated with id %d\n", id );
                }
            }
            free_list( types );
            break;

        case 't':	/* set timeout value */
            getline( line, sizeof(line), stdin, "timeout? " );
            timeout.tv_sec = atoi( line );
            break;

        case 'U':	/* set ufn search prefix */
            getline( line, sizeof(line), stdin, "ufn prefix? " );
            ldap_ufn_setprefix( ld, line );
            break;

        case 'u':	/* user friendly search w/optional timeout */
            getline( dn, sizeof(dn), stdin, "ufn? " );
            strcat( dn, dnsuffix );
            types = get_list( "attrs to return? " );
            getline( line, sizeof(line), stdin,
                     "attrsonly (0=attrs&values, 1=attrs only)? " );
            attrsonly = atoi( line );

            if ( command2 == 't' ) {
                id = ldap_ufn_search_c( ld, dn, types,
                                        attrsonly, &res, ldap_ufn_timeout,
                                        &timeout );
            } else {
                id = ldap_ufn_search_s( ld, dn, types,
                                        attrsonly, &res );
            }
            if ( res == NULL )
                ldap_perror( ld, "ldap_ufn_search" );
            else {
                printf( "\nresult: err %d\n", id );
                handle_result( ld, res );
                res = NULLMSG;
            }
            free_list( types );
            break;

        case 'l':	/* URL search */
            getline( line, sizeof(line), stdin,
                     "attrsonly (0=attrs&values, 1=attrs only)? " );
            attrsonly = atoi( line );
            getline( line, sizeof(line), stdin, "LDAP URL? " );
            if (( id = ldap_url_search( ld, line, attrsonly  ))
                    == -1 ) {
                ldap_perror( ld, "ldap_url_search" );
            } else {
                printf( "URL search initiated with id %d\n", id );
            }
            break;

        case 'p':	/* parse LDAP URL */
            getline( line, sizeof(line), stdin, "LDAP URL? " );
            if (( i = ldap_url_parse( line, &ludp )) != 0 ) {
                fprintf( stderr, "ldap_url_parse: error %d\n", i );
            } else {
                printf( "\t  host: " );
                if ( ludp->lud_host == NULL ) {
                    printf( "DEFAULT\n" );
                } else {
                    printf( "<%s>\n", ludp->lud_host );
                }
                printf( "\t  port: " );
                if ( ludp->lud_port == 0 ) {
                    printf( "DEFAULT\n" );
                } else {
                    printf( "%d\n", ludp->lud_port );
                }
                printf( "\t    dn: <%s>\n", ludp->lud_dn );
                printf( "\t attrs:" );
                if ( ludp->lud_attrs == NULL ) {
                    printf( " ALL" );
                } else {
                    for ( i = 0; ludp->lud_attrs[ i ] != NULL; ++i ) {
                        printf( " <%s>", ludp->lud_attrs[ i ] );
                    }
                }
                printf( "\n\t scope: %s\n",
                        ludp->lud_scope == LDAP_SCOPE_ONELEVEL ? "ONE"
                        : ludp->lud_scope == LDAP_SCOPE_BASE ? "BASE" :
                        ludp->lud_scope == LDAP_SCOPE_SUBTREE ? "SUB" :
                        "**invalid**" );
                printf( "\tfilter: <%s>\n", ludp->lud_filter );
                ldap_free_urldesc( ludp );
            }
            break;

        case 'n':	/* set dn suffix, for convenience */
            getline( line, sizeof(line), stdin, "DN suffix? " );
            strcpy( dnsuffix, line );
            break;

        case 'e':	/* enable cache */
#ifdef NO_CACHE
            printf( NOCACHEERRMSG );
#else /* NO_CACHE */
            getline( line, sizeof(line), stdin,
                     "Cache timeout (secs)? " );
            i = atoi( line );
            getline( line, sizeof(line), stdin,
                     "Maximum memory to use (bytes)? " );
            if ( ldap_enable_cache( ld, i, atoi( line )) == 0 ) {
                printf( "local cache is on\n" );
            } else {
                printf( "ldap_enable_cache failed\n" );
            }
#endif /* NO_CACHE */
            break;

        case 'x':	/* uncache entry */
#ifdef NO_CACHE
            printf( NOCACHEERRMSG );
#else /* NO_CACHE */
            getline( line, sizeof(line), stdin, "DN? " );
            ldap_uncache_entry( ld, line );
#endif /* NO_CACHE */
            break;

        case 'X':	/* uncache request */
#ifdef NO_CACHE
            printf( NOCACHEERRMSG );
#else /* NO_CACHE */
            getline( line, sizeof(line), stdin, "request msgid? " );
            ldap_uncache_request( ld, atoi( line ));
#endif /* NO_CACHE */
            break;

        case 'o':	/* set ldap options */
            getline( line, sizeof(line), stdin,
                     "alias deref (0=never, 1=searching, 2"
                     "=finding, 3=always)?" );
            ld->ld_deref = atoi( line );
            getline( line, sizeof(line), stdin, "timelimit?" );
            ld->ld_timelimit = atoi( line );
            getline( line, sizeof(line), stdin, "sizelimit?" );
            ld->ld_sizelimit = atoi( line );

            ld->ld_options = 0;

#ifdef STR_TRANSLATION
            getline( line, sizeof(line), stdin,
                     "Automatic translation of T.61 strings "
                     "(0=no, 1=yes)?" );
            if ( atoi( line ) == 0 ) {
                ld->ld_lberoptions &= ~LBER_TRANSLATE_STRINGS;
            } else {
                ld->ld_lberoptions |= LBER_TRANSLATE_STRINGS;
#ifdef LDAP_CHARSET_8859
                getline( line, sizeof(line), stdin,
                         "Translate to/from ISO-8859 "
                         "(0=no, 1=yes?" );
                if ( atoi( line ) != 0 ) {
                    ldap_set_string_translators( ld,
                                                 ldap_8859_to_t61,
                                                 ldap_t61_to_8859 );
                }
#endif /* LDAP_CHARSET_8859 */
            }
#endif /* STR_TRANSLATION */

#ifdef LDAP_DNS
            getline( line, sizeof(line), stdin,
                     "Use DN & DNS to determine where to send "
                     "requests (0=no, 1=yes)?" );
            if ( atoi( line ) != 0 ) {
                ld->ld_options |= LDAP_OPT_DNS;
            }
#endif /* LDAP_DNS */

#ifdef LDAP_REFERRALS
            getline( line, sizeof(line), stdin,
                     "Recognize and chase referrals (0=no, 1=yes)?");
            if ( atoi( line ) != 0 ) {
                ld->ld_options |= LDAP_OPT_REFERRALS;
                getline( line, sizeof(line), stdin,
                         "Prompt for bind credentials when "
                         "chasing referrals (0=no, 1=yes)?" );
                if ( atoi( line ) != 0 ) {
                    ldap_set_rebind_proc( ld, bind_prompt );
                }
            }
#endif /* LDAP_REFERRALS */
            break;

        case 'O':	/* set cache options */
#ifdef NO_CACHE
            printf( NOCACHEERRMSG );
#else /* NO_CACHE */
            getline( line, sizeof(line), stdin,
                     "cache errors (0=smart, 1=never, 2=always)?" );
            switch( atoi( line )) {
            case 0:
                ldap_set_cache_options( ld, 0 );
                break;
            case 1:
                ldap_set_cache_options( ld,
                                        LDAP_CACHE_OPT_CACHENOERRS );
                break;
            case 2:
                ldap_set_cache_options( ld,
                                        LDAP_CACHE_OPT_CACHEALLERRS );
                break;
            default:
                printf( "not a valid cache option\n" );
            }
#endif /* NO_CACHE */
            break;

        case '?':	/* help */
            printf( "Commands: [ad]d         [ab]andon         [b]ind\n" );
            printf( "          [B]ind async  [c]ompare         [l]URL search\n" );
            printf( "          [modi]fy      [modr]dn          [rem]ove\n" );
            printf( "          [res]ult      [s]earch          [q]uit/unbind\n\n" );
            printf( "          [u]fn search  [ut]fn search with timeout\n" );
            printf( "          [d]ebug       [e]nable cache    set ms[g]id\n" );
            printf( "          d[n]suffix    [t]imeout         [v]ersion\n" );
            printf( "          [U]fn prefix  [x]uncache entry  [X]uncache request\n" );
            printf( "          [?]help       [o]ptions         [O]cache options\n" );
            printf( "          [E]xplode dn  [p]arse LDAP URL\n" );
            break;

        default:
            printf( "Invalid command.  Type ? for help.\n" );
            break;
        }

        (void) memset( line, '\0', sizeof(line) );
    }

    return( 0 );
}