/* This file is part of GQ
 *
 * AUTHORS
 *     Sven Herzberg  <herzi@gnome-de.org>
 *
 * Copyright (C) 2007  Sven Herzberg
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
 * USA
 */

#include "gq-sasl.h"

#include <string.h>

#ifdef HAVE_CONFIG_H
# include <config.h>
#endif

#ifdef HAVE_SASL
# ifdef HAVE_SASL_H
#  include <sasl.h>
# else
#  include <sasl/sasl.h>
# endif
#endif

gboolean
gq_sasl_is_available(void)
{
#ifdef HAVE_SASL
	return TRUE;
#else
	return FALSE;
#endif
}

#ifdef HAVE_SASL
struct GqSaslCallbackData {
	GqServer   * server;
	gchar const* bind_pw;
};

static int
util_ldap_sasl_interact(LDAP    * ld        G_GNUC_UNUSED,
			unsigned  flags     G_GNUC_UNUSED,
			gpointer  user_data,
			void    * in)
{
	struct GqSaslCallbackData* data = user_data;
	sasl_interact_t *interact = in;

	for (; interact->id != SASL_CB_LIST_END; interact++) {
		switch (interact->id) {
		case SASL_CB_AUTHNAME:
			interact->result = gq_server_get_bind_dn(data->server);
			interact->len = strlen(interact->result);
			break;

		case SASL_CB_PASS:
			interact->result = data->bind_pw;;
			interact->len = strlen(interact->result);
			break;
		}
	}
	return LDAP_SUCCESS;
}
#endif

int
gq_ldap_sasl_bind_s(GqServer   * server,
		    LDAP       * ld,
		    gchar const* bind_pw)
{
#ifdef HAVE_SASL
	struct GqSaslCallbackData data = {
		server,
		bind_pw
	};
	return ldap_sasl_interactive_bind_s(ld, NULL,
					    NULL, NULL, NULL,
					    LDAP_SASL_QUIET,
					    util_ldap_sasl_interact, &data);
#else
	return LDAP_AUTH_METHOD_NOT_SUPPORTED;
#endif
}

