ldap.c 22.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942
/* GNU Mailutils -- a suite of utilities for electronic mail
   Copyright (C) 2005, 2007-2012, 2014-2016 Free Software Foundation,
   Inc.

   This library 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 3 of the License, or (at your option) any later version.

   This library 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 library.  If not, see
   <http://www.gnu.org/licenses/>. */

#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <ctype.h>

#include <mailutils/mu_auth.h>
#include <mailutils/cstr.h>
#include <mailutils/io.h>

#ifdef WITH_LDAP
#include "mailutils/argcv.h"
#include "mailutils/wordsplit.h"
#include "mailutils/assoc.h"
#include "mailutils/list.h"
#include "mailutils/iterator.h"
#include "mailutils/mailbox.h"
#include "mailutils/sql.h"
#include "mailutils/mu_auth.h"
#include "mailutils/error.h"
#include "mailutils/errno.h"
#include "mailutils/nls.h"
#include "mailutils/util.h"
#include "mailutils/stream.h"
#include "mailutils/filter.h"
#include "mailutils/md5.h"
#include "mailutils/sha1.h"
#include "mailutils/ldap.h"

#include <ldap.h>
#include <lber.h>

const char *default_field_map =
"name=uid:"
"passwd=userPassword:"
"uid=uidNumber:"
"gid=gidNumber:"
"gecos=gecos:"
"dir=homeDirectory:"
"shell=loginShell";

static struct mu_ldap_module_config ldap_param;

static int
cb_field_map (void *data, mu_config_value_t *val)
{
  char *err_term;
  int rc = mu_cfg_field_map (val, &ldap_param.field_map, &err_term);

  if (rc)
    {
      if (err_term)
	mu_error (_("error near %s: %s"), err_term, mu_strerror (rc));
      else
	mu_error ("%s", mu_strerror (rc));
    }

  return rc;
}

static struct mu_cfg_param mu_ldap_param[] = {
  { "enable", mu_c_bool, &ldap_param.enable, 0, NULL,
    N_("Enable LDAP lookups.") },
  { "url", mu_c_string, &ldap_param.url, 0, NULL,
    N_("Set URL of the LDAP server."),
    N_("url") },
  { "base", mu_c_string, &ldap_param.base, 0, NULL,
    N_("Base DN for LDAP lookups."),
    N_("dn") },
  { "binddn", mu_c_string, &ldap_param.binddn, 0, NULL,
    N_("DN for accessing LDAP database."),
    N_("dn") },
  { "passwd", mu_c_string, &ldap_param.passwd, 0, NULL,
    N_("Password for use with binddn.") },
  { "tls", mu_c_bool, &ldap_param.tls, 0, NULL,
    N_("Use TLS encryption.") },
  { "debug", mu_c_int, &ldap_param.debug, 0, NULL,
    N_("Set LDAP debugging level.") },
  { "field-map", mu_cfg_callback, NULL, 0, cb_field_map,
    N_("Set a field-map for parsing LDAP replies.  The map is a "
       "column-separated list of definitions.  Each definition has the "
       "following form:\n"
       "   <name: string>=<attr: string>\n"
       "where <name> is one of the following: name, passwd, uid, gid, "
       "gecos, dir, shell, mailbox, quota, and <attr> is the name of "
       "the corresponding LDAP attribute."),
    N_("map: definition") },
  { "getpwnam", mu_c_string, &ldap_param.getpwnam_filter, 0, NULL,
    N_("LDAP filter to use for getpwnam requests."),
    N_("filter") },
  { "getpwuid", mu_c_string, &ldap_param.getpwuid_filter, 0, NULL,
    N_("LDAP filter to use for getpwuid requests."),
    N_("filter") },
  { NULL }
};

int									      
mu_ldap_section_parser
   (enum mu_cfg_section_stage stage, const mu_cfg_node_t *node,	      
    const char *section_label, void **section_data,
    void *call_data, mu_cfg_tree_t *tree)
{									      
  switch (stage)							      
    {									      
    case mu_cfg_section_start:
      ldap_param.enable = 1;
      break;
    default:
      break;
    }									      
  return 0;								      
}


static void
module_init (void *ptr)
{
  if (ldap_param.enable)
    {
      if (!ldap_param.getpwnam_filter)
	ldap_param.getpwnam_filter =
	  "(&(objectClass=posixAccount) (uid=$user))";
      if (!ldap_param.getpwuid_filter)
	ldap_param.getpwuid_filter =
	  "(&(objectClass=posixAccount) (uidNumber=$user))";
      if (!ldap_param.field_map)
	{
	  struct mu_config_value val;
	  val.type = MU_CFG_STRING;
	  val.v.string = default_field_map;
	  if (mu_cfg_field_map (&val, &ldap_param.field_map, NULL))
	    abort ();
	}
    }
}

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

static int
_mu_ldap_bind (LDAP *ld)
{
  int msgid, err, rc;
  LDAPMessage *result;
  LDAPControl **ctrls;
  char msgbuf[256];
  char *matched = NULL;
  char *info = NULL;
  char **refs = NULL;
  static struct berval passwd;

  passwd.bv_val = ldap_param.passwd;
  passwd.bv_len = passwd.bv_val ? strlen (passwd.bv_val) : 0;


  msgbuf[0] = 0;

  rc = ldap_sasl_bind (ld, ldap_param.binddn, LDAP_SASL_SIMPLE, &passwd,
		       NULL, NULL, &msgid);
  if (msgid == -1)
    {
      mu_error ("ldap_sasl_bind(SIMPLE) failed: %s", ldap_err2string (rc));
      return 1;
    }

  if (ldap_result (ld, msgid, LDAP_MSG_ALL, NULL, &result ) == -1)
    {
      mu_error ("ldap_result failed");
      return 1;
    }

  rc = ldap_parse_result (ld, result, &err, &matched, &info, &refs,
			  &ctrls, 1);
  if (rc != LDAP_SUCCESS)
    {
      mu_error ("ldap_parse_result failed: %s", ldap_err2string (rc));
      return 1;
    }

  if (ctrls)
    ldap_controls_free (ctrls);

  if (err != LDAP_SUCCESS
      || msgbuf[0]
      || (matched && matched[0])
      || (info && info[0])
      || refs)
    {
      /* FIXME: Use debug output for that */
      mu_error ("ldap_bind: %s (%d)%s", ldap_err2string (err), err, msgbuf);

      if (matched && *matched) 
	mu_error ("matched DN: %s", matched);

      if (info && *info)
	mu_error ("additional info: %s", info);

      if (refs && *refs)
	{
	  int i;
	  mu_error ("referrals:");
	  for (i = 0; refs[i]; i++) 
	    mu_error ("%s", refs[i]);
	}

    }

  if (matched)
    ber_memfree (matched);
  if (info)
    ber_memfree (info);
  if (refs)
    ber_memvfree ((void **)refs);

  return err == LDAP_SUCCESS ? 0 : MU_ERR_FAILURE;
}

static void
_mu_ldap_unbind (LDAP *ld)
{
  if (ld)
    {
      ldap_set_option (ld, LDAP_OPT_SERVER_CONTROLS, NULL);
      ldap_unbind_ext (ld, NULL, NULL);
    }
}

static int 
_construct_attr_array (size_t *pargc, char ***pargv)
{
  size_t count, i;
  char **argv;
  mu_iterator_t itr = NULL;
  
  mu_assoc_count (ldap_param.field_map, &count);
  if (count == 0)
    return MU_ERR_FAILURE;
  argv = calloc (count + 1, sizeof argv[0]);

  mu_assoc_get_iterator (ldap_param.field_map, &itr);
  for (i = 0, mu_iterator_first (itr); !mu_iterator_is_done (itr);
       mu_iterator_next (itr), i++)
    {
      char **str;
      mu_iterator_current (itr, (void**) &str); 
      if ((argv[i] = strdup (*str)) == NULL)
        {
          mu_argcv_free (i, argv);
          return ENOMEM;
        }
    }
  mu_iterator_destroy (&itr);
  argv[i] = NULL;
  
  *pargc = count;
  *pargv = argv;
  
  return 0;
}

/* FIXME: Duplicated in other modules */
static void
get_quota (mu_off_t *pquota, const char *str)
{
  char *p;
  mu_off_t quota = strtoul (str, &p, 10);
  switch (*p)
    {
    case 0:
      break;
	      
    case 'k':
    case 'K':
      quota *= 1024;
      break;
      
    case 'm':
    case 'M':
      quota *= 1024*1024;
      break;
	      
    default:
      mu_error (_("invalid value for quota: %s"), str);
    }
}

static void
_free_partial_auth_data (struct mu_auth_data *d)
{
  free (d->name);
  free (d->passwd);
  free (d->gecos);
  free (d->dir);
  free (d->shell);
  free (d->mailbox);
}

static int
_assign_partial_auth_data (struct mu_auth_data *d, const char *key,
			   const char *val)
{
  int rc = 0;
  
  if (strcmp (key, MU_AUTH_NAME) == 0)
    rc = (d->name = strdup (val)) ? 0 : errno;
  else if (strcmp (key, MU_AUTH_PASSWD) == 0)
    rc = (d->passwd = strdup (val)) ? 0 : errno;
  else if (strcmp (key, MU_AUTH_UID) == 0)
    d->uid = atoi (val);
  else if (strcmp (key, MU_AUTH_GID) == 0)
    d->gid = atoi (val);
  else if (strcmp (key, MU_AUTH_GECOS) == 0)
    rc = (d->gecos = strdup (val)) ? 0 : errno;
  else if (strcmp (key, MU_AUTH_DIR) == 0)
    rc = (d->dir = strdup (val)) ? 0 : errno;
  else if (strcmp (key, MU_AUTH_SHELL) == 0)   
    rc = (d->shell = strdup (val)) ? 0 : errno;
  else if (strcmp (key, MU_AUTH_MAILBOX) == 0)
    rc = (d->mailbox = strdup (val)) ? 0 : errno;
  else if (strcmp (key, MU_AUTH_QUOTA) == 0)   
    get_quota (&d->quota, val);
  return rc;
}

static int
_mu_entry_to_auth_data (LDAP *ld, LDAPMessage *msg,
			struct mu_auth_data **return_data)
{
  int rc;
  BerElement *ber = NULL;
  struct berval bv;
  char *ufn = NULL;
  struct mu_auth_data d;
  mu_iterator_t itr = NULL;
  
  memset (&d, 0, sizeof d);
  
  rc = ldap_get_dn_ber (ld, msg, &ber, &bv);
  ufn = ldap_dn2ufn (bv.bv_val);
  /* FIXME: Use debug or diag functions */
  mu_error ("INFO: %s", ufn);
  ldap_memfree (ufn);
  
  mu_assoc_get_iterator (ldap_param.field_map, &itr);
  for (mu_iterator_first (itr); !mu_iterator_is_done (itr);
       mu_iterator_next (itr))
    {
      char *key;
      char **pattr;
      char *attr;
      struct berval **values;
      
      mu_iterator_current_kv (itr, (const void **)&key, (void**) &pattr);
      attr = *pattr;
      values = ldap_get_values_len (ld, msg, attr);
      if (!values || !values[0])
	{
	  mu_error ("LDAP field `%s' (`%s') has NULL value",
		    key, *pattr);
	  _free_partial_auth_data (&d);
	  return MU_ERR_READ;
	}
      
      rc = _assign_partial_auth_data (&d, key, values[0]->bv_val);
      
      ldap_value_free_len (values);
      if (rc)
	{
	  _free_partial_auth_data (&d);
	  return rc;
	}
    }
  
  rc = mu_auth_data_alloc (return_data,
			   d.name,
			   d.passwd,
			   d.uid,
			   d.gid,
			   d.gecos,
			   d.dir,
			   d.shell,
			   d.mailbox,
			   1);
  if (rc == 0)
    mu_auth_data_set_quota (*return_data, d.quota);

  _free_partial_auth_data (&d);
  
  return rc;
}
    

static int
_mu_ldap_search (LDAP *ld, const char *filter_pat, const char *key,
		 struct mu_auth_data **return_data)
{
  int rc;
  char **attrs;
  size_t nattrs;
  LDAPMessage *res, *msg;
  ber_int_t msgid;
  const char *env[3];
  struct mu_wordsplit ws;

  rc = _construct_attr_array (&nattrs, &attrs);
  if (rc)
    return rc;

  env[0] = "user";
  env[1] = key;
  env[2] = NULL;

  ws.ws_env = env;
  if (mu_wordsplit (filter_pat, &ws,
		    MU_WRDSF_NOSPLIT | MU_WRDSF_NOCMD |
		    MU_WRDSF_ENV | MU_WRDSF_ENV_KV))
    {
      mu_error (_("cannot expand line `%s': %s"), filter_pat,
		mu_wordsplit_strerror (&ws));
      return MU_ERR_FAILURE;
    }
  else if (ws.ws_wordc == 0)
    {
      mu_error (_("expanding %s yields empty string"), filter_pat);
      mu_wordsplit_free (&ws);
      mu_argcv_free (nattrs, attrs);
      return MU_ERR_FAILURE;
    }
  
  rc = ldap_search_ext (ld, ldap_param.base, LDAP_SCOPE_SUBTREE,
			ws.ws_wordv[0], attrs, 0,
			NULL, NULL, NULL, -1, &msgid);
  mu_wordsplit_free (&ws);
  mu_argcv_free (nattrs, attrs);

  if (rc != LDAP_SUCCESS)
    {
      mu_error ("ldap_search_ext: %s", ldap_err2string (rc));
      if (rc == LDAP_NO_SUCH_OBJECT)
	return MU_ERR_NOENT;
      else
	return MU_ERR_FAILURE;
    }

  rc = ldap_result (ld, msgid, LDAP_MSG_ALL, NULL, &res );
  if (rc < 0)
    {
      mu_error ("ldap_result failed");
      return MU_ERR_FAILURE;
    }

  rc = ldap_count_entries (ld, res);
  if (rc == 0)
    {
      mu_error ("not enough entires");
      return MU_ERR_NOENT;
    }
  if (rc > 1)
    mu_error ("LDAP: too many entries for key %s", key);
      

  msg = ldap_first_entry (ld, res);
  rc = _mu_entry_to_auth_data (ld, msg, return_data);
  ldap_msgfree (res);
  
  return rc;
}



typedef int (*pwcheck_fp) (const char *, const char *);


static int
chk_crypt (const char *db_pass, const char *pass)
{
  return strcmp (db_pass, crypt (pass, db_pass)) == 0 ?
              0 : MU_ERR_AUTH_FAILURE;
}

static int
chk_md5 (const char *db_pass, const char *pass)
{
  unsigned char md5digest[16];
  unsigned char d1[16];
  struct mu_md5_ctx md5context;
  mu_stream_t str = NULL, flt = NULL;
  
  mu_md5_init_ctx (&md5context);
  mu_md5_process_bytes (pass, strlen (pass), &md5context);
  mu_md5_finish_ctx (&md5context, md5digest);

  mu_static_memory_stream_create (&str, db_pass, strlen (db_pass));
  mu_filter_create (&flt, str, "base64", MU_FILTER_DECODE, MU_STREAM_READ);
  mu_stream_unref (str);

  mu_stream_read (flt, (char*) d1, sizeof d1, NULL);
  mu_stream_destroy (&flt);
  
  return memcmp (md5digest, d1, sizeof md5digest) == 0 ?
                  0 : MU_ERR_AUTH_FAILURE;
}

static int
chk_smd5 (const char *db_pass, const char *pass)
{
  int rc;
  unsigned char md5digest[16];
  unsigned char *d1;
  struct mu_md5_ctx md5context;
  mu_stream_t str = NULL, flt = NULL;
  size_t size;
  
  size = strlen (db_pass);
  mu_static_memory_stream_create (&str, db_pass, size);
  mu_filter_create (&flt, str, "base64", MU_FILTER_DECODE, MU_STREAM_READ);
  mu_stream_unref (str);

  d1 = malloc (size);
  if (!d1)
    {
      mu_stream_destroy (&flt);
      return ENOMEM;
    }
  
  mu_stream_read (flt, (char*) d1, size, &size);
  mu_stream_destroy (&flt);

  if (size <= 16)
    {
      mu_error ("malformed SMD5 password: %s", db_pass);
      return MU_ERR_FAILURE;
    }
  
  mu_md5_init_ctx (&md5context);
  mu_md5_process_bytes (pass, strlen (pass), &md5context);
  mu_md5_process_bytes (d1 + 16, size - 16, &md5context);
  mu_md5_finish_ctx (&md5context, md5digest);

  rc = memcmp (md5digest, d1, sizeof md5digest) == 0 ?
                  0 : MU_ERR_AUTH_FAILURE;
  free (d1);
  return rc;
}

static int
chk_sha (const char *db_pass, const char *pass)
{
  unsigned char sha1digest[20];
  unsigned char d1[20];
  mu_stream_t str = NULL, flt = NULL;
  struct mu_sha1_ctx sha1context;
   
  mu_sha1_init_ctx (&sha1context);
  mu_sha1_process_bytes (pass, strlen (pass), &sha1context);
  mu_sha1_finish_ctx (&sha1context, sha1digest);

  mu_static_memory_stream_create (&str, db_pass, strlen (db_pass));
  mu_filter_create (&flt, str, "base64", MU_FILTER_DECODE, MU_STREAM_READ);
  mu_stream_unref (str);

  mu_stream_read (flt, (char*) d1, sizeof d1, NULL);
  mu_stream_destroy (&flt);
  
  return memcmp (sha1digest, d1, sizeof sha1digest) == 0 ?
                  0 : MU_ERR_AUTH_FAILURE;
}

static int
chk_ssha (const char *db_pass, const char *pass)
{
  int rc;
  unsigned char sha1digest[20];
  unsigned char *d1;
  struct mu_sha1_ctx sha1context;
  mu_stream_t str = NULL, flt = NULL;
  size_t size;
  
  size = strlen (db_pass);
  mu_static_memory_stream_create (&str, db_pass, size);
  mu_filter_create (&flt, str, "base64", MU_FILTER_DECODE, MU_STREAM_READ);
  mu_stream_unref (str);

  d1 = malloc (size);
  if (!d1)
    {
      mu_stream_destroy (&flt);
      return ENOMEM;
    }
  
  mu_stream_read (flt, (char*) d1, size, &size);
  mu_stream_destroy (&flt);

  if (size <= 16)
    {
      mu_error ("malformed SSHA1 password: %s", db_pass);
      return MU_ERR_FAILURE;
    }
  
  mu_sha1_init_ctx (&sha1context);
  mu_sha1_process_bytes (pass, strlen (pass), &sha1context);
  mu_sha1_process_bytes (d1 + 20, size - 20, &sha1context);
  mu_sha1_finish_ctx (&sha1context, sha1digest);

  rc = memcmp (sha1digest, d1, sizeof sha1digest) == 0 ?
                  0 : MU_ERR_AUTH_FAILURE;
  free (d1);
  return rc;
}

static struct passwd_algo
{
  char *algo;
  size_t len;
  pwcheck_fp pwcheck;
} pwtab[] = {
#define DP(s, f) { #s, sizeof (#s) - 1, f }
  DP (CRYPT, chk_crypt),
  DP (MD5, chk_md5),
  DP (SMD5, chk_smd5),
  DP (SHA, chk_sha),
  DP (SSHA, chk_ssha),
  { NULL }
#undef DP
};

static pwcheck_fp
find_pwcheck (const char *algo, int len)
{
  struct passwd_algo *p;
  for (p = pwtab; p->algo; p++)
    if (len == p->len && mu_c_strncasecmp (p->algo, algo, len) == 0)
      return p->pwcheck;
  return NULL;
}

static int
mu_ldap_authenticate (struct mu_auth_data **return_data MU_ARG_UNUSED,
		      const void *key,
		      void *func_data MU_ARG_UNUSED, void *call_data)
{
  const struct mu_auth_data *auth_data = key;
  char *db_pass = auth_data->passwd;
  char *pass = call_data;

  if (auth_data->passwd == NULL || !pass)
    return EINVAL;

  if (db_pass[0] == '{')
    {
      int len;
      char *algo;
      pwcheck_fp pwcheck;

      
      algo = db_pass + 1;
      for (len = 0; algo[len] != '}'; len++)
	if (algo[len] == 0)
	  {
	    /* Possibly malformed password, try plaintext anyway */
	    return strcmp (db_pass, pass) == 0 ? 0 : MU_ERR_FAILURE;
	  }
      db_pass = algo + len + 1;
      pwcheck = find_pwcheck (algo, len);
      if (pwcheck)
	return pwcheck (db_pass, pass);
      else
	{
	  mu_error ("Unsupported password algorithm scheme: %.*s",
		    len, algo);
	  return MU_ERR_FAILURE;
	}
    }
  
  return strcmp (db_pass, pass) == 0 ? 0 : MU_ERR_AUTH_FAILURE;
}


static int
mu_auth_ldap_user_by_name (struct mu_auth_data **return_data,
			   const void *key,
			   void *func_data MU_ARG_UNUSED,
			   void *call_data MU_ARG_UNUSED)
{
  int rc;
  LDAP *ld;

  if (!ldap_param.enable)
    return ENOSYS;
  if (_mu_conn_setup (&ld))
    return MU_ERR_FAILURE;
  if (_mu_ldap_bind (ld))
    return MU_ERR_FAILURE;
  rc = _mu_ldap_search (ld, ldap_param.getpwnam_filter, key, return_data);
  _mu_ldap_unbind (ld);
  return rc;
}

static int
mu_auth_ldap_user_by_uid (struct mu_auth_data **return_data,
			  const void *key,
			  void *func_data MU_ARG_UNUSED,
			  void *call_data MU_ARG_UNUSED)
{
  int rc;
  LDAP *ld;
  char uidstr[128];

  if (!ldap_param.enable)
    return ENOSYS;
  if (_mu_conn_setup (&ld))
    return MU_ERR_FAILURE;
  if (_mu_ldap_bind (ld))
    return MU_ERR_FAILURE;

  snprintf (uidstr, sizeof (uidstr), "%u", *(uid_t*)key);
  rc = _mu_ldap_search (ld, ldap_param.getpwuid_filter, uidstr, return_data);
  _mu_ldap_unbind (ld);
  return rc;
}


#else
# define module_init NULL
# define mu_ldap_authenticate mu_auth_nosupport
# define mu_auth_ldap_user_by_name mu_auth_nosupport 
# define mu_auth_ldap_user_by_uid mu_auth_nosupport
# define mu_ldap_param NULL

#endif

struct mu_auth_module mu_auth_ldap_module = {
  .name = "ldap",
  .commit = module_init,
  .handler = {
    [mu_auth_authenticate] = mu_ldap_authenticate,
    [mu_auth_getpwnam]     = mu_auth_ldap_user_by_name,
    [mu_auth_getpwuid]     = mu_auth_ldap_user_by_uid
  },
  .cfg = mu_ldap_param
};