Exemple #1
0
Filter *
str2filter_x( Operation *op, const char *str )
{
	int rc;
	Filter	*f = NULL;
	BerElementBuffer berbuf;
	BerElement *ber = (BerElement *)&berbuf;
	const char *text = NULL;

	Debug( LDAP_DEBUG_FILTER, "str2filter \"%s\"\n", str, 0, 0 );

	if ( str == NULL || *str == '\0' ) {
		return NULL;
	}

	ber_init2( ber, NULL, LBER_USE_DER );
	if ( op->o_tmpmemctx ) {
		ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
	}

	rc = ldap_pvt_put_filter( ber, str );
	if( rc < 0 ) {
		goto done;
	}

	ber_reset( ber, 1 );

	rc = get_filter( op, ber, &f, &text );

done:
	ber_free_buf( ber );

	return f;
}
Exemple #2
0
void (lutil_debug)( int debug, int level, const char *fmt, ... )
{
    char buffer[4096];
    va_list vl;

    if ( !(level & debug ) ) return;

#ifdef HAVE_WINSOCK
    if( log_file == NULL ) {
        log_file = fopen( LDAP_RUNDIR LDAP_DIRSEP "openldap.log", "w" );

        if ( log_file == NULL ) {
            log_file = fopen( "openldap.log", "w" );
            if ( log_file == NULL ) return;
        }

        ber_set_option( NULL, LBER_OPT_LOG_PRINT_FILE, log_file );
    }
#endif

    va_start( vl, fmt );
    vsnprintf( buffer, sizeof(buffer), fmt, vl );
    buffer[sizeof(buffer)-1] = '\0';
    if( log_file != NULL ) {
        fputs( buffer, log_file );
        fflush( log_file );
    }
    fputs( buffer, stderr );
    va_end( vl );
}
Exemple #3
0
int lutil_debug_file( FILE *file )
{
    log_file = file;
    ber_set_option( NULL, LBER_OPT_LOG_PRINT_FILE, file );

    return 0;
}
Exemple #4
0
void
slap_sl_mem_init()
{
	assert( Align == 1 << Align_log2 );

	ber_set_option( NULL, LBER_OPT_MEMORY_FNS, &slap_sl_mfuncs );
}
Exemple #5
0
int slap_read_controls(
	Operation *op,
	SlapReply *rs,
	Entry *e,
	const struct berval *oid,
	LDAPControl **ctrl )
{
	int rc;
	struct berval bv;
	BerElementBuffer berbuf;
	BerElement *ber = (BerElement *) &berbuf;
	LDAPControl c;
	Operation myop;

	Debug( LDAP_DEBUG_ANY, "%s slap_read_controls: (%s) %s\n",
		op->o_log_prefix, oid->bv_val, e->e_dn );

	rs->sr_entry = e;
	rs->sr_attrs = ( oid == &slap_pre_read_bv ) ?
		op->o_preread_attrs : op->o_postread_attrs;

	bv.bv_len = entry_flatsize( rs->sr_entry, 0 );
	bv.bv_val = op->o_tmpalloc( bv.bv_len, op->o_tmpmemctx );

	ber_init2( ber, &bv, LBER_USE_DER );
	ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );

	/* create new operation */
	myop = *op;
	/* FIXME: o_bd needed for ACL */
	myop.o_bd = op->o_bd;
	myop.o_res_ber = ber;
	myop.o_callback = NULL;
	myop.ors_slimit = 1;
	myop.ors_attrsonly = 0;

	rc = slap_send_search_entry( &myop, rs );
	if( rc ) return rc;

	rc = ber_flatten2( ber, &c.ldctl_value, 0 );

	if( rc == -1 ) return LDAP_OTHER;

	c.ldctl_oid = oid->bv_val;
	c.ldctl_iscritical = 0;

	if ( *ctrl == NULL ) {
		/* first try */
		*ctrl = (LDAPControl *) slap_sl_calloc( 1, sizeof(LDAPControl), NULL );
	} else {
		/* retry: free previous try */
		slap_sl_free( (*ctrl)->ldctl_value.bv_val, op->o_tmpmemctx );
	}

	**ctrl = c;
	return LDAP_SUCCESS;
}
Exemple #6
0
int ldap_debug_file( FILE *file )
{
	ldap_debug_lock();
	log_file = file;
	ber_set_option( NULL, LBER_OPT_LOG_PRINT_FILE, file );
	ldap_debug_unlock();

	return 0;
}
Exemple #7
0
static int pack_pagedresult_response_control(
	Operation		*op,
	SlapReply		*rs,
	sort_op			*so,
	LDAPControl	**ctrlsp )
{
	LDAPControl			*ctrl;
	BerElementBuffer	berbuf;
	BerElement			*ber		= (BerElement *)&berbuf;
	PagedResultsCookie	resp_cookie;
	struct berval		cookie, bv;
	int					rc;

	ber_init2( ber, NULL, LBER_USE_DER );
	ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );

	if ( so->so_nentries > 0 ) {
		resp_cookie		= ( PagedResultsCookie )so->so_tree;
		cookie.bv_len	= sizeof( PagedResultsCookie );
		cookie.bv_val	= (char *)&resp_cookie;
	} else {
		resp_cookie		= ( PagedResultsCookie )0;
		BER_BVZERO( &cookie );
	}

	op->o_conn->c_pagedresults_state.ps_cookie = resp_cookie;
	op->o_conn->c_pagedresults_state.ps_count
		= ((PagedResultsState *)op->o_pagedresults_state)->ps_count
		  + rs->sr_nentries;

	rc = ber_printf( ber, "{iO}", so->so_nentries, &cookie );
	if ( rc != -1 ) {
		rc = ber_flatten2( ber, &bv, 0 );
	}

	if ( rc != -1 ) {
		ctrl = (LDAPControl *)op->o_tmpalloc( sizeof(LDAPControl)+
			bv.bv_len, op->o_tmpmemctx );
		ctrl->ldctl_oid			= LDAP_CONTROL_PAGEDRESULTS;
		ctrl->ldctl_iscritical	= 0;
		ctrl->ldctl_value.bv_val = (char *)(ctrl+1);
		ctrl->ldctl_value.bv_len = bv.bv_len;
		memcpy( ctrl->ldctl_value.bv_val, bv.bv_val, bv.bv_len );
		ctrlsp[0] = ctrl;
	} else {
		ctrlsp[0] = NULL;
		rs->sr_err = LDAP_OTHER;
	}

	ber_free_buf( ber );

	return rs->sr_err;
}
Exemple #8
0
/* Rewrite an LDAP DN in DER form
 * Input must be valid DN, therefore no error checking is done here.
 */
static int autoca_dnbv2der( Operation *op, struct berval *bv, struct berval *der )
{
	BerElementBuffer berbuf;
	BerElement *ber = (BerElement *)&berbuf;
	LDAPDN dn;
	LDAPRDN rdn;
	LDAPAVA *ava;
	AttributeDescription *ad;
	int irdn, iava;

	ldap_bv2dn_x( bv, &dn, LDAP_DN_FORMAT_LDAP, op->o_tmpmemctx );

	ber_init2( ber, NULL, LBER_USE_DER );
	ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );

	/* count RDNs, we need them in reverse order */
	for (irdn = 0; dn[irdn]; irdn++);
	irdn--;

	/* DN is a SEQuence of RDNs */
	ber_start_seq( ber, LBER_SEQUENCE );
	for (; irdn >=0; irdn--)
	{
		/* RDN is a SET of AVAs */
		ber_start_set( ber, LBER_SET );
		rdn = dn[irdn];
		for (iava = 0; rdn[iava]; iava++)
		{
			const char *text;
			char oid[1024];
			struct berval bvo = { sizeof(oid), oid };
			struct berval bva;

			/* AVA is a SEQuence of attr and value */
			ber_start_seq( ber, LBER_SEQUENCE );
			ava = rdn[iava];
			ad = NULL;
			slap_bv2ad( &ava->la_attr, &ad, &text );
			ber_str2bv( ad->ad_type->sat_oid, 0, 0, &bva );
			ber_encode_oid( &bva, &bvo );
			ber_put_berval( ber, &bvo, LBER_TAG_OID );
			ber_put_berval( ber, &ava->la_value, LBER_TAG_UTF8 );
			ber_put_seq( ber );
		}
		ber_put_set( ber );
	}
	ber_put_seq( ber );
	ber_flatten2( ber, der, 0 );
	ldap_dnfree_x( dn, op->o_tmpmemctx );
	return 0;
}
Exemple #9
0
static int pack_vlv_response_control(
	Operation		*op,
	SlapReply		*rs,
	sort_op			*so,
	LDAPControl	**ctrlsp )
{
	LDAPControl			*ctrl;
	BerElementBuffer	berbuf;
	BerElement			*ber		= (BerElement *)&berbuf;
	struct berval		cookie, bv;
	int					rc;

	ber_init2( ber, NULL, LBER_USE_DER );
	ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );

	rc = ber_printf( ber, "{iie", so->so_vlv_target, so->so_nentries,
		so->so_vlv_rc );

	if ( rc != -1 && so->so_vcontext ) {
		cookie.bv_val = (char *)&so->so_vcontext;
		cookie.bv_len = sizeof(so->so_vcontext);
		rc = ber_printf( ber, "tO", LDAP_VLVCONTEXT_IDENTIFIER, &cookie );
	}

	if ( rc != -1 ) {
		rc = ber_printf( ber, "}" );
	}

	if ( rc != -1 ) {
		rc = ber_flatten2( ber, &bv, 0 );
	}

	if ( rc != -1 ) {
		ctrl = (LDAPControl *)op->o_tmpalloc( sizeof(LDAPControl)+
			bv.bv_len, op->o_tmpmemctx );
		ctrl->ldctl_oid			= LDAP_CONTROL_VLVRESPONSE;
		ctrl->ldctl_iscritical	= 0;
		ctrl->ldctl_value.bv_val = (char *)(ctrl+1);
		ctrl->ldctl_value.bv_len = bv.bv_len;
		memcpy( ctrl->ldctl_value.bv_val, bv.bv_val, bv.bv_len );
		ctrlsp[0] = ctrl;
	} else {
		ctrlsp[0] = NULL;
		rs->sr_err = LDAP_OTHER;
	}

	ber_free_buf( ber );

	return rs->sr_err;
}
Exemple #10
0
char *
first_attribute(BerElement *ber )
{
	int rc;
	ber_tag_t tag;
	ber_len_t len = 0;
	char *attr;
	
	/* 
	 * Skip past the sequence, dn, sequence of sequence leaving
	 * us at the first attribute.
	 */

	tag = ber_scanf( ber, "{xl{" /*}}*/, &len );
	if( tag == LBER_ERROR ) {
		
		ber_free( ber, 0 );
		return NULL;
	}

	/* set the length to avoid overrun */
	rc = ber_set_option( ber, LBER_OPT_REMAINING_BYTES, &len );
	if( rc != LBER_OPT_SUCCESS ) {
		printf(">>Error<< Avoid overrun failed!\n");
		ber_free( ber, 0 );
		return NULL;
	}

	if ( ber_pvt_ber_remaining( ber ) == 0 ) {
		assert( len == 0 );
		ber_free( ber, 0 );
		return NULL;
	}
	

	/* snatch the first attribute */
	tag = ber_scanf( ber, "{ax}", &attr );
	if( tag == LBER_ERROR ) {
		printf(">>Error<< Snatch first Attr failed!\n");
		ber_free( ber, 0 );
		return NULL;
	}
	
	return attr;

}
Exemple #11
0
/** @brief Connect to a LDAP server.
  * @param uri Server to connect too.
  * @param starttls Starttls flags to disallow,allow or enforce SSL.
  * @param timelimit Query timelimit.
  * @param limit Results limit.
  * @param debug Set LDAP_OPT_DEBUG_LEVEL and LBER_OPT_DEBUG_LEVEL to this level.
  * @param err Pointer to a int that will contain the ldap error on failure.
  * @returns Reference to LDAP connection if its NULL the error is returned in err.*/
extern struct ldap_conn *ldap_connect(const char *uri, enum ldap_starttls starttls, int timelimit, int limit, int debug, int *err) {
	struct ldap_conn *ld;
	int version = 3;
	int res, sslres;
	struct timeval timeout;

	if (!(ld = objalloc(sizeof(*ld), free_ldapconn))) {
		return NULL;
	}

	ld->uri = strdup(uri);
	ld->sctrlsp = NULL;
	ld->timelim = timelimit;
	ld->limit = limit;
	ld->sasl = NULL;

	if ((res = ldap_initialize(&ld->ldap, ld->uri) != LDAP_SUCCESS)) {
		objunref(ld);
		ld = NULL;
	} else {
		if (debug) {
			ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, &debug);
			ber_set_option(NULL, LBER_OPT_DEBUG_LEVEL, &debug);
		}
		if (timelimit) {
			timeout.tv_sec = timelimit;
			timeout.tv_usec = 0;
			ldap_set_option(ld->ldap, LDAP_OPT_NETWORK_TIMEOUT, (void *)&timeout);
		}
		ldap_set_option(ld->ldap, LDAP_OPT_PROTOCOL_VERSION, &version);
		ldap_set_option(ld->ldap, LDAP_OPT_REFERRALS, (void *)LDAP_OPT_ON);
		ldap_set_rebind_proc(ld->ldap, ldap_rebind_proc, ld);

		if ((starttls != LDAP_STARTTLS_NONE) & !ldap_tls_inplace(ld->ldap) && (sslres = ldap_start_tls_s(ld->ldap, ld->sctrlsp, NULL))) {
			if (starttls == LDAP_STARTTLS_ENFORCE) {
				objunref(ld);
				ld = NULL;
				res = sslres;
			}
		}
	}
	*err = res;
	return ld;
}
Exemple #12
0
static int
_dico_conn_setup(struct _dico_ldap_handle *lp)
{
    int rc;
    LDAP *ld = NULL;
    int protocol = LDAP_VERSION3; /* FIXME: must be configurable */
  
    if (lp->debug) {
	if (ber_set_option(NULL, LBER_OPT_DEBUG_LEVEL, &lp->debug)
	    != LBER_OPT_SUCCESS )
	    dico_log(L_ERR, 0, _("cannot set LBER_OPT_DEBUG_LEVEL %d"),
		     lp->debug);

	if (ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, &lp->debug)
	    != LDAP_OPT_SUCCESS )
	    dico_log(L_ERR, 0, _("could not set LDAP_OPT_DEBUG_LEVEL %d"),
		     lp->debug);
    }


    rc = ldap_initialize(&ld, lp->url);
    if (rc != LDAP_SUCCESS) {
	dico_log(L_ERR, 0,
		 _("cannot create LDAP session handle for URI=%s (%d): %s"),
		 lp->url, rc, ldap_err2string(rc));
	return 1;
    }
  
    if (lp->tls) {
	rc = ldap_start_tls_s(ld, NULL, NULL);
	if (rc != LDAP_SUCCESS) {
	    dico_log(L_ERR, 0, _("ldap_start_tls failed: %s"),
		     ldap_err2string(rc));
	    return 1;
	}
    }

    ldap_set_option(ld, LDAP_OPT_PROTOCOL_VERSION, &protocol);

    /* FIXME: Timeouts, SASL, etc. */
    lp->ldap = ld;
    return 0;
}
Exemple #13
0
void init_ldap_debugging(void)
{
#if defined(HAVE_LDAP) && defined(HAVE_LBER_LOG_PRINT_FN)
	int ret;
	int ldap_debug_level = lp_ldap_debug_level();

	ret = ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, &ldap_debug_level);
	if (ret != LDAP_OPT_SUCCESS) {
		DEBUG(10, ("Error setting LDAP debug level.\n"));
	}

	if (ldap_debug_level == 0) {
		return;
	}

	ret = ber_set_option(NULL, LBER_OPT_LOG_PRINT_FN,
			     (void *)samba_ldap_log_print_fn);
	if (ret != LBER_OPT_SUCCESS) {
		DEBUG(10, ("Error setting LBER log print function.\n"));
	}
#endif /* HAVE_LDAP && HAVE_LBER_LOG_PRINT_FN */
}
Exemple #14
0
int
main( int argc, char *argv[] )
{
	int c;
	int debug=0;

    while( (c = getopt( argc, argv, "d:" )) != EOF ) {
		switch ( c ) {
		case 'd':
			debug = atoi( optarg );
			break;
		default:
			fprintf( stderr, "ftest: unrecognized option -%c\n",
				optopt );
			return usage();
		}
	}

	if ( debug ) {
		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 ( argc - optind != 1 ) {
		return usage();
	}

	return filter2ber( strdup( argv[optind] ) );
}
Exemple #15
0
static int pack_sss_response_control(
	Operation		*op,
	SlapReply		*rs,
	LDAPControl	**ctrlsp )
{
	LDAPControl			*ctrl;
	BerElementBuffer	berbuf;
	BerElement			*ber		= (BerElement *)&berbuf;
	struct berval		bv;
	int					rc;

	ber_init2( ber, NULL, LBER_USE_DER );
	ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );

	/* Pack error code */
	rc = ber_printf(ber, "{e}", rs->sr_err);

	if ( rc != -1)
		rc = ber_flatten2( ber, &bv, 0 );

	if ( rc != -1 ) {
		ctrl = (LDAPControl *)op->o_tmpalloc( sizeof(LDAPControl)+
			bv.bv_len, op->o_tmpmemctx );
		ctrl->ldctl_oid			= LDAP_CONTROL_SORTRESPONSE;
		ctrl->ldctl_iscritical	= 0;
		ctrl->ldctl_value.bv_val = (char *)(ctrl+1);
		ctrl->ldctl_value.bv_len = bv.bv_len;
		memcpy( ctrl->ldctl_value.bv_val, bv.bv_val, bv.bv_len );
		ctrlsp[0] = ctrl;
	} else {
		ctrlsp[0] = NULL;
		rs->sr_err = LDAP_OTHER;
	}

	ber_free_buf( ber );

	return rs->sr_err;
}
Exemple #16
0
int checkBindRes(BerElement *ber)
	{
		ber_tag_t tag;
		ber_int_t resultCode;
		ber_len_t len;
#ifdef DEBUG		
		int ival = -1;
        ber_set_option( NULL, LBER_OPT_DEBUG_LEVEL, &ival );
#endif
		if ( (tag = ber_peek_tag( ber, &len )) == LBER_ERROR ) {
			/* log, close and send error */
			printf(">>Error<< PeeK failed, tag;%d\n", tag);
			ber_free( ber, 1 );
			return LBER_ERROR;
		}

		
		tag = ber_scanf( ber, "{i}" , &resultCode );
		if ( tag == LBER_ERROR ) {
			return LBER_ERROR;
			//printf("BER decode Error! Ber_Scanf return tag:%d.\n", tag);
		}
		return resultCode;
	}
Exemple #17
0
static int
asyncmeta_send_entry(
	Operation 	*op,
	SlapReply	*rs,
	a_metaconn_t	*mc,
	int 		target,
	LDAPMessage 	*e )
{
	a_metainfo_t 		*mi = mc->mc_info;
	struct berval		a, mapped = BER_BVNULL;
	int			check_sorted_attrs = 0;
	Entry 			ent = {0};
	BerElement 		ber = *ldap_get_message_ber( e );
	Attribute 		*attr, **attrp;
	struct berval 		bdn,
				dn = BER_BVNULL;
	const char 		*text;
	a_dncookie		dc;
	ber_len_t		len;
	int			rc;
	void	*mem_mark;

	mem_mark = slap_sl_mark( op->o_tmpmemctx );
	ber_set_option( &ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );

	if ( ber_scanf( &ber, "l{", &len ) == LBER_ERROR ) {
		return LDAP_DECODING_ERROR;
	}

	if ( ber_set_option( &ber, LBER_OPT_REMAINING_BYTES, &len ) != LBER_OPT_SUCCESS ) {
		return LDAP_OTHER;
	}

	if ( ber_scanf( &ber, "m{", &bdn ) == LBER_ERROR ) {
		return LDAP_DECODING_ERROR;
	}

	/*
	 * Rewrite the dn of the result, if needed
	 */
	dc.op = op;
	dc.target = mi->mi_targets[ target ];
	dc.memctx = op->o_tmpmemctx;
	dc.to_from = MASSAGE_REP;
	asyncmeta_dn_massage( &dc, &bdn, &dn );

	/*
	 * Note: this may fail if the target host(s) schema differs
	 * from the one known to the meta, and a DN with unknown
	 * attributes is returned.
	 *
	 * FIXME: should we log anything, or delegate to dnNormalize?
	 */
	rc = dnPrettyNormal( NULL, &dn, &ent.e_name, &ent.e_nname,
		op->o_tmpmemctx );
	if ( dn.bv_val != bdn.bv_val ) {
			op->o_tmpfree( dn.bv_val, op->o_tmpmemctx );
	}
	BER_BVZERO( &dn );

	if ( rc != LDAP_SUCCESS ) {
		Debug( LDAP_DEBUG_ANY,
			"%s asyncmeta_send_entry(\"%s\"): "
			"invalid DN syntax\n",
			op->o_log_prefix, ent.e_name.bv_val );
		rc = LDAP_INVALID_DN_SYNTAX;
		goto done;
	}

	/*
	 * cache dn
	 */
	if ( mi->mi_cache.ttl != META_DNCACHE_DISABLED ) {
		( void )asyncmeta_dncache_update_entry( &mi->mi_cache,
				&ent.e_nname, target );
	}

	attrp = &ent.e_attrs;

	while ( ber_scanf( &ber, "{m", &a ) != LBER_ERROR ) {
		int				last = 0;
		slap_syntax_validate_func	*validate;
		slap_syntax_transform_func	*pretty;

		if ( ber_pvt_ber_remaining( &ber ) < 0 ) {
			Debug( LDAP_DEBUG_ANY,
				"%s asyncmeta_send_entry(\"%s\"): "
				"unable to parse attr \"%s\".\n",
				op->o_log_prefix, ent.e_name.bv_val, a.bv_val );

			rc = LDAP_OTHER;
			goto done;
		}

		if ( ber_pvt_ber_remaining( &ber ) == 0 ) {
			break;
		}

		attr = op->o_tmpcalloc( 1, sizeof(Attribute), op->o_tmpmemctx );
		if ( slap_bv2ad( &a, &attr->a_desc, &text )
				!= LDAP_SUCCESS) {
			if ( slap_bv2undef_ad( &a, &attr->a_desc, &text,
				SLAP_AD_PROXIED ) != LDAP_SUCCESS )
			{
				Debug(LDAP_DEBUG_ANY,
				      "%s meta_send_entry(\"%s\"): " "slap_bv2undef_ad(%s): %s\n",
				      op->o_log_prefix, ent.e_name.bv_val,
				      mapped.bv_val, text );
				( void )ber_scanf( &ber, "x" /* [W] */ );
				op->o_tmpfree( attr, op->o_tmpmemctx );
				continue;
			}
		}

		if ( attr->a_desc->ad_type->sat_flags & SLAP_AT_SORTED_VAL )
			check_sorted_attrs = 1;

		/* no subschemaSubentry */
		if ( attr->a_desc == slap_schema.si_ad_subschemaSubentry
			|| attr->a_desc == slap_schema.si_ad_entryDN )
		{

			/*
			 * We eat target's subschemaSubentry because
			 * a search for this value is likely not
			 * to resolve to the appropriate backend;
			 * later, the local subschemaSubentry is
			 * added.
			 *
			 * We also eat entryDN because the frontend
			 * will reattach it without checking if already
			 * present...
			 */
			( void )ber_scanf( &ber, "x" /* [W] */ );
			op->o_tmpfree( attr, op->o_tmpmemctx );
			continue;
		}

		if ( ber_scanf( &ber, "[W]", &attr->a_vals ) == LBER_ERROR
				|| attr->a_vals == NULL )
		{
			attr->a_vals = (struct berval *)&slap_dummy_bv;

		} else {
			for ( last = 0; !BER_BVISNULL( &attr->a_vals[ last ] ); ++last )
				;
		}
		attr->a_numvals = last;

		validate = attr->a_desc->ad_type->sat_syntax->ssyn_validate;
		pretty = attr->a_desc->ad_type->sat_syntax->ssyn_pretty;

		if ( !validate && !pretty ) {
			ber_bvarray_free_x( attr->a_vals, op->o_tmpmemctx );
			op->o_tmpfree( attr, op->o_tmpmemctx );
			goto next_attr;
		}

		/*
		 * It is necessary to try to rewrite attributes with
		 * dn syntax because they might be used in ACLs as
		 * members of groups; since ACLs are applied to the
		 * rewritten stuff, no dn-based subecj clause could
		 * be used at the ldap backend side (see
		 * http://www.OpenLDAP.org/faq/data/cache/452.html)
		 * The problem can be overcome by moving the dn-based
		 * ACLs to the target directory server, and letting
		 * everything pass thru the ldap backend.
		 */
		{
			int	i;

			if ( attr->a_desc->ad_type->sat_syntax ==
				slap_schema.si_syn_distinguishedName )
			{
				asyncmeta_dnattr_result_rewrite( &dc, attr->a_vals );

			} else if ( attr->a_desc == slap_schema.si_ad_ref ) {
				asyncmeta_referral_result_rewrite( &dc, attr->a_vals );

			}

			for ( i = 0; i < last; i++ ) {
				struct berval	pval;
				int		rc;

				if ( pretty ) {
					rc = ordered_value_pretty( attr->a_desc,
						&attr->a_vals[i], &pval, op->o_tmpmemctx );

				} else {
					rc = ordered_value_validate( attr->a_desc,
						&attr->a_vals[i], 0 );
				}

				if ( rc ) {
					ber_memfree_x( attr->a_vals[i].bv_val, op->o_tmpmemctx );
					if ( --last == i ) {
						BER_BVZERO( &attr->a_vals[ i ] );
						break;
					}
					attr->a_vals[i] = attr->a_vals[last];
					BER_BVZERO( &attr->a_vals[last] );
					i--;
					continue;
				}

				if ( pretty ) {
					ber_memfree_x( attr->a_vals[i].bv_val, op->o_tmpmemctx );
					attr->a_vals[i] = pval;
				}
			}

			if ( last == 0 && attr->a_vals != &slap_dummy_bv ) {
				ber_bvarray_free_x( attr->a_vals, op->o_tmpmemctx );
				op->o_tmpfree( attr, op->o_tmpmemctx );
				goto next_attr;
			}
		}

		if ( last && attr->a_desc->ad_type->sat_equality &&
			attr->a_desc->ad_type->sat_equality->smr_normalize )
		{
			int i;

			attr->a_nvals = op->o_tmpalloc( ( last + 1 ) * sizeof( struct berval ), op->o_tmpmemctx );
			for ( i = 0; i<last; i++ ) {
				/* if normalizer fails, drop this value */
				if ( ordered_value_normalize(
					SLAP_MR_VALUE_OF_ATTRIBUTE_SYNTAX,
					attr->a_desc,
					attr->a_desc->ad_type->sat_equality,
					&attr->a_vals[i], &attr->a_nvals[i],
					op->o_tmpmemctx )) {
					ber_memfree_x( attr->a_vals[i].bv_val, op->o_tmpmemctx );
					if ( --last == i ) {
						BER_BVZERO( &attr->a_vals[ i ] );
						break;
					}
					attr->a_vals[i] = attr->a_vals[last];
					BER_BVZERO( &attr->a_vals[last] );
					i--;
				}
			}
			BER_BVZERO( &attr->a_nvals[i] );
			if ( last == 0 ) {
				ber_bvarray_free_x( attr->a_vals, op->o_tmpmemctx );
				ber_bvarray_free_x( attr->a_nvals, op->o_tmpmemctx );
				op->o_tmpfree( attr, op->o_tmpmemctx );
				goto next_attr;
			}

		} else {
			attr->a_nvals = attr->a_vals;
		}

		attr->a_numvals = last;
		*attrp = attr;
		attrp = &attr->a_next;
next_attr:;
	}

	/* Check for sorted attributes */
	if ( check_sorted_attrs ) {
		for ( attr = ent.e_attrs; attr; attr = attr->a_next ) {
			if ( attr->a_desc->ad_type->sat_flags & SLAP_AT_SORTED_VAL ) {
				while ( attr->a_numvals > 1 ) {
					int i;
					int rc = slap_sort_vals( (Modifications *)attr, &text, &i, op->o_tmpmemctx );
					if ( rc != LDAP_TYPE_OR_VALUE_EXISTS )
						break;

					/* Strip duplicate values */
					if ( attr->a_nvals != attr->a_vals )
						ber_memfree_x( attr->a_nvals[i].bv_val, op->o_tmpmemctx );
					ber_memfree_x( attr->a_vals[i].bv_val, op->o_tmpmemctx );
					attr->a_numvals--;
					if ( (unsigned)i < attr->a_numvals ) {
						attr->a_vals[i] = attr->a_vals[attr->a_numvals];
						if ( attr->a_nvals != attr->a_vals )
							attr->a_nvals[i] = attr->a_nvals[attr->a_numvals];
					}
					BER_BVZERO(&attr->a_vals[attr->a_numvals]);
					if ( attr->a_nvals != attr->a_vals )
						BER_BVZERO(&attr->a_nvals[attr->a_numvals]);
				}
				attr->a_flags |= SLAP_ATTR_SORTED_VALS;
			}
		}
	}
	Debug( LDAP_DEBUG_TRACE,
	       "%s asyncmeta_send_entry(\"%s\"): "
	       ".\n",
	       op->o_log_prefix, ent.e_name.bv_val );
	ldap_get_entry_controls( mc->mc_conns[target].msc_ldr,
		e, &rs->sr_ctrls );
	rs->sr_entry = &ent;
	rs->sr_attrs = op->ors_attrs;
	rs->sr_operational_attrs = NULL;
	rs->sr_flags = mi->mi_targets[ target ]->mt_rep_flags;
	rs->sr_err = LDAP_SUCCESS;
	rc = send_search_entry( op, rs );
	switch ( rc ) {
	case LDAP_UNAVAILABLE:
		rc = LDAP_OTHER;
		break;
	}

done:;
	if ( rs->sr_ctrls != NULL ) {
		ldap_controls_free( rs->sr_ctrls );
		rs->sr_ctrls = NULL;
	}
#if 0
	while ( ent.e_attrs ) {
		attr = ent.e_attrs;
		ent.e_attrs = attr->a_next;
		if ( attr->a_nvals != attr->a_vals )
			ber_bvarray_free_x( attr->a_nvals, op->o_tmpmemctx );
		ber_bvarray_free_x( attr->a_vals, op->o_tmpmemctx );
		op->o_tmpfree( attr, op->o_tmpmemctx );
	}
	if (ent.e_name.bv_val != NULL) {
		op->o_tmpfree( ent.e_name.bv_val, op->o_tmpmemctx );
	}

	if (ent.e_nname.bv_val != NULL) {
		op->o_tmpfree( ent.e_nname.bv_val, op->o_tmpmemctx );
	}
	if (rs->sr_entry && rs->sr_entry != &ent) {
		entry_free( rs->sr_entry );
	}
#endif
	slap_sl_release( mem_mark, op->o_tmpmemctx );
	rs->sr_entry = NULL;
	rs->sr_attrs = NULL;
	return rc;
}
Exemple #18
0
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 );
}
Exemple #19
0
int checkSearchEntry(BerElement *ber)
{
	int rc = LDAP_SUCCESS;
	ber_tag_t tag;
	ber_len_t len =0;
	BerValue attr;
	BerVarray vals;
	attr.bv_val = NULL;
	attr.bv_len = 0;
	char *a;
	int n;
	struct berval dn = BER_BVNULL;
	BerElement ber_value, ber_backup;
	ber_value = ber_backup= *ber;
		
	
#ifdef DEBUG 
	    int ival = -1;
        ber_set_option( NULL, LBER_OPT_DEBUG_LEVEL, &ival );
#endif
	
	 n=0;
	for ( a = first_attribute( ber ); a != NULL; a = next_attribute(  ber ) )
		{
			struct berval	**vals;
			//printf( "| | ATTR: %s\n", a );
			if ( (vals = get_values_len( &ber_value, a )) == NULL )
			{
				printf( "| | %s:\t(no values)\n" , a);
			}else {
				int i;
				for ( i = 0; vals[i] != NULL; i++ ) {
					int	j, nonascii;

					nonascii = 0;
					for ( j = 0; (ber_len_t) j < vals[i]->bv_len; j++ )
					//Non-display ASCII will be shown as HEX, It is Control code before 33 in ASCII Table
						if ( !isascii( vals[i]->bv_val[j] ) || vals[i]->bv_val[j] < 33 ) {
							nonascii = 1;
							break;
						}
					
					if ( nonascii ) {
						printf( "|-%s(not ascii):\tlen (%ld) \n",a, vals[i]->bv_len );
					
						ber_bprint( vals[i]->bv_val, vals[i]->bv_len );
					
						continue;
					}
				
#ifdef DETAIL
					printf( "|-%s:\tlen (%ld) \t%s\n",a, vals[i]->bv_len, vals[i]->bv_val );
#else					
					printf( "|-%s:\t\t%s\n",a, vals[i]->bv_val );
					
#endif					
				}
				
				ber_bvecfree( vals );
			}
			ber_value = ber_backup;
			n++;
		}
		
	
	return n;
}
Exemple #20
0
int  checkSearchReq(BerElement *ber,PREQ *preq)
	{
	/*
	 * Parse the search request.  It looks like this:
	 *
	 *	SearchRequest := [APPLICATION 3] SEQUENCE {
	 *		baseObject	DistinguishedName,
	 *		scope		ENUMERATED {
	 *			baseObject	(0),
	 *			singleLevel	(1),
	 *			wholeSubtree (2),
	 *          subordinate (3)  -- OpenLDAP extension
	 *		},
	 *		derefAliases	ENUMERATED {
	 *			neverDerefaliases	(0),
	 *			derefInSearching	(1),
	 *			derefFindingBaseObj	(2),
	 *			alwaysDerefAliases	(3)
	 *		},
	 *		sizelimit	INTEGER (0 .. 65535),
	 *		timelimit	INTEGER (0 .. 65535),
	 *		attrsOnly	BOOLEAN,
	 *		filter		Filter,
	 *		attributes	SEQUENCE OF AttributeType
	 *	}
	 */		
		Filter f;
		ber_tag_t tag;
		ber_len_t len;
		ber_int_t scope=0;
		ber_int_t ali=0;
		ber_int_t size=0;
		ber_int_t time=0; 
		ber_int_t filter=0;
		ber_int_t attrsonly=0;
		ber_len_t	siz,  i;
		struct berval dn = BER_BVNULL;
		//BerVarray  Attri;
		AttributeName *Attri;
		//BerVarray AttributeDescriptionList = NULL;
		BerElement Ber_Bkp = *ber;
		ber_len_t cnt = sizeof(struct berval);
		ber_len_t off = 0;
		
		char text[128]={} ; // storing the filter
		
#ifdef DEBUG
	    int ival = -1;
        ber_set_option( NULL, LBER_OPT_DEBUG_LEVEL, &ival );
#endif

		if ( ber_scanf( ber, "{miiiib" /*}*/,
			&dn, &scope, &ali, &size, &time, &attrsonly ) == LBER_ERROR )
		{
                   printf(">>Error<< SRCH decode Error! Ber_Scanf return tag:%d.\n", tag);
					return -1;
		}
		
		
		
		if(Ldap_get_filter(ber, text) == LBER_ERROR)
		{
			printf(">>Error<< Filter Decode Error\n");
		}
		strcat(text, "\n");
		//tag = ber_skip_tag( ber, &len );
		/* attributes */
		siz = sizeof(AttributeName);
		off = offsetof(AttributeName,an_name);
		
		//printf("Attribute Decode DEBUG: siz-%d,  off-%d\n", siz, off);
		
			if ( ber_scanf( ber, "{M}}", &Attri, &siz, off) == LBER_ERROR )
			{
              	     printf(">>Error<< Attir decode Error! Ber_Scanf return tag:%d.\n", tag);
					//return -1;
			}
			i=0;
		 	/* success */
			printf("|-\033[1m\033[40;35mBaseDN\033[0m:\t%s\n", dn.bv_val);
			printf("|-scope:\t%s\n", ScopeString[scope]);
			printf("|-ali:\t%s\n", AliasString[ali]);
			printf("|-size:\t%d\n", size);
			printf("|-time:\t%d\n", time);
			printf("|-attrsonly:\t%d\n", attrsonly);
			printf("|-Filter:\t%s", text);
			for ( i=0; i<siz; i++ )  {
				printf("|-Attribute(%d):\t%s\n",i, Attri[i].an_name.bv_val );
			}
	
			preq->dn = dn.bv_val;
			preq->scope     = scope; 
			preq->ali       = ali;
			preq->size      = size;
			preq->time      = time;
			preq->attrsonly = attrsonly;
				
			Trace Subs, GetSubs;
			char *p,*q,*j,*m,*n;
		int type=0;
		GetSubs.IMSI=NULL;
		GetSubs.MSISDN=NULL;
		GetSubs.mscID=NULL;
		m=dn.bv_val;
		do 
			{
			p=strtok(m, ",");	//CPU=12434,
			if(p)
			{
			n=strtok(NULL,","); //MSISDN=1234567890123,dc=msisdn,ou=identities,dc=telcel
				
			q=strtok(p,"=");//CPU
			j=strtok(NULL,"=");//1234
			printf("---------Strtok:%s=%s\n----------",q,j);
			if(strcasecmp(q,"IMSI")==0) {type=1;  GetSubs.IMSI=j;}//IMSI case;
			if(strcasecmp(q,"MSISDN")==0) {type=2;GetSubs.MSISDN=j;}//MSISDN case;
			if(strcasecmp(q,"mscid")==0) {type=3; GetSubs.mscID=j;}//MSCID case;
				//if(strcasecmp(q,"associd")==0) type=4;//IMS case;
			m=n;
			}
			}
			while(p != NULL);
	printf("The fetch DATA(type:%d): \n-->IMSI-%s\n-->MSISDN-%s\n-->mscID-%s\n",type, GetSubs.IMSI, GetSubs.MSISDN, GetSubs.mscID);
			return 0;
	}
Exemple #21
0
int newthread_start(PeerClient *client_info)
{
		
		ber_tag_t       tag;
		ber_int_t		msgid;
		ber_int_t		msgid_before;
		ber_len_t       len;
     	BerElement      *ber;
     	Sockbuf         *sb;
    	ber_len_t max = 409600;
		ber_tag_t LdapOpt;
		int rc;
		TcpHeadInfo socketTcpHead;
		int client_conn = client_info->client_conn;
		int loop=0;
	
		PrintCap capInfor;
		capInfor.peer = *client_info;
	
#ifdef DEBUG	
		/* enable debugging */
        int ival = -1;
        ber_set_option( NULL, LBER_OPT_DEBUG_LEVEL, &ival );
#endif 
		sb = ber_sockbuf_alloc();
    	ber_sockbuf_ctrl( sb, LBER_SB_OPT_SET_MAX_INCOMING, &max );

    	while(1){
    		loop ++;
    		//printf(">>>>>>>>>>>>>>>>>While Loop the %d Packet<<<<<<<<<<<<<<<<<<<<<<\n", loop);	
    
    		/*---------------------------------------------------------------------
    		 Recieve the data from Socket, Function of "recv" is a standard func of
    		 getting data from socket, the purpose of "recv" is getting the TCP head
    		 related infor that sent from client, and put into a struct. 
    		 This struct must be exactly aligned with client side,otherwis the data
    		 may not readable
    		----------------------------------------------------------------------*/
    		//printf("\n\nDebug:-------Recv Data of TCP head\n");
   			rc = recv(client_conn, (char *)&socketTcpHead, sizeof(socketTcpHead),0);
    		if(rc < 0){
    			printf("TCP Head Recv failed!\n");
    			exit (0);
    		}

    		capInfor.PackageHead = socketTcpHead;
    		
#ifdef DEBUGA    		
    		printf("TCP Head info len:	%d\n", rc);
    		printf("Time tag: 			%u:%u\n", PCAP.TimeStmap.tv_sec,PCAP.TimeStmap.tv_usec );
    		printf("Pkt number:			%d\n", capInfor.PackageHead.GetPackageNumber);
    		printf("IP layer len:		%d\n", capInfor.PackageHead.size_ip);
    		printf("TCP layer len:		%d\n", capInfor.PackageHead.size_tcp);
    		printf("Protocol:			%d\n", capInfor.PackageHead.Prctl);
    		printf("Src IP:				%s\n", capInfor.PackageHead.ipSrc);
    		printf("Dst IP:				%s\n", capInfor.PackageHead.ipDst);
    		printf("Payload len			%d\n", capInfor.PackageHead.Payload_size);
#endif    		
    		
    		/*----------------------------------------------------------------------
    		 "ber_sockbuf_add_io" is a function that supplied by "liblber" , it can
    		 get the socket information like "recv", that means here no need to call
    		 recv agian.
    		 Why here use the "ber_sockbuf_add_io" instead of recv?
    		 this time the payload, actually there is ldap protocol data streams are
    		 sent by client, and LDAP protocol use BER(ASN.1) encode method,if use
    		 this function, handy for decode the ldap information.
    		 Like recv, it also is stuck before any data coming. 
    				sb : 		socket buff, storing the data gather from socket.
    		-------------------------------------------------------------------------*/
    		//printf("Debug:-------Recv Data of Payload infor\n");
    		
    		ber_sockbuf_add_io( sb, &ber_sockbuf_io_tcp, LBER_SBIOD_LEVEL_PROVIDER, (void *)&client_conn );
			
    		//printf("Debug:-------Decode BER starting\n");
    		//Create and allocate memory for BER struct, BER struct can store the infor which was parsed by above function
        	ber = ber_alloc_t(LBER_USE_DER);
    		if( ber == NULL ) {
				perror( "ber_alloc_t" );
				return( EXIT_FAILURE );
			}
    		
    		/*----------------------------------------------------------------------
    		 "ber_get_next", it links the socket buff and BER struct. now all ldap data
    		 has been transfer to the struct of ber. lib of lber and ldap can use it for
    		 ldap layer decoding.
    		-------------------------------------------------------------------------*/
    		for (;;) {
				tag = ber_get_next( sb, &len, ber);
				if( tag != LBER_ERROR ) break;
				if( errno == EWOULDBLOCK ) continue;
				if( errno == EAGAIN ) continue;
				//perror( "ber_get_next" );
				return( EXIT_FAILURE );
			}
    		
    		//determine the Ldap option kind 
    		LdapOpt=checkLDAPoption(ber, &msgid);
    		
    		if(LdapOpt==LBER_ERROR){
    			printf("|-Error:LDAP option decode failed.\n");
    		}
    		/*  -1 Sem: Sync the displaying in STDOUT. Only 1 thread is able to 
    		throw the information to screen in same time, othre thread is waiting 
    		for the bin_sem become a non-zero(1) value to take the charge in output
    		*/
    		//printf("Debug:------Sem Wait!\n");
    	
    	/*-----------------Sync-Area--BEGIN---Semaphore-Control-------------------------------*/	
    	/*---Below function displays decoded information of PDU to screen inside each thread--*/
    	/*---Screen resource would be used by different	threads, in order to make a complete--*/
    	/*---LDAP packet output,I use semaphore to sync each thread. the below command lines--*/
    	/*---realize a packet decode and display.---------------------------------------------*/
    	/*-*/  sem_wait(&bin_sem);
    	/*-*/	//printf("Debug:------Sem OK go ahead!\n");
    	/*-*/	msgid_before = msgid;
    	/*-*/	
    	/*-*/	//printf("Debug:------Format output infor\n");
    	/*-*/	FormatPrintLdap(LdapOpt, msgid, ber, capInfor);
    	/*-*/	
    	/*-*/	/* +1 Sem: After this time the LDAP PDU Decoding&Outputing completed, 
    	/*-*/	// plus 1 to set the bin_sem, then other thread will be able to use the
    	/*-*/	// STDOUT.
    	/*-*/
    	/*-*/ sem_post(&bin_sem);// +1 Sem
    	/*-----------------Sync-Area---END----Semaphore-Control--------------------------------*/
    	
	}
        //close(client_conn);
}
Exemple #22
0
static
DWORD
vmdirConnAccept(
    Sockbuf_IO*         pSockbuf_IO,
    DWORD               dwPort,
    BOOLEAN             bIsLdaps
    )
{
    ber_socket_t         newsockfd = -1;
    int                  retVal = LDAP_SUCCESS;
    ber_socket_t         ip4_fd = -1;
    ber_socket_t         ip6_fd = -1;
    ber_socket_t         max_fd = -1;
    VMDIR_THREAD         threadId;
    BOOLEAN              bInLock = FALSE;
    int                  iLocalLogMask = 0;
    PVDIR_CONNECTION_CTX pConnCtx = NULL;
    fd_set               event_fd_set;
    fd_set               poll_fd_set;
    struct timeval       timeout = {0};

    // Wait for ***1st*** replication cycle to be over.
    if (gVmdirServerGlobals.serverId == 0) // instance has not been initialized
    {
        VMDIR_LOG_WARNING( VMDIR_LOG_MASK_ALL, "Connection accept thread: Have NOT yet started listening on LDAP port (%u),"
                  " waiting for the 1st replication cycle to be over.", dwPort);

        VMDIR_LOCK_MUTEX(bInLock, gVmdirGlobals.replCycleDoneMutex);
        // wait till 1st replication cycle is over
        if (VmDirConditionWait( gVmdirGlobals.replCycleDoneCondition, gVmdirGlobals.replCycleDoneMutex ) != 0)
        {
            VMDIR_LOG_ERROR( VMDIR_LOG_MASK_ALL, "Connection accept thread: VmDirConditionWait failed." );
            retVal = LDAP_OPERATIONS_ERROR;
            goto cleanup;
        }
        // also wake up the other (normal LDAP port/SSL LDAP port listner) LDAP connection accept thread,
        // waiting on 1st replication cycle to be over
        // BUGBUG Does not handle spurious wake up
        VmDirConditionSignal(gVmdirGlobals.replCycleDoneCondition);
        VMDIR_UNLOCK_MUTEX(bInLock, gVmdirGlobals.replCycleDoneMutex);

        if (VmDirdState() == VMDIRD_STATE_SHUTDOWN) // Asked to shutdown before we started accepting
        {
            goto cleanup;
        }

        VMDIR_LOG_INFO( VMDIR_LOG_MASK_ALL, "Connection accept thread: listening on LDAP port (%u).", dwPort);
    }

    iLocalLogMask = VmDirLogGetMask();
    ber_set_option(NULL, LBER_OPT_DEBUG_LEVEL, &iLocalLogMask);

    SetupLdapPort(dwPort, &ip4_fd, &ip6_fd);
    if (ip4_fd < 0 && ip6_fd < 0)
    {
        VmDirSleep(1000);
        goto cleanup;
    }

    FD_ZERO(&event_fd_set);
    if (ip4_fd >= 0)
    {
        FD_SET (ip4_fd, &event_fd_set);
        if (ip4_fd > max_fd)
        {
            max_fd = ip4_fd;
        }
    }

    if (ip6_fd >= 0)
    {
        FD_SET (ip6_fd, &event_fd_set);
        if (ip6_fd > max_fd)
        {
            max_fd = ip6_fd;
        }
    }

    retVal = VmDirSyncCounterIncrement(gVmdirGlobals.pPortListenSyncCounter);
    if (retVal != 0 )
    {
        VMDIR_LOG_ERROR(VMDIR_LOG_MASK_ALL, "%s: VmDirSyncCounterIncrement(gVmdirGlobals.pPortListenSyncCounter) returned error", __func__);
        BAIL_ON_VMDIR_ERROR(retVal);
    }

    while (TRUE)
    {
        if (VmDirdState() == VMDIRD_STATE_SHUTDOWN)
        {
            goto cleanup;
        }

        poll_fd_set = event_fd_set;
        timeout.tv_sec = 3;
        timeout.tv_usec = 0;
        retVal = select ((int)max_fd+1, &poll_fd_set, NULL, NULL, &timeout);
        if (retVal < 0 )
        {
#ifdef _WIN32
            errno = WSAGetLastError();
#endif
            VMDIR_LOG_ERROR( VMDIR_LOG_MASK_ALL, "%s: select() (port %d) call failed: %d.", __func__, dwPort, errno);
            VmDirSleep( 1000 );
            continue;
        } else if (retVal == 0)
        {
            //VMDIR_LOG_INFO( LDAP_DEBUG_CONNS, "%s: select() timeout (port %d)", __func__, dwPort);
            continue;
        }

        if (ip4_fd >= 0 && FD_ISSET(ip4_fd, &poll_fd_set))
        {
            newsockfd = accept(ip4_fd, (struct sockaddr *) NULL, NULL);
        } else if (ip6_fd >= 0 && FD_ISSET(ip6_fd, &poll_fd_set))
        {
            newsockfd = accept(ip6_fd, (struct sockaddr *) NULL, NULL);
        } else
        {
            VMDIR_LOG_INFO( LDAP_DEBUG_CONNS, "%s: select() returned with no data (port %d), return: %d",
                            __func__, dwPort, retVal);
            continue;
        }

        if (newsockfd < 0)
        {
#ifdef _WIN32
            errno = WSAGetLastError();
#endif
            if (errno != EAGAIN && errno != EWOULDBLOCK )
            {
                VMDIR_LOG_ERROR( VMDIR_LOG_MASK_ALL, "%s: accept() (port %d) failed with errno: %d.",
                                 __func__, dwPort, errno );
            }
            continue;
        }

        if ( _VmDirFlowCtrlThrEnter() == TRUE )
        {
            tcp_close(newsockfd);
            newsockfd = -1;
            VMDIR_LOG_WARNING( VMDIR_LOG_MASK_ALL, "Maxmimum number of concurrent LDAP threads reached. Blocking new connection" );

            continue;
        }

        retVal = VmDirAllocateMemory(
                sizeof(VDIR_CONNECTION_CTX),
                (PVOID*)&pConnCtx);
        BAIL_ON_VMDIR_ERROR(retVal);

        pConnCtx->sockFd  = newsockfd;
        newsockfd = -1;
        pConnCtx->pSockbuf_IO = pSockbuf_IO;

        retVal = VmDirCreateThread(&threadId, TRUE, ProcessAConnection, (PVOID)pConnCtx);
        if (retVal != 0)
        {
            VMDIR_LOG_ERROR( VMDIR_LOG_MASK_ALL, "%s: VmDirCreateThread() (port) failed with errno: %d",
                             __func__, dwPort, errno );

            tcp_close(pConnCtx->sockFd);
            _VmDirFlowCtrlThrExit();
            VMDIR_SAFE_FREE_MEMORY(pConnCtx);
            continue;
        }
        else
        {
            pConnCtx = NULL; //thread take ownership on pConnCtx
            VmDirFreeVmDirThread(&threadId);
        }
    }

cleanup:

    VMDIR_UNLOCK_MUTEX(bInLock, gVmdirGlobals.replCycleDoneMutex);

    if (ip4_fd >= 0)
    {
        tcp_close(ip4_fd);
    }
    if (ip6_fd >= 0)
    {
        tcp_close(ip6_fd);
    }
    if (newsockfd >= 0)
    {
        tcp_close(newsockfd);
    }
#ifndef _WIN32
    raise(SIGTERM);
#endif

    VMDIR_LOG_INFO( VMDIR_LOG_MASK_ALL, "%s: Connection accept thread: stop (port %d)", __func__, dwPort);

    return retVal;

error:
    goto cleanup;
}
Exemple #23
0
static int 
monitor_subsys_log_modify( 
	Operation		*op,
	SlapReply		*rs,
	Entry 			*e )
{
	monitor_info_t	*mi = ( monitor_info_t * )op->o_bd->be_private;
	int		rc = LDAP_OTHER;
	int		newlevel = ldap_syslog;
	Attribute	*save_attrs;
	Modifications	*modlist = op->orm_modlist;
	Modifications	*ml;

	ldap_pvt_thread_mutex_lock( &monitor_log_mutex );

	save_attrs = e->e_attrs;
	e->e_attrs = attrs_dup( e->e_attrs );

	for ( ml = modlist; ml != NULL; ml = ml->sml_next ) {
		Modification	*mod = &ml->sml_mod;

		/*
		 * accept all operational attributes;
		 * this includes modifersName and modifyTimestamp
		 * if lastmod is "on"
		 */
		if ( is_at_operational( mod->sm_desc->ad_type ) ) {
			( void ) attr_delete( &e->e_attrs, mod->sm_desc );
			rc = rs->sr_err = attr_merge( e, mod->sm_desc,
					mod->sm_values, mod->sm_nvalues );
			if ( rc != LDAP_SUCCESS ) {
				break;
			}
			continue;

		/*
		 * only the "managedInfo" attribute can be modified
		 */
		} else if ( mod->sm_desc != mi->mi_ad_managedInfo ) {
			rc = rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
			break;
		}

		switch ( mod->sm_op ) {
		case LDAP_MOD_ADD:
			rc = add_values( op, e, mod, &newlevel );
			break;
			
		case LDAP_MOD_DELETE:
			rc = delete_values( op, e, mod, &newlevel );
			break;

		case LDAP_MOD_REPLACE:
			rc = replace_values( op, e, mod, &newlevel );
			break;

		default:
			rc = LDAP_OTHER;
			break;
		}

		if ( rc != LDAP_SUCCESS ) {
			rs->sr_err = rc;
			break;
		}
	}

	/* set the new debug level */
	if ( rc == LDAP_SUCCESS ) {
		const char	*text;
		static char	textbuf[ BACKMONITOR_BUFSIZE ];

		/* check for abandon */
		if ( op->o_abandon ) {
			rc = rs->sr_err = SLAPD_ABANDON;

			goto cleanup;
		}

		/* check that the entry still obeys the schema */
		rc = entry_schema_check( op, e, save_attrs, 0, 0, NULL,
			&text, textbuf, sizeof( textbuf ) );
		if ( rc != LDAP_SUCCESS ) {
			rs->sr_err = rc;
			goto cleanup;
		}

		/*
		 * Do we need to protect this with a mutex?
		 */
		ldap_syslog = newlevel;

#if 0	/* debug rather than log */
		slap_debug = newlevel;
		lutil_set_debug_level( "slapd", slap_debug );
		ber_set_option(NULL, LBER_OPT_DEBUG_LEVEL, &slap_debug);
		ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, &slap_debug);
		ldif_debug = slap_debug;
#endif
	}

cleanup:;
	if ( rc == LDAP_SUCCESS ) {
		attrs_free( save_attrs );

	} else {
		attrs_free( e->e_attrs );
		e->e_attrs = save_attrs;
	}
	
	ldap_pvt_thread_mutex_unlock( &monitor_log_mutex );

	if ( rc == LDAP_SUCCESS ) {
		rc = SLAP_CB_CONTINUE;
	}

	return rc;
}
Exemple #24
0
int
tester_config_opt( struct tester_conn_args *config, char opt, char *optarg )
{
	switch ( opt ) {
		case 'C':
			config->chaserefs++;
			break;

		case 'D':
			config->binddn = strdup( optarg );
			break;

		case 'd':
			{
				int debug;
				if ( lutil_atoi( &debug, optarg ) != 0 ) {
					return -1;
				}

				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 );
				}
				break;
			}

		case 'H':
			config->uri = strdup( optarg );
			break;

		case 'h':
			config->host = strdup( optarg );
			break;

		case 'i':
			tester_ignore_str2errlist( optarg );
			break;

		case 'L':
			if ( lutil_atoi( &config->outerloops, optarg ) != 0 ) {
				return -1;
			}
			break;

		case 'l':
			if ( lutil_atoi( &config->loops, optarg ) != 0 ) {
				return -1;
			}
			break;

#ifdef HAVE_CYRUS_SASL
		case 'O':
			if ( config->secprops != NULL ) {
				return -1;
			}
			if ( config->authmethod != -1 && config->authmethod != LDAP_AUTH_SASL ) {
				return -1;
			}
			config->authmethod = LDAP_AUTH_SASL;
			config->secprops = ber_strdup( optarg );
			break;

		case 'R':
			if ( config->realm != NULL ) {
				return -1;
			}
			if ( config->authmethod != -1 && config->authmethod != LDAP_AUTH_SASL ) {
				return -1;
			}
			config->authmethod = LDAP_AUTH_SASL;
			config->realm = ber_strdup( optarg );
			break;

		case 'U':
			if ( config->authc_id != NULL ) {
				return -1;
			}
			if ( config->authmethod != -1 && config->authmethod != LDAP_AUTH_SASL ) {
				return -1;
			}
			config->authmethod = LDAP_AUTH_SASL;
			config->authc_id = ber_strdup( optarg );
			break;

		case 'X':
			if ( config->authz_id != NULL ) {
				return -1;
			}
			if ( config->authmethod != -1 && config->authmethod != LDAP_AUTH_SASL ) {
				return -1;
			}
			config->authmethod = LDAP_AUTH_SASL;
			config->authz_id = ber_strdup( optarg );
			break;

		case 'Y':
			if ( config->mech != NULL ) {
				return -1;
			}
			if ( config->authmethod != -1 && config->authmethod != LDAP_AUTH_SASL ) {
				return -1;
			}
			config->authmethod = LDAP_AUTH_SASL;
			config->mech = ber_strdup( optarg );
			break;
#endif

		case 'p':
			if ( lutil_atoi( &config->port, optarg ) != 0 ) {
				return -1;
			}
			break;

		case 'r':
			if ( lutil_atoi( &config->retries, optarg ) != 0 ) {
				return -1;
			}
			break;

		case 't':
			if ( lutil_atoi( &config->delay, optarg ) != 0 ) {
				return -1;
			}
			break;

		case 'w':
			config->pass.bv_val = strdup( optarg );
			config->pass.bv_len = strlen( optarg );
			memset( optarg, '*', config->pass.bv_len );
			break;

		case 'x':
			if ( config->authmethod != -1 && config->authmethod != LDAP_AUTH_SIMPLE ) {
				return -1;
			}
			config->authmethod = LDAP_AUTH_SIMPLE;
			break;

		default:
			return -1;
	}

	return LDAP_SUCCESS;
}
Exemple #25
0
char *
ldap_first_attribute( LDAP *ld, LDAPMessage *entry, BerElement **berout )
{
	int rc;
	ber_tag_t tag;
	ber_len_t len = 0;
	char *attr;
	BerElement *ber;

	Debug( LDAP_DEBUG_TRACE, "ldap_first_attribute\n", 0, 0, 0 );

	assert( ld != NULL );
	assert( LDAP_VALID( ld ) );
	assert( entry != NULL );
	assert( berout != NULL );

	*berout = NULL;

	ber = ldap_alloc_ber_with_options( ld );
	if( ber == NULL ) {
		return NULL;
	}

	*ber = *entry->lm_ber;

	/* 
	 * Skip past the sequence, dn, sequence of sequence leaving
	 * us at the first attribute.
	 */

	tag = ber_scanf( ber, "{xl{" /*}}*/, &len );
	if( tag == LBER_ERROR ) {
		ld->ld_errno = LDAP_DECODING_ERROR;
		ber_free( ber, 0 );
		return NULL;
	}

	/* set the length to avoid overrun */
	rc = ber_set_option( ber, LBER_OPT_REMAINING_BYTES, &len );
	if( rc != LBER_OPT_SUCCESS ) {
		ld->ld_errno = LDAP_LOCAL_ERROR;
		ber_free( ber, 0 );
		return NULL;
	}

	if ( ber_pvt_ber_remaining( ber ) == 0 ) {
		assert( len == 0 );
		ber_free( ber, 0 );
		return NULL;
	}
	assert( len != 0 );

	/* snatch the first attribute */
	tag = ber_scanf( ber, "{ax}", &attr );
	if( tag == LBER_ERROR ) {
		ld->ld_errno = LDAP_DECODING_ERROR;
		ber_free( ber, 0 );
		return NULL;
	}

	*berout = ber;
	return attr;
}
Exemple #26
0
int main(int argc, char *argv[])
{
	testitem_t item;
	testedhost_t host;
	service_t ldapservice;
	int argi = 1;
	int ldapdebug = 0;

	while ((argi < argc) && (strncmp(argv[argi], "--", 2) == 0)) {
		if (strcmp(argv[argi], "--debug") == 0) {
			debug = 1;
		}
		else if (strncmp(argv[argi], "--ldapdebug=", strlen("--ldapdebug=")) == 0) {
			char *p = strchr(argv[argi], '=');
			ldapdebug = atoi(p+1);
		}
		argi++;
	}

	/* For testing, dont crash in sendmsg when no XYMSRV defined */
	dontsendmessages = 1;
	if (xgetenv("XYMSRV") == NULL) putenv("XYMSRV=127.0.0.1");

	memset(&item, 0, sizeof(item));
	memset(&host, 0, sizeof(host));
	memset(&ldapservice, 0, sizeof(ldapservice));

	ldapservice.portnum = 389;
	ldapservice.testname = "ldap";
	ldapservice.namelen = strlen(ldapservice.testname);
	ldapservice.items = &item;

	item.host = &host;
	item.service = &ldapservice;
	item.dialup = item.reverse = item.silenttest = item.alwaystrue = 0;
	item.testspec = urlunescape(argv[argi]);

	host.firstldap = &item;
	host.hostname = "ldaptest.xymon";
	host.ldapuser = NULL;
	host.ldappasswd = NULL;

	init_ldap_library();

	if (ldapdebug) {
#if defined(LBER_OPT_DEBUG_LEVEL) && defined(LDAP_OPT_DEBUG_LEVEL)
		ber_set_option(NULL, LBER_OPT_DEBUG_LEVEL, &ldapdebug);
		ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, &ldapdebug);
#else
		printf("LDAP library does not support change of debug level\n");
#endif
	}

	if (add_ldap_test(&item) == 0) {
		run_ldap_tests(&ldapservice, 0, 10);
		combo_start();
		send_ldap_results(&ldapservice, &host, "", 0);
		combo_end();
	}

	shutdown_ldap_library();
	return 0;
}
Exemple #27
0
static int
deref_response( Operation *op, SlapReply *rs )
{
	int rc = SLAP_CB_CONTINUE;

	if ( rs->sr_type == REP_SEARCH ) {
		BerElementBuffer berbuf;
		BerElement *ber = (BerElement *) &berbuf;
		deref_cb_t *dc = (deref_cb_t *)op->o_callback->sc_private;
		DerefSpec *ds;
		DerefRes *dr, *drhead = NULL, **drp = &drhead;
		struct berval bv = BER_BVNULL;
		int nDerefRes = 0, nDerefVals = 0, nAttrs = 0, nVals = 0;
		struct berval ctrlval;
		LDAPControl *ctrl, *ctrlsp[2];
		AccessControlState acl_state = ACL_STATE_INIT;
		static char dummy = '\0';
		Entry *ebase;
		int i;

		rc = overlay_entry_get_ov( op, &rs->sr_entry->e_nname, NULL, NULL, 0, &ebase, dc->dc_on );
		if ( rc != LDAP_SUCCESS || ebase == NULL ) {
			return SLAP_CB_CONTINUE;
		}

		for ( ds = dc->dc_ds; ds; ds = ds->ds_next ) {
			Attribute *a = attr_find( ebase->e_attrs, ds->ds_derefAttr );

			if ( a != NULL ) {
				DerefVal *dv;
				BerVarray *bva;

				if ( !access_allowed( op, rs->sr_entry, a->a_desc,
						NULL, ACL_READ, &acl_state ) )
				{
					continue;
				}

				dr = op->o_tmpcalloc( 1,
					sizeof( DerefRes ) + ( sizeof( DerefVal ) + sizeof( BerVarray * ) * ds->ds_nattrs ) * ( a->a_numvals + 1 ),
					op->o_tmpmemctx );
				dr->dr_spec = *ds;
				dv = dr->dr_vals = (DerefVal *)&dr[ 1 ];
				bva = (BerVarray *)&dv[ a->a_numvals + 1 ];

				bv.bv_len += ds->ds_derefAttr->ad_cname.bv_len;
				nAttrs++;
				nDerefRes++;

				for ( i = 0; !BER_BVISNULL( &a->a_nvals[ i ] ); i++ ) {
					Entry *e = NULL;

					dv[ i ].dv_attrVals = bva;
					bva += ds->ds_nattrs;


					if ( !access_allowed( op, rs->sr_entry, a->a_desc,
							&a->a_nvals[ i ], ACL_READ, &acl_state ) )
					{
						dv[ i ].dv_derefSpecVal.bv_val = &dummy;
						continue;
					}

					ber_dupbv_x( &dv[ i ].dv_derefSpecVal, &a->a_vals[ i ], op->o_tmpmemctx );
					bv.bv_len += dv[ i ].dv_derefSpecVal.bv_len;
					nVals++;
					nDerefVals++;

					rc = overlay_entry_get_ov( op, &a->a_nvals[ i ], NULL, NULL, 0, &e, dc->dc_on );
					if ( rc == LDAP_SUCCESS && e != NULL ) {
						int j;

						if ( access_allowed( op, e, slap_schema.si_ad_entry,
							NULL, ACL_READ, NULL ) )
						{
							for ( j = 0; j < ds->ds_nattrs; j++ ) {
								Attribute *aa;

								if ( !access_allowed( op, e, ds->ds_attributes[ j ], NULL,
									ACL_READ, &acl_state ) )
								{
									continue;
								}

								aa = attr_find( e->e_attrs, ds->ds_attributes[ j ] );
								if ( aa != NULL ) {
									unsigned k, h, last = aa->a_numvals;

									ber_bvarray_dup_x( &dv[ i ].dv_attrVals[ j ],
										aa->a_vals, op->o_tmpmemctx );

									bv.bv_len += ds->ds_attributes[ j ]->ad_cname.bv_len;

									for ( k = 0, h = 0; k < aa->a_numvals; k++ ) {
										if ( !access_allowed( op, e,
											aa->a_desc,
											&aa->a_nvals[ k ],
											ACL_READ, &acl_state ) )
										{
											op->o_tmpfree( dv[ i ].dv_attrVals[ j ][ h ].bv_val,
												op->o_tmpmemctx );
											dv[ i ].dv_attrVals[ j ][ h ] = dv[ i ].dv_attrVals[ j ][ --last ];
											BER_BVZERO( &dv[ i ].dv_attrVals[ j ][ last ] );
											continue;
										}
										bv.bv_len += dv[ i ].dv_attrVals[ j ][ h ].bv_len;
										nVals++;
										h++;
									}
									nAttrs++;
								}
							}
						}

						overlay_entry_release_ov( op, e, 0, dc->dc_on );
					}
				}

				*drp = dr;
				drp = &dr->dr_next;
			}
		}
		overlay_entry_release_ov( op, ebase, 0, dc->dc_on );

		if ( drhead == NULL ) {
			return SLAP_CB_CONTINUE;
		}

		/* cook the control value */
		bv.bv_len += nVals * sizeof(struct berval)
			+ nAttrs * sizeof(struct berval)
			+ nDerefVals * sizeof(DerefVal)
			+ nDerefRes * sizeof(DerefRes);
		bv.bv_val = op->o_tmpalloc( bv.bv_len, op->o_tmpmemctx );

		ber_init2( ber, &bv, LBER_USE_DER );
		ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );

		rc = ber_printf( ber, "{" /*}*/ );
		for ( dr = drhead; dr != NULL; dr = dr->dr_next ) {
			for ( i = 0; !BER_BVISNULL( &dr->dr_vals[ i ].dv_derefSpecVal ); i++ ) {
				int j, first = 1;

				if ( dr->dr_vals[ i ].dv_derefSpecVal.bv_val == &dummy ) {
					continue;
				}

				rc = ber_printf( ber, "{OO" /*}*/,
					&dr->dr_spec.ds_derefAttr->ad_cname,
					&dr->dr_vals[ i ].dv_derefSpecVal );
				op->o_tmpfree( dr->dr_vals[ i ].dv_derefSpecVal.bv_val, op->o_tmpmemctx );
				for ( j = 0; j < dr->dr_spec.ds_nattrs; j++ ) {
					if ( dr->dr_vals[ i ].dv_attrVals[ j ] != NULL ) {
						if ( first ) {
							rc = ber_printf( ber, "t{" /*}*/,
								(LBER_CONSTRUCTED|LBER_CLASS_CONTEXT) );
							first = 0;
						}
						rc = ber_printf( ber, "{O[W]}",
							&dr->dr_spec.ds_attributes[ j ]->ad_cname,
							dr->dr_vals[ i ].dv_attrVals[ j ] );
						op->o_tmpfree( dr->dr_vals[ i ].dv_attrVals[ j ],
							op->o_tmpmemctx );
					}
				}
				if ( !first ) {
					rc = ber_printf( ber, /*{{*/ "}N}" );
				} else {
					rc = ber_printf( ber, /*{*/ "}" );
				}
			}
		}
		rc = ber_printf( ber, /*{*/ "}" );
		if ( ber_flatten2( ber, &ctrlval, 0 ) == -1 ) {
			if ( op->o_deref == SLAP_CONTROL_CRITICAL ) {
				rc = LDAP_CONSTRAINT_VIOLATION;

			} else {
				rc = SLAP_CB_CONTINUE;
			}
			goto cleanup;
		}

		ctrl = op->o_tmpcalloc( 1,
			sizeof( LDAPControl ) + ctrlval.bv_len + 1,
			op->o_tmpmemctx );
		ctrl->ldctl_value.bv_val = (char *)&ctrl[ 1 ];
		ctrl->ldctl_oid = LDAP_CONTROL_X_DEREF;
		ctrl->ldctl_iscritical = 0;
		ctrl->ldctl_value.bv_len = ctrlval.bv_len;
		memcpy( ctrl->ldctl_value.bv_val, ctrlval.bv_val, ctrlval.bv_len );
		ctrl->ldctl_value.bv_val[ ctrl->ldctl_value.bv_len ] = '\0';

		ber_free_buf( ber );

		ctrlsp[0] = ctrl;
		ctrlsp[1] = NULL;
		slap_add_ctrls( op, rs, ctrlsp );

		rc = SLAP_CB_CONTINUE;

cleanup:;
		/* release all */
		for ( ; drhead != NULL; ) {
			DerefRes *drnext = drhead->dr_next;
			op->o_tmpfree( drhead, op->o_tmpmemctx );
			drhead = drnext;
		}

	} else if ( rs->sr_type == REP_RESULT ) {
		rc = deref_cleanup( op, rs );
	}

	return rc;
}
Exemple #28
0
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 );
}
Exemple #29
0
static int
_mu_conn_setup (LDAP **pld)
{
  int rc;
  LDAPURLDesc *ludlist, **ludp;
  char **urls = NULL;
  int nurls = 0;
  char *ldapuri = NULL;
  LDAP *ld = NULL;
  int protocol = LDAP_VERSION3; /* FIXME: must be configurable */
  
  if (ldap_param.debug)
    {
      if (ber_set_option (NULL, LBER_OPT_DEBUG_LEVEL, &ldap_param.debug)
	  != LBER_OPT_SUCCESS )
	mu_error (_("cannot set LBER_OPT_DEBUG_LEVEL %d"), ldap_param.debug);

      if (ldap_set_option (NULL, LDAP_OPT_DEBUG_LEVEL, &ldap_param.debug)
	  != LDAP_OPT_SUCCESS )
	mu_error (_("could not set LDAP_OPT_DEBUG_LEVEL %d"),
		  ldap_param.debug);
    }

  if (ldap_param.url)
    {
      rc = ldap_url_parse (ldap_param.url, &ludlist);
      if (rc != LDAP_URL_SUCCESS)
	{
	  mu_error (_("cannot parse LDAP URL(s)=%s (%d)"),
		    ldap_param.url, rc);
	  return 1;
	}
      
      for (ludp = &ludlist; *ludp; )
	{
	  LDAPURLDesc *lud = *ludp;
	  char **tmp;
	  
	  if (lud->lud_dn && lud->lud_dn[0]
	      && (lud->lud_host == NULL || lud->lud_host[0] == '\0'))
	    {
	      /* if no host but a DN is provided, try DNS SRV to gather the
		 host list */
	      char *domain = NULL, *hostlist = NULL;
	      size_t i;
	      struct mu_wordsplit ws;
	      
	      if (ldap_dn2domain (lud->lud_dn, &domain) || !domain)
		{
		  mu_error (_("DNS SRV: cannot convert DN=\"%s\" into a domain"),
			    lud->lud_dn );
		  goto dnssrv_free;
		}
	      
	      rc = ldap_domain2hostlist (domain, &hostlist);
	      if (rc)
		{
		  mu_error (_("DNS SRV: cannot convert domain=%s into a hostlist"),
			    domain);
		  goto dnssrv_free;
		}

	      if (mu_wordsplit (hostlist, &ws, MU_WRDSF_DEFFLAGS))
		{
		  mu_error (_("DNS SRV: could not parse hostlist=\"%s\": %s"),
			    hostlist, mu_wordsplit_strerror (&ws));
		  goto dnssrv_free;
		}
	      
	      tmp = realloc (urls, sizeof(char *) * (nurls + ws.ws_wordc + 1));
	      if (!tmp)
		{
		  mu_error ("DNS SRV %s", mu_strerror (errno));
		  goto dnssrv_free;
		}
	      
	      urls = tmp;
	      urls[nurls] = NULL;
	      
	      for (i = 0; i < ws.ws_wordc; i++)
		{
		  urls[nurls + i + 1] = NULL;
		  rc = mu_asprintf (&urls[nurls + i],
				    "%s://%s",
				    lud->lud_scheme, ws.ws_wordv[i]);
		  if (rc)
		    {
		      mu_error ("DNS SRV %s", mu_strerror (rc));
		      goto dnssrv_free;
		    }
		}
	      
	      nurls += i;
	      
	    dnssrv_free:
	      mu_wordsplit_free (&ws);
	      ber_memfree (hostlist);
	      ber_memfree (domain);
	    }
	  else
	    {
	      tmp = realloc (urls, sizeof(char *) * (nurls + 2));
	      if (!tmp)
		{
		  mu_error ("DNS SRV %s", mu_strerror (errno));
		  break;
		}
	      urls = tmp;
	      urls[nurls + 1] = NULL;
	      
	      urls[nurls] = ldap_url_desc2str (lud);
	      if (!urls[nurls])
		{
		  mu_error ("DNS SRV %s", mu_strerror (errno));
		  break;
		}
	      nurls++;
	    }
	  
	  *ludp = lud->lud_next;
	  
	  lud->lud_next = NULL;
	  ldap_free_urldesc (lud);
	}

      if (ludlist)
	{
	  ldap_free_urldesc (ludlist);
	  return 1;
	}
      else if (!urls)
	return 1;
      
      rc = mu_argcv_string (nurls, urls, &ldapuri);
      if (rc)
	{
	  mu_error ("%s", mu_strerror (rc));
	  return 1;
	}
      
      ber_memvfree ((void **)urls);
    }

  mu_diag_output (MU_DIAG_INFO,
		  "constructed LDAP URI: %s", ldapuri ? ldapuri : "<DEFAULT>");

  rc = ldap_initialize (&ld, ldapuri);
  if (rc != LDAP_SUCCESS)
    {
      mu_error (_("cannot create LDAP session handle for URI=%s (%d): %s"),
		ldapuri, rc, ldap_err2string (rc));

      free (ldapuri);
      return 1;
    }
  free (ldapuri);
  
  ldap_set_option (ld, LDAP_OPT_PROTOCOL_VERSION, &protocol);

  if (ldap_param.tls)
    {
      rc = ldap_start_tls_s (ld, NULL, NULL);
      if (rc != LDAP_SUCCESS)
	{
	  char *msg = NULL;
	  ldap_get_option (ld,
			   LDAP_OPT_DIAGNOSTIC_MESSAGE,
			   (void*)&msg);
	  
	  mu_error (_("ldap_start_tls failed: %s"), ldap_err2string (rc));
	  mu_error (_("TLS diagnostics: %s"), msg);
	  ldap_memfree (msg);

	  ldap_unbind_ext (ld, NULL, NULL);
	  
	  return 1;
	}
    }

  /* FIXME: Timeouts, SASL, etc. */
  *pld = ld;
  return 0;
}
Exemple #30
0
void
slap_sl_mem_init()
{
    ber_set_option( NULL, LBER_OPT_MEMORY_FNS, &slap_sl_mfuncs );
}